es6.js 4.5 MB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730873187328733873487358736873787388739874087418742874387448745874687478748874987508751875287538754875587568757875887598760876187628763876487658766876787688769877087718772877387748775877687778778877987808781878287838784878587868787878887898790879187928793879487958796879787988799880088018802880388048805880688078808880988108811881288138814881588168817881888198820882188228823882488258826882788288829883088318832883388348835883688378838883988408841884288438844884588468847884888498850885188528853885488558856885788588859886088618862886388648865886688678868886988708871887288738874887588768877887888798880888188828883888488858886888788888889889088918892889388948895889688978898889989008901890289038904890589068907890889098910891189128913891489158916891789188919892089218922892389248925892689278928892989308931893289338934893589368937893889398940894189428943894489458946894789488949895089518952895389548955895689578958895989608961896289638964896589668967896889698970897189728973897489758976897789788979898089818982898389848985898689878988898989908991899289938994899589968997899889999000900190029003900490059006900790089009901090119012901390149015901690179018901990209021902290239024902590269027902890299030903190329033903490359036903790389039904090419042904390449045904690479048904990509051905290539054905590569057905890599060906190629063906490659066906790689069907090719072907390749075907690779078907990809081908290839084908590869087908890899090909190929093909490959096909790989099910091019102910391049105910691079108910991109111911291139114911591169117911891199120912191229123912491259126912791289129913091319132913391349135913691379138913991409141914291439144914591469147914891499150915191529153915491559156915791589159916091619162916391649165916691679168916991709171917291739174917591769177917891799180918191829183918491859186918791889189919091919192919391949195919691979198919992009201920292039204920592069207920892099210921192129213921492159216921792189219922092219222922392249225922692279228922992309231923292339234923592369237923892399240924192429243924492459246924792489249925092519252925392549255925692579258925992609261926292639264926592669267926892699270927192729273927492759276927792789279928092819282928392849285928692879288928992909291929292939294929592969297929892999300930193029303930493059306930793089309931093119312931393149315931693179318931993209321932293239324932593269327932893299330933193329333933493359336933793389339934093419342934393449345934693479348934993509351935293539354935593569357935893599360936193629363936493659366936793689369937093719372937393749375937693779378937993809381938293839384938593869387938893899390939193929393939493959396939793989399940094019402940394049405940694079408940994109411941294139414941594169417941894199420942194229423942494259426942794289429943094319432943394349435943694379438943994409441944294439444944594469447944894499450945194529453945494559456945794589459946094619462946394649465946694679468946994709471947294739474947594769477947894799480948194829483948494859486948794889489949094919492949394949495949694979498949995009501950295039504950595069507950895099510951195129513951495159516951795189519952095219522952395249525952695279528952995309531953295339534953595369537953895399540954195429543954495459546954795489549955095519552955395549555955695579558955995609561956295639564956595669567956895699570957195729573957495759576957795789579958095819582958395849585958695879588958995909591959295939594959595969597959895999600960196029603960496059606960796089609961096119612961396149615961696179618961996209621962296239624962596269627962896299630963196329633963496359636963796389639964096419642964396449645964696479648964996509651965296539654965596569657965896599660966196629663966496659666966796689669967096719672967396749675967696779678967996809681968296839684968596869687968896899690969196929693969496959696969796989699970097019702970397049705970697079708970997109711971297139714971597169717971897199720972197229723972497259726972797289729973097319732973397349735973697379738973997409741974297439744974597469747974897499750975197529753975497559756975797589759976097619762976397649765976697679768976997709771977297739774977597769777977897799780978197829783978497859786978797889789979097919792979397949795979697979798979998009801980298039804980598069807980898099810981198129813981498159816981798189819982098219822982398249825982698279828982998309831983298339834983598369837983898399840984198429843984498459846984798489849985098519852985398549855985698579858985998609861986298639864986598669867986898699870987198729873987498759876987798789879988098819882988398849885988698879888988998909891989298939894989598969897989898999900990199029903990499059906990799089909991099119912991399149915991699179918991999209921992299239924992599269927992899299930993199329933993499359936993799389939994099419942994399449945994699479948994999509951995299539954995599569957995899599960996199629963996499659966996799689969997099719972997399749975997699779978997999809981998299839984998599869987998899899990999199929993999499959996999799989999100001000110002100031000410005100061000710008100091001010011100121001310014100151001610017100181001910020100211002210023100241002510026100271002810029100301003110032100331003410035100361003710038100391004010041100421004310044100451004610047100481004910050100511005210053100541005510056100571005810059100601006110062100631006410065100661006710068100691007010071100721007310074100751007610077100781007910080100811008210083100841008510086100871008810089100901009110092100931009410095100961009710098100991010010101101021010310104101051010610107101081010910110101111011210113101141011510116101171011810119101201012110122101231012410125101261012710128101291013010131101321013310134101351013610137101381013910140101411014210143101441014510146101471014810149101501015110152101531015410155101561015710158101591016010161101621016310164101651016610167101681016910170101711017210173101741017510176101771017810179101801018110182101831018410185101861018710188101891019010191101921019310194101951019610197101981019910200102011020210203102041020510206102071020810209102101021110212102131021410215102161021710218102191022010221102221022310224102251022610227102281022910230102311023210233102341023510236102371023810239102401024110242102431024410245102461024710248102491025010251102521025310254102551025610257102581025910260102611026210263102641026510266102671026810269102701027110272102731027410275102761027710278102791028010281102821028310284102851028610287102881028910290102911029210293102941029510296102971029810299103001030110302103031030410305103061030710308103091031010311103121031310314103151031610317103181031910320103211032210323103241032510326103271032810329103301033110332103331033410335103361033710338103391034010341103421034310344103451034610347103481034910350103511035210353103541035510356103571035810359103601036110362103631036410365103661036710368103691037010371103721037310374103751037610377103781037910380103811038210383103841038510386103871038810389103901039110392103931039410395103961039710398103991040010401104021040310404104051040610407104081040910410104111041210413104141041510416104171041810419104201042110422104231042410425104261042710428104291043010431104321043310434104351043610437104381043910440104411044210443104441044510446104471044810449104501045110452104531045410455104561045710458104591046010461104621046310464104651046610467104681046910470104711047210473104741047510476104771047810479104801048110482104831048410485104861048710488104891049010491104921049310494104951049610497104981049910500105011050210503105041050510506105071050810509105101051110512105131051410515105161051710518105191052010521105221052310524105251052610527105281052910530105311053210533105341053510536105371053810539105401054110542105431054410545105461054710548105491055010551105521055310554105551055610557105581055910560105611056210563105641056510566105671056810569105701057110572105731057410575105761057710578105791058010581105821058310584105851058610587105881058910590105911059210593105941059510596105971059810599106001060110602106031060410605106061060710608106091061010611106121061310614106151061610617106181061910620106211062210623106241062510626106271062810629106301063110632106331063410635106361063710638106391064010641106421064310644106451064610647106481064910650106511065210653106541065510656106571065810659106601066110662106631066410665106661066710668106691067010671106721067310674106751067610677106781067910680106811068210683106841068510686106871068810689106901069110692106931069410695106961069710698106991070010701107021070310704107051070610707107081070910710107111071210713107141071510716107171071810719107201072110722107231072410725107261072710728107291073010731107321073310734107351073610737107381073910740107411074210743107441074510746107471074810749107501075110752107531075410755107561075710758107591076010761107621076310764107651076610767107681076910770107711077210773107741077510776107771077810779107801078110782107831078410785107861078710788107891079010791107921079310794107951079610797107981079910800108011080210803108041080510806108071080810809108101081110812108131081410815108161081710818108191082010821108221082310824108251082610827108281082910830108311083210833108341083510836108371083810839108401084110842108431084410845108461084710848108491085010851108521085310854108551085610857108581085910860108611086210863108641086510866108671086810869108701087110872108731087410875108761087710878108791088010881108821088310884108851088610887108881088910890108911089210893108941089510896108971089810899109001090110902109031090410905109061090710908109091091010911109121091310914109151091610917109181091910920109211092210923109241092510926109271092810929109301093110932109331093410935109361093710938109391094010941109421094310944109451094610947109481094910950109511095210953109541095510956109571095810959109601096110962109631096410965109661096710968109691097010971109721097310974109751097610977109781097910980109811098210983109841098510986109871098810989109901099110992109931099410995109961099710998109991100011001110021100311004110051100611007110081100911010110111101211013110141101511016110171101811019110201102111022110231102411025110261102711028110291103011031110321103311034110351103611037110381103911040110411104211043110441104511046110471104811049110501105111052110531105411055110561105711058110591106011061110621106311064110651106611067110681106911070110711107211073110741107511076110771107811079110801108111082110831108411085110861108711088110891109011091110921109311094110951109611097110981109911100111011110211103111041110511106111071110811109111101111111112111131111411115111161111711118111191112011121111221112311124111251112611127111281112911130111311113211133111341113511136111371113811139111401114111142111431114411145111461114711148111491115011151111521115311154111551115611157111581115911160111611116211163111641116511166111671116811169111701117111172111731117411175111761117711178111791118011181111821118311184111851118611187111881118911190111911119211193111941119511196111971119811199112001120111202112031120411205112061120711208112091121011211112121121311214112151121611217112181121911220112211122211223112241122511226112271122811229112301123111232112331123411235112361123711238112391124011241112421124311244112451124611247112481124911250112511125211253112541125511256112571125811259112601126111262112631126411265112661126711268112691127011271112721127311274112751127611277112781127911280112811128211283112841128511286112871128811289112901129111292112931129411295112961129711298112991130011301113021130311304113051130611307113081130911310113111131211313113141131511316113171131811319113201132111322113231132411325113261132711328113291133011331113321133311334113351133611337113381133911340113411134211343113441134511346113471134811349113501135111352113531135411355113561135711358113591136011361113621136311364113651136611367113681136911370113711137211373113741137511376113771137811379113801138111382113831138411385113861138711388113891139011391113921139311394113951139611397113981139911400114011140211403114041140511406114071140811409114101141111412114131141411415114161141711418114191142011421114221142311424114251142611427114281142911430114311143211433114341143511436114371143811439114401144111442114431144411445114461144711448114491145011451114521145311454114551145611457114581145911460114611146211463114641146511466114671146811469114701147111472114731147411475114761147711478114791148011481114821148311484114851148611487114881148911490114911149211493114941149511496114971149811499115001150111502115031150411505115061150711508115091151011511115121151311514115151151611517115181151911520115211152211523115241152511526115271152811529115301153111532115331153411535115361153711538115391154011541115421154311544115451154611547115481154911550115511155211553115541155511556115571155811559115601156111562115631156411565115661156711568115691157011571115721157311574115751157611577115781157911580115811158211583115841158511586115871158811589115901159111592115931159411595115961159711598115991160011601116021160311604116051160611607116081160911610116111161211613116141161511616116171161811619116201162111622116231162411625116261162711628116291163011631116321163311634116351163611637116381163911640116411164211643116441164511646116471164811649116501165111652116531165411655116561165711658116591166011661116621166311664116651166611667116681166911670116711167211673116741167511676116771167811679116801168111682116831168411685116861168711688116891169011691116921169311694116951169611697116981169911700117011170211703117041170511706117071170811709117101171111712117131171411715117161171711718117191172011721117221172311724117251172611727117281172911730117311173211733117341173511736117371173811739117401174111742117431174411745117461174711748117491175011751117521175311754117551175611757117581175911760117611176211763117641176511766117671176811769117701177111772117731177411775117761177711778117791178011781117821178311784117851178611787117881178911790117911179211793117941179511796117971179811799118001180111802118031180411805118061180711808118091181011811118121181311814118151181611817118181181911820118211182211823118241182511826118271182811829118301183111832118331183411835118361183711838118391184011841118421184311844118451184611847118481184911850118511185211853118541185511856118571185811859118601186111862118631186411865118661186711868118691187011871118721187311874118751187611877118781187911880118811188211883118841188511886118871188811889118901189111892118931189411895118961189711898118991190011901119021190311904119051190611907119081190911910119111191211913119141191511916119171191811919119201192111922119231192411925119261192711928119291193011931119321193311934119351193611937119381193911940119411194211943119441194511946119471194811949119501195111952119531195411955119561195711958119591196011961119621196311964119651196611967119681196911970119711197211973119741197511976119771197811979119801198111982119831198411985119861198711988119891199011991119921199311994119951199611997119981199912000120011200212003120041200512006120071200812009120101201112012120131201412015120161201712018120191202012021120221202312024120251202612027120281202912030120311203212033120341203512036120371203812039120401204112042120431204412045120461204712048120491205012051120521205312054120551205612057120581205912060120611206212063120641206512066120671206812069120701207112072120731207412075120761207712078120791208012081120821208312084120851208612087120881208912090120911209212093120941209512096120971209812099121001210112102121031210412105121061210712108121091211012111121121211312114121151211612117121181211912120121211212212123121241212512126121271212812129121301213112132121331213412135121361213712138121391214012141121421214312144121451214612147121481214912150121511215212153121541215512156121571215812159121601216112162121631216412165121661216712168121691217012171121721217312174121751217612177121781217912180121811218212183121841218512186121871218812189121901219112192121931219412195121961219712198121991220012201122021220312204122051220612207122081220912210122111221212213122141221512216122171221812219122201222112222122231222412225122261222712228122291223012231122321223312234122351223612237122381223912240122411224212243122441224512246122471224812249122501225112252122531225412255122561225712258122591226012261122621226312264122651226612267122681226912270122711227212273122741227512276122771227812279122801228112282122831228412285122861228712288122891229012291122921229312294122951229612297122981229912300123011230212303123041230512306123071230812309123101231112312123131231412315123161231712318123191232012321123221232312324123251232612327123281232912330123311233212333123341233512336123371233812339123401234112342123431234412345123461234712348123491235012351123521235312354123551235612357123581235912360123611236212363123641236512366123671236812369123701237112372123731237412375123761237712378123791238012381123821238312384123851238612387123881238912390123911239212393123941239512396123971239812399124001240112402124031240412405124061240712408124091241012411124121241312414124151241612417124181241912420124211242212423124241242512426124271242812429124301243112432124331243412435124361243712438124391244012441124421244312444124451244612447124481244912450124511245212453124541245512456124571245812459124601246112462124631246412465124661246712468124691247012471124721247312474124751247612477124781247912480124811248212483124841248512486124871248812489124901249112492124931249412495124961249712498124991250012501125021250312504125051250612507125081250912510125111251212513125141251512516125171251812519125201252112522125231252412525125261252712528125291253012531125321253312534125351253612537125381253912540125411254212543125441254512546125471254812549125501255112552125531255412555125561255712558125591256012561125621256312564125651256612567125681256912570125711257212573125741257512576125771257812579125801258112582125831258412585125861258712588125891259012591125921259312594125951259612597125981259912600126011260212603126041260512606126071260812609126101261112612126131261412615126161261712618126191262012621126221262312624126251262612627126281262912630126311263212633126341263512636126371263812639126401264112642126431264412645126461264712648126491265012651126521265312654126551265612657126581265912660126611266212663126641266512666126671266812669126701267112672126731267412675126761267712678126791268012681126821268312684126851268612687126881268912690126911269212693126941269512696126971269812699127001270112702127031270412705127061270712708127091271012711127121271312714127151271612717127181271912720127211272212723127241272512726127271272812729127301273112732127331273412735127361273712738127391274012741127421274312744127451274612747127481274912750127511275212753127541275512756127571275812759127601276112762127631276412765127661276712768127691277012771127721277312774127751277612777127781277912780127811278212783127841278512786127871278812789127901279112792127931279412795127961279712798127991280012801128021280312804128051280612807128081280912810128111281212813128141281512816128171281812819128201282112822128231282412825128261282712828128291283012831128321283312834128351283612837128381283912840128411284212843128441284512846128471284812849128501285112852128531285412855128561285712858128591286012861128621286312864128651286612867128681286912870128711287212873128741287512876128771287812879128801288112882128831288412885128861288712888128891289012891128921289312894128951289612897128981289912900129011290212903129041290512906129071290812909129101291112912129131291412915129161291712918129191292012921129221292312924129251292612927129281292912930129311293212933129341293512936129371293812939129401294112942129431294412945129461294712948129491295012951129521295312954129551295612957129581295912960129611296212963129641296512966129671296812969129701297112972129731297412975129761297712978129791298012981129821298312984129851298612987129881298912990129911299212993129941299512996129971299812999130001300113002130031300413005130061300713008130091301013011130121301313014130151301613017130181301913020130211302213023130241302513026130271302813029130301303113032130331303413035130361303713038130391304013041130421304313044130451304613047130481304913050130511305213053130541305513056130571305813059130601306113062130631306413065130661306713068130691307013071130721307313074130751307613077130781307913080130811308213083130841308513086130871308813089130901309113092130931309413095130961309713098130991310013101131021310313104131051310613107131081310913110131111311213113131141311513116131171311813119131201312113122131231312413125131261312713128131291313013131131321313313134131351313613137131381313913140131411314213143131441314513146131471314813149131501315113152131531315413155131561315713158131591316013161131621316313164131651316613167131681316913170131711317213173131741317513176131771317813179131801318113182131831318413185131861318713188131891319013191131921319313194131951319613197131981319913200132011320213203132041320513206132071320813209132101321113212132131321413215132161321713218132191322013221132221322313224132251322613227132281322913230132311323213233132341323513236132371323813239132401324113242132431324413245132461324713248132491325013251132521325313254132551325613257132581325913260132611326213263132641326513266132671326813269132701327113272132731327413275132761327713278132791328013281132821328313284132851328613287132881328913290132911329213293132941329513296132971329813299133001330113302133031330413305133061330713308133091331013311133121331313314133151331613317133181331913320133211332213323133241332513326133271332813329133301333113332133331333413335133361333713338133391334013341133421334313344133451334613347133481334913350133511335213353133541335513356133571335813359133601336113362133631336413365133661336713368133691337013371133721337313374133751337613377133781337913380133811338213383133841338513386133871338813389133901339113392133931339413395133961339713398133991340013401134021340313404134051340613407134081340913410134111341213413134141341513416134171341813419134201342113422134231342413425134261342713428134291343013431134321343313434134351343613437134381343913440134411344213443134441344513446134471344813449134501345113452134531345413455134561345713458134591346013461134621346313464134651346613467134681346913470134711347213473134741347513476134771347813479134801348113482134831348413485134861348713488134891349013491134921349313494134951349613497134981349913500135011350213503135041350513506135071350813509135101351113512135131351413515135161351713518135191352013521135221352313524135251352613527135281352913530135311353213533135341353513536135371353813539135401354113542135431354413545135461354713548135491355013551135521355313554135551355613557135581355913560135611356213563135641356513566135671356813569135701357113572135731357413575135761357713578135791358013581135821358313584135851358613587135881358913590135911359213593135941359513596135971359813599136001360113602136031360413605136061360713608136091361013611136121361313614136151361613617136181361913620136211362213623136241362513626136271362813629136301363113632136331363413635136361363713638136391364013641136421364313644136451364613647136481364913650136511365213653136541365513656136571365813659136601366113662136631366413665136661366713668136691367013671136721367313674136751367613677136781367913680136811368213683136841368513686136871368813689136901369113692136931369413695136961369713698136991370013701137021370313704137051370613707137081370913710137111371213713137141371513716137171371813719137201372113722137231372413725137261372713728137291373013731137321373313734137351373613737137381373913740137411374213743137441374513746137471374813749137501375113752137531375413755137561375713758137591376013761137621376313764137651376613767137681376913770137711377213773137741377513776137771377813779137801378113782137831378413785137861378713788137891379013791137921379313794137951379613797137981379913800138011380213803138041380513806138071380813809138101381113812138131381413815138161381713818138191382013821138221382313824138251382613827138281382913830138311383213833138341383513836138371383813839138401384113842138431384413845138461384713848138491385013851138521385313854138551385613857138581385913860138611386213863138641386513866138671386813869138701387113872138731387413875138761387713878138791388013881138821388313884138851388613887138881388913890138911389213893138941389513896138971389813899139001390113902139031390413905139061390713908139091391013911139121391313914139151391613917139181391913920139211392213923139241392513926139271392813929139301393113932139331393413935139361393713938139391394013941139421394313944139451394613947139481394913950139511395213953139541395513956139571395813959139601396113962139631396413965139661396713968139691397013971139721397313974139751397613977139781397913980139811398213983139841398513986139871398813989139901399113992139931399413995139961399713998139991400014001140021400314004140051400614007140081400914010140111401214013140141401514016140171401814019140201402114022140231402414025140261402714028140291403014031140321403314034140351403614037140381403914040140411404214043140441404514046140471404814049140501405114052140531405414055140561405714058140591406014061140621406314064140651406614067140681406914070140711407214073140741407514076140771407814079140801408114082140831408414085140861408714088140891409014091140921409314094140951409614097140981409914100141011410214103141041410514106141071410814109141101411114112141131411414115141161411714118141191412014121141221412314124141251412614127141281412914130141311413214133141341413514136141371413814139141401414114142141431414414145141461414714148141491415014151141521415314154141551415614157141581415914160141611416214163141641416514166141671416814169141701417114172141731417414175141761417714178141791418014181141821418314184141851418614187141881418914190141911419214193141941419514196141971419814199142001420114202142031420414205142061420714208142091421014211142121421314214142151421614217142181421914220142211422214223142241422514226142271422814229142301423114232142331423414235142361423714238142391424014241142421424314244142451424614247142481424914250142511425214253142541425514256142571425814259142601426114262142631426414265142661426714268142691427014271142721427314274142751427614277142781427914280142811428214283142841428514286142871428814289142901429114292142931429414295142961429714298142991430014301143021430314304143051430614307143081430914310143111431214313143141431514316143171431814319143201432114322143231432414325143261432714328143291433014331143321433314334143351433614337143381433914340143411434214343143441434514346143471434814349143501435114352143531435414355143561435714358143591436014361143621436314364143651436614367143681436914370143711437214373143741437514376143771437814379143801438114382143831438414385143861438714388143891439014391143921439314394143951439614397143981439914400144011440214403144041440514406144071440814409144101441114412144131441414415144161441714418144191442014421144221442314424144251442614427144281442914430144311443214433144341443514436144371443814439144401444114442144431444414445144461444714448144491445014451144521445314454144551445614457144581445914460144611446214463144641446514466144671446814469144701447114472144731447414475144761447714478144791448014481144821448314484144851448614487144881448914490144911449214493144941449514496144971449814499145001450114502145031450414505145061450714508145091451014511145121451314514145151451614517145181451914520145211452214523145241452514526145271452814529145301453114532145331453414535145361453714538145391454014541145421454314544145451454614547145481454914550145511455214553145541455514556145571455814559145601456114562145631456414565145661456714568145691457014571145721457314574145751457614577145781457914580145811458214583145841458514586145871458814589145901459114592145931459414595145961459714598145991460014601146021460314604146051460614607146081460914610146111461214613146141461514616146171461814619146201462114622146231462414625146261462714628146291463014631146321463314634146351463614637146381463914640146411464214643146441464514646146471464814649146501465114652146531465414655146561465714658146591466014661146621466314664146651466614667146681466914670146711467214673146741467514676146771467814679146801468114682146831468414685146861468714688146891469014691146921469314694146951469614697146981469914700147011470214703147041470514706147071470814709147101471114712147131471414715147161471714718147191472014721147221472314724147251472614727147281472914730147311473214733147341473514736147371473814739147401474114742147431474414745147461474714748147491475014751147521475314754147551475614757147581475914760147611476214763147641476514766147671476814769147701477114772147731477414775147761477714778147791478014781147821478314784147851478614787147881478914790147911479214793147941479514796147971479814799148001480114802148031480414805148061480714808148091481014811148121481314814148151481614817148181481914820148211482214823148241482514826148271482814829148301483114832148331483414835148361483714838148391484014841148421484314844148451484614847148481484914850148511485214853148541485514856148571485814859148601486114862148631486414865148661486714868148691487014871148721487314874148751487614877148781487914880148811488214883148841488514886148871488814889148901489114892148931489414895148961489714898148991490014901149021490314904149051490614907149081490914910149111491214913149141491514916149171491814919149201492114922149231492414925149261492714928149291493014931149321493314934149351493614937149381493914940149411494214943149441494514946149471494814949149501495114952149531495414955149561495714958149591496014961149621496314964149651496614967149681496914970149711497214973149741497514976149771497814979149801498114982149831498414985149861498714988149891499014991149921499314994149951499614997149981499915000150011500215003150041500515006150071500815009150101501115012150131501415015150161501715018150191502015021150221502315024150251502615027150281502915030150311503215033150341503515036150371503815039150401504115042150431504415045150461504715048150491505015051150521505315054150551505615057150581505915060150611506215063150641506515066150671506815069150701507115072150731507415075150761507715078150791508015081150821508315084150851508615087150881508915090150911509215093150941509515096150971509815099151001510115102151031510415105151061510715108151091511015111151121511315114151151511615117151181511915120151211512215123151241512515126151271512815129151301513115132151331513415135151361513715138151391514015141151421514315144151451514615147151481514915150151511515215153151541515515156151571515815159151601516115162151631516415165151661516715168151691517015171151721517315174151751517615177151781517915180151811518215183151841518515186151871518815189151901519115192151931519415195151961519715198151991520015201152021520315204152051520615207152081520915210152111521215213152141521515216152171521815219152201522115222152231522415225152261522715228152291523015231152321523315234152351523615237152381523915240152411524215243152441524515246152471524815249152501525115252152531525415255152561525715258152591526015261152621526315264152651526615267152681526915270152711527215273152741527515276152771527815279152801528115282152831528415285152861528715288152891529015291152921529315294152951529615297152981529915300153011530215303153041530515306153071530815309153101531115312153131531415315153161531715318153191532015321153221532315324153251532615327153281532915330153311533215333153341533515336153371533815339153401534115342153431534415345153461534715348153491535015351153521535315354153551535615357153581535915360153611536215363153641536515366153671536815369153701537115372153731537415375153761537715378153791538015381153821538315384153851538615387153881538915390153911539215393153941539515396153971539815399154001540115402154031540415405154061540715408154091541015411154121541315414154151541615417154181541915420154211542215423154241542515426154271542815429154301543115432154331543415435154361543715438154391544015441154421544315444154451544615447154481544915450154511545215453154541545515456154571545815459154601546115462154631546415465154661546715468154691547015471154721547315474154751547615477154781547915480154811548215483154841548515486154871548815489154901549115492154931549415495154961549715498154991550015501155021550315504155051550615507155081550915510155111551215513155141551515516155171551815519155201552115522155231552415525155261552715528155291553015531155321553315534155351553615537155381553915540155411554215543155441554515546155471554815549155501555115552155531555415555155561555715558155591556015561155621556315564155651556615567155681556915570155711557215573155741557515576155771557815579155801558115582155831558415585155861558715588155891559015591155921559315594155951559615597155981559915600156011560215603156041560515606156071560815609156101561115612156131561415615156161561715618156191562015621156221562315624156251562615627156281562915630156311563215633156341563515636156371563815639156401564115642156431564415645156461564715648156491565015651156521565315654156551565615657156581565915660156611566215663156641566515666156671566815669156701567115672156731567415675156761567715678156791568015681156821568315684156851568615687156881568915690156911569215693156941569515696156971569815699157001570115702157031570415705157061570715708157091571015711157121571315714157151571615717157181571915720157211572215723157241572515726157271572815729157301573115732157331573415735157361573715738157391574015741157421574315744157451574615747157481574915750157511575215753157541575515756157571575815759157601576115762157631576415765157661576715768157691577015771157721577315774157751577615777157781577915780157811578215783157841578515786157871578815789157901579115792157931579415795157961579715798157991580015801158021580315804158051580615807158081580915810158111581215813158141581515816158171581815819158201582115822158231582415825158261582715828158291583015831158321583315834158351583615837158381583915840158411584215843158441584515846158471584815849158501585115852158531585415855158561585715858158591586015861158621586315864158651586615867158681586915870158711587215873158741587515876158771587815879158801588115882158831588415885158861588715888158891589015891158921589315894158951589615897158981589915900159011590215903159041590515906159071590815909159101591115912159131591415915159161591715918159191592015921159221592315924159251592615927159281592915930159311593215933159341593515936159371593815939159401594115942159431594415945159461594715948159491595015951159521595315954159551595615957159581595915960159611596215963159641596515966159671596815969159701597115972159731597415975159761597715978159791598015981159821598315984159851598615987159881598915990159911599215993159941599515996159971599815999160001600116002160031600416005160061600716008160091601016011160121601316014160151601616017160181601916020160211602216023160241602516026160271602816029160301603116032160331603416035160361603716038160391604016041160421604316044160451604616047160481604916050160511605216053160541605516056160571605816059160601606116062160631606416065160661606716068160691607016071160721607316074160751607616077160781607916080160811608216083160841608516086160871608816089160901609116092160931609416095160961609716098160991610016101161021610316104161051610616107161081610916110161111611216113161141611516116161171611816119161201612116122161231612416125161261612716128161291613016131161321613316134161351613616137161381613916140161411614216143161441614516146161471614816149161501615116152161531615416155161561615716158161591616016161161621616316164161651616616167161681616916170161711617216173161741617516176161771617816179161801618116182161831618416185161861618716188161891619016191161921619316194161951619616197161981619916200162011620216203162041620516206162071620816209162101621116212162131621416215162161621716218162191622016221162221622316224162251622616227162281622916230162311623216233162341623516236162371623816239162401624116242162431624416245162461624716248162491625016251162521625316254162551625616257162581625916260162611626216263162641626516266162671626816269162701627116272162731627416275162761627716278162791628016281162821628316284162851628616287162881628916290162911629216293162941629516296162971629816299163001630116302163031630416305163061630716308163091631016311163121631316314163151631616317163181631916320163211632216323163241632516326163271632816329163301633116332163331633416335163361633716338163391634016341163421634316344163451634616347163481634916350163511635216353163541635516356163571635816359163601636116362163631636416365163661636716368163691637016371163721637316374163751637616377163781637916380163811638216383163841638516386163871638816389163901639116392163931639416395163961639716398163991640016401164021640316404164051640616407164081640916410164111641216413164141641516416164171641816419164201642116422164231642416425164261642716428164291643016431164321643316434164351643616437164381643916440164411644216443164441644516446164471644816449164501645116452164531645416455164561645716458164591646016461164621646316464164651646616467164681646916470164711647216473164741647516476164771647816479164801648116482164831648416485164861648716488164891649016491164921649316494164951649616497164981649916500165011650216503165041650516506165071650816509165101651116512165131651416515165161651716518165191652016521165221652316524165251652616527165281652916530165311653216533165341653516536165371653816539165401654116542165431654416545165461654716548165491655016551165521655316554165551655616557165581655916560165611656216563165641656516566165671656816569165701657116572165731657416575165761657716578165791658016581165821658316584165851658616587165881658916590165911659216593165941659516596165971659816599166001660116602166031660416605166061660716608166091661016611166121661316614166151661616617166181661916620166211662216623166241662516626166271662816629166301663116632166331663416635166361663716638166391664016641166421664316644166451664616647166481664916650166511665216653166541665516656166571665816659166601666116662166631666416665166661666716668166691667016671166721667316674166751667616677166781667916680166811668216683166841668516686166871668816689166901669116692166931669416695166961669716698166991670016701167021670316704167051670616707167081670916710167111671216713167141671516716167171671816719167201672116722167231672416725167261672716728167291673016731167321673316734167351673616737167381673916740167411674216743167441674516746167471674816749167501675116752167531675416755167561675716758167591676016761167621676316764167651676616767167681676916770167711677216773167741677516776167771677816779167801678116782167831678416785167861678716788167891679016791167921679316794167951679616797167981679916800168011680216803168041680516806168071680816809168101681116812168131681416815168161681716818168191682016821168221682316824168251682616827168281682916830168311683216833168341683516836168371683816839168401684116842168431684416845168461684716848168491685016851168521685316854168551685616857168581685916860168611686216863168641686516866168671686816869168701687116872168731687416875168761687716878168791688016881168821688316884168851688616887168881688916890168911689216893168941689516896168971689816899169001690116902169031690416905169061690716908169091691016911169121691316914169151691616917169181691916920169211692216923169241692516926169271692816929169301693116932169331693416935169361693716938169391694016941169421694316944169451694616947169481694916950169511695216953169541695516956169571695816959169601696116962169631696416965169661696716968169691697016971169721697316974169751697616977169781697916980169811698216983169841698516986169871698816989169901699116992169931699416995169961699716998169991700017001170021700317004170051700617007170081700917010170111701217013170141701517016170171701817019170201702117022170231702417025170261702717028170291703017031170321703317034170351703617037170381703917040170411704217043170441704517046170471704817049170501705117052170531705417055170561705717058170591706017061170621706317064170651706617067170681706917070170711707217073170741707517076170771707817079170801708117082170831708417085170861708717088170891709017091170921709317094170951709617097170981709917100171011710217103171041710517106171071710817109171101711117112171131711417115171161711717118171191712017121171221712317124171251712617127171281712917130171311713217133171341713517136171371713817139171401714117142171431714417145171461714717148171491715017151171521715317154171551715617157171581715917160171611716217163171641716517166171671716817169171701717117172171731717417175171761717717178171791718017181171821718317184171851718617187171881718917190171911719217193171941719517196171971719817199172001720117202172031720417205172061720717208172091721017211172121721317214172151721617217172181721917220172211722217223172241722517226172271722817229172301723117232172331723417235172361723717238172391724017241172421724317244172451724617247172481724917250172511725217253172541725517256172571725817259172601726117262172631726417265172661726717268172691727017271172721727317274172751727617277172781727917280172811728217283172841728517286172871728817289172901729117292172931729417295172961729717298172991730017301173021730317304173051730617307173081730917310173111731217313173141731517316173171731817319173201732117322173231732417325173261732717328173291733017331173321733317334173351733617337173381733917340173411734217343173441734517346173471734817349173501735117352173531735417355173561735717358173591736017361173621736317364173651736617367173681736917370173711737217373173741737517376173771737817379173801738117382173831738417385173861738717388173891739017391173921739317394173951739617397173981739917400174011740217403174041740517406174071740817409174101741117412174131741417415174161741717418174191742017421174221742317424174251742617427174281742917430174311743217433174341743517436174371743817439174401744117442174431744417445174461744717448174491745017451174521745317454174551745617457174581745917460174611746217463174641746517466174671746817469174701747117472174731747417475174761747717478174791748017481174821748317484174851748617487174881748917490174911749217493174941749517496174971749817499175001750117502175031750417505175061750717508175091751017511175121751317514175151751617517175181751917520175211752217523175241752517526175271752817529175301753117532175331753417535175361753717538175391754017541175421754317544175451754617547175481754917550175511755217553175541755517556175571755817559175601756117562175631756417565175661756717568175691757017571175721757317574175751757617577175781757917580175811758217583175841758517586175871758817589175901759117592175931759417595175961759717598175991760017601176021760317604176051760617607176081760917610176111761217613176141761517616176171761817619176201762117622176231762417625176261762717628176291763017631176321763317634176351763617637176381763917640176411764217643176441764517646176471764817649176501765117652176531765417655176561765717658176591766017661176621766317664176651766617667176681766917670176711767217673176741767517676176771767817679176801768117682176831768417685176861768717688176891769017691176921769317694176951769617697176981769917700177011770217703177041770517706177071770817709177101771117712177131771417715177161771717718177191772017721177221772317724177251772617727177281772917730177311773217733177341773517736177371773817739177401774117742177431774417745177461774717748177491775017751177521775317754177551775617757177581775917760177611776217763177641776517766177671776817769177701777117772177731777417775177761777717778177791778017781177821778317784177851778617787177881778917790177911779217793177941779517796177971779817799178001780117802178031780417805178061780717808178091781017811178121781317814178151781617817178181781917820178211782217823178241782517826178271782817829178301783117832178331783417835178361783717838178391784017841178421784317844178451784617847178481784917850178511785217853178541785517856178571785817859178601786117862178631786417865178661786717868178691787017871178721787317874178751787617877178781787917880178811788217883178841788517886178871788817889178901789117892178931789417895178961789717898178991790017901179021790317904179051790617907179081790917910179111791217913179141791517916179171791817919179201792117922179231792417925179261792717928179291793017931179321793317934179351793617937179381793917940179411794217943179441794517946179471794817949179501795117952179531795417955179561795717958179591796017961179621796317964179651796617967179681796917970179711797217973179741797517976179771797817979179801798117982179831798417985179861798717988179891799017991179921799317994179951799617997179981799918000180011800218003180041800518006180071800818009180101801118012180131801418015180161801718018180191802018021180221802318024180251802618027180281802918030180311803218033180341803518036180371803818039180401804118042180431804418045180461804718048180491805018051180521805318054180551805618057180581805918060180611806218063180641806518066180671806818069180701807118072180731807418075180761807718078180791808018081180821808318084180851808618087180881808918090180911809218093180941809518096180971809818099181001810118102181031810418105181061810718108181091811018111181121811318114181151811618117181181811918120181211812218123181241812518126181271812818129181301813118132181331813418135181361813718138181391814018141181421814318144181451814618147181481814918150181511815218153181541815518156181571815818159181601816118162181631816418165181661816718168181691817018171181721817318174181751817618177181781817918180181811818218183181841818518186181871818818189181901819118192181931819418195181961819718198181991820018201182021820318204182051820618207182081820918210182111821218213182141821518216182171821818219182201822118222182231822418225182261822718228182291823018231182321823318234182351823618237182381823918240182411824218243182441824518246182471824818249182501825118252182531825418255182561825718258182591826018261182621826318264182651826618267182681826918270182711827218273182741827518276182771827818279182801828118282182831828418285182861828718288182891829018291182921829318294182951829618297182981829918300183011830218303183041830518306183071830818309183101831118312183131831418315183161831718318183191832018321183221832318324183251832618327183281832918330183311833218333183341833518336183371833818339183401834118342183431834418345183461834718348183491835018351183521835318354183551835618357183581835918360183611836218363183641836518366183671836818369183701837118372183731837418375183761837718378183791838018381183821838318384183851838618387183881838918390183911839218393183941839518396183971839818399184001840118402184031840418405184061840718408184091841018411184121841318414184151841618417184181841918420184211842218423184241842518426184271842818429184301843118432184331843418435184361843718438184391844018441184421844318444184451844618447184481844918450184511845218453184541845518456184571845818459184601846118462184631846418465184661846718468184691847018471184721847318474184751847618477184781847918480184811848218483184841848518486184871848818489184901849118492184931849418495184961849718498184991850018501185021850318504185051850618507185081850918510185111851218513185141851518516185171851818519185201852118522185231852418525185261852718528185291853018531185321853318534185351853618537185381853918540185411854218543185441854518546185471854818549185501855118552185531855418555185561855718558185591856018561185621856318564185651856618567185681856918570185711857218573185741857518576185771857818579185801858118582185831858418585185861858718588185891859018591185921859318594185951859618597185981859918600186011860218603186041860518606186071860818609186101861118612186131861418615186161861718618186191862018621186221862318624186251862618627186281862918630186311863218633186341863518636186371863818639186401864118642186431864418645186461864718648186491865018651186521865318654186551865618657186581865918660186611866218663186641866518666186671866818669186701867118672186731867418675186761867718678186791868018681186821868318684186851868618687186881868918690186911869218693186941869518696186971869818699187001870118702187031870418705187061870718708187091871018711187121871318714187151871618717187181871918720187211872218723187241872518726187271872818729187301873118732187331873418735187361873718738187391874018741187421874318744187451874618747187481874918750187511875218753187541875518756187571875818759187601876118762187631876418765187661876718768187691877018771187721877318774187751877618777187781877918780187811878218783187841878518786187871878818789187901879118792187931879418795187961879718798187991880018801188021880318804188051880618807188081880918810188111881218813188141881518816188171881818819188201882118822188231882418825188261882718828188291883018831188321883318834188351883618837188381883918840188411884218843188441884518846188471884818849188501885118852188531885418855188561885718858188591886018861188621886318864188651886618867188681886918870188711887218873188741887518876188771887818879188801888118882188831888418885188861888718888188891889018891188921889318894188951889618897188981889918900189011890218903189041890518906189071890818909189101891118912189131891418915189161891718918189191892018921189221892318924189251892618927189281892918930189311893218933189341893518936189371893818939189401894118942189431894418945189461894718948189491895018951189521895318954189551895618957189581895918960189611896218963189641896518966189671896818969189701897118972189731897418975189761897718978189791898018981189821898318984189851898618987189881898918990189911899218993189941899518996189971899818999190001900119002190031900419005190061900719008190091901019011190121901319014190151901619017190181901919020190211902219023190241902519026190271902819029190301903119032190331903419035190361903719038190391904019041190421904319044190451904619047190481904919050190511905219053190541905519056190571905819059190601906119062190631906419065190661906719068190691907019071190721907319074190751907619077190781907919080190811908219083190841908519086190871908819089190901909119092190931909419095190961909719098190991910019101191021910319104191051910619107191081910919110191111911219113191141911519116191171911819119191201912119122191231912419125191261912719128191291913019131191321913319134191351913619137191381913919140191411914219143191441914519146191471914819149191501915119152191531915419155191561915719158191591916019161191621916319164191651916619167191681916919170191711917219173191741917519176191771917819179191801918119182191831918419185191861918719188191891919019191191921919319194191951919619197191981919919200192011920219203192041920519206192071920819209192101921119212192131921419215192161921719218192191922019221192221922319224192251922619227192281922919230192311923219233192341923519236192371923819239192401924119242192431924419245192461924719248192491925019251192521925319254192551925619257192581925919260192611926219263192641926519266192671926819269192701927119272192731927419275192761927719278192791928019281192821928319284192851928619287192881928919290192911929219293192941929519296192971929819299193001930119302193031930419305193061930719308193091931019311193121931319314193151931619317193181931919320193211932219323193241932519326193271932819329193301933119332193331933419335193361933719338193391934019341193421934319344193451934619347193481934919350193511935219353193541935519356193571935819359193601936119362193631936419365193661936719368193691937019371193721937319374193751937619377193781937919380193811938219383193841938519386193871938819389193901939119392193931939419395193961939719398193991940019401194021940319404194051940619407194081940919410194111941219413194141941519416194171941819419194201942119422194231942419425194261942719428194291943019431194321943319434194351943619437194381943919440194411944219443194441944519446194471944819449194501945119452194531945419455194561945719458194591946019461194621946319464194651946619467194681946919470194711947219473194741947519476194771947819479194801948119482194831948419485194861948719488194891949019491194921949319494194951949619497194981949919500195011950219503195041950519506195071950819509195101951119512195131951419515195161951719518195191952019521195221952319524195251952619527195281952919530195311953219533195341953519536195371953819539195401954119542195431954419545195461954719548195491955019551195521955319554195551955619557195581955919560195611956219563195641956519566195671956819569195701957119572195731957419575195761957719578195791958019581195821958319584195851958619587195881958919590195911959219593195941959519596195971959819599196001960119602196031960419605196061960719608196091961019611196121961319614196151961619617196181961919620196211962219623196241962519626196271962819629196301963119632196331963419635196361963719638196391964019641196421964319644196451964619647196481964919650196511965219653196541965519656196571965819659196601966119662196631966419665196661966719668196691967019671196721967319674196751967619677196781967919680196811968219683196841968519686196871968819689196901969119692196931969419695196961969719698196991970019701197021970319704197051970619707197081970919710197111971219713197141971519716197171971819719197201972119722197231972419725197261972719728197291973019731197321973319734197351973619737197381973919740197411974219743197441974519746197471974819749197501975119752197531975419755197561975719758197591976019761197621976319764197651976619767197681976919770197711977219773197741977519776197771977819779197801978119782197831978419785197861978719788197891979019791197921979319794197951979619797197981979919800198011980219803198041980519806198071980819809198101981119812198131981419815198161981719818198191982019821198221982319824198251982619827198281982919830198311983219833198341983519836198371983819839198401984119842198431984419845198461984719848198491985019851198521985319854198551985619857198581985919860198611986219863198641986519866198671986819869198701987119872198731987419875198761987719878198791988019881198821988319884198851988619887198881988919890198911989219893198941989519896198971989819899199001990119902199031990419905199061990719908199091991019911199121991319914199151991619917199181991919920199211992219923199241992519926199271992819929199301993119932199331993419935199361993719938199391994019941199421994319944199451994619947199481994919950199511995219953199541995519956199571995819959199601996119962199631996419965199661996719968199691997019971199721997319974199751997619977199781997919980199811998219983199841998519986199871998819989199901999119992199931999419995199961999719998199992000020001200022000320004200052000620007200082000920010200112001220013200142001520016200172001820019200202002120022200232002420025200262002720028200292003020031200322003320034200352003620037200382003920040200412004220043200442004520046200472004820049200502005120052200532005420055200562005720058200592006020061200622006320064200652006620067200682006920070200712007220073200742007520076200772007820079200802008120082200832008420085200862008720088200892009020091200922009320094200952009620097200982009920100201012010220103201042010520106201072010820109201102011120112201132011420115201162011720118201192012020121201222012320124201252012620127201282012920130201312013220133201342013520136201372013820139201402014120142201432014420145201462014720148201492015020151201522015320154201552015620157201582015920160201612016220163201642016520166201672016820169201702017120172201732017420175201762017720178201792018020181201822018320184201852018620187201882018920190201912019220193201942019520196201972019820199202002020120202202032020420205202062020720208202092021020211202122021320214202152021620217202182021920220202212022220223202242022520226202272022820229202302023120232202332023420235202362023720238202392024020241202422024320244202452024620247202482024920250202512025220253202542025520256202572025820259202602026120262202632026420265202662026720268202692027020271202722027320274202752027620277202782027920280202812028220283202842028520286202872028820289202902029120292202932029420295202962029720298202992030020301203022030320304203052030620307203082030920310203112031220313203142031520316203172031820319203202032120322203232032420325203262032720328203292033020331203322033320334203352033620337203382033920340203412034220343203442034520346203472034820349203502035120352203532035420355203562035720358203592036020361203622036320364203652036620367203682036920370203712037220373203742037520376203772037820379203802038120382203832038420385203862038720388203892039020391203922039320394203952039620397203982039920400204012040220403204042040520406204072040820409204102041120412204132041420415204162041720418204192042020421204222042320424204252042620427204282042920430204312043220433204342043520436204372043820439204402044120442204432044420445204462044720448204492045020451204522045320454204552045620457204582045920460204612046220463204642046520466204672046820469204702047120472204732047420475204762047720478204792048020481204822048320484204852048620487204882048920490204912049220493204942049520496204972049820499205002050120502205032050420505205062050720508205092051020511205122051320514205152051620517205182051920520205212052220523205242052520526205272052820529205302053120532205332053420535205362053720538205392054020541205422054320544205452054620547205482054920550205512055220553205542055520556205572055820559205602056120562205632056420565205662056720568205692057020571205722057320574205752057620577205782057920580205812058220583205842058520586205872058820589205902059120592205932059420595205962059720598205992060020601206022060320604206052060620607206082060920610206112061220613206142061520616206172061820619206202062120622206232062420625206262062720628206292063020631206322063320634206352063620637206382063920640206412064220643206442064520646206472064820649206502065120652206532065420655206562065720658206592066020661206622066320664206652066620667206682066920670206712067220673206742067520676206772067820679206802068120682206832068420685206862068720688206892069020691206922069320694206952069620697206982069920700207012070220703207042070520706207072070820709207102071120712207132071420715207162071720718207192072020721207222072320724207252072620727207282072920730207312073220733207342073520736207372073820739207402074120742207432074420745207462074720748207492075020751207522075320754207552075620757207582075920760207612076220763207642076520766207672076820769207702077120772207732077420775207762077720778207792078020781207822078320784207852078620787207882078920790207912079220793207942079520796207972079820799208002080120802208032080420805208062080720808208092081020811208122081320814208152081620817208182081920820208212082220823208242082520826208272082820829208302083120832208332083420835208362083720838208392084020841208422084320844208452084620847208482084920850208512085220853208542085520856208572085820859208602086120862208632086420865208662086720868208692087020871208722087320874208752087620877208782087920880208812088220883208842088520886208872088820889208902089120892208932089420895208962089720898208992090020901209022090320904209052090620907209082090920910209112091220913209142091520916209172091820919209202092120922209232092420925209262092720928209292093020931209322093320934209352093620937209382093920940209412094220943209442094520946209472094820949209502095120952209532095420955209562095720958209592096020961209622096320964209652096620967209682096920970209712097220973209742097520976209772097820979209802098120982209832098420985209862098720988209892099020991209922099320994209952099620997209982099921000210012100221003210042100521006210072100821009210102101121012210132101421015210162101721018210192102021021210222102321024210252102621027210282102921030210312103221033210342103521036210372103821039210402104121042210432104421045210462104721048210492105021051210522105321054210552105621057210582105921060210612106221063210642106521066210672106821069210702107121072210732107421075210762107721078210792108021081210822108321084210852108621087210882108921090210912109221093210942109521096210972109821099211002110121102211032110421105211062110721108211092111021111211122111321114211152111621117211182111921120211212112221123211242112521126211272112821129211302113121132211332113421135211362113721138211392114021141211422114321144211452114621147211482114921150211512115221153211542115521156211572115821159211602116121162211632116421165211662116721168211692117021171211722117321174211752117621177211782117921180211812118221183211842118521186211872118821189211902119121192211932119421195211962119721198211992120021201212022120321204212052120621207212082120921210212112121221213212142121521216212172121821219212202122121222212232122421225212262122721228212292123021231212322123321234212352123621237212382123921240212412124221243212442124521246212472124821249212502125121252212532125421255212562125721258212592126021261212622126321264212652126621267212682126921270212712127221273212742127521276212772127821279212802128121282212832128421285212862128721288212892129021291212922129321294212952129621297212982129921300213012130221303213042130521306213072130821309213102131121312213132131421315213162131721318213192132021321213222132321324213252132621327213282132921330213312133221333213342133521336213372133821339213402134121342213432134421345213462134721348213492135021351213522135321354213552135621357213582135921360213612136221363213642136521366213672136821369213702137121372213732137421375213762137721378213792138021381213822138321384213852138621387213882138921390213912139221393213942139521396213972139821399214002140121402214032140421405214062140721408214092141021411214122141321414214152141621417214182141921420214212142221423214242142521426214272142821429214302143121432214332143421435214362143721438214392144021441214422144321444214452144621447214482144921450214512145221453214542145521456214572145821459214602146121462214632146421465214662146721468214692147021471214722147321474214752147621477214782147921480214812148221483214842148521486214872148821489214902149121492214932149421495214962149721498214992150021501215022150321504215052150621507215082150921510215112151221513215142151521516215172151821519215202152121522215232152421525215262152721528215292153021531215322153321534215352153621537215382153921540215412154221543215442154521546215472154821549215502155121552215532155421555215562155721558215592156021561215622156321564215652156621567215682156921570215712157221573215742157521576215772157821579215802158121582215832158421585215862158721588215892159021591215922159321594215952159621597215982159921600216012160221603216042160521606216072160821609216102161121612216132161421615216162161721618216192162021621216222162321624216252162621627216282162921630216312163221633216342163521636216372163821639216402164121642216432164421645216462164721648216492165021651216522165321654216552165621657216582165921660216612166221663216642166521666216672166821669216702167121672216732167421675216762167721678216792168021681216822168321684216852168621687216882168921690216912169221693216942169521696216972169821699217002170121702217032170421705217062170721708217092171021711217122171321714217152171621717217182171921720217212172221723217242172521726217272172821729217302173121732217332173421735217362173721738217392174021741217422174321744217452174621747217482174921750217512175221753217542175521756217572175821759217602176121762217632176421765217662176721768217692177021771217722177321774217752177621777217782177921780217812178221783217842178521786217872178821789217902179121792217932179421795217962179721798217992180021801218022180321804218052180621807218082180921810218112181221813218142181521816218172181821819218202182121822218232182421825218262182721828218292183021831218322183321834218352183621837218382183921840218412184221843218442184521846218472184821849218502185121852218532185421855218562185721858218592186021861218622186321864218652186621867218682186921870218712187221873218742187521876218772187821879218802188121882218832188421885218862188721888218892189021891218922189321894218952189621897218982189921900219012190221903219042190521906219072190821909219102191121912219132191421915219162191721918219192192021921219222192321924219252192621927219282192921930219312193221933219342193521936219372193821939219402194121942219432194421945219462194721948219492195021951219522195321954219552195621957219582195921960219612196221963219642196521966219672196821969219702197121972219732197421975219762197721978219792198021981219822198321984219852198621987219882198921990219912199221993219942199521996219972199821999220002200122002220032200422005220062200722008220092201022011220122201322014220152201622017220182201922020220212202222023220242202522026220272202822029220302203122032220332203422035220362203722038220392204022041220422204322044220452204622047220482204922050220512205222053220542205522056220572205822059220602206122062220632206422065220662206722068220692207022071220722207322074220752207622077220782207922080220812208222083220842208522086220872208822089220902209122092220932209422095220962209722098220992210022101221022210322104221052210622107221082210922110221112211222113221142211522116221172211822119221202212122122221232212422125221262212722128221292213022131221322213322134221352213622137221382213922140221412214222143221442214522146221472214822149221502215122152221532215422155221562215722158221592216022161221622216322164221652216622167221682216922170221712217222173221742217522176221772217822179221802218122182221832218422185221862218722188221892219022191221922219322194221952219622197221982219922200222012220222203222042220522206222072220822209222102221122212222132221422215222162221722218222192222022221222222222322224222252222622227222282222922230222312223222233222342223522236222372223822239222402224122242222432224422245222462224722248222492225022251222522225322254222552225622257222582225922260222612226222263222642226522266222672226822269222702227122272222732227422275222762227722278222792228022281222822228322284222852228622287222882228922290222912229222293222942229522296222972229822299223002230122302223032230422305223062230722308223092231022311223122231322314223152231622317223182231922320223212232222323223242232522326223272232822329223302233122332223332233422335223362233722338223392234022341223422234322344223452234622347223482234922350223512235222353223542235522356223572235822359223602236122362223632236422365223662236722368223692237022371223722237322374223752237622377223782237922380223812238222383223842238522386223872238822389223902239122392223932239422395223962239722398223992240022401224022240322404224052240622407224082240922410224112241222413224142241522416224172241822419224202242122422224232242422425224262242722428224292243022431224322243322434224352243622437224382243922440224412244222443224442244522446224472244822449224502245122452224532245422455224562245722458224592246022461224622246322464224652246622467224682246922470224712247222473224742247522476224772247822479224802248122482224832248422485224862248722488224892249022491224922249322494224952249622497224982249922500225012250222503225042250522506225072250822509225102251122512225132251422515225162251722518225192252022521225222252322524225252252622527225282252922530225312253222533225342253522536225372253822539225402254122542225432254422545225462254722548225492255022551225522255322554225552255622557225582255922560225612256222563225642256522566225672256822569225702257122572225732257422575225762257722578225792258022581225822258322584225852258622587225882258922590225912259222593225942259522596225972259822599226002260122602226032260422605226062260722608226092261022611226122261322614226152261622617226182261922620226212262222623226242262522626226272262822629226302263122632226332263422635226362263722638226392264022641226422264322644226452264622647226482264922650226512265222653226542265522656226572265822659226602266122662226632266422665226662266722668226692267022671226722267322674226752267622677226782267922680226812268222683226842268522686226872268822689226902269122692226932269422695226962269722698226992270022701227022270322704227052270622707227082270922710227112271222713227142271522716227172271822719227202272122722227232272422725227262272722728227292273022731227322273322734227352273622737227382273922740227412274222743227442274522746227472274822749227502275122752227532275422755227562275722758227592276022761227622276322764227652276622767227682276922770227712277222773227742277522776227772277822779227802278122782227832278422785227862278722788227892279022791227922279322794227952279622797227982279922800228012280222803228042280522806228072280822809228102281122812228132281422815228162281722818228192282022821228222282322824228252282622827228282282922830228312283222833228342283522836228372283822839228402284122842228432284422845228462284722848228492285022851228522285322854228552285622857228582285922860228612286222863228642286522866228672286822869228702287122872228732287422875228762287722878228792288022881228822288322884228852288622887228882288922890228912289222893228942289522896228972289822899229002290122902229032290422905229062290722908229092291022911229122291322914229152291622917229182291922920229212292222923229242292522926229272292822929229302293122932229332293422935229362293722938229392294022941229422294322944229452294622947229482294922950229512295222953229542295522956229572295822959229602296122962229632296422965229662296722968229692297022971229722297322974229752297622977229782297922980229812298222983229842298522986229872298822989229902299122992229932299422995229962299722998229992300023001230022300323004230052300623007230082300923010230112301223013230142301523016230172301823019230202302123022230232302423025230262302723028230292303023031230322303323034230352303623037230382303923040230412304223043230442304523046230472304823049230502305123052230532305423055230562305723058230592306023061230622306323064230652306623067230682306923070230712307223073230742307523076230772307823079230802308123082230832308423085230862308723088230892309023091230922309323094230952309623097230982309923100231012310223103231042310523106231072310823109231102311123112231132311423115231162311723118231192312023121231222312323124231252312623127231282312923130231312313223133231342313523136231372313823139231402314123142231432314423145231462314723148231492315023151231522315323154231552315623157231582315923160231612316223163231642316523166231672316823169231702317123172231732317423175231762317723178231792318023181231822318323184231852318623187231882318923190231912319223193231942319523196231972319823199232002320123202232032320423205232062320723208232092321023211232122321323214232152321623217232182321923220232212322223223232242322523226232272322823229232302323123232232332323423235232362323723238232392324023241232422324323244232452324623247232482324923250232512325223253232542325523256232572325823259232602326123262232632326423265232662326723268232692327023271232722327323274232752327623277232782327923280232812328223283232842328523286232872328823289232902329123292232932329423295232962329723298232992330023301233022330323304233052330623307233082330923310233112331223313233142331523316233172331823319233202332123322233232332423325233262332723328233292333023331233322333323334233352333623337233382333923340233412334223343233442334523346233472334823349233502335123352233532335423355233562335723358233592336023361233622336323364233652336623367233682336923370233712337223373233742337523376233772337823379233802338123382233832338423385233862338723388233892339023391233922339323394233952339623397233982339923400234012340223403234042340523406234072340823409234102341123412234132341423415234162341723418234192342023421234222342323424234252342623427234282342923430234312343223433234342343523436234372343823439234402344123442234432344423445234462344723448234492345023451234522345323454234552345623457234582345923460234612346223463234642346523466234672346823469234702347123472234732347423475234762347723478234792348023481234822348323484234852348623487234882348923490234912349223493234942349523496234972349823499235002350123502235032350423505235062350723508235092351023511235122351323514235152351623517235182351923520235212352223523235242352523526235272352823529235302353123532235332353423535235362353723538235392354023541235422354323544235452354623547235482354923550235512355223553235542355523556235572355823559235602356123562235632356423565235662356723568235692357023571235722357323574235752357623577235782357923580235812358223583235842358523586235872358823589235902359123592235932359423595235962359723598235992360023601236022360323604236052360623607236082360923610236112361223613236142361523616236172361823619236202362123622236232362423625236262362723628236292363023631236322363323634236352363623637236382363923640236412364223643236442364523646236472364823649236502365123652236532365423655236562365723658236592366023661236622366323664236652366623667236682366923670236712367223673236742367523676236772367823679236802368123682236832368423685236862368723688236892369023691236922369323694236952369623697236982369923700237012370223703237042370523706237072370823709237102371123712237132371423715237162371723718237192372023721237222372323724237252372623727237282372923730237312373223733237342373523736237372373823739237402374123742237432374423745237462374723748237492375023751237522375323754237552375623757237582375923760237612376223763237642376523766237672376823769237702377123772237732377423775237762377723778237792378023781237822378323784237852378623787237882378923790237912379223793237942379523796237972379823799238002380123802238032380423805238062380723808238092381023811238122381323814238152381623817238182381923820238212382223823238242382523826238272382823829238302383123832238332383423835238362383723838238392384023841238422384323844238452384623847238482384923850238512385223853238542385523856238572385823859238602386123862238632386423865238662386723868238692387023871238722387323874238752387623877238782387923880238812388223883238842388523886238872388823889238902389123892238932389423895238962389723898238992390023901239022390323904239052390623907239082390923910239112391223913239142391523916239172391823919239202392123922239232392423925239262392723928239292393023931239322393323934239352393623937239382393923940239412394223943239442394523946239472394823949239502395123952239532395423955239562395723958239592396023961239622396323964239652396623967239682396923970239712397223973239742397523976239772397823979239802398123982239832398423985239862398723988239892399023991239922399323994239952399623997239982399924000240012400224003240042400524006240072400824009240102401124012240132401424015240162401724018240192402024021240222402324024240252402624027240282402924030240312403224033240342403524036240372403824039240402404124042240432404424045240462404724048240492405024051240522405324054240552405624057240582405924060240612406224063240642406524066240672406824069240702407124072240732407424075240762407724078240792408024081240822408324084240852408624087240882408924090240912409224093240942409524096240972409824099241002410124102241032410424105241062410724108241092411024111241122411324114241152411624117241182411924120241212412224123241242412524126241272412824129241302413124132241332413424135241362413724138241392414024141241422414324144241452414624147241482414924150241512415224153241542415524156241572415824159241602416124162241632416424165241662416724168241692417024171241722417324174241752417624177241782417924180241812418224183241842418524186241872418824189241902419124192241932419424195241962419724198241992420024201242022420324204242052420624207242082420924210242112421224213242142421524216242172421824219242202422124222242232422424225242262422724228242292423024231242322423324234242352423624237242382423924240242412424224243242442424524246242472424824249242502425124252242532425424255242562425724258242592426024261242622426324264242652426624267242682426924270242712427224273242742427524276242772427824279242802428124282242832428424285242862428724288242892429024291242922429324294242952429624297242982429924300243012430224303243042430524306243072430824309243102431124312243132431424315243162431724318243192432024321243222432324324243252432624327243282432924330243312433224333243342433524336243372433824339243402434124342243432434424345243462434724348243492435024351243522435324354243552435624357243582435924360243612436224363243642436524366243672436824369243702437124372243732437424375243762437724378243792438024381243822438324384243852438624387243882438924390243912439224393243942439524396243972439824399244002440124402244032440424405244062440724408244092441024411244122441324414244152441624417244182441924420244212442224423244242442524426244272442824429244302443124432244332443424435244362443724438244392444024441244422444324444244452444624447244482444924450244512445224453244542445524456244572445824459244602446124462244632446424465244662446724468244692447024471244722447324474244752447624477244782447924480244812448224483244842448524486244872448824489244902449124492244932449424495244962449724498244992450024501245022450324504245052450624507245082450924510245112451224513245142451524516245172451824519245202452124522245232452424525245262452724528245292453024531245322453324534245352453624537245382453924540245412454224543245442454524546245472454824549245502455124552245532455424555245562455724558245592456024561245622456324564245652456624567245682456924570245712457224573245742457524576245772457824579245802458124582245832458424585245862458724588245892459024591245922459324594245952459624597245982459924600246012460224603246042460524606246072460824609246102461124612246132461424615246162461724618246192462024621246222462324624246252462624627246282462924630246312463224633246342463524636246372463824639246402464124642246432464424645246462464724648246492465024651246522465324654246552465624657246582465924660246612466224663246642466524666246672466824669246702467124672246732467424675246762467724678246792468024681246822468324684246852468624687246882468924690246912469224693246942469524696246972469824699247002470124702247032470424705247062470724708247092471024711247122471324714247152471624717247182471924720247212472224723247242472524726247272472824729247302473124732247332473424735247362473724738247392474024741247422474324744247452474624747247482474924750247512475224753247542475524756247572475824759247602476124762247632476424765247662476724768247692477024771247722477324774247752477624777247782477924780247812478224783247842478524786247872478824789247902479124792247932479424795247962479724798247992480024801248022480324804248052480624807248082480924810248112481224813248142481524816248172481824819248202482124822248232482424825248262482724828248292483024831248322483324834248352483624837248382483924840248412484224843248442484524846248472484824849248502485124852248532485424855248562485724858248592486024861248622486324864248652486624867248682486924870248712487224873248742487524876248772487824879248802488124882248832488424885248862488724888248892489024891248922489324894248952489624897248982489924900249012490224903249042490524906249072490824909249102491124912249132491424915249162491724918249192492024921249222492324924249252492624927249282492924930249312493224933249342493524936249372493824939249402494124942249432494424945249462494724948249492495024951249522495324954249552495624957249582495924960249612496224963249642496524966249672496824969249702497124972249732497424975249762497724978249792498024981249822498324984249852498624987249882498924990249912499224993249942499524996249972499824999250002500125002250032500425005250062500725008250092501025011250122501325014250152501625017250182501925020250212502225023250242502525026250272502825029250302503125032250332503425035250362503725038250392504025041250422504325044250452504625047250482504925050250512505225053250542505525056250572505825059250602506125062250632506425065250662506725068250692507025071250722507325074250752507625077250782507925080250812508225083250842508525086250872508825089250902509125092250932509425095250962509725098250992510025101251022510325104251052510625107251082510925110251112511225113251142511525116251172511825119251202512125122251232512425125251262512725128251292513025131251322513325134251352513625137251382513925140251412514225143251442514525146251472514825149251502515125152251532515425155251562515725158251592516025161251622516325164251652516625167251682516925170251712517225173251742517525176251772517825179251802518125182251832518425185251862518725188251892519025191251922519325194251952519625197251982519925200252012520225203252042520525206252072520825209252102521125212252132521425215252162521725218252192522025221252222522325224252252522625227252282522925230252312523225233252342523525236252372523825239252402524125242252432524425245252462524725248252492525025251252522525325254252552525625257252582525925260252612526225263252642526525266252672526825269252702527125272252732527425275252762527725278252792528025281252822528325284252852528625287252882528925290252912529225293252942529525296252972529825299253002530125302253032530425305253062530725308253092531025311253122531325314253152531625317253182531925320253212532225323253242532525326253272532825329253302533125332253332533425335253362533725338253392534025341253422534325344253452534625347253482534925350253512535225353253542535525356253572535825359253602536125362253632536425365253662536725368253692537025371253722537325374253752537625377253782537925380253812538225383253842538525386253872538825389253902539125392253932539425395253962539725398253992540025401254022540325404254052540625407254082540925410254112541225413254142541525416254172541825419254202542125422254232542425425254262542725428254292543025431254322543325434254352543625437254382543925440254412544225443254442544525446254472544825449254502545125452254532545425455254562545725458254592546025461254622546325464254652546625467254682546925470254712547225473254742547525476254772547825479254802548125482254832548425485254862548725488254892549025491254922549325494254952549625497254982549925500255012550225503255042550525506255072550825509255102551125512255132551425515255162551725518255192552025521255222552325524255252552625527255282552925530255312553225533255342553525536255372553825539255402554125542255432554425545255462554725548255492555025551255522555325554255552555625557255582555925560255612556225563255642556525566255672556825569255702557125572255732557425575255762557725578255792558025581255822558325584255852558625587255882558925590255912559225593255942559525596255972559825599256002560125602256032560425605256062560725608256092561025611256122561325614256152561625617256182561925620256212562225623256242562525626256272562825629256302563125632256332563425635256362563725638256392564025641256422564325644256452564625647256482564925650256512565225653256542565525656256572565825659256602566125662256632566425665256662566725668256692567025671256722567325674256752567625677256782567925680256812568225683256842568525686256872568825689256902569125692256932569425695256962569725698256992570025701257022570325704257052570625707257082570925710257112571225713257142571525716257172571825719257202572125722257232572425725257262572725728257292573025731257322573325734257352573625737257382573925740257412574225743257442574525746257472574825749257502575125752257532575425755257562575725758257592576025761257622576325764257652576625767257682576925770257712577225773257742577525776257772577825779257802578125782257832578425785257862578725788257892579025791257922579325794257952579625797257982579925800258012580225803258042580525806258072580825809258102581125812258132581425815258162581725818258192582025821258222582325824258252582625827258282582925830258312583225833258342583525836258372583825839258402584125842258432584425845258462584725848258492585025851258522585325854258552585625857258582585925860258612586225863258642586525866258672586825869258702587125872258732587425875258762587725878258792588025881258822588325884258852588625887258882588925890258912589225893258942589525896258972589825899259002590125902259032590425905259062590725908259092591025911259122591325914259152591625917259182591925920259212592225923259242592525926259272592825929259302593125932259332593425935259362593725938259392594025941259422594325944259452594625947259482594925950259512595225953259542595525956259572595825959259602596125962259632596425965259662596725968259692597025971259722597325974259752597625977259782597925980259812598225983259842598525986259872598825989259902599125992259932599425995259962599725998259992600026001260022600326004260052600626007260082600926010260112601226013260142601526016260172601826019260202602126022260232602426025260262602726028260292603026031260322603326034260352603626037260382603926040260412604226043260442604526046260472604826049260502605126052260532605426055260562605726058260592606026061260622606326064260652606626067260682606926070260712607226073260742607526076260772607826079260802608126082260832608426085260862608726088260892609026091260922609326094260952609626097260982609926100261012610226103261042610526106261072610826109261102611126112261132611426115261162611726118261192612026121261222612326124261252612626127261282612926130261312613226133261342613526136261372613826139261402614126142261432614426145261462614726148261492615026151261522615326154261552615626157261582615926160261612616226163261642616526166261672616826169261702617126172261732617426175261762617726178261792618026181261822618326184261852618626187261882618926190261912619226193261942619526196261972619826199262002620126202262032620426205262062620726208262092621026211262122621326214262152621626217262182621926220262212622226223262242622526226262272622826229262302623126232262332623426235262362623726238262392624026241262422624326244262452624626247262482624926250262512625226253262542625526256262572625826259262602626126262262632626426265262662626726268262692627026271262722627326274262752627626277262782627926280262812628226283262842628526286262872628826289262902629126292262932629426295262962629726298262992630026301263022630326304263052630626307263082630926310263112631226313263142631526316263172631826319263202632126322263232632426325263262632726328263292633026331263322633326334263352633626337263382633926340263412634226343263442634526346263472634826349263502635126352263532635426355263562635726358263592636026361263622636326364263652636626367263682636926370263712637226373263742637526376263772637826379263802638126382263832638426385263862638726388263892639026391263922639326394263952639626397263982639926400264012640226403264042640526406264072640826409264102641126412264132641426415264162641726418264192642026421264222642326424264252642626427264282642926430264312643226433264342643526436264372643826439264402644126442264432644426445264462644726448264492645026451264522645326454264552645626457264582645926460264612646226463264642646526466264672646826469264702647126472264732647426475264762647726478264792648026481264822648326484264852648626487264882648926490264912649226493264942649526496264972649826499265002650126502265032650426505265062650726508265092651026511265122651326514265152651626517265182651926520265212652226523265242652526526265272652826529265302653126532265332653426535265362653726538265392654026541265422654326544265452654626547265482654926550265512655226553265542655526556265572655826559265602656126562265632656426565265662656726568265692657026571265722657326574265752657626577265782657926580265812658226583265842658526586265872658826589265902659126592265932659426595265962659726598265992660026601266022660326604266052660626607266082660926610266112661226613266142661526616266172661826619266202662126622266232662426625266262662726628266292663026631266322663326634266352663626637266382663926640266412664226643266442664526646266472664826649266502665126652266532665426655266562665726658266592666026661266622666326664266652666626667266682666926670266712667226673266742667526676266772667826679266802668126682266832668426685266862668726688266892669026691266922669326694266952669626697266982669926700267012670226703267042670526706267072670826709267102671126712267132671426715267162671726718267192672026721267222672326724267252672626727267282672926730267312673226733267342673526736267372673826739267402674126742267432674426745267462674726748267492675026751267522675326754267552675626757267582675926760267612676226763267642676526766267672676826769267702677126772267732677426775267762677726778267792678026781267822678326784267852678626787267882678926790267912679226793267942679526796267972679826799268002680126802268032680426805268062680726808268092681026811268122681326814268152681626817268182681926820268212682226823268242682526826268272682826829268302683126832268332683426835268362683726838268392684026841268422684326844268452684626847268482684926850268512685226853268542685526856268572685826859268602686126862268632686426865268662686726868268692687026871268722687326874268752687626877268782687926880268812688226883268842688526886268872688826889268902689126892268932689426895268962689726898268992690026901269022690326904269052690626907269082690926910269112691226913269142691526916269172691826919269202692126922269232692426925269262692726928269292693026931269322693326934269352693626937269382693926940269412694226943269442694526946269472694826949269502695126952269532695426955269562695726958269592696026961269622696326964269652696626967269682696926970269712697226973269742697526976269772697826979269802698126982269832698426985269862698726988269892699026991269922699326994269952699626997269982699927000270012700227003270042700527006270072700827009270102701127012270132701427015270162701727018270192702027021270222702327024270252702627027270282702927030270312703227033270342703527036270372703827039270402704127042270432704427045270462704727048270492705027051270522705327054270552705627057270582705927060270612706227063270642706527066270672706827069270702707127072270732707427075270762707727078270792708027081270822708327084270852708627087270882708927090270912709227093270942709527096270972709827099271002710127102271032710427105271062710727108271092711027111271122711327114271152711627117271182711927120271212712227123271242712527126271272712827129271302713127132271332713427135271362713727138271392714027141271422714327144271452714627147271482714927150271512715227153271542715527156271572715827159271602716127162271632716427165271662716727168271692717027171271722717327174271752717627177271782717927180271812718227183271842718527186271872718827189271902719127192271932719427195271962719727198271992720027201272022720327204272052720627207272082720927210272112721227213272142721527216272172721827219272202722127222272232722427225272262722727228272292723027231272322723327234272352723627237272382723927240272412724227243272442724527246272472724827249272502725127252272532725427255272562725727258272592726027261272622726327264272652726627267272682726927270272712727227273272742727527276272772727827279272802728127282272832728427285272862728727288272892729027291272922729327294272952729627297272982729927300273012730227303273042730527306273072730827309273102731127312273132731427315273162731727318273192732027321273222732327324273252732627327273282732927330273312733227333273342733527336273372733827339273402734127342273432734427345273462734727348273492735027351273522735327354273552735627357273582735927360273612736227363273642736527366273672736827369273702737127372273732737427375273762737727378273792738027381273822738327384273852738627387273882738927390273912739227393273942739527396273972739827399274002740127402274032740427405274062740727408274092741027411274122741327414274152741627417274182741927420274212742227423274242742527426274272742827429274302743127432274332743427435274362743727438274392744027441274422744327444274452744627447274482744927450274512745227453274542745527456274572745827459274602746127462274632746427465274662746727468274692747027471274722747327474274752747627477274782747927480274812748227483274842748527486274872748827489274902749127492274932749427495274962749727498274992750027501275022750327504275052750627507275082750927510275112751227513275142751527516275172751827519275202752127522275232752427525275262752727528275292753027531275322753327534275352753627537275382753927540275412754227543275442754527546275472754827549275502755127552275532755427555275562755727558275592756027561275622756327564275652756627567275682756927570275712757227573275742757527576275772757827579275802758127582275832758427585275862758727588275892759027591275922759327594275952759627597275982759927600276012760227603276042760527606276072760827609276102761127612276132761427615276162761727618276192762027621276222762327624276252762627627276282762927630276312763227633276342763527636276372763827639276402764127642276432764427645276462764727648276492765027651276522765327654276552765627657276582765927660276612766227663276642766527666276672766827669276702767127672276732767427675276762767727678276792768027681276822768327684276852768627687276882768927690276912769227693276942769527696276972769827699277002770127702277032770427705277062770727708277092771027711277122771327714277152771627717277182771927720277212772227723277242772527726277272772827729277302773127732277332773427735277362773727738277392774027741277422774327744277452774627747277482774927750277512775227753277542775527756277572775827759277602776127762277632776427765277662776727768277692777027771277722777327774277752777627777277782777927780277812778227783277842778527786277872778827789277902779127792277932779427795277962779727798277992780027801278022780327804278052780627807278082780927810278112781227813278142781527816278172781827819278202782127822278232782427825278262782727828278292783027831278322783327834278352783627837278382783927840278412784227843278442784527846278472784827849278502785127852278532785427855278562785727858278592786027861278622786327864278652786627867278682786927870278712787227873278742787527876278772787827879278802788127882278832788427885278862788727888278892789027891278922789327894278952789627897278982789927900279012790227903279042790527906279072790827909279102791127912279132791427915279162791727918279192792027921279222792327924279252792627927279282792927930279312793227933279342793527936279372793827939279402794127942279432794427945279462794727948279492795027951279522795327954279552795627957279582795927960279612796227963279642796527966279672796827969279702797127972279732797427975279762797727978279792798027981279822798327984279852798627987279882798927990279912799227993279942799527996279972799827999280002800128002280032800428005280062800728008280092801028011280122801328014280152801628017280182801928020280212802228023280242802528026280272802828029280302803128032280332803428035280362803728038280392804028041280422804328044280452804628047280482804928050280512805228053280542805528056280572805828059280602806128062280632806428065280662806728068280692807028071280722807328074280752807628077280782807928080280812808228083280842808528086280872808828089280902809128092280932809428095280962809728098280992810028101281022810328104281052810628107281082810928110281112811228113281142811528116281172811828119281202812128122281232812428125281262812728128281292813028131281322813328134281352813628137281382813928140281412814228143281442814528146281472814828149281502815128152281532815428155281562815728158281592816028161281622816328164281652816628167281682816928170281712817228173281742817528176281772817828179281802818128182281832818428185281862818728188281892819028191281922819328194281952819628197281982819928200282012820228203282042820528206282072820828209282102821128212282132821428215282162821728218282192822028221282222822328224282252822628227282282822928230282312823228233282342823528236282372823828239282402824128242282432824428245282462824728248282492825028251282522825328254282552825628257282582825928260282612826228263282642826528266282672826828269282702827128272282732827428275282762827728278282792828028281282822828328284282852828628287282882828928290282912829228293282942829528296282972829828299283002830128302283032830428305283062830728308283092831028311283122831328314283152831628317283182831928320283212832228323283242832528326283272832828329283302833128332283332833428335283362833728338283392834028341283422834328344283452834628347283482834928350283512835228353283542835528356283572835828359283602836128362283632836428365283662836728368283692837028371283722837328374283752837628377283782837928380283812838228383283842838528386283872838828389283902839128392283932839428395283962839728398283992840028401284022840328404284052840628407284082840928410284112841228413284142841528416284172841828419284202842128422284232842428425284262842728428284292843028431284322843328434284352843628437284382843928440284412844228443284442844528446284472844828449284502845128452284532845428455284562845728458284592846028461284622846328464284652846628467284682846928470284712847228473284742847528476284772847828479284802848128482284832848428485284862848728488284892849028491284922849328494284952849628497284982849928500285012850228503285042850528506285072850828509285102851128512285132851428515285162851728518285192852028521285222852328524285252852628527285282852928530285312853228533285342853528536285372853828539285402854128542285432854428545285462854728548285492855028551285522855328554285552855628557285582855928560285612856228563285642856528566285672856828569285702857128572285732857428575285762857728578285792858028581285822858328584285852858628587285882858928590285912859228593285942859528596285972859828599286002860128602286032860428605286062860728608286092861028611286122861328614286152861628617286182861928620286212862228623286242862528626286272862828629286302863128632286332863428635286362863728638286392864028641286422864328644286452864628647286482864928650286512865228653286542865528656286572865828659286602866128662286632866428665286662866728668286692867028671286722867328674286752867628677286782867928680286812868228683286842868528686286872868828689286902869128692286932869428695286962869728698286992870028701287022870328704287052870628707287082870928710287112871228713287142871528716287172871828719287202872128722287232872428725287262872728728287292873028731287322873328734287352873628737287382873928740287412874228743287442874528746287472874828749287502875128752287532875428755287562875728758287592876028761287622876328764287652876628767287682876928770287712877228773287742877528776287772877828779287802878128782287832878428785287862878728788287892879028791287922879328794287952879628797287982879928800288012880228803288042880528806288072880828809288102881128812288132881428815288162881728818288192882028821288222882328824288252882628827288282882928830288312883228833288342883528836288372883828839288402884128842288432884428845288462884728848288492885028851288522885328854288552885628857288582885928860288612886228863288642886528866288672886828869288702887128872288732887428875288762887728878288792888028881288822888328884288852888628887288882888928890288912889228893288942889528896288972889828899289002890128902289032890428905289062890728908289092891028911289122891328914289152891628917289182891928920289212892228923289242892528926289272892828929289302893128932289332893428935289362893728938289392894028941289422894328944289452894628947289482894928950289512895228953289542895528956289572895828959289602896128962289632896428965289662896728968289692897028971289722897328974289752897628977289782897928980289812898228983289842898528986289872898828989289902899128992289932899428995289962899728998289992900029001290022900329004290052900629007290082900929010290112901229013290142901529016290172901829019290202902129022290232902429025290262902729028290292903029031290322903329034290352903629037290382903929040290412904229043290442904529046290472904829049290502905129052290532905429055290562905729058290592906029061290622906329064290652906629067290682906929070290712907229073290742907529076290772907829079290802908129082290832908429085290862908729088290892909029091290922909329094290952909629097290982909929100291012910229103291042910529106291072910829109291102911129112291132911429115291162911729118291192912029121291222912329124291252912629127291282912929130291312913229133291342913529136291372913829139291402914129142291432914429145291462914729148291492915029151291522915329154291552915629157291582915929160291612916229163291642916529166291672916829169291702917129172291732917429175291762917729178291792918029181291822918329184291852918629187291882918929190291912919229193291942919529196291972919829199292002920129202292032920429205292062920729208292092921029211292122921329214292152921629217292182921929220292212922229223292242922529226292272922829229292302923129232292332923429235292362923729238292392924029241292422924329244292452924629247292482924929250292512925229253292542925529256292572925829259292602926129262292632926429265292662926729268292692927029271292722927329274292752927629277292782927929280292812928229283292842928529286292872928829289292902929129292292932929429295292962929729298292992930029301293022930329304293052930629307293082930929310293112931229313293142931529316293172931829319293202932129322293232932429325293262932729328293292933029331293322933329334293352933629337293382933929340293412934229343293442934529346293472934829349293502935129352293532935429355293562935729358293592936029361293622936329364293652936629367293682936929370293712937229373293742937529376293772937829379293802938129382293832938429385293862938729388293892939029391293922939329394293952939629397293982939929400294012940229403294042940529406294072940829409294102941129412294132941429415294162941729418294192942029421294222942329424294252942629427294282942929430294312943229433294342943529436294372943829439294402944129442294432944429445294462944729448294492945029451294522945329454294552945629457294582945929460294612946229463294642946529466294672946829469294702947129472294732947429475294762947729478294792948029481294822948329484294852948629487294882948929490294912949229493294942949529496294972949829499295002950129502295032950429505295062950729508295092951029511295122951329514295152951629517295182951929520295212952229523295242952529526295272952829529295302953129532295332953429535295362953729538295392954029541295422954329544295452954629547295482954929550295512955229553295542955529556295572955829559295602956129562295632956429565295662956729568295692957029571295722957329574295752957629577295782957929580295812958229583295842958529586295872958829589295902959129592295932959429595295962959729598295992960029601296022960329604296052960629607296082960929610296112961229613296142961529616296172961829619296202962129622296232962429625296262962729628296292963029631296322963329634296352963629637296382963929640296412964229643296442964529646296472964829649296502965129652296532965429655296562965729658296592966029661296622966329664296652966629667296682966929670296712967229673296742967529676296772967829679296802968129682296832968429685296862968729688296892969029691296922969329694296952969629697296982969929700297012970229703297042970529706297072970829709297102971129712297132971429715297162971729718297192972029721297222972329724297252972629727297282972929730297312973229733297342973529736297372973829739297402974129742297432974429745297462974729748297492975029751297522975329754297552975629757297582975929760297612976229763297642976529766297672976829769297702977129772297732977429775297762977729778297792978029781297822978329784297852978629787297882978929790297912979229793297942979529796297972979829799298002980129802298032980429805298062980729808298092981029811298122981329814298152981629817298182981929820298212982229823298242982529826298272982829829298302983129832298332983429835298362983729838298392984029841298422984329844298452984629847298482984929850298512985229853298542985529856298572985829859298602986129862298632986429865298662986729868298692987029871298722987329874298752987629877298782987929880298812988229883298842988529886298872988829889298902989129892298932989429895298962989729898298992990029901299022990329904299052990629907299082990929910299112991229913299142991529916299172991829919299202992129922299232992429925299262992729928299292993029931299322993329934299352993629937299382993929940299412994229943299442994529946299472994829949299502995129952299532995429955299562995729958299592996029961299622996329964299652996629967299682996929970299712997229973299742997529976299772997829979299802998129982299832998429985299862998729988299892999029991299922999329994299952999629997299982999930000300013000230003300043000530006300073000830009300103001130012300133001430015300163001730018300193002030021300223002330024300253002630027300283002930030300313003230033300343003530036300373003830039300403004130042300433004430045300463004730048300493005030051300523005330054300553005630057300583005930060300613006230063300643006530066300673006830069300703007130072300733007430075300763007730078300793008030081300823008330084300853008630087300883008930090300913009230093300943009530096300973009830099301003010130102301033010430105301063010730108301093011030111301123011330114301153011630117301183011930120301213012230123301243012530126301273012830129301303013130132301333013430135301363013730138301393014030141301423014330144301453014630147301483014930150301513015230153301543015530156301573015830159301603016130162301633016430165301663016730168301693017030171301723017330174301753017630177301783017930180301813018230183301843018530186301873018830189301903019130192301933019430195301963019730198301993020030201302023020330204302053020630207302083020930210302113021230213302143021530216302173021830219302203022130222302233022430225302263022730228302293023030231302323023330234302353023630237302383023930240302413024230243302443024530246302473024830249302503025130252302533025430255302563025730258302593026030261302623026330264302653026630267302683026930270302713027230273302743027530276302773027830279302803028130282302833028430285302863028730288302893029030291302923029330294302953029630297302983029930300303013030230303303043030530306303073030830309303103031130312303133031430315303163031730318303193032030321303223032330324303253032630327303283032930330303313033230333303343033530336303373033830339303403034130342303433034430345303463034730348303493035030351303523035330354303553035630357303583035930360303613036230363303643036530366303673036830369303703037130372303733037430375303763037730378303793038030381303823038330384303853038630387303883038930390303913039230393303943039530396303973039830399304003040130402304033040430405304063040730408304093041030411304123041330414304153041630417304183041930420304213042230423304243042530426304273042830429304303043130432304333043430435304363043730438304393044030441304423044330444304453044630447304483044930450304513045230453304543045530456304573045830459304603046130462304633046430465304663046730468304693047030471304723047330474304753047630477304783047930480304813048230483304843048530486304873048830489304903049130492304933049430495304963049730498304993050030501305023050330504305053050630507305083050930510305113051230513305143051530516305173051830519305203052130522305233052430525305263052730528305293053030531305323053330534305353053630537305383053930540305413054230543305443054530546305473054830549305503055130552305533055430555305563055730558305593056030561305623056330564305653056630567305683056930570305713057230573305743057530576305773057830579305803058130582305833058430585305863058730588305893059030591305923059330594305953059630597305983059930600306013060230603306043060530606306073060830609306103061130612306133061430615306163061730618306193062030621306223062330624306253062630627306283062930630306313063230633306343063530636306373063830639306403064130642306433064430645306463064730648306493065030651306523065330654306553065630657306583065930660306613066230663306643066530666306673066830669306703067130672306733067430675306763067730678306793068030681306823068330684306853068630687306883068930690306913069230693306943069530696306973069830699307003070130702307033070430705307063070730708307093071030711307123071330714307153071630717307183071930720307213072230723307243072530726307273072830729307303073130732307333073430735307363073730738307393074030741307423074330744307453074630747307483074930750307513075230753307543075530756307573075830759307603076130762307633076430765307663076730768307693077030771307723077330774307753077630777307783077930780307813078230783307843078530786307873078830789307903079130792307933079430795307963079730798307993080030801308023080330804308053080630807308083080930810308113081230813308143081530816308173081830819308203082130822308233082430825308263082730828308293083030831308323083330834308353083630837308383083930840308413084230843308443084530846308473084830849308503085130852308533085430855308563085730858308593086030861308623086330864308653086630867308683086930870308713087230873308743087530876308773087830879308803088130882308833088430885308863088730888308893089030891308923089330894308953089630897308983089930900309013090230903309043090530906309073090830909309103091130912309133091430915309163091730918309193092030921309223092330924309253092630927309283092930930309313093230933309343093530936309373093830939309403094130942309433094430945309463094730948309493095030951309523095330954309553095630957309583095930960309613096230963309643096530966309673096830969309703097130972309733097430975309763097730978309793098030981309823098330984309853098630987309883098930990309913099230993309943099530996309973099830999310003100131002310033100431005310063100731008310093101031011310123101331014310153101631017310183101931020310213102231023310243102531026310273102831029310303103131032310333103431035310363103731038310393104031041310423104331044310453104631047310483104931050310513105231053310543105531056310573105831059310603106131062310633106431065310663106731068310693107031071310723107331074310753107631077310783107931080310813108231083310843108531086310873108831089310903109131092310933109431095310963109731098310993110031101311023110331104311053110631107311083110931110311113111231113311143111531116311173111831119311203112131122311233112431125311263112731128311293113031131311323113331134311353113631137311383113931140311413114231143311443114531146311473114831149311503115131152311533115431155311563115731158311593116031161311623116331164311653116631167311683116931170311713117231173311743117531176311773117831179311803118131182311833118431185311863118731188311893119031191311923119331194311953119631197311983119931200312013120231203312043120531206312073120831209312103121131212312133121431215312163121731218312193122031221312223122331224312253122631227312283122931230312313123231233312343123531236312373123831239312403124131242312433124431245312463124731248312493125031251312523125331254312553125631257312583125931260312613126231263312643126531266312673126831269312703127131272312733127431275312763127731278312793128031281312823128331284312853128631287312883128931290312913129231293312943129531296312973129831299313003130131302313033130431305313063130731308313093131031311313123131331314313153131631317313183131931320313213132231323313243132531326313273132831329313303133131332313333133431335313363133731338313393134031341313423134331344313453134631347313483134931350313513135231353313543135531356313573135831359313603136131362313633136431365313663136731368313693137031371313723137331374313753137631377313783137931380313813138231383313843138531386313873138831389313903139131392313933139431395313963139731398313993140031401314023140331404314053140631407314083140931410314113141231413314143141531416314173141831419314203142131422314233142431425314263142731428314293143031431314323143331434314353143631437314383143931440314413144231443314443144531446314473144831449314503145131452314533145431455314563145731458314593146031461314623146331464314653146631467314683146931470314713147231473314743147531476314773147831479314803148131482314833148431485314863148731488314893149031491314923149331494314953149631497314983149931500315013150231503315043150531506315073150831509315103151131512315133151431515315163151731518315193152031521315223152331524315253152631527315283152931530315313153231533315343153531536315373153831539315403154131542315433154431545315463154731548315493155031551315523155331554315553155631557315583155931560315613156231563315643156531566315673156831569315703157131572315733157431575315763157731578315793158031581315823158331584315853158631587315883158931590315913159231593315943159531596315973159831599316003160131602316033160431605316063160731608316093161031611316123161331614316153161631617316183161931620316213162231623316243162531626316273162831629316303163131632316333163431635316363163731638316393164031641316423164331644316453164631647316483164931650316513165231653316543165531656316573165831659316603166131662316633166431665316663166731668316693167031671316723167331674316753167631677316783167931680316813168231683316843168531686316873168831689316903169131692316933169431695316963169731698316993170031701317023170331704317053170631707317083170931710317113171231713317143171531716317173171831719317203172131722317233172431725317263172731728317293173031731317323173331734317353173631737317383173931740317413174231743317443174531746317473174831749317503175131752317533175431755317563175731758317593176031761317623176331764317653176631767317683176931770317713177231773317743177531776317773177831779317803178131782317833178431785317863178731788317893179031791317923179331794317953179631797317983179931800318013180231803318043180531806318073180831809318103181131812318133181431815318163181731818318193182031821318223182331824318253182631827318283182931830318313183231833318343183531836318373183831839318403184131842318433184431845318463184731848318493185031851318523185331854318553185631857318583185931860318613186231863318643186531866318673186831869318703187131872318733187431875318763187731878318793188031881318823188331884318853188631887318883188931890318913189231893318943189531896318973189831899319003190131902319033190431905319063190731908319093191031911319123191331914319153191631917319183191931920319213192231923319243192531926319273192831929319303193131932319333193431935319363193731938319393194031941319423194331944319453194631947319483194931950319513195231953319543195531956319573195831959319603196131962319633196431965319663196731968319693197031971319723197331974319753197631977319783197931980319813198231983319843198531986319873198831989319903199131992319933199431995319963199731998319993200032001320023200332004320053200632007320083200932010320113201232013320143201532016320173201832019320203202132022320233202432025320263202732028320293203032031320323203332034320353203632037320383203932040320413204232043320443204532046320473204832049320503205132052320533205432055320563205732058320593206032061320623206332064320653206632067320683206932070320713207232073320743207532076320773207832079320803208132082320833208432085320863208732088320893209032091320923209332094320953209632097320983209932100321013210232103321043210532106321073210832109321103211132112321133211432115321163211732118321193212032121321223212332124321253212632127321283212932130321313213232133321343213532136321373213832139321403214132142321433214432145321463214732148321493215032151321523215332154321553215632157321583215932160321613216232163321643216532166321673216832169321703217132172321733217432175321763217732178321793218032181321823218332184321853218632187321883218932190321913219232193321943219532196321973219832199322003220132202322033220432205322063220732208322093221032211322123221332214322153221632217322183221932220322213222232223322243222532226322273222832229322303223132232322333223432235322363223732238322393224032241322423224332244322453224632247322483224932250322513225232253322543225532256322573225832259322603226132262322633226432265322663226732268322693227032271322723227332274322753227632277322783227932280322813228232283322843228532286322873228832289322903229132292322933229432295322963229732298322993230032301323023230332304323053230632307323083230932310323113231232313323143231532316323173231832319323203232132322323233232432325323263232732328323293233032331323323233332334323353233632337323383233932340323413234232343323443234532346323473234832349323503235132352323533235432355323563235732358323593236032361323623236332364323653236632367323683236932370323713237232373323743237532376323773237832379323803238132382323833238432385323863238732388323893239032391323923239332394323953239632397323983239932400324013240232403324043240532406324073240832409324103241132412324133241432415324163241732418324193242032421324223242332424324253242632427324283242932430324313243232433324343243532436324373243832439324403244132442324433244432445324463244732448324493245032451324523245332454324553245632457324583245932460324613246232463324643246532466324673246832469324703247132472324733247432475324763247732478324793248032481324823248332484324853248632487324883248932490324913249232493324943249532496324973249832499325003250132502325033250432505325063250732508325093251032511325123251332514325153251632517325183251932520325213252232523325243252532526325273252832529325303253132532325333253432535325363253732538325393254032541325423254332544325453254632547325483254932550325513255232553325543255532556325573255832559325603256132562325633256432565325663256732568325693257032571325723257332574325753257632577325783257932580325813258232583325843258532586325873258832589325903259132592325933259432595325963259732598325993260032601326023260332604326053260632607326083260932610326113261232613326143261532616326173261832619326203262132622326233262432625326263262732628326293263032631326323263332634326353263632637326383263932640326413264232643326443264532646326473264832649326503265132652326533265432655326563265732658326593266032661326623266332664326653266632667326683266932670326713267232673326743267532676326773267832679326803268132682326833268432685326863268732688326893269032691326923269332694326953269632697326983269932700327013270232703327043270532706327073270832709327103271132712327133271432715327163271732718327193272032721327223272332724327253272632727327283272932730327313273232733327343273532736327373273832739327403274132742327433274432745327463274732748327493275032751327523275332754327553275632757327583275932760327613276232763327643276532766327673276832769327703277132772327733277432775327763277732778327793278032781327823278332784327853278632787327883278932790327913279232793327943279532796327973279832799328003280132802328033280432805328063280732808328093281032811328123281332814328153281632817328183281932820328213282232823328243282532826328273282832829328303283132832328333283432835328363283732838328393284032841328423284332844328453284632847328483284932850328513285232853328543285532856328573285832859328603286132862328633286432865328663286732868328693287032871328723287332874328753287632877328783287932880328813288232883328843288532886328873288832889328903289132892328933289432895328963289732898328993290032901329023290332904329053290632907329083290932910329113291232913329143291532916329173291832919329203292132922329233292432925329263292732928329293293032931329323293332934329353293632937329383293932940329413294232943329443294532946329473294832949329503295132952329533295432955329563295732958329593296032961329623296332964329653296632967329683296932970329713297232973329743297532976329773297832979329803298132982329833298432985329863298732988329893299032991329923299332994329953299632997329983299933000330013300233003330043300533006330073300833009330103301133012330133301433015330163301733018330193302033021330223302333024330253302633027330283302933030330313303233033330343303533036330373303833039330403304133042330433304433045330463304733048330493305033051330523305333054330553305633057330583305933060330613306233063330643306533066330673306833069330703307133072330733307433075330763307733078330793308033081330823308333084330853308633087330883308933090330913309233093330943309533096330973309833099331003310133102331033310433105331063310733108331093311033111331123311333114331153311633117331183311933120331213312233123331243312533126331273312833129331303313133132331333313433135331363313733138331393314033141331423314333144331453314633147331483314933150331513315233153331543315533156331573315833159331603316133162331633316433165331663316733168331693317033171331723317333174331753317633177331783317933180331813318233183331843318533186331873318833189331903319133192331933319433195331963319733198331993320033201332023320333204332053320633207332083320933210332113321233213332143321533216332173321833219332203322133222332233322433225332263322733228332293323033231332323323333234332353323633237332383323933240332413324233243332443324533246332473324833249332503325133252332533325433255332563325733258332593326033261332623326333264332653326633267332683326933270332713327233273332743327533276332773327833279332803328133282332833328433285332863328733288332893329033291332923329333294332953329633297332983329933300333013330233303333043330533306333073330833309333103331133312333133331433315333163331733318333193332033321333223332333324333253332633327333283332933330333313333233333333343333533336333373333833339333403334133342333433334433345333463334733348333493335033351333523335333354333553335633357333583335933360333613336233363333643336533366333673336833369333703337133372333733337433375333763337733378333793338033381333823338333384333853338633387333883338933390333913339233393333943339533396333973339833399334003340133402334033340433405334063340733408334093341033411334123341333414334153341633417334183341933420334213342233423334243342533426334273342833429334303343133432334333343433435334363343733438334393344033441334423344333444334453344633447334483344933450334513345233453334543345533456334573345833459334603346133462334633346433465334663346733468334693347033471334723347333474334753347633477334783347933480334813348233483334843348533486334873348833489334903349133492334933349433495334963349733498334993350033501335023350333504335053350633507335083350933510335113351233513335143351533516335173351833519335203352133522335233352433525335263352733528335293353033531335323353333534335353353633537335383353933540335413354233543335443354533546335473354833549335503355133552335533355433555335563355733558335593356033561335623356333564335653356633567335683356933570335713357233573335743357533576335773357833579335803358133582335833358433585335863358733588335893359033591335923359333594335953359633597335983359933600336013360233603336043360533606336073360833609336103361133612336133361433615336163361733618336193362033621336223362333624336253362633627336283362933630336313363233633336343363533636336373363833639336403364133642336433364433645336463364733648336493365033651336523365333654336553365633657336583365933660336613366233663336643366533666336673366833669336703367133672336733367433675336763367733678336793368033681336823368333684336853368633687336883368933690336913369233693336943369533696336973369833699337003370133702337033370433705337063370733708337093371033711337123371333714337153371633717337183371933720337213372233723337243372533726337273372833729337303373133732337333373433735337363373733738337393374033741337423374333744337453374633747337483374933750337513375233753337543375533756337573375833759337603376133762337633376433765337663376733768337693377033771337723377333774337753377633777337783377933780337813378233783337843378533786337873378833789337903379133792337933379433795337963379733798337993380033801338023380333804338053380633807338083380933810338113381233813338143381533816338173381833819338203382133822338233382433825338263382733828338293383033831338323383333834338353383633837338383383933840338413384233843338443384533846338473384833849338503385133852338533385433855338563385733858338593386033861338623386333864338653386633867338683386933870338713387233873338743387533876338773387833879338803388133882338833388433885338863388733888338893389033891338923389333894338953389633897338983389933900339013390233903339043390533906339073390833909339103391133912339133391433915339163391733918339193392033921339223392333924339253392633927339283392933930339313393233933339343393533936339373393833939339403394133942339433394433945339463394733948339493395033951339523395333954339553395633957339583395933960339613396233963339643396533966339673396833969339703397133972339733397433975339763397733978339793398033981339823398333984339853398633987339883398933990339913399233993339943399533996339973399833999340003400134002340033400434005340063400734008340093401034011340123401334014340153401634017340183401934020340213402234023340243402534026340273402834029340303403134032340333403434035340363403734038340393404034041340423404334044340453404634047340483404934050340513405234053340543405534056340573405834059340603406134062340633406434065340663406734068340693407034071340723407334074340753407634077340783407934080340813408234083340843408534086340873408834089340903409134092340933409434095340963409734098340993410034101341023410334104341053410634107341083410934110341113411234113341143411534116341173411834119341203412134122341233412434125341263412734128341293413034131341323413334134341353413634137341383413934140341413414234143341443414534146341473414834149341503415134152341533415434155341563415734158341593416034161341623416334164341653416634167341683416934170341713417234173341743417534176341773417834179341803418134182341833418434185341863418734188341893419034191341923419334194341953419634197341983419934200342013420234203342043420534206342073420834209342103421134212342133421434215342163421734218342193422034221342223422334224342253422634227342283422934230342313423234233342343423534236342373423834239342403424134242342433424434245342463424734248342493425034251342523425334254342553425634257342583425934260342613426234263342643426534266342673426834269342703427134272342733427434275342763427734278342793428034281342823428334284342853428634287342883428934290342913429234293342943429534296342973429834299343003430134302343033430434305343063430734308343093431034311343123431334314343153431634317343183431934320343213432234323343243432534326343273432834329343303433134332343333433434335343363433734338343393434034341343423434334344343453434634347343483434934350343513435234353343543435534356343573435834359343603436134362343633436434365343663436734368343693437034371343723437334374343753437634377343783437934380343813438234383343843438534386343873438834389343903439134392343933439434395343963439734398343993440034401344023440334404344053440634407344083440934410344113441234413344143441534416344173441834419344203442134422344233442434425344263442734428344293443034431344323443334434344353443634437344383443934440344413444234443344443444534446344473444834449344503445134452344533445434455344563445734458344593446034461344623446334464344653446634467344683446934470344713447234473344743447534476344773447834479344803448134482344833448434485344863448734488344893449034491344923449334494344953449634497344983449934500345013450234503345043450534506345073450834509345103451134512345133451434515345163451734518345193452034521345223452334524345253452634527345283452934530345313453234533345343453534536345373453834539345403454134542345433454434545345463454734548345493455034551345523455334554345553455634557345583455934560345613456234563345643456534566345673456834569345703457134572345733457434575345763457734578345793458034581345823458334584345853458634587345883458934590345913459234593345943459534596345973459834599346003460134602346033460434605346063460734608346093461034611346123461334614346153461634617346183461934620346213462234623346243462534626346273462834629346303463134632346333463434635346363463734638346393464034641346423464334644346453464634647346483464934650346513465234653346543465534656346573465834659346603466134662346633466434665346663466734668346693467034671346723467334674346753467634677346783467934680346813468234683346843468534686346873468834689346903469134692346933469434695346963469734698346993470034701347023470334704347053470634707347083470934710347113471234713347143471534716347173471834719347203472134722347233472434725347263472734728347293473034731347323473334734347353473634737347383473934740347413474234743347443474534746347473474834749347503475134752347533475434755347563475734758347593476034761347623476334764347653476634767347683476934770347713477234773347743477534776347773477834779347803478134782347833478434785347863478734788347893479034791347923479334794347953479634797347983479934800348013480234803348043480534806348073480834809348103481134812348133481434815348163481734818348193482034821348223482334824348253482634827348283482934830348313483234833348343483534836348373483834839348403484134842348433484434845348463484734848348493485034851348523485334854348553485634857348583485934860348613486234863348643486534866348673486834869348703487134872348733487434875348763487734878348793488034881348823488334884348853488634887348883488934890348913489234893348943489534896348973489834899349003490134902349033490434905349063490734908349093491034911349123491334914349153491634917349183491934920349213492234923349243492534926349273492834929349303493134932349333493434935349363493734938349393494034941349423494334944349453494634947349483494934950349513495234953349543495534956349573495834959349603496134962349633496434965349663496734968349693497034971349723497334974349753497634977349783497934980349813498234983349843498534986349873498834989349903499134992349933499434995349963499734998349993500035001350023500335004350053500635007350083500935010350113501235013350143501535016350173501835019350203502135022350233502435025350263502735028350293503035031350323503335034350353503635037350383503935040350413504235043350443504535046350473504835049350503505135052350533505435055350563505735058350593506035061350623506335064350653506635067350683506935070350713507235073350743507535076350773507835079350803508135082350833508435085350863508735088350893509035091350923509335094350953509635097350983509935100351013510235103351043510535106351073510835109351103511135112351133511435115351163511735118351193512035121351223512335124351253512635127351283512935130351313513235133351343513535136351373513835139351403514135142351433514435145351463514735148351493515035151351523515335154351553515635157351583515935160351613516235163351643516535166351673516835169351703517135172351733517435175351763517735178351793518035181351823518335184351853518635187351883518935190351913519235193351943519535196351973519835199352003520135202352033520435205352063520735208352093521035211352123521335214352153521635217352183521935220352213522235223352243522535226352273522835229352303523135232352333523435235352363523735238352393524035241352423524335244352453524635247352483524935250352513525235253352543525535256352573525835259352603526135262352633526435265352663526735268352693527035271352723527335274352753527635277352783527935280352813528235283352843528535286352873528835289352903529135292352933529435295352963529735298352993530035301353023530335304353053530635307353083530935310353113531235313353143531535316353173531835319353203532135322353233532435325353263532735328353293533035331353323533335334353353533635337353383533935340353413534235343353443534535346353473534835349353503535135352353533535435355353563535735358353593536035361353623536335364353653536635367353683536935370353713537235373353743537535376353773537835379353803538135382353833538435385353863538735388353893539035391353923539335394353953539635397353983539935400354013540235403354043540535406354073540835409354103541135412354133541435415354163541735418354193542035421354223542335424354253542635427354283542935430354313543235433354343543535436354373543835439354403544135442354433544435445354463544735448354493545035451354523545335454354553545635457354583545935460354613546235463354643546535466354673546835469354703547135472354733547435475354763547735478354793548035481354823548335484354853548635487354883548935490354913549235493354943549535496354973549835499355003550135502355033550435505355063550735508355093551035511355123551335514355153551635517355183551935520355213552235523355243552535526355273552835529355303553135532355333553435535355363553735538355393554035541355423554335544355453554635547355483554935550355513555235553355543555535556355573555835559355603556135562355633556435565355663556735568355693557035571355723557335574355753557635577355783557935580355813558235583355843558535586355873558835589355903559135592355933559435595355963559735598355993560035601356023560335604356053560635607356083560935610356113561235613356143561535616356173561835619356203562135622356233562435625356263562735628356293563035631356323563335634356353563635637356383563935640356413564235643356443564535646356473564835649356503565135652356533565435655356563565735658356593566035661356623566335664356653566635667356683566935670356713567235673356743567535676356773567835679356803568135682356833568435685356863568735688356893569035691356923569335694356953569635697356983569935700357013570235703357043570535706357073570835709357103571135712357133571435715357163571735718357193572035721357223572335724357253572635727357283572935730357313573235733357343573535736357373573835739357403574135742357433574435745357463574735748357493575035751357523575335754357553575635757357583575935760357613576235763357643576535766357673576835769357703577135772357733577435775357763577735778357793578035781357823578335784357853578635787357883578935790357913579235793357943579535796357973579835799358003580135802358033580435805358063580735808358093581035811358123581335814358153581635817358183581935820358213582235823358243582535826358273582835829358303583135832358333583435835358363583735838358393584035841358423584335844358453584635847358483584935850358513585235853358543585535856358573585835859358603586135862358633586435865358663586735868358693587035871358723587335874358753587635877358783587935880358813588235883358843588535886358873588835889358903589135892358933589435895358963589735898358993590035901359023590335904359053590635907359083590935910359113591235913359143591535916359173591835919359203592135922359233592435925359263592735928359293593035931359323593335934359353593635937359383593935940359413594235943359443594535946359473594835949359503595135952359533595435955359563595735958359593596035961359623596335964359653596635967359683596935970359713597235973359743597535976359773597835979359803598135982359833598435985359863598735988359893599035991359923599335994359953599635997359983599936000360013600236003360043600536006360073600836009360103601136012360133601436015360163601736018360193602036021360223602336024360253602636027360283602936030360313603236033360343603536036360373603836039360403604136042360433604436045360463604736048360493605036051360523605336054360553605636057360583605936060360613606236063360643606536066360673606836069360703607136072360733607436075360763607736078360793608036081360823608336084360853608636087360883608936090360913609236093360943609536096360973609836099361003610136102361033610436105361063610736108361093611036111361123611336114361153611636117361183611936120361213612236123361243612536126361273612836129361303613136132361333613436135361363613736138361393614036141361423614336144361453614636147361483614936150361513615236153361543615536156361573615836159361603616136162361633616436165361663616736168361693617036171361723617336174361753617636177361783617936180361813618236183361843618536186361873618836189361903619136192361933619436195361963619736198361993620036201362023620336204362053620636207362083620936210362113621236213362143621536216362173621836219362203622136222362233622436225362263622736228362293623036231362323623336234362353623636237362383623936240362413624236243362443624536246362473624836249362503625136252362533625436255362563625736258362593626036261362623626336264362653626636267362683626936270362713627236273362743627536276362773627836279362803628136282362833628436285362863628736288362893629036291362923629336294362953629636297362983629936300363013630236303363043630536306363073630836309363103631136312363133631436315363163631736318363193632036321363223632336324363253632636327363283632936330363313633236333363343633536336363373633836339363403634136342363433634436345363463634736348363493635036351363523635336354363553635636357363583635936360363613636236363363643636536366363673636836369363703637136372363733637436375363763637736378363793638036381363823638336384363853638636387363883638936390363913639236393363943639536396363973639836399364003640136402364033640436405364063640736408364093641036411364123641336414364153641636417364183641936420364213642236423364243642536426364273642836429364303643136432364333643436435364363643736438364393644036441364423644336444364453644636447364483644936450364513645236453364543645536456364573645836459364603646136462364633646436465364663646736468364693647036471364723647336474364753647636477364783647936480364813648236483364843648536486364873648836489364903649136492364933649436495364963649736498364993650036501365023650336504365053650636507365083650936510365113651236513365143651536516365173651836519365203652136522365233652436525365263652736528365293653036531365323653336534365353653636537365383653936540365413654236543365443654536546365473654836549365503655136552365533655436555365563655736558365593656036561365623656336564365653656636567365683656936570365713657236573365743657536576365773657836579365803658136582365833658436585365863658736588365893659036591365923659336594365953659636597365983659936600366013660236603366043660536606366073660836609366103661136612366133661436615366163661736618366193662036621366223662336624366253662636627366283662936630366313663236633366343663536636366373663836639366403664136642366433664436645366463664736648366493665036651366523665336654366553665636657366583665936660366613666236663366643666536666366673666836669366703667136672366733667436675366763667736678366793668036681366823668336684366853668636687366883668936690366913669236693366943669536696366973669836699367003670136702367033670436705367063670736708367093671036711367123671336714367153671636717367183671936720367213672236723367243672536726367273672836729367303673136732367333673436735367363673736738367393674036741367423674336744367453674636747367483674936750367513675236753367543675536756367573675836759367603676136762367633676436765367663676736768367693677036771367723677336774367753677636777367783677936780367813678236783367843678536786367873678836789367903679136792367933679436795367963679736798367993680036801368023680336804368053680636807368083680936810368113681236813368143681536816368173681836819368203682136822368233682436825368263682736828368293683036831368323683336834368353683636837368383683936840368413684236843368443684536846368473684836849368503685136852368533685436855368563685736858368593686036861368623686336864368653686636867368683686936870368713687236873368743687536876368773687836879368803688136882368833688436885368863688736888368893689036891368923689336894368953689636897368983689936900369013690236903369043690536906369073690836909369103691136912369133691436915369163691736918369193692036921369223692336924369253692636927369283692936930369313693236933369343693536936369373693836939369403694136942369433694436945369463694736948369493695036951369523695336954369553695636957369583695936960369613696236963369643696536966369673696836969369703697136972369733697436975369763697736978369793698036981369823698336984369853698636987369883698936990369913699236993369943699536996369973699836999370003700137002370033700437005370063700737008370093701037011370123701337014370153701637017370183701937020370213702237023370243702537026370273702837029370303703137032370333703437035370363703737038370393704037041370423704337044370453704637047370483704937050370513705237053370543705537056370573705837059370603706137062370633706437065370663706737068370693707037071370723707337074370753707637077370783707937080370813708237083370843708537086370873708837089370903709137092370933709437095370963709737098370993710037101371023710337104371053710637107371083710937110371113711237113371143711537116371173711837119371203712137122371233712437125371263712737128371293713037131371323713337134371353713637137371383713937140371413714237143371443714537146371473714837149371503715137152371533715437155371563715737158371593716037161371623716337164371653716637167371683716937170371713717237173371743717537176371773717837179371803718137182371833718437185371863718737188371893719037191371923719337194371953719637197371983719937200372013720237203372043720537206372073720837209372103721137212372133721437215372163721737218372193722037221372223722337224372253722637227372283722937230372313723237233372343723537236372373723837239372403724137242372433724437245372463724737248372493725037251372523725337254372553725637257372583725937260372613726237263372643726537266372673726837269372703727137272372733727437275372763727737278372793728037281372823728337284372853728637287372883728937290372913729237293372943729537296372973729837299373003730137302373033730437305373063730737308373093731037311373123731337314373153731637317373183731937320373213732237323373243732537326373273732837329373303733137332373333733437335373363733737338373393734037341373423734337344373453734637347373483734937350373513735237353373543735537356373573735837359373603736137362373633736437365373663736737368373693737037371373723737337374373753737637377373783737937380373813738237383373843738537386373873738837389373903739137392373933739437395373963739737398373993740037401374023740337404374053740637407374083740937410374113741237413374143741537416374173741837419374203742137422374233742437425374263742737428374293743037431374323743337434374353743637437374383743937440374413744237443374443744537446374473744837449374503745137452374533745437455374563745737458374593746037461374623746337464374653746637467374683746937470374713747237473374743747537476374773747837479374803748137482374833748437485374863748737488374893749037491374923749337494374953749637497374983749937500375013750237503375043750537506375073750837509375103751137512375133751437515375163751737518375193752037521375223752337524375253752637527375283752937530375313753237533375343753537536375373753837539375403754137542375433754437545375463754737548375493755037551375523755337554375553755637557375583755937560375613756237563375643756537566375673756837569375703757137572375733757437575375763757737578375793758037581375823758337584375853758637587375883758937590375913759237593375943759537596375973759837599376003760137602376033760437605376063760737608376093761037611376123761337614376153761637617376183761937620376213762237623376243762537626376273762837629376303763137632376333763437635376363763737638376393764037641376423764337644376453764637647376483764937650376513765237653376543765537656376573765837659376603766137662376633766437665376663766737668376693767037671376723767337674376753767637677376783767937680376813768237683376843768537686376873768837689376903769137692376933769437695376963769737698376993770037701377023770337704377053770637707377083770937710377113771237713377143771537716377173771837719377203772137722377233772437725377263772737728377293773037731377323773337734377353773637737377383773937740377413774237743377443774537746377473774837749377503775137752377533775437755377563775737758377593776037761377623776337764377653776637767377683776937770377713777237773377743777537776377773777837779377803778137782377833778437785377863778737788377893779037791377923779337794377953779637797377983779937800378013780237803378043780537806378073780837809378103781137812378133781437815378163781737818378193782037821378223782337824378253782637827378283782937830378313783237833378343783537836378373783837839378403784137842378433784437845378463784737848378493785037851378523785337854378553785637857378583785937860378613786237863378643786537866378673786837869378703787137872378733787437875378763787737878378793788037881378823788337884378853788637887378883788937890378913789237893378943789537896378973789837899379003790137902379033790437905379063790737908379093791037911379123791337914379153791637917379183791937920379213792237923379243792537926379273792837929379303793137932379333793437935379363793737938379393794037941379423794337944379453794637947379483794937950379513795237953379543795537956379573795837959379603796137962379633796437965379663796737968379693797037971379723797337974379753797637977379783797937980379813798237983379843798537986379873798837989379903799137992379933799437995379963799737998379993800038001380023800338004380053800638007380083800938010380113801238013380143801538016380173801838019380203802138022380233802438025380263802738028380293803038031380323803338034380353803638037380383803938040380413804238043380443804538046380473804838049380503805138052380533805438055380563805738058380593806038061380623806338064380653806638067380683806938070380713807238073380743807538076380773807838079380803808138082380833808438085380863808738088380893809038091380923809338094380953809638097380983809938100381013810238103381043810538106381073810838109381103811138112381133811438115381163811738118381193812038121381223812338124381253812638127381283812938130381313813238133381343813538136381373813838139381403814138142381433814438145381463814738148381493815038151381523815338154381553815638157381583815938160381613816238163381643816538166381673816838169381703817138172381733817438175381763817738178381793818038181381823818338184381853818638187381883818938190381913819238193381943819538196381973819838199382003820138202382033820438205382063820738208382093821038211382123821338214382153821638217382183821938220382213822238223382243822538226382273822838229382303823138232382333823438235382363823738238382393824038241382423824338244382453824638247382483824938250382513825238253382543825538256382573825838259382603826138262382633826438265382663826738268382693827038271382723827338274382753827638277382783827938280382813828238283382843828538286382873828838289382903829138292382933829438295382963829738298382993830038301383023830338304383053830638307383083830938310383113831238313383143831538316383173831838319383203832138322383233832438325383263832738328383293833038331383323833338334383353833638337383383833938340383413834238343383443834538346383473834838349383503835138352383533835438355383563835738358383593836038361383623836338364383653836638367383683836938370383713837238373383743837538376383773837838379383803838138382383833838438385383863838738388383893839038391383923839338394383953839638397383983839938400384013840238403384043840538406384073840838409384103841138412384133841438415384163841738418384193842038421384223842338424384253842638427384283842938430384313843238433384343843538436384373843838439384403844138442384433844438445384463844738448384493845038451384523845338454384553845638457384583845938460384613846238463384643846538466384673846838469384703847138472384733847438475384763847738478384793848038481384823848338484384853848638487384883848938490384913849238493384943849538496384973849838499385003850138502385033850438505385063850738508385093851038511385123851338514385153851638517385183851938520385213852238523385243852538526385273852838529385303853138532385333853438535385363853738538385393854038541385423854338544385453854638547385483854938550385513855238553385543855538556385573855838559385603856138562385633856438565385663856738568385693857038571385723857338574385753857638577385783857938580385813858238583385843858538586385873858838589385903859138592385933859438595385963859738598385993860038601386023860338604386053860638607386083860938610386113861238613386143861538616386173861838619386203862138622386233862438625386263862738628386293863038631386323863338634386353863638637386383863938640386413864238643386443864538646386473864838649386503865138652386533865438655386563865738658386593866038661386623866338664386653866638667386683866938670386713867238673386743867538676386773867838679386803868138682386833868438685386863868738688386893869038691386923869338694386953869638697386983869938700387013870238703387043870538706387073870838709387103871138712387133871438715387163871738718387193872038721387223872338724387253872638727387283872938730387313873238733387343873538736387373873838739387403874138742387433874438745387463874738748387493875038751387523875338754387553875638757387583875938760387613876238763387643876538766387673876838769387703877138772387733877438775387763877738778387793878038781387823878338784387853878638787387883878938790387913879238793387943879538796387973879838799388003880138802388033880438805388063880738808388093881038811388123881338814388153881638817388183881938820388213882238823388243882538826388273882838829388303883138832388333883438835388363883738838388393884038841388423884338844388453884638847388483884938850388513885238853388543885538856388573885838859388603886138862388633886438865388663886738868388693887038871388723887338874388753887638877388783887938880388813888238883388843888538886388873888838889388903889138892388933889438895388963889738898388993890038901389023890338904389053890638907389083890938910389113891238913389143891538916389173891838919389203892138922389233892438925389263892738928389293893038931389323893338934389353893638937389383893938940389413894238943389443894538946389473894838949389503895138952389533895438955389563895738958389593896038961389623896338964389653896638967389683896938970389713897238973389743897538976389773897838979389803898138982389833898438985389863898738988389893899038991389923899338994389953899638997389983899939000390013900239003390043900539006390073900839009390103901139012390133901439015390163901739018390193902039021390223902339024390253902639027390283902939030390313903239033390343903539036390373903839039390403904139042390433904439045390463904739048390493905039051390523905339054390553905639057390583905939060390613906239063390643906539066390673906839069390703907139072390733907439075390763907739078390793908039081390823908339084390853908639087390883908939090390913909239093390943909539096390973909839099391003910139102391033910439105391063910739108391093911039111391123911339114391153911639117391183911939120391213912239123391243912539126391273912839129391303913139132391333913439135391363913739138391393914039141391423914339144391453914639147391483914939150391513915239153391543915539156391573915839159391603916139162391633916439165391663916739168391693917039171391723917339174391753917639177391783917939180391813918239183391843918539186391873918839189391903919139192391933919439195391963919739198391993920039201392023920339204392053920639207392083920939210392113921239213392143921539216392173921839219392203922139222392233922439225392263922739228392293923039231392323923339234392353923639237392383923939240392413924239243392443924539246392473924839249392503925139252392533925439255392563925739258392593926039261392623926339264392653926639267392683926939270392713927239273392743927539276392773927839279392803928139282392833928439285392863928739288392893929039291392923929339294392953929639297392983929939300393013930239303393043930539306393073930839309393103931139312393133931439315393163931739318393193932039321393223932339324393253932639327393283932939330393313933239333393343933539336393373933839339393403934139342393433934439345393463934739348393493935039351393523935339354393553935639357393583935939360393613936239363393643936539366393673936839369393703937139372393733937439375393763937739378393793938039381393823938339384393853938639387393883938939390393913939239393393943939539396393973939839399394003940139402394033940439405394063940739408394093941039411394123941339414394153941639417394183941939420394213942239423394243942539426394273942839429394303943139432394333943439435394363943739438394393944039441394423944339444394453944639447394483944939450394513945239453394543945539456394573945839459394603946139462394633946439465394663946739468394693947039471394723947339474394753947639477394783947939480394813948239483394843948539486394873948839489394903949139492394933949439495394963949739498394993950039501395023950339504395053950639507395083950939510395113951239513395143951539516395173951839519395203952139522395233952439525395263952739528395293953039531395323953339534395353953639537395383953939540395413954239543395443954539546395473954839549395503955139552395533955439555395563955739558395593956039561395623956339564395653956639567395683956939570395713957239573395743957539576395773957839579395803958139582395833958439585395863958739588395893959039591395923959339594395953959639597395983959939600396013960239603396043960539606396073960839609396103961139612396133961439615396163961739618396193962039621396223962339624396253962639627396283962939630396313963239633396343963539636396373963839639396403964139642396433964439645396463964739648396493965039651396523965339654396553965639657396583965939660396613966239663396643966539666396673966839669396703967139672396733967439675396763967739678396793968039681396823968339684396853968639687396883968939690396913969239693396943969539696396973969839699397003970139702397033970439705397063970739708397093971039711397123971339714397153971639717397183971939720397213972239723397243972539726397273972839729397303973139732397333973439735397363973739738397393974039741397423974339744397453974639747397483974939750397513975239753397543975539756397573975839759397603976139762397633976439765397663976739768397693977039771397723977339774397753977639777397783977939780397813978239783397843978539786397873978839789397903979139792397933979439795397963979739798397993980039801398023980339804398053980639807398083980939810398113981239813398143981539816398173981839819398203982139822398233982439825398263982739828398293983039831398323983339834398353983639837398383983939840398413984239843398443984539846398473984839849398503985139852398533985439855398563985739858398593986039861398623986339864398653986639867398683986939870398713987239873398743987539876398773987839879398803988139882398833988439885398863988739888398893989039891398923989339894398953989639897398983989939900399013990239903399043990539906399073990839909399103991139912399133991439915399163991739918399193992039921399223992339924399253992639927399283992939930399313993239933399343993539936399373993839939399403994139942399433994439945399463994739948399493995039951399523995339954399553995639957399583995939960399613996239963399643996539966399673996839969399703997139972399733997439975399763997739978399793998039981399823998339984399853998639987399883998939990399913999239993399943999539996399973999839999400004000140002400034000440005400064000740008400094001040011400124001340014400154001640017400184001940020400214002240023400244002540026400274002840029400304003140032400334003440035400364003740038400394004040041400424004340044400454004640047400484004940050400514005240053400544005540056400574005840059400604006140062400634006440065400664006740068400694007040071400724007340074400754007640077400784007940080400814008240083400844008540086400874008840089400904009140092400934009440095400964009740098400994010040101401024010340104401054010640107401084010940110401114011240113401144011540116401174011840119401204012140122401234012440125401264012740128401294013040131401324013340134401354013640137401384013940140401414014240143401444014540146401474014840149401504015140152401534015440155401564015740158401594016040161401624016340164401654016640167401684016940170401714017240173401744017540176401774017840179401804018140182401834018440185401864018740188401894019040191401924019340194401954019640197401984019940200402014020240203402044020540206402074020840209402104021140212402134021440215402164021740218402194022040221402224022340224402254022640227402284022940230402314023240233402344023540236402374023840239402404024140242402434024440245402464024740248402494025040251402524025340254402554025640257402584025940260402614026240263402644026540266402674026840269402704027140272402734027440275402764027740278402794028040281402824028340284402854028640287402884028940290402914029240293402944029540296402974029840299403004030140302403034030440305403064030740308403094031040311403124031340314403154031640317403184031940320403214032240323403244032540326403274032840329403304033140332403334033440335403364033740338403394034040341403424034340344403454034640347403484034940350403514035240353403544035540356403574035840359403604036140362403634036440365403664036740368403694037040371403724037340374403754037640377403784037940380403814038240383403844038540386403874038840389403904039140392403934039440395403964039740398403994040040401404024040340404404054040640407404084040940410404114041240413404144041540416404174041840419404204042140422404234042440425404264042740428404294043040431404324043340434404354043640437404384043940440404414044240443404444044540446404474044840449404504045140452404534045440455404564045740458404594046040461404624046340464404654046640467404684046940470404714047240473404744047540476404774047840479404804048140482404834048440485404864048740488404894049040491404924049340494404954049640497404984049940500405014050240503405044050540506405074050840509405104051140512405134051440515405164051740518405194052040521405224052340524405254052640527405284052940530405314053240533405344053540536405374053840539405404054140542405434054440545405464054740548405494055040551405524055340554405554055640557405584055940560405614056240563405644056540566405674056840569405704057140572405734057440575405764057740578405794058040581405824058340584405854058640587405884058940590405914059240593405944059540596405974059840599406004060140602406034060440605406064060740608406094061040611406124061340614406154061640617406184061940620406214062240623406244062540626406274062840629406304063140632406334063440635406364063740638406394064040641406424064340644406454064640647406484064940650406514065240653406544065540656406574065840659406604066140662406634066440665406664066740668406694067040671406724067340674406754067640677406784067940680406814068240683406844068540686406874068840689406904069140692406934069440695406964069740698406994070040701407024070340704407054070640707407084070940710407114071240713407144071540716407174071840719407204072140722407234072440725407264072740728407294073040731407324073340734407354073640737407384073940740407414074240743407444074540746407474074840749407504075140752407534075440755407564075740758407594076040761407624076340764407654076640767407684076940770407714077240773407744077540776407774077840779407804078140782407834078440785407864078740788407894079040791407924079340794407954079640797407984079940800408014080240803408044080540806408074080840809408104081140812408134081440815408164081740818408194082040821408224082340824408254082640827408284082940830408314083240833408344083540836408374083840839408404084140842408434084440845408464084740848408494085040851408524085340854408554085640857408584085940860408614086240863408644086540866408674086840869408704087140872408734087440875408764087740878408794088040881408824088340884408854088640887408884088940890408914089240893408944089540896408974089840899409004090140902409034090440905409064090740908409094091040911409124091340914409154091640917409184091940920409214092240923409244092540926409274092840929409304093140932409334093440935409364093740938409394094040941409424094340944409454094640947409484094940950409514095240953409544095540956409574095840959409604096140962409634096440965409664096740968409694097040971409724097340974409754097640977409784097940980409814098240983409844098540986409874098840989409904099140992409934099440995409964099740998409994100041001410024100341004410054100641007410084100941010410114101241013410144101541016410174101841019410204102141022410234102441025410264102741028410294103041031410324103341034410354103641037410384103941040410414104241043410444104541046410474104841049410504105141052410534105441055410564105741058410594106041061410624106341064410654106641067410684106941070410714107241073410744107541076410774107841079410804108141082410834108441085410864108741088410894109041091410924109341094410954109641097410984109941100411014110241103411044110541106411074110841109411104111141112411134111441115411164111741118411194112041121411224112341124411254112641127411284112941130411314113241133411344113541136411374113841139411404114141142411434114441145411464114741148411494115041151411524115341154411554115641157411584115941160411614116241163411644116541166411674116841169411704117141172411734117441175411764117741178411794118041181411824118341184411854118641187411884118941190411914119241193411944119541196411974119841199412004120141202412034120441205412064120741208412094121041211412124121341214412154121641217412184121941220412214122241223412244122541226412274122841229412304123141232412334123441235412364123741238412394124041241412424124341244412454124641247412484124941250412514125241253412544125541256412574125841259412604126141262412634126441265412664126741268412694127041271412724127341274412754127641277412784127941280412814128241283412844128541286412874128841289412904129141292412934129441295412964129741298412994130041301413024130341304413054130641307413084130941310413114131241313413144131541316413174131841319413204132141322413234132441325413264132741328413294133041331413324133341334413354133641337413384133941340413414134241343413444134541346413474134841349413504135141352413534135441355413564135741358413594136041361413624136341364413654136641367413684136941370413714137241373413744137541376413774137841379413804138141382413834138441385413864138741388413894139041391413924139341394413954139641397413984139941400414014140241403414044140541406414074140841409414104141141412414134141441415414164141741418414194142041421414224142341424414254142641427414284142941430414314143241433414344143541436414374143841439414404144141442414434144441445414464144741448414494145041451414524145341454414554145641457414584145941460414614146241463414644146541466414674146841469414704147141472414734147441475414764147741478414794148041481414824148341484414854148641487414884148941490414914149241493414944149541496414974149841499415004150141502415034150441505415064150741508415094151041511415124151341514415154151641517415184151941520415214152241523415244152541526415274152841529415304153141532415334153441535415364153741538415394154041541415424154341544415454154641547415484154941550415514155241553415544155541556415574155841559415604156141562415634156441565415664156741568415694157041571415724157341574415754157641577415784157941580415814158241583415844158541586415874158841589415904159141592415934159441595415964159741598415994160041601416024160341604416054160641607416084160941610416114161241613416144161541616416174161841619416204162141622416234162441625416264162741628416294163041631416324163341634416354163641637416384163941640416414164241643416444164541646416474164841649416504165141652416534165441655416564165741658416594166041661416624166341664416654166641667416684166941670416714167241673416744167541676416774167841679416804168141682416834168441685416864168741688416894169041691416924169341694416954169641697416984169941700417014170241703417044170541706417074170841709417104171141712417134171441715417164171741718417194172041721417224172341724417254172641727417284172941730417314173241733417344173541736417374173841739417404174141742417434174441745417464174741748417494175041751417524175341754417554175641757417584175941760417614176241763417644176541766417674176841769417704177141772417734177441775417764177741778417794178041781417824178341784417854178641787417884178941790417914179241793417944179541796417974179841799418004180141802418034180441805418064180741808418094181041811418124181341814418154181641817418184181941820418214182241823418244182541826418274182841829418304183141832418334183441835418364183741838418394184041841418424184341844418454184641847418484184941850418514185241853418544185541856418574185841859418604186141862418634186441865418664186741868418694187041871418724187341874418754187641877418784187941880418814188241883418844188541886418874188841889418904189141892418934189441895418964189741898418994190041901419024190341904419054190641907419084190941910419114191241913419144191541916419174191841919419204192141922419234192441925419264192741928419294193041931419324193341934419354193641937419384193941940419414194241943419444194541946419474194841949419504195141952419534195441955419564195741958419594196041961419624196341964419654196641967419684196941970419714197241973419744197541976419774197841979419804198141982419834198441985419864198741988419894199041991419924199341994419954199641997419984199942000420014200242003420044200542006420074200842009420104201142012420134201442015420164201742018420194202042021420224202342024420254202642027420284202942030420314203242033420344203542036420374203842039420404204142042420434204442045420464204742048420494205042051420524205342054420554205642057420584205942060420614206242063420644206542066420674206842069420704207142072420734207442075420764207742078420794208042081420824208342084420854208642087420884208942090420914209242093420944209542096420974209842099421004210142102421034210442105421064210742108421094211042111421124211342114421154211642117421184211942120421214212242123421244212542126421274212842129421304213142132421334213442135421364213742138421394214042141421424214342144421454214642147421484214942150421514215242153421544215542156421574215842159421604216142162421634216442165421664216742168421694217042171421724217342174421754217642177421784217942180421814218242183421844218542186421874218842189421904219142192421934219442195421964219742198421994220042201422024220342204422054220642207422084220942210422114221242213422144221542216422174221842219422204222142222422234222442225422264222742228422294223042231422324223342234422354223642237422384223942240422414224242243422444224542246422474224842249422504225142252422534225442255422564225742258422594226042261422624226342264422654226642267422684226942270422714227242273422744227542276422774227842279422804228142282422834228442285422864228742288422894229042291422924229342294422954229642297422984229942300423014230242303423044230542306423074230842309423104231142312423134231442315423164231742318423194232042321423224232342324423254232642327423284232942330423314233242333423344233542336423374233842339423404234142342423434234442345423464234742348423494235042351423524235342354423554235642357423584235942360423614236242363423644236542366423674236842369423704237142372423734237442375423764237742378423794238042381423824238342384423854238642387423884238942390423914239242393423944239542396423974239842399424004240142402424034240442405424064240742408424094241042411424124241342414424154241642417424184241942420424214242242423424244242542426424274242842429424304243142432424334243442435424364243742438424394244042441424424244342444424454244642447424484244942450424514245242453424544245542456424574245842459424604246142462424634246442465424664246742468424694247042471424724247342474424754247642477424784247942480424814248242483424844248542486424874248842489424904249142492424934249442495424964249742498424994250042501425024250342504425054250642507425084250942510425114251242513425144251542516425174251842519425204252142522425234252442525425264252742528425294253042531425324253342534425354253642537425384253942540425414254242543425444254542546425474254842549425504255142552425534255442555425564255742558425594256042561425624256342564425654256642567425684256942570425714257242573425744257542576425774257842579425804258142582425834258442585425864258742588425894259042591425924259342594425954259642597425984259942600426014260242603426044260542606426074260842609426104261142612426134261442615426164261742618426194262042621426224262342624426254262642627426284262942630426314263242633426344263542636426374263842639426404264142642426434264442645426464264742648426494265042651426524265342654426554265642657426584265942660426614266242663426644266542666426674266842669426704267142672426734267442675426764267742678426794268042681426824268342684426854268642687426884268942690426914269242693426944269542696426974269842699427004270142702427034270442705427064270742708427094271042711427124271342714427154271642717427184271942720427214272242723427244272542726427274272842729427304273142732427334273442735427364273742738427394274042741427424274342744427454274642747427484274942750427514275242753427544275542756427574275842759427604276142762427634276442765427664276742768427694277042771427724277342774427754277642777427784277942780427814278242783427844278542786427874278842789427904279142792427934279442795427964279742798427994280042801428024280342804428054280642807428084280942810428114281242813428144281542816428174281842819428204282142822428234282442825428264282742828428294283042831428324283342834428354283642837428384283942840428414284242843428444284542846428474284842849428504285142852428534285442855428564285742858428594286042861428624286342864428654286642867428684286942870428714287242873428744287542876428774287842879428804288142882428834288442885428864288742888428894289042891428924289342894428954289642897428984289942900429014290242903429044290542906429074290842909429104291142912429134291442915429164291742918429194292042921429224292342924429254292642927429284292942930429314293242933429344293542936429374293842939429404294142942429434294442945429464294742948429494295042951429524295342954429554295642957429584295942960429614296242963429644296542966429674296842969429704297142972429734297442975429764297742978429794298042981429824298342984429854298642987429884298942990429914299242993429944299542996429974299842999430004300143002430034300443005430064300743008430094301043011430124301343014430154301643017430184301943020430214302243023430244302543026430274302843029430304303143032430334303443035430364303743038430394304043041430424304343044430454304643047430484304943050430514305243053430544305543056430574305843059430604306143062430634306443065430664306743068430694307043071430724307343074430754307643077430784307943080430814308243083430844308543086430874308843089430904309143092430934309443095430964309743098430994310043101431024310343104431054310643107431084310943110431114311243113431144311543116431174311843119431204312143122431234312443125431264312743128431294313043131431324313343134431354313643137431384313943140431414314243143431444314543146431474314843149431504315143152431534315443155431564315743158431594316043161431624316343164431654316643167431684316943170431714317243173431744317543176431774317843179431804318143182431834318443185431864318743188431894319043191431924319343194431954319643197431984319943200432014320243203432044320543206432074320843209432104321143212432134321443215432164321743218432194322043221432224322343224432254322643227432284322943230432314323243233432344323543236432374323843239432404324143242432434324443245432464324743248432494325043251432524325343254432554325643257432584325943260432614326243263432644326543266432674326843269432704327143272432734327443275432764327743278432794328043281432824328343284432854328643287432884328943290432914329243293432944329543296432974329843299433004330143302433034330443305433064330743308433094331043311433124331343314433154331643317433184331943320433214332243323433244332543326433274332843329433304333143332433334333443335433364333743338433394334043341433424334343344433454334643347433484334943350433514335243353433544335543356433574335843359433604336143362433634336443365433664336743368433694337043371433724337343374433754337643377433784337943380433814338243383433844338543386433874338843389433904339143392433934339443395433964339743398433994340043401434024340343404434054340643407434084340943410434114341243413434144341543416434174341843419434204342143422434234342443425434264342743428434294343043431434324343343434434354343643437434384343943440434414344243443434444344543446434474344843449434504345143452434534345443455434564345743458434594346043461434624346343464434654346643467434684346943470434714347243473434744347543476434774347843479434804348143482434834348443485434864348743488434894349043491434924349343494434954349643497434984349943500435014350243503435044350543506435074350843509435104351143512435134351443515435164351743518435194352043521435224352343524435254352643527435284352943530435314353243533435344353543536435374353843539435404354143542435434354443545435464354743548435494355043551435524355343554435554355643557435584355943560435614356243563435644356543566435674356843569435704357143572435734357443575435764357743578435794358043581435824358343584435854358643587435884358943590435914359243593435944359543596435974359843599436004360143602436034360443605436064360743608436094361043611436124361343614436154361643617436184361943620436214362243623436244362543626436274362843629436304363143632436334363443635436364363743638436394364043641436424364343644436454364643647436484364943650436514365243653436544365543656436574365843659436604366143662436634366443665436664366743668436694367043671436724367343674436754367643677436784367943680436814368243683436844368543686436874368843689436904369143692436934369443695436964369743698436994370043701437024370343704437054370643707437084370943710437114371243713437144371543716437174371843719437204372143722437234372443725437264372743728437294373043731437324373343734437354373643737437384373943740437414374243743437444374543746437474374843749437504375143752437534375443755437564375743758437594376043761437624376343764437654376643767437684376943770437714377243773437744377543776437774377843779437804378143782437834378443785437864378743788437894379043791437924379343794437954379643797437984379943800438014380243803438044380543806438074380843809438104381143812438134381443815438164381743818438194382043821438224382343824438254382643827438284382943830438314383243833438344383543836438374383843839438404384143842438434384443845438464384743848438494385043851438524385343854438554385643857438584385943860438614386243863438644386543866438674386843869438704387143872438734387443875438764387743878438794388043881438824388343884438854388643887438884388943890438914389243893438944389543896438974389843899439004390143902439034390443905439064390743908439094391043911439124391343914439154391643917439184391943920439214392243923439244392543926439274392843929439304393143932439334393443935439364393743938439394394043941439424394343944439454394643947439484394943950439514395243953439544395543956439574395843959439604396143962439634396443965439664396743968439694397043971439724397343974439754397643977439784397943980439814398243983439844398543986439874398843989439904399143992439934399443995439964399743998439994400044001440024400344004440054400644007440084400944010440114401244013440144401544016440174401844019440204402144022440234402444025440264402744028440294403044031440324403344034440354403644037440384403944040440414404244043440444404544046440474404844049440504405144052440534405444055440564405744058440594406044061440624406344064440654406644067440684406944070440714407244073440744407544076440774407844079440804408144082440834408444085440864408744088440894409044091440924409344094440954409644097440984409944100441014410244103441044410544106441074410844109441104411144112441134411444115441164411744118441194412044121441224412344124441254412644127441284412944130441314413244133441344413544136441374413844139441404414144142441434414444145441464414744148441494415044151441524415344154441554415644157441584415944160441614416244163441644416544166441674416844169441704417144172441734417444175441764417744178441794418044181441824418344184441854418644187441884418944190441914419244193441944419544196441974419844199442004420144202442034420444205442064420744208442094421044211442124421344214442154421644217442184421944220442214422244223442244422544226442274422844229442304423144232442334423444235442364423744238442394424044241442424424344244442454424644247442484424944250442514425244253442544425544256442574425844259442604426144262442634426444265442664426744268442694427044271442724427344274442754427644277442784427944280442814428244283442844428544286442874428844289442904429144292442934429444295442964429744298442994430044301443024430344304443054430644307443084430944310443114431244313443144431544316443174431844319443204432144322443234432444325443264432744328443294433044331443324433344334443354433644337443384433944340443414434244343443444434544346443474434844349443504435144352443534435444355443564435744358443594436044361443624436344364443654436644367443684436944370443714437244373443744437544376443774437844379443804438144382443834438444385443864438744388443894439044391443924439344394443954439644397443984439944400444014440244403444044440544406444074440844409444104441144412444134441444415444164441744418444194442044421444224442344424444254442644427444284442944430444314443244433444344443544436444374443844439444404444144442444434444444445444464444744448444494445044451444524445344454444554445644457444584445944460444614446244463444644446544466444674446844469444704447144472444734447444475444764447744478444794448044481444824448344484444854448644487444884448944490444914449244493444944449544496444974449844499445004450144502445034450444505445064450744508445094451044511445124451344514445154451644517445184451944520445214452244523445244452544526445274452844529445304453144532445334453444535445364453744538445394454044541445424454344544445454454644547445484454944550445514455244553445544455544556445574455844559445604456144562445634456444565445664456744568445694457044571445724457344574445754457644577445784457944580445814458244583445844458544586445874458844589445904459144592445934459444595445964459744598445994460044601446024460344604446054460644607446084460944610446114461244613446144461544616446174461844619446204462144622446234462444625446264462744628446294463044631446324463344634446354463644637446384463944640446414464244643446444464544646446474464844649446504465144652446534465444655446564465744658446594466044661446624466344664446654466644667446684466944670446714467244673446744467544676446774467844679446804468144682446834468444685446864468744688446894469044691446924469344694446954469644697446984469944700447014470244703447044470544706447074470844709447104471144712447134471444715447164471744718447194472044721447224472344724447254472644727447284472944730447314473244733447344473544736447374473844739447404474144742447434474444745447464474744748447494475044751447524475344754447554475644757447584475944760447614476244763447644476544766447674476844769447704477144772447734477444775447764477744778447794478044781447824478344784447854478644787447884478944790447914479244793447944479544796447974479844799448004480144802448034480444805448064480744808448094481044811448124481344814448154481644817448184481944820448214482244823448244482544826448274482844829448304483144832448334483444835448364483744838448394484044841448424484344844448454484644847448484484944850448514485244853448544485544856448574485844859448604486144862448634486444865448664486744868448694487044871448724487344874448754487644877448784487944880448814488244883448844488544886448874488844889448904489144892448934489444895448964489744898448994490044901449024490344904449054490644907449084490944910449114491244913449144491544916449174491844919449204492144922449234492444925449264492744928449294493044931449324493344934449354493644937449384493944940449414494244943449444494544946449474494844949449504495144952449534495444955449564495744958449594496044961449624496344964449654496644967449684496944970449714497244973449744497544976449774497844979449804498144982449834498444985449864498744988449894499044991449924499344994449954499644997449984499945000450014500245003450044500545006450074500845009450104501145012450134501445015450164501745018450194502045021450224502345024450254502645027450284502945030450314503245033450344503545036450374503845039450404504145042450434504445045450464504745048450494505045051450524505345054450554505645057450584505945060450614506245063450644506545066450674506845069450704507145072450734507445075450764507745078450794508045081450824508345084450854508645087450884508945090450914509245093450944509545096450974509845099451004510145102451034510445105451064510745108451094511045111451124511345114451154511645117451184511945120451214512245123451244512545126451274512845129451304513145132451334513445135451364513745138451394514045141451424514345144451454514645147451484514945150451514515245153451544515545156451574515845159451604516145162451634516445165451664516745168451694517045171451724517345174451754517645177451784517945180451814518245183451844518545186451874518845189451904519145192451934519445195451964519745198451994520045201452024520345204452054520645207452084520945210452114521245213452144521545216452174521845219452204522145222452234522445225452264522745228452294523045231452324523345234452354523645237452384523945240452414524245243452444524545246452474524845249452504525145252452534525445255452564525745258452594526045261452624526345264452654526645267452684526945270452714527245273452744527545276452774527845279452804528145282452834528445285452864528745288452894529045291452924529345294452954529645297452984529945300453014530245303453044530545306453074530845309453104531145312453134531445315453164531745318453194532045321453224532345324453254532645327453284532945330453314533245333453344533545336453374533845339453404534145342453434534445345453464534745348453494535045351453524535345354453554535645357453584535945360453614536245363453644536545366453674536845369453704537145372453734537445375453764537745378453794538045381453824538345384453854538645387453884538945390453914539245393453944539545396453974539845399454004540145402454034540445405454064540745408454094541045411454124541345414454154541645417454184541945420454214542245423454244542545426454274542845429454304543145432454334543445435454364543745438454394544045441454424544345444454454544645447454484544945450454514545245453454544545545456454574545845459454604546145462454634546445465454664546745468454694547045471454724547345474454754547645477454784547945480454814548245483454844548545486454874548845489454904549145492454934549445495454964549745498454994550045501455024550345504455054550645507455084550945510455114551245513455144551545516455174551845519455204552145522455234552445525455264552745528455294553045531455324553345534455354553645537455384553945540455414554245543455444554545546455474554845549455504555145552455534555445555455564555745558455594556045561455624556345564455654556645567455684556945570455714557245573455744557545576455774557845579455804558145582455834558445585455864558745588455894559045591455924559345594455954559645597455984559945600456014560245603456044560545606456074560845609456104561145612456134561445615456164561745618456194562045621456224562345624456254562645627456284562945630456314563245633456344563545636456374563845639456404564145642456434564445645456464564745648456494565045651456524565345654456554565645657456584565945660456614566245663456644566545666456674566845669456704567145672456734567445675456764567745678456794568045681456824568345684456854568645687456884568945690456914569245693456944569545696456974569845699457004570145702457034570445705457064570745708457094571045711457124571345714457154571645717457184571945720457214572245723457244572545726457274572845729457304573145732457334573445735457364573745738457394574045741457424574345744457454574645747457484574945750457514575245753457544575545756457574575845759457604576145762457634576445765457664576745768457694577045771457724577345774457754577645777457784577945780457814578245783457844578545786457874578845789457904579145792457934579445795457964579745798457994580045801458024580345804458054580645807458084580945810458114581245813458144581545816458174581845819458204582145822458234582445825458264582745828458294583045831458324583345834458354583645837458384583945840458414584245843458444584545846458474584845849458504585145852458534585445855458564585745858458594586045861458624586345864458654586645867458684586945870458714587245873458744587545876458774587845879458804588145882458834588445885458864588745888458894589045891458924589345894458954589645897458984589945900459014590245903459044590545906459074590845909459104591145912459134591445915459164591745918459194592045921459224592345924459254592645927459284592945930459314593245933459344593545936459374593845939459404594145942459434594445945459464594745948459494595045951459524595345954459554595645957459584595945960459614596245963459644596545966459674596845969459704597145972459734597445975459764597745978459794598045981459824598345984459854598645987459884598945990459914599245993459944599545996459974599845999460004600146002460034600446005460064600746008460094601046011460124601346014460154601646017460184601946020460214602246023460244602546026460274602846029460304603146032460334603446035460364603746038460394604046041460424604346044460454604646047460484604946050460514605246053460544605546056460574605846059460604606146062460634606446065460664606746068460694607046071460724607346074460754607646077460784607946080460814608246083460844608546086460874608846089460904609146092460934609446095460964609746098460994610046101461024610346104461054610646107461084610946110461114611246113461144611546116461174611846119461204612146122461234612446125461264612746128461294613046131461324613346134461354613646137461384613946140461414614246143461444614546146461474614846149461504615146152461534615446155461564615746158461594616046161461624616346164461654616646167461684616946170461714617246173461744617546176461774617846179461804618146182461834618446185461864618746188461894619046191461924619346194461954619646197461984619946200462014620246203462044620546206462074620846209462104621146212462134621446215462164621746218462194622046221462224622346224462254622646227462284622946230462314623246233462344623546236462374623846239462404624146242462434624446245462464624746248462494625046251462524625346254462554625646257462584625946260462614626246263462644626546266462674626846269462704627146272462734627446275462764627746278462794628046281462824628346284462854628646287462884628946290462914629246293462944629546296462974629846299463004630146302463034630446305463064630746308463094631046311463124631346314463154631646317463184631946320463214632246323463244632546326463274632846329463304633146332463334633446335463364633746338463394634046341463424634346344463454634646347463484634946350463514635246353463544635546356463574635846359463604636146362463634636446365463664636746368463694637046371463724637346374463754637646377463784637946380463814638246383463844638546386463874638846389463904639146392463934639446395463964639746398463994640046401464024640346404464054640646407464084640946410464114641246413464144641546416464174641846419464204642146422464234642446425464264642746428464294643046431464324643346434464354643646437464384643946440464414644246443464444644546446464474644846449464504645146452464534645446455464564645746458464594646046461464624646346464464654646646467464684646946470464714647246473464744647546476464774647846479464804648146482464834648446485464864648746488464894649046491464924649346494464954649646497464984649946500465014650246503465044650546506465074650846509465104651146512465134651446515465164651746518465194652046521465224652346524465254652646527465284652946530465314653246533465344653546536465374653846539465404654146542465434654446545465464654746548465494655046551465524655346554465554655646557465584655946560465614656246563465644656546566465674656846569465704657146572465734657446575465764657746578465794658046581465824658346584465854658646587465884658946590465914659246593465944659546596465974659846599466004660146602466034660446605466064660746608466094661046611466124661346614466154661646617466184661946620466214662246623466244662546626466274662846629466304663146632466334663446635466364663746638466394664046641466424664346644466454664646647466484664946650466514665246653466544665546656466574665846659466604666146662466634666446665466664666746668466694667046671466724667346674466754667646677466784667946680466814668246683466844668546686466874668846689466904669146692466934669446695466964669746698466994670046701467024670346704467054670646707467084670946710467114671246713467144671546716467174671846719467204672146722467234672446725467264672746728467294673046731467324673346734467354673646737467384673946740467414674246743467444674546746467474674846749467504675146752467534675446755467564675746758467594676046761467624676346764467654676646767467684676946770467714677246773467744677546776467774677846779467804678146782467834678446785467864678746788467894679046791467924679346794467954679646797467984679946800468014680246803468044680546806468074680846809468104681146812468134681446815468164681746818468194682046821468224682346824468254682646827468284682946830468314683246833468344683546836468374683846839468404684146842468434684446845468464684746848468494685046851468524685346854468554685646857468584685946860468614686246863468644686546866468674686846869468704687146872468734687446875468764687746878468794688046881468824688346884468854688646887468884688946890468914689246893468944689546896468974689846899469004690146902469034690446905469064690746908469094691046911469124691346914469154691646917469184691946920469214692246923469244692546926469274692846929469304693146932469334693446935469364693746938469394694046941469424694346944469454694646947469484694946950469514695246953469544695546956469574695846959469604696146962469634696446965469664696746968469694697046971469724697346974469754697646977469784697946980469814698246983469844698546986469874698846989469904699146992469934699446995469964699746998469994700047001470024700347004470054700647007470084700947010470114701247013470144701547016470174701847019470204702147022470234702447025470264702747028470294703047031470324703347034470354703647037470384703947040470414704247043470444704547046470474704847049470504705147052470534705447055470564705747058470594706047061470624706347064470654706647067470684706947070470714707247073470744707547076470774707847079470804708147082470834708447085470864708747088470894709047091470924709347094470954709647097470984709947100471014710247103471044710547106471074710847109471104711147112471134711447115471164711747118471194712047121471224712347124471254712647127471284712947130471314713247133471344713547136471374713847139471404714147142471434714447145471464714747148471494715047151471524715347154471554715647157471584715947160471614716247163471644716547166471674716847169471704717147172471734717447175471764717747178471794718047181471824718347184471854718647187471884718947190471914719247193471944719547196471974719847199472004720147202472034720447205472064720747208472094721047211472124721347214472154721647217472184721947220472214722247223472244722547226472274722847229472304723147232472334723447235472364723747238472394724047241472424724347244472454724647247472484724947250472514725247253472544725547256472574725847259472604726147262472634726447265472664726747268472694727047271472724727347274472754727647277472784727947280472814728247283472844728547286472874728847289472904729147292472934729447295472964729747298472994730047301473024730347304473054730647307473084730947310473114731247313473144731547316473174731847319473204732147322473234732447325473264732747328473294733047331473324733347334473354733647337473384733947340473414734247343473444734547346473474734847349473504735147352473534735447355473564735747358473594736047361473624736347364473654736647367473684736947370473714737247373473744737547376473774737847379473804738147382473834738447385473864738747388473894739047391473924739347394473954739647397473984739947400474014740247403474044740547406474074740847409474104741147412474134741447415474164741747418474194742047421474224742347424474254742647427474284742947430474314743247433474344743547436474374743847439474404744147442474434744447445474464744747448474494745047451474524745347454474554745647457474584745947460474614746247463474644746547466474674746847469474704747147472474734747447475474764747747478474794748047481474824748347484474854748647487474884748947490474914749247493474944749547496474974749847499475004750147502475034750447505475064750747508475094751047511475124751347514475154751647517475184751947520475214752247523475244752547526475274752847529475304753147532475334753447535475364753747538475394754047541475424754347544475454754647547475484754947550475514755247553475544755547556475574755847559475604756147562475634756447565475664756747568475694757047571475724757347574475754757647577475784757947580475814758247583475844758547586475874758847589475904759147592475934759447595475964759747598475994760047601476024760347604476054760647607476084760947610476114761247613476144761547616476174761847619476204762147622476234762447625476264762747628476294763047631476324763347634476354763647637476384763947640476414764247643476444764547646476474764847649476504765147652476534765447655476564765747658476594766047661476624766347664476654766647667476684766947670476714767247673476744767547676476774767847679476804768147682476834768447685476864768747688476894769047691476924769347694476954769647697476984769947700477014770247703477044770547706477074770847709477104771147712477134771447715477164771747718477194772047721477224772347724477254772647727477284772947730477314773247733477344773547736477374773847739477404774147742477434774447745477464774747748477494775047751477524775347754477554775647757477584775947760477614776247763477644776547766477674776847769477704777147772477734777447775477764777747778477794778047781477824778347784477854778647787477884778947790477914779247793477944779547796477974779847799478004780147802478034780447805478064780747808478094781047811478124781347814478154781647817478184781947820478214782247823478244782547826478274782847829478304783147832478334783447835478364783747838478394784047841478424784347844478454784647847478484784947850478514785247853478544785547856478574785847859478604786147862478634786447865478664786747868478694787047871478724787347874478754787647877478784787947880478814788247883478844788547886478874788847889478904789147892478934789447895478964789747898478994790047901479024790347904479054790647907479084790947910479114791247913479144791547916479174791847919479204792147922479234792447925479264792747928479294793047931479324793347934479354793647937479384793947940479414794247943479444794547946479474794847949479504795147952479534795447955479564795747958479594796047961479624796347964479654796647967479684796947970479714797247973479744797547976479774797847979479804798147982479834798447985479864798747988479894799047991479924799347994479954799647997479984799948000480014800248003480044800548006480074800848009480104801148012480134801448015480164801748018480194802048021480224802348024480254802648027480284802948030480314803248033480344803548036480374803848039480404804148042480434804448045480464804748048480494805048051480524805348054480554805648057480584805948060480614806248063480644806548066480674806848069480704807148072480734807448075480764807748078480794808048081480824808348084480854808648087480884808948090480914809248093480944809548096480974809848099481004810148102481034810448105481064810748108481094811048111481124811348114481154811648117481184811948120481214812248123481244812548126481274812848129481304813148132481334813448135481364813748138481394814048141481424814348144481454814648147481484814948150481514815248153481544815548156481574815848159481604816148162481634816448165481664816748168481694817048171481724817348174481754817648177481784817948180481814818248183481844818548186481874818848189481904819148192481934819448195481964819748198481994820048201482024820348204482054820648207482084820948210482114821248213482144821548216482174821848219482204822148222482234822448225482264822748228482294823048231482324823348234482354823648237482384823948240482414824248243482444824548246482474824848249482504825148252482534825448255482564825748258482594826048261482624826348264482654826648267482684826948270482714827248273482744827548276482774827848279482804828148282482834828448285482864828748288482894829048291482924829348294482954829648297482984829948300483014830248303483044830548306483074830848309483104831148312483134831448315483164831748318483194832048321483224832348324483254832648327483284832948330483314833248333483344833548336483374833848339483404834148342483434834448345483464834748348483494835048351483524835348354483554835648357483584835948360483614836248363483644836548366483674836848369483704837148372483734837448375483764837748378483794838048381483824838348384483854838648387483884838948390483914839248393483944839548396483974839848399484004840148402484034840448405484064840748408484094841048411484124841348414484154841648417484184841948420484214842248423484244842548426484274842848429484304843148432484334843448435484364843748438484394844048441484424844348444484454844648447484484844948450484514845248453484544845548456484574845848459484604846148462484634846448465484664846748468484694847048471484724847348474484754847648477484784847948480484814848248483484844848548486484874848848489484904849148492484934849448495484964849748498484994850048501485024850348504485054850648507485084850948510485114851248513485144851548516485174851848519485204852148522485234852448525485264852748528485294853048531485324853348534485354853648537485384853948540485414854248543485444854548546485474854848549485504855148552485534855448555485564855748558485594856048561485624856348564485654856648567485684856948570485714857248573485744857548576485774857848579485804858148582485834858448585485864858748588485894859048591485924859348594485954859648597485984859948600486014860248603486044860548606486074860848609486104861148612486134861448615486164861748618486194862048621486224862348624486254862648627486284862948630486314863248633486344863548636486374863848639486404864148642486434864448645486464864748648486494865048651486524865348654486554865648657486584865948660486614866248663486644866548666486674866848669486704867148672486734867448675486764867748678486794868048681486824868348684486854868648687486884868948690486914869248693486944869548696486974869848699487004870148702487034870448705487064870748708487094871048711487124871348714487154871648717487184871948720487214872248723487244872548726487274872848729487304873148732487334873448735487364873748738487394874048741487424874348744487454874648747487484874948750487514875248753487544875548756487574875848759487604876148762487634876448765487664876748768487694877048771487724877348774487754877648777487784877948780487814878248783487844878548786487874878848789487904879148792487934879448795487964879748798487994880048801488024880348804488054880648807488084880948810488114881248813488144881548816488174881848819488204882148822488234882448825488264882748828488294883048831488324883348834488354883648837488384883948840488414884248843488444884548846488474884848849488504885148852488534885448855488564885748858488594886048861488624886348864488654886648867488684886948870488714887248873488744887548876488774887848879488804888148882488834888448885488864888748888488894889048891488924889348894488954889648897488984889948900489014890248903489044890548906489074890848909489104891148912489134891448915489164891748918489194892048921489224892348924489254892648927489284892948930489314893248933489344893548936489374893848939489404894148942489434894448945489464894748948489494895048951489524895348954489554895648957489584895948960489614896248963489644896548966489674896848969489704897148972489734897448975489764897748978489794898048981489824898348984489854898648987489884898948990489914899248993489944899548996489974899848999490004900149002490034900449005490064900749008490094901049011490124901349014490154901649017490184901949020490214902249023490244902549026490274902849029490304903149032490334903449035490364903749038490394904049041490424904349044490454904649047490484904949050490514905249053490544905549056490574905849059490604906149062490634906449065490664906749068490694907049071490724907349074490754907649077490784907949080490814908249083490844908549086490874908849089490904909149092490934909449095490964909749098490994910049101491024910349104491054910649107491084910949110491114911249113491144911549116491174911849119491204912149122491234912449125491264912749128491294913049131491324913349134491354913649137491384913949140491414914249143491444914549146491474914849149491504915149152491534915449155491564915749158491594916049161491624916349164491654916649167491684916949170491714917249173491744917549176491774917849179491804918149182491834918449185491864918749188491894919049191491924919349194491954919649197491984919949200492014920249203492044920549206492074920849209492104921149212492134921449215492164921749218492194922049221492224922349224492254922649227492284922949230492314923249233492344923549236492374923849239492404924149242492434924449245492464924749248492494925049251492524925349254492554925649257492584925949260492614926249263492644926549266492674926849269492704927149272492734927449275492764927749278492794928049281492824928349284492854928649287492884928949290492914929249293492944929549296492974929849299493004930149302493034930449305493064930749308493094931049311493124931349314493154931649317493184931949320493214932249323493244932549326493274932849329493304933149332493334933449335493364933749338493394934049341493424934349344493454934649347493484934949350493514935249353493544935549356493574935849359493604936149362493634936449365493664936749368493694937049371493724937349374493754937649377493784937949380493814938249383493844938549386493874938849389493904939149392493934939449395493964939749398493994940049401494024940349404494054940649407494084940949410494114941249413494144941549416494174941849419494204942149422494234942449425494264942749428494294943049431494324943349434494354943649437494384943949440494414944249443494444944549446494474944849449494504945149452494534945449455494564945749458494594946049461494624946349464494654946649467494684946949470494714947249473494744947549476494774947849479494804948149482494834948449485494864948749488494894949049491494924949349494494954949649497494984949949500495014950249503495044950549506495074950849509495104951149512495134951449515495164951749518495194952049521495224952349524495254952649527495284952949530495314953249533495344953549536495374953849539495404954149542495434954449545495464954749548495494955049551495524955349554495554955649557495584955949560495614956249563495644956549566495674956849569495704957149572495734957449575495764957749578495794958049581495824958349584495854958649587495884958949590495914959249593495944959549596495974959849599496004960149602496034960449605496064960749608496094961049611496124961349614496154961649617496184961949620496214962249623496244962549626496274962849629496304963149632496334963449635496364963749638496394964049641496424964349644496454964649647496484964949650496514965249653496544965549656496574965849659496604966149662496634966449665496664966749668496694967049671496724967349674496754967649677496784967949680496814968249683496844968549686496874968849689496904969149692496934969449695496964969749698496994970049701497024970349704497054970649707497084970949710497114971249713497144971549716497174971849719497204972149722497234972449725497264972749728497294973049731497324973349734497354973649737497384973949740497414974249743497444974549746497474974849749497504975149752497534975449755497564975749758497594976049761497624976349764497654976649767497684976949770497714977249773497744977549776497774977849779497804978149782497834978449785497864978749788497894979049791497924979349794497954979649797497984979949800498014980249803498044980549806498074980849809498104981149812498134981449815498164981749818498194982049821498224982349824498254982649827498284982949830498314983249833498344983549836498374983849839498404984149842498434984449845498464984749848498494985049851498524985349854498554985649857498584985949860498614986249863498644986549866498674986849869498704987149872498734987449875498764987749878498794988049881498824988349884498854988649887498884988949890498914989249893498944989549896498974989849899499004990149902499034990449905499064990749908499094991049911499124991349914499154991649917499184991949920499214992249923499244992549926499274992849929499304993149932499334993449935499364993749938499394994049941499424994349944499454994649947499484994949950499514995249953499544995549956499574995849959499604996149962499634996449965499664996749968499694997049971499724997349974499754997649977499784997949980499814998249983499844998549986499874998849989499904999149992499934999449995499964999749998499995000050001500025000350004500055000650007500085000950010500115001250013500145001550016500175001850019500205002150022500235002450025500265002750028500295003050031500325003350034500355003650037500385003950040500415004250043500445004550046500475004850049500505005150052500535005450055500565005750058500595006050061500625006350064500655006650067500685006950070500715007250073500745007550076500775007850079500805008150082500835008450085500865008750088500895009050091500925009350094500955009650097500985009950100501015010250103501045010550106501075010850109501105011150112501135011450115501165011750118501195012050121501225012350124501255012650127501285012950130501315013250133501345013550136501375013850139501405014150142501435014450145501465014750148501495015050151501525015350154501555015650157501585015950160501615016250163501645016550166501675016850169501705017150172501735017450175501765017750178501795018050181501825018350184501855018650187501885018950190501915019250193501945019550196501975019850199502005020150202502035020450205502065020750208502095021050211502125021350214502155021650217502185021950220502215022250223502245022550226502275022850229502305023150232502335023450235502365023750238502395024050241502425024350244502455024650247502485024950250502515025250253502545025550256502575025850259502605026150262502635026450265502665026750268502695027050271502725027350274502755027650277502785027950280502815028250283502845028550286502875028850289502905029150292502935029450295502965029750298502995030050301503025030350304503055030650307503085030950310503115031250313503145031550316503175031850319503205032150322503235032450325503265032750328503295033050331503325033350334503355033650337503385033950340503415034250343503445034550346503475034850349503505035150352503535035450355503565035750358503595036050361503625036350364503655036650367503685036950370503715037250373503745037550376503775037850379503805038150382503835038450385503865038750388503895039050391503925039350394503955039650397503985039950400504015040250403504045040550406504075040850409504105041150412504135041450415504165041750418504195042050421504225042350424504255042650427504285042950430504315043250433504345043550436504375043850439504405044150442504435044450445504465044750448504495045050451504525045350454504555045650457504585045950460504615046250463504645046550466504675046850469504705047150472504735047450475504765047750478504795048050481504825048350484504855048650487504885048950490504915049250493504945049550496504975049850499505005050150502505035050450505505065050750508505095051050511505125051350514505155051650517505185051950520505215052250523505245052550526505275052850529505305053150532505335053450535505365053750538505395054050541505425054350544505455054650547505485054950550505515055250553505545055550556505575055850559505605056150562505635056450565505665056750568505695057050571505725057350574505755057650577505785057950580505815058250583505845058550586505875058850589505905059150592505935059450595505965059750598505995060050601506025060350604506055060650607506085060950610506115061250613506145061550616506175061850619506205062150622506235062450625506265062750628506295063050631506325063350634506355063650637506385063950640506415064250643506445064550646506475064850649506505065150652506535065450655506565065750658506595066050661506625066350664506655066650667506685066950670506715067250673506745067550676506775067850679506805068150682506835068450685506865068750688506895069050691506925069350694506955069650697506985069950700507015070250703507045070550706507075070850709507105071150712507135071450715507165071750718507195072050721507225072350724507255072650727507285072950730507315073250733507345073550736507375073850739507405074150742507435074450745507465074750748507495075050751507525075350754507555075650757507585075950760507615076250763507645076550766507675076850769507705077150772507735077450775507765077750778507795078050781507825078350784507855078650787507885078950790507915079250793507945079550796507975079850799508005080150802508035080450805508065080750808508095081050811508125081350814508155081650817508185081950820508215082250823508245082550826508275082850829508305083150832508335083450835508365083750838508395084050841508425084350844508455084650847508485084950850508515085250853508545085550856508575085850859508605086150862508635086450865508665086750868508695087050871508725087350874508755087650877508785087950880508815088250883508845088550886508875088850889508905089150892508935089450895508965089750898508995090050901509025090350904509055090650907509085090950910509115091250913509145091550916509175091850919509205092150922509235092450925509265092750928509295093050931509325093350934509355093650937509385093950940509415094250943509445094550946509475094850949509505095150952509535095450955509565095750958509595096050961509625096350964509655096650967509685096950970509715097250973509745097550976509775097850979509805098150982509835098450985509865098750988509895099050991509925099350994509955099650997509985099951000510015100251003510045100551006510075100851009510105101151012510135101451015510165101751018510195102051021510225102351024510255102651027510285102951030510315103251033510345103551036510375103851039510405104151042510435104451045510465104751048510495105051051510525105351054510555105651057510585105951060510615106251063510645106551066510675106851069510705107151072510735107451075510765107751078510795108051081510825108351084510855108651087510885108951090510915109251093510945109551096510975109851099511005110151102511035110451105511065110751108511095111051111511125111351114511155111651117511185111951120511215112251123511245112551126511275112851129511305113151132511335113451135511365113751138511395114051141511425114351144511455114651147511485114951150511515115251153511545115551156511575115851159511605116151162511635116451165511665116751168511695117051171511725117351174511755117651177511785117951180511815118251183511845118551186511875118851189511905119151192511935119451195511965119751198511995120051201512025120351204512055120651207512085120951210512115121251213512145121551216512175121851219512205122151222512235122451225512265122751228512295123051231512325123351234512355123651237512385123951240512415124251243512445124551246512475124851249512505125151252512535125451255512565125751258512595126051261512625126351264512655126651267512685126951270512715127251273512745127551276512775127851279512805128151282512835128451285512865128751288512895129051291512925129351294512955129651297512985129951300513015130251303513045130551306513075130851309513105131151312513135131451315513165131751318513195132051321513225132351324513255132651327513285132951330513315133251333513345133551336513375133851339513405134151342513435134451345513465134751348513495135051351513525135351354513555135651357513585135951360513615136251363513645136551366513675136851369513705137151372513735137451375513765137751378513795138051381513825138351384513855138651387513885138951390513915139251393513945139551396513975139851399514005140151402514035140451405514065140751408514095141051411514125141351414514155141651417514185141951420514215142251423514245142551426514275142851429514305143151432514335143451435514365143751438514395144051441514425144351444514455144651447514485144951450514515145251453514545145551456514575145851459514605146151462514635146451465514665146751468514695147051471514725147351474514755147651477514785147951480514815148251483514845148551486514875148851489514905149151492514935149451495514965149751498514995150051501515025150351504515055150651507515085150951510515115151251513515145151551516515175151851519515205152151522515235152451525515265152751528515295153051531515325153351534515355153651537515385153951540515415154251543515445154551546515475154851549515505155151552515535155451555515565155751558515595156051561515625156351564515655156651567515685156951570515715157251573515745157551576515775157851579515805158151582515835158451585515865158751588515895159051591515925159351594515955159651597515985159951600516015160251603516045160551606516075160851609516105161151612516135161451615516165161751618516195162051621516225162351624516255162651627516285162951630516315163251633516345163551636516375163851639516405164151642516435164451645516465164751648516495165051651516525165351654516555165651657516585165951660516615166251663516645166551666516675166851669516705167151672516735167451675516765167751678516795168051681516825168351684516855168651687516885168951690516915169251693516945169551696516975169851699517005170151702517035170451705517065170751708517095171051711517125171351714517155171651717517185171951720517215172251723517245172551726517275172851729517305173151732517335173451735517365173751738517395174051741517425174351744517455174651747517485174951750517515175251753517545175551756517575175851759517605176151762517635176451765517665176751768517695177051771517725177351774517755177651777517785177951780517815178251783517845178551786517875178851789517905179151792517935179451795517965179751798517995180051801518025180351804518055180651807518085180951810518115181251813518145181551816518175181851819518205182151822518235182451825518265182751828518295183051831518325183351834518355183651837518385183951840518415184251843518445184551846518475184851849518505185151852518535185451855518565185751858518595186051861518625186351864518655186651867518685186951870518715187251873518745187551876518775187851879518805188151882518835188451885518865188751888518895189051891518925189351894518955189651897518985189951900519015190251903519045190551906519075190851909519105191151912519135191451915519165191751918519195192051921519225192351924519255192651927519285192951930519315193251933519345193551936519375193851939519405194151942519435194451945519465194751948519495195051951519525195351954519555195651957519585195951960519615196251963519645196551966519675196851969519705197151972519735197451975519765197751978519795198051981519825198351984519855198651987519885198951990519915199251993519945199551996519975199851999520005200152002520035200452005520065200752008520095201052011520125201352014520155201652017520185201952020520215202252023520245202552026520275202852029520305203152032520335203452035520365203752038520395204052041520425204352044520455204652047520485204952050520515205252053520545205552056520575205852059520605206152062520635206452065520665206752068520695207052071520725207352074520755207652077520785207952080520815208252083520845208552086520875208852089520905209152092520935209452095520965209752098520995210052101521025210352104521055210652107521085210952110521115211252113521145211552116521175211852119521205212152122521235212452125521265212752128521295213052131521325213352134521355213652137521385213952140521415214252143521445214552146521475214852149521505215152152521535215452155521565215752158521595216052161521625216352164521655216652167521685216952170521715217252173521745217552176521775217852179521805218152182521835218452185521865218752188521895219052191521925219352194521955219652197521985219952200522015220252203522045220552206522075220852209522105221152212522135221452215522165221752218522195222052221522225222352224522255222652227522285222952230522315223252233522345223552236522375223852239522405224152242522435224452245522465224752248522495225052251522525225352254522555225652257522585225952260522615226252263522645226552266522675226852269522705227152272522735227452275522765227752278522795228052281522825228352284522855228652287522885228952290522915229252293522945229552296522975229852299523005230152302523035230452305523065230752308523095231052311523125231352314523155231652317523185231952320523215232252323523245232552326523275232852329523305233152332523335233452335523365233752338523395234052341523425234352344523455234652347523485234952350523515235252353523545235552356523575235852359523605236152362523635236452365523665236752368523695237052371523725237352374523755237652377523785237952380523815238252383523845238552386523875238852389523905239152392523935239452395523965239752398523995240052401524025240352404524055240652407524085240952410524115241252413524145241552416524175241852419524205242152422524235242452425524265242752428524295243052431524325243352434524355243652437524385243952440524415244252443524445244552446524475244852449524505245152452524535245452455524565245752458524595246052461524625246352464524655246652467524685246952470524715247252473524745247552476524775247852479524805248152482524835248452485524865248752488524895249052491524925249352494524955249652497524985249952500525015250252503525045250552506525075250852509525105251152512525135251452515525165251752518525195252052521525225252352524525255252652527525285252952530525315253252533525345253552536525375253852539525405254152542525435254452545525465254752548525495255052551525525255352554525555255652557525585255952560525615256252563525645256552566525675256852569525705257152572525735257452575525765257752578525795258052581525825258352584525855258652587525885258952590525915259252593525945259552596525975259852599526005260152602526035260452605526065260752608526095261052611526125261352614526155261652617526185261952620526215262252623526245262552626526275262852629526305263152632526335263452635526365263752638526395264052641526425264352644526455264652647526485264952650526515265252653526545265552656526575265852659526605266152662526635266452665526665266752668526695267052671526725267352674526755267652677526785267952680526815268252683526845268552686526875268852689526905269152692526935269452695526965269752698526995270052701527025270352704527055270652707527085270952710527115271252713527145271552716527175271852719527205272152722527235272452725527265272752728527295273052731527325273352734527355273652737527385273952740527415274252743527445274552746527475274852749527505275152752527535275452755527565275752758527595276052761527625276352764527655276652767527685276952770527715277252773527745277552776527775277852779527805278152782527835278452785527865278752788527895279052791527925279352794527955279652797527985279952800528015280252803528045280552806528075280852809528105281152812528135281452815528165281752818528195282052821528225282352824528255282652827528285282952830528315283252833528345283552836528375283852839528405284152842528435284452845528465284752848528495285052851528525285352854528555285652857528585285952860528615286252863528645286552866528675286852869528705287152872528735287452875528765287752878528795288052881528825288352884528855288652887528885288952890528915289252893528945289552896528975289852899529005290152902529035290452905529065290752908529095291052911529125291352914529155291652917529185291952920529215292252923529245292552926529275292852929529305293152932529335293452935529365293752938529395294052941529425294352944529455294652947529485294952950529515295252953529545295552956529575295852959529605296152962529635296452965529665296752968529695297052971529725297352974529755297652977529785297952980529815298252983529845298552986529875298852989529905299152992529935299452995529965299752998529995300053001530025300353004530055300653007530085300953010530115301253013530145301553016530175301853019530205302153022530235302453025530265302753028530295303053031530325303353034530355303653037530385303953040530415304253043530445304553046530475304853049530505305153052530535305453055530565305753058530595306053061530625306353064530655306653067530685306953070530715307253073530745307553076530775307853079530805308153082530835308453085530865308753088530895309053091530925309353094530955309653097530985309953100531015310253103531045310553106531075310853109531105311153112531135311453115531165311753118531195312053121531225312353124531255312653127531285312953130531315313253133531345313553136531375313853139531405314153142531435314453145531465314753148531495315053151531525315353154531555315653157531585315953160531615316253163531645316553166531675316853169531705317153172531735317453175531765317753178531795318053181531825318353184531855318653187531885318953190531915319253193531945319553196531975319853199532005320153202532035320453205532065320753208532095321053211532125321353214532155321653217532185321953220532215322253223532245322553226532275322853229532305323153232532335323453235532365323753238532395324053241532425324353244532455324653247532485324953250532515325253253532545325553256532575325853259532605326153262532635326453265532665326753268532695327053271532725327353274532755327653277532785327953280532815328253283532845328553286532875328853289532905329153292532935329453295532965329753298532995330053301533025330353304533055330653307533085330953310533115331253313533145331553316533175331853319533205332153322533235332453325533265332753328533295333053331533325333353334533355333653337533385333953340533415334253343533445334553346533475334853349533505335153352533535335453355533565335753358533595336053361533625336353364533655336653367533685336953370533715337253373533745337553376533775337853379533805338153382533835338453385533865338753388533895339053391533925339353394533955339653397533985339953400534015340253403534045340553406534075340853409534105341153412534135341453415534165341753418534195342053421534225342353424534255342653427534285342953430534315343253433534345343553436534375343853439534405344153442534435344453445534465344753448534495345053451534525345353454534555345653457534585345953460534615346253463534645346553466534675346853469534705347153472534735347453475534765347753478534795348053481534825348353484534855348653487534885348953490534915349253493534945349553496534975349853499535005350153502535035350453505535065350753508535095351053511535125351353514535155351653517535185351953520535215352253523535245352553526535275352853529535305353153532535335353453535535365353753538535395354053541535425354353544535455354653547535485354953550535515355253553535545355553556535575355853559535605356153562535635356453565535665356753568535695357053571535725357353574535755357653577535785357953580535815358253583535845358553586535875358853589535905359153592535935359453595535965359753598535995360053601536025360353604536055360653607536085360953610536115361253613536145361553616536175361853619536205362153622536235362453625536265362753628536295363053631536325363353634536355363653637536385363953640536415364253643536445364553646536475364853649536505365153652536535365453655536565365753658536595366053661536625366353664536655366653667536685366953670536715367253673536745367553676536775367853679536805368153682536835368453685536865368753688536895369053691536925369353694536955369653697536985369953700537015370253703537045370553706537075370853709537105371153712537135371453715537165371753718537195372053721537225372353724537255372653727537285372953730537315373253733537345373553736537375373853739537405374153742537435374453745537465374753748537495375053751537525375353754537555375653757537585375953760537615376253763537645376553766537675376853769537705377153772537735377453775537765377753778537795378053781537825378353784537855378653787537885378953790537915379253793537945379553796537975379853799538005380153802538035380453805538065380753808538095381053811538125381353814538155381653817538185381953820538215382253823538245382553826538275382853829538305383153832538335383453835538365383753838538395384053841538425384353844538455384653847538485384953850538515385253853538545385553856538575385853859538605386153862538635386453865538665386753868538695387053871538725387353874538755387653877538785387953880538815388253883538845388553886538875388853889538905389153892538935389453895538965389753898538995390053901539025390353904539055390653907539085390953910539115391253913539145391553916539175391853919539205392153922539235392453925539265392753928539295393053931539325393353934539355393653937539385393953940539415394253943539445394553946539475394853949539505395153952539535395453955539565395753958539595396053961539625396353964539655396653967539685396953970539715397253973539745397553976539775397853979539805398153982539835398453985539865398753988539895399053991539925399353994539955399653997539985399954000540015400254003540045400554006540075400854009540105401154012540135401454015540165401754018540195402054021540225402354024540255402654027540285402954030540315403254033540345403554036540375403854039540405404154042540435404454045540465404754048540495405054051540525405354054540555405654057540585405954060540615406254063540645406554066540675406854069540705407154072540735407454075540765407754078540795408054081540825408354084540855408654087540885408954090540915409254093540945409554096540975409854099541005410154102541035410454105541065410754108541095411054111541125411354114541155411654117541185411954120541215412254123541245412554126541275412854129541305413154132541335413454135541365413754138541395414054141541425414354144541455414654147541485414954150541515415254153541545415554156541575415854159541605416154162541635416454165541665416754168541695417054171541725417354174541755417654177541785417954180541815418254183541845418554186541875418854189541905419154192541935419454195541965419754198541995420054201542025420354204542055420654207542085420954210542115421254213542145421554216542175421854219542205422154222542235422454225542265422754228542295423054231542325423354234542355423654237542385423954240542415424254243542445424554246542475424854249542505425154252542535425454255542565425754258542595426054261542625426354264542655426654267542685426954270542715427254273542745427554276542775427854279542805428154282542835428454285542865428754288542895429054291542925429354294542955429654297542985429954300543015430254303543045430554306543075430854309543105431154312543135431454315543165431754318543195432054321543225432354324543255432654327543285432954330543315433254333543345433554336543375433854339543405434154342543435434454345543465434754348543495435054351543525435354354543555435654357543585435954360543615436254363543645436554366543675436854369543705437154372543735437454375543765437754378543795438054381543825438354384543855438654387543885438954390543915439254393543945439554396543975439854399544005440154402544035440454405544065440754408544095441054411544125441354414544155441654417544185441954420544215442254423544245442554426544275442854429544305443154432544335443454435544365443754438544395444054441544425444354444544455444654447544485444954450544515445254453544545445554456544575445854459544605446154462544635446454465544665446754468544695447054471544725447354474544755447654477544785447954480544815448254483544845448554486544875448854489544905449154492544935449454495544965449754498544995450054501545025450354504545055450654507545085450954510545115451254513545145451554516545175451854519545205452154522545235452454525545265452754528545295453054531545325453354534545355453654537545385453954540545415454254543545445454554546545475454854549545505455154552545535455454555545565455754558545595456054561545625456354564545655456654567545685456954570545715457254573545745457554576545775457854579545805458154582545835458454585545865458754588545895459054591545925459354594545955459654597545985459954600546015460254603546045460554606546075460854609546105461154612546135461454615546165461754618546195462054621546225462354624546255462654627546285462954630546315463254633546345463554636546375463854639546405464154642546435464454645546465464754648546495465054651546525465354654546555465654657546585465954660546615466254663546645466554666546675466854669546705467154672546735467454675546765467754678546795468054681546825468354684546855468654687546885468954690546915469254693546945469554696546975469854699547005470154702547035470454705547065470754708547095471054711547125471354714547155471654717547185471954720547215472254723547245472554726547275472854729547305473154732547335473454735547365473754738547395474054741547425474354744547455474654747547485474954750547515475254753547545475554756547575475854759547605476154762547635476454765547665476754768547695477054771547725477354774547755477654777547785477954780547815478254783547845478554786547875478854789547905479154792547935479454795547965479754798547995480054801548025480354804548055480654807548085480954810548115481254813548145481554816548175481854819548205482154822548235482454825548265482754828548295483054831548325483354834548355483654837548385483954840548415484254843548445484554846548475484854849548505485154852548535485454855548565485754858548595486054861548625486354864548655486654867548685486954870548715487254873548745487554876548775487854879548805488154882548835488454885548865488754888548895489054891548925489354894548955489654897548985489954900549015490254903549045490554906549075490854909549105491154912549135491454915549165491754918549195492054921549225492354924549255492654927549285492954930549315493254933549345493554936549375493854939549405494154942549435494454945549465494754948549495495054951549525495354954549555495654957549585495954960549615496254963549645496554966549675496854969549705497154972549735497454975549765497754978549795498054981549825498354984549855498654987549885498954990549915499254993549945499554996549975499854999550005500155002550035500455005550065500755008550095501055011550125501355014550155501655017550185501955020550215502255023550245502555026550275502855029550305503155032550335503455035550365503755038550395504055041550425504355044550455504655047550485504955050550515505255053550545505555056550575505855059550605506155062550635506455065550665506755068550695507055071550725507355074550755507655077550785507955080550815508255083550845508555086550875508855089550905509155092550935509455095550965509755098550995510055101551025510355104551055510655107551085510955110551115511255113551145511555116551175511855119551205512155122551235512455125551265512755128551295513055131551325513355134551355513655137551385513955140551415514255143551445514555146551475514855149551505515155152551535515455155551565515755158551595516055161551625516355164551655516655167551685516955170551715517255173551745517555176551775517855179551805518155182551835518455185551865518755188551895519055191551925519355194551955519655197551985519955200552015520255203552045520555206552075520855209552105521155212552135521455215552165521755218552195522055221552225522355224552255522655227552285522955230552315523255233552345523555236552375523855239552405524155242552435524455245552465524755248552495525055251552525525355254552555525655257552585525955260552615526255263552645526555266552675526855269552705527155272552735527455275552765527755278552795528055281552825528355284552855528655287552885528955290552915529255293552945529555296552975529855299553005530155302553035530455305553065530755308553095531055311553125531355314553155531655317553185531955320553215532255323553245532555326553275532855329553305533155332553335533455335553365533755338553395534055341553425534355344553455534655347553485534955350553515535255353553545535555356553575535855359553605536155362553635536455365553665536755368553695537055371553725537355374553755537655377553785537955380553815538255383553845538555386553875538855389553905539155392553935539455395553965539755398553995540055401554025540355404554055540655407554085540955410554115541255413554145541555416554175541855419554205542155422554235542455425554265542755428554295543055431554325543355434554355543655437554385543955440554415544255443554445544555446554475544855449554505545155452554535545455455554565545755458554595546055461554625546355464554655546655467554685546955470554715547255473554745547555476554775547855479554805548155482554835548455485554865548755488554895549055491554925549355494554955549655497554985549955500555015550255503555045550555506555075550855509555105551155512555135551455515555165551755518555195552055521555225552355524555255552655527555285552955530555315553255533555345553555536555375553855539555405554155542555435554455545555465554755548555495555055551555525555355554555555555655557555585555955560555615556255563555645556555566555675556855569555705557155572555735557455575555765557755578555795558055581555825558355584555855558655587555885558955590555915559255593555945559555596555975559855599556005560155602556035560455605556065560755608556095561055611556125561355614556155561655617556185561955620556215562255623556245562555626556275562855629556305563155632556335563455635556365563755638556395564055641556425564355644556455564655647556485564955650556515565255653556545565555656556575565855659556605566155662556635566455665556665566755668556695567055671556725567355674556755567655677556785567955680556815568255683556845568555686556875568855689556905569155692556935569455695556965569755698556995570055701557025570355704557055570655707557085570955710557115571255713557145571555716557175571855719557205572155722557235572455725557265572755728557295573055731557325573355734557355573655737557385573955740557415574255743557445574555746557475574855749557505575155752557535575455755557565575755758557595576055761557625576355764557655576655767557685576955770557715577255773557745577555776557775577855779557805578155782557835578455785557865578755788557895579055791557925579355794557955579655797557985579955800558015580255803558045580555806558075580855809558105581155812558135581455815558165581755818558195582055821558225582355824558255582655827558285582955830558315583255833558345583555836558375583855839558405584155842558435584455845558465584755848558495585055851558525585355854558555585655857558585585955860558615586255863558645586555866558675586855869558705587155872558735587455875558765587755878558795588055881558825588355884558855588655887558885588955890558915589255893558945589555896558975589855899559005590155902559035590455905559065590755908559095591055911559125591355914559155591655917559185591955920559215592255923559245592555926559275592855929559305593155932559335593455935559365593755938559395594055941559425594355944559455594655947559485594955950559515595255953559545595555956559575595855959559605596155962559635596455965559665596755968559695597055971559725597355974559755597655977559785597955980559815598255983559845598555986559875598855989559905599155992559935599455995559965599755998559995600056001560025600356004560055600656007560085600956010560115601256013560145601556016560175601856019560205602156022560235602456025560265602756028560295603056031560325603356034560355603656037560385603956040560415604256043560445604556046560475604856049560505605156052560535605456055560565605756058560595606056061560625606356064560655606656067560685606956070560715607256073560745607556076560775607856079560805608156082560835608456085560865608756088560895609056091560925609356094560955609656097560985609956100561015610256103561045610556106561075610856109561105611156112561135611456115561165611756118561195612056121561225612356124561255612656127561285612956130561315613256133561345613556136561375613856139561405614156142561435614456145561465614756148561495615056151561525615356154561555615656157561585615956160561615616256163561645616556166561675616856169561705617156172561735617456175561765617756178561795618056181561825618356184561855618656187561885618956190561915619256193561945619556196561975619856199562005620156202562035620456205562065620756208562095621056211562125621356214562155621656217562185621956220562215622256223562245622556226562275622856229562305623156232562335623456235562365623756238562395624056241562425624356244562455624656247562485624956250562515625256253562545625556256562575625856259562605626156262562635626456265562665626756268562695627056271562725627356274562755627656277562785627956280562815628256283562845628556286562875628856289562905629156292562935629456295562965629756298562995630056301563025630356304563055630656307563085630956310563115631256313563145631556316563175631856319563205632156322563235632456325563265632756328563295633056331563325633356334563355633656337563385633956340563415634256343563445634556346563475634856349563505635156352563535635456355563565635756358563595636056361563625636356364563655636656367563685636956370563715637256373563745637556376563775637856379563805638156382563835638456385563865638756388563895639056391563925639356394563955639656397563985639956400564015640256403564045640556406564075640856409564105641156412564135641456415564165641756418564195642056421564225642356424564255642656427564285642956430564315643256433564345643556436564375643856439564405644156442564435644456445564465644756448564495645056451564525645356454564555645656457564585645956460564615646256463564645646556466564675646856469564705647156472564735647456475564765647756478564795648056481564825648356484564855648656487564885648956490564915649256493564945649556496564975649856499565005650156502565035650456505565065650756508565095651056511565125651356514565155651656517565185651956520565215652256523565245652556526565275652856529565305653156532565335653456535565365653756538565395654056541565425654356544565455654656547565485654956550565515655256553565545655556556565575655856559565605656156562565635656456565565665656756568565695657056571565725657356574565755657656577565785657956580565815658256583565845658556586565875658856589565905659156592565935659456595565965659756598565995660056601566025660356604566055660656607566085660956610566115661256613566145661556616566175661856619566205662156622566235662456625566265662756628566295663056631566325663356634566355663656637566385663956640566415664256643566445664556646566475664856649566505665156652566535665456655566565665756658566595666056661566625666356664566655666656667566685666956670566715667256673566745667556676566775667856679566805668156682566835668456685566865668756688566895669056691566925669356694566955669656697566985669956700567015670256703567045670556706567075670856709567105671156712567135671456715567165671756718567195672056721567225672356724567255672656727567285672956730567315673256733567345673556736567375673856739567405674156742567435674456745567465674756748567495675056751567525675356754567555675656757567585675956760567615676256763567645676556766567675676856769567705677156772567735677456775567765677756778567795678056781567825678356784567855678656787567885678956790567915679256793567945679556796567975679856799568005680156802568035680456805568065680756808568095681056811568125681356814568155681656817568185681956820568215682256823568245682556826568275682856829568305683156832568335683456835568365683756838568395684056841568425684356844568455684656847568485684956850568515685256853568545685556856568575685856859568605686156862568635686456865568665686756868568695687056871568725687356874568755687656877568785687956880568815688256883568845688556886568875688856889568905689156892568935689456895568965689756898568995690056901569025690356904569055690656907569085690956910569115691256913569145691556916569175691856919569205692156922569235692456925569265692756928569295693056931569325693356934569355693656937569385693956940569415694256943569445694556946569475694856949569505695156952569535695456955569565695756958569595696056961569625696356964569655696656967569685696956970569715697256973569745697556976569775697856979569805698156982569835698456985569865698756988569895699056991569925699356994569955699656997569985699957000570015700257003570045700557006570075700857009570105701157012570135701457015570165701757018570195702057021570225702357024570255702657027570285702957030570315703257033570345703557036570375703857039570405704157042570435704457045570465704757048570495705057051570525705357054570555705657057570585705957060570615706257063570645706557066570675706857069570705707157072570735707457075570765707757078570795708057081570825708357084570855708657087570885708957090570915709257093570945709557096570975709857099571005710157102571035710457105571065710757108571095711057111571125711357114571155711657117571185711957120571215712257123571245712557126571275712857129571305713157132571335713457135571365713757138571395714057141571425714357144571455714657147571485714957150571515715257153571545715557156571575715857159571605716157162571635716457165571665716757168571695717057171571725717357174571755717657177571785717957180571815718257183571845718557186571875718857189571905719157192571935719457195571965719757198571995720057201572025720357204572055720657207572085720957210572115721257213572145721557216572175721857219572205722157222572235722457225572265722757228572295723057231572325723357234572355723657237572385723957240572415724257243572445724557246572475724857249572505725157252572535725457255572565725757258572595726057261572625726357264572655726657267572685726957270572715727257273572745727557276572775727857279572805728157282572835728457285572865728757288572895729057291572925729357294572955729657297572985729957300573015730257303573045730557306573075730857309573105731157312573135731457315573165731757318573195732057321573225732357324573255732657327573285732957330573315733257333573345733557336573375733857339573405734157342573435734457345573465734757348573495735057351573525735357354573555735657357573585735957360573615736257363573645736557366573675736857369573705737157372573735737457375573765737757378573795738057381573825738357384573855738657387573885738957390573915739257393573945739557396573975739857399574005740157402574035740457405574065740757408574095741057411574125741357414574155741657417574185741957420574215742257423574245742557426574275742857429574305743157432574335743457435574365743757438574395744057441574425744357444574455744657447574485744957450574515745257453574545745557456574575745857459574605746157462574635746457465574665746757468574695747057471574725747357474574755747657477574785747957480574815748257483574845748557486574875748857489574905749157492574935749457495574965749757498574995750057501575025750357504575055750657507575085750957510575115751257513575145751557516575175751857519575205752157522575235752457525575265752757528575295753057531575325753357534575355753657537575385753957540575415754257543575445754557546575475754857549575505755157552575535755457555575565755757558575595756057561575625756357564575655756657567575685756957570575715757257573575745757557576575775757857579575805758157582575835758457585575865758757588575895759057591575925759357594575955759657597575985759957600576015760257603576045760557606576075760857609576105761157612576135761457615576165761757618576195762057621576225762357624576255762657627576285762957630576315763257633576345763557636576375763857639576405764157642576435764457645576465764757648576495765057651576525765357654576555765657657576585765957660576615766257663576645766557666576675766857669576705767157672576735767457675576765767757678576795768057681576825768357684576855768657687576885768957690576915769257693576945769557696576975769857699577005770157702577035770457705577065770757708577095771057711577125771357714577155771657717577185771957720577215772257723577245772557726577275772857729577305773157732577335773457735577365773757738577395774057741577425774357744577455774657747577485774957750577515775257753577545775557756577575775857759577605776157762577635776457765577665776757768577695777057771577725777357774577755777657777577785777957780577815778257783577845778557786577875778857789577905779157792577935779457795577965779757798577995780057801578025780357804578055780657807578085780957810578115781257813578145781557816578175781857819578205782157822578235782457825578265782757828578295783057831578325783357834578355783657837578385783957840578415784257843578445784557846578475784857849578505785157852578535785457855578565785757858578595786057861578625786357864578655786657867578685786957870578715787257873578745787557876578775787857879578805788157882578835788457885578865788757888578895789057891578925789357894578955789657897578985789957900579015790257903579045790557906579075790857909579105791157912579135791457915579165791757918579195792057921579225792357924579255792657927579285792957930579315793257933579345793557936579375793857939579405794157942579435794457945579465794757948579495795057951579525795357954579555795657957579585795957960579615796257963579645796557966579675796857969579705797157972579735797457975579765797757978579795798057981579825798357984579855798657987579885798957990579915799257993579945799557996579975799857999580005800158002580035800458005580065800758008580095801058011580125801358014580155801658017580185801958020580215802258023580245802558026580275802858029580305803158032580335803458035580365803758038580395804058041580425804358044580455804658047580485804958050580515805258053580545805558056580575805858059580605806158062580635806458065580665806758068580695807058071580725807358074580755807658077580785807958080580815808258083580845808558086580875808858089580905809158092580935809458095580965809758098580995810058101581025810358104581055810658107581085810958110581115811258113581145811558116581175811858119581205812158122581235812458125581265812758128581295813058131581325813358134581355813658137581385813958140581415814258143581445814558146581475814858149581505815158152581535815458155581565815758158581595816058161581625816358164581655816658167581685816958170581715817258173581745817558176581775817858179581805818158182581835818458185581865818758188581895819058191581925819358194581955819658197581985819958200582015820258203582045820558206582075820858209582105821158212582135821458215582165821758218582195822058221582225822358224582255822658227582285822958230582315823258233582345823558236582375823858239582405824158242582435824458245582465824758248582495825058251582525825358254582555825658257582585825958260582615826258263582645826558266582675826858269582705827158272582735827458275582765827758278582795828058281582825828358284582855828658287582885828958290582915829258293582945829558296582975829858299583005830158302583035830458305583065830758308583095831058311583125831358314583155831658317583185831958320583215832258323583245832558326583275832858329583305833158332583335833458335583365833758338583395834058341583425834358344583455834658347583485834958350583515835258353583545835558356583575835858359583605836158362583635836458365583665836758368583695837058371583725837358374583755837658377583785837958380583815838258383583845838558386583875838858389583905839158392583935839458395583965839758398583995840058401584025840358404584055840658407584085840958410584115841258413584145841558416584175841858419584205842158422584235842458425584265842758428584295843058431584325843358434584355843658437584385843958440584415844258443584445844558446584475844858449584505845158452584535845458455584565845758458584595846058461584625846358464584655846658467584685846958470584715847258473584745847558476584775847858479584805848158482584835848458485584865848758488584895849058491584925849358494584955849658497584985849958500585015850258503585045850558506585075850858509585105851158512585135851458515585165851758518585195852058521585225852358524585255852658527585285852958530585315853258533585345853558536585375853858539585405854158542585435854458545585465854758548585495855058551585525855358554585555855658557585585855958560585615856258563585645856558566585675856858569585705857158572585735857458575585765857758578585795858058581585825858358584585855858658587585885858958590585915859258593585945859558596585975859858599586005860158602586035860458605586065860758608586095861058611586125861358614586155861658617586185861958620586215862258623586245862558626586275862858629586305863158632586335863458635586365863758638586395864058641586425864358644586455864658647586485864958650586515865258653586545865558656586575865858659586605866158662586635866458665586665866758668586695867058671586725867358674586755867658677586785867958680586815868258683586845868558686586875868858689586905869158692586935869458695586965869758698586995870058701587025870358704587055870658707587085870958710587115871258713587145871558716587175871858719587205872158722587235872458725587265872758728587295873058731587325873358734587355873658737587385873958740587415874258743587445874558746587475874858749587505875158752587535875458755587565875758758587595876058761587625876358764587655876658767587685876958770587715877258773587745877558776587775877858779587805878158782587835878458785587865878758788587895879058791587925879358794587955879658797587985879958800588015880258803588045880558806588075880858809588105881158812588135881458815588165881758818588195882058821588225882358824588255882658827588285882958830588315883258833588345883558836588375883858839588405884158842588435884458845588465884758848588495885058851588525885358854588555885658857588585885958860588615886258863588645886558866588675886858869588705887158872588735887458875588765887758878588795888058881588825888358884588855888658887588885888958890588915889258893588945889558896588975889858899589005890158902589035890458905589065890758908589095891058911589125891358914589155891658917589185891958920589215892258923589245892558926589275892858929589305893158932589335893458935589365893758938589395894058941589425894358944589455894658947589485894958950589515895258953589545895558956589575895858959589605896158962589635896458965589665896758968589695897058971589725897358974589755897658977589785897958980589815898258983589845898558986589875898858989589905899158992589935899458995589965899758998589995900059001590025900359004590055900659007590085900959010590115901259013590145901559016590175901859019590205902159022590235902459025590265902759028590295903059031590325903359034590355903659037590385903959040590415904259043590445904559046590475904859049590505905159052590535905459055590565905759058590595906059061590625906359064590655906659067590685906959070590715907259073590745907559076590775907859079590805908159082590835908459085590865908759088590895909059091590925909359094590955909659097590985909959100591015910259103591045910559106591075910859109591105911159112591135911459115591165911759118591195912059121591225912359124591255912659127591285912959130591315913259133591345913559136591375913859139591405914159142591435914459145591465914759148591495915059151591525915359154591555915659157591585915959160591615916259163591645916559166591675916859169591705917159172591735917459175591765917759178591795918059181591825918359184591855918659187591885918959190591915919259193591945919559196591975919859199592005920159202592035920459205592065920759208592095921059211592125921359214592155921659217592185921959220592215922259223592245922559226592275922859229592305923159232592335923459235592365923759238592395924059241592425924359244592455924659247592485924959250592515925259253592545925559256592575925859259592605926159262592635926459265592665926759268592695927059271592725927359274592755927659277592785927959280592815928259283592845928559286592875928859289592905929159292592935929459295592965929759298592995930059301593025930359304593055930659307593085930959310593115931259313593145931559316593175931859319593205932159322593235932459325593265932759328593295933059331593325933359334593355933659337593385933959340593415934259343593445934559346593475934859349593505935159352593535935459355593565935759358593595936059361593625936359364593655936659367593685936959370593715937259373593745937559376593775937859379593805938159382593835938459385593865938759388593895939059391593925939359394593955939659397593985939959400594015940259403594045940559406594075940859409594105941159412594135941459415594165941759418594195942059421594225942359424594255942659427594285942959430594315943259433594345943559436594375943859439594405944159442594435944459445594465944759448594495945059451594525945359454594555945659457594585945959460594615946259463594645946559466594675946859469594705947159472594735947459475594765947759478594795948059481594825948359484594855948659487594885948959490594915949259493594945949559496594975949859499595005950159502595035950459505595065950759508595095951059511595125951359514595155951659517595185951959520595215952259523595245952559526595275952859529595305953159532595335953459535595365953759538595395954059541595425954359544595455954659547595485954959550595515955259553595545955559556595575955859559595605956159562595635956459565595665956759568595695957059571595725957359574595755957659577595785957959580595815958259583595845958559586595875958859589595905959159592595935959459595595965959759598595995960059601596025960359604596055960659607596085960959610596115961259613596145961559616596175961859619596205962159622596235962459625596265962759628596295963059631596325963359634596355963659637596385963959640596415964259643596445964559646596475964859649596505965159652596535965459655596565965759658596595966059661596625966359664596655966659667596685966959670596715967259673596745967559676596775967859679596805968159682596835968459685596865968759688596895969059691596925969359694596955969659697596985969959700597015970259703597045970559706597075970859709597105971159712597135971459715597165971759718597195972059721597225972359724597255972659727597285972959730597315973259733597345973559736597375973859739597405974159742597435974459745597465974759748597495975059751597525975359754597555975659757597585975959760597615976259763597645976559766597675976859769597705977159772597735977459775597765977759778597795978059781597825978359784597855978659787597885978959790597915979259793597945979559796597975979859799598005980159802598035980459805598065980759808598095981059811598125981359814598155981659817598185981959820598215982259823598245982559826598275982859829598305983159832598335983459835598365983759838598395984059841598425984359844598455984659847598485984959850598515985259853598545985559856598575985859859598605986159862598635986459865598665986759868598695987059871598725987359874598755987659877598785987959880598815988259883598845988559886598875988859889598905989159892598935989459895598965989759898598995990059901599025990359904599055990659907599085990959910599115991259913599145991559916599175991859919599205992159922599235992459925599265992759928599295993059931599325993359934599355993659937599385993959940599415994259943599445994559946599475994859949599505995159952599535995459955599565995759958599595996059961599625996359964599655996659967599685996959970599715997259973599745997559976599775997859979599805998159982599835998459985599865998759988599895999059991599925999359994599955999659997599985999960000600016000260003600046000560006600076000860009600106001160012600136001460015600166001760018600196002060021600226002360024600256002660027600286002960030600316003260033600346003560036600376003860039600406004160042600436004460045600466004760048600496005060051600526005360054600556005660057600586005960060600616006260063600646006560066600676006860069600706007160072600736007460075600766007760078600796008060081600826008360084600856008660087600886008960090600916009260093600946009560096600976009860099601006010160102601036010460105601066010760108601096011060111601126011360114601156011660117601186011960120601216012260123601246012560126601276012860129601306013160132601336013460135601366013760138601396014060141601426014360144601456014660147601486014960150601516015260153601546015560156601576015860159601606016160162601636016460165601666016760168601696017060171601726017360174601756017660177601786017960180601816018260183601846018560186601876018860189601906019160192601936019460195601966019760198601996020060201602026020360204602056020660207602086020960210602116021260213602146021560216602176021860219602206022160222602236022460225602266022760228602296023060231602326023360234602356023660237602386023960240602416024260243602446024560246602476024860249602506025160252602536025460255602566025760258602596026060261602626026360264602656026660267602686026960270602716027260273602746027560276602776027860279602806028160282602836028460285602866028760288602896029060291602926029360294602956029660297602986029960300603016030260303603046030560306603076030860309603106031160312603136031460315603166031760318603196032060321603226032360324603256032660327603286032960330603316033260333603346033560336603376033860339603406034160342603436034460345603466034760348603496035060351603526035360354603556035660357603586035960360603616036260363603646036560366603676036860369603706037160372603736037460375603766037760378603796038060381603826038360384603856038660387603886038960390603916039260393603946039560396603976039860399604006040160402604036040460405604066040760408604096041060411604126041360414604156041660417604186041960420604216042260423604246042560426604276042860429604306043160432604336043460435604366043760438604396044060441604426044360444604456044660447604486044960450604516045260453604546045560456604576045860459604606046160462604636046460465604666046760468604696047060471604726047360474604756047660477604786047960480604816048260483604846048560486604876048860489604906049160492604936049460495604966049760498604996050060501605026050360504605056050660507605086050960510605116051260513605146051560516605176051860519605206052160522605236052460525605266052760528605296053060531605326053360534605356053660537605386053960540605416054260543605446054560546605476054860549605506055160552605536055460555605566055760558605596056060561605626056360564605656056660567605686056960570605716057260573605746057560576605776057860579605806058160582605836058460585605866058760588605896059060591605926059360594605956059660597605986059960600606016060260603606046060560606606076060860609606106061160612606136061460615606166061760618606196062060621606226062360624606256062660627606286062960630606316063260633606346063560636606376063860639606406064160642606436064460645606466064760648606496065060651606526065360654606556065660657606586065960660606616066260663606646066560666606676066860669606706067160672606736067460675606766067760678606796068060681606826068360684606856068660687606886068960690606916069260693606946069560696606976069860699607006070160702607036070460705607066070760708607096071060711607126071360714607156071660717607186071960720607216072260723607246072560726607276072860729607306073160732607336073460735607366073760738607396074060741607426074360744607456074660747607486074960750607516075260753607546075560756607576075860759607606076160762607636076460765607666076760768607696077060771607726077360774607756077660777607786077960780607816078260783607846078560786607876078860789607906079160792607936079460795607966079760798607996080060801608026080360804608056080660807608086080960810608116081260813608146081560816608176081860819608206082160822608236082460825608266082760828608296083060831608326083360834608356083660837608386083960840608416084260843608446084560846608476084860849608506085160852608536085460855608566085760858608596086060861608626086360864608656086660867608686086960870608716087260873608746087560876608776087860879608806088160882608836088460885608866088760888608896089060891608926089360894608956089660897608986089960900609016090260903609046090560906609076090860909609106091160912609136091460915609166091760918609196092060921609226092360924609256092660927609286092960930609316093260933609346093560936609376093860939609406094160942609436094460945609466094760948609496095060951609526095360954609556095660957609586095960960609616096260963609646096560966609676096860969609706097160972609736097460975609766097760978609796098060981609826098360984609856098660987609886098960990609916099260993609946099560996609976099860999610006100161002610036100461005610066100761008610096101061011610126101361014610156101661017610186101961020610216102261023610246102561026610276102861029610306103161032610336103461035610366103761038610396104061041610426104361044610456104661047610486104961050610516105261053610546105561056610576105861059610606106161062610636106461065610666106761068610696107061071610726107361074610756107661077610786107961080610816108261083610846108561086610876108861089610906109161092610936109461095610966109761098610996110061101611026110361104611056110661107611086110961110611116111261113611146111561116611176111861119611206112161122611236112461125611266112761128611296113061131611326113361134611356113661137611386113961140611416114261143611446114561146611476114861149611506115161152611536115461155611566115761158611596116061161611626116361164611656116661167611686116961170611716117261173611746117561176611776117861179611806118161182611836118461185611866118761188611896119061191611926119361194611956119661197611986119961200612016120261203612046120561206612076120861209612106121161212612136121461215612166121761218612196122061221612226122361224612256122661227612286122961230612316123261233612346123561236612376123861239612406124161242612436124461245612466124761248612496125061251612526125361254612556125661257612586125961260612616126261263612646126561266612676126861269612706127161272612736127461275612766127761278612796128061281612826128361284612856128661287612886128961290612916129261293612946129561296612976129861299613006130161302613036130461305613066130761308613096131061311613126131361314613156131661317613186131961320613216132261323613246132561326613276132861329613306133161332613336133461335613366133761338613396134061341613426134361344613456134661347613486134961350613516135261353613546135561356613576135861359613606136161362613636136461365613666136761368613696137061371613726137361374613756137661377613786137961380613816138261383613846138561386613876138861389613906139161392613936139461395613966139761398613996140061401614026140361404614056140661407614086140961410614116141261413614146141561416614176141861419614206142161422614236142461425614266142761428614296143061431614326143361434614356143661437614386143961440614416144261443614446144561446614476144861449614506145161452614536145461455614566145761458614596146061461614626146361464614656146661467614686146961470614716147261473614746147561476614776147861479614806148161482614836148461485614866148761488614896149061491614926149361494614956149661497614986149961500615016150261503615046150561506615076150861509615106151161512615136151461515615166151761518615196152061521615226152361524615256152661527615286152961530615316153261533615346153561536615376153861539615406154161542615436154461545615466154761548615496155061551615526155361554615556155661557615586155961560615616156261563615646156561566615676156861569615706157161572615736157461575615766157761578615796158061581615826158361584615856158661587615886158961590615916159261593615946159561596615976159861599616006160161602616036160461605616066160761608616096161061611616126161361614616156161661617616186161961620616216162261623616246162561626616276162861629616306163161632616336163461635616366163761638616396164061641616426164361644616456164661647616486164961650616516165261653616546165561656616576165861659616606166161662616636166461665616666166761668616696167061671616726167361674616756167661677616786167961680616816168261683616846168561686616876168861689616906169161692616936169461695616966169761698616996170061701617026170361704617056170661707617086170961710617116171261713617146171561716617176171861719617206172161722617236172461725617266172761728617296173061731617326173361734617356173661737617386173961740617416174261743617446174561746617476174861749617506175161752617536175461755617566175761758617596176061761617626176361764617656176661767617686176961770617716177261773617746177561776617776177861779617806178161782617836178461785617866178761788617896179061791617926179361794617956179661797617986179961800618016180261803618046180561806618076180861809618106181161812618136181461815618166181761818618196182061821618226182361824618256182661827618286182961830618316183261833618346183561836618376183861839618406184161842618436184461845618466184761848618496185061851618526185361854618556185661857618586185961860618616186261863618646186561866618676186861869618706187161872618736187461875618766187761878618796188061881618826188361884618856188661887618886188961890618916189261893618946189561896618976189861899619006190161902619036190461905619066190761908619096191061911619126191361914619156191661917619186191961920619216192261923619246192561926619276192861929619306193161932619336193461935619366193761938619396194061941619426194361944619456194661947619486194961950619516195261953619546195561956619576195861959619606196161962619636196461965619666196761968619696197061971619726197361974619756197661977619786197961980619816198261983619846198561986619876198861989619906199161992619936199461995619966199761998619996200062001620026200362004620056200662007620086200962010620116201262013620146201562016620176201862019620206202162022620236202462025620266202762028620296203062031620326203362034620356203662037620386203962040620416204262043620446204562046620476204862049620506205162052620536205462055620566205762058620596206062061620626206362064620656206662067620686206962070620716207262073620746207562076620776207862079620806208162082620836208462085620866208762088620896209062091620926209362094620956209662097620986209962100621016210262103621046210562106621076210862109621106211162112621136211462115621166211762118621196212062121621226212362124621256212662127621286212962130621316213262133621346213562136621376213862139621406214162142621436214462145621466214762148621496215062151621526215362154621556215662157621586215962160621616216262163621646216562166621676216862169621706217162172621736217462175621766217762178621796218062181621826218362184621856218662187621886218962190621916219262193621946219562196621976219862199622006220162202622036220462205622066220762208622096221062211622126221362214622156221662217622186221962220622216222262223622246222562226622276222862229622306223162232622336223462235622366223762238622396224062241622426224362244622456224662247622486224962250622516225262253622546225562256622576225862259622606226162262622636226462265622666226762268622696227062271622726227362274622756227662277622786227962280622816228262283622846228562286622876228862289622906229162292622936229462295622966229762298622996230062301623026230362304623056230662307623086230962310623116231262313623146231562316623176231862319623206232162322623236232462325623266232762328623296233062331623326233362334623356233662337623386233962340623416234262343623446234562346623476234862349623506235162352623536235462355623566235762358623596236062361623626236362364623656236662367623686236962370623716237262373623746237562376623776237862379623806238162382623836238462385623866238762388623896239062391623926239362394623956239662397623986239962400624016240262403624046240562406624076240862409624106241162412624136241462415624166241762418624196242062421624226242362424624256242662427624286242962430624316243262433624346243562436624376243862439624406244162442624436244462445624466244762448624496245062451624526245362454624556245662457624586245962460624616246262463624646246562466624676246862469624706247162472624736247462475624766247762478624796248062481624826248362484624856248662487624886248962490624916249262493624946249562496624976249862499625006250162502625036250462505625066250762508625096251062511625126251362514625156251662517625186251962520625216252262523625246252562526625276252862529625306253162532625336253462535625366253762538625396254062541625426254362544625456254662547625486254962550625516255262553625546255562556625576255862559625606256162562625636256462565625666256762568625696257062571625726257362574625756257662577625786257962580625816258262583625846258562586625876258862589625906259162592625936259462595625966259762598625996260062601626026260362604626056260662607626086260962610626116261262613626146261562616626176261862619626206262162622626236262462625626266262762628626296263062631626326263362634626356263662637626386263962640626416264262643626446264562646626476264862649626506265162652626536265462655626566265762658626596266062661626626266362664626656266662667626686266962670626716267262673626746267562676626776267862679626806268162682626836268462685626866268762688626896269062691626926269362694626956269662697626986269962700627016270262703627046270562706627076270862709627106271162712627136271462715627166271762718627196272062721627226272362724627256272662727627286272962730627316273262733627346273562736627376273862739627406274162742627436274462745627466274762748627496275062751627526275362754627556275662757627586275962760627616276262763627646276562766627676276862769627706277162772627736277462775627766277762778627796278062781627826278362784627856278662787627886278962790627916279262793627946279562796627976279862799628006280162802628036280462805628066280762808628096281062811628126281362814628156281662817628186281962820628216282262823628246282562826628276282862829628306283162832628336283462835628366283762838628396284062841628426284362844628456284662847628486284962850628516285262853628546285562856628576285862859628606286162862628636286462865628666286762868628696287062871628726287362874628756287662877628786287962880628816288262883628846288562886628876288862889628906289162892628936289462895628966289762898628996290062901629026290362904629056290662907629086290962910629116291262913629146291562916629176291862919629206292162922629236292462925629266292762928629296293062931629326293362934629356293662937629386293962940629416294262943629446294562946629476294862949629506295162952629536295462955629566295762958629596296062961629626296362964629656296662967629686296962970629716297262973629746297562976629776297862979629806298162982629836298462985629866298762988629896299062991629926299362994629956299662997629986299963000630016300263003630046300563006630076300863009630106301163012630136301463015630166301763018630196302063021630226302363024630256302663027630286302963030630316303263033630346303563036630376303863039630406304163042630436304463045630466304763048630496305063051630526305363054630556305663057630586305963060630616306263063630646306563066630676306863069630706307163072630736307463075630766307763078630796308063081630826308363084630856308663087630886308963090630916309263093630946309563096630976309863099631006310163102631036310463105631066310763108631096311063111631126311363114631156311663117631186311963120631216312263123631246312563126631276312863129631306313163132631336313463135631366313763138631396314063141631426314363144631456314663147631486314963150631516315263153631546315563156631576315863159631606316163162631636316463165631666316763168631696317063171631726317363174631756317663177631786317963180631816318263183631846318563186631876318863189631906319163192631936319463195631966319763198631996320063201632026320363204632056320663207632086320963210632116321263213632146321563216632176321863219632206322163222632236322463225632266322763228632296323063231632326323363234632356323663237632386323963240632416324263243632446324563246632476324863249632506325163252632536325463255632566325763258632596326063261632626326363264632656326663267632686326963270632716327263273632746327563276632776327863279632806328163282632836328463285632866328763288632896329063291632926329363294632956329663297632986329963300633016330263303633046330563306633076330863309633106331163312633136331463315633166331763318633196332063321633226332363324633256332663327633286332963330633316333263333633346333563336633376333863339633406334163342633436334463345633466334763348633496335063351633526335363354633556335663357633586335963360633616336263363633646336563366633676336863369633706337163372633736337463375633766337763378633796338063381633826338363384633856338663387633886338963390633916339263393633946339563396633976339863399634006340163402634036340463405634066340763408634096341063411634126341363414634156341663417634186341963420634216342263423634246342563426634276342863429634306343163432634336343463435634366343763438634396344063441634426344363444634456344663447634486344963450634516345263453634546345563456634576345863459634606346163462634636346463465634666346763468634696347063471634726347363474634756347663477634786347963480634816348263483634846348563486634876348863489634906349163492634936349463495634966349763498634996350063501635026350363504635056350663507635086350963510635116351263513635146351563516635176351863519635206352163522635236352463525635266352763528635296353063531635326353363534635356353663537635386353963540635416354263543635446354563546635476354863549635506355163552635536355463555635566355763558635596356063561635626356363564635656356663567635686356963570635716357263573635746357563576635776357863579635806358163582635836358463585635866358763588635896359063591635926359363594635956359663597635986359963600636016360263603636046360563606636076360863609636106361163612636136361463615636166361763618636196362063621636226362363624636256362663627636286362963630636316363263633636346363563636636376363863639636406364163642636436364463645636466364763648636496365063651636526365363654636556365663657636586365963660636616366263663636646366563666636676366863669636706367163672636736367463675636766367763678636796368063681636826368363684636856368663687636886368963690636916369263693636946369563696636976369863699637006370163702637036370463705637066370763708637096371063711637126371363714637156371663717637186371963720637216372263723637246372563726637276372863729637306373163732637336373463735637366373763738637396374063741637426374363744637456374663747637486374963750637516375263753637546375563756637576375863759637606376163762637636376463765637666376763768637696377063771637726377363774637756377663777637786377963780637816378263783637846378563786637876378863789637906379163792637936379463795637966379763798637996380063801638026380363804638056380663807638086380963810638116381263813638146381563816638176381863819638206382163822638236382463825638266382763828638296383063831638326383363834638356383663837638386383963840638416384263843638446384563846638476384863849638506385163852638536385463855638566385763858638596386063861638626386363864638656386663867638686386963870638716387263873638746387563876638776387863879638806388163882638836388463885638866388763888638896389063891638926389363894638956389663897638986389963900639016390263903639046390563906639076390863909639106391163912639136391463915639166391763918639196392063921639226392363924639256392663927639286392963930639316393263933639346393563936639376393863939639406394163942639436394463945639466394763948639496395063951639526395363954639556395663957639586395963960639616396263963639646396563966639676396863969639706397163972639736397463975639766397763978639796398063981639826398363984639856398663987639886398963990639916399263993639946399563996639976399863999640006400164002640036400464005640066400764008640096401064011640126401364014640156401664017640186401964020640216402264023640246402564026640276402864029640306403164032640336403464035640366403764038640396404064041640426404364044640456404664047640486404964050640516405264053640546405564056640576405864059640606406164062640636406464065640666406764068640696407064071640726407364074640756407664077640786407964080640816408264083640846408564086640876408864089640906409164092640936409464095640966409764098640996410064101641026410364104641056410664107641086410964110641116411264113641146411564116641176411864119641206412164122641236412464125641266412764128641296413064131641326413364134641356413664137641386413964140641416414264143641446414564146641476414864149641506415164152641536415464155641566415764158641596416064161641626416364164641656416664167641686416964170641716417264173641746417564176641776417864179641806418164182641836418464185641866418764188641896419064191641926419364194641956419664197641986419964200642016420264203642046420564206642076420864209642106421164212642136421464215642166421764218642196422064221642226422364224642256422664227642286422964230642316423264233642346423564236642376423864239642406424164242642436424464245642466424764248642496425064251642526425364254642556425664257642586425964260642616426264263642646426564266642676426864269642706427164272642736427464275642766427764278642796428064281642826428364284642856428664287642886428964290642916429264293642946429564296642976429864299643006430164302643036430464305643066430764308643096431064311643126431364314643156431664317643186431964320643216432264323643246432564326643276432864329643306433164332643336433464335643366433764338643396434064341643426434364344643456434664347643486434964350643516435264353643546435564356643576435864359643606436164362643636436464365643666436764368643696437064371643726437364374643756437664377643786437964380643816438264383643846438564386643876438864389643906439164392643936439464395643966439764398643996440064401644026440364404644056440664407644086440964410644116441264413644146441564416644176441864419644206442164422644236442464425644266442764428644296443064431644326443364434644356443664437644386443964440644416444264443644446444564446644476444864449644506445164452644536445464455644566445764458644596446064461644626446364464644656446664467644686446964470644716447264473644746447564476644776447864479644806448164482644836448464485644866448764488644896449064491644926449364494644956449664497644986449964500645016450264503645046450564506645076450864509645106451164512645136451464515645166451764518645196452064521645226452364524645256452664527645286452964530645316453264533645346453564536645376453864539645406454164542645436454464545645466454764548645496455064551645526455364554645556455664557645586455964560645616456264563645646456564566645676456864569645706457164572645736457464575645766457764578645796458064581645826458364584645856458664587645886458964590645916459264593645946459564596645976459864599646006460164602646036460464605646066460764608646096461064611646126461364614646156461664617646186461964620646216462264623646246462564626646276462864629646306463164632646336463464635646366463764638646396464064641646426464364644646456464664647646486464964650646516465264653646546465564656646576465864659646606466164662646636466464665646666466764668646696467064671646726467364674646756467664677646786467964680646816468264683646846468564686646876468864689646906469164692646936469464695646966469764698646996470064701647026470364704647056470664707647086470964710647116471264713647146471564716647176471864719647206472164722647236472464725647266472764728647296473064731647326473364734647356473664737647386473964740647416474264743647446474564746647476474864749647506475164752647536475464755647566475764758647596476064761647626476364764647656476664767647686476964770647716477264773647746477564776647776477864779647806478164782647836478464785647866478764788647896479064791647926479364794647956479664797647986479964800648016480264803648046480564806648076480864809648106481164812648136481464815648166481764818648196482064821648226482364824648256482664827648286482964830648316483264833648346483564836648376483864839648406484164842648436484464845648466484764848648496485064851648526485364854648556485664857648586485964860648616486264863648646486564866648676486864869648706487164872648736487464875648766487764878648796488064881648826488364884648856488664887648886488964890648916489264893648946489564896648976489864899649006490164902649036490464905649066490764908649096491064911649126491364914649156491664917649186491964920649216492264923649246492564926649276492864929649306493164932649336493464935649366493764938649396494064941649426494364944649456494664947649486494964950649516495264953649546495564956649576495864959649606496164962649636496464965649666496764968649696497064971649726497364974649756497664977649786497964980649816498264983649846498564986649876498864989649906499164992649936499464995649966499764998649996500065001650026500365004650056500665007650086500965010650116501265013650146501565016650176501865019650206502165022650236502465025650266502765028650296503065031650326503365034650356503665037650386503965040650416504265043650446504565046650476504865049650506505165052650536505465055650566505765058650596506065061650626506365064650656506665067650686506965070650716507265073650746507565076650776507865079650806508165082650836508465085650866508765088650896509065091650926509365094650956509665097650986509965100651016510265103651046510565106651076510865109651106511165112651136511465115651166511765118651196512065121651226512365124651256512665127651286512965130651316513265133651346513565136651376513865139651406514165142651436514465145651466514765148651496515065151651526515365154651556515665157651586515965160651616516265163651646516565166651676516865169651706517165172651736517465175651766517765178651796518065181651826518365184651856518665187651886518965190651916519265193651946519565196651976519865199652006520165202652036520465205652066520765208652096521065211652126521365214652156521665217652186521965220652216522265223652246522565226652276522865229652306523165232652336523465235652366523765238652396524065241652426524365244652456524665247652486524965250652516525265253652546525565256652576525865259652606526165262652636526465265652666526765268652696527065271652726527365274652756527665277652786527965280652816528265283652846528565286652876528865289652906529165292652936529465295652966529765298652996530065301653026530365304653056530665307653086530965310653116531265313653146531565316653176531865319653206532165322653236532465325653266532765328653296533065331653326533365334653356533665337653386533965340653416534265343653446534565346653476534865349653506535165352653536535465355653566535765358653596536065361653626536365364653656536665367653686536965370653716537265373653746537565376653776537865379653806538165382653836538465385653866538765388653896539065391653926539365394653956539665397653986539965400654016540265403654046540565406654076540865409654106541165412654136541465415654166541765418654196542065421654226542365424654256542665427654286542965430654316543265433654346543565436654376543865439654406544165442654436544465445654466544765448654496545065451654526545365454654556545665457654586545965460654616546265463654646546565466654676546865469654706547165472654736547465475654766547765478654796548065481654826548365484654856548665487654886548965490654916549265493654946549565496654976549865499655006550165502655036550465505655066550765508655096551065511655126551365514655156551665517655186551965520655216552265523655246552565526655276552865529655306553165532655336553465535655366553765538655396554065541655426554365544655456554665547655486554965550655516555265553655546555565556655576555865559655606556165562655636556465565655666556765568655696557065571655726557365574655756557665577655786557965580655816558265583655846558565586655876558865589655906559165592655936559465595655966559765598655996560065601656026560365604656056560665607656086560965610656116561265613656146561565616656176561865619656206562165622656236562465625656266562765628656296563065631656326563365634656356563665637656386563965640656416564265643656446564565646656476564865649656506565165652656536565465655656566565765658656596566065661656626566365664656656566665667656686566965670656716567265673656746567565676656776567865679656806568165682656836568465685656866568765688656896569065691656926569365694656956569665697656986569965700657016570265703657046570565706657076570865709657106571165712657136571465715657166571765718657196572065721657226572365724657256572665727657286572965730657316573265733657346573565736657376573865739657406574165742657436574465745657466574765748657496575065751657526575365754657556575665757657586575965760657616576265763657646576565766657676576865769657706577165772657736577465775657766577765778657796578065781657826578365784657856578665787657886578965790657916579265793657946579565796657976579865799658006580165802658036580465805658066580765808658096581065811658126581365814658156581665817658186581965820658216582265823658246582565826658276582865829658306583165832658336583465835658366583765838658396584065841658426584365844658456584665847658486584965850658516585265853658546585565856658576585865859658606586165862658636586465865658666586765868658696587065871658726587365874658756587665877658786587965880658816588265883658846588565886658876588865889658906589165892658936589465895658966589765898658996590065901659026590365904659056590665907659086590965910659116591265913659146591565916659176591865919659206592165922659236592465925659266592765928659296593065931659326593365934659356593665937659386593965940659416594265943659446594565946659476594865949659506595165952659536595465955659566595765958659596596065961659626596365964659656596665967659686596965970659716597265973659746597565976659776597865979659806598165982659836598465985659866598765988659896599065991659926599365994659956599665997659986599966000660016600266003660046600566006660076600866009660106601166012660136601466015660166601766018660196602066021660226602366024660256602666027660286602966030660316603266033660346603566036660376603866039660406604166042660436604466045660466604766048660496605066051660526605366054660556605666057660586605966060660616606266063660646606566066660676606866069660706607166072660736607466075660766607766078660796608066081660826608366084660856608666087660886608966090660916609266093660946609566096660976609866099661006610166102661036610466105661066610766108661096611066111661126611366114661156611666117661186611966120661216612266123661246612566126661276612866129661306613166132661336613466135661366613766138661396614066141661426614366144661456614666147661486614966150661516615266153661546615566156661576615866159661606616166162661636616466165661666616766168661696617066171661726617366174661756617666177661786617966180661816618266183661846618566186661876618866189661906619166192661936619466195661966619766198661996620066201662026620366204662056620666207662086620966210662116621266213662146621566216662176621866219662206622166222662236622466225662266622766228662296623066231662326623366234662356623666237662386623966240662416624266243662446624566246662476624866249662506625166252662536625466255662566625766258662596626066261662626626366264662656626666267662686626966270662716627266273662746627566276662776627866279662806628166282662836628466285662866628766288662896629066291662926629366294662956629666297662986629966300663016630266303663046630566306663076630866309663106631166312663136631466315663166631766318663196632066321663226632366324663256632666327663286632966330663316633266333663346633566336663376633866339663406634166342663436634466345663466634766348663496635066351663526635366354663556635666357663586635966360663616636266363663646636566366663676636866369663706637166372663736637466375663766637766378663796638066381663826638366384663856638666387663886638966390663916639266393663946639566396663976639866399664006640166402664036640466405664066640766408664096641066411664126641366414664156641666417664186641966420664216642266423664246642566426664276642866429664306643166432664336643466435664366643766438664396644066441664426644366444664456644666447664486644966450664516645266453664546645566456664576645866459664606646166462664636646466465664666646766468664696647066471664726647366474664756647666477664786647966480664816648266483664846648566486664876648866489664906649166492664936649466495664966649766498664996650066501665026650366504665056650666507665086650966510665116651266513665146651566516665176651866519665206652166522665236652466525665266652766528665296653066531665326653366534665356653666537665386653966540665416654266543665446654566546665476654866549665506655166552665536655466555665566655766558665596656066561665626656366564665656656666567665686656966570665716657266573665746657566576665776657866579665806658166582665836658466585665866658766588665896659066591665926659366594665956659666597665986659966600666016660266603666046660566606666076660866609666106661166612666136661466615666166661766618666196662066621666226662366624666256662666627666286662966630666316663266633666346663566636666376663866639666406664166642666436664466645666466664766648666496665066651666526665366654666556665666657666586665966660666616666266663666646666566666666676666866669666706667166672666736667466675666766667766678666796668066681666826668366684666856668666687666886668966690666916669266693666946669566696666976669866699667006670166702667036670466705667066670766708667096671066711667126671366714667156671666717667186671966720667216672266723667246672566726667276672866729667306673166732667336673466735667366673766738667396674066741667426674366744667456674666747667486674966750667516675266753667546675566756667576675866759667606676166762667636676466765667666676766768667696677066771667726677366774667756677666777667786677966780667816678266783667846678566786667876678866789667906679166792667936679466795667966679766798667996680066801668026680366804668056680666807668086680966810668116681266813668146681566816668176681866819668206682166822668236682466825668266682766828668296683066831668326683366834668356683666837668386683966840668416684266843668446684566846668476684866849668506685166852668536685466855668566685766858668596686066861668626686366864668656686666867668686686966870668716687266873668746687566876668776687866879668806688166882668836688466885668866688766888668896689066891668926689366894668956689666897668986689966900669016690266903669046690566906669076690866909669106691166912669136691466915669166691766918669196692066921669226692366924669256692666927669286692966930669316693266933669346693566936669376693866939669406694166942669436694466945669466694766948669496695066951669526695366954669556695666957669586695966960669616696266963669646696566966669676696866969669706697166972669736697466975669766697766978669796698066981669826698366984669856698666987669886698966990669916699266993669946699566996669976699866999670006700167002670036700467005670066700767008670096701067011670126701367014670156701667017670186701967020670216702267023670246702567026670276702867029670306703167032670336703467035670366703767038670396704067041670426704367044670456704667047670486704967050670516705267053670546705567056670576705867059670606706167062670636706467065670666706767068670696707067071670726707367074670756707667077670786707967080670816708267083670846708567086670876708867089670906709167092670936709467095670966709767098670996710067101671026710367104671056710667107671086710967110671116711267113671146711567116671176711867119671206712167122671236712467125671266712767128671296713067131671326713367134671356713667137671386713967140671416714267143671446714567146671476714867149671506715167152671536715467155671566715767158671596716067161671626716367164671656716667167671686716967170671716717267173671746717567176671776717867179671806718167182671836718467185671866718767188671896719067191671926719367194671956719667197671986719967200672016720267203672046720567206672076720867209672106721167212672136721467215672166721767218672196722067221672226722367224672256722667227672286722967230672316723267233672346723567236672376723867239672406724167242672436724467245672466724767248672496725067251672526725367254672556725667257672586725967260672616726267263672646726567266672676726867269672706727167272672736727467275672766727767278672796728067281672826728367284672856728667287672886728967290672916729267293672946729567296672976729867299673006730167302673036730467305673066730767308673096731067311673126731367314673156731667317673186731967320673216732267323673246732567326673276732867329673306733167332673336733467335673366733767338673396734067341673426734367344673456734667347673486734967350673516735267353673546735567356673576735867359673606736167362673636736467365673666736767368673696737067371673726737367374673756737667377673786737967380673816738267383673846738567386673876738867389673906739167392673936739467395673966739767398673996740067401674026740367404674056740667407674086740967410674116741267413674146741567416674176741867419674206742167422674236742467425674266742767428674296743067431674326743367434674356743667437674386743967440674416744267443674446744567446674476744867449674506745167452674536745467455674566745767458674596746067461674626746367464674656746667467674686746967470674716747267473674746747567476674776747867479674806748167482674836748467485674866748767488674896749067491674926749367494674956749667497674986749967500675016750267503675046750567506675076750867509675106751167512675136751467515675166751767518675196752067521675226752367524675256752667527675286752967530675316753267533675346753567536675376753867539675406754167542675436754467545675466754767548675496755067551675526755367554675556755667557675586755967560675616756267563675646756567566675676756867569675706757167572675736757467575675766757767578675796758067581675826758367584675856758667587675886758967590675916759267593675946759567596675976759867599676006760167602676036760467605676066760767608676096761067611676126761367614676156761667617676186761967620676216762267623676246762567626676276762867629676306763167632676336763467635676366763767638676396764067641676426764367644676456764667647676486764967650676516765267653676546765567656676576765867659676606766167662676636766467665676666766767668676696767067671676726767367674676756767667677676786767967680676816768267683676846768567686676876768867689676906769167692676936769467695676966769767698676996770067701677026770367704677056770667707677086770967710677116771267713677146771567716677176771867719677206772167722677236772467725677266772767728677296773067731677326773367734677356773667737677386773967740677416774267743677446774567746677476774867749677506775167752677536775467755677566775767758677596776067761677626776367764677656776667767677686776967770677716777267773677746777567776677776777867779677806778167782677836778467785677866778767788677896779067791677926779367794677956779667797677986779967800678016780267803678046780567806678076780867809678106781167812678136781467815678166781767818678196782067821678226782367824678256782667827678286782967830678316783267833678346783567836678376783867839678406784167842678436784467845678466784767848678496785067851678526785367854678556785667857678586785967860678616786267863678646786567866678676786867869678706787167872678736787467875678766787767878678796788067881678826788367884678856788667887678886788967890678916789267893678946789567896678976789867899679006790167902679036790467905679066790767908679096791067911679126791367914679156791667917679186791967920679216792267923679246792567926679276792867929679306793167932679336793467935679366793767938679396794067941679426794367944679456794667947679486794967950679516795267953679546795567956679576795867959679606796167962679636796467965679666796767968679696797067971679726797367974679756797667977679786797967980679816798267983679846798567986679876798867989679906799167992679936799467995679966799767998679996800068001680026800368004680056800668007680086800968010680116801268013680146801568016680176801868019680206802168022680236802468025680266802768028680296803068031680326803368034680356803668037680386803968040680416804268043680446804568046680476804868049680506805168052680536805468055680566805768058680596806068061680626806368064680656806668067680686806968070680716807268073680746807568076680776807868079680806808168082680836808468085680866808768088680896809068091680926809368094680956809668097680986809968100681016810268103681046810568106681076810868109681106811168112681136811468115681166811768118681196812068121681226812368124681256812668127681286812968130681316813268133681346813568136681376813868139681406814168142681436814468145681466814768148681496815068151681526815368154681556815668157681586815968160681616816268163681646816568166681676816868169681706817168172681736817468175681766817768178681796818068181681826818368184681856818668187681886818968190681916819268193681946819568196681976819868199682006820168202682036820468205682066820768208682096821068211682126821368214682156821668217682186821968220682216822268223682246822568226682276822868229682306823168232682336823468235682366823768238682396824068241682426824368244682456824668247682486824968250682516825268253682546825568256682576825868259682606826168262682636826468265682666826768268682696827068271682726827368274682756827668277682786827968280682816828268283682846828568286682876828868289682906829168292682936829468295682966829768298682996830068301683026830368304683056830668307683086830968310683116831268313683146831568316683176831868319683206832168322683236832468325683266832768328683296833068331683326833368334683356833668337683386833968340683416834268343683446834568346683476834868349683506835168352683536835468355683566835768358683596836068361683626836368364683656836668367683686836968370683716837268373683746837568376683776837868379683806838168382683836838468385683866838768388683896839068391683926839368394683956839668397683986839968400684016840268403684046840568406684076840868409684106841168412684136841468415684166841768418684196842068421684226842368424684256842668427684286842968430684316843268433684346843568436684376843868439684406844168442684436844468445684466844768448684496845068451684526845368454684556845668457684586845968460684616846268463684646846568466684676846868469684706847168472684736847468475684766847768478684796848068481684826848368484684856848668487684886848968490684916849268493684946849568496684976849868499685006850168502685036850468505685066850768508685096851068511685126851368514685156851668517685186851968520685216852268523685246852568526685276852868529685306853168532685336853468535685366853768538685396854068541685426854368544685456854668547685486854968550685516855268553685546855568556685576855868559685606856168562685636856468565685666856768568685696857068571685726857368574685756857668577685786857968580685816858268583685846858568586685876858868589685906859168592685936859468595685966859768598685996860068601686026860368604686056860668607686086860968610686116861268613686146861568616686176861868619686206862168622686236862468625686266862768628686296863068631686326863368634686356863668637686386863968640686416864268643686446864568646686476864868649686506865168652686536865468655686566865768658686596866068661686626866368664686656866668667686686866968670686716867268673686746867568676686776867868679686806868168682686836868468685686866868768688686896869068691686926869368694686956869668697686986869968700687016870268703687046870568706687076870868709687106871168712687136871468715687166871768718687196872068721687226872368724687256872668727687286872968730687316873268733687346873568736687376873868739687406874168742687436874468745687466874768748687496875068751687526875368754687556875668757687586875968760687616876268763687646876568766687676876868769687706877168772687736877468775687766877768778687796878068781687826878368784687856878668787687886878968790687916879268793687946879568796687976879868799688006880168802688036880468805688066880768808688096881068811688126881368814688156881668817688186881968820688216882268823688246882568826688276882868829688306883168832688336883468835688366883768838688396884068841688426884368844688456884668847688486884968850688516885268853688546885568856688576885868859688606886168862688636886468865688666886768868688696887068871688726887368874688756887668877688786887968880688816888268883688846888568886688876888868889688906889168892688936889468895688966889768898688996890068901689026890368904689056890668907689086890968910689116891268913689146891568916689176891868919689206892168922689236892468925689266892768928689296893068931689326893368934689356893668937689386893968940689416894268943689446894568946689476894868949689506895168952689536895468955689566895768958689596896068961689626896368964689656896668967689686896968970689716897268973689746897568976689776897868979689806898168982689836898468985689866898768988689896899068991689926899368994689956899668997689986899969000690016900269003690046900569006690076900869009690106901169012690136901469015690166901769018690196902069021690226902369024690256902669027690286902969030690316903269033690346903569036690376903869039690406904169042690436904469045690466904769048690496905069051690526905369054690556905669057690586905969060690616906269063690646906569066690676906869069690706907169072690736907469075690766907769078690796908069081690826908369084690856908669087690886908969090690916909269093690946909569096690976909869099691006910169102691036910469105691066910769108691096911069111691126911369114691156911669117691186911969120691216912269123691246912569126691276912869129691306913169132691336913469135691366913769138691396914069141691426914369144691456914669147691486914969150691516915269153691546915569156691576915869159691606916169162691636916469165691666916769168691696917069171691726917369174691756917669177691786917969180691816918269183691846918569186691876918869189691906919169192691936919469195691966919769198691996920069201692026920369204692056920669207692086920969210692116921269213692146921569216692176921869219692206922169222692236922469225692266922769228692296923069231692326923369234692356923669237692386923969240692416924269243692446924569246692476924869249692506925169252692536925469255692566925769258692596926069261692626926369264692656926669267692686926969270692716927269273692746927569276692776927869279692806928169282692836928469285692866928769288692896929069291692926929369294692956929669297692986929969300693016930269303693046930569306693076930869309693106931169312693136931469315693166931769318693196932069321693226932369324693256932669327693286932969330693316933269333693346933569336693376933869339693406934169342693436934469345693466934769348693496935069351693526935369354693556935669357693586935969360693616936269363693646936569366693676936869369693706937169372693736937469375693766937769378693796938069381693826938369384693856938669387693886938969390693916939269393693946939569396693976939869399694006940169402694036940469405694066940769408694096941069411694126941369414694156941669417694186941969420694216942269423694246942569426694276942869429694306943169432694336943469435694366943769438694396944069441694426944369444694456944669447694486944969450694516945269453694546945569456694576945869459694606946169462694636946469465694666946769468694696947069471694726947369474694756947669477694786947969480694816948269483694846948569486694876948869489694906949169492694936949469495694966949769498694996950069501695026950369504695056950669507695086950969510695116951269513695146951569516695176951869519695206952169522695236952469525695266952769528695296953069531695326953369534695356953669537695386953969540695416954269543695446954569546695476954869549695506955169552695536955469555695566955769558695596956069561695626956369564695656956669567695686956969570695716957269573695746957569576695776957869579695806958169582695836958469585695866958769588695896959069591695926959369594695956959669597695986959969600696016960269603696046960569606696076960869609696106961169612696136961469615696166961769618696196962069621696226962369624696256962669627696286962969630696316963269633696346963569636696376963869639696406964169642696436964469645696466964769648696496965069651696526965369654696556965669657696586965969660696616966269663696646966569666696676966869669696706967169672696736967469675696766967769678696796968069681696826968369684696856968669687696886968969690696916969269693696946969569696696976969869699697006970169702697036970469705697066970769708697096971069711697126971369714697156971669717697186971969720697216972269723697246972569726697276972869729697306973169732697336973469735697366973769738697396974069741697426974369744697456974669747697486974969750697516975269753697546975569756697576975869759697606976169762697636976469765697666976769768697696977069771697726977369774697756977669777697786977969780697816978269783697846978569786697876978869789697906979169792697936979469795697966979769798697996980069801698026980369804698056980669807698086980969810698116981269813698146981569816698176981869819698206982169822698236982469825698266982769828698296983069831698326983369834698356983669837698386983969840698416984269843698446984569846698476984869849698506985169852698536985469855698566985769858698596986069861698626986369864698656986669867698686986969870698716987269873698746987569876698776987869879698806988169882698836988469885698866988769888698896989069891698926989369894698956989669897698986989969900699016990269903699046990569906699076990869909699106991169912699136991469915699166991769918699196992069921699226992369924699256992669927699286992969930699316993269933699346993569936699376993869939699406994169942699436994469945699466994769948699496995069951699526995369954699556995669957699586995969960699616996269963699646996569966699676996869969699706997169972699736997469975699766997769978699796998069981699826998369984699856998669987699886998969990699916999269993699946999569996699976999869999700007000170002700037000470005700067000770008700097001070011700127001370014700157001670017700187001970020700217002270023700247002570026700277002870029700307003170032700337003470035700367003770038700397004070041700427004370044700457004670047700487004970050700517005270053700547005570056700577005870059700607006170062700637006470065700667006770068700697007070071700727007370074700757007670077700787007970080700817008270083700847008570086700877008870089700907009170092700937009470095700967009770098700997010070101701027010370104701057010670107701087010970110701117011270113701147011570116701177011870119701207012170122701237012470125701267012770128701297013070131701327013370134701357013670137701387013970140701417014270143701447014570146701477014870149701507015170152701537015470155701567015770158701597016070161701627016370164701657016670167701687016970170701717017270173701747017570176701777017870179701807018170182701837018470185701867018770188701897019070191701927019370194701957019670197701987019970200702017020270203702047020570206702077020870209702107021170212702137021470215702167021770218702197022070221702227022370224702257022670227702287022970230702317023270233702347023570236702377023870239702407024170242702437024470245702467024770248702497025070251702527025370254702557025670257702587025970260702617026270263702647026570266702677026870269702707027170272702737027470275702767027770278702797028070281702827028370284702857028670287702887028970290702917029270293702947029570296702977029870299703007030170302703037030470305703067030770308703097031070311703127031370314703157031670317703187031970320703217032270323703247032570326703277032870329703307033170332703337033470335703367033770338703397034070341703427034370344703457034670347703487034970350703517035270353703547035570356703577035870359703607036170362703637036470365703667036770368703697037070371703727037370374703757037670377703787037970380703817038270383703847038570386703877038870389703907039170392703937039470395703967039770398703997040070401704027040370404704057040670407704087040970410704117041270413704147041570416704177041870419704207042170422704237042470425704267042770428704297043070431704327043370434704357043670437704387043970440704417044270443704447044570446704477044870449704507045170452704537045470455704567045770458704597046070461704627046370464704657046670467704687046970470704717047270473704747047570476704777047870479704807048170482704837048470485704867048770488704897049070491704927049370494704957049670497704987049970500705017050270503705047050570506705077050870509705107051170512705137051470515705167051770518705197052070521705227052370524705257052670527705287052970530705317053270533705347053570536705377053870539705407054170542705437054470545705467054770548705497055070551705527055370554705557055670557705587055970560705617056270563705647056570566705677056870569705707057170572705737057470575705767057770578705797058070581705827058370584705857058670587705887058970590705917059270593705947059570596705977059870599706007060170602706037060470605706067060770608706097061070611706127061370614706157061670617706187061970620706217062270623706247062570626706277062870629706307063170632706337063470635706367063770638706397064070641706427064370644706457064670647706487064970650706517065270653706547065570656706577065870659706607066170662706637066470665706667066770668706697067070671706727067370674706757067670677706787067970680706817068270683706847068570686706877068870689706907069170692706937069470695706967069770698706997070070701707027070370704707057070670707707087070970710707117071270713707147071570716707177071870719707207072170722707237072470725707267072770728707297073070731707327073370734707357073670737707387073970740707417074270743707447074570746707477074870749707507075170752707537075470755707567075770758707597076070761707627076370764707657076670767707687076970770707717077270773707747077570776707777077870779707807078170782707837078470785707867078770788707897079070791707927079370794707957079670797707987079970800708017080270803708047080570806708077080870809708107081170812708137081470815708167081770818708197082070821708227082370824708257082670827708287082970830708317083270833708347083570836708377083870839708407084170842708437084470845708467084770848708497085070851708527085370854708557085670857708587085970860708617086270863708647086570866708677086870869708707087170872708737087470875708767087770878708797088070881708827088370884708857088670887708887088970890708917089270893708947089570896708977089870899709007090170902709037090470905709067090770908709097091070911709127091370914709157091670917709187091970920709217092270923709247092570926709277092870929709307093170932709337093470935709367093770938709397094070941709427094370944709457094670947709487094970950709517095270953709547095570956709577095870959709607096170962709637096470965709667096770968709697097070971709727097370974709757097670977709787097970980709817098270983709847098570986709877098870989709907099170992709937099470995709967099770998709997100071001710027100371004710057100671007710087100971010710117101271013710147101571016710177101871019710207102171022710237102471025710267102771028710297103071031710327103371034710357103671037710387103971040710417104271043710447104571046710477104871049710507105171052710537105471055710567105771058710597106071061710627106371064710657106671067710687106971070710717107271073710747107571076710777107871079710807108171082710837108471085710867108771088710897109071091710927109371094710957109671097710987109971100711017110271103711047110571106711077110871109711107111171112711137111471115711167111771118711197112071121711227112371124711257112671127711287112971130711317113271133711347113571136711377113871139711407114171142711437114471145711467114771148711497115071151711527115371154711557115671157711587115971160711617116271163711647116571166711677116871169711707117171172711737117471175711767117771178711797118071181711827118371184711857118671187711887118971190711917119271193711947119571196711977119871199712007120171202712037120471205712067120771208712097121071211712127121371214712157121671217712187121971220712217122271223712247122571226712277122871229712307123171232712337123471235712367123771238712397124071241712427124371244712457124671247712487124971250712517125271253712547125571256712577125871259712607126171262712637126471265712667126771268712697127071271712727127371274712757127671277712787127971280712817128271283712847128571286712877128871289712907129171292712937129471295712967129771298712997130071301713027130371304713057130671307713087130971310713117131271313713147131571316713177131871319713207132171322713237132471325713267132771328713297133071331713327133371334713357133671337713387133971340713417134271343713447134571346713477134871349713507135171352713537135471355713567135771358713597136071361713627136371364713657136671367713687136971370713717137271373713747137571376713777137871379713807138171382713837138471385713867138771388713897139071391713927139371394713957139671397713987139971400714017140271403714047140571406714077140871409714107141171412714137141471415714167141771418714197142071421714227142371424714257142671427714287142971430714317143271433714347143571436714377143871439714407144171442714437144471445714467144771448714497145071451714527145371454714557145671457714587145971460714617146271463714647146571466714677146871469714707147171472714737147471475714767147771478714797148071481714827148371484714857148671487714887148971490714917149271493714947149571496714977149871499715007150171502715037150471505715067150771508715097151071511715127151371514715157151671517715187151971520715217152271523715247152571526715277152871529715307153171532715337153471535715367153771538715397154071541715427154371544715457154671547715487154971550715517155271553715547155571556715577155871559715607156171562715637156471565715667156771568715697157071571715727157371574715757157671577715787157971580715817158271583715847158571586715877158871589715907159171592715937159471595715967159771598715997160071601716027160371604716057160671607716087160971610716117161271613716147161571616716177161871619716207162171622716237162471625716267162771628716297163071631716327163371634716357163671637716387163971640716417164271643716447164571646716477164871649716507165171652716537165471655716567165771658716597166071661716627166371664716657166671667716687166971670716717167271673716747167571676716777167871679716807168171682716837168471685716867168771688716897169071691716927169371694716957169671697716987169971700717017170271703717047170571706717077170871709717107171171712717137171471715717167171771718717197172071721717227172371724717257172671727717287172971730717317173271733717347173571736717377173871739717407174171742717437174471745717467174771748717497175071751717527175371754717557175671757717587175971760717617176271763717647176571766717677176871769717707177171772717737177471775717767177771778717797178071781717827178371784717857178671787717887178971790717917179271793717947179571796717977179871799718007180171802718037180471805718067180771808718097181071811718127181371814718157181671817718187181971820718217182271823718247182571826718277182871829718307183171832718337183471835718367183771838718397184071841718427184371844718457184671847718487184971850718517185271853718547185571856718577185871859718607186171862718637186471865718667186771868718697187071871718727187371874718757187671877718787187971880718817188271883718847188571886718877188871889718907189171892718937189471895718967189771898718997190071901719027190371904719057190671907719087190971910719117191271913719147191571916719177191871919719207192171922719237192471925719267192771928719297193071931719327193371934719357193671937719387193971940719417194271943719447194571946719477194871949719507195171952719537195471955719567195771958719597196071961719627196371964719657196671967719687196971970719717197271973719747197571976719777197871979719807198171982719837198471985719867198771988719897199071991719927199371994719957199671997719987199972000720017200272003720047200572006720077200872009720107201172012720137201472015720167201772018720197202072021720227202372024720257202672027720287202972030720317203272033720347203572036720377203872039720407204172042720437204472045720467204772048720497205072051720527205372054720557205672057720587205972060720617206272063720647206572066720677206872069720707207172072720737207472075720767207772078720797208072081720827208372084720857208672087720887208972090720917209272093720947209572096720977209872099721007210172102721037210472105721067210772108721097211072111721127211372114721157211672117721187211972120721217212272123721247212572126721277212872129721307213172132721337213472135721367213772138721397214072141721427214372144721457214672147721487214972150721517215272153721547215572156721577215872159721607216172162721637216472165721667216772168721697217072171721727217372174721757217672177721787217972180721817218272183721847218572186721877218872189721907219172192721937219472195721967219772198721997220072201722027220372204722057220672207722087220972210722117221272213722147221572216722177221872219722207222172222722237222472225722267222772228722297223072231722327223372234722357223672237722387223972240722417224272243722447224572246722477224872249722507225172252722537225472255722567225772258722597226072261722627226372264722657226672267722687226972270722717227272273722747227572276722777227872279722807228172282722837228472285722867228772288722897229072291722927229372294722957229672297722987229972300723017230272303723047230572306723077230872309723107231172312723137231472315723167231772318723197232072321723227232372324723257232672327723287232972330723317233272333723347233572336723377233872339723407234172342723437234472345723467234772348723497235072351723527235372354723557235672357723587235972360723617236272363723647236572366723677236872369723707237172372723737237472375723767237772378723797238072381723827238372384723857238672387723887238972390723917239272393723947239572396723977239872399724007240172402724037240472405724067240772408724097241072411724127241372414724157241672417724187241972420724217242272423724247242572426724277242872429724307243172432724337243472435724367243772438724397244072441724427244372444724457244672447724487244972450724517245272453724547245572456724577245872459724607246172462724637246472465724667246772468724697247072471724727247372474724757247672477724787247972480724817248272483724847248572486724877248872489724907249172492724937249472495724967249772498724997250072501725027250372504725057250672507725087250972510725117251272513725147251572516725177251872519725207252172522725237252472525725267252772528725297253072531725327253372534725357253672537725387253972540725417254272543725447254572546725477254872549725507255172552725537255472555725567255772558725597256072561725627256372564725657256672567725687256972570725717257272573725747257572576725777257872579725807258172582725837258472585725867258772588725897259072591725927259372594725957259672597725987259972600726017260272603726047260572606726077260872609726107261172612726137261472615726167261772618726197262072621726227262372624726257262672627726287262972630726317263272633726347263572636726377263872639726407264172642726437264472645726467264772648726497265072651726527265372654726557265672657726587265972660726617266272663726647266572666726677266872669726707267172672726737267472675726767267772678726797268072681726827268372684726857268672687726887268972690726917269272693726947269572696726977269872699727007270172702727037270472705727067270772708727097271072711727127271372714727157271672717727187271972720727217272272723727247272572726727277272872729727307273172732727337273472735727367273772738727397274072741727427274372744727457274672747727487274972750727517275272753727547275572756727577275872759727607276172762727637276472765727667276772768727697277072771727727277372774727757277672777727787277972780727817278272783727847278572786727877278872789727907279172792727937279472795727967279772798727997280072801728027280372804728057280672807728087280972810728117281272813728147281572816728177281872819728207282172822728237282472825728267282772828728297283072831728327283372834728357283672837728387283972840728417284272843728447284572846728477284872849728507285172852728537285472855728567285772858728597286072861728627286372864728657286672867728687286972870728717287272873728747287572876728777287872879728807288172882728837288472885728867288772888728897289072891728927289372894728957289672897728987289972900729017290272903729047290572906729077290872909729107291172912729137291472915729167291772918729197292072921729227292372924729257292672927729287292972930729317293272933729347293572936729377293872939729407294172942729437294472945729467294772948729497295072951729527295372954729557295672957729587295972960729617296272963729647296572966729677296872969729707297172972729737297472975729767297772978729797298072981729827298372984729857298672987729887298972990729917299272993729947299572996729977299872999730007300173002730037300473005730067300773008730097301073011730127301373014730157301673017730187301973020730217302273023730247302573026730277302873029730307303173032730337303473035730367303773038730397304073041730427304373044730457304673047730487304973050730517305273053730547305573056730577305873059730607306173062730637306473065730667306773068730697307073071730727307373074730757307673077730787307973080730817308273083730847308573086730877308873089730907309173092730937309473095730967309773098730997310073101731027310373104731057310673107731087310973110731117311273113731147311573116731177311873119731207312173122731237312473125731267312773128731297313073131731327313373134731357313673137731387313973140731417314273143731447314573146731477314873149731507315173152731537315473155731567315773158731597316073161731627316373164731657316673167731687316973170731717317273173731747317573176731777317873179731807318173182731837318473185731867318773188731897319073191731927319373194731957319673197731987319973200732017320273203732047320573206732077320873209732107321173212732137321473215732167321773218732197322073221732227322373224732257322673227732287322973230732317323273233732347323573236732377323873239732407324173242732437324473245732467324773248732497325073251732527325373254732557325673257732587325973260732617326273263732647326573266732677326873269732707327173272732737327473275732767327773278732797328073281732827328373284732857328673287732887328973290732917329273293732947329573296732977329873299733007330173302733037330473305733067330773308733097331073311733127331373314733157331673317733187331973320733217332273323733247332573326733277332873329733307333173332733337333473335733367333773338733397334073341733427334373344733457334673347733487334973350733517335273353733547335573356733577335873359733607336173362733637336473365733667336773368733697337073371733727337373374733757337673377733787337973380733817338273383733847338573386733877338873389733907339173392733937339473395733967339773398733997340073401734027340373404734057340673407734087340973410734117341273413734147341573416734177341873419734207342173422734237342473425734267342773428734297343073431734327343373434734357343673437734387343973440734417344273443734447344573446734477344873449734507345173452734537345473455734567345773458734597346073461734627346373464734657346673467734687346973470734717347273473734747347573476734777347873479734807348173482734837348473485734867348773488734897349073491734927349373494734957349673497734987349973500735017350273503735047350573506735077350873509735107351173512735137351473515735167351773518735197352073521735227352373524735257352673527735287352973530735317353273533735347353573536735377353873539735407354173542735437354473545735467354773548735497355073551735527355373554735557355673557735587355973560735617356273563735647356573566735677356873569735707357173572735737357473575735767357773578735797358073581735827358373584735857358673587735887358973590735917359273593735947359573596735977359873599736007360173602736037360473605736067360773608736097361073611736127361373614736157361673617736187361973620736217362273623736247362573626736277362873629736307363173632736337363473635736367363773638736397364073641736427364373644736457364673647736487364973650736517365273653736547365573656736577365873659736607366173662736637366473665736667366773668736697367073671736727367373674736757367673677736787367973680736817368273683736847368573686736877368873689736907369173692736937369473695736967369773698736997370073701737027370373704737057370673707737087370973710737117371273713737147371573716737177371873719737207372173722737237372473725737267372773728737297373073731737327373373734737357373673737737387373973740737417374273743737447374573746737477374873749737507375173752737537375473755737567375773758737597376073761737627376373764737657376673767737687376973770737717377273773737747377573776737777377873779737807378173782737837378473785737867378773788737897379073791737927379373794737957379673797737987379973800738017380273803738047380573806738077380873809738107381173812738137381473815738167381773818738197382073821738227382373824738257382673827738287382973830738317383273833738347383573836738377383873839738407384173842738437384473845738467384773848738497385073851738527385373854738557385673857738587385973860738617386273863738647386573866738677386873869738707387173872738737387473875738767387773878738797388073881738827388373884738857388673887738887388973890738917389273893738947389573896738977389873899739007390173902739037390473905739067390773908739097391073911739127391373914739157391673917739187391973920739217392273923739247392573926739277392873929739307393173932739337393473935739367393773938739397394073941739427394373944739457394673947739487394973950739517395273953739547395573956739577395873959739607396173962739637396473965739667396773968739697397073971739727397373974739757397673977739787397973980739817398273983739847398573986739877398873989739907399173992739937399473995739967399773998739997400074001740027400374004740057400674007740087400974010740117401274013740147401574016740177401874019740207402174022740237402474025740267402774028740297403074031740327403374034740357403674037740387403974040740417404274043740447404574046740477404874049740507405174052740537405474055740567405774058740597406074061740627406374064740657406674067740687406974070740717407274073740747407574076740777407874079740807408174082740837408474085740867408774088740897409074091740927409374094740957409674097740987409974100741017410274103741047410574106741077410874109741107411174112741137411474115741167411774118741197412074121741227412374124741257412674127741287412974130741317413274133741347413574136741377413874139741407414174142741437414474145741467414774148741497415074151741527415374154741557415674157741587415974160741617416274163741647416574166741677416874169741707417174172741737417474175741767417774178741797418074181741827418374184741857418674187741887418974190741917419274193741947419574196741977419874199742007420174202742037420474205742067420774208742097421074211742127421374214742157421674217742187421974220742217422274223742247422574226742277422874229742307423174232742337423474235742367423774238742397424074241742427424374244742457424674247742487424974250742517425274253742547425574256742577425874259742607426174262742637426474265742667426774268742697427074271742727427374274742757427674277742787427974280742817428274283742847428574286742877428874289742907429174292742937429474295742967429774298742997430074301743027430374304743057430674307743087430974310743117431274313743147431574316743177431874319743207432174322743237432474325743267432774328743297433074331743327433374334743357433674337743387433974340743417434274343743447434574346743477434874349743507435174352743537435474355743567435774358743597436074361743627436374364743657436674367743687436974370743717437274373743747437574376743777437874379743807438174382743837438474385743867438774388743897439074391743927439374394743957439674397743987439974400744017440274403744047440574406744077440874409744107441174412744137441474415744167441774418744197442074421744227442374424744257442674427744287442974430744317443274433744347443574436744377443874439744407444174442744437444474445744467444774448744497445074451744527445374454744557445674457744587445974460744617446274463744647446574466744677446874469744707447174472744737447474475744767447774478744797448074481744827448374484744857448674487744887448974490744917449274493744947449574496744977449874499745007450174502745037450474505745067450774508745097451074511745127451374514745157451674517745187451974520745217452274523745247452574526745277452874529745307453174532745337453474535745367453774538745397454074541745427454374544745457454674547745487454974550745517455274553745547455574556745577455874559745607456174562745637456474565745667456774568745697457074571745727457374574745757457674577745787457974580745817458274583745847458574586745877458874589745907459174592745937459474595745967459774598745997460074601746027460374604746057460674607746087460974610746117461274613746147461574616746177461874619746207462174622746237462474625746267462774628746297463074631746327463374634746357463674637746387463974640746417464274643746447464574646746477464874649746507465174652746537465474655746567465774658746597466074661746627466374664746657466674667746687466974670746717467274673746747467574676746777467874679746807468174682746837468474685746867468774688746897469074691746927469374694746957469674697746987469974700747017470274703747047470574706747077470874709747107471174712747137471474715747167471774718747197472074721747227472374724747257472674727747287472974730747317473274733747347473574736747377473874739747407474174742747437474474745747467474774748747497475074751747527475374754747557475674757747587475974760747617476274763747647476574766747677476874769747707477174772747737477474775747767477774778747797478074781747827478374784747857478674787747887478974790747917479274793747947479574796747977479874799748007480174802748037480474805748067480774808748097481074811748127481374814748157481674817748187481974820748217482274823748247482574826748277482874829748307483174832748337483474835748367483774838748397484074841748427484374844748457484674847748487484974850748517485274853748547485574856748577485874859748607486174862748637486474865748667486774868748697487074871748727487374874748757487674877748787487974880748817488274883748847488574886748877488874889748907489174892748937489474895748967489774898748997490074901749027490374904749057490674907749087490974910749117491274913749147491574916749177491874919749207492174922749237492474925749267492774928749297493074931749327493374934749357493674937749387493974940749417494274943749447494574946749477494874949749507495174952749537495474955749567495774958749597496074961749627496374964749657496674967749687496974970749717497274973749747497574976749777497874979749807498174982749837498474985749867498774988749897499074991749927499374994749957499674997749987499975000750017500275003750047500575006750077500875009750107501175012750137501475015750167501775018750197502075021750227502375024750257502675027750287502975030750317503275033750347503575036750377503875039750407504175042750437504475045750467504775048750497505075051750527505375054750557505675057750587505975060750617506275063750647506575066750677506875069750707507175072750737507475075750767507775078750797508075081750827508375084750857508675087750887508975090750917509275093750947509575096750977509875099751007510175102751037510475105751067510775108751097511075111751127511375114751157511675117751187511975120751217512275123751247512575126751277512875129751307513175132751337513475135751367513775138751397514075141751427514375144751457514675147751487514975150751517515275153751547515575156751577515875159751607516175162751637516475165751667516775168751697517075171751727517375174751757517675177751787517975180751817518275183751847518575186751877518875189751907519175192751937519475195751967519775198751997520075201752027520375204752057520675207752087520975210752117521275213752147521575216752177521875219752207522175222752237522475225752267522775228752297523075231752327523375234752357523675237752387523975240752417524275243752447524575246752477524875249752507525175252752537525475255752567525775258752597526075261752627526375264752657526675267752687526975270752717527275273752747527575276752777527875279752807528175282752837528475285752867528775288752897529075291752927529375294752957529675297752987529975300753017530275303753047530575306753077530875309753107531175312753137531475315753167531775318753197532075321753227532375324753257532675327753287532975330753317533275333753347533575336753377533875339753407534175342753437534475345753467534775348753497535075351753527535375354753557535675357753587535975360753617536275363753647536575366753677536875369753707537175372753737537475375753767537775378753797538075381753827538375384753857538675387753887538975390753917539275393753947539575396753977539875399754007540175402754037540475405754067540775408754097541075411754127541375414754157541675417754187541975420754217542275423754247542575426754277542875429754307543175432754337543475435754367543775438754397544075441754427544375444754457544675447754487544975450754517545275453754547545575456754577545875459754607546175462754637546475465754667546775468754697547075471754727547375474754757547675477754787547975480754817548275483754847548575486754877548875489754907549175492754937549475495754967549775498754997550075501755027550375504755057550675507755087550975510755117551275513755147551575516755177551875519755207552175522755237552475525755267552775528755297553075531755327553375534755357553675537755387553975540755417554275543755447554575546755477554875549755507555175552755537555475555755567555775558755597556075561755627556375564755657556675567755687556975570755717557275573755747557575576755777557875579755807558175582755837558475585755867558775588755897559075591755927559375594755957559675597755987559975600756017560275603756047560575606756077560875609756107561175612756137561475615756167561775618756197562075621756227562375624756257562675627756287562975630756317563275633756347563575636756377563875639756407564175642756437564475645756467564775648756497565075651756527565375654756557565675657756587565975660756617566275663756647566575666756677566875669756707567175672756737567475675756767567775678756797568075681756827568375684756857568675687756887568975690756917569275693756947569575696756977569875699757007570175702757037570475705757067570775708757097571075711757127571375714757157571675717757187571975720757217572275723757247572575726757277572875729757307573175732757337573475735757367573775738757397574075741757427574375744757457574675747757487574975750757517575275753757547575575756757577575875759757607576175762757637576475765757667576775768757697577075771757727577375774757757577675777757787577975780757817578275783757847578575786757877578875789757907579175792757937579475795757967579775798757997580075801758027580375804758057580675807758087580975810758117581275813758147581575816758177581875819758207582175822758237582475825758267582775828758297583075831758327583375834758357583675837758387583975840758417584275843758447584575846758477584875849758507585175852758537585475855758567585775858758597586075861758627586375864758657586675867758687586975870758717587275873758747587575876758777587875879758807588175882758837588475885758867588775888758897589075891758927589375894758957589675897758987589975900759017590275903759047590575906759077590875909759107591175912759137591475915759167591775918759197592075921759227592375924759257592675927759287592975930759317593275933759347593575936759377593875939759407594175942759437594475945759467594775948759497595075951759527595375954759557595675957759587595975960759617596275963759647596575966759677596875969759707597175972759737597475975759767597775978759797598075981759827598375984759857598675987759887598975990759917599275993759947599575996759977599875999760007600176002760037600476005760067600776008760097601076011760127601376014760157601676017760187601976020760217602276023760247602576026760277602876029760307603176032760337603476035760367603776038760397604076041760427604376044760457604676047760487604976050760517605276053760547605576056760577605876059760607606176062760637606476065760667606776068760697607076071760727607376074760757607676077760787607976080760817608276083760847608576086760877608876089760907609176092760937609476095760967609776098760997610076101761027610376104761057610676107761087610976110761117611276113761147611576116761177611876119761207612176122761237612476125761267612776128761297613076131761327613376134761357613676137761387613976140761417614276143761447614576146761477614876149761507615176152761537615476155761567615776158761597616076161761627616376164761657616676167761687616976170761717617276173761747617576176761777617876179761807618176182761837618476185761867618776188761897619076191761927619376194761957619676197761987619976200762017620276203762047620576206762077620876209762107621176212762137621476215762167621776218762197622076221762227622376224762257622676227762287622976230762317623276233762347623576236762377623876239762407624176242762437624476245762467624776248762497625076251762527625376254762557625676257762587625976260762617626276263762647626576266762677626876269762707627176272762737627476275762767627776278762797628076281762827628376284762857628676287762887628976290762917629276293762947629576296762977629876299763007630176302763037630476305763067630776308763097631076311763127631376314763157631676317763187631976320763217632276323763247632576326763277632876329763307633176332763337633476335763367633776338763397634076341763427634376344763457634676347763487634976350763517635276353763547635576356763577635876359763607636176362763637636476365763667636776368763697637076371763727637376374763757637676377763787637976380763817638276383763847638576386763877638876389763907639176392763937639476395763967639776398763997640076401764027640376404764057640676407764087640976410764117641276413764147641576416764177641876419764207642176422764237642476425764267642776428764297643076431764327643376434764357643676437764387643976440764417644276443764447644576446764477644876449764507645176452764537645476455764567645776458764597646076461764627646376464764657646676467764687646976470764717647276473764747647576476764777647876479764807648176482764837648476485764867648776488764897649076491764927649376494764957649676497764987649976500765017650276503765047650576506765077650876509765107651176512765137651476515765167651776518765197652076521765227652376524765257652676527765287652976530765317653276533765347653576536765377653876539765407654176542765437654476545765467654776548765497655076551765527655376554765557655676557765587655976560765617656276563765647656576566765677656876569765707657176572765737657476575765767657776578765797658076581765827658376584765857658676587765887658976590765917659276593765947659576596765977659876599766007660176602766037660476605766067660776608766097661076611766127661376614766157661676617766187661976620766217662276623766247662576626766277662876629766307663176632766337663476635766367663776638766397664076641766427664376644766457664676647766487664976650766517665276653766547665576656766577665876659766607666176662766637666476665766667666776668766697667076671766727667376674766757667676677766787667976680766817668276683766847668576686766877668876689766907669176692766937669476695766967669776698766997670076701767027670376704767057670676707767087670976710767117671276713767147671576716767177671876719767207672176722767237672476725767267672776728767297673076731767327673376734767357673676737767387673976740767417674276743767447674576746767477674876749767507675176752767537675476755767567675776758767597676076761767627676376764767657676676767767687676976770767717677276773767747677576776767777677876779767807678176782767837678476785767867678776788767897679076791767927679376794767957679676797767987679976800768017680276803768047680576806768077680876809768107681176812768137681476815768167681776818768197682076821768227682376824768257682676827768287682976830768317683276833768347683576836768377683876839768407684176842768437684476845768467684776848768497685076851768527685376854768557685676857768587685976860768617686276863768647686576866768677686876869768707687176872768737687476875768767687776878768797688076881768827688376884768857688676887768887688976890768917689276893768947689576896768977689876899769007690176902769037690476905769067690776908769097691076911769127691376914769157691676917769187691976920769217692276923769247692576926769277692876929769307693176932769337693476935769367693776938769397694076941769427694376944769457694676947769487694976950769517695276953769547695576956769577695876959769607696176962769637696476965769667696776968769697697076971769727697376974769757697676977769787697976980769817698276983769847698576986769877698876989769907699176992769937699476995769967699776998769997700077001770027700377004770057700677007770087700977010770117701277013770147701577016770177701877019770207702177022770237702477025770267702777028770297703077031770327703377034770357703677037770387703977040770417704277043770447704577046770477704877049770507705177052770537705477055770567705777058770597706077061770627706377064770657706677067770687706977070770717707277073770747707577076770777707877079770807708177082770837708477085770867708777088770897709077091770927709377094770957709677097770987709977100771017710277103771047710577106771077710877109771107711177112771137711477115771167711777118771197712077121771227712377124771257712677127771287712977130771317713277133771347713577136771377713877139771407714177142771437714477145771467714777148771497715077151771527715377154771557715677157771587715977160771617716277163771647716577166771677716877169771707717177172771737717477175771767717777178771797718077181771827718377184771857718677187771887718977190771917719277193771947719577196771977719877199772007720177202772037720477205772067720777208772097721077211772127721377214772157721677217772187721977220772217722277223772247722577226772277722877229772307723177232772337723477235772367723777238772397724077241772427724377244772457724677247772487724977250772517725277253772547725577256772577725877259772607726177262772637726477265772667726777268772697727077271772727727377274772757727677277772787727977280772817728277283772847728577286772877728877289772907729177292772937729477295772967729777298772997730077301773027730377304773057730677307773087730977310773117731277313773147731577316773177731877319773207732177322773237732477325773267732777328773297733077331773327733377334773357733677337773387733977340773417734277343773447734577346773477734877349773507735177352773537735477355773567735777358773597736077361773627736377364773657736677367773687736977370773717737277373773747737577376773777737877379773807738177382773837738477385773867738777388773897739077391773927739377394773957739677397773987739977400774017740277403774047740577406774077740877409774107741177412774137741477415774167741777418774197742077421774227742377424774257742677427774287742977430774317743277433774347743577436774377743877439774407744177442774437744477445774467744777448774497745077451774527745377454774557745677457774587745977460774617746277463774647746577466774677746877469774707747177472774737747477475774767747777478774797748077481774827748377484774857748677487774887748977490774917749277493774947749577496774977749877499775007750177502775037750477505775067750777508775097751077511775127751377514775157751677517775187751977520775217752277523775247752577526775277752877529775307753177532775337753477535775367753777538775397754077541775427754377544775457754677547775487754977550775517755277553775547755577556775577755877559775607756177562775637756477565775667756777568775697757077571775727757377574775757757677577775787757977580775817758277583775847758577586775877758877589775907759177592775937759477595775967759777598775997760077601776027760377604776057760677607776087760977610776117761277613776147761577616776177761877619776207762177622776237762477625776267762777628776297763077631776327763377634776357763677637776387763977640776417764277643776447764577646776477764877649776507765177652776537765477655776567765777658776597766077661776627766377664776657766677667776687766977670776717767277673776747767577676776777767877679776807768177682776837768477685776867768777688776897769077691776927769377694776957769677697776987769977700777017770277703777047770577706777077770877709777107771177712777137771477715777167771777718777197772077721777227772377724777257772677727777287772977730777317773277733777347773577736777377773877739777407774177742777437774477745777467774777748777497775077751777527775377754777557775677757777587775977760777617776277763777647776577766777677776877769777707777177772777737777477775777767777777778777797778077781777827778377784777857778677787777887778977790777917779277793777947779577796777977779877799778007780177802778037780477805778067780777808778097781077811778127781377814778157781677817778187781977820778217782277823778247782577826778277782877829778307783177832778337783477835778367783777838778397784077841778427784377844778457784677847778487784977850778517785277853778547785577856778577785877859778607786177862778637786477865778667786777868778697787077871778727787377874778757787677877778787787977880778817788277883778847788577886778877788877889778907789177892778937789477895778967789777898778997790077901779027790377904779057790677907779087790977910779117791277913779147791577916779177791877919779207792177922779237792477925779267792777928779297793077931779327793377934779357793677937779387793977940779417794277943779447794577946779477794877949779507795177952779537795477955779567795777958779597796077961779627796377964779657796677967779687796977970779717797277973779747797577976779777797877979779807798177982779837798477985779867798777988779897799077991779927799377994779957799677997779987799978000780017800278003780047800578006780077800878009780107801178012780137801478015780167801778018780197802078021780227802378024780257802678027780287802978030780317803278033780347803578036780377803878039780407804178042780437804478045780467804778048780497805078051780527805378054780557805678057780587805978060780617806278063780647806578066780677806878069780707807178072780737807478075780767807778078780797808078081780827808378084780857808678087780887808978090780917809278093780947809578096780977809878099781007810178102781037810478105781067810778108781097811078111781127811378114781157811678117781187811978120781217812278123781247812578126781277812878129781307813178132781337813478135781367813778138781397814078141781427814378144781457814678147781487814978150781517815278153781547815578156781577815878159781607816178162781637816478165781667816778168781697817078171781727817378174781757817678177781787817978180781817818278183781847818578186781877818878189781907819178192781937819478195781967819778198781997820078201782027820378204782057820678207782087820978210782117821278213782147821578216782177821878219782207822178222782237822478225782267822778228782297823078231782327823378234782357823678237782387823978240782417824278243782447824578246782477824878249782507825178252782537825478255782567825778258782597826078261782627826378264782657826678267782687826978270782717827278273782747827578276782777827878279782807828178282782837828478285782867828778288782897829078291782927829378294782957829678297782987829978300783017830278303783047830578306783077830878309783107831178312783137831478315783167831778318783197832078321783227832378324783257832678327783287832978330783317833278333783347833578336783377833878339783407834178342783437834478345783467834778348783497835078351783527835378354783557835678357783587835978360783617836278363783647836578366783677836878369783707837178372783737837478375783767837778378783797838078381783827838378384783857838678387783887838978390783917839278393783947839578396783977839878399784007840178402784037840478405784067840778408784097841078411784127841378414784157841678417784187841978420784217842278423784247842578426784277842878429784307843178432784337843478435784367843778438784397844078441784427844378444784457844678447784487844978450784517845278453784547845578456784577845878459784607846178462784637846478465784667846778468784697847078471784727847378474784757847678477784787847978480784817848278483784847848578486784877848878489784907849178492784937849478495784967849778498784997850078501785027850378504785057850678507785087850978510785117851278513785147851578516785177851878519785207852178522785237852478525785267852778528785297853078531785327853378534785357853678537785387853978540785417854278543785447854578546785477854878549785507855178552785537855478555785567855778558785597856078561785627856378564785657856678567785687856978570785717857278573785747857578576785777857878579785807858178582785837858478585785867858778588785897859078591785927859378594785957859678597785987859978600786017860278603786047860578606786077860878609786107861178612786137861478615786167861778618786197862078621786227862378624786257862678627786287862978630786317863278633786347863578636786377863878639786407864178642786437864478645786467864778648786497865078651786527865378654786557865678657786587865978660786617866278663786647866578666786677866878669786707867178672786737867478675786767867778678786797868078681786827868378684786857868678687786887868978690786917869278693786947869578696786977869878699787007870178702787037870478705787067870778708787097871078711787127871378714787157871678717787187871978720787217872278723787247872578726787277872878729787307873178732787337873478735787367873778738787397874078741787427874378744787457874678747787487874978750787517875278753787547875578756787577875878759787607876178762787637876478765787667876778768787697877078771787727877378774787757877678777787787877978780787817878278783787847878578786787877878878789787907879178792787937879478795787967879778798787997880078801788027880378804788057880678807788087880978810788117881278813788147881578816788177881878819788207882178822788237882478825788267882778828788297883078831788327883378834788357883678837788387883978840788417884278843788447884578846788477884878849788507885178852788537885478855788567885778858788597886078861788627886378864788657886678867788687886978870788717887278873788747887578876788777887878879788807888178882788837888478885788867888778888788897889078891788927889378894788957889678897788987889978900789017890278903789047890578906789077890878909789107891178912789137891478915789167891778918789197892078921789227892378924789257892678927789287892978930789317893278933789347893578936789377893878939789407894178942789437894478945789467894778948789497895078951789527895378954789557895678957789587895978960789617896278963789647896578966789677896878969789707897178972789737897478975789767897778978789797898078981789827898378984789857898678987789887898978990789917899278993789947899578996789977899878999790007900179002790037900479005790067900779008790097901079011790127901379014790157901679017790187901979020790217902279023790247902579026790277902879029790307903179032790337903479035790367903779038790397904079041790427904379044790457904679047790487904979050790517905279053790547905579056790577905879059790607906179062790637906479065790667906779068790697907079071790727907379074790757907679077790787907979080790817908279083790847908579086790877908879089790907909179092790937909479095790967909779098790997910079101791027910379104791057910679107791087910979110791117911279113791147911579116791177911879119791207912179122791237912479125791267912779128791297913079131791327913379134791357913679137791387913979140791417914279143791447914579146791477914879149791507915179152791537915479155791567915779158791597916079161791627916379164791657916679167791687916979170791717917279173791747917579176791777917879179791807918179182791837918479185791867918779188791897919079191791927919379194791957919679197791987919979200792017920279203792047920579206792077920879209792107921179212792137921479215792167921779218792197922079221792227922379224792257922679227792287922979230792317923279233792347923579236792377923879239792407924179242792437924479245792467924779248792497925079251792527925379254792557925679257792587925979260792617926279263792647926579266792677926879269792707927179272792737927479275792767927779278792797928079281792827928379284792857928679287792887928979290792917929279293792947929579296792977929879299793007930179302793037930479305793067930779308793097931079311793127931379314793157931679317793187931979320793217932279323793247932579326793277932879329793307933179332793337933479335793367933779338793397934079341793427934379344793457934679347793487934979350793517935279353793547935579356793577935879359793607936179362793637936479365793667936779368793697937079371793727937379374793757937679377793787937979380793817938279383793847938579386793877938879389793907939179392793937939479395793967939779398793997940079401794027940379404794057940679407794087940979410794117941279413794147941579416794177941879419794207942179422794237942479425794267942779428794297943079431794327943379434794357943679437794387943979440794417944279443794447944579446794477944879449794507945179452794537945479455794567945779458794597946079461794627946379464794657946679467794687946979470794717947279473794747947579476794777947879479794807948179482794837948479485794867948779488794897949079491794927949379494794957949679497794987949979500795017950279503795047950579506795077950879509795107951179512795137951479515795167951779518795197952079521795227952379524795257952679527795287952979530795317953279533795347953579536795377953879539795407954179542795437954479545795467954779548795497955079551795527955379554795557955679557795587955979560795617956279563795647956579566795677956879569795707957179572795737957479575795767957779578795797958079581795827958379584795857958679587795887958979590795917959279593795947959579596795977959879599796007960179602796037960479605796067960779608796097961079611796127961379614796157961679617796187961979620796217962279623796247962579626796277962879629796307963179632796337963479635796367963779638796397964079641796427964379644796457964679647796487964979650796517965279653796547965579656796577965879659796607966179662796637966479665796667966779668796697967079671796727967379674796757967679677796787967979680796817968279683796847968579686796877968879689796907969179692796937969479695796967969779698796997970079701797027970379704797057970679707797087970979710797117971279713797147971579716797177971879719797207972179722797237972479725797267972779728797297973079731797327973379734797357973679737797387973979740797417974279743797447974579746797477974879749797507975179752797537975479755797567975779758797597976079761797627976379764797657976679767797687976979770797717977279773797747977579776797777977879779797807978179782797837978479785797867978779788797897979079791797927979379794797957979679797797987979979800798017980279803798047980579806798077980879809798107981179812798137981479815798167981779818798197982079821798227982379824798257982679827798287982979830798317983279833798347983579836798377983879839798407984179842798437984479845798467984779848798497985079851798527985379854798557985679857798587985979860798617986279863798647986579866798677986879869798707987179872798737987479875798767987779878798797988079881798827988379884798857988679887798887988979890798917989279893798947989579896798977989879899799007990179902799037990479905799067990779908799097991079911799127991379914799157991679917799187991979920799217992279923799247992579926799277992879929799307993179932799337993479935799367993779938799397994079941799427994379944799457994679947799487994979950799517995279953799547995579956799577995879959799607996179962799637996479965799667996779968799697997079971799727997379974799757997679977799787997979980799817998279983799847998579986799877998879989799907999179992799937999479995799967999779998799998000080001800028000380004800058000680007800088000980010800118001280013800148001580016800178001880019800208002180022800238002480025800268002780028800298003080031800328003380034800358003680037800388003980040800418004280043800448004580046800478004880049800508005180052800538005480055800568005780058800598006080061800628006380064800658006680067800688006980070800718007280073800748007580076800778007880079800808008180082800838008480085800868008780088800898009080091800928009380094800958009680097800988009980100801018010280103801048010580106801078010880109801108011180112801138011480115801168011780118801198012080121801228012380124801258012680127801288012980130801318013280133801348013580136801378013880139801408014180142801438014480145801468014780148801498015080151801528015380154801558015680157801588015980160801618016280163801648016580166801678016880169801708017180172801738017480175801768017780178801798018080181801828018380184801858018680187801888018980190801918019280193801948019580196801978019880199802008020180202802038020480205802068020780208802098021080211802128021380214802158021680217802188021980220802218022280223802248022580226802278022880229802308023180232802338023480235802368023780238802398024080241802428024380244802458024680247802488024980250802518025280253802548025580256802578025880259802608026180262802638026480265802668026780268802698027080271802728027380274802758027680277802788027980280802818028280283802848028580286802878028880289802908029180292802938029480295802968029780298802998030080301803028030380304803058030680307803088030980310803118031280313803148031580316803178031880319803208032180322803238032480325803268032780328803298033080331803328033380334803358033680337803388033980340803418034280343803448034580346803478034880349803508035180352803538035480355803568035780358803598036080361803628036380364803658036680367803688036980370803718037280373803748037580376803778037880379803808038180382803838038480385803868038780388803898039080391803928039380394803958039680397803988039980400804018040280403804048040580406804078040880409804108041180412804138041480415804168041780418804198042080421804228042380424804258042680427804288042980430804318043280433804348043580436804378043880439804408044180442804438044480445804468044780448804498045080451804528045380454804558045680457804588045980460804618046280463804648046580466804678046880469804708047180472804738047480475804768047780478804798048080481804828048380484804858048680487804888048980490804918049280493804948049580496804978049880499805008050180502805038050480505805068050780508805098051080511805128051380514805158051680517805188051980520805218052280523805248052580526805278052880529805308053180532805338053480535805368053780538805398054080541805428054380544805458054680547805488054980550805518055280553805548055580556805578055880559805608056180562805638056480565805668056780568805698057080571805728057380574805758057680577805788057980580805818058280583805848058580586805878058880589805908059180592805938059480595805968059780598805998060080601806028060380604806058060680607806088060980610806118061280613806148061580616806178061880619806208062180622806238062480625806268062780628806298063080631806328063380634806358063680637806388063980640806418064280643806448064580646806478064880649806508065180652806538065480655806568065780658806598066080661806628066380664806658066680667806688066980670806718067280673806748067580676806778067880679806808068180682806838068480685806868068780688806898069080691806928069380694806958069680697806988069980700807018070280703807048070580706807078070880709807108071180712807138071480715807168071780718807198072080721807228072380724807258072680727807288072980730807318073280733807348073580736807378073880739807408074180742807438074480745807468074780748807498075080751807528075380754807558075680757807588075980760807618076280763807648076580766807678076880769807708077180772807738077480775807768077780778807798078080781807828078380784807858078680787807888078980790807918079280793807948079580796807978079880799808008080180802808038080480805808068080780808808098081080811808128081380814808158081680817808188081980820808218082280823808248082580826808278082880829808308083180832808338083480835808368083780838808398084080841808428084380844808458084680847808488084980850808518085280853808548085580856808578085880859808608086180862808638086480865808668086780868808698087080871808728087380874808758087680877808788087980880808818088280883808848088580886808878088880889808908089180892808938089480895808968089780898808998090080901809028090380904809058090680907809088090980910809118091280913809148091580916809178091880919809208092180922809238092480925809268092780928809298093080931809328093380934809358093680937809388093980940809418094280943809448094580946809478094880949809508095180952809538095480955809568095780958809598096080961809628096380964809658096680967809688096980970809718097280973809748097580976809778097880979809808098180982809838098480985809868098780988809898099080991809928099380994809958099680997809988099981000810018100281003810048100581006810078100881009810108101181012810138101481015810168101781018810198102081021810228102381024810258102681027810288102981030810318103281033810348103581036810378103881039810408104181042810438104481045810468104781048810498105081051810528105381054810558105681057810588105981060810618106281063810648106581066810678106881069810708107181072810738107481075810768107781078810798108081081810828108381084810858108681087810888108981090810918109281093810948109581096810978109881099811008110181102811038110481105811068110781108811098111081111811128111381114811158111681117811188111981120811218112281123811248112581126811278112881129811308113181132811338113481135811368113781138811398114081141811428114381144811458114681147811488114981150811518115281153811548115581156811578115881159811608116181162811638116481165811668116781168811698117081171811728117381174811758117681177811788117981180811818118281183811848118581186811878118881189811908119181192811938119481195811968119781198811998120081201812028120381204812058120681207812088120981210812118121281213812148121581216812178121881219812208122181222812238122481225812268122781228812298123081231812328123381234812358123681237812388123981240812418124281243812448124581246812478124881249812508125181252812538125481255812568125781258812598126081261812628126381264812658126681267812688126981270812718127281273812748127581276812778127881279812808128181282812838128481285812868128781288812898129081291812928129381294812958129681297812988129981300813018130281303813048130581306813078130881309813108131181312813138131481315813168131781318813198132081321813228132381324813258132681327813288132981330813318133281333813348133581336813378133881339813408134181342813438134481345813468134781348813498135081351813528135381354813558135681357813588135981360813618136281363813648136581366813678136881369813708137181372813738137481375813768137781378813798138081381813828138381384813858138681387813888138981390813918139281393813948139581396813978139881399814008140181402814038140481405814068140781408814098141081411814128141381414814158141681417814188141981420814218142281423814248142581426814278142881429814308143181432814338143481435814368143781438814398144081441814428144381444814458144681447814488144981450814518145281453814548145581456814578145881459814608146181462814638146481465814668146781468814698147081471814728147381474814758147681477814788147981480814818148281483814848148581486814878148881489814908149181492814938149481495814968149781498814998150081501815028150381504815058150681507815088150981510815118151281513815148151581516815178151881519815208152181522815238152481525815268152781528815298153081531815328153381534815358153681537815388153981540815418154281543815448154581546815478154881549815508155181552815538155481555815568155781558815598156081561815628156381564815658156681567815688156981570815718157281573815748157581576815778157881579815808158181582815838158481585815868158781588815898159081591815928159381594815958159681597815988159981600816018160281603816048160581606816078160881609816108161181612816138161481615816168161781618816198162081621816228162381624816258162681627816288162981630816318163281633816348163581636816378163881639816408164181642816438164481645816468164781648816498165081651816528165381654816558165681657816588165981660816618166281663816648166581666816678166881669816708167181672816738167481675816768167781678816798168081681816828168381684816858168681687816888168981690816918169281693816948169581696816978169881699817008170181702817038170481705817068170781708817098171081711817128171381714817158171681717817188171981720817218172281723817248172581726817278172881729817308173181732817338173481735817368173781738817398174081741817428174381744817458174681747817488174981750817518175281753817548175581756817578175881759817608176181762817638176481765817668176781768817698177081771817728177381774817758177681777817788177981780817818178281783817848178581786817878178881789817908179181792817938179481795817968179781798817998180081801818028180381804818058180681807818088180981810818118181281813818148181581816818178181881819818208182181822818238182481825818268182781828818298183081831818328183381834818358183681837818388183981840818418184281843818448184581846818478184881849818508185181852818538185481855818568185781858818598186081861818628186381864818658186681867818688186981870818718187281873818748187581876818778187881879818808188181882818838188481885818868188781888818898189081891818928189381894818958189681897818988189981900819018190281903819048190581906819078190881909819108191181912819138191481915819168191781918819198192081921819228192381924819258192681927819288192981930819318193281933819348193581936819378193881939819408194181942819438194481945819468194781948819498195081951819528195381954819558195681957819588195981960819618196281963819648196581966819678196881969819708197181972819738197481975819768197781978819798198081981819828198381984819858198681987819888198981990819918199281993819948199581996819978199881999820008200182002820038200482005820068200782008820098201082011820128201382014820158201682017820188201982020820218202282023820248202582026820278202882029820308203182032820338203482035820368203782038820398204082041820428204382044820458204682047820488204982050820518205282053820548205582056820578205882059820608206182062820638206482065820668206782068820698207082071820728207382074820758207682077820788207982080820818208282083820848208582086820878208882089820908209182092820938209482095820968209782098820998210082101821028210382104821058210682107821088210982110821118211282113821148211582116821178211882119821208212182122821238212482125821268212782128821298213082131821328213382134821358213682137821388213982140821418214282143821448214582146821478214882149821508215182152821538215482155821568215782158821598216082161821628216382164821658216682167821688216982170821718217282173821748217582176821778217882179821808218182182821838218482185821868218782188821898219082191821928219382194821958219682197821988219982200822018220282203822048220582206822078220882209822108221182212822138221482215822168221782218822198222082221822228222382224822258222682227822288222982230822318223282233822348223582236822378223882239822408224182242822438224482245822468224782248822498225082251822528225382254822558225682257822588225982260822618226282263822648226582266822678226882269822708227182272822738227482275822768227782278822798228082281822828228382284822858228682287822888228982290822918229282293822948229582296822978229882299823008230182302823038230482305823068230782308823098231082311823128231382314823158231682317823188231982320823218232282323823248232582326823278232882329823308233182332823338233482335823368233782338823398234082341823428234382344823458234682347823488234982350823518235282353823548235582356823578235882359823608236182362823638236482365823668236782368823698237082371823728237382374823758237682377823788237982380823818238282383823848238582386823878238882389823908239182392823938239482395823968239782398823998240082401824028240382404824058240682407824088240982410824118241282413824148241582416824178241882419824208242182422824238242482425824268242782428824298243082431824328243382434824358243682437824388243982440824418244282443824448244582446824478244882449824508245182452824538245482455824568245782458824598246082461824628246382464824658246682467824688246982470824718247282473824748247582476824778247882479824808248182482824838248482485824868248782488824898249082491824928249382494824958249682497824988249982500825018250282503825048250582506825078250882509825108251182512825138251482515825168251782518825198252082521825228252382524825258252682527825288252982530825318253282533825348253582536825378253882539825408254182542825438254482545825468254782548825498255082551825528255382554825558255682557825588255982560825618256282563825648256582566825678256882569825708257182572825738257482575825768257782578825798258082581825828258382584825858258682587825888258982590825918259282593825948259582596825978259882599826008260182602826038260482605826068260782608826098261082611826128261382614826158261682617826188261982620826218262282623826248262582626826278262882629826308263182632826338263482635826368263782638826398264082641826428264382644826458264682647826488264982650826518265282653826548265582656826578265882659826608266182662826638266482665826668266782668826698267082671826728267382674826758267682677826788267982680826818268282683826848268582686826878268882689826908269182692826938269482695826968269782698826998270082701827028270382704827058270682707827088270982710827118271282713827148271582716827178271882719827208272182722827238272482725827268272782728827298273082731827328273382734827358273682737827388273982740827418274282743827448274582746827478274882749827508275182752827538275482755827568275782758827598276082761827628276382764827658276682767827688276982770827718277282773827748277582776827778277882779827808278182782827838278482785827868278782788827898279082791827928279382794827958279682797827988279982800828018280282803828048280582806828078280882809828108281182812828138281482815828168281782818828198282082821828228282382824828258282682827828288282982830828318283282833828348283582836828378283882839828408284182842828438284482845828468284782848828498285082851828528285382854828558285682857828588285982860828618286282863828648286582866828678286882869828708287182872828738287482875828768287782878828798288082881828828288382884828858288682887828888288982890828918289282893828948289582896828978289882899829008290182902829038290482905829068290782908829098291082911829128291382914829158291682917829188291982920829218292282923829248292582926829278292882929829308293182932829338293482935829368293782938829398294082941829428294382944829458294682947829488294982950829518295282953829548295582956829578295882959829608296182962829638296482965829668296782968829698297082971829728297382974829758297682977829788297982980829818298282983829848298582986829878298882989829908299182992829938299482995829968299782998829998300083001830028300383004830058300683007830088300983010830118301283013830148301583016830178301883019830208302183022830238302483025830268302783028830298303083031830328303383034830358303683037830388303983040830418304283043830448304583046830478304883049830508305183052830538305483055830568305783058830598306083061830628306383064830658306683067830688306983070830718307283073830748307583076830778307883079830808308183082830838308483085830868308783088830898309083091830928309383094830958309683097830988309983100831018310283103831048310583106831078310883109831108311183112831138311483115831168311783118831198312083121831228312383124831258312683127831288312983130831318313283133831348313583136831378313883139831408314183142831438314483145831468314783148831498315083151831528315383154831558315683157831588315983160831618316283163831648316583166831678316883169831708317183172831738317483175831768317783178831798318083181831828318383184831858318683187831888318983190831918319283193831948319583196831978319883199832008320183202832038320483205832068320783208832098321083211832128321383214832158321683217832188321983220832218322283223832248322583226832278322883229832308323183232832338323483235832368323783238832398324083241832428324383244832458324683247832488324983250832518325283253832548325583256832578325883259832608326183262832638326483265832668326783268832698327083271832728327383274832758327683277832788327983280832818328283283832848328583286832878328883289832908329183292832938329483295832968329783298832998330083301833028330383304833058330683307833088330983310833118331283313833148331583316833178331883319833208332183322833238332483325833268332783328833298333083331833328333383334833358333683337833388333983340833418334283343833448334583346833478334883349833508335183352833538335483355833568335783358833598336083361833628336383364833658336683367833688336983370833718337283373833748337583376833778337883379833808338183382833838338483385833868338783388833898339083391833928339383394833958339683397833988339983400834018340283403834048340583406834078340883409834108341183412834138341483415834168341783418834198342083421834228342383424834258342683427834288342983430834318343283433834348343583436834378343883439834408344183442834438344483445834468344783448834498345083451834528345383454834558345683457834588345983460834618346283463834648346583466834678346883469834708347183472834738347483475834768347783478834798348083481834828348383484834858348683487834888348983490834918349283493834948349583496834978349883499835008350183502835038350483505835068350783508835098351083511835128351383514835158351683517835188351983520835218352283523835248352583526835278352883529835308353183532835338353483535835368353783538835398354083541835428354383544835458354683547835488354983550835518355283553835548355583556835578355883559835608356183562835638356483565835668356783568835698357083571835728357383574835758357683577835788357983580835818358283583835848358583586835878358883589835908359183592835938359483595835968359783598835998360083601836028360383604836058360683607836088360983610836118361283613836148361583616836178361883619836208362183622836238362483625836268362783628836298363083631836328363383634836358363683637836388363983640836418364283643836448364583646836478364883649836508365183652836538365483655836568365783658836598366083661836628366383664836658366683667836688366983670836718367283673836748367583676836778367883679836808368183682836838368483685836868368783688836898369083691836928369383694836958369683697836988369983700837018370283703837048370583706837078370883709837108371183712837138371483715837168371783718837198372083721837228372383724837258372683727837288372983730837318373283733837348373583736837378373883739837408374183742837438374483745837468374783748837498375083751837528375383754837558375683757837588375983760837618376283763837648376583766837678376883769837708377183772837738377483775837768377783778837798378083781837828378383784837858378683787837888378983790837918379283793837948379583796837978379883799838008380183802838038380483805838068380783808838098381083811838128381383814838158381683817838188381983820838218382283823838248382583826838278382883829838308383183832838338383483835838368383783838838398384083841838428384383844838458384683847838488384983850838518385283853838548385583856838578385883859838608386183862838638386483865838668386783868838698387083871838728387383874838758387683877838788387983880838818388283883838848388583886838878388883889838908389183892838938389483895838968389783898838998390083901839028390383904839058390683907839088390983910839118391283913839148391583916839178391883919839208392183922839238392483925839268392783928839298393083931839328393383934839358393683937839388393983940839418394283943839448394583946839478394883949839508395183952839538395483955839568395783958839598396083961839628396383964839658396683967839688396983970839718397283973839748397583976839778397883979839808398183982839838398483985839868398783988839898399083991839928399383994839958399683997839988399984000840018400284003840048400584006840078400884009840108401184012840138401484015840168401784018840198402084021840228402384024840258402684027840288402984030840318403284033840348403584036840378403884039840408404184042840438404484045840468404784048840498405084051840528405384054840558405684057840588405984060840618406284063840648406584066840678406884069840708407184072840738407484075840768407784078840798408084081840828408384084840858408684087840888408984090840918409284093840948409584096840978409884099841008410184102841038410484105841068410784108841098411084111841128411384114841158411684117841188411984120841218412284123841248412584126841278412884129841308413184132841338413484135841368413784138841398414084141841428414384144841458414684147841488414984150841518415284153841548415584156841578415884159841608416184162841638416484165841668416784168841698417084171841728417384174841758417684177841788417984180841818418284183841848418584186841878418884189841908419184192841938419484195841968419784198841998420084201842028420384204842058420684207842088420984210842118421284213842148421584216842178421884219842208422184222842238422484225842268422784228842298423084231842328423384234842358423684237842388423984240842418424284243842448424584246842478424884249842508425184252842538425484255842568425784258842598426084261842628426384264842658426684267842688426984270842718427284273842748427584276842778427884279842808428184282842838428484285842868428784288842898429084291842928429384294842958429684297842988429984300843018430284303843048430584306843078430884309843108431184312843138431484315843168431784318843198432084321843228432384324843258432684327843288432984330843318433284333843348433584336843378433884339843408434184342843438434484345843468434784348843498435084351843528435384354843558435684357843588435984360843618436284363843648436584366843678436884369843708437184372843738437484375843768437784378843798438084381843828438384384843858438684387843888438984390843918439284393843948439584396843978439884399844008440184402844038440484405844068440784408844098441084411844128441384414844158441684417844188441984420844218442284423844248442584426844278442884429844308443184432844338443484435844368443784438844398444084441844428444384444844458444684447844488444984450844518445284453844548445584456844578445884459844608446184462844638446484465844668446784468844698447084471844728447384474844758447684477844788447984480844818448284483844848448584486844878448884489844908449184492844938449484495844968449784498844998450084501845028450384504845058450684507845088450984510845118451284513845148451584516845178451884519845208452184522845238452484525845268452784528845298453084531845328453384534845358453684537845388453984540845418454284543845448454584546845478454884549845508455184552845538455484555845568455784558845598456084561845628456384564845658456684567845688456984570845718457284573845748457584576845778457884579845808458184582845838458484585845868458784588845898459084591845928459384594845958459684597845988459984600846018460284603846048460584606846078460884609846108461184612846138461484615846168461784618846198462084621846228462384624846258462684627846288462984630846318463284633846348463584636846378463884639846408464184642846438464484645846468464784648846498465084651846528465384654846558465684657846588465984660846618466284663846648466584666846678466884669846708467184672846738467484675846768467784678846798468084681846828468384684846858468684687846888468984690846918469284693846948469584696846978469884699847008470184702847038470484705847068470784708847098471084711847128471384714847158471684717847188471984720847218472284723847248472584726847278472884729847308473184732847338473484735847368473784738847398474084741847428474384744847458474684747847488474984750847518475284753847548475584756847578475884759847608476184762847638476484765847668476784768847698477084771847728477384774847758477684777847788477984780847818478284783847848478584786847878478884789847908479184792847938479484795847968479784798847998480084801848028480384804848058480684807848088480984810848118481284813848148481584816848178481884819848208482184822848238482484825848268482784828848298483084831848328483384834848358483684837848388483984840848418484284843848448484584846848478484884849848508485184852848538485484855848568485784858848598486084861848628486384864848658486684867848688486984870848718487284873848748487584876848778487884879848808488184882848838488484885848868488784888848898489084891848928489384894848958489684897848988489984900849018490284903849048490584906849078490884909849108491184912849138491484915849168491784918849198492084921849228492384924849258492684927849288492984930849318493284933849348493584936849378493884939849408494184942849438494484945849468494784948849498495084951849528495384954849558495684957849588495984960849618496284963849648496584966849678496884969849708497184972849738497484975849768497784978849798498084981849828498384984849858498684987849888498984990849918499284993849948499584996849978499884999850008500185002850038500485005850068500785008850098501085011850128501385014850158501685017850188501985020850218502285023850248502585026850278502885029850308503185032850338503485035850368503785038850398504085041850428504385044850458504685047850488504985050850518505285053850548505585056850578505885059850608506185062850638506485065850668506785068850698507085071850728507385074850758507685077850788507985080850818508285083850848508585086850878508885089850908509185092850938509485095850968509785098850998510085101851028510385104851058510685107851088510985110851118511285113851148511585116851178511885119851208512185122851238512485125851268512785128851298513085131851328513385134851358513685137851388513985140851418514285143851448514585146851478514885149851508515185152851538515485155851568515785158851598516085161851628516385164851658516685167851688516985170851718517285173851748517585176851778517885179851808518185182851838518485185851868518785188851898519085191851928519385194851958519685197851988519985200852018520285203852048520585206852078520885209852108521185212852138521485215852168521785218852198522085221852228522385224852258522685227852288522985230852318523285233852348523585236852378523885239852408524185242852438524485245852468524785248852498525085251852528525385254852558525685257852588525985260852618526285263852648526585266852678526885269852708527185272852738527485275852768527785278852798528085281852828528385284852858528685287852888528985290852918529285293852948529585296852978529885299853008530185302853038530485305853068530785308853098531085311853128531385314853158531685317853188531985320853218532285323853248532585326853278532885329853308533185332853338533485335853368533785338853398534085341853428534385344853458534685347853488534985350853518535285353853548535585356853578535885359853608536185362853638536485365853668536785368853698537085371853728537385374853758537685377853788537985380853818538285383853848538585386853878538885389853908539185392853938539485395853968539785398853998540085401854028540385404854058540685407854088540985410854118541285413854148541585416854178541885419854208542185422854238542485425854268542785428854298543085431854328543385434854358543685437854388543985440854418544285443854448544585446854478544885449854508545185452854538545485455854568545785458854598546085461854628546385464854658546685467854688546985470854718547285473854748547585476854778547885479854808548185482854838548485485854868548785488854898549085491854928549385494854958549685497854988549985500855018550285503855048550585506855078550885509855108551185512855138551485515855168551785518855198552085521855228552385524855258552685527855288552985530855318553285533855348553585536855378553885539855408554185542855438554485545855468554785548855498555085551855528555385554855558555685557855588555985560855618556285563855648556585566855678556885569855708557185572855738557485575855768557785578855798558085581855828558385584855858558685587855888558985590855918559285593855948559585596855978559885599856008560185602856038560485605856068560785608856098561085611856128561385614856158561685617856188561985620856218562285623856248562585626856278562885629856308563185632856338563485635856368563785638856398564085641856428564385644856458564685647856488564985650856518565285653856548565585656856578565885659856608566185662856638566485665856668566785668856698567085671856728567385674856758567685677856788567985680856818568285683856848568585686856878568885689856908569185692856938569485695856968569785698856998570085701857028570385704857058570685707857088570985710857118571285713857148571585716857178571885719857208572185722857238572485725857268572785728857298573085731857328573385734857358573685737857388573985740857418574285743857448574585746857478574885749857508575185752857538575485755857568575785758857598576085761857628576385764857658576685767857688576985770857718577285773857748577585776857778577885779857808578185782857838578485785857868578785788857898579085791857928579385794857958579685797857988579985800858018580285803858048580585806858078580885809858108581185812858138581485815858168581785818858198582085821858228582385824858258582685827858288582985830858318583285833858348583585836858378583885839858408584185842858438584485845858468584785848858498585085851858528585385854858558585685857858588585985860858618586285863858648586585866858678586885869858708587185872858738587485875858768587785878858798588085881858828588385884858858588685887858888588985890858918589285893858948589585896858978589885899859008590185902859038590485905859068590785908859098591085911859128591385914859158591685917859188591985920859218592285923859248592585926859278592885929859308593185932859338593485935859368593785938859398594085941859428594385944859458594685947859488594985950859518595285953859548595585956859578595885959859608596185962859638596485965859668596785968859698597085971859728597385974859758597685977859788597985980859818598285983859848598585986859878598885989859908599185992859938599485995859968599785998859998600086001860028600386004860058600686007860088600986010860118601286013860148601586016860178601886019860208602186022860238602486025860268602786028860298603086031860328603386034860358603686037860388603986040860418604286043860448604586046860478604886049860508605186052860538605486055860568605786058860598606086061860628606386064860658606686067860688606986070860718607286073860748607586076860778607886079860808608186082860838608486085860868608786088860898609086091860928609386094860958609686097860988609986100861018610286103861048610586106861078610886109861108611186112861138611486115861168611786118861198612086121861228612386124861258612686127861288612986130861318613286133861348613586136861378613886139861408614186142861438614486145861468614786148861498615086151861528615386154861558615686157861588615986160861618616286163861648616586166861678616886169861708617186172861738617486175861768617786178861798618086181861828618386184861858618686187861888618986190861918619286193861948619586196861978619886199862008620186202862038620486205862068620786208862098621086211862128621386214862158621686217862188621986220862218622286223862248622586226862278622886229862308623186232862338623486235862368623786238862398624086241862428624386244862458624686247862488624986250862518625286253862548625586256862578625886259862608626186262862638626486265862668626786268862698627086271862728627386274862758627686277862788627986280862818628286283862848628586286862878628886289862908629186292862938629486295862968629786298862998630086301863028630386304863058630686307863088630986310863118631286313863148631586316863178631886319863208632186322863238632486325863268632786328863298633086331863328633386334863358633686337863388633986340863418634286343863448634586346863478634886349863508635186352863538635486355863568635786358863598636086361863628636386364863658636686367863688636986370863718637286373863748637586376863778637886379863808638186382863838638486385863868638786388863898639086391863928639386394863958639686397863988639986400864018640286403864048640586406864078640886409864108641186412864138641486415864168641786418864198642086421864228642386424864258642686427864288642986430864318643286433864348643586436864378643886439864408644186442864438644486445864468644786448864498645086451864528645386454864558645686457864588645986460864618646286463864648646586466864678646886469864708647186472864738647486475864768647786478864798648086481864828648386484864858648686487864888648986490864918649286493864948649586496864978649886499865008650186502865038650486505865068650786508865098651086511865128651386514865158651686517865188651986520865218652286523865248652586526865278652886529865308653186532865338653486535865368653786538865398654086541865428654386544865458654686547865488654986550865518655286553865548655586556865578655886559865608656186562865638656486565865668656786568865698657086571865728657386574865758657686577865788657986580865818658286583865848658586586865878658886589865908659186592865938659486595865968659786598865998660086601866028660386604866058660686607866088660986610866118661286613866148661586616866178661886619866208662186622866238662486625866268662786628866298663086631866328663386634866358663686637866388663986640866418664286643866448664586646866478664886649866508665186652866538665486655866568665786658866598666086661866628666386664866658666686667866688666986670866718667286673866748667586676866778667886679866808668186682866838668486685866868668786688866898669086691866928669386694866958669686697866988669986700867018670286703867048670586706867078670886709867108671186712867138671486715867168671786718867198672086721867228672386724867258672686727867288672986730867318673286733867348673586736867378673886739867408674186742867438674486745867468674786748867498675086751867528675386754867558675686757867588675986760867618676286763867648676586766867678676886769867708677186772867738677486775867768677786778867798678086781867828678386784867858678686787867888678986790867918679286793867948679586796867978679886799868008680186802868038680486805868068680786808868098681086811868128681386814868158681686817868188681986820868218682286823868248682586826868278682886829868308683186832868338683486835868368683786838868398684086841868428684386844868458684686847868488684986850868518685286853868548685586856868578685886859868608686186862868638686486865868668686786868868698687086871868728687386874868758687686877868788687986880868818688286883868848688586886868878688886889868908689186892868938689486895868968689786898868998690086901869028690386904869058690686907869088690986910869118691286913869148691586916869178691886919869208692186922869238692486925869268692786928869298693086931869328693386934869358693686937869388693986940869418694286943869448694586946869478694886949869508695186952869538695486955869568695786958869598696086961869628696386964869658696686967869688696986970869718697286973869748697586976869778697886979869808698186982869838698486985869868698786988869898699086991869928699386994869958699686997869988699987000870018700287003870048700587006870078700887009870108701187012870138701487015870168701787018870198702087021870228702387024870258702687027870288702987030870318703287033870348703587036870378703887039870408704187042870438704487045870468704787048870498705087051870528705387054870558705687057870588705987060870618706287063870648706587066870678706887069870708707187072870738707487075870768707787078870798708087081870828708387084870858708687087870888708987090870918709287093870948709587096870978709887099871008710187102871038710487105871068710787108871098711087111871128711387114871158711687117871188711987120871218712287123871248712587126871278712887129871308713187132871338713487135871368713787138871398714087141871428714387144871458714687147871488714987150871518715287153871548715587156871578715887159871608716187162871638716487165871668716787168871698717087171871728717387174871758717687177871788717987180871818718287183871848718587186871878718887189871908719187192871938719487195871968719787198871998720087201872028720387204872058720687207872088720987210872118721287213872148721587216872178721887219872208722187222872238722487225872268722787228872298723087231872328723387234872358723687237872388723987240872418724287243872448724587246872478724887249872508725187252872538725487255872568725787258872598726087261872628726387264872658726687267872688726987270872718727287273872748727587276872778727887279872808728187282872838728487285872868728787288872898729087291872928729387294872958729687297872988729987300873018730287303873048730587306873078730887309873108731187312873138731487315873168731787318873198732087321873228732387324873258732687327873288732987330873318733287333873348733587336873378733887339873408734187342873438734487345873468734787348873498735087351873528735387354873558735687357873588735987360873618736287363873648736587366873678736887369873708737187372873738737487375873768737787378873798738087381873828738387384873858738687387873888738987390873918739287393873948739587396873978739887399874008740187402874038740487405874068740787408874098741087411874128741387414874158741687417874188741987420874218742287423874248742587426874278742887429874308743187432874338743487435874368743787438874398744087441874428744387444874458744687447874488744987450874518745287453874548745587456874578745887459874608746187462874638746487465874668746787468874698747087471874728747387474874758747687477874788747987480874818748287483874848748587486874878748887489874908749187492874938749487495874968749787498874998750087501875028750387504875058750687507875088750987510875118751287513875148751587516875178751887519875208752187522875238752487525875268752787528875298753087531875328753387534875358753687537875388753987540875418754287543875448754587546875478754887549875508755187552875538755487555875568755787558875598756087561875628756387564875658756687567875688756987570875718757287573875748757587576875778757887579875808758187582875838758487585875868758787588875898759087591875928759387594875958759687597875988759987600876018760287603876048760587606876078760887609876108761187612876138761487615876168761787618876198762087621876228762387624876258762687627876288762987630876318763287633876348763587636876378763887639876408764187642876438764487645876468764787648876498765087651876528765387654876558765687657876588765987660876618766287663876648766587666876678766887669876708767187672876738767487675876768767787678876798768087681876828768387684876858768687687876888768987690876918769287693876948769587696876978769887699877008770187702877038770487705877068770787708877098771087711877128771387714877158771687717877188771987720877218772287723877248772587726877278772887729877308773187732877338773487735877368773787738877398774087741877428774387744877458774687747877488774987750877518775287753877548775587756877578775887759877608776187762877638776487765877668776787768877698777087771877728777387774877758777687777877788777987780877818778287783877848778587786877878778887789877908779187792877938779487795877968779787798877998780087801878028780387804878058780687807878088780987810878118781287813878148781587816878178781887819878208782187822878238782487825878268782787828878298783087831878328783387834878358783687837878388783987840878418784287843878448784587846878478784887849878508785187852878538785487855878568785787858878598786087861878628786387864878658786687867878688786987870878718787287873878748787587876878778787887879878808788187882878838788487885878868788787888878898789087891878928789387894878958789687897878988789987900879018790287903879048790587906879078790887909879108791187912879138791487915879168791787918879198792087921879228792387924879258792687927879288792987930879318793287933879348793587936879378793887939879408794187942879438794487945879468794787948879498795087951879528795387954879558795687957879588795987960879618796287963879648796587966879678796887969879708797187972879738797487975879768797787978879798798087981879828798387984879858798687987879888798987990879918799287993879948799587996879978799887999880008800188002880038800488005880068800788008880098801088011880128801388014880158801688017880188801988020880218802288023880248802588026880278802888029880308803188032880338803488035880368803788038880398804088041880428804388044880458804688047880488804988050880518805288053880548805588056880578805888059880608806188062880638806488065880668806788068880698807088071880728807388074880758807688077880788807988080880818808288083880848808588086880878808888089880908809188092880938809488095880968809788098880998810088101881028810388104881058810688107881088810988110881118811288113881148811588116881178811888119881208812188122881238812488125881268812788128881298813088131881328813388134881358813688137881388813988140881418814288143881448814588146881478814888149881508815188152881538815488155881568815788158881598816088161881628816388164881658816688167881688816988170881718817288173881748817588176881778817888179881808818188182881838818488185881868818788188881898819088191881928819388194881958819688197881988819988200882018820288203882048820588206882078820888209882108821188212882138821488215882168821788218882198822088221882228822388224882258822688227882288822988230882318823288233882348823588236882378823888239882408824188242882438824488245882468824788248882498825088251882528825388254882558825688257882588825988260882618826288263882648826588266882678826888269882708827188272882738827488275882768827788278882798828088281882828828388284882858828688287882888828988290882918829288293882948829588296882978829888299883008830188302883038830488305883068830788308883098831088311883128831388314883158831688317883188831988320883218832288323883248832588326883278832888329883308833188332883338833488335883368833788338883398834088341883428834388344883458834688347883488834988350883518835288353883548835588356883578835888359883608836188362883638836488365883668836788368883698837088371883728837388374883758837688377883788837988380883818838288383883848838588386883878838888389883908839188392883938839488395883968839788398883998840088401884028840388404884058840688407884088840988410884118841288413884148841588416884178841888419884208842188422884238842488425884268842788428884298843088431884328843388434884358843688437884388843988440884418844288443884448844588446884478844888449884508845188452884538845488455884568845788458884598846088461884628846388464884658846688467884688846988470884718847288473884748847588476884778847888479884808848188482884838848488485884868848788488884898849088491884928849388494884958849688497884988849988500885018850288503885048850588506885078850888509885108851188512885138851488515885168851788518885198852088521885228852388524885258852688527885288852988530885318853288533885348853588536885378853888539885408854188542885438854488545885468854788548885498855088551885528855388554885558855688557885588855988560885618856288563885648856588566885678856888569885708857188572885738857488575885768857788578885798858088581885828858388584885858858688587885888858988590885918859288593885948859588596885978859888599886008860188602886038860488605886068860788608886098861088611886128861388614886158861688617886188861988620886218862288623886248862588626886278862888629886308863188632886338863488635886368863788638886398864088641886428864388644886458864688647886488864988650886518865288653886548865588656886578865888659886608866188662886638866488665886668866788668886698867088671886728867388674886758867688677886788867988680886818868288683886848868588686886878868888689886908869188692886938869488695886968869788698886998870088701887028870388704887058870688707887088870988710887118871288713887148871588716887178871888719887208872188722887238872488725887268872788728887298873088731887328873388734887358873688737887388873988740887418874288743887448874588746887478874888749887508875188752887538875488755887568875788758887598876088761887628876388764887658876688767887688876988770887718877288773887748877588776887778877888779887808878188782887838878488785887868878788788887898879088791887928879388794887958879688797887988879988800888018880288803888048880588806888078880888809888108881188812888138881488815888168881788818888198882088821888228882388824888258882688827888288882988830888318883288833888348883588836888378883888839888408884188842888438884488845888468884788848888498885088851888528885388854888558885688857888588885988860888618886288863888648886588866888678886888869888708887188872888738887488875888768887788878888798888088881888828888388884888858888688887888888888988890888918889288893888948889588896888978889888899889008890188902889038890488905889068890788908889098891088911889128891388914889158891688917889188891988920889218892288923889248892588926889278892888929889308893188932889338893488935889368893788938889398894088941889428894388944889458894688947889488894988950889518895288953889548895588956889578895888959889608896188962889638896488965889668896788968889698897088971889728897388974889758897688977889788897988980889818898288983889848898588986889878898888989889908899188992889938899488995889968899788998889998900089001890028900389004890058900689007890088900989010890118901289013890148901589016890178901889019890208902189022890238902489025890268902789028890298903089031890328903389034890358903689037890388903989040890418904289043890448904589046890478904889049890508905189052890538905489055890568905789058890598906089061890628906389064890658906689067890688906989070890718907289073890748907589076890778907889079890808908189082890838908489085890868908789088890898909089091890928909389094890958909689097890988909989100891018910289103891048910589106891078910889109891108911189112891138911489115891168911789118891198912089121891228912389124891258912689127891288912989130891318913289133891348913589136891378913889139891408914189142891438914489145891468914789148891498915089151891528915389154891558915689157891588915989160891618916289163891648916589166891678916889169891708917189172891738917489175891768917789178891798918089181891828918389184891858918689187891888918989190891918919289193891948919589196891978919889199892008920189202892038920489205892068920789208892098921089211892128921389214892158921689217892188921989220892218922289223892248922589226892278922889229892308923189232892338923489235892368923789238892398924089241892428924389244892458924689247892488924989250892518925289253892548925589256892578925889259892608926189262892638926489265892668926789268892698927089271892728927389274892758927689277892788927989280892818928289283892848928589286892878928889289892908929189292892938929489295892968929789298892998930089301893028930389304893058930689307893088930989310893118931289313893148931589316893178931889319893208932189322893238932489325893268932789328893298933089331893328933389334893358933689337893388933989340893418934289343893448934589346893478934889349893508935189352893538935489355893568935789358893598936089361893628936389364893658936689367893688936989370893718937289373893748937589376893778937889379893808938189382893838938489385893868938789388893898939089391893928939389394893958939689397893988939989400894018940289403894048940589406894078940889409894108941189412894138941489415894168941789418894198942089421894228942389424894258942689427894288942989430894318943289433894348943589436894378943889439894408944189442894438944489445894468944789448894498945089451894528945389454894558945689457894588945989460894618946289463894648946589466894678946889469894708947189472894738947489475894768947789478894798948089481894828948389484894858948689487894888948989490894918949289493894948949589496894978949889499895008950189502895038950489505895068950789508895098951089511895128951389514895158951689517895188951989520895218952289523895248952589526895278952889529895308953189532895338953489535895368953789538895398954089541895428954389544895458954689547895488954989550895518955289553895548955589556895578955889559895608956189562895638956489565895668956789568895698957089571895728957389574895758957689577895788957989580895818958289583895848958589586895878958889589895908959189592895938959489595895968959789598895998960089601896028960389604896058960689607896088960989610896118961289613896148961589616896178961889619896208962189622896238962489625896268962789628896298963089631896328963389634896358963689637896388963989640896418964289643896448964589646896478964889649896508965189652896538965489655896568965789658896598966089661896628966389664896658966689667896688966989670896718967289673896748967589676896778967889679896808968189682896838968489685896868968789688896898969089691896928969389694896958969689697896988969989700897018970289703897048970589706897078970889709897108971189712897138971489715897168971789718897198972089721897228972389724897258972689727897288972989730897318973289733897348973589736897378973889739897408974189742897438974489745897468974789748897498975089751897528975389754897558975689757897588975989760897618976289763897648976589766897678976889769897708977189772897738977489775897768977789778897798978089781897828978389784897858978689787897888978989790897918979289793897948979589796897978979889799898008980189802898038980489805898068980789808898098981089811898128981389814898158981689817898188981989820898218982289823898248982589826898278982889829898308983189832898338983489835898368983789838898398984089841898428984389844898458984689847898488984989850898518985289853898548985589856898578985889859898608986189862898638986489865898668986789868898698987089871898728987389874898758987689877898788987989880898818988289883898848988589886898878988889889898908989189892898938989489895898968989789898898998990089901899028990389904899058990689907899088990989910899118991289913899148991589916899178991889919899208992189922899238992489925899268992789928899298993089931899328993389934899358993689937899388993989940899418994289943899448994589946899478994889949899508995189952899538995489955899568995789958899598996089961899628996389964899658996689967899688996989970899718997289973899748997589976899778997889979899808998189982899838998489985899868998789988899898999089991899928999389994899958999689997899988999990000900019000290003900049000590006900079000890009900109001190012900139001490015900169001790018900199002090021900229002390024900259002690027900289002990030900319003290033900349003590036900379003890039900409004190042900439004490045900469004790048900499005090051900529005390054900559005690057900589005990060900619006290063900649006590066900679006890069900709007190072900739007490075900769007790078900799008090081900829008390084900859008690087900889008990090900919009290093900949009590096900979009890099901009010190102901039010490105901069010790108901099011090111901129011390114901159011690117901189011990120901219012290123901249012590126901279012890129901309013190132901339013490135901369013790138901399014090141901429014390144901459014690147901489014990150901519015290153901549015590156901579015890159901609016190162901639016490165901669016790168901699017090171901729017390174901759017690177901789017990180901819018290183901849018590186901879018890189901909019190192901939019490195901969019790198901999020090201902029020390204902059020690207902089020990210902119021290213902149021590216902179021890219902209022190222902239022490225902269022790228902299023090231902329023390234902359023690237902389023990240902419024290243902449024590246902479024890249902509025190252902539025490255902569025790258902599026090261902629026390264902659026690267902689026990270902719027290273902749027590276902779027890279902809028190282902839028490285902869028790288902899029090291902929029390294902959029690297902989029990300903019030290303903049030590306903079030890309903109031190312903139031490315903169031790318903199032090321903229032390324903259032690327903289032990330903319033290333903349033590336903379033890339903409034190342903439034490345903469034790348903499035090351903529035390354903559035690357903589035990360903619036290363903649036590366903679036890369903709037190372903739037490375903769037790378903799038090381903829038390384903859038690387903889038990390903919039290393903949039590396903979039890399904009040190402904039040490405904069040790408904099041090411904129041390414904159041690417904189041990420904219042290423904249042590426904279042890429904309043190432904339043490435904369043790438904399044090441904429044390444904459044690447904489044990450904519045290453904549045590456904579045890459904609046190462904639046490465904669046790468904699047090471904729047390474904759047690477904789047990480904819048290483904849048590486904879048890489904909049190492904939049490495904969049790498904999050090501905029050390504905059050690507905089050990510905119051290513905149051590516905179051890519905209052190522905239052490525905269052790528905299053090531905329053390534905359053690537905389053990540905419054290543905449054590546905479054890549905509055190552905539055490555905569055790558905599056090561905629056390564905659056690567905689056990570905719057290573905749057590576905779057890579905809058190582905839058490585905869058790588905899059090591905929059390594905959059690597905989059990600906019060290603906049060590606906079060890609906109061190612906139061490615906169061790618906199062090621906229062390624906259062690627906289062990630906319063290633906349063590636906379063890639906409064190642906439064490645906469064790648906499065090651906529065390654906559065690657906589065990660906619066290663906649066590666906679066890669906709067190672906739067490675906769067790678906799068090681906829068390684906859068690687906889068990690906919069290693906949069590696906979069890699907009070190702907039070490705907069070790708907099071090711907129071390714907159071690717907189071990720907219072290723907249072590726907279072890729907309073190732907339073490735907369073790738907399074090741907429074390744907459074690747907489074990750907519075290753907549075590756907579075890759907609076190762907639076490765907669076790768907699077090771907729077390774907759077690777907789077990780907819078290783907849078590786907879078890789907909079190792907939079490795907969079790798907999080090801908029080390804908059080690807908089080990810908119081290813908149081590816908179081890819908209082190822908239082490825908269082790828908299083090831908329083390834908359083690837908389083990840908419084290843908449084590846908479084890849908509085190852908539085490855908569085790858908599086090861908629086390864908659086690867908689086990870908719087290873908749087590876908779087890879908809088190882908839088490885908869088790888908899089090891908929089390894908959089690897908989089990900909019090290903909049090590906909079090890909909109091190912909139091490915909169091790918909199092090921909229092390924909259092690927909289092990930909319093290933909349093590936909379093890939909409094190942909439094490945909469094790948909499095090951909529095390954909559095690957909589095990960909619096290963909649096590966909679096890969909709097190972909739097490975909769097790978909799098090981909829098390984909859098690987909889098990990909919099290993909949099590996909979099890999910009100191002910039100491005910069100791008910099101091011910129101391014910159101691017910189101991020910219102291023910249102591026910279102891029910309103191032910339103491035910369103791038910399104091041910429104391044910459104691047910489104991050910519105291053910549105591056910579105891059910609106191062910639106491065910669106791068910699107091071910729107391074910759107691077910789107991080910819108291083910849108591086910879108891089910909109191092910939109491095910969109791098910999110091101911029110391104911059110691107911089110991110911119111291113911149111591116911179111891119911209112191122911239112491125911269112791128911299113091131911329113391134911359113691137911389113991140911419114291143911449114591146911479114891149911509115191152911539115491155911569115791158911599116091161911629116391164911659116691167911689116991170911719117291173911749117591176911779117891179911809118191182911839118491185911869118791188911899119091191911929119391194911959119691197911989119991200912019120291203912049120591206912079120891209912109121191212912139121491215912169121791218912199122091221912229122391224912259122691227912289122991230912319123291233912349123591236912379123891239912409124191242912439124491245912469124791248912499125091251912529125391254912559125691257912589125991260912619126291263912649126591266912679126891269912709127191272912739127491275912769127791278912799128091281912829128391284912859128691287912889128991290912919129291293912949129591296912979129891299913009130191302913039130491305913069130791308913099131091311913129131391314913159131691317913189131991320913219132291323913249132591326913279132891329913309133191332913339133491335913369133791338913399134091341913429134391344913459134691347913489134991350913519135291353913549135591356913579135891359913609136191362913639136491365913669136791368913699137091371913729137391374913759137691377913789137991380913819138291383913849138591386913879138891389913909139191392913939139491395913969139791398913999140091401914029140391404914059140691407914089140991410914119141291413914149141591416914179141891419914209142191422914239142491425914269142791428914299143091431914329143391434914359143691437914389143991440914419144291443914449144591446914479144891449914509145191452914539145491455914569145791458914599146091461914629146391464914659146691467914689146991470914719147291473914749147591476914779147891479914809148191482914839148491485914869148791488914899149091491914929149391494914959149691497914989149991500915019150291503915049150591506915079150891509915109151191512915139151491515915169151791518915199152091521915229152391524915259152691527915289152991530915319153291533915349153591536915379153891539915409154191542915439154491545915469154791548915499155091551915529155391554915559155691557915589155991560915619156291563915649156591566915679156891569915709157191572915739157491575915769157791578915799158091581915829158391584915859158691587915889158991590915919159291593915949159591596915979159891599916009160191602916039160491605916069160791608916099161091611916129161391614916159161691617916189161991620916219162291623916249162591626916279162891629916309163191632916339163491635916369163791638916399164091641916429164391644916459164691647916489164991650916519165291653916549165591656916579165891659916609166191662916639166491665916669166791668916699167091671916729167391674916759167691677916789167991680916819168291683916849168591686916879168891689916909169191692916939169491695916969169791698916999170091701917029170391704917059170691707917089170991710917119171291713917149171591716917179171891719917209172191722917239172491725917269172791728917299173091731917329173391734917359173691737917389173991740917419174291743917449174591746917479174891749917509175191752917539175491755917569175791758917599176091761917629176391764917659176691767917689176991770917719177291773917749177591776917779177891779917809178191782917839178491785917869178791788917899179091791917929179391794917959179691797917989179991800918019180291803918049180591806918079180891809918109181191812918139181491815918169181791818918199182091821918229182391824918259182691827918289182991830918319183291833918349183591836918379183891839918409184191842918439184491845918469184791848918499185091851918529185391854918559185691857918589185991860918619186291863918649186591866918679186891869918709187191872918739187491875918769187791878918799188091881918829188391884918859188691887918889188991890918919189291893918949189591896918979189891899919009190191902919039190491905919069190791908919099191091911919129191391914919159191691917919189191991920919219192291923919249192591926919279192891929919309193191932919339193491935919369193791938919399194091941919429194391944919459194691947919489194991950919519195291953919549195591956919579195891959919609196191962919639196491965919669196791968919699197091971919729197391974919759197691977919789197991980919819198291983919849198591986919879198891989919909199191992919939199491995919969199791998919999200092001920029200392004920059200692007920089200992010920119201292013920149201592016920179201892019920209202192022920239202492025920269202792028920299203092031920329203392034920359203692037920389203992040920419204292043920449204592046920479204892049920509205192052920539205492055920569205792058920599206092061920629206392064920659206692067920689206992070920719207292073920749207592076920779207892079920809208192082920839208492085920869208792088920899209092091920929209392094920959209692097920989209992100921019210292103921049210592106921079210892109921109211192112921139211492115921169211792118921199212092121921229212392124921259212692127921289212992130921319213292133921349213592136921379213892139921409214192142921439214492145921469214792148921499215092151921529215392154921559215692157921589215992160921619216292163921649216592166921679216892169921709217192172921739217492175921769217792178921799218092181921829218392184921859218692187921889218992190921919219292193921949219592196921979219892199922009220192202922039220492205922069220792208922099221092211922129221392214922159221692217922189221992220922219222292223922249222592226922279222892229922309223192232922339223492235922369223792238922399224092241922429224392244922459224692247922489224992250922519225292253922549225592256922579225892259922609226192262922639226492265922669226792268922699227092271922729227392274922759227692277922789227992280922819228292283922849228592286922879228892289922909229192292922939229492295922969229792298922999230092301923029230392304923059230692307923089230992310923119231292313923149231592316923179231892319923209232192322923239232492325923269232792328923299233092331923329233392334923359233692337923389233992340923419234292343923449234592346923479234892349923509235192352923539235492355923569235792358923599236092361923629236392364923659236692367923689236992370923719237292373923749237592376923779237892379923809238192382923839238492385923869238792388923899239092391923929239392394923959239692397923989239992400924019240292403924049240592406924079240892409924109241192412924139241492415924169241792418924199242092421924229242392424924259242692427924289242992430924319243292433924349243592436924379243892439924409244192442924439244492445924469244792448924499245092451924529245392454924559245692457924589245992460924619246292463924649246592466924679246892469924709247192472924739247492475924769247792478924799248092481924829248392484924859248692487924889248992490924919249292493924949249592496924979249892499925009250192502925039250492505925069250792508925099251092511925129251392514925159251692517925189251992520925219252292523925249252592526925279252892529925309253192532925339253492535925369253792538925399254092541925429254392544925459254692547925489254992550925519255292553925549255592556925579255892559925609256192562925639256492565925669256792568925699257092571925729257392574925759257692577925789257992580925819258292583925849258592586925879258892589925909259192592925939259492595925969259792598925999260092601926029260392604926059260692607926089260992610926119261292613926149261592616926179261892619926209262192622926239262492625926269262792628926299263092631926329263392634926359263692637926389263992640926419264292643926449264592646926479264892649926509265192652926539265492655926569265792658926599266092661926629266392664926659266692667926689266992670926719267292673926749267592676926779267892679926809268192682926839268492685926869268792688926899269092691926929269392694926959269692697926989269992700927019270292703927049270592706927079270892709927109271192712927139271492715927169271792718927199272092721927229272392724927259272692727927289272992730927319273292733927349273592736927379273892739927409274192742927439274492745927469274792748927499275092751927529275392754927559275692757927589275992760927619276292763927649276592766927679276892769927709277192772927739277492775927769277792778927799278092781927829278392784927859278692787927889278992790927919279292793927949279592796927979279892799928009280192802928039280492805928069280792808928099281092811928129281392814928159281692817928189281992820928219282292823928249282592826928279282892829928309283192832928339283492835928369283792838928399284092841928429284392844928459284692847928489284992850928519285292853928549285592856928579285892859928609286192862928639286492865928669286792868928699287092871928729287392874928759287692877928789287992880928819288292883928849288592886928879288892889928909289192892928939289492895928969289792898928999290092901929029290392904929059290692907929089290992910929119291292913929149291592916929179291892919929209292192922929239292492925929269292792928929299293092931929329293392934929359293692937929389293992940929419294292943929449294592946929479294892949929509295192952929539295492955929569295792958929599296092961929629296392964929659296692967929689296992970929719297292973929749297592976929779297892979929809298192982929839298492985929869298792988929899299092991929929299392994929959299692997929989299993000930019300293003930049300593006930079300893009930109301193012930139301493015930169301793018930199302093021930229302393024930259302693027930289302993030930319303293033930349303593036930379303893039930409304193042930439304493045930469304793048930499305093051930529305393054930559305693057930589305993060930619306293063930649306593066930679306893069930709307193072930739307493075930769307793078930799308093081930829308393084930859308693087930889308993090930919309293093930949309593096930979309893099931009310193102931039310493105931069310793108931099311093111931129311393114931159311693117931189311993120931219312293123931249312593126931279312893129931309313193132931339313493135931369313793138931399314093141931429314393144931459314693147931489314993150931519315293153931549315593156931579315893159931609316193162931639316493165931669316793168931699317093171931729317393174931759317693177931789317993180931819318293183931849318593186931879318893189931909319193192931939319493195931969319793198931999320093201932029320393204932059320693207932089320993210932119321293213932149321593216932179321893219932209322193222932239322493225932269322793228932299323093231932329323393234932359323693237932389323993240932419324293243932449324593246932479324893249932509325193252932539325493255932569325793258932599326093261932629326393264932659326693267932689326993270932719327293273932749327593276932779327893279932809328193282932839328493285932869328793288932899329093291932929329393294932959329693297932989329993300933019330293303933049330593306933079330893309933109331193312933139331493315933169331793318933199332093321933229332393324933259332693327933289332993330933319333293333933349333593336933379333893339933409334193342933439334493345933469334793348933499335093351933529335393354933559335693357933589335993360933619336293363933649336593366933679336893369933709337193372933739337493375933769337793378933799338093381933829338393384933859338693387933889338993390933919339293393933949339593396933979339893399934009340193402934039340493405934069340793408934099341093411934129341393414934159341693417934189341993420934219342293423934249342593426934279342893429934309343193432934339343493435934369343793438934399344093441934429344393444934459344693447934489344993450934519345293453934549345593456
  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. "use strict";
  4. var BABYLON;
  5. (function (BABYLON) {
  6. /**
  7. * EffectFallbacks can be used to add fallbacks (properties to disable) to certain properties when desired to improve performance.
  8. * (Eg. Start at high quality with reflection and fog, if fps is low, remove reflection, if still low remove fog)
  9. */
  10. var EffectFallbacks = /** @class */ (function () {
  11. function EffectFallbacks() {
  12. this._defines = {};
  13. this._currentRank = 32;
  14. this._maxRank = -1;
  15. }
  16. /**
  17. * Removes the fallback from the bound mesh.
  18. */
  19. EffectFallbacks.prototype.unBindMesh = function () {
  20. this._mesh = null;
  21. };
  22. /**
  23. * Adds a fallback on the specified property.
  24. * @param rank The rank of the fallback (Lower ranks will be fallbacked to first)
  25. * @param define The name of the define in the shader
  26. */
  27. EffectFallbacks.prototype.addFallback = function (rank, define) {
  28. if (!this._defines[rank]) {
  29. if (rank < this._currentRank) {
  30. this._currentRank = rank;
  31. }
  32. if (rank > this._maxRank) {
  33. this._maxRank = rank;
  34. }
  35. this._defines[rank] = new Array();
  36. }
  37. this._defines[rank].push(define);
  38. };
  39. /**
  40. * Sets the mesh to use CPU skinning when needing to fallback.
  41. * @param rank The rank of the fallback (Lower ranks will be fallbacked to first)
  42. * @param mesh The mesh to use the fallbacks.
  43. */
  44. EffectFallbacks.prototype.addCPUSkinningFallback = function (rank, mesh) {
  45. this._mesh = mesh;
  46. if (rank < this._currentRank) {
  47. this._currentRank = rank;
  48. }
  49. if (rank > this._maxRank) {
  50. this._maxRank = rank;
  51. }
  52. };
  53. Object.defineProperty(EffectFallbacks.prototype, "isMoreFallbacks", {
  54. /**
  55. * Checks to see if more fallbacks are still availible.
  56. */
  57. get: function () {
  58. return this._currentRank <= this._maxRank;
  59. },
  60. enumerable: true,
  61. configurable: true
  62. });
  63. /**
  64. * Removes the defines that shoould be removed when falling back.
  65. * @param currentDefines defines the current define statements for the shader.
  66. * @param effect defines the current effect we try to compile
  67. * @returns The resulting defines with defines of the current rank removed.
  68. */
  69. EffectFallbacks.prototype.reduce = function (currentDefines, effect) {
  70. // First we try to switch to CPU skinning
  71. if (this._mesh && this._mesh.computeBonesUsingShaders && this._mesh.numBoneInfluencers > 0 && this._mesh.material) {
  72. this._mesh.computeBonesUsingShaders = false;
  73. currentDefines = currentDefines.replace("#define NUM_BONE_INFLUENCERS " + this._mesh.numBoneInfluencers, "#define NUM_BONE_INFLUENCERS 0");
  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 {
  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. this._uniformBuffersNames = {};
  163. this._isReady = false;
  164. this._compilationError = "";
  165. this.name = baseName;
  166. if (attributesNamesOrOptions.attributes) {
  167. var options = attributesNamesOrOptions;
  168. this._engine = uniformsNamesOrEngine;
  169. this._attributesNames = options.attributes;
  170. this._uniformsNames = options.uniformsNames.concat(options.samplers);
  171. this._samplers = options.samplers.slice();
  172. this.defines = options.defines;
  173. this.onError = options.onError;
  174. this.onCompiled = options.onCompiled;
  175. this._fallbacks = options.fallbacks;
  176. this._indexParameters = options.indexParameters;
  177. this._transformFeedbackVaryings = options.transformFeedbackVaryings;
  178. if (options.uniformBuffersNames) {
  179. for (var i = 0; i < options.uniformBuffersNames.length; i++) {
  180. this._uniformBuffersNames[options.uniformBuffersNames[i]] = i;
  181. }
  182. }
  183. }
  184. else {
  185. this._engine = engine;
  186. this.defines = defines;
  187. this._uniformsNames = uniformsNamesOrEngine.concat(samplers);
  188. this._samplers = samplers ? samplers.slice() : [];
  189. this._attributesNames = attributesNamesOrOptions;
  190. this.onError = onError;
  191. this.onCompiled = onCompiled;
  192. this._indexParameters = indexParameters;
  193. this._fallbacks = fallbacks;
  194. }
  195. this.uniqueId = Effect._uniqueIdSeed++;
  196. var vertexSource;
  197. var fragmentSource;
  198. if (baseName.vertexElement) {
  199. vertexSource = document.getElementById(baseName.vertexElement);
  200. if (!vertexSource) {
  201. vertexSource = baseName.vertexElement;
  202. }
  203. }
  204. else {
  205. vertexSource = baseName.vertex || baseName;
  206. }
  207. if (baseName.fragmentElement) {
  208. fragmentSource = document.getElementById(baseName.fragmentElement);
  209. if (!fragmentSource) {
  210. fragmentSource = baseName.fragmentElement;
  211. }
  212. }
  213. else {
  214. fragmentSource = baseName.fragment || baseName;
  215. }
  216. this._loadVertexShader(vertexSource, function (vertexCode) {
  217. _this._processIncludes(vertexCode, function (vertexCodeWithIncludes) {
  218. _this._processShaderConversion(vertexCodeWithIncludes, false, function (migratedVertexCode) {
  219. _this._loadFragmentShader(fragmentSource, function (fragmentCode) {
  220. _this._processIncludes(fragmentCode, function (fragmentCodeWithIncludes) {
  221. _this._processShaderConversion(fragmentCodeWithIncludes, true, function (migratedFragmentCode) {
  222. if (baseName) {
  223. var vertex = baseName.vertexElement || baseName.vertex || baseName;
  224. var fragment = baseName.fragmentElement || baseName.fragment || baseName;
  225. _this._vertexSourceCode = "#define SHADER_NAME vertex:" + vertex + "\n" + migratedVertexCode;
  226. _this._fragmentSourceCode = "#define SHADER_NAME fragment:" + fragment + "\n" + migratedFragmentCode;
  227. }
  228. else {
  229. _this._vertexSourceCode = migratedVertexCode;
  230. _this._fragmentSourceCode = migratedFragmentCode;
  231. }
  232. _this._prepareEffect();
  233. });
  234. });
  235. });
  236. });
  237. });
  238. });
  239. }
  240. Object.defineProperty(Effect.prototype, "key", {
  241. /**
  242. * Unique key for this effect
  243. */
  244. get: function () {
  245. return this._key;
  246. },
  247. enumerable: true,
  248. configurable: true
  249. });
  250. /**
  251. * If the effect has been compiled and prepared.
  252. * @returns if the effect is compiled and prepared.
  253. */
  254. Effect.prototype.isReady = function () {
  255. return this._isReady;
  256. };
  257. /**
  258. * The engine the effect was initialized with.
  259. * @returns the engine.
  260. */
  261. Effect.prototype.getEngine = function () {
  262. return this._engine;
  263. };
  264. /**
  265. * The compiled webGL program for the effect
  266. * @returns the webGL program.
  267. */
  268. Effect.prototype.getProgram = function () {
  269. return this._program;
  270. };
  271. /**
  272. * The set of names of attribute variables for the shader.
  273. * @returns An array of attribute names.
  274. */
  275. Effect.prototype.getAttributesNames = function () {
  276. return this._attributesNames;
  277. };
  278. /**
  279. * Returns the attribute at the given index.
  280. * @param index The index of the attribute.
  281. * @returns The location of the attribute.
  282. */
  283. Effect.prototype.getAttributeLocation = function (index) {
  284. return this._attributes[index];
  285. };
  286. /**
  287. * Returns the attribute based on the name of the variable.
  288. * @param name of the attribute to look up.
  289. * @returns the attribute location.
  290. */
  291. Effect.prototype.getAttributeLocationByName = function (name) {
  292. var index = this._attributesNames.indexOf(name);
  293. return this._attributes[index];
  294. };
  295. /**
  296. * The number of attributes.
  297. * @returns the numnber of attributes.
  298. */
  299. Effect.prototype.getAttributesCount = function () {
  300. return this._attributes.length;
  301. };
  302. /**
  303. * Gets the index of a uniform variable.
  304. * @param uniformName of the uniform to look up.
  305. * @returns the index.
  306. */
  307. Effect.prototype.getUniformIndex = function (uniformName) {
  308. return this._uniformsNames.indexOf(uniformName);
  309. };
  310. /**
  311. * Returns the attribute based on the name of the variable.
  312. * @param uniformName of the uniform to look up.
  313. * @returns the location of the uniform.
  314. */
  315. Effect.prototype.getUniform = function (uniformName) {
  316. return this._uniforms[this._uniformsNames.indexOf(uniformName)];
  317. };
  318. /**
  319. * Returns an array of sampler variable names
  320. * @returns The array of sampler variable neames.
  321. */
  322. Effect.prototype.getSamplers = function () {
  323. return this._samplers;
  324. };
  325. /**
  326. * The error from the last compilation.
  327. * @returns the error string.
  328. */
  329. Effect.prototype.getCompilationError = function () {
  330. return this._compilationError;
  331. };
  332. /**
  333. * Adds a callback to the onCompiled observable and call the callback imediatly if already ready.
  334. * @param func The callback to be used.
  335. */
  336. Effect.prototype.executeWhenCompiled = function (func) {
  337. if (this.isReady()) {
  338. func(this);
  339. return;
  340. }
  341. this.onCompileObservable.add(function (effect) {
  342. func(effect);
  343. });
  344. };
  345. /** @ignore */
  346. Effect.prototype._loadVertexShader = function (vertex, callback) {
  347. if (BABYLON.Tools.IsWindowObjectExist()) {
  348. // DOM element ?
  349. if (vertex instanceof HTMLElement) {
  350. var vertexCode = BABYLON.Tools.GetDOMTextContent(vertex);
  351. callback(vertexCode);
  352. return;
  353. }
  354. }
  355. // Base64 encoded ?
  356. if (vertex.substr(0, 7) === "base64:") {
  357. var vertexBinary = window.atob(vertex.substr(7));
  358. callback(vertexBinary);
  359. return;
  360. }
  361. // Is in local store ?
  362. if (Effect.ShadersStore[vertex + "VertexShader"]) {
  363. callback(Effect.ShadersStore[vertex + "VertexShader"]);
  364. return;
  365. }
  366. var vertexShaderUrl;
  367. if (vertex[0] === "." || vertex[0] === "/" || vertex.indexOf("http") > -1) {
  368. vertexShaderUrl = vertex;
  369. }
  370. else {
  371. vertexShaderUrl = BABYLON.Engine.ShadersRepository + vertex;
  372. }
  373. // Vertex shader
  374. this._engine._loadFile(vertexShaderUrl + ".vertex.fx", callback);
  375. };
  376. /** @ignore */
  377. Effect.prototype._loadFragmentShader = function (fragment, callback) {
  378. if (BABYLON.Tools.IsWindowObjectExist()) {
  379. // DOM element ?
  380. if (fragment instanceof HTMLElement) {
  381. var fragmentCode = BABYLON.Tools.GetDOMTextContent(fragment);
  382. callback(fragmentCode);
  383. return;
  384. }
  385. }
  386. // Base64 encoded ?
  387. if (fragment.substr(0, 7) === "base64:") {
  388. var fragmentBinary = window.atob(fragment.substr(7));
  389. callback(fragmentBinary);
  390. return;
  391. }
  392. // Is in local store ?
  393. if (Effect.ShadersStore[fragment + "PixelShader"]) {
  394. callback(Effect.ShadersStore[fragment + "PixelShader"]);
  395. return;
  396. }
  397. if (Effect.ShadersStore[fragment + "FragmentShader"]) {
  398. callback(Effect.ShadersStore[fragment + "FragmentShader"]);
  399. return;
  400. }
  401. var fragmentShaderUrl;
  402. if (fragment[0] === "." || fragment[0] === "/" || fragment.indexOf("http") > -1) {
  403. fragmentShaderUrl = fragment;
  404. }
  405. else {
  406. fragmentShaderUrl = BABYLON.Engine.ShadersRepository + fragment;
  407. }
  408. // Fragment shader
  409. this._engine._loadFile(fragmentShaderUrl + ".fragment.fx", callback);
  410. };
  411. Effect.prototype._dumpShadersSource = function (vertexCode, fragmentCode, defines) {
  412. // Rebuild shaders source code
  413. var shaderVersion = (this._engine.webGLVersion > 1) ? "#version 300 es\n#define WEBGL2 \n" : "";
  414. var prefix = shaderVersion + (defines ? defines + "\n" : "");
  415. vertexCode = prefix + vertexCode;
  416. fragmentCode = prefix + fragmentCode;
  417. // Number lines of shaders source code
  418. var i = 2;
  419. var regex = /\n/gm;
  420. var formattedVertexCode = "\n1\t" + vertexCode.replace(regex, function () { return "\n" + (i++) + "\t"; });
  421. i = 2;
  422. var formattedFragmentCode = "\n1\t" + fragmentCode.replace(regex, function () { return "\n" + (i++) + "\t"; });
  423. // Dump shaders name and formatted source code
  424. if (this.name.vertexElement) {
  425. BABYLON.Tools.Error("Vertex shader: " + this.name.vertexElement + formattedVertexCode);
  426. BABYLON.Tools.Error("Fragment shader: " + this.name.fragmentElement + formattedFragmentCode);
  427. }
  428. else if (this.name.vertex) {
  429. BABYLON.Tools.Error("Vertex shader: " + this.name.vertex + formattedVertexCode);
  430. BABYLON.Tools.Error("Fragment shader: " + this.name.fragment + formattedFragmentCode);
  431. }
  432. else {
  433. BABYLON.Tools.Error("Vertex shader: " + this.name + formattedVertexCode);
  434. BABYLON.Tools.Error("Fragment shader: " + this.name + formattedFragmentCode);
  435. }
  436. };
  437. ;
  438. Effect.prototype._processShaderConversion = function (sourceCode, isFragment, callback) {
  439. var preparedSourceCode = this._processPrecision(sourceCode);
  440. if (this._engine.webGLVersion == 1) {
  441. callback(preparedSourceCode);
  442. return;
  443. }
  444. // Already converted
  445. if (preparedSourceCode.indexOf("#version 3") !== -1) {
  446. callback(preparedSourceCode.replace("#version 300 es", ""));
  447. return;
  448. }
  449. var hasDrawBuffersExtension = preparedSourceCode.search(/#extension.+GL_EXT_draw_buffers.+require/) !== -1;
  450. // Remove extensions
  451. // #extension GL_OES_standard_derivatives : enable
  452. // #extension GL_EXT_shader_texture_lod : enable
  453. // #extension GL_EXT_frag_depth : enable
  454. // #extension GL_EXT_draw_buffers : require
  455. var regex = /#extension.+(GL_OES_standard_derivatives|GL_EXT_shader_texture_lod|GL_EXT_frag_depth|GL_EXT_draw_buffers).+(enable|require)/g;
  456. var result = preparedSourceCode.replace(regex, "");
  457. // Migrate to GLSL v300
  458. result = result.replace(/varying(?![\n\r])\s/g, isFragment ? "in " : "out ");
  459. result = result.replace(/attribute[ \t]/g, "in ");
  460. result = result.replace(/[ \t]attribute/g, " in");
  461. if (isFragment) {
  462. result = result.replace(/texture2DLodEXT\s*\(/g, "textureLod(");
  463. result = result.replace(/textureCubeLodEXT\s*\(/g, "textureLod(");
  464. result = result.replace(/texture2D\s*\(/g, "texture(");
  465. result = result.replace(/textureCube\s*\(/g, "texture(");
  466. result = result.replace(/gl_FragDepthEXT/g, "gl_FragDepth");
  467. result = result.replace(/gl_FragColor/g, "glFragColor");
  468. result = result.replace(/gl_FragData/g, "glFragData");
  469. result = result.replace(/void\s+?main\s*\(/g, (hasDrawBuffersExtension ? "" : "out vec4 glFragColor;\n") + "void main(");
  470. }
  471. callback(result);
  472. };
  473. Effect.prototype._processIncludes = function (sourceCode, callback) {
  474. var _this = this;
  475. var regex = /#include<(.+)>(\((.*)\))*(\[(.*)\])*/g;
  476. var match = regex.exec(sourceCode);
  477. var returnValue = new String(sourceCode);
  478. while (match != null) {
  479. var includeFile = match[1];
  480. // Uniform declaration
  481. if (includeFile.indexOf("__decl__") !== -1) {
  482. includeFile = includeFile.replace(/__decl__/, "");
  483. if (this._engine.supportsUniformBuffers) {
  484. includeFile = includeFile.replace(/Vertex/, "Ubo");
  485. includeFile = includeFile.replace(/Fragment/, "Ubo");
  486. }
  487. includeFile = includeFile + "Declaration";
  488. }
  489. if (Effect.IncludesShadersStore[includeFile]) {
  490. // Substitution
  491. var includeContent = Effect.IncludesShadersStore[includeFile];
  492. if (match[2]) {
  493. var splits = match[3].split(",");
  494. for (var index = 0; index < splits.length; index += 2) {
  495. var source = new RegExp(splits[index], "g");
  496. var dest = splits[index + 1];
  497. includeContent = includeContent.replace(source, dest);
  498. }
  499. }
  500. if (match[4]) {
  501. var indexString = match[5];
  502. if (indexString.indexOf("..") !== -1) {
  503. var indexSplits = indexString.split("..");
  504. var minIndex = parseInt(indexSplits[0]);
  505. var maxIndex = parseInt(indexSplits[1]);
  506. var sourceIncludeContent = includeContent.slice(0);
  507. includeContent = "";
  508. if (isNaN(maxIndex)) {
  509. maxIndex = this._indexParameters[indexSplits[1]];
  510. }
  511. for (var i = minIndex; i < maxIndex; i++) {
  512. if (!this._engine.supportsUniformBuffers) {
  513. // Ubo replacement
  514. sourceIncludeContent = sourceIncludeContent.replace(/light\{X\}.(\w*)/g, function (str, p1) {
  515. return p1 + "{X}";
  516. });
  517. }
  518. includeContent += sourceIncludeContent.replace(/\{X\}/g, i.toString()) + "\n";
  519. }
  520. }
  521. else {
  522. if (!this._engine.supportsUniformBuffers) {
  523. // Ubo replacement
  524. includeContent = includeContent.replace(/light\{X\}.(\w*)/g, function (str, p1) {
  525. return p1 + "{X}";
  526. });
  527. }
  528. includeContent = includeContent.replace(/\{X\}/g, indexString);
  529. }
  530. }
  531. // Replace
  532. returnValue = returnValue.replace(match[0], includeContent);
  533. }
  534. else {
  535. var includeShaderUrl = BABYLON.Engine.ShadersRepository + "ShadersInclude/" + includeFile + ".fx";
  536. this._engine._loadFile(includeShaderUrl, function (fileContent) {
  537. Effect.IncludesShadersStore[includeFile] = fileContent;
  538. _this._processIncludes(returnValue, callback);
  539. });
  540. return;
  541. }
  542. match = regex.exec(sourceCode);
  543. }
  544. callback(returnValue);
  545. };
  546. Effect.prototype._processPrecision = function (source) {
  547. if (source.indexOf("precision highp float") === -1) {
  548. if (!this._engine.getCaps().highPrecisionShaderSupported) {
  549. source = "precision mediump float;\n" + source;
  550. }
  551. else {
  552. source = "precision highp float;\n" + source;
  553. }
  554. }
  555. else {
  556. if (!this._engine.getCaps().highPrecisionShaderSupported) {
  557. source = source.replace("precision highp float", "precision mediump float");
  558. }
  559. }
  560. return source;
  561. };
  562. /**
  563. * Recompiles the webGL program
  564. * @param vertexSourceCode The source code for the vertex shader.
  565. * @param fragmentSourceCode The source code for the fragment shader.
  566. * @param onCompiled Callback called when completed.
  567. * @param onError Callback called on error.
  568. */
  569. Effect.prototype._rebuildProgram = function (vertexSourceCode, fragmentSourceCode, onCompiled, onError) {
  570. var _this = this;
  571. this._isReady = false;
  572. this._vertexSourceCodeOverride = vertexSourceCode;
  573. this._fragmentSourceCodeOverride = fragmentSourceCode;
  574. this.onError = function (effect, error) {
  575. if (onError) {
  576. onError(error);
  577. }
  578. };
  579. this.onCompiled = function () {
  580. var scenes = _this.getEngine().scenes;
  581. for (var i = 0; i < scenes.length; i++) {
  582. scenes[i].markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  583. }
  584. if (onCompiled) {
  585. onCompiled(_this._program);
  586. }
  587. };
  588. this._fallbacks = null;
  589. this._prepareEffect();
  590. };
  591. /**
  592. * Gets the uniform locations of the the specified variable names
  593. * @param names THe names of the variables to lookup.
  594. * @returns Array of locations in the same order as variable names.
  595. */
  596. Effect.prototype.getSpecificUniformLocations = function (names) {
  597. var engine = this._engine;
  598. return engine.getUniforms(this._program, names);
  599. };
  600. /**
  601. * Prepares the effect
  602. */
  603. Effect.prototype._prepareEffect = function () {
  604. var attributesNames = this._attributesNames;
  605. var defines = this.defines;
  606. var fallbacks = this._fallbacks;
  607. this._valueCache = {};
  608. var previousProgram = this._program;
  609. try {
  610. var engine = this._engine;
  611. if (this._vertexSourceCodeOverride && this._fragmentSourceCodeOverride) {
  612. this._program = engine.createRawShaderProgram(this._vertexSourceCodeOverride, this._fragmentSourceCodeOverride, undefined, this._transformFeedbackVaryings);
  613. }
  614. else {
  615. this._program = engine.createShaderProgram(this._vertexSourceCode, this._fragmentSourceCode, defines, undefined, this._transformFeedbackVaryings);
  616. }
  617. this._program.__SPECTOR_rebuildProgram = this._rebuildProgram.bind(this);
  618. if (engine.supportsUniformBuffers) {
  619. for (var name in this._uniformBuffersNames) {
  620. this.bindUniformBlock(name, this._uniformBuffersNames[name]);
  621. }
  622. }
  623. this._uniforms = engine.getUniforms(this._program, this._uniformsNames);
  624. this._attributes = engine.getAttributes(this._program, attributesNames);
  625. var index;
  626. for (index = 0; index < this._samplers.length; index++) {
  627. var sampler = this.getUniform(this._samplers[index]);
  628. if (sampler == null) {
  629. this._samplers.splice(index, 1);
  630. index--;
  631. }
  632. }
  633. engine.bindSamplers(this);
  634. this._compilationError = "";
  635. this._isReady = true;
  636. if (this.onCompiled) {
  637. this.onCompiled(this);
  638. }
  639. this.onCompileObservable.notifyObservers(this);
  640. this.onCompileObservable.clear();
  641. // Unbind mesh reference in fallbacks
  642. if (this._fallbacks) {
  643. this._fallbacks.unBindMesh();
  644. }
  645. if (previousProgram) {
  646. this.getEngine()._deleteProgram(previousProgram);
  647. }
  648. }
  649. catch (e) {
  650. this._compilationError = e.message;
  651. // Let's go through fallbacks then
  652. BABYLON.Tools.Error("Unable to compile effect:");
  653. BABYLON.Tools.Error("Uniforms: " + this._uniformsNames.map(function (uniform) {
  654. return " " + uniform;
  655. }));
  656. BABYLON.Tools.Error("Attributes: " + attributesNames.map(function (attribute) {
  657. return " " + attribute;
  658. }));
  659. this._dumpShadersSource(this._vertexSourceCode, this._fragmentSourceCode, defines);
  660. BABYLON.Tools.Error("Error: " + this._compilationError);
  661. if (previousProgram) {
  662. this._program = previousProgram;
  663. this._isReady = true;
  664. if (this.onError) {
  665. this.onError(this, this._compilationError);
  666. }
  667. this.onErrorObservable.notifyObservers(this);
  668. }
  669. if (fallbacks && fallbacks.isMoreFallbacks) {
  670. BABYLON.Tools.Error("Trying next fallback.");
  671. this.defines = fallbacks.reduce(this.defines, this);
  672. this._prepareEffect();
  673. }
  674. else {
  675. if (this.onError) {
  676. this.onError(this, this._compilationError);
  677. }
  678. this.onErrorObservable.notifyObservers(this);
  679. this.onErrorObservable.clear();
  680. // Unbind mesh reference in fallbacks
  681. if (this._fallbacks) {
  682. this._fallbacks.unBindMesh();
  683. }
  684. }
  685. }
  686. };
  687. Object.defineProperty(Effect.prototype, "isSupported", {
  688. /**
  689. * Checks if the effect is supported. (Must be called after compilation)
  690. */
  691. get: function () {
  692. return this._compilationError === "";
  693. },
  694. enumerable: true,
  695. configurable: true
  696. });
  697. /**
  698. * Binds a texture to the engine to be used as output of the shader.
  699. * @param channel Name of the output variable.
  700. * @param texture Texture to bind.
  701. */
  702. Effect.prototype._bindTexture = function (channel, texture) {
  703. this._engine._bindTexture(this._samplers.indexOf(channel), texture);
  704. };
  705. /**
  706. * Sets a texture on the engine to be used in the shader.
  707. * @param channel Name of the sampler variable.
  708. * @param texture Texture to set.
  709. */
  710. Effect.prototype.setTexture = function (channel, texture) {
  711. this._engine.setTexture(this._samplers.indexOf(channel), this.getUniform(channel), texture);
  712. };
  713. /**
  714. * Sets a depth stencil texture from a render target on the engine to be used in the shader.
  715. * @param channel Name of the sampler variable.
  716. * @param texture Texture to set.
  717. */
  718. Effect.prototype.setDepthStencilTexture = function (channel, texture) {
  719. this._engine.setDepthStencilTexture(this._samplers.indexOf(channel), this.getUniform(channel), texture);
  720. };
  721. /**
  722. * Sets an array of textures on the engine to be used in the shader.
  723. * @param channel Name of the variable.
  724. * @param textures Textures to set.
  725. */
  726. Effect.prototype.setTextureArray = function (channel, textures) {
  727. if (this._samplers.indexOf(channel + "Ex") === -1) {
  728. var initialPos = this._samplers.indexOf(channel);
  729. for (var index = 1; index < textures.length; index++) {
  730. this._samplers.splice(initialPos + index, 0, channel + "Ex");
  731. }
  732. }
  733. this._engine.setTextureArray(this._samplers.indexOf(channel), this.getUniform(channel), textures);
  734. };
  735. /**
  736. * 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)
  737. * @param channel Name of the sampler variable.
  738. * @param postProcess Post process to get the input texture from.
  739. */
  740. Effect.prototype.setTextureFromPostProcess = function (channel, postProcess) {
  741. this._engine.setTextureFromPostProcess(this._samplers.indexOf(channel), postProcess);
  742. };
  743. /**
  744. * (Warning! setTextureFromPostProcessOutput may be desired instead)
  745. * 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)
  746. * @param channel Name of the sampler variable.
  747. * @param postProcess Post process to get the output texture from.
  748. */
  749. Effect.prototype.setTextureFromPostProcessOutput = function (channel, postProcess) {
  750. this._engine.setTextureFromPostProcessOutput(this._samplers.indexOf(channel), postProcess);
  751. };
  752. /** @ignore */
  753. Effect.prototype._cacheMatrix = function (uniformName, matrix) {
  754. var cache = this._valueCache[uniformName];
  755. var flag = matrix.updateFlag;
  756. if (cache !== undefined && cache === flag) {
  757. return false;
  758. }
  759. this._valueCache[uniformName] = flag;
  760. return true;
  761. };
  762. /** @ignore */
  763. Effect.prototype._cacheFloat2 = function (uniformName, x, y) {
  764. var cache = this._valueCache[uniformName];
  765. if (!cache) {
  766. cache = [x, y];
  767. this._valueCache[uniformName] = cache;
  768. return true;
  769. }
  770. var changed = false;
  771. if (cache[0] !== x) {
  772. cache[0] = x;
  773. changed = true;
  774. }
  775. if (cache[1] !== y) {
  776. cache[1] = y;
  777. changed = true;
  778. }
  779. return changed;
  780. };
  781. /** @ignore */
  782. Effect.prototype._cacheFloat3 = function (uniformName, x, y, z) {
  783. var cache = this._valueCache[uniformName];
  784. if (!cache) {
  785. cache = [x, y, z];
  786. this._valueCache[uniformName] = cache;
  787. return true;
  788. }
  789. var changed = false;
  790. if (cache[0] !== x) {
  791. cache[0] = x;
  792. changed = true;
  793. }
  794. if (cache[1] !== y) {
  795. cache[1] = y;
  796. changed = true;
  797. }
  798. if (cache[2] !== z) {
  799. cache[2] = z;
  800. changed = true;
  801. }
  802. return changed;
  803. };
  804. /** @ignore */
  805. Effect.prototype._cacheFloat4 = function (uniformName, x, y, z, w) {
  806. var cache = this._valueCache[uniformName];
  807. if (!cache) {
  808. cache = [x, y, z, w];
  809. this._valueCache[uniformName] = cache;
  810. return true;
  811. }
  812. var changed = false;
  813. if (cache[0] !== x) {
  814. cache[0] = x;
  815. changed = true;
  816. }
  817. if (cache[1] !== y) {
  818. cache[1] = y;
  819. changed = true;
  820. }
  821. if (cache[2] !== z) {
  822. cache[2] = z;
  823. changed = true;
  824. }
  825. if (cache[3] !== w) {
  826. cache[3] = w;
  827. changed = true;
  828. }
  829. return changed;
  830. };
  831. /**
  832. * Binds a buffer to a uniform.
  833. * @param buffer Buffer to bind.
  834. * @param name Name of the uniform variable to bind to.
  835. */
  836. Effect.prototype.bindUniformBuffer = function (buffer, name) {
  837. var bufferName = this._uniformBuffersNames[name];
  838. if (bufferName === undefined || Effect._baseCache[bufferName] === buffer) {
  839. return;
  840. }
  841. Effect._baseCache[bufferName] = buffer;
  842. this._engine.bindUniformBufferBase(buffer, bufferName);
  843. };
  844. /**
  845. * Binds block to a uniform.
  846. * @param blockName Name of the block to bind.
  847. * @param index Index to bind.
  848. */
  849. Effect.prototype.bindUniformBlock = function (blockName, index) {
  850. this._engine.bindUniformBlock(this._program, blockName, index);
  851. };
  852. /**
  853. * Sets an interger value on a uniform variable.
  854. * @param uniformName Name of the variable.
  855. * @param value Value to be set.
  856. * @returns this effect.
  857. */
  858. Effect.prototype.setInt = function (uniformName, value) {
  859. var cache = this._valueCache[uniformName];
  860. if (cache !== undefined && cache === value)
  861. return this;
  862. this._valueCache[uniformName] = value;
  863. this._engine.setInt(this.getUniform(uniformName), value);
  864. return this;
  865. };
  866. /**
  867. * Sets an int array on a uniform variable.
  868. * @param uniformName Name of the variable.
  869. * @param array array to be set.
  870. * @returns this effect.
  871. */
  872. Effect.prototype.setIntArray = function (uniformName, array) {
  873. this._valueCache[uniformName] = null;
  874. this._engine.setIntArray(this.getUniform(uniformName), array);
  875. return this;
  876. };
  877. /**
  878. * 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)
  879. * @param uniformName Name of the variable.
  880. * @param array array to be set.
  881. * @returns this effect.
  882. */
  883. Effect.prototype.setIntArray2 = function (uniformName, array) {
  884. this._valueCache[uniformName] = null;
  885. this._engine.setIntArray2(this.getUniform(uniformName), array);
  886. return this;
  887. };
  888. /**
  889. * 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)
  890. * @param uniformName Name of the variable.
  891. * @param array array to be set.
  892. * @returns this effect.
  893. */
  894. Effect.prototype.setIntArray3 = function (uniformName, array) {
  895. this._valueCache[uniformName] = null;
  896. this._engine.setIntArray3(this.getUniform(uniformName), array);
  897. return this;
  898. };
  899. /**
  900. * 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)
  901. * @param uniformName Name of the variable.
  902. * @param array array to be set.
  903. * @returns this effect.
  904. */
  905. Effect.prototype.setIntArray4 = function (uniformName, array) {
  906. this._valueCache[uniformName] = null;
  907. this._engine.setIntArray4(this.getUniform(uniformName), array);
  908. return this;
  909. };
  910. /**
  911. * Sets an float array on a uniform variable.
  912. * @param uniformName Name of the variable.
  913. * @param array array to be set.
  914. * @returns this effect.
  915. */
  916. Effect.prototype.setFloatArray = function (uniformName, array) {
  917. this._valueCache[uniformName] = null;
  918. this._engine.setFloatArray(this.getUniform(uniformName), array);
  919. return this;
  920. };
  921. /**
  922. * 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)
  923. * @param uniformName Name of the variable.
  924. * @param array array to be set.
  925. * @returns this effect.
  926. */
  927. Effect.prototype.setFloatArray2 = function (uniformName, array) {
  928. this._valueCache[uniformName] = null;
  929. this._engine.setFloatArray2(this.getUniform(uniformName), array);
  930. return this;
  931. };
  932. /**
  933. * 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)
  934. * @param uniformName Name of the variable.
  935. * @param array array to be set.
  936. * @returns this effect.
  937. */
  938. Effect.prototype.setFloatArray3 = function (uniformName, array) {
  939. this._valueCache[uniformName] = null;
  940. this._engine.setFloatArray3(this.getUniform(uniformName), array);
  941. return this;
  942. };
  943. /**
  944. * 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)
  945. * @param uniformName Name of the variable.
  946. * @param array array to be set.
  947. * @returns this effect.
  948. */
  949. Effect.prototype.setFloatArray4 = function (uniformName, array) {
  950. this._valueCache[uniformName] = null;
  951. this._engine.setFloatArray4(this.getUniform(uniformName), array);
  952. return this;
  953. };
  954. /**
  955. * Sets an array on a uniform variable.
  956. * @param uniformName Name of the variable.
  957. * @param array array to be set.
  958. * @returns this effect.
  959. */
  960. Effect.prototype.setArray = function (uniformName, array) {
  961. this._valueCache[uniformName] = null;
  962. this._engine.setArray(this.getUniform(uniformName), array);
  963. return this;
  964. };
  965. /**
  966. * 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)
  967. * @param uniformName Name of the variable.
  968. * @param array array to be set.
  969. * @returns this effect.
  970. */
  971. Effect.prototype.setArray2 = function (uniformName, array) {
  972. this._valueCache[uniformName] = null;
  973. this._engine.setArray2(this.getUniform(uniformName), array);
  974. return this;
  975. };
  976. /**
  977. * 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)
  978. * @param uniformName Name of the variable.
  979. * @param array array to be set.
  980. * @returns this effect.
  981. */
  982. Effect.prototype.setArray3 = function (uniformName, array) {
  983. this._valueCache[uniformName] = null;
  984. this._engine.setArray3(this.getUniform(uniformName), array);
  985. return this;
  986. };
  987. /**
  988. * 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)
  989. * @param uniformName Name of the variable.
  990. * @param array array to be set.
  991. * @returns this effect.
  992. */
  993. Effect.prototype.setArray4 = function (uniformName, array) {
  994. this._valueCache[uniformName] = null;
  995. this._engine.setArray4(this.getUniform(uniformName), array);
  996. return this;
  997. };
  998. /**
  999. * Sets matrices on a uniform variable.
  1000. * @param uniformName Name of the variable.
  1001. * @param matrices matrices to be set.
  1002. * @returns this effect.
  1003. */
  1004. Effect.prototype.setMatrices = function (uniformName, matrices) {
  1005. if (!matrices) {
  1006. return this;
  1007. }
  1008. this._valueCache[uniformName] = null;
  1009. this._engine.setMatrices(this.getUniform(uniformName), matrices);
  1010. return this;
  1011. };
  1012. /**
  1013. * Sets matrix on a uniform variable.
  1014. * @param uniformName Name of the variable.
  1015. * @param matrix matrix to be set.
  1016. * @returns this effect.
  1017. */
  1018. Effect.prototype.setMatrix = function (uniformName, matrix) {
  1019. if (this._cacheMatrix(uniformName, matrix)) {
  1020. this._engine.setMatrix(this.getUniform(uniformName), matrix);
  1021. }
  1022. return this;
  1023. };
  1024. /**
  1025. * 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)
  1026. * @param uniformName Name of the variable.
  1027. * @param matrix matrix to be set.
  1028. * @returns this effect.
  1029. */
  1030. Effect.prototype.setMatrix3x3 = function (uniformName, matrix) {
  1031. this._valueCache[uniformName] = null;
  1032. this._engine.setMatrix3x3(this.getUniform(uniformName), matrix);
  1033. return this;
  1034. };
  1035. /**
  1036. * Sets a 2x2 matrix on a uniform variable. (Speicified as [1,2,3,4] will result in [1,2][3,4] matrix)
  1037. * @param uniformName Name of the variable.
  1038. * @param matrix matrix to be set.
  1039. * @returns this effect.
  1040. */
  1041. Effect.prototype.setMatrix2x2 = function (uniformName, matrix) {
  1042. this._valueCache[uniformName] = null;
  1043. this._engine.setMatrix2x2(this.getUniform(uniformName), matrix);
  1044. return this;
  1045. };
  1046. /**
  1047. * Sets a float on a uniform variable.
  1048. * @param uniformName Name of the variable.
  1049. * @param value value to be set.
  1050. * @returns this effect.
  1051. */
  1052. Effect.prototype.setFloat = function (uniformName, value) {
  1053. var cache = this._valueCache[uniformName];
  1054. if (cache !== undefined && cache === value)
  1055. return this;
  1056. this._valueCache[uniformName] = value;
  1057. this._engine.setFloat(this.getUniform(uniformName), value);
  1058. return this;
  1059. };
  1060. /**
  1061. * Sets a boolean on a uniform variable.
  1062. * @param uniformName Name of the variable.
  1063. * @param bool value to be set.
  1064. * @returns this effect.
  1065. */
  1066. Effect.prototype.setBool = function (uniformName, bool) {
  1067. var cache = this._valueCache[uniformName];
  1068. if (cache !== undefined && cache === bool)
  1069. return this;
  1070. this._valueCache[uniformName] = bool;
  1071. this._engine.setBool(this.getUniform(uniformName), bool ? 1 : 0);
  1072. return this;
  1073. };
  1074. /**
  1075. * Sets a Vector2 on a uniform variable.
  1076. * @param uniformName Name of the variable.
  1077. * @param vector2 vector2 to be set.
  1078. * @returns this effect.
  1079. */
  1080. Effect.prototype.setVector2 = function (uniformName, vector2) {
  1081. if (this._cacheFloat2(uniformName, vector2.x, vector2.y)) {
  1082. this._engine.setFloat2(this.getUniform(uniformName), vector2.x, vector2.y);
  1083. }
  1084. return this;
  1085. };
  1086. /**
  1087. * Sets a float2 on a uniform variable.
  1088. * @param uniformName Name of the variable.
  1089. * @param x First float in float2.
  1090. * @param y Second float in float2.
  1091. * @returns this effect.
  1092. */
  1093. Effect.prototype.setFloat2 = function (uniformName, x, y) {
  1094. if (this._cacheFloat2(uniformName, x, y)) {
  1095. this._engine.setFloat2(this.getUniform(uniformName), x, y);
  1096. }
  1097. return this;
  1098. };
  1099. /**
  1100. * Sets a Vector3 on a uniform variable.
  1101. * @param uniformName Name of the variable.
  1102. * @param vector3 Value to be set.
  1103. * @returns this effect.
  1104. */
  1105. Effect.prototype.setVector3 = function (uniformName, vector3) {
  1106. if (this._cacheFloat3(uniformName, vector3.x, vector3.y, vector3.z)) {
  1107. this._engine.setFloat3(this.getUniform(uniformName), vector3.x, vector3.y, vector3.z);
  1108. }
  1109. return this;
  1110. };
  1111. /**
  1112. * Sets a float3 on a uniform variable.
  1113. * @param uniformName Name of the variable.
  1114. * @param x First float in float3.
  1115. * @param y Second float in float3.
  1116. * @param z Third float in float3.
  1117. * @returns this effect.
  1118. */
  1119. Effect.prototype.setFloat3 = function (uniformName, x, y, z) {
  1120. if (this._cacheFloat3(uniformName, x, y, z)) {
  1121. this._engine.setFloat3(this.getUniform(uniformName), x, y, z);
  1122. }
  1123. return this;
  1124. };
  1125. /**
  1126. * Sets a Vector4 on a uniform variable.
  1127. * @param uniformName Name of the variable.
  1128. * @param vector4 Value to be set.
  1129. * @returns this effect.
  1130. */
  1131. Effect.prototype.setVector4 = function (uniformName, vector4) {
  1132. if (this._cacheFloat4(uniformName, vector4.x, vector4.y, vector4.z, vector4.w)) {
  1133. this._engine.setFloat4(this.getUniform(uniformName), vector4.x, vector4.y, vector4.z, vector4.w);
  1134. }
  1135. return this;
  1136. };
  1137. /**
  1138. * Sets a float4 on a uniform variable.
  1139. * @param uniformName Name of the variable.
  1140. * @param x First float in float4.
  1141. * @param y Second float in float4.
  1142. * @param z Third float in float4.
  1143. * @param w Fourth float in float4.
  1144. * @returns this effect.
  1145. */
  1146. Effect.prototype.setFloat4 = function (uniformName, x, y, z, w) {
  1147. if (this._cacheFloat4(uniformName, x, y, z, w)) {
  1148. this._engine.setFloat4(this.getUniform(uniformName), x, y, z, w);
  1149. }
  1150. return this;
  1151. };
  1152. /**
  1153. * Sets a Color3 on a uniform variable.
  1154. * @param uniformName Name of the variable.
  1155. * @param color3 Value to be set.
  1156. * @returns this effect.
  1157. */
  1158. Effect.prototype.setColor3 = function (uniformName, color3) {
  1159. if (this._cacheFloat3(uniformName, color3.r, color3.g, color3.b)) {
  1160. this._engine.setColor3(this.getUniform(uniformName), color3);
  1161. }
  1162. return this;
  1163. };
  1164. /**
  1165. * Sets a Color4 on a uniform variable.
  1166. * @param uniformName Name of the variable.
  1167. * @param color3 Value to be set.
  1168. * @param alpha Alpha value to be set.
  1169. * @returns this effect.
  1170. */
  1171. Effect.prototype.setColor4 = function (uniformName, color3, alpha) {
  1172. if (this._cacheFloat4(uniformName, color3.r, color3.g, color3.b, alpha)) {
  1173. this._engine.setColor4(this.getUniform(uniformName), color3, alpha);
  1174. }
  1175. return this;
  1176. };
  1177. /**
  1178. * Sets a Color4 on a uniform variable
  1179. * @param uniformName defines the name of the variable
  1180. * @param color4 defines the value to be set
  1181. * @returns this effect.
  1182. */
  1183. Effect.prototype.setDirectColor4 = function (uniformName, color4) {
  1184. if (this._cacheFloat4(uniformName, color4.r, color4.g, color4.b, color4.a)) {
  1185. this._engine.setDirectColor4(this.getUniform(uniformName), color4);
  1186. }
  1187. return this;
  1188. };
  1189. /**
  1190. * Resets the cache of effects.
  1191. */
  1192. Effect.ResetCache = function () {
  1193. Effect._baseCache = {};
  1194. };
  1195. Effect._uniqueIdSeed = 0;
  1196. Effect._baseCache = {};
  1197. /**
  1198. * Store of each shader (The can be looked up using effect.key)
  1199. */
  1200. Effect.ShadersStore = {};
  1201. /**
  1202. * Store of each included file for a shader (The can be looked up using effect.key)
  1203. */
  1204. Effect.IncludesShadersStore = {};
  1205. return Effect;
  1206. }());
  1207. BABYLON.Effect = Effect;
  1208. })(BABYLON || (BABYLON = {}));
  1209. //# sourceMappingURL=babylon.effect.js.map
  1210. "use strict";
  1211. //# sourceMappingURL=babylon.types.js.map
  1212. "use strict";
  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. "use strict";
  1262. var BABYLON;
  1263. (function (BABYLON) {
  1264. var PointerEventTypes = /** @class */ (function () {
  1265. function PointerEventTypes() {
  1266. }
  1267. Object.defineProperty(PointerEventTypes, "POINTERDOWN", {
  1268. get: function () {
  1269. return PointerEventTypes._POINTERDOWN;
  1270. },
  1271. enumerable: true,
  1272. configurable: true
  1273. });
  1274. Object.defineProperty(PointerEventTypes, "POINTERUP", {
  1275. get: function () {
  1276. return PointerEventTypes._POINTERUP;
  1277. },
  1278. enumerable: true,
  1279. configurable: true
  1280. });
  1281. Object.defineProperty(PointerEventTypes, "POINTERMOVE", {
  1282. get: function () {
  1283. return PointerEventTypes._POINTERMOVE;
  1284. },
  1285. enumerable: true,
  1286. configurable: true
  1287. });
  1288. Object.defineProperty(PointerEventTypes, "POINTERWHEEL", {
  1289. get: function () {
  1290. return PointerEventTypes._POINTERWHEEL;
  1291. },
  1292. enumerable: true,
  1293. configurable: true
  1294. });
  1295. Object.defineProperty(PointerEventTypes, "POINTERPICK", {
  1296. get: function () {
  1297. return PointerEventTypes._POINTERPICK;
  1298. },
  1299. enumerable: true,
  1300. configurable: true
  1301. });
  1302. Object.defineProperty(PointerEventTypes, "POINTERTAP", {
  1303. get: function () {
  1304. return PointerEventTypes._POINTERTAP;
  1305. },
  1306. enumerable: true,
  1307. configurable: true
  1308. });
  1309. Object.defineProperty(PointerEventTypes, "POINTERDOUBLETAP", {
  1310. get: function () {
  1311. return PointerEventTypes._POINTERDOUBLETAP;
  1312. },
  1313. enumerable: true,
  1314. configurable: true
  1315. });
  1316. PointerEventTypes._POINTERDOWN = 0x01;
  1317. PointerEventTypes._POINTERUP = 0x02;
  1318. PointerEventTypes._POINTERMOVE = 0x04;
  1319. PointerEventTypes._POINTERWHEEL = 0x08;
  1320. PointerEventTypes._POINTERPICK = 0x10;
  1321. PointerEventTypes._POINTERTAP = 0x20;
  1322. PointerEventTypes._POINTERDOUBLETAP = 0x40;
  1323. return PointerEventTypes;
  1324. }());
  1325. BABYLON.PointerEventTypes = PointerEventTypes;
  1326. var PointerInfoBase = /** @class */ (function () {
  1327. function PointerInfoBase(type, event) {
  1328. this.type = type;
  1329. this.event = event;
  1330. }
  1331. return PointerInfoBase;
  1332. }());
  1333. BABYLON.PointerInfoBase = PointerInfoBase;
  1334. /**
  1335. * This class is used to store pointer related info for the onPrePointerObservable event.
  1336. * Set the skipOnPointerObservable property to true if you want the engine to stop any process after this event is triggered, even not calling onPointerObservable
  1337. */
  1338. var PointerInfoPre = /** @class */ (function (_super) {
  1339. __extends(PointerInfoPre, _super);
  1340. function PointerInfoPre(type, event, localX, localY) {
  1341. var _this = _super.call(this, type, event) || this;
  1342. _this.skipOnPointerObservable = false;
  1343. _this.localPosition = new BABYLON.Vector2(localX, localY);
  1344. return _this;
  1345. }
  1346. return PointerInfoPre;
  1347. }(PointerInfoBase));
  1348. BABYLON.PointerInfoPre = PointerInfoPre;
  1349. /**
  1350. * This type contains all the data related to a pointer event in Babylon.js.
  1351. * 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.
  1352. */
  1353. var PointerInfo = /** @class */ (function (_super) {
  1354. __extends(PointerInfo, _super);
  1355. function PointerInfo(type, event, pickInfo) {
  1356. var _this = _super.call(this, type, event) || this;
  1357. _this.pickInfo = pickInfo;
  1358. return _this;
  1359. }
  1360. return PointerInfo;
  1361. }(PointerInfoBase));
  1362. BABYLON.PointerInfo = PointerInfo;
  1363. })(BABYLON || (BABYLON = {}));
  1364. //# sourceMappingURL=babylon.pointerEvents.js.map
  1365. "use strict";
  1366. var BABYLON;
  1367. (function (BABYLON) {
  1368. BABYLON.ToGammaSpace = 1 / 2.2;
  1369. BABYLON.ToLinearSpace = 2.2;
  1370. BABYLON.Epsilon = 0.001;
  1371. /**
  1372. * Class used to hold a RBG color
  1373. */
  1374. var Color3 = /** @class */ (function () {
  1375. /**
  1376. * Creates a new Color3 object from red, green, blue values, all between 0 and 1
  1377. * @param r defines the red component (between 0 and 1, default is 0)
  1378. * @param g defines the green component (between 0 and 1, default is 0)
  1379. * @param b defines the blue component (between 0 and 1, default is 0)
  1380. */
  1381. function Color3(
  1382. /**
  1383. * Defines the red component (between 0 and 1, default is 0)
  1384. */
  1385. r,
  1386. /**
  1387. * Defines the green component (between 0 and 1, default is 0)
  1388. */
  1389. g,
  1390. /**
  1391. * Defines the blue component (between 0 and 1, default is 0)
  1392. */
  1393. b) {
  1394. if (r === void 0) { r = 0; }
  1395. if (g === void 0) { g = 0; }
  1396. if (b === void 0) { b = 0; }
  1397. this.r = r;
  1398. this.g = g;
  1399. this.b = b;
  1400. }
  1401. /**
  1402. * Creates a string with the Color3 current values
  1403. * @returns the string representation of the Color3 object
  1404. */
  1405. Color3.prototype.toString = function () {
  1406. return "{R: " + this.r + " G:" + this.g + " B:" + this.b + "}";
  1407. };
  1408. /**
  1409. * Returns the string "Color3"
  1410. * @returns "Color3"
  1411. */
  1412. Color3.prototype.getClassName = function () {
  1413. return "Color3";
  1414. };
  1415. /**
  1416. * Compute the Color3 hash code
  1417. * @returns an unique number that can be used to hash Color3 objects
  1418. */
  1419. Color3.prototype.getHashCode = function () {
  1420. var hash = this.r || 0;
  1421. hash = (hash * 397) ^ (this.g || 0);
  1422. hash = (hash * 397) ^ (this.b || 0);
  1423. return hash;
  1424. };
  1425. // Operators
  1426. /**
  1427. * Stores in the passed array from the passed starting index the red, green, blue values as successive elements
  1428. * @param array defines the array where to store the r,g,b components
  1429. * @param index defines an optional index in the target array to define where to start storing values
  1430. * @returns the current Color3 object
  1431. */
  1432. Color3.prototype.toArray = function (array, index) {
  1433. if (index === undefined) {
  1434. index = 0;
  1435. }
  1436. array[index] = this.r;
  1437. array[index + 1] = this.g;
  1438. array[index + 2] = this.b;
  1439. return this;
  1440. };
  1441. /**
  1442. * Returns a new {BABYLON.Color4} object from the current Color3 and the passed alpha
  1443. * @param alpha defines the alpha component on the new {BABYLON.Color4} object (default is 1)
  1444. * @returns a new {BABYLON.Color4} object
  1445. */
  1446. Color3.prototype.toColor4 = function (alpha) {
  1447. if (alpha === void 0) { alpha = 1; }
  1448. return new Color4(this.r, this.g, this.b, alpha);
  1449. };
  1450. /**
  1451. * Returns a new array populated with 3 numeric elements : red, green and blue values
  1452. * @returns the new array
  1453. */
  1454. Color3.prototype.asArray = function () {
  1455. var result = new Array();
  1456. this.toArray(result, 0);
  1457. return result;
  1458. };
  1459. /**
  1460. * Returns the luminance value
  1461. * @returns a float value
  1462. */
  1463. Color3.prototype.toLuminance = function () {
  1464. return this.r * 0.3 + this.g * 0.59 + this.b * 0.11;
  1465. };
  1466. /**
  1467. * Multiply each Color3 rgb values by the passed Color3 rgb values in a new Color3 object
  1468. * @param otherColor defines the second operand
  1469. * @returns the new Color3 object
  1470. */
  1471. Color3.prototype.multiply = function (otherColor) {
  1472. return new Color3(this.r * otherColor.r, this.g * otherColor.g, this.b * otherColor.b);
  1473. };
  1474. /**
  1475. * Multiply the rgb values of the Color3 and the passed Color3 and stores the result in the object "result"
  1476. * @param otherColor defines the second operand
  1477. * @param result defines the Color3 object where to store the result
  1478. * @returns the current Color3
  1479. */
  1480. Color3.prototype.multiplyToRef = function (otherColor, result) {
  1481. result.r = this.r * otherColor.r;
  1482. result.g = this.g * otherColor.g;
  1483. result.b = this.b * otherColor.b;
  1484. return this;
  1485. };
  1486. /**
  1487. * Determines equality between Color3 objects
  1488. * @param otherColor defines the second operand
  1489. * @returns true if the rgb values are equal to the passed ones
  1490. */
  1491. Color3.prototype.equals = function (otherColor) {
  1492. return otherColor && this.r === otherColor.r && this.g === otherColor.g && this.b === otherColor.b;
  1493. };
  1494. /**
  1495. * Determines equality between the current Color3 object and a set of r,b,g values
  1496. * @param r defines the red component to check
  1497. * @param g defines the green component to check
  1498. * @param b defines the blue component to check
  1499. * @returns true if the rgb values are equal to the passed ones
  1500. */
  1501. Color3.prototype.equalsFloats = function (r, g, b) {
  1502. return this.r === r && this.g === g && this.b === b;
  1503. };
  1504. /**
  1505. * Multiplies in place each rgb value by scale
  1506. * @param scale defines the scaling factor
  1507. * @returns the updated Color3
  1508. */
  1509. Color3.prototype.scale = function (scale) {
  1510. return new Color3(this.r * scale, this.g * scale, this.b * scale);
  1511. };
  1512. /**
  1513. * Multiplies the rgb values by scale and stores the result into "result"
  1514. * @param scale defines the scaling factor
  1515. * @param result defines the Color3 object where to store the result
  1516. * @returns the unmodified current Color3
  1517. */
  1518. Color3.prototype.scaleToRef = function (scale, result) {
  1519. result.r = this.r * scale;
  1520. result.g = this.g * scale;
  1521. result.b = this.b * scale;
  1522. return this;
  1523. };
  1524. /**
  1525. * Scale the current Color3 values by a factor and add the result to a given Color3
  1526. * @param scale defines the scale factor
  1527. * @param result defines color to store the result into
  1528. * @returns the unmodified current Color3
  1529. */
  1530. Color3.prototype.scaleAndAddToRef = function (scale, result) {
  1531. result.r += this.r * scale;
  1532. result.g += this.g * scale;
  1533. result.b += this.b * scale;
  1534. return this;
  1535. };
  1536. /**
  1537. * Clamps the rgb values by the min and max values and stores the result into "result"
  1538. * @param min defines minimum clamping value (default is 0)
  1539. * @param max defines maximum clamping value (default is 1)
  1540. * @param result defines color to store the result into
  1541. * @returns the original Color3
  1542. */
  1543. Color3.prototype.clampToRef = function (min, max, result) {
  1544. if (min === void 0) { min = 0; }
  1545. if (max === void 0) { max = 1; }
  1546. result.r = BABYLON.Scalar.Clamp(this.r, min, max);
  1547. result.g = BABYLON.Scalar.Clamp(this.g, min, max);
  1548. result.b = BABYLON.Scalar.Clamp(this.b, min, max);
  1549. return this;
  1550. };
  1551. /**
  1552. * Creates a new Color3 set with the added values of the current Color3 and of the passed one
  1553. * @param otherColor defines the second operand
  1554. * @returns the new Color3
  1555. */
  1556. Color3.prototype.add = function (otherColor) {
  1557. return new Color3(this.r + otherColor.r, this.g + otherColor.g, this.b + otherColor.b);
  1558. };
  1559. /**
  1560. * Stores the result of the addition of the current Color3 and passed one rgb values into "result"
  1561. * @param otherColor defines the second operand
  1562. * @param result defines Color3 object to store the result into
  1563. * @returns the unmodified current Color3
  1564. */
  1565. Color3.prototype.addToRef = function (otherColor, result) {
  1566. result.r = this.r + otherColor.r;
  1567. result.g = this.g + otherColor.g;
  1568. result.b = this.b + otherColor.b;
  1569. return this;
  1570. };
  1571. /**
  1572. * Returns a new Color3 set with the subtracted values of the passed one from the current Color3
  1573. * @param otherColor defines the second operand
  1574. * @returns the new Color3
  1575. */
  1576. Color3.prototype.subtract = function (otherColor) {
  1577. return new Color3(this.r - otherColor.r, this.g - otherColor.g, this.b - otherColor.b);
  1578. };
  1579. /**
  1580. * Stores the result of the subtraction of passed one from the current Color3 rgb values into "result"
  1581. * @param otherColor defines the second operand
  1582. * @param result defines Color3 object to store the result into
  1583. * @returns the unmodified current Color3
  1584. */
  1585. Color3.prototype.subtractToRef = function (otherColor, result) {
  1586. result.r = this.r - otherColor.r;
  1587. result.g = this.g - otherColor.g;
  1588. result.b = this.b - otherColor.b;
  1589. return this;
  1590. };
  1591. /**
  1592. * Copy the current object
  1593. * @returns a new Color3 copied the current one
  1594. */
  1595. Color3.prototype.clone = function () {
  1596. return new Color3(this.r, this.g, this.b);
  1597. };
  1598. /**
  1599. * Copies the rgb values from the source in the current Color3
  1600. * @param source defines the source Color3 object
  1601. * @returns the updated Color3 object
  1602. */
  1603. Color3.prototype.copyFrom = function (source) {
  1604. this.r = source.r;
  1605. this.g = source.g;
  1606. this.b = source.b;
  1607. return this;
  1608. };
  1609. /**
  1610. * Updates the Color3 rgb values from the passed floats
  1611. * @param r defines the red component to read from
  1612. * @param g defines the green component to read from
  1613. * @param b defines the blue component to read from
  1614. * @returns the current Color3 object
  1615. */
  1616. Color3.prototype.copyFromFloats = function (r, g, b) {
  1617. this.r = r;
  1618. this.g = g;
  1619. this.b = b;
  1620. return this;
  1621. };
  1622. /**
  1623. * Updates the Color3 rgb values from the passed floats
  1624. * @param r defines the red component to read from
  1625. * @param g defines the green component to read from
  1626. * @param b defines the blue component to read from
  1627. * @returns the current Color3 object
  1628. */
  1629. Color3.prototype.set = function (r, g, b) {
  1630. return this.copyFromFloats(r, g, b);
  1631. };
  1632. /**
  1633. * Compute the Color3 hexadecimal code as a string
  1634. * @returns a string containing the hexadecimal representation of the Color3 object
  1635. */
  1636. Color3.prototype.toHexString = function () {
  1637. var intR = (this.r * 255) | 0;
  1638. var intG = (this.g * 255) | 0;
  1639. var intB = (this.b * 255) | 0;
  1640. return "#" + BABYLON.Scalar.ToHex(intR) + BABYLON.Scalar.ToHex(intG) + BABYLON.Scalar.ToHex(intB);
  1641. };
  1642. /**
  1643. * Computes a new Color3 converted from the current one to linear space
  1644. * @returns a new Color3 object
  1645. */
  1646. Color3.prototype.toLinearSpace = function () {
  1647. var convertedColor = new Color3();
  1648. this.toLinearSpaceToRef(convertedColor);
  1649. return convertedColor;
  1650. };
  1651. /**
  1652. * Converts the Color3 values to linear space and stores the result in "convertedColor"
  1653. * @param convertedColor defines the Color3 object where to store the linear space version
  1654. * @returns the unmodified Color3
  1655. */
  1656. Color3.prototype.toLinearSpaceToRef = function (convertedColor) {
  1657. convertedColor.r = Math.pow(this.r, BABYLON.ToLinearSpace);
  1658. convertedColor.g = Math.pow(this.g, BABYLON.ToLinearSpace);
  1659. convertedColor.b = Math.pow(this.b, BABYLON.ToLinearSpace);
  1660. return this;
  1661. };
  1662. /**
  1663. * Computes a new Color3 converted from the current one to gamma space
  1664. * @returns a new Color3 object
  1665. */
  1666. Color3.prototype.toGammaSpace = function () {
  1667. var convertedColor = new Color3();
  1668. this.toGammaSpaceToRef(convertedColor);
  1669. return convertedColor;
  1670. };
  1671. /**
  1672. * Converts the Color3 values to gamma space and stores the result in "convertedColor"
  1673. * @param convertedColor defines the Color3 object where to store the gamma space version
  1674. * @returns the unmodified Color3
  1675. */
  1676. Color3.prototype.toGammaSpaceToRef = function (convertedColor) {
  1677. convertedColor.r = Math.pow(this.r, BABYLON.ToGammaSpace);
  1678. convertedColor.g = Math.pow(this.g, BABYLON.ToGammaSpace);
  1679. convertedColor.b = Math.pow(this.b, BABYLON.ToGammaSpace);
  1680. return this;
  1681. };
  1682. // Statics
  1683. /**
  1684. * Creates a new Color3 from the string containing valid hexadecimal values
  1685. * @param hex defines a string containing valid hexadecimal values
  1686. * @returns a new Color3 object
  1687. */
  1688. Color3.FromHexString = function (hex) {
  1689. if (hex.substring(0, 1) !== "#" || hex.length !== 7) {
  1690. return new Color3(0, 0, 0);
  1691. }
  1692. var r = parseInt(hex.substring(1, 3), 16);
  1693. var g = parseInt(hex.substring(3, 5), 16);
  1694. var b = parseInt(hex.substring(5, 7), 16);
  1695. return Color3.FromInts(r, g, b);
  1696. };
  1697. /**
  1698. * Creates a new Vector3 from the starting index of the passed array
  1699. * @param array defines the source array
  1700. * @param offset defines an offset in the source array
  1701. * @returns a new Color3 object
  1702. */
  1703. Color3.FromArray = function (array, offset) {
  1704. if (offset === void 0) { offset = 0; }
  1705. return new Color3(array[offset], array[offset + 1], array[offset + 2]);
  1706. };
  1707. /**
  1708. * Creates a new Color3 from integer values (< 256)
  1709. * @param r defines the red component to read from (value between 0 and 255)
  1710. * @param g defines the green component to read from (value between 0 and 255)
  1711. * @param b defines the blue component to read from (value between 0 and 255)
  1712. * @returns a new Color3 object
  1713. */
  1714. Color3.FromInts = function (r, g, b) {
  1715. return new Color3(r / 255.0, g / 255.0, b / 255.0);
  1716. };
  1717. /**
  1718. * Creates a new Color3 with values linearly interpolated of "amount" between the start Color3 and the end Color3
  1719. * @param start defines the start Color3 value
  1720. * @param end defines the end Color3 value
  1721. * @param amount defines the gradient value between start and end
  1722. * @returns a new Color3 object
  1723. */
  1724. Color3.Lerp = function (start, end, amount) {
  1725. var r = start.r + ((end.r - start.r) * amount);
  1726. var g = start.g + ((end.g - start.g) * amount);
  1727. var b = start.b + ((end.b - start.b) * amount);
  1728. return new Color3(r, g, b);
  1729. };
  1730. /**
  1731. * Returns a Color3 value containing a red color
  1732. * @returns a new Color3 object
  1733. */
  1734. Color3.Red = function () { return new Color3(1, 0, 0); };
  1735. /**
  1736. * Returns a Color3 value containing a green color
  1737. * @returns a new Color3 object
  1738. */
  1739. Color3.Green = function () { return new Color3(0, 1, 0); };
  1740. /**
  1741. * Returns a Color3 value containing a blue color
  1742. * @returns a new Color3 object
  1743. */
  1744. Color3.Blue = function () { return new Color3(0, 0, 1); };
  1745. /**
  1746. * Returns a Color3 value containing a black color
  1747. * @returns a new Color3 object
  1748. */
  1749. Color3.Black = function () { return new Color3(0, 0, 0); };
  1750. /**
  1751. * Returns a Color3 value containing a white color
  1752. * @returns a new Color3 object
  1753. */
  1754. Color3.White = function () { return new Color3(1, 1, 1); };
  1755. /**
  1756. * Returns a Color3 value containing a purple color
  1757. * @returns a new Color3 object
  1758. */
  1759. Color3.Purple = function () { return new Color3(0.5, 0, 0.5); };
  1760. /**
  1761. * Returns a Color3 value containing a magenta color
  1762. * @returns a new Color3 object
  1763. */
  1764. Color3.Magenta = function () { return new Color3(1, 0, 1); };
  1765. /**
  1766. * Returns a Color3 value containing a yellow color
  1767. * @returns a new Color3 object
  1768. */
  1769. Color3.Yellow = function () { return new Color3(1, 1, 0); };
  1770. /**
  1771. * Returns a Color3 value containing a gray color
  1772. * @returns a new Color3 object
  1773. */
  1774. Color3.Gray = function () { return new Color3(0.5, 0.5, 0.5); };
  1775. /**
  1776. * Returns a Color3 value containing a teal color
  1777. * @returns a new Color3 object
  1778. */
  1779. Color3.Teal = function () { return new Color3(0, 1.0, 1.0); };
  1780. /**
  1781. * Returns a Color3 value containing a random color
  1782. * @returns a new Color3 object
  1783. */
  1784. Color3.Random = function () { return new Color3(Math.random(), Math.random(), Math.random()); };
  1785. return Color3;
  1786. }());
  1787. BABYLON.Color3 = Color3;
  1788. /**
  1789. * Class used to hold a RBGA color
  1790. */
  1791. var Color4 = /** @class */ (function () {
  1792. /**
  1793. * Creates a new Color4 object from red, green, blue values, all between 0 and 1
  1794. * @param r defines the red component (between 0 and 1, default is 0)
  1795. * @param g defines the green component (between 0 and 1, default is 0)
  1796. * @param b defines the blue component (between 0 and 1, default is 0)
  1797. * @param a defines the alpha component (between 0 and 1, default is 1)
  1798. */
  1799. function Color4(
  1800. /**
  1801. * Defines the red component (between 0 and 1, default is 0)
  1802. */
  1803. r,
  1804. /**
  1805. * Defines the green component (between 0 and 1, default is 0)
  1806. */
  1807. g,
  1808. /**
  1809. * Defines the blue component (between 0 and 1, default is 0)
  1810. */
  1811. b,
  1812. /**
  1813. * Defines the alpha component (between 0 and 1, default is 1)
  1814. */
  1815. a) {
  1816. if (r === void 0) { r = 0; }
  1817. if (g === void 0) { g = 0; }
  1818. if (b === void 0) { b = 0; }
  1819. if (a === void 0) { a = 1; }
  1820. this.r = r;
  1821. this.g = g;
  1822. this.b = b;
  1823. this.a = a;
  1824. }
  1825. // Operators
  1826. /**
  1827. * Adds in place the passed Color4 values to the current Color4 object
  1828. * @param right defines the second operand
  1829. * @returns the current updated Color4 object
  1830. */
  1831. Color4.prototype.addInPlace = function (right) {
  1832. this.r += right.r;
  1833. this.g += right.g;
  1834. this.b += right.b;
  1835. this.a += right.a;
  1836. return this;
  1837. };
  1838. /**
  1839. * Creates a new array populated with 4 numeric elements : red, green, blue, alpha values
  1840. * @returns the new array
  1841. */
  1842. Color4.prototype.asArray = function () {
  1843. var result = new Array();
  1844. this.toArray(result, 0);
  1845. return result;
  1846. };
  1847. /**
  1848. * Stores from the starting index in the passed array the Color4 successive values
  1849. * @param array defines the array where to store the r,g,b components
  1850. * @param index defines an optional index in the target array to define where to start storing values
  1851. * @returns the current Color4 object
  1852. */
  1853. Color4.prototype.toArray = function (array, index) {
  1854. if (index === undefined) {
  1855. index = 0;
  1856. }
  1857. array[index] = this.r;
  1858. array[index + 1] = this.g;
  1859. array[index + 2] = this.b;
  1860. array[index + 3] = this.a;
  1861. return this;
  1862. };
  1863. /**
  1864. * Creates a new Color4 set with the added values of the current Color4 and of the passed one
  1865. * @param right defines the second operand
  1866. * @returns a new Color4 object
  1867. */
  1868. Color4.prototype.add = function (right) {
  1869. return new Color4(this.r + right.r, this.g + right.g, this.b + right.b, this.a + right.a);
  1870. };
  1871. /**
  1872. * Creates a new Color4 set with the subtracted values of the passed one from the current Color4
  1873. * @param right defines the second operand
  1874. * @returns a new Color4 object
  1875. */
  1876. Color4.prototype.subtract = function (right) {
  1877. return new Color4(this.r - right.r, this.g - right.g, this.b - right.b, this.a - right.a);
  1878. };
  1879. /**
  1880. * Subtracts the passed ones from the current Color4 values and stores the results in "result"
  1881. * @param right defines the second operand
  1882. * @param result defines the Color4 object where to store the result
  1883. * @returns the current Color4 object
  1884. */
  1885. Color4.prototype.subtractToRef = function (right, result) {
  1886. result.r = this.r - right.r;
  1887. result.g = this.g - right.g;
  1888. result.b = this.b - right.b;
  1889. result.a = this.a - right.a;
  1890. return this;
  1891. };
  1892. /**
  1893. * Creates a new Color4 with the current Color4 values multiplied by scale
  1894. * @param scale defines the scaling factor to apply
  1895. * @returns a new Color4 object
  1896. */
  1897. Color4.prototype.scale = function (scale) {
  1898. return new Color4(this.r * scale, this.g * scale, this.b * scale, this.a * scale);
  1899. };
  1900. /**
  1901. * Multiplies the current Color4 values by scale and stores the result in "result"
  1902. * @param scale defines the scaling factor to apply
  1903. * @param result defines the Color4 object where to store the result
  1904. * @returns the current unmodified Color4
  1905. */
  1906. Color4.prototype.scaleToRef = function (scale, result) {
  1907. result.r = this.r * scale;
  1908. result.g = this.g * scale;
  1909. result.b = this.b * scale;
  1910. result.a = this.a * scale;
  1911. return this;
  1912. };
  1913. /**
  1914. * Scale the current Color4 values by a factor and add the result to a given Color4
  1915. * @param scale defines the scale factor
  1916. * @param result defines the Color4 object where to store the result
  1917. * @returns the unmodified current Color4
  1918. */
  1919. Color4.prototype.scaleAndAddToRef = function (scale, result) {
  1920. result.r += this.r * scale;
  1921. result.g += this.g * scale;
  1922. result.b += this.b * scale;
  1923. result.a += this.a * scale;
  1924. return this;
  1925. };
  1926. /**
  1927. * Clamps the rgb values by the min and max values and stores the result into "result"
  1928. * @param min defines minimum clamping value (default is 0)
  1929. * @param max defines maximum clamping value (default is 1)
  1930. * @param result defines color to store the result into.
  1931. * @returns the cuurent Color4
  1932. */
  1933. Color4.prototype.clampToRef = function (min, max, result) {
  1934. if (min === void 0) { min = 0; }
  1935. if (max === void 0) { max = 1; }
  1936. result.r = BABYLON.Scalar.Clamp(this.r, min, max);
  1937. result.g = BABYLON.Scalar.Clamp(this.g, min, max);
  1938. result.b = BABYLON.Scalar.Clamp(this.b, min, max);
  1939. result.a = BABYLON.Scalar.Clamp(this.a, min, max);
  1940. return this;
  1941. };
  1942. /**
  1943. * Multipy an Color4 value by another and return a new Color4 object
  1944. * @param color defines the Color4 value to multiply by
  1945. * @returns a new Color4 object
  1946. */
  1947. Color4.prototype.multiply = function (color) {
  1948. return new Color4(this.r * color.r, this.g * color.g, this.b * color.b, this.a * color.a);
  1949. };
  1950. /**
  1951. * Multipy a Color4 value by another and push the result in a reference value
  1952. * @param color defines the Color4 value to multiply by
  1953. * @param result defines the Color4 to fill the result in
  1954. * @returns the result Color4
  1955. */
  1956. Color4.prototype.multiplyToRef = function (color, result) {
  1957. result.r = this.r * color.r;
  1958. result.g = this.g * color.g;
  1959. result.b = this.b * color.b;
  1960. result.a = this.a * color.a;
  1961. return result;
  1962. };
  1963. /**
  1964. * Creates a string with the Color4 current values
  1965. * @returns the string representation of the Color4 object
  1966. */
  1967. Color4.prototype.toString = function () {
  1968. return "{R: " + this.r + " G:" + this.g + " B:" + this.b + " A:" + this.a + "}";
  1969. };
  1970. /**
  1971. * Returns the string "Color4"
  1972. * @returns "Color4"
  1973. */
  1974. Color4.prototype.getClassName = function () {
  1975. return "Color4";
  1976. };
  1977. /**
  1978. * Compute the Color4 hash code
  1979. * @returns an unique number that can be used to hash Color4 objects
  1980. */
  1981. Color4.prototype.getHashCode = function () {
  1982. var hash = this.r || 0;
  1983. hash = (hash * 397) ^ (this.g || 0);
  1984. hash = (hash * 397) ^ (this.b || 0);
  1985. hash = (hash * 397) ^ (this.a || 0);
  1986. return hash;
  1987. };
  1988. /**
  1989. * Creates a new Color4 copied from the current one
  1990. * @returns a new Color4 object
  1991. */
  1992. Color4.prototype.clone = function () {
  1993. return new Color4(this.r, this.g, this.b, this.a);
  1994. };
  1995. /**
  1996. * Copies the passed Color4 values into the current one
  1997. * @param source defines the source Color4 object
  1998. * @returns the current updated Color4 object
  1999. */
  2000. Color4.prototype.copyFrom = function (source) {
  2001. this.r = source.r;
  2002. this.g = source.g;
  2003. this.b = source.b;
  2004. this.a = source.a;
  2005. return this;
  2006. };
  2007. /**
  2008. * Copies the passed float values into the current one
  2009. * @param r defines the red component to read from
  2010. * @param g defines the green component to read from
  2011. * @param b defines the blue component to read from
  2012. * @param a defines the alpha component to read from
  2013. * @returns the current updated Color4 object
  2014. */
  2015. Color4.prototype.copyFromFloats = function (r, g, b, a) {
  2016. this.r = r;
  2017. this.g = g;
  2018. this.b = b;
  2019. this.a = a;
  2020. return this;
  2021. };
  2022. /**
  2023. * Copies the passed float values into the current one
  2024. * @param r defines the red component to read from
  2025. * @param g defines the green component to read from
  2026. * @param b defines the blue component to read from
  2027. * @param a defines the alpha component to read from
  2028. * @returns the current updated Color4 object
  2029. */
  2030. Color4.prototype.set = function (r, g, b, a) {
  2031. return this.copyFromFloats(r, g, b, a);
  2032. };
  2033. /**
  2034. * Compute the Color4 hexadecimal code as a string
  2035. * @returns a string containing the hexadecimal representation of the Color4 object
  2036. */
  2037. Color4.prototype.toHexString = function () {
  2038. var intR = (this.r * 255) | 0;
  2039. var intG = (this.g * 255) | 0;
  2040. var intB = (this.b * 255) | 0;
  2041. var intA = (this.a * 255) | 0;
  2042. return "#" + BABYLON.Scalar.ToHex(intR) + BABYLON.Scalar.ToHex(intG) + BABYLON.Scalar.ToHex(intB) + BABYLON.Scalar.ToHex(intA);
  2043. };
  2044. /**
  2045. * Computes a new Color4 converted from the current one to linear space
  2046. * @returns a new Color4 object
  2047. */
  2048. Color4.prototype.toLinearSpace = function () {
  2049. var convertedColor = new Color4();
  2050. this.toLinearSpaceToRef(convertedColor);
  2051. return convertedColor;
  2052. };
  2053. /**
  2054. * Converts the Color4 values to linear space and stores the result in "convertedColor"
  2055. * @param convertedColor defines the Color4 object where to store the linear space version
  2056. * @returns the unmodified Color4
  2057. */
  2058. Color4.prototype.toLinearSpaceToRef = function (convertedColor) {
  2059. convertedColor.r = Math.pow(this.r, BABYLON.ToLinearSpace);
  2060. convertedColor.g = Math.pow(this.g, BABYLON.ToLinearSpace);
  2061. convertedColor.b = Math.pow(this.b, BABYLON.ToLinearSpace);
  2062. convertedColor.a = this.a;
  2063. return this;
  2064. };
  2065. /**
  2066. * Computes a new Color4 converted from the current one to gamma space
  2067. * @returns a new Color4 object
  2068. */
  2069. Color4.prototype.toGammaSpace = function () {
  2070. var convertedColor = new Color4();
  2071. this.toGammaSpaceToRef(convertedColor);
  2072. return convertedColor;
  2073. };
  2074. /**
  2075. * Converts the Color4 values to gamma space and stores the result in "convertedColor"
  2076. * @param convertedColor defines the Color4 object where to store the gamma space version
  2077. * @returns the unmodified Color4
  2078. */
  2079. Color4.prototype.toGammaSpaceToRef = function (convertedColor) {
  2080. convertedColor.r = Math.pow(this.r, BABYLON.ToGammaSpace);
  2081. convertedColor.g = Math.pow(this.g, BABYLON.ToGammaSpace);
  2082. convertedColor.b = Math.pow(this.b, BABYLON.ToGammaSpace);
  2083. convertedColor.a = this.a;
  2084. return this;
  2085. };
  2086. // Statics
  2087. /**
  2088. * Creates a new Color4 from the string containing valid hexadecimal values
  2089. * @param hex defines a string containing valid hexadecimal values
  2090. * @returns a new Color4 object
  2091. */
  2092. Color4.FromHexString = function (hex) {
  2093. if (hex.substring(0, 1) !== "#" || hex.length !== 9) {
  2094. return new Color4(0.0, 0.0, 0.0, 0.0);
  2095. }
  2096. var r = parseInt(hex.substring(1, 3), 16);
  2097. var g = parseInt(hex.substring(3, 5), 16);
  2098. var b = parseInt(hex.substring(5, 7), 16);
  2099. var a = parseInt(hex.substring(7, 9), 16);
  2100. return Color4.FromInts(r, g, b, a);
  2101. };
  2102. /**
  2103. * Creates a new Color4 object set with the linearly interpolated values of "amount" between the left Color4 object and the right Color4 object
  2104. * @param left defines the start value
  2105. * @param right defines the end value
  2106. * @param amount defines the gradient factor
  2107. * @returns a new Color4 object
  2108. */
  2109. Color4.Lerp = function (left, right, amount) {
  2110. var result = new Color4(0.0, 0.0, 0.0, 0.0);
  2111. Color4.LerpToRef(left, right, amount, result);
  2112. return result;
  2113. };
  2114. /**
  2115. * Set the passed "result" with the linearly interpolated values of "amount" between the left Color4 object and the right Color4 object
  2116. * @param left defines the start value
  2117. * @param right defines the end value
  2118. * @param amount defines the gradient factor
  2119. * @param result defines the Color4 object where to store data
  2120. */
  2121. Color4.LerpToRef = function (left, right, amount, result) {
  2122. result.r = left.r + (right.r - left.r) * amount;
  2123. result.g = left.g + (right.g - left.g) * amount;
  2124. result.b = left.b + (right.b - left.b) * amount;
  2125. result.a = left.a + (right.a - left.a) * amount;
  2126. };
  2127. /**
  2128. * Creates a new Color4 from the starting index element of the passed array
  2129. * @param array defines the source array to read from
  2130. * @param offset defines the offset in the source array
  2131. * @returns a new Color4 object
  2132. */
  2133. Color4.FromArray = function (array, offset) {
  2134. if (offset === void 0) { offset = 0; }
  2135. return new Color4(array[offset], array[offset + 1], array[offset + 2], array[offset + 3]);
  2136. };
  2137. /**
  2138. * Creates a new Color3 from integer values (< 256)
  2139. * @param r defines the red component to read from (value between 0 and 255)
  2140. * @param g defines the green component to read from (value between 0 and 255)
  2141. * @param b defines the blue component to read from (value between 0 and 255)
  2142. * @param a defines the alpha component to read from (value between 0 and 255)
  2143. * @returns a new Color3 object
  2144. */
  2145. Color4.FromInts = function (r, g, b, a) {
  2146. return new Color4(r / 255.0, g / 255.0, b / 255.0, a / 255.0);
  2147. };
  2148. /**
  2149. * Check the content of a given array and convert it to an array containing RGBA data
  2150. * If the original array was already containing count * 4 values then it is returned directly
  2151. * @param colors defines the array to check
  2152. * @param count defines the number of RGBA data to expect
  2153. * @returns an array containing count * 4 values (RGBA)
  2154. */
  2155. Color4.CheckColors4 = function (colors, count) {
  2156. // Check if color3 was used
  2157. if (colors.length === count * 3) {
  2158. var colors4 = [];
  2159. for (var index = 0; index < colors.length; index += 3) {
  2160. var newIndex = (index / 3) * 4;
  2161. colors4[newIndex] = colors[index];
  2162. colors4[newIndex + 1] = colors[index + 1];
  2163. colors4[newIndex + 2] = colors[index + 2];
  2164. colors4[newIndex + 3] = 1.0;
  2165. }
  2166. return colors4;
  2167. }
  2168. return colors;
  2169. };
  2170. return Color4;
  2171. }());
  2172. BABYLON.Color4 = Color4;
  2173. var Vector2 = /** @class */ (function () {
  2174. /**
  2175. * Creates a new Vector2 from the passed x and y coordinates.
  2176. */
  2177. function Vector2(x, y) {
  2178. this.x = x;
  2179. this.y = y;
  2180. }
  2181. /**
  2182. * Returns a string with the Vector2 coordinates.
  2183. */
  2184. Vector2.prototype.toString = function () {
  2185. return "{X: " + this.x + " Y:" + this.y + "}";
  2186. };
  2187. /**
  2188. * Returns the string "Vector2"
  2189. */
  2190. Vector2.prototype.getClassName = function () {
  2191. return "Vector2";
  2192. };
  2193. /**
  2194. * Returns the Vector2 hash code as a number.
  2195. */
  2196. Vector2.prototype.getHashCode = function () {
  2197. var hash = this.x || 0;
  2198. hash = (hash * 397) ^ (this.y || 0);
  2199. return hash;
  2200. };
  2201. // Operators
  2202. /**
  2203. * Sets the Vector2 coordinates in the passed array or Float32Array from the passed index.
  2204. * Returns the Vector2.
  2205. */
  2206. Vector2.prototype.toArray = function (array, index) {
  2207. if (index === void 0) { index = 0; }
  2208. array[index] = this.x;
  2209. array[index + 1] = this.y;
  2210. return this;
  2211. };
  2212. /**
  2213. * Returns a new array with 2 elements : the Vector2 coordinates.
  2214. */
  2215. Vector2.prototype.asArray = function () {
  2216. var result = new Array();
  2217. this.toArray(result, 0);
  2218. return result;
  2219. };
  2220. /**
  2221. * Sets the Vector2 coordinates with the passed Vector2 coordinates.
  2222. * Returns the updated Vector2.
  2223. */
  2224. Vector2.prototype.copyFrom = function (source) {
  2225. this.x = source.x;
  2226. this.y = source.y;
  2227. return this;
  2228. };
  2229. /**
  2230. * Sets the Vector2 coordinates with the passed floats.
  2231. * Returns the updated Vector2.
  2232. */
  2233. Vector2.prototype.copyFromFloats = function (x, y) {
  2234. this.x = x;
  2235. this.y = y;
  2236. return this;
  2237. };
  2238. /**
  2239. * Sets the Vector2 coordinates with the passed floats.
  2240. * Returns the updated Vector2.
  2241. */
  2242. Vector2.prototype.set = function (x, y) {
  2243. return this.copyFromFloats(x, y);
  2244. };
  2245. /**
  2246. * Returns a new Vector2 set with the addition of the current Vector2 and the passed one coordinates.
  2247. */
  2248. Vector2.prototype.add = function (otherVector) {
  2249. return new Vector2(this.x + otherVector.x, this.y + otherVector.y);
  2250. };
  2251. /**
  2252. * Sets the "result" coordinates with the addition of the current Vector2 and the passed one coordinates.
  2253. * Returns the Vector2.
  2254. */
  2255. Vector2.prototype.addToRef = function (otherVector, result) {
  2256. result.x = this.x + otherVector.x;
  2257. result.y = this.y + otherVector.y;
  2258. return this;
  2259. };
  2260. /**
  2261. * Set the Vector2 coordinates by adding the passed Vector2 coordinates.
  2262. * Returns the updated Vector2.
  2263. */
  2264. Vector2.prototype.addInPlace = function (otherVector) {
  2265. this.x += otherVector.x;
  2266. this.y += otherVector.y;
  2267. return this;
  2268. };
  2269. /**
  2270. * Returns a new Vector2 by adding the current Vector2 coordinates to the passed Vector3 x, y coordinates.
  2271. */
  2272. Vector2.prototype.addVector3 = function (otherVector) {
  2273. return new Vector2(this.x + otherVector.x, this.y + otherVector.y);
  2274. };
  2275. /**
  2276. * Returns a new Vector2 set with the subtracted coordinates of the passed one from the current Vector2.
  2277. */
  2278. Vector2.prototype.subtract = function (otherVector) {
  2279. return new Vector2(this.x - otherVector.x, this.y - otherVector.y);
  2280. };
  2281. /**
  2282. * Sets the "result" coordinates with the subtraction of the passed one from the current Vector2 coordinates.
  2283. * Returns the Vector2.
  2284. */
  2285. Vector2.prototype.subtractToRef = function (otherVector, result) {
  2286. result.x = this.x - otherVector.x;
  2287. result.y = this.y - otherVector.y;
  2288. return this;
  2289. };
  2290. /**
  2291. * Sets the current Vector2 coordinates by subtracting from it the passed one coordinates.
  2292. * Returns the updated Vector2.
  2293. */
  2294. Vector2.prototype.subtractInPlace = function (otherVector) {
  2295. this.x -= otherVector.x;
  2296. this.y -= otherVector.y;
  2297. return this;
  2298. };
  2299. /**
  2300. * Multiplies in place the current Vector2 coordinates by the passed ones.
  2301. * Returns the updated Vector2.
  2302. */
  2303. Vector2.prototype.multiplyInPlace = function (otherVector) {
  2304. this.x *= otherVector.x;
  2305. this.y *= otherVector.y;
  2306. return this;
  2307. };
  2308. /**
  2309. * Returns a new Vector2 set with the multiplication of the current Vector2 and the passed one coordinates.
  2310. */
  2311. Vector2.prototype.multiply = function (otherVector) {
  2312. return new Vector2(this.x * otherVector.x, this.y * otherVector.y);
  2313. };
  2314. /**
  2315. * Sets "result" coordinates with the multiplication of the current Vector2 and the passed one coordinates.
  2316. * Returns the Vector2.
  2317. */
  2318. Vector2.prototype.multiplyToRef = function (otherVector, result) {
  2319. result.x = this.x * otherVector.x;
  2320. result.y = this.y * otherVector.y;
  2321. return this;
  2322. };
  2323. /**
  2324. * Returns a new Vector2 set with the Vector2 coordinates multiplied by the passed floats.
  2325. */
  2326. Vector2.prototype.multiplyByFloats = function (x, y) {
  2327. return new Vector2(this.x * x, this.y * y);
  2328. };
  2329. /**
  2330. * Returns a new Vector2 set with the Vector2 coordinates divided by the passed one coordinates.
  2331. */
  2332. Vector2.prototype.divide = function (otherVector) {
  2333. return new Vector2(this.x / otherVector.x, this.y / otherVector.y);
  2334. };
  2335. /**
  2336. * Sets the "result" coordinates with the Vector2 divided by the passed one coordinates.
  2337. * Returns the Vector2.
  2338. */
  2339. Vector2.prototype.divideToRef = function (otherVector, result) {
  2340. result.x = this.x / otherVector.x;
  2341. result.y = this.y / otherVector.y;
  2342. return this;
  2343. };
  2344. /**
  2345. * Divides the current Vector3 coordinates by the passed ones.
  2346. * Returns the updated Vector3.
  2347. */
  2348. Vector2.prototype.divideInPlace = function (otherVector) {
  2349. return this.divideToRef(otherVector, this);
  2350. };
  2351. /**
  2352. * Returns a new Vector2 with current Vector2 negated coordinates.
  2353. */
  2354. Vector2.prototype.negate = function () {
  2355. return new Vector2(-this.x, -this.y);
  2356. };
  2357. /**
  2358. * Multiply the Vector2 coordinates by scale.
  2359. * Returns the updated Vector2.
  2360. */
  2361. Vector2.prototype.scaleInPlace = function (scale) {
  2362. this.x *= scale;
  2363. this.y *= scale;
  2364. return this;
  2365. };
  2366. /**
  2367. * Returns a new Vector2 scaled by "scale" from the current Vector2.
  2368. */
  2369. Vector2.prototype.scale = function (scale) {
  2370. var result = new Vector2(0, 0);
  2371. this.scaleToRef(scale, result);
  2372. return result;
  2373. };
  2374. /**
  2375. * Scale the current Vector2 values by a factor to a given Vector2
  2376. * @param scale defines the scale factor
  2377. * @param result defines the Vector2 object where to store the result
  2378. * @returns the unmodified current Vector2
  2379. */
  2380. Vector2.prototype.scaleToRef = function (scale, result) {
  2381. result.x = this.x * scale;
  2382. result.y = this.y * scale;
  2383. return this;
  2384. };
  2385. /**
  2386. * Scale the current Vector2 values by a factor and add the result to a given Vector2
  2387. * @param scale defines the scale factor
  2388. * @param result defines the Vector2 object where to store the result
  2389. * @returns the unmodified current Vector2
  2390. */
  2391. Vector2.prototype.scaleAndAddToRef = function (scale, result) {
  2392. result.x += this.x * scale;
  2393. result.y += this.y * scale;
  2394. return this;
  2395. };
  2396. /**
  2397. * Boolean : True if the passed vector coordinates strictly equal the current Vector2 ones.
  2398. */
  2399. Vector2.prototype.equals = function (otherVector) {
  2400. return otherVector && this.x === otherVector.x && this.y === otherVector.y;
  2401. };
  2402. /**
  2403. * Boolean : True if the passed vector coordinates are close to the current ones by a distance of epsilon.
  2404. */
  2405. Vector2.prototype.equalsWithEpsilon = function (otherVector, epsilon) {
  2406. if (epsilon === void 0) { epsilon = BABYLON.Epsilon; }
  2407. return otherVector && BABYLON.Scalar.WithinEpsilon(this.x, otherVector.x, epsilon) && BABYLON.Scalar.WithinEpsilon(this.y, otherVector.y, epsilon);
  2408. };
  2409. // Properties
  2410. /**
  2411. * Returns the vector length (float).
  2412. */
  2413. Vector2.prototype.length = function () {
  2414. return Math.sqrt(this.x * this.x + this.y * this.y);
  2415. };
  2416. /**
  2417. * Returns the vector squared length (float);
  2418. */
  2419. Vector2.prototype.lengthSquared = function () {
  2420. return (this.x * this.x + this.y * this.y);
  2421. };
  2422. // Methods
  2423. /**
  2424. * Normalize the vector.
  2425. * Returns the updated Vector2.
  2426. */
  2427. Vector2.prototype.normalize = function () {
  2428. var len = this.length();
  2429. if (len === 0)
  2430. return this;
  2431. var num = 1.0 / len;
  2432. this.x *= num;
  2433. this.y *= num;
  2434. return this;
  2435. };
  2436. /**
  2437. * Returns a new Vector2 copied from the Vector2.
  2438. */
  2439. Vector2.prototype.clone = function () {
  2440. return new Vector2(this.x, this.y);
  2441. };
  2442. // Statics
  2443. /**
  2444. * Returns a new Vector2(0, 0)
  2445. */
  2446. Vector2.Zero = function () {
  2447. return new Vector2(0, 0);
  2448. };
  2449. /**
  2450. * Returns a new Vector2(1, 1)
  2451. */
  2452. Vector2.One = function () {
  2453. return new Vector2(1, 1);
  2454. };
  2455. /**
  2456. * Returns a new Vector2 set from the passed index element of the passed array.
  2457. */
  2458. Vector2.FromArray = function (array, offset) {
  2459. if (offset === void 0) { offset = 0; }
  2460. return new Vector2(array[offset], array[offset + 1]);
  2461. };
  2462. /**
  2463. * Sets "result" from the passed index element of the passed array.
  2464. */
  2465. Vector2.FromArrayToRef = function (array, offset, result) {
  2466. result.x = array[offset];
  2467. result.y = array[offset + 1];
  2468. };
  2469. /**
  2470. * Retuns a new Vector2 located for "amount" (float) on the CatmullRom spline defined by the passed four Vector2.
  2471. */
  2472. Vector2.CatmullRom = function (value1, value2, value3, value4, amount) {
  2473. var squared = amount * amount;
  2474. var cubed = amount * squared;
  2475. var x = 0.5 * ((((2.0 * value2.x) + ((-value1.x + value3.x) * amount)) +
  2476. (((((2.0 * value1.x) - (5.0 * value2.x)) + (4.0 * value3.x)) - value4.x) * squared)) +
  2477. ((((-value1.x + (3.0 * value2.x)) - (3.0 * value3.x)) + value4.x) * cubed));
  2478. var y = 0.5 * ((((2.0 * value2.y) + ((-value1.y + value3.y) * amount)) +
  2479. (((((2.0 * value1.y) - (5.0 * value2.y)) + (4.0 * value3.y)) - value4.y) * squared)) +
  2480. ((((-value1.y + (3.0 * value2.y)) - (3.0 * value3.y)) + value4.y) * cubed));
  2481. return new Vector2(x, y);
  2482. };
  2483. /**
  2484. * 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".
  2485. * If a coordinate of "value" is lower than "min" coordinates, the returned Vector2 is given this "min" coordinate.
  2486. * If a coordinate of "value" is greater than "max" coordinates, the returned Vector2 is given this "max" coordinate.
  2487. */
  2488. Vector2.Clamp = function (value, min, max) {
  2489. var x = value.x;
  2490. x = (x > max.x) ? max.x : x;
  2491. x = (x < min.x) ? min.x : x;
  2492. var y = value.y;
  2493. y = (y > max.y) ? max.y : y;
  2494. y = (y < min.y) ? min.y : y;
  2495. return new Vector2(x, y);
  2496. };
  2497. /**
  2498. * Returns a new Vector2 located for "amount" (float) on the Hermite spline defined by the vectors "value1", "value3", "tangent1", "tangent2".
  2499. */
  2500. Vector2.Hermite = function (value1, tangent1, value2, tangent2, amount) {
  2501. var squared = amount * amount;
  2502. var cubed = amount * squared;
  2503. var part1 = ((2.0 * cubed) - (3.0 * squared)) + 1.0;
  2504. var part2 = (-2.0 * cubed) + (3.0 * squared);
  2505. var part3 = (cubed - (2.0 * squared)) + amount;
  2506. var part4 = cubed - squared;
  2507. var x = (((value1.x * part1) + (value2.x * part2)) + (tangent1.x * part3)) + (tangent2.x * part4);
  2508. var y = (((value1.y * part1) + (value2.y * part2)) + (tangent1.y * part3)) + (tangent2.y * part4);
  2509. return new Vector2(x, y);
  2510. };
  2511. /**
  2512. * Returns a new Vector2 located for "amount" (float) on the linear interpolation between the vector "start" adn the vector "end".
  2513. */
  2514. Vector2.Lerp = function (start, end, amount) {
  2515. var x = start.x + ((end.x - start.x) * amount);
  2516. var y = start.y + ((end.y - start.y) * amount);
  2517. return new Vector2(x, y);
  2518. };
  2519. /**
  2520. * Returns the dot product (float) of the vector "left" and the vector "right".
  2521. */
  2522. Vector2.Dot = function (left, right) {
  2523. return left.x * right.x + left.y * right.y;
  2524. };
  2525. /**
  2526. * Returns a new Vector2 equal to the normalized passed vector.
  2527. */
  2528. Vector2.Normalize = function (vector) {
  2529. var newVector = vector.clone();
  2530. newVector.normalize();
  2531. return newVector;
  2532. };
  2533. /**
  2534. * Returns a new Vecto2 set with the minimal coordinate values from the "left" and "right" vectors.
  2535. */
  2536. Vector2.Minimize = function (left, right) {
  2537. var x = (left.x < right.x) ? left.x : right.x;
  2538. var y = (left.y < right.y) ? left.y : right.y;
  2539. return new Vector2(x, y);
  2540. };
  2541. /**
  2542. * Returns a new Vecto2 set with the maximal coordinate values from the "left" and "right" vectors.
  2543. */
  2544. Vector2.Maximize = function (left, right) {
  2545. var x = (left.x > right.x) ? left.x : right.x;
  2546. var y = (left.y > right.y) ? left.y : right.y;
  2547. return new Vector2(x, y);
  2548. };
  2549. /**
  2550. * Returns a new Vecto2 set with the transformed coordinates of the passed vector by the passed transformation matrix.
  2551. */
  2552. Vector2.Transform = function (vector, transformation) {
  2553. var r = Vector2.Zero();
  2554. Vector2.TransformToRef(vector, transformation, r);
  2555. return r;
  2556. };
  2557. /**
  2558. * Transforms the passed vector coordinates by the passed transformation matrix and stores the result in the vector "result" coordinates.
  2559. */
  2560. Vector2.TransformToRef = function (vector, transformation, result) {
  2561. var x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]) + transformation.m[12];
  2562. var y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]) + transformation.m[13];
  2563. result.x = x;
  2564. result.y = y;
  2565. };
  2566. /**
  2567. * Boolean : True if the point "p" is in the triangle defined by the vertors "p0", "p1", "p2"
  2568. */
  2569. Vector2.PointInTriangle = function (p, p0, p1, p2) {
  2570. var a = 1 / 2 * (-p1.y * p2.x + p0.y * (-p1.x + p2.x) + p0.x * (p1.y - p2.y) + p1.x * p2.y);
  2571. var sign = a < 0 ? -1 : 1;
  2572. var s = (p0.y * p2.x - p0.x * p2.y + (p2.y - p0.y) * p.x + (p0.x - p2.x) * p.y) * sign;
  2573. var t = (p0.x * p1.y - p0.y * p1.x + (p0.y - p1.y) * p.x + (p1.x - p0.x) * p.y) * sign;
  2574. return s > 0 && t > 0 && (s + t) < 2 * a * sign;
  2575. };
  2576. /**
  2577. * Returns the distance (float) between the vectors "value1" and "value2".
  2578. */
  2579. Vector2.Distance = function (value1, value2) {
  2580. return Math.sqrt(Vector2.DistanceSquared(value1, value2));
  2581. };
  2582. /**
  2583. * Returns the squared distance (float) between the vectors "value1" and "value2".
  2584. */
  2585. Vector2.DistanceSquared = function (value1, value2) {
  2586. var x = value1.x - value2.x;
  2587. var y = value1.y - value2.y;
  2588. return (x * x) + (y * y);
  2589. };
  2590. /**
  2591. * Returns a new Vecto2 located at the center of the vectors "value1" and "value2".
  2592. */
  2593. Vector2.Center = function (value1, value2) {
  2594. var center = value1.add(value2);
  2595. center.scaleInPlace(0.5);
  2596. return center;
  2597. };
  2598. /**
  2599. * Returns the shortest distance (float) between the point "p" and the segment defined by the two points "segA" and "segB".
  2600. */
  2601. Vector2.DistanceOfPointFromSegment = function (p, segA, segB) {
  2602. var l2 = Vector2.DistanceSquared(segA, segB);
  2603. if (l2 === 0.0) {
  2604. return Vector2.Distance(p, segA);
  2605. }
  2606. var v = segB.subtract(segA);
  2607. var t = Math.max(0, Math.min(1, Vector2.Dot(p.subtract(segA), v) / l2));
  2608. var proj = segA.add(v.multiplyByFloats(t, t));
  2609. return Vector2.Distance(p, proj);
  2610. };
  2611. return Vector2;
  2612. }());
  2613. BABYLON.Vector2 = Vector2;
  2614. /**
  2615. * Classed used to store (x,y,z) vector representation
  2616. * A Vector3 is the main object used in 3D geometry
  2617. * It can represent etiher the coordinates of a point the space, either a direction
  2618. * Reminder: Babylon.js uses a left handed forward facing system
  2619. */
  2620. var Vector3 = /** @class */ (function () {
  2621. /**
  2622. * Creates a new Vector3 object from the passed x, y, z (floats) coordinates.
  2623. * @param x defines the first coordinates (on X axis)
  2624. * @param y defines the second coordinates (on Y axis)
  2625. * @param z defines the third coordinates (on Z axis)
  2626. */
  2627. function Vector3(
  2628. /**
  2629. * Defines the first coordinates (on X axis)
  2630. */
  2631. x,
  2632. /**
  2633. * Defines the second coordinates (on Y axis)
  2634. */
  2635. y,
  2636. /**
  2637. * Defines the third coordinates (on Z axis)
  2638. */
  2639. z) {
  2640. this.x = x;
  2641. this.y = y;
  2642. this.z = z;
  2643. }
  2644. /**
  2645. * Creates a string representation of the Vector3
  2646. * @returns a string with the Vector3 coordinates.
  2647. */
  2648. Vector3.prototype.toString = function () {
  2649. return "{X: " + this.x + " Y:" + this.y + " Z:" + this.z + "}";
  2650. };
  2651. /**
  2652. * Gets the class name
  2653. * @returns the string "Vector3"
  2654. */
  2655. Vector3.prototype.getClassName = function () {
  2656. return "Vector3";
  2657. };
  2658. /**
  2659. * Creates the Vector3 hash code
  2660. * @returns a number which tends to be unique between Vector3 instances
  2661. */
  2662. Vector3.prototype.getHashCode = function () {
  2663. var hash = this.x || 0;
  2664. hash = (hash * 397) ^ (this.y || 0);
  2665. hash = (hash * 397) ^ (this.z || 0);
  2666. return hash;
  2667. };
  2668. // Operators
  2669. /**
  2670. * Creates an array containing three elements : the coordinates of the Vector3
  2671. * @returns a new array of numbers
  2672. */
  2673. Vector3.prototype.asArray = function () {
  2674. var result = [];
  2675. this.toArray(result, 0);
  2676. return result;
  2677. };
  2678. /**
  2679. * Populates the passed array or Float32Array from the passed index with the successive coordinates of the Vector3
  2680. * @param array defines the destination array
  2681. * @param index defines the offset in the destination array
  2682. * @returns the current Vector3
  2683. */
  2684. Vector3.prototype.toArray = function (array, index) {
  2685. if (index === void 0) { index = 0; }
  2686. array[index] = this.x;
  2687. array[index + 1] = this.y;
  2688. array[index + 2] = this.z;
  2689. return this;
  2690. };
  2691. /**
  2692. * Converts the current Vector3 into a quaternion (considering that the Vector3 contains Euler angles representation of a rotation)
  2693. * @returns a new Quaternion object, computed from the Vector3 coordinates
  2694. */
  2695. Vector3.prototype.toQuaternion = function () {
  2696. var result = new Quaternion(0.0, 0.0, 0.0, 1.0);
  2697. var cosxPlusz = Math.cos((this.x + this.z) * 0.5);
  2698. var sinxPlusz = Math.sin((this.x + this.z) * 0.5);
  2699. var coszMinusx = Math.cos((this.z - this.x) * 0.5);
  2700. var sinzMinusx = Math.sin((this.z - this.x) * 0.5);
  2701. var cosy = Math.cos(this.y * 0.5);
  2702. var siny = Math.sin(this.y * 0.5);
  2703. result.x = coszMinusx * siny;
  2704. result.y = -sinzMinusx * siny;
  2705. result.z = sinxPlusz * cosy;
  2706. result.w = cosxPlusz * cosy;
  2707. return result;
  2708. };
  2709. /**
  2710. * Adds the passed vector to the current Vector3
  2711. * @param otherVector defines the second operand
  2712. * @returns the current updated Vector3
  2713. */
  2714. Vector3.prototype.addInPlace = function (otherVector) {
  2715. this.x += otherVector.x;
  2716. this.y += otherVector.y;
  2717. this.z += otherVector.z;
  2718. return this;
  2719. };
  2720. /**
  2721. * Gets a new Vector3, result of the addition the current Vector3 and the passed vector
  2722. * @param otherVector defines the second operand
  2723. * @returns the resulting Vector3
  2724. */
  2725. Vector3.prototype.add = function (otherVector) {
  2726. return new Vector3(this.x + otherVector.x, this.y + otherVector.y, this.z + otherVector.z);
  2727. };
  2728. /**
  2729. * Adds the current Vector3 to the passed one and stores the result in the vector "result"
  2730. * @param otherVector defines the second operand
  2731. * @param result defines the Vector3 object where to store the result
  2732. * @returns the current Vector3
  2733. */
  2734. Vector3.prototype.addToRef = function (otherVector, result) {
  2735. result.x = this.x + otherVector.x;
  2736. result.y = this.y + otherVector.y;
  2737. result.z = this.z + otherVector.z;
  2738. return this;
  2739. };
  2740. /**
  2741. * Subtract the passed vector from the current Vector3
  2742. * @param otherVector defines the second operand
  2743. * @returns the current updated Vector3
  2744. */
  2745. Vector3.prototype.subtractInPlace = function (otherVector) {
  2746. this.x -= otherVector.x;
  2747. this.y -= otherVector.y;
  2748. this.z -= otherVector.z;
  2749. return this;
  2750. };
  2751. /**
  2752. * Returns a new Vector3, result of the subtraction of the passed vector from the current Vector3
  2753. * @param otherVector defines the second operand
  2754. * @returns the resulting Vector3
  2755. */
  2756. Vector3.prototype.subtract = function (otherVector) {
  2757. return new Vector3(this.x - otherVector.x, this.y - otherVector.y, this.z - otherVector.z);
  2758. };
  2759. /**
  2760. * Subtracts the passed vector from the current Vector3 and stores the result in the vector "result".
  2761. * @param otherVector defines the second operand
  2762. * @param result defines the Vector3 object where to store the result
  2763. * @returns the current Vector3
  2764. */
  2765. Vector3.prototype.subtractToRef = function (otherVector, result) {
  2766. result.x = this.x - otherVector.x;
  2767. result.y = this.y - otherVector.y;
  2768. result.z = this.z - otherVector.z;
  2769. return this;
  2770. };
  2771. /**
  2772. * Returns a new Vector3 set with the subtraction of the passed floats from the current Vector3 coordinates
  2773. * @param x defines the x coordinate of the operand
  2774. * @param y defines the y coordinate of the operand
  2775. * @param z defines the z coordinate of the operand
  2776. * @returns the resulting Vector3
  2777. */
  2778. Vector3.prototype.subtractFromFloats = function (x, y, z) {
  2779. return new Vector3(this.x - x, this.y - y, this.z - z);
  2780. };
  2781. /**
  2782. * Subtracts the passed floats from the current Vector3 coordinates and set the passed vector "result" with this result
  2783. * @param x defines the x coordinate of the operand
  2784. * @param y defines the y coordinate of the operand
  2785. * @param z defines the z coordinate of the operand
  2786. * @param result defines the Vector3 object where to store the result
  2787. * @returns the current Vector3
  2788. */
  2789. Vector3.prototype.subtractFromFloatsToRef = function (x, y, z, result) {
  2790. result.x = this.x - x;
  2791. result.y = this.y - y;
  2792. result.z = this.z - z;
  2793. return this;
  2794. };
  2795. /**
  2796. * Gets a new Vector3 set with the current Vector3 negated coordinates
  2797. * @returns a new Vector3
  2798. */
  2799. Vector3.prototype.negate = function () {
  2800. return new Vector3(-this.x, -this.y, -this.z);
  2801. };
  2802. /**
  2803. * Multiplies the Vector3 coordinates by the float "scale"
  2804. * @param scale defines the multiplier factor
  2805. * @returns the current updated Vector3
  2806. */
  2807. Vector3.prototype.scaleInPlace = function (scale) {
  2808. this.x *= scale;
  2809. this.y *= scale;
  2810. this.z *= scale;
  2811. return this;
  2812. };
  2813. /**
  2814. * Returns a new Vector3 set with the current Vector3 coordinates multiplied by the float "scale"
  2815. * @param scale defines the multiplier factor
  2816. * @returns a new Vector3
  2817. */
  2818. Vector3.prototype.scale = function (scale) {
  2819. return new Vector3(this.x * scale, this.y * scale, this.z * scale);
  2820. };
  2821. /**
  2822. * Multiplies the current Vector3 coordinates by the float "scale" and stores the result in the passed vector "result" coordinates
  2823. * @param scale defines the multiplier factor
  2824. * @param result defines the Vector3 object where to store the result
  2825. * @returns the current Vector3
  2826. */
  2827. Vector3.prototype.scaleToRef = function (scale, result) {
  2828. result.x = this.x * scale;
  2829. result.y = this.y * scale;
  2830. result.z = this.z * scale;
  2831. return this;
  2832. };
  2833. /**
  2834. * Scale the current Vector3 values by a factor and add the result to a given Vector3
  2835. * @param scale defines the scale factor
  2836. * @param result defines the Vector3 object where to store the result
  2837. * @returns the unmodified current Vector3
  2838. */
  2839. Vector3.prototype.scaleAndAddToRef = function (scale, result) {
  2840. result.x += this.x * scale;
  2841. result.y += this.y * scale;
  2842. result.z += this.z * scale;
  2843. return this;
  2844. };
  2845. /**
  2846. * Returns true if the current Vector3 and the passed vector coordinates are strictly equal
  2847. * @param otherVector defines the second operand
  2848. * @returns true if both vectors are equals
  2849. */
  2850. Vector3.prototype.equals = function (otherVector) {
  2851. return otherVector && this.x === otherVector.x && this.y === otherVector.y && this.z === otherVector.z;
  2852. };
  2853. /**
  2854. * Returns true if the current Vector3 and the passed vector coordinates are distant less than epsilon
  2855. * @param otherVector defines the second operand
  2856. * @param epsilon defines the minimal distance to define values as equals
  2857. * @returns true if both vectors are distant less than epsilon
  2858. */
  2859. Vector3.prototype.equalsWithEpsilon = function (otherVector, epsilon) {
  2860. if (epsilon === void 0) { epsilon = BABYLON.Epsilon; }
  2861. 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);
  2862. };
  2863. /**
  2864. * Returns true if the current Vector3 coordinates equals the passed floats
  2865. * @param x defines the x coordinate of the operand
  2866. * @param y defines the y coordinate of the operand
  2867. * @param z defines the z coordinate of the operand
  2868. * @returns true if both vectors are equals
  2869. */
  2870. Vector3.prototype.equalsToFloats = function (x, y, z) {
  2871. return this.x === x && this.y === y && this.z === z;
  2872. };
  2873. /**
  2874. * Multiplies the current Vector3 coordinates by the passed ones
  2875. * @param otherVector defines the second operand
  2876. * @returns the current updated Vector3
  2877. */
  2878. Vector3.prototype.multiplyInPlace = function (otherVector) {
  2879. this.x *= otherVector.x;
  2880. this.y *= otherVector.y;
  2881. this.z *= otherVector.z;
  2882. return this;
  2883. };
  2884. /**
  2885. * Returns a new Vector3, result of the multiplication of the current Vector3 by the passed vector
  2886. * @param otherVector defines the second operand
  2887. * @returns the new Vector3
  2888. */
  2889. Vector3.prototype.multiply = function (otherVector) {
  2890. return new Vector3(this.x * otherVector.x, this.y * otherVector.y, this.z * otherVector.z);
  2891. };
  2892. /**
  2893. * Multiplies the current Vector3 by the passed one and stores the result in the passed vector "result"
  2894. * @param otherVector defines the second operand
  2895. * @param result defines the Vector3 object where to store the result
  2896. * @returns the current Vector3
  2897. */
  2898. Vector3.prototype.multiplyToRef = function (otherVector, result) {
  2899. result.x = this.x * otherVector.x;
  2900. result.y = this.y * otherVector.y;
  2901. result.z = this.z * otherVector.z;
  2902. return this;
  2903. };
  2904. /**
  2905. * Returns a new Vector3 set with the result of the mulliplication of the current Vector3 coordinates by the passed floats
  2906. * @param x defines the x coordinate of the operand
  2907. * @param y defines the y coordinate of the operand
  2908. * @param z defines the z coordinate of the operand
  2909. * @returns the new Vector3
  2910. */
  2911. Vector3.prototype.multiplyByFloats = function (x, y, z) {
  2912. return new Vector3(this.x * x, this.y * y, this.z * z);
  2913. };
  2914. /**
  2915. * Returns a new Vector3 set with the result of the division of the current Vector3 coordinates by the passed ones
  2916. * @param otherVector defines the second operand
  2917. * @returns the new Vector3
  2918. */
  2919. Vector3.prototype.divide = function (otherVector) {
  2920. return new Vector3(this.x / otherVector.x, this.y / otherVector.y, this.z / otherVector.z);
  2921. };
  2922. /**
  2923. * Divides the current Vector3 coordinates by the passed ones and stores the result in the passed vector "result"
  2924. * @param otherVector defines the second operand
  2925. * @param result defines the Vector3 object where to store the result
  2926. * @returns the current Vector3
  2927. */
  2928. Vector3.prototype.divideToRef = function (otherVector, result) {
  2929. result.x = this.x / otherVector.x;
  2930. result.y = this.y / otherVector.y;
  2931. result.z = this.z / otherVector.z;
  2932. return this;
  2933. };
  2934. /**
  2935. * Divides the current Vector3 coordinates by the passed ones.
  2936. * @param otherVector defines the second operand
  2937. * @returns the current updated Vector3
  2938. */
  2939. Vector3.prototype.divideInPlace = function (otherVector) {
  2940. return this.divideToRef(otherVector, this);
  2941. };
  2942. /**
  2943. * Updates the current Vector3 with the minimal coordinate values between its and the passed vector ones
  2944. * @param other defines the second operand
  2945. * @returns the current updated Vector3
  2946. */
  2947. Vector3.prototype.minimizeInPlace = function (other) {
  2948. if (other.x < this.x)
  2949. this.x = other.x;
  2950. if (other.y < this.y)
  2951. this.y = other.y;
  2952. if (other.z < this.z)
  2953. this.z = other.z;
  2954. return this;
  2955. };
  2956. /**
  2957. * Updates the current Vector3 with the maximal coordinate values between its and the passed vector ones.
  2958. * @param other defines the second operand
  2959. * @returns the current updated Vector3
  2960. */
  2961. Vector3.prototype.maximizeInPlace = function (other) {
  2962. if (other.x > this.x)
  2963. this.x = other.x;
  2964. if (other.y > this.y)
  2965. this.y = other.y;
  2966. if (other.z > this.z)
  2967. this.z = other.z;
  2968. return this;
  2969. };
  2970. Object.defineProperty(Vector3.prototype, "isNonUniform", {
  2971. /**
  2972. * Gets a boolean indicating that the vector is non uniform meaning x, y or z are not all the same
  2973. */
  2974. get: function () {
  2975. var absX = Math.abs(this.x);
  2976. var absY = Math.abs(this.y);
  2977. if (absX !== absY) {
  2978. return true;
  2979. }
  2980. var absZ = Math.abs(this.z);
  2981. if (absX !== absZ) {
  2982. return true;
  2983. }
  2984. if (absY !== absZ) {
  2985. return true;
  2986. }
  2987. return false;
  2988. },
  2989. enumerable: true,
  2990. configurable: true
  2991. });
  2992. // Properties
  2993. /**
  2994. * Gets the length of the Vector3
  2995. * @returns the length of the Vecto3
  2996. */
  2997. Vector3.prototype.length = function () {
  2998. return Math.sqrt(this.x * this.x + this.y * this.y + this.z * this.z);
  2999. };
  3000. /**
  3001. * Gets the squared length of the Vector3
  3002. * @returns squared length of the Vector3
  3003. */
  3004. Vector3.prototype.lengthSquared = function () {
  3005. return (this.x * this.x + this.y * this.y + this.z * this.z);
  3006. };
  3007. /**
  3008. * Normalize the current Vector3.
  3009. * Please note that this is an in place operation.
  3010. * @returns the current updated Vector3
  3011. */
  3012. Vector3.prototype.normalize = function () {
  3013. var len = this.length();
  3014. if (len === 0 || len === 1.0)
  3015. return this;
  3016. var num = 1.0 / len;
  3017. this.x *= num;
  3018. this.y *= num;
  3019. this.z *= num;
  3020. return this;
  3021. };
  3022. /**
  3023. * Normalize the current Vector3 to a new vector
  3024. * @returns the new Vector3
  3025. */
  3026. Vector3.prototype.normalizeToNew = function () {
  3027. var normalized = new Vector3(0, 0, 0);
  3028. this.normalizeToRef(normalized);
  3029. return normalized;
  3030. };
  3031. /**
  3032. * Normalize the current Vector3 to the reference
  3033. * @param reference define the Vector3 to update
  3034. * @returns the updated Vector3
  3035. */
  3036. Vector3.prototype.normalizeToRef = function (reference) {
  3037. var len = this.length();
  3038. if (len === 0 || len === 1.0) {
  3039. reference.set(this.x, this.y, this.z);
  3040. return reference;
  3041. }
  3042. var scale = 1.0 / len;
  3043. this.scaleToRef(scale, reference);
  3044. return reference;
  3045. };
  3046. /**
  3047. * Creates a new Vector3 copied from the current Vector3
  3048. * @returns the new Vector3
  3049. */
  3050. Vector3.prototype.clone = function () {
  3051. return new Vector3(this.x, this.y, this.z);
  3052. };
  3053. /**
  3054. * Copies the passed vector coordinates to the current Vector3 ones
  3055. * @param source defines the source Vector3
  3056. * @returns the current updated Vector3
  3057. */
  3058. Vector3.prototype.copyFrom = function (source) {
  3059. this.x = source.x;
  3060. this.y = source.y;
  3061. this.z = source.z;
  3062. return this;
  3063. };
  3064. /**
  3065. * Copies the passed floats to the current Vector3 coordinates
  3066. * @param x defines the x coordinate of the operand
  3067. * @param y defines the y coordinate of the operand
  3068. * @param z defines the z coordinate of the operand
  3069. * @returns the current updated Vector3
  3070. */
  3071. Vector3.prototype.copyFromFloats = function (x, y, z) {
  3072. this.x = x;
  3073. this.y = y;
  3074. this.z = z;
  3075. return this;
  3076. };
  3077. /**
  3078. * Copies the passed floats to the current Vector3 coordinates
  3079. * @param x defines the x coordinate of the operand
  3080. * @param y defines the y coordinate of the operand
  3081. * @param z defines the z coordinate of the operand
  3082. * @returns the current updated Vector3
  3083. */
  3084. Vector3.prototype.set = function (x, y, z) {
  3085. return this.copyFromFloats(x, y, z);
  3086. };
  3087. // Statics
  3088. /**
  3089. * Get the clip factor between two vectors
  3090. * @param vector0 defines the first operand
  3091. * @param vector1 defines the second operand
  3092. * @param axis defines the axis to use
  3093. * @param size defines the size along the axis
  3094. * @returns the clip factor
  3095. */
  3096. Vector3.GetClipFactor = function (vector0, vector1, axis, size) {
  3097. var d0 = Vector3.Dot(vector0, axis) - size;
  3098. var d1 = Vector3.Dot(vector1, axis) - size;
  3099. var s = d0 / (d0 - d1);
  3100. return s;
  3101. };
  3102. /**
  3103. * Get angle between two vectors
  3104. * @param vector0 angle between vector0 and vector1
  3105. * @param vector1 angle between vector0 and vector1
  3106. * @param normal direction of the normal
  3107. * @return the angle between vector0 and vector1
  3108. */
  3109. Vector3.GetAngleBetweenVectors = function (vector0, vector1, normal) {
  3110. var v0 = vector0.clone().normalize();
  3111. var v1 = vector1.clone().normalize();
  3112. var dot = Vector3.Dot(v0, v1);
  3113. var n = Vector3.Cross(v0, v1);
  3114. if (Vector3.Dot(n, normal) > 0) {
  3115. return Math.acos(dot);
  3116. }
  3117. return -Math.acos(dot);
  3118. };
  3119. /**
  3120. * Returns a new Vector3 set from the index "offset" of the passed array
  3121. * @param array defines the source array
  3122. * @param offset defines the offset in the source array
  3123. * @returns the new Vector3
  3124. */
  3125. Vector3.FromArray = function (array, offset) {
  3126. if (!offset) {
  3127. offset = 0;
  3128. }
  3129. return new Vector3(array[offset], array[offset + 1], array[offset + 2]);
  3130. };
  3131. /**
  3132. * Returns a new Vector3 set from the index "offset" of the passed Float32Array
  3133. * This function is deprecated. Use FromArray instead
  3134. * @param array defines the source array
  3135. * @param offset defines the offset in the source array
  3136. * @returns the new Vector3
  3137. */
  3138. Vector3.FromFloatArray = function (array, offset) {
  3139. return Vector3.FromArray(array, offset);
  3140. };
  3141. /**
  3142. * Sets the passed vector "result" with the element values from the index "offset" of the passed array
  3143. * @param array defines the source array
  3144. * @param offset defines the offset in the source array
  3145. * @param result defines the Vector3 where to store the result
  3146. */
  3147. Vector3.FromArrayToRef = function (array, offset, result) {
  3148. result.x = array[offset];
  3149. result.y = array[offset + 1];
  3150. result.z = array[offset + 2];
  3151. };
  3152. /**
  3153. * Sets the passed vector "result" with the element values from the index "offset" of the passed Float32Array
  3154. * This function is deprecated. Use FromArrayToRef instead.
  3155. * @param array defines the source array
  3156. * @param offset defines the offset in the source array
  3157. * @param result defines the Vector3 where to store the result
  3158. */
  3159. Vector3.FromFloatArrayToRef = function (array, offset, result) {
  3160. return Vector3.FromArrayToRef(array, offset, result);
  3161. };
  3162. /**
  3163. * Sets the passed vector "result" with the passed floats.
  3164. * @param x defines the x coordinate of the source
  3165. * @param y defines the y coordinate of the source
  3166. * @param z defines the z coordinate of the source
  3167. * @param result defines the Vector3 where to store the result
  3168. */
  3169. Vector3.FromFloatsToRef = function (x, y, z, result) {
  3170. result.x = x;
  3171. result.y = y;
  3172. result.z = z;
  3173. };
  3174. /**
  3175. * Returns a new Vector3 set to (0.0, 0.0, 0.0)
  3176. * @returns a new empty Vector3
  3177. */
  3178. Vector3.Zero = function () {
  3179. return new Vector3(0.0, 0.0, 0.0);
  3180. };
  3181. /**
  3182. * Returns a new Vector3 set to (1.0, 1.0, 1.0)
  3183. * @returns a new unit Vector3
  3184. */
  3185. Vector3.One = function () {
  3186. return new Vector3(1.0, 1.0, 1.0);
  3187. };
  3188. /**
  3189. * Returns a new Vector3 set to (0.0, 1.0, 0.0)
  3190. * @returns a new up Vector3
  3191. */
  3192. Vector3.Up = function () {
  3193. return new Vector3(0.0, 1.0, 0.0);
  3194. };
  3195. /**
  3196. * Returns a new Vector3 set to (0.0, 0.0, 1.0)
  3197. * @returns a new forward Vector3
  3198. */
  3199. Vector3.Forward = function () {
  3200. return new Vector3(0.0, 0.0, 1.0);
  3201. };
  3202. /**
  3203. * Returns a new Vector3 set to (1.0, 0.0, 0.0)
  3204. * @returns a new right Vector3
  3205. */
  3206. Vector3.Right = function () {
  3207. return new Vector3(1.0, 0.0, 0.0);
  3208. };
  3209. /**
  3210. * Returns a new Vector3 set to (-1.0, 0.0, 0.0)
  3211. * @returns a new left Vector3
  3212. */
  3213. Vector3.Left = function () {
  3214. return new Vector3(-1.0, 0.0, 0.0);
  3215. };
  3216. /**
  3217. * Returns a new Vector3 set with the result of the transformation by the passed matrix of the passed vector.
  3218. * This method computes tranformed coordinates only, not transformed direction vectors (ie. it takes translation in account)
  3219. * @param vector defines the Vector3 to transform
  3220. * @param transformation defines the transformation matrix
  3221. * @returns the transformed Vector3
  3222. */
  3223. Vector3.TransformCoordinates = function (vector, transformation) {
  3224. var result = Vector3.Zero();
  3225. Vector3.TransformCoordinatesToRef(vector, transformation, result);
  3226. return result;
  3227. };
  3228. /**
  3229. * Sets the passed vector "result" coordinates with the result of the transformation by the passed matrix of the passed vector
  3230. * This method computes tranformed coordinates only, not transformed direction vectors (ie. it takes translation in account)
  3231. * @param vector defines the Vector3 to transform
  3232. * @param transformation defines the transformation matrix
  3233. * @param result defines the Vector3 where to store the result
  3234. */
  3235. Vector3.TransformCoordinatesToRef = function (vector, transformation, result) {
  3236. var x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]) + (vector.z * transformation.m[8]) + transformation.m[12];
  3237. var y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]) + (vector.z * transformation.m[9]) + transformation.m[13];
  3238. var z = (vector.x * transformation.m[2]) + (vector.y * transformation.m[6]) + (vector.z * transformation.m[10]) + transformation.m[14];
  3239. var w = (vector.x * transformation.m[3]) + (vector.y * transformation.m[7]) + (vector.z * transformation.m[11]) + transformation.m[15];
  3240. result.x = x / w;
  3241. result.y = y / w;
  3242. result.z = z / w;
  3243. };
  3244. /**
  3245. * Sets the passed vector "result" coordinates with the result of the transformation by the passed matrix of the passed floats (x, y, z)
  3246. * This method computes tranformed coordinates only, not transformed direction vectors
  3247. * @param x define the x coordinate of the source vector
  3248. * @param y define the y coordinate of the source vector
  3249. * @param z define the z coordinate of the source vector
  3250. * @param transformation defines the transformation matrix
  3251. * @param result defines the Vector3 where to store the result
  3252. */
  3253. Vector3.TransformCoordinatesFromFloatsToRef = function (x, y, z, transformation, result) {
  3254. var rx = (x * transformation.m[0]) + (y * transformation.m[4]) + (z * transformation.m[8]) + transformation.m[12];
  3255. var ry = (x * transformation.m[1]) + (y * transformation.m[5]) + (z * transformation.m[9]) + transformation.m[13];
  3256. var rz = (x * transformation.m[2]) + (y * transformation.m[6]) + (z * transformation.m[10]) + transformation.m[14];
  3257. var rw = (x * transformation.m[3]) + (y * transformation.m[7]) + (z * transformation.m[11]) + transformation.m[15];
  3258. result.x = rx / rw;
  3259. result.y = ry / rw;
  3260. result.z = rz / rw;
  3261. };
  3262. /**
  3263. * Returns a new Vector3 set with the result of the normal transformation by the passed matrix of the passed vector
  3264. * This methods computes transformed normalized direction vectors only (ie. it does not apply translation)
  3265. * @param vector defines the Vector3 to transform
  3266. * @param transformation defines the transformation matrix
  3267. * @returns the new Vector3
  3268. */
  3269. Vector3.TransformNormal = function (vector, transformation) {
  3270. var result = Vector3.Zero();
  3271. Vector3.TransformNormalToRef(vector, transformation, result);
  3272. return result;
  3273. };
  3274. /**
  3275. * Sets the passed vector "result" with the result of the normal transformation by the passed matrix of the passed vector
  3276. * This methods computes transformed normalized direction vectors only (ie. it does not apply translation)
  3277. * @param vector defines the Vector3 to transform
  3278. * @param transformation defines the transformation matrix
  3279. * @param result defines the Vector3 where to store the result
  3280. */
  3281. Vector3.TransformNormalToRef = function (vector, transformation, result) {
  3282. var x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]) + (vector.z * transformation.m[8]);
  3283. var y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]) + (vector.z * transformation.m[9]);
  3284. var z = (vector.x * transformation.m[2]) + (vector.y * transformation.m[6]) + (vector.z * transformation.m[10]);
  3285. result.x = x;
  3286. result.y = y;
  3287. result.z = z;
  3288. };
  3289. /**
  3290. * Sets the passed vector "result" with the result of the normal transformation by the passed matrix of the passed floats (x, y, z)
  3291. * This methods computes transformed normalized direction vectors only (ie. it does not apply translation)
  3292. * @param x define the x coordinate of the source vector
  3293. * @param y define the y coordinate of the source vector
  3294. * @param z define the z coordinate of the source vector
  3295. * @param transformation defines the transformation matrix
  3296. * @param result defines the Vector3 where to store the result
  3297. */
  3298. Vector3.TransformNormalFromFloatsToRef = function (x, y, z, transformation, result) {
  3299. result.x = (x * transformation.m[0]) + (y * transformation.m[4]) + (z * transformation.m[8]);
  3300. result.y = (x * transformation.m[1]) + (y * transformation.m[5]) + (z * transformation.m[9]);
  3301. result.z = (x * transformation.m[2]) + (y * transformation.m[6]) + (z * transformation.m[10]);
  3302. };
  3303. /**
  3304. * Returns a new Vector3 located for "amount" on the CatmullRom interpolation spline defined by the vectors "value1", "value2", "value3", "value4"
  3305. * @param value1 defines the first control point
  3306. * @param value2 defines the second control point
  3307. * @param value3 defines the third control point
  3308. * @param value4 defines the fourth control point
  3309. * @param amount defines the amount on the spline to use
  3310. * @returns the new Vector3
  3311. */
  3312. Vector3.CatmullRom = function (value1, value2, value3, value4, amount) {
  3313. var squared = amount * amount;
  3314. var cubed = amount * squared;
  3315. var x = 0.5 * ((((2.0 * value2.x) + ((-value1.x + value3.x) * amount)) +
  3316. (((((2.0 * value1.x) - (5.0 * value2.x)) + (4.0 * value3.x)) - value4.x) * squared)) +
  3317. ((((-value1.x + (3.0 * value2.x)) - (3.0 * value3.x)) + value4.x) * cubed));
  3318. var y = 0.5 * ((((2.0 * value2.y) + ((-value1.y + value3.y) * amount)) +
  3319. (((((2.0 * value1.y) - (5.0 * value2.y)) + (4.0 * value3.y)) - value4.y) * squared)) +
  3320. ((((-value1.y + (3.0 * value2.y)) - (3.0 * value3.y)) + value4.y) * cubed));
  3321. var z = 0.5 * ((((2.0 * value2.z) + ((-value1.z + value3.z) * amount)) +
  3322. (((((2.0 * value1.z) - (5.0 * value2.z)) + (4.0 * value3.z)) - value4.z) * squared)) +
  3323. ((((-value1.z + (3.0 * value2.z)) - (3.0 * value3.z)) + value4.z) * cubed));
  3324. return new Vector3(x, y, z);
  3325. };
  3326. /**
  3327. * 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"
  3328. * If a coordinate value of "value" is lower than one of the "min" coordinate, then this "value" coordinate is set with the "min" one
  3329. * If a coordinate value of "value" is greater than one of the "max" coordinate, then this "value" coordinate is set with the "max" one
  3330. * @param value defines the current value
  3331. * @param min defines the lower range value
  3332. * @param max defines the upper range value
  3333. * @returns the new Vector3
  3334. */
  3335. Vector3.Clamp = function (value, min, max) {
  3336. var x = value.x;
  3337. x = (x > max.x) ? max.x : x;
  3338. x = (x < min.x) ? min.x : x;
  3339. var y = value.y;
  3340. y = (y > max.y) ? max.y : y;
  3341. y = (y < min.y) ? min.y : y;
  3342. var z = value.z;
  3343. z = (z > max.z) ? max.z : z;
  3344. z = (z < min.z) ? min.z : z;
  3345. return new Vector3(x, y, z);
  3346. };
  3347. /**
  3348. * Returns a new Vector3 located for "amount" (float) on the Hermite interpolation spline defined by the vectors "value1", "tangent1", "value2", "tangent2"
  3349. * @param value1 defines the first control point
  3350. * @param tangent1 defines the first tangent vector
  3351. * @param value2 defines the second control point
  3352. * @param tangent2 defines the second tangent vector
  3353. * @param amount defines the amount on the interpolation spline (between 0 and 1)
  3354. * @returns the new Vector3
  3355. */
  3356. Vector3.Hermite = function (value1, tangent1, value2, tangent2, amount) {
  3357. var squared = amount * amount;
  3358. var cubed = amount * squared;
  3359. var part1 = ((2.0 * cubed) - (3.0 * squared)) + 1.0;
  3360. var part2 = (-2.0 * cubed) + (3.0 * squared);
  3361. var part3 = (cubed - (2.0 * squared)) + amount;
  3362. var part4 = cubed - squared;
  3363. var x = (((value1.x * part1) + (value2.x * part2)) + (tangent1.x * part3)) + (tangent2.x * part4);
  3364. var y = (((value1.y * part1) + (value2.y * part2)) + (tangent1.y * part3)) + (tangent2.y * part4);
  3365. var z = (((value1.z * part1) + (value2.z * part2)) + (tangent1.z * part3)) + (tangent2.z * part4);
  3366. return new Vector3(x, y, z);
  3367. };
  3368. /**
  3369. * Returns a new Vector3 located for "amount" (float) on the linear interpolation between the vectors "start" and "end"
  3370. * @param start defines the start value
  3371. * @param end defines the end value
  3372. * @param amount max defines amount between both (between 0 and 1)
  3373. * @returns the new Vector3
  3374. */
  3375. Vector3.Lerp = function (start, end, amount) {
  3376. var result = new Vector3(0, 0, 0);
  3377. Vector3.LerpToRef(start, end, amount, result);
  3378. return result;
  3379. };
  3380. /**
  3381. * Sets the passed vector "result" with the result of the linear interpolation from the vector "start" for "amount" to the vector "end"
  3382. * @param start defines the start value
  3383. * @param end defines the end value
  3384. * @param amount max defines amount between both (between 0 and 1)
  3385. * @param result defines the Vector3 where to store the result
  3386. */
  3387. Vector3.LerpToRef = function (start, end, amount, result) {
  3388. result.x = start.x + ((end.x - start.x) * amount);
  3389. result.y = start.y + ((end.y - start.y) * amount);
  3390. result.z = start.z + ((end.z - start.z) * amount);
  3391. };
  3392. /**
  3393. * Returns the dot product (float) between the vectors "left" and "right"
  3394. * @param left defines the left operand
  3395. * @param right defines the right operand
  3396. * @returns the dot product
  3397. */
  3398. Vector3.Dot = function (left, right) {
  3399. return (left.x * right.x + left.y * right.y + left.z * right.z);
  3400. };
  3401. /**
  3402. * Returns a new Vector3 as the cross product of the vectors "left" and "right"
  3403. * The cross product is then orthogonal to both "left" and "right"
  3404. * @param left defines the left operand
  3405. * @param right defines the right operand
  3406. * @returns the cross product
  3407. */
  3408. Vector3.Cross = function (left, right) {
  3409. var result = Vector3.Zero();
  3410. Vector3.CrossToRef(left, right, result);
  3411. return result;
  3412. };
  3413. /**
  3414. * Sets the passed vector "result" with the cross product of "left" and "right"
  3415. * The cross product is then orthogonal to both "left" and "right"
  3416. * @param left defines the left operand
  3417. * @param right defines the right operand
  3418. * @param result defines the Vector3 where to store the result
  3419. */
  3420. Vector3.CrossToRef = function (left, right, result) {
  3421. MathTmp.Vector3[0].x = left.y * right.z - left.z * right.y;
  3422. MathTmp.Vector3[0].y = left.z * right.x - left.x * right.z;
  3423. MathTmp.Vector3[0].z = left.x * right.y - left.y * right.x;
  3424. result.copyFrom(MathTmp.Vector3[0]);
  3425. };
  3426. /**
  3427. * Returns a new Vector3 as the normalization of the passed vector
  3428. * @param vector defines the Vector3 to normalize
  3429. * @returns the new Vector3
  3430. */
  3431. Vector3.Normalize = function (vector) {
  3432. var result = Vector3.Zero();
  3433. Vector3.NormalizeToRef(vector, result);
  3434. return result;
  3435. };
  3436. /**
  3437. * Sets the passed vector "result" with the normalization of the passed first vector
  3438. * @param vector defines the Vector3 to normalize
  3439. * @param result defines the Vector3 where to store the result
  3440. */
  3441. Vector3.NormalizeToRef = function (vector, result) {
  3442. result.copyFrom(vector);
  3443. result.normalize();
  3444. };
  3445. /**
  3446. * Project a Vector3 onto screen space
  3447. * @param vector defines the Vector3 to project
  3448. * @param world defines the world matrix to use
  3449. * @param transform defines the transform (view x projection) matrix to use
  3450. * @param viewport defines the screen viewport to use
  3451. * @returns the new Vector3
  3452. */
  3453. Vector3.Project = function (vector, world, transform, viewport) {
  3454. var cw = viewport.width;
  3455. var ch = viewport.height;
  3456. var cx = viewport.x;
  3457. var cy = viewport.y;
  3458. var viewportMatrix = Vector3._viewportMatrixCache ? Vector3._viewportMatrixCache : (Vector3._viewportMatrixCache = new Matrix());
  3459. 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);
  3460. var matrix = MathTmp.Matrix[0];
  3461. world.multiplyToRef(transform, matrix);
  3462. matrix.multiplyToRef(viewportMatrix, matrix);
  3463. return Vector3.TransformCoordinates(vector, matrix);
  3464. };
  3465. /**
  3466. * Unproject from screen space to object space
  3467. * @param source defines the screen space Vector3 to use
  3468. * @param viewportWidth defines the current width of the viewport
  3469. * @param viewportHeight defines the current height of the viewport
  3470. * @param world defines the world matrix to use (can be set to Identity to go to world space)
  3471. * @param transform defines the transform (view x projection) matrix to use
  3472. * @returns the new Vector3
  3473. */
  3474. Vector3.UnprojectFromTransform = function (source, viewportWidth, viewportHeight, world, transform) {
  3475. var matrix = MathTmp.Matrix[0];
  3476. world.multiplyToRef(transform, matrix);
  3477. matrix.invert();
  3478. source.x = source.x / viewportWidth * 2 - 1;
  3479. source.y = -(source.y / viewportHeight * 2 - 1);
  3480. var vector = Vector3.TransformCoordinates(source, matrix);
  3481. var num = source.x * matrix.m[3] + source.y * matrix.m[7] + source.z * matrix.m[11] + matrix.m[15];
  3482. if (BABYLON.Scalar.WithinEpsilon(num, 1.0)) {
  3483. vector = vector.scale(1.0 / num);
  3484. }
  3485. return vector;
  3486. };
  3487. /**
  3488. * Unproject from screen space to object space
  3489. * @param source defines the screen space Vector3 to use
  3490. * @param viewportWidth defines the current width of the viewport
  3491. * @param viewportHeight defines the current height of the viewport
  3492. * @param world defines the world matrix to use (can be set to Identity to go to world space)
  3493. * @param view defines the view matrix to use
  3494. * @param projection defines the projection matrix to use
  3495. * @returns the new Vector3
  3496. */
  3497. Vector3.Unproject = function (source, viewportWidth, viewportHeight, world, view, projection) {
  3498. var result = Vector3.Zero();
  3499. Vector3.UnprojectToRef(source, viewportWidth, viewportHeight, world, view, projection, result);
  3500. return result;
  3501. };
  3502. /**
  3503. * Unproject from screen space to object space
  3504. * @param source defines the screen space Vector3 to use
  3505. * @param viewportWidth defines the current width of the viewport
  3506. * @param viewportHeight defines the current height of the viewport
  3507. * @param world defines the world matrix to use (can be set to Identity to go to world space)
  3508. * @param view defines the view matrix to use
  3509. * @param projection defines the projection matrix to use
  3510. * @param result defines the Vector3 where to store the result
  3511. */
  3512. Vector3.UnprojectToRef = function (source, viewportWidth, viewportHeight, world, view, projection, result) {
  3513. Vector3.UnprojectFloatsToRef(source.x, source.y, source.z, viewportWidth, viewportHeight, world, view, projection, result);
  3514. };
  3515. /**
  3516. * Unproject from screen space to object space
  3517. * @param sourceX defines the screen space x coordinate to use
  3518. * @param sourceY defines the screen space y coordinate to use
  3519. * @param sourceZ defines the screen space z coordinate to use
  3520. * @param viewportWidth defines the current width of the viewport
  3521. * @param viewportHeight defines the current height of the viewport
  3522. * @param world defines the world matrix to use (can be set to Identity to go to world space)
  3523. * @param view defines the view matrix to use
  3524. * @param projection defines the projection matrix to use
  3525. * @param result defines the Vector3 where to store the result
  3526. */
  3527. Vector3.UnprojectFloatsToRef = function (sourceX, sourceY, sourceZ, viewportWidth, viewportHeight, world, view, projection, result) {
  3528. var matrix = MathTmp.Matrix[0];
  3529. world.multiplyToRef(view, matrix);
  3530. matrix.multiplyToRef(projection, matrix);
  3531. matrix.invert();
  3532. var screenSource = MathTmp.Vector3[0];
  3533. screenSource.x = sourceX / viewportWidth * 2 - 1;
  3534. screenSource.y = -(sourceY / viewportHeight * 2 - 1);
  3535. screenSource.z = 2 * sourceZ - 1.0;
  3536. Vector3.TransformCoordinatesToRef(screenSource, matrix, result);
  3537. var num = screenSource.x * matrix.m[3] + screenSource.y * matrix.m[7] + screenSource.z * matrix.m[11] + matrix.m[15];
  3538. if (BABYLON.Scalar.WithinEpsilon(num, 1.0)) {
  3539. result.scaleInPlace(1.0 / num);
  3540. }
  3541. };
  3542. /**
  3543. * Gets the minimal coordinate values between two Vector3
  3544. * @param left defines the first operand
  3545. * @param right defines the second operand
  3546. * @returns the new Vector3
  3547. */
  3548. Vector3.Minimize = function (left, right) {
  3549. var min = left.clone();
  3550. min.minimizeInPlace(right);
  3551. return min;
  3552. };
  3553. /**
  3554. * Gets the maximal coordinate values between two Vector3
  3555. * @param left defines the first operand
  3556. * @param right defines the second operand
  3557. * @returns the new Vector3
  3558. */
  3559. Vector3.Maximize = function (left, right) {
  3560. var max = left.clone();
  3561. max.maximizeInPlace(right);
  3562. return max;
  3563. };
  3564. /**
  3565. * Returns the distance between the vectors "value1" and "value2"
  3566. * @param value1 defines the first operand
  3567. * @param value2 defines the second operand
  3568. * @returns the distance
  3569. */
  3570. Vector3.Distance = function (value1, value2) {
  3571. return Math.sqrt(Vector3.DistanceSquared(value1, value2));
  3572. };
  3573. /**
  3574. * Returns the squared distance between the vectors "value1" and "value2"
  3575. * @param value1 defines the first operand
  3576. * @param value2 defines the second operand
  3577. * @returns the squared distance
  3578. */
  3579. Vector3.DistanceSquared = function (value1, value2) {
  3580. var x = value1.x - value2.x;
  3581. var y = value1.y - value2.y;
  3582. var z = value1.z - value2.z;
  3583. return (x * x) + (y * y) + (z * z);
  3584. };
  3585. /**
  3586. * Returns a new Vector3 located at the center between "value1" and "value2"
  3587. * @param value1 defines the first operand
  3588. * @param value2 defines the second operand
  3589. * @returns the new Vector3
  3590. */
  3591. Vector3.Center = function (value1, value2) {
  3592. var center = value1.add(value2);
  3593. center.scaleInPlace(0.5);
  3594. return center;
  3595. };
  3596. /**
  3597. * Given three orthogonal normalized left-handed oriented Vector3 axis in space (target system),
  3598. * RotationFromAxis() returns the rotation Euler angles (ex : rotation.x, rotation.y, rotation.z) to apply
  3599. * to something in order to rotate it from its local system to the given target system
  3600. * Note: axis1, axis2 and axis3 are normalized during this operation
  3601. * @param axis1 defines the first axis
  3602. * @param axis2 defines the second axis
  3603. * @param axis3 defines the third axis
  3604. * @returns a new Vector3
  3605. */
  3606. Vector3.RotationFromAxis = function (axis1, axis2, axis3) {
  3607. var rotation = Vector3.Zero();
  3608. Vector3.RotationFromAxisToRef(axis1, axis2, axis3, rotation);
  3609. return rotation;
  3610. };
  3611. /**
  3612. * The same than RotationFromAxis but updates the passed ref Vector3 parameter instead of returning a new Vector3
  3613. * @param axis1 defines the first axis
  3614. * @param axis2 defines the second axis
  3615. * @param axis3 defines the third axis
  3616. * @param ref defines the Vector3 where to store the result
  3617. */
  3618. Vector3.RotationFromAxisToRef = function (axis1, axis2, axis3, ref) {
  3619. var quat = MathTmp.Quaternion[0];
  3620. Quaternion.RotationQuaternionFromAxisToRef(axis1, axis2, axis3, quat);
  3621. quat.toEulerAnglesToRef(ref);
  3622. };
  3623. return Vector3;
  3624. }());
  3625. BABYLON.Vector3 = Vector3;
  3626. //Vector4 class created for EulerAngle class conversion to Quaternion
  3627. var Vector4 = /** @class */ (function () {
  3628. /**
  3629. * Creates a Vector4 object from the passed floats.
  3630. */
  3631. function Vector4(x, y, z, w) {
  3632. this.x = x;
  3633. this.y = y;
  3634. this.z = z;
  3635. this.w = w;
  3636. }
  3637. /**
  3638. * Returns the string with the Vector4 coordinates.
  3639. */
  3640. Vector4.prototype.toString = function () {
  3641. return "{X: " + this.x + " Y:" + this.y + " Z:" + this.z + " W:" + this.w + "}";
  3642. };
  3643. /**
  3644. * Returns the string "Vector4".
  3645. */
  3646. Vector4.prototype.getClassName = function () {
  3647. return "Vector4";
  3648. };
  3649. /**
  3650. * Returns the Vector4 hash code.
  3651. */
  3652. Vector4.prototype.getHashCode = function () {
  3653. var hash = this.x || 0;
  3654. hash = (hash * 397) ^ (this.y || 0);
  3655. hash = (hash * 397) ^ (this.z || 0);
  3656. hash = (hash * 397) ^ (this.w || 0);
  3657. return hash;
  3658. };
  3659. // Operators
  3660. /**
  3661. * Returns a new array populated with 4 elements : the Vector4 coordinates.
  3662. */
  3663. Vector4.prototype.asArray = function () {
  3664. var result = new Array();
  3665. this.toArray(result, 0);
  3666. return result;
  3667. };
  3668. /**
  3669. * Populates the passed array from the passed index with the Vector4 coordinates.
  3670. * Returns the Vector4.
  3671. */
  3672. Vector4.prototype.toArray = function (array, index) {
  3673. if (index === undefined) {
  3674. index = 0;
  3675. }
  3676. array[index] = this.x;
  3677. array[index + 1] = this.y;
  3678. array[index + 2] = this.z;
  3679. array[index + 3] = this.w;
  3680. return this;
  3681. };
  3682. /**
  3683. * Adds the passed vector to the current Vector4.
  3684. * Returns the updated Vector4.
  3685. */
  3686. Vector4.prototype.addInPlace = function (otherVector) {
  3687. this.x += otherVector.x;
  3688. this.y += otherVector.y;
  3689. this.z += otherVector.z;
  3690. this.w += otherVector.w;
  3691. return this;
  3692. };
  3693. /**
  3694. * Returns a new Vector4 as the result of the addition of the current Vector4 and the passed one.
  3695. */
  3696. Vector4.prototype.add = function (otherVector) {
  3697. return new Vector4(this.x + otherVector.x, this.y + otherVector.y, this.z + otherVector.z, this.w + otherVector.w);
  3698. };
  3699. /**
  3700. * Updates the passed vector "result" with the result of the addition of the current Vector4 and the passed one.
  3701. * Returns the current Vector4.
  3702. */
  3703. Vector4.prototype.addToRef = function (otherVector, result) {
  3704. result.x = this.x + otherVector.x;
  3705. result.y = this.y + otherVector.y;
  3706. result.z = this.z + otherVector.z;
  3707. result.w = this.w + otherVector.w;
  3708. return this;
  3709. };
  3710. /**
  3711. * Subtract in place the passed vector from the current Vector4.
  3712. * Returns the updated Vector4.
  3713. */
  3714. Vector4.prototype.subtractInPlace = function (otherVector) {
  3715. this.x -= otherVector.x;
  3716. this.y -= otherVector.y;
  3717. this.z -= otherVector.z;
  3718. this.w -= otherVector.w;
  3719. return this;
  3720. };
  3721. /**
  3722. * Returns a new Vector4 with the result of the subtraction of the passed vector from the current Vector4.
  3723. */
  3724. Vector4.prototype.subtract = function (otherVector) {
  3725. return new Vector4(this.x - otherVector.x, this.y - otherVector.y, this.z - otherVector.z, this.w - otherVector.w);
  3726. };
  3727. /**
  3728. * Sets the passed vector "result" with the result of the subtraction of the passed vector from the current Vector4.
  3729. * Returns the current Vector4.
  3730. */
  3731. Vector4.prototype.subtractToRef = function (otherVector, result) {
  3732. result.x = this.x - otherVector.x;
  3733. result.y = this.y - otherVector.y;
  3734. result.z = this.z - otherVector.z;
  3735. result.w = this.w - otherVector.w;
  3736. return this;
  3737. };
  3738. /**
  3739. * Returns a new Vector4 set with the result of the subtraction of the passed floats from the current Vector4 coordinates.
  3740. */
  3741. Vector4.prototype.subtractFromFloats = function (x, y, z, w) {
  3742. return new Vector4(this.x - x, this.y - y, this.z - z, this.w - w);
  3743. };
  3744. /**
  3745. * Sets the passed vector "result" set with the result of the subtraction of the passed floats from the current Vector4 coordinates.
  3746. * Returns the current Vector4.
  3747. */
  3748. Vector4.prototype.subtractFromFloatsToRef = function (x, y, z, w, result) {
  3749. result.x = this.x - x;
  3750. result.y = this.y - y;
  3751. result.z = this.z - z;
  3752. result.w = this.w - w;
  3753. return this;
  3754. };
  3755. /**
  3756. * Returns a new Vector4 set with the current Vector4 negated coordinates.
  3757. */
  3758. Vector4.prototype.negate = function () {
  3759. return new Vector4(-this.x, -this.y, -this.z, -this.w);
  3760. };
  3761. /**
  3762. * Multiplies the current Vector4 coordinates by scale (float).
  3763. * Returns the updated Vector4.
  3764. */
  3765. Vector4.prototype.scaleInPlace = function (scale) {
  3766. this.x *= scale;
  3767. this.y *= scale;
  3768. this.z *= scale;
  3769. this.w *= scale;
  3770. return this;
  3771. };
  3772. /**
  3773. * Returns a new Vector4 set with the current Vector4 coordinates multiplied by scale (float).
  3774. */
  3775. Vector4.prototype.scale = function (scale) {
  3776. return new Vector4(this.x * scale, this.y * scale, this.z * scale, this.w * scale);
  3777. };
  3778. /**
  3779. * Sets the passed vector "result" with the current Vector4 coordinates multiplied by scale (float).
  3780. * Returns the current Vector4.
  3781. */
  3782. Vector4.prototype.scaleToRef = function (scale, result) {
  3783. result.x = this.x * scale;
  3784. result.y = this.y * scale;
  3785. result.z = this.z * scale;
  3786. result.w = this.w * scale;
  3787. return this;
  3788. };
  3789. /**
  3790. * Scale the current Vector4 values by a factor and add the result to a given Vector4
  3791. * @param scale defines the scale factor
  3792. * @param result defines the Vector4 object where to store the result
  3793. * @returns the unmodified current Vector4
  3794. */
  3795. Vector4.prototype.scaleAndAddToRef = function (scale, result) {
  3796. result.x += this.x * scale;
  3797. result.y += this.y * scale;
  3798. result.z += this.z * scale;
  3799. result.w += this.w * scale;
  3800. return this;
  3801. };
  3802. /**
  3803. * Boolean : True if the current Vector4 coordinates are stricly equal to the passed ones.
  3804. */
  3805. Vector4.prototype.equals = function (otherVector) {
  3806. return otherVector && this.x === otherVector.x && this.y === otherVector.y && this.z === otherVector.z && this.w === otherVector.w;
  3807. };
  3808. /**
  3809. * Boolean : True if the current Vector4 coordinates are each beneath the distance "epsilon" from the passed vector ones.
  3810. */
  3811. Vector4.prototype.equalsWithEpsilon = function (otherVector, epsilon) {
  3812. if (epsilon === void 0) { epsilon = BABYLON.Epsilon; }
  3813. return otherVector
  3814. && BABYLON.Scalar.WithinEpsilon(this.x, otherVector.x, epsilon)
  3815. && BABYLON.Scalar.WithinEpsilon(this.y, otherVector.y, epsilon)
  3816. && BABYLON.Scalar.WithinEpsilon(this.z, otherVector.z, epsilon)
  3817. && BABYLON.Scalar.WithinEpsilon(this.w, otherVector.w, epsilon);
  3818. };
  3819. /**
  3820. * Boolean : True if the passed floats are strictly equal to the current Vector4 coordinates.
  3821. */
  3822. Vector4.prototype.equalsToFloats = function (x, y, z, w) {
  3823. return this.x === x && this.y === y && this.z === z && this.w === w;
  3824. };
  3825. /**
  3826. * Multiplies in place the current Vector4 by the passed one.
  3827. * Returns the updated Vector4.
  3828. */
  3829. Vector4.prototype.multiplyInPlace = function (otherVector) {
  3830. this.x *= otherVector.x;
  3831. this.y *= otherVector.y;
  3832. this.z *= otherVector.z;
  3833. this.w *= otherVector.w;
  3834. return this;
  3835. };
  3836. /**
  3837. * Returns a new Vector4 set with the multiplication result of the current Vector4 and the passed one.
  3838. */
  3839. Vector4.prototype.multiply = function (otherVector) {
  3840. return new Vector4(this.x * otherVector.x, this.y * otherVector.y, this.z * otherVector.z, this.w * otherVector.w);
  3841. };
  3842. /**
  3843. * Updates the passed vector "result" with the multiplication result of the current Vector4 and the passed one.
  3844. * Returns the current Vector4.
  3845. */
  3846. Vector4.prototype.multiplyToRef = function (otherVector, result) {
  3847. result.x = this.x * otherVector.x;
  3848. result.y = this.y * otherVector.y;
  3849. result.z = this.z * otherVector.z;
  3850. result.w = this.w * otherVector.w;
  3851. return this;
  3852. };
  3853. /**
  3854. * Returns a new Vector4 set with the multiplication result of the passed floats and the current Vector4 coordinates.
  3855. */
  3856. Vector4.prototype.multiplyByFloats = function (x, y, z, w) {
  3857. return new Vector4(this.x * x, this.y * y, this.z * z, this.w * w);
  3858. };
  3859. /**
  3860. * Returns a new Vector4 set with the division result of the current Vector4 by the passed one.
  3861. */
  3862. Vector4.prototype.divide = function (otherVector) {
  3863. return new Vector4(this.x / otherVector.x, this.y / otherVector.y, this.z / otherVector.z, this.w / otherVector.w);
  3864. };
  3865. /**
  3866. * Updates the passed vector "result" with the division result of the current Vector4 by the passed one.
  3867. * Returns the current Vector4.
  3868. */
  3869. Vector4.prototype.divideToRef = function (otherVector, result) {
  3870. result.x = this.x / otherVector.x;
  3871. result.y = this.y / otherVector.y;
  3872. result.z = this.z / otherVector.z;
  3873. result.w = this.w / otherVector.w;
  3874. return this;
  3875. };
  3876. /**
  3877. * Divides the current Vector3 coordinates by the passed ones.
  3878. * @returns the updated Vector3.
  3879. */
  3880. Vector4.prototype.divideInPlace = function (otherVector) {
  3881. return this.divideToRef(otherVector, this);
  3882. };
  3883. /**
  3884. * Updates the Vector4 coordinates with the minimum values between its own and the passed vector ones
  3885. * @param other defines the second operand
  3886. * @returns the current updated Vector4
  3887. */
  3888. Vector4.prototype.minimizeInPlace = function (other) {
  3889. if (other.x < this.x)
  3890. this.x = other.x;
  3891. if (other.y < this.y)
  3892. this.y = other.y;
  3893. if (other.z < this.z)
  3894. this.z = other.z;
  3895. if (other.w < this.w)
  3896. this.w = other.w;
  3897. return this;
  3898. };
  3899. /**
  3900. * Updates the Vector4 coordinates with the maximum values between its own and the passed vector ones
  3901. * @param other defines the second operand
  3902. * @returns the current updated Vector4
  3903. */
  3904. Vector4.prototype.maximizeInPlace = function (other) {
  3905. if (other.x > this.x)
  3906. this.x = other.x;
  3907. if (other.y > this.y)
  3908. this.y = other.y;
  3909. if (other.z > this.z)
  3910. this.z = other.z;
  3911. if (other.w > this.w)
  3912. this.w = other.w;
  3913. return this;
  3914. };
  3915. // Properties
  3916. /**
  3917. * Returns the Vector4 length (float).
  3918. */
  3919. Vector4.prototype.length = function () {
  3920. return Math.sqrt(this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w);
  3921. };
  3922. /**
  3923. * Returns the Vector4 squared length (float).
  3924. */
  3925. Vector4.prototype.lengthSquared = function () {
  3926. return (this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w);
  3927. };
  3928. // Methods
  3929. /**
  3930. * Normalizes in place the Vector4.
  3931. * Returns the updated Vector4.
  3932. */
  3933. Vector4.prototype.normalize = function () {
  3934. var len = this.length();
  3935. if (len === 0)
  3936. return this;
  3937. var num = 1.0 / len;
  3938. this.x *= num;
  3939. this.y *= num;
  3940. this.z *= num;
  3941. this.w *= num;
  3942. return this;
  3943. };
  3944. /**
  3945. * Returns a new Vector3 from the Vector4 (x, y, z) coordinates.
  3946. */
  3947. Vector4.prototype.toVector3 = function () {
  3948. return new Vector3(this.x, this.y, this.z);
  3949. };
  3950. /**
  3951. * Returns a new Vector4 copied from the current one.
  3952. */
  3953. Vector4.prototype.clone = function () {
  3954. return new Vector4(this.x, this.y, this.z, this.w);
  3955. };
  3956. /**
  3957. * Updates the current Vector4 with the passed one coordinates.
  3958. * Returns the updated Vector4.
  3959. */
  3960. Vector4.prototype.copyFrom = function (source) {
  3961. this.x = source.x;
  3962. this.y = source.y;
  3963. this.z = source.z;
  3964. this.w = source.w;
  3965. return this;
  3966. };
  3967. /**
  3968. * Updates the current Vector4 coordinates with the passed floats.
  3969. * Returns the updated Vector4.
  3970. */
  3971. Vector4.prototype.copyFromFloats = function (x, y, z, w) {
  3972. this.x = x;
  3973. this.y = y;
  3974. this.z = z;
  3975. this.w = w;
  3976. return this;
  3977. };
  3978. /**
  3979. * Updates the current Vector4 coordinates with the passed floats.
  3980. * Returns the updated Vector4.
  3981. */
  3982. Vector4.prototype.set = function (x, y, z, w) {
  3983. return this.copyFromFloats(x, y, z, w);
  3984. };
  3985. // Statics
  3986. /**
  3987. * Returns a new Vector4 set from the starting index of the passed array.
  3988. */
  3989. Vector4.FromArray = function (array, offset) {
  3990. if (!offset) {
  3991. offset = 0;
  3992. }
  3993. return new Vector4(array[offset], array[offset + 1], array[offset + 2], array[offset + 3]);
  3994. };
  3995. /**
  3996. * Updates the passed vector "result" from the starting index of the passed array.
  3997. */
  3998. Vector4.FromArrayToRef = function (array, offset, result) {
  3999. result.x = array[offset];
  4000. result.y = array[offset + 1];
  4001. result.z = array[offset + 2];
  4002. result.w = array[offset + 3];
  4003. };
  4004. /**
  4005. * Updates the passed vector "result" from the starting index of the passed Float32Array.
  4006. */
  4007. Vector4.FromFloatArrayToRef = function (array, offset, result) {
  4008. Vector4.FromArrayToRef(array, offset, result);
  4009. };
  4010. /**
  4011. * Updates the passed vector "result" coordinates from the passed floats.
  4012. */
  4013. Vector4.FromFloatsToRef = function (x, y, z, w, result) {
  4014. result.x = x;
  4015. result.y = y;
  4016. result.z = z;
  4017. result.w = w;
  4018. };
  4019. /**
  4020. * Returns a new Vector4 set to (0.0, 0.0, 0.0, 0.0)
  4021. */
  4022. Vector4.Zero = function () {
  4023. return new Vector4(0.0, 0.0, 0.0, 0.0);
  4024. };
  4025. /**
  4026. * Returns a new Vector4 set to (1.0, 1.0, 1.0, 1.0)
  4027. */
  4028. Vector4.One = function () {
  4029. return new Vector4(1.0, 1.0, 1.0, 1.0);
  4030. };
  4031. /**
  4032. * Returns a new normalized Vector4 from the passed one.
  4033. */
  4034. Vector4.Normalize = function (vector) {
  4035. var result = Vector4.Zero();
  4036. Vector4.NormalizeToRef(vector, result);
  4037. return result;
  4038. };
  4039. /**
  4040. * Updates the passed vector "result" from the normalization of the passed one.
  4041. */
  4042. Vector4.NormalizeToRef = function (vector, result) {
  4043. result.copyFrom(vector);
  4044. result.normalize();
  4045. };
  4046. Vector4.Minimize = function (left, right) {
  4047. var min = left.clone();
  4048. min.minimizeInPlace(right);
  4049. return min;
  4050. };
  4051. Vector4.Maximize = function (left, right) {
  4052. var max = left.clone();
  4053. max.maximizeInPlace(right);
  4054. return max;
  4055. };
  4056. /**
  4057. * Returns the distance (float) between the vectors "value1" and "value2".
  4058. */
  4059. Vector4.Distance = function (value1, value2) {
  4060. return Math.sqrt(Vector4.DistanceSquared(value1, value2));
  4061. };
  4062. /**
  4063. * Returns the squared distance (float) between the vectors "value1" and "value2".
  4064. */
  4065. Vector4.DistanceSquared = function (value1, value2) {
  4066. var x = value1.x - value2.x;
  4067. var y = value1.y - value2.y;
  4068. var z = value1.z - value2.z;
  4069. var w = value1.w - value2.w;
  4070. return (x * x) + (y * y) + (z * z) + (w * w);
  4071. };
  4072. /**
  4073. * Returns a new Vector4 located at the center between the vectors "value1" and "value2".
  4074. */
  4075. Vector4.Center = function (value1, value2) {
  4076. var center = value1.add(value2);
  4077. center.scaleInPlace(0.5);
  4078. return center;
  4079. };
  4080. /**
  4081. * Returns a new Vector4 set with the result of the normal transformation by the passed matrix of the passed vector.
  4082. * This methods computes transformed normalized direction vectors only.
  4083. */
  4084. Vector4.TransformNormal = function (vector, transformation) {
  4085. var result = Vector4.Zero();
  4086. Vector4.TransformNormalToRef(vector, transformation, result);
  4087. return result;
  4088. };
  4089. /**
  4090. * Sets the passed vector "result" with the result of the normal transformation by the passed matrix of the passed vector.
  4091. * This methods computes transformed normalized direction vectors only.
  4092. */
  4093. Vector4.TransformNormalToRef = function (vector, transformation, result) {
  4094. var x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]) + (vector.z * transformation.m[8]);
  4095. var y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]) + (vector.z * transformation.m[9]);
  4096. var z = (vector.x * transformation.m[2]) + (vector.y * transformation.m[6]) + (vector.z * transformation.m[10]);
  4097. result.x = x;
  4098. result.y = y;
  4099. result.z = z;
  4100. result.w = vector.w;
  4101. };
  4102. /**
  4103. * Sets the passed vector "result" with the result of the normal transformation by the passed matrix of the passed floats (x, y, z, w).
  4104. * This methods computes transformed normalized direction vectors only.
  4105. */
  4106. Vector4.TransformNormalFromFloatsToRef = function (x, y, z, w, transformation, result) {
  4107. result.x = (x * transformation.m[0]) + (y * transformation.m[4]) + (z * transformation.m[8]);
  4108. result.y = (x * transformation.m[1]) + (y * transformation.m[5]) + (z * transformation.m[9]);
  4109. result.z = (x * transformation.m[2]) + (y * transformation.m[6]) + (z * transformation.m[10]);
  4110. result.w = w;
  4111. };
  4112. return Vector4;
  4113. }());
  4114. BABYLON.Vector4 = Vector4;
  4115. var Size = /** @class */ (function () {
  4116. /**
  4117. * Creates a Size object from the passed width and height (floats).
  4118. */
  4119. function Size(width, height) {
  4120. this.width = width;
  4121. this.height = height;
  4122. }
  4123. // Returns a string with the Size width and height.
  4124. Size.prototype.toString = function () {
  4125. return "{W: " + this.width + ", H: " + this.height + "}";
  4126. };
  4127. /**
  4128. * Returns the string "Size"
  4129. */
  4130. Size.prototype.getClassName = function () {
  4131. return "Size";
  4132. };
  4133. /**
  4134. * Returns the Size hash code.
  4135. */
  4136. Size.prototype.getHashCode = function () {
  4137. var hash = this.width || 0;
  4138. hash = (hash * 397) ^ (this.height || 0);
  4139. return hash;
  4140. };
  4141. /**
  4142. * Updates the current size from the passed one.
  4143. * Returns the updated Size.
  4144. */
  4145. Size.prototype.copyFrom = function (src) {
  4146. this.width = src.width;
  4147. this.height = src.height;
  4148. };
  4149. /**
  4150. * Updates in place the current Size from the passed floats.
  4151. * Returns the updated Size.
  4152. */
  4153. Size.prototype.copyFromFloats = function (width, height) {
  4154. this.width = width;
  4155. this.height = height;
  4156. return this;
  4157. };
  4158. /**
  4159. * Updates in place the current Size from the passed floats.
  4160. * Returns the updated Size.
  4161. */
  4162. Size.prototype.set = function (width, height) {
  4163. return this.copyFromFloats(width, height);
  4164. };
  4165. /**
  4166. * Returns a new Size set with the multiplication result of the current Size and the passed floats.
  4167. */
  4168. Size.prototype.multiplyByFloats = function (w, h) {
  4169. return new Size(this.width * w, this.height * h);
  4170. };
  4171. /**
  4172. * Returns a new Size copied from the passed one.
  4173. */
  4174. Size.prototype.clone = function () {
  4175. return new Size(this.width, this.height);
  4176. };
  4177. /**
  4178. * Boolean : True if the current Size and the passed one width and height are strictly equal.
  4179. */
  4180. Size.prototype.equals = function (other) {
  4181. if (!other) {
  4182. return false;
  4183. }
  4184. return (this.width === other.width) && (this.height === other.height);
  4185. };
  4186. Object.defineProperty(Size.prototype, "surface", {
  4187. /**
  4188. * Returns the surface of the Size : width * height (float).
  4189. */
  4190. get: function () {
  4191. return this.width * this.height;
  4192. },
  4193. enumerable: true,
  4194. configurable: true
  4195. });
  4196. /**
  4197. * Returns a new Size set to (0.0, 0.0)
  4198. */
  4199. Size.Zero = function () {
  4200. return new Size(0.0, 0.0);
  4201. };
  4202. /**
  4203. * Returns a new Size set as the addition result of the current Size and the passed one.
  4204. */
  4205. Size.prototype.add = function (otherSize) {
  4206. var r = new Size(this.width + otherSize.width, this.height + otherSize.height);
  4207. return r;
  4208. };
  4209. /**
  4210. * Returns a new Size set as the subtraction result of the passed one from the current Size.
  4211. */
  4212. Size.prototype.subtract = function (otherSize) {
  4213. var r = new Size(this.width - otherSize.width, this.height - otherSize.height);
  4214. return r;
  4215. };
  4216. /**
  4217. * Returns a new Size set at the linear interpolation "amount" between "start" and "end".
  4218. */
  4219. Size.Lerp = function (start, end, amount) {
  4220. var w = start.width + ((end.width - start.width) * amount);
  4221. var h = start.height + ((end.height - start.height) * amount);
  4222. return new Size(w, h);
  4223. };
  4224. return Size;
  4225. }());
  4226. BABYLON.Size = Size;
  4227. var Quaternion = /** @class */ (function () {
  4228. /**
  4229. * Creates a new Quaternion from the passed floats.
  4230. */
  4231. function Quaternion(x, y, z, w) {
  4232. if (x === void 0) { x = 0.0; }
  4233. if (y === void 0) { y = 0.0; }
  4234. if (z === void 0) { z = 0.0; }
  4235. if (w === void 0) { w = 1.0; }
  4236. this.x = x;
  4237. this.y = y;
  4238. this.z = z;
  4239. this.w = w;
  4240. }
  4241. /**
  4242. * Returns a string with the Quaternion coordinates.
  4243. */
  4244. Quaternion.prototype.toString = function () {
  4245. return "{X: " + this.x + " Y:" + this.y + " Z:" + this.z + " W:" + this.w + "}";
  4246. };
  4247. /**
  4248. * Returns the string "Quaternion".
  4249. */
  4250. Quaternion.prototype.getClassName = function () {
  4251. return "Quaternion";
  4252. };
  4253. /**
  4254. * Returns the Quaternion hash code.
  4255. */
  4256. Quaternion.prototype.getHashCode = function () {
  4257. var hash = this.x || 0;
  4258. hash = (hash * 397) ^ (this.y || 0);
  4259. hash = (hash * 397) ^ (this.z || 0);
  4260. hash = (hash * 397) ^ (this.w || 0);
  4261. return hash;
  4262. };
  4263. /**
  4264. * Returns a new array populated with 4 elements : the Quaternion coordinates.
  4265. */
  4266. Quaternion.prototype.asArray = function () {
  4267. return [this.x, this.y, this.z, this.w];
  4268. };
  4269. /**
  4270. * Boolean : True if the current Quaterion and the passed one coordinates are strictly equal.
  4271. */
  4272. Quaternion.prototype.equals = function (otherQuaternion) {
  4273. return otherQuaternion && this.x === otherQuaternion.x && this.y === otherQuaternion.y && this.z === otherQuaternion.z && this.w === otherQuaternion.w;
  4274. };
  4275. /**
  4276. * Returns a new Quaternion copied from the current one.
  4277. */
  4278. Quaternion.prototype.clone = function () {
  4279. return new Quaternion(this.x, this.y, this.z, this.w);
  4280. };
  4281. /**
  4282. * Updates the current Quaternion from the passed one coordinates.
  4283. * Returns the updated Quaterion.
  4284. */
  4285. Quaternion.prototype.copyFrom = function (other) {
  4286. this.x = other.x;
  4287. this.y = other.y;
  4288. this.z = other.z;
  4289. this.w = other.w;
  4290. return this;
  4291. };
  4292. /**
  4293. * Updates the current Quaternion from the passed float coordinates.
  4294. * Returns the updated Quaterion.
  4295. */
  4296. Quaternion.prototype.copyFromFloats = function (x, y, z, w) {
  4297. this.x = x;
  4298. this.y = y;
  4299. this.z = z;
  4300. this.w = w;
  4301. return this;
  4302. };
  4303. /**
  4304. * Updates the current Quaternion from the passed float coordinates.
  4305. * Returns the updated Quaterion.
  4306. */
  4307. Quaternion.prototype.set = function (x, y, z, w) {
  4308. return this.copyFromFloats(x, y, z, w);
  4309. };
  4310. /**
  4311. * Returns a new Quaternion as the addition result of the passed one and the current Quaternion.
  4312. */
  4313. Quaternion.prototype.add = function (other) {
  4314. return new Quaternion(this.x + other.x, this.y + other.y, this.z + other.z, this.w + other.w);
  4315. };
  4316. /**
  4317. * Returns a new Quaternion as the subtraction result of the passed one from the current Quaternion.
  4318. */
  4319. Quaternion.prototype.subtract = function (other) {
  4320. return new Quaternion(this.x - other.x, this.y - other.y, this.z - other.z, this.w - other.w);
  4321. };
  4322. /**
  4323. * Returns a new Quaternion set by multiplying the current Quaterion coordinates by the float "scale".
  4324. */
  4325. Quaternion.prototype.scale = function (value) {
  4326. return new Quaternion(this.x * value, this.y * value, this.z * value, this.w * value);
  4327. };
  4328. /**
  4329. * Scale the current Quaternion values by a factor to a given Quaternion
  4330. * @param scale defines the scale factor
  4331. * @param result defines the Quaternion object where to store the result
  4332. * @returns the unmodified current Quaternion
  4333. */
  4334. Quaternion.prototype.scaleToRef = function (scale, result) {
  4335. result.x = this.x * scale;
  4336. result.y = this.y * scale;
  4337. result.z = this.z * scale;
  4338. result.w = this.w * scale;
  4339. return this;
  4340. };
  4341. /**
  4342. * Scale the current Quaternion values by a factor and add the result to a given Quaternion
  4343. * @param scale defines the scale factor
  4344. * @param result defines the Quaternion object where to store the result
  4345. * @returns the unmodified current Quaternion
  4346. */
  4347. Quaternion.prototype.scaleAndAddToRef = function (scale, result) {
  4348. result.x += this.x * scale;
  4349. result.y += this.y * scale;
  4350. result.z += this.z * scale;
  4351. result.w += this.w * scale;
  4352. return this;
  4353. };
  4354. /**
  4355. * Returns a new Quaternion set as the quaternion mulplication result of the current one with the passed one "q1".
  4356. */
  4357. Quaternion.prototype.multiply = function (q1) {
  4358. var result = new Quaternion(0, 0, 0, 1.0);
  4359. this.multiplyToRef(q1, result);
  4360. return result;
  4361. };
  4362. /**
  4363. * Sets the passed "result" as the quaternion mulplication result of the current one with the passed one "q1".
  4364. * Returns the current Quaternion.
  4365. */
  4366. Quaternion.prototype.multiplyToRef = function (q1, result) {
  4367. var x = this.x * q1.w + this.y * q1.z - this.z * q1.y + this.w * q1.x;
  4368. var y = -this.x * q1.z + this.y * q1.w + this.z * q1.x + this.w * q1.y;
  4369. var z = this.x * q1.y - this.y * q1.x + this.z * q1.w + this.w * q1.z;
  4370. var w = -this.x * q1.x - this.y * q1.y - this.z * q1.z + this.w * q1.w;
  4371. result.copyFromFloats(x, y, z, w);
  4372. return this;
  4373. };
  4374. /**
  4375. * Updates the current Quaternion with the quaternion mulplication result of itself with the passed one "q1".
  4376. * Returns the updated Quaternion.
  4377. */
  4378. Quaternion.prototype.multiplyInPlace = function (q1) {
  4379. this.multiplyToRef(q1, this);
  4380. return this;
  4381. };
  4382. /**
  4383. * Sets the passed "ref" with the conjugation of the current Quaternion.
  4384. * Returns the current Quaternion.
  4385. */
  4386. Quaternion.prototype.conjugateToRef = function (ref) {
  4387. ref.copyFromFloats(-this.x, -this.y, -this.z, this.w);
  4388. return this;
  4389. };
  4390. /**
  4391. * Conjugates in place the current Quaternion.
  4392. * Returns the updated Quaternion.
  4393. */
  4394. Quaternion.prototype.conjugateInPlace = function () {
  4395. this.x *= -1;
  4396. this.y *= -1;
  4397. this.z *= -1;
  4398. return this;
  4399. };
  4400. /**
  4401. * Returns a new Quaternion as the conjugate of the current Quaternion.
  4402. */
  4403. Quaternion.prototype.conjugate = function () {
  4404. var result = new Quaternion(-this.x, -this.y, -this.z, this.w);
  4405. return result;
  4406. };
  4407. /**
  4408. * Returns the Quaternion length (float).
  4409. */
  4410. Quaternion.prototype.length = function () {
  4411. return Math.sqrt((this.x * this.x) + (this.y * this.y) + (this.z * this.z) + (this.w * this.w));
  4412. };
  4413. /**
  4414. * Normalize in place the current Quaternion.
  4415. * Returns the updated Quaternion.
  4416. */
  4417. Quaternion.prototype.normalize = function () {
  4418. var length = 1.0 / this.length();
  4419. this.x *= length;
  4420. this.y *= length;
  4421. this.z *= length;
  4422. this.w *= length;
  4423. return this;
  4424. };
  4425. /**
  4426. * Returns a new Vector3 set with the Euler angles translated from the current Quaternion
  4427. * @param order is a reserved parameter and is ignore for now
  4428. * @returns the new Vector3
  4429. */
  4430. Quaternion.prototype.toEulerAngles = function (order) {
  4431. if (order === void 0) { order = "YZX"; }
  4432. var result = Vector3.Zero();
  4433. this.toEulerAnglesToRef(result, order);
  4434. return result;
  4435. };
  4436. /**
  4437. * Sets the passed vector3 "result" with the Euler angles translated from the current Quaternion
  4438. * @param result defines the vector which will be filled with the Euler angles
  4439. * @param order is a reserved parameter and is ignore for now
  4440. * @returns the current Quaternion
  4441. */
  4442. Quaternion.prototype.toEulerAnglesToRef = function (result, order) {
  4443. if (order === void 0) { order = "YZX"; }
  4444. var qz = this.z;
  4445. var qx = this.x;
  4446. var qy = this.y;
  4447. var qw = this.w;
  4448. var sqw = qw * qw;
  4449. var sqz = qz * qz;
  4450. var sqx = qx * qx;
  4451. var sqy = qy * qy;
  4452. var zAxisY = qy * qz - qx * qw;
  4453. var limit = .4999999;
  4454. if (zAxisY < -limit) {
  4455. result.y = 2 * Math.atan2(qy, qw);
  4456. result.x = Math.PI / 2;
  4457. result.z = 0;
  4458. }
  4459. else if (zAxisY > limit) {
  4460. result.y = 2 * Math.atan2(qy, qw);
  4461. result.x = -Math.PI / 2;
  4462. result.z = 0;
  4463. }
  4464. else {
  4465. result.z = Math.atan2(2.0 * (qx * qy + qz * qw), (-sqz - sqx + sqy + sqw));
  4466. result.x = Math.asin(-2.0 * (qz * qy - qx * qw));
  4467. result.y = Math.atan2(2.0 * (qz * qx + qy * qw), (sqz - sqx - sqy + sqw));
  4468. }
  4469. return this;
  4470. };
  4471. /**
  4472. * Updates the passed rotation matrix with the current Quaternion values.
  4473. * Returns the current Quaternion.
  4474. */
  4475. Quaternion.prototype.toRotationMatrix = function (result) {
  4476. var xx = this.x * this.x;
  4477. var yy = this.y * this.y;
  4478. var zz = this.z * this.z;
  4479. var xy = this.x * this.y;
  4480. var zw = this.z * this.w;
  4481. var zx = this.z * this.x;
  4482. var yw = this.y * this.w;
  4483. var yz = this.y * this.z;
  4484. var xw = this.x * this.w;
  4485. result.m[0] = 1.0 - (2.0 * (yy + zz));
  4486. result.m[1] = 2.0 * (xy + zw);
  4487. result.m[2] = 2.0 * (zx - yw);
  4488. result.m[3] = 0;
  4489. result.m[4] = 2.0 * (xy - zw);
  4490. result.m[5] = 1.0 - (2.0 * (zz + xx));
  4491. result.m[6] = 2.0 * (yz + xw);
  4492. result.m[7] = 0;
  4493. result.m[8] = 2.0 * (zx + yw);
  4494. result.m[9] = 2.0 * (yz - xw);
  4495. result.m[10] = 1.0 - (2.0 * (yy + xx));
  4496. result.m[11] = 0;
  4497. result.m[12] = 0;
  4498. result.m[13] = 0;
  4499. result.m[14] = 0;
  4500. result.m[15] = 1.0;
  4501. result._markAsUpdated();
  4502. return this;
  4503. };
  4504. /**
  4505. * Updates the current Quaternion from the passed rotation matrix values.
  4506. * Returns the updated Quaternion.
  4507. */
  4508. Quaternion.prototype.fromRotationMatrix = function (matrix) {
  4509. Quaternion.FromRotationMatrixToRef(matrix, this);
  4510. return this;
  4511. };
  4512. // Statics
  4513. /**
  4514. * Returns a new Quaternion set from the passed rotation matrix values.
  4515. */
  4516. Quaternion.FromRotationMatrix = function (matrix) {
  4517. var result = new Quaternion();
  4518. Quaternion.FromRotationMatrixToRef(matrix, result);
  4519. return result;
  4520. };
  4521. /**
  4522. * Updates the passed quaternion "result" with the passed rotation matrix values.
  4523. */
  4524. Quaternion.FromRotationMatrixToRef = function (matrix, result) {
  4525. var data = matrix.m;
  4526. var m11 = data[0], m12 = data[4], m13 = data[8];
  4527. var m21 = data[1], m22 = data[5], m23 = data[9];
  4528. var m31 = data[2], m32 = data[6], m33 = data[10];
  4529. var trace = m11 + m22 + m33;
  4530. var s;
  4531. if (trace > 0) {
  4532. s = 0.5 / Math.sqrt(trace + 1.0);
  4533. result.w = 0.25 / s;
  4534. result.x = (m32 - m23) * s;
  4535. result.y = (m13 - m31) * s;
  4536. result.z = (m21 - m12) * s;
  4537. }
  4538. else if (m11 > m22 && m11 > m33) {
  4539. s = 2.0 * Math.sqrt(1.0 + m11 - m22 - m33);
  4540. result.w = (m32 - m23) / s;
  4541. result.x = 0.25 * s;
  4542. result.y = (m12 + m21) / s;
  4543. result.z = (m13 + m31) / s;
  4544. }
  4545. else if (m22 > m33) {
  4546. s = 2.0 * Math.sqrt(1.0 + m22 - m11 - m33);
  4547. result.w = (m13 - m31) / s;
  4548. result.x = (m12 + m21) / s;
  4549. result.y = 0.25 * s;
  4550. result.z = (m23 + m32) / s;
  4551. }
  4552. else {
  4553. s = 2.0 * Math.sqrt(1.0 + m33 - m11 - m22);
  4554. result.w = (m21 - m12) / s;
  4555. result.x = (m13 + m31) / s;
  4556. result.y = (m23 + m32) / s;
  4557. result.z = 0.25 * s;
  4558. }
  4559. };
  4560. /**
  4561. * Returns a new Quaternion set to (0.0, 0.0, 0.0).
  4562. */
  4563. Quaternion.Zero = function () {
  4564. return new Quaternion(0.0, 0.0, 0.0, 0.0);
  4565. };
  4566. /**
  4567. * Returns a new Quaternion as the inverted current Quaternion.
  4568. */
  4569. Quaternion.Inverse = function (q) {
  4570. return new Quaternion(-q.x, -q.y, -q.z, q.w);
  4571. };
  4572. /**
  4573. * Returns the identity Quaternion.
  4574. */
  4575. Quaternion.Identity = function () {
  4576. return new Quaternion(0.0, 0.0, 0.0, 1.0);
  4577. };
  4578. Quaternion.IsIdentity = function (quaternion) {
  4579. return quaternion && quaternion.x === 0 && quaternion.y === 0 && quaternion.z === 0 && quaternion.w === 1;
  4580. };
  4581. /**
  4582. * Returns a new Quaternion set from the passed axis (Vector3) and angle in radians (float).
  4583. */
  4584. Quaternion.RotationAxis = function (axis, angle) {
  4585. return Quaternion.RotationAxisToRef(axis, angle, new Quaternion());
  4586. };
  4587. /**
  4588. * Sets the passed quaternion "result" from the passed axis (Vector3) and angle in radians (float).
  4589. */
  4590. Quaternion.RotationAxisToRef = function (axis, angle, result) {
  4591. var sin = Math.sin(angle / 2);
  4592. axis.normalize();
  4593. result.w = Math.cos(angle / 2);
  4594. result.x = axis.x * sin;
  4595. result.y = axis.y * sin;
  4596. result.z = axis.z * sin;
  4597. return result;
  4598. };
  4599. /**
  4600. * Retuns a new Quaternion set from the starting index of the passed array.
  4601. */
  4602. Quaternion.FromArray = function (array, offset) {
  4603. if (!offset) {
  4604. offset = 0;
  4605. }
  4606. return new Quaternion(array[offset], array[offset + 1], array[offset + 2], array[offset + 3]);
  4607. };
  4608. /**
  4609. * Returns a new Quaternion set from the passed Euler float angles (y, x, z).
  4610. */
  4611. Quaternion.RotationYawPitchRoll = function (yaw, pitch, roll) {
  4612. var q = new Quaternion();
  4613. Quaternion.RotationYawPitchRollToRef(yaw, pitch, roll, q);
  4614. return q;
  4615. };
  4616. /**
  4617. * Sets the passed quaternion "result" from the passed float Euler angles (y, x, z).
  4618. */
  4619. Quaternion.RotationYawPitchRollToRef = function (yaw, pitch, roll, result) {
  4620. // Produces a quaternion from Euler angles in the z-y-x orientation (Tait-Bryan angles)
  4621. var halfRoll = roll * 0.5;
  4622. var halfPitch = pitch * 0.5;
  4623. var halfYaw = yaw * 0.5;
  4624. var sinRoll = Math.sin(halfRoll);
  4625. var cosRoll = Math.cos(halfRoll);
  4626. var sinPitch = Math.sin(halfPitch);
  4627. var cosPitch = Math.cos(halfPitch);
  4628. var sinYaw = Math.sin(halfYaw);
  4629. var cosYaw = Math.cos(halfYaw);
  4630. result.x = (cosYaw * sinPitch * cosRoll) + (sinYaw * cosPitch * sinRoll);
  4631. result.y = (sinYaw * cosPitch * cosRoll) - (cosYaw * sinPitch * sinRoll);
  4632. result.z = (cosYaw * cosPitch * sinRoll) - (sinYaw * sinPitch * cosRoll);
  4633. result.w = (cosYaw * cosPitch * cosRoll) + (sinYaw * sinPitch * sinRoll);
  4634. };
  4635. /**
  4636. * Returns a new Quaternion from the passed float Euler angles expressed in z-x-z orientation
  4637. */
  4638. Quaternion.RotationAlphaBetaGamma = function (alpha, beta, gamma) {
  4639. var result = new Quaternion();
  4640. Quaternion.RotationAlphaBetaGammaToRef(alpha, beta, gamma, result);
  4641. return result;
  4642. };
  4643. /**
  4644. * Sets the passed quaternion "result" from the passed float Euler angles expressed in z-x-z orientation
  4645. */
  4646. Quaternion.RotationAlphaBetaGammaToRef = function (alpha, beta, gamma, result) {
  4647. // Produces a quaternion from Euler angles in the z-x-z orientation
  4648. var halfGammaPlusAlpha = (gamma + alpha) * 0.5;
  4649. var halfGammaMinusAlpha = (gamma - alpha) * 0.5;
  4650. var halfBeta = beta * 0.5;
  4651. result.x = Math.cos(halfGammaMinusAlpha) * Math.sin(halfBeta);
  4652. result.y = Math.sin(halfGammaMinusAlpha) * Math.sin(halfBeta);
  4653. result.z = Math.sin(halfGammaPlusAlpha) * Math.cos(halfBeta);
  4654. result.w = Math.cos(halfGammaPlusAlpha) * Math.cos(halfBeta);
  4655. };
  4656. /**
  4657. * Returns a new Quaternion as the quaternion rotation value to reach the target (axis1, axis2, axis3) orientation as a rotated XYZ system.
  4658. * cf to Vector3.RotationFromAxis() documentation.
  4659. * Note : axis1, axis2 and axis3 are normalized during this operation.
  4660. */
  4661. Quaternion.RotationQuaternionFromAxis = function (axis1, axis2, axis3, ref) {
  4662. var quat = new Quaternion(0.0, 0.0, 0.0, 0.0);
  4663. Quaternion.RotationQuaternionFromAxisToRef(axis1, axis2, axis3, quat);
  4664. return quat;
  4665. };
  4666. /**
  4667. * Sets the passed quaternion "ref" with the quaternion rotation value to reach the target (axis1, axis2, axis3) orientation as a rotated XYZ system.
  4668. * cf to Vector3.RotationFromAxis() documentation.
  4669. * Note : axis1, axis2 and axis3 are normalized during this operation.
  4670. */
  4671. Quaternion.RotationQuaternionFromAxisToRef = function (axis1, axis2, axis3, ref) {
  4672. var rotMat = MathTmp.Matrix[0];
  4673. Matrix.FromXYZAxesToRef(axis1.normalize(), axis2.normalize(), axis3.normalize(), rotMat);
  4674. Quaternion.FromRotationMatrixToRef(rotMat, ref);
  4675. };
  4676. Quaternion.Slerp = function (left, right, amount) {
  4677. var result = Quaternion.Identity();
  4678. Quaternion.SlerpToRef(left, right, amount, result);
  4679. return result;
  4680. };
  4681. Quaternion.SlerpToRef = function (left, right, amount, result) {
  4682. var num2;
  4683. var num3;
  4684. var num = amount;
  4685. var num4 = (((left.x * right.x) + (left.y * right.y)) + (left.z * right.z)) + (left.w * right.w);
  4686. var flag = false;
  4687. if (num4 < 0) {
  4688. flag = true;
  4689. num4 = -num4;
  4690. }
  4691. if (num4 > 0.999999) {
  4692. num3 = 1 - num;
  4693. num2 = flag ? -num : num;
  4694. }
  4695. else {
  4696. var num5 = Math.acos(num4);
  4697. var num6 = (1.0 / Math.sin(num5));
  4698. num3 = (Math.sin((1.0 - num) * num5)) * num6;
  4699. num2 = flag ? ((-Math.sin(num * num5)) * num6) : ((Math.sin(num * num5)) * num6);
  4700. }
  4701. result.x = (num3 * left.x) + (num2 * right.x);
  4702. result.y = (num3 * left.y) + (num2 * right.y);
  4703. result.z = (num3 * left.z) + (num2 * right.z);
  4704. result.w = (num3 * left.w) + (num2 * right.w);
  4705. };
  4706. /**
  4707. * Returns a new Quaternion located for "amount" (float) on the Hermite interpolation spline defined by the vectors "value1", "tangent1", "value2", "tangent2".
  4708. */
  4709. Quaternion.Hermite = function (value1, tangent1, value2, tangent2, amount) {
  4710. var squared = amount * amount;
  4711. var cubed = amount * squared;
  4712. var part1 = ((2.0 * cubed) - (3.0 * squared)) + 1.0;
  4713. var part2 = (-2.0 * cubed) + (3.0 * squared);
  4714. var part3 = (cubed - (2.0 * squared)) + amount;
  4715. var part4 = cubed - squared;
  4716. var x = (((value1.x * part1) + (value2.x * part2)) + (tangent1.x * part3)) + (tangent2.x * part4);
  4717. var y = (((value1.y * part1) + (value2.y * part2)) + (tangent1.y * part3)) + (tangent2.y * part4);
  4718. var z = (((value1.z * part1) + (value2.z * part2)) + (tangent1.z * part3)) + (tangent2.z * part4);
  4719. var w = (((value1.w * part1) + (value2.w * part2)) + (tangent1.w * part3)) + (tangent2.w * part4);
  4720. return new Quaternion(x, y, z, w);
  4721. };
  4722. return Quaternion;
  4723. }());
  4724. BABYLON.Quaternion = Quaternion;
  4725. var Matrix = /** @class */ (function () {
  4726. function Matrix() {
  4727. this._isIdentity = false;
  4728. this._isIdentityDirty = true;
  4729. this.m = new Float32Array(16);
  4730. this._markAsUpdated();
  4731. }
  4732. Matrix.prototype._markAsUpdated = function () {
  4733. this.updateFlag = Matrix._updateFlagSeed++;
  4734. this._isIdentityDirty = true;
  4735. };
  4736. // Properties
  4737. /**
  4738. * Boolean : True is the matrix is the identity matrix
  4739. */
  4740. Matrix.prototype.isIdentity = function (considerAsTextureMatrix) {
  4741. if (considerAsTextureMatrix === void 0) { considerAsTextureMatrix = false; }
  4742. if (this._isIdentityDirty) {
  4743. this._isIdentityDirty = false;
  4744. if (this.m[0] !== 1.0 || this.m[5] !== 1.0 || this.m[15] !== 1.0) {
  4745. this._isIdentity = false;
  4746. }
  4747. else if (this.m[1] !== 0.0 || this.m[2] !== 0.0 || this.m[3] !== 0.0 ||
  4748. this.m[4] !== 0.0 || this.m[6] !== 0.0 || this.m[7] !== 0.0 ||
  4749. this.m[8] !== 0.0 || this.m[9] !== 0.0 || this.m[11] !== 0.0 ||
  4750. this.m[12] !== 0.0 || this.m[13] !== 0.0 || this.m[14] !== 0.0) {
  4751. this._isIdentity = false;
  4752. }
  4753. else {
  4754. this._isIdentity = true;
  4755. }
  4756. if (!considerAsTextureMatrix && this.m[10] !== 1.0) {
  4757. this._isIdentity = false;
  4758. }
  4759. }
  4760. return this._isIdentity;
  4761. };
  4762. /**
  4763. * Returns the matrix determinant (float).
  4764. */
  4765. Matrix.prototype.determinant = function () {
  4766. var temp1 = (this.m[10] * this.m[15]) - (this.m[11] * this.m[14]);
  4767. var temp2 = (this.m[9] * this.m[15]) - (this.m[11] * this.m[13]);
  4768. var temp3 = (this.m[9] * this.m[14]) - (this.m[10] * this.m[13]);
  4769. var temp4 = (this.m[8] * this.m[15]) - (this.m[11] * this.m[12]);
  4770. var temp5 = (this.m[8] * this.m[14]) - (this.m[10] * this.m[12]);
  4771. var temp6 = (this.m[8] * this.m[13]) - (this.m[9] * this.m[12]);
  4772. return ((((this.m[0] * (((this.m[5] * temp1) - (this.m[6] * temp2)) + (this.m[7] * temp3))) - (this.m[1] * (((this.m[4] * temp1) -
  4773. (this.m[6] * temp4)) + (this.m[7] * temp5)))) + (this.m[2] * (((this.m[4] * temp2) - (this.m[5] * temp4)) + (this.m[7] * temp6)))) -
  4774. (this.m[3] * (((this.m[4] * temp3) - (this.m[5] * temp5)) + (this.m[6] * temp6))));
  4775. };
  4776. // Methods
  4777. /**
  4778. * Returns the matrix underlying array.
  4779. */
  4780. Matrix.prototype.toArray = function () {
  4781. return this.m;
  4782. };
  4783. /**
  4784. * Returns the matrix underlying array.
  4785. */
  4786. Matrix.prototype.asArray = function () {
  4787. return this.toArray();
  4788. };
  4789. /**
  4790. * Inverts in place the Matrix.
  4791. * Returns the Matrix inverted.
  4792. */
  4793. Matrix.prototype.invert = function () {
  4794. this.invertToRef(this);
  4795. return this;
  4796. };
  4797. /**
  4798. * Sets all the matrix elements to zero.
  4799. * Returns the Matrix.
  4800. */
  4801. Matrix.prototype.reset = function () {
  4802. for (var index = 0; index < 16; index++) {
  4803. this.m[index] = 0.0;
  4804. }
  4805. this._markAsUpdated();
  4806. return this;
  4807. };
  4808. /**
  4809. * Returns a new Matrix as the addition result of the current Matrix and the passed one.
  4810. */
  4811. Matrix.prototype.add = function (other) {
  4812. var result = new Matrix();
  4813. this.addToRef(other, result);
  4814. return result;
  4815. };
  4816. /**
  4817. * Sets the passed matrix "result" with the ddition result of the current Matrix and the passed one.
  4818. * Returns the Matrix.
  4819. */
  4820. Matrix.prototype.addToRef = function (other, result) {
  4821. for (var index = 0; index < 16; index++) {
  4822. result.m[index] = this.m[index] + other.m[index];
  4823. }
  4824. result._markAsUpdated();
  4825. return this;
  4826. };
  4827. /**
  4828. * Adds in place the passed matrix to the current Matrix.
  4829. * Returns the updated Matrix.
  4830. */
  4831. Matrix.prototype.addToSelf = function (other) {
  4832. for (var index = 0; index < 16; index++) {
  4833. this.m[index] += other.m[index];
  4834. }
  4835. this._markAsUpdated();
  4836. return this;
  4837. };
  4838. /**
  4839. * Sets the passed matrix with the current inverted Matrix.
  4840. * Returns the unmodified current Matrix.
  4841. */
  4842. Matrix.prototype.invertToRef = function (other) {
  4843. var l1 = this.m[0];
  4844. var l2 = this.m[1];
  4845. var l3 = this.m[2];
  4846. var l4 = this.m[3];
  4847. var l5 = this.m[4];
  4848. var l6 = this.m[5];
  4849. var l7 = this.m[6];
  4850. var l8 = this.m[7];
  4851. var l9 = this.m[8];
  4852. var l10 = this.m[9];
  4853. var l11 = this.m[10];
  4854. var l12 = this.m[11];
  4855. var l13 = this.m[12];
  4856. var l14 = this.m[13];
  4857. var l15 = this.m[14];
  4858. var l16 = this.m[15];
  4859. var l17 = (l11 * l16) - (l12 * l15);
  4860. var l18 = (l10 * l16) - (l12 * l14);
  4861. var l19 = (l10 * l15) - (l11 * l14);
  4862. var l20 = (l9 * l16) - (l12 * l13);
  4863. var l21 = (l9 * l15) - (l11 * l13);
  4864. var l22 = (l9 * l14) - (l10 * l13);
  4865. var l23 = ((l6 * l17) - (l7 * l18)) + (l8 * l19);
  4866. var l24 = -(((l5 * l17) - (l7 * l20)) + (l8 * l21));
  4867. var l25 = ((l5 * l18) - (l6 * l20)) + (l8 * l22);
  4868. var l26 = -(((l5 * l19) - (l6 * l21)) + (l7 * l22));
  4869. var l27 = 1.0 / ((((l1 * l23) + (l2 * l24)) + (l3 * l25)) + (l4 * l26));
  4870. var l28 = (l7 * l16) - (l8 * l15);
  4871. var l29 = (l6 * l16) - (l8 * l14);
  4872. var l30 = (l6 * l15) - (l7 * l14);
  4873. var l31 = (l5 * l16) - (l8 * l13);
  4874. var l32 = (l5 * l15) - (l7 * l13);
  4875. var l33 = (l5 * l14) - (l6 * l13);
  4876. var l34 = (l7 * l12) - (l8 * l11);
  4877. var l35 = (l6 * l12) - (l8 * l10);
  4878. var l36 = (l6 * l11) - (l7 * l10);
  4879. var l37 = (l5 * l12) - (l8 * l9);
  4880. var l38 = (l5 * l11) - (l7 * l9);
  4881. var l39 = (l5 * l10) - (l6 * l9);
  4882. other.m[0] = l23 * l27;
  4883. other.m[4] = l24 * l27;
  4884. other.m[8] = l25 * l27;
  4885. other.m[12] = l26 * l27;
  4886. other.m[1] = -(((l2 * l17) - (l3 * l18)) + (l4 * l19)) * l27;
  4887. other.m[5] = (((l1 * l17) - (l3 * l20)) + (l4 * l21)) * l27;
  4888. other.m[9] = -(((l1 * l18) - (l2 * l20)) + (l4 * l22)) * l27;
  4889. other.m[13] = (((l1 * l19) - (l2 * l21)) + (l3 * l22)) * l27;
  4890. other.m[2] = (((l2 * l28) - (l3 * l29)) + (l4 * l30)) * l27;
  4891. other.m[6] = -(((l1 * l28) - (l3 * l31)) + (l4 * l32)) * l27;
  4892. other.m[10] = (((l1 * l29) - (l2 * l31)) + (l4 * l33)) * l27;
  4893. other.m[14] = -(((l1 * l30) - (l2 * l32)) + (l3 * l33)) * l27;
  4894. other.m[3] = -(((l2 * l34) - (l3 * l35)) + (l4 * l36)) * l27;
  4895. other.m[7] = (((l1 * l34) - (l3 * l37)) + (l4 * l38)) * l27;
  4896. other.m[11] = -(((l1 * l35) - (l2 * l37)) + (l4 * l39)) * l27;
  4897. other.m[15] = (((l1 * l36) - (l2 * l38)) + (l3 * l39)) * l27;
  4898. other._markAsUpdated();
  4899. return this;
  4900. };
  4901. /**
  4902. * Inserts the translation vector (using 3 x floats) in the current Matrix.
  4903. * Returns the updated Matrix.
  4904. */
  4905. Matrix.prototype.setTranslationFromFloats = function (x, y, z) {
  4906. this.m[12] = x;
  4907. this.m[13] = y;
  4908. this.m[14] = z;
  4909. this._markAsUpdated();
  4910. return this;
  4911. };
  4912. /**
  4913. * Inserts the translation vector in the current Matrix.
  4914. * Returns the updated Matrix.
  4915. */
  4916. Matrix.prototype.setTranslation = function (vector3) {
  4917. this.m[12] = vector3.x;
  4918. this.m[13] = vector3.y;
  4919. this.m[14] = vector3.z;
  4920. this._markAsUpdated();
  4921. return this;
  4922. };
  4923. /**
  4924. * Returns a new Vector3 as the extracted translation from the Matrix.
  4925. */
  4926. Matrix.prototype.getTranslation = function () {
  4927. return new Vector3(this.m[12], this.m[13], this.m[14]);
  4928. };
  4929. /**
  4930. * Fill a Vector3 with the extracted translation from the Matrix.
  4931. */
  4932. Matrix.prototype.getTranslationToRef = function (result) {
  4933. result.x = this.m[12];
  4934. result.y = this.m[13];
  4935. result.z = this.m[14];
  4936. return this;
  4937. };
  4938. /**
  4939. * Remove rotation and scaling part from the Matrix.
  4940. * Returns the updated Matrix.
  4941. */
  4942. Matrix.prototype.removeRotationAndScaling = function () {
  4943. this.setRowFromFloats(0, 1, 0, 0, 0);
  4944. this.setRowFromFloats(1, 0, 1, 0, 0);
  4945. this.setRowFromFloats(2, 0, 0, 1, 0);
  4946. return this;
  4947. };
  4948. /**
  4949. * Returns a new Matrix set with the multiplication result of the current Matrix and the passed one.
  4950. */
  4951. Matrix.prototype.multiply = function (other) {
  4952. var result = new Matrix();
  4953. this.multiplyToRef(other, result);
  4954. return result;
  4955. };
  4956. /**
  4957. * Updates the current Matrix from the passed one values.
  4958. * Returns the updated Matrix.
  4959. */
  4960. Matrix.prototype.copyFrom = function (other) {
  4961. for (var index = 0; index < 16; index++) {
  4962. this.m[index] = other.m[index];
  4963. }
  4964. this._markAsUpdated();
  4965. return this;
  4966. };
  4967. /**
  4968. * Populates the passed array from the starting index with the Matrix values.
  4969. * Returns the Matrix.
  4970. */
  4971. Matrix.prototype.copyToArray = function (array, offset) {
  4972. if (offset === void 0) { offset = 0; }
  4973. for (var index = 0; index < 16; index++) {
  4974. array[offset + index] = this.m[index];
  4975. }
  4976. return this;
  4977. };
  4978. /**
  4979. * Sets the passed matrix "result" with the multiplication result of the current Matrix and the passed one.
  4980. */
  4981. Matrix.prototype.multiplyToRef = function (other, result) {
  4982. this.multiplyToArray(other, result.m, 0);
  4983. result._markAsUpdated();
  4984. return this;
  4985. };
  4986. /**
  4987. * Sets the Float32Array "result" from the passed index "offset" with the multiplication result of the current Matrix and the passed one.
  4988. */
  4989. Matrix.prototype.multiplyToArray = function (other, result, offset) {
  4990. var tm0 = this.m[0];
  4991. var tm1 = this.m[1];
  4992. var tm2 = this.m[2];
  4993. var tm3 = this.m[3];
  4994. var tm4 = this.m[4];
  4995. var tm5 = this.m[5];
  4996. var tm6 = this.m[6];
  4997. var tm7 = this.m[7];
  4998. var tm8 = this.m[8];
  4999. var tm9 = this.m[9];
  5000. var tm10 = this.m[10];
  5001. var tm11 = this.m[11];
  5002. var tm12 = this.m[12];
  5003. var tm13 = this.m[13];
  5004. var tm14 = this.m[14];
  5005. var tm15 = this.m[15];
  5006. var om0 = other.m[0];
  5007. var om1 = other.m[1];
  5008. var om2 = other.m[2];
  5009. var om3 = other.m[3];
  5010. var om4 = other.m[4];
  5011. var om5 = other.m[5];
  5012. var om6 = other.m[6];
  5013. var om7 = other.m[7];
  5014. var om8 = other.m[8];
  5015. var om9 = other.m[9];
  5016. var om10 = other.m[10];
  5017. var om11 = other.m[11];
  5018. var om12 = other.m[12];
  5019. var om13 = other.m[13];
  5020. var om14 = other.m[14];
  5021. var om15 = other.m[15];
  5022. result[offset] = tm0 * om0 + tm1 * om4 + tm2 * om8 + tm3 * om12;
  5023. result[offset + 1] = tm0 * om1 + tm1 * om5 + tm2 * om9 + tm3 * om13;
  5024. result[offset + 2] = tm0 * om2 + tm1 * om6 + tm2 * om10 + tm3 * om14;
  5025. result[offset + 3] = tm0 * om3 + tm1 * om7 + tm2 * om11 + tm3 * om15;
  5026. result[offset + 4] = tm4 * om0 + tm5 * om4 + tm6 * om8 + tm7 * om12;
  5027. result[offset + 5] = tm4 * om1 + tm5 * om5 + tm6 * om9 + tm7 * om13;
  5028. result[offset + 6] = tm4 * om2 + tm5 * om6 + tm6 * om10 + tm7 * om14;
  5029. result[offset + 7] = tm4 * om3 + tm5 * om7 + tm6 * om11 + tm7 * om15;
  5030. result[offset + 8] = tm8 * om0 + tm9 * om4 + tm10 * om8 + tm11 * om12;
  5031. result[offset + 9] = tm8 * om1 + tm9 * om5 + tm10 * om9 + tm11 * om13;
  5032. result[offset + 10] = tm8 * om2 + tm9 * om6 + tm10 * om10 + tm11 * om14;
  5033. result[offset + 11] = tm8 * om3 + tm9 * om7 + tm10 * om11 + tm11 * om15;
  5034. result[offset + 12] = tm12 * om0 + tm13 * om4 + tm14 * om8 + tm15 * om12;
  5035. result[offset + 13] = tm12 * om1 + tm13 * om5 + tm14 * om9 + tm15 * om13;
  5036. result[offset + 14] = tm12 * om2 + tm13 * om6 + tm14 * om10 + tm15 * om14;
  5037. result[offset + 15] = tm12 * om3 + tm13 * om7 + tm14 * om11 + tm15 * om15;
  5038. return this;
  5039. };
  5040. /**
  5041. * Boolean : True is the current Matrix and the passed one values are strictly equal.
  5042. */
  5043. Matrix.prototype.equals = function (value) {
  5044. return value &&
  5045. (this.m[0] === value.m[0] && this.m[1] === value.m[1] && this.m[2] === value.m[2] && this.m[3] === value.m[3] &&
  5046. this.m[4] === value.m[4] && this.m[5] === value.m[5] && this.m[6] === value.m[6] && this.m[7] === value.m[7] &&
  5047. this.m[8] === value.m[8] && this.m[9] === value.m[9] && this.m[10] === value.m[10] && this.m[11] === value.m[11] &&
  5048. this.m[12] === value.m[12] && this.m[13] === value.m[13] && this.m[14] === value.m[14] && this.m[15] === value.m[15]);
  5049. };
  5050. /**
  5051. * Returns a new Matrix from the current Matrix.
  5052. */
  5053. Matrix.prototype.clone = function () {
  5054. 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]);
  5055. };
  5056. /**
  5057. * Returns the string "Matrix"
  5058. */
  5059. Matrix.prototype.getClassName = function () {
  5060. return "Matrix";
  5061. };
  5062. /**
  5063. * Returns the Matrix hash code.
  5064. */
  5065. Matrix.prototype.getHashCode = function () {
  5066. var hash = this.m[0] || 0;
  5067. for (var i = 1; i < 16; i++) {
  5068. hash = (hash * 397) ^ (this.m[i] || 0);
  5069. }
  5070. return hash;
  5071. };
  5072. /**
  5073. * Decomposes the current Matrix into :
  5074. * - a scale vector3 passed as a reference to update,
  5075. * - a rotation quaternion passed as a reference to update,
  5076. * - a translation vector3 passed as a reference to update.
  5077. * Returns the true if operation was successful.
  5078. */
  5079. Matrix.prototype.decompose = function (scale, rotation, translation) {
  5080. translation.x = this.m[12];
  5081. translation.y = this.m[13];
  5082. translation.z = this.m[14];
  5083. scale.x = Math.sqrt(this.m[0] * this.m[0] + this.m[1] * this.m[1] + this.m[2] * this.m[2]);
  5084. scale.y = Math.sqrt(this.m[4] * this.m[4] + this.m[5] * this.m[5] + this.m[6] * this.m[6]);
  5085. scale.z = Math.sqrt(this.m[8] * this.m[8] + this.m[9] * this.m[9] + this.m[10] * this.m[10]);
  5086. if (this.determinant() <= 0) {
  5087. scale.y *= -1;
  5088. }
  5089. if (scale.x === 0 || scale.y === 0 || scale.z === 0) {
  5090. rotation.x = 0;
  5091. rotation.y = 0;
  5092. rotation.z = 0;
  5093. rotation.w = 1;
  5094. return false;
  5095. }
  5096. 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]);
  5097. Quaternion.FromRotationMatrixToRef(MathTmp.Matrix[0], rotation);
  5098. return true;
  5099. };
  5100. /**
  5101. * Returns the index-th row of the current matrix as a new Vector4.
  5102. */
  5103. Matrix.prototype.getRow = function (index) {
  5104. if (index < 0 || index > 3) {
  5105. return null;
  5106. }
  5107. var i = index * 4;
  5108. return new Vector4(this.m[i + 0], this.m[i + 1], this.m[i + 2], this.m[i + 3]);
  5109. };
  5110. /**
  5111. * Sets the index-th row of the current matrix with the passed Vector4 values.
  5112. * Returns the updated Matrix.
  5113. */
  5114. Matrix.prototype.setRow = function (index, row) {
  5115. if (index < 0 || index > 3) {
  5116. return this;
  5117. }
  5118. var i = index * 4;
  5119. this.m[i + 0] = row.x;
  5120. this.m[i + 1] = row.y;
  5121. this.m[i + 2] = row.z;
  5122. this.m[i + 3] = row.w;
  5123. this._markAsUpdated();
  5124. return this;
  5125. };
  5126. /**
  5127. * Compute the transpose of the matrix.
  5128. * Returns a new Matrix.
  5129. */
  5130. Matrix.prototype.transpose = function () {
  5131. return Matrix.Transpose(this);
  5132. };
  5133. /**
  5134. * Compute the transpose of the matrix.
  5135. * Returns the current matrix.
  5136. */
  5137. Matrix.prototype.transposeToRef = function (result) {
  5138. Matrix.TransposeToRef(this, result);
  5139. return this;
  5140. };
  5141. /**
  5142. * Sets the index-th row of the current matrix with the passed 4 x float values.
  5143. * Returns the updated Matrix.
  5144. */
  5145. Matrix.prototype.setRowFromFloats = function (index, x, y, z, w) {
  5146. if (index < 0 || index > 3) {
  5147. return this;
  5148. }
  5149. var i = index * 4;
  5150. this.m[i + 0] = x;
  5151. this.m[i + 1] = y;
  5152. this.m[i + 2] = z;
  5153. this.m[i + 3] = w;
  5154. this._markAsUpdated();
  5155. return this;
  5156. };
  5157. /**
  5158. * Compute a new Matrix set with the current Matrix values multiplied by scale (float)
  5159. * @param scale defines the scale factor
  5160. * @returns a new Matrix
  5161. */
  5162. Matrix.prototype.scale = function (scale) {
  5163. var result = new Matrix();
  5164. this.scaleToRef(scale, result);
  5165. return result;
  5166. };
  5167. /**
  5168. * Scale the current Matrix values by a factor to a given result Matrix
  5169. * @param scale defines the scale factor
  5170. * @param result defines the Matrix to store the result
  5171. * @returns the current Matrix
  5172. */
  5173. Matrix.prototype.scaleToRef = function (scale, result) {
  5174. for (var index = 0; index < 16; index++) {
  5175. result.m[index] = this.m[index] * scale;
  5176. }
  5177. result._markAsUpdated();
  5178. return this;
  5179. };
  5180. /**
  5181. * Scale the current Matrix values by a factor and add the result to a given Matrix
  5182. * @param scale defines the scale factor
  5183. * @param result defines the Matrix to store the result
  5184. * @returns the current Matrix
  5185. */
  5186. Matrix.prototype.scaleAndAddToRef = function (scale, result) {
  5187. for (var index = 0; index < 16; index++) {
  5188. result.m[index] += this.m[index] * scale;
  5189. }
  5190. result._markAsUpdated();
  5191. return this;
  5192. };
  5193. /**
  5194. * Writes to the given matrix a normal matrix, computed from this one (using values from identity matrix for fourth row and column).
  5195. * @param ref matrix to store the result
  5196. */
  5197. Matrix.prototype.toNormalMatrix = function (ref) {
  5198. this.invertToRef(ref);
  5199. ref.transpose();
  5200. var m = ref.m;
  5201. 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);
  5202. };
  5203. /**
  5204. * Returns a new Matrix as the extracted rotation matrix from the current one.
  5205. */
  5206. Matrix.prototype.getRotationMatrix = function () {
  5207. var result = Matrix.Identity();
  5208. this.getRotationMatrixToRef(result);
  5209. return result;
  5210. };
  5211. /**
  5212. * Extracts the rotation matrix from the current one and sets it as the passed "result".
  5213. * Returns the current Matrix.
  5214. */
  5215. Matrix.prototype.getRotationMatrixToRef = function (result) {
  5216. var m = this.m;
  5217. var xs = m[0] * m[1] * m[2] * m[3] < 0 ? -1 : 1;
  5218. var ys = m[4] * m[5] * m[6] * m[7] < 0 ? -1 : 1;
  5219. var zs = m[8] * m[9] * m[10] * m[11] < 0 ? -1 : 1;
  5220. var sx = xs * Math.sqrt(m[0] * m[0] + m[1] * m[1] + m[2] * m[2]);
  5221. var sy = ys * Math.sqrt(m[4] * m[4] + m[5] * m[5] + m[6] * m[6]);
  5222. var sz = zs * Math.sqrt(m[8] * m[8] + m[9] * m[9] + m[10] * m[10]);
  5223. 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);
  5224. return this;
  5225. };
  5226. // Statics
  5227. /**
  5228. * Returns a new Matrix set from the starting index of the passed array.
  5229. */
  5230. Matrix.FromArray = function (array, offset) {
  5231. var result = new Matrix();
  5232. if (!offset) {
  5233. offset = 0;
  5234. }
  5235. Matrix.FromArrayToRef(array, offset, result);
  5236. return result;
  5237. };
  5238. /**
  5239. * Sets the passed "result" matrix from the starting index of the passed array.
  5240. */
  5241. Matrix.FromArrayToRef = function (array, offset, result) {
  5242. for (var index = 0; index < 16; index++) {
  5243. result.m[index] = array[index + offset];
  5244. }
  5245. result._markAsUpdated();
  5246. };
  5247. /**
  5248. * Sets the passed "result" matrix from the starting index of the passed Float32Array by multiplying each element by the float "scale".
  5249. */
  5250. Matrix.FromFloat32ArrayToRefScaled = function (array, offset, scale, result) {
  5251. for (var index = 0; index < 16; index++) {
  5252. result.m[index] = array[index + offset] * scale;
  5253. }
  5254. result._markAsUpdated();
  5255. };
  5256. /**
  5257. * Sets the passed matrix "result" with the 16 passed floats.
  5258. */
  5259. Matrix.FromValuesToRef = function (initialM11, initialM12, initialM13, initialM14, initialM21, initialM22, initialM23, initialM24, initialM31, initialM32, initialM33, initialM34, initialM41, initialM42, initialM43, initialM44, result) {
  5260. result.m[0] = initialM11;
  5261. result.m[1] = initialM12;
  5262. result.m[2] = initialM13;
  5263. result.m[3] = initialM14;
  5264. result.m[4] = initialM21;
  5265. result.m[5] = initialM22;
  5266. result.m[6] = initialM23;
  5267. result.m[7] = initialM24;
  5268. result.m[8] = initialM31;
  5269. result.m[9] = initialM32;
  5270. result.m[10] = initialM33;
  5271. result.m[11] = initialM34;
  5272. result.m[12] = initialM41;
  5273. result.m[13] = initialM42;
  5274. result.m[14] = initialM43;
  5275. result.m[15] = initialM44;
  5276. result._markAsUpdated();
  5277. };
  5278. Object.defineProperty(Matrix, "IdentityReadOnly", {
  5279. /**
  5280. * Static identity matrix to be used as readonly matrix
  5281. * Must not be updated.
  5282. */
  5283. get: function () {
  5284. return Matrix._identityReadOnly;
  5285. },
  5286. enumerable: true,
  5287. configurable: true
  5288. });
  5289. /**
  5290. * Returns a new Matrix set from the 16 passed floats.
  5291. */
  5292. Matrix.FromValues = function (initialM11, initialM12, initialM13, initialM14, initialM21, initialM22, initialM23, initialM24, initialM31, initialM32, initialM33, initialM34, initialM41, initialM42, initialM43, initialM44) {
  5293. var result = new Matrix();
  5294. result.m[0] = initialM11;
  5295. result.m[1] = initialM12;
  5296. result.m[2] = initialM13;
  5297. result.m[3] = initialM14;
  5298. result.m[4] = initialM21;
  5299. result.m[5] = initialM22;
  5300. result.m[6] = initialM23;
  5301. result.m[7] = initialM24;
  5302. result.m[8] = initialM31;
  5303. result.m[9] = initialM32;
  5304. result.m[10] = initialM33;
  5305. result.m[11] = initialM34;
  5306. result.m[12] = initialM41;
  5307. result.m[13] = initialM42;
  5308. result.m[14] = initialM43;
  5309. result.m[15] = initialM44;
  5310. return result;
  5311. };
  5312. /**
  5313. * Returns a new Matrix composed by the passed scale (vector3), rotation (quaternion) and translation (vector3).
  5314. */
  5315. Matrix.Compose = function (scale, rotation, translation) {
  5316. var result = Matrix.Identity();
  5317. Matrix.ComposeToRef(scale, rotation, translation, result);
  5318. return result;
  5319. };
  5320. /**
  5321. * Update a Matrix with values composed by the passed scale (vector3), rotation (quaternion) and translation (vector3).
  5322. */
  5323. Matrix.ComposeToRef = function (scale, rotation, translation, result) {
  5324. Matrix.FromValuesToRef(scale.x, 0, 0, 0, 0, scale.y, 0, 0, 0, 0, scale.z, 0, 0, 0, 0, 1, MathTmp.Matrix[1]);
  5325. rotation.toRotationMatrix(MathTmp.Matrix[0]);
  5326. MathTmp.Matrix[1].multiplyToRef(MathTmp.Matrix[0], result);
  5327. result.setTranslation(translation);
  5328. };
  5329. /**
  5330. * Returns a new indentity Matrix.
  5331. */
  5332. Matrix.Identity = function () {
  5333. 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);
  5334. };
  5335. /**
  5336. * Sets the passed "result" as an identity matrix.
  5337. */
  5338. Matrix.IdentityToRef = function (result) {
  5339. 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);
  5340. };
  5341. /**
  5342. * Returns a new zero Matrix.
  5343. */
  5344. Matrix.Zero = function () {
  5345. 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);
  5346. };
  5347. /**
  5348. * Returns a new rotation matrix for "angle" radians around the X axis.
  5349. */
  5350. Matrix.RotationX = function (angle) {
  5351. var result = new Matrix();
  5352. Matrix.RotationXToRef(angle, result);
  5353. return result;
  5354. };
  5355. /**
  5356. * Returns a new Matrix as the passed inverted one.
  5357. */
  5358. Matrix.Invert = function (source) {
  5359. var result = new Matrix();
  5360. source.invertToRef(result);
  5361. return result;
  5362. };
  5363. /**
  5364. * Sets the passed matrix "result" as a rotation matrix for "angle" radians around the X axis.
  5365. */
  5366. Matrix.RotationXToRef = function (angle, result) {
  5367. var s = Math.sin(angle);
  5368. var c = Math.cos(angle);
  5369. result.m[0] = 1.0;
  5370. result.m[15] = 1.0;
  5371. result.m[5] = c;
  5372. result.m[10] = c;
  5373. result.m[9] = -s;
  5374. result.m[6] = s;
  5375. result.m[1] = 0.0;
  5376. result.m[2] = 0.0;
  5377. result.m[3] = 0.0;
  5378. result.m[4] = 0.0;
  5379. result.m[7] = 0.0;
  5380. result.m[8] = 0.0;
  5381. result.m[11] = 0.0;
  5382. result.m[12] = 0.0;
  5383. result.m[13] = 0.0;
  5384. result.m[14] = 0.0;
  5385. result._markAsUpdated();
  5386. };
  5387. /**
  5388. * Returns a new rotation matrix for "angle" radians around the Y axis.
  5389. */
  5390. Matrix.RotationY = function (angle) {
  5391. var result = new Matrix();
  5392. Matrix.RotationYToRef(angle, result);
  5393. return result;
  5394. };
  5395. /**
  5396. * Sets the passed matrix "result" as a rotation matrix for "angle" radians around the Y axis.
  5397. */
  5398. Matrix.RotationYToRef = function (angle, result) {
  5399. var s = Math.sin(angle);
  5400. var c = Math.cos(angle);
  5401. result.m[5] = 1.0;
  5402. result.m[15] = 1.0;
  5403. result.m[0] = c;
  5404. result.m[2] = -s;
  5405. result.m[8] = s;
  5406. result.m[10] = c;
  5407. result.m[1] = 0.0;
  5408. result.m[3] = 0.0;
  5409. result.m[4] = 0.0;
  5410. result.m[6] = 0.0;
  5411. result.m[7] = 0.0;
  5412. result.m[9] = 0.0;
  5413. result.m[11] = 0.0;
  5414. result.m[12] = 0.0;
  5415. result.m[13] = 0.0;
  5416. result.m[14] = 0.0;
  5417. result._markAsUpdated();
  5418. };
  5419. /**
  5420. * Returns a new rotation matrix for "angle" radians around the Z axis.
  5421. */
  5422. Matrix.RotationZ = function (angle) {
  5423. var result = new Matrix();
  5424. Matrix.RotationZToRef(angle, result);
  5425. return result;
  5426. };
  5427. /**
  5428. * Sets the passed matrix "result" as a rotation matrix for "angle" radians around the Z axis.
  5429. */
  5430. Matrix.RotationZToRef = function (angle, result) {
  5431. var s = Math.sin(angle);
  5432. var c = Math.cos(angle);
  5433. result.m[10] = 1.0;
  5434. result.m[15] = 1.0;
  5435. result.m[0] = c;
  5436. result.m[1] = s;
  5437. result.m[4] = -s;
  5438. result.m[5] = c;
  5439. result.m[2] = 0.0;
  5440. result.m[3] = 0.0;
  5441. result.m[6] = 0.0;
  5442. result.m[7] = 0.0;
  5443. result.m[8] = 0.0;
  5444. result.m[9] = 0.0;
  5445. result.m[11] = 0.0;
  5446. result.m[12] = 0.0;
  5447. result.m[13] = 0.0;
  5448. result.m[14] = 0.0;
  5449. result._markAsUpdated();
  5450. };
  5451. /**
  5452. * Returns a new rotation matrix for "angle" radians around the passed axis.
  5453. */
  5454. Matrix.RotationAxis = function (axis, angle) {
  5455. var result = Matrix.Zero();
  5456. Matrix.RotationAxisToRef(axis, angle, result);
  5457. return result;
  5458. };
  5459. /**
  5460. * Sets the passed matrix "result" as a rotation matrix for "angle" radians around the passed axis.
  5461. */
  5462. Matrix.RotationAxisToRef = function (axis, angle, result) {
  5463. var s = Math.sin(-angle);
  5464. var c = Math.cos(-angle);
  5465. var c1 = 1 - c;
  5466. axis.normalize();
  5467. result.m[0] = (axis.x * axis.x) * c1 + c;
  5468. result.m[1] = (axis.x * axis.y) * c1 - (axis.z * s);
  5469. result.m[2] = (axis.x * axis.z) * c1 + (axis.y * s);
  5470. result.m[3] = 0.0;
  5471. result.m[4] = (axis.y * axis.x) * c1 + (axis.z * s);
  5472. result.m[5] = (axis.y * axis.y) * c1 + c;
  5473. result.m[6] = (axis.y * axis.z) * c1 - (axis.x * s);
  5474. result.m[7] = 0.0;
  5475. result.m[8] = (axis.z * axis.x) * c1 - (axis.y * s);
  5476. result.m[9] = (axis.z * axis.y) * c1 + (axis.x * s);
  5477. result.m[10] = (axis.z * axis.z) * c1 + c;
  5478. result.m[11] = 0.0;
  5479. result.m[15] = 1.0;
  5480. result._markAsUpdated();
  5481. };
  5482. /**
  5483. * Returns a new Matrix as a rotation matrix from the Euler angles (y, x, z).
  5484. */
  5485. Matrix.RotationYawPitchRoll = function (yaw, pitch, roll) {
  5486. var result = new Matrix();
  5487. Matrix.RotationYawPitchRollToRef(yaw, pitch, roll, result);
  5488. return result;
  5489. };
  5490. /**
  5491. * Sets the passed matrix "result" as a rotation matrix from the Euler angles (y, x, z).
  5492. */
  5493. Matrix.RotationYawPitchRollToRef = function (yaw, pitch, roll, result) {
  5494. Quaternion.RotationYawPitchRollToRef(yaw, pitch, roll, this._tempQuaternion);
  5495. this._tempQuaternion.toRotationMatrix(result);
  5496. };
  5497. /**
  5498. * Returns a new Matrix as a scaling matrix from the passed floats (x, y, z).
  5499. */
  5500. Matrix.Scaling = function (x, y, z) {
  5501. var result = Matrix.Zero();
  5502. Matrix.ScalingToRef(x, y, z, result);
  5503. return result;
  5504. };
  5505. /**
  5506. * Sets the passed matrix "result" as a scaling matrix from the passed floats (x, y, z).
  5507. */
  5508. Matrix.ScalingToRef = function (x, y, z, result) {
  5509. result.m[0] = x;
  5510. result.m[1] = 0.0;
  5511. result.m[2] = 0.0;
  5512. result.m[3] = 0.0;
  5513. result.m[4] = 0.0;
  5514. result.m[5] = y;
  5515. result.m[6] = 0.0;
  5516. result.m[7] = 0.0;
  5517. result.m[8] = 0.0;
  5518. result.m[9] = 0.0;
  5519. result.m[10] = z;
  5520. result.m[11] = 0.0;
  5521. result.m[12] = 0.0;
  5522. result.m[13] = 0.0;
  5523. result.m[14] = 0.0;
  5524. result.m[15] = 1.0;
  5525. result._markAsUpdated();
  5526. };
  5527. /**
  5528. * Returns a new Matrix as a translation matrix from the passed floats (x, y, z).
  5529. */
  5530. Matrix.Translation = function (x, y, z) {
  5531. var result = Matrix.Identity();
  5532. Matrix.TranslationToRef(x, y, z, result);
  5533. return result;
  5534. };
  5535. /**
  5536. * Sets the passed matrix "result" as a translation matrix from the passed floats (x, y, z).
  5537. */
  5538. Matrix.TranslationToRef = function (x, y, z, result) {
  5539. 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);
  5540. };
  5541. /**
  5542. * Returns a new Matrix whose values are the interpolated values for "gradient" (float) between the ones of the matrices "startValue" and "endValue".
  5543. * @param startValue defines the start value
  5544. * @param endValue defines the end value
  5545. * @param gradient defines the gradient factor
  5546. * @returns the new matrix
  5547. */
  5548. Matrix.Lerp = function (startValue, endValue, gradient) {
  5549. var result = Matrix.Zero();
  5550. Matrix.LerpToRef(startValue, endValue, gradient, result);
  5551. return result;
  5552. };
  5553. /**
  5554. * Set the passed matrix "result" as the interpolated values for "gradient" (float) between the ones of the matrices "startValue" and "endValue".
  5555. * @param startValue defines the start value
  5556. * @param endValue defines the end value
  5557. * @param gradient defines the gradient factor
  5558. * @param result defines the Matrix object where to store data
  5559. */
  5560. Matrix.LerpToRef = function (startValue, endValue, gradient, result) {
  5561. for (var index = 0; index < 16; index++) {
  5562. result.m[index] = startValue.m[index] * (1.0 - gradient) + endValue.m[index] * gradient;
  5563. }
  5564. result._markAsUpdated();
  5565. };
  5566. /**
  5567. * Returns a new Matrix whose values are computed by :
  5568. * - decomposing the the "startValue" and "endValue" matrices into their respective scale, rotation and translation matrices,
  5569. * - interpolating for "gradient" (float) the values between each of these decomposed matrices between the start and the end,
  5570. * - recomposing a new matrix from these 3 interpolated scale, rotation and translation matrices.
  5571. */
  5572. Matrix.DecomposeLerp = function (startValue, endValue, gradient) {
  5573. var startScale = new Vector3(0, 0, 0);
  5574. var startRotation = new Quaternion();
  5575. var startTranslation = new Vector3(0, 0, 0);
  5576. startValue.decompose(startScale, startRotation, startTranslation);
  5577. var endScale = new Vector3(0, 0, 0);
  5578. var endRotation = new Quaternion();
  5579. var endTranslation = new Vector3(0, 0, 0);
  5580. endValue.decompose(endScale, endRotation, endTranslation);
  5581. var resultScale = Vector3.Lerp(startScale, endScale, gradient);
  5582. var resultRotation = Quaternion.Slerp(startRotation, endRotation, gradient);
  5583. var resultTranslation = Vector3.Lerp(startTranslation, endTranslation, gradient);
  5584. return Matrix.Compose(resultScale, resultRotation, resultTranslation);
  5585. };
  5586. /**
  5587. * Returns a new rotation Matrix used to rotate a mesh so as it looks at the target Vector3, from the eye Vector3, the UP vector3 being orientated like "up".
  5588. * This methods works for a Left-Handed system.
  5589. */
  5590. Matrix.LookAtLH = function (eye, target, up) {
  5591. var result = Matrix.Zero();
  5592. Matrix.LookAtLHToRef(eye, target, up, result);
  5593. return result;
  5594. };
  5595. /**
  5596. * Sets the passed "result" Matrix as a rotation matrix used to rotate a mesh so as it looks at the target Vector3, from the eye Vector3, the UP vector3 being orientated like "up".
  5597. * This methods works for a Left-Handed system.
  5598. */
  5599. Matrix.LookAtLHToRef = function (eye, target, up, result) {
  5600. // Z axis
  5601. target.subtractToRef(eye, this._zAxis);
  5602. this._zAxis.normalize();
  5603. // X axis
  5604. Vector3.CrossToRef(up, this._zAxis, this._xAxis);
  5605. if (this._xAxis.lengthSquared() === 0) {
  5606. this._xAxis.x = 1.0;
  5607. }
  5608. else {
  5609. this._xAxis.normalize();
  5610. }
  5611. // Y axis
  5612. Vector3.CrossToRef(this._zAxis, this._xAxis, this._yAxis);
  5613. this._yAxis.normalize();
  5614. // Eye angles
  5615. var ex = -Vector3.Dot(this._xAxis, eye);
  5616. var ey = -Vector3.Dot(this._yAxis, eye);
  5617. var ez = -Vector3.Dot(this._zAxis, eye);
  5618. 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);
  5619. };
  5620. /**
  5621. * Returns a new rotation Matrix used to rotate a mesh so as it looks at the target Vector3, from the eye Vector3, the UP vector3 being orientated like "up".
  5622. * This methods works for a Right-Handed system.
  5623. */
  5624. Matrix.LookAtRH = function (eye, target, up) {
  5625. var result = Matrix.Zero();
  5626. Matrix.LookAtRHToRef(eye, target, up, result);
  5627. return result;
  5628. };
  5629. /**
  5630. * Sets the passed "result" Matrix as a rotation matrix used to rotate a mesh so as it looks at the target Vector3, from the eye Vector3, the UP vector3 being orientated like "up".
  5631. * This methods works for a Left-Handed system.
  5632. */
  5633. Matrix.LookAtRHToRef = function (eye, target, up, result) {
  5634. // Z axis
  5635. eye.subtractToRef(target, this._zAxis);
  5636. this._zAxis.normalize();
  5637. // X axis
  5638. Vector3.CrossToRef(up, this._zAxis, this._xAxis);
  5639. if (this._xAxis.lengthSquared() === 0) {
  5640. this._xAxis.x = 1.0;
  5641. }
  5642. else {
  5643. this._xAxis.normalize();
  5644. }
  5645. // Y axis
  5646. Vector3.CrossToRef(this._zAxis, this._xAxis, this._yAxis);
  5647. this._yAxis.normalize();
  5648. // Eye angles
  5649. var ex = -Vector3.Dot(this._xAxis, eye);
  5650. var ey = -Vector3.Dot(this._yAxis, eye);
  5651. var ez = -Vector3.Dot(this._zAxis, eye);
  5652. 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);
  5653. };
  5654. /**
  5655. * Returns a new Matrix as a left-handed orthographic projection matrix computed from the passed floats : width and height of the projection plane, z near and far limits.
  5656. */
  5657. Matrix.OrthoLH = function (width, height, znear, zfar) {
  5658. var matrix = Matrix.Zero();
  5659. Matrix.OrthoLHToRef(width, height, znear, zfar, matrix);
  5660. return matrix;
  5661. };
  5662. /**
  5663. * Sets the passed matrix "result" as a left-handed orthographic projection matrix computed from the passed floats : width and height of the projection plane, z near and far limits.
  5664. */
  5665. Matrix.OrthoLHToRef = function (width, height, znear, zfar, result) {
  5666. var n = znear;
  5667. var f = zfar;
  5668. var a = 2.0 / width;
  5669. var b = 2.0 / height;
  5670. var c = 2.0 / (f - n);
  5671. var d = -(f + n) / (f - n);
  5672. 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);
  5673. };
  5674. /**
  5675. * Returns a new Matrix as a left-handed orthographic projection matrix computed from the passed floats : left, right, top and bottom being the coordinates of the projection plane, z near and far limits.
  5676. */
  5677. Matrix.OrthoOffCenterLH = function (left, right, bottom, top, znear, zfar) {
  5678. var matrix = Matrix.Zero();
  5679. Matrix.OrthoOffCenterLHToRef(left, right, bottom, top, znear, zfar, matrix);
  5680. return matrix;
  5681. };
  5682. /**
  5683. * Sets the passed matrix "result" as a left-handed orthographic projection matrix computed from the passed floats : left, right, top and bottom being the coordinates of the projection plane, z near and far limits.
  5684. */
  5685. Matrix.OrthoOffCenterLHToRef = function (left, right, bottom, top, znear, zfar, result) {
  5686. var n = znear;
  5687. var f = zfar;
  5688. var a = 2.0 / (right - left);
  5689. var b = 2.0 / (top - bottom);
  5690. var c = 2.0 / (f - n);
  5691. var d = -(f + n) / (f - n);
  5692. var i0 = (left + right) / (left - right);
  5693. var i1 = (top + bottom) / (bottom - top);
  5694. 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);
  5695. };
  5696. /**
  5697. * Returns a new Matrix as a right-handed orthographic projection matrix computed from the passed floats : left, right, top and bottom being the coordinates of the projection plane, z near and far limits.
  5698. */
  5699. Matrix.OrthoOffCenterRH = function (left, right, bottom, top, znear, zfar) {
  5700. var matrix = Matrix.Zero();
  5701. Matrix.OrthoOffCenterRHToRef(left, right, bottom, top, znear, zfar, matrix);
  5702. return matrix;
  5703. };
  5704. /**
  5705. * Sets the passed matrix "result" as a right-handed orthographic projection matrix computed from the passed floats : left, right, top and bottom being the coordinates of the projection plane, z near and far limits.
  5706. */
  5707. Matrix.OrthoOffCenterRHToRef = function (left, right, bottom, top, znear, zfar, result) {
  5708. Matrix.OrthoOffCenterLHToRef(left, right, bottom, top, znear, zfar, result);
  5709. result.m[10] *= -1.0;
  5710. };
  5711. /**
  5712. * Returns a new Matrix as a left-handed perspective projection matrix computed from the passed floats : width and height of the projection plane, z near and far limits.
  5713. */
  5714. Matrix.PerspectiveLH = function (width, height, znear, zfar) {
  5715. var matrix = Matrix.Zero();
  5716. var n = znear;
  5717. var f = zfar;
  5718. var a = 2.0 * n / width;
  5719. var b = 2.0 * n / height;
  5720. var c = (f + n) / (f - n);
  5721. var d = -2.0 * f * n / (f - n);
  5722. 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);
  5723. return matrix;
  5724. };
  5725. /**
  5726. * Returns a new Matrix as a left-handed perspective projection matrix computed from the passed floats : vertical angle of view (fov), width/height ratio (aspect), z near and far limits.
  5727. */
  5728. Matrix.PerspectiveFovLH = function (fov, aspect, znear, zfar) {
  5729. var matrix = Matrix.Zero();
  5730. Matrix.PerspectiveFovLHToRef(fov, aspect, znear, zfar, matrix);
  5731. return matrix;
  5732. };
  5733. /**
  5734. * Sets the passed matrix "result" as a left-handed perspective projection matrix computed from the passed floats : vertical angle of view (fov), width/height ratio (aspect), z near and far limits.
  5735. */
  5736. Matrix.PerspectiveFovLHToRef = function (fov, aspect, znear, zfar, result, isVerticalFovFixed) {
  5737. if (isVerticalFovFixed === void 0) { isVerticalFovFixed = true; }
  5738. var n = znear;
  5739. var f = zfar;
  5740. var t = 1.0 / (Math.tan(fov * 0.5));
  5741. var a = isVerticalFovFixed ? (t / aspect) : t;
  5742. var b = isVerticalFovFixed ? t : (t * aspect);
  5743. var c = (f + n) / (f - n);
  5744. var d = -2.0 * f * n / (f - n);
  5745. 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);
  5746. };
  5747. /**
  5748. * Returns a new Matrix as a right-handed perspective projection matrix computed from the passed floats : vertical angle of view (fov), width/height ratio (aspect), z near and far limits.
  5749. */
  5750. Matrix.PerspectiveFovRH = function (fov, aspect, znear, zfar) {
  5751. var matrix = Matrix.Zero();
  5752. Matrix.PerspectiveFovRHToRef(fov, aspect, znear, zfar, matrix);
  5753. return matrix;
  5754. };
  5755. /**
  5756. * Sets the passed matrix "result" as a right-handed perspective projection matrix computed from the passed floats : vertical angle of view (fov), width/height ratio (aspect), z near and far limits.
  5757. */
  5758. Matrix.PerspectiveFovRHToRef = function (fov, aspect, znear, zfar, result, isVerticalFovFixed) {
  5759. //alternatively this could be expressed as:
  5760. // m = PerspectiveFovLHToRef
  5761. // m[10] *= -1.0;
  5762. // m[11] *= -1.0;
  5763. if (isVerticalFovFixed === void 0) { isVerticalFovFixed = true; }
  5764. var n = znear;
  5765. var f = zfar;
  5766. var t = 1.0 / (Math.tan(fov * 0.5));
  5767. var a = isVerticalFovFixed ? (t / aspect) : t;
  5768. var b = isVerticalFovFixed ? t : (t * aspect);
  5769. var c = -(f + n) / (f - n);
  5770. var d = -2 * f * n / (f - n);
  5771. 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);
  5772. };
  5773. /**
  5774. * Sets the passed matrix "result" as a left-handed perspective projection matrix for WebVR computed from the passed floats : vertical angle of view (fov), width/height ratio (aspect), z near and far limits.
  5775. */
  5776. Matrix.PerspectiveFovWebVRToRef = function (fov, znear, zfar, result, rightHanded) {
  5777. if (rightHanded === void 0) { rightHanded = false; }
  5778. var rightHandedFactor = rightHanded ? -1 : 1;
  5779. var upTan = Math.tan(fov.upDegrees * Math.PI / 180.0);
  5780. var downTan = Math.tan(fov.downDegrees * Math.PI / 180.0);
  5781. var leftTan = Math.tan(fov.leftDegrees * Math.PI / 180.0);
  5782. var rightTan = Math.tan(fov.rightDegrees * Math.PI / 180.0);
  5783. var xScale = 2.0 / (leftTan + rightTan);
  5784. var yScale = 2.0 / (upTan + downTan);
  5785. result.m[0] = xScale;
  5786. result.m[1] = result.m[2] = result.m[3] = result.m[4] = 0.0;
  5787. result.m[5] = yScale;
  5788. result.m[6] = result.m[7] = 0.0;
  5789. result.m[8] = ((leftTan - rightTan) * xScale * 0.5); // * rightHandedFactor;
  5790. result.m[9] = -((upTan - downTan) * yScale * 0.5); // * rightHandedFactor;
  5791. //result.m[10] = -(znear + zfar) / (zfar - znear) * rightHandedFactor;
  5792. result.m[10] = -zfar / (znear - zfar);
  5793. result.m[11] = 1.0 * rightHandedFactor;
  5794. result.m[12] = result.m[13] = result.m[15] = 0.0;
  5795. result.m[14] = -(2.0 * zfar * znear) / (zfar - znear);
  5796. // result.m[14] = (znear * zfar) / (znear - zfar);
  5797. result._markAsUpdated();
  5798. };
  5799. /**
  5800. * Returns the final transformation matrix : world * view * projection * viewport
  5801. */
  5802. Matrix.GetFinalMatrix = function (viewport, world, view, projection, zmin, zmax) {
  5803. var cw = viewport.width;
  5804. var ch = viewport.height;
  5805. var cx = viewport.x;
  5806. var cy = viewport.y;
  5807. 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);
  5808. return world.multiply(view).multiply(projection).multiply(viewportMatrix);
  5809. };
  5810. /**
  5811. * Returns a new Float32Array array with 4 elements : the 2x2 matrix extracted from the passed Matrix.
  5812. */
  5813. Matrix.GetAsMatrix2x2 = function (matrix) {
  5814. return new Float32Array([
  5815. matrix.m[0], matrix.m[1],
  5816. matrix.m[4], matrix.m[5]
  5817. ]);
  5818. };
  5819. /**
  5820. * Returns a new Float32Array array with 9 elements : the 3x3 matrix extracted from the passed Matrix.
  5821. */
  5822. Matrix.GetAsMatrix3x3 = function (matrix) {
  5823. return new Float32Array([
  5824. matrix.m[0], matrix.m[1], matrix.m[2],
  5825. matrix.m[4], matrix.m[5], matrix.m[6],
  5826. matrix.m[8], matrix.m[9], matrix.m[10]
  5827. ]);
  5828. };
  5829. /**
  5830. * Compute the transpose of the passed Matrix.
  5831. * Returns a new Matrix.
  5832. */
  5833. Matrix.Transpose = function (matrix) {
  5834. var result = new Matrix();
  5835. Matrix.TransposeToRef(matrix, result);
  5836. return result;
  5837. };
  5838. /**
  5839. * Compute the transpose of the passed Matrix and store it in the result matrix.
  5840. */
  5841. Matrix.TransposeToRef = function (matrix, result) {
  5842. result.m[0] = matrix.m[0];
  5843. result.m[1] = matrix.m[4];
  5844. result.m[2] = matrix.m[8];
  5845. result.m[3] = matrix.m[12];
  5846. result.m[4] = matrix.m[1];
  5847. result.m[5] = matrix.m[5];
  5848. result.m[6] = matrix.m[9];
  5849. result.m[7] = matrix.m[13];
  5850. result.m[8] = matrix.m[2];
  5851. result.m[9] = matrix.m[6];
  5852. result.m[10] = matrix.m[10];
  5853. result.m[11] = matrix.m[14];
  5854. result.m[12] = matrix.m[3];
  5855. result.m[13] = matrix.m[7];
  5856. result.m[14] = matrix.m[11];
  5857. result.m[15] = matrix.m[15];
  5858. };
  5859. /**
  5860. * Returns a new Matrix as the reflection matrix across the passed plane.
  5861. */
  5862. Matrix.Reflection = function (plane) {
  5863. var matrix = new Matrix();
  5864. Matrix.ReflectionToRef(plane, matrix);
  5865. return matrix;
  5866. };
  5867. /**
  5868. * Sets the passed matrix "result" as the reflection matrix across the passed plane.
  5869. */
  5870. Matrix.ReflectionToRef = function (plane, result) {
  5871. plane.normalize();
  5872. var x = plane.normal.x;
  5873. var y = plane.normal.y;
  5874. var z = plane.normal.z;
  5875. var temp = -2 * x;
  5876. var temp2 = -2 * y;
  5877. var temp3 = -2 * z;
  5878. result.m[0] = (temp * x) + 1;
  5879. result.m[1] = temp2 * x;
  5880. result.m[2] = temp3 * x;
  5881. result.m[3] = 0.0;
  5882. result.m[4] = temp * y;
  5883. result.m[5] = (temp2 * y) + 1;
  5884. result.m[6] = temp3 * y;
  5885. result.m[7] = 0.0;
  5886. result.m[8] = temp * z;
  5887. result.m[9] = temp2 * z;
  5888. result.m[10] = (temp3 * z) + 1;
  5889. result.m[11] = 0.0;
  5890. result.m[12] = temp * plane.d;
  5891. result.m[13] = temp2 * plane.d;
  5892. result.m[14] = temp3 * plane.d;
  5893. result.m[15] = 1.0;
  5894. result._markAsUpdated();
  5895. };
  5896. /**
  5897. * Sets the passed matrix "mat" as a rotation matrix composed from the 3 passed left handed axis.
  5898. */
  5899. Matrix.FromXYZAxesToRef = function (xaxis, yaxis, zaxis, result) {
  5900. result.m[0] = xaxis.x;
  5901. result.m[1] = xaxis.y;
  5902. result.m[2] = xaxis.z;
  5903. result.m[3] = 0.0;
  5904. result.m[4] = yaxis.x;
  5905. result.m[5] = yaxis.y;
  5906. result.m[6] = yaxis.z;
  5907. result.m[7] = 0.0;
  5908. result.m[8] = zaxis.x;
  5909. result.m[9] = zaxis.y;
  5910. result.m[10] = zaxis.z;
  5911. result.m[11] = 0.0;
  5912. result.m[12] = 0.0;
  5913. result.m[13] = 0.0;
  5914. result.m[14] = 0.0;
  5915. result.m[15] = 1.0;
  5916. result._markAsUpdated();
  5917. };
  5918. /**
  5919. * Sets the passed matrix "result" as a rotation matrix according to the passed quaternion.
  5920. */
  5921. Matrix.FromQuaternionToRef = function (quat, result) {
  5922. var xx = quat.x * quat.x;
  5923. var yy = quat.y * quat.y;
  5924. var zz = quat.z * quat.z;
  5925. var xy = quat.x * quat.y;
  5926. var zw = quat.z * quat.w;
  5927. var zx = quat.z * quat.x;
  5928. var yw = quat.y * quat.w;
  5929. var yz = quat.y * quat.z;
  5930. var xw = quat.x * quat.w;
  5931. result.m[0] = 1.0 - (2.0 * (yy + zz));
  5932. result.m[1] = 2.0 * (xy + zw);
  5933. result.m[2] = 2.0 * (zx - yw);
  5934. result.m[3] = 0.0;
  5935. result.m[4] = 2.0 * (xy - zw);
  5936. result.m[5] = 1.0 - (2.0 * (zz + xx));
  5937. result.m[6] = 2.0 * (yz + xw);
  5938. result.m[7] = 0.0;
  5939. result.m[8] = 2.0 * (zx + yw);
  5940. result.m[9] = 2.0 * (yz - xw);
  5941. result.m[10] = 1.0 - (2.0 * (yy + xx));
  5942. result.m[11] = 0.0;
  5943. result.m[12] = 0.0;
  5944. result.m[13] = 0.0;
  5945. result.m[14] = 0.0;
  5946. result.m[15] = 1.0;
  5947. result._markAsUpdated();
  5948. };
  5949. Matrix._tempQuaternion = new Quaternion();
  5950. Matrix._xAxis = Vector3.Zero();
  5951. Matrix._yAxis = Vector3.Zero();
  5952. Matrix._zAxis = Vector3.Zero();
  5953. Matrix._updateFlagSeed = 0;
  5954. Matrix._identityReadOnly = Matrix.Identity();
  5955. return Matrix;
  5956. }());
  5957. BABYLON.Matrix = Matrix;
  5958. var Plane = /** @class */ (function () {
  5959. /**
  5960. * Creates a Plane object according to the passed floats a, b, c, d and the plane equation : ax + by + cz + d = 0
  5961. */
  5962. function Plane(a, b, c, d) {
  5963. this.normal = new Vector3(a, b, c);
  5964. this.d = d;
  5965. }
  5966. /**
  5967. * Returns the plane coordinates as a new array of 4 elements [a, b, c, d].
  5968. */
  5969. Plane.prototype.asArray = function () {
  5970. return [this.normal.x, this.normal.y, this.normal.z, this.d];
  5971. };
  5972. // Methods
  5973. /**
  5974. * Returns a new plane copied from the current Plane.
  5975. */
  5976. Plane.prototype.clone = function () {
  5977. return new Plane(this.normal.x, this.normal.y, this.normal.z, this.d);
  5978. };
  5979. /**
  5980. * Returns the string "Plane".
  5981. */
  5982. Plane.prototype.getClassName = function () {
  5983. return "Plane";
  5984. };
  5985. /**
  5986. * Returns the Plane hash code.
  5987. */
  5988. Plane.prototype.getHashCode = function () {
  5989. var hash = this.normal.getHashCode();
  5990. hash = (hash * 397) ^ (this.d || 0);
  5991. return hash;
  5992. };
  5993. /**
  5994. * Normalize the current Plane in place.
  5995. * Returns the updated Plane.
  5996. */
  5997. Plane.prototype.normalize = function () {
  5998. var norm = (Math.sqrt((this.normal.x * this.normal.x) + (this.normal.y * this.normal.y) + (this.normal.z * this.normal.z)));
  5999. var magnitude = 0.0;
  6000. if (norm !== 0) {
  6001. magnitude = 1.0 / norm;
  6002. }
  6003. this.normal.x *= magnitude;
  6004. this.normal.y *= magnitude;
  6005. this.normal.z *= magnitude;
  6006. this.d *= magnitude;
  6007. return this;
  6008. };
  6009. /**
  6010. * Returns a new Plane as the result of the transformation of the current Plane by the passed matrix.
  6011. */
  6012. Plane.prototype.transform = function (transformation) {
  6013. var transposedMatrix = Matrix.Transpose(transformation);
  6014. var x = this.normal.x;
  6015. var y = this.normal.y;
  6016. var z = this.normal.z;
  6017. var d = this.d;
  6018. var normalX = (((x * transposedMatrix.m[0]) + (y * transposedMatrix.m[1])) + (z * transposedMatrix.m[2])) + (d * transposedMatrix.m[3]);
  6019. var normalY = (((x * transposedMatrix.m[4]) + (y * transposedMatrix.m[5])) + (z * transposedMatrix.m[6])) + (d * transposedMatrix.m[7]);
  6020. var normalZ = (((x * transposedMatrix.m[8]) + (y * transposedMatrix.m[9])) + (z * transposedMatrix.m[10])) + (d * transposedMatrix.m[11]);
  6021. var finalD = (((x * transposedMatrix.m[12]) + (y * transposedMatrix.m[13])) + (z * transposedMatrix.m[14])) + (d * transposedMatrix.m[15]);
  6022. return new Plane(normalX, normalY, normalZ, finalD);
  6023. };
  6024. /**
  6025. * Returns the dot product (float) of the point coordinates and the plane normal.
  6026. */
  6027. Plane.prototype.dotCoordinate = function (point) {
  6028. return ((((this.normal.x * point.x) + (this.normal.y * point.y)) + (this.normal.z * point.z)) + this.d);
  6029. };
  6030. /**
  6031. * Updates the current Plane from the plane defined by the three passed points.
  6032. * Returns the updated Plane.
  6033. */
  6034. Plane.prototype.copyFromPoints = function (point1, point2, point3) {
  6035. var x1 = point2.x - point1.x;
  6036. var y1 = point2.y - point1.y;
  6037. var z1 = point2.z - point1.z;
  6038. var x2 = point3.x - point1.x;
  6039. var y2 = point3.y - point1.y;
  6040. var z2 = point3.z - point1.z;
  6041. var yz = (y1 * z2) - (z1 * y2);
  6042. var xz = (z1 * x2) - (x1 * z2);
  6043. var xy = (x1 * y2) - (y1 * x2);
  6044. var pyth = (Math.sqrt((yz * yz) + (xz * xz) + (xy * xy)));
  6045. var invPyth;
  6046. if (pyth !== 0) {
  6047. invPyth = 1.0 / pyth;
  6048. }
  6049. else {
  6050. invPyth = 0.0;
  6051. }
  6052. this.normal.x = yz * invPyth;
  6053. this.normal.y = xz * invPyth;
  6054. this.normal.z = xy * invPyth;
  6055. this.d = -((this.normal.x * point1.x) + (this.normal.y * point1.y) + (this.normal.z * point1.z));
  6056. return this;
  6057. };
  6058. /**
  6059. * Boolean : True is the vector "direction" is the same side than the plane normal.
  6060. */
  6061. Plane.prototype.isFrontFacingTo = function (direction, epsilon) {
  6062. var dot = Vector3.Dot(this.normal, direction);
  6063. return (dot <= epsilon);
  6064. };
  6065. /**
  6066. * Returns the signed distance (float) from the passed point to the Plane.
  6067. */
  6068. Plane.prototype.signedDistanceTo = function (point) {
  6069. return Vector3.Dot(point, this.normal) + this.d;
  6070. };
  6071. // Statics
  6072. /**
  6073. * Returns a new Plane from the passed array.
  6074. */
  6075. Plane.FromArray = function (array) {
  6076. return new Plane(array[0], array[1], array[2], array[3]);
  6077. };
  6078. /**
  6079. * Returns a new Plane defined by the three passed points.
  6080. */
  6081. Plane.FromPoints = function (point1, point2, point3) {
  6082. var result = new Plane(0.0, 0.0, 0.0, 0.0);
  6083. result.copyFromPoints(point1, point2, point3);
  6084. return result;
  6085. };
  6086. /**
  6087. * Returns a new Plane the normal vector to this plane at the passed origin point.
  6088. * Note : the vector "normal" is updated because normalized.
  6089. */
  6090. Plane.FromPositionAndNormal = function (origin, normal) {
  6091. var result = new Plane(0.0, 0.0, 0.0, 0.0);
  6092. normal.normalize();
  6093. result.normal = normal;
  6094. result.d = -(normal.x * origin.x + normal.y * origin.y + normal.z * origin.z);
  6095. return result;
  6096. };
  6097. /**
  6098. * Returns the signed distance between the plane defined by the normal vector at the "origin"" point and the passed other point.
  6099. */
  6100. Plane.SignedDistanceToPlaneFromPositionAndNormal = function (origin, normal, point) {
  6101. var d = -(normal.x * origin.x + normal.y * origin.y + normal.z * origin.z);
  6102. return Vector3.Dot(point, normal) + d;
  6103. };
  6104. return Plane;
  6105. }());
  6106. BABYLON.Plane = Plane;
  6107. var Viewport = /** @class */ (function () {
  6108. /**
  6109. * Creates a Viewport object located at (x, y) and sized (width, height).
  6110. */
  6111. function Viewport(x, y, width, height) {
  6112. this.x = x;
  6113. this.y = y;
  6114. this.width = width;
  6115. this.height = height;
  6116. }
  6117. Viewport.prototype.toGlobal = function (renderWidthOrEngine, renderHeight) {
  6118. if (renderWidthOrEngine.getRenderWidth) {
  6119. var engine = renderWidthOrEngine;
  6120. return this.toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  6121. }
  6122. var renderWidth = renderWidthOrEngine;
  6123. return new Viewport(this.x * renderWidth, this.y * renderHeight, this.width * renderWidth, this.height * renderHeight);
  6124. };
  6125. /**
  6126. * Returns a new Viewport copied from the current one.
  6127. */
  6128. Viewport.prototype.clone = function () {
  6129. return new Viewport(this.x, this.y, this.width, this.height);
  6130. };
  6131. return Viewport;
  6132. }());
  6133. BABYLON.Viewport = Viewport;
  6134. var Frustum = /** @class */ (function () {
  6135. function Frustum() {
  6136. }
  6137. /**
  6138. * Returns a new array of 6 Frustum planes computed by the passed transformation matrix.
  6139. */
  6140. Frustum.GetPlanes = function (transform) {
  6141. var frustumPlanes = [];
  6142. for (var index = 0; index < 6; index++) {
  6143. frustumPlanes.push(new Plane(0.0, 0.0, 0.0, 0.0));
  6144. }
  6145. Frustum.GetPlanesToRef(transform, frustumPlanes);
  6146. return frustumPlanes;
  6147. };
  6148. Frustum.GetNearPlaneToRef = function (transform, frustumPlane) {
  6149. frustumPlane.normal.x = transform.m[3] + transform.m[2];
  6150. frustumPlane.normal.y = transform.m[7] + transform.m[6];
  6151. frustumPlane.normal.z = transform.m[11] + transform.m[10];
  6152. frustumPlane.d = transform.m[15] + transform.m[14];
  6153. frustumPlane.normalize();
  6154. };
  6155. Frustum.GetFarPlaneToRef = function (transform, frustumPlane) {
  6156. frustumPlane.normal.x = transform.m[3] - transform.m[2];
  6157. frustumPlane.normal.y = transform.m[7] - transform.m[6];
  6158. frustumPlane.normal.z = transform.m[11] - transform.m[10];
  6159. frustumPlane.d = transform.m[15] - transform.m[14];
  6160. frustumPlane.normalize();
  6161. };
  6162. Frustum.GetLeftPlaneToRef = function (transform, frustumPlane) {
  6163. frustumPlane.normal.x = transform.m[3] + transform.m[0];
  6164. frustumPlane.normal.y = transform.m[7] + transform.m[4];
  6165. frustumPlane.normal.z = transform.m[11] + transform.m[8];
  6166. frustumPlane.d = transform.m[15] + transform.m[12];
  6167. frustumPlane.normalize();
  6168. };
  6169. Frustum.GetRightPlaneToRef = function (transform, frustumPlane) {
  6170. frustumPlane.normal.x = transform.m[3] - transform.m[0];
  6171. frustumPlane.normal.y = transform.m[7] - transform.m[4];
  6172. frustumPlane.normal.z = transform.m[11] - transform.m[8];
  6173. frustumPlane.d = transform.m[15] - transform.m[12];
  6174. frustumPlane.normalize();
  6175. };
  6176. Frustum.GetTopPlaneToRef = function (transform, frustumPlane) {
  6177. frustumPlane.normal.x = transform.m[3] - transform.m[1];
  6178. frustumPlane.normal.y = transform.m[7] - transform.m[5];
  6179. frustumPlane.normal.z = transform.m[11] - transform.m[9];
  6180. frustumPlane.d = transform.m[15] - transform.m[13];
  6181. frustumPlane.normalize();
  6182. };
  6183. Frustum.GetBottomPlaneToRef = function (transform, frustumPlane) {
  6184. frustumPlane.normal.x = transform.m[3] + transform.m[1];
  6185. frustumPlane.normal.y = transform.m[7] + transform.m[5];
  6186. frustumPlane.normal.z = transform.m[11] + transform.m[9];
  6187. frustumPlane.d = transform.m[15] + transform.m[13];
  6188. frustumPlane.normalize();
  6189. };
  6190. /**
  6191. * Sets the passed array "frustumPlanes" with the 6 Frustum planes computed by the passed transformation matrix.
  6192. */
  6193. Frustum.GetPlanesToRef = function (transform, frustumPlanes) {
  6194. // Near
  6195. Frustum.GetNearPlaneToRef(transform, frustumPlanes[0]);
  6196. // Far
  6197. Frustum.GetFarPlaneToRef(transform, frustumPlanes[1]);
  6198. // Left
  6199. Frustum.GetLeftPlaneToRef(transform, frustumPlanes[2]);
  6200. // Right
  6201. Frustum.GetRightPlaneToRef(transform, frustumPlanes[3]);
  6202. // Top
  6203. Frustum.GetTopPlaneToRef(transform, frustumPlanes[4]);
  6204. // Bottom
  6205. Frustum.GetBottomPlaneToRef(transform, frustumPlanes[5]);
  6206. };
  6207. return Frustum;
  6208. }());
  6209. BABYLON.Frustum = Frustum;
  6210. var Space;
  6211. (function (Space) {
  6212. Space[Space["LOCAL"] = 0] = "LOCAL";
  6213. Space[Space["WORLD"] = 1] = "WORLD";
  6214. Space[Space["BONE"] = 2] = "BONE";
  6215. })(Space = BABYLON.Space || (BABYLON.Space = {}));
  6216. var Axis = /** @class */ (function () {
  6217. function Axis() {
  6218. }
  6219. Axis.X = new Vector3(1.0, 0.0, 0.0);
  6220. Axis.Y = new Vector3(0.0, 1.0, 0.0);
  6221. Axis.Z = new Vector3(0.0, 0.0, 1.0);
  6222. return Axis;
  6223. }());
  6224. BABYLON.Axis = Axis;
  6225. ;
  6226. var BezierCurve = /** @class */ (function () {
  6227. function BezierCurve() {
  6228. }
  6229. /**
  6230. * Returns the cubic Bezier interpolated value (float) at "t" (float) from the passed x1, y1, x2, y2 floats.
  6231. */
  6232. BezierCurve.interpolate = function (t, x1, y1, x2, y2) {
  6233. // Extract X (which is equal to time here)
  6234. var f0 = 1 - 3 * x2 + 3 * x1;
  6235. var f1 = 3 * x2 - 6 * x1;
  6236. var f2 = 3 * x1;
  6237. var refinedT = t;
  6238. for (var i = 0; i < 5; i++) {
  6239. var refinedT2 = refinedT * refinedT;
  6240. var refinedT3 = refinedT2 * refinedT;
  6241. var x = f0 * refinedT3 + f1 * refinedT2 + f2 * refinedT;
  6242. var slope = 1.0 / (3.0 * f0 * refinedT2 + 2.0 * f1 * refinedT + f2);
  6243. refinedT -= (x - t) * slope;
  6244. refinedT = Math.min(1, Math.max(0, refinedT));
  6245. }
  6246. // Resolve cubic bezier for the given x
  6247. return 3 * Math.pow(1 - refinedT, 2) * refinedT * y1 +
  6248. 3 * (1 - refinedT) * Math.pow(refinedT, 2) * y2 +
  6249. Math.pow(refinedT, 3);
  6250. };
  6251. return BezierCurve;
  6252. }());
  6253. BABYLON.BezierCurve = BezierCurve;
  6254. var Orientation;
  6255. (function (Orientation) {
  6256. Orientation[Orientation["CW"] = 0] = "CW";
  6257. Orientation[Orientation["CCW"] = 1] = "CCW";
  6258. })(Orientation = BABYLON.Orientation || (BABYLON.Orientation = {}));
  6259. var Angle = /** @class */ (function () {
  6260. /**
  6261. * Creates an Angle object of "radians" radians (float).
  6262. */
  6263. function Angle(radians) {
  6264. var _this = this;
  6265. /**
  6266. * Returns the Angle value in degrees (float).
  6267. */
  6268. this.degrees = function () { return _this._radians * 180.0 / Math.PI; };
  6269. /**
  6270. * Returns the Angle value in radians (float).
  6271. */
  6272. this.radians = function () { return _this._radians; };
  6273. this._radians = radians;
  6274. if (this._radians < 0.0)
  6275. this._radians += (2.0 * Math.PI);
  6276. }
  6277. /**
  6278. * Returns a new Angle object valued with the angle value in radians between the two passed vectors.
  6279. */
  6280. Angle.BetweenTwoPoints = function (a, b) {
  6281. var delta = b.subtract(a);
  6282. var theta = Math.atan2(delta.y, delta.x);
  6283. return new Angle(theta);
  6284. };
  6285. /**
  6286. * Returns a new Angle object from the passed float in radians.
  6287. */
  6288. Angle.FromRadians = function (radians) {
  6289. return new Angle(radians);
  6290. };
  6291. /**
  6292. * Returns a new Angle object from the passed float in degrees.
  6293. */
  6294. Angle.FromDegrees = function (degrees) {
  6295. return new Angle(degrees * Math.PI / 180.0);
  6296. };
  6297. return Angle;
  6298. }());
  6299. BABYLON.Angle = Angle;
  6300. var Arc2 = /** @class */ (function () {
  6301. /**
  6302. * Creates an Arc object from the three passed points : start, middle and end.
  6303. */
  6304. function Arc2(startPoint, midPoint, endPoint) {
  6305. this.startPoint = startPoint;
  6306. this.midPoint = midPoint;
  6307. this.endPoint = endPoint;
  6308. var temp = Math.pow(midPoint.x, 2) + Math.pow(midPoint.y, 2);
  6309. var startToMid = (Math.pow(startPoint.x, 2) + Math.pow(startPoint.y, 2) - temp) / 2.;
  6310. var midToEnd = (temp - Math.pow(endPoint.x, 2) - Math.pow(endPoint.y, 2)) / 2.;
  6311. var det = (startPoint.x - midPoint.x) * (midPoint.y - endPoint.y) - (midPoint.x - endPoint.x) * (startPoint.y - midPoint.y);
  6312. 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);
  6313. this.radius = this.centerPoint.subtract(this.startPoint).length();
  6314. this.startAngle = Angle.BetweenTwoPoints(this.centerPoint, this.startPoint);
  6315. var a1 = this.startAngle.degrees();
  6316. var a2 = Angle.BetweenTwoPoints(this.centerPoint, this.midPoint).degrees();
  6317. var a3 = Angle.BetweenTwoPoints(this.centerPoint, this.endPoint).degrees();
  6318. // angles correction
  6319. if (a2 - a1 > +180.0)
  6320. a2 -= 360.0;
  6321. if (a2 - a1 < -180.0)
  6322. a2 += 360.0;
  6323. if (a3 - a2 > +180.0)
  6324. a3 -= 360.0;
  6325. if (a3 - a2 < -180.0)
  6326. a3 += 360.0;
  6327. this.orientation = (a2 - a1) < 0 ? Orientation.CW : Orientation.CCW;
  6328. this.angle = Angle.FromDegrees(this.orientation === Orientation.CW ? a1 - a3 : a3 - a1);
  6329. }
  6330. return Arc2;
  6331. }());
  6332. BABYLON.Arc2 = Arc2;
  6333. var Path2 = /** @class */ (function () {
  6334. /**
  6335. * Creates a Path2 object from the starting 2D coordinates x and y.
  6336. */
  6337. function Path2(x, y) {
  6338. this._points = new Array();
  6339. this._length = 0.0;
  6340. this.closed = false;
  6341. this._points.push(new Vector2(x, y));
  6342. }
  6343. /**
  6344. * Adds a new segment until the passed coordinates (x, y) to the current Path2.
  6345. * Returns the updated Path2.
  6346. */
  6347. Path2.prototype.addLineTo = function (x, y) {
  6348. if (this.closed) {
  6349. return this;
  6350. }
  6351. var newPoint = new Vector2(x, y);
  6352. var previousPoint = this._points[this._points.length - 1];
  6353. this._points.push(newPoint);
  6354. this._length += newPoint.subtract(previousPoint).length();
  6355. return this;
  6356. };
  6357. /**
  6358. * 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.
  6359. * Returns the updated Path2.
  6360. */
  6361. Path2.prototype.addArcTo = function (midX, midY, endX, endY, numberOfSegments) {
  6362. if (numberOfSegments === void 0) { numberOfSegments = 36; }
  6363. if (this.closed) {
  6364. return this;
  6365. }
  6366. var startPoint = this._points[this._points.length - 1];
  6367. var midPoint = new Vector2(midX, midY);
  6368. var endPoint = new Vector2(endX, endY);
  6369. var arc = new Arc2(startPoint, midPoint, endPoint);
  6370. var increment = arc.angle.radians() / numberOfSegments;
  6371. if (arc.orientation === Orientation.CW)
  6372. increment *= -1;
  6373. var currentAngle = arc.startAngle.radians() + increment;
  6374. for (var i = 0; i < numberOfSegments; i++) {
  6375. var x = Math.cos(currentAngle) * arc.radius + arc.centerPoint.x;
  6376. var y = Math.sin(currentAngle) * arc.radius + arc.centerPoint.y;
  6377. this.addLineTo(x, y);
  6378. currentAngle += increment;
  6379. }
  6380. return this;
  6381. };
  6382. /**
  6383. * Closes the Path2.
  6384. * Returns the Path2.
  6385. */
  6386. Path2.prototype.close = function () {
  6387. this.closed = true;
  6388. return this;
  6389. };
  6390. /**
  6391. * Returns the Path2 total length (float).
  6392. */
  6393. Path2.prototype.length = function () {
  6394. var result = this._length;
  6395. if (!this.closed) {
  6396. var lastPoint = this._points[this._points.length - 1];
  6397. var firstPoint = this._points[0];
  6398. result += (firstPoint.subtract(lastPoint).length());
  6399. }
  6400. return result;
  6401. };
  6402. /**
  6403. * Returns the Path2 internal array of points.
  6404. */
  6405. Path2.prototype.getPoints = function () {
  6406. return this._points;
  6407. };
  6408. /**
  6409. * Returns a new Vector2 located at a percentage of the Path2 total length on this path.
  6410. */
  6411. Path2.prototype.getPointAtLengthPosition = function (normalizedLengthPosition) {
  6412. if (normalizedLengthPosition < 0 || normalizedLengthPosition > 1) {
  6413. return Vector2.Zero();
  6414. }
  6415. var lengthPosition = normalizedLengthPosition * this.length();
  6416. var previousOffset = 0;
  6417. for (var i = 0; i < this._points.length; i++) {
  6418. var j = (i + 1) % this._points.length;
  6419. var a = this._points[i];
  6420. var b = this._points[j];
  6421. var bToA = b.subtract(a);
  6422. var nextOffset = (bToA.length() + previousOffset);
  6423. if (lengthPosition >= previousOffset && lengthPosition <= nextOffset) {
  6424. var dir = bToA.normalize();
  6425. var localOffset = lengthPosition - previousOffset;
  6426. return new Vector2(a.x + (dir.x * localOffset), a.y + (dir.y * localOffset));
  6427. }
  6428. previousOffset = nextOffset;
  6429. }
  6430. return Vector2.Zero();
  6431. };
  6432. /**
  6433. * Returns a new Path2 starting at the coordinates (x, y).
  6434. */
  6435. Path2.StartingAt = function (x, y) {
  6436. return new Path2(x, y);
  6437. };
  6438. return Path2;
  6439. }());
  6440. BABYLON.Path2 = Path2;
  6441. var Path3D = /** @class */ (function () {
  6442. /**
  6443. * new Path3D(path, normal, raw)
  6444. * Creates a Path3D. A Path3D is a logical math object, so not a mesh.
  6445. * please read the description in the tutorial : http://doc.babylonjs.com/tutorials/How_to_use_Path3D
  6446. * path : an array of Vector3, the curve axis of the Path3D
  6447. * normal (optional) : Vector3, the first wanted normal to the curve. Ex (0, 1, 0) for a vertical normal.
  6448. * raw (optional, default false) : boolean, if true the returned Path3D isn't normalized. Useful to depict path acceleration or speed.
  6449. */
  6450. function Path3D(path, firstNormal, raw) {
  6451. if (firstNormal === void 0) { firstNormal = null; }
  6452. this.path = path;
  6453. this._curve = new Array();
  6454. this._distances = new Array();
  6455. this._tangents = new Array();
  6456. this._normals = new Array();
  6457. this._binormals = new Array();
  6458. for (var p = 0; p < path.length; p++) {
  6459. this._curve[p] = path[p].clone(); // hard copy
  6460. }
  6461. this._raw = raw || false;
  6462. this._compute(firstNormal);
  6463. }
  6464. /**
  6465. * Returns the Path3D array of successive Vector3 designing its curve.
  6466. */
  6467. Path3D.prototype.getCurve = function () {
  6468. return this._curve;
  6469. };
  6470. /**
  6471. * Returns an array populated with tangent vectors on each Path3D curve point.
  6472. */
  6473. Path3D.prototype.getTangents = function () {
  6474. return this._tangents;
  6475. };
  6476. /**
  6477. * Returns an array populated with normal vectors on each Path3D curve point.
  6478. */
  6479. Path3D.prototype.getNormals = function () {
  6480. return this._normals;
  6481. };
  6482. /**
  6483. * Returns an array populated with binormal vectors on each Path3D curve point.
  6484. */
  6485. Path3D.prototype.getBinormals = function () {
  6486. return this._binormals;
  6487. };
  6488. /**
  6489. * Returns an array populated with distances (float) of the i-th point from the first curve point.
  6490. */
  6491. Path3D.prototype.getDistances = function () {
  6492. return this._distances;
  6493. };
  6494. /**
  6495. * Forces the Path3D tangent, normal, binormal and distance recomputation.
  6496. * Returns the same object updated.
  6497. */
  6498. Path3D.prototype.update = function (path, firstNormal) {
  6499. if (firstNormal === void 0) { firstNormal = null; }
  6500. for (var p = 0; p < path.length; p++) {
  6501. this._curve[p].x = path[p].x;
  6502. this._curve[p].y = path[p].y;
  6503. this._curve[p].z = path[p].z;
  6504. }
  6505. this._compute(firstNormal);
  6506. return this;
  6507. };
  6508. // private function compute() : computes tangents, normals and binormals
  6509. Path3D.prototype._compute = function (firstNormal) {
  6510. var l = this._curve.length;
  6511. // first and last tangents
  6512. this._tangents[0] = this._getFirstNonNullVector(0);
  6513. if (!this._raw) {
  6514. this._tangents[0].normalize();
  6515. }
  6516. this._tangents[l - 1] = this._curve[l - 1].subtract(this._curve[l - 2]);
  6517. if (!this._raw) {
  6518. this._tangents[l - 1].normalize();
  6519. }
  6520. // normals and binormals at first point : arbitrary vector with _normalVector()
  6521. var tg0 = this._tangents[0];
  6522. var pp0 = this._normalVector(this._curve[0], tg0, firstNormal);
  6523. this._normals[0] = pp0;
  6524. if (!this._raw) {
  6525. this._normals[0].normalize();
  6526. }
  6527. this._binormals[0] = Vector3.Cross(tg0, this._normals[0]);
  6528. if (!this._raw) {
  6529. this._binormals[0].normalize();
  6530. }
  6531. this._distances[0] = 0.0;
  6532. // normals and binormals : next points
  6533. var prev; // previous vector (segment)
  6534. var cur; // current vector (segment)
  6535. var curTang; // current tangent
  6536. // previous normal
  6537. var prevBinor; // previous binormal
  6538. for (var i = 1; i < l; i++) {
  6539. // tangents
  6540. prev = this._getLastNonNullVector(i);
  6541. if (i < l - 1) {
  6542. cur = this._getFirstNonNullVector(i);
  6543. this._tangents[i] = prev.add(cur);
  6544. this._tangents[i].normalize();
  6545. }
  6546. this._distances[i] = this._distances[i - 1] + prev.length();
  6547. // normals and binormals
  6548. // http://www.cs.cmu.edu/afs/andrew/scs/cs/15-462/web/old/asst2camera.html
  6549. curTang = this._tangents[i];
  6550. prevBinor = this._binormals[i - 1];
  6551. this._normals[i] = Vector3.Cross(prevBinor, curTang);
  6552. if (!this._raw) {
  6553. this._normals[i].normalize();
  6554. }
  6555. this._binormals[i] = Vector3.Cross(curTang, this._normals[i]);
  6556. if (!this._raw) {
  6557. this._binormals[i].normalize();
  6558. }
  6559. }
  6560. };
  6561. // private function getFirstNonNullVector(index)
  6562. // returns the first non null vector from index : curve[index + N].subtract(curve[index])
  6563. Path3D.prototype._getFirstNonNullVector = function (index) {
  6564. var i = 1;
  6565. var nNVector = this._curve[index + i].subtract(this._curve[index]);
  6566. while (nNVector.length() === 0 && index + i + 1 < this._curve.length) {
  6567. i++;
  6568. nNVector = this._curve[index + i].subtract(this._curve[index]);
  6569. }
  6570. return nNVector;
  6571. };
  6572. // private function getLastNonNullVector(index)
  6573. // returns the last non null vector from index : curve[index].subtract(curve[index - N])
  6574. Path3D.prototype._getLastNonNullVector = function (index) {
  6575. var i = 1;
  6576. var nLVector = this._curve[index].subtract(this._curve[index - i]);
  6577. while (nLVector.length() === 0 && index > i + 1) {
  6578. i++;
  6579. nLVector = this._curve[index].subtract(this._curve[index - i]);
  6580. }
  6581. return nLVector;
  6582. };
  6583. // private function normalVector(v0, vt, va) :
  6584. // returns an arbitrary point in the plane defined by the point v0 and the vector vt orthogonal to this plane
  6585. // if va is passed, it returns the va projection on the plane orthogonal to vt at the point v0
  6586. Path3D.prototype._normalVector = function (v0, vt, va) {
  6587. var normal0;
  6588. var tgl = vt.length();
  6589. if (tgl === 0.0) {
  6590. tgl = 1.0;
  6591. }
  6592. if (va === undefined || va === null) {
  6593. var point;
  6594. if (!BABYLON.Scalar.WithinEpsilon(Math.abs(vt.y) / tgl, 1.0, BABYLON.Epsilon)) {
  6595. point = new Vector3(0.0, -1.0, 0.0);
  6596. }
  6597. else if (!BABYLON.Scalar.WithinEpsilon(Math.abs(vt.x) / tgl, 1.0, BABYLON.Epsilon)) {
  6598. point = new Vector3(1.0, 0.0, 0.0);
  6599. }
  6600. else if (!BABYLON.Scalar.WithinEpsilon(Math.abs(vt.z) / tgl, 1.0, BABYLON.Epsilon)) {
  6601. point = new Vector3(0.0, 0.0, 1.0);
  6602. }
  6603. else {
  6604. point = Vector3.Zero();
  6605. }
  6606. normal0 = Vector3.Cross(vt, point);
  6607. }
  6608. else {
  6609. normal0 = Vector3.Cross(vt, va);
  6610. Vector3.CrossToRef(normal0, vt, normal0);
  6611. }
  6612. normal0.normalize();
  6613. return normal0;
  6614. };
  6615. return Path3D;
  6616. }());
  6617. BABYLON.Path3D = Path3D;
  6618. var Curve3 = /** @class */ (function () {
  6619. /**
  6620. * A Curve3 object is a logical object, so not a mesh, to handle curves in the 3D geometric space.
  6621. * A Curve3 is designed from a series of successive Vector3.
  6622. * Tuto : http://doc.babylonjs.com/tutorials/How_to_use_Curve3#curve3-object
  6623. */
  6624. function Curve3(points) {
  6625. this._length = 0.0;
  6626. this._points = points;
  6627. this._length = this._computeLength(points);
  6628. }
  6629. /**
  6630. * Returns a Curve3 object along a Quadratic Bezier curve : http://doc.babylonjs.com/tutorials/How_to_use_Curve3#quadratic-bezier-curve
  6631. * @param v0 (Vector3) the origin point of the Quadratic Bezier
  6632. * @param v1 (Vector3) the control point
  6633. * @param v2 (Vector3) the end point of the Quadratic Bezier
  6634. * @param nbPoints (integer) the wanted number of points in the curve
  6635. */
  6636. Curve3.CreateQuadraticBezier = function (v0, v1, v2, nbPoints) {
  6637. nbPoints = nbPoints > 2 ? nbPoints : 3;
  6638. var bez = new Array();
  6639. var equation = function (t, val0, val1, val2) {
  6640. var res = (1.0 - t) * (1.0 - t) * val0 + 2.0 * t * (1.0 - t) * val1 + t * t * val2;
  6641. return res;
  6642. };
  6643. for (var i = 0; i <= nbPoints; i++) {
  6644. 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)));
  6645. }
  6646. return new Curve3(bez);
  6647. };
  6648. /**
  6649. * Returns a Curve3 object along a Cubic Bezier curve : http://doc.babylonjs.com/tutorials/How_to_use_Curve3#cubic-bezier-curve
  6650. * @param v0 (Vector3) the origin point of the Cubic Bezier
  6651. * @param v1 (Vector3) the first control point
  6652. * @param v2 (Vector3) the second control point
  6653. * @param v3 (Vector3) the end point of the Cubic Bezier
  6654. * @param nbPoints (integer) the wanted number of points in the curve
  6655. */
  6656. Curve3.CreateCubicBezier = function (v0, v1, v2, v3, nbPoints) {
  6657. nbPoints = nbPoints > 3 ? nbPoints : 4;
  6658. var bez = new Array();
  6659. var equation = function (t, val0, val1, val2, val3) {
  6660. 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;
  6661. return res;
  6662. };
  6663. for (var i = 0; i <= nbPoints; i++) {
  6664. 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)));
  6665. }
  6666. return new Curve3(bez);
  6667. };
  6668. /**
  6669. * Returns a Curve3 object along a Hermite Spline curve : http://doc.babylonjs.com/tutorials/How_to_use_Curve3#hermite-spline
  6670. * @param p1 (Vector3) the origin point of the Hermite Spline
  6671. * @param t1 (Vector3) the tangent vector at the origin point
  6672. * @param p2 (Vector3) the end point of the Hermite Spline
  6673. * @param t2 (Vector3) the tangent vector at the end point
  6674. * @param nbPoints (integer) the wanted number of points in the curve
  6675. */
  6676. Curve3.CreateHermiteSpline = function (p1, t1, p2, t2, nbPoints) {
  6677. var hermite = new Array();
  6678. var step = 1.0 / nbPoints;
  6679. for (var i = 0; i <= nbPoints; i++) {
  6680. hermite.push(Vector3.Hermite(p1, t1, p2, t2, i * step));
  6681. }
  6682. return new Curve3(hermite);
  6683. };
  6684. /**
  6685. * Returns a Curve3 object along a CatmullRom Spline curve :
  6686. * @param points (array of Vector3) the points the spline must pass through. At least, four points required.
  6687. * @param nbPoints (integer) the wanted number of points between each curve control points.
  6688. */
  6689. Curve3.CreateCatmullRomSpline = function (points, nbPoints) {
  6690. var totalPoints = new Array();
  6691. totalPoints.push(points[0].clone());
  6692. Array.prototype.push.apply(totalPoints, points);
  6693. totalPoints.push(points[points.length - 1].clone());
  6694. var catmullRom = new Array();
  6695. var step = 1.0 / nbPoints;
  6696. var amount = 0.0;
  6697. for (var i = 0; i < totalPoints.length - 3; i++) {
  6698. amount = 0;
  6699. for (var c = 0; c < nbPoints; c++) {
  6700. catmullRom.push(Vector3.CatmullRom(totalPoints[i], totalPoints[i + 1], totalPoints[i + 2], totalPoints[i + 3], amount));
  6701. amount += step;
  6702. }
  6703. }
  6704. i--;
  6705. catmullRom.push(Vector3.CatmullRom(totalPoints[i], totalPoints[i + 1], totalPoints[i + 2], totalPoints[i + 3], amount));
  6706. return new Curve3(catmullRom);
  6707. };
  6708. /**
  6709. * Returns the Curve3 stored array of successive Vector3
  6710. */
  6711. Curve3.prototype.getPoints = function () {
  6712. return this._points;
  6713. };
  6714. /**
  6715. * Returns the computed length (float) of the curve.
  6716. */
  6717. Curve3.prototype.length = function () {
  6718. return this._length;
  6719. };
  6720. /**
  6721. * Returns a new instance of Curve3 object : var curve = curveA.continue(curveB);
  6722. * This new Curve3 is built by translating and sticking the curveB at the end of the curveA.
  6723. * curveA and curveB keep unchanged.
  6724. */
  6725. Curve3.prototype.continue = function (curve) {
  6726. var lastPoint = this._points[this._points.length - 1];
  6727. var continuedPoints = this._points.slice();
  6728. var curvePoints = curve.getPoints();
  6729. for (var i = 1; i < curvePoints.length; i++) {
  6730. continuedPoints.push(curvePoints[i].subtract(curvePoints[0]).add(lastPoint));
  6731. }
  6732. var continuedCurve = new Curve3(continuedPoints);
  6733. return continuedCurve;
  6734. };
  6735. Curve3.prototype._computeLength = function (path) {
  6736. var l = 0;
  6737. for (var i = 1; i < path.length; i++) {
  6738. l += (path[i].subtract(path[i - 1])).length();
  6739. }
  6740. return l;
  6741. };
  6742. return Curve3;
  6743. }());
  6744. BABYLON.Curve3 = Curve3;
  6745. // Vertex formats
  6746. var PositionNormalVertex = /** @class */ (function () {
  6747. function PositionNormalVertex(position, normal) {
  6748. if (position === void 0) { position = Vector3.Zero(); }
  6749. if (normal === void 0) { normal = Vector3.Up(); }
  6750. this.position = position;
  6751. this.normal = normal;
  6752. }
  6753. PositionNormalVertex.prototype.clone = function () {
  6754. return new PositionNormalVertex(this.position.clone(), this.normal.clone());
  6755. };
  6756. return PositionNormalVertex;
  6757. }());
  6758. BABYLON.PositionNormalVertex = PositionNormalVertex;
  6759. var PositionNormalTextureVertex = /** @class */ (function () {
  6760. function PositionNormalTextureVertex(position, normal, uv) {
  6761. if (position === void 0) { position = Vector3.Zero(); }
  6762. if (normal === void 0) { normal = Vector3.Up(); }
  6763. if (uv === void 0) { uv = Vector2.Zero(); }
  6764. this.position = position;
  6765. this.normal = normal;
  6766. this.uv = uv;
  6767. }
  6768. PositionNormalTextureVertex.prototype.clone = function () {
  6769. return new PositionNormalTextureVertex(this.position.clone(), this.normal.clone(), this.uv.clone());
  6770. };
  6771. return PositionNormalTextureVertex;
  6772. }());
  6773. BABYLON.PositionNormalTextureVertex = PositionNormalTextureVertex;
  6774. // Temporary pre-allocated objects for engine internal use
  6775. // usage in any internal function :
  6776. // var tmp = Tmp.Vector3[0]; <= gets access to the first pre-created Vector3
  6777. // There's a Tmp array per object type : int, float, Vector2, Vector3, Vector4, Quaternion, Matrix
  6778. var Tmp = /** @class */ (function () {
  6779. function Tmp() {
  6780. }
  6781. Tmp.Color3 = [Color3.Black(), Color3.Black(), Color3.Black()];
  6782. Tmp.Vector2 = [Vector2.Zero(), Vector2.Zero(), Vector2.Zero()]; // 3 temp Vector2 at once should be enough
  6783. Tmp.Vector3 = [Vector3.Zero(), Vector3.Zero(), Vector3.Zero(),
  6784. Vector3.Zero(), Vector3.Zero(), Vector3.Zero(), Vector3.Zero(), Vector3.Zero(), Vector3.Zero()]; // 9 temp Vector3 at once should be enough
  6785. Tmp.Vector4 = [Vector4.Zero(), Vector4.Zero(), Vector4.Zero()]; // 3 temp Vector4 at once should be enough
  6786. Tmp.Quaternion = [Quaternion.Zero(), Quaternion.Zero()]; // 2 temp Quaternion at once should be enough
  6787. Tmp.Matrix = [Matrix.Zero(), Matrix.Zero(),
  6788. Matrix.Zero(), Matrix.Zero(),
  6789. Matrix.Zero(), Matrix.Zero(),
  6790. Matrix.Zero(), Matrix.Zero()]; // 6 temp Matrices at once should be enough
  6791. return Tmp;
  6792. }());
  6793. BABYLON.Tmp = Tmp;
  6794. // Same as Tmp but not exported to keep it onyl for math functions to avoid conflicts
  6795. var MathTmp = /** @class */ (function () {
  6796. function MathTmp() {
  6797. }
  6798. MathTmp.Vector3 = [Vector3.Zero()];
  6799. MathTmp.Matrix = [Matrix.Zero(), Matrix.Zero()];
  6800. MathTmp.Quaternion = [Quaternion.Zero()];
  6801. return MathTmp;
  6802. }());
  6803. })(BABYLON || (BABYLON = {}));
  6804. //# sourceMappingURL=babylon.math.js.map
  6805. "use strict";
  6806. var BABYLON;
  6807. (function (BABYLON) {
  6808. var Scalar = /** @class */ (function () {
  6809. function Scalar() {
  6810. }
  6811. /**
  6812. * Boolean : true if the absolute difference between a and b is lower than epsilon (default = 1.401298E-45)
  6813. */
  6814. Scalar.WithinEpsilon = function (a, b, epsilon) {
  6815. if (epsilon === void 0) { epsilon = 1.401298E-45; }
  6816. var num = a - b;
  6817. return -epsilon <= num && num <= epsilon;
  6818. };
  6819. /**
  6820. * Returns a string : the upper case translation of the number i to hexadecimal.
  6821. */
  6822. Scalar.ToHex = function (i) {
  6823. var str = i.toString(16);
  6824. if (i <= 15) {
  6825. return ("0" + str).toUpperCase();
  6826. }
  6827. return str.toUpperCase();
  6828. };
  6829. /**
  6830. * Returns -1 if value is negative and +1 is value is positive.
  6831. * Returns the value itself if it's equal to zero.
  6832. */
  6833. Scalar.Sign = function (value) {
  6834. value = +value; // convert to a number
  6835. if (value === 0 || isNaN(value))
  6836. return value;
  6837. return value > 0 ? 1 : -1;
  6838. };
  6839. /**
  6840. * Returns the value itself if it's between min and max.
  6841. * Returns min if the value is lower than min.
  6842. * Returns max if the value is greater than max.
  6843. */
  6844. Scalar.Clamp = function (value, min, max) {
  6845. if (min === void 0) { min = 0; }
  6846. if (max === void 0) { max = 1; }
  6847. return Math.min(max, Math.max(min, value));
  6848. };
  6849. /**
  6850. * Returns the log2 of value.
  6851. */
  6852. Scalar.Log2 = function (value) {
  6853. return Math.log(value) * Math.LOG2E;
  6854. };
  6855. /**
  6856. * Loops the value, so that it is never larger than length and never smaller than 0.
  6857. *
  6858. * This is similar to the modulo operator but it works with floating point numbers.
  6859. * For example, using 3.0 for t and 2.5 for length, the result would be 0.5.
  6860. * With t = 5 and length = 2.5, the result would be 0.0.
  6861. * Note, however, that the behaviour is not defined for negative numbers as it is for the modulo operator
  6862. */
  6863. Scalar.Repeat = function (value, length) {
  6864. return value - Math.floor(value / length) * length;
  6865. };
  6866. /**
  6867. * Normalize the value between 0.0 and 1.0 using min and max values
  6868. */
  6869. Scalar.Normalize = function (value, min, max) {
  6870. return (value - min) / (max - min);
  6871. };
  6872. /**
  6873. * Denormalize the value from 0.0 and 1.0 using min and max values
  6874. */
  6875. Scalar.Denormalize = function (normalized, min, max) {
  6876. return (normalized * (max - min) + min);
  6877. };
  6878. /**
  6879. * Calculates the shortest difference between two given angles given in degrees.
  6880. */
  6881. Scalar.DeltaAngle = function (current, target) {
  6882. var num = Scalar.Repeat(target - current, 360.0);
  6883. if (num > 180.0) {
  6884. num -= 360.0;
  6885. }
  6886. return num;
  6887. };
  6888. /**
  6889. * PingPongs the value t, so that it is never larger than length and never smaller than 0.
  6890. *
  6891. * The returned value will move back and forth between 0 and length
  6892. */
  6893. Scalar.PingPong = function (tx, length) {
  6894. var t = Scalar.Repeat(tx, length * 2.0);
  6895. return length - Math.abs(t - length);
  6896. };
  6897. /**
  6898. * Interpolates between min and max with smoothing at the limits.
  6899. *
  6900. * This function interpolates between min and max in a similar way to Lerp. However, the interpolation will gradually speed up
  6901. * from the start and slow down toward the end. This is useful for creating natural-looking animation, fading and other transitions.
  6902. */
  6903. Scalar.SmoothStep = function (from, to, tx) {
  6904. var t = Scalar.Clamp(tx);
  6905. t = -2.0 * t * t * t + 3.0 * t * t;
  6906. return to * t + from * (1.0 - t);
  6907. };
  6908. /**
  6909. * Moves a value current towards target.
  6910. *
  6911. * This is essentially the same as Mathf.Lerp but instead the function will ensure that the speed never exceeds maxDelta.
  6912. * Negative values of maxDelta pushes the value away from target.
  6913. */
  6914. Scalar.MoveTowards = function (current, target, maxDelta) {
  6915. var result = 0;
  6916. if (Math.abs(target - current) <= maxDelta) {
  6917. result = target;
  6918. }
  6919. else {
  6920. result = current + Scalar.Sign(target - current) * maxDelta;
  6921. }
  6922. return result;
  6923. };
  6924. /**
  6925. * Same as MoveTowards but makes sure the values interpolate correctly when they wrap around 360 degrees.
  6926. *
  6927. * Variables current and target are assumed to be in degrees. For optimization reasons, negative values of maxDelta
  6928. * are not supported and may cause oscillation. To push current away from a target angle, add 180 to that angle instead.
  6929. */
  6930. Scalar.MoveTowardsAngle = function (current, target, maxDelta) {
  6931. var num = Scalar.DeltaAngle(current, target);
  6932. var result = 0;
  6933. if (-maxDelta < num && num < maxDelta) {
  6934. result = target;
  6935. }
  6936. else {
  6937. target = current + num;
  6938. result = Scalar.MoveTowards(current, target, maxDelta);
  6939. }
  6940. return result;
  6941. };
  6942. /**
  6943. * Creates a new scalar with values linearly interpolated of "amount" between the start scalar and the end scalar.
  6944. */
  6945. Scalar.Lerp = function (start, end, amount) {
  6946. return start + ((end - start) * amount);
  6947. };
  6948. /**
  6949. * Same as Lerp but makes sure the values interpolate correctly when they wrap around 360 degrees.
  6950. * The parameter t is clamped to the range [0, 1]. Variables a and b are assumed to be in degrees.
  6951. */
  6952. Scalar.LerpAngle = function (start, end, amount) {
  6953. var num = Scalar.Repeat(end - start, 360.0);
  6954. if (num > 180.0) {
  6955. num -= 360.0;
  6956. }
  6957. return start + num * Scalar.Clamp(amount);
  6958. };
  6959. /**
  6960. * Calculates the linear parameter t that produces the interpolant value within the range [a, b].
  6961. */
  6962. Scalar.InverseLerp = function (a, b, value) {
  6963. var result = 0;
  6964. if (a != b) {
  6965. result = Scalar.Clamp((value - a) / (b - a));
  6966. }
  6967. else {
  6968. result = 0.0;
  6969. }
  6970. return result;
  6971. };
  6972. /**
  6973. * Returns a new scalar located for "amount" (float) on the Hermite spline defined by the scalars "value1", "value3", "tangent1", "tangent2".
  6974. */
  6975. Scalar.Hermite = function (value1, tangent1, value2, tangent2, amount) {
  6976. var squared = amount * amount;
  6977. var cubed = amount * squared;
  6978. var part1 = ((2.0 * cubed) - (3.0 * squared)) + 1.0;
  6979. var part2 = (-2.0 * cubed) + (3.0 * squared);
  6980. var part3 = (cubed - (2.0 * squared)) + amount;
  6981. var part4 = cubed - squared;
  6982. return (((value1 * part1) + (value2 * part2)) + (tangent1 * part3)) + (tangent2 * part4);
  6983. };
  6984. /**
  6985. * Returns a random float number between and min and max values
  6986. */
  6987. Scalar.RandomRange = function (min, max) {
  6988. if (min === max)
  6989. return min;
  6990. return ((Math.random() * (max - min)) + min);
  6991. };
  6992. /**
  6993. * This function returns percentage of a number in a given range.
  6994. *
  6995. * RangeToPercent(40,20,60) will return 0.5 (50%)
  6996. * RangeToPercent(34,0,100) will return 0.34 (34%)
  6997. */
  6998. Scalar.RangeToPercent = function (number, min, max) {
  6999. return ((number - min) / (max - min));
  7000. };
  7001. /**
  7002. * This function returns number that corresponds to the percentage in a given range.
  7003. *
  7004. * PercentToRange(0.34,0,100) will return 34.
  7005. */
  7006. Scalar.PercentToRange = function (percent, min, max) {
  7007. return ((max - min) * percent + min);
  7008. };
  7009. /**
  7010. * Returns the angle converted to equivalent value between -Math.PI and Math.PI radians.
  7011. * @param angle The angle to normalize in radian.
  7012. * @return The converted angle.
  7013. */
  7014. Scalar.NormalizeRadians = function (angle) {
  7015. // More precise but slower version kept for reference.
  7016. // angle = angle % Tools.TwoPi;
  7017. // angle = (angle + Tools.TwoPi) % Tools.TwoPi;
  7018. //if (angle > Math.PI) {
  7019. // angle -= Tools.TwoPi;
  7020. //}
  7021. angle -= (Scalar.TwoPi * Math.floor((angle + Math.PI) / Scalar.TwoPi));
  7022. return angle;
  7023. };
  7024. /**
  7025. * Two pi constants convenient for computation.
  7026. */
  7027. Scalar.TwoPi = Math.PI * 2;
  7028. return Scalar;
  7029. }());
  7030. BABYLON.Scalar = Scalar;
  7031. })(BABYLON || (BABYLON = {}));
  7032. //# sourceMappingURL=babylon.math.scalar.js.map
  7033. "use strict";
  7034. //# sourceMappingURL=babylon.mixins.js.map
  7035. "use strict";
  7036. // Type definitions for WebGL 2, Editor's Draft Fri Feb 24 16:10:18 2017 -0800
  7037. // Project: https://www.khronos.org/registry/webgl/specs/latest/2.0/
  7038. // Definitions by: Nico Kemnitz <https://github.com/nkemnitz/>
  7039. // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
  7040. //# sourceMappingURL=babylon.webgl2.js.map
  7041. "use strict";
  7042. var BABYLON;
  7043. (function (BABYLON) {
  7044. var __decoratorInitialStore = {};
  7045. var __mergedStore = {};
  7046. var _copySource = function (creationFunction, source, instanciate) {
  7047. var destination = creationFunction();
  7048. // Tags
  7049. if (BABYLON.Tags) {
  7050. BABYLON.Tags.AddTagsTo(destination, source.tags);
  7051. }
  7052. var classStore = getMergedStore(destination);
  7053. // Properties
  7054. for (var property in classStore) {
  7055. var propertyDescriptor = classStore[property];
  7056. var sourceProperty = source[property];
  7057. var propertyType = propertyDescriptor.type;
  7058. if (sourceProperty !== undefined && sourceProperty !== null) {
  7059. switch (propertyType) {
  7060. case 0: // Value
  7061. case 6:// Mesh reference
  7062. destination[property] = sourceProperty;
  7063. break;
  7064. case 1:// Texture
  7065. destination[property] = (instanciate || sourceProperty.isRenderTarget) ? sourceProperty : sourceProperty.clone();
  7066. break;
  7067. case 2: // Color3
  7068. case 3: // FresnelParameters
  7069. case 4: // Vector2
  7070. case 5: // Vector3
  7071. case 7: // Color Curves
  7072. case 10:// Quaternion
  7073. destination[property] = instanciate ? sourceProperty : sourceProperty.clone();
  7074. break;
  7075. }
  7076. }
  7077. }
  7078. return destination;
  7079. };
  7080. function getDirectStore(target) {
  7081. var classKey = target.getClassName();
  7082. if (!__decoratorInitialStore[classKey]) {
  7083. __decoratorInitialStore[classKey] = {};
  7084. }
  7085. return __decoratorInitialStore[classKey];
  7086. }
  7087. /**
  7088. * Return the list of properties flagged as serializable
  7089. * @param target: host object
  7090. */
  7091. function getMergedStore(target) {
  7092. var classKey = target.getClassName();
  7093. if (__mergedStore[classKey]) {
  7094. return __mergedStore[classKey];
  7095. }
  7096. __mergedStore[classKey] = {};
  7097. var store = __mergedStore[classKey];
  7098. var currentTarget = target;
  7099. var currentKey = classKey;
  7100. while (currentKey) {
  7101. var initialStore = __decoratorInitialStore[currentKey];
  7102. for (var property in initialStore) {
  7103. store[property] = initialStore[property];
  7104. }
  7105. var parent_1 = void 0;
  7106. var done = false;
  7107. do {
  7108. parent_1 = Object.getPrototypeOf(currentTarget);
  7109. if (!parent_1.getClassName) {
  7110. done = true;
  7111. break;
  7112. }
  7113. if (parent_1.getClassName() !== currentKey) {
  7114. break;
  7115. }
  7116. currentTarget = parent_1;
  7117. } while (parent_1);
  7118. if (done) {
  7119. break;
  7120. }
  7121. currentKey = parent_1.getClassName();
  7122. currentTarget = parent_1;
  7123. }
  7124. return store;
  7125. }
  7126. function generateSerializableMember(type, sourceName) {
  7127. return function (target, propertyKey) {
  7128. var classStore = getDirectStore(target);
  7129. if (!classStore[propertyKey]) {
  7130. classStore[propertyKey] = { type: type, sourceName: sourceName };
  7131. }
  7132. };
  7133. }
  7134. function generateExpandMember(setCallback, targetKey) {
  7135. if (targetKey === void 0) { targetKey = null; }
  7136. return function (target, propertyKey) {
  7137. var key = targetKey || ("_" + propertyKey);
  7138. Object.defineProperty(target, propertyKey, {
  7139. get: function () {
  7140. return this[key];
  7141. },
  7142. set: function (value) {
  7143. if (this[key] === value) {
  7144. return;
  7145. }
  7146. this[key] = value;
  7147. target[setCallback].apply(this);
  7148. },
  7149. enumerable: true,
  7150. configurable: true
  7151. });
  7152. };
  7153. }
  7154. function expandToProperty(callback, targetKey) {
  7155. if (targetKey === void 0) { targetKey = null; }
  7156. return generateExpandMember(callback, targetKey);
  7157. }
  7158. BABYLON.expandToProperty = expandToProperty;
  7159. function serialize(sourceName) {
  7160. return generateSerializableMember(0, sourceName); // value member
  7161. }
  7162. BABYLON.serialize = serialize;
  7163. function serializeAsTexture(sourceName) {
  7164. return generateSerializableMember(1, sourceName); // texture member
  7165. }
  7166. BABYLON.serializeAsTexture = serializeAsTexture;
  7167. function serializeAsColor3(sourceName) {
  7168. return generateSerializableMember(2, sourceName); // color3 member
  7169. }
  7170. BABYLON.serializeAsColor3 = serializeAsColor3;
  7171. function serializeAsFresnelParameters(sourceName) {
  7172. return generateSerializableMember(3, sourceName); // fresnel parameters member
  7173. }
  7174. BABYLON.serializeAsFresnelParameters = serializeAsFresnelParameters;
  7175. function serializeAsVector2(sourceName) {
  7176. return generateSerializableMember(4, sourceName); // vector2 member
  7177. }
  7178. BABYLON.serializeAsVector2 = serializeAsVector2;
  7179. function serializeAsVector3(sourceName) {
  7180. return generateSerializableMember(5, sourceName); // vector3 member
  7181. }
  7182. BABYLON.serializeAsVector3 = serializeAsVector3;
  7183. function serializeAsMeshReference(sourceName) {
  7184. return generateSerializableMember(6, sourceName); // mesh reference member
  7185. }
  7186. BABYLON.serializeAsMeshReference = serializeAsMeshReference;
  7187. function serializeAsColorCurves(sourceName) {
  7188. return generateSerializableMember(7, sourceName); // color curves
  7189. }
  7190. BABYLON.serializeAsColorCurves = serializeAsColorCurves;
  7191. function serializeAsColor4(sourceName) {
  7192. return generateSerializableMember(8, sourceName); // color 4
  7193. }
  7194. BABYLON.serializeAsColor4 = serializeAsColor4;
  7195. function serializeAsImageProcessingConfiguration(sourceName) {
  7196. return generateSerializableMember(9, sourceName); // image processing
  7197. }
  7198. BABYLON.serializeAsImageProcessingConfiguration = serializeAsImageProcessingConfiguration;
  7199. function serializeAsQuaternion(sourceName) {
  7200. return generateSerializableMember(10, sourceName); // quaternion member
  7201. }
  7202. BABYLON.serializeAsQuaternion = serializeAsQuaternion;
  7203. var SerializationHelper = /** @class */ (function () {
  7204. function SerializationHelper() {
  7205. }
  7206. SerializationHelper.Serialize = function (entity, serializationObject) {
  7207. if (!serializationObject) {
  7208. serializationObject = {};
  7209. }
  7210. // Tags
  7211. if (BABYLON.Tags) {
  7212. serializationObject.tags = BABYLON.Tags.GetTags(entity);
  7213. }
  7214. var serializedProperties = getMergedStore(entity);
  7215. // Properties
  7216. for (var property in serializedProperties) {
  7217. var propertyDescriptor = serializedProperties[property];
  7218. var targetPropertyName = propertyDescriptor.sourceName || property;
  7219. var propertyType = propertyDescriptor.type;
  7220. var sourceProperty = entity[property];
  7221. if (sourceProperty !== undefined && sourceProperty !== null) {
  7222. switch (propertyType) {
  7223. case 0:// Value
  7224. serializationObject[targetPropertyName] = sourceProperty;
  7225. break;
  7226. case 1:// Texture
  7227. serializationObject[targetPropertyName] = sourceProperty.serialize();
  7228. break;
  7229. case 2:// Color3
  7230. serializationObject[targetPropertyName] = sourceProperty.asArray();
  7231. break;
  7232. case 3:// FresnelParameters
  7233. serializationObject[targetPropertyName] = sourceProperty.serialize();
  7234. break;
  7235. case 4:// Vector2
  7236. serializationObject[targetPropertyName] = sourceProperty.asArray();
  7237. break;
  7238. case 5:// Vector3
  7239. serializationObject[targetPropertyName] = sourceProperty.asArray();
  7240. break;
  7241. case 6:// Mesh reference
  7242. serializationObject[targetPropertyName] = sourceProperty.id;
  7243. break;
  7244. case 7:// Color Curves
  7245. serializationObject[targetPropertyName] = sourceProperty.serialize();
  7246. break;
  7247. case 8:// Color 4
  7248. serializationObject[targetPropertyName] = sourceProperty.asArray();
  7249. break;
  7250. case 9:// Image Processing
  7251. serializationObject[targetPropertyName] = sourceProperty.serialize();
  7252. break;
  7253. }
  7254. }
  7255. }
  7256. return serializationObject;
  7257. };
  7258. SerializationHelper.Parse = function (creationFunction, source, scene, rootUrl) {
  7259. if (rootUrl === void 0) { rootUrl = null; }
  7260. var destination = creationFunction();
  7261. if (!rootUrl) {
  7262. rootUrl = "";
  7263. }
  7264. // Tags
  7265. if (BABYLON.Tags) {
  7266. BABYLON.Tags.AddTagsTo(destination, source.tags);
  7267. }
  7268. var classStore = getMergedStore(destination);
  7269. // Properties
  7270. for (var property in classStore) {
  7271. var propertyDescriptor = classStore[property];
  7272. var sourceProperty = source[propertyDescriptor.sourceName || property];
  7273. var propertyType = propertyDescriptor.type;
  7274. if (sourceProperty !== undefined && sourceProperty !== null) {
  7275. var dest = destination;
  7276. switch (propertyType) {
  7277. case 0:// Value
  7278. dest[property] = sourceProperty;
  7279. break;
  7280. case 1:// Texture
  7281. if (scene) {
  7282. dest[property] = BABYLON.Texture.Parse(sourceProperty, scene, rootUrl);
  7283. }
  7284. break;
  7285. case 2:// Color3
  7286. dest[property] = BABYLON.Color3.FromArray(sourceProperty);
  7287. break;
  7288. case 3:// FresnelParameters
  7289. dest[property] = BABYLON.FresnelParameters.Parse(sourceProperty);
  7290. break;
  7291. case 4:// Vector2
  7292. dest[property] = BABYLON.Vector2.FromArray(sourceProperty);
  7293. break;
  7294. case 5:// Vector3
  7295. dest[property] = BABYLON.Vector3.FromArray(sourceProperty);
  7296. break;
  7297. case 6:// Mesh reference
  7298. if (scene) {
  7299. dest[property] = scene.getLastMeshByID(sourceProperty);
  7300. }
  7301. break;
  7302. case 7:// Color Curves
  7303. dest[property] = BABYLON.ColorCurves.Parse(sourceProperty);
  7304. break;
  7305. case 8:// Color 4
  7306. dest[property] = BABYLON.Color4.FromArray(sourceProperty);
  7307. break;
  7308. case 9:// Image Processing
  7309. dest[property] = BABYLON.ImageProcessingConfiguration.Parse(sourceProperty);
  7310. break;
  7311. }
  7312. }
  7313. }
  7314. return destination;
  7315. };
  7316. SerializationHelper.Clone = function (creationFunction, source) {
  7317. return _copySource(creationFunction, source, false);
  7318. };
  7319. SerializationHelper.Instanciate = function (creationFunction, source) {
  7320. return _copySource(creationFunction, source, true);
  7321. };
  7322. return SerializationHelper;
  7323. }());
  7324. BABYLON.SerializationHelper = SerializationHelper;
  7325. })(BABYLON || (BABYLON = {}));
  7326. //# sourceMappingURL=babylon.decorators.js.map
  7327. "use strict";
  7328. var BABYLON;
  7329. (function (BABYLON) {
  7330. /**
  7331. * Wrapper class for promise with external resolve and reject.
  7332. */
  7333. var Deferred = /** @class */ (function () {
  7334. /**
  7335. * Constructor for this deferred object.
  7336. */
  7337. function Deferred() {
  7338. var _this = this;
  7339. this.promise = new Promise(function (resolve, reject) {
  7340. _this._resolve = resolve;
  7341. _this._reject = reject;
  7342. });
  7343. }
  7344. Object.defineProperty(Deferred.prototype, "resolve", {
  7345. /**
  7346. * The resolve method of the promise associated with this deferred object.
  7347. */
  7348. get: function () {
  7349. return this._resolve;
  7350. },
  7351. enumerable: true,
  7352. configurable: true
  7353. });
  7354. Object.defineProperty(Deferred.prototype, "reject", {
  7355. /**
  7356. * The reject method of the promise associated with this deferred object.
  7357. */
  7358. get: function () {
  7359. return this._reject;
  7360. },
  7361. enumerable: true,
  7362. configurable: true
  7363. });
  7364. return Deferred;
  7365. }());
  7366. BABYLON.Deferred = Deferred;
  7367. })(BABYLON || (BABYLON = {}));
  7368. //# sourceMappingURL=babylon.deferred.js.map
  7369. "use strict";
  7370. var BABYLON;
  7371. (function (BABYLON) {
  7372. /**
  7373. * A class serves as a medium between the observable and its observers
  7374. */
  7375. var EventState = /** @class */ (function () {
  7376. /**
  7377. * Create a new EventState
  7378. * @param mask defines the mask associated with this state
  7379. * @param skipNextObservers defines a flag which will instruct the observable to skip following observers when set to true
  7380. * @param target defines the original target of the state
  7381. * @param currentTarget defines the current target of the state
  7382. */
  7383. function EventState(mask, skipNextObservers, target, currentTarget) {
  7384. if (skipNextObservers === void 0) { skipNextObservers = false; }
  7385. this.initalize(mask, skipNextObservers, target, currentTarget);
  7386. }
  7387. /**
  7388. * Initialize the current event state
  7389. * @param mask defines the mask associated with this state
  7390. * @param skipNextObservers defines a flag which will instruct the observable to skip following observers when set to true
  7391. * @param target defines the original target of the state
  7392. * @param currentTarget defines the current target of the state
  7393. * @returns the current event state
  7394. */
  7395. EventState.prototype.initalize = function (mask, skipNextObservers, target, currentTarget) {
  7396. if (skipNextObservers === void 0) { skipNextObservers = false; }
  7397. this.mask = mask;
  7398. this.skipNextObservers = skipNextObservers;
  7399. this.target = target;
  7400. this.currentTarget = currentTarget;
  7401. return this;
  7402. };
  7403. return EventState;
  7404. }());
  7405. BABYLON.EventState = EventState;
  7406. /**
  7407. * Represent an Observer registered to a given Observable object.
  7408. */
  7409. var Observer = /** @class */ (function () {
  7410. /**
  7411. * Creates a new observer
  7412. * @param callback defines the callback to call when the observer is notified
  7413. * @param mask defines the mask of the observer (used to filter notifications)
  7414. * @param scope defines the current scope used to restore the JS context
  7415. */
  7416. function Observer(
  7417. /**
  7418. * Defines the callback to call when the observer is notified
  7419. */
  7420. callback,
  7421. /**
  7422. * Defines the mask of the observer (used to filter notifications)
  7423. */
  7424. mask,
  7425. /**
  7426. * Defines the current scope used to restore the JS context
  7427. */
  7428. scope) {
  7429. if (scope === void 0) { scope = null; }
  7430. this.callback = callback;
  7431. this.mask = mask;
  7432. this.scope = scope;
  7433. /** @ignore */
  7434. this._willBeUnregistered = false;
  7435. /**
  7436. * Gets or sets a property defining that the observer as to be unregistered after the next notification
  7437. */
  7438. this.unregisterOnNextCall = false;
  7439. }
  7440. return Observer;
  7441. }());
  7442. BABYLON.Observer = Observer;
  7443. /**
  7444. * Represent a list of observers registered to multiple Observables object.
  7445. */
  7446. var MultiObserver = /** @class */ (function () {
  7447. function MultiObserver() {
  7448. }
  7449. /**
  7450. * Release associated resources
  7451. */
  7452. MultiObserver.prototype.dispose = function () {
  7453. if (this._observers && this._observables) {
  7454. for (var index = 0; index < this._observers.length; index++) {
  7455. this._observables[index].remove(this._observers[index]);
  7456. }
  7457. }
  7458. this._observers = null;
  7459. this._observables = null;
  7460. };
  7461. /**
  7462. * Raise a callback when one of the observable will notify
  7463. * @param observables defines a list of observables to watch
  7464. * @param callback defines the callback to call on notification
  7465. * @param mask defines the mask used to filter notifications
  7466. * @param scope defines the current scope used to restore the JS context
  7467. * @returns the new MultiObserver
  7468. */
  7469. MultiObserver.Watch = function (observables, callback, mask, scope) {
  7470. if (mask === void 0) { mask = -1; }
  7471. if (scope === void 0) { scope = null; }
  7472. var result = new MultiObserver();
  7473. result._observers = new Array();
  7474. result._observables = observables;
  7475. for (var _i = 0, observables_1 = observables; _i < observables_1.length; _i++) {
  7476. var observable = observables_1[_i];
  7477. var observer = observable.add(callback, mask, false, scope);
  7478. if (observer) {
  7479. result._observers.push(observer);
  7480. }
  7481. }
  7482. return result;
  7483. };
  7484. return MultiObserver;
  7485. }());
  7486. BABYLON.MultiObserver = MultiObserver;
  7487. /**
  7488. * The Observable class is a simple implementation of the Observable pattern.
  7489. *
  7490. * 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.
  7491. * This enable a more fine grained execution without having to rely on multiple different Observable objects.
  7492. * 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).
  7493. * 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.
  7494. */
  7495. var Observable = /** @class */ (function () {
  7496. /**
  7497. * Creates a new observable
  7498. * @param onObserverAdded defines a callback to call when a new observer is added
  7499. */
  7500. function Observable(onObserverAdded) {
  7501. this._observers = new Array();
  7502. this._eventState = new EventState(0);
  7503. if (onObserverAdded) {
  7504. this._onObserverAdded = onObserverAdded;
  7505. }
  7506. }
  7507. /**
  7508. * Create a new Observer with the specified callback
  7509. * @param callback the callback that will be executed for that Observer
  7510. * @param mask the mask used to filter observers
  7511. * @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.
  7512. * @param scope optional scope for the callback to be called from
  7513. * @param unregisterOnFirstCall defines if the observer as to be unregistered after the next notification
  7514. * @returns the new observer created for the callback
  7515. */
  7516. Observable.prototype.add = function (callback, mask, insertFirst, scope, unregisterOnFirstCall) {
  7517. if (mask === void 0) { mask = -1; }
  7518. if (insertFirst === void 0) { insertFirst = false; }
  7519. if (scope === void 0) { scope = null; }
  7520. if (unregisterOnFirstCall === void 0) { unregisterOnFirstCall = false; }
  7521. if (!callback) {
  7522. return null;
  7523. }
  7524. var observer = new Observer(callback, mask, scope);
  7525. observer.unregisterOnNextCall = unregisterOnFirstCall;
  7526. if (insertFirst) {
  7527. this._observers.unshift(observer);
  7528. }
  7529. else {
  7530. this._observers.push(observer);
  7531. }
  7532. if (this._onObserverAdded) {
  7533. this._onObserverAdded(observer);
  7534. }
  7535. return observer;
  7536. };
  7537. /**
  7538. * Remove an Observer from the Observable object
  7539. * @param observer the instance of the Observer to remove
  7540. * @returns false if it doesn't belong to this Observable
  7541. */
  7542. Observable.prototype.remove = function (observer) {
  7543. if (!observer) {
  7544. return false;
  7545. }
  7546. var index = this._observers.indexOf(observer);
  7547. if (index !== -1) {
  7548. this._observers.splice(index, 1);
  7549. return true;
  7550. }
  7551. return false;
  7552. };
  7553. /**
  7554. * Remove a callback from the Observable object
  7555. * @param callback the callback to remove
  7556. * @param scope optional scope. If used only the callbacks with this scope will be removed
  7557. * @returns false if it doesn't belong to this Observable
  7558. */
  7559. Observable.prototype.removeCallback = function (callback, scope) {
  7560. for (var index = 0; index < this._observers.length; index++) {
  7561. if (this._observers[index].callback === callback && (!scope || scope === this._observers[index].scope)) {
  7562. this._observers.splice(index, 1);
  7563. return true;
  7564. }
  7565. }
  7566. return false;
  7567. };
  7568. Observable.prototype._deferUnregister = function (observer) {
  7569. var _this = this;
  7570. observer.unregisterOnNextCall = false;
  7571. observer._willBeUnregistered = true;
  7572. BABYLON.Tools.SetImmediate(function () {
  7573. _this.remove(observer);
  7574. });
  7575. };
  7576. /**
  7577. * Notify all Observers by calling their respective callback with the given data
  7578. * Will return true if all observers were executed, false if an observer set skipNextObservers to true, then prevent the subsequent ones to execute
  7579. * @param eventData defines the data to send to all observers
  7580. * @param mask defines the mask of the current notification (observers with incompatible mask (ie mask & observer.mask === 0) will not be notified)
  7581. * @param target defines the original target of the state
  7582. * @param currentTarget defines the current target of the state
  7583. * @returns false if the complete observer chain was not processed (because one observer set the skipNextObservers to true)
  7584. */
  7585. Observable.prototype.notifyObservers = function (eventData, mask, target, currentTarget) {
  7586. if (mask === void 0) { mask = -1; }
  7587. if (!this._observers.length) {
  7588. return true;
  7589. }
  7590. var state = this._eventState;
  7591. state.mask = mask;
  7592. state.target = target;
  7593. state.currentTarget = currentTarget;
  7594. state.skipNextObservers = false;
  7595. state.lastReturnValue = eventData;
  7596. for (var _i = 0, _a = this._observers; _i < _a.length; _i++) {
  7597. var obs = _a[_i];
  7598. if (obs._willBeUnregistered) {
  7599. continue;
  7600. }
  7601. if (obs.mask & mask) {
  7602. if (obs.scope) {
  7603. state.lastReturnValue = obs.callback.apply(obs.scope, [eventData, state]);
  7604. }
  7605. else {
  7606. state.lastReturnValue = obs.callback(eventData, state);
  7607. }
  7608. if (obs.unregisterOnNextCall) {
  7609. this._deferUnregister(obs);
  7610. }
  7611. }
  7612. if (state.skipNextObservers) {
  7613. return false;
  7614. }
  7615. }
  7616. return true;
  7617. };
  7618. /**
  7619. * Calling this will execute each callback, expecting it to be a promise or return a value.
  7620. * If at any point in the chain one function fails, the promise will fail and the execution will not continue.
  7621. * This is useful when a chain of events (sometimes async events) is needed to initialize a certain object
  7622. * and it is crucial that all callbacks will be executed.
  7623. * The order of the callbacks is kept, callbacks are not executed parallel.
  7624. *
  7625. * @param eventData The data to be sent to each callback
  7626. * @param mask is used to filter observers defaults to -1
  7627. * @param target defines the callback target (see EventState)
  7628. * @param currentTarget defines he current object in the bubbling phase
  7629. * @returns {Promise<T>} will return a Promise than resolves when all callbacks executed successfully.
  7630. */
  7631. Observable.prototype.notifyObserversWithPromise = function (eventData, mask, target, currentTarget) {
  7632. var _this = this;
  7633. if (mask === void 0) { mask = -1; }
  7634. // create an empty promise
  7635. var p = Promise.resolve(eventData);
  7636. // no observers? return this promise.
  7637. if (!this._observers.length) {
  7638. return p;
  7639. }
  7640. var state = this._eventState;
  7641. state.mask = mask;
  7642. state.target = target;
  7643. state.currentTarget = currentTarget;
  7644. state.skipNextObservers = false;
  7645. // execute one callback after another (not using Promise.all, the order is important)
  7646. this._observers.forEach(function (obs) {
  7647. if (state.skipNextObservers) {
  7648. return;
  7649. }
  7650. if (obs._willBeUnregistered) {
  7651. return;
  7652. }
  7653. if (obs.mask & mask) {
  7654. if (obs.scope) {
  7655. p = p.then(function (lastReturnedValue) {
  7656. state.lastReturnValue = lastReturnedValue;
  7657. return obs.callback.apply(obs.scope, [eventData, state]);
  7658. });
  7659. }
  7660. else {
  7661. p = p.then(function (lastReturnedValue) {
  7662. state.lastReturnValue = lastReturnedValue;
  7663. return obs.callback(eventData, state);
  7664. });
  7665. }
  7666. if (obs.unregisterOnNextCall) {
  7667. _this._deferUnregister(obs);
  7668. }
  7669. }
  7670. });
  7671. // return the eventData
  7672. return p.then(function () { return eventData; });
  7673. };
  7674. /**
  7675. * Notify a specific observer
  7676. * @param observer defines the observer to notify
  7677. * @param eventData defines the data to be sent to each callback
  7678. * @param mask is used to filter observers defaults to -1
  7679. */
  7680. Observable.prototype.notifyObserver = function (observer, eventData, mask) {
  7681. if (mask === void 0) { mask = -1; }
  7682. var state = this._eventState;
  7683. state.mask = mask;
  7684. state.skipNextObservers = false;
  7685. observer.callback(eventData, state);
  7686. };
  7687. /**
  7688. * Gets a boolean indicating if the observable has at least one observer
  7689. * @returns true is the Observable has at least one Observer registered
  7690. */
  7691. Observable.prototype.hasObservers = function () {
  7692. return this._observers.length > 0;
  7693. };
  7694. /**
  7695. * Clear the list of observers
  7696. */
  7697. Observable.prototype.clear = function () {
  7698. this._observers = new Array();
  7699. this._onObserverAdded = null;
  7700. };
  7701. /**
  7702. * Clone the current observable
  7703. * @returns a new observable
  7704. */
  7705. Observable.prototype.clone = function () {
  7706. var result = new Observable();
  7707. result._observers = this._observers.slice(0);
  7708. return result;
  7709. };
  7710. /**
  7711. * Does this observable handles observer registered with a given mask
  7712. * @param mask defines the mask to be tested
  7713. * @return whether or not one observer registered with the given mask is handeled
  7714. **/
  7715. Observable.prototype.hasSpecificMask = function (mask) {
  7716. if (mask === void 0) { mask = -1; }
  7717. for (var _i = 0, _a = this._observers; _i < _a.length; _i++) {
  7718. var obs = _a[_i];
  7719. if (obs.mask & mask || obs.mask === mask) {
  7720. return true;
  7721. }
  7722. }
  7723. return false;
  7724. };
  7725. return Observable;
  7726. }());
  7727. BABYLON.Observable = Observable;
  7728. })(BABYLON || (BABYLON = {}));
  7729. //# sourceMappingURL=babylon.observable.js.map
  7730. "use strict";
  7731. var BABYLON;
  7732. (function (BABYLON) {
  7733. var SmartArray = /** @class */ (function () {
  7734. function SmartArray(capacity) {
  7735. this.length = 0;
  7736. this.data = new Array(capacity);
  7737. this._id = SmartArray._GlobalId++;
  7738. }
  7739. SmartArray.prototype.push = function (value) {
  7740. this.data[this.length++] = value;
  7741. if (this.length > this.data.length) {
  7742. this.data.length *= 2;
  7743. }
  7744. };
  7745. SmartArray.prototype.forEach = function (func) {
  7746. for (var index = 0; index < this.length; index++) {
  7747. func(this.data[index]);
  7748. }
  7749. };
  7750. SmartArray.prototype.sort = function (compareFn) {
  7751. this.data.sort(compareFn);
  7752. };
  7753. SmartArray.prototype.reset = function () {
  7754. this.length = 0;
  7755. };
  7756. SmartArray.prototype.dispose = function () {
  7757. this.reset();
  7758. if (this.data) {
  7759. this.data.length = 0;
  7760. this.data = [];
  7761. }
  7762. };
  7763. SmartArray.prototype.concat = function (array) {
  7764. if (array.length === 0) {
  7765. return;
  7766. }
  7767. if (this.length + array.length > this.data.length) {
  7768. this.data.length = (this.length + array.length) * 2;
  7769. }
  7770. for (var index = 0; index < array.length; index++) {
  7771. this.data[this.length++] = (array.data || array)[index];
  7772. }
  7773. };
  7774. SmartArray.prototype.indexOf = function (value) {
  7775. var position = this.data.indexOf(value);
  7776. if (position >= this.length) {
  7777. return -1;
  7778. }
  7779. return position;
  7780. };
  7781. SmartArray.prototype.contains = function (value) {
  7782. return this.data.indexOf(value) !== -1;
  7783. };
  7784. // Statics
  7785. SmartArray._GlobalId = 0;
  7786. return SmartArray;
  7787. }());
  7788. BABYLON.SmartArray = SmartArray;
  7789. var SmartArrayNoDuplicate = /** @class */ (function (_super) {
  7790. __extends(SmartArrayNoDuplicate, _super);
  7791. function SmartArrayNoDuplicate() {
  7792. var _this = _super !== null && _super.apply(this, arguments) || this;
  7793. _this._duplicateId = 0;
  7794. return _this;
  7795. }
  7796. SmartArrayNoDuplicate.prototype.push = function (value) {
  7797. _super.prototype.push.call(this, value);
  7798. if (!value.__smartArrayFlags) {
  7799. value.__smartArrayFlags = {};
  7800. }
  7801. value.__smartArrayFlags[this._id] = this._duplicateId;
  7802. };
  7803. SmartArrayNoDuplicate.prototype.pushNoDuplicate = function (value) {
  7804. if (value.__smartArrayFlags && value.__smartArrayFlags[this._id] === this._duplicateId) {
  7805. return false;
  7806. }
  7807. this.push(value);
  7808. return true;
  7809. };
  7810. SmartArrayNoDuplicate.prototype.reset = function () {
  7811. _super.prototype.reset.call(this);
  7812. this._duplicateId++;
  7813. };
  7814. SmartArrayNoDuplicate.prototype.concatWithNoDuplicate = function (array) {
  7815. if (array.length === 0) {
  7816. return;
  7817. }
  7818. if (this.length + array.length > this.data.length) {
  7819. this.data.length = (this.length + array.length) * 2;
  7820. }
  7821. for (var index = 0; index < array.length; index++) {
  7822. var item = (array.data || array)[index];
  7823. this.pushNoDuplicate(item);
  7824. }
  7825. };
  7826. return SmartArrayNoDuplicate;
  7827. }(SmartArray));
  7828. BABYLON.SmartArrayNoDuplicate = SmartArrayNoDuplicate;
  7829. })(BABYLON || (BABYLON = {}));
  7830. //# sourceMappingURL=babylon.smartArray.js.map
  7831. "use strict";
  7832. var BABYLON;
  7833. (function (BABYLON) {
  7834. // See https://stackoverflow.com/questions/12915412/how-do-i-extend-a-host-object-e-g-error-in-typescript
  7835. // and https://github.com/Microsoft/TypeScript/wiki/Breaking-Changes#extending-built-ins-like-error-array-and-map-may-no-longer-work
  7836. var LoadFileError = /** @class */ (function (_super) {
  7837. __extends(LoadFileError, _super);
  7838. function LoadFileError(message, request) {
  7839. var _this = _super.call(this, message) || this;
  7840. _this.request = request;
  7841. _this.name = "LoadFileError";
  7842. LoadFileError._setPrototypeOf(_this, LoadFileError.prototype);
  7843. return _this;
  7844. }
  7845. // Polyfill for Object.setPrototypeOf if necessary.
  7846. LoadFileError._setPrototypeOf = Object.setPrototypeOf || (function (o, proto) { o.__proto__ = proto; return o; });
  7847. return LoadFileError;
  7848. }(Error));
  7849. BABYLON.LoadFileError = LoadFileError;
  7850. var RetryStrategy = /** @class */ (function () {
  7851. function RetryStrategy() {
  7852. }
  7853. RetryStrategy.ExponentialBackoff = function (maxRetries, baseInterval) {
  7854. if (maxRetries === void 0) { maxRetries = 3; }
  7855. if (baseInterval === void 0) { baseInterval = 500; }
  7856. return function (url, request, retryIndex) {
  7857. if (request.status !== 0 || retryIndex >= maxRetries || url.indexOf("file:") !== -1) {
  7858. return -1;
  7859. }
  7860. return Math.pow(2, retryIndex) * baseInterval;
  7861. };
  7862. };
  7863. return RetryStrategy;
  7864. }());
  7865. BABYLON.RetryStrategy = RetryStrategy;
  7866. // Screenshots
  7867. var screenshotCanvas;
  7868. var cloneValue = function (source, destinationObject) {
  7869. if (!source)
  7870. return null;
  7871. if (source instanceof BABYLON.Mesh) {
  7872. return null;
  7873. }
  7874. if (source instanceof BABYLON.SubMesh) {
  7875. return source.clone(destinationObject);
  7876. }
  7877. else if (source.clone) {
  7878. return source.clone();
  7879. }
  7880. return null;
  7881. };
  7882. var Tools = /** @class */ (function () {
  7883. function Tools() {
  7884. }
  7885. /**
  7886. * Interpolates between a and b via alpha
  7887. * @param a The lower value (returned when alpha = 0)
  7888. * @param b The upper value (returned when alpha = 1)
  7889. * @param alpha The interpolation-factor
  7890. * @return The mixed value
  7891. */
  7892. Tools.Mix = function (a, b, alpha) {
  7893. return a * (1 - alpha) + b * alpha;
  7894. };
  7895. Tools.Instantiate = function (className) {
  7896. if (Tools.RegisteredExternalClasses && Tools.RegisteredExternalClasses[className]) {
  7897. return Tools.RegisteredExternalClasses[className];
  7898. }
  7899. var arr = className.split(".");
  7900. var fn = (window || this);
  7901. for (var i = 0, len = arr.length; i < len; i++) {
  7902. fn = fn[arr[i]];
  7903. }
  7904. if (typeof fn !== "function") {
  7905. return null;
  7906. }
  7907. return fn;
  7908. };
  7909. /**
  7910. * Provides a slice function that will work even on IE
  7911. * @param data defines the array to slice
  7912. * @returns the new sliced array
  7913. */
  7914. Tools.Slice = function (data) {
  7915. if (data.slice) {
  7916. return data.slice();
  7917. }
  7918. return Array.prototype.slice.call(data);
  7919. };
  7920. Tools.SetImmediate = function (action) {
  7921. if (window.setImmediate) {
  7922. window.setImmediate(action);
  7923. }
  7924. else {
  7925. setTimeout(action, 1);
  7926. }
  7927. };
  7928. Tools.IsExponentOfTwo = function (value) {
  7929. var count = 1;
  7930. do {
  7931. count *= 2;
  7932. } while (count < value);
  7933. return count === value;
  7934. };
  7935. /**
  7936. * Find the next highest power of two.
  7937. * @param x Number to start search from.
  7938. * @return Next highest power of two.
  7939. */
  7940. Tools.CeilingPOT = function (x) {
  7941. x--;
  7942. x |= x >> 1;
  7943. x |= x >> 2;
  7944. x |= x >> 4;
  7945. x |= x >> 8;
  7946. x |= x >> 16;
  7947. x++;
  7948. return x;
  7949. };
  7950. /**
  7951. * Find the next lowest power of two.
  7952. * @param x Number to start search from.
  7953. * @return Next lowest power of two.
  7954. */
  7955. Tools.FloorPOT = function (x) {
  7956. x = x | (x >> 1);
  7957. x = x | (x >> 2);
  7958. x = x | (x >> 4);
  7959. x = x | (x >> 8);
  7960. x = x | (x >> 16);
  7961. return x - (x >> 1);
  7962. };
  7963. /**
  7964. * Find the nearest power of two.
  7965. * @param x Number to start search from.
  7966. * @return Next nearest power of two.
  7967. */
  7968. Tools.NearestPOT = function (x) {
  7969. var c = Tools.CeilingPOT(x);
  7970. var f = Tools.FloorPOT(x);
  7971. return (c - x) > (x - f) ? f : c;
  7972. };
  7973. Tools.GetExponentOfTwo = function (value, max, mode) {
  7974. if (mode === void 0) { mode = BABYLON.Engine.SCALEMODE_NEAREST; }
  7975. var pot;
  7976. switch (mode) {
  7977. case BABYLON.Engine.SCALEMODE_FLOOR:
  7978. pot = Tools.FloorPOT(value);
  7979. break;
  7980. case BABYLON.Engine.SCALEMODE_NEAREST:
  7981. pot = Tools.NearestPOT(value);
  7982. break;
  7983. case BABYLON.Engine.SCALEMODE_CEILING:
  7984. default:
  7985. pot = Tools.CeilingPOT(value);
  7986. break;
  7987. }
  7988. return Math.min(pot, max);
  7989. };
  7990. Tools.GetFilename = function (path) {
  7991. var index = path.lastIndexOf("/");
  7992. if (index < 0)
  7993. return path;
  7994. return path.substring(index + 1);
  7995. };
  7996. /**
  7997. * Extracts the "folder" part of a path (everything before the filename).
  7998. * @param uri The URI to extract the info from
  7999. * @param returnUnchangedIfNoSlash Do not touch the URI if no slashes are present
  8000. * @returns The "folder" part of the path
  8001. */
  8002. Tools.GetFolderPath = function (uri, returnUnchangedIfNoSlash) {
  8003. if (returnUnchangedIfNoSlash === void 0) { returnUnchangedIfNoSlash = false; }
  8004. var index = uri.lastIndexOf("/");
  8005. if (index < 0) {
  8006. if (returnUnchangedIfNoSlash) {
  8007. return uri;
  8008. }
  8009. return "";
  8010. }
  8011. return uri.substring(0, index + 1);
  8012. };
  8013. Tools.GetDOMTextContent = function (element) {
  8014. var result = "";
  8015. var child = element.firstChild;
  8016. while (child) {
  8017. if (child.nodeType === 3) {
  8018. result += child.textContent;
  8019. }
  8020. child = child.nextSibling;
  8021. }
  8022. return result;
  8023. };
  8024. Tools.ToDegrees = function (angle) {
  8025. return angle * 180 / Math.PI;
  8026. };
  8027. Tools.ToRadians = function (angle) {
  8028. return angle * Math.PI / 180;
  8029. };
  8030. Tools.EncodeArrayBufferTobase64 = function (buffer) {
  8031. var keyStr = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";
  8032. var output = "";
  8033. var chr1, chr2, chr3, enc1, enc2, enc3, enc4;
  8034. var i = 0;
  8035. var bytes = new Uint8Array(buffer);
  8036. while (i < bytes.length) {
  8037. chr1 = bytes[i++];
  8038. chr2 = i < bytes.length ? bytes[i++] : Number.NaN; // Not sure if the index
  8039. chr3 = i < bytes.length ? bytes[i++] : Number.NaN; // checks are needed here
  8040. enc1 = chr1 >> 2;
  8041. enc2 = ((chr1 & 3) << 4) | (chr2 >> 4);
  8042. enc3 = ((chr2 & 15) << 2) | (chr3 >> 6);
  8043. enc4 = chr3 & 63;
  8044. if (isNaN(chr2)) {
  8045. enc3 = enc4 = 64;
  8046. }
  8047. else if (isNaN(chr3)) {
  8048. enc4 = 64;
  8049. }
  8050. output += keyStr.charAt(enc1) + keyStr.charAt(enc2) +
  8051. keyStr.charAt(enc3) + keyStr.charAt(enc4);
  8052. }
  8053. return "data:image/png;base64," + output;
  8054. };
  8055. Tools.ExtractMinAndMaxIndexed = function (positions, indices, indexStart, indexCount, bias) {
  8056. if (bias === void 0) { bias = null; }
  8057. var minimum = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  8058. var maximum = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  8059. for (var index = indexStart; index < indexStart + indexCount; index++) {
  8060. var current = new BABYLON.Vector3(positions[indices[index] * 3], positions[indices[index] * 3 + 1], positions[indices[index] * 3 + 2]);
  8061. minimum = BABYLON.Vector3.Minimize(current, minimum);
  8062. maximum = BABYLON.Vector3.Maximize(current, maximum);
  8063. }
  8064. if (bias) {
  8065. minimum.x -= minimum.x * bias.x + bias.y;
  8066. minimum.y -= minimum.y * bias.x + bias.y;
  8067. minimum.z -= minimum.z * bias.x + bias.y;
  8068. maximum.x += maximum.x * bias.x + bias.y;
  8069. maximum.y += maximum.y * bias.x + bias.y;
  8070. maximum.z += maximum.z * bias.x + bias.y;
  8071. }
  8072. return {
  8073. minimum: minimum,
  8074. maximum: maximum
  8075. };
  8076. };
  8077. Tools.ExtractMinAndMax = function (positions, start, count, bias, stride) {
  8078. if (bias === void 0) { bias = null; }
  8079. var minimum = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  8080. var maximum = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  8081. if (!stride) {
  8082. stride = 3;
  8083. }
  8084. for (var index = start; index < start + count; index++) {
  8085. var current = new BABYLON.Vector3(positions[index * stride], positions[index * stride + 1], positions[index * stride + 2]);
  8086. minimum = BABYLON.Vector3.Minimize(current, minimum);
  8087. maximum = BABYLON.Vector3.Maximize(current, maximum);
  8088. }
  8089. if (bias) {
  8090. minimum.x -= minimum.x * bias.x + bias.y;
  8091. minimum.y -= minimum.y * bias.x + bias.y;
  8092. minimum.z -= minimum.z * bias.x + bias.y;
  8093. maximum.x += maximum.x * bias.x + bias.y;
  8094. maximum.y += maximum.y * bias.x + bias.y;
  8095. maximum.z += maximum.z * bias.x + bias.y;
  8096. }
  8097. return {
  8098. minimum: minimum,
  8099. maximum: maximum
  8100. };
  8101. };
  8102. Tools.Vector2ArrayFeeder = function (array) {
  8103. return function (index) {
  8104. var isFloatArray = (array.BYTES_PER_ELEMENT !== undefined);
  8105. var length = isFloatArray ? array.length / 2 : array.length;
  8106. if (index >= length) {
  8107. return null;
  8108. }
  8109. if (isFloatArray) {
  8110. var fa = array;
  8111. return new BABYLON.Vector2(fa[index * 2 + 0], fa[index * 2 + 1]);
  8112. }
  8113. var a = array;
  8114. return a[index];
  8115. };
  8116. };
  8117. Tools.ExtractMinAndMaxVector2 = function (feeder, bias) {
  8118. if (bias === void 0) { bias = null; }
  8119. var minimum = new BABYLON.Vector2(Number.MAX_VALUE, Number.MAX_VALUE);
  8120. var maximum = new BABYLON.Vector2(-Number.MAX_VALUE, -Number.MAX_VALUE);
  8121. var i = 0;
  8122. var cur = feeder(i++);
  8123. while (cur) {
  8124. minimum = BABYLON.Vector2.Minimize(cur, minimum);
  8125. maximum = BABYLON.Vector2.Maximize(cur, maximum);
  8126. cur = feeder(i++);
  8127. }
  8128. if (bias) {
  8129. minimum.x -= minimum.x * bias.x + bias.y;
  8130. minimum.y -= minimum.y * bias.x + bias.y;
  8131. maximum.x += maximum.x * bias.x + bias.y;
  8132. maximum.y += maximum.y * bias.x + bias.y;
  8133. }
  8134. return {
  8135. minimum: minimum,
  8136. maximum: maximum
  8137. };
  8138. };
  8139. Tools.MakeArray = function (obj, allowsNullUndefined) {
  8140. if (allowsNullUndefined !== true && (obj === undefined || obj == null))
  8141. return null;
  8142. return Array.isArray(obj) ? obj : [obj];
  8143. };
  8144. // Misc.
  8145. Tools.GetPointerPrefix = function () {
  8146. var eventPrefix = "pointer";
  8147. // Check if pointer events are supported
  8148. if (Tools.IsWindowObjectExist() && !window.PointerEvent && !navigator.pointerEnabled) {
  8149. eventPrefix = "mouse";
  8150. }
  8151. return eventPrefix;
  8152. };
  8153. /**
  8154. * @param func - the function to be called
  8155. * @param requester - the object that will request the next frame. Falls back to window.
  8156. */
  8157. Tools.QueueNewFrame = function (func, requester) {
  8158. if (!Tools.IsWindowObjectExist()) {
  8159. return setTimeout(func, 16);
  8160. }
  8161. if (!requester) {
  8162. requester = window;
  8163. }
  8164. if (requester.requestAnimationFrame) {
  8165. return requester.requestAnimationFrame(func);
  8166. }
  8167. else if (requester.msRequestAnimationFrame) {
  8168. return requester.msRequestAnimationFrame(func);
  8169. }
  8170. else if (requester.webkitRequestAnimationFrame) {
  8171. return requester.webkitRequestAnimationFrame(func);
  8172. }
  8173. else if (requester.mozRequestAnimationFrame) {
  8174. return requester.mozRequestAnimationFrame(func);
  8175. }
  8176. else if (requester.oRequestAnimationFrame) {
  8177. return requester.oRequestAnimationFrame(func);
  8178. }
  8179. else {
  8180. return window.setTimeout(func, 16);
  8181. }
  8182. };
  8183. Tools.RequestFullscreen = function (element) {
  8184. var requestFunction = element.requestFullscreen || element.msRequestFullscreen || element.webkitRequestFullscreen || element.mozRequestFullScreen;
  8185. if (!requestFunction)
  8186. return;
  8187. requestFunction.call(element);
  8188. };
  8189. Tools.ExitFullscreen = function () {
  8190. if (document.exitFullscreen) {
  8191. document.exitFullscreen();
  8192. }
  8193. else if (document.mozCancelFullScreen) {
  8194. document.mozCancelFullScreen();
  8195. }
  8196. else if (document.webkitCancelFullScreen) {
  8197. document.webkitCancelFullScreen();
  8198. }
  8199. else if (document.msCancelFullScreen) {
  8200. document.msCancelFullScreen();
  8201. }
  8202. };
  8203. Tools.SetCorsBehavior = function (url, element) {
  8204. if (url && url.indexOf("data:") === 0) {
  8205. return;
  8206. }
  8207. if (Tools.CorsBehavior) {
  8208. if (typeof (Tools.CorsBehavior) === 'string' || Tools.CorsBehavior instanceof String) {
  8209. element.crossOrigin = Tools.CorsBehavior;
  8210. }
  8211. else {
  8212. var result = Tools.CorsBehavior(url);
  8213. if (result) {
  8214. element.crossOrigin = result;
  8215. }
  8216. }
  8217. }
  8218. };
  8219. // External files
  8220. Tools.CleanUrl = function (url) {
  8221. url = url.replace(/#/mg, "%23");
  8222. return url;
  8223. };
  8224. Tools.LoadImage = function (url, onLoad, onError, database) {
  8225. if (url instanceof ArrayBuffer) {
  8226. url = Tools.EncodeArrayBufferTobase64(url);
  8227. }
  8228. url = Tools.CleanUrl(url);
  8229. url = Tools.PreprocessUrl(url);
  8230. var img = new Image();
  8231. Tools.SetCorsBehavior(url, img);
  8232. var loadHandler = function () {
  8233. img.removeEventListener("load", loadHandler);
  8234. img.removeEventListener("error", errorHandler);
  8235. onLoad(img);
  8236. };
  8237. var errorHandler = function (err) {
  8238. img.removeEventListener("load", loadHandler);
  8239. img.removeEventListener("error", errorHandler);
  8240. Tools.Error("Error while trying to load image: " + url);
  8241. if (onError) {
  8242. onError("Error while trying to load image: " + url, err);
  8243. }
  8244. };
  8245. img.addEventListener("load", loadHandler);
  8246. img.addEventListener("error", errorHandler);
  8247. var noIndexedDB = function () {
  8248. img.src = url;
  8249. };
  8250. var loadFromIndexedDB = function () {
  8251. if (database) {
  8252. database.loadImageFromDB(url, img);
  8253. }
  8254. };
  8255. //ANY database to do!
  8256. if (url.substr(0, 5) !== "data:" && database && database.enableTexturesOffline && BABYLON.Database.IsUASupportingBlobStorage) {
  8257. database.openAsync(loadFromIndexedDB, noIndexedDB);
  8258. }
  8259. else {
  8260. if (url.indexOf("file:") !== -1) {
  8261. var textureName = decodeURIComponent(url.substring(5).toLowerCase());
  8262. if (BABYLON.FilesInput.FilesToLoad[textureName]) {
  8263. try {
  8264. var blobURL;
  8265. try {
  8266. blobURL = URL.createObjectURL(BABYLON.FilesInput.FilesToLoad[textureName], { oneTimeOnly: true });
  8267. }
  8268. catch (ex) {
  8269. // Chrome doesn't support oneTimeOnly parameter
  8270. blobURL = URL.createObjectURL(BABYLON.FilesInput.FilesToLoad[textureName]);
  8271. }
  8272. img.src = blobURL;
  8273. }
  8274. catch (e) {
  8275. img.src = "";
  8276. }
  8277. return img;
  8278. }
  8279. }
  8280. noIndexedDB();
  8281. }
  8282. return img;
  8283. };
  8284. Tools.LoadFile = function (url, onSuccess, onProgress, database, useArrayBuffer, onError) {
  8285. url = Tools.CleanUrl(url);
  8286. url = Tools.PreprocessUrl(url);
  8287. // If file and file input are set
  8288. if (url.indexOf("file:") !== -1) {
  8289. var fileName = decodeURIComponent(url.substring(5).toLowerCase());
  8290. if (BABYLON.FilesInput.FilesToLoad[fileName]) {
  8291. return Tools.ReadFile(BABYLON.FilesInput.FilesToLoad[fileName], onSuccess, onProgress, useArrayBuffer);
  8292. }
  8293. }
  8294. var loadUrl = Tools.BaseUrl + url;
  8295. var aborted = false;
  8296. var fileRequest = {
  8297. onCompleteObservable: new BABYLON.Observable(),
  8298. abort: function () { return aborted = true; },
  8299. };
  8300. var requestFile = function () {
  8301. var request = new XMLHttpRequest();
  8302. var retryHandle = null;
  8303. fileRequest.abort = function () {
  8304. aborted = true;
  8305. if (request.readyState !== (XMLHttpRequest.DONE || 4)) {
  8306. request.abort();
  8307. }
  8308. if (retryHandle !== null) {
  8309. clearTimeout(retryHandle);
  8310. retryHandle = null;
  8311. }
  8312. };
  8313. var retryLoop = function (retryIndex) {
  8314. request.open('GET', loadUrl, true);
  8315. if (useArrayBuffer) {
  8316. request.responseType = "arraybuffer";
  8317. }
  8318. if (onProgress) {
  8319. request.addEventListener("progress", onProgress);
  8320. }
  8321. var onLoadEnd = function () {
  8322. request.removeEventListener("loadend", onLoadEnd);
  8323. fileRequest.onCompleteObservable.notifyObservers(fileRequest);
  8324. fileRequest.onCompleteObservable.clear();
  8325. };
  8326. request.addEventListener("loadend", onLoadEnd);
  8327. var onReadyStateChange = function () {
  8328. if (aborted) {
  8329. return;
  8330. }
  8331. // In case of undefined state in some browsers.
  8332. if (request.readyState === (XMLHttpRequest.DONE || 4)) {
  8333. // Some browsers have issues where onreadystatechange can be called multiple times with the same value.
  8334. request.removeEventListener("readystatechange", onReadyStateChange);
  8335. if (request.status >= 200 && request.status < 300 || (!Tools.IsWindowObjectExist() && (request.status === 0))) {
  8336. onSuccess(!useArrayBuffer ? request.responseText : request.response, request.responseURL);
  8337. return;
  8338. }
  8339. var retryStrategy = Tools.DefaultRetryStrategy;
  8340. if (retryStrategy) {
  8341. var waitTime = retryStrategy(loadUrl, request, retryIndex);
  8342. if (waitTime !== -1) {
  8343. // Prevent the request from completing for retry.
  8344. request.removeEventListener("loadend", onLoadEnd);
  8345. request = new XMLHttpRequest();
  8346. retryHandle = setTimeout(function () { return retryLoop(retryIndex + 1); }, waitTime);
  8347. return;
  8348. }
  8349. }
  8350. var e = new LoadFileError("Error status: " + request.status + " " + request.statusText + " - Unable to load " + loadUrl, request);
  8351. if (onError) {
  8352. onError(request, e);
  8353. }
  8354. else {
  8355. throw e;
  8356. }
  8357. }
  8358. };
  8359. request.addEventListener("readystatechange", onReadyStateChange);
  8360. request.send();
  8361. };
  8362. retryLoop(0);
  8363. };
  8364. // Caching all files
  8365. if (database && database.enableSceneOffline) {
  8366. var noIndexedDB_1 = function () {
  8367. if (!aborted) {
  8368. requestFile();
  8369. }
  8370. };
  8371. var loadFromIndexedDB = function () {
  8372. // TODO: database needs to support aborting and should return a IFileRequest
  8373. if (aborted) {
  8374. return;
  8375. }
  8376. if (database) {
  8377. database.loadFileFromDB(url, function (data) {
  8378. if (!aborted) {
  8379. onSuccess(data);
  8380. }
  8381. fileRequest.onCompleteObservable.notifyObservers(fileRequest);
  8382. }, onProgress ? function (event) {
  8383. if (!aborted) {
  8384. onProgress(event);
  8385. }
  8386. } : undefined, noIndexedDB_1, useArrayBuffer);
  8387. }
  8388. };
  8389. database.openAsync(loadFromIndexedDB, noIndexedDB_1);
  8390. }
  8391. else {
  8392. requestFile();
  8393. }
  8394. return fileRequest;
  8395. };
  8396. /**
  8397. * Load a script (identified by an url). When the url returns, the
  8398. * content of this file is added into a new script element, attached to the DOM (body element)
  8399. */
  8400. Tools.LoadScript = function (scriptUrl, onSuccess, onError) {
  8401. var head = document.getElementsByTagName('head')[0];
  8402. var script = document.createElement('script');
  8403. script.type = 'text/javascript';
  8404. script.src = scriptUrl;
  8405. script.onload = function () {
  8406. if (onSuccess) {
  8407. onSuccess();
  8408. }
  8409. };
  8410. script.onerror = function (e) {
  8411. if (onError) {
  8412. onError("Unable to load script", e);
  8413. }
  8414. };
  8415. head.appendChild(script);
  8416. };
  8417. Tools.ReadFileAsDataURL = function (fileToLoad, callback, progressCallback) {
  8418. var reader = new FileReader();
  8419. var request = {
  8420. onCompleteObservable: new BABYLON.Observable(),
  8421. abort: function () { return reader.abort(); },
  8422. };
  8423. reader.onloadend = function (e) {
  8424. request.onCompleteObservable.notifyObservers(request);
  8425. };
  8426. reader.onload = function (e) {
  8427. //target doesn't have result from ts 1.3
  8428. callback(e.target['result']);
  8429. };
  8430. reader.onprogress = progressCallback;
  8431. reader.readAsDataURL(fileToLoad);
  8432. return request;
  8433. };
  8434. Tools.ReadFile = function (fileToLoad, callback, progressCallBack, useArrayBuffer) {
  8435. var reader = new FileReader();
  8436. var request = {
  8437. onCompleteObservable: new BABYLON.Observable(),
  8438. abort: function () { return reader.abort(); },
  8439. };
  8440. reader.onloadend = function (e) { return request.onCompleteObservable.notifyObservers(request); };
  8441. reader.onerror = function (e) {
  8442. Tools.Log("Error while reading file: " + fileToLoad.name);
  8443. callback(JSON.stringify({ autoClear: true, clearColor: [1, 0, 0], ambientColor: [0, 0, 0], gravity: [0, -9.807, 0], meshes: [], cameras: [], lights: [] }));
  8444. };
  8445. reader.onload = function (e) {
  8446. //target doesn't have result from ts 1.3
  8447. callback(e.target['result']);
  8448. };
  8449. if (progressCallBack) {
  8450. reader.onprogress = progressCallBack;
  8451. }
  8452. if (!useArrayBuffer) {
  8453. // Asynchronous read
  8454. reader.readAsText(fileToLoad);
  8455. }
  8456. else {
  8457. reader.readAsArrayBuffer(fileToLoad);
  8458. }
  8459. return request;
  8460. };
  8461. //returns a downloadable url to a file content.
  8462. Tools.FileAsURL = function (content) {
  8463. var fileBlob = new Blob([content]);
  8464. var url = window.URL || window.webkitURL;
  8465. var link = url.createObjectURL(fileBlob);
  8466. return link;
  8467. };
  8468. // Misc.
  8469. Tools.Format = function (value, decimals) {
  8470. if (decimals === void 0) { decimals = 2; }
  8471. return value.toFixed(decimals);
  8472. };
  8473. Tools.CheckExtends = function (v, min, max) {
  8474. if (v.x < min.x)
  8475. min.x = v.x;
  8476. if (v.y < min.y)
  8477. min.y = v.y;
  8478. if (v.z < min.z)
  8479. min.z = v.z;
  8480. if (v.x > max.x)
  8481. max.x = v.x;
  8482. if (v.y > max.y)
  8483. max.y = v.y;
  8484. if (v.z > max.z)
  8485. max.z = v.z;
  8486. };
  8487. Tools.DeepCopy = function (source, destination, doNotCopyList, mustCopyList) {
  8488. for (var prop in source) {
  8489. if (prop[0] === "_" && (!mustCopyList || mustCopyList.indexOf(prop) === -1)) {
  8490. continue;
  8491. }
  8492. if (doNotCopyList && doNotCopyList.indexOf(prop) !== -1) {
  8493. continue;
  8494. }
  8495. var sourceValue = source[prop];
  8496. var typeOfSourceValue = typeof sourceValue;
  8497. if (typeOfSourceValue === "function") {
  8498. continue;
  8499. }
  8500. try {
  8501. if (typeOfSourceValue === "object") {
  8502. if (sourceValue instanceof Array) {
  8503. destination[prop] = [];
  8504. if (sourceValue.length > 0) {
  8505. if (typeof sourceValue[0] == "object") {
  8506. for (var index = 0; index < sourceValue.length; index++) {
  8507. var clonedValue = cloneValue(sourceValue[index], destination);
  8508. if (destination[prop].indexOf(clonedValue) === -1) {
  8509. destination[prop].push(clonedValue);
  8510. }
  8511. }
  8512. }
  8513. else {
  8514. destination[prop] = sourceValue.slice(0);
  8515. }
  8516. }
  8517. }
  8518. else {
  8519. destination[prop] = cloneValue(sourceValue, destination);
  8520. }
  8521. }
  8522. else {
  8523. destination[prop] = sourceValue;
  8524. }
  8525. }
  8526. catch (e) {
  8527. // Just ignore error (it could be because of a read-only property)
  8528. }
  8529. }
  8530. };
  8531. Tools.IsEmpty = function (obj) {
  8532. for (var i in obj) {
  8533. if (obj.hasOwnProperty(i)) {
  8534. return false;
  8535. }
  8536. }
  8537. return true;
  8538. };
  8539. Tools.RegisterTopRootEvents = function (events) {
  8540. for (var index = 0; index < events.length; index++) {
  8541. var event = events[index];
  8542. window.addEventListener(event.name, event.handler, false);
  8543. try {
  8544. if (window.parent) {
  8545. window.parent.addEventListener(event.name, event.handler, false);
  8546. }
  8547. }
  8548. catch (e) {
  8549. // Silently fails...
  8550. }
  8551. }
  8552. };
  8553. Tools.UnregisterTopRootEvents = function (events) {
  8554. for (var index = 0; index < events.length; index++) {
  8555. var event = events[index];
  8556. window.removeEventListener(event.name, event.handler);
  8557. try {
  8558. if (window.parent) {
  8559. window.parent.removeEventListener(event.name, event.handler);
  8560. }
  8561. }
  8562. catch (e) {
  8563. // Silently fails...
  8564. }
  8565. }
  8566. };
  8567. Tools.DumpFramebuffer = function (width, height, engine, successCallback, mimeType, fileName) {
  8568. if (mimeType === void 0) { mimeType = "image/png"; }
  8569. // Read the contents of the framebuffer
  8570. var numberOfChannelsByLine = width * 4;
  8571. var halfHeight = height / 2;
  8572. //Reading datas from WebGL
  8573. var data = engine.readPixels(0, 0, width, height);
  8574. //To flip image on Y axis.
  8575. for (var i = 0; i < halfHeight; i++) {
  8576. for (var j = 0; j < numberOfChannelsByLine; j++) {
  8577. var currentCell = j + i * numberOfChannelsByLine;
  8578. var targetLine = height - i - 1;
  8579. var targetCell = j + targetLine * numberOfChannelsByLine;
  8580. var temp = data[currentCell];
  8581. data[currentCell] = data[targetCell];
  8582. data[targetCell] = temp;
  8583. }
  8584. }
  8585. // Create a 2D canvas to store the result
  8586. if (!screenshotCanvas) {
  8587. screenshotCanvas = document.createElement('canvas');
  8588. }
  8589. screenshotCanvas.width = width;
  8590. screenshotCanvas.height = height;
  8591. var context = screenshotCanvas.getContext('2d');
  8592. if (context) {
  8593. // Copy the pixels to a 2D canvas
  8594. var imageData = context.createImageData(width, height);
  8595. var castData = (imageData.data);
  8596. castData.set(data);
  8597. context.putImageData(imageData, 0, 0);
  8598. Tools.EncodeScreenshotCanvasData(successCallback, mimeType, fileName);
  8599. }
  8600. };
  8601. Tools.EncodeScreenshotCanvasData = function (successCallback, mimeType, fileName) {
  8602. if (mimeType === void 0) { mimeType = "image/png"; }
  8603. var base64Image = screenshotCanvas.toDataURL(mimeType);
  8604. if (successCallback) {
  8605. successCallback(base64Image);
  8606. }
  8607. else {
  8608. // We need HTMLCanvasElement.toBlob for HD screenshots
  8609. if (!screenshotCanvas.toBlob) {
  8610. // low performance polyfill based on toDataURL (https://developer.mozilla.org/en-US/docs/Web/API/HTMLCanvasElement/toBlob)
  8611. screenshotCanvas.toBlob = function (callback, type, quality) {
  8612. var _this = this;
  8613. setTimeout(function () {
  8614. var binStr = atob(_this.toDataURL(type, quality).split(',')[1]), len = binStr.length, arr = new Uint8Array(len);
  8615. for (var i = 0; i < len; i++) {
  8616. arr[i] = binStr.charCodeAt(i);
  8617. }
  8618. callback(new Blob([arr], { type: type || 'image/png' }));
  8619. });
  8620. };
  8621. }
  8622. screenshotCanvas.toBlob(function (blob) {
  8623. var url = URL.createObjectURL(blob);
  8624. //Creating a link if the browser have the download attribute on the a tag, to automatically start download generated image.
  8625. if (("download" in document.createElement("a"))) {
  8626. var a = window.document.createElement("a");
  8627. a.href = url;
  8628. if (fileName) {
  8629. a.setAttribute("download", fileName);
  8630. }
  8631. else {
  8632. var date = new Date();
  8633. var stringDate = (date.getFullYear() + "-" + (date.getMonth() + 1)).slice(-2) + "-" + date.getDate() + "_" + date.getHours() + "-" + ('0' + date.getMinutes()).slice(-2);
  8634. a.setAttribute("download", "screenshot_" + stringDate + ".png");
  8635. }
  8636. window.document.body.appendChild(a);
  8637. a.addEventListener("click", function () {
  8638. if (a.parentElement) {
  8639. a.parentElement.removeChild(a);
  8640. }
  8641. });
  8642. a.click();
  8643. }
  8644. else {
  8645. var newWindow = window.open("");
  8646. if (!newWindow)
  8647. return;
  8648. var img = newWindow.document.createElement("img");
  8649. img.onload = function () {
  8650. // no longer need to read the blob so it's revoked
  8651. URL.revokeObjectURL(url);
  8652. };
  8653. img.src = url;
  8654. newWindow.document.body.appendChild(img);
  8655. }
  8656. });
  8657. }
  8658. };
  8659. Tools.CreateScreenshot = function (engine, camera, size, successCallback, mimeType) {
  8660. if (mimeType === void 0) { mimeType = "image/png"; }
  8661. var width;
  8662. var height;
  8663. // If a precision value is specified
  8664. if (size.precision) {
  8665. width = Math.round(engine.getRenderWidth() * size.precision);
  8666. height = Math.round(width / engine.getAspectRatio(camera));
  8667. }
  8668. else if (size.width && size.height) {
  8669. width = size.width;
  8670. height = size.height;
  8671. }
  8672. else if (size.width && !size.height) {
  8673. width = size.width;
  8674. height = Math.round(width / engine.getAspectRatio(camera));
  8675. }
  8676. else if (size.height && !size.width) {
  8677. height = size.height;
  8678. width = Math.round(height * engine.getAspectRatio(camera));
  8679. }
  8680. else if (!isNaN(size)) {
  8681. height = size;
  8682. width = size;
  8683. }
  8684. else {
  8685. Tools.Error("Invalid 'size' parameter !");
  8686. return;
  8687. }
  8688. if (!screenshotCanvas) {
  8689. screenshotCanvas = document.createElement('canvas');
  8690. }
  8691. screenshotCanvas.width = width;
  8692. screenshotCanvas.height = height;
  8693. var renderContext = screenshotCanvas.getContext("2d");
  8694. var ratio = engine.getRenderWidth() / engine.getRenderHeight();
  8695. var newWidth = width;
  8696. var newHeight = newWidth / ratio;
  8697. if (newHeight > height) {
  8698. newHeight = height;
  8699. newWidth = newHeight * ratio;
  8700. }
  8701. var offsetX = Math.max(0, width - newWidth) / 2;
  8702. var offsetY = Math.max(0, height - newHeight) / 2;
  8703. var renderingCanvas = engine.getRenderingCanvas();
  8704. if (renderContext && renderingCanvas) {
  8705. renderContext.drawImage(renderingCanvas, offsetX, offsetY, newWidth, newHeight);
  8706. }
  8707. Tools.EncodeScreenshotCanvasData(successCallback, mimeType);
  8708. };
  8709. /**
  8710. * Generates an image screenshot from the specified camera.
  8711. *
  8712. * @param engine The engine to use for rendering
  8713. * @param camera The camera to use for rendering
  8714. * @param size This parameter can be set to a single number or to an object with the
  8715. * following (optional) properties: precision, width, height. If a single number is passed,
  8716. * it will be used for both width and height. If an object is passed, the screenshot size
  8717. * will be derived from the parameters. The precision property is a multiplier allowing
  8718. * rendering at a higher or lower resolution.
  8719. * @param successCallback The callback receives a single parameter which contains the
  8720. * screenshot as a string of base64-encoded characters. This string can be assigned to the
  8721. * src parameter of an <img> to display it.
  8722. * @param mimeType The MIME type of the screenshot image (default: image/png).
  8723. * Check your browser for supported MIME types.
  8724. * @param samples Texture samples (default: 1)
  8725. * @param antialiasing Whether antialiasing should be turned on or not (default: false)
  8726. * @param fileName A name for for the downloaded file.
  8727. * @constructor
  8728. */
  8729. Tools.CreateScreenshotUsingRenderTarget = function (engine, camera, size, successCallback, mimeType, samples, antialiasing, fileName) {
  8730. if (mimeType === void 0) { mimeType = "image/png"; }
  8731. if (samples === void 0) { samples = 1; }
  8732. if (antialiasing === void 0) { antialiasing = false; }
  8733. var width;
  8734. var height;
  8735. //If a precision value is specified
  8736. if (size.precision) {
  8737. width = Math.round(engine.getRenderWidth() * size.precision);
  8738. height = Math.round(width / engine.getAspectRatio(camera));
  8739. size = { width: width, height: height };
  8740. }
  8741. else if (size.width && size.height) {
  8742. width = size.width;
  8743. height = size.height;
  8744. }
  8745. else if (size.width && !size.height) {
  8746. width = size.width;
  8747. height = Math.round(width / engine.getAspectRatio(camera));
  8748. size = { width: width, height: height };
  8749. }
  8750. else if (size.height && !size.width) {
  8751. height = size.height;
  8752. width = Math.round(height * engine.getAspectRatio(camera));
  8753. size = { width: width, height: height };
  8754. }
  8755. else if (!isNaN(size)) {
  8756. height = size;
  8757. width = size;
  8758. }
  8759. else {
  8760. Tools.Error("Invalid 'size' parameter !");
  8761. return;
  8762. }
  8763. var scene = camera.getScene();
  8764. var previousCamera = null;
  8765. if (scene.activeCamera !== camera) {
  8766. previousCamera = scene.activeCamera;
  8767. scene.activeCamera = camera;
  8768. }
  8769. //At this point size can be a number, or an object (according to engine.prototype.createRenderTargetTexture method)
  8770. var texture = new BABYLON.RenderTargetTexture("screenShot", size, scene, false, false, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT, false, BABYLON.Texture.NEAREST_SAMPLINGMODE);
  8771. texture.renderList = null;
  8772. texture.samples = samples;
  8773. if (antialiasing) {
  8774. texture.addPostProcess(new BABYLON.FxaaPostProcess('antialiasing', 1.0, scene.activeCamera));
  8775. }
  8776. texture.onAfterRenderObservable.add(function () {
  8777. Tools.DumpFramebuffer(width, height, engine, successCallback, mimeType, fileName);
  8778. });
  8779. scene.incrementRenderId();
  8780. scene.resetCachedMaterial();
  8781. texture.render(true);
  8782. texture.dispose();
  8783. if (previousCamera) {
  8784. scene.activeCamera = previousCamera;
  8785. }
  8786. camera.getProjectionMatrix(true); // Force cache refresh;
  8787. };
  8788. // XHR response validator for local file scenario
  8789. Tools.ValidateXHRData = function (xhr, dataType) {
  8790. // 1 for text (.babylon, manifest and shaders), 2 for TGA, 4 for DDS, 7 for all
  8791. if (dataType === void 0) { dataType = 7; }
  8792. try {
  8793. if (dataType & 1) {
  8794. if (xhr.responseText && xhr.responseText.length > 0) {
  8795. return true;
  8796. }
  8797. else if (dataType === 1) {
  8798. return false;
  8799. }
  8800. }
  8801. if (dataType & 2) {
  8802. // Check header width and height since there is no "TGA" magic number
  8803. var tgaHeader = BABYLON.TGATools.GetTGAHeader(xhr.response);
  8804. if (tgaHeader.width && tgaHeader.height && tgaHeader.width > 0 && tgaHeader.height > 0) {
  8805. return true;
  8806. }
  8807. else if (dataType === 2) {
  8808. return false;
  8809. }
  8810. }
  8811. if (dataType & 4) {
  8812. // Check for the "DDS" magic number
  8813. var ddsHeader = new Uint8Array(xhr.response, 0, 3);
  8814. if (ddsHeader[0] === 68 && ddsHeader[1] === 68 && ddsHeader[2] === 83) {
  8815. return true;
  8816. }
  8817. else {
  8818. return false;
  8819. }
  8820. }
  8821. }
  8822. catch (e) {
  8823. // Global protection
  8824. }
  8825. return false;
  8826. };
  8827. /**
  8828. * Implementation from http://stackoverflow.com/questions/105034/how-to-create-a-guid-uuid-in-javascript/2117523#answer-2117523
  8829. * Be aware Math.random() could cause collisions, but:
  8830. * "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"
  8831. */
  8832. Tools.RandomId = function () {
  8833. return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function (c) {
  8834. var r = Math.random() * 16 | 0, v = c === 'x' ? r : (r & 0x3 | 0x8);
  8835. return v.toString(16);
  8836. });
  8837. };
  8838. /**
  8839. * Test if the given uri is a base64 string.
  8840. * @param uri The uri to test
  8841. * @return True if the uri is a base64 string or false otherwise.
  8842. */
  8843. Tools.IsBase64 = function (uri) {
  8844. return uri.length < 5 ? false : uri.substr(0, 5) === "data:";
  8845. };
  8846. /**
  8847. * Decode the given base64 uri.
  8848. * @param uri The uri to decode
  8849. * @return The decoded base64 data.
  8850. */
  8851. Tools.DecodeBase64 = function (uri) {
  8852. var decodedString = atob(uri.split(",")[1]);
  8853. var bufferLength = decodedString.length;
  8854. var bufferView = new Uint8Array(new ArrayBuffer(bufferLength));
  8855. for (var i = 0; i < bufferLength; i++) {
  8856. bufferView[i] = decodedString.charCodeAt(i);
  8857. }
  8858. return bufferView.buffer;
  8859. };
  8860. Object.defineProperty(Tools, "NoneLogLevel", {
  8861. get: function () {
  8862. return Tools._NoneLogLevel;
  8863. },
  8864. enumerable: true,
  8865. configurable: true
  8866. });
  8867. Object.defineProperty(Tools, "MessageLogLevel", {
  8868. get: function () {
  8869. return Tools._MessageLogLevel;
  8870. },
  8871. enumerable: true,
  8872. configurable: true
  8873. });
  8874. Object.defineProperty(Tools, "WarningLogLevel", {
  8875. get: function () {
  8876. return Tools._WarningLogLevel;
  8877. },
  8878. enumerable: true,
  8879. configurable: true
  8880. });
  8881. Object.defineProperty(Tools, "ErrorLogLevel", {
  8882. get: function () {
  8883. return Tools._ErrorLogLevel;
  8884. },
  8885. enumerable: true,
  8886. configurable: true
  8887. });
  8888. Object.defineProperty(Tools, "AllLogLevel", {
  8889. get: function () {
  8890. return Tools._MessageLogLevel | Tools._WarningLogLevel | Tools._ErrorLogLevel;
  8891. },
  8892. enumerable: true,
  8893. configurable: true
  8894. });
  8895. Tools._AddLogEntry = function (entry) {
  8896. Tools._LogCache = entry + Tools._LogCache;
  8897. if (Tools.OnNewCacheEntry) {
  8898. Tools.OnNewCacheEntry(entry);
  8899. }
  8900. };
  8901. Tools._FormatMessage = function (message) {
  8902. var padStr = function (i) { return (i < 10) ? "0" + i : "" + i; };
  8903. var date = new Date();
  8904. return "[" + padStr(date.getHours()) + ":" + padStr(date.getMinutes()) + ":" + padStr(date.getSeconds()) + "]: " + message;
  8905. };
  8906. Tools._LogDisabled = function (message) {
  8907. // nothing to do
  8908. };
  8909. Tools._LogEnabled = function (message) {
  8910. var formattedMessage = Tools._FormatMessage(message);
  8911. console.log("BJS - " + formattedMessage);
  8912. var entry = "<div style='color:white'>" + formattedMessage + "</div><br>";
  8913. Tools._AddLogEntry(entry);
  8914. };
  8915. Tools._WarnDisabled = function (message) {
  8916. // nothing to do
  8917. };
  8918. Tools._WarnEnabled = function (message) {
  8919. var formattedMessage = Tools._FormatMessage(message);
  8920. console.warn("BJS - " + formattedMessage);
  8921. var entry = "<div style='color:orange'>" + formattedMessage + "</div><br>";
  8922. Tools._AddLogEntry(entry);
  8923. };
  8924. Tools._ErrorDisabled = function (message) {
  8925. // nothing to do
  8926. };
  8927. Tools._ErrorEnabled = function (message) {
  8928. Tools.errorsCount++;
  8929. var formattedMessage = Tools._FormatMessage(message);
  8930. console.error("BJS - " + formattedMessage);
  8931. var entry = "<div style='color:red'>" + formattedMessage + "</div><br>";
  8932. Tools._AddLogEntry(entry);
  8933. };
  8934. Object.defineProperty(Tools, "LogCache", {
  8935. get: function () {
  8936. return Tools._LogCache;
  8937. },
  8938. enumerable: true,
  8939. configurable: true
  8940. });
  8941. Tools.ClearLogCache = function () {
  8942. Tools._LogCache = "";
  8943. Tools.errorsCount = 0;
  8944. };
  8945. Object.defineProperty(Tools, "LogLevels", {
  8946. set: function (level) {
  8947. if ((level & Tools.MessageLogLevel) === Tools.MessageLogLevel) {
  8948. Tools.Log = Tools._LogEnabled;
  8949. }
  8950. else {
  8951. Tools.Log = Tools._LogDisabled;
  8952. }
  8953. if ((level & Tools.WarningLogLevel) === Tools.WarningLogLevel) {
  8954. Tools.Warn = Tools._WarnEnabled;
  8955. }
  8956. else {
  8957. Tools.Warn = Tools._WarnDisabled;
  8958. }
  8959. if ((level & Tools.ErrorLogLevel) === Tools.ErrorLogLevel) {
  8960. Tools.Error = Tools._ErrorEnabled;
  8961. }
  8962. else {
  8963. Tools.Error = Tools._ErrorDisabled;
  8964. }
  8965. },
  8966. enumerable: true,
  8967. configurable: true
  8968. });
  8969. Tools.IsWindowObjectExist = function () {
  8970. return (typeof window) !== "undefined";
  8971. };
  8972. Object.defineProperty(Tools, "PerformanceNoneLogLevel", {
  8973. get: function () {
  8974. return Tools._PerformanceNoneLogLevel;
  8975. },
  8976. enumerable: true,
  8977. configurable: true
  8978. });
  8979. Object.defineProperty(Tools, "PerformanceUserMarkLogLevel", {
  8980. get: function () {
  8981. return Tools._PerformanceUserMarkLogLevel;
  8982. },
  8983. enumerable: true,
  8984. configurable: true
  8985. });
  8986. Object.defineProperty(Tools, "PerformanceConsoleLogLevel", {
  8987. get: function () {
  8988. return Tools._PerformanceConsoleLogLevel;
  8989. },
  8990. enumerable: true,
  8991. configurable: true
  8992. });
  8993. Object.defineProperty(Tools, "PerformanceLogLevel", {
  8994. set: function (level) {
  8995. if ((level & Tools.PerformanceUserMarkLogLevel) === Tools.PerformanceUserMarkLogLevel) {
  8996. Tools.StartPerformanceCounter = Tools._StartUserMark;
  8997. Tools.EndPerformanceCounter = Tools._EndUserMark;
  8998. return;
  8999. }
  9000. if ((level & Tools.PerformanceConsoleLogLevel) === Tools.PerformanceConsoleLogLevel) {
  9001. Tools.StartPerformanceCounter = Tools._StartPerformanceConsole;
  9002. Tools.EndPerformanceCounter = Tools._EndPerformanceConsole;
  9003. return;
  9004. }
  9005. Tools.StartPerformanceCounter = Tools._StartPerformanceCounterDisabled;
  9006. Tools.EndPerformanceCounter = Tools._EndPerformanceCounterDisabled;
  9007. },
  9008. enumerable: true,
  9009. configurable: true
  9010. });
  9011. Tools._StartPerformanceCounterDisabled = function (counterName, condition) {
  9012. };
  9013. Tools._EndPerformanceCounterDisabled = function (counterName, condition) {
  9014. };
  9015. Tools._StartUserMark = function (counterName, condition) {
  9016. if (condition === void 0) { condition = true; }
  9017. if (!Tools._performance) {
  9018. if (!Tools.IsWindowObjectExist()) {
  9019. return;
  9020. }
  9021. Tools._performance = window.performance;
  9022. }
  9023. if (!condition || !Tools._performance.mark) {
  9024. return;
  9025. }
  9026. Tools._performance.mark(counterName + "-Begin");
  9027. };
  9028. Tools._EndUserMark = function (counterName, condition) {
  9029. if (condition === void 0) { condition = true; }
  9030. if (!condition || !Tools._performance.mark) {
  9031. return;
  9032. }
  9033. Tools._performance.mark(counterName + "-End");
  9034. Tools._performance.measure(counterName, counterName + "-Begin", counterName + "-End");
  9035. };
  9036. Tools._StartPerformanceConsole = function (counterName, condition) {
  9037. if (condition === void 0) { condition = true; }
  9038. if (!condition) {
  9039. return;
  9040. }
  9041. Tools._StartUserMark(counterName, condition);
  9042. if (console.time) {
  9043. console.time(counterName);
  9044. }
  9045. };
  9046. Tools._EndPerformanceConsole = function (counterName, condition) {
  9047. if (condition === void 0) { condition = true; }
  9048. if (!condition) {
  9049. return;
  9050. }
  9051. Tools._EndUserMark(counterName, condition);
  9052. if (console.time) {
  9053. console.timeEnd(counterName);
  9054. }
  9055. };
  9056. Object.defineProperty(Tools, "Now", {
  9057. get: function () {
  9058. if (Tools.IsWindowObjectExist() && window.performance && window.performance.now) {
  9059. return window.performance.now();
  9060. }
  9061. return new Date().getTime();
  9062. },
  9063. enumerable: true,
  9064. configurable: true
  9065. });
  9066. /**
  9067. * This method will return the name of the class used to create the instance of the given object.
  9068. * It will works only on Javascript basic data types (number, string, ...) and instance of class declared with the @className decorator.
  9069. * @param object the object to get the class name from
  9070. * @return the name of the class, will be "object" for a custom data type not using the @className decorator
  9071. */
  9072. Tools.GetClassName = function (object, isType) {
  9073. if (isType === void 0) { isType = false; }
  9074. var name = null;
  9075. if (!isType && object.getClassName) {
  9076. name = object.getClassName();
  9077. }
  9078. else {
  9079. if (object instanceof Object) {
  9080. var classObj = isType ? object : Object.getPrototypeOf(object);
  9081. name = classObj.constructor["__bjsclassName__"];
  9082. }
  9083. if (!name) {
  9084. name = typeof object;
  9085. }
  9086. }
  9087. return name;
  9088. };
  9089. Tools.First = function (array, predicate) {
  9090. for (var _i = 0, array_1 = array; _i < array_1.length; _i++) {
  9091. var el = array_1[_i];
  9092. if (predicate(el)) {
  9093. return el;
  9094. }
  9095. }
  9096. return null;
  9097. };
  9098. /**
  9099. * This method will return the name of the full name of the class, including its owning module (if any).
  9100. * 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).
  9101. * @param object the object to get the class name from
  9102. * @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.
  9103. */
  9104. Tools.getFullClassName = function (object, isType) {
  9105. if (isType === void 0) { isType = false; }
  9106. var className = null;
  9107. var moduleName = null;
  9108. if (!isType && object.getClassName) {
  9109. className = object.getClassName();
  9110. }
  9111. else {
  9112. if (object instanceof Object) {
  9113. var classObj = isType ? object : Object.getPrototypeOf(object);
  9114. className = classObj.constructor["__bjsclassName__"];
  9115. moduleName = classObj.constructor["__bjsmoduleName__"];
  9116. }
  9117. if (!className) {
  9118. className = typeof object;
  9119. }
  9120. }
  9121. if (!className) {
  9122. return null;
  9123. }
  9124. return ((moduleName != null) ? (moduleName + ".") : "") + className;
  9125. };
  9126. /**
  9127. * 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.
  9128. * @param array
  9129. */
  9130. Tools.arrayOrStringFeeder = function (array) {
  9131. return function (index) {
  9132. if (index >= array.length) {
  9133. return null;
  9134. }
  9135. var val = array.charCodeAt ? array.charCodeAt(index) : array[index];
  9136. if (val && val.getHashCode) {
  9137. val = val.getHashCode();
  9138. }
  9139. if (typeof val === "string") {
  9140. return Tools.hashCodeFromStream(Tools.arrayOrStringFeeder(val));
  9141. }
  9142. return val;
  9143. };
  9144. };
  9145. /**
  9146. * Compute the hashCode of a stream of number
  9147. * To compute the HashCode on a string or an Array of data types implementing the getHashCode() method, use the arrayOrStringFeeder method.
  9148. * @param feeder a callback that will be called until it returns null, each valid returned values will be used to compute the hash code.
  9149. * @return the hash code computed
  9150. */
  9151. Tools.hashCodeFromStream = function (feeder) {
  9152. // Based from here: http://stackoverflow.com/a/7616484/802124
  9153. var hash = 0;
  9154. var index = 0;
  9155. var chr = feeder(index++);
  9156. while (chr != null) {
  9157. hash = ((hash << 5) - hash) + chr;
  9158. hash |= 0; // Convert to 32bit integer
  9159. chr = feeder(index++);
  9160. }
  9161. return hash;
  9162. };
  9163. /**
  9164. * Returns a promise that resolves after the given amount of time.
  9165. * @param delay Number of milliseconds to delay
  9166. * @returns Promise that resolves after the given amount of time
  9167. */
  9168. Tools.DelayAsync = function (delay) {
  9169. return new Promise(function (resolve) {
  9170. setTimeout(function () {
  9171. resolve();
  9172. }, delay);
  9173. });
  9174. };
  9175. Tools.BaseUrl = "";
  9176. Tools.DefaultRetryStrategy = RetryStrategy.ExponentialBackoff();
  9177. /**
  9178. * Default behaviour for cors in the application.
  9179. * It can be a string if the expected behavior is identical in the entire app.
  9180. * Or a callback to be able to set it per url or on a group of them (in case of Video source for instance)
  9181. */
  9182. Tools.CorsBehavior = "anonymous";
  9183. Tools.UseFallbackTexture = true;
  9184. /**
  9185. * Use this object to register external classes like custom textures or material
  9186. * to allow the laoders to instantiate them
  9187. */
  9188. Tools.RegisteredExternalClasses = {};
  9189. // Used in case of a texture loading problem
  9190. 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";
  9191. Tools.PreprocessUrl = function (url) {
  9192. return url;
  9193. };
  9194. // Logs
  9195. Tools._NoneLogLevel = 0;
  9196. Tools._MessageLogLevel = 1;
  9197. Tools._WarningLogLevel = 2;
  9198. Tools._ErrorLogLevel = 4;
  9199. Tools._LogCache = "";
  9200. Tools.errorsCount = 0;
  9201. Tools.Log = Tools._LogEnabled;
  9202. Tools.Warn = Tools._WarnEnabled;
  9203. Tools.Error = Tools._ErrorEnabled;
  9204. // Performances
  9205. Tools._PerformanceNoneLogLevel = 0;
  9206. Tools._PerformanceUserMarkLogLevel = 1;
  9207. Tools._PerformanceConsoleLogLevel = 2;
  9208. Tools.StartPerformanceCounter = Tools._StartPerformanceCounterDisabled;
  9209. Tools.EndPerformanceCounter = Tools._EndPerformanceCounterDisabled;
  9210. return Tools;
  9211. }());
  9212. BABYLON.Tools = Tools;
  9213. /**
  9214. * This class is used to track a performance counter which is number based.
  9215. * The user has access to many properties which give statistics of different nature
  9216. *
  9217. * The implementer can track two kinds of Performance Counter: time and count
  9218. * 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.
  9219. * 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.
  9220. */
  9221. var PerfCounter = /** @class */ (function () {
  9222. function PerfCounter() {
  9223. this._startMonitoringTime = 0;
  9224. this._min = 0;
  9225. this._max = 0;
  9226. this._average = 0;
  9227. this._lastSecAverage = 0;
  9228. this._current = 0;
  9229. this._totalValueCount = 0;
  9230. this._totalAccumulated = 0;
  9231. this._lastSecAccumulated = 0;
  9232. this._lastSecTime = 0;
  9233. this._lastSecValueCount = 0;
  9234. }
  9235. Object.defineProperty(PerfCounter.prototype, "min", {
  9236. /**
  9237. * Returns the smallest value ever
  9238. */
  9239. get: function () {
  9240. return this._min;
  9241. },
  9242. enumerable: true,
  9243. configurable: true
  9244. });
  9245. Object.defineProperty(PerfCounter.prototype, "max", {
  9246. /**
  9247. * Returns the biggest value ever
  9248. */
  9249. get: function () {
  9250. return this._max;
  9251. },
  9252. enumerable: true,
  9253. configurable: true
  9254. });
  9255. Object.defineProperty(PerfCounter.prototype, "average", {
  9256. /**
  9257. * Returns the average value since the performance counter is running
  9258. */
  9259. get: function () {
  9260. return this._average;
  9261. },
  9262. enumerable: true,
  9263. configurable: true
  9264. });
  9265. Object.defineProperty(PerfCounter.prototype, "lastSecAverage", {
  9266. /**
  9267. * Returns the average value of the last second the counter was monitored
  9268. */
  9269. get: function () {
  9270. return this._lastSecAverage;
  9271. },
  9272. enumerable: true,
  9273. configurable: true
  9274. });
  9275. Object.defineProperty(PerfCounter.prototype, "current", {
  9276. /**
  9277. * Returns the current value
  9278. */
  9279. get: function () {
  9280. return this._current;
  9281. },
  9282. enumerable: true,
  9283. configurable: true
  9284. });
  9285. Object.defineProperty(PerfCounter.prototype, "total", {
  9286. get: function () {
  9287. return this._totalAccumulated;
  9288. },
  9289. enumerable: true,
  9290. configurable: true
  9291. });
  9292. Object.defineProperty(PerfCounter.prototype, "count", {
  9293. get: function () {
  9294. return this._totalValueCount;
  9295. },
  9296. enumerable: true,
  9297. configurable: true
  9298. });
  9299. /**
  9300. * Call this method to start monitoring a new frame.
  9301. * 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.
  9302. */
  9303. PerfCounter.prototype.fetchNewFrame = function () {
  9304. this._totalValueCount++;
  9305. this._current = 0;
  9306. this._lastSecValueCount++;
  9307. };
  9308. /**
  9309. * Call this method to monitor a count of something (e.g. mesh drawn in viewport count)
  9310. * @param newCount the count value to add to the monitored count
  9311. * @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.
  9312. */
  9313. PerfCounter.prototype.addCount = function (newCount, fetchResult) {
  9314. if (!PerfCounter.Enabled) {
  9315. return;
  9316. }
  9317. this._current += newCount;
  9318. if (fetchResult) {
  9319. this._fetchResult();
  9320. }
  9321. };
  9322. /**
  9323. * Start monitoring this performance counter
  9324. */
  9325. PerfCounter.prototype.beginMonitoring = function () {
  9326. if (!PerfCounter.Enabled) {
  9327. return;
  9328. }
  9329. this._startMonitoringTime = Tools.Now;
  9330. };
  9331. /**
  9332. * Compute the time lapsed since the previous beginMonitoring() call.
  9333. * @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
  9334. */
  9335. PerfCounter.prototype.endMonitoring = function (newFrame) {
  9336. if (newFrame === void 0) { newFrame = true; }
  9337. if (!PerfCounter.Enabled) {
  9338. return;
  9339. }
  9340. if (newFrame) {
  9341. this.fetchNewFrame();
  9342. }
  9343. var currentTime = Tools.Now;
  9344. this._current = currentTime - this._startMonitoringTime;
  9345. if (newFrame) {
  9346. this._fetchResult();
  9347. }
  9348. };
  9349. PerfCounter.prototype._fetchResult = function () {
  9350. this._totalAccumulated += this._current;
  9351. this._lastSecAccumulated += this._current;
  9352. // Min/Max update
  9353. this._min = Math.min(this._min, this._current);
  9354. this._max = Math.max(this._max, this._current);
  9355. this._average = this._totalAccumulated / this._totalValueCount;
  9356. // Reset last sec?
  9357. var now = Tools.Now;
  9358. if ((now - this._lastSecTime) > 1000) {
  9359. this._lastSecAverage = this._lastSecAccumulated / this._lastSecValueCount;
  9360. this._lastSecTime = now;
  9361. this._lastSecAccumulated = 0;
  9362. this._lastSecValueCount = 0;
  9363. }
  9364. };
  9365. PerfCounter.Enabled = true;
  9366. return PerfCounter;
  9367. }());
  9368. BABYLON.PerfCounter = PerfCounter;
  9369. /**
  9370. * Use this className as a decorator on a given class definition to add it a name and optionally its module.
  9371. * You can then use the Tools.getClassName(obj) on an instance to retrieve its class name.
  9372. * This method is the only way to get it done in all cases, even if the .js file declaring the class is minified
  9373. * @param name The name of the class, case should be preserved
  9374. * @param module The name of the Module hosting the class, optional, but strongly recommended to specify if possible. Case should be preserved.
  9375. */
  9376. function className(name, module) {
  9377. return function (target) {
  9378. target["__bjsclassName__"] = name;
  9379. target["__bjsmoduleName__"] = (module != null) ? module : null;
  9380. };
  9381. }
  9382. BABYLON.className = className;
  9383. /**
  9384. * An implementation of a loop for asynchronous functions.
  9385. */
  9386. var AsyncLoop = /** @class */ (function () {
  9387. /**
  9388. * Constroctor.
  9389. * @param iterations the number of iterations.
  9390. * @param _fn the function to run each iteration
  9391. * @param _successCallback the callback that will be called upon succesful execution
  9392. * @param offset starting offset.
  9393. */
  9394. function AsyncLoop(iterations, _fn, _successCallback, offset) {
  9395. if (offset === void 0) { offset = 0; }
  9396. this.iterations = iterations;
  9397. this._fn = _fn;
  9398. this._successCallback = _successCallback;
  9399. this.index = offset - 1;
  9400. this._done = false;
  9401. }
  9402. /**
  9403. * Execute the next iteration. Must be called after the last iteration was finished.
  9404. */
  9405. AsyncLoop.prototype.executeNext = function () {
  9406. if (!this._done) {
  9407. if (this.index + 1 < this.iterations) {
  9408. ++this.index;
  9409. this._fn(this);
  9410. }
  9411. else {
  9412. this.breakLoop();
  9413. }
  9414. }
  9415. };
  9416. /**
  9417. * Break the loop and run the success callback.
  9418. */
  9419. AsyncLoop.prototype.breakLoop = function () {
  9420. this._done = true;
  9421. this._successCallback();
  9422. };
  9423. /**
  9424. * Helper function
  9425. */
  9426. AsyncLoop.Run = function (iterations, _fn, _successCallback, offset) {
  9427. if (offset === void 0) { offset = 0; }
  9428. var loop = new AsyncLoop(iterations, _fn, _successCallback, offset);
  9429. loop.executeNext();
  9430. return loop;
  9431. };
  9432. /**
  9433. * A for-loop that will run a given number of iterations synchronous and the rest async.
  9434. * @param iterations total number of iterations
  9435. * @param syncedIterations number of synchronous iterations in each async iteration.
  9436. * @param fn the function to call each iteration.
  9437. * @param callback a success call back that will be called when iterating stops.
  9438. * @param breakFunction a break condition (optional)
  9439. * @param timeout timeout settings for the setTimeout function. default - 0.
  9440. * @constructor
  9441. */
  9442. AsyncLoop.SyncAsyncForLoop = function (iterations, syncedIterations, fn, callback, breakFunction, timeout) {
  9443. if (timeout === void 0) { timeout = 0; }
  9444. AsyncLoop.Run(Math.ceil(iterations / syncedIterations), function (loop) {
  9445. if (breakFunction && breakFunction())
  9446. loop.breakLoop();
  9447. else {
  9448. setTimeout(function () {
  9449. for (var i = 0; i < syncedIterations; ++i) {
  9450. var iteration = (loop.index * syncedIterations) + i;
  9451. if (iteration >= iterations)
  9452. break;
  9453. fn(iteration);
  9454. if (breakFunction && breakFunction()) {
  9455. loop.breakLoop();
  9456. break;
  9457. }
  9458. }
  9459. loop.executeNext();
  9460. }, timeout);
  9461. }
  9462. }, callback);
  9463. };
  9464. return AsyncLoop;
  9465. }());
  9466. BABYLON.AsyncLoop = AsyncLoop;
  9467. })(BABYLON || (BABYLON = {}));
  9468. //# sourceMappingURL=babylon.tools.js.map
  9469. "use strict";
  9470. var BABYLON;
  9471. (function (BABYLON) {
  9472. var PromiseStates;
  9473. (function (PromiseStates) {
  9474. PromiseStates[PromiseStates["Pending"] = 0] = "Pending";
  9475. PromiseStates[PromiseStates["Fulfilled"] = 1] = "Fulfilled";
  9476. PromiseStates[PromiseStates["Rejected"] = 2] = "Rejected";
  9477. })(PromiseStates || (PromiseStates = {}));
  9478. var FulFillmentAgregator = /** @class */ (function () {
  9479. function FulFillmentAgregator() {
  9480. this.count = 0;
  9481. this.target = 0;
  9482. this.results = [];
  9483. }
  9484. return FulFillmentAgregator;
  9485. }());
  9486. var InternalPromise = /** @class */ (function () {
  9487. function InternalPromise(resolver) {
  9488. var _this = this;
  9489. this._state = PromiseStates.Pending;
  9490. this._children = new Array();
  9491. this._rejectWasConsumed = false;
  9492. if (!resolver) {
  9493. return;
  9494. }
  9495. try {
  9496. resolver(function (value) {
  9497. _this._resolve(value);
  9498. }, function (reason) {
  9499. _this._reject(reason);
  9500. });
  9501. }
  9502. catch (e) {
  9503. this._reject(e);
  9504. }
  9505. }
  9506. InternalPromise.prototype.catch = function (onRejected) {
  9507. return this.then(undefined, onRejected);
  9508. };
  9509. InternalPromise.prototype.then = function (onFulfilled, onRejected) {
  9510. var _this = this;
  9511. var newPromise = new InternalPromise();
  9512. newPromise._onFulfilled = onFulfilled;
  9513. newPromise._onRejected = onRejected;
  9514. // Composition
  9515. this._children.push(newPromise);
  9516. if (this._state !== PromiseStates.Pending) {
  9517. BABYLON.Tools.SetImmediate(function () {
  9518. if (_this._state === PromiseStates.Fulfilled || _this._rejectWasConsumed) {
  9519. var returnedValue = newPromise._resolve(_this._result);
  9520. if (returnedValue !== undefined && returnedValue !== null) {
  9521. if (returnedValue._state !== undefined) {
  9522. var returnedPromise = returnedValue;
  9523. newPromise._children.push(returnedPromise);
  9524. newPromise = returnedPromise;
  9525. }
  9526. else {
  9527. newPromise._result = returnedValue;
  9528. }
  9529. }
  9530. }
  9531. else {
  9532. newPromise._reject(_this._reason);
  9533. }
  9534. });
  9535. }
  9536. return newPromise;
  9537. };
  9538. InternalPromise.prototype._moveChildren = function (children) {
  9539. (_a = this._children).push.apply(_a, children.splice(0, children.length));
  9540. if (this._state === PromiseStates.Fulfilled) {
  9541. for (var _i = 0, _b = this._children; _i < _b.length; _i++) {
  9542. var child = _b[_i];
  9543. child._resolve(this._result);
  9544. }
  9545. }
  9546. else if (this._state === PromiseStates.Rejected) {
  9547. for (var _c = 0, _d = this._children; _c < _d.length; _c++) {
  9548. var child = _d[_c];
  9549. child._reject(this._reason);
  9550. }
  9551. }
  9552. var _a;
  9553. };
  9554. InternalPromise.prototype._resolve = function (value) {
  9555. try {
  9556. this._state = PromiseStates.Fulfilled;
  9557. var returnedValue = null;
  9558. if (this._onFulfilled) {
  9559. returnedValue = this._onFulfilled(value);
  9560. }
  9561. if (returnedValue !== undefined && returnedValue !== null) {
  9562. if (returnedValue._state !== undefined) {
  9563. // Transmit children
  9564. var returnedPromise = returnedValue;
  9565. returnedPromise._moveChildren(this._children);
  9566. value = returnedPromise._result;
  9567. }
  9568. else {
  9569. value = returnedValue;
  9570. }
  9571. }
  9572. this._result = value;
  9573. for (var _i = 0, _a = this._children; _i < _a.length; _i++) {
  9574. var child = _a[_i];
  9575. child._resolve(value);
  9576. }
  9577. this._children.length = 0;
  9578. delete this._onFulfilled;
  9579. delete this._onRejected;
  9580. }
  9581. catch (e) {
  9582. this._reject(e, true);
  9583. }
  9584. };
  9585. InternalPromise.prototype._reject = function (reason, onLocalThrow) {
  9586. if (onLocalThrow === void 0) { onLocalThrow = false; }
  9587. this._state = PromiseStates.Rejected;
  9588. this._reason = reason;
  9589. if (this._onRejected && !onLocalThrow) {
  9590. try {
  9591. this._onRejected(reason);
  9592. this._rejectWasConsumed = true;
  9593. }
  9594. catch (e) {
  9595. reason = e;
  9596. }
  9597. }
  9598. for (var _i = 0, _a = this._children; _i < _a.length; _i++) {
  9599. var child = _a[_i];
  9600. if (this._rejectWasConsumed) {
  9601. child._resolve(null);
  9602. }
  9603. else {
  9604. child._reject(reason);
  9605. }
  9606. }
  9607. this._children.length = 0;
  9608. delete this._onFulfilled;
  9609. delete this._onRejected;
  9610. };
  9611. InternalPromise.resolve = function (value) {
  9612. var newPromise = new InternalPromise();
  9613. newPromise._resolve(value);
  9614. return newPromise;
  9615. };
  9616. InternalPromise._RegisterForFulfillment = function (promise, agregator, index) {
  9617. promise.then(function (value) {
  9618. agregator.results[index] = value;
  9619. agregator.count++;
  9620. if (agregator.count === agregator.target) {
  9621. agregator.rootPromise._resolve(agregator.results);
  9622. }
  9623. return null;
  9624. }, function (reason) {
  9625. if (agregator.rootPromise._state !== PromiseStates.Rejected) {
  9626. agregator.rootPromise._reject(reason);
  9627. }
  9628. });
  9629. };
  9630. InternalPromise.all = function (promises) {
  9631. var newPromise = new InternalPromise();
  9632. var agregator = new FulFillmentAgregator();
  9633. agregator.target = promises.length;
  9634. agregator.rootPromise = newPromise;
  9635. if (promises.length) {
  9636. for (var index = 0; index < promises.length; index++) {
  9637. InternalPromise._RegisterForFulfillment(promises[index], agregator, index);
  9638. }
  9639. }
  9640. else {
  9641. newPromise._resolve([]);
  9642. }
  9643. return newPromise;
  9644. };
  9645. InternalPromise.race = function (promises) {
  9646. var newPromise = new InternalPromise();
  9647. if (promises.length) {
  9648. for (var _i = 0, promises_1 = promises; _i < promises_1.length; _i++) {
  9649. var promise = promises_1[_i];
  9650. promise.then(function (value) {
  9651. if (newPromise) {
  9652. newPromise._resolve(value);
  9653. newPromise = null;
  9654. }
  9655. return null;
  9656. }, function (reason) {
  9657. if (newPromise) {
  9658. newPromise._reject(reason);
  9659. newPromise = null;
  9660. }
  9661. });
  9662. }
  9663. }
  9664. return newPromise;
  9665. };
  9666. return InternalPromise;
  9667. }());
  9668. /**
  9669. * Helper class that provides a small promise polyfill
  9670. */
  9671. var PromisePolyfill = /** @class */ (function () {
  9672. function PromisePolyfill() {
  9673. }
  9674. /**
  9675. * Static function used to check if the polyfill is required
  9676. * If this is the case then the function will inject the polyfill to window.Promise
  9677. * @param force defines a boolean used to force the injection (mostly for testing purposes)
  9678. */
  9679. PromisePolyfill.Apply = function (force) {
  9680. if (force === void 0) { force = false; }
  9681. if (force || typeof Promise === 'undefined') {
  9682. var root = window;
  9683. root.Promise = InternalPromise;
  9684. }
  9685. };
  9686. return PromisePolyfill;
  9687. }());
  9688. BABYLON.PromisePolyfill = PromisePolyfill;
  9689. })(BABYLON || (BABYLON = {}));
  9690. //# sourceMappingURL=babylon.promise.js.map
  9691. "use strict";
  9692. /// <reference path="../../../dist/preview release/babylon.d.ts" />
  9693. var BABYLON;
  9694. (function (BABYLON) {
  9695. /**
  9696. * Helper class to push actions to a pool of workers.
  9697. */
  9698. var WorkerPool = /** @class */ (function () {
  9699. /**
  9700. * Constructor
  9701. * @param workers Array of workers to use for actions
  9702. */
  9703. function WorkerPool(workers) {
  9704. this._pendingActions = new Array();
  9705. this._workerInfos = workers.map(function (worker) { return ({
  9706. worker: worker,
  9707. active: false
  9708. }); });
  9709. }
  9710. /**
  9711. * Terminates all workers and clears any pending actions.
  9712. */
  9713. WorkerPool.prototype.dispose = function () {
  9714. for (var _i = 0, _a = this._workerInfos; _i < _a.length; _i++) {
  9715. var workerInfo = _a[_i];
  9716. workerInfo.worker.terminate();
  9717. }
  9718. delete this._workerInfos;
  9719. delete this._pendingActions;
  9720. };
  9721. /**
  9722. * Pushes an action to the worker pool. If all the workers are active, the action will be
  9723. * pended until a worker has completed its action.
  9724. * @param action The action to perform. Call onComplete when the action is complete.
  9725. */
  9726. WorkerPool.prototype.push = function (action) {
  9727. for (var _i = 0, _a = this._workerInfos; _i < _a.length; _i++) {
  9728. var workerInfo = _a[_i];
  9729. if (!workerInfo.active) {
  9730. this._execute(workerInfo, action);
  9731. return;
  9732. }
  9733. }
  9734. this._pendingActions.push(action);
  9735. };
  9736. WorkerPool.prototype._execute = function (workerInfo, action) {
  9737. var _this = this;
  9738. workerInfo.active = true;
  9739. action(workerInfo.worker, function () {
  9740. workerInfo.active = false;
  9741. var nextAction = _this._pendingActions.shift();
  9742. if (nextAction) {
  9743. _this._execute(workerInfo, nextAction);
  9744. }
  9745. });
  9746. };
  9747. return WorkerPool;
  9748. }());
  9749. BABYLON.WorkerPool = WorkerPool;
  9750. })(BABYLON || (BABYLON = {}));
  9751. //# sourceMappingURL=babylon.workerPool.js.map
  9752. "use strict";
  9753. var BABYLON;
  9754. (function (BABYLON) {
  9755. var _AlphaState = /** @class */ (function () {
  9756. /**
  9757. * Initializes the state.
  9758. */
  9759. function _AlphaState() {
  9760. this._isAlphaBlendDirty = false;
  9761. this._isBlendFunctionParametersDirty = false;
  9762. this._isBlendEquationParametersDirty = false;
  9763. this._isBlendConstantsDirty = false;
  9764. this._alphaBlend = false;
  9765. this._blendFunctionParameters = new Array(4);
  9766. this._blendEquationParameters = new Array(2);
  9767. this._blendConstants = new Array(4);
  9768. this.reset();
  9769. }
  9770. Object.defineProperty(_AlphaState.prototype, "isDirty", {
  9771. get: function () {
  9772. return this._isAlphaBlendDirty || this._isBlendFunctionParametersDirty;
  9773. },
  9774. enumerable: true,
  9775. configurable: true
  9776. });
  9777. Object.defineProperty(_AlphaState.prototype, "alphaBlend", {
  9778. get: function () {
  9779. return this._alphaBlend;
  9780. },
  9781. set: function (value) {
  9782. if (this._alphaBlend === value) {
  9783. return;
  9784. }
  9785. this._alphaBlend = value;
  9786. this._isAlphaBlendDirty = true;
  9787. },
  9788. enumerable: true,
  9789. configurable: true
  9790. });
  9791. _AlphaState.prototype.setAlphaBlendConstants = function (r, g, b, a) {
  9792. if (this._blendConstants[0] === r &&
  9793. this._blendConstants[1] === g &&
  9794. this._blendConstants[2] === b &&
  9795. this._blendConstants[3] === a) {
  9796. return;
  9797. }
  9798. this._blendConstants[0] = r;
  9799. this._blendConstants[1] = g;
  9800. this._blendConstants[2] = b;
  9801. this._blendConstants[3] = a;
  9802. this._isBlendConstantsDirty = true;
  9803. };
  9804. _AlphaState.prototype.setAlphaBlendFunctionParameters = function (value0, value1, value2, value3) {
  9805. if (this._blendFunctionParameters[0] === value0 &&
  9806. this._blendFunctionParameters[1] === value1 &&
  9807. this._blendFunctionParameters[2] === value2 &&
  9808. this._blendFunctionParameters[3] === value3) {
  9809. return;
  9810. }
  9811. this._blendFunctionParameters[0] = value0;
  9812. this._blendFunctionParameters[1] = value1;
  9813. this._blendFunctionParameters[2] = value2;
  9814. this._blendFunctionParameters[3] = value3;
  9815. this._isBlendFunctionParametersDirty = true;
  9816. };
  9817. _AlphaState.prototype.setAlphaEquationParameters = function (rgb, alpha) {
  9818. if (this._blendEquationParameters[0] === rgb &&
  9819. this._blendEquationParameters[1] === alpha) {
  9820. return;
  9821. }
  9822. this._blendEquationParameters[0] = rgb;
  9823. this._blendEquationParameters[1] = alpha;
  9824. this._isBlendEquationParametersDirty = true;
  9825. };
  9826. _AlphaState.prototype.reset = function () {
  9827. this._alphaBlend = false;
  9828. this._blendFunctionParameters[0] = null;
  9829. this._blendFunctionParameters[1] = null;
  9830. this._blendFunctionParameters[2] = null;
  9831. this._blendFunctionParameters[3] = null;
  9832. this._blendEquationParameters[0] = null;
  9833. this._blendEquationParameters[1] = null;
  9834. this._blendConstants[0] = null;
  9835. this._blendConstants[1] = null;
  9836. this._blendConstants[2] = null;
  9837. this._blendConstants[3] = null;
  9838. this._isAlphaBlendDirty = true;
  9839. this._isBlendFunctionParametersDirty = false;
  9840. this._isBlendEquationParametersDirty = false;
  9841. this._isBlendConstantsDirty = false;
  9842. };
  9843. _AlphaState.prototype.apply = function (gl) {
  9844. if (!this.isDirty) {
  9845. return;
  9846. }
  9847. // Alpha blend
  9848. if (this._isAlphaBlendDirty) {
  9849. if (this._alphaBlend) {
  9850. gl.enable(gl.BLEND);
  9851. }
  9852. else {
  9853. gl.disable(gl.BLEND);
  9854. }
  9855. this._isAlphaBlendDirty = false;
  9856. }
  9857. // Alpha function
  9858. if (this._isBlendFunctionParametersDirty) {
  9859. gl.blendFuncSeparate(this._blendFunctionParameters[0], this._blendFunctionParameters[1], this._blendFunctionParameters[2], this._blendFunctionParameters[3]);
  9860. this._isBlendFunctionParametersDirty = false;
  9861. }
  9862. // Alpha equation
  9863. if (this._isBlendEquationParametersDirty) {
  9864. gl.blendEquationSeparate(this._isBlendEquationParametersDirty[0], this._isBlendEquationParametersDirty[1]);
  9865. this._isBlendEquationParametersDirty = false;
  9866. }
  9867. // Constants
  9868. if (this._isBlendConstantsDirty) {
  9869. gl.blendColor(this._blendConstants[0], this._blendConstants[1], this._blendConstants[2], this._blendConstants[3]);
  9870. this._isBlendConstantsDirty = false;
  9871. }
  9872. };
  9873. return _AlphaState;
  9874. }());
  9875. BABYLON._AlphaState = _AlphaState;
  9876. })(BABYLON || (BABYLON = {}));
  9877. //# sourceMappingURL=babylon.alphaCullingState.js.map
  9878. "use strict";
  9879. var BABYLON;
  9880. (function (BABYLON) {
  9881. var _DepthCullingState = /** @class */ (function () {
  9882. /**
  9883. * Initializes the state.
  9884. */
  9885. function _DepthCullingState() {
  9886. this._isDepthTestDirty = false;
  9887. this._isDepthMaskDirty = false;
  9888. this._isDepthFuncDirty = false;
  9889. this._isCullFaceDirty = false;
  9890. this._isCullDirty = false;
  9891. this._isZOffsetDirty = false;
  9892. this._isFrontFaceDirty = false;
  9893. this.reset();
  9894. }
  9895. Object.defineProperty(_DepthCullingState.prototype, "isDirty", {
  9896. get: function () {
  9897. return this._isDepthFuncDirty || this._isDepthTestDirty || this._isDepthMaskDirty || this._isCullFaceDirty || this._isCullDirty || this._isZOffsetDirty || this._isFrontFaceDirty;
  9898. },
  9899. enumerable: true,
  9900. configurable: true
  9901. });
  9902. Object.defineProperty(_DepthCullingState.prototype, "zOffset", {
  9903. get: function () {
  9904. return this._zOffset;
  9905. },
  9906. set: function (value) {
  9907. if (this._zOffset === value) {
  9908. return;
  9909. }
  9910. this._zOffset = value;
  9911. this._isZOffsetDirty = true;
  9912. },
  9913. enumerable: true,
  9914. configurable: true
  9915. });
  9916. Object.defineProperty(_DepthCullingState.prototype, "cullFace", {
  9917. get: function () {
  9918. return this._cullFace;
  9919. },
  9920. set: function (value) {
  9921. if (this._cullFace === value) {
  9922. return;
  9923. }
  9924. this._cullFace = value;
  9925. this._isCullFaceDirty = true;
  9926. },
  9927. enumerable: true,
  9928. configurable: true
  9929. });
  9930. Object.defineProperty(_DepthCullingState.prototype, "cull", {
  9931. get: function () {
  9932. return this._cull;
  9933. },
  9934. set: function (value) {
  9935. if (this._cull === value) {
  9936. return;
  9937. }
  9938. this._cull = value;
  9939. this._isCullDirty = true;
  9940. },
  9941. enumerable: true,
  9942. configurable: true
  9943. });
  9944. Object.defineProperty(_DepthCullingState.prototype, "depthFunc", {
  9945. get: function () {
  9946. return this._depthFunc;
  9947. },
  9948. set: function (value) {
  9949. if (this._depthFunc === value) {
  9950. return;
  9951. }
  9952. this._depthFunc = value;
  9953. this._isDepthFuncDirty = true;
  9954. },
  9955. enumerable: true,
  9956. configurable: true
  9957. });
  9958. Object.defineProperty(_DepthCullingState.prototype, "depthMask", {
  9959. get: function () {
  9960. return this._depthMask;
  9961. },
  9962. set: function (value) {
  9963. if (this._depthMask === value) {
  9964. return;
  9965. }
  9966. this._depthMask = value;
  9967. this._isDepthMaskDirty = true;
  9968. },
  9969. enumerable: true,
  9970. configurable: true
  9971. });
  9972. Object.defineProperty(_DepthCullingState.prototype, "depthTest", {
  9973. get: function () {
  9974. return this._depthTest;
  9975. },
  9976. set: function (value) {
  9977. if (this._depthTest === value) {
  9978. return;
  9979. }
  9980. this._depthTest = value;
  9981. this._isDepthTestDirty = true;
  9982. },
  9983. enumerable: true,
  9984. configurable: true
  9985. });
  9986. Object.defineProperty(_DepthCullingState.prototype, "frontFace", {
  9987. get: function () {
  9988. return this._frontFace;
  9989. },
  9990. set: function (value) {
  9991. if (this._frontFace === value) {
  9992. return;
  9993. }
  9994. this._frontFace = value;
  9995. this._isFrontFaceDirty = true;
  9996. },
  9997. enumerable: true,
  9998. configurable: true
  9999. });
  10000. _DepthCullingState.prototype.reset = function () {
  10001. this._depthMask = true;
  10002. this._depthTest = true;
  10003. this._depthFunc = null;
  10004. this._cullFace = null;
  10005. this._cull = null;
  10006. this._zOffset = 0;
  10007. this._frontFace = null;
  10008. this._isDepthTestDirty = true;
  10009. this._isDepthMaskDirty = true;
  10010. this._isDepthFuncDirty = false;
  10011. this._isCullFaceDirty = false;
  10012. this._isCullDirty = false;
  10013. this._isZOffsetDirty = false;
  10014. this._isFrontFaceDirty = false;
  10015. };
  10016. _DepthCullingState.prototype.apply = function (gl) {
  10017. if (!this.isDirty) {
  10018. return;
  10019. }
  10020. // Cull
  10021. if (this._isCullDirty) {
  10022. if (this.cull) {
  10023. gl.enable(gl.CULL_FACE);
  10024. }
  10025. else {
  10026. gl.disable(gl.CULL_FACE);
  10027. }
  10028. this._isCullDirty = false;
  10029. }
  10030. // Cull face
  10031. if (this._isCullFaceDirty) {
  10032. gl.cullFace(this.cullFace);
  10033. this._isCullFaceDirty = false;
  10034. }
  10035. // Depth mask
  10036. if (this._isDepthMaskDirty) {
  10037. gl.depthMask(this.depthMask);
  10038. this._isDepthMaskDirty = false;
  10039. }
  10040. // Depth test
  10041. if (this._isDepthTestDirty) {
  10042. if (this.depthTest) {
  10043. gl.enable(gl.DEPTH_TEST);
  10044. }
  10045. else {
  10046. gl.disable(gl.DEPTH_TEST);
  10047. }
  10048. this._isDepthTestDirty = false;
  10049. }
  10050. // Depth func
  10051. if (this._isDepthFuncDirty) {
  10052. gl.depthFunc(this.depthFunc);
  10053. this._isDepthFuncDirty = false;
  10054. }
  10055. // zOffset
  10056. if (this._isZOffsetDirty) {
  10057. if (this.zOffset) {
  10058. gl.enable(gl.POLYGON_OFFSET_FILL);
  10059. gl.polygonOffset(this.zOffset, 0);
  10060. }
  10061. else {
  10062. gl.disable(gl.POLYGON_OFFSET_FILL);
  10063. }
  10064. this._isZOffsetDirty = false;
  10065. }
  10066. // Front face
  10067. if (this._isFrontFaceDirty) {
  10068. gl.frontFace(this.frontFace);
  10069. this._isFrontFaceDirty = false;
  10070. }
  10071. };
  10072. return _DepthCullingState;
  10073. }());
  10074. BABYLON._DepthCullingState = _DepthCullingState;
  10075. })(BABYLON || (BABYLON = {}));
  10076. //# sourceMappingURL=babylon.depthCullingState.js.map
  10077. "use strict";
  10078. var BABYLON;
  10079. (function (BABYLON) {
  10080. var _StencilState = /** @class */ (function () {
  10081. function _StencilState() {
  10082. this._isStencilTestDirty = false;
  10083. this._isStencilMaskDirty = false;
  10084. this._isStencilFuncDirty = false;
  10085. this._isStencilOpDirty = false;
  10086. this.reset();
  10087. }
  10088. Object.defineProperty(_StencilState.prototype, "isDirty", {
  10089. get: function () {
  10090. return this._isStencilTestDirty || this._isStencilMaskDirty || this._isStencilFuncDirty || this._isStencilOpDirty;
  10091. },
  10092. enumerable: true,
  10093. configurable: true
  10094. });
  10095. Object.defineProperty(_StencilState.prototype, "stencilFunc", {
  10096. get: function () {
  10097. return this._stencilFunc;
  10098. },
  10099. set: function (value) {
  10100. if (this._stencilFunc === value) {
  10101. return;
  10102. }
  10103. this._stencilFunc = value;
  10104. this._isStencilFuncDirty = true;
  10105. },
  10106. enumerable: true,
  10107. configurable: true
  10108. });
  10109. Object.defineProperty(_StencilState.prototype, "stencilFuncRef", {
  10110. get: function () {
  10111. return this._stencilFuncRef;
  10112. },
  10113. set: function (value) {
  10114. if (this._stencilFuncRef === value) {
  10115. return;
  10116. }
  10117. this._stencilFuncRef = value;
  10118. this._isStencilFuncDirty = true;
  10119. },
  10120. enumerable: true,
  10121. configurable: true
  10122. });
  10123. Object.defineProperty(_StencilState.prototype, "stencilFuncMask", {
  10124. get: function () {
  10125. return this._stencilFuncMask;
  10126. },
  10127. set: function (value) {
  10128. if (this._stencilFuncMask === value) {
  10129. return;
  10130. }
  10131. this._stencilFuncMask = value;
  10132. this._isStencilFuncDirty = true;
  10133. },
  10134. enumerable: true,
  10135. configurable: true
  10136. });
  10137. Object.defineProperty(_StencilState.prototype, "stencilOpStencilFail", {
  10138. get: function () {
  10139. return this._stencilOpStencilFail;
  10140. },
  10141. set: function (value) {
  10142. if (this._stencilOpStencilFail === value) {
  10143. return;
  10144. }
  10145. this._stencilOpStencilFail = value;
  10146. this._isStencilOpDirty = true;
  10147. },
  10148. enumerable: true,
  10149. configurable: true
  10150. });
  10151. Object.defineProperty(_StencilState.prototype, "stencilOpDepthFail", {
  10152. get: function () {
  10153. return this._stencilOpDepthFail;
  10154. },
  10155. set: function (value) {
  10156. if (this._stencilOpDepthFail === value) {
  10157. return;
  10158. }
  10159. this._stencilOpDepthFail = value;
  10160. this._isStencilOpDirty = true;
  10161. },
  10162. enumerable: true,
  10163. configurable: true
  10164. });
  10165. Object.defineProperty(_StencilState.prototype, "stencilOpStencilDepthPass", {
  10166. get: function () {
  10167. return this._stencilOpStencilDepthPass;
  10168. },
  10169. set: function (value) {
  10170. if (this._stencilOpStencilDepthPass === value) {
  10171. return;
  10172. }
  10173. this._stencilOpStencilDepthPass = value;
  10174. this._isStencilOpDirty = true;
  10175. },
  10176. enumerable: true,
  10177. configurable: true
  10178. });
  10179. Object.defineProperty(_StencilState.prototype, "stencilMask", {
  10180. get: function () {
  10181. return this._stencilMask;
  10182. },
  10183. set: function (value) {
  10184. if (this._stencilMask === value) {
  10185. return;
  10186. }
  10187. this._stencilMask = value;
  10188. this._isStencilMaskDirty = true;
  10189. },
  10190. enumerable: true,
  10191. configurable: true
  10192. });
  10193. Object.defineProperty(_StencilState.prototype, "stencilTest", {
  10194. get: function () {
  10195. return this._stencilTest;
  10196. },
  10197. set: function (value) {
  10198. if (this._stencilTest === value) {
  10199. return;
  10200. }
  10201. this._stencilTest = value;
  10202. this._isStencilTestDirty = true;
  10203. },
  10204. enumerable: true,
  10205. configurable: true
  10206. });
  10207. _StencilState.prototype.reset = function () {
  10208. this._stencilTest = false;
  10209. this._stencilMask = 0xFF;
  10210. this._stencilFunc = BABYLON.Engine.ALWAYS;
  10211. this._stencilFuncRef = 1;
  10212. this._stencilFuncMask = 0xFF;
  10213. this._stencilOpStencilFail = BABYLON.Engine.KEEP;
  10214. this._stencilOpDepthFail = BABYLON.Engine.KEEP;
  10215. this._stencilOpStencilDepthPass = BABYLON.Engine.REPLACE;
  10216. this._isStencilTestDirty = true;
  10217. this._isStencilMaskDirty = true;
  10218. this._isStencilFuncDirty = true;
  10219. this._isStencilOpDirty = true;
  10220. };
  10221. _StencilState.prototype.apply = function (gl) {
  10222. if (!this.isDirty) {
  10223. return;
  10224. }
  10225. // Stencil test
  10226. if (this._isStencilTestDirty) {
  10227. if (this.stencilTest) {
  10228. gl.enable(gl.STENCIL_TEST);
  10229. }
  10230. else {
  10231. gl.disable(gl.STENCIL_TEST);
  10232. }
  10233. this._isStencilTestDirty = false;
  10234. }
  10235. // Stencil mask
  10236. if (this._isStencilMaskDirty) {
  10237. gl.stencilMask(this.stencilMask);
  10238. this._isStencilMaskDirty = false;
  10239. }
  10240. // Stencil func
  10241. if (this._isStencilFuncDirty) {
  10242. gl.stencilFunc(this.stencilFunc, this.stencilFuncRef, this.stencilFuncMask);
  10243. this._isStencilFuncDirty = false;
  10244. }
  10245. // Stencil op
  10246. if (this._isStencilOpDirty) {
  10247. gl.stencilOp(this.stencilOpStencilFail, this.stencilOpDepthFail, this.stencilOpStencilDepthPass);
  10248. this._isStencilOpDirty = false;
  10249. }
  10250. };
  10251. return _StencilState;
  10252. }());
  10253. BABYLON._StencilState = _StencilState;
  10254. })(BABYLON || (BABYLON = {}));
  10255. //# sourceMappingURL=babylon.stencilState.js.map
  10256. "use strict";
  10257. var __assign = (this && this.__assign) || Object.assign || function(t) {
  10258. for (var s, i = 1, n = arguments.length; i < n; i++) {
  10259. s = arguments[i];
  10260. for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
  10261. t[p] = s[p];
  10262. }
  10263. return t;
  10264. };
  10265. var BABYLON;
  10266. (function (BABYLON) {
  10267. var compileShader = function (gl, source, type, defines, shaderVersion) {
  10268. return compileRawShader(gl, shaderVersion + (defines ? defines + "\n" : "") + source, type);
  10269. };
  10270. var compileRawShader = function (gl, source, type) {
  10271. var shader = gl.createShader(type === "vertex" ? gl.VERTEX_SHADER : gl.FRAGMENT_SHADER);
  10272. gl.shaderSource(shader, source);
  10273. gl.compileShader(shader);
  10274. if (!gl.getShaderParameter(shader, gl.COMPILE_STATUS)) {
  10275. var log = gl.getShaderInfoLog(shader);
  10276. if (log) {
  10277. throw new Error(log);
  10278. }
  10279. }
  10280. if (!shader) {
  10281. throw new Error("Something went wrong while compile the shader.");
  10282. }
  10283. return shader;
  10284. };
  10285. var getSamplingParameters = function (samplingMode, generateMipMaps, gl) {
  10286. var magFilter = gl.NEAREST;
  10287. var minFilter = gl.NEAREST;
  10288. switch (samplingMode) {
  10289. case BABYLON.Texture.BILINEAR_SAMPLINGMODE:
  10290. magFilter = gl.LINEAR;
  10291. if (generateMipMaps) {
  10292. minFilter = gl.LINEAR_MIPMAP_NEAREST;
  10293. }
  10294. else {
  10295. minFilter = gl.LINEAR;
  10296. }
  10297. break;
  10298. case BABYLON.Texture.TRILINEAR_SAMPLINGMODE:
  10299. magFilter = gl.LINEAR;
  10300. if (generateMipMaps) {
  10301. minFilter = gl.LINEAR_MIPMAP_LINEAR;
  10302. }
  10303. else {
  10304. minFilter = gl.LINEAR;
  10305. }
  10306. break;
  10307. case BABYLON.Texture.NEAREST_SAMPLINGMODE:
  10308. magFilter = gl.NEAREST;
  10309. if (generateMipMaps) {
  10310. minFilter = gl.NEAREST_MIPMAP_LINEAR;
  10311. }
  10312. else {
  10313. minFilter = gl.NEAREST;
  10314. }
  10315. break;
  10316. case BABYLON.Texture.NEAREST_NEAREST_MIPNEAREST:
  10317. magFilter = gl.NEAREST;
  10318. if (generateMipMaps) {
  10319. minFilter = gl.NEAREST_MIPMAP_NEAREST;
  10320. }
  10321. else {
  10322. minFilter = gl.NEAREST;
  10323. }
  10324. break;
  10325. case BABYLON.Texture.NEAREST_LINEAR_MIPNEAREST:
  10326. magFilter = gl.NEAREST;
  10327. if (generateMipMaps) {
  10328. minFilter = gl.LINEAR_MIPMAP_NEAREST;
  10329. }
  10330. else {
  10331. minFilter = gl.LINEAR;
  10332. }
  10333. break;
  10334. case BABYLON.Texture.NEAREST_LINEAR_MIPLINEAR:
  10335. magFilter = gl.NEAREST;
  10336. if (generateMipMaps) {
  10337. minFilter = gl.LINEAR_MIPMAP_LINEAR;
  10338. }
  10339. else {
  10340. minFilter = gl.LINEAR;
  10341. }
  10342. break;
  10343. case BABYLON.Texture.NEAREST_LINEAR:
  10344. magFilter = gl.NEAREST;
  10345. minFilter = gl.LINEAR;
  10346. break;
  10347. case BABYLON.Texture.NEAREST_NEAREST:
  10348. magFilter = gl.NEAREST;
  10349. minFilter = gl.NEAREST;
  10350. break;
  10351. case BABYLON.Texture.LINEAR_NEAREST_MIPNEAREST:
  10352. magFilter = gl.LINEAR;
  10353. if (generateMipMaps) {
  10354. minFilter = gl.NEAREST_MIPMAP_NEAREST;
  10355. }
  10356. else {
  10357. minFilter = gl.NEAREST;
  10358. }
  10359. break;
  10360. case BABYLON.Texture.LINEAR_NEAREST_MIPLINEAR:
  10361. magFilter = gl.LINEAR;
  10362. if (generateMipMaps) {
  10363. minFilter = gl.NEAREST_MIPMAP_LINEAR;
  10364. }
  10365. else {
  10366. minFilter = gl.NEAREST;
  10367. }
  10368. break;
  10369. case BABYLON.Texture.LINEAR_LINEAR:
  10370. magFilter = gl.LINEAR;
  10371. minFilter = gl.LINEAR;
  10372. break;
  10373. case BABYLON.Texture.LINEAR_NEAREST:
  10374. magFilter = gl.LINEAR;
  10375. minFilter = gl.NEAREST;
  10376. break;
  10377. }
  10378. return {
  10379. min: minFilter,
  10380. mag: magFilter
  10381. };
  10382. };
  10383. var partialLoadImg = function (url, index, loadedImages, scene, onfinish, onErrorCallBack) {
  10384. if (onErrorCallBack === void 0) { onErrorCallBack = null; }
  10385. var img;
  10386. var onload = function () {
  10387. loadedImages[index] = img;
  10388. loadedImages._internalCount++;
  10389. if (scene) {
  10390. scene._removePendingData(img);
  10391. }
  10392. if (loadedImages._internalCount === 6) {
  10393. onfinish(loadedImages);
  10394. }
  10395. };
  10396. var onerror = function (message, exception) {
  10397. if (scene) {
  10398. scene._removePendingData(img);
  10399. }
  10400. if (onErrorCallBack) {
  10401. onErrorCallBack(message, exception);
  10402. }
  10403. };
  10404. img = BABYLON.Tools.LoadImage(url, onload, onerror, scene ? scene.database : null);
  10405. if (scene) {
  10406. scene._addPendingData(img);
  10407. }
  10408. };
  10409. var cascadeLoadImgs = function (rootUrl, scene, onfinish, files, onError) {
  10410. if (onError === void 0) { onError = null; }
  10411. var loadedImages = [];
  10412. loadedImages._internalCount = 0;
  10413. for (var index = 0; index < 6; index++) {
  10414. partialLoadImg(files[index], index, loadedImages, scene, onfinish, onError);
  10415. }
  10416. };
  10417. var BufferPointer = /** @class */ (function () {
  10418. function BufferPointer() {
  10419. }
  10420. return BufferPointer;
  10421. }());
  10422. var InstancingAttributeInfo = /** @class */ (function () {
  10423. function InstancingAttributeInfo() {
  10424. }
  10425. return InstancingAttributeInfo;
  10426. }());
  10427. BABYLON.InstancingAttributeInfo = InstancingAttributeInfo;
  10428. /**
  10429. * Define options used to create a render target texture
  10430. */
  10431. var RenderTargetCreationOptions = /** @class */ (function () {
  10432. function RenderTargetCreationOptions() {
  10433. }
  10434. return RenderTargetCreationOptions;
  10435. }());
  10436. BABYLON.RenderTargetCreationOptions = RenderTargetCreationOptions;
  10437. /**
  10438. * Define options used to create a depth texture
  10439. */
  10440. var DepthTextureCreationOptions = /** @class */ (function () {
  10441. function DepthTextureCreationOptions() {
  10442. }
  10443. return DepthTextureCreationOptions;
  10444. }());
  10445. BABYLON.DepthTextureCreationOptions = DepthTextureCreationOptions;
  10446. /**
  10447. * Regroup several parameters relative to the browser in use
  10448. */
  10449. var EngineCapabilities = /** @class */ (function () {
  10450. function EngineCapabilities() {
  10451. }
  10452. return EngineCapabilities;
  10453. }());
  10454. BABYLON.EngineCapabilities = EngineCapabilities;
  10455. /**
  10456. * The engine class is responsible for interfacing with all lower-level APIs such as WebGL and Audio.
  10457. */
  10458. var Engine = /** @class */ (function () {
  10459. /**
  10460. * @constructor
  10461. * @param canvasOrContext defines the canvas or WebGL context to use for rendering
  10462. * @param antialias defines enable antialiasing (default: false)
  10463. * @param options defines further options to be sent to the getContext() function
  10464. * @param adaptToDeviceRatio defines whether to adapt to the device's viewport characteristics (default: false)
  10465. */
  10466. function Engine(canvasOrContext, antialias, options, adaptToDeviceRatio) {
  10467. if (adaptToDeviceRatio === void 0) { adaptToDeviceRatio = false; }
  10468. var _this = this;
  10469. // Public members
  10470. this.forcePOTTextures = false;
  10471. this.isFullscreen = false;
  10472. this.isPointerLock = false;
  10473. this.cullBackFaces = true;
  10474. this.renderEvenInBackground = true;
  10475. this.preventCacheWipeBetweenFrames = false;
  10476. /**
  10477. * To enable/disable IDB support and avoid XHR on .manifest
  10478. **/
  10479. this.enableOfflineSupport = false;
  10480. this.scenes = new Array();
  10481. this.postProcesses = new Array();
  10482. // Observables
  10483. /**
  10484. * Observable event triggered each time the rendering canvas is resized
  10485. */
  10486. this.onResizeObservable = new BABYLON.Observable();
  10487. /**
  10488. * Observable event triggered each time the canvas loses focus
  10489. */
  10490. this.onCanvasBlurObservable = new BABYLON.Observable();
  10491. /**
  10492. * Observable event triggered each time the canvas gains focus
  10493. */
  10494. this.onCanvasFocusObservable = new BABYLON.Observable();
  10495. /**
  10496. * Observable event triggered each time the canvas receives pointerout event
  10497. */
  10498. this.onCanvasPointerOutObservable = new BABYLON.Observable();
  10499. /**
  10500. * Observable event triggered before each texture is initialized
  10501. */
  10502. this.onBeforeTextureInitObservable = new BABYLON.Observable();
  10503. //WebVR
  10504. this._vrDisplay = undefined;
  10505. this._vrSupported = false;
  10506. this._vrExclusivePointerMode = false;
  10507. // Uniform buffers list
  10508. this.disableUniformBuffers = false;
  10509. this._uniformBuffers = new Array();
  10510. // Observables
  10511. /**
  10512. * Observable raised when the engine begins a new frame
  10513. */
  10514. this.onBeginFrameObservable = new BABYLON.Observable();
  10515. /**
  10516. * Observable raised when the engine ends the current frame
  10517. */
  10518. this.onEndFrameObservable = new BABYLON.Observable();
  10519. /**
  10520. * Observable raised when the engine is about to compile a shader
  10521. */
  10522. this.onBeforeShaderCompilationObservable = new BABYLON.Observable();
  10523. /**
  10524. * Observable raised when the engine has jsut compiled a shader
  10525. */
  10526. this.onAfterShaderCompilationObservable = new BABYLON.Observable();
  10527. this._windowIsBackground = false;
  10528. this._webGLVersion = 1.0;
  10529. this._badOS = false;
  10530. this._badDesktopOS = false;
  10531. /**
  10532. * Gets or sets a value indicating if we want to disable texture binding optmization.
  10533. * This could be required on some buggy drivers which wants to have textures bound in a progressive order
  10534. * By default Babylon.js will try to let textures bound where they are and only update the samplers to point where the texture is.
  10535. */
  10536. this.disableTextureBindingOptimization = false;
  10537. this.onVRDisplayChangedObservable = new BABYLON.Observable();
  10538. this.onVRRequestPresentComplete = new BABYLON.Observable();
  10539. this.onVRRequestPresentStart = new BABYLON.Observable();
  10540. this._colorWrite = true;
  10541. this._drawCalls = new BABYLON.PerfCounter();
  10542. this._textureCollisions = new BABYLON.PerfCounter();
  10543. this._renderingQueueLaunched = false;
  10544. this._activeRenderLoops = new Array();
  10545. // Deterministic lockstepMaxSteps
  10546. this._deterministicLockstep = false;
  10547. this._lockstepMaxSteps = 4;
  10548. // Lost context
  10549. this.onContextLostObservable = new BABYLON.Observable();
  10550. this.onContextRestoredObservable = new BABYLON.Observable();
  10551. this._contextWasLost = false;
  10552. this._doNotHandleContextLost = false;
  10553. // FPS
  10554. this._performanceMonitor = new BABYLON.PerformanceMonitor();
  10555. this._fps = 60;
  10556. this._deltaTime = 0;
  10557. /**
  10558. * Turn this value on if you want to pause FPS computation when in background
  10559. */
  10560. this.disablePerformanceMonitorInBackground = false;
  10561. // States
  10562. this._depthCullingState = new BABYLON._DepthCullingState();
  10563. this._stencilState = new BABYLON._StencilState();
  10564. this._alphaState = new BABYLON._AlphaState();
  10565. this._alphaMode = Engine.ALPHA_DISABLE;
  10566. // Cache
  10567. this._internalTexturesCache = new Array();
  10568. this._activeChannel = 0;
  10569. this._currentTextureChannel = -1;
  10570. this._boundTexturesCache = {};
  10571. this._compiledEffects = {};
  10572. this._vertexAttribArraysEnabled = [];
  10573. this._uintIndicesCurrentlySet = false;
  10574. this._currentBoundBuffer = new Array();
  10575. this._currentBufferPointers = new Array();
  10576. this._currentInstanceLocations = new Array();
  10577. this._currentInstanceBuffers = new Array();
  10578. this._firstBoundInternalTextureTracker = new BABYLON.DummyInternalTextureTracker();
  10579. this._lastBoundInternalTextureTracker = new BABYLON.DummyInternalTextureTracker();
  10580. this._vaoRecordInProgress = false;
  10581. this._mustWipeVertexAttributes = false;
  10582. this._nextFreeTextureSlots = new Array();
  10583. this._maxSimultaneousTextures = 0;
  10584. this._activeRequests = new Array();
  10585. // Hardware supported Compressed Textures
  10586. this._texturesSupported = new Array();
  10587. this._onVRFullScreenTriggered = function () {
  10588. if (_this._vrDisplay && _this._vrDisplay.isPresenting) {
  10589. //get the old size before we change
  10590. _this._oldSize = new BABYLON.Size(_this.getRenderWidth(), _this.getRenderHeight());
  10591. _this._oldHardwareScaleFactor = _this.getHardwareScalingLevel();
  10592. //get the width and height, change the render size
  10593. var leftEye = _this._vrDisplay.getEyeParameters('left');
  10594. _this.setHardwareScalingLevel(1);
  10595. _this.setSize(leftEye.renderWidth * 2, leftEye.renderHeight);
  10596. }
  10597. else {
  10598. _this.setHardwareScalingLevel(_this._oldHardwareScaleFactor);
  10599. _this.setSize(_this._oldSize.width, _this._oldSize.height);
  10600. }
  10601. };
  10602. this._boundUniforms = {};
  10603. // Register promises
  10604. BABYLON.PromisePolyfill.Apply();
  10605. var canvas = null;
  10606. Engine.Instances.push(this);
  10607. if (!canvasOrContext) {
  10608. return;
  10609. }
  10610. options = options || {};
  10611. if (canvasOrContext.getContext) {
  10612. canvas = canvasOrContext;
  10613. this._renderingCanvas = canvas;
  10614. if (antialias != null) {
  10615. options.antialias = antialias;
  10616. }
  10617. if (options.deterministicLockstep === undefined) {
  10618. options.deterministicLockstep = false;
  10619. }
  10620. if (options.lockstepMaxSteps === undefined) {
  10621. options.lockstepMaxSteps = 4;
  10622. }
  10623. if (options.preserveDrawingBuffer === undefined) {
  10624. options.preserveDrawingBuffer = false;
  10625. }
  10626. if (options.audioEngine === undefined) {
  10627. options.audioEngine = true;
  10628. }
  10629. if (options.stencil === undefined) {
  10630. options.stencil = true;
  10631. }
  10632. this._deterministicLockstep = options.deterministicLockstep;
  10633. this._lockstepMaxSteps = options.lockstepMaxSteps;
  10634. this._doNotHandleContextLost = options.doNotHandleContextLost ? true : false;
  10635. // Exceptions
  10636. if (navigator && navigator.userAgent) {
  10637. var ua = navigator.userAgent;
  10638. for (var _i = 0, _a = Engine.ExceptionList; _i < _a.length; _i++) {
  10639. var exception = _a[_i];
  10640. var key = exception.key;
  10641. var targets = exception.targets;
  10642. if (ua.indexOf(key) > -1) {
  10643. if (exception.capture && exception.captureConstraint) {
  10644. var capture = exception.capture;
  10645. var constraint = exception.captureConstraint;
  10646. var regex = new RegExp(capture);
  10647. var matches = regex.exec(ua);
  10648. if (matches && matches.length > 0) {
  10649. var capturedValue = parseInt(matches[matches.length - 1]);
  10650. if (capturedValue >= constraint) {
  10651. continue;
  10652. }
  10653. }
  10654. }
  10655. for (var _b = 0, targets_1 = targets; _b < targets_1.length; _b++) {
  10656. var target = targets_1[_b];
  10657. switch (target) {
  10658. case "uniformBuffer":
  10659. this.disableUniformBuffers = true;
  10660. break;
  10661. case "textureBindingOptimization":
  10662. this.disableTextureBindingOptimization = true;
  10663. break;
  10664. }
  10665. }
  10666. }
  10667. }
  10668. }
  10669. // GL
  10670. if (!options.disableWebGL2Support) {
  10671. try {
  10672. this._gl = (canvas.getContext("webgl2", options) || canvas.getContext("experimental-webgl2", options));
  10673. if (this._gl) {
  10674. this._webGLVersion = 2.0;
  10675. }
  10676. }
  10677. catch (e) {
  10678. // Do nothing
  10679. }
  10680. }
  10681. if (!this._gl) {
  10682. if (!canvas) {
  10683. throw new Error("The provided canvas is null or undefined.");
  10684. }
  10685. try {
  10686. this._gl = (canvas.getContext("webgl", options) || canvas.getContext("experimental-webgl", options));
  10687. }
  10688. catch (e) {
  10689. throw new Error("WebGL not supported");
  10690. }
  10691. }
  10692. if (!this._gl) {
  10693. throw new Error("WebGL not supported");
  10694. }
  10695. this._onCanvasFocus = function () {
  10696. _this.onCanvasFocusObservable.notifyObservers(_this);
  10697. };
  10698. this._onCanvasBlur = function () {
  10699. _this.onCanvasBlurObservable.notifyObservers(_this);
  10700. };
  10701. canvas.addEventListener("focus", this._onCanvasFocus);
  10702. canvas.addEventListener("blur", this._onCanvasBlur);
  10703. this._onBlur = function () {
  10704. if (_this.disablePerformanceMonitorInBackground) {
  10705. _this._performanceMonitor.disable();
  10706. }
  10707. _this._windowIsBackground = true;
  10708. };
  10709. this._onFocus = function () {
  10710. if (_this.disablePerformanceMonitorInBackground) {
  10711. _this._performanceMonitor.enable();
  10712. }
  10713. _this._windowIsBackground = false;
  10714. };
  10715. this._onCanvasPointerOut = function (ev) {
  10716. _this.onCanvasPointerOutObservable.notifyObservers(ev);
  10717. };
  10718. window.addEventListener("blur", this._onBlur);
  10719. window.addEventListener("focus", this._onFocus);
  10720. canvas.addEventListener("pointerout", this._onCanvasPointerOut);
  10721. // Context lost
  10722. if (!this._doNotHandleContextLost) {
  10723. this._onContextLost = function (evt) {
  10724. evt.preventDefault();
  10725. _this._contextWasLost = true;
  10726. BABYLON.Tools.Warn("WebGL context lost.");
  10727. _this.onContextLostObservable.notifyObservers(_this);
  10728. };
  10729. this._onContextRestored = function (evt) {
  10730. // Adding a timeout to avoid race condition at browser level
  10731. setTimeout(function () {
  10732. // Rebuild gl context
  10733. _this._initGLContext();
  10734. // Rebuild effects
  10735. _this._rebuildEffects();
  10736. // Rebuild textures
  10737. _this._rebuildInternalTextures();
  10738. // Rebuild buffers
  10739. _this._rebuildBuffers();
  10740. // Cache
  10741. _this.wipeCaches(true);
  10742. BABYLON.Tools.Warn("WebGL context successfully restored.");
  10743. _this.onContextRestoredObservable.notifyObservers(_this);
  10744. _this._contextWasLost = false;
  10745. }, 0);
  10746. };
  10747. canvas.addEventListener("webglcontextlost", this._onContextLost, false);
  10748. canvas.addEventListener("webglcontextrestored", this._onContextRestored, false);
  10749. }
  10750. }
  10751. else {
  10752. this._gl = canvasOrContext;
  10753. this._renderingCanvas = this._gl.canvas;
  10754. if (this._gl.renderbufferStorageMultisample) {
  10755. this._webGLVersion = 2.0;
  10756. }
  10757. options.stencil = this._gl.getContextAttributes().stencil;
  10758. }
  10759. // Viewport
  10760. var limitDeviceRatio = options.limitDeviceRatio || window.devicePixelRatio || 1.0;
  10761. this._hardwareScalingLevel = adaptToDeviceRatio ? 1.0 / Math.min(limitDeviceRatio, window.devicePixelRatio || 1.0) : 1.0;
  10762. this.resize();
  10763. this._isStencilEnable = options.stencil ? true : false;
  10764. this._initGLContext();
  10765. if (canvas) {
  10766. // Fullscreen
  10767. this._onFullscreenChange = function () {
  10768. if (document.fullscreen !== undefined) {
  10769. _this.isFullscreen = document.fullscreen;
  10770. }
  10771. else if (document.mozFullScreen !== undefined) {
  10772. _this.isFullscreen = document.mozFullScreen;
  10773. }
  10774. else if (document.webkitIsFullScreen !== undefined) {
  10775. _this.isFullscreen = document.webkitIsFullScreen;
  10776. }
  10777. else if (document.msIsFullScreen !== undefined) {
  10778. _this.isFullscreen = document.msIsFullScreen;
  10779. }
  10780. // Pointer lock
  10781. if (_this.isFullscreen && _this._pointerLockRequested && canvas) {
  10782. canvas.requestPointerLock = canvas.requestPointerLock ||
  10783. canvas.msRequestPointerLock ||
  10784. canvas.mozRequestPointerLock ||
  10785. canvas.webkitRequestPointerLock;
  10786. if (canvas.requestPointerLock) {
  10787. canvas.requestPointerLock();
  10788. }
  10789. }
  10790. };
  10791. document.addEventListener("fullscreenchange", this._onFullscreenChange, false);
  10792. document.addEventListener("mozfullscreenchange", this._onFullscreenChange, false);
  10793. document.addEventListener("webkitfullscreenchange", this._onFullscreenChange, false);
  10794. document.addEventListener("msfullscreenchange", this._onFullscreenChange, false);
  10795. // Pointer lock
  10796. this._onPointerLockChange = function () {
  10797. _this.isPointerLock = (document.mozPointerLockElement === canvas ||
  10798. document.webkitPointerLockElement === canvas ||
  10799. document.msPointerLockElement === canvas ||
  10800. document.pointerLockElement === canvas);
  10801. };
  10802. document.addEventListener("pointerlockchange", this._onPointerLockChange, false);
  10803. document.addEventListener("mspointerlockchange", this._onPointerLockChange, false);
  10804. document.addEventListener("mozpointerlockchange", this._onPointerLockChange, false);
  10805. document.addEventListener("webkitpointerlockchange", this._onPointerLockChange, false);
  10806. this._onVRDisplayPointerRestricted = function () {
  10807. if (canvas) {
  10808. canvas.requestPointerLock();
  10809. }
  10810. };
  10811. this._onVRDisplayPointerUnrestricted = function () {
  10812. document.exitPointerLock();
  10813. };
  10814. window.addEventListener('vrdisplaypointerrestricted', this._onVRDisplayPointerRestricted, false);
  10815. window.addEventListener('vrdisplaypointerunrestricted', this._onVRDisplayPointerUnrestricted, false);
  10816. }
  10817. if (options.audioEngine && BABYLON.AudioEngine && !Engine.audioEngine) {
  10818. Engine.audioEngine = new BABYLON.AudioEngine();
  10819. }
  10820. // Prepare buffer pointers
  10821. for (var i = 0; i < this._caps.maxVertexAttribs; i++) {
  10822. this._currentBufferPointers[i] = new BufferPointer();
  10823. }
  10824. this._linkTrackers(this._firstBoundInternalTextureTracker, this._lastBoundInternalTextureTracker);
  10825. // Load WebVR Devices
  10826. if (options.autoEnableWebVR) {
  10827. this.initWebVR();
  10828. }
  10829. // Detect if we are running on a faulty buggy OS.
  10830. this._badOS = /iPad/i.test(navigator.userAgent) || /iPhone/i.test(navigator.userAgent);
  10831. // Detect if we are running on a faulty buggy desktop OS.
  10832. this._badDesktopOS = /^((?!chrome|android).)*safari/i.test(navigator.userAgent);
  10833. console.log("Babylon.js engine (v" + Engine.Version + ") launched");
  10834. this.enableOfflineSupport = (BABYLON.Database !== undefined);
  10835. }
  10836. Object.defineProperty(Engine, "LastCreatedEngine", {
  10837. get: function () {
  10838. if (Engine.Instances.length === 0) {
  10839. return null;
  10840. }
  10841. return Engine.Instances[Engine.Instances.length - 1];
  10842. },
  10843. enumerable: true,
  10844. configurable: true
  10845. });
  10846. Object.defineProperty(Engine, "LastCreatedScene", {
  10847. get: function () {
  10848. var lastCreatedEngine = Engine.LastCreatedEngine;
  10849. if (!lastCreatedEngine) {
  10850. return null;
  10851. }
  10852. if (lastCreatedEngine.scenes.length === 0) {
  10853. return null;
  10854. }
  10855. return lastCreatedEngine.scenes[lastCreatedEngine.scenes.length - 1];
  10856. },
  10857. enumerable: true,
  10858. configurable: true
  10859. });
  10860. /**
  10861. * Will flag all materials in all scenes in all engines as dirty to trigger new shader compilation
  10862. */
  10863. Engine.MarkAllMaterialsAsDirty = function (flag, predicate) {
  10864. for (var engineIndex = 0; engineIndex < Engine.Instances.length; engineIndex++) {
  10865. var engine = Engine.Instances[engineIndex];
  10866. for (var sceneIndex = 0; sceneIndex < engine.scenes.length; sceneIndex++) {
  10867. engine.scenes[sceneIndex].markAllMaterialsAsDirty(flag, predicate);
  10868. }
  10869. }
  10870. };
  10871. Object.defineProperty(Engine, "NEVER", {
  10872. get: function () {
  10873. return Engine._NEVER;
  10874. },
  10875. enumerable: true,
  10876. configurable: true
  10877. });
  10878. Object.defineProperty(Engine, "ALWAYS", {
  10879. get: function () {
  10880. return Engine._ALWAYS;
  10881. },
  10882. enumerable: true,
  10883. configurable: true
  10884. });
  10885. Object.defineProperty(Engine, "LESS", {
  10886. get: function () {
  10887. return Engine._LESS;
  10888. },
  10889. enumerable: true,
  10890. configurable: true
  10891. });
  10892. Object.defineProperty(Engine, "EQUAL", {
  10893. get: function () {
  10894. return Engine._EQUAL;
  10895. },
  10896. enumerable: true,
  10897. configurable: true
  10898. });
  10899. Object.defineProperty(Engine, "LEQUAL", {
  10900. get: function () {
  10901. return Engine._LEQUAL;
  10902. },
  10903. enumerable: true,
  10904. configurable: true
  10905. });
  10906. Object.defineProperty(Engine, "GREATER", {
  10907. get: function () {
  10908. return Engine._GREATER;
  10909. },
  10910. enumerable: true,
  10911. configurable: true
  10912. });
  10913. Object.defineProperty(Engine, "GEQUAL", {
  10914. get: function () {
  10915. return Engine._GEQUAL;
  10916. },
  10917. enumerable: true,
  10918. configurable: true
  10919. });
  10920. Object.defineProperty(Engine, "NOTEQUAL", {
  10921. get: function () {
  10922. return Engine._NOTEQUAL;
  10923. },
  10924. enumerable: true,
  10925. configurable: true
  10926. });
  10927. Object.defineProperty(Engine, "KEEP", {
  10928. get: function () {
  10929. return Engine._KEEP;
  10930. },
  10931. enumerable: true,
  10932. configurable: true
  10933. });
  10934. Object.defineProperty(Engine, "REPLACE", {
  10935. get: function () {
  10936. return Engine._REPLACE;
  10937. },
  10938. enumerable: true,
  10939. configurable: true
  10940. });
  10941. Object.defineProperty(Engine, "INCR", {
  10942. get: function () {
  10943. return Engine._INCR;
  10944. },
  10945. enumerable: true,
  10946. configurable: true
  10947. });
  10948. Object.defineProperty(Engine, "DECR", {
  10949. get: function () {
  10950. return Engine._DECR;
  10951. },
  10952. enumerable: true,
  10953. configurable: true
  10954. });
  10955. Object.defineProperty(Engine, "INVERT", {
  10956. get: function () {
  10957. return Engine._INVERT;
  10958. },
  10959. enumerable: true,
  10960. configurable: true
  10961. });
  10962. Object.defineProperty(Engine, "INCR_WRAP", {
  10963. get: function () {
  10964. return Engine._INCR_WRAP;
  10965. },
  10966. enumerable: true,
  10967. configurable: true
  10968. });
  10969. Object.defineProperty(Engine, "DECR_WRAP", {
  10970. get: function () {
  10971. return Engine._DECR_WRAP;
  10972. },
  10973. enumerable: true,
  10974. configurable: true
  10975. });
  10976. Object.defineProperty(Engine, "ALPHA_DISABLE", {
  10977. get: function () {
  10978. return Engine._ALPHA_DISABLE;
  10979. },
  10980. enumerable: true,
  10981. configurable: true
  10982. });
  10983. Object.defineProperty(Engine, "ALPHA_ONEONE", {
  10984. get: function () {
  10985. return Engine._ALPHA_ONEONE;
  10986. },
  10987. enumerable: true,
  10988. configurable: true
  10989. });
  10990. Object.defineProperty(Engine, "ALPHA_ADD", {
  10991. get: function () {
  10992. return Engine._ALPHA_ADD;
  10993. },
  10994. enumerable: true,
  10995. configurable: true
  10996. });
  10997. Object.defineProperty(Engine, "ALPHA_COMBINE", {
  10998. get: function () {
  10999. return Engine._ALPHA_COMBINE;
  11000. },
  11001. enumerable: true,
  11002. configurable: true
  11003. });
  11004. Object.defineProperty(Engine, "ALPHA_SUBTRACT", {
  11005. get: function () {
  11006. return Engine._ALPHA_SUBTRACT;
  11007. },
  11008. enumerable: true,
  11009. configurable: true
  11010. });
  11011. Object.defineProperty(Engine, "ALPHA_MULTIPLY", {
  11012. get: function () {
  11013. return Engine._ALPHA_MULTIPLY;
  11014. },
  11015. enumerable: true,
  11016. configurable: true
  11017. });
  11018. Object.defineProperty(Engine, "ALPHA_MAXIMIZED", {
  11019. get: function () {
  11020. return Engine._ALPHA_MAXIMIZED;
  11021. },
  11022. enumerable: true,
  11023. configurable: true
  11024. });
  11025. Object.defineProperty(Engine, "ALPHA_PREMULTIPLIED", {
  11026. get: function () {
  11027. return Engine._ALPHA_PREMULTIPLIED;
  11028. },
  11029. enumerable: true,
  11030. configurable: true
  11031. });
  11032. Object.defineProperty(Engine, "ALPHA_PREMULTIPLIED_PORTERDUFF", {
  11033. get: function () {
  11034. return Engine._ALPHA_PREMULTIPLIED_PORTERDUFF;
  11035. },
  11036. enumerable: true,
  11037. configurable: true
  11038. });
  11039. Object.defineProperty(Engine, "ALPHA_INTERPOLATE", {
  11040. get: function () {
  11041. return Engine._ALPHA_INTERPOLATE;
  11042. },
  11043. enumerable: true,
  11044. configurable: true
  11045. });
  11046. Object.defineProperty(Engine, "ALPHA_SCREENMODE", {
  11047. get: function () {
  11048. return Engine._ALPHA_SCREENMODE;
  11049. },
  11050. enumerable: true,
  11051. configurable: true
  11052. });
  11053. Object.defineProperty(Engine, "DELAYLOADSTATE_NONE", {
  11054. get: function () {
  11055. return Engine._DELAYLOADSTATE_NONE;
  11056. },
  11057. enumerable: true,
  11058. configurable: true
  11059. });
  11060. Object.defineProperty(Engine, "DELAYLOADSTATE_LOADED", {
  11061. get: function () {
  11062. return Engine._DELAYLOADSTATE_LOADED;
  11063. },
  11064. enumerable: true,
  11065. configurable: true
  11066. });
  11067. Object.defineProperty(Engine, "DELAYLOADSTATE_LOADING", {
  11068. get: function () {
  11069. return Engine._DELAYLOADSTATE_LOADING;
  11070. },
  11071. enumerable: true,
  11072. configurable: true
  11073. });
  11074. Object.defineProperty(Engine, "DELAYLOADSTATE_NOTLOADED", {
  11075. get: function () {
  11076. return Engine._DELAYLOADSTATE_NOTLOADED;
  11077. },
  11078. enumerable: true,
  11079. configurable: true
  11080. });
  11081. Object.defineProperty(Engine, "TEXTUREFORMAT_ALPHA", {
  11082. get: function () {
  11083. return Engine._TEXTUREFORMAT_ALPHA;
  11084. },
  11085. enumerable: true,
  11086. configurable: true
  11087. });
  11088. Object.defineProperty(Engine, "TEXTUREFORMAT_LUMINANCE", {
  11089. get: function () {
  11090. return Engine._TEXTUREFORMAT_LUMINANCE;
  11091. },
  11092. enumerable: true,
  11093. configurable: true
  11094. });
  11095. Object.defineProperty(Engine, "TEXTUREFORMAT_R32F", {
  11096. /**
  11097. * R32F
  11098. */
  11099. get: function () {
  11100. return Engine._TEXTUREFORMAT_R32F;
  11101. },
  11102. enumerable: true,
  11103. configurable: true
  11104. });
  11105. Object.defineProperty(Engine, "TEXTUREFORMAT_RG32F", {
  11106. /**
  11107. * RG32F
  11108. */
  11109. get: function () {
  11110. return Engine._TEXTUREFORMAT_RG32F;
  11111. },
  11112. enumerable: true,
  11113. configurable: true
  11114. });
  11115. Object.defineProperty(Engine, "TEXTUREFORMAT_RGB32F", {
  11116. /**
  11117. * RGB32F
  11118. */
  11119. get: function () {
  11120. return Engine._TEXTUREFORMAT_RGB32F;
  11121. },
  11122. enumerable: true,
  11123. configurable: true
  11124. });
  11125. Object.defineProperty(Engine, "TEXTUREFORMAT_RGBA32F", {
  11126. /**
  11127. * RGBA32F
  11128. */
  11129. get: function () {
  11130. return Engine._TEXTUREFORMAT_RGBA32F;
  11131. },
  11132. enumerable: true,
  11133. configurable: true
  11134. });
  11135. Object.defineProperty(Engine, "TEXTUREFORMAT_LUMINANCE_ALPHA", {
  11136. get: function () {
  11137. return Engine._TEXTUREFORMAT_LUMINANCE_ALPHA;
  11138. },
  11139. enumerable: true,
  11140. configurable: true
  11141. });
  11142. Object.defineProperty(Engine, "TEXTUREFORMAT_RGB", {
  11143. get: function () {
  11144. return Engine._TEXTUREFORMAT_RGB;
  11145. },
  11146. enumerable: true,
  11147. configurable: true
  11148. });
  11149. Object.defineProperty(Engine, "TEXTUREFORMAT_RGBA", {
  11150. get: function () {
  11151. return Engine._TEXTUREFORMAT_RGBA;
  11152. },
  11153. enumerable: true,
  11154. configurable: true
  11155. });
  11156. Object.defineProperty(Engine, "TEXTURETYPE_UNSIGNED_INT", {
  11157. get: function () {
  11158. return Engine._TEXTURETYPE_UNSIGNED_INT;
  11159. },
  11160. enumerable: true,
  11161. configurable: true
  11162. });
  11163. Object.defineProperty(Engine, "TEXTURETYPE_FLOAT", {
  11164. get: function () {
  11165. return Engine._TEXTURETYPE_FLOAT;
  11166. },
  11167. enumerable: true,
  11168. configurable: true
  11169. });
  11170. Object.defineProperty(Engine, "TEXTURETYPE_HALF_FLOAT", {
  11171. get: function () {
  11172. return Engine._TEXTURETYPE_HALF_FLOAT;
  11173. },
  11174. enumerable: true,
  11175. configurable: true
  11176. });
  11177. Object.defineProperty(Engine, "SCALEMODE_FLOOR", {
  11178. get: function () {
  11179. return Engine._SCALEMODE_FLOOR;
  11180. },
  11181. enumerable: true,
  11182. configurable: true
  11183. });
  11184. Object.defineProperty(Engine, "SCALEMODE_NEAREST", {
  11185. get: function () {
  11186. return Engine._SCALEMODE_NEAREST;
  11187. },
  11188. enumerable: true,
  11189. configurable: true
  11190. });
  11191. Object.defineProperty(Engine, "SCALEMODE_CEILING", {
  11192. get: function () {
  11193. return Engine._SCALEMODE_CEILING;
  11194. },
  11195. enumerable: true,
  11196. configurable: true
  11197. });
  11198. Object.defineProperty(Engine, "Version", {
  11199. get: function () {
  11200. return "3.2.0-beta.2";
  11201. },
  11202. enumerable: true,
  11203. configurable: true
  11204. });
  11205. Object.defineProperty(Engine.prototype, "isInVRExclusivePointerMode", {
  11206. get: function () {
  11207. return this._vrExclusivePointerMode;
  11208. },
  11209. enumerable: true,
  11210. configurable: true
  11211. });
  11212. Object.defineProperty(Engine.prototype, "supportsUniformBuffers", {
  11213. get: function () {
  11214. return this.webGLVersion > 1 && !this.disableUniformBuffers;
  11215. },
  11216. enumerable: true,
  11217. configurable: true
  11218. });
  11219. Object.defineProperty(Engine.prototype, "needPOTTextures", {
  11220. get: function () {
  11221. return this._webGLVersion < 2 || this.forcePOTTextures;
  11222. },
  11223. enumerable: true,
  11224. configurable: true
  11225. });
  11226. Object.defineProperty(Engine.prototype, "badOS", {
  11227. get: function () {
  11228. return this._badOS;
  11229. },
  11230. enumerable: true,
  11231. configurable: true
  11232. });
  11233. Object.defineProperty(Engine.prototype, "badDesktopOS", {
  11234. get: function () {
  11235. return this._badDesktopOS;
  11236. },
  11237. enumerable: true,
  11238. configurable: true
  11239. });
  11240. Object.defineProperty(Engine.prototype, "performanceMonitor", {
  11241. get: function () {
  11242. return this._performanceMonitor;
  11243. },
  11244. enumerable: true,
  11245. configurable: true
  11246. });
  11247. Object.defineProperty(Engine.prototype, "texturesSupported", {
  11248. get: function () {
  11249. return this._texturesSupported;
  11250. },
  11251. enumerable: true,
  11252. configurable: true
  11253. });
  11254. Object.defineProperty(Engine.prototype, "textureFormatInUse", {
  11255. get: function () {
  11256. return this._textureFormatInUse;
  11257. },
  11258. enumerable: true,
  11259. configurable: true
  11260. });
  11261. Object.defineProperty(Engine.prototype, "currentViewport", {
  11262. get: function () {
  11263. return this._cachedViewport;
  11264. },
  11265. enumerable: true,
  11266. configurable: true
  11267. });
  11268. Object.defineProperty(Engine.prototype, "emptyTexture", {
  11269. // Empty texture
  11270. get: function () {
  11271. if (!this._emptyTexture) {
  11272. this._emptyTexture = this.createRawTexture(new Uint8Array(4), 1, 1, Engine.TEXTUREFORMAT_RGBA, false, false, BABYLON.Texture.NEAREST_SAMPLINGMODE);
  11273. }
  11274. return this._emptyTexture;
  11275. },
  11276. enumerable: true,
  11277. configurable: true
  11278. });
  11279. Object.defineProperty(Engine.prototype, "emptyTexture3D", {
  11280. get: function () {
  11281. if (!this._emptyTexture3D) {
  11282. this._emptyTexture3D = this.createRawTexture3D(new Uint8Array(4), 1, 1, 1, Engine.TEXTUREFORMAT_RGBA, false, false, BABYLON.Texture.NEAREST_SAMPLINGMODE);
  11283. }
  11284. return this._emptyTexture3D;
  11285. },
  11286. enumerable: true,
  11287. configurable: true
  11288. });
  11289. Object.defineProperty(Engine.prototype, "emptyCubeTexture", {
  11290. get: function () {
  11291. if (!this._emptyCubeTexture) {
  11292. var faceData = new Uint8Array(4);
  11293. var cubeData = [faceData, faceData, faceData, faceData, faceData, faceData];
  11294. this._emptyCubeTexture = this.createRawCubeTexture(cubeData, 1, Engine.TEXTUREFORMAT_RGBA, Engine.TEXTURETYPE_UNSIGNED_INT, false, false, BABYLON.Texture.NEAREST_SAMPLINGMODE);
  11295. }
  11296. return this._emptyCubeTexture;
  11297. },
  11298. enumerable: true,
  11299. configurable: true
  11300. });
  11301. Engine.prototype._rebuildInternalTextures = function () {
  11302. var currentState = this._internalTexturesCache.slice(); // Do a copy because the rebuild will add proxies
  11303. for (var _i = 0, currentState_1 = currentState; _i < currentState_1.length; _i++) {
  11304. var internalTexture = currentState_1[_i];
  11305. internalTexture._rebuild();
  11306. }
  11307. };
  11308. Engine.prototype._rebuildEffects = function () {
  11309. for (var key in this._compiledEffects) {
  11310. var effect = this._compiledEffects[key];
  11311. effect._prepareEffect();
  11312. }
  11313. BABYLON.Effect.ResetCache();
  11314. };
  11315. Engine.prototype._rebuildBuffers = function () {
  11316. // Index / Vertex
  11317. for (var _i = 0, _a = this.scenes; _i < _a.length; _i++) {
  11318. var scene = _a[_i];
  11319. scene.resetCachedMaterial();
  11320. scene._rebuildGeometries();
  11321. scene._rebuildTextures();
  11322. }
  11323. // Uniforms
  11324. for (var _b = 0, _c = this._uniformBuffers; _b < _c.length; _b++) {
  11325. var uniformBuffer = _c[_b];
  11326. uniformBuffer._rebuild();
  11327. }
  11328. };
  11329. Engine.prototype._initGLContext = function () {
  11330. // Caps
  11331. this._caps = new EngineCapabilities();
  11332. this._caps.maxTexturesImageUnits = this._gl.getParameter(this._gl.MAX_TEXTURE_IMAGE_UNITS);
  11333. this._caps.maxCombinedTexturesImageUnits = this._gl.getParameter(this._gl.MAX_COMBINED_TEXTURE_IMAGE_UNITS);
  11334. this._caps.maxVertexTextureImageUnits = this._gl.getParameter(this._gl.MAX_VERTEX_TEXTURE_IMAGE_UNITS);
  11335. this._caps.maxTextureSize = this._gl.getParameter(this._gl.MAX_TEXTURE_SIZE);
  11336. this._caps.maxCubemapTextureSize = this._gl.getParameter(this._gl.MAX_CUBE_MAP_TEXTURE_SIZE);
  11337. this._caps.maxRenderTextureSize = this._gl.getParameter(this._gl.MAX_RENDERBUFFER_SIZE);
  11338. this._caps.maxVertexAttribs = this._gl.getParameter(this._gl.MAX_VERTEX_ATTRIBS);
  11339. this._caps.maxVaryingVectors = this._gl.getParameter(this._gl.MAX_VARYING_VECTORS);
  11340. this._caps.maxFragmentUniformVectors = this._gl.getParameter(this._gl.MAX_FRAGMENT_UNIFORM_VECTORS);
  11341. this._caps.maxVertexUniformVectors = this._gl.getParameter(this._gl.MAX_VERTEX_UNIFORM_VECTORS);
  11342. // Infos
  11343. this._glVersion = this._gl.getParameter(this._gl.VERSION);
  11344. var rendererInfo = this._gl.getExtension("WEBGL_debug_renderer_info");
  11345. if (rendererInfo != null) {
  11346. this._glRenderer = this._gl.getParameter(rendererInfo.UNMASKED_RENDERER_WEBGL);
  11347. this._glVendor = this._gl.getParameter(rendererInfo.UNMASKED_VENDOR_WEBGL);
  11348. }
  11349. if (!this._glVendor) {
  11350. this._glVendor = "Unknown vendor";
  11351. }
  11352. if (!this._glRenderer) {
  11353. this._glRenderer = "Unknown renderer";
  11354. }
  11355. // Constants
  11356. this._gl.HALF_FLOAT_OES = 0x8D61; // Half floating-point type (16-bit).
  11357. if (this._gl.RGBA16F !== 0x881A) {
  11358. this._gl.RGBA16F = 0x881A; // RGBA 16-bit floating-point color-renderable internal sized format.
  11359. }
  11360. if (this._gl.RGBA32F !== 0x8814) {
  11361. this._gl.RGBA32F = 0x8814; // RGBA 32-bit floating-point color-renderable internal sized format.
  11362. }
  11363. if (this._gl.DEPTH24_STENCIL8 !== 35056) {
  11364. this._gl.DEPTH24_STENCIL8 = 35056;
  11365. }
  11366. // Extensions
  11367. this._caps.standardDerivatives = this._webGLVersion > 1 || (this._gl.getExtension('OES_standard_derivatives') !== null);
  11368. this._caps.astc = this._gl.getExtension('WEBGL_compressed_texture_astc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_astc');
  11369. this._caps.s3tc = this._gl.getExtension('WEBGL_compressed_texture_s3tc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_s3tc');
  11370. this._caps.pvrtc = this._gl.getExtension('WEBGL_compressed_texture_pvrtc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_pvrtc');
  11371. this._caps.etc1 = this._gl.getExtension('WEBGL_compressed_texture_etc1') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_etc1');
  11372. this._caps.etc2 = this._gl.getExtension('WEBGL_compressed_texture_etc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_etc') ||
  11373. this._gl.getExtension('WEBGL_compressed_texture_es3_0'); // also a requirement of OpenGL ES 3
  11374. 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');
  11375. this._caps.maxAnisotropy = this._caps.textureAnisotropicFilterExtension ? this._gl.getParameter(this._caps.textureAnisotropicFilterExtension.MAX_TEXTURE_MAX_ANISOTROPY_EXT) : 0;
  11376. this._caps.uintIndices = this._webGLVersion > 1 || this._gl.getExtension('OES_element_index_uint') !== null;
  11377. this._caps.fragmentDepthSupported = this._webGLVersion > 1 || this._gl.getExtension('EXT_frag_depth') !== null;
  11378. this._caps.highPrecisionShaderSupported = true;
  11379. this._caps.timerQuery = this._gl.getExtension('EXT_disjoint_timer_query_webgl2') || this._gl.getExtension("EXT_disjoint_timer_query");
  11380. if (this._caps.timerQuery) {
  11381. if (this._webGLVersion === 1) {
  11382. this._gl.getQuery = this._caps.timerQuery.getQueryEXT.bind(this._caps.timerQuery);
  11383. }
  11384. this._caps.canUseTimestampForTimerQuery = this._gl.getQuery(this._caps.timerQuery.TIMESTAMP_EXT, this._caps.timerQuery.QUERY_COUNTER_BITS_EXT) > 0;
  11385. }
  11386. // Checks if some of the format renders first to allow the use of webgl inspector.
  11387. this._caps.colorBufferFloat = this._webGLVersion > 1 && this._gl.getExtension('EXT_color_buffer_float');
  11388. this._caps.textureFloat = (this._webGLVersion > 1 || this._gl.getExtension('OES_texture_float')) ? true : false;
  11389. this._caps.textureFloatLinearFiltering = this._caps.textureFloat && this._gl.getExtension('OES_texture_float_linear') ? true : false;
  11390. this._caps.textureFloatRender = this._caps.textureFloat && this._canRenderToFloatFramebuffer() ? true : false;
  11391. this._caps.textureHalfFloat = (this._webGLVersion > 1 || this._gl.getExtension('OES_texture_half_float')) ? true : false;
  11392. this._caps.textureHalfFloatLinearFiltering = (this._webGLVersion > 1 || (this._caps.textureHalfFloat && this._gl.getExtension('OES_texture_half_float_linear'))) ? true : false;
  11393. if (this._webGLVersion > 1) {
  11394. this._gl.HALF_FLOAT_OES = 0x140B;
  11395. }
  11396. this._caps.textureHalfFloatRender = this._caps.textureHalfFloat && this._canRenderToHalfFloatFramebuffer();
  11397. this._caps.textureLOD = (this._webGLVersion > 1 || this._gl.getExtension('EXT_shader_texture_lod')) ? true : false;
  11398. // Draw buffers
  11399. if (this._webGLVersion > 1) {
  11400. this._caps.drawBuffersExtension = true;
  11401. }
  11402. else {
  11403. var drawBuffersExtension = this._gl.getExtension('WEBGL_draw_buffers');
  11404. if (drawBuffersExtension !== null) {
  11405. this._caps.drawBuffersExtension = true;
  11406. this._gl.drawBuffers = drawBuffersExtension.drawBuffersWEBGL.bind(drawBuffersExtension);
  11407. this._gl.DRAW_FRAMEBUFFER = this._gl.FRAMEBUFFER;
  11408. for (var i = 0; i < 16; i++) {
  11409. this._gl["COLOR_ATTACHMENT" + i + "_WEBGL"] = drawBuffersExtension["COLOR_ATTACHMENT" + i + "_WEBGL"];
  11410. }
  11411. }
  11412. else {
  11413. this._caps.drawBuffersExtension = false;
  11414. }
  11415. }
  11416. // Depth Texture
  11417. if (this._webGLVersion > 1) {
  11418. this._caps.depthTextureExtension = true;
  11419. }
  11420. else {
  11421. var depthTextureExtension = this._gl.getExtension('WEBGL_depth_texture');
  11422. if (depthTextureExtension != null) {
  11423. this._caps.depthTextureExtension = true;
  11424. this._gl.UNSIGNED_INT_24_8 = depthTextureExtension.UNSIGNED_INT_24_8_WEBGL;
  11425. }
  11426. }
  11427. // Vertex array object
  11428. if (this._webGLVersion > 1) {
  11429. this._caps.vertexArrayObject = true;
  11430. }
  11431. else {
  11432. var vertexArrayObjectExtension = this._gl.getExtension('OES_vertex_array_object');
  11433. if (vertexArrayObjectExtension != null) {
  11434. this._caps.vertexArrayObject = true;
  11435. this._gl.createVertexArray = vertexArrayObjectExtension.createVertexArrayOES.bind(vertexArrayObjectExtension);
  11436. this._gl.bindVertexArray = vertexArrayObjectExtension.bindVertexArrayOES.bind(vertexArrayObjectExtension);
  11437. this._gl.deleteVertexArray = vertexArrayObjectExtension.deleteVertexArrayOES.bind(vertexArrayObjectExtension);
  11438. }
  11439. else {
  11440. this._caps.vertexArrayObject = false;
  11441. }
  11442. }
  11443. // Instances count
  11444. if (this._webGLVersion > 1) {
  11445. this._caps.instancedArrays = true;
  11446. }
  11447. else {
  11448. var instanceExtension = this._gl.getExtension('ANGLE_instanced_arrays');
  11449. if (instanceExtension != null) {
  11450. this._caps.instancedArrays = true;
  11451. this._gl.drawArraysInstanced = instanceExtension.drawArraysInstancedANGLE.bind(instanceExtension);
  11452. this._gl.drawElementsInstanced = instanceExtension.drawElementsInstancedANGLE.bind(instanceExtension);
  11453. this._gl.vertexAttribDivisor = instanceExtension.vertexAttribDivisorANGLE.bind(instanceExtension);
  11454. }
  11455. else {
  11456. this._caps.instancedArrays = false;
  11457. }
  11458. }
  11459. // Intelligently add supported compressed formats in order to check for.
  11460. // Check for ASTC support first as it is most powerful and to be very cross platform.
  11461. // Next PVRTC & DXT, which are probably superior to ETC1/2.
  11462. // Likely no hardware which supports both PVR & DXT, so order matters little.
  11463. // ETC2 is newer and handles ETC1 (no alpha capability), so check for first.
  11464. if (this._caps.astc)
  11465. this.texturesSupported.push('-astc.ktx');
  11466. if (this._caps.s3tc)
  11467. this.texturesSupported.push('-dxt.ktx');
  11468. if (this._caps.pvrtc)
  11469. this.texturesSupported.push('-pvrtc.ktx');
  11470. if (this._caps.etc2)
  11471. this.texturesSupported.push('-etc2.ktx');
  11472. if (this._caps.etc1)
  11473. this.texturesSupported.push('-etc1.ktx');
  11474. if (this._gl.getShaderPrecisionFormat) {
  11475. var highp = this._gl.getShaderPrecisionFormat(this._gl.FRAGMENT_SHADER, this._gl.HIGH_FLOAT);
  11476. if (highp) {
  11477. this._caps.highPrecisionShaderSupported = highp.precision !== 0;
  11478. }
  11479. }
  11480. // Depth buffer
  11481. this.setDepthBuffer(true);
  11482. this.setDepthFunctionToLessOrEqual();
  11483. this.setDepthWrite(true);
  11484. // Texture maps
  11485. this._maxSimultaneousTextures = this._caps.maxCombinedTexturesImageUnits;
  11486. for (var slot = 0; slot < this._maxSimultaneousTextures; slot++) {
  11487. this._nextFreeTextureSlots.push(slot);
  11488. }
  11489. };
  11490. Object.defineProperty(Engine.prototype, "webGLVersion", {
  11491. get: function () {
  11492. return this._webGLVersion;
  11493. },
  11494. enumerable: true,
  11495. configurable: true
  11496. });
  11497. Object.defineProperty(Engine.prototype, "isStencilEnable", {
  11498. /**
  11499. * Returns true if the stencil buffer has been enabled through the creation option of the context.
  11500. */
  11501. get: function () {
  11502. return this._isStencilEnable;
  11503. },
  11504. enumerable: true,
  11505. configurable: true
  11506. });
  11507. Engine.prototype._prepareWorkingCanvas = function () {
  11508. if (this._workingCanvas) {
  11509. return;
  11510. }
  11511. this._workingCanvas = document.createElement("canvas");
  11512. var context = this._workingCanvas.getContext("2d");
  11513. if (context) {
  11514. this._workingContext = context;
  11515. }
  11516. };
  11517. Engine.prototype.resetTextureCache = function () {
  11518. for (var key in this._boundTexturesCache) {
  11519. var boundTexture = this._boundTexturesCache[key];
  11520. if (boundTexture) {
  11521. this._removeDesignatedSlot(boundTexture);
  11522. }
  11523. this._boundTexturesCache[key] = null;
  11524. }
  11525. if (!this.disableTextureBindingOptimization) {
  11526. this._nextFreeTextureSlots = [];
  11527. for (var slot = 0; slot < this._maxSimultaneousTextures; slot++) {
  11528. this._nextFreeTextureSlots.push(slot);
  11529. }
  11530. }
  11531. this._currentTextureChannel = -1;
  11532. };
  11533. Engine.prototype.isDeterministicLockStep = function () {
  11534. return this._deterministicLockstep;
  11535. };
  11536. Engine.prototype.getLockstepMaxSteps = function () {
  11537. return this._lockstepMaxSteps;
  11538. };
  11539. Engine.prototype.getGlInfo = function () {
  11540. return {
  11541. vendor: this._glVendor,
  11542. renderer: this._glRenderer,
  11543. version: this._glVersion
  11544. };
  11545. };
  11546. Engine.prototype.getAspectRatio = function (camera, useScreen) {
  11547. if (useScreen === void 0) { useScreen = false; }
  11548. var viewport = camera.viewport;
  11549. return (this.getRenderWidth(useScreen) * viewport.width) / (this.getRenderHeight(useScreen) * viewport.height);
  11550. };
  11551. Engine.prototype.getRenderWidth = function (useScreen) {
  11552. if (useScreen === void 0) { useScreen = false; }
  11553. if (!useScreen && this._currentRenderTarget) {
  11554. return this._currentRenderTarget.width;
  11555. }
  11556. return this._gl.drawingBufferWidth;
  11557. };
  11558. Engine.prototype.getRenderHeight = function (useScreen) {
  11559. if (useScreen === void 0) { useScreen = false; }
  11560. if (!useScreen && this._currentRenderTarget) {
  11561. return this._currentRenderTarget.height;
  11562. }
  11563. return this._gl.drawingBufferHeight;
  11564. };
  11565. Engine.prototype.getRenderingCanvas = function () {
  11566. return this._renderingCanvas;
  11567. };
  11568. Engine.prototype.getRenderingCanvasClientRect = function () {
  11569. if (!this._renderingCanvas) {
  11570. return null;
  11571. }
  11572. return this._renderingCanvas.getBoundingClientRect();
  11573. };
  11574. Engine.prototype.setHardwareScalingLevel = function (level) {
  11575. this._hardwareScalingLevel = level;
  11576. this.resize();
  11577. };
  11578. Engine.prototype.getHardwareScalingLevel = function () {
  11579. return this._hardwareScalingLevel;
  11580. };
  11581. Engine.prototype.getLoadedTexturesCache = function () {
  11582. return this._internalTexturesCache;
  11583. };
  11584. Engine.prototype.getCaps = function () {
  11585. return this._caps;
  11586. };
  11587. Object.defineProperty(Engine.prototype, "drawCalls", {
  11588. /** The number of draw calls submitted last frame */
  11589. get: function () {
  11590. BABYLON.Tools.Warn("drawCalls is deprecated. Please use SceneInstrumentation class");
  11591. return 0;
  11592. },
  11593. enumerable: true,
  11594. configurable: true
  11595. });
  11596. Object.defineProperty(Engine.prototype, "drawCallsPerfCounter", {
  11597. get: function () {
  11598. BABYLON.Tools.Warn("drawCallsPerfCounter is deprecated. Please use SceneInstrumentation class");
  11599. return null;
  11600. },
  11601. enumerable: true,
  11602. configurable: true
  11603. });
  11604. Engine.prototype.getDepthFunction = function () {
  11605. return this._depthCullingState.depthFunc;
  11606. };
  11607. Engine.prototype.setDepthFunction = function (depthFunc) {
  11608. this._depthCullingState.depthFunc = depthFunc;
  11609. };
  11610. Engine.prototype.setDepthFunctionToGreater = function () {
  11611. this._depthCullingState.depthFunc = this._gl.GREATER;
  11612. };
  11613. Engine.prototype.setDepthFunctionToGreaterOrEqual = function () {
  11614. this._depthCullingState.depthFunc = this._gl.GEQUAL;
  11615. };
  11616. Engine.prototype.setDepthFunctionToLess = function () {
  11617. this._depthCullingState.depthFunc = this._gl.LESS;
  11618. };
  11619. Engine.prototype.setDepthFunctionToLessOrEqual = function () {
  11620. this._depthCullingState.depthFunc = this._gl.LEQUAL;
  11621. };
  11622. Engine.prototype.getStencilBuffer = function () {
  11623. return this._stencilState.stencilTest;
  11624. };
  11625. Engine.prototype.setStencilBuffer = function (enable) {
  11626. this._stencilState.stencilTest = enable;
  11627. };
  11628. Engine.prototype.getStencilMask = function () {
  11629. return this._stencilState.stencilMask;
  11630. };
  11631. Engine.prototype.setStencilMask = function (mask) {
  11632. this._stencilState.stencilMask = mask;
  11633. };
  11634. Engine.prototype.getStencilFunction = function () {
  11635. return this._stencilState.stencilFunc;
  11636. };
  11637. Engine.prototype.getStencilFunctionReference = function () {
  11638. return this._stencilState.stencilFuncRef;
  11639. };
  11640. Engine.prototype.getStencilFunctionMask = function () {
  11641. return this._stencilState.stencilFuncMask;
  11642. };
  11643. Engine.prototype.setStencilFunction = function (stencilFunc) {
  11644. this._stencilState.stencilFunc = stencilFunc;
  11645. };
  11646. Engine.prototype.setStencilFunctionReference = function (reference) {
  11647. this._stencilState.stencilFuncRef = reference;
  11648. };
  11649. Engine.prototype.setStencilFunctionMask = function (mask) {
  11650. this._stencilState.stencilFuncMask = mask;
  11651. };
  11652. Engine.prototype.getStencilOperationFail = function () {
  11653. return this._stencilState.stencilOpStencilFail;
  11654. };
  11655. Engine.prototype.getStencilOperationDepthFail = function () {
  11656. return this._stencilState.stencilOpDepthFail;
  11657. };
  11658. Engine.prototype.getStencilOperationPass = function () {
  11659. return this._stencilState.stencilOpStencilDepthPass;
  11660. };
  11661. Engine.prototype.setStencilOperationFail = function (operation) {
  11662. this._stencilState.stencilOpStencilFail = operation;
  11663. };
  11664. Engine.prototype.setStencilOperationDepthFail = function (operation) {
  11665. this._stencilState.stencilOpDepthFail = operation;
  11666. };
  11667. Engine.prototype.setStencilOperationPass = function (operation) {
  11668. this._stencilState.stencilOpStencilDepthPass = operation;
  11669. };
  11670. Engine.prototype.setDitheringState = function (value) {
  11671. if (value) {
  11672. this._gl.enable(this._gl.DITHER);
  11673. }
  11674. else {
  11675. this._gl.disable(this._gl.DITHER);
  11676. }
  11677. };
  11678. Engine.prototype.setRasterizerState = function (value) {
  11679. if (value) {
  11680. this._gl.disable(this._gl.RASTERIZER_DISCARD);
  11681. }
  11682. else {
  11683. this._gl.enable(this._gl.RASTERIZER_DISCARD);
  11684. }
  11685. };
  11686. /**
  11687. * stop executing a render loop function and remove it from the execution array
  11688. * @param {Function} [renderFunction] the function to be removed. If not provided all functions will be removed.
  11689. */
  11690. Engine.prototype.stopRenderLoop = function (renderFunction) {
  11691. if (!renderFunction) {
  11692. this._activeRenderLoops = [];
  11693. return;
  11694. }
  11695. var index = this._activeRenderLoops.indexOf(renderFunction);
  11696. if (index >= 0) {
  11697. this._activeRenderLoops.splice(index, 1);
  11698. }
  11699. };
  11700. Engine.prototype._renderLoop = function () {
  11701. if (!this._contextWasLost) {
  11702. var shouldRender = true;
  11703. if (!this.renderEvenInBackground && this._windowIsBackground) {
  11704. shouldRender = false;
  11705. }
  11706. if (shouldRender) {
  11707. // Start new frame
  11708. this.beginFrame();
  11709. for (var index = 0; index < this._activeRenderLoops.length; index++) {
  11710. var renderFunction = this._activeRenderLoops[index];
  11711. renderFunction();
  11712. }
  11713. // Present
  11714. this.endFrame();
  11715. }
  11716. }
  11717. if (this._activeRenderLoops.length > 0) {
  11718. // Register new frame
  11719. var requester = null;
  11720. if (this._vrDisplay && this._vrDisplay.isPresenting)
  11721. requester = this._vrDisplay;
  11722. this._frameHandler = BABYLON.Tools.QueueNewFrame(this._bindedRenderFunction, requester);
  11723. }
  11724. else {
  11725. this._renderingQueueLaunched = false;
  11726. }
  11727. };
  11728. /**
  11729. * Register and execute a render loop. The engine can have more than one render function.
  11730. * @param {Function} renderFunction - the function to continuously execute starting the next render loop.
  11731. * @example
  11732. * engine.runRenderLoop(function () {
  11733. * scene.render()
  11734. * })
  11735. */
  11736. Engine.prototype.runRenderLoop = function (renderFunction) {
  11737. if (this._activeRenderLoops.indexOf(renderFunction) !== -1) {
  11738. return;
  11739. }
  11740. this._activeRenderLoops.push(renderFunction);
  11741. if (!this._renderingQueueLaunched) {
  11742. this._renderingQueueLaunched = true;
  11743. this._bindedRenderFunction = this._renderLoop.bind(this);
  11744. this._frameHandler = BABYLON.Tools.QueueNewFrame(this._bindedRenderFunction);
  11745. }
  11746. };
  11747. /**
  11748. * Toggle full screen mode.
  11749. * @param {boolean} requestPointerLock - should a pointer lock be requested from the user
  11750. * @param {any} options - an options object to be sent to the requestFullscreen function
  11751. */
  11752. Engine.prototype.switchFullscreen = function (requestPointerLock) {
  11753. if (this.isFullscreen) {
  11754. BABYLON.Tools.ExitFullscreen();
  11755. }
  11756. else {
  11757. this._pointerLockRequested = requestPointerLock;
  11758. if (this._renderingCanvas) {
  11759. BABYLON.Tools.RequestFullscreen(this._renderingCanvas);
  11760. }
  11761. }
  11762. };
  11763. Engine.prototype.clear = function (color, backBuffer, depth, stencil) {
  11764. if (stencil === void 0) { stencil = false; }
  11765. this.applyStates();
  11766. var mode = 0;
  11767. if (backBuffer && color) {
  11768. this._gl.clearColor(color.r, color.g, color.b, color.a !== undefined ? color.a : 1.0);
  11769. mode |= this._gl.COLOR_BUFFER_BIT;
  11770. }
  11771. if (depth) {
  11772. this._gl.clearDepth(1.0);
  11773. mode |= this._gl.DEPTH_BUFFER_BIT;
  11774. }
  11775. if (stencil) {
  11776. this._gl.clearStencil(0);
  11777. mode |= this._gl.STENCIL_BUFFER_BIT;
  11778. }
  11779. this._gl.clear(mode);
  11780. };
  11781. Engine.prototype.scissorClear = function (x, y, width, height, clearColor) {
  11782. var gl = this._gl;
  11783. // Save state
  11784. var curScissor = gl.getParameter(gl.SCISSOR_TEST);
  11785. var curScissorBox = gl.getParameter(gl.SCISSOR_BOX);
  11786. // Change state
  11787. gl.enable(gl.SCISSOR_TEST);
  11788. gl.scissor(x, y, width, height);
  11789. // Clear
  11790. this.clear(clearColor, true, true, true);
  11791. // Restore state
  11792. gl.scissor(curScissorBox[0], curScissorBox[1], curScissorBox[2], curScissorBox[3]);
  11793. if (curScissor === true) {
  11794. gl.enable(gl.SCISSOR_TEST);
  11795. }
  11796. else {
  11797. gl.disable(gl.SCISSOR_TEST);
  11798. }
  11799. };
  11800. /**
  11801. * Set the WebGL's viewport
  11802. * @param {BABYLON.Viewport} viewport - the viewport element to be used.
  11803. * @param {number} [requiredWidth] - the width required for rendering. If not provided the rendering canvas' width is used.
  11804. * @param {number} [requiredHeight] - the height required for rendering. If not provided the rendering canvas' height is used.
  11805. */
  11806. Engine.prototype.setViewport = function (viewport, requiredWidth, requiredHeight) {
  11807. var width = requiredWidth || this.getRenderWidth();
  11808. var height = requiredHeight || this.getRenderHeight();
  11809. var x = viewport.x || 0;
  11810. var y = viewport.y || 0;
  11811. this._cachedViewport = viewport;
  11812. this._gl.viewport(x * width, y * height, width * viewport.width, height * viewport.height);
  11813. };
  11814. /**
  11815. * Directly set the WebGL Viewport
  11816. * The x, y, width & height are directly passed to the WebGL call
  11817. * @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.
  11818. */
  11819. Engine.prototype.setDirectViewport = function (x, y, width, height) {
  11820. var currentViewport = this._cachedViewport;
  11821. this._cachedViewport = null;
  11822. this._gl.viewport(x, y, width, height);
  11823. return currentViewport;
  11824. };
  11825. Engine.prototype.beginFrame = function () {
  11826. this.onBeginFrameObservable.notifyObservers(this);
  11827. this._measureFps();
  11828. };
  11829. Engine.prototype.endFrame = function () {
  11830. //force a flush in case we are using a bad OS.
  11831. if (this._badOS) {
  11832. this.flushFramebuffer();
  11833. }
  11834. //submit frame to the vr device, if enabled
  11835. if (this._vrDisplay && this._vrDisplay.isPresenting) {
  11836. // TODO: We should only submit the frame if we read frameData successfully.
  11837. this._vrDisplay.submitFrame();
  11838. }
  11839. this.onEndFrameObservable.notifyObservers(this);
  11840. };
  11841. /**
  11842. * resize the view according to the canvas' size.
  11843. * @example
  11844. * window.addEventListener("resize", function () {
  11845. * engine.resize();
  11846. * });
  11847. */
  11848. Engine.prototype.resize = function () {
  11849. // We're not resizing the size of the canvas while in VR mode & presenting
  11850. if (!(this._vrDisplay && this._vrDisplay.isPresenting)) {
  11851. var width = this._renderingCanvas ? this._renderingCanvas.clientWidth : window.innerWidth;
  11852. var height = this._renderingCanvas ? this._renderingCanvas.clientHeight : window.innerHeight;
  11853. this.setSize(width / this._hardwareScalingLevel, height / this._hardwareScalingLevel);
  11854. }
  11855. };
  11856. /**
  11857. * force a specific size of the canvas
  11858. * @param {number} width - the new canvas' width
  11859. * @param {number} height - the new canvas' height
  11860. */
  11861. Engine.prototype.setSize = function (width, height) {
  11862. if (!this._renderingCanvas) {
  11863. return;
  11864. }
  11865. if (this._renderingCanvas.width === width && this._renderingCanvas.height === height) {
  11866. return;
  11867. }
  11868. this._renderingCanvas.width = width;
  11869. this._renderingCanvas.height = height;
  11870. for (var index = 0; index < this.scenes.length; index++) {
  11871. var scene = this.scenes[index];
  11872. for (var camIndex = 0; camIndex < scene.cameras.length; camIndex++) {
  11873. var cam = scene.cameras[camIndex];
  11874. cam._currentRenderId = 0;
  11875. }
  11876. }
  11877. if (this.onResizeObservable.hasObservers) {
  11878. this.onResizeObservable.notifyObservers(this);
  11879. }
  11880. };
  11881. // WebVR functions
  11882. Engine.prototype.isVRDevicePresent = function () {
  11883. return !!this._vrDisplay;
  11884. };
  11885. Engine.prototype.getVRDevice = function () {
  11886. return this._vrDisplay;
  11887. };
  11888. /**
  11889. * Initializes a webVR display and starts listening to display change events.
  11890. * The onVRDisplayChangedObservable will be notified upon these changes.
  11891. * @returns The onVRDisplayChangedObservable.
  11892. */
  11893. Engine.prototype.initWebVR = function () {
  11894. this.initWebVRAsync();
  11895. return this.onVRDisplayChangedObservable;
  11896. };
  11897. /**
  11898. * Initializes a webVR display and starts listening to display change events.
  11899. * The onVRDisplayChangedObservable will be notified upon these changes.
  11900. * @returns A promise containing a VRDisplay and if vr is supported.
  11901. */
  11902. Engine.prototype.initWebVRAsync = function () {
  11903. var _this = this;
  11904. var notifyObservers = function () {
  11905. var eventArgs = {
  11906. vrDisplay: _this._vrDisplay,
  11907. vrSupported: _this._vrSupported
  11908. };
  11909. _this.onVRDisplayChangedObservable.notifyObservers(eventArgs);
  11910. _this._webVRInitPromise = new Promise(function (res) { res(eventArgs); });
  11911. };
  11912. if (!this._onVrDisplayConnect) {
  11913. this._onVrDisplayConnect = function (event) {
  11914. _this._vrDisplay = event.display;
  11915. notifyObservers();
  11916. };
  11917. this._onVrDisplayDisconnect = function () {
  11918. _this._vrDisplay.cancelAnimationFrame(_this._frameHandler);
  11919. _this._vrDisplay = undefined;
  11920. _this._frameHandler = BABYLON.Tools.QueueNewFrame(_this._bindedRenderFunction);
  11921. notifyObservers();
  11922. };
  11923. this._onVrDisplayPresentChange = function () {
  11924. _this._vrExclusivePointerMode = _this._vrDisplay && _this._vrDisplay.isPresenting;
  11925. };
  11926. window.addEventListener('vrdisplayconnect', this._onVrDisplayConnect);
  11927. window.addEventListener('vrdisplaydisconnect', this._onVrDisplayDisconnect);
  11928. window.addEventListener('vrdisplaypresentchange', this._onVrDisplayPresentChange);
  11929. }
  11930. this._webVRInitPromise = this._webVRInitPromise || this._getVRDisplaysAsync();
  11931. this._webVRInitPromise.then(notifyObservers);
  11932. return this._webVRInitPromise;
  11933. };
  11934. Engine.prototype.enableVR = function () {
  11935. var _this = this;
  11936. if (this._vrDisplay && !this._vrDisplay.isPresenting) {
  11937. var onResolved = function () {
  11938. _this.onVRRequestPresentComplete.notifyObservers(true);
  11939. _this._onVRFullScreenTriggered();
  11940. };
  11941. var onRejected = function () {
  11942. _this.onVRRequestPresentComplete.notifyObservers(false);
  11943. };
  11944. this.onVRRequestPresentStart.notifyObservers(this);
  11945. this._vrDisplay.requestPresent([{ source: this.getRenderingCanvas() }]).then(onResolved).catch(onRejected);
  11946. }
  11947. };
  11948. Engine.prototype.disableVR = function () {
  11949. if (this._vrDisplay && this._vrDisplay.isPresenting) {
  11950. this._vrDisplay.exitPresent().then(this._onVRFullScreenTriggered).catch(this._onVRFullScreenTriggered);
  11951. }
  11952. };
  11953. Engine.prototype._getVRDisplaysAsync = function () {
  11954. var _this = this;
  11955. return new Promise(function (res, rej) {
  11956. if (navigator.getVRDisplays) {
  11957. navigator.getVRDisplays().then(function (devices) {
  11958. _this._vrSupported = true;
  11959. // note that devices may actually be an empty array. This is fine;
  11960. // we expect this._vrDisplay to be undefined in this case.
  11961. _this._vrDisplay = devices[0];
  11962. res({
  11963. vrDisplay: _this._vrDisplay,
  11964. vrSupported: _this._vrSupported
  11965. });
  11966. });
  11967. }
  11968. else {
  11969. _this._vrDisplay = undefined;
  11970. _this._vrSupported = false;
  11971. res({
  11972. vrDisplay: _this._vrDisplay,
  11973. vrSupported: _this._vrSupported
  11974. });
  11975. }
  11976. });
  11977. };
  11978. /**
  11979. * Binds the frame buffer to the specified texture.
  11980. * @param texture The texture to render to or null for the default canvas
  11981. * @param faceIndex The face of the texture to render to in case of cube texture
  11982. * @param requiredWidth The width of the target to render to
  11983. * @param requiredHeight The height of the target to render to
  11984. * @param forceFullscreenViewport Forces the viewport to be the entire texture/screen if true
  11985. * @param depthStencilTexture The depth stencil texture to use to render
  11986. */
  11987. Engine.prototype.bindFramebuffer = function (texture, faceIndex, requiredWidth, requiredHeight, forceFullscreenViewport, depthStencilTexture) {
  11988. if (this._currentRenderTarget) {
  11989. this.unBindFramebuffer(this._currentRenderTarget);
  11990. }
  11991. this._currentRenderTarget = texture;
  11992. this.bindUnboundFramebuffer(texture._MSAAFramebuffer ? texture._MSAAFramebuffer : texture._framebuffer);
  11993. var gl = this._gl;
  11994. if (texture.isCube) {
  11995. if (faceIndex === undefined) {
  11996. faceIndex = 0;
  11997. }
  11998. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, texture._webGLTexture, 0);
  11999. if (depthStencilTexture) {
  12000. if (depthStencilTexture._generateStencilBuffer) {
  12001. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_STENCIL_ATTACHMENT, gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, depthStencilTexture._webGLTexture, 0);
  12002. }
  12003. else {
  12004. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, depthStencilTexture._webGLTexture, 0);
  12005. }
  12006. }
  12007. }
  12008. if (this._cachedViewport && !forceFullscreenViewport) {
  12009. this.setViewport(this._cachedViewport, requiredWidth, requiredHeight);
  12010. }
  12011. else {
  12012. gl.viewport(0, 0, requiredWidth || texture.width, requiredHeight || texture.height);
  12013. }
  12014. this.wipeCaches();
  12015. };
  12016. Engine.prototype.bindUnboundFramebuffer = function (framebuffer) {
  12017. if (this._currentFramebuffer !== framebuffer) {
  12018. this._gl.bindFramebuffer(this._gl.FRAMEBUFFER, framebuffer);
  12019. this._currentFramebuffer = framebuffer;
  12020. }
  12021. };
  12022. Engine.prototype.unBindFramebuffer = function (texture, disableGenerateMipMaps, onBeforeUnbind) {
  12023. if (disableGenerateMipMaps === void 0) { disableGenerateMipMaps = false; }
  12024. this._currentRenderTarget = null;
  12025. // If MSAA, we need to bitblt back to main texture
  12026. var gl = this._gl;
  12027. if (texture._MSAAFramebuffer) {
  12028. gl.bindFramebuffer(gl.READ_FRAMEBUFFER, texture._MSAAFramebuffer);
  12029. gl.bindFramebuffer(gl.DRAW_FRAMEBUFFER, texture._framebuffer);
  12030. gl.blitFramebuffer(0, 0, texture.width, texture.height, 0, 0, texture.width, texture.height, gl.COLOR_BUFFER_BIT, gl.NEAREST);
  12031. }
  12032. if (texture.generateMipMaps && !disableGenerateMipMaps && !texture.isCube) {
  12033. this._bindTextureDirectly(gl.TEXTURE_2D, texture, true);
  12034. gl.generateMipmap(gl.TEXTURE_2D);
  12035. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  12036. }
  12037. if (onBeforeUnbind) {
  12038. if (texture._MSAAFramebuffer) {
  12039. // Bind the correct framebuffer
  12040. this.bindUnboundFramebuffer(texture._framebuffer);
  12041. }
  12042. onBeforeUnbind();
  12043. }
  12044. this.bindUnboundFramebuffer(null);
  12045. };
  12046. Engine.prototype.unBindMultiColorAttachmentFramebuffer = function (textures, disableGenerateMipMaps, onBeforeUnbind) {
  12047. if (disableGenerateMipMaps === void 0) { disableGenerateMipMaps = false; }
  12048. this._currentRenderTarget = null;
  12049. // If MSAA, we need to bitblt back to main texture
  12050. var gl = this._gl;
  12051. if (textures[0]._MSAAFramebuffer) {
  12052. gl.bindFramebuffer(gl.READ_FRAMEBUFFER, textures[0]._MSAAFramebuffer);
  12053. gl.bindFramebuffer(gl.DRAW_FRAMEBUFFER, textures[0]._framebuffer);
  12054. var attachments = textures[0]._attachments;
  12055. if (!attachments) {
  12056. attachments = new Array(textures.length);
  12057. textures[0]._attachments = attachments;
  12058. }
  12059. for (var i = 0; i < textures.length; i++) {
  12060. var texture = textures[i];
  12061. for (var j = 0; j < attachments.length; j++) {
  12062. attachments[j] = gl.NONE;
  12063. }
  12064. attachments[i] = gl[this.webGLVersion > 1 ? "COLOR_ATTACHMENT" + i : "COLOR_ATTACHMENT" + i + "_WEBGL"];
  12065. gl.readBuffer(attachments[i]);
  12066. gl.drawBuffers(attachments);
  12067. gl.blitFramebuffer(0, 0, texture.width, texture.height, 0, 0, texture.width, texture.height, gl.COLOR_BUFFER_BIT, gl.NEAREST);
  12068. }
  12069. for (var i = 0; i < attachments.length; i++) {
  12070. attachments[i] = gl[this.webGLVersion > 1 ? "COLOR_ATTACHMENT" + i : "COLOR_ATTACHMENT" + i + "_WEBGL"];
  12071. }
  12072. gl.drawBuffers(attachments);
  12073. }
  12074. for (var i = 0; i < textures.length; i++) {
  12075. var texture = textures[i];
  12076. if (texture.generateMipMaps && !disableGenerateMipMaps && !texture.isCube) {
  12077. this._bindTextureDirectly(gl.TEXTURE_2D, texture);
  12078. gl.generateMipmap(gl.TEXTURE_2D);
  12079. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  12080. }
  12081. }
  12082. if (onBeforeUnbind) {
  12083. if (textures[0]._MSAAFramebuffer) {
  12084. // Bind the correct framebuffer
  12085. this.bindUnboundFramebuffer(textures[0]._framebuffer);
  12086. }
  12087. onBeforeUnbind();
  12088. }
  12089. this.bindUnboundFramebuffer(null);
  12090. };
  12091. Engine.prototype.generateMipMapsForCubemap = function (texture) {
  12092. if (texture.generateMipMaps) {
  12093. var gl = this._gl;
  12094. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  12095. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  12096. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  12097. }
  12098. };
  12099. Engine.prototype.flushFramebuffer = function () {
  12100. this._gl.flush();
  12101. };
  12102. Engine.prototype.restoreDefaultFramebuffer = function () {
  12103. if (this._currentRenderTarget) {
  12104. this.unBindFramebuffer(this._currentRenderTarget);
  12105. }
  12106. else {
  12107. this.bindUnboundFramebuffer(null);
  12108. }
  12109. if (this._cachedViewport) {
  12110. this.setViewport(this._cachedViewport);
  12111. }
  12112. this.wipeCaches();
  12113. };
  12114. // UBOs
  12115. Engine.prototype.createUniformBuffer = function (elements) {
  12116. var ubo = this._gl.createBuffer();
  12117. if (!ubo) {
  12118. throw new Error("Unable to create uniform buffer");
  12119. }
  12120. this.bindUniformBuffer(ubo);
  12121. if (elements instanceof Float32Array) {
  12122. this._gl.bufferData(this._gl.UNIFORM_BUFFER, elements, this._gl.STATIC_DRAW);
  12123. }
  12124. else {
  12125. this._gl.bufferData(this._gl.UNIFORM_BUFFER, new Float32Array(elements), this._gl.STATIC_DRAW);
  12126. }
  12127. this.bindUniformBuffer(null);
  12128. ubo.references = 1;
  12129. return ubo;
  12130. };
  12131. Engine.prototype.createDynamicUniformBuffer = function (elements) {
  12132. var ubo = this._gl.createBuffer();
  12133. if (!ubo) {
  12134. throw new Error("Unable to create dynamic uniform buffer");
  12135. }
  12136. this.bindUniformBuffer(ubo);
  12137. if (elements instanceof Float32Array) {
  12138. this._gl.bufferData(this._gl.UNIFORM_BUFFER, elements, this._gl.DYNAMIC_DRAW);
  12139. }
  12140. else {
  12141. this._gl.bufferData(this._gl.UNIFORM_BUFFER, new Float32Array(elements), this._gl.DYNAMIC_DRAW);
  12142. }
  12143. this.bindUniformBuffer(null);
  12144. ubo.references = 1;
  12145. return ubo;
  12146. };
  12147. Engine.prototype.updateUniformBuffer = function (uniformBuffer, elements, offset, count) {
  12148. this.bindUniformBuffer(uniformBuffer);
  12149. if (offset === undefined) {
  12150. offset = 0;
  12151. }
  12152. if (count === undefined) {
  12153. if (elements instanceof Float32Array) {
  12154. this._gl.bufferSubData(this._gl.UNIFORM_BUFFER, offset, elements);
  12155. }
  12156. else {
  12157. this._gl.bufferSubData(this._gl.UNIFORM_BUFFER, offset, new Float32Array(elements));
  12158. }
  12159. }
  12160. else {
  12161. if (elements instanceof Float32Array) {
  12162. this._gl.bufferSubData(this._gl.UNIFORM_BUFFER, 0, elements.subarray(offset, offset + count));
  12163. }
  12164. else {
  12165. this._gl.bufferSubData(this._gl.UNIFORM_BUFFER, 0, new Float32Array(elements).subarray(offset, offset + count));
  12166. }
  12167. }
  12168. this.bindUniformBuffer(null);
  12169. };
  12170. // VBOs
  12171. Engine.prototype._resetVertexBufferBinding = function () {
  12172. this.bindArrayBuffer(null);
  12173. this._cachedVertexBuffers = null;
  12174. };
  12175. Engine.prototype.createVertexBuffer = function (vertices) {
  12176. var vbo = this._gl.createBuffer();
  12177. if (!vbo) {
  12178. throw new Error("Unable to create vertex buffer");
  12179. }
  12180. this.bindArrayBuffer(vbo);
  12181. if (vertices instanceof Float32Array) {
  12182. this._gl.bufferData(this._gl.ARRAY_BUFFER, vertices, this._gl.STATIC_DRAW);
  12183. }
  12184. else {
  12185. this._gl.bufferData(this._gl.ARRAY_BUFFER, new Float32Array(vertices), this._gl.STATIC_DRAW);
  12186. }
  12187. this._resetVertexBufferBinding();
  12188. vbo.references = 1;
  12189. return vbo;
  12190. };
  12191. Engine.prototype.createDynamicVertexBuffer = function (vertices) {
  12192. var vbo = this._gl.createBuffer();
  12193. if (!vbo) {
  12194. throw new Error("Unable to create dynamic vertex buffer");
  12195. }
  12196. this.bindArrayBuffer(vbo);
  12197. if (vertices instanceof Float32Array) {
  12198. this._gl.bufferData(this._gl.ARRAY_BUFFER, vertices, this._gl.DYNAMIC_DRAW);
  12199. }
  12200. else {
  12201. this._gl.bufferData(this._gl.ARRAY_BUFFER, new Float32Array(vertices), this._gl.DYNAMIC_DRAW);
  12202. }
  12203. this._resetVertexBufferBinding();
  12204. vbo.references = 1;
  12205. return vbo;
  12206. };
  12207. Engine.prototype.updateDynamicIndexBuffer = function (indexBuffer, indices, offset) {
  12208. if (offset === void 0) { offset = 0; }
  12209. // Force cache update
  12210. this._currentBoundBuffer[this._gl.ELEMENT_ARRAY_BUFFER] = null;
  12211. this.bindIndexBuffer(indexBuffer);
  12212. var arrayBuffer;
  12213. if (indices instanceof Uint16Array || indices instanceof Uint32Array) {
  12214. arrayBuffer = indices;
  12215. }
  12216. else {
  12217. arrayBuffer = indexBuffer.is32Bits ? new Uint32Array(indices) : new Uint16Array(indices);
  12218. }
  12219. this._gl.bufferData(this._gl.ELEMENT_ARRAY_BUFFER, arrayBuffer, this._gl.DYNAMIC_DRAW);
  12220. this._resetIndexBufferBinding();
  12221. };
  12222. Engine.prototype.updateDynamicVertexBuffer = function (vertexBuffer, vertices, offset, count) {
  12223. this.bindArrayBuffer(vertexBuffer);
  12224. if (offset === undefined) {
  12225. offset = 0;
  12226. }
  12227. if (count === undefined) {
  12228. if (vertices instanceof Float32Array) {
  12229. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, offset, vertices);
  12230. }
  12231. else {
  12232. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, offset, new Float32Array(vertices));
  12233. }
  12234. }
  12235. else {
  12236. if (vertices instanceof Float32Array) {
  12237. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, vertices.subarray(offset, offset + count));
  12238. }
  12239. else {
  12240. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, new Float32Array(vertices).subarray(offset, offset + count));
  12241. }
  12242. }
  12243. this._resetVertexBufferBinding();
  12244. };
  12245. Engine.prototype._resetIndexBufferBinding = function () {
  12246. this.bindIndexBuffer(null);
  12247. this._cachedIndexBuffer = null;
  12248. };
  12249. Engine.prototype.createIndexBuffer = function (indices, updatable) {
  12250. var vbo = this._gl.createBuffer();
  12251. if (!vbo) {
  12252. throw new Error("Unable to create index buffer");
  12253. }
  12254. this.bindIndexBuffer(vbo);
  12255. // Check for 32 bits indices
  12256. var arrayBuffer;
  12257. var need32Bits = false;
  12258. if (indices instanceof Uint16Array) {
  12259. arrayBuffer = indices;
  12260. }
  12261. else {
  12262. //check 32 bit support
  12263. if (this._caps.uintIndices) {
  12264. if (indices instanceof Uint32Array) {
  12265. arrayBuffer = indices;
  12266. need32Bits = true;
  12267. }
  12268. else {
  12269. //number[] or Int32Array, check if 32 bit is necessary
  12270. for (var index = 0; index < indices.length; index++) {
  12271. if (indices[index] > 65535) {
  12272. need32Bits = true;
  12273. break;
  12274. }
  12275. }
  12276. arrayBuffer = need32Bits ? new Uint32Array(indices) : new Uint16Array(indices);
  12277. }
  12278. }
  12279. else {
  12280. //no 32 bit support, force conversion to 16 bit (values greater 16 bit are lost)
  12281. arrayBuffer = new Uint16Array(indices);
  12282. }
  12283. }
  12284. this._gl.bufferData(this._gl.ELEMENT_ARRAY_BUFFER, arrayBuffer, updatable ? this._gl.DYNAMIC_DRAW : this._gl.STATIC_DRAW);
  12285. this._resetIndexBufferBinding();
  12286. vbo.references = 1;
  12287. vbo.is32Bits = need32Bits;
  12288. return vbo;
  12289. };
  12290. Engine.prototype.bindArrayBuffer = function (buffer) {
  12291. if (!this._vaoRecordInProgress) {
  12292. this._unbindVertexArrayObject();
  12293. }
  12294. this.bindBuffer(buffer, this._gl.ARRAY_BUFFER);
  12295. };
  12296. Engine.prototype.bindUniformBuffer = function (buffer) {
  12297. this._gl.bindBuffer(this._gl.UNIFORM_BUFFER, buffer);
  12298. };
  12299. Engine.prototype.bindUniformBufferBase = function (buffer, location) {
  12300. this._gl.bindBufferBase(this._gl.UNIFORM_BUFFER, location, buffer);
  12301. };
  12302. Engine.prototype.bindUniformBlock = function (shaderProgram, blockName, index) {
  12303. var uniformLocation = this._gl.getUniformBlockIndex(shaderProgram, blockName);
  12304. this._gl.uniformBlockBinding(shaderProgram, uniformLocation, index);
  12305. };
  12306. ;
  12307. Engine.prototype.bindIndexBuffer = function (buffer) {
  12308. if (!this._vaoRecordInProgress) {
  12309. this._unbindVertexArrayObject();
  12310. }
  12311. this.bindBuffer(buffer, this._gl.ELEMENT_ARRAY_BUFFER);
  12312. };
  12313. Engine.prototype.bindBuffer = function (buffer, target) {
  12314. if (this._vaoRecordInProgress || this._currentBoundBuffer[target] !== buffer) {
  12315. this._gl.bindBuffer(target, buffer);
  12316. this._currentBoundBuffer[target] = buffer;
  12317. }
  12318. };
  12319. Engine.prototype.updateArrayBuffer = function (data) {
  12320. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, data);
  12321. };
  12322. Engine.prototype.vertexAttribPointer = function (buffer, indx, size, type, normalized, stride, offset) {
  12323. var pointer = this._currentBufferPointers[indx];
  12324. var changed = false;
  12325. if (!pointer.active) {
  12326. changed = true;
  12327. pointer.active = true;
  12328. pointer.index = indx;
  12329. pointer.size = size;
  12330. pointer.type = type;
  12331. pointer.normalized = normalized;
  12332. pointer.stride = stride;
  12333. pointer.offset = offset;
  12334. pointer.buffer = buffer;
  12335. }
  12336. else {
  12337. if (pointer.buffer !== buffer) {
  12338. pointer.buffer = buffer;
  12339. changed = true;
  12340. }
  12341. if (pointer.size !== size) {
  12342. pointer.size = size;
  12343. changed = true;
  12344. }
  12345. if (pointer.type !== type) {
  12346. pointer.type = type;
  12347. changed = true;
  12348. }
  12349. if (pointer.normalized !== normalized) {
  12350. pointer.normalized = normalized;
  12351. changed = true;
  12352. }
  12353. if (pointer.stride !== stride) {
  12354. pointer.stride = stride;
  12355. changed = true;
  12356. }
  12357. if (pointer.offset !== offset) {
  12358. pointer.offset = offset;
  12359. changed = true;
  12360. }
  12361. }
  12362. if (changed || this._vaoRecordInProgress) {
  12363. this.bindArrayBuffer(buffer);
  12364. this._gl.vertexAttribPointer(indx, size, type, normalized, stride, offset);
  12365. }
  12366. };
  12367. Engine.prototype._bindIndexBufferWithCache = function (indexBuffer) {
  12368. if (indexBuffer == null) {
  12369. return;
  12370. }
  12371. if (this._cachedIndexBuffer !== indexBuffer) {
  12372. this._cachedIndexBuffer = indexBuffer;
  12373. this.bindIndexBuffer(indexBuffer);
  12374. this._uintIndicesCurrentlySet = indexBuffer.is32Bits;
  12375. }
  12376. };
  12377. Engine.prototype._bindVertexBuffersAttributes = function (vertexBuffers, effect) {
  12378. var attributes = effect.getAttributesNames();
  12379. if (!this._vaoRecordInProgress) {
  12380. this._unbindVertexArrayObject();
  12381. }
  12382. this.unbindAllAttributes();
  12383. for (var index = 0; index < attributes.length; index++) {
  12384. var order = effect.getAttributeLocation(index);
  12385. if (order >= 0) {
  12386. var vertexBuffer = vertexBuffers[attributes[index]];
  12387. if (!vertexBuffer) {
  12388. continue;
  12389. }
  12390. this._gl.enableVertexAttribArray(order);
  12391. if (!this._vaoRecordInProgress) {
  12392. this._vertexAttribArraysEnabled[order] = true;
  12393. }
  12394. var buffer = vertexBuffer.getBuffer();
  12395. if (buffer) {
  12396. this.vertexAttribPointer(buffer, order, vertexBuffer.getSize(), this._gl.FLOAT, false, vertexBuffer.getStrideSize() * 4, vertexBuffer.getOffset() * 4);
  12397. if (vertexBuffer.getIsInstanced()) {
  12398. this._gl.vertexAttribDivisor(order, vertexBuffer.getInstanceDivisor());
  12399. if (!this._vaoRecordInProgress) {
  12400. this._currentInstanceLocations.push(order);
  12401. this._currentInstanceBuffers.push(buffer);
  12402. }
  12403. }
  12404. }
  12405. }
  12406. }
  12407. };
  12408. Engine.prototype.recordVertexArrayObject = function (vertexBuffers, indexBuffer, effect) {
  12409. var vao = this._gl.createVertexArray();
  12410. this._vaoRecordInProgress = true;
  12411. this._gl.bindVertexArray(vao);
  12412. this._mustWipeVertexAttributes = true;
  12413. this._bindVertexBuffersAttributes(vertexBuffers, effect);
  12414. this.bindIndexBuffer(indexBuffer);
  12415. this._vaoRecordInProgress = false;
  12416. this._gl.bindVertexArray(null);
  12417. return vao;
  12418. };
  12419. Engine.prototype.bindVertexArrayObject = function (vertexArrayObject, indexBuffer) {
  12420. if (this._cachedVertexArrayObject !== vertexArrayObject) {
  12421. this._cachedVertexArrayObject = vertexArrayObject;
  12422. this._gl.bindVertexArray(vertexArrayObject);
  12423. this._cachedVertexBuffers = null;
  12424. this._cachedIndexBuffer = null;
  12425. this._uintIndicesCurrentlySet = indexBuffer != null && indexBuffer.is32Bits;
  12426. this._mustWipeVertexAttributes = true;
  12427. }
  12428. };
  12429. Engine.prototype.bindBuffersDirectly = function (vertexBuffer, indexBuffer, vertexDeclaration, vertexStrideSize, effect) {
  12430. if (this._cachedVertexBuffers !== vertexBuffer || this._cachedEffectForVertexBuffers !== effect) {
  12431. this._cachedVertexBuffers = vertexBuffer;
  12432. this._cachedEffectForVertexBuffers = effect;
  12433. var attributesCount = effect.getAttributesCount();
  12434. this._unbindVertexArrayObject();
  12435. this.unbindAllAttributes();
  12436. var offset = 0;
  12437. for (var index = 0; index < attributesCount; index++) {
  12438. if (index < vertexDeclaration.length) {
  12439. var order = effect.getAttributeLocation(index);
  12440. if (order >= 0) {
  12441. this._gl.enableVertexAttribArray(order);
  12442. this._vertexAttribArraysEnabled[order] = true;
  12443. this.vertexAttribPointer(vertexBuffer, order, vertexDeclaration[index], this._gl.FLOAT, false, vertexStrideSize, offset);
  12444. }
  12445. offset += vertexDeclaration[index] * 4;
  12446. }
  12447. }
  12448. }
  12449. this._bindIndexBufferWithCache(indexBuffer);
  12450. };
  12451. Engine.prototype._unbindVertexArrayObject = function () {
  12452. if (!this._cachedVertexArrayObject) {
  12453. return;
  12454. }
  12455. this._cachedVertexArrayObject = null;
  12456. this._gl.bindVertexArray(null);
  12457. };
  12458. Engine.prototype.bindBuffers = function (vertexBuffers, indexBuffer, effect) {
  12459. if (this._cachedVertexBuffers !== vertexBuffers || this._cachedEffectForVertexBuffers !== effect) {
  12460. this._cachedVertexBuffers = vertexBuffers;
  12461. this._cachedEffectForVertexBuffers = effect;
  12462. this._bindVertexBuffersAttributes(vertexBuffers, effect);
  12463. }
  12464. this._bindIndexBufferWithCache(indexBuffer);
  12465. };
  12466. Engine.prototype.unbindInstanceAttributes = function () {
  12467. var boundBuffer;
  12468. for (var i = 0, ul = this._currentInstanceLocations.length; i < ul; i++) {
  12469. var instancesBuffer = this._currentInstanceBuffers[i];
  12470. if (boundBuffer != instancesBuffer && instancesBuffer.references) {
  12471. boundBuffer = instancesBuffer;
  12472. this.bindArrayBuffer(instancesBuffer);
  12473. }
  12474. var offsetLocation = this._currentInstanceLocations[i];
  12475. this._gl.vertexAttribDivisor(offsetLocation, 0);
  12476. }
  12477. this._currentInstanceBuffers.length = 0;
  12478. this._currentInstanceLocations.length = 0;
  12479. };
  12480. Engine.prototype.releaseVertexArrayObject = function (vao) {
  12481. this._gl.deleteVertexArray(vao);
  12482. };
  12483. Engine.prototype._releaseBuffer = function (buffer) {
  12484. buffer.references--;
  12485. if (buffer.references === 0) {
  12486. this._gl.deleteBuffer(buffer);
  12487. return true;
  12488. }
  12489. return false;
  12490. };
  12491. Engine.prototype.createInstancesBuffer = function (capacity) {
  12492. var buffer = this._gl.createBuffer();
  12493. if (!buffer) {
  12494. throw new Error("Unable to create instance buffer");
  12495. }
  12496. buffer.capacity = capacity;
  12497. this.bindArrayBuffer(buffer);
  12498. this._gl.bufferData(this._gl.ARRAY_BUFFER, capacity, this._gl.DYNAMIC_DRAW);
  12499. return buffer;
  12500. };
  12501. Engine.prototype.deleteInstancesBuffer = function (buffer) {
  12502. this._gl.deleteBuffer(buffer);
  12503. };
  12504. Engine.prototype.updateAndBindInstancesBuffer = function (instancesBuffer, data, offsetLocations) {
  12505. this.bindArrayBuffer(instancesBuffer);
  12506. if (data) {
  12507. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, data);
  12508. }
  12509. if (offsetLocations[0].index !== undefined) {
  12510. var stride = 0;
  12511. for (var i = 0; i < offsetLocations.length; i++) {
  12512. var ai = offsetLocations[i];
  12513. stride += ai.attributeSize * 4;
  12514. }
  12515. for (var i = 0; i < offsetLocations.length; i++) {
  12516. var ai = offsetLocations[i];
  12517. if (!this._vertexAttribArraysEnabled[ai.index]) {
  12518. this._gl.enableVertexAttribArray(ai.index);
  12519. this._vertexAttribArraysEnabled[ai.index] = true;
  12520. }
  12521. this.vertexAttribPointer(instancesBuffer, ai.index, ai.attributeSize, ai.attribyteType || this._gl.FLOAT, ai.normalized || false, stride, ai.offset);
  12522. this._gl.vertexAttribDivisor(ai.index, 1);
  12523. this._currentInstanceLocations.push(ai.index);
  12524. this._currentInstanceBuffers.push(instancesBuffer);
  12525. }
  12526. }
  12527. else {
  12528. for (var index = 0; index < 4; index++) {
  12529. var offsetLocation = offsetLocations[index];
  12530. if (!this._vertexAttribArraysEnabled[offsetLocation]) {
  12531. this._gl.enableVertexAttribArray(offsetLocation);
  12532. this._vertexAttribArraysEnabled[offsetLocation] = true;
  12533. }
  12534. this.vertexAttribPointer(instancesBuffer, offsetLocation, 4, this._gl.FLOAT, false, 64, index * 16);
  12535. this._gl.vertexAttribDivisor(offsetLocation, 1);
  12536. this._currentInstanceLocations.push(offsetLocation);
  12537. this._currentInstanceBuffers.push(instancesBuffer);
  12538. }
  12539. }
  12540. };
  12541. Engine.prototype.applyStates = function () {
  12542. this._depthCullingState.apply(this._gl);
  12543. this._stencilState.apply(this._gl);
  12544. this._alphaState.apply(this._gl);
  12545. };
  12546. Engine.prototype.draw = function (useTriangles, indexStart, indexCount, instancesCount) {
  12547. this.drawElementsType(useTriangles ? BABYLON.Material.TriangleFillMode : BABYLON.Material.WireFrameFillMode, indexStart, indexCount, instancesCount);
  12548. };
  12549. Engine.prototype.drawPointClouds = function (verticesStart, verticesCount, instancesCount) {
  12550. this.drawArraysType(BABYLON.Material.PointFillMode, verticesStart, verticesCount, instancesCount);
  12551. };
  12552. Engine.prototype.drawUnIndexed = function (useTriangles, verticesStart, verticesCount, instancesCount) {
  12553. this.drawArraysType(useTriangles ? BABYLON.Material.TriangleFillMode : BABYLON.Material.WireFrameFillMode, verticesStart, verticesCount, instancesCount);
  12554. };
  12555. Engine.prototype.drawElementsType = function (fillMode, indexStart, indexCount, instancesCount) {
  12556. // Apply states
  12557. this.applyStates();
  12558. this._drawCalls.addCount(1, false);
  12559. // Render
  12560. var drawMode = this._drawMode(fillMode);
  12561. var indexFormat = this._uintIndicesCurrentlySet ? this._gl.UNSIGNED_INT : this._gl.UNSIGNED_SHORT;
  12562. var mult = this._uintIndicesCurrentlySet ? 4 : 2;
  12563. if (instancesCount) {
  12564. this._gl.drawElementsInstanced(drawMode, indexCount, indexFormat, indexStart * mult, instancesCount);
  12565. }
  12566. else {
  12567. this._gl.drawElements(drawMode, indexCount, indexFormat, indexStart * mult);
  12568. }
  12569. };
  12570. Engine.prototype.drawArraysType = function (fillMode, verticesStart, verticesCount, instancesCount) {
  12571. // Apply states
  12572. this.applyStates();
  12573. this._drawCalls.addCount(1, false);
  12574. var drawMode = this._drawMode(fillMode);
  12575. if (instancesCount) {
  12576. this._gl.drawArraysInstanced(drawMode, verticesStart, verticesCount, instancesCount);
  12577. }
  12578. else {
  12579. this._gl.drawArrays(drawMode, verticesStart, verticesCount);
  12580. }
  12581. };
  12582. Engine.prototype._drawMode = function (fillMode) {
  12583. switch (fillMode) {
  12584. // Triangle views
  12585. case BABYLON.Material.TriangleFillMode:
  12586. return this._gl.TRIANGLES;
  12587. case BABYLON.Material.PointFillMode:
  12588. return this._gl.POINTS;
  12589. case BABYLON.Material.WireFrameFillMode:
  12590. return this._gl.LINES;
  12591. // Draw modes
  12592. case BABYLON.Material.PointListDrawMode:
  12593. return this._gl.POINTS;
  12594. case BABYLON.Material.LineListDrawMode:
  12595. return this._gl.LINES;
  12596. case BABYLON.Material.LineLoopDrawMode:
  12597. return this._gl.LINE_LOOP;
  12598. case BABYLON.Material.LineStripDrawMode:
  12599. return this._gl.LINE_STRIP;
  12600. case BABYLON.Material.TriangleStripDrawMode:
  12601. return this._gl.TRIANGLE_STRIP;
  12602. case BABYLON.Material.TriangleFanDrawMode:
  12603. return this._gl.TRIANGLE_FAN;
  12604. default:
  12605. return this._gl.TRIANGLES;
  12606. }
  12607. };
  12608. // Shaders
  12609. Engine.prototype._releaseEffect = function (effect) {
  12610. if (this._compiledEffects[effect._key]) {
  12611. delete this._compiledEffects[effect._key];
  12612. this._deleteProgram(effect.getProgram());
  12613. }
  12614. };
  12615. Engine.prototype._deleteProgram = function (program) {
  12616. if (program) {
  12617. program.__SPECTOR_rebuildProgram = null;
  12618. if (program.transformFeedback) {
  12619. this.deleteTransformFeedback(program.transformFeedback);
  12620. program.transformFeedback = null;
  12621. }
  12622. this._gl.deleteProgram(program);
  12623. }
  12624. };
  12625. /**
  12626. * @param baseName The base name of the effect (The name of file without .fragment.fx or .vertex.fx)
  12627. * @param samplers An array of string used to represent textures
  12628. */
  12629. Engine.prototype.createEffect = function (baseName, attributesNamesOrOptions, uniformsNamesOrEngine, samplers, defines, fallbacks, onCompiled, onError, indexParameters) {
  12630. var vertex = baseName.vertexElement || baseName.vertex || baseName;
  12631. var fragment = baseName.fragmentElement || baseName.fragment || baseName;
  12632. var name = vertex + "+" + fragment + "@" + (defines ? defines : attributesNamesOrOptions.defines);
  12633. if (this._compiledEffects[name]) {
  12634. var compiledEffect = this._compiledEffects[name];
  12635. if (onCompiled && compiledEffect.isReady()) {
  12636. onCompiled(compiledEffect);
  12637. }
  12638. return compiledEffect;
  12639. }
  12640. var effect = new BABYLON.Effect(baseName, attributesNamesOrOptions, uniformsNamesOrEngine, samplers, this, defines, fallbacks, onCompiled, onError, indexParameters);
  12641. effect._key = name;
  12642. this._compiledEffects[name] = effect;
  12643. return effect;
  12644. };
  12645. Engine.prototype.createEffectForParticles = function (fragmentName, uniformsNames, samplers, defines, fallbacks, onCompiled, onError) {
  12646. if (uniformsNames === void 0) { uniformsNames = []; }
  12647. if (samplers === void 0) { samplers = []; }
  12648. if (defines === void 0) { defines = ""; }
  12649. return this.createEffect({
  12650. vertex: "particles",
  12651. fragmentElement: fragmentName
  12652. }, ["position", "color", "options"], ["view", "projection"].concat(uniformsNames), ["diffuseSampler"].concat(samplers), defines, fallbacks, onCompiled, onError);
  12653. };
  12654. Engine.prototype.createRawShaderProgram = function (vertexCode, fragmentCode, context, transformFeedbackVaryings) {
  12655. if (transformFeedbackVaryings === void 0) { transformFeedbackVaryings = null; }
  12656. context = context || this._gl;
  12657. var vertexShader = compileRawShader(context, vertexCode, "vertex");
  12658. var fragmentShader = compileRawShader(context, fragmentCode, "fragment");
  12659. return this._createShaderProgram(vertexShader, fragmentShader, context, transformFeedbackVaryings);
  12660. };
  12661. Engine.prototype.createShaderProgram = function (vertexCode, fragmentCode, defines, context, transformFeedbackVaryings) {
  12662. if (transformFeedbackVaryings === void 0) { transformFeedbackVaryings = null; }
  12663. context = context || this._gl;
  12664. this.onBeforeShaderCompilationObservable.notifyObservers(this);
  12665. var shaderVersion = (this._webGLVersion > 1) ? "#version 300 es\n#define WEBGL2 \n" : "";
  12666. var vertexShader = compileShader(context, vertexCode, "vertex", defines, shaderVersion);
  12667. var fragmentShader = compileShader(context, fragmentCode, "fragment", defines, shaderVersion);
  12668. var program = this._createShaderProgram(vertexShader, fragmentShader, context, transformFeedbackVaryings);
  12669. this.onAfterShaderCompilationObservable.notifyObservers(this);
  12670. return program;
  12671. };
  12672. Engine.prototype._createShaderProgram = function (vertexShader, fragmentShader, context, transformFeedbackVaryings) {
  12673. if (transformFeedbackVaryings === void 0) { transformFeedbackVaryings = null; }
  12674. var shaderProgram = context.createProgram();
  12675. if (!shaderProgram) {
  12676. throw new Error("Unable to create program");
  12677. }
  12678. context.attachShader(shaderProgram, vertexShader);
  12679. context.attachShader(shaderProgram, fragmentShader);
  12680. if (this.webGLVersion > 1 && transformFeedbackVaryings) {
  12681. var transformFeedback = this.createTransformFeedback();
  12682. this.bindTransformFeedback(transformFeedback);
  12683. this.setTranformFeedbackVaryings(shaderProgram, transformFeedbackVaryings);
  12684. shaderProgram.transformFeedback = transformFeedback;
  12685. }
  12686. context.linkProgram(shaderProgram);
  12687. if (this.webGLVersion > 1 && transformFeedbackVaryings) {
  12688. this.bindTransformFeedback(null);
  12689. }
  12690. var linked = context.getProgramParameter(shaderProgram, context.LINK_STATUS);
  12691. if (!linked) {
  12692. context.validateProgram(shaderProgram);
  12693. var error = context.getProgramInfoLog(shaderProgram);
  12694. if (error) {
  12695. throw new Error(error);
  12696. }
  12697. }
  12698. context.deleteShader(vertexShader);
  12699. context.deleteShader(fragmentShader);
  12700. return shaderProgram;
  12701. };
  12702. Engine.prototype.getUniforms = function (shaderProgram, uniformsNames) {
  12703. var results = new Array();
  12704. for (var index = 0; index < uniformsNames.length; index++) {
  12705. results.push(this._gl.getUniformLocation(shaderProgram, uniformsNames[index]));
  12706. }
  12707. return results;
  12708. };
  12709. Engine.prototype.getAttributes = function (shaderProgram, attributesNames) {
  12710. var results = [];
  12711. for (var index = 0; index < attributesNames.length; index++) {
  12712. try {
  12713. results.push(this._gl.getAttribLocation(shaderProgram, attributesNames[index]));
  12714. }
  12715. catch (e) {
  12716. results.push(-1);
  12717. }
  12718. }
  12719. return results;
  12720. };
  12721. Engine.prototype.enableEffect = function (effect) {
  12722. if (!effect) {
  12723. return;
  12724. }
  12725. // Use program
  12726. this.bindSamplers(effect);
  12727. this._currentEffect = effect;
  12728. if (effect.onBind) {
  12729. effect.onBind(effect);
  12730. }
  12731. effect.onBindObservable.notifyObservers(effect);
  12732. };
  12733. Engine.prototype.setIntArray = function (uniform, array) {
  12734. if (!uniform)
  12735. return;
  12736. this._gl.uniform1iv(uniform, array);
  12737. };
  12738. Engine.prototype.setIntArray2 = function (uniform, array) {
  12739. if (!uniform || array.length % 2 !== 0)
  12740. return;
  12741. this._gl.uniform2iv(uniform, array);
  12742. };
  12743. Engine.prototype.setIntArray3 = function (uniform, array) {
  12744. if (!uniform || array.length % 3 !== 0)
  12745. return;
  12746. this._gl.uniform3iv(uniform, array);
  12747. };
  12748. Engine.prototype.setIntArray4 = function (uniform, array) {
  12749. if (!uniform || array.length % 4 !== 0)
  12750. return;
  12751. this._gl.uniform4iv(uniform, array);
  12752. };
  12753. Engine.prototype.setFloatArray = function (uniform, array) {
  12754. if (!uniform)
  12755. return;
  12756. this._gl.uniform1fv(uniform, array);
  12757. };
  12758. Engine.prototype.setFloatArray2 = function (uniform, array) {
  12759. if (!uniform || array.length % 2 !== 0)
  12760. return;
  12761. this._gl.uniform2fv(uniform, array);
  12762. };
  12763. Engine.prototype.setFloatArray3 = function (uniform, array) {
  12764. if (!uniform || array.length % 3 !== 0)
  12765. return;
  12766. this._gl.uniform3fv(uniform, array);
  12767. };
  12768. Engine.prototype.setFloatArray4 = function (uniform, array) {
  12769. if (!uniform || array.length % 4 !== 0)
  12770. return;
  12771. this._gl.uniform4fv(uniform, array);
  12772. };
  12773. Engine.prototype.setArray = function (uniform, array) {
  12774. if (!uniform)
  12775. return;
  12776. this._gl.uniform1fv(uniform, array);
  12777. };
  12778. Engine.prototype.setArray2 = function (uniform, array) {
  12779. if (!uniform || array.length % 2 !== 0)
  12780. return;
  12781. this._gl.uniform2fv(uniform, array);
  12782. };
  12783. Engine.prototype.setArray3 = function (uniform, array) {
  12784. if (!uniform || array.length % 3 !== 0)
  12785. return;
  12786. this._gl.uniform3fv(uniform, array);
  12787. };
  12788. Engine.prototype.setArray4 = function (uniform, array) {
  12789. if (!uniform || array.length % 4 !== 0)
  12790. return;
  12791. this._gl.uniform4fv(uniform, array);
  12792. };
  12793. Engine.prototype.setMatrices = function (uniform, matrices) {
  12794. if (!uniform)
  12795. return;
  12796. this._gl.uniformMatrix4fv(uniform, false, matrices);
  12797. };
  12798. Engine.prototype.setMatrix = function (uniform, matrix) {
  12799. if (!uniform)
  12800. return;
  12801. this._gl.uniformMatrix4fv(uniform, false, matrix.toArray());
  12802. };
  12803. Engine.prototype.setMatrix3x3 = function (uniform, matrix) {
  12804. if (!uniform)
  12805. return;
  12806. this._gl.uniformMatrix3fv(uniform, false, matrix);
  12807. };
  12808. Engine.prototype.setMatrix2x2 = function (uniform, matrix) {
  12809. if (!uniform)
  12810. return;
  12811. this._gl.uniformMatrix2fv(uniform, false, matrix);
  12812. };
  12813. Engine.prototype.setInt = function (uniform, value) {
  12814. if (!uniform)
  12815. return;
  12816. this._gl.uniform1i(uniform, value);
  12817. };
  12818. Engine.prototype.setFloat = function (uniform, value) {
  12819. if (!uniform)
  12820. return;
  12821. this._gl.uniform1f(uniform, value);
  12822. };
  12823. Engine.prototype.setFloat2 = function (uniform, x, y) {
  12824. if (!uniform)
  12825. return;
  12826. this._gl.uniform2f(uniform, x, y);
  12827. };
  12828. Engine.prototype.setFloat3 = function (uniform, x, y, z) {
  12829. if (!uniform)
  12830. return;
  12831. this._gl.uniform3f(uniform, x, y, z);
  12832. };
  12833. Engine.prototype.setBool = function (uniform, bool) {
  12834. if (!uniform)
  12835. return;
  12836. this._gl.uniform1i(uniform, bool);
  12837. };
  12838. Engine.prototype.setFloat4 = function (uniform, x, y, z, w) {
  12839. if (!uniform)
  12840. return;
  12841. this._gl.uniform4f(uniform, x, y, z, w);
  12842. };
  12843. Engine.prototype.setColor3 = function (uniform, color3) {
  12844. if (!uniform)
  12845. return;
  12846. this._gl.uniform3f(uniform, color3.r, color3.g, color3.b);
  12847. };
  12848. Engine.prototype.setColor4 = function (uniform, color3, alpha) {
  12849. if (!uniform)
  12850. return;
  12851. this._gl.uniform4f(uniform, color3.r, color3.g, color3.b, alpha);
  12852. };
  12853. /**
  12854. * Sets a Color4 on a uniform variable
  12855. * @param uniform defines the uniform location
  12856. * @param color4 defines the value to be set
  12857. */
  12858. Engine.prototype.setDirectColor4 = function (uniform, color4) {
  12859. if (!uniform)
  12860. return;
  12861. this._gl.uniform4f(uniform, color4.r, color4.g, color4.b, color4.a);
  12862. };
  12863. // States
  12864. Engine.prototype.setState = function (culling, zOffset, force, reverseSide) {
  12865. if (zOffset === void 0) { zOffset = 0; }
  12866. if (reverseSide === void 0) { reverseSide = false; }
  12867. // Culling
  12868. if (this._depthCullingState.cull !== culling || force) {
  12869. this._depthCullingState.cull = culling;
  12870. }
  12871. // Cull face
  12872. var cullFace = this.cullBackFaces ? this._gl.BACK : this._gl.FRONT;
  12873. if (this._depthCullingState.cullFace !== cullFace || force) {
  12874. this._depthCullingState.cullFace = cullFace;
  12875. }
  12876. // Z offset
  12877. this.setZOffset(zOffset);
  12878. // Front face
  12879. var frontFace = reverseSide ? this._gl.CW : this._gl.CCW;
  12880. if (this._depthCullingState.frontFace !== frontFace || force) {
  12881. this._depthCullingState.frontFace = frontFace;
  12882. }
  12883. };
  12884. Engine.prototype.setZOffset = function (value) {
  12885. this._depthCullingState.zOffset = value;
  12886. };
  12887. Engine.prototype.getZOffset = function () {
  12888. return this._depthCullingState.zOffset;
  12889. };
  12890. Engine.prototype.setDepthBuffer = function (enable) {
  12891. this._depthCullingState.depthTest = enable;
  12892. };
  12893. Engine.prototype.getDepthWrite = function () {
  12894. return this._depthCullingState.depthMask;
  12895. };
  12896. Engine.prototype.setDepthWrite = function (enable) {
  12897. this._depthCullingState.depthMask = enable;
  12898. };
  12899. Engine.prototype.setColorWrite = function (enable) {
  12900. this._gl.colorMask(enable, enable, enable, enable);
  12901. this._colorWrite = enable;
  12902. };
  12903. Engine.prototype.getColorWrite = function () {
  12904. return this._colorWrite;
  12905. };
  12906. Engine.prototype.setAlphaConstants = function (r, g, b, a) {
  12907. this._alphaState.setAlphaBlendConstants(r, g, b, a);
  12908. };
  12909. Engine.prototype.setAlphaMode = function (mode, noDepthWriteChange) {
  12910. if (noDepthWriteChange === void 0) { noDepthWriteChange = false; }
  12911. if (this._alphaMode === mode) {
  12912. return;
  12913. }
  12914. switch (mode) {
  12915. case Engine.ALPHA_DISABLE:
  12916. this._alphaState.alphaBlend = false;
  12917. break;
  12918. case Engine.ALPHA_PREMULTIPLIED:
  12919. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA, this._gl.ONE, this._gl.ONE);
  12920. this._alphaState.alphaBlend = true;
  12921. break;
  12922. case Engine.ALPHA_PREMULTIPLIED_PORTERDUFF:
  12923. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA, this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA);
  12924. this._alphaState.alphaBlend = true;
  12925. break;
  12926. case Engine.ALPHA_COMBINE:
  12927. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE_MINUS_SRC_ALPHA, this._gl.ONE, this._gl.ONE);
  12928. this._alphaState.alphaBlend = true;
  12929. break;
  12930. case Engine.ALPHA_ONEONE:
  12931. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE, this._gl.ZERO, this._gl.ONE);
  12932. this._alphaState.alphaBlend = true;
  12933. break;
  12934. case Engine.ALPHA_ADD:
  12935. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE, this._gl.ZERO, this._gl.ONE);
  12936. this._alphaState.alphaBlend = true;
  12937. break;
  12938. case Engine.ALPHA_SUBTRACT:
  12939. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ZERO, this._gl.ONE_MINUS_SRC_COLOR, this._gl.ONE, this._gl.ONE);
  12940. this._alphaState.alphaBlend = true;
  12941. break;
  12942. case Engine.ALPHA_MULTIPLY:
  12943. this._alphaState.setAlphaBlendFunctionParameters(this._gl.DST_COLOR, this._gl.ZERO, this._gl.ONE, this._gl.ONE);
  12944. this._alphaState.alphaBlend = true;
  12945. break;
  12946. case Engine.ALPHA_MAXIMIZED:
  12947. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE_MINUS_SRC_COLOR, this._gl.ONE, this._gl.ONE);
  12948. this._alphaState.alphaBlend = true;
  12949. break;
  12950. case Engine.ALPHA_INTERPOLATE:
  12951. this._alphaState.setAlphaBlendFunctionParameters(this._gl.CONSTANT_COLOR, this._gl.ONE_MINUS_CONSTANT_COLOR, this._gl.CONSTANT_ALPHA, this._gl.ONE_MINUS_CONSTANT_ALPHA);
  12952. this._alphaState.alphaBlend = true;
  12953. break;
  12954. case Engine.ALPHA_SCREENMODE:
  12955. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE_MINUS_SRC_COLOR, this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA);
  12956. this._alphaState.alphaBlend = true;
  12957. break;
  12958. }
  12959. if (!noDepthWriteChange) {
  12960. this.setDepthWrite(mode === Engine.ALPHA_DISABLE);
  12961. }
  12962. this._alphaMode = mode;
  12963. };
  12964. Engine.prototype.getAlphaMode = function () {
  12965. return this._alphaMode;
  12966. };
  12967. // Textures
  12968. Engine.prototype.wipeCaches = function (bruteForce) {
  12969. if (this.preventCacheWipeBetweenFrames && !bruteForce) {
  12970. return;
  12971. }
  12972. this._currentEffect = null;
  12973. // 6/8/2017: deltakosh: Should not be required anymore.
  12974. // This message is then mostly for the future myself who will scream out loud when seeing that it was actually required :)
  12975. if (bruteForce) {
  12976. this.resetTextureCache();
  12977. this._currentProgram = null;
  12978. this._stencilState.reset();
  12979. this._depthCullingState.reset();
  12980. this.setDepthFunctionToLessOrEqual();
  12981. this._alphaState.reset();
  12982. }
  12983. this._resetVertexBufferBinding();
  12984. this._cachedIndexBuffer = null;
  12985. this._cachedEffectForVertexBuffers = null;
  12986. this._unbindVertexArrayObject();
  12987. this.bindIndexBuffer(null);
  12988. };
  12989. /**
  12990. * Set the compressed texture format to use, based on the formats you have, and the formats
  12991. * supported by the hardware / browser.
  12992. *
  12993. * Khronos Texture Container (.ktx) files are used to support this. This format has the
  12994. * advantage of being specifically designed for OpenGL. Header elements directly correspond
  12995. * to API arguments needed to compressed textures. This puts the burden on the container
  12996. * generator to house the arcane code for determining these for current & future formats.
  12997. *
  12998. * for description see https://www.khronos.org/opengles/sdk/tools/KTX/
  12999. * for file layout see https://www.khronos.org/opengles/sdk/tools/KTX/file_format_spec/
  13000. *
  13001. * Note: The result of this call is not taken into account when a texture is base64.
  13002. *
  13003. * @param {Array<string>} formatsAvailable- The list of those format families you have created
  13004. * on your server. Syntax: '-' + format family + '.ktx'. (Case and order do not matter.)
  13005. *
  13006. * Current families are astc, dxt, pvrtc, etc2, & etc1.
  13007. * @returns The extension selected.
  13008. */
  13009. Engine.prototype.setTextureFormatToUse = function (formatsAvailable) {
  13010. for (var i = 0, len1 = this.texturesSupported.length; i < len1; i++) {
  13011. for (var j = 0, len2 = formatsAvailable.length; j < len2; j++) {
  13012. if (this._texturesSupported[i] === formatsAvailable[j].toLowerCase()) {
  13013. return this._textureFormatInUse = this._texturesSupported[i];
  13014. }
  13015. }
  13016. }
  13017. // actively set format to nothing, to allow this to be called more than once
  13018. // and possibly fail the 2nd time
  13019. this._textureFormatInUse = null;
  13020. return null;
  13021. };
  13022. Engine.prototype._createTexture = function () {
  13023. var texture = this._gl.createTexture();
  13024. if (!texture) {
  13025. throw new Error("Unable to create texture");
  13026. }
  13027. return texture;
  13028. };
  13029. /**
  13030. * Usually called from BABYLON.Texture.ts. Passed information to create a WebGLTexture.
  13031. * @param {string} urlArg- This contains one of the following:
  13032. * 1. A conventional http URL, e.g. 'http://...' or 'file://...'
  13033. * 2. A base64 string of in-line texture data, e.g. 'data:image/jpg;base64,/...'
  13034. * 3. An indicator that data being passed using the buffer parameter, e.g. 'data:mytexture.jpg'
  13035. *
  13036. * @param {boolean} noMipmap- When true, no mipmaps shall be generated. Ignored for compressed textures. They must be in the file.
  13037. * @param {boolean} invertY- When true, image is flipped when loaded. You probably want true. Ignored for compressed textures. Must be flipped in the file.
  13038. * @param {Scene} scene- Needed for loading to the correct scene.
  13039. * @param {number} samplingMode- Mode with should be used sample / access the texture. Default: TRILINEAR
  13040. * @param {callback} onLoad- Optional callback to be called upon successful completion.
  13041. * @param {callback} onError- Optional callback to be called upon failure.
  13042. * @param {ArrayBuffer | HTMLImageElement} buffer- A source of a file previously fetched as either an ArrayBuffer (compressed or image format) or HTMLImageElement (image format)
  13043. * @param {WebGLTexture} fallback- An internal argument in case the function must be called again, due to etc1 not having alpha capabilities.
  13044. * @param {number} format- Internal format. Default: RGB when extension is '.jpg' else RGBA. Ignored for compressed textures.
  13045. *
  13046. * @returns {WebGLTexture} for assignment back into BABYLON.Texture
  13047. */
  13048. Engine.prototype.createTexture = function (urlArg, noMipmap, invertY, scene, samplingMode, onLoad, onError, buffer, fallBack, format) {
  13049. var _this = this;
  13050. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  13051. if (onLoad === void 0) { onLoad = null; }
  13052. if (onError === void 0) { onError = null; }
  13053. if (buffer === void 0) { buffer = null; }
  13054. if (fallBack === void 0) { fallBack = null; }
  13055. if (format === void 0) { format = null; }
  13056. var url = String(urlArg); // assign a new string, so that the original is still available in case of fallback
  13057. var fromData = url.substr(0, 5) === "data:";
  13058. var fromBlob = url.substr(0, 5) === "blob:";
  13059. var isBase64 = fromData && url.indexOf("base64") !== -1;
  13060. var texture = fallBack ? fallBack : new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_URL);
  13061. // establish the file extension, if possible
  13062. var lastDot = url.lastIndexOf('.');
  13063. var extension = (lastDot > 0) ? url.substring(lastDot).toLowerCase() : "";
  13064. var isDDS = this.getCaps().s3tc && (extension.indexOf(".dds") === 0);
  13065. var isTGA = (extension.indexOf(".tga") === 0);
  13066. // determine if a ktx file should be substituted
  13067. var isKTX = false;
  13068. if (this._textureFormatInUse && !isBase64 && !fallBack) {
  13069. url = url.substring(0, lastDot) + this._textureFormatInUse;
  13070. isKTX = true;
  13071. }
  13072. if (scene) {
  13073. scene._addPendingData(texture);
  13074. }
  13075. texture.url = url;
  13076. texture.generateMipMaps = !noMipmap;
  13077. texture.samplingMode = samplingMode;
  13078. texture.invertY = invertY;
  13079. if (!this._doNotHandleContextLost) {
  13080. // Keep a link to the buffer only if we plan to handle context lost
  13081. texture._buffer = buffer;
  13082. }
  13083. var onLoadObserver = null;
  13084. if (onLoad && !fallBack) {
  13085. onLoadObserver = texture.onLoadedObservable.add(onLoad);
  13086. }
  13087. if (!fallBack)
  13088. this._internalTexturesCache.push(texture);
  13089. var onerror = function (message, exception) {
  13090. if (scene) {
  13091. scene._removePendingData(texture);
  13092. }
  13093. if (onLoadObserver) {
  13094. texture.onLoadedObservable.remove(onLoadObserver);
  13095. }
  13096. // fallback for when compressed file not found to try again. For instance, etc1 does not have an alpha capable type
  13097. if (isKTX) {
  13098. _this.createTexture(urlArg, noMipmap, invertY, scene, samplingMode, null, onError, buffer, texture);
  13099. }
  13100. else if (BABYLON.Tools.UseFallbackTexture) {
  13101. _this.createTexture(BABYLON.Tools.fallbackTexture, noMipmap, invertY, scene, samplingMode, null, onError, buffer, texture);
  13102. }
  13103. if (onError) {
  13104. onError(message || "Unknown error", exception);
  13105. }
  13106. };
  13107. var callback = null;
  13108. // processing for non-image formats
  13109. if (isKTX || isTGA || isDDS) {
  13110. if (isKTX) {
  13111. callback = function (data) {
  13112. var ktx = new BABYLON.KhronosTextureContainer(data, 1);
  13113. _this._prepareWebGLTexture(texture, scene, ktx.pixelWidth, ktx.pixelHeight, invertY, false, true, function () {
  13114. ktx.uploadLevels(_this._gl, !noMipmap);
  13115. return false;
  13116. }, samplingMode);
  13117. };
  13118. }
  13119. else if (isTGA) {
  13120. callback = function (arrayBuffer) {
  13121. var data = new Uint8Array(arrayBuffer);
  13122. var header = BABYLON.TGATools.GetTGAHeader(data);
  13123. _this._prepareWebGLTexture(texture, scene, header.width, header.height, invertY, noMipmap, false, function () {
  13124. BABYLON.TGATools.UploadContent(_this._gl, data);
  13125. return false;
  13126. }, samplingMode);
  13127. };
  13128. }
  13129. else if (isDDS) {
  13130. callback = function (data) {
  13131. var info = BABYLON.DDSTools.GetDDSInfo(data);
  13132. var loadMipmap = (info.isRGB || info.isLuminance || info.mipmapCount > 1) && !noMipmap && ((info.width >> (info.mipmapCount - 1)) === 1);
  13133. _this._prepareWebGLTexture(texture, scene, info.width, info.height, invertY, !loadMipmap, info.isFourCC, function () {
  13134. BABYLON.DDSTools.UploadDDSLevels(_this, _this._gl, data, info, loadMipmap, 1);
  13135. return false;
  13136. }, samplingMode);
  13137. };
  13138. }
  13139. if (!buffer) {
  13140. this._loadFile(url, function (data) {
  13141. if (callback) {
  13142. callback(data);
  13143. }
  13144. }, undefined, scene ? scene.database : undefined, true, function (request, exception) {
  13145. onerror("Unable to load " + (request ? request.responseURL : url, exception));
  13146. });
  13147. }
  13148. else {
  13149. if (callback) {
  13150. callback(buffer);
  13151. }
  13152. }
  13153. // image format processing
  13154. }
  13155. else {
  13156. var onload = function (img) {
  13157. if (fromBlob && !_this._doNotHandleContextLost) {
  13158. // We need to store the image if we need to rebuild the texture
  13159. // in case of a webgl context lost
  13160. texture._buffer = img;
  13161. }
  13162. _this._prepareWebGLTexture(texture, scene, img.width, img.height, invertY, noMipmap, false, function (potWidth, potHeight, continuationCallback) {
  13163. var gl = _this._gl;
  13164. var isPot = (img.width === potWidth && img.height === potHeight);
  13165. var internalFormat = format ? _this._getInternalFormat(format) : ((extension === ".jpg") ? gl.RGB : gl.RGBA);
  13166. if (isPot) {
  13167. gl.texImage2D(gl.TEXTURE_2D, 0, internalFormat, internalFormat, gl.UNSIGNED_BYTE, img);
  13168. return false;
  13169. }
  13170. // Using shaders to rescale because canvas.drawImage is lossy
  13171. var source = new BABYLON.InternalTexture(_this, BABYLON.InternalTexture.DATASOURCE_TEMP);
  13172. _this._bindTextureDirectly(gl.TEXTURE_2D, source, true);
  13173. gl.texImage2D(gl.TEXTURE_2D, 0, internalFormat, internalFormat, gl.UNSIGNED_BYTE, img);
  13174. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  13175. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.LINEAR);
  13176. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  13177. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  13178. _this._rescaleTexture(source, texture, scene, internalFormat, function () {
  13179. _this._releaseTexture(source);
  13180. _this._bindTextureDirectly(gl.TEXTURE_2D, texture, true);
  13181. continuationCallback();
  13182. });
  13183. return true;
  13184. }, samplingMode);
  13185. };
  13186. if (!fromData || isBase64)
  13187. if (buffer instanceof HTMLImageElement) {
  13188. onload(buffer);
  13189. }
  13190. else {
  13191. BABYLON.Tools.LoadImage(url, onload, onerror, scene ? scene.database : null);
  13192. }
  13193. else if (buffer instanceof Array || typeof buffer === "string" || buffer instanceof ArrayBuffer)
  13194. BABYLON.Tools.LoadImage(buffer, onload, onerror, scene ? scene.database : null);
  13195. else
  13196. onload(buffer);
  13197. }
  13198. return texture;
  13199. };
  13200. Engine.prototype._rescaleTexture = function (source, destination, scene, internalFormat, onComplete) {
  13201. var _this = this;
  13202. var rtt = this.createRenderTargetTexture({
  13203. width: destination.width,
  13204. height: destination.height,
  13205. }, {
  13206. generateMipMaps: false,
  13207. type: Engine.TEXTURETYPE_UNSIGNED_INT,
  13208. samplingMode: BABYLON.Texture.BILINEAR_SAMPLINGMODE,
  13209. generateDepthBuffer: false,
  13210. generateStencilBuffer: false
  13211. });
  13212. if (!this._rescalePostProcess) {
  13213. this._rescalePostProcess = new BABYLON.PassPostProcess("rescale", 1, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this, false, Engine.TEXTURETYPE_UNSIGNED_INT);
  13214. }
  13215. this._rescalePostProcess.getEffect().executeWhenCompiled(function () {
  13216. _this._rescalePostProcess.onApply = function (effect) {
  13217. effect._bindTexture("textureSampler", source);
  13218. };
  13219. var hostingScene = scene;
  13220. if (!hostingScene) {
  13221. hostingScene = _this.scenes[_this.scenes.length - 1];
  13222. }
  13223. hostingScene.postProcessManager.directRender([_this._rescalePostProcess], rtt, true);
  13224. _this._bindTextureDirectly(_this._gl.TEXTURE_2D, destination, true);
  13225. _this._gl.copyTexImage2D(_this._gl.TEXTURE_2D, 0, internalFormat, 0, 0, destination.width, destination.height, 0);
  13226. _this.unBindFramebuffer(rtt);
  13227. _this._releaseTexture(rtt);
  13228. if (onComplete) {
  13229. onComplete();
  13230. }
  13231. });
  13232. };
  13233. Engine.prototype.updateRawTexture = function (texture, data, format, invertY, compression, type) {
  13234. if (compression === void 0) { compression = null; }
  13235. if (type === void 0) { type = Engine.TEXTURETYPE_UNSIGNED_INT; }
  13236. if (!texture) {
  13237. return;
  13238. }
  13239. var internalSizedFomat = this._getRGBABufferInternalSizedFormat(type, format);
  13240. var internalFormat = this._getInternalFormat(format);
  13241. var textureType = this._getWebGLTextureType(type);
  13242. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture, true);
  13243. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY === undefined ? 1 : (invertY ? 1 : 0));
  13244. if (!this._doNotHandleContextLost) {
  13245. texture._bufferView = data;
  13246. texture.format = format;
  13247. texture.type = type;
  13248. texture.invertY = invertY;
  13249. texture._compression = compression;
  13250. }
  13251. if (texture.width % 4 !== 0) {
  13252. this._gl.pixelStorei(this._gl.UNPACK_ALIGNMENT, 1);
  13253. }
  13254. if (compression && data) {
  13255. this._gl.compressedTexImage2D(this._gl.TEXTURE_2D, 0, this.getCaps().s3tc[compression], texture.width, texture.height, 0, data);
  13256. }
  13257. else {
  13258. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, internalSizedFomat, texture.width, texture.height, 0, internalFormat, textureType, data);
  13259. }
  13260. if (texture.generateMipMaps) {
  13261. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  13262. }
  13263. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  13264. // this.resetTextureCache();
  13265. texture.isReady = true;
  13266. };
  13267. Engine.prototype.createRawTexture = function (data, width, height, format, generateMipMaps, invertY, samplingMode, compression, type) {
  13268. if (compression === void 0) { compression = null; }
  13269. if (type === void 0) { type = Engine.TEXTURETYPE_UNSIGNED_INT; }
  13270. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_RAW);
  13271. texture.baseWidth = width;
  13272. texture.baseHeight = height;
  13273. texture.width = width;
  13274. texture.height = height;
  13275. texture.format = format;
  13276. texture.generateMipMaps = generateMipMaps;
  13277. texture.samplingMode = samplingMode;
  13278. texture.invertY = invertY;
  13279. texture._compression = compression;
  13280. texture.type = type;
  13281. if (!this._doNotHandleContextLost) {
  13282. texture._bufferView = data;
  13283. }
  13284. this.updateRawTexture(texture, data, format, invertY, compression, type);
  13285. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture, true);
  13286. // Filters
  13287. var filters = getSamplingParameters(samplingMode, generateMipMaps, this._gl);
  13288. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  13289. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  13290. if (generateMipMaps) {
  13291. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  13292. }
  13293. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  13294. this._internalTexturesCache.push(texture);
  13295. return texture;
  13296. };
  13297. Engine.prototype.createDynamicTexture = function (width, height, generateMipMaps, samplingMode) {
  13298. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_DYNAMIC);
  13299. texture.baseWidth = width;
  13300. texture.baseHeight = height;
  13301. if (generateMipMaps) {
  13302. width = this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(width, this._caps.maxTextureSize) : width;
  13303. height = this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(height, this._caps.maxTextureSize) : height;
  13304. }
  13305. // this.resetTextureCache();
  13306. texture.width = width;
  13307. texture.height = height;
  13308. texture.isReady = false;
  13309. texture.generateMipMaps = generateMipMaps;
  13310. texture.samplingMode = samplingMode;
  13311. this.updateTextureSamplingMode(samplingMode, texture);
  13312. this._internalTexturesCache.push(texture);
  13313. return texture;
  13314. };
  13315. Engine.prototype.updateTextureSamplingMode = function (samplingMode, texture) {
  13316. var filters = getSamplingParameters(samplingMode, texture.generateMipMaps, this._gl);
  13317. if (texture.isCube) {
  13318. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, texture, true);
  13319. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  13320. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_MIN_FILTER, filters.min);
  13321. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  13322. }
  13323. else if (texture.is3D) {
  13324. this._bindTextureDirectly(this._gl.TEXTURE_3D, texture, true);
  13325. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  13326. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  13327. this._bindTextureDirectly(this._gl.TEXTURE_3D, null);
  13328. }
  13329. else {
  13330. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture, true);
  13331. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  13332. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  13333. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  13334. }
  13335. texture.samplingMode = samplingMode;
  13336. };
  13337. Engine.prototype.updateDynamicTexture = function (texture, canvas, invertY, premulAlpha, format) {
  13338. if (premulAlpha === void 0) { premulAlpha = false; }
  13339. if (!texture) {
  13340. return;
  13341. }
  13342. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture, true);
  13343. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY ? 1 : 0);
  13344. if (premulAlpha) {
  13345. this._gl.pixelStorei(this._gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, 1);
  13346. }
  13347. var internalFormat = format ? this._getInternalFormat(format) : this._gl.RGBA;
  13348. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, internalFormat, internalFormat, this._gl.UNSIGNED_BYTE, canvas);
  13349. if (texture.generateMipMaps) {
  13350. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  13351. }
  13352. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  13353. if (premulAlpha) {
  13354. this._gl.pixelStorei(this._gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, 0);
  13355. }
  13356. texture.isReady = true;
  13357. };
  13358. Engine.prototype.updateVideoTexture = function (texture, video, invertY) {
  13359. if (!texture || texture._isDisabled) {
  13360. return;
  13361. }
  13362. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture, true);
  13363. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY ? 0 : 1); // Video are upside down by default
  13364. try {
  13365. // Testing video texture support
  13366. if (this._videoTextureSupported === undefined) {
  13367. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, video);
  13368. if (this._gl.getError() !== 0) {
  13369. this._videoTextureSupported = false;
  13370. }
  13371. else {
  13372. this._videoTextureSupported = true;
  13373. }
  13374. }
  13375. // Copy video through the current working canvas if video texture is not supported
  13376. if (!this._videoTextureSupported) {
  13377. if (!texture._workingCanvas) {
  13378. texture._workingCanvas = document.createElement("canvas");
  13379. var context = texture._workingCanvas.getContext("2d");
  13380. if (!context) {
  13381. throw new Error("Unable to get 2d context");
  13382. }
  13383. texture._workingContext = context;
  13384. texture._workingCanvas.width = texture.width;
  13385. texture._workingCanvas.height = texture.height;
  13386. }
  13387. texture._workingContext.drawImage(video, 0, 0, video.videoWidth, video.videoHeight, 0, 0, texture.width, texture.height);
  13388. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, texture._workingCanvas);
  13389. }
  13390. else {
  13391. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, video);
  13392. }
  13393. if (texture.generateMipMaps) {
  13394. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  13395. }
  13396. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  13397. // this.resetTextureCache();
  13398. texture.isReady = true;
  13399. }
  13400. catch (ex) {
  13401. // Something unexpected
  13402. // Let's disable the texture
  13403. texture._isDisabled = true;
  13404. }
  13405. };
  13406. /**
  13407. * Updates a depth texture Comparison Mode and Function.
  13408. * If the comparison Function is equal to 0, the mode will be set to none.
  13409. * Otherwise, this only works in webgl 2 and requires a shadow sampler in the shader.
  13410. * @param texture The texture to set the comparison function for
  13411. * @param comparisonFunction The comparison function to set, 0 if no comparison required
  13412. */
  13413. Engine.prototype.updateTextureComparisonFunction = function (texture, comparisonFunction) {
  13414. if (this.webGLVersion === 1) {
  13415. BABYLON.Tools.Error("WebGL 1 does not support texture comparison.");
  13416. return;
  13417. }
  13418. var gl = this._gl;
  13419. if (texture.isCube) {
  13420. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, texture, true);
  13421. if (comparisonFunction === 0) {
  13422. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_COMPARE_FUNC, Engine.LEQUAL);
  13423. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_COMPARE_MODE, gl.NONE);
  13424. }
  13425. else {
  13426. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_COMPARE_FUNC, comparisonFunction);
  13427. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_COMPARE_MODE, gl.COMPARE_REF_TO_TEXTURE);
  13428. }
  13429. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  13430. }
  13431. else {
  13432. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture, true);
  13433. if (comparisonFunction === 0) {
  13434. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_COMPARE_FUNC, Engine.LEQUAL);
  13435. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_COMPARE_MODE, gl.NONE);
  13436. }
  13437. else {
  13438. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_COMPARE_FUNC, comparisonFunction);
  13439. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_COMPARE_MODE, gl.COMPARE_REF_TO_TEXTURE);
  13440. }
  13441. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  13442. }
  13443. texture._comparisonFunction = comparisonFunction;
  13444. };
  13445. Engine.prototype._setupDepthStencilTexture = function (internalTexture, size, generateStencil, bilinearFiltering, comparisonFunction) {
  13446. var width = size.width || size;
  13447. var height = size.height || size;
  13448. internalTexture.baseWidth = width;
  13449. internalTexture.baseHeight = height;
  13450. internalTexture.width = width;
  13451. internalTexture.height = height;
  13452. internalTexture.isReady = true;
  13453. internalTexture.samples = 1;
  13454. internalTexture.generateMipMaps = false;
  13455. internalTexture._generateDepthBuffer = true;
  13456. internalTexture._generateStencilBuffer = generateStencil;
  13457. internalTexture.samplingMode = bilinearFiltering ? BABYLON.Texture.BILINEAR_SAMPLINGMODE : BABYLON.Texture.NEAREST_SAMPLINGMODE;
  13458. internalTexture.type = Engine.TEXTURETYPE_UNSIGNED_INT;
  13459. internalTexture._comparisonFunction = comparisonFunction;
  13460. var gl = this._gl;
  13461. var target = internalTexture.isCube ? gl.TEXTURE_CUBE_MAP : gl.TEXTURE_2D;
  13462. var samplingParameters = getSamplingParameters(internalTexture.samplingMode, false, gl);
  13463. gl.texParameteri(target, gl.TEXTURE_MAG_FILTER, samplingParameters.mag);
  13464. gl.texParameteri(target, gl.TEXTURE_MIN_FILTER, samplingParameters.min);
  13465. gl.texParameteri(target, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  13466. gl.texParameteri(target, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  13467. if (comparisonFunction === 0) {
  13468. gl.texParameteri(target, gl.TEXTURE_COMPARE_FUNC, Engine.LEQUAL);
  13469. gl.texParameteri(target, gl.TEXTURE_COMPARE_MODE, gl.NONE);
  13470. }
  13471. else {
  13472. gl.texParameteri(target, gl.TEXTURE_COMPARE_FUNC, comparisonFunction);
  13473. gl.texParameteri(target, gl.TEXTURE_COMPARE_MODE, gl.COMPARE_REF_TO_TEXTURE);
  13474. }
  13475. };
  13476. /**
  13477. * Creates a depth stencil texture.
  13478. * This is only available in WebGL 2 or with the depth texture extension available.
  13479. * @param size The size of face edge in the texture.
  13480. * @param options The options defining the texture.
  13481. * @returns The texture
  13482. */
  13483. Engine.prototype.createDepthStencilTexture = function (size, options) {
  13484. if (options.isCube) {
  13485. var width = size.width || size;
  13486. return this._createDepthStencilCubeTexture(width, options);
  13487. }
  13488. else {
  13489. return this._createDepthStencilTexture(size, options);
  13490. }
  13491. };
  13492. /**
  13493. * Creates a depth stencil texture.
  13494. * This is only available in WebGL 2 or with the depth texture extension available.
  13495. * @param size The size of face edge in the texture.
  13496. * @param options The options defining the texture.
  13497. * @returns The texture
  13498. */
  13499. Engine.prototype._createDepthStencilTexture = function (size, options) {
  13500. var internalTexture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_DEPTHTEXTURE);
  13501. if (!this._caps.depthTextureExtension) {
  13502. BABYLON.Tools.Error("Depth texture is not supported by your browser or hardware.");
  13503. return internalTexture;
  13504. }
  13505. var internalOptions = __assign({ bilinearFiltering: false, comparisonFunction: 0, generateStencil: false }, options);
  13506. var gl = this._gl;
  13507. this._bindTextureDirectly(gl.TEXTURE_2D, internalTexture, true);
  13508. this._setupDepthStencilTexture(internalTexture, size, internalOptions.generateStencil, internalOptions.bilinearFiltering, internalOptions.comparisonFunction);
  13509. if (this.webGLVersion > 1) {
  13510. if (internalOptions.generateStencil) {
  13511. gl.texImage2D(gl.TEXTURE_2D, 0, gl.DEPTH24_STENCIL8, internalTexture.width, internalTexture.height, 0, gl.DEPTH_STENCIL, gl.UNSIGNED_INT_24_8, null);
  13512. }
  13513. else {
  13514. gl.texImage2D(gl.TEXTURE_2D, 0, gl.DEPTH_COMPONENT24, internalTexture.width, internalTexture.height, 0, gl.DEPTH_COMPONENT, gl.UNSIGNED_INT, null);
  13515. }
  13516. }
  13517. else {
  13518. if (internalOptions.generateStencil) {
  13519. gl.texImage2D(gl.TEXTURE_2D, 0, gl.DEPTH_STENCIL, internalTexture.width, internalTexture.height, 0, gl.DEPTH_STENCIL, gl.UNSIGNED_INT_24_8, null);
  13520. }
  13521. else {
  13522. gl.texImage2D(gl.TEXTURE_2D, 0, gl.DEPTH_COMPONENT, internalTexture.width, internalTexture.height, 0, gl.DEPTH_COMPONENT, gl.UNSIGNED_INT, null);
  13523. }
  13524. }
  13525. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  13526. return internalTexture;
  13527. };
  13528. /**
  13529. * Creates a depth stencil cube texture.
  13530. * This is only available in WebGL 2.
  13531. * @param size The size of face edge in the cube texture.
  13532. * @param options The options defining the cube texture.
  13533. * @returns The cube texture
  13534. */
  13535. Engine.prototype._createDepthStencilCubeTexture = function (size, options) {
  13536. var internalTexture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_UNKNOWN);
  13537. internalTexture.isCube = true;
  13538. if (this.webGLVersion === 1) {
  13539. BABYLON.Tools.Error("Depth cube texture is not supported by WebGL 1.");
  13540. return internalTexture;
  13541. }
  13542. var internalOptions = __assign({ bilinearFiltering: false, comparisonFunction: 0, generateStencil: false }, options);
  13543. var gl = this._gl;
  13544. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, internalTexture, true);
  13545. this._setupDepthStencilTexture(internalTexture, size, internalOptions.generateStencil, internalOptions.bilinearFiltering, internalOptions.comparisonFunction);
  13546. // Create the depth/stencil buffer
  13547. for (var face = 0; face < 6; face++) {
  13548. if (internalOptions.generateStencil) {
  13549. 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);
  13550. }
  13551. else {
  13552. gl.texImage2D(gl.TEXTURE_CUBE_MAP_POSITIVE_X + face, 0, gl.DEPTH_COMPONENT24, size, size, 0, gl.DEPTH_COMPONENT, gl.UNSIGNED_INT, null);
  13553. }
  13554. }
  13555. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  13556. return internalTexture;
  13557. };
  13558. /**
  13559. * Sets the frame buffer Depth / Stencil attachement of the render target to the defined depth stencil texture.
  13560. * @param renderTarget The render target to set the frame buffer for
  13561. */
  13562. Engine.prototype.setFrameBufferDepthStencilTexture = function (renderTarget) {
  13563. // Create the framebuffer
  13564. var internalTexture = renderTarget.getInternalTexture();
  13565. if (!internalTexture || !internalTexture._framebuffer || !renderTarget.depthStencilTexture) {
  13566. return;
  13567. }
  13568. var gl = this._gl;
  13569. var depthStencilTexture = renderTarget.depthStencilTexture;
  13570. this.bindUnboundFramebuffer(internalTexture._framebuffer);
  13571. if (depthStencilTexture.isCube) {
  13572. if (depthStencilTexture._generateStencilBuffer) {
  13573. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_STENCIL_ATTACHMENT, gl.TEXTURE_CUBE_MAP_POSITIVE_X, depthStencilTexture._webGLTexture, 0);
  13574. }
  13575. else {
  13576. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.TEXTURE_CUBE_MAP_POSITIVE_X, depthStencilTexture._webGLTexture, 0);
  13577. }
  13578. }
  13579. else {
  13580. if (depthStencilTexture._generateStencilBuffer) {
  13581. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_STENCIL_ATTACHMENT, gl.TEXTURE_2D, depthStencilTexture._webGLTexture, 0);
  13582. }
  13583. else {
  13584. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.TEXTURE_2D, depthStencilTexture._webGLTexture, 0);
  13585. }
  13586. }
  13587. this.bindUnboundFramebuffer(null);
  13588. };
  13589. Engine.prototype.createRenderTargetTexture = function (size, options) {
  13590. var fullOptions = new RenderTargetCreationOptions();
  13591. if (options !== undefined && typeof options === "object") {
  13592. fullOptions.generateMipMaps = options.generateMipMaps;
  13593. fullOptions.generateDepthBuffer = options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  13594. fullOptions.generateStencilBuffer = fullOptions.generateDepthBuffer && options.generateStencilBuffer;
  13595. fullOptions.type = options.type === undefined ? Engine.TEXTURETYPE_UNSIGNED_INT : options.type;
  13596. fullOptions.samplingMode = options.samplingMode === undefined ? BABYLON.Texture.TRILINEAR_SAMPLINGMODE : options.samplingMode;
  13597. fullOptions.format = options.format === undefined ? Engine.TEXTUREFORMAT_RGBA : options.format;
  13598. }
  13599. else {
  13600. fullOptions.generateMipMaps = options;
  13601. fullOptions.generateDepthBuffer = true;
  13602. fullOptions.generateStencilBuffer = false;
  13603. fullOptions.type = Engine.TEXTURETYPE_UNSIGNED_INT;
  13604. fullOptions.samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE;
  13605. fullOptions.format = Engine.TEXTUREFORMAT_RGBA;
  13606. }
  13607. if (fullOptions.type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloatLinearFiltering) {
  13608. // if floating point linear (gl.FLOAT) then force to NEAREST_SAMPLINGMODE
  13609. fullOptions.samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  13610. }
  13611. else if (fullOptions.type === Engine.TEXTURETYPE_HALF_FLOAT && !this._caps.textureHalfFloatLinearFiltering) {
  13612. // if floating point linear (HALF_FLOAT) then force to NEAREST_SAMPLINGMODE
  13613. fullOptions.samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  13614. }
  13615. var gl = this._gl;
  13616. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_RENDERTARGET);
  13617. this._bindTextureDirectly(gl.TEXTURE_2D, texture, true);
  13618. var width = size.width || size;
  13619. var height = size.height || size;
  13620. var filters = getSamplingParameters(fullOptions.samplingMode, fullOptions.generateMipMaps ? true : false, gl);
  13621. if (fullOptions.type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloat) {
  13622. fullOptions.type = Engine.TEXTURETYPE_UNSIGNED_INT;
  13623. BABYLON.Tools.Warn("Float textures are not supported. Render target forced to TEXTURETYPE_UNSIGNED_BYTE type");
  13624. }
  13625. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  13626. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  13627. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  13628. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  13629. gl.texImage2D(gl.TEXTURE_2D, 0, this._getRGBABufferInternalSizedFormat(fullOptions.type, fullOptions.format), width, height, 0, this._getInternalFormat(fullOptions.format), this._getWebGLTextureType(fullOptions.type), null);
  13630. // Create the framebuffer
  13631. var framebuffer = gl.createFramebuffer();
  13632. this.bindUnboundFramebuffer(framebuffer);
  13633. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texture._webGLTexture, 0);
  13634. texture._depthStencilBuffer = this._setupFramebufferDepthAttachments(fullOptions.generateStencilBuffer ? true : false, fullOptions.generateDepthBuffer, width, height);
  13635. if (fullOptions.generateMipMaps) {
  13636. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  13637. }
  13638. // Unbind
  13639. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  13640. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  13641. this.bindUnboundFramebuffer(null);
  13642. texture._framebuffer = framebuffer;
  13643. texture.baseWidth = width;
  13644. texture.baseHeight = height;
  13645. texture.width = width;
  13646. texture.height = height;
  13647. texture.isReady = true;
  13648. texture.samples = 1;
  13649. texture.generateMipMaps = fullOptions.generateMipMaps ? true : false;
  13650. texture.samplingMode = fullOptions.samplingMode;
  13651. texture.type = fullOptions.type;
  13652. texture._generateDepthBuffer = fullOptions.generateDepthBuffer;
  13653. texture._generateStencilBuffer = fullOptions.generateStencilBuffer ? true : false;
  13654. // this.resetTextureCache();
  13655. this._internalTexturesCache.push(texture);
  13656. return texture;
  13657. };
  13658. Engine.prototype.createMultipleRenderTarget = function (size, options) {
  13659. var generateMipMaps = false;
  13660. var generateDepthBuffer = true;
  13661. var generateStencilBuffer = false;
  13662. var generateDepthTexture = false;
  13663. var textureCount = 1;
  13664. var defaultType = Engine.TEXTURETYPE_UNSIGNED_INT;
  13665. var defaultSamplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE;
  13666. var types = [], samplingModes = [];
  13667. if (options !== undefined) {
  13668. generateMipMaps = options.generateMipMaps;
  13669. generateDepthBuffer = options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  13670. generateStencilBuffer = options.generateStencilBuffer;
  13671. generateDepthTexture = options.generateDepthTexture;
  13672. textureCount = options.textureCount || 1;
  13673. if (options.types) {
  13674. types = options.types;
  13675. }
  13676. if (options.samplingModes) {
  13677. samplingModes = options.samplingModes;
  13678. }
  13679. }
  13680. var gl = this._gl;
  13681. // Create the framebuffer
  13682. var framebuffer = gl.createFramebuffer();
  13683. this.bindUnboundFramebuffer(framebuffer);
  13684. var width = size.width || size;
  13685. var height = size.height || size;
  13686. var textures = [];
  13687. var attachments = [];
  13688. var depthStencilBuffer = this._setupFramebufferDepthAttachments(generateStencilBuffer, generateDepthBuffer, width, height);
  13689. for (var i = 0; i < textureCount; i++) {
  13690. var samplingMode = samplingModes[i] || defaultSamplingMode;
  13691. var type = types[i] || defaultType;
  13692. if (type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloatLinearFiltering) {
  13693. // if floating point linear (gl.FLOAT) then force to NEAREST_SAMPLINGMODE
  13694. samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  13695. }
  13696. else if (type === Engine.TEXTURETYPE_HALF_FLOAT && !this._caps.textureHalfFloatLinearFiltering) {
  13697. // if floating point linear (HALF_FLOAT) then force to NEAREST_SAMPLINGMODE
  13698. samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  13699. }
  13700. var filters = getSamplingParameters(samplingMode, generateMipMaps, gl);
  13701. if (type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloat) {
  13702. type = Engine.TEXTURETYPE_UNSIGNED_INT;
  13703. BABYLON.Tools.Warn("Float textures are not supported. Render target forced to TEXTURETYPE_UNSIGNED_BYTE type");
  13704. }
  13705. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_MULTIRENDERTARGET);
  13706. var attachment = gl[this.webGLVersion > 1 ? "COLOR_ATTACHMENT" + i : "COLOR_ATTACHMENT" + i + "_WEBGL"];
  13707. textures.push(texture);
  13708. attachments.push(attachment);
  13709. gl.activeTexture(gl["TEXTURE" + i]);
  13710. gl.bindTexture(gl.TEXTURE_2D, texture._webGLTexture);
  13711. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  13712. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  13713. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  13714. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  13715. gl.texImage2D(gl.TEXTURE_2D, 0, this._getRGBABufferInternalSizedFormat(type), width, height, 0, gl.RGBA, this._getWebGLTextureType(type), null);
  13716. gl.framebufferTexture2D(gl.DRAW_FRAMEBUFFER, attachment, gl.TEXTURE_2D, texture._webGLTexture, 0);
  13717. if (generateMipMaps) {
  13718. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  13719. }
  13720. // Unbind
  13721. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  13722. texture._framebuffer = framebuffer;
  13723. texture._depthStencilBuffer = depthStencilBuffer;
  13724. texture.baseWidth = width;
  13725. texture.baseHeight = height;
  13726. texture.width = width;
  13727. texture.height = height;
  13728. texture.isReady = true;
  13729. texture.samples = 1;
  13730. texture.generateMipMaps = generateMipMaps;
  13731. texture.samplingMode = samplingMode;
  13732. texture.type = type;
  13733. texture._generateDepthBuffer = generateDepthBuffer;
  13734. texture._generateStencilBuffer = generateStencilBuffer;
  13735. texture._attachments = attachments;
  13736. this._internalTexturesCache.push(texture);
  13737. }
  13738. if (generateDepthTexture && this._caps.depthTextureExtension) {
  13739. // Depth texture
  13740. var depthTexture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_MULTIRENDERTARGET);
  13741. gl.activeTexture(gl.TEXTURE0);
  13742. gl.bindTexture(gl.TEXTURE_2D, depthTexture._webGLTexture);
  13743. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  13744. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  13745. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  13746. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  13747. 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);
  13748. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.TEXTURE_2D, depthTexture._webGLTexture, 0);
  13749. depthTexture._framebuffer = framebuffer;
  13750. depthTexture.baseWidth = width;
  13751. depthTexture.baseHeight = height;
  13752. depthTexture.width = width;
  13753. depthTexture.height = height;
  13754. depthTexture.isReady = true;
  13755. depthTexture.samples = 1;
  13756. depthTexture.generateMipMaps = generateMipMaps;
  13757. depthTexture.samplingMode = gl.NEAREST;
  13758. depthTexture._generateDepthBuffer = generateDepthBuffer;
  13759. depthTexture._generateStencilBuffer = generateStencilBuffer;
  13760. textures.push(depthTexture);
  13761. this._internalTexturesCache.push(depthTexture);
  13762. }
  13763. gl.drawBuffers(attachments);
  13764. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  13765. this.bindUnboundFramebuffer(null);
  13766. this.resetTextureCache();
  13767. return textures;
  13768. };
  13769. Engine.prototype._setupFramebufferDepthAttachments = function (generateStencilBuffer, generateDepthBuffer, width, height, samples) {
  13770. if (samples === void 0) { samples = 1; }
  13771. var depthStencilBuffer = null;
  13772. var gl = this._gl;
  13773. // Create the depth/stencil buffer
  13774. if (generateStencilBuffer) {
  13775. depthStencilBuffer = gl.createRenderbuffer();
  13776. gl.bindRenderbuffer(gl.RENDERBUFFER, depthStencilBuffer);
  13777. if (samples > 1) {
  13778. gl.renderbufferStorageMultisample(gl.RENDERBUFFER, samples, gl.DEPTH24_STENCIL8, width, height);
  13779. }
  13780. else {
  13781. gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_STENCIL, width, height);
  13782. }
  13783. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.DEPTH_STENCIL_ATTACHMENT, gl.RENDERBUFFER, depthStencilBuffer);
  13784. }
  13785. else if (generateDepthBuffer) {
  13786. depthStencilBuffer = gl.createRenderbuffer();
  13787. gl.bindRenderbuffer(gl.RENDERBUFFER, depthStencilBuffer);
  13788. if (samples > 1) {
  13789. gl.renderbufferStorageMultisample(gl.RENDERBUFFER, samples, gl.DEPTH_COMPONENT16, width, height);
  13790. }
  13791. else {
  13792. gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_COMPONENT16, width, height);
  13793. }
  13794. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.RENDERBUFFER, depthStencilBuffer);
  13795. }
  13796. return depthStencilBuffer;
  13797. };
  13798. Engine.prototype.updateRenderTargetTextureSampleCount = function (texture, samples) {
  13799. if (this.webGLVersion < 2 || !texture) {
  13800. return 1;
  13801. }
  13802. if (texture.samples === samples) {
  13803. return samples;
  13804. }
  13805. var gl = this._gl;
  13806. samples = Math.min(samples, gl.getParameter(gl.MAX_SAMPLES));
  13807. // Dispose previous render buffers
  13808. if (texture._depthStencilBuffer) {
  13809. gl.deleteRenderbuffer(texture._depthStencilBuffer);
  13810. texture._depthStencilBuffer = null;
  13811. }
  13812. if (texture._MSAAFramebuffer) {
  13813. gl.deleteFramebuffer(texture._MSAAFramebuffer);
  13814. texture._MSAAFramebuffer = null;
  13815. }
  13816. if (texture._MSAARenderBuffer) {
  13817. gl.deleteRenderbuffer(texture._MSAARenderBuffer);
  13818. texture._MSAARenderBuffer = null;
  13819. }
  13820. if (samples > 1) {
  13821. var framebuffer = gl.createFramebuffer();
  13822. if (!framebuffer) {
  13823. throw new Error("Unable to create multi sampled framebuffer");
  13824. }
  13825. texture._MSAAFramebuffer = framebuffer;
  13826. this.bindUnboundFramebuffer(texture._MSAAFramebuffer);
  13827. var colorRenderbuffer = gl.createRenderbuffer();
  13828. if (!colorRenderbuffer) {
  13829. throw new Error("Unable to create multi sampled framebuffer");
  13830. }
  13831. gl.bindRenderbuffer(gl.RENDERBUFFER, colorRenderbuffer);
  13832. gl.renderbufferStorageMultisample(gl.RENDERBUFFER, samples, this._getRGBAMultiSampleBufferFormat(texture.type), texture.width, texture.height);
  13833. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.RENDERBUFFER, colorRenderbuffer);
  13834. texture._MSAARenderBuffer = colorRenderbuffer;
  13835. }
  13836. else {
  13837. this.bindUnboundFramebuffer(texture._framebuffer);
  13838. }
  13839. texture.samples = samples;
  13840. texture._depthStencilBuffer = this._setupFramebufferDepthAttachments(texture._generateStencilBuffer, texture._generateDepthBuffer, texture.width, texture.height, samples);
  13841. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  13842. this.bindUnboundFramebuffer(null);
  13843. return samples;
  13844. };
  13845. Engine.prototype.updateMultipleRenderTargetTextureSampleCount = function (textures, samples) {
  13846. if (this.webGLVersion < 2 || !textures || textures.length == 0) {
  13847. return 1;
  13848. }
  13849. if (textures[0].samples === samples) {
  13850. return samples;
  13851. }
  13852. var gl = this._gl;
  13853. samples = Math.min(samples, gl.getParameter(gl.MAX_SAMPLES));
  13854. // Dispose previous render buffers
  13855. if (textures[0]._depthStencilBuffer) {
  13856. gl.deleteRenderbuffer(textures[0]._depthStencilBuffer);
  13857. textures[0]._depthStencilBuffer = null;
  13858. }
  13859. if (textures[0]._MSAAFramebuffer) {
  13860. gl.deleteFramebuffer(textures[0]._MSAAFramebuffer);
  13861. textures[0]._MSAAFramebuffer = null;
  13862. }
  13863. for (var i = 0; i < textures.length; i++) {
  13864. if (textures[i]._MSAARenderBuffer) {
  13865. gl.deleteRenderbuffer(textures[i]._MSAARenderBuffer);
  13866. textures[i]._MSAARenderBuffer = null;
  13867. }
  13868. }
  13869. if (samples > 1) {
  13870. var framebuffer = gl.createFramebuffer();
  13871. if (!framebuffer) {
  13872. throw new Error("Unable to create multi sampled framebuffer");
  13873. }
  13874. this.bindUnboundFramebuffer(framebuffer);
  13875. var depthStencilBuffer = this._setupFramebufferDepthAttachments(textures[0]._generateStencilBuffer, textures[0]._generateDepthBuffer, textures[0].width, textures[0].height, samples);
  13876. var attachments = [];
  13877. for (var i = 0; i < textures.length; i++) {
  13878. var texture = textures[i];
  13879. var attachment = gl[this.webGLVersion > 1 ? "COLOR_ATTACHMENT" + i : "COLOR_ATTACHMENT" + i + "_WEBGL"];
  13880. var colorRenderbuffer = gl.createRenderbuffer();
  13881. if (!colorRenderbuffer) {
  13882. throw new Error("Unable to create multi sampled framebuffer");
  13883. }
  13884. gl.bindRenderbuffer(gl.RENDERBUFFER, colorRenderbuffer);
  13885. gl.renderbufferStorageMultisample(gl.RENDERBUFFER, samples, this._getRGBAMultiSampleBufferFormat(texture.type), texture.width, texture.height);
  13886. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, attachment, gl.RENDERBUFFER, colorRenderbuffer);
  13887. texture._MSAAFramebuffer = framebuffer;
  13888. texture._MSAARenderBuffer = colorRenderbuffer;
  13889. texture.samples = samples;
  13890. texture._depthStencilBuffer = depthStencilBuffer;
  13891. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  13892. attachments.push(attachment);
  13893. }
  13894. gl.drawBuffers(attachments);
  13895. }
  13896. else {
  13897. this.bindUnboundFramebuffer(textures[0]._framebuffer);
  13898. }
  13899. this.bindUnboundFramebuffer(null);
  13900. return samples;
  13901. };
  13902. Engine.prototype._uploadDataToTexture = function (target, lod, internalFormat, width, height, format, type, data) {
  13903. this._gl.texImage2D(target, lod, internalFormat, width, height, 0, format, type, data);
  13904. };
  13905. Engine.prototype._uploadCompressedDataToTexture = function (target, lod, internalFormat, width, height, data) {
  13906. this._gl.compressedTexImage2D(target, lod, internalFormat, width, height, 0, data);
  13907. };
  13908. Engine.prototype.createRenderTargetCubeTexture = function (size, options) {
  13909. var fullOptions = __assign({ generateMipMaps: true, generateDepthBuffer: true, generateStencilBuffer: false, type: Engine.TEXTURETYPE_UNSIGNED_INT, samplingMode: BABYLON.Texture.TRILINEAR_SAMPLINGMODE, format: Engine.TEXTUREFORMAT_RGBA }, options);
  13910. fullOptions.generateStencilBuffer = fullOptions.generateDepthBuffer && fullOptions.generateStencilBuffer;
  13911. if (fullOptions.type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloatLinearFiltering) {
  13912. // if floating point linear (gl.FLOAT) then force to NEAREST_SAMPLINGMODE
  13913. fullOptions.samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  13914. }
  13915. else if (fullOptions.type === Engine.TEXTURETYPE_HALF_FLOAT && !this._caps.textureHalfFloatLinearFiltering) {
  13916. // if floating point linear (HALF_FLOAT) then force to NEAREST_SAMPLINGMODE
  13917. fullOptions.samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  13918. }
  13919. var gl = this._gl;
  13920. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_RENDERTARGET);
  13921. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  13922. var filters = getSamplingParameters(fullOptions.samplingMode, fullOptions.generateMipMaps, gl);
  13923. if (fullOptions.type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloat) {
  13924. fullOptions.type = Engine.TEXTURETYPE_UNSIGNED_INT;
  13925. BABYLON.Tools.Warn("Float textures are not supported. Cube render target forced to TEXTURETYPE_UNESIGNED_BYTE type");
  13926. }
  13927. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, filters.mag);
  13928. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, filters.min);
  13929. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  13930. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  13931. for (var face = 0; face < 6; face++) {
  13932. 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);
  13933. }
  13934. // Create the framebuffer
  13935. var framebuffer = gl.createFramebuffer();
  13936. this.bindUnboundFramebuffer(framebuffer);
  13937. texture._depthStencilBuffer = this._setupFramebufferDepthAttachments(fullOptions.generateStencilBuffer, fullOptions.generateDepthBuffer, size, size);
  13938. // MipMaps
  13939. if (fullOptions.generateMipMaps) {
  13940. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  13941. }
  13942. // Unbind
  13943. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  13944. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  13945. this.bindUnboundFramebuffer(null);
  13946. texture._framebuffer = framebuffer;
  13947. texture.width = size;
  13948. texture.height = size;
  13949. texture.isReady = true;
  13950. texture.isCube = true;
  13951. texture.samples = 1;
  13952. texture.generateMipMaps = fullOptions.generateMipMaps;
  13953. texture.samplingMode = fullOptions.samplingMode;
  13954. texture.type = fullOptions.type;
  13955. texture._generateDepthBuffer = fullOptions.generateDepthBuffer;
  13956. texture._generateStencilBuffer = fullOptions.generateStencilBuffer;
  13957. this._internalTexturesCache.push(texture);
  13958. return texture;
  13959. };
  13960. Engine.prototype.createPrefilteredCubeTexture = function (rootUrl, scene, scale, offset, onLoad, onError, format, forcedExtension) {
  13961. var _this = this;
  13962. if (onLoad === void 0) { onLoad = null; }
  13963. if (onError === void 0) { onError = null; }
  13964. if (forcedExtension === void 0) { forcedExtension = null; }
  13965. var callback = function (loadData) {
  13966. if (!loadData) {
  13967. if (onLoad) {
  13968. onLoad(null);
  13969. }
  13970. return;
  13971. }
  13972. var texture = loadData.texture;
  13973. texture._dataSource = BABYLON.InternalTexture.DATASOURCE_CUBEPREFILTERED;
  13974. texture._lodGenerationScale = scale;
  13975. texture._lodGenerationOffset = offset;
  13976. if (_this._caps.textureLOD) {
  13977. // Do not add extra process if texture lod is supported.
  13978. if (onLoad) {
  13979. onLoad(texture);
  13980. }
  13981. return;
  13982. }
  13983. var mipSlices = 3;
  13984. var gl = _this._gl;
  13985. var width = loadData.width;
  13986. if (!width) {
  13987. return;
  13988. }
  13989. var textures = [];
  13990. for (var i = 0; i < mipSlices; i++) {
  13991. //compute LOD from even spacing in smoothness (matching shader calculation)
  13992. var smoothness = i / (mipSlices - 1);
  13993. var roughness = 1 - smoothness;
  13994. var minLODIndex = offset; // roughness = 0
  13995. var maxLODIndex = BABYLON.Scalar.Log2(width) * scale + offset; // roughness = 1
  13996. var lodIndex = minLODIndex + (maxLODIndex - minLODIndex) * roughness;
  13997. var mipmapIndex = Math.round(Math.min(Math.max(lodIndex, 0), maxLODIndex));
  13998. var glTextureFromLod = new BABYLON.InternalTexture(_this, BABYLON.InternalTexture.DATASOURCE_TEMP);
  13999. glTextureFromLod.isCube = true;
  14000. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, glTextureFromLod, true);
  14001. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  14002. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, gl.LINEAR);
  14003. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  14004. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  14005. if (loadData.isDDS) {
  14006. var info = loadData.info;
  14007. var data = loadData.data;
  14008. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, info.isCompressed ? 1 : 0);
  14009. BABYLON.DDSTools.UploadDDSLevels(_this, _this._gl, data, info, true, 6, mipmapIndex);
  14010. }
  14011. else {
  14012. BABYLON.Tools.Warn("DDS is the only prefiltered cube map supported so far.");
  14013. }
  14014. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  14015. // Wrap in a base texture for easy binding.
  14016. var lodTexture = new BABYLON.BaseTexture(scene);
  14017. lodTexture.isCube = true;
  14018. lodTexture._texture = glTextureFromLod;
  14019. glTextureFromLod.isReady = true;
  14020. textures.push(lodTexture);
  14021. }
  14022. texture._lodTextureHigh = textures[2];
  14023. texture._lodTextureMid = textures[1];
  14024. texture._lodTextureLow = textures[0];
  14025. if (onLoad) {
  14026. onLoad(texture);
  14027. }
  14028. };
  14029. return this.createCubeTexture(rootUrl, scene, null, false, callback, onError, format, forcedExtension);
  14030. };
  14031. Engine.prototype.createCubeTexture = function (rootUrl, scene, files, noMipmap, onLoad, onError, format, forcedExtension) {
  14032. var _this = this;
  14033. if (onLoad === void 0) { onLoad = null; }
  14034. if (onError === void 0) { onError = null; }
  14035. if (forcedExtension === void 0) { forcedExtension = null; }
  14036. var gl = this._gl;
  14037. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_CUBE);
  14038. texture.isCube = true;
  14039. texture.url = rootUrl;
  14040. texture.generateMipMaps = !noMipmap;
  14041. if (!this._doNotHandleContextLost) {
  14042. texture._extension = forcedExtension;
  14043. texture._files = files;
  14044. }
  14045. var isKTX = false;
  14046. var isDDS = false;
  14047. var lastDot = rootUrl.lastIndexOf('.');
  14048. var extension = forcedExtension ? forcedExtension : (lastDot > -1 ? rootUrl.substring(lastDot).toLowerCase() : "");
  14049. if (this._textureFormatInUse) {
  14050. extension = this._textureFormatInUse;
  14051. rootUrl = (lastDot > -1 ? rootUrl.substring(0, lastDot) : rootUrl) + this._textureFormatInUse;
  14052. isKTX = true;
  14053. }
  14054. else {
  14055. isDDS = (extension === ".dds");
  14056. }
  14057. var onerror = function (request, exception) {
  14058. if (onError && request) {
  14059. onError(request.status + " " + request.statusText, exception);
  14060. }
  14061. };
  14062. if (isKTX) {
  14063. this._loadFile(rootUrl, function (data) {
  14064. var ktx = new BABYLON.KhronosTextureContainer(data, 6);
  14065. var loadMipmap = ktx.numberOfMipmapLevels > 1 && !noMipmap;
  14066. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  14067. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 1);
  14068. ktx.uploadLevels(_this._gl, !noMipmap);
  14069. _this.setCubeMapTextureParams(gl, loadMipmap);
  14070. texture.width = ktx.pixelWidth;
  14071. texture.height = ktx.pixelHeight;
  14072. texture.isReady = true;
  14073. }, undefined, undefined, true, onerror);
  14074. }
  14075. else if (isDDS) {
  14076. if (files && files.length === 6) {
  14077. this._cascadeLoadFiles(scene, function (imgs) {
  14078. var info;
  14079. var loadMipmap = false;
  14080. var width = 0;
  14081. for (var index = 0; index < imgs.length; index++) {
  14082. var data = imgs[index];
  14083. info = BABYLON.DDSTools.GetDDSInfo(data);
  14084. loadMipmap = (info.isRGB || info.isLuminance || info.mipmapCount > 1) && !noMipmap;
  14085. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  14086. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, info.isCompressed ? 1 : 0);
  14087. BABYLON.DDSTools.UploadDDSLevels(_this, _this._gl, data, info, loadMipmap, 6, -1, index);
  14088. if (!noMipmap && !info.isFourCC && info.mipmapCount === 1) {
  14089. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  14090. }
  14091. texture.width = info.width;
  14092. texture.height = info.height;
  14093. texture.type = info.textureType;
  14094. width = info.width;
  14095. }
  14096. _this.setCubeMapTextureParams(gl, loadMipmap);
  14097. texture.isReady = true;
  14098. if (onLoad) {
  14099. onLoad({ isDDS: true, width: width, info: info, imgs: imgs, texture: texture });
  14100. }
  14101. }, files, onError);
  14102. }
  14103. else {
  14104. this._loadFile(rootUrl, function (data) {
  14105. var info = BABYLON.DDSTools.GetDDSInfo(data);
  14106. var loadMipmap = (info.isRGB || info.isLuminance || info.mipmapCount > 1) && !noMipmap;
  14107. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  14108. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, info.isCompressed ? 1 : 0);
  14109. BABYLON.DDSTools.UploadDDSLevels(_this, _this._gl, data, info, loadMipmap, 6);
  14110. if (!noMipmap && !info.isFourCC && info.mipmapCount === 1) {
  14111. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  14112. }
  14113. _this.setCubeMapTextureParams(gl, loadMipmap);
  14114. texture.width = info.width;
  14115. texture.height = info.height;
  14116. texture.isReady = true;
  14117. texture.type = info.textureType;
  14118. if (onLoad) {
  14119. onLoad({ isDDS: true, width: info.width, info: info, data: data, texture: texture });
  14120. }
  14121. }, undefined, undefined, true, onerror);
  14122. }
  14123. }
  14124. else {
  14125. if (!files) {
  14126. throw new Error("Cannot load cubemap because files were not defined");
  14127. }
  14128. cascadeLoadImgs(rootUrl, scene, function (imgs) {
  14129. var width = _this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(imgs[0].width, _this._caps.maxCubemapTextureSize) : imgs[0].width;
  14130. var height = width;
  14131. _this._prepareWorkingCanvas();
  14132. if (!_this._workingCanvas || !_this._workingContext) {
  14133. return;
  14134. }
  14135. _this._workingCanvas.width = width;
  14136. _this._workingCanvas.height = height;
  14137. var faces = [
  14138. gl.TEXTURE_CUBE_MAP_POSITIVE_X, gl.TEXTURE_CUBE_MAP_POSITIVE_Y, gl.TEXTURE_CUBE_MAP_POSITIVE_Z,
  14139. gl.TEXTURE_CUBE_MAP_NEGATIVE_X, gl.TEXTURE_CUBE_MAP_NEGATIVE_Y, gl.TEXTURE_CUBE_MAP_NEGATIVE_Z
  14140. ];
  14141. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  14142. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 0);
  14143. var internalFormat = format ? _this._getInternalFormat(format) : _this._gl.RGBA;
  14144. for (var index = 0; index < faces.length; index++) {
  14145. _this._workingContext.drawImage(imgs[index], 0, 0, imgs[index].width, imgs[index].height, 0, 0, width, height);
  14146. gl.texImage2D(faces[index], 0, internalFormat, internalFormat, gl.UNSIGNED_BYTE, _this._workingCanvas);
  14147. }
  14148. if (!noMipmap) {
  14149. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  14150. }
  14151. _this.setCubeMapTextureParams(gl, !noMipmap);
  14152. texture.width = width;
  14153. texture.height = height;
  14154. texture.isReady = true;
  14155. if (format) {
  14156. texture.format = format;
  14157. }
  14158. texture.onLoadedObservable.notifyObservers(texture);
  14159. texture.onLoadedObservable.clear();
  14160. if (onLoad) {
  14161. onLoad();
  14162. }
  14163. }, files, onError);
  14164. }
  14165. this._internalTexturesCache.push(texture);
  14166. return texture;
  14167. };
  14168. Engine.prototype.setCubeMapTextureParams = function (gl, loadMipmap) {
  14169. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  14170. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, loadMipmap ? gl.LINEAR_MIPMAP_LINEAR : gl.LINEAR);
  14171. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  14172. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  14173. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  14174. // this.resetTextureCache();
  14175. };
  14176. Engine.prototype.updateRawCubeTexture = function (texture, data, format, type, invertY, compression, level) {
  14177. if (compression === void 0) { compression = null; }
  14178. if (level === void 0) { level = 0; }
  14179. texture._bufferViewArray = data;
  14180. texture.format = format;
  14181. texture.type = type;
  14182. texture.invertY = invertY;
  14183. texture._compression = compression;
  14184. var gl = this._gl;
  14185. var textureType = this._getWebGLTextureType(type);
  14186. var internalFormat = this._getInternalFormat(format);
  14187. var internalSizedFomat = this._getRGBABufferInternalSizedFormat(type);
  14188. var needConversion = false;
  14189. if (internalFormat === gl.RGB) {
  14190. internalFormat = gl.RGBA;
  14191. needConversion = true;
  14192. }
  14193. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  14194. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, invertY === undefined ? 1 : (invertY ? 1 : 0));
  14195. if (texture.width % 4 !== 0) {
  14196. gl.pixelStorei(gl.UNPACK_ALIGNMENT, 1);
  14197. }
  14198. // Data are known to be in +X +Y +Z -X -Y -Z
  14199. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  14200. var faceData = data[faceIndex];
  14201. if (compression) {
  14202. gl.compressedTexImage2D(gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, level, (this.getCaps().s3tc)[compression], texture.width, texture.height, 0, faceData);
  14203. }
  14204. else {
  14205. if (needConversion) {
  14206. faceData = this._convertRGBtoRGBATextureData(faceData, texture.width, texture.height, type);
  14207. }
  14208. gl.texImage2D(gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, level, internalSizedFomat, texture.width, texture.height, 0, internalFormat, textureType, faceData);
  14209. }
  14210. }
  14211. var isPot = !this.needPOTTextures || (BABYLON.Tools.IsExponentOfTwo(texture.width) && BABYLON.Tools.IsExponentOfTwo(texture.height));
  14212. if (isPot && texture.generateMipMaps && level === 0) {
  14213. this._gl.generateMipmap(this._gl.TEXTURE_CUBE_MAP);
  14214. }
  14215. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  14216. // this.resetTextureCache();
  14217. texture.isReady = true;
  14218. };
  14219. Engine.prototype.createRawCubeTexture = function (data, size, format, type, generateMipMaps, invertY, samplingMode, compression) {
  14220. if (compression === void 0) { compression = null; }
  14221. var gl = this._gl;
  14222. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_CUBERAW);
  14223. texture.isCube = true;
  14224. texture.generateMipMaps = generateMipMaps;
  14225. texture.format = format;
  14226. texture.type = type;
  14227. if (!this._doNotHandleContextLost) {
  14228. texture._bufferViewArray = data;
  14229. }
  14230. var textureType = this._getWebGLTextureType(type);
  14231. var internalFormat = this._getInternalFormat(format);
  14232. if (internalFormat === gl.RGB) {
  14233. internalFormat = gl.RGBA;
  14234. }
  14235. var width = size;
  14236. var height = width;
  14237. texture.width = width;
  14238. texture.height = height;
  14239. // Double check on POT to generate Mips.
  14240. var isPot = !this.needPOTTextures || (BABYLON.Tools.IsExponentOfTwo(texture.width) && BABYLON.Tools.IsExponentOfTwo(texture.height));
  14241. if (!isPot) {
  14242. generateMipMaps = false;
  14243. }
  14244. // Upload data if needed. The texture won't be ready until then.
  14245. if (data) {
  14246. this.updateRawCubeTexture(texture, data, format, type, invertY, compression);
  14247. }
  14248. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, texture, true);
  14249. // Filters
  14250. if (data && generateMipMaps) {
  14251. this._gl.generateMipmap(this._gl.TEXTURE_CUBE_MAP);
  14252. }
  14253. if (textureType === gl.FLOAT && !this._caps.textureFloatLinearFiltering) {
  14254. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  14255. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  14256. }
  14257. else if (textureType === this._gl.HALF_FLOAT_OES && !this._caps.textureHalfFloatLinearFiltering) {
  14258. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  14259. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  14260. }
  14261. else {
  14262. var filters = getSamplingParameters(samplingMode, generateMipMaps, gl);
  14263. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, filters.mag);
  14264. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, filters.min);
  14265. }
  14266. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  14267. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  14268. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  14269. return texture;
  14270. };
  14271. Engine.prototype.createRawCubeTextureFromUrl = function (url, scene, size, format, type, noMipmap, callback, mipmmapGenerator, onLoad, onError, samplingMode, invertY) {
  14272. var _this = this;
  14273. if (onLoad === void 0) { onLoad = null; }
  14274. if (onError === void 0) { onError = null; }
  14275. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  14276. if (invertY === void 0) { invertY = false; }
  14277. var gl = this._gl;
  14278. var texture = this.createRawCubeTexture(null, size, format, type, !noMipmap, invertY, samplingMode);
  14279. scene._addPendingData(texture);
  14280. texture.url = url;
  14281. this._internalTexturesCache.push(texture);
  14282. var onerror = function (request, exception) {
  14283. scene._removePendingData(texture);
  14284. if (onError && request) {
  14285. onError(request.status + " " + request.statusText, exception);
  14286. }
  14287. };
  14288. var internalCallback = function (data) {
  14289. var width = texture.width;
  14290. var faceDataArrays = callback(data);
  14291. if (!faceDataArrays) {
  14292. return;
  14293. }
  14294. if (mipmmapGenerator) {
  14295. var textureType = _this._getWebGLTextureType(type);
  14296. var internalFormat = _this._getInternalFormat(format);
  14297. var internalSizedFomat = _this._getRGBABufferInternalSizedFormat(type);
  14298. var needConversion = false;
  14299. if (internalFormat === gl.RGB) {
  14300. internalFormat = gl.RGBA;
  14301. needConversion = true;
  14302. }
  14303. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  14304. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 0);
  14305. var mipData = mipmmapGenerator(faceDataArrays);
  14306. for (var level = 0; level < mipData.length; level++) {
  14307. var mipSize = width >> level;
  14308. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  14309. var mipFaceData = mipData[level][faceIndex];
  14310. if (needConversion) {
  14311. mipFaceData = _this._convertRGBtoRGBATextureData(mipFaceData, mipSize, mipSize, type);
  14312. }
  14313. gl.texImage2D(faceIndex, level, internalSizedFomat, mipSize, mipSize, 0, internalFormat, textureType, mipFaceData);
  14314. }
  14315. }
  14316. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  14317. }
  14318. else {
  14319. texture.generateMipMaps = !noMipmap;
  14320. _this.updateRawCubeTexture(texture, faceDataArrays, format, type, invertY);
  14321. }
  14322. texture.isReady = true;
  14323. // this.resetTextureCache();
  14324. scene._removePendingData(texture);
  14325. if (onLoad) {
  14326. onLoad();
  14327. }
  14328. };
  14329. this._loadFile(url, function (data) {
  14330. internalCallback(data);
  14331. }, undefined, scene.database, true, onerror);
  14332. return texture;
  14333. };
  14334. ;
  14335. Engine.prototype.updateRawTexture3D = function (texture, data, format, invertY, compression) {
  14336. if (compression === void 0) { compression = null; }
  14337. var internalFormat = this._getInternalFormat(format);
  14338. this._bindTextureDirectly(this._gl.TEXTURE_3D, texture, true);
  14339. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY === undefined ? 1 : (invertY ? 1 : 0));
  14340. if (!this._doNotHandleContextLost) {
  14341. texture._bufferView = data;
  14342. texture.format = format;
  14343. texture.invertY = invertY;
  14344. texture._compression = compression;
  14345. }
  14346. if (texture.width % 4 !== 0) {
  14347. this._gl.pixelStorei(this._gl.UNPACK_ALIGNMENT, 1);
  14348. }
  14349. if (compression && data) {
  14350. this._gl.compressedTexImage3D(this._gl.TEXTURE_3D, 0, this.getCaps().s3tc[compression], texture.width, texture.height, texture.depth, 0, data);
  14351. }
  14352. else {
  14353. this._gl.texImage3D(this._gl.TEXTURE_3D, 0, internalFormat, texture.width, texture.height, texture.depth, 0, internalFormat, this._gl.UNSIGNED_BYTE, data);
  14354. }
  14355. if (texture.generateMipMaps) {
  14356. this._gl.generateMipmap(this._gl.TEXTURE_3D);
  14357. }
  14358. this._bindTextureDirectly(this._gl.TEXTURE_3D, null);
  14359. // this.resetTextureCache();
  14360. texture.isReady = true;
  14361. };
  14362. Engine.prototype.createRawTexture3D = function (data, width, height, depth, format, generateMipMaps, invertY, samplingMode, compression) {
  14363. if (compression === void 0) { compression = null; }
  14364. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_RAW3D);
  14365. texture.baseWidth = width;
  14366. texture.baseHeight = height;
  14367. texture.baseDepth = depth;
  14368. texture.width = width;
  14369. texture.height = height;
  14370. texture.depth = depth;
  14371. texture.format = format;
  14372. texture.generateMipMaps = generateMipMaps;
  14373. texture.samplingMode = samplingMode;
  14374. texture.is3D = true;
  14375. if (!this._doNotHandleContextLost) {
  14376. texture._bufferView = data;
  14377. }
  14378. this.updateRawTexture3D(texture, data, format, invertY, compression);
  14379. this._bindTextureDirectly(this._gl.TEXTURE_3D, texture, true);
  14380. // Filters
  14381. var filters = getSamplingParameters(samplingMode, generateMipMaps, this._gl);
  14382. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  14383. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  14384. if (generateMipMaps) {
  14385. this._gl.generateMipmap(this._gl.TEXTURE_3D);
  14386. }
  14387. this._bindTextureDirectly(this._gl.TEXTURE_3D, null);
  14388. this._internalTexturesCache.push(texture);
  14389. return texture;
  14390. };
  14391. Engine.prototype._prepareWebGLTextureContinuation = function (texture, scene, noMipmap, isCompressed, samplingMode) {
  14392. var gl = this._gl;
  14393. if (!gl) {
  14394. return;
  14395. }
  14396. var filters = getSamplingParameters(samplingMode, !noMipmap, gl);
  14397. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  14398. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  14399. if (!noMipmap && !isCompressed) {
  14400. gl.generateMipmap(gl.TEXTURE_2D);
  14401. }
  14402. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  14403. // this.resetTextureCache();
  14404. if (scene) {
  14405. scene._removePendingData(texture);
  14406. }
  14407. texture.onLoadedObservable.notifyObservers(texture);
  14408. texture.onLoadedObservable.clear();
  14409. };
  14410. Engine.prototype._prepareWebGLTexture = function (texture, scene, width, height, invertY, noMipmap, isCompressed, processFunction, samplingMode) {
  14411. var _this = this;
  14412. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  14413. var potWidth = this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(width, this.getCaps().maxTextureSize) : width;
  14414. var potHeight = this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(height, this.getCaps().maxTextureSize) : height;
  14415. var gl = this._gl;
  14416. if (!gl) {
  14417. return;
  14418. }
  14419. if (!texture._webGLTexture) {
  14420. // this.resetTextureCache();
  14421. if (scene) {
  14422. scene._removePendingData(texture);
  14423. }
  14424. return;
  14425. }
  14426. this._bindTextureDirectly(gl.TEXTURE_2D, texture, true);
  14427. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, invertY === undefined ? 1 : (invertY ? 1 : 0));
  14428. texture.baseWidth = width;
  14429. texture.baseHeight = height;
  14430. texture.width = potWidth;
  14431. texture.height = potHeight;
  14432. texture.isReady = true;
  14433. if (processFunction(potWidth, potHeight, function () {
  14434. _this._prepareWebGLTextureContinuation(texture, scene, noMipmap, isCompressed, samplingMode);
  14435. })) {
  14436. // Returning as texture needs extra async steps
  14437. return;
  14438. }
  14439. this._prepareWebGLTextureContinuation(texture, scene, noMipmap, isCompressed, samplingMode);
  14440. };
  14441. Engine.prototype._convertRGBtoRGBATextureData = function (rgbData, width, height, textureType) {
  14442. // Create new RGBA data container.
  14443. var rgbaData;
  14444. if (textureType === Engine.TEXTURETYPE_FLOAT) {
  14445. rgbaData = new Float32Array(width * height * 4);
  14446. }
  14447. else {
  14448. rgbaData = new Uint32Array(width * height * 4);
  14449. }
  14450. // Convert each pixel.
  14451. for (var x = 0; x < width; x++) {
  14452. for (var y = 0; y < height; y++) {
  14453. var index = (y * width + x) * 3;
  14454. var newIndex = (y * width + x) * 4;
  14455. // Map Old Value to new value.
  14456. rgbaData[newIndex + 0] = rgbData[index + 0];
  14457. rgbaData[newIndex + 1] = rgbData[index + 1];
  14458. rgbaData[newIndex + 2] = rgbData[index + 2];
  14459. // Add fully opaque alpha channel.
  14460. rgbaData[newIndex + 3] = 1;
  14461. }
  14462. }
  14463. return rgbaData;
  14464. };
  14465. Engine.prototype._releaseFramebufferObjects = function (texture) {
  14466. var gl = this._gl;
  14467. if (texture._framebuffer) {
  14468. gl.deleteFramebuffer(texture._framebuffer);
  14469. texture._framebuffer = null;
  14470. }
  14471. if (texture._depthStencilBuffer) {
  14472. gl.deleteRenderbuffer(texture._depthStencilBuffer);
  14473. texture._depthStencilBuffer = null;
  14474. }
  14475. if (texture._MSAAFramebuffer) {
  14476. gl.deleteFramebuffer(texture._MSAAFramebuffer);
  14477. texture._MSAAFramebuffer = null;
  14478. }
  14479. if (texture._MSAARenderBuffer) {
  14480. gl.deleteRenderbuffer(texture._MSAARenderBuffer);
  14481. texture._MSAARenderBuffer = null;
  14482. }
  14483. };
  14484. Engine.prototype._releaseTexture = function (texture) {
  14485. var gl = this._gl;
  14486. this._releaseFramebufferObjects(texture);
  14487. gl.deleteTexture(texture._webGLTexture);
  14488. // Unbind channels
  14489. this.unbindAllTextures();
  14490. var index = this._internalTexturesCache.indexOf(texture);
  14491. if (index !== -1) {
  14492. this._internalTexturesCache.splice(index, 1);
  14493. }
  14494. // Integrated fixed lod samplers.
  14495. if (texture._lodTextureHigh) {
  14496. texture._lodTextureHigh.dispose();
  14497. }
  14498. if (texture._lodTextureMid) {
  14499. texture._lodTextureMid.dispose();
  14500. }
  14501. if (texture._lodTextureLow) {
  14502. texture._lodTextureLow.dispose();
  14503. }
  14504. // Set output texture of post process to null if the texture has been released/disposed
  14505. this.scenes.forEach(function (scene) {
  14506. scene.postProcesses.forEach(function (postProcess) {
  14507. if (postProcess._outputTexture == texture) {
  14508. postProcess._outputTexture = null;
  14509. }
  14510. });
  14511. scene.cameras.forEach(function (camera) {
  14512. camera._postProcesses.forEach(function (postProcess) {
  14513. if (postProcess) {
  14514. if (postProcess._outputTexture == texture) {
  14515. postProcess._outputTexture = null;
  14516. }
  14517. }
  14518. });
  14519. });
  14520. });
  14521. };
  14522. Engine.prototype.setProgram = function (program) {
  14523. if (this._currentProgram !== program) {
  14524. this._gl.useProgram(program);
  14525. this._currentProgram = program;
  14526. }
  14527. };
  14528. Engine.prototype.bindSamplers = function (effect) {
  14529. this.setProgram(effect.getProgram());
  14530. var samplers = effect.getSamplers();
  14531. for (var index = 0; index < samplers.length; index++) {
  14532. var uniform = effect.getUniform(samplers[index]);
  14533. if (uniform) {
  14534. this._boundUniforms[index] = uniform;
  14535. }
  14536. }
  14537. this._currentEffect = null;
  14538. };
  14539. Engine.prototype._moveBoundTextureOnTop = function (internalTexture) {
  14540. if (this.disableTextureBindingOptimization || this._lastBoundInternalTextureTracker.previous === internalTexture) {
  14541. return;
  14542. }
  14543. // Remove
  14544. this._linkTrackers(internalTexture.previous, internalTexture.next);
  14545. // Bind last to it
  14546. this._linkTrackers(this._lastBoundInternalTextureTracker.previous, internalTexture);
  14547. // Bind to dummy
  14548. this._linkTrackers(internalTexture, this._lastBoundInternalTextureTracker);
  14549. };
  14550. Engine.prototype._getCorrectTextureChannel = function (channel, internalTexture) {
  14551. if (!internalTexture) {
  14552. return -1;
  14553. }
  14554. internalTexture._initialSlot = channel;
  14555. if (this.disableTextureBindingOptimization) {
  14556. if (channel !== internalTexture._designatedSlot) {
  14557. this._textureCollisions.addCount(1, false);
  14558. }
  14559. }
  14560. else {
  14561. if (channel !== internalTexture._designatedSlot) {
  14562. if (internalTexture._designatedSlot > -1) {
  14563. return internalTexture._designatedSlot;
  14564. }
  14565. else {
  14566. // No slot for this texture, let's pick a new one (if we find a free slot)
  14567. if (this._nextFreeTextureSlots.length) {
  14568. return this._nextFreeTextureSlots[0];
  14569. }
  14570. // We need to recycle the oldest bound texture, sorry.
  14571. this._textureCollisions.addCount(1, false);
  14572. return this._removeDesignatedSlot(this._firstBoundInternalTextureTracker.next);
  14573. }
  14574. }
  14575. }
  14576. return channel;
  14577. };
  14578. Engine.prototype._linkTrackers = function (previous, next) {
  14579. previous.next = next;
  14580. next.previous = previous;
  14581. };
  14582. Engine.prototype._removeDesignatedSlot = function (internalTexture) {
  14583. var currentSlot = internalTexture._designatedSlot;
  14584. if (currentSlot === -1) {
  14585. return -1;
  14586. }
  14587. internalTexture._designatedSlot = -1;
  14588. if (this.disableTextureBindingOptimization) {
  14589. return -1;
  14590. }
  14591. // Remove from bound list
  14592. this._linkTrackers(internalTexture.previous, internalTexture.next);
  14593. // Free the slot
  14594. this._boundTexturesCache[currentSlot] = null;
  14595. this._nextFreeTextureSlots.push(currentSlot);
  14596. return currentSlot;
  14597. };
  14598. Engine.prototype._activateCurrentTexture = function () {
  14599. if (this._currentTextureChannel !== this._activeChannel) {
  14600. this._gl.activeTexture(this._gl.TEXTURE0 + this._activeChannel);
  14601. this._currentTextureChannel = this._activeChannel;
  14602. }
  14603. };
  14604. Engine.prototype._bindTextureDirectly = function (target, texture, forTextureDataUpdate) {
  14605. if (forTextureDataUpdate === void 0) { forTextureDataUpdate = false; }
  14606. if (forTextureDataUpdate && texture && texture._designatedSlot > -1) {
  14607. this._activeChannel = texture._designatedSlot;
  14608. }
  14609. var currentTextureBound = this._boundTexturesCache[this._activeChannel];
  14610. var isTextureForRendering = texture && texture._initialSlot > -1;
  14611. if (currentTextureBound !== texture) {
  14612. if (currentTextureBound) {
  14613. this._removeDesignatedSlot(currentTextureBound);
  14614. }
  14615. this._activateCurrentTexture();
  14616. this._gl.bindTexture(target, texture ? texture._webGLTexture : null);
  14617. this._boundTexturesCache[this._activeChannel] = texture;
  14618. if (texture) {
  14619. if (!this.disableTextureBindingOptimization) {
  14620. var slotIndex = this._nextFreeTextureSlots.indexOf(this._activeChannel);
  14621. if (slotIndex > -1) {
  14622. this._nextFreeTextureSlots.splice(slotIndex, 1);
  14623. }
  14624. this._linkTrackers(this._lastBoundInternalTextureTracker.previous, texture);
  14625. this._linkTrackers(texture, this._lastBoundInternalTextureTracker);
  14626. }
  14627. texture._designatedSlot = this._activeChannel;
  14628. }
  14629. }
  14630. else if (forTextureDataUpdate) {
  14631. this._activateCurrentTexture();
  14632. }
  14633. if (isTextureForRendering && !forTextureDataUpdate) {
  14634. this._bindSamplerUniformToChannel(texture._initialSlot, this._activeChannel);
  14635. }
  14636. };
  14637. Engine.prototype._bindTexture = function (channel, texture) {
  14638. if (channel < 0) {
  14639. return;
  14640. }
  14641. if (texture) {
  14642. channel = this._getCorrectTextureChannel(channel, texture);
  14643. }
  14644. this._activeChannel = channel;
  14645. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture);
  14646. };
  14647. Engine.prototype.setTextureFromPostProcess = function (channel, postProcess) {
  14648. this._bindTexture(channel, postProcess ? postProcess._textures.data[postProcess._currentRenderTextureInd] : null);
  14649. };
  14650. /**
  14651. * Binds the output of the passed in post process to the texture channel specified
  14652. * @param channel The channel the texture should be bound to
  14653. * @param postProcess The post process which's output should be bound
  14654. */
  14655. Engine.prototype.setTextureFromPostProcessOutput = function (channel, postProcess) {
  14656. this._bindTexture(channel, postProcess ? postProcess._outputTexture : null);
  14657. };
  14658. Engine.prototype.unbindAllTextures = function () {
  14659. for (var channel = 0; channel < this._maxSimultaneousTextures; channel++) {
  14660. this._activeChannel = channel;
  14661. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  14662. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  14663. if (this.webGLVersion > 1) {
  14664. this._bindTextureDirectly(this._gl.TEXTURE_3D, null);
  14665. }
  14666. }
  14667. };
  14668. /**
  14669. * Sets a texture to the according uniform.
  14670. * @param channel The texture channel
  14671. * @param uniform The uniform to set
  14672. * @param texture The texture to apply
  14673. */
  14674. Engine.prototype.setTexture = function (channel, uniform, texture) {
  14675. if (channel < 0) {
  14676. return;
  14677. }
  14678. if (uniform) {
  14679. this._boundUniforms[channel] = uniform;
  14680. }
  14681. this._setTexture(channel, texture);
  14682. };
  14683. /**
  14684. * Sets a depth stencil texture from a render target to the according uniform.
  14685. * @param channel The texture channel
  14686. * @param uniform The uniform to set
  14687. * @param texture The render target texture containing the depth stencil texture to apply
  14688. */
  14689. Engine.prototype.setDepthStencilTexture = function (channel, uniform, texture) {
  14690. if (channel < 0) {
  14691. return;
  14692. }
  14693. if (uniform) {
  14694. this._boundUniforms[channel] = uniform;
  14695. }
  14696. if (!texture || !texture.depthStencilTexture) {
  14697. this._setTexture(channel, null);
  14698. }
  14699. else {
  14700. this._setTexture(channel, texture, false, true);
  14701. }
  14702. };
  14703. Engine.prototype._bindSamplerUniformToChannel = function (sourceSlot, destination) {
  14704. var uniform = this._boundUniforms[sourceSlot];
  14705. if (uniform._currentState === destination) {
  14706. return;
  14707. }
  14708. this._gl.uniform1i(uniform, destination);
  14709. uniform._currentState = destination;
  14710. };
  14711. Engine.prototype._setTexture = function (channel, texture, isPartOfTextureArray, depthStencilTexture) {
  14712. if (isPartOfTextureArray === void 0) { isPartOfTextureArray = false; }
  14713. if (depthStencilTexture === void 0) { depthStencilTexture = false; }
  14714. // Not ready?
  14715. if (!texture) {
  14716. if (this._boundTexturesCache[channel] != null) {
  14717. this._activeChannel = channel;
  14718. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  14719. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  14720. if (this.webGLVersion > 1) {
  14721. this._bindTextureDirectly(this._gl.TEXTURE_3D, null);
  14722. }
  14723. }
  14724. return false;
  14725. }
  14726. // Video
  14727. if (texture.video) {
  14728. this._activeChannel = channel;
  14729. texture.update();
  14730. }
  14731. else if (texture.delayLoadState === Engine.DELAYLOADSTATE_NOTLOADED) {
  14732. texture.delayLoad();
  14733. return false;
  14734. }
  14735. var internalTexture;
  14736. if (depthStencilTexture) {
  14737. internalTexture = texture.depthStencilTexture;
  14738. }
  14739. else if (texture.isReady()) {
  14740. internalTexture = texture.getInternalTexture();
  14741. }
  14742. else if (texture.isCube) {
  14743. internalTexture = this.emptyCubeTexture;
  14744. }
  14745. else if (texture.is3D) {
  14746. internalTexture = this.emptyTexture3D;
  14747. }
  14748. else {
  14749. internalTexture = this.emptyTexture;
  14750. }
  14751. if (!isPartOfTextureArray) {
  14752. channel = this._getCorrectTextureChannel(channel, internalTexture);
  14753. }
  14754. if (this._boundTexturesCache[channel] === internalTexture) {
  14755. this._moveBoundTextureOnTop(internalTexture);
  14756. if (!isPartOfTextureArray) {
  14757. this._bindSamplerUniformToChannel(internalTexture._initialSlot, channel);
  14758. }
  14759. return false;
  14760. }
  14761. this._activeChannel = channel;
  14762. if (internalTexture && internalTexture.is3D) {
  14763. this._bindTextureDirectly(this._gl.TEXTURE_3D, internalTexture, isPartOfTextureArray);
  14764. if (internalTexture && internalTexture._cachedWrapU !== texture.wrapU) {
  14765. internalTexture._cachedWrapU = texture.wrapU;
  14766. switch (texture.wrapU) {
  14767. case BABYLON.Texture.WRAP_ADDRESSMODE:
  14768. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_S, this._gl.REPEAT);
  14769. break;
  14770. case BABYLON.Texture.CLAMP_ADDRESSMODE:
  14771. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_S, this._gl.CLAMP_TO_EDGE);
  14772. break;
  14773. case BABYLON.Texture.MIRROR_ADDRESSMODE:
  14774. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_S, this._gl.MIRRORED_REPEAT);
  14775. break;
  14776. }
  14777. }
  14778. if (internalTexture && internalTexture._cachedWrapV !== texture.wrapV) {
  14779. internalTexture._cachedWrapV = texture.wrapV;
  14780. switch (texture.wrapV) {
  14781. case BABYLON.Texture.WRAP_ADDRESSMODE:
  14782. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_T, this._gl.REPEAT);
  14783. break;
  14784. case BABYLON.Texture.CLAMP_ADDRESSMODE:
  14785. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_T, this._gl.CLAMP_TO_EDGE);
  14786. break;
  14787. case BABYLON.Texture.MIRROR_ADDRESSMODE:
  14788. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_T, this._gl.MIRRORED_REPEAT);
  14789. break;
  14790. }
  14791. }
  14792. if (internalTexture && internalTexture._cachedWrapR !== texture.wrapR) {
  14793. internalTexture._cachedWrapR = texture.wrapR;
  14794. switch (texture.wrapR) {
  14795. case BABYLON.Texture.WRAP_ADDRESSMODE:
  14796. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_R, this._gl.REPEAT);
  14797. break;
  14798. case BABYLON.Texture.CLAMP_ADDRESSMODE:
  14799. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_R, this._gl.CLAMP_TO_EDGE);
  14800. break;
  14801. case BABYLON.Texture.MIRROR_ADDRESSMODE:
  14802. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_R, this._gl.MIRRORED_REPEAT);
  14803. break;
  14804. }
  14805. }
  14806. this._setAnisotropicLevel(this._gl.TEXTURE_3D, texture);
  14807. }
  14808. else if (internalTexture && internalTexture.isCube) {
  14809. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, internalTexture, isPartOfTextureArray);
  14810. if (internalTexture._cachedCoordinatesMode !== texture.coordinatesMode) {
  14811. internalTexture._cachedCoordinatesMode = texture.coordinatesMode;
  14812. // CUBIC_MODE and SKYBOX_MODE both require CLAMP_TO_EDGE. All other modes use REPEAT.
  14813. var textureWrapMode = (texture.coordinatesMode !== BABYLON.Texture.CUBIC_MODE && texture.coordinatesMode !== BABYLON.Texture.SKYBOX_MODE) ? this._gl.REPEAT : this._gl.CLAMP_TO_EDGE;
  14814. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_WRAP_S, textureWrapMode);
  14815. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_WRAP_T, textureWrapMode);
  14816. }
  14817. this._setAnisotropicLevel(this._gl.TEXTURE_CUBE_MAP, texture);
  14818. }
  14819. else {
  14820. this._bindTextureDirectly(this._gl.TEXTURE_2D, internalTexture, isPartOfTextureArray);
  14821. if (internalTexture && internalTexture._cachedWrapU !== texture.wrapU) {
  14822. internalTexture._cachedWrapU = texture.wrapU;
  14823. switch (texture.wrapU) {
  14824. case BABYLON.Texture.WRAP_ADDRESSMODE:
  14825. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._gl.REPEAT);
  14826. break;
  14827. case BABYLON.Texture.CLAMP_ADDRESSMODE:
  14828. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._gl.CLAMP_TO_EDGE);
  14829. break;
  14830. case BABYLON.Texture.MIRROR_ADDRESSMODE:
  14831. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._gl.MIRRORED_REPEAT);
  14832. break;
  14833. }
  14834. }
  14835. if (internalTexture && internalTexture._cachedWrapV !== texture.wrapV) {
  14836. internalTexture._cachedWrapV = texture.wrapV;
  14837. switch (texture.wrapV) {
  14838. case BABYLON.Texture.WRAP_ADDRESSMODE:
  14839. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._gl.REPEAT);
  14840. break;
  14841. case BABYLON.Texture.CLAMP_ADDRESSMODE:
  14842. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._gl.CLAMP_TO_EDGE);
  14843. break;
  14844. case BABYLON.Texture.MIRROR_ADDRESSMODE:
  14845. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._gl.MIRRORED_REPEAT);
  14846. break;
  14847. }
  14848. }
  14849. this._setAnisotropicLevel(this._gl.TEXTURE_2D, texture);
  14850. }
  14851. return true;
  14852. };
  14853. Engine.prototype.setTextureArray = function (channel, uniform, textures) {
  14854. if (channel < 0 || !uniform) {
  14855. return;
  14856. }
  14857. if (!this._textureUnits || this._textureUnits.length !== textures.length) {
  14858. this._textureUnits = new Int32Array(textures.length);
  14859. }
  14860. for (var i = 0; i < textures.length; i++) {
  14861. this._textureUnits[i] = this._getCorrectTextureChannel(channel + i, textures[i].getInternalTexture());
  14862. }
  14863. this._gl.uniform1iv(uniform, this._textureUnits);
  14864. for (var index = 0; index < textures.length; index++) {
  14865. this._setTexture(this._textureUnits[index], textures[index], true);
  14866. }
  14867. };
  14868. Engine.prototype._setAnisotropicLevel = function (key, texture) {
  14869. var internalTexture = texture.getInternalTexture();
  14870. if (!internalTexture) {
  14871. return;
  14872. }
  14873. var anisotropicFilterExtension = this._caps.textureAnisotropicFilterExtension;
  14874. var value = texture.anisotropicFilteringLevel;
  14875. if (internalTexture.samplingMode !== BABYLON.Texture.LINEAR_LINEAR_MIPNEAREST
  14876. && internalTexture.samplingMode !== BABYLON.Texture.LINEAR_LINEAR_MIPLINEAR
  14877. && internalTexture.samplingMode !== BABYLON.Texture.LINEAR_LINEAR) {
  14878. value = 1; // Forcing the anisotropic to 1 because else webgl will force filters to linear
  14879. }
  14880. if (anisotropicFilterExtension && internalTexture._cachedAnisotropicFilteringLevel !== value) {
  14881. this._gl.texParameterf(key, anisotropicFilterExtension.TEXTURE_MAX_ANISOTROPY_EXT, Math.min(value, this._caps.maxAnisotropy));
  14882. internalTexture._cachedAnisotropicFilteringLevel = value;
  14883. }
  14884. };
  14885. Engine.prototype.readPixels = function (x, y, width, height) {
  14886. var data = new Uint8Array(height * width * 4);
  14887. this._gl.readPixels(x, y, width, height, this._gl.RGBA, this._gl.UNSIGNED_BYTE, data);
  14888. return data;
  14889. };
  14890. /**
  14891. * Add an externaly attached data from its key.
  14892. * This method call will fail and return false, if such key already exists.
  14893. * If you don't care and just want to get the data no matter what, use the more convenient getOrAddExternalDataWithFactory() method.
  14894. * @param key the unique key that identifies the data
  14895. * @param data the data object to associate to the key for this Engine instance
  14896. * @return true if no such key were already present and the data was added successfully, false otherwise
  14897. */
  14898. Engine.prototype.addExternalData = function (key, data) {
  14899. if (!this._externalData) {
  14900. this._externalData = new BABYLON.StringDictionary();
  14901. }
  14902. return this._externalData.add(key, data);
  14903. };
  14904. /**
  14905. * Get an externaly attached data from its key
  14906. * @param key the unique key that identifies the data
  14907. * @return the associated data, if present (can be null), or undefined if not present
  14908. */
  14909. Engine.prototype.getExternalData = function (key) {
  14910. if (!this._externalData) {
  14911. this._externalData = new BABYLON.StringDictionary();
  14912. }
  14913. return this._externalData.get(key);
  14914. };
  14915. /**
  14916. * Get an externaly attached data from its key, create it using a factory if it's not already present
  14917. * @param key the unique key that identifies the data
  14918. * @param factory the factory that will be called to create the instance if and only if it doesn't exists
  14919. * @return the associated data, can be null if the factory returned null.
  14920. */
  14921. Engine.prototype.getOrAddExternalDataWithFactory = function (key, factory) {
  14922. if (!this._externalData) {
  14923. this._externalData = new BABYLON.StringDictionary();
  14924. }
  14925. return this._externalData.getOrAddWithFactory(key, factory);
  14926. };
  14927. /**
  14928. * Remove an externaly attached data from the Engine instance
  14929. * @param key the unique key that identifies the data
  14930. * @return true if the data was successfully removed, false if it doesn't exist
  14931. */
  14932. Engine.prototype.removeExternalData = function (key) {
  14933. if (!this._externalData) {
  14934. this._externalData = new BABYLON.StringDictionary();
  14935. }
  14936. return this._externalData.remove(key);
  14937. };
  14938. Engine.prototype.unbindAllAttributes = function () {
  14939. if (this._mustWipeVertexAttributes) {
  14940. this._mustWipeVertexAttributes = false;
  14941. for (var i = 0; i < this._caps.maxVertexAttribs; i++) {
  14942. this._gl.disableVertexAttribArray(i);
  14943. this._vertexAttribArraysEnabled[i] = false;
  14944. this._currentBufferPointers[i].active = false;
  14945. }
  14946. return;
  14947. }
  14948. for (var i = 0, ul = this._vertexAttribArraysEnabled.length; i < ul; i++) {
  14949. if (i >= this._caps.maxVertexAttribs || !this._vertexAttribArraysEnabled[i]) {
  14950. continue;
  14951. }
  14952. this._gl.disableVertexAttribArray(i);
  14953. this._vertexAttribArraysEnabled[i] = false;
  14954. this._currentBufferPointers[i].active = false;
  14955. }
  14956. };
  14957. Engine.prototype.releaseEffects = function () {
  14958. for (var name in this._compiledEffects) {
  14959. this._deleteProgram(this._compiledEffects[name]._program);
  14960. }
  14961. this._compiledEffects = {};
  14962. };
  14963. // Dispose
  14964. Engine.prototype.dispose = function () {
  14965. this.hideLoadingUI();
  14966. this.stopRenderLoop();
  14967. // Release postProcesses
  14968. while (this.postProcesses.length) {
  14969. this.postProcesses[0].dispose();
  14970. }
  14971. // Empty texture
  14972. if (this._emptyTexture) {
  14973. this._releaseTexture(this._emptyTexture);
  14974. this._emptyTexture = null;
  14975. }
  14976. if (this._emptyCubeTexture) {
  14977. this._releaseTexture(this._emptyCubeTexture);
  14978. this._emptyCubeTexture = null;
  14979. }
  14980. // Rescale PP
  14981. if (this._rescalePostProcess) {
  14982. this._rescalePostProcess.dispose();
  14983. }
  14984. // Release scenes
  14985. while (this.scenes.length) {
  14986. this.scenes[0].dispose();
  14987. }
  14988. // Release audio engine
  14989. if (Engine.audioEngine) {
  14990. Engine.audioEngine.dispose();
  14991. }
  14992. // Release effects
  14993. this.releaseEffects();
  14994. // Unbind
  14995. this.unbindAllAttributes();
  14996. this._boundUniforms = [];
  14997. if (this._dummyFramebuffer) {
  14998. this._gl.deleteFramebuffer(this._dummyFramebuffer);
  14999. }
  15000. //WebVR
  15001. this.disableVR();
  15002. // Events
  15003. if (BABYLON.Tools.IsWindowObjectExist()) {
  15004. window.removeEventListener("blur", this._onBlur);
  15005. window.removeEventListener("focus", this._onFocus);
  15006. window.removeEventListener('vrdisplaypointerrestricted', this._onVRDisplayPointerRestricted);
  15007. window.removeEventListener('vrdisplaypointerunrestricted', this._onVRDisplayPointerUnrestricted);
  15008. if (this._renderingCanvas) {
  15009. this._renderingCanvas.removeEventListener("focus", this._onCanvasFocus);
  15010. this._renderingCanvas.removeEventListener("blur", this._onCanvasBlur);
  15011. this._renderingCanvas.removeEventListener("pointerout", this._onCanvasPointerOut);
  15012. if (!this._doNotHandleContextLost) {
  15013. this._renderingCanvas.removeEventListener("webglcontextlost", this._onContextLost);
  15014. this._renderingCanvas.removeEventListener("webglcontextrestored", this._onContextRestored);
  15015. }
  15016. }
  15017. document.removeEventListener("fullscreenchange", this._onFullscreenChange);
  15018. document.removeEventListener("mozfullscreenchange", this._onFullscreenChange);
  15019. document.removeEventListener("webkitfullscreenchange", this._onFullscreenChange);
  15020. document.removeEventListener("msfullscreenchange", this._onFullscreenChange);
  15021. document.removeEventListener("pointerlockchange", this._onPointerLockChange);
  15022. document.removeEventListener("mspointerlockchange", this._onPointerLockChange);
  15023. document.removeEventListener("mozpointerlockchange", this._onPointerLockChange);
  15024. document.removeEventListener("webkitpointerlockchange", this._onPointerLockChange);
  15025. if (this._onVrDisplayConnect) {
  15026. window.removeEventListener('vrdisplayconnect', this._onVrDisplayConnect);
  15027. if (this._onVrDisplayDisconnect) {
  15028. window.removeEventListener('vrdisplaydisconnect', this._onVrDisplayDisconnect);
  15029. }
  15030. if (this._onVrDisplayPresentChange) {
  15031. window.removeEventListener('vrdisplaypresentchange', this._onVrDisplayPresentChange);
  15032. }
  15033. this._onVrDisplayConnect = null;
  15034. this._onVrDisplayDisconnect = null;
  15035. }
  15036. }
  15037. // Remove from Instances
  15038. var index = Engine.Instances.indexOf(this);
  15039. if (index >= 0) {
  15040. Engine.Instances.splice(index, 1);
  15041. }
  15042. this._workingCanvas = null;
  15043. this._workingContext = null;
  15044. this._currentBufferPointers = [];
  15045. this._renderingCanvas = null;
  15046. this._currentProgram = null;
  15047. this._bindedRenderFunction = null;
  15048. this.onResizeObservable.clear();
  15049. this.onCanvasBlurObservable.clear();
  15050. this.onCanvasFocusObservable.clear();
  15051. this.onCanvasPointerOutObservable.clear();
  15052. this.onBeginFrameObservable.clear();
  15053. this.onEndFrameObservable.clear();
  15054. BABYLON.Effect.ResetCache();
  15055. // Abort active requests
  15056. for (var _i = 0, _a = this._activeRequests; _i < _a.length; _i++) {
  15057. var request = _a[_i];
  15058. request.abort();
  15059. }
  15060. };
  15061. // Loading screen
  15062. Engine.prototype.displayLoadingUI = function () {
  15063. if (!BABYLON.Tools.IsWindowObjectExist()) {
  15064. return;
  15065. }
  15066. var loadingScreen = this.loadingScreen;
  15067. if (loadingScreen) {
  15068. loadingScreen.displayLoadingUI();
  15069. }
  15070. };
  15071. Engine.prototype.hideLoadingUI = function () {
  15072. if (!BABYLON.Tools.IsWindowObjectExist()) {
  15073. return;
  15074. }
  15075. var loadingScreen = this.loadingScreen;
  15076. if (loadingScreen) {
  15077. loadingScreen.hideLoadingUI();
  15078. }
  15079. };
  15080. Object.defineProperty(Engine.prototype, "loadingScreen", {
  15081. get: function () {
  15082. if (!this._loadingScreen && BABYLON.DefaultLoadingScreen && this._renderingCanvas)
  15083. this._loadingScreen = new BABYLON.DefaultLoadingScreen(this._renderingCanvas);
  15084. return this._loadingScreen;
  15085. },
  15086. set: function (loadingScreen) {
  15087. this._loadingScreen = loadingScreen;
  15088. },
  15089. enumerable: true,
  15090. configurable: true
  15091. });
  15092. Object.defineProperty(Engine.prototype, "loadingUIText", {
  15093. set: function (text) {
  15094. this.loadingScreen.loadingUIText = text;
  15095. },
  15096. enumerable: true,
  15097. configurable: true
  15098. });
  15099. Object.defineProperty(Engine.prototype, "loadingUIBackgroundColor", {
  15100. set: function (color) {
  15101. this.loadingScreen.loadingUIBackgroundColor = color;
  15102. },
  15103. enumerable: true,
  15104. configurable: true
  15105. });
  15106. Engine.prototype.attachContextLostEvent = function (callback) {
  15107. if (this._renderingCanvas) {
  15108. this._renderingCanvas.addEventListener("webglcontextlost", callback, false);
  15109. }
  15110. };
  15111. Engine.prototype.attachContextRestoredEvent = function (callback) {
  15112. if (this._renderingCanvas) {
  15113. this._renderingCanvas.addEventListener("webglcontextrestored", callback, false);
  15114. }
  15115. };
  15116. Engine.prototype.getVertexShaderSource = function (program) {
  15117. var shaders = this._gl.getAttachedShaders(program);
  15118. if (!shaders) {
  15119. return null;
  15120. }
  15121. return this._gl.getShaderSource(shaders[0]);
  15122. };
  15123. Engine.prototype.getFragmentShaderSource = function (program) {
  15124. var shaders = this._gl.getAttachedShaders(program);
  15125. if (!shaders) {
  15126. return null;
  15127. }
  15128. return this._gl.getShaderSource(shaders[1]);
  15129. };
  15130. Engine.prototype.getError = function () {
  15131. return this._gl.getError();
  15132. };
  15133. // FPS
  15134. Engine.prototype.getFps = function () {
  15135. return this._fps;
  15136. };
  15137. Engine.prototype.getDeltaTime = function () {
  15138. return this._deltaTime;
  15139. };
  15140. Engine.prototype._measureFps = function () {
  15141. this._performanceMonitor.sampleFrame();
  15142. this._fps = this._performanceMonitor.averageFPS;
  15143. this._deltaTime = this._performanceMonitor.instantaneousFrameTime || 0;
  15144. };
  15145. Engine.prototype._readTexturePixels = function (texture, width, height, faceIndex) {
  15146. if (faceIndex === void 0) { faceIndex = -1; }
  15147. var gl = this._gl;
  15148. if (!this._dummyFramebuffer) {
  15149. var dummy = gl.createFramebuffer();
  15150. if (!dummy) {
  15151. throw new Error("Unable to create dummy framebuffer");
  15152. }
  15153. this._dummyFramebuffer = dummy;
  15154. }
  15155. gl.bindFramebuffer(gl.FRAMEBUFFER, this._dummyFramebuffer);
  15156. if (faceIndex > -1) {
  15157. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, texture._webGLTexture, 0);
  15158. }
  15159. else {
  15160. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texture._webGLTexture, 0);
  15161. }
  15162. var readType = (texture.type !== undefined) ? this._getWebGLTextureType(texture.type) : gl.UNSIGNED_BYTE;
  15163. var buffer;
  15164. switch (readType) {
  15165. case gl.UNSIGNED_BYTE:
  15166. buffer = new Uint8Array(4 * width * height);
  15167. readType = gl.UNSIGNED_BYTE;
  15168. break;
  15169. default:
  15170. buffer = new Float32Array(4 * width * height);
  15171. readType = gl.FLOAT;
  15172. break;
  15173. }
  15174. gl.readPixels(0, 0, width, height, gl.RGBA, readType, buffer);
  15175. gl.bindFramebuffer(gl.FRAMEBUFFER, this._currentFramebuffer);
  15176. return buffer;
  15177. };
  15178. Engine.prototype._canRenderToFloatFramebuffer = function () {
  15179. if (this._webGLVersion > 1) {
  15180. return this._caps.colorBufferFloat;
  15181. }
  15182. return this._canRenderToFramebuffer(Engine.TEXTURETYPE_FLOAT);
  15183. };
  15184. Engine.prototype._canRenderToHalfFloatFramebuffer = function () {
  15185. if (this._webGLVersion > 1) {
  15186. return this._caps.colorBufferFloat;
  15187. }
  15188. return this._canRenderToFramebuffer(Engine.TEXTURETYPE_HALF_FLOAT);
  15189. };
  15190. // Thank you : http://stackoverflow.com/questions/28827511/webgl-ios-render-to-floating-point-texture
  15191. Engine.prototype._canRenderToFramebuffer = function (type) {
  15192. var gl = this._gl;
  15193. //clear existing errors
  15194. while (gl.getError() !== gl.NO_ERROR) { }
  15195. var successful = true;
  15196. var texture = gl.createTexture();
  15197. gl.bindTexture(gl.TEXTURE_2D, texture);
  15198. gl.texImage2D(gl.TEXTURE_2D, 0, this._getRGBABufferInternalSizedFormat(type), 1, 1, 0, gl.RGBA, this._getWebGLTextureType(type), null);
  15199. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  15200. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  15201. var fb = gl.createFramebuffer();
  15202. gl.bindFramebuffer(gl.FRAMEBUFFER, fb);
  15203. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texture, 0);
  15204. var status = gl.checkFramebufferStatus(gl.FRAMEBUFFER);
  15205. successful = successful && (status === gl.FRAMEBUFFER_COMPLETE);
  15206. successful = successful && (gl.getError() === gl.NO_ERROR);
  15207. //try render by clearing frame buffer's color buffer
  15208. if (successful) {
  15209. gl.clear(gl.COLOR_BUFFER_BIT);
  15210. successful = successful && (gl.getError() === gl.NO_ERROR);
  15211. }
  15212. //try reading from frame to ensure render occurs (just creating the FBO is not sufficient to determine if rendering is supported)
  15213. if (successful) {
  15214. //in practice it's sufficient to just read from the backbuffer rather than handle potentially issues reading from the texture
  15215. gl.bindFramebuffer(gl.FRAMEBUFFER, null);
  15216. var readFormat = gl.RGBA;
  15217. var readType = gl.UNSIGNED_BYTE;
  15218. var buffer = new Uint8Array(4);
  15219. gl.readPixels(0, 0, 1, 1, readFormat, readType, buffer);
  15220. successful = successful && (gl.getError() === gl.NO_ERROR);
  15221. }
  15222. //clean up
  15223. gl.deleteTexture(texture);
  15224. gl.deleteFramebuffer(fb);
  15225. gl.bindFramebuffer(gl.FRAMEBUFFER, null);
  15226. //clear accumulated errors
  15227. while (!successful && (gl.getError() !== gl.NO_ERROR)) { }
  15228. return successful;
  15229. };
  15230. Engine.prototype._getWebGLTextureType = function (type) {
  15231. if (type === Engine.TEXTURETYPE_FLOAT) {
  15232. return this._gl.FLOAT;
  15233. }
  15234. else if (type === Engine.TEXTURETYPE_HALF_FLOAT) {
  15235. // Add Half Float Constant.
  15236. return this._gl.HALF_FLOAT_OES;
  15237. }
  15238. return this._gl.UNSIGNED_BYTE;
  15239. };
  15240. ;
  15241. Engine.prototype._getInternalFormat = function (format) {
  15242. var internalFormat = this._gl.RGBA;
  15243. switch (format) {
  15244. case Engine.TEXTUREFORMAT_ALPHA:
  15245. internalFormat = this._gl.ALPHA;
  15246. break;
  15247. case Engine.TEXTUREFORMAT_LUMINANCE:
  15248. internalFormat = this._gl.LUMINANCE;
  15249. break;
  15250. case Engine.TEXTUREFORMAT_LUMINANCE_ALPHA:
  15251. internalFormat = this._gl.LUMINANCE_ALPHA;
  15252. break;
  15253. case Engine.TEXTUREFORMAT_RGB:
  15254. case Engine.TEXTUREFORMAT_RGB32F:
  15255. internalFormat = this._gl.RGB;
  15256. break;
  15257. case Engine.TEXTUREFORMAT_RGBA:
  15258. case Engine.TEXTUREFORMAT_RGBA32F:
  15259. internalFormat = this._gl.RGBA;
  15260. break;
  15261. case Engine.TEXTUREFORMAT_R32F:
  15262. internalFormat = this._gl.RED;
  15263. break;
  15264. case Engine.TEXTUREFORMAT_RG32F:
  15265. internalFormat = this._gl.RG;
  15266. break;
  15267. }
  15268. return internalFormat;
  15269. };
  15270. /** @ignore */
  15271. Engine.prototype._getRGBABufferInternalSizedFormat = function (type, format) {
  15272. if (this._webGLVersion === 1) {
  15273. if (format) {
  15274. switch (format) {
  15275. case Engine.TEXTUREFORMAT_LUMINANCE:
  15276. return this._gl.LUMINANCE;
  15277. }
  15278. }
  15279. return this._gl.RGBA;
  15280. }
  15281. if (type === Engine.TEXTURETYPE_FLOAT) {
  15282. if (format) {
  15283. switch (format) {
  15284. case Engine.TEXTUREFORMAT_R32F:
  15285. return this._gl.R32F;
  15286. case Engine.TEXTUREFORMAT_RG32F:
  15287. return this._gl.RG32F;
  15288. case Engine.TEXTUREFORMAT_RGB32F:
  15289. return this._gl.RGB32F;
  15290. }
  15291. }
  15292. return this._gl.RGBA32F;
  15293. }
  15294. else if (type === Engine.TEXTURETYPE_HALF_FLOAT) {
  15295. return this._gl.RGBA16F;
  15296. }
  15297. if (format) {
  15298. switch (format) {
  15299. case Engine.TEXTUREFORMAT_LUMINANCE:
  15300. return this._gl.LUMINANCE;
  15301. }
  15302. }
  15303. return this._gl.RGBA;
  15304. };
  15305. ;
  15306. Engine.prototype._getRGBAMultiSampleBufferFormat = function (type) {
  15307. if (type === Engine.TEXTURETYPE_FLOAT) {
  15308. return this._gl.RGBA32F;
  15309. }
  15310. else if (type === Engine.TEXTURETYPE_HALF_FLOAT) {
  15311. return this._gl.RGBA16F;
  15312. }
  15313. return this._gl.RGBA8;
  15314. };
  15315. ;
  15316. Engine.prototype.createQuery = function () {
  15317. return this._gl.createQuery();
  15318. };
  15319. Engine.prototype.deleteQuery = function (query) {
  15320. this._gl.deleteQuery(query);
  15321. return this;
  15322. };
  15323. Engine.prototype.isQueryResultAvailable = function (query) {
  15324. return this._gl.getQueryParameter(query, this._gl.QUERY_RESULT_AVAILABLE);
  15325. };
  15326. Engine.prototype.getQueryResult = function (query) {
  15327. return this._gl.getQueryParameter(query, this._gl.QUERY_RESULT);
  15328. };
  15329. Engine.prototype.beginOcclusionQuery = function (algorithmType, query) {
  15330. var glAlgorithm = this.getGlAlgorithmType(algorithmType);
  15331. this._gl.beginQuery(glAlgorithm, query);
  15332. return this;
  15333. };
  15334. Engine.prototype.endOcclusionQuery = function (algorithmType) {
  15335. var glAlgorithm = this.getGlAlgorithmType(algorithmType);
  15336. this._gl.endQuery(glAlgorithm);
  15337. return this;
  15338. };
  15339. /* Time queries */
  15340. Engine.prototype._createTimeQuery = function () {
  15341. var timerQuery = this._caps.timerQuery;
  15342. if (timerQuery.createQueryEXT) {
  15343. return timerQuery.createQueryEXT();
  15344. }
  15345. return this.createQuery();
  15346. };
  15347. Engine.prototype._deleteTimeQuery = function (query) {
  15348. var timerQuery = this._caps.timerQuery;
  15349. if (timerQuery.deleteQueryEXT) {
  15350. timerQuery.deleteQueryEXT(query);
  15351. return;
  15352. }
  15353. this.deleteQuery(query);
  15354. };
  15355. Engine.prototype._getTimeQueryResult = function (query) {
  15356. var timerQuery = this._caps.timerQuery;
  15357. if (timerQuery.getQueryObjectEXT) {
  15358. return timerQuery.getQueryObjectEXT(query, timerQuery.QUERY_RESULT_EXT);
  15359. }
  15360. return this.getQueryResult(query);
  15361. };
  15362. Engine.prototype._getTimeQueryAvailability = function (query) {
  15363. var timerQuery = this._caps.timerQuery;
  15364. if (timerQuery.getQueryObjectEXT) {
  15365. return timerQuery.getQueryObjectEXT(query, timerQuery.QUERY_RESULT_AVAILABLE_EXT);
  15366. }
  15367. return this.isQueryResultAvailable(query);
  15368. };
  15369. Engine.prototype.startTimeQuery = function () {
  15370. var timerQuery = this._caps.timerQuery;
  15371. if (!timerQuery) {
  15372. return null;
  15373. }
  15374. var token = new BABYLON._TimeToken();
  15375. this._gl.getParameter(timerQuery.GPU_DISJOINT_EXT);
  15376. if (this._caps.canUseTimestampForTimerQuery) {
  15377. token._startTimeQuery = this._createTimeQuery();
  15378. timerQuery.queryCounterEXT(token._startTimeQuery, timerQuery.TIMESTAMP_EXT);
  15379. }
  15380. else {
  15381. if (this._currentNonTimestampToken) {
  15382. return this._currentNonTimestampToken;
  15383. }
  15384. token._timeElapsedQuery = this._createTimeQuery();
  15385. if (timerQuery.beginQueryEXT) {
  15386. timerQuery.beginQueryEXT(timerQuery.TIME_ELAPSED_EXT, token._timeElapsedQuery);
  15387. }
  15388. else {
  15389. this._gl.beginQuery(timerQuery.TIME_ELAPSED_EXT, token._timeElapsedQuery);
  15390. }
  15391. this._currentNonTimestampToken = token;
  15392. }
  15393. return token;
  15394. };
  15395. Engine.prototype.endTimeQuery = function (token) {
  15396. var timerQuery = this._caps.timerQuery;
  15397. if (!timerQuery || !token) {
  15398. return -1;
  15399. }
  15400. if (this._caps.canUseTimestampForTimerQuery) {
  15401. if (!token._startTimeQuery) {
  15402. return -1;
  15403. }
  15404. if (!token._endTimeQuery) {
  15405. token._endTimeQuery = this._createTimeQuery();
  15406. timerQuery.queryCounterEXT(token._endTimeQuery, timerQuery.TIMESTAMP_EXT);
  15407. }
  15408. }
  15409. else if (!token._timeElapsedQueryEnded) {
  15410. if (!token._timeElapsedQuery) {
  15411. return -1;
  15412. }
  15413. if (timerQuery.endQueryEXT) {
  15414. timerQuery.endQueryEXT(timerQuery.TIME_ELAPSED_EXT);
  15415. }
  15416. else {
  15417. this._gl.endQuery(timerQuery.TIME_ELAPSED_EXT);
  15418. }
  15419. token._timeElapsedQueryEnded = true;
  15420. }
  15421. var disjoint = this._gl.getParameter(timerQuery.GPU_DISJOINT_EXT);
  15422. var available = false;
  15423. if (token._endTimeQuery) {
  15424. available = this._getTimeQueryAvailability(token._endTimeQuery);
  15425. }
  15426. else if (token._timeElapsedQuery) {
  15427. available = this._getTimeQueryAvailability(token._timeElapsedQuery);
  15428. }
  15429. if (available && !disjoint) {
  15430. var result = 0;
  15431. if (this._caps.canUseTimestampForTimerQuery) {
  15432. if (!token._startTimeQuery || !token._endTimeQuery) {
  15433. return -1;
  15434. }
  15435. var timeStart = this._getTimeQueryResult(token._startTimeQuery);
  15436. var timeEnd = this._getTimeQueryResult(token._endTimeQuery);
  15437. result = timeEnd - timeStart;
  15438. this._deleteTimeQuery(token._startTimeQuery);
  15439. this._deleteTimeQuery(token._endTimeQuery);
  15440. token._startTimeQuery = null;
  15441. token._endTimeQuery = null;
  15442. }
  15443. else {
  15444. if (!token._timeElapsedQuery) {
  15445. return -1;
  15446. }
  15447. result = this._getTimeQueryResult(token._timeElapsedQuery);
  15448. this._deleteTimeQuery(token._timeElapsedQuery);
  15449. token._timeElapsedQuery = null;
  15450. token._timeElapsedQueryEnded = false;
  15451. this._currentNonTimestampToken = null;
  15452. }
  15453. return result;
  15454. }
  15455. return -1;
  15456. };
  15457. Engine.prototype.getGlAlgorithmType = function (algorithmType) {
  15458. return algorithmType === BABYLON.AbstractMesh.OCCLUSION_ALGORITHM_TYPE_CONSERVATIVE ? this._gl.ANY_SAMPLES_PASSED_CONSERVATIVE : this._gl.ANY_SAMPLES_PASSED;
  15459. };
  15460. // Transform feedback
  15461. Engine.prototype.createTransformFeedback = function () {
  15462. return this._gl.createTransformFeedback();
  15463. };
  15464. Engine.prototype.deleteTransformFeedback = function (value) {
  15465. this._gl.deleteTransformFeedback(value);
  15466. };
  15467. Engine.prototype.bindTransformFeedback = function (value) {
  15468. this._gl.bindTransformFeedback(this._gl.TRANSFORM_FEEDBACK, value);
  15469. };
  15470. Engine.prototype.beginTransformFeedback = function (usePoints) {
  15471. if (usePoints === void 0) { usePoints = true; }
  15472. this._gl.beginTransformFeedback(usePoints ? this._gl.POINTS : this._gl.TRIANGLES);
  15473. };
  15474. Engine.prototype.endTransformFeedback = function () {
  15475. this._gl.endTransformFeedback();
  15476. };
  15477. Engine.prototype.setTranformFeedbackVaryings = function (program, value) {
  15478. this._gl.transformFeedbackVaryings(program, value, this._gl.INTERLEAVED_ATTRIBS);
  15479. };
  15480. Engine.prototype.bindTransformFeedbackBuffer = function (value) {
  15481. this._gl.bindBufferBase(this._gl.TRANSFORM_FEEDBACK_BUFFER, 0, value);
  15482. };
  15483. Engine.prototype._loadFile = function (url, onSuccess, onProgress, database, useArrayBuffer, onError) {
  15484. var _this = this;
  15485. var request = BABYLON.Tools.LoadFile(url, onSuccess, onProgress, database, useArrayBuffer, onError);
  15486. this._activeRequests.push(request);
  15487. request.onCompleteObservable.add(function (request) {
  15488. _this._activeRequests.splice(_this._activeRequests.indexOf(request), 1);
  15489. });
  15490. return request;
  15491. };
  15492. /** @ignore */
  15493. Engine.prototype._loadFileAsync = function (url, database, useArrayBuffer) {
  15494. var _this = this;
  15495. return new Promise(function (resolve, reject) {
  15496. _this._loadFile(url, function (data) {
  15497. resolve(data);
  15498. }, undefined, database, useArrayBuffer, function (request, exception) {
  15499. reject(exception);
  15500. });
  15501. });
  15502. };
  15503. Engine.prototype._partialLoadFile = function (url, index, loadedFiles, scene, onfinish, onErrorCallBack) {
  15504. if (onErrorCallBack === void 0) { onErrorCallBack = null; }
  15505. var onload = function (data) {
  15506. loadedFiles[index] = data;
  15507. loadedFiles._internalCount++;
  15508. if (loadedFiles._internalCount === 6) {
  15509. onfinish(loadedFiles);
  15510. }
  15511. };
  15512. var onerror = function (request, exception) {
  15513. if (onErrorCallBack && request) {
  15514. onErrorCallBack(request.status + " " + request.statusText, exception);
  15515. }
  15516. };
  15517. this._loadFile(url, onload, undefined, undefined, true, onerror);
  15518. };
  15519. Engine.prototype._cascadeLoadFiles = function (scene, onfinish, files, onError) {
  15520. if (onError === void 0) { onError = null; }
  15521. var loadedFiles = [];
  15522. loadedFiles._internalCount = 0;
  15523. for (var index = 0; index < 6; index++) {
  15524. this._partialLoadFile(files[index], index, loadedFiles, scene, onfinish, onError);
  15525. }
  15526. };
  15527. // Statics
  15528. Engine.isSupported = function () {
  15529. try {
  15530. var tempcanvas = document.createElement("canvas");
  15531. var gl = tempcanvas.getContext("webgl") || tempcanvas.getContext("experimental-webgl");
  15532. return gl != null && !!window.WebGLRenderingContext;
  15533. }
  15534. catch (e) {
  15535. return false;
  15536. }
  15537. };
  15538. /** Use this array to turn off some WebGL2 features on known buggy browsers version */
  15539. Engine.ExceptionList = [
  15540. { key: "Chrome/63.0", capture: "63\\.0\\.3239\\.(\\d+)", captureConstraint: 108, targets: ["uniformBuffer"] },
  15541. { key: "Firefox/58", capture: null, captureConstraint: null, targets: ["uniformBuffer"] },
  15542. { key: "Firefox/59", capture: null, captureConstraint: null, targets: ["uniformBuffer"] },
  15543. { key: "Macintosh", capture: null, captureConstraint: null, targets: ["textureBindingOptimization"] },
  15544. { key: "iPhone", capture: null, captureConstraint: null, targets: ["textureBindingOptimization"] },
  15545. { key: "iPad", capture: null, captureConstraint: null, targets: ["textureBindingOptimization"] }
  15546. ];
  15547. Engine.Instances = new Array();
  15548. // Const statics
  15549. Engine._ALPHA_DISABLE = 0;
  15550. Engine._ALPHA_ADD = 1;
  15551. Engine._ALPHA_COMBINE = 2;
  15552. Engine._ALPHA_SUBTRACT = 3;
  15553. Engine._ALPHA_MULTIPLY = 4;
  15554. Engine._ALPHA_MAXIMIZED = 5;
  15555. Engine._ALPHA_ONEONE = 6;
  15556. Engine._ALPHA_PREMULTIPLIED = 7;
  15557. Engine._ALPHA_PREMULTIPLIED_PORTERDUFF = 8;
  15558. Engine._ALPHA_INTERPOLATE = 9;
  15559. Engine._ALPHA_SCREENMODE = 10;
  15560. Engine._DELAYLOADSTATE_NONE = 0;
  15561. Engine._DELAYLOADSTATE_LOADED = 1;
  15562. Engine._DELAYLOADSTATE_LOADING = 2;
  15563. Engine._DELAYLOADSTATE_NOTLOADED = 4;
  15564. Engine._TEXTUREFORMAT_ALPHA = 0;
  15565. Engine._TEXTUREFORMAT_LUMINANCE = 1;
  15566. Engine._TEXTUREFORMAT_LUMINANCE_ALPHA = 2;
  15567. Engine._TEXTUREFORMAT_RGB = 4;
  15568. Engine._TEXTUREFORMAT_RGBA = 5;
  15569. Engine._TEXTUREFORMAT_R32F = 6;
  15570. Engine._TEXTUREFORMAT_RG32F = 7;
  15571. Engine._TEXTUREFORMAT_RGB32F = 8;
  15572. Engine._TEXTUREFORMAT_RGBA32F = 9;
  15573. Engine._TEXTURETYPE_UNSIGNED_INT = 0;
  15574. Engine._TEXTURETYPE_FLOAT = 1;
  15575. Engine._TEXTURETYPE_HALF_FLOAT = 2;
  15576. // Depht or Stencil test Constants.
  15577. Engine._NEVER = 0x0200; // Passed to depthFunction or stencilFunction to specify depth or stencil tests will never pass. i.e. Nothing will be drawn.
  15578. 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.
  15579. 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.
  15580. 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.
  15581. 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.
  15582. 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.
  15583. 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.
  15584. 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.
  15585. // Stencil Actions Constants.
  15586. Engine._KEEP = 0x1E00;
  15587. Engine._REPLACE = 0x1E01;
  15588. Engine._INCR = 0x1E02;
  15589. Engine._DECR = 0x1E03;
  15590. Engine._INVERT = 0x150A;
  15591. Engine._INCR_WRAP = 0x8507;
  15592. Engine._DECR_WRAP = 0x8508;
  15593. // Texture rescaling mode
  15594. Engine._SCALEMODE_FLOOR = 1;
  15595. Engine._SCALEMODE_NEAREST = 2;
  15596. Engine._SCALEMODE_CEILING = 3;
  15597. // Updatable statics so stick with vars here
  15598. Engine.CollisionsEpsilon = 0.001;
  15599. Engine.CodeRepository = "src/";
  15600. Engine.ShadersRepository = "src/Shaders/";
  15601. return Engine;
  15602. }());
  15603. BABYLON.Engine = Engine;
  15604. })(BABYLON || (BABYLON = {}));
  15605. //# sourceMappingURL=babylon.engine.js.map
  15606. "use strict";
  15607. var BABYLON;
  15608. (function (BABYLON) {
  15609. /**
  15610. * Node is the basic class for all scene objects (Mesh, Light Camera).
  15611. */
  15612. var Node = /** @class */ (function () {
  15613. /**
  15614. * Creates a new Node
  15615. * @param {string} name - the name and id to be given to this node
  15616. * @param {BABYLON.Scene} the scene this node will be added to
  15617. */
  15618. function Node(name, scene) {
  15619. if (scene === void 0) { scene = null; }
  15620. /**
  15621. * Gets or sets a string used to store user defined state for the node
  15622. */
  15623. this.state = "";
  15624. /**
  15625. * Gets or sets an object used to store user defined information for the node
  15626. */
  15627. this.metadata = null;
  15628. /**
  15629. * Gets or sets a boolean used to define if the node must be serialized
  15630. */
  15631. this.doNotSerialize = false;
  15632. /** @ignore */
  15633. this._isDisposed = false;
  15634. /**
  15635. * Gets a list of {BABYLON.Animation} associated with the node
  15636. */
  15637. this.animations = new Array();
  15638. this._ranges = {};
  15639. this._isEnabled = true;
  15640. this._isReady = true;
  15641. /** @ignore */
  15642. this._currentRenderId = -1;
  15643. this._parentRenderId = -1;
  15644. this._childRenderId = -1;
  15645. this._animationPropertiesOverride = null;
  15646. /**
  15647. * An event triggered when the mesh is disposed
  15648. */
  15649. this.onDisposeObservable = new BABYLON.Observable();
  15650. // Behaviors
  15651. this._behaviors = new Array();
  15652. this.name = name;
  15653. this.id = name;
  15654. this._scene = (scene || BABYLON.Engine.LastCreatedScene);
  15655. this.uniqueId = this._scene.getUniqueId();
  15656. this._initCache();
  15657. }
  15658. /**
  15659. * Gets a boolean indicating if the node has been disposed
  15660. * @returns true if the node was disposed
  15661. */
  15662. Node.prototype.isDisposed = function () {
  15663. return this._isDisposed;
  15664. };
  15665. Object.defineProperty(Node.prototype, "parent", {
  15666. get: function () {
  15667. return this._parentNode;
  15668. },
  15669. /**
  15670. * Gets or sets the parent of the node
  15671. */
  15672. set: function (parent) {
  15673. if (this._parentNode === parent) {
  15674. return;
  15675. }
  15676. // Remove self from list of children of parent
  15677. if (this._parentNode && this._parentNode._children !== undefined && this._parentNode._children !== null) {
  15678. var index = this._parentNode._children.indexOf(this);
  15679. if (index !== -1) {
  15680. this._parentNode._children.splice(index, 1);
  15681. }
  15682. }
  15683. // Store new parent
  15684. this._parentNode = parent;
  15685. // Add as child to new parent
  15686. if (this._parentNode) {
  15687. if (this._parentNode._children === undefined || this._parentNode._children === null) {
  15688. this._parentNode._children = new Array();
  15689. }
  15690. this._parentNode._children.push(this);
  15691. }
  15692. },
  15693. enumerable: true,
  15694. configurable: true
  15695. });
  15696. Object.defineProperty(Node.prototype, "animationPropertiesOverride", {
  15697. /**
  15698. * Gets or sets the animation properties override
  15699. */
  15700. get: function () {
  15701. return this._animationPropertiesOverride;
  15702. },
  15703. set: function (value) {
  15704. this._animationPropertiesOverride = value;
  15705. },
  15706. enumerable: true,
  15707. configurable: true
  15708. });
  15709. /**
  15710. * Gets a string idenfifying the name of the class
  15711. * @returns "Node" string
  15712. */
  15713. Node.prototype.getClassName = function () {
  15714. return "Node";
  15715. };
  15716. Object.defineProperty(Node.prototype, "onDispose", {
  15717. /**
  15718. * Sets a callback that will be raised when the node will be disposed
  15719. */
  15720. set: function (callback) {
  15721. if (this._onDisposeObserver) {
  15722. this.onDisposeObservable.remove(this._onDisposeObserver);
  15723. }
  15724. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  15725. },
  15726. enumerable: true,
  15727. configurable: true
  15728. });
  15729. /**
  15730. * Gets the scene of the node
  15731. * @returns a {BABYLON.Scene}
  15732. */
  15733. Node.prototype.getScene = function () {
  15734. return this._scene;
  15735. };
  15736. /**
  15737. * Gets the engine of the node
  15738. * @returns a {BABYLON.Engine}
  15739. */
  15740. Node.prototype.getEngine = function () {
  15741. return this._scene.getEngine();
  15742. };
  15743. /**
  15744. * Attach a behavior to the node
  15745. * @see http://doc.babylonjs.com/features/behaviour
  15746. * @param behavior defines the behavior to attach
  15747. * @returns the current Node
  15748. */
  15749. Node.prototype.addBehavior = function (behavior) {
  15750. var _this = this;
  15751. var index = this._behaviors.indexOf(behavior);
  15752. if (index !== -1) {
  15753. return this;
  15754. }
  15755. behavior.init();
  15756. if (this._scene.isLoading) {
  15757. // We defer the attach when the scene will be loaded
  15758. var observer = this._scene.onDataLoadedObservable.add(function () {
  15759. behavior.attach(_this);
  15760. setTimeout(function () {
  15761. // Need to use a timeout to avoid removing an observer while iterating the list of observers
  15762. _this._scene.onDataLoadedObservable.remove(observer);
  15763. }, 0);
  15764. });
  15765. }
  15766. else {
  15767. behavior.attach(this);
  15768. }
  15769. this._behaviors.push(behavior);
  15770. return this;
  15771. };
  15772. /**
  15773. * Remove an attached behavior
  15774. * @see http://doc.babylonjs.com/features/behaviour
  15775. * @param behavior defines the behavior to attach
  15776. * @returns the current Node
  15777. */
  15778. Node.prototype.removeBehavior = function (behavior) {
  15779. var index = this._behaviors.indexOf(behavior);
  15780. if (index === -1) {
  15781. return this;
  15782. }
  15783. this._behaviors[index].detach();
  15784. this._behaviors.splice(index, 1);
  15785. return this;
  15786. };
  15787. Object.defineProperty(Node.prototype, "behaviors", {
  15788. /**
  15789. * Gets the list of attached behaviors
  15790. * @see http://doc.babylonjs.com/features/behaviour
  15791. */
  15792. get: function () {
  15793. return this._behaviors;
  15794. },
  15795. enumerable: true,
  15796. configurable: true
  15797. });
  15798. /**
  15799. * Gets an attached behavior by name
  15800. * @param name defines the name of the behavior to look for
  15801. * @see http://doc.babylonjs.com/features/behaviour
  15802. * @returns null if behavior was not found else the requested behavior
  15803. */
  15804. Node.prototype.getBehaviorByName = function (name) {
  15805. for (var _i = 0, _a = this._behaviors; _i < _a.length; _i++) {
  15806. var behavior = _a[_i];
  15807. if (behavior.name === name) {
  15808. return behavior;
  15809. }
  15810. }
  15811. return null;
  15812. };
  15813. /**
  15814. * Returns the world matrix of the node
  15815. * @returns a matrix containing the node's world matrix
  15816. */
  15817. Node.prototype.getWorldMatrix = function () {
  15818. return BABYLON.Matrix.Identity();
  15819. };
  15820. // override it in derived class if you add new variables to the cache
  15821. // and call the parent class method
  15822. /** @ignore */
  15823. Node.prototype._initCache = function () {
  15824. this._cache = {};
  15825. this._cache.parent = undefined;
  15826. };
  15827. /** @ignore */
  15828. Node.prototype.updateCache = function (force) {
  15829. if (!force && this.isSynchronized())
  15830. return;
  15831. this._cache.parent = this.parent;
  15832. this._updateCache();
  15833. };
  15834. // override it in derived class if you add new variables to the cache
  15835. // and call the parent class method if !ignoreParentClass
  15836. /** @ignore */
  15837. Node.prototype._updateCache = function (ignoreParentClass) {
  15838. };
  15839. // override it in derived class if you add new variables to the cache
  15840. /** @ignore */
  15841. Node.prototype._isSynchronized = function () {
  15842. return true;
  15843. };
  15844. /** @ignore */
  15845. Node.prototype._markSyncedWithParent = function () {
  15846. if (this.parent) {
  15847. this._parentRenderId = this.parent._childRenderId;
  15848. }
  15849. };
  15850. /** @ignore */
  15851. Node.prototype.isSynchronizedWithParent = function () {
  15852. if (!this.parent) {
  15853. return true;
  15854. }
  15855. if (this._parentRenderId !== this.parent._childRenderId) {
  15856. return false;
  15857. }
  15858. return this.parent.isSynchronized();
  15859. };
  15860. /** @ignore */
  15861. Node.prototype.isSynchronized = function (updateCache) {
  15862. var check = this.hasNewParent();
  15863. check = check || !this.isSynchronizedWithParent();
  15864. check = check || !this._isSynchronized();
  15865. if (updateCache)
  15866. this.updateCache(true);
  15867. return !check;
  15868. };
  15869. /** @ignore */
  15870. Node.prototype.hasNewParent = function (update) {
  15871. if (this._cache.parent === this.parent)
  15872. return false;
  15873. if (update)
  15874. this._cache.parent = this.parent;
  15875. return true;
  15876. };
  15877. /**
  15878. * Is this node ready to be used/rendered
  15879. * @param completeCheck defines if a complete check (including materials and lights) has to be done (false by default)
  15880. * @return true if the node is ready
  15881. */
  15882. Node.prototype.isReady = function (completeCheck) {
  15883. if (completeCheck === void 0) { completeCheck = false; }
  15884. return this._isReady;
  15885. };
  15886. /**
  15887. * Is this node enabled?
  15888. * 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
  15889. * @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
  15890. * @return whether this node (and its parent) is enabled
  15891. */
  15892. Node.prototype.isEnabled = function (checkAncestors) {
  15893. if (checkAncestors === void 0) { checkAncestors = true; }
  15894. if (checkAncestors === false) {
  15895. return this._isEnabled;
  15896. }
  15897. if (this._isEnabled === false) {
  15898. return false;
  15899. }
  15900. if (this.parent !== undefined && this.parent !== null) {
  15901. return this.parent.isEnabled(checkAncestors);
  15902. }
  15903. return true;
  15904. };
  15905. /**
  15906. * Set the enabled state of this node
  15907. * @param value defines the new enabled state
  15908. */
  15909. Node.prototype.setEnabled = function (value) {
  15910. this._isEnabled = value;
  15911. };
  15912. /**
  15913. * Is this node a descendant of the given node?
  15914. * The function will iterate up the hierarchy until the ancestor was found or no more parents defined
  15915. * @param ancestor defines the parent node to inspect
  15916. * @returns a boolean indicating if this node is a descendant of the given node
  15917. */
  15918. Node.prototype.isDescendantOf = function (ancestor) {
  15919. if (this.parent) {
  15920. if (this.parent === ancestor) {
  15921. return true;
  15922. }
  15923. return this.parent.isDescendantOf(ancestor);
  15924. }
  15925. return false;
  15926. };
  15927. /** @ignore */
  15928. Node.prototype._getDescendants = function (results, directDescendantsOnly, predicate) {
  15929. if (directDescendantsOnly === void 0) { directDescendantsOnly = false; }
  15930. if (!this._children) {
  15931. return;
  15932. }
  15933. for (var index = 0; index < this._children.length; index++) {
  15934. var item = this._children[index];
  15935. if (!predicate || predicate(item)) {
  15936. results.push(item);
  15937. }
  15938. if (!directDescendantsOnly) {
  15939. item._getDescendants(results, false, predicate);
  15940. }
  15941. }
  15942. };
  15943. /**
  15944. * Will return all nodes that have this node as ascendant
  15945. * @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
  15946. * @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
  15947. * @return all children nodes of all types
  15948. */
  15949. Node.prototype.getDescendants = function (directDescendantsOnly, predicate) {
  15950. var results = new Array();
  15951. this._getDescendants(results, directDescendantsOnly, predicate);
  15952. return results;
  15953. };
  15954. /**
  15955. * Get all child-meshes of this node
  15956. * @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
  15957. * @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
  15958. * @returns an array of {BABYLON.AbstractMesh}
  15959. */
  15960. Node.prototype.getChildMeshes = function (directDescendantsOnly, predicate) {
  15961. var results = [];
  15962. this._getDescendants(results, directDescendantsOnly, function (node) {
  15963. return ((!predicate || predicate(node)) && (node instanceof BABYLON.AbstractMesh));
  15964. });
  15965. return results;
  15966. };
  15967. /**
  15968. * Get all child-transformNodes of this node
  15969. * @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
  15970. * @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
  15971. * @returns an array of {BABYLON.TransformNode}
  15972. */
  15973. Node.prototype.getChildTransformNodes = function (directDescendantsOnly, predicate) {
  15974. var results = [];
  15975. this._getDescendants(results, directDescendantsOnly, function (node) {
  15976. return ((!predicate || predicate(node)) && (node instanceof BABYLON.TransformNode));
  15977. });
  15978. return results;
  15979. };
  15980. /**
  15981. * Get all direct children of this node
  15982. * @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
  15983. * @returns an array of {BABYLON.Node}
  15984. */
  15985. Node.prototype.getChildren = function (predicate) {
  15986. return this.getDescendants(true, predicate);
  15987. };
  15988. /** @ignore */
  15989. Node.prototype._setReady = function (state) {
  15990. if (state === this._isReady) {
  15991. return;
  15992. }
  15993. if (!state) {
  15994. this._isReady = false;
  15995. return;
  15996. }
  15997. if (this.onReady) {
  15998. this.onReady(this);
  15999. }
  16000. this._isReady = true;
  16001. };
  16002. /**
  16003. * Get an animation by name
  16004. * @param name defines the name of the animation to look for
  16005. * @returns null if not found else the requested animation
  16006. */
  16007. Node.prototype.getAnimationByName = function (name) {
  16008. for (var i = 0; i < this.animations.length; i++) {
  16009. var animation = this.animations[i];
  16010. if (animation.name === name) {
  16011. return animation;
  16012. }
  16013. }
  16014. return null;
  16015. };
  16016. /**
  16017. * Creates an animation range for this node
  16018. * @param name defines the name of the range
  16019. * @param from defines the starting key
  16020. * @param to defines the end key
  16021. */
  16022. Node.prototype.createAnimationRange = function (name, from, to) {
  16023. // check name not already in use
  16024. if (!this._ranges[name]) {
  16025. this._ranges[name] = new BABYLON.AnimationRange(name, from, to);
  16026. for (var i = 0, nAnimations = this.animations.length; i < nAnimations; i++) {
  16027. if (this.animations[i]) {
  16028. this.animations[i].createRange(name, from, to);
  16029. }
  16030. }
  16031. }
  16032. };
  16033. /**
  16034. * Delete a specific animation range
  16035. * @param name defines the name of the range to delete
  16036. * @param deleteFrames defines if animation frames from the range must be deleted as well
  16037. */
  16038. Node.prototype.deleteAnimationRange = function (name, deleteFrames) {
  16039. if (deleteFrames === void 0) { deleteFrames = true; }
  16040. for (var i = 0, nAnimations = this.animations.length; i < nAnimations; i++) {
  16041. if (this.animations[i]) {
  16042. this.animations[i].deleteRange(name, deleteFrames);
  16043. }
  16044. }
  16045. this._ranges[name] = null; // said much faster than 'delete this._range[name]'
  16046. };
  16047. /**
  16048. * Get an animation range by name
  16049. * @param name defines the name of the animation range to look for
  16050. * @returns null if not found else the requested animation range
  16051. */
  16052. Node.prototype.getAnimationRange = function (name) {
  16053. return this._ranges[name];
  16054. };
  16055. /**
  16056. * Will start the animation sequence
  16057. * @param name defines the range frames for animation sequence
  16058. * @param loop defines if the animation should loop (false by default)
  16059. * @param speedRatio defines the speed factor in which to run the animation (1 by default)
  16060. * @param onAnimationEnd defines a function to be executed when the animation ended (undefined by default)
  16061. * @returns the object created for this animation. If range does not exist, it will return null
  16062. */
  16063. Node.prototype.beginAnimation = function (name, loop, speedRatio, onAnimationEnd) {
  16064. var range = this.getAnimationRange(name);
  16065. if (!range) {
  16066. return null;
  16067. }
  16068. return this._scene.beginAnimation(this, range.from, range.to, loop, speedRatio, onAnimationEnd);
  16069. };
  16070. /**
  16071. * Serialize animation ranges into a JSON compatible object
  16072. * @returns serialization object
  16073. */
  16074. Node.prototype.serializeAnimationRanges = function () {
  16075. var serializationRanges = [];
  16076. for (var name in this._ranges) {
  16077. var localRange = this._ranges[name];
  16078. if (!localRange) {
  16079. continue;
  16080. }
  16081. var range = {};
  16082. range.name = name;
  16083. range.from = localRange.from;
  16084. range.to = localRange.to;
  16085. serializationRanges.push(range);
  16086. }
  16087. return serializationRanges;
  16088. };
  16089. /**
  16090. * Computes the world matrix of the node
  16091. * @param force defines if the cache version should be invalidated forcing the world matrix to be created from scratch
  16092. * @returns the world matrix
  16093. */
  16094. Node.prototype.computeWorldMatrix = function (force) {
  16095. return BABYLON.Matrix.Identity();
  16096. };
  16097. /**
  16098. * Releases resources associated with this node.
  16099. * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default)
  16100. * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default)
  16101. */
  16102. Node.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  16103. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  16104. if (!doNotRecurse) {
  16105. var nodes = this.getDescendants(true);
  16106. for (var _i = 0, nodes_1 = nodes; _i < nodes_1.length; _i++) {
  16107. var node = nodes_1[_i];
  16108. node.dispose(doNotRecurse, disposeMaterialAndTextures);
  16109. }
  16110. }
  16111. else {
  16112. var transformNodes = this.getChildTransformNodes(true);
  16113. for (var _a = 0, transformNodes_1 = transformNodes; _a < transformNodes_1.length; _a++) {
  16114. var transformNode = transformNodes_1[_a];
  16115. transformNode.parent = null;
  16116. transformNode.computeWorldMatrix(true);
  16117. }
  16118. }
  16119. this.parent = null;
  16120. // Callback
  16121. this.onDisposeObservable.notifyObservers(this);
  16122. this.onDisposeObservable.clear();
  16123. // Behaviors
  16124. for (var _b = 0, _c = this._behaviors; _b < _c.length; _b++) {
  16125. var behavior = _c[_b];
  16126. behavior.detach();
  16127. }
  16128. this._behaviors = [];
  16129. this._isDisposed = true;
  16130. };
  16131. /**
  16132. * Parse animation range data from a serialization object and store them into a given node
  16133. * @param node defines where to store the animation ranges
  16134. * @param parsedNode defines the serialization object to read data from
  16135. * @param scene defines the hosting scene
  16136. */
  16137. Node.ParseAnimationRanges = function (node, parsedNode, scene) {
  16138. if (parsedNode.ranges) {
  16139. for (var index = 0; index < parsedNode.ranges.length; index++) {
  16140. var data = parsedNode.ranges[index];
  16141. node.createAnimationRange(data.name, data.from, data.to);
  16142. }
  16143. }
  16144. };
  16145. __decorate([
  16146. BABYLON.serialize()
  16147. ], Node.prototype, "name", void 0);
  16148. __decorate([
  16149. BABYLON.serialize()
  16150. ], Node.prototype, "id", void 0);
  16151. __decorate([
  16152. BABYLON.serialize()
  16153. ], Node.prototype, "uniqueId", void 0);
  16154. __decorate([
  16155. BABYLON.serialize()
  16156. ], Node.prototype, "state", void 0);
  16157. __decorate([
  16158. BABYLON.serialize()
  16159. ], Node.prototype, "metadata", void 0);
  16160. return Node;
  16161. }());
  16162. BABYLON.Node = Node;
  16163. })(BABYLON || (BABYLON = {}));
  16164. //# sourceMappingURL=babylon.node.js.map
  16165. "use strict";
  16166. var BABYLON;
  16167. (function (BABYLON) {
  16168. var BoundingSphere = /** @class */ (function () {
  16169. function BoundingSphere(minimum, maximum) {
  16170. this.minimum = minimum;
  16171. this.maximum = maximum;
  16172. this._tempRadiusVector = BABYLON.Vector3.Zero();
  16173. var distance = BABYLON.Vector3.Distance(minimum, maximum);
  16174. this.center = BABYLON.Vector3.Lerp(minimum, maximum, 0.5);
  16175. this.radius = distance * 0.5;
  16176. this.centerWorld = BABYLON.Vector3.Zero();
  16177. this._update(BABYLON.Matrix.Identity());
  16178. }
  16179. // Methods
  16180. BoundingSphere.prototype._update = function (world) {
  16181. BABYLON.Vector3.TransformCoordinatesToRef(this.center, world, this.centerWorld);
  16182. BABYLON.Vector3.TransformNormalFromFloatsToRef(1.0, 1.0, 1.0, world, this._tempRadiusVector);
  16183. this.radiusWorld = Math.max(Math.abs(this._tempRadiusVector.x), Math.abs(this._tempRadiusVector.y), Math.abs(this._tempRadiusVector.z)) * this.radius;
  16184. };
  16185. BoundingSphere.prototype.isInFrustum = function (frustumPlanes) {
  16186. for (var i = 0; i < 6; i++) {
  16187. if (frustumPlanes[i].dotCoordinate(this.centerWorld) <= -this.radiusWorld)
  16188. return false;
  16189. }
  16190. return true;
  16191. };
  16192. BoundingSphere.prototype.intersectsPoint = function (point) {
  16193. var x = this.centerWorld.x - point.x;
  16194. var y = this.centerWorld.y - point.y;
  16195. var z = this.centerWorld.z - point.z;
  16196. var distance = Math.sqrt((x * x) + (y * y) + (z * z));
  16197. if (Math.abs(this.radiusWorld - distance) < BABYLON.Epsilon)
  16198. return false;
  16199. return true;
  16200. };
  16201. // Statics
  16202. BoundingSphere.Intersects = function (sphere0, sphere1) {
  16203. var x = sphere0.centerWorld.x - sphere1.centerWorld.x;
  16204. var y = sphere0.centerWorld.y - sphere1.centerWorld.y;
  16205. var z = sphere0.centerWorld.z - sphere1.centerWorld.z;
  16206. var distance = Math.sqrt((x * x) + (y * y) + (z * z));
  16207. if (sphere0.radiusWorld + sphere1.radiusWorld < distance)
  16208. return false;
  16209. return true;
  16210. };
  16211. return BoundingSphere;
  16212. }());
  16213. BABYLON.BoundingSphere = BoundingSphere;
  16214. })(BABYLON || (BABYLON = {}));
  16215. //# sourceMappingURL=babylon.boundingSphere.js.map
  16216. "use strict";
  16217. var BABYLON;
  16218. (function (BABYLON) {
  16219. var BoundingBox = /** @class */ (function () {
  16220. function BoundingBox(minimum, maximum) {
  16221. this.minimum = minimum;
  16222. this.maximum = maximum;
  16223. this.vectors = new Array();
  16224. this.vectorsWorld = new Array();
  16225. // Bounding vectors
  16226. this.vectors.push(this.minimum.clone());
  16227. this.vectors.push(this.maximum.clone());
  16228. this.vectors.push(this.minimum.clone());
  16229. this.vectors[2].x = this.maximum.x;
  16230. this.vectors.push(this.minimum.clone());
  16231. this.vectors[3].y = this.maximum.y;
  16232. this.vectors.push(this.minimum.clone());
  16233. this.vectors[4].z = this.maximum.z;
  16234. this.vectors.push(this.maximum.clone());
  16235. this.vectors[5].z = this.minimum.z;
  16236. this.vectors.push(this.maximum.clone());
  16237. this.vectors[6].x = this.minimum.x;
  16238. this.vectors.push(this.maximum.clone());
  16239. this.vectors[7].y = this.minimum.y;
  16240. // OBB
  16241. this.center = this.maximum.add(this.minimum).scale(0.5);
  16242. this.extendSize = this.maximum.subtract(this.minimum).scale(0.5);
  16243. this.directions = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  16244. // World
  16245. for (var index = 0; index < this.vectors.length; index++) {
  16246. this.vectorsWorld[index] = BABYLON.Vector3.Zero();
  16247. }
  16248. this.minimumWorld = BABYLON.Vector3.Zero();
  16249. this.maximumWorld = BABYLON.Vector3.Zero();
  16250. this.centerWorld = BABYLON.Vector3.Zero();
  16251. this.extendSizeWorld = BABYLON.Vector3.Zero();
  16252. this._update(BABYLON.Matrix.Identity());
  16253. }
  16254. // Methods
  16255. BoundingBox.prototype.getWorldMatrix = function () {
  16256. return this._worldMatrix;
  16257. };
  16258. BoundingBox.prototype.setWorldMatrix = function (matrix) {
  16259. this._worldMatrix.copyFrom(matrix);
  16260. return this;
  16261. };
  16262. BoundingBox.prototype._update = function (world) {
  16263. BABYLON.Vector3.FromFloatsToRef(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, this.minimumWorld);
  16264. BABYLON.Vector3.FromFloatsToRef(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE, this.maximumWorld);
  16265. for (var index = 0; index < this.vectors.length; index++) {
  16266. var v = this.vectorsWorld[index];
  16267. BABYLON.Vector3.TransformCoordinatesToRef(this.vectors[index], world, v);
  16268. if (v.x < this.minimumWorld.x)
  16269. this.minimumWorld.x = v.x;
  16270. if (v.y < this.minimumWorld.y)
  16271. this.minimumWorld.y = v.y;
  16272. if (v.z < this.minimumWorld.z)
  16273. this.minimumWorld.z = v.z;
  16274. if (v.x > this.maximumWorld.x)
  16275. this.maximumWorld.x = v.x;
  16276. if (v.y > this.maximumWorld.y)
  16277. this.maximumWorld.y = v.y;
  16278. if (v.z > this.maximumWorld.z)
  16279. this.maximumWorld.z = v.z;
  16280. }
  16281. // Extend
  16282. this.maximumWorld.subtractToRef(this.minimumWorld, this.extendSizeWorld);
  16283. this.extendSizeWorld.scaleInPlace(0.5);
  16284. // OBB
  16285. this.maximumWorld.addToRef(this.minimumWorld, this.centerWorld);
  16286. this.centerWorld.scaleInPlace(0.5);
  16287. BABYLON.Vector3.FromFloatArrayToRef(world.m, 0, this.directions[0]);
  16288. BABYLON.Vector3.FromFloatArrayToRef(world.m, 4, this.directions[1]);
  16289. BABYLON.Vector3.FromFloatArrayToRef(world.m, 8, this.directions[2]);
  16290. this._worldMatrix = world;
  16291. };
  16292. BoundingBox.prototype.isInFrustum = function (frustumPlanes) {
  16293. return BoundingBox.IsInFrustum(this.vectorsWorld, frustumPlanes);
  16294. };
  16295. BoundingBox.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  16296. return BoundingBox.IsCompletelyInFrustum(this.vectorsWorld, frustumPlanes);
  16297. };
  16298. BoundingBox.prototype.intersectsPoint = function (point) {
  16299. var delta = -BABYLON.Epsilon;
  16300. if (this.maximumWorld.x - point.x < delta || delta > point.x - this.minimumWorld.x)
  16301. return false;
  16302. if (this.maximumWorld.y - point.y < delta || delta > point.y - this.minimumWorld.y)
  16303. return false;
  16304. if (this.maximumWorld.z - point.z < delta || delta > point.z - this.minimumWorld.z)
  16305. return false;
  16306. return true;
  16307. };
  16308. BoundingBox.prototype.intersectsSphere = function (sphere) {
  16309. return BoundingBox.IntersectsSphere(this.minimumWorld, this.maximumWorld, sphere.centerWorld, sphere.radiusWorld);
  16310. };
  16311. BoundingBox.prototype.intersectsMinMax = function (min, max) {
  16312. if (this.maximumWorld.x < min.x || this.minimumWorld.x > max.x)
  16313. return false;
  16314. if (this.maximumWorld.y < min.y || this.minimumWorld.y > max.y)
  16315. return false;
  16316. if (this.maximumWorld.z < min.z || this.minimumWorld.z > max.z)
  16317. return false;
  16318. return true;
  16319. };
  16320. // Statics
  16321. BoundingBox.Intersects = function (box0, box1) {
  16322. if (box0.maximumWorld.x < box1.minimumWorld.x || box0.minimumWorld.x > box1.maximumWorld.x)
  16323. return false;
  16324. if (box0.maximumWorld.y < box1.minimumWorld.y || box0.minimumWorld.y > box1.maximumWorld.y)
  16325. return false;
  16326. if (box0.maximumWorld.z < box1.minimumWorld.z || box0.minimumWorld.z > box1.maximumWorld.z)
  16327. return false;
  16328. return true;
  16329. };
  16330. BoundingBox.IntersectsSphere = function (minPoint, maxPoint, sphereCenter, sphereRadius) {
  16331. var vector = BABYLON.Vector3.Clamp(sphereCenter, minPoint, maxPoint);
  16332. var num = BABYLON.Vector3.DistanceSquared(sphereCenter, vector);
  16333. return (num <= (sphereRadius * sphereRadius));
  16334. };
  16335. BoundingBox.IsCompletelyInFrustum = function (boundingVectors, frustumPlanes) {
  16336. for (var p = 0; p < 6; p++) {
  16337. for (var i = 0; i < 8; i++) {
  16338. if (frustumPlanes[p].dotCoordinate(boundingVectors[i]) < 0) {
  16339. return false;
  16340. }
  16341. }
  16342. }
  16343. return true;
  16344. };
  16345. BoundingBox.IsInFrustum = function (boundingVectors, frustumPlanes) {
  16346. for (var p = 0; p < 6; p++) {
  16347. var inCount = 8;
  16348. for (var i = 0; i < 8; i++) {
  16349. if (frustumPlanes[p].dotCoordinate(boundingVectors[i]) < 0) {
  16350. --inCount;
  16351. }
  16352. else {
  16353. break;
  16354. }
  16355. }
  16356. if (inCount === 0)
  16357. return false;
  16358. }
  16359. return true;
  16360. };
  16361. return BoundingBox;
  16362. }());
  16363. BABYLON.BoundingBox = BoundingBox;
  16364. })(BABYLON || (BABYLON = {}));
  16365. //# sourceMappingURL=babylon.boundingBox.js.map
  16366. "use strict";
  16367. var BABYLON;
  16368. (function (BABYLON) {
  16369. var computeBoxExtents = function (axis, box) {
  16370. var p = BABYLON.Vector3.Dot(box.centerWorld, axis);
  16371. var r0 = Math.abs(BABYLON.Vector3.Dot(box.directions[0], axis)) * box.extendSize.x;
  16372. var r1 = Math.abs(BABYLON.Vector3.Dot(box.directions[1], axis)) * box.extendSize.y;
  16373. var r2 = Math.abs(BABYLON.Vector3.Dot(box.directions[2], axis)) * box.extendSize.z;
  16374. var r = r0 + r1 + r2;
  16375. return {
  16376. min: p - r,
  16377. max: p + r
  16378. };
  16379. };
  16380. var extentsOverlap = function (min0, max0, min1, max1) { return !(min0 > max1 || min1 > max0); };
  16381. var axisOverlap = function (axis, box0, box1) {
  16382. var result0 = computeBoxExtents(axis, box0);
  16383. var result1 = computeBoxExtents(axis, box1);
  16384. return extentsOverlap(result0.min, result0.max, result1.min, result1.max);
  16385. };
  16386. var BoundingInfo = /** @class */ (function () {
  16387. function BoundingInfo(minimum, maximum) {
  16388. this.minimum = minimum;
  16389. this.maximum = maximum;
  16390. this._isLocked = false;
  16391. this.boundingBox = new BABYLON.BoundingBox(minimum, maximum);
  16392. this.boundingSphere = new BABYLON.BoundingSphere(minimum, maximum);
  16393. }
  16394. Object.defineProperty(BoundingInfo.prototype, "isLocked", {
  16395. get: function () {
  16396. return this._isLocked;
  16397. },
  16398. set: function (value) {
  16399. this._isLocked = value;
  16400. },
  16401. enumerable: true,
  16402. configurable: true
  16403. });
  16404. // Methods
  16405. BoundingInfo.prototype.update = function (world) {
  16406. if (this._isLocked) {
  16407. return;
  16408. }
  16409. this.boundingBox._update(world);
  16410. this.boundingSphere._update(world);
  16411. };
  16412. /**
  16413. * Recreate the bounding info to be centered around a specific point given a specific extend.
  16414. * @param center New center of the bounding info
  16415. * @param extend New extend of the bounding info
  16416. */
  16417. BoundingInfo.prototype.centerOn = function (center, extend) {
  16418. this.minimum = center.subtract(extend);
  16419. this.maximum = center.add(extend);
  16420. this.boundingBox = new BABYLON.BoundingBox(this.minimum, this.maximum);
  16421. this.boundingSphere = new BABYLON.BoundingSphere(this.minimum, this.maximum);
  16422. return this;
  16423. };
  16424. BoundingInfo.prototype.isInFrustum = function (frustumPlanes) {
  16425. if (!this.boundingSphere.isInFrustum(frustumPlanes))
  16426. return false;
  16427. return this.boundingBox.isInFrustum(frustumPlanes);
  16428. };
  16429. Object.defineProperty(BoundingInfo.prototype, "diagonalLength", {
  16430. /**
  16431. * Gets the world distance between the min and max points of the bounding box
  16432. */
  16433. get: function () {
  16434. var boundingBox = this.boundingBox;
  16435. var size = boundingBox.maximumWorld.subtract(boundingBox.minimumWorld);
  16436. return size.length();
  16437. },
  16438. enumerable: true,
  16439. configurable: true
  16440. });
  16441. BoundingInfo.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  16442. return this.boundingBox.isCompletelyInFrustum(frustumPlanes);
  16443. };
  16444. BoundingInfo.prototype._checkCollision = function (collider) {
  16445. return collider._canDoCollision(this.boundingSphere.centerWorld, this.boundingSphere.radiusWorld, this.boundingBox.minimumWorld, this.boundingBox.maximumWorld);
  16446. };
  16447. BoundingInfo.prototype.intersectsPoint = function (point) {
  16448. if (!this.boundingSphere.centerWorld) {
  16449. return false;
  16450. }
  16451. if (!this.boundingSphere.intersectsPoint(point)) {
  16452. return false;
  16453. }
  16454. if (!this.boundingBox.intersectsPoint(point)) {
  16455. return false;
  16456. }
  16457. return true;
  16458. };
  16459. BoundingInfo.prototype.intersects = function (boundingInfo, precise) {
  16460. if (!this.boundingSphere.centerWorld || !boundingInfo.boundingSphere.centerWorld) {
  16461. return false;
  16462. }
  16463. if (!BABYLON.BoundingSphere.Intersects(this.boundingSphere, boundingInfo.boundingSphere)) {
  16464. return false;
  16465. }
  16466. if (!BABYLON.BoundingBox.Intersects(this.boundingBox, boundingInfo.boundingBox)) {
  16467. return false;
  16468. }
  16469. if (!precise) {
  16470. return true;
  16471. }
  16472. var box0 = this.boundingBox;
  16473. var box1 = boundingInfo.boundingBox;
  16474. if (!axisOverlap(box0.directions[0], box0, box1))
  16475. return false;
  16476. if (!axisOverlap(box0.directions[1], box0, box1))
  16477. return false;
  16478. if (!axisOverlap(box0.directions[2], box0, box1))
  16479. return false;
  16480. if (!axisOverlap(box1.directions[0], box0, box1))
  16481. return false;
  16482. if (!axisOverlap(box1.directions[1], box0, box1))
  16483. return false;
  16484. if (!axisOverlap(box1.directions[2], box0, box1))
  16485. return false;
  16486. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[0]), box0, box1))
  16487. return false;
  16488. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[1]), box0, box1))
  16489. return false;
  16490. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[2]), box0, box1))
  16491. return false;
  16492. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[0]), box0, box1))
  16493. return false;
  16494. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[1]), box0, box1))
  16495. return false;
  16496. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[2]), box0, box1))
  16497. return false;
  16498. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[0]), box0, box1))
  16499. return false;
  16500. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[1]), box0, box1))
  16501. return false;
  16502. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[2]), box0, box1))
  16503. return false;
  16504. return true;
  16505. };
  16506. return BoundingInfo;
  16507. }());
  16508. BABYLON.BoundingInfo = BoundingInfo;
  16509. })(BABYLON || (BABYLON = {}));
  16510. //# sourceMappingURL=babylon.boundingInfo.js.map
  16511. "use strict";
  16512. var BABYLON;
  16513. (function (BABYLON) {
  16514. var TransformNode = /** @class */ (function (_super) {
  16515. __extends(TransformNode, _super);
  16516. function TransformNode(name, scene, isPure) {
  16517. if (scene === void 0) { scene = null; }
  16518. if (isPure === void 0) { isPure = true; }
  16519. var _this = _super.call(this, name, scene) || this;
  16520. _this._forward = new BABYLON.Vector3(0, 0, 1);
  16521. _this._forwardInverted = new BABYLON.Vector3(0, 0, -1);
  16522. _this._up = new BABYLON.Vector3(0, 1, 0);
  16523. _this._right = new BABYLON.Vector3(1, 0, 0);
  16524. _this._rightInverted = new BABYLON.Vector3(-1, 0, 0);
  16525. // Properties
  16526. _this._rotation = BABYLON.Vector3.Zero();
  16527. _this._scaling = BABYLON.Vector3.One();
  16528. _this._isDirty = false;
  16529. _this.billboardMode = TransformNode.BILLBOARDMODE_NONE;
  16530. _this.scalingDeterminant = 1;
  16531. _this.infiniteDistance = false;
  16532. _this.position = BABYLON.Vector3.Zero();
  16533. _this._localWorld = BABYLON.Matrix.Zero();
  16534. _this._worldMatrix = BABYLON.Matrix.Zero();
  16535. _this._worldMatrixDeterminant = 0;
  16536. _this._absolutePosition = BABYLON.Vector3.Zero();
  16537. _this._pivotMatrix = BABYLON.Matrix.Identity();
  16538. _this._postMultiplyPivotMatrix = false;
  16539. _this._isWorldMatrixFrozen = false;
  16540. /**
  16541. * An event triggered after the world matrix is updated
  16542. */
  16543. _this.onAfterWorldMatrixUpdateObservable = new BABYLON.Observable();
  16544. _this._nonUniformScaling = false;
  16545. if (isPure) {
  16546. _this.getScene().addTransformNode(_this);
  16547. }
  16548. return _this;
  16549. }
  16550. /**
  16551. * Gets a string idenfifying the name of the class
  16552. * @returns "TransformNode" string
  16553. */
  16554. TransformNode.prototype.getClassName = function () {
  16555. return "TransformNode";
  16556. };
  16557. Object.defineProperty(TransformNode.prototype, "rotation", {
  16558. /**
  16559. * Rotation property : a Vector3 depicting the rotation value in radians around each local axis X, Y, Z.
  16560. * If rotation quaternion is set, this Vector3 will (almost always) be the Zero vector!
  16561. * Default : (0.0, 0.0, 0.0)
  16562. */
  16563. get: function () {
  16564. return this._rotation;
  16565. },
  16566. set: function (newRotation) {
  16567. this._rotation = newRotation;
  16568. },
  16569. enumerable: true,
  16570. configurable: true
  16571. });
  16572. Object.defineProperty(TransformNode.prototype, "scaling", {
  16573. /**
  16574. * Scaling property : a Vector3 depicting the mesh scaling along each local axis X, Y, Z.
  16575. * Default : (1.0, 1.0, 1.0)
  16576. */
  16577. get: function () {
  16578. return this._scaling;
  16579. },
  16580. /**
  16581. * Scaling property : a Vector3 depicting the mesh scaling along each local axis X, Y, Z.
  16582. * Default : (1.0, 1.0, 1.0)
  16583. */
  16584. set: function (newScaling) {
  16585. this._scaling = newScaling;
  16586. },
  16587. enumerable: true,
  16588. configurable: true
  16589. });
  16590. Object.defineProperty(TransformNode.prototype, "rotationQuaternion", {
  16591. /**
  16592. * Rotation Quaternion property : this a Quaternion object depicting the mesh rotation by using a unit quaternion.
  16593. * It's null by default.
  16594. * 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)
  16595. */
  16596. get: function () {
  16597. return this._rotationQuaternion;
  16598. },
  16599. set: function (quaternion) {
  16600. this._rotationQuaternion = quaternion;
  16601. //reset the rotation vector.
  16602. if (quaternion && this.rotation.length()) {
  16603. this.rotation.copyFromFloats(0.0, 0.0, 0.0);
  16604. }
  16605. },
  16606. enumerable: true,
  16607. configurable: true
  16608. });
  16609. Object.defineProperty(TransformNode.prototype, "forward", {
  16610. /**
  16611. * The forward direction of that transform in world space.
  16612. */
  16613. get: function () {
  16614. return BABYLON.Vector3.Normalize(BABYLON.Vector3.TransformNormal(this.getScene().useRightHandedSystem ? this._forwardInverted : this._forward, this.getWorldMatrix()));
  16615. },
  16616. enumerable: true,
  16617. configurable: true
  16618. });
  16619. Object.defineProperty(TransformNode.prototype, "up", {
  16620. /**
  16621. * The up direction of that transform in world space.
  16622. */
  16623. get: function () {
  16624. return BABYLON.Vector3.Normalize(BABYLON.Vector3.TransformNormal(this._up, this.getWorldMatrix()));
  16625. },
  16626. enumerable: true,
  16627. configurable: true
  16628. });
  16629. Object.defineProperty(TransformNode.prototype, "right", {
  16630. /**
  16631. * The right direction of that transform in world space.
  16632. */
  16633. get: function () {
  16634. return BABYLON.Vector3.Normalize(BABYLON.Vector3.TransformNormal(this.getScene().useRightHandedSystem ? this._rightInverted : this._right, this.getWorldMatrix()));
  16635. },
  16636. enumerable: true,
  16637. configurable: true
  16638. });
  16639. /**
  16640. * Returns the latest update of the World matrix
  16641. * Returns a Matrix.
  16642. */
  16643. TransformNode.prototype.getWorldMatrix = function () {
  16644. if (this._currentRenderId !== this.getScene().getRenderId()) {
  16645. this.computeWorldMatrix();
  16646. }
  16647. return this._worldMatrix;
  16648. };
  16649. /**
  16650. * Returns the latest update of the World matrix determinant.
  16651. */
  16652. TransformNode.prototype._getWorldMatrixDeterminant = function () {
  16653. return this._worldMatrixDeterminant;
  16654. };
  16655. Object.defineProperty(TransformNode.prototype, "worldMatrixFromCache", {
  16656. /**
  16657. * Returns directly the latest state of the mesh World matrix.
  16658. * A Matrix is returned.
  16659. */
  16660. get: function () {
  16661. return this._worldMatrix;
  16662. },
  16663. enumerable: true,
  16664. configurable: true
  16665. });
  16666. /**
  16667. * Copies the paramater passed Matrix into the mesh Pose matrix.
  16668. * Returns the TransformNode.
  16669. */
  16670. TransformNode.prototype.updatePoseMatrix = function (matrix) {
  16671. this._poseMatrix.copyFrom(matrix);
  16672. return this;
  16673. };
  16674. /**
  16675. * Returns the mesh Pose matrix.
  16676. * Returned object : Matrix
  16677. */
  16678. TransformNode.prototype.getPoseMatrix = function () {
  16679. return this._poseMatrix;
  16680. };
  16681. TransformNode.prototype._isSynchronized = function () {
  16682. if (this._isDirty) {
  16683. return false;
  16684. }
  16685. if (this.billboardMode !== this._cache.billboardMode || this.billboardMode !== TransformNode.BILLBOARDMODE_NONE)
  16686. return false;
  16687. if (this._cache.pivotMatrixUpdated) {
  16688. return false;
  16689. }
  16690. if (this.infiniteDistance) {
  16691. return false;
  16692. }
  16693. if (!this._cache.position.equals(this.position))
  16694. return false;
  16695. if (this.rotationQuaternion) {
  16696. if (!this._cache.rotationQuaternion.equals(this.rotationQuaternion))
  16697. return false;
  16698. }
  16699. if (!this._cache.rotation.equals(this.rotation))
  16700. return false;
  16701. if (!this._cache.scaling.equals(this.scaling))
  16702. return false;
  16703. return true;
  16704. };
  16705. TransformNode.prototype._initCache = function () {
  16706. _super.prototype._initCache.call(this);
  16707. this._cache.localMatrixUpdated = false;
  16708. this._cache.position = BABYLON.Vector3.Zero();
  16709. this._cache.scaling = BABYLON.Vector3.Zero();
  16710. this._cache.rotation = BABYLON.Vector3.Zero();
  16711. this._cache.rotationQuaternion = new BABYLON.Quaternion(0, 0, 0, 0);
  16712. this._cache.billboardMode = -1;
  16713. };
  16714. TransformNode.prototype.markAsDirty = function (property) {
  16715. if (property === "rotation") {
  16716. this.rotationQuaternion = null;
  16717. }
  16718. this._currentRenderId = Number.MAX_VALUE;
  16719. this._isDirty = true;
  16720. return this;
  16721. };
  16722. Object.defineProperty(TransformNode.prototype, "absolutePosition", {
  16723. /**
  16724. * Returns the current mesh absolute position.
  16725. * Retuns a Vector3.
  16726. */
  16727. get: function () {
  16728. return this._absolutePosition;
  16729. },
  16730. enumerable: true,
  16731. configurable: true
  16732. });
  16733. /**
  16734. * Sets a new matrix to apply before all other transformation
  16735. * @param matrix defines the transform matrix
  16736. * @returns the current TransformNode
  16737. */
  16738. TransformNode.prototype.setPreTransformMatrix = function (matrix) {
  16739. return this.setPivotMatrix(matrix, false);
  16740. };
  16741. /**
  16742. * Sets a new pivot matrix to the current node
  16743. * @param matrix defines the new pivot matrix to use
  16744. * @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
  16745. * @returns the current TransformNode
  16746. */
  16747. TransformNode.prototype.setPivotMatrix = function (matrix, postMultiplyPivotMatrix) {
  16748. if (postMultiplyPivotMatrix === void 0) { postMultiplyPivotMatrix = true; }
  16749. this._pivotMatrix = matrix.clone();
  16750. this._cache.pivotMatrixUpdated = true;
  16751. this._postMultiplyPivotMatrix = postMultiplyPivotMatrix;
  16752. if (this._postMultiplyPivotMatrix) {
  16753. if (!this._pivotMatrixInverse) {
  16754. this._pivotMatrixInverse = BABYLON.Matrix.Invert(this._pivotMatrix);
  16755. }
  16756. else {
  16757. this._pivotMatrix.invertToRef(this._pivotMatrixInverse);
  16758. }
  16759. }
  16760. return this;
  16761. };
  16762. /**
  16763. * Returns the mesh pivot matrix.
  16764. * Default : Identity.
  16765. * A Matrix is returned.
  16766. */
  16767. TransformNode.prototype.getPivotMatrix = function () {
  16768. return this._pivotMatrix;
  16769. };
  16770. /**
  16771. * Prevents the World matrix to be computed any longer.
  16772. * Returns the TransformNode.
  16773. */
  16774. TransformNode.prototype.freezeWorldMatrix = function () {
  16775. this._isWorldMatrixFrozen = false; // no guarantee world is not already frozen, switch off temporarily
  16776. this.computeWorldMatrix(true);
  16777. this._isWorldMatrixFrozen = true;
  16778. return this;
  16779. };
  16780. /**
  16781. * Allows back the World matrix computation.
  16782. * Returns the TransformNode.
  16783. */
  16784. TransformNode.prototype.unfreezeWorldMatrix = function () {
  16785. this._isWorldMatrixFrozen = false;
  16786. this.computeWorldMatrix(true);
  16787. return this;
  16788. };
  16789. Object.defineProperty(TransformNode.prototype, "isWorldMatrixFrozen", {
  16790. /**
  16791. * True if the World matrix has been frozen.
  16792. * Returns a boolean.
  16793. */
  16794. get: function () {
  16795. return this._isWorldMatrixFrozen;
  16796. },
  16797. enumerable: true,
  16798. configurable: true
  16799. });
  16800. /**
  16801. * Retuns the mesh absolute position in the World.
  16802. * Returns a Vector3.
  16803. */
  16804. TransformNode.prototype.getAbsolutePosition = function () {
  16805. this.computeWorldMatrix();
  16806. return this._absolutePosition;
  16807. };
  16808. /**
  16809. * Sets the mesh absolute position in the World from a Vector3 or an Array(3).
  16810. * Returns the TransformNode.
  16811. */
  16812. TransformNode.prototype.setAbsolutePosition = function (absolutePosition) {
  16813. if (!absolutePosition) {
  16814. return this;
  16815. }
  16816. var absolutePositionX;
  16817. var absolutePositionY;
  16818. var absolutePositionZ;
  16819. if (absolutePosition.x === undefined) {
  16820. if (arguments.length < 3) {
  16821. return this;
  16822. }
  16823. absolutePositionX = arguments[0];
  16824. absolutePositionY = arguments[1];
  16825. absolutePositionZ = arguments[2];
  16826. }
  16827. else {
  16828. absolutePositionX = absolutePosition.x;
  16829. absolutePositionY = absolutePosition.y;
  16830. absolutePositionZ = absolutePosition.z;
  16831. }
  16832. if (this.parent) {
  16833. var invertParentWorldMatrix = this.parent.getWorldMatrix().clone();
  16834. invertParentWorldMatrix.invert();
  16835. var worldPosition = new BABYLON.Vector3(absolutePositionX, absolutePositionY, absolutePositionZ);
  16836. this.position = BABYLON.Vector3.TransformCoordinates(worldPosition, invertParentWorldMatrix);
  16837. }
  16838. else {
  16839. this.position.x = absolutePositionX;
  16840. this.position.y = absolutePositionY;
  16841. this.position.z = absolutePositionZ;
  16842. }
  16843. return this;
  16844. };
  16845. /**
  16846. * Sets the mesh position in its local space.
  16847. * Returns the TransformNode.
  16848. */
  16849. TransformNode.prototype.setPositionWithLocalVector = function (vector3) {
  16850. this.computeWorldMatrix();
  16851. this.position = BABYLON.Vector3.TransformNormal(vector3, this._localWorld);
  16852. return this;
  16853. };
  16854. /**
  16855. * Returns the mesh position in the local space from the current World matrix values.
  16856. * Returns a new Vector3.
  16857. */
  16858. TransformNode.prototype.getPositionExpressedInLocalSpace = function () {
  16859. this.computeWorldMatrix();
  16860. var invLocalWorldMatrix = this._localWorld.clone();
  16861. invLocalWorldMatrix.invert();
  16862. return BABYLON.Vector3.TransformNormal(this.position, invLocalWorldMatrix);
  16863. };
  16864. /**
  16865. * Translates the mesh along the passed Vector3 in its local space.
  16866. * Returns the TransformNode.
  16867. */
  16868. TransformNode.prototype.locallyTranslate = function (vector3) {
  16869. this.computeWorldMatrix(true);
  16870. this.position = BABYLON.Vector3.TransformCoordinates(vector3, this._localWorld);
  16871. return this;
  16872. };
  16873. /**
  16874. * Orients a mesh towards a target point. Mesh must be drawn facing user.
  16875. * @param targetPoint the position (must be in same space as current mesh) to look at
  16876. * @param yawCor optional yaw (y-axis) correction in radians
  16877. * @param pitchCor optional pitch (x-axis) correction in radians
  16878. * @param rollCor optional roll (z-axis) correction in radians
  16879. * @param space the choosen space of the target
  16880. * @returns the TransformNode.
  16881. */
  16882. TransformNode.prototype.lookAt = function (targetPoint, yawCor, pitchCor, rollCor, space) {
  16883. if (yawCor === void 0) { yawCor = 0; }
  16884. if (pitchCor === void 0) { pitchCor = 0; }
  16885. if (rollCor === void 0) { rollCor = 0; }
  16886. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  16887. var dv = TransformNode._lookAtVectorCache;
  16888. var pos = space === BABYLON.Space.LOCAL ? this.position : this.getAbsolutePosition();
  16889. targetPoint.subtractToRef(pos, dv);
  16890. var yaw = -Math.atan2(dv.z, dv.x) - Math.PI / 2;
  16891. var len = Math.sqrt(dv.x * dv.x + dv.z * dv.z);
  16892. var pitch = Math.atan2(dv.y, len);
  16893. if (this.rotationQuaternion) {
  16894. BABYLON.Quaternion.RotationYawPitchRollToRef(yaw + yawCor, pitch + pitchCor, rollCor, this.rotationQuaternion);
  16895. }
  16896. else {
  16897. this.rotation.x = pitch + pitchCor;
  16898. this.rotation.y = yaw + yawCor;
  16899. this.rotation.z = rollCor;
  16900. }
  16901. return this;
  16902. };
  16903. /**
  16904. * Returns a new Vector3 what is the localAxis, expressed in the mesh local space, rotated like the mesh.
  16905. * This Vector3 is expressed in the World space.
  16906. */
  16907. TransformNode.prototype.getDirection = function (localAxis) {
  16908. var result = BABYLON.Vector3.Zero();
  16909. this.getDirectionToRef(localAxis, result);
  16910. return result;
  16911. };
  16912. /**
  16913. * Sets the Vector3 "result" as the rotated Vector3 "localAxis" in the same rotation than the mesh.
  16914. * localAxis is expressed in the mesh local space.
  16915. * result is computed in the Wordl space from the mesh World matrix.
  16916. * Returns the TransformNode.
  16917. */
  16918. TransformNode.prototype.getDirectionToRef = function (localAxis, result) {
  16919. BABYLON.Vector3.TransformNormalToRef(localAxis, this.getWorldMatrix(), result);
  16920. return this;
  16921. };
  16922. /**
  16923. * Sets a new pivot point to the current node
  16924. * @param point defines the new pivot point to use
  16925. * @param space defines if the point is in world or local space (local by default)
  16926. * @returns the current TransformNode
  16927. */
  16928. TransformNode.prototype.setPivotPoint = function (point, space) {
  16929. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  16930. if (this.getScene().getRenderId() == 0) {
  16931. this.computeWorldMatrix(true);
  16932. }
  16933. var wm = this.getWorldMatrix();
  16934. if (space == BABYLON.Space.WORLD) {
  16935. var tmat = BABYLON.Tmp.Matrix[0];
  16936. wm.invertToRef(tmat);
  16937. point = BABYLON.Vector3.TransformCoordinates(point, tmat);
  16938. }
  16939. return this.setPivotMatrix(BABYLON.Matrix.Translation(-point.x, -point.y, -point.z), true);
  16940. };
  16941. /**
  16942. * Returns a new Vector3 set with the mesh pivot point coordinates in the local space.
  16943. */
  16944. TransformNode.prototype.getPivotPoint = function () {
  16945. var point = BABYLON.Vector3.Zero();
  16946. this.getPivotPointToRef(point);
  16947. return point;
  16948. };
  16949. /**
  16950. * Sets the passed Vector3 "result" with the coordinates of the mesh pivot point in the local space.
  16951. * Returns the TransformNode.
  16952. */
  16953. TransformNode.prototype.getPivotPointToRef = function (result) {
  16954. result.x = -this._pivotMatrix.m[12];
  16955. result.y = -this._pivotMatrix.m[13];
  16956. result.z = -this._pivotMatrix.m[14];
  16957. return this;
  16958. };
  16959. /**
  16960. * Returns a new Vector3 set with the mesh pivot point World coordinates.
  16961. */
  16962. TransformNode.prototype.getAbsolutePivotPoint = function () {
  16963. var point = BABYLON.Vector3.Zero();
  16964. this.getAbsolutePivotPointToRef(point);
  16965. return point;
  16966. };
  16967. /**
  16968. * Sets the Vector3 "result" coordinates with the mesh pivot point World coordinates.
  16969. * Returns the TransformNode.
  16970. */
  16971. TransformNode.prototype.getAbsolutePivotPointToRef = function (result) {
  16972. result.x = this._pivotMatrix.m[12];
  16973. result.y = this._pivotMatrix.m[13];
  16974. result.z = this._pivotMatrix.m[14];
  16975. this.getPivotPointToRef(result);
  16976. BABYLON.Vector3.TransformCoordinatesToRef(result, this.getWorldMatrix(), result);
  16977. return this;
  16978. };
  16979. /**
  16980. * Defines the passed node as the parent of the current node.
  16981. * The node will remain exactly where it is and its position / rotation will be updated accordingly
  16982. * Returns the TransformNode.
  16983. */
  16984. TransformNode.prototype.setParent = function (node) {
  16985. if (node === null) {
  16986. var rotation = BABYLON.Tmp.Quaternion[0];
  16987. var position = BABYLON.Tmp.Vector3[0];
  16988. var scale = BABYLON.Tmp.Vector3[1];
  16989. if (this.parent && this.parent.computeWorldMatrix) {
  16990. this.parent.computeWorldMatrix(true);
  16991. }
  16992. this.computeWorldMatrix(true);
  16993. this.getWorldMatrix().decompose(scale, rotation, position);
  16994. if (this.rotationQuaternion) {
  16995. this.rotationQuaternion.copyFrom(rotation);
  16996. }
  16997. else {
  16998. rotation.toEulerAnglesToRef(this.rotation);
  16999. }
  17000. this.scaling.x = scale.x;
  17001. this.scaling.y = scale.y;
  17002. this.scaling.z = scale.z;
  17003. this.position.x = position.x;
  17004. this.position.y = position.y;
  17005. this.position.z = position.z;
  17006. }
  17007. else {
  17008. var rotation = BABYLON.Tmp.Quaternion[0];
  17009. var position = BABYLON.Tmp.Vector3[0];
  17010. var scale = BABYLON.Tmp.Vector3[1];
  17011. var diffMatrix = BABYLON.Tmp.Matrix[0];
  17012. var invParentMatrix = BABYLON.Tmp.Matrix[1];
  17013. this.computeWorldMatrix(true);
  17014. node.computeWorldMatrix(true);
  17015. node.getWorldMatrix().invertToRef(invParentMatrix);
  17016. this.getWorldMatrix().multiplyToRef(invParentMatrix, diffMatrix);
  17017. diffMatrix.decompose(scale, rotation, position);
  17018. if (this.rotationQuaternion) {
  17019. this.rotationQuaternion.copyFrom(rotation);
  17020. }
  17021. else {
  17022. rotation.toEulerAnglesToRef(this.rotation);
  17023. }
  17024. this.position.x = position.x;
  17025. this.position.y = position.y;
  17026. this.position.z = position.z;
  17027. this.scaling.x = scale.x;
  17028. this.scaling.y = scale.y;
  17029. this.scaling.z = scale.z;
  17030. }
  17031. this.parent = node;
  17032. return this;
  17033. };
  17034. Object.defineProperty(TransformNode.prototype, "nonUniformScaling", {
  17035. get: function () {
  17036. return this._nonUniformScaling;
  17037. },
  17038. enumerable: true,
  17039. configurable: true
  17040. });
  17041. TransformNode.prototype._updateNonUniformScalingState = function (value) {
  17042. if (this._nonUniformScaling === value) {
  17043. return false;
  17044. }
  17045. this._nonUniformScaling = true;
  17046. return true;
  17047. };
  17048. /**
  17049. * Attach the current TransformNode to another TransformNode associated with a bone
  17050. * @param bone Bone affecting the TransformNode
  17051. * @param affectedTransformNode TransformNode associated with the bone
  17052. */
  17053. TransformNode.prototype.attachToBone = function (bone, affectedTransformNode) {
  17054. this._transformToBoneReferal = affectedTransformNode;
  17055. this.parent = bone;
  17056. if (bone.getWorldMatrix().determinant() < 0) {
  17057. this.scalingDeterminant *= -1;
  17058. }
  17059. return this;
  17060. };
  17061. TransformNode.prototype.detachFromBone = function () {
  17062. if (!this.parent) {
  17063. return this;
  17064. }
  17065. if (this.parent.getWorldMatrix().determinant() < 0) {
  17066. this.scalingDeterminant *= -1;
  17067. }
  17068. this._transformToBoneReferal = null;
  17069. this.parent = null;
  17070. return this;
  17071. };
  17072. /**
  17073. * Rotates the mesh around the axis vector for the passed angle (amount) expressed in radians, in the given space.
  17074. * space (default LOCAL) can be either BABYLON.Space.LOCAL, either BABYLON.Space.WORLD.
  17075. * Note that the property `rotationQuaternion` is then automatically updated and the property `rotation` is set to (0,0,0) and no longer used.
  17076. * The passed axis is also normalized.
  17077. * Returns the TransformNode.
  17078. */
  17079. TransformNode.prototype.rotate = function (axis, amount, space) {
  17080. axis.normalize();
  17081. if (!this.rotationQuaternion) {
  17082. this.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z);
  17083. this.rotation = BABYLON.Vector3.Zero();
  17084. }
  17085. var rotationQuaternion;
  17086. if (!space || space === BABYLON.Space.LOCAL) {
  17087. rotationQuaternion = BABYLON.Quaternion.RotationAxisToRef(axis, amount, TransformNode._rotationAxisCache);
  17088. this.rotationQuaternion.multiplyToRef(rotationQuaternion, this.rotationQuaternion);
  17089. }
  17090. else {
  17091. if (this.parent) {
  17092. var invertParentWorldMatrix = this.parent.getWorldMatrix().clone();
  17093. invertParentWorldMatrix.invert();
  17094. axis = BABYLON.Vector3.TransformNormal(axis, invertParentWorldMatrix);
  17095. }
  17096. rotationQuaternion = BABYLON.Quaternion.RotationAxisToRef(axis, amount, TransformNode._rotationAxisCache);
  17097. rotationQuaternion.multiplyToRef(this.rotationQuaternion, this.rotationQuaternion);
  17098. }
  17099. return this;
  17100. };
  17101. /**
  17102. * Rotates the mesh around the axis vector for the passed angle (amount) expressed in radians, in world space.
  17103. * Note that the property `rotationQuaternion` is then automatically updated and the property `rotation` is set to (0,0,0) and no longer used.
  17104. * The passed axis is also normalized.
  17105. * Returns the TransformNode.
  17106. * Method is based on http://www.euclideanspace.com/maths/geometry/affine/aroundPoint/index.htm
  17107. */
  17108. TransformNode.prototype.rotateAround = function (point, axis, amount) {
  17109. axis.normalize();
  17110. if (!this.rotationQuaternion) {
  17111. this.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z);
  17112. this.rotation.copyFromFloats(0, 0, 0);
  17113. }
  17114. point.subtractToRef(this.position, BABYLON.Tmp.Vector3[0]);
  17115. BABYLON.Matrix.TranslationToRef(BABYLON.Tmp.Vector3[0].x, BABYLON.Tmp.Vector3[0].y, BABYLON.Tmp.Vector3[0].z, BABYLON.Tmp.Matrix[0]);
  17116. BABYLON.Tmp.Matrix[0].invertToRef(BABYLON.Tmp.Matrix[2]);
  17117. BABYLON.Matrix.RotationAxisToRef(axis, amount, BABYLON.Tmp.Matrix[1]);
  17118. BABYLON.Tmp.Matrix[2].multiplyToRef(BABYLON.Tmp.Matrix[1], BABYLON.Tmp.Matrix[2]);
  17119. BABYLON.Tmp.Matrix[2].multiplyToRef(BABYLON.Tmp.Matrix[0], BABYLON.Tmp.Matrix[2]);
  17120. BABYLON.Tmp.Matrix[2].decompose(BABYLON.Tmp.Vector3[0], BABYLON.Tmp.Quaternion[0], BABYLON.Tmp.Vector3[1]);
  17121. this.position.addInPlace(BABYLON.Tmp.Vector3[1]);
  17122. BABYLON.Tmp.Quaternion[0].multiplyToRef(this.rotationQuaternion, this.rotationQuaternion);
  17123. return this;
  17124. };
  17125. /**
  17126. * Translates the mesh along the axis vector for the passed distance in the given space.
  17127. * space (default LOCAL) can be either BABYLON.Space.LOCAL, either BABYLON.Space.WORLD.
  17128. * Returns the TransformNode.
  17129. */
  17130. TransformNode.prototype.translate = function (axis, distance, space) {
  17131. var displacementVector = axis.scale(distance);
  17132. if (!space || space === BABYLON.Space.LOCAL) {
  17133. var tempV3 = this.getPositionExpressedInLocalSpace().add(displacementVector);
  17134. this.setPositionWithLocalVector(tempV3);
  17135. }
  17136. else {
  17137. this.setAbsolutePosition(this.getAbsolutePosition().add(displacementVector));
  17138. }
  17139. return this;
  17140. };
  17141. /**
  17142. * Adds a rotation step to the mesh current rotation.
  17143. * x, y, z are Euler angles expressed in radians.
  17144. * This methods updates the current mesh rotation, either mesh.rotation, either mesh.rotationQuaternion if it's set.
  17145. * This means this rotation is made in the mesh local space only.
  17146. * It's useful to set a custom rotation order different from the BJS standard one YXZ.
  17147. * Example : this rotates the mesh first around its local X axis, then around its local Z axis, finally around its local Y axis.
  17148. * ```javascript
  17149. * mesh.addRotation(x1, 0, 0).addRotation(0, 0, z2).addRotation(0, 0, y3);
  17150. * ```
  17151. * Note that `addRotation()` accumulates the passed rotation values to the current ones and computes the .rotation or .rotationQuaternion updated values.
  17152. * 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.
  17153. * Returns the TransformNode.
  17154. */
  17155. TransformNode.prototype.addRotation = function (x, y, z) {
  17156. var rotationQuaternion;
  17157. if (this.rotationQuaternion) {
  17158. rotationQuaternion = this.rotationQuaternion;
  17159. }
  17160. else {
  17161. rotationQuaternion = BABYLON.Tmp.Quaternion[1];
  17162. BABYLON.Quaternion.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, rotationQuaternion);
  17163. }
  17164. var accumulation = BABYLON.Tmp.Quaternion[0];
  17165. BABYLON.Quaternion.RotationYawPitchRollToRef(y, x, z, accumulation);
  17166. rotationQuaternion.multiplyInPlace(accumulation);
  17167. if (!this.rotationQuaternion) {
  17168. rotationQuaternion.toEulerAnglesToRef(this.rotation);
  17169. }
  17170. return this;
  17171. };
  17172. /**
  17173. * Computes the mesh World matrix and returns it.
  17174. * If the mesh world matrix is frozen, this computation does nothing more than returning the last frozen values.
  17175. * If the parameter `force` is let to `false` (default), the current cached World matrix is returned.
  17176. * If the parameter `force`is set to `true`, the actual computation is done.
  17177. * Returns the mesh World Matrix.
  17178. */
  17179. TransformNode.prototype.computeWorldMatrix = function (force) {
  17180. if (this._isWorldMatrixFrozen) {
  17181. return this._worldMatrix;
  17182. }
  17183. if (!force && this.isSynchronized(true)) {
  17184. this._currentRenderId = this.getScene().getRenderId();
  17185. return this._worldMatrix;
  17186. }
  17187. this._cache.position.copyFrom(this.position);
  17188. this._cache.scaling.copyFrom(this.scaling);
  17189. this._cache.pivotMatrixUpdated = false;
  17190. this._cache.billboardMode = this.billboardMode;
  17191. this._currentRenderId = this.getScene().getRenderId();
  17192. this._childRenderId = this.getScene().getRenderId();
  17193. this._isDirty = false;
  17194. // Scaling
  17195. BABYLON.Matrix.ScalingToRef(this.scaling.x * this.scalingDeterminant, this.scaling.y * this.scalingDeterminant, this.scaling.z * this.scalingDeterminant, BABYLON.Tmp.Matrix[1]);
  17196. // Rotation
  17197. //rotate, if quaternion is set and rotation was used
  17198. if (this.rotationQuaternion) {
  17199. var len = this.rotation.length();
  17200. if (len) {
  17201. this.rotationQuaternion.multiplyInPlace(BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z));
  17202. this.rotation.copyFromFloats(0, 0, 0);
  17203. }
  17204. }
  17205. if (this.rotationQuaternion) {
  17206. this.rotationQuaternion.toRotationMatrix(BABYLON.Tmp.Matrix[0]);
  17207. this._cache.rotationQuaternion.copyFrom(this.rotationQuaternion);
  17208. }
  17209. else {
  17210. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, BABYLON.Tmp.Matrix[0]);
  17211. this._cache.rotation.copyFrom(this.rotation);
  17212. }
  17213. // Translation
  17214. var camera = this.getScene().activeCamera;
  17215. if (this.infiniteDistance && !this.parent && camera) {
  17216. var cameraWorldMatrix = camera.getWorldMatrix();
  17217. var cameraGlobalPosition = new BABYLON.Vector3(cameraWorldMatrix.m[12], cameraWorldMatrix.m[13], cameraWorldMatrix.m[14]);
  17218. BABYLON.Matrix.TranslationToRef(this.position.x + cameraGlobalPosition.x, this.position.y + cameraGlobalPosition.y, this.position.z + cameraGlobalPosition.z, BABYLON.Tmp.Matrix[2]);
  17219. }
  17220. else {
  17221. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, BABYLON.Tmp.Matrix[2]);
  17222. }
  17223. // Composing transformations
  17224. this._pivotMatrix.multiplyToRef(BABYLON.Tmp.Matrix[1], BABYLON.Tmp.Matrix[4]);
  17225. BABYLON.Tmp.Matrix[4].multiplyToRef(BABYLON.Tmp.Matrix[0], BABYLON.Tmp.Matrix[5]);
  17226. // Billboarding (testing PG:http://www.babylonjs-playground.com/#UJEIL#13)
  17227. if (this.billboardMode !== TransformNode.BILLBOARDMODE_NONE && camera) {
  17228. if ((this.billboardMode & TransformNode.BILLBOARDMODE_ALL) !== TransformNode.BILLBOARDMODE_ALL) {
  17229. // Need to decompose each rotation here
  17230. var currentPosition = BABYLON.Tmp.Vector3[3];
  17231. if (this.parent && this.parent.getWorldMatrix) {
  17232. if (this._transformToBoneReferal) {
  17233. this.parent.getWorldMatrix().multiplyToRef(this._transformToBoneReferal.getWorldMatrix(), BABYLON.Tmp.Matrix[6]);
  17234. BABYLON.Vector3.TransformCoordinatesToRef(this.position, BABYLON.Tmp.Matrix[6], currentPosition);
  17235. }
  17236. else {
  17237. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this.parent.getWorldMatrix(), currentPosition);
  17238. }
  17239. }
  17240. else {
  17241. currentPosition.copyFrom(this.position);
  17242. }
  17243. currentPosition.subtractInPlace(camera.globalPosition);
  17244. var finalEuler = BABYLON.Tmp.Vector3[4].copyFromFloats(0, 0, 0);
  17245. if ((this.billboardMode & TransformNode.BILLBOARDMODE_X) === TransformNode.BILLBOARDMODE_X) {
  17246. finalEuler.x = Math.atan2(-currentPosition.y, currentPosition.z);
  17247. }
  17248. if ((this.billboardMode & TransformNode.BILLBOARDMODE_Y) === TransformNode.BILLBOARDMODE_Y) {
  17249. finalEuler.y = Math.atan2(currentPosition.x, currentPosition.z);
  17250. }
  17251. if ((this.billboardMode & TransformNode.BILLBOARDMODE_Z) === TransformNode.BILLBOARDMODE_Z) {
  17252. finalEuler.z = Math.atan2(currentPosition.y, currentPosition.x);
  17253. }
  17254. BABYLON.Matrix.RotationYawPitchRollToRef(finalEuler.y, finalEuler.x, finalEuler.z, BABYLON.Tmp.Matrix[0]);
  17255. }
  17256. else {
  17257. BABYLON.Tmp.Matrix[1].copyFrom(camera.getViewMatrix());
  17258. BABYLON.Tmp.Matrix[1].setTranslationFromFloats(0, 0, 0);
  17259. BABYLON.Tmp.Matrix[1].invertToRef(BABYLON.Tmp.Matrix[0]);
  17260. }
  17261. BABYLON.Tmp.Matrix[1].copyFrom(BABYLON.Tmp.Matrix[5]);
  17262. BABYLON.Tmp.Matrix[1].multiplyToRef(BABYLON.Tmp.Matrix[0], BABYLON.Tmp.Matrix[5]);
  17263. }
  17264. // Local world
  17265. BABYLON.Tmp.Matrix[5].multiplyToRef(BABYLON.Tmp.Matrix[2], this._localWorld);
  17266. // Parent
  17267. if (this.parent && this.parent.getWorldMatrix) {
  17268. if (this.billboardMode !== TransformNode.BILLBOARDMODE_NONE) {
  17269. if (this._transformToBoneReferal) {
  17270. this.parent.getWorldMatrix().multiplyToRef(this._transformToBoneReferal.getWorldMatrix(), BABYLON.Tmp.Matrix[6]);
  17271. BABYLON.Tmp.Matrix[5].copyFrom(BABYLON.Tmp.Matrix[6]);
  17272. }
  17273. else {
  17274. BABYLON.Tmp.Matrix[5].copyFrom(this.parent.getWorldMatrix());
  17275. }
  17276. this._localWorld.getTranslationToRef(BABYLON.Tmp.Vector3[5]);
  17277. BABYLON.Vector3.TransformCoordinatesToRef(BABYLON.Tmp.Vector3[5], BABYLON.Tmp.Matrix[5], BABYLON.Tmp.Vector3[5]);
  17278. this._worldMatrix.copyFrom(this._localWorld);
  17279. this._worldMatrix.setTranslation(BABYLON.Tmp.Vector3[5]);
  17280. }
  17281. else {
  17282. if (this._transformToBoneReferal) {
  17283. this._localWorld.multiplyToRef(this.parent.getWorldMatrix(), BABYLON.Tmp.Matrix[6]);
  17284. BABYLON.Tmp.Matrix[6].multiplyToRef(this._transformToBoneReferal.getWorldMatrix(), this._worldMatrix);
  17285. }
  17286. else {
  17287. this._localWorld.multiplyToRef(this.parent.getWorldMatrix(), this._worldMatrix);
  17288. }
  17289. }
  17290. this._markSyncedWithParent();
  17291. }
  17292. else {
  17293. this._worldMatrix.copyFrom(this._localWorld);
  17294. }
  17295. // Post multiply inverse of pivotMatrix
  17296. if (this._postMultiplyPivotMatrix) {
  17297. this._worldMatrix.multiplyToRef(this._pivotMatrixInverse, this._worldMatrix);
  17298. }
  17299. // Normal matrix
  17300. if (this.scaling.isNonUniform) {
  17301. this._updateNonUniformScalingState(true);
  17302. }
  17303. else if (this.parent && this.parent._nonUniformScaling) {
  17304. this._updateNonUniformScalingState(this.parent._nonUniformScaling);
  17305. }
  17306. else {
  17307. this._updateNonUniformScalingState(false);
  17308. }
  17309. this._afterComputeWorldMatrix();
  17310. // Absolute position
  17311. this._absolutePosition.copyFromFloats(this._worldMatrix.m[12], this._worldMatrix.m[13], this._worldMatrix.m[14]);
  17312. // Callbacks
  17313. this.onAfterWorldMatrixUpdateObservable.notifyObservers(this);
  17314. if (!this._poseMatrix) {
  17315. this._poseMatrix = BABYLON.Matrix.Invert(this._worldMatrix);
  17316. }
  17317. // Cache the determinant
  17318. this._worldMatrixDeterminant = this._worldMatrix.determinant();
  17319. return this._worldMatrix;
  17320. };
  17321. TransformNode.prototype._afterComputeWorldMatrix = function () {
  17322. };
  17323. /**
  17324. * If you'd like to be called back after the mesh position, rotation or scaling has been updated.
  17325. * @param func: callback function to add
  17326. *
  17327. * Returns the TransformNode.
  17328. */
  17329. TransformNode.prototype.registerAfterWorldMatrixUpdate = function (func) {
  17330. this.onAfterWorldMatrixUpdateObservable.add(func);
  17331. return this;
  17332. };
  17333. /**
  17334. * Removes a registered callback function.
  17335. * Returns the TransformNode.
  17336. */
  17337. TransformNode.prototype.unregisterAfterWorldMatrixUpdate = function (func) {
  17338. this.onAfterWorldMatrixUpdateObservable.removeCallback(func);
  17339. return this;
  17340. };
  17341. /**
  17342. * Clone the current transform node
  17343. * Returns the new transform node
  17344. * @param name Name of the new clone
  17345. * @param newParent New parent for the clone
  17346. * @param doNotCloneChildren Do not clone children hierarchy
  17347. */
  17348. TransformNode.prototype.clone = function (name, newParent, doNotCloneChildren) {
  17349. var _this = this;
  17350. var result = BABYLON.SerializationHelper.Clone(function () { return new TransformNode(name, _this.getScene()); }, this);
  17351. result.name = name;
  17352. result.id = name;
  17353. if (newParent) {
  17354. result.parent = newParent;
  17355. }
  17356. if (!doNotCloneChildren) {
  17357. // Children
  17358. var directDescendants = this.getDescendants(true);
  17359. for (var index = 0; index < directDescendants.length; index++) {
  17360. var child = directDescendants[index];
  17361. if (child.clone) {
  17362. child.clone(name + "." + child.name, result);
  17363. }
  17364. }
  17365. }
  17366. return result;
  17367. };
  17368. TransformNode.prototype.serialize = function (currentSerializationObject) {
  17369. var serializationObject = BABYLON.SerializationHelper.Serialize(this, currentSerializationObject);
  17370. serializationObject.type = this.getClassName();
  17371. // Parent
  17372. if (this.parent) {
  17373. serializationObject.parentId = this.parent.id;
  17374. }
  17375. if (BABYLON.Tags && BABYLON.Tags.HasTags(this)) {
  17376. serializationObject.tags = BABYLON.Tags.GetTags(this);
  17377. }
  17378. serializationObject.localMatrix = this.getPivotMatrix().asArray();
  17379. serializationObject.isEnabled = this.isEnabled();
  17380. // Parent
  17381. if (this.parent) {
  17382. serializationObject.parentId = this.parent.id;
  17383. }
  17384. return serializationObject;
  17385. };
  17386. // Statics
  17387. /**
  17388. * Returns a new TransformNode object parsed from the source provided.
  17389. * The parameter `parsedMesh` is the source.
  17390. * The parameter `rootUrl` is a string, it's the root URL to prefix the `delayLoadingFile` property with
  17391. */
  17392. TransformNode.Parse = function (parsedTransformNode, scene, rootUrl) {
  17393. var transformNode = BABYLON.SerializationHelper.Parse(function () { return new TransformNode(parsedTransformNode.name, scene); }, parsedTransformNode, scene, rootUrl);
  17394. if (BABYLON.Tags) {
  17395. BABYLON.Tags.AddTagsTo(transformNode, parsedTransformNode.tags);
  17396. }
  17397. if (parsedTransformNode.localMatrix) {
  17398. transformNode.setPreTransformMatrix(BABYLON.Matrix.FromArray(parsedTransformNode.localMatrix));
  17399. }
  17400. else if (parsedTransformNode.pivotMatrix) {
  17401. transformNode.setPivotMatrix(BABYLON.Matrix.FromArray(parsedTransformNode.pivotMatrix));
  17402. }
  17403. transformNode.setEnabled(parsedTransformNode.isEnabled);
  17404. // Parent
  17405. if (parsedTransformNode.parentId) {
  17406. transformNode._waitingParentId = parsedTransformNode.parentId;
  17407. }
  17408. return transformNode;
  17409. };
  17410. /**
  17411. * Releases resources associated with this transform node.
  17412. * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default)
  17413. * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default)
  17414. */
  17415. TransformNode.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  17416. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  17417. // Animations
  17418. this.getScene().stopAnimation(this);
  17419. // Remove from scene
  17420. this.getScene().removeTransformNode(this);
  17421. this.onAfterWorldMatrixUpdateObservable.clear();
  17422. _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
  17423. };
  17424. // Statics
  17425. TransformNode.BILLBOARDMODE_NONE = 0;
  17426. TransformNode.BILLBOARDMODE_X = 1;
  17427. TransformNode.BILLBOARDMODE_Y = 2;
  17428. TransformNode.BILLBOARDMODE_Z = 4;
  17429. TransformNode.BILLBOARDMODE_ALL = 7;
  17430. TransformNode._lookAtVectorCache = new BABYLON.Vector3(0, 0, 0);
  17431. TransformNode._rotationAxisCache = new BABYLON.Quaternion();
  17432. __decorate([
  17433. BABYLON.serializeAsVector3()
  17434. ], TransformNode.prototype, "_rotation", void 0);
  17435. __decorate([
  17436. BABYLON.serializeAsQuaternion()
  17437. ], TransformNode.prototype, "_rotationQuaternion", void 0);
  17438. __decorate([
  17439. BABYLON.serializeAsVector3()
  17440. ], TransformNode.prototype, "_scaling", void 0);
  17441. __decorate([
  17442. BABYLON.serialize()
  17443. ], TransformNode.prototype, "billboardMode", void 0);
  17444. __decorate([
  17445. BABYLON.serialize()
  17446. ], TransformNode.prototype, "scalingDeterminant", void 0);
  17447. __decorate([
  17448. BABYLON.serialize()
  17449. ], TransformNode.prototype, "infiniteDistance", void 0);
  17450. __decorate([
  17451. BABYLON.serializeAsVector3()
  17452. ], TransformNode.prototype, "position", void 0);
  17453. return TransformNode;
  17454. }(BABYLON.Node));
  17455. BABYLON.TransformNode = TransformNode;
  17456. })(BABYLON || (BABYLON = {}));
  17457. //# sourceMappingURL=babylon.transformNode.js.map
  17458. "use strict";
  17459. var BABYLON;
  17460. (function (BABYLON) {
  17461. var AbstractMesh = /** @class */ (function (_super) {
  17462. __extends(AbstractMesh, _super);
  17463. // Constructor
  17464. function AbstractMesh(name, scene) {
  17465. if (scene === void 0) { scene = null; }
  17466. var _this = _super.call(this, name, scene, false) || this;
  17467. _this._facetNb = 0; // facet number
  17468. _this._partitioningSubdivisions = 10; // number of subdivisions per axis in the partioning space
  17469. _this._partitioningBBoxRatio = 1.01; // the partioning array space is by default 1% bigger than the bounding box
  17470. _this._facetDataEnabled = false; // is the facet data feature enabled on this mesh ?
  17471. _this._facetParameters = {}; // keep a reference to the object parameters to avoid memory re-allocation
  17472. _this._bbSize = BABYLON.Vector3.Zero(); // bbox size approximated for facet data
  17473. _this._subDiv = {
  17474. max: 1,
  17475. X: 1,
  17476. Y: 1,
  17477. Z: 1
  17478. };
  17479. _this._facetDepthSort = false; // is the facet depth sort to be computed
  17480. _this._facetDepthSortEnabled = false; // is the facet depth sort initialized
  17481. // Events
  17482. /**
  17483. * An event triggered when this mesh collides with another one
  17484. */
  17485. _this.onCollideObservable = new BABYLON.Observable();
  17486. /**
  17487. * An event triggered when the collision's position changes
  17488. */
  17489. _this.onCollisionPositionChangeObservable = new BABYLON.Observable();
  17490. /**
  17491. * An event triggered when material is changed
  17492. */
  17493. _this.onMaterialChangedObservable = new BABYLON.Observable();
  17494. // Properties
  17495. _this.definedFacingForward = true; // orientation for POV movement & rotation
  17496. /**
  17497. * This property determines the type of occlusion query algorithm to run in WebGl, you can use:
  17498. * AbstractMesh.OCCLUSION_ALGORITHM_TYPE_ACCURATE which is mapped to GL_ANY_SAMPLES_PASSED.
  17499. * or
  17500. * 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.
  17501. * for more info check WebGl documentations
  17502. */
  17503. _this.occlusionQueryAlgorithmType = AbstractMesh.OCCLUSION_ALGORITHM_TYPE_CONSERVATIVE;
  17504. /**
  17505. * 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:
  17506. * OCCLUSION_TYPE_NONE (Default Value): this option means no occlusion query whith the Mesh.
  17507. * OCCLUSION_TYPE_OPTIMISTIC: this option is means use occlusion query and if occlusionRetryCount is reached and the query is broken show the mesh.
  17508. * 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.
  17509. */
  17510. _this.occlusionType = AbstractMesh.OCCLUSION_TYPE_NONE;
  17511. /**
  17512. * 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.
  17513. * The default value is -1 which means don't break the query and wait till the result.
  17514. */
  17515. _this.occlusionRetryCount = -1;
  17516. _this._occlusionInternalRetryCounter = 0;
  17517. _this._isOccluded = false;
  17518. _this._isOcclusionQueryInProgress = false;
  17519. _this._visibility = 1.0;
  17520. _this.alphaIndex = Number.MAX_VALUE;
  17521. _this.isVisible = true;
  17522. _this.isPickable = true;
  17523. _this.showBoundingBox = false;
  17524. _this.showSubMeshesBoundingBox = false;
  17525. _this.isBlocker = false;
  17526. _this.enablePointerMoveEvents = false;
  17527. _this.renderingGroupId = 0;
  17528. _this._receiveShadows = false;
  17529. _this.renderOutline = false;
  17530. _this.outlineColor = BABYLON.Color3.Red();
  17531. _this.outlineWidth = 0.02;
  17532. _this.renderOverlay = false;
  17533. _this.overlayColor = BABYLON.Color3.Red();
  17534. _this.overlayAlpha = 0.5;
  17535. _this._hasVertexAlpha = false;
  17536. _this._useVertexColors = true;
  17537. _this._computeBonesUsingShaders = true;
  17538. _this._numBoneInfluencers = 4;
  17539. _this._applyFog = true;
  17540. _this.useOctreeForRenderingSelection = true;
  17541. _this.useOctreeForPicking = true;
  17542. _this.useOctreeForCollisions = true;
  17543. _this._layerMask = 0x0FFFFFFF;
  17544. /**
  17545. * True if the mesh must be rendered in any case.
  17546. */
  17547. _this.alwaysSelectAsActiveMesh = false;
  17548. /**
  17549. * This scene's action manager
  17550. */
  17551. _this.actionManager = null;
  17552. // Physics
  17553. _this.physicsImpostor = null;
  17554. // Collisions
  17555. _this._checkCollisions = false;
  17556. _this._collisionMask = -1;
  17557. _this._collisionGroup = -1;
  17558. _this.ellipsoid = new BABYLON.Vector3(0.5, 1, 0.5);
  17559. _this.ellipsoidOffset = new BABYLON.Vector3(0, 0, 0);
  17560. _this._oldPositionForCollisions = new BABYLON.Vector3(0, 0, 0);
  17561. _this._diffPositionForCollisions = new BABYLON.Vector3(0, 0, 0);
  17562. // Edges
  17563. _this.edgesWidth = 1;
  17564. _this.edgesColor = new BABYLON.Color4(1, 0, 0, 1);
  17565. // Cache
  17566. _this._collisionsTransformMatrix = BABYLON.Matrix.Zero();
  17567. _this._collisionsScalingMatrix = BABYLON.Matrix.Zero();
  17568. _this._renderId = 0;
  17569. _this._intersectionsInProgress = new Array();
  17570. _this._unIndexed = false;
  17571. _this._lightSources = new Array();
  17572. _this._onCollisionPositionChange = function (collisionId, newPosition, collidedMesh) {
  17573. if (collidedMesh === void 0) { collidedMesh = null; }
  17574. //TODO move this to the collision coordinator!
  17575. if (_this.getScene().workerCollisions)
  17576. newPosition.multiplyInPlace(_this._collider._radius);
  17577. newPosition.subtractToRef(_this._oldPositionForCollisions, _this._diffPositionForCollisions);
  17578. if (_this._diffPositionForCollisions.length() > BABYLON.Engine.CollisionsEpsilon) {
  17579. _this.position.addInPlace(_this._diffPositionForCollisions);
  17580. }
  17581. if (collidedMesh) {
  17582. _this.onCollideObservable.notifyObservers(collidedMesh);
  17583. }
  17584. _this.onCollisionPositionChangeObservable.notifyObservers(_this.position);
  17585. };
  17586. _this.getScene().addMesh(_this);
  17587. _this._resyncLightSources();
  17588. return _this;
  17589. }
  17590. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_NONE", {
  17591. get: function () {
  17592. return BABYLON.TransformNode.BILLBOARDMODE_NONE;
  17593. },
  17594. enumerable: true,
  17595. configurable: true
  17596. });
  17597. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_X", {
  17598. get: function () {
  17599. return BABYLON.TransformNode.BILLBOARDMODE_X;
  17600. },
  17601. enumerable: true,
  17602. configurable: true
  17603. });
  17604. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_Y", {
  17605. get: function () {
  17606. return BABYLON.TransformNode.BILLBOARDMODE_Y;
  17607. },
  17608. enumerable: true,
  17609. configurable: true
  17610. });
  17611. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_Z", {
  17612. get: function () {
  17613. return BABYLON.TransformNode.BILLBOARDMODE_Z;
  17614. },
  17615. enumerable: true,
  17616. configurable: true
  17617. });
  17618. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_ALL", {
  17619. get: function () {
  17620. return BABYLON.TransformNode.BILLBOARDMODE_ALL;
  17621. },
  17622. enumerable: true,
  17623. configurable: true
  17624. });
  17625. Object.defineProperty(AbstractMesh.prototype, "facetNb", {
  17626. /**
  17627. * Read-only : the number of facets in the mesh
  17628. */
  17629. get: function () {
  17630. return this._facetNb;
  17631. },
  17632. enumerable: true,
  17633. configurable: true
  17634. });
  17635. Object.defineProperty(AbstractMesh.prototype, "partitioningSubdivisions", {
  17636. /**
  17637. * The number (integer) of subdivisions per axis in the partioning space
  17638. */
  17639. get: function () {
  17640. return this._partitioningSubdivisions;
  17641. },
  17642. set: function (nb) {
  17643. this._partitioningSubdivisions = nb;
  17644. },
  17645. enumerable: true,
  17646. configurable: true
  17647. });
  17648. Object.defineProperty(AbstractMesh.prototype, "partitioningBBoxRatio", {
  17649. /**
  17650. * The ratio (float) to apply to the bouding box size to set to the partioning space.
  17651. * Ex : 1.01 (default) the partioning space is 1% bigger than the bounding box.
  17652. */
  17653. get: function () {
  17654. return this._partitioningBBoxRatio;
  17655. },
  17656. set: function (ratio) {
  17657. this._partitioningBBoxRatio = ratio;
  17658. },
  17659. enumerable: true,
  17660. configurable: true
  17661. });
  17662. Object.defineProperty(AbstractMesh.prototype, "mustDepthSortFacets", {
  17663. /**
  17664. * Boolean : must the facet be depth sorted on next call to `updateFacetData()` ?
  17665. * Works only for updatable meshes.
  17666. * Doesn't work with multi-materials.
  17667. */
  17668. get: function () {
  17669. return this._facetDepthSort;
  17670. },
  17671. set: function (sort) {
  17672. this._facetDepthSort = sort;
  17673. },
  17674. enumerable: true,
  17675. configurable: true
  17676. });
  17677. Object.defineProperty(AbstractMesh.prototype, "facetDepthSortFrom", {
  17678. /**
  17679. * The location (Vector3) where the facet depth sort must be computed from.
  17680. * By default, the active camera position.
  17681. * Used only when facet depth sort is enabled.
  17682. */
  17683. get: function () {
  17684. return this._facetDepthSortFrom;
  17685. },
  17686. set: function (location) {
  17687. this._facetDepthSortFrom = location;
  17688. },
  17689. enumerable: true,
  17690. configurable: true
  17691. });
  17692. Object.defineProperty(AbstractMesh.prototype, "isFacetDataEnabled", {
  17693. /**
  17694. * Read-only boolean : is the feature facetData enabled ?
  17695. */
  17696. get: function () {
  17697. return this._facetDataEnabled;
  17698. },
  17699. enumerable: true,
  17700. configurable: true
  17701. });
  17702. AbstractMesh.prototype._updateNonUniformScalingState = function (value) {
  17703. if (!_super.prototype._updateNonUniformScalingState.call(this, value)) {
  17704. return false;
  17705. }
  17706. this._markSubMeshesAsMiscDirty();
  17707. return true;
  17708. };
  17709. Object.defineProperty(AbstractMesh.prototype, "onCollide", {
  17710. set: function (callback) {
  17711. if (this._onCollideObserver) {
  17712. this.onCollideObservable.remove(this._onCollideObserver);
  17713. }
  17714. this._onCollideObserver = this.onCollideObservable.add(callback);
  17715. },
  17716. enumerable: true,
  17717. configurable: true
  17718. });
  17719. Object.defineProperty(AbstractMesh.prototype, "onCollisionPositionChange", {
  17720. set: function (callback) {
  17721. if (this._onCollisionPositionChangeObserver) {
  17722. this.onCollisionPositionChangeObservable.remove(this._onCollisionPositionChangeObserver);
  17723. }
  17724. this._onCollisionPositionChangeObserver = this.onCollisionPositionChangeObservable.add(callback);
  17725. },
  17726. enumerable: true,
  17727. configurable: true
  17728. });
  17729. Object.defineProperty(AbstractMesh.prototype, "isOccluded", {
  17730. /**
  17731. * Property isOccluded : 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.
  17732. */
  17733. get: function () {
  17734. return this._isOccluded;
  17735. },
  17736. set: function (value) {
  17737. this._isOccluded = value;
  17738. },
  17739. enumerable: true,
  17740. configurable: true
  17741. });
  17742. Object.defineProperty(AbstractMesh.prototype, "isOcclusionQueryInProgress", {
  17743. /**
  17744. * Flag to check the progress status of the query
  17745. */
  17746. get: function () {
  17747. return this._isOcclusionQueryInProgress;
  17748. },
  17749. enumerable: true,
  17750. configurable: true
  17751. });
  17752. Object.defineProperty(AbstractMesh.prototype, "visibility", {
  17753. /**
  17754. * Gets or sets mesh visibility between 0 and 1 (defult is 1)
  17755. */
  17756. get: function () {
  17757. return this._visibility;
  17758. },
  17759. /**
  17760. * Gets or sets mesh visibility between 0 and 1 (defult is 1)
  17761. */
  17762. set: function (value) {
  17763. if (this._visibility === value) {
  17764. return;
  17765. }
  17766. this._visibility = value;
  17767. this._markSubMeshesAsMiscDirty();
  17768. },
  17769. enumerable: true,
  17770. configurable: true
  17771. });
  17772. Object.defineProperty(AbstractMesh.prototype, "material", {
  17773. get: function () {
  17774. return this._material;
  17775. },
  17776. set: function (value) {
  17777. if (this._material === value) {
  17778. return;
  17779. }
  17780. this._material = value;
  17781. if (this.onMaterialChangedObservable.hasObservers) {
  17782. this.onMaterialChangedObservable.notifyObservers(this);
  17783. }
  17784. if (!this.subMeshes) {
  17785. return;
  17786. }
  17787. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  17788. var subMesh = _a[_i];
  17789. subMesh.setEffect(null);
  17790. }
  17791. },
  17792. enumerable: true,
  17793. configurable: true
  17794. });
  17795. Object.defineProperty(AbstractMesh.prototype, "receiveShadows", {
  17796. get: function () {
  17797. return this._receiveShadows;
  17798. },
  17799. set: function (value) {
  17800. if (this._receiveShadows === value) {
  17801. return;
  17802. }
  17803. this._receiveShadows = value;
  17804. this._markSubMeshesAsLightDirty();
  17805. },
  17806. enumerable: true,
  17807. configurable: true
  17808. });
  17809. Object.defineProperty(AbstractMesh.prototype, "hasVertexAlpha", {
  17810. get: function () {
  17811. return this._hasVertexAlpha;
  17812. },
  17813. set: function (value) {
  17814. if (this._hasVertexAlpha === value) {
  17815. return;
  17816. }
  17817. this._hasVertexAlpha = value;
  17818. this._markSubMeshesAsAttributesDirty();
  17819. this._markSubMeshesAsMiscDirty();
  17820. },
  17821. enumerable: true,
  17822. configurable: true
  17823. });
  17824. Object.defineProperty(AbstractMesh.prototype, "useVertexColors", {
  17825. get: function () {
  17826. return this._useVertexColors;
  17827. },
  17828. set: function (value) {
  17829. if (this._useVertexColors === value) {
  17830. return;
  17831. }
  17832. this._useVertexColors = value;
  17833. this._markSubMeshesAsAttributesDirty();
  17834. },
  17835. enumerable: true,
  17836. configurable: true
  17837. });
  17838. Object.defineProperty(AbstractMesh.prototype, "computeBonesUsingShaders", {
  17839. get: function () {
  17840. return this._computeBonesUsingShaders;
  17841. },
  17842. set: function (value) {
  17843. if (this._computeBonesUsingShaders === value) {
  17844. return;
  17845. }
  17846. this._computeBonesUsingShaders = value;
  17847. this._markSubMeshesAsAttributesDirty();
  17848. },
  17849. enumerable: true,
  17850. configurable: true
  17851. });
  17852. Object.defineProperty(AbstractMesh.prototype, "numBoneInfluencers", {
  17853. get: function () {
  17854. return this._numBoneInfluencers;
  17855. },
  17856. set: function (value) {
  17857. if (this._numBoneInfluencers === value) {
  17858. return;
  17859. }
  17860. this._numBoneInfluencers = value;
  17861. this._markSubMeshesAsAttributesDirty();
  17862. },
  17863. enumerable: true,
  17864. configurable: true
  17865. });
  17866. Object.defineProperty(AbstractMesh.prototype, "applyFog", {
  17867. get: function () {
  17868. return this._applyFog;
  17869. },
  17870. set: function (value) {
  17871. if (this._applyFog === value) {
  17872. return;
  17873. }
  17874. this._applyFog = value;
  17875. this._markSubMeshesAsMiscDirty();
  17876. },
  17877. enumerable: true,
  17878. configurable: true
  17879. });
  17880. Object.defineProperty(AbstractMesh.prototype, "layerMask", {
  17881. get: function () {
  17882. return this._layerMask;
  17883. },
  17884. set: function (value) {
  17885. if (value === this._layerMask) {
  17886. return;
  17887. }
  17888. this._layerMask = value;
  17889. this._resyncLightSources();
  17890. },
  17891. enumerable: true,
  17892. configurable: true
  17893. });
  17894. Object.defineProperty(AbstractMesh.prototype, "collisionMask", {
  17895. get: function () {
  17896. return this._collisionMask;
  17897. },
  17898. set: function (mask) {
  17899. this._collisionMask = !isNaN(mask) ? mask : -1;
  17900. },
  17901. enumerable: true,
  17902. configurable: true
  17903. });
  17904. Object.defineProperty(AbstractMesh.prototype, "collisionGroup", {
  17905. get: function () {
  17906. return this._collisionGroup;
  17907. },
  17908. set: function (mask) {
  17909. this._collisionGroup = !isNaN(mask) ? mask : -1;
  17910. },
  17911. enumerable: true,
  17912. configurable: true
  17913. });
  17914. Object.defineProperty(AbstractMesh.prototype, "_positions", {
  17915. get: function () {
  17916. return null;
  17917. },
  17918. enumerable: true,
  17919. configurable: true
  17920. });
  17921. Object.defineProperty(AbstractMesh.prototype, "skeleton", {
  17922. get: function () {
  17923. return this._skeleton;
  17924. },
  17925. set: function (value) {
  17926. if (this._skeleton && this._skeleton.needInitialSkinMatrix) {
  17927. this._skeleton._unregisterMeshWithPoseMatrix(this);
  17928. }
  17929. if (value && value.needInitialSkinMatrix) {
  17930. value._registerMeshWithPoseMatrix(this);
  17931. }
  17932. this._skeleton = value;
  17933. if (!this._skeleton) {
  17934. this._bonesTransformMatrices = null;
  17935. }
  17936. this._markSubMeshesAsAttributesDirty();
  17937. },
  17938. enumerable: true,
  17939. configurable: true
  17940. });
  17941. /**
  17942. * Returns the string "AbstractMesh"
  17943. */
  17944. AbstractMesh.prototype.getClassName = function () {
  17945. return "AbstractMesh";
  17946. };
  17947. /**
  17948. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  17949. */
  17950. AbstractMesh.prototype.toString = function (fullDetails) {
  17951. var ret = "Name: " + this.name + ", isInstance: " + (this instanceof BABYLON.InstancedMesh ? "YES" : "NO");
  17952. ret += ", # of submeshes: " + (this.subMeshes ? this.subMeshes.length : 0);
  17953. if (this._skeleton) {
  17954. ret += ", skeleton: " + this._skeleton.name;
  17955. }
  17956. if (fullDetails) {
  17957. ret += ", billboard mode: " + (["NONE", "X", "Y", null, "Z", null, null, "ALL"])[this.billboardMode];
  17958. ret += ", freeze wrld mat: " + (this._isWorldMatrixFrozen || this._waitingFreezeWorldMatrix ? "YES" : "NO");
  17959. }
  17960. return ret;
  17961. };
  17962. AbstractMesh.prototype._rebuild = function () {
  17963. if (this._occlusionQuery) {
  17964. this._occlusionQuery = null;
  17965. }
  17966. if (this._edgesRenderer) {
  17967. this._edgesRenderer._rebuild();
  17968. }
  17969. if (!this.subMeshes) {
  17970. return;
  17971. }
  17972. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  17973. var subMesh = _a[_i];
  17974. subMesh._rebuild();
  17975. }
  17976. };
  17977. AbstractMesh.prototype._resyncLightSources = function () {
  17978. this._lightSources.length = 0;
  17979. for (var _i = 0, _a = this.getScene().lights; _i < _a.length; _i++) {
  17980. var light = _a[_i];
  17981. if (!light.isEnabled()) {
  17982. continue;
  17983. }
  17984. if (light.canAffectMesh(this)) {
  17985. this._lightSources.push(light);
  17986. }
  17987. }
  17988. this._markSubMeshesAsLightDirty();
  17989. };
  17990. AbstractMesh.prototype._resyncLighSource = function (light) {
  17991. var isIn = light.isEnabled() && light.canAffectMesh(this);
  17992. var index = this._lightSources.indexOf(light);
  17993. if (index === -1) {
  17994. if (!isIn) {
  17995. return;
  17996. }
  17997. this._lightSources.push(light);
  17998. }
  17999. else {
  18000. if (isIn) {
  18001. return;
  18002. }
  18003. this._lightSources.splice(index, 1);
  18004. }
  18005. this._markSubMeshesAsLightDirty();
  18006. };
  18007. AbstractMesh.prototype._removeLightSource = function (light) {
  18008. var index = this._lightSources.indexOf(light);
  18009. if (index === -1) {
  18010. return;
  18011. }
  18012. this._lightSources.splice(index, 1);
  18013. this._markSubMeshesAsLightDirty();
  18014. };
  18015. AbstractMesh.prototype._markSubMeshesAsDirty = function (func) {
  18016. if (!this.subMeshes) {
  18017. return;
  18018. }
  18019. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  18020. var subMesh = _a[_i];
  18021. if (subMesh._materialDefines) {
  18022. func(subMesh._materialDefines);
  18023. }
  18024. }
  18025. };
  18026. AbstractMesh.prototype._markSubMeshesAsLightDirty = function () {
  18027. this._markSubMeshesAsDirty(function (defines) { return defines.markAsLightDirty(); });
  18028. };
  18029. AbstractMesh.prototype._markSubMeshesAsAttributesDirty = function () {
  18030. this._markSubMeshesAsDirty(function (defines) { return defines.markAsAttributesDirty(); });
  18031. };
  18032. AbstractMesh.prototype._markSubMeshesAsMiscDirty = function () {
  18033. if (!this.subMeshes) {
  18034. return;
  18035. }
  18036. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  18037. var subMesh = _a[_i];
  18038. var material = subMesh.getMaterial();
  18039. if (material) {
  18040. material.markAsDirty(BABYLON.Material.MiscDirtyFlag);
  18041. }
  18042. }
  18043. };
  18044. Object.defineProperty(AbstractMesh.prototype, "scaling", {
  18045. /**
  18046. * Scaling property : a Vector3 depicting the mesh scaling along each local axis X, Y, Z.
  18047. * Default : (1.0, 1.0, 1.0)
  18048. */
  18049. get: function () {
  18050. return this._scaling;
  18051. },
  18052. /**
  18053. * Scaling property : a Vector3 depicting the mesh scaling along each local axis X, Y, Z.
  18054. * Default : (1.0, 1.0, 1.0)
  18055. */
  18056. set: function (newScaling) {
  18057. this._scaling = newScaling;
  18058. if (this.physicsImpostor) {
  18059. this.physicsImpostor.forceUpdate();
  18060. }
  18061. },
  18062. enumerable: true,
  18063. configurable: true
  18064. });
  18065. // Methods
  18066. /**
  18067. * Disables the mesh edger rendering mode.
  18068. * Returns the AbstractMesh.
  18069. */
  18070. AbstractMesh.prototype.disableEdgesRendering = function () {
  18071. if (this._edgesRenderer) {
  18072. this._edgesRenderer.dispose();
  18073. this._edgesRenderer = null;
  18074. }
  18075. return this;
  18076. };
  18077. /**
  18078. * Enables the edge rendering mode on the mesh.
  18079. * This mode makes the mesh edges visible.
  18080. * Returns the AbstractMesh.
  18081. */
  18082. AbstractMesh.prototype.enableEdgesRendering = function (epsilon, checkVerticesInsteadOfIndices) {
  18083. if (epsilon === void 0) { epsilon = 0.95; }
  18084. if (checkVerticesInsteadOfIndices === void 0) { checkVerticesInsteadOfIndices = false; }
  18085. this.disableEdgesRendering();
  18086. this._edgesRenderer = new BABYLON.EdgesRenderer(this, epsilon, checkVerticesInsteadOfIndices);
  18087. return this;
  18088. };
  18089. Object.defineProperty(AbstractMesh.prototype, "isBlocked", {
  18090. /**
  18091. * Returns true if the mesh is blocked. Used by the class Mesh.
  18092. * Returns the boolean `false` by default.
  18093. */
  18094. get: function () {
  18095. return false;
  18096. },
  18097. enumerable: true,
  18098. configurable: true
  18099. });
  18100. /**
  18101. * Returns the mesh itself by default, used by the class Mesh.
  18102. * Returned type : AbstractMesh
  18103. */
  18104. AbstractMesh.prototype.getLOD = function (camera) {
  18105. return this;
  18106. };
  18107. /**
  18108. * Returns 0 by default, used by the class Mesh.
  18109. * Returns an integer.
  18110. */
  18111. AbstractMesh.prototype.getTotalVertices = function () {
  18112. return 0;
  18113. };
  18114. /**
  18115. * Returns null by default, used by the class Mesh.
  18116. * Returned type : integer array
  18117. */
  18118. AbstractMesh.prototype.getIndices = function () {
  18119. return null;
  18120. };
  18121. /**
  18122. * Returns the array of the requested vertex data kind. Used by the class Mesh. Returns null here.
  18123. * Returned type : float array or Float32Array
  18124. */
  18125. AbstractMesh.prototype.getVerticesData = function (kind) {
  18126. return null;
  18127. };
  18128. /**
  18129. * Sets the vertex data of the mesh geometry for the requested `kind`.
  18130. * If the mesh has no geometry, a new Geometry object is set to the mesh and then passed this vertex data.
  18131. * The `data` are either a numeric array either a Float32Array.
  18132. * The parameter `updatable` is passed as is to the underlying Geometry object constructor (if initianilly none) or updater.
  18133. * 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).
  18134. * Note that a new underlying VertexBuffer object is created each call.
  18135. * If the `kind` is the `PositionKind`, the mesh BoundingInfo is renewed, so the bounding box and sphere, and the mesh World Matrix is recomputed.
  18136. *
  18137. * Possible `kind` values :
  18138. * - BABYLON.VertexBuffer.PositionKind
  18139. * - BABYLON.VertexBuffer.UVKind
  18140. * - BABYLON.VertexBuffer.UV2Kind
  18141. * - BABYLON.VertexBuffer.UV3Kind
  18142. * - BABYLON.VertexBuffer.UV4Kind
  18143. * - BABYLON.VertexBuffer.UV5Kind
  18144. * - BABYLON.VertexBuffer.UV6Kind
  18145. * - BABYLON.VertexBuffer.ColorKind
  18146. * - BABYLON.VertexBuffer.MatricesIndicesKind
  18147. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  18148. * - BABYLON.VertexBuffer.MatricesWeightsKind
  18149. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  18150. *
  18151. * Returns the Mesh.
  18152. */
  18153. AbstractMesh.prototype.setVerticesData = function (kind, data, updatable, stride) {
  18154. return this;
  18155. };
  18156. /**
  18157. * Updates the existing vertex data of the mesh geometry for the requested `kind`.
  18158. * If the mesh has no geometry, it is simply returned as it is.
  18159. * The `data` are either a numeric array either a Float32Array.
  18160. * No new underlying VertexBuffer object is created.
  18161. * 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.
  18162. * If the parameter `makeItUnique` is true, a new global geometry is created from this positions and is set to the mesh.
  18163. *
  18164. * Possible `kind` values :
  18165. * - BABYLON.VertexBuffer.PositionKind
  18166. * - BABYLON.VertexBuffer.UVKind
  18167. * - BABYLON.VertexBuffer.UV2Kind
  18168. * - BABYLON.VertexBuffer.UV3Kind
  18169. * - BABYLON.VertexBuffer.UV4Kind
  18170. * - BABYLON.VertexBuffer.UV5Kind
  18171. * - BABYLON.VertexBuffer.UV6Kind
  18172. * - BABYLON.VertexBuffer.ColorKind
  18173. * - BABYLON.VertexBuffer.MatricesIndicesKind
  18174. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  18175. * - BABYLON.VertexBuffer.MatricesWeightsKind
  18176. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  18177. *
  18178. * Returns the Mesh.
  18179. */
  18180. AbstractMesh.prototype.updateVerticesData = function (kind, data, updateExtends, makeItUnique) {
  18181. return this;
  18182. };
  18183. /**
  18184. * Sets the mesh indices.
  18185. * Expects an array populated with integers or a typed array (Int32Array, Uint32Array, Uint16Array).
  18186. * If the mesh has no geometry, a new Geometry object is created and set to the mesh.
  18187. * This method creates a new index buffer each call.
  18188. * Returns the Mesh.
  18189. */
  18190. AbstractMesh.prototype.setIndices = function (indices, totalVertices) {
  18191. return this;
  18192. };
  18193. /** Returns false by default, used by the class Mesh.
  18194. * Returns a boolean
  18195. */
  18196. AbstractMesh.prototype.isVerticesDataPresent = function (kind) {
  18197. return false;
  18198. };
  18199. /**
  18200. * Returns the mesh BoundingInfo object or creates a new one and returns it if undefined.
  18201. * Returns a BoundingInfo
  18202. */
  18203. AbstractMesh.prototype.getBoundingInfo = function () {
  18204. if (this._masterMesh) {
  18205. return this._masterMesh.getBoundingInfo();
  18206. }
  18207. if (!this._boundingInfo) {
  18208. // this._boundingInfo is being created here
  18209. this._updateBoundingInfo();
  18210. }
  18211. // cannot be null.
  18212. return this._boundingInfo;
  18213. };
  18214. /**
  18215. * Uniformly scales the mesh to fit inside of a unit cube (1 X 1 X 1 units).
  18216. * @param includeDescendants Take the hierarchy's bounding box instead of the mesh's bounding box.
  18217. */
  18218. AbstractMesh.prototype.normalizeToUnitCube = function (includeDescendants) {
  18219. if (includeDescendants === void 0) { includeDescendants = true; }
  18220. var boundingVectors = this.getHierarchyBoundingVectors(includeDescendants);
  18221. var sizeVec = boundingVectors.max.subtract(boundingVectors.min);
  18222. var maxDimension = Math.max(sizeVec.x, sizeVec.y, sizeVec.z);
  18223. if (maxDimension === 0) {
  18224. return this;
  18225. }
  18226. var scale = 1 / maxDimension;
  18227. this.scaling.scaleInPlace(scale);
  18228. return this;
  18229. };
  18230. /**
  18231. * Sets a mesh new object BoundingInfo.
  18232. * Returns the AbstractMesh.
  18233. */
  18234. AbstractMesh.prototype.setBoundingInfo = function (boundingInfo) {
  18235. this._boundingInfo = boundingInfo;
  18236. return this;
  18237. };
  18238. Object.defineProperty(AbstractMesh.prototype, "useBones", {
  18239. get: function () {
  18240. return (this.skeleton && this.getScene().skeletonsEnabled && this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind) && this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind));
  18241. },
  18242. enumerable: true,
  18243. configurable: true
  18244. });
  18245. AbstractMesh.prototype._preActivate = function () {
  18246. };
  18247. AbstractMesh.prototype._preActivateForIntermediateRendering = function (renderId) {
  18248. };
  18249. AbstractMesh.prototype._activate = function (renderId) {
  18250. this._renderId = renderId;
  18251. };
  18252. /**
  18253. * Returns the latest update of the World matrix
  18254. * Returns a Matrix.
  18255. */
  18256. AbstractMesh.prototype.getWorldMatrix = function () {
  18257. if (this._masterMesh) {
  18258. return this._masterMesh.getWorldMatrix();
  18259. }
  18260. return _super.prototype.getWorldMatrix.call(this);
  18261. };
  18262. /**
  18263. * Returns the latest update of the World matrix determinant.
  18264. */
  18265. AbstractMesh.prototype._getWorldMatrixDeterminant = function () {
  18266. if (this._masterMesh) {
  18267. return this._masterMesh._getWorldMatrixDeterminant();
  18268. }
  18269. return _super.prototype._getWorldMatrixDeterminant.call(this);
  18270. };
  18271. // ================================== Point of View Movement =================================
  18272. /**
  18273. * Perform relative position change from the point of view of behind the front of the mesh.
  18274. * This is performed taking into account the meshes current rotation, so you do not have to care.
  18275. * Supports definition of mesh facing forward or backward.
  18276. * @param {number} amountRight
  18277. * @param {number} amountUp
  18278. * @param {number} amountForward
  18279. *
  18280. * Returns the AbstractMesh.
  18281. */
  18282. AbstractMesh.prototype.movePOV = function (amountRight, amountUp, amountForward) {
  18283. this.position.addInPlace(this.calcMovePOV(amountRight, amountUp, amountForward));
  18284. return this;
  18285. };
  18286. /**
  18287. * Calculate relative position change from the point of view of behind the front of the mesh.
  18288. * This is performed taking into account the meshes current rotation, so you do not have to care.
  18289. * Supports definition of mesh facing forward or backward.
  18290. * @param {number} amountRight
  18291. * @param {number} amountUp
  18292. * @param {number} amountForward
  18293. *
  18294. * Returns a new Vector3.
  18295. */
  18296. AbstractMesh.prototype.calcMovePOV = function (amountRight, amountUp, amountForward) {
  18297. var rotMatrix = new BABYLON.Matrix();
  18298. var rotQuaternion = (this.rotationQuaternion) ? this.rotationQuaternion : BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z);
  18299. rotQuaternion.toRotationMatrix(rotMatrix);
  18300. var translationDelta = BABYLON.Vector3.Zero();
  18301. var defForwardMult = this.definedFacingForward ? -1 : 1;
  18302. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(amountRight * defForwardMult, amountUp, amountForward * defForwardMult, rotMatrix, translationDelta);
  18303. return translationDelta;
  18304. };
  18305. // ================================== Point of View Rotation =================================
  18306. /**
  18307. * Perform relative rotation change from the point of view of behind the front of the mesh.
  18308. * Supports definition of mesh facing forward or backward.
  18309. * @param {number} flipBack
  18310. * @param {number} twirlClockwise
  18311. * @param {number} tiltRight
  18312. *
  18313. * Returns the AbstractMesh.
  18314. */
  18315. AbstractMesh.prototype.rotatePOV = function (flipBack, twirlClockwise, tiltRight) {
  18316. this.rotation.addInPlace(this.calcRotatePOV(flipBack, twirlClockwise, tiltRight));
  18317. return this;
  18318. };
  18319. /**
  18320. * Calculate relative rotation change from the point of view of behind the front of the mesh.
  18321. * Supports definition of mesh facing forward or backward.
  18322. * @param {number} flipBack
  18323. * @param {number} twirlClockwise
  18324. * @param {number} tiltRight
  18325. *
  18326. * Returns a new Vector3.
  18327. */
  18328. AbstractMesh.prototype.calcRotatePOV = function (flipBack, twirlClockwise, tiltRight) {
  18329. var defForwardMult = this.definedFacingForward ? 1 : -1;
  18330. return new BABYLON.Vector3(flipBack * defForwardMult, twirlClockwise, tiltRight * defForwardMult);
  18331. };
  18332. /**
  18333. * Return the minimum and maximum world vectors of the entire hierarchy under current mesh
  18334. * @param includeDescendants Include bounding info from descendants as well (true by default).
  18335. */
  18336. AbstractMesh.prototype.getHierarchyBoundingVectors = function (includeDescendants) {
  18337. if (includeDescendants === void 0) { includeDescendants = true; }
  18338. this.computeWorldMatrix(true);
  18339. var min;
  18340. var max;
  18341. var boundingInfo = this.getBoundingInfo();
  18342. if (!this.subMeshes) {
  18343. min = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  18344. max = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  18345. }
  18346. else {
  18347. min = boundingInfo.boundingBox.minimumWorld;
  18348. max = boundingInfo.boundingBox.maximumWorld;
  18349. }
  18350. if (includeDescendants) {
  18351. var descendants = this.getDescendants(false);
  18352. for (var _i = 0, descendants_1 = descendants; _i < descendants_1.length; _i++) {
  18353. var descendant = descendants_1[_i];
  18354. var childMesh = descendant;
  18355. childMesh.computeWorldMatrix(true);
  18356. //make sure we have the needed params to get mix and max
  18357. if (!childMesh.getBoundingInfo || childMesh.getTotalVertices() === 0) {
  18358. continue;
  18359. }
  18360. var childBoundingInfo = childMesh.getBoundingInfo();
  18361. var boundingBox = childBoundingInfo.boundingBox;
  18362. var minBox = boundingBox.minimumWorld;
  18363. var maxBox = boundingBox.maximumWorld;
  18364. BABYLON.Tools.CheckExtends(minBox, min, max);
  18365. BABYLON.Tools.CheckExtends(maxBox, min, max);
  18366. }
  18367. }
  18368. return {
  18369. min: min,
  18370. max: max
  18371. };
  18372. };
  18373. /**
  18374. * Updates the mesh BoundingInfo object and all its children BoundingInfo objects also.
  18375. * Returns the AbstractMesh.
  18376. */
  18377. AbstractMesh.prototype._updateBoundingInfo = function () {
  18378. this._boundingInfo = this._boundingInfo || new BABYLON.BoundingInfo(this.absolutePosition, this.absolutePosition);
  18379. this._boundingInfo.update(this.worldMatrixFromCache);
  18380. this._updateSubMeshesBoundingInfo(this.worldMatrixFromCache);
  18381. return this;
  18382. };
  18383. /**
  18384. * Update a mesh's children BoundingInfo objects only.
  18385. * Returns the AbstractMesh.
  18386. */
  18387. AbstractMesh.prototype._updateSubMeshesBoundingInfo = function (matrix) {
  18388. if (!this.subMeshes) {
  18389. return this;
  18390. }
  18391. for (var subIndex = 0; subIndex < this.subMeshes.length; subIndex++) {
  18392. var subMesh = this.subMeshes[subIndex];
  18393. if (!subMesh.IsGlobal) {
  18394. subMesh.updateBoundingInfo(matrix);
  18395. }
  18396. }
  18397. return this;
  18398. };
  18399. AbstractMesh.prototype._afterComputeWorldMatrix = function () {
  18400. // Bounding info
  18401. this._updateBoundingInfo();
  18402. };
  18403. /**
  18404. * Returns `true` if the mesh is within the frustum defined by the passed array of planes.
  18405. * A mesh is in the frustum if its bounding box intersects the frustum.
  18406. * Boolean returned.
  18407. */
  18408. AbstractMesh.prototype.isInFrustum = function (frustumPlanes) {
  18409. return this._boundingInfo !== null && this._boundingInfo.isInFrustum(frustumPlanes);
  18410. };
  18411. /**
  18412. * Returns `true` if the mesh is completely in the frustum defined be the passed array of planes.
  18413. * A mesh is completely in the frustum if its bounding box it completely inside the frustum.
  18414. * Boolean returned.
  18415. */
  18416. AbstractMesh.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  18417. return this._boundingInfo !== null && this._boundingInfo.isCompletelyInFrustum(frustumPlanes);
  18418. ;
  18419. };
  18420. /**
  18421. * True if the mesh intersects another mesh or a SolidParticle object.
  18422. * 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)
  18423. * includeDescendants can be set to true to test if the mesh defined in parameters intersects with the current mesh or any child meshes
  18424. * Returns a boolean.
  18425. */
  18426. AbstractMesh.prototype.intersectsMesh = function (mesh, precise, includeDescendants) {
  18427. if (precise === void 0) { precise = false; }
  18428. if (!this._boundingInfo || !mesh._boundingInfo) {
  18429. return false;
  18430. }
  18431. if (this._boundingInfo.intersects(mesh._boundingInfo, precise)) {
  18432. return true;
  18433. }
  18434. if (includeDescendants) {
  18435. for (var _i = 0, _a = this.getChildMeshes(); _i < _a.length; _i++) {
  18436. var child = _a[_i];
  18437. if (child.intersectsMesh(mesh, precise, true)) {
  18438. return true;
  18439. }
  18440. }
  18441. }
  18442. return false;
  18443. };
  18444. /**
  18445. * Returns true if the passed point (Vector3) is inside the mesh bounding box.
  18446. * Returns a boolean.
  18447. */
  18448. AbstractMesh.prototype.intersectsPoint = function (point) {
  18449. if (!this._boundingInfo) {
  18450. return false;
  18451. }
  18452. return this._boundingInfo.intersectsPoint(point);
  18453. };
  18454. AbstractMesh.prototype.getPhysicsImpostor = function () {
  18455. return this.physicsImpostor;
  18456. };
  18457. AbstractMesh.prototype.getPositionInCameraSpace = function (camera) {
  18458. if (camera === void 0) { camera = null; }
  18459. if (!camera) {
  18460. camera = this.getScene().activeCamera;
  18461. }
  18462. return BABYLON.Vector3.TransformCoordinates(this.absolutePosition, camera.getViewMatrix());
  18463. };
  18464. /**
  18465. * Returns the distance from the mesh to the active camera.
  18466. * Returns a float.
  18467. */
  18468. AbstractMesh.prototype.getDistanceToCamera = function (camera) {
  18469. if (camera === void 0) { camera = null; }
  18470. if (!camera) {
  18471. camera = this.getScene().activeCamera;
  18472. }
  18473. return this.absolutePosition.subtract(camera.position).length();
  18474. };
  18475. AbstractMesh.prototype.applyImpulse = function (force, contactPoint) {
  18476. if (!this.physicsImpostor) {
  18477. return this;
  18478. }
  18479. this.physicsImpostor.applyImpulse(force, contactPoint);
  18480. return this;
  18481. };
  18482. AbstractMesh.prototype.setPhysicsLinkWith = function (otherMesh, pivot1, pivot2, options) {
  18483. if (!this.physicsImpostor || !otherMesh.physicsImpostor) {
  18484. return this;
  18485. }
  18486. this.physicsImpostor.createJoint(otherMesh.physicsImpostor, BABYLON.PhysicsJoint.HingeJoint, {
  18487. mainPivot: pivot1,
  18488. connectedPivot: pivot2,
  18489. nativeParams: options
  18490. });
  18491. return this;
  18492. };
  18493. Object.defineProperty(AbstractMesh.prototype, "checkCollisions", {
  18494. // Collisions
  18495. /**
  18496. * Property checkCollisions : Boolean, whether the camera should check the collisions against the mesh.
  18497. * Default `false`.
  18498. */
  18499. get: function () {
  18500. return this._checkCollisions;
  18501. },
  18502. set: function (collisionEnabled) {
  18503. this._checkCollisions = collisionEnabled;
  18504. if (this.getScene().workerCollisions) {
  18505. this.getScene().collisionCoordinator.onMeshUpdated(this);
  18506. }
  18507. },
  18508. enumerable: true,
  18509. configurable: true
  18510. });
  18511. Object.defineProperty(AbstractMesh.prototype, "collider", {
  18512. /**
  18513. * Gets Collider object used to compute collisions (not physics)
  18514. */
  18515. get: function () {
  18516. return this._collider;
  18517. },
  18518. enumerable: true,
  18519. configurable: true
  18520. });
  18521. AbstractMesh.prototype.moveWithCollisions = function (displacement) {
  18522. var globalPosition = this.getAbsolutePosition();
  18523. globalPosition.addToRef(this.ellipsoidOffset, this._oldPositionForCollisions);
  18524. if (!this._collider) {
  18525. this._collider = new BABYLON.Collider();
  18526. }
  18527. this._collider._radius = this.ellipsoid;
  18528. this.getScene().collisionCoordinator.getNewPosition(this._oldPositionForCollisions, displacement, this._collider, 3, this, this._onCollisionPositionChange, this.uniqueId);
  18529. return this;
  18530. };
  18531. // Submeshes octree
  18532. /**
  18533. * This function will create an octree to help to select the right submeshes for rendering, picking and collision computations.
  18534. * Please note that you must have a decent number of submeshes to get performance improvements when using an octree.
  18535. * Returns an Octree of submeshes.
  18536. */
  18537. AbstractMesh.prototype.createOrUpdateSubmeshesOctree = function (maxCapacity, maxDepth) {
  18538. if (maxCapacity === void 0) { maxCapacity = 64; }
  18539. if (maxDepth === void 0) { maxDepth = 2; }
  18540. if (!this._submeshesOctree) {
  18541. this._submeshesOctree = new BABYLON.Octree(BABYLON.Octree.CreationFuncForSubMeshes, maxCapacity, maxDepth);
  18542. }
  18543. this.computeWorldMatrix(true);
  18544. var boundingInfo = this.getBoundingInfo();
  18545. // Update octree
  18546. var bbox = boundingInfo.boundingBox;
  18547. this._submeshesOctree.update(bbox.minimumWorld, bbox.maximumWorld, this.subMeshes);
  18548. return this._submeshesOctree;
  18549. };
  18550. // Collisions
  18551. AbstractMesh.prototype._collideForSubMesh = function (subMesh, transformMatrix, collider) {
  18552. this._generatePointsArray();
  18553. if (!this._positions) {
  18554. return this;
  18555. }
  18556. // Transformation
  18557. if (!subMesh._lastColliderWorldVertices || !subMesh._lastColliderTransformMatrix.equals(transformMatrix)) {
  18558. subMesh._lastColliderTransformMatrix = transformMatrix.clone();
  18559. subMesh._lastColliderWorldVertices = [];
  18560. subMesh._trianglePlanes = [];
  18561. var start = subMesh.verticesStart;
  18562. var end = (subMesh.verticesStart + subMesh.verticesCount);
  18563. for (var i = start; i < end; i++) {
  18564. subMesh._lastColliderWorldVertices.push(BABYLON.Vector3.TransformCoordinates(this._positions[i], transformMatrix));
  18565. }
  18566. }
  18567. // Collide
  18568. collider._collide(subMesh._trianglePlanes, subMesh._lastColliderWorldVertices, this.getIndices(), subMesh.indexStart, subMesh.indexStart + subMesh.indexCount, subMesh.verticesStart, !!subMesh.getMaterial());
  18569. if (collider.collisionFound) {
  18570. collider.collidedMesh = this;
  18571. }
  18572. return this;
  18573. };
  18574. AbstractMesh.prototype._processCollisionsForSubMeshes = function (collider, transformMatrix) {
  18575. var subMeshes;
  18576. var len;
  18577. // Octrees
  18578. if (this._submeshesOctree && this.useOctreeForCollisions) {
  18579. var radius = collider._velocityWorldLength + Math.max(collider._radius.x, collider._radius.y, collider._radius.z);
  18580. var intersections = this._submeshesOctree.intersects(collider._basePointWorld, radius);
  18581. len = intersections.length;
  18582. subMeshes = intersections.data;
  18583. }
  18584. else {
  18585. subMeshes = this.subMeshes;
  18586. len = subMeshes.length;
  18587. }
  18588. for (var index = 0; index < len; index++) {
  18589. var subMesh = subMeshes[index];
  18590. // Bounding test
  18591. if (len > 1 && !subMesh._checkCollision(collider))
  18592. continue;
  18593. this._collideForSubMesh(subMesh, transformMatrix, collider);
  18594. }
  18595. return this;
  18596. };
  18597. AbstractMesh.prototype._checkCollision = function (collider) {
  18598. // Bounding box test
  18599. if (!this._boundingInfo || !this._boundingInfo._checkCollision(collider))
  18600. return this;
  18601. // Transformation matrix
  18602. BABYLON.Matrix.ScalingToRef(1.0 / collider._radius.x, 1.0 / collider._radius.y, 1.0 / collider._radius.z, this._collisionsScalingMatrix);
  18603. this.worldMatrixFromCache.multiplyToRef(this._collisionsScalingMatrix, this._collisionsTransformMatrix);
  18604. this._processCollisionsForSubMeshes(collider, this._collisionsTransformMatrix);
  18605. return this;
  18606. };
  18607. // Picking
  18608. AbstractMesh.prototype._generatePointsArray = function () {
  18609. return false;
  18610. };
  18611. /**
  18612. * Checks if the passed Ray intersects with the mesh.
  18613. * Returns an object PickingInfo.
  18614. */
  18615. AbstractMesh.prototype.intersects = function (ray, fastCheck) {
  18616. var pickingInfo = new BABYLON.PickingInfo();
  18617. if (!this.subMeshes || !this._boundingInfo || !ray.intersectsSphere(this._boundingInfo.boundingSphere) || !ray.intersectsBox(this._boundingInfo.boundingBox)) {
  18618. return pickingInfo;
  18619. }
  18620. if (!this._generatePointsArray()) {
  18621. return pickingInfo;
  18622. }
  18623. var intersectInfo = null;
  18624. // Octrees
  18625. var subMeshes;
  18626. var len;
  18627. if (this._submeshesOctree && this.useOctreeForPicking) {
  18628. var worldRay = BABYLON.Ray.Transform(ray, this.getWorldMatrix());
  18629. var intersections = this._submeshesOctree.intersectsRay(worldRay);
  18630. len = intersections.length;
  18631. subMeshes = intersections.data;
  18632. }
  18633. else {
  18634. subMeshes = this.subMeshes;
  18635. len = subMeshes.length;
  18636. }
  18637. for (var index = 0; index < len; index++) {
  18638. var subMesh = subMeshes[index];
  18639. // Bounding test
  18640. if (len > 1 && !subMesh.canIntersects(ray))
  18641. continue;
  18642. var currentIntersectInfo = subMesh.intersects(ray, this._positions, this.getIndices(), fastCheck);
  18643. if (currentIntersectInfo) {
  18644. if (fastCheck || !intersectInfo || currentIntersectInfo.distance < intersectInfo.distance) {
  18645. intersectInfo = currentIntersectInfo;
  18646. intersectInfo.subMeshId = index;
  18647. if (fastCheck) {
  18648. break;
  18649. }
  18650. }
  18651. }
  18652. }
  18653. if (intersectInfo) {
  18654. // Get picked point
  18655. var world = this.getWorldMatrix();
  18656. var worldOrigin = BABYLON.Vector3.TransformCoordinates(ray.origin, world);
  18657. var direction = ray.direction.clone();
  18658. direction = direction.scale(intersectInfo.distance);
  18659. var worldDirection = BABYLON.Vector3.TransformNormal(direction, world);
  18660. var pickedPoint = worldOrigin.add(worldDirection);
  18661. // Return result
  18662. pickingInfo.hit = true;
  18663. pickingInfo.distance = BABYLON.Vector3.Distance(worldOrigin, pickedPoint);
  18664. pickingInfo.pickedPoint = pickedPoint;
  18665. pickingInfo.pickedMesh = this;
  18666. pickingInfo.bu = intersectInfo.bu || 0;
  18667. pickingInfo.bv = intersectInfo.bv || 0;
  18668. pickingInfo.faceId = intersectInfo.faceId;
  18669. pickingInfo.subMeshId = intersectInfo.subMeshId;
  18670. return pickingInfo;
  18671. }
  18672. return pickingInfo;
  18673. };
  18674. /**
  18675. * Clones the mesh, used by the class Mesh.
  18676. * Just returns `null` for an AbstractMesh.
  18677. */
  18678. AbstractMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  18679. return null;
  18680. };
  18681. /**
  18682. * Disposes all the mesh submeshes.
  18683. * Returns the AbstractMesh.
  18684. */
  18685. AbstractMesh.prototype.releaseSubMeshes = function () {
  18686. if (this.subMeshes) {
  18687. while (this.subMeshes.length) {
  18688. this.subMeshes[0].dispose();
  18689. }
  18690. }
  18691. else {
  18692. this.subMeshes = new Array();
  18693. }
  18694. return this;
  18695. };
  18696. /**
  18697. * Releases resources associated with this abstract mesh.
  18698. * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default)
  18699. * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default)
  18700. */
  18701. AbstractMesh.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  18702. var _this = this;
  18703. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  18704. var index;
  18705. // Smart Array Retainers.
  18706. this.getScene().freeActiveMeshes();
  18707. this.getScene().freeRenderingGroups();
  18708. // Action manager
  18709. if (this.actionManager !== undefined && this.actionManager !== null) {
  18710. this.actionManager.dispose();
  18711. this.actionManager = null;
  18712. }
  18713. // Skeleton
  18714. this._skeleton = null;
  18715. // Physics
  18716. if (this.physicsImpostor) {
  18717. this.physicsImpostor.dispose();
  18718. }
  18719. // Intersections in progress
  18720. for (index = 0; index < this._intersectionsInProgress.length; index++) {
  18721. var other = this._intersectionsInProgress[index];
  18722. var pos = other._intersectionsInProgress.indexOf(this);
  18723. other._intersectionsInProgress.splice(pos, 1);
  18724. }
  18725. this._intersectionsInProgress = [];
  18726. // Lights
  18727. var lights = this.getScene().lights;
  18728. lights.forEach(function (light) {
  18729. var meshIndex = light.includedOnlyMeshes.indexOf(_this);
  18730. if (meshIndex !== -1) {
  18731. light.includedOnlyMeshes.splice(meshIndex, 1);
  18732. }
  18733. meshIndex = light.excludedMeshes.indexOf(_this);
  18734. if (meshIndex !== -1) {
  18735. light.excludedMeshes.splice(meshIndex, 1);
  18736. }
  18737. // Shadow generators
  18738. var generator = light.getShadowGenerator();
  18739. if (generator) {
  18740. var shadowMap = generator.getShadowMap();
  18741. if (shadowMap && shadowMap.renderList) {
  18742. meshIndex = shadowMap.renderList.indexOf(_this);
  18743. if (meshIndex !== -1) {
  18744. shadowMap.renderList.splice(meshIndex, 1);
  18745. }
  18746. }
  18747. }
  18748. });
  18749. // Edges
  18750. if (this._edgesRenderer) {
  18751. this._edgesRenderer.dispose();
  18752. this._edgesRenderer = null;
  18753. }
  18754. // SubMeshes
  18755. if (this.getClassName() !== "InstancedMesh") {
  18756. this.releaseSubMeshes();
  18757. }
  18758. // Octree
  18759. var sceneOctree = this.getScene().selectionOctree;
  18760. if (sceneOctree !== undefined && sceneOctree !== null) {
  18761. var index = sceneOctree.dynamicContent.indexOf(this);
  18762. if (index !== -1) {
  18763. sceneOctree.dynamicContent.splice(index, 1);
  18764. }
  18765. }
  18766. // Query
  18767. var engine = this.getScene().getEngine();
  18768. if (this._occlusionQuery) {
  18769. this._isOcclusionQueryInProgress = false;
  18770. engine.deleteQuery(this._occlusionQuery);
  18771. this._occlusionQuery = null;
  18772. }
  18773. // Engine
  18774. engine.wipeCaches();
  18775. // Remove from scene
  18776. this.getScene().removeMesh(this);
  18777. if (disposeMaterialAndTextures) {
  18778. if (this.material) {
  18779. this.material.dispose(false, true);
  18780. }
  18781. }
  18782. if (!doNotRecurse) {
  18783. // Particles
  18784. for (index = 0; index < this.getScene().particleSystems.length; index++) {
  18785. if (this.getScene().particleSystems[index].emitter === this) {
  18786. this.getScene().particleSystems[index].dispose();
  18787. index--;
  18788. }
  18789. }
  18790. }
  18791. // facet data
  18792. if (this._facetDataEnabled) {
  18793. this.disableFacetData();
  18794. }
  18795. this.onAfterWorldMatrixUpdateObservable.clear();
  18796. this.onCollideObservable.clear();
  18797. this.onCollisionPositionChangeObservable.clear();
  18798. _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
  18799. };
  18800. /**
  18801. * Adds the passed mesh as a child to the current mesh.
  18802. * Returns the AbstractMesh.
  18803. */
  18804. AbstractMesh.prototype.addChild = function (mesh) {
  18805. mesh.setParent(this);
  18806. return this;
  18807. };
  18808. /**
  18809. * Removes the passed mesh from the current mesh children list.
  18810. * Returns the AbstractMesh.
  18811. */
  18812. AbstractMesh.prototype.removeChild = function (mesh) {
  18813. mesh.setParent(null);
  18814. return this;
  18815. };
  18816. // Facet data
  18817. /**
  18818. * Initialize the facet data arrays : facetNormals, facetPositions and facetPartitioning.
  18819. * Returns the AbstractMesh.
  18820. */
  18821. AbstractMesh.prototype._initFacetData = function () {
  18822. if (!this._facetNormals) {
  18823. this._facetNormals = new Array();
  18824. }
  18825. if (!this._facetPositions) {
  18826. this._facetPositions = new Array();
  18827. }
  18828. if (!this._facetPartitioning) {
  18829. this._facetPartitioning = new Array();
  18830. }
  18831. this._facetNb = (this.getIndices().length / 3) | 0;
  18832. this._partitioningSubdivisions = (this._partitioningSubdivisions) ? this._partitioningSubdivisions : 10; // default nb of partitioning subdivisions = 10
  18833. this._partitioningBBoxRatio = (this._partitioningBBoxRatio) ? this._partitioningBBoxRatio : 1.01; // default ratio 1.01 = the partitioning is 1% bigger than the bounding box
  18834. for (var f = 0; f < this._facetNb; f++) {
  18835. this._facetNormals[f] = BABYLON.Vector3.Zero();
  18836. this._facetPositions[f] = BABYLON.Vector3.Zero();
  18837. }
  18838. this._facetDataEnabled = true;
  18839. return this;
  18840. };
  18841. /**
  18842. * Updates the mesh facetData arrays and the internal partitioning when the mesh is morphed or updated.
  18843. * This method can be called within the render loop.
  18844. * 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.
  18845. * Returns the AbstractMesh.
  18846. */
  18847. AbstractMesh.prototype.updateFacetData = function () {
  18848. if (!this._facetDataEnabled) {
  18849. this._initFacetData();
  18850. }
  18851. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  18852. var indices = this.getIndices();
  18853. var normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  18854. var bInfo = this.getBoundingInfo();
  18855. if (this._facetDepthSort && !this._facetDepthSortEnabled) {
  18856. // init arrays, matrix and sort function on first call
  18857. this._facetDepthSortEnabled = true;
  18858. if (indices instanceof Uint16Array) {
  18859. this._depthSortedIndices = new Uint16Array(indices);
  18860. }
  18861. else if (indices instanceof Uint32Array) {
  18862. this._depthSortedIndices = new Uint32Array(indices);
  18863. }
  18864. else {
  18865. var needs32bits = false;
  18866. for (var i = 0; i < indices.length; i++) {
  18867. if (indices[i] > 65535) {
  18868. needs32bits = true;
  18869. break;
  18870. }
  18871. }
  18872. if (needs32bits) {
  18873. this._depthSortedIndices = new Uint32Array(indices);
  18874. }
  18875. else {
  18876. this._depthSortedIndices = new Uint16Array(indices);
  18877. }
  18878. }
  18879. this._facetDepthSortFunction = function (f1, f2) {
  18880. return (f2.sqDistance - f1.sqDistance);
  18881. };
  18882. if (!this._facetDepthSortFrom) {
  18883. var camera = this.getScene().activeCamera;
  18884. this._facetDepthSortFrom = (camera) ? camera.position : BABYLON.Vector3.Zero();
  18885. }
  18886. this._depthSortedFacets = [];
  18887. for (var f = 0; f < this._facetNb; f++) {
  18888. var depthSortedFacet = { ind: f * 3, sqDistance: 0.0 };
  18889. this._depthSortedFacets.push(depthSortedFacet);
  18890. }
  18891. this._invertedMatrix = BABYLON.Matrix.Identity();
  18892. this._facetDepthSortOrigin = BABYLON.Vector3.Zero();
  18893. }
  18894. this._bbSize.x = (bInfo.maximum.x - bInfo.minimum.x > BABYLON.Epsilon) ? bInfo.maximum.x - bInfo.minimum.x : BABYLON.Epsilon;
  18895. this._bbSize.y = (bInfo.maximum.y - bInfo.minimum.y > BABYLON.Epsilon) ? bInfo.maximum.y - bInfo.minimum.y : BABYLON.Epsilon;
  18896. this._bbSize.z = (bInfo.maximum.z - bInfo.minimum.z > BABYLON.Epsilon) ? bInfo.maximum.z - bInfo.minimum.z : BABYLON.Epsilon;
  18897. var bbSizeMax = (this._bbSize.x > this._bbSize.y) ? this._bbSize.x : this._bbSize.y;
  18898. bbSizeMax = (bbSizeMax > this._bbSize.z) ? bbSizeMax : this._bbSize.z;
  18899. this._subDiv.max = this._partitioningSubdivisions;
  18900. this._subDiv.X = Math.floor(this._subDiv.max * this._bbSize.x / bbSizeMax); // adjust the number of subdivisions per axis
  18901. this._subDiv.Y = Math.floor(this._subDiv.max * this._bbSize.y / bbSizeMax); // according to each bbox size per axis
  18902. this._subDiv.Z = Math.floor(this._subDiv.max * this._bbSize.z / bbSizeMax);
  18903. this._subDiv.X = this._subDiv.X < 1 ? 1 : this._subDiv.X; // at least one subdivision
  18904. this._subDiv.Y = this._subDiv.Y < 1 ? 1 : this._subDiv.Y;
  18905. this._subDiv.Z = this._subDiv.Z < 1 ? 1 : this._subDiv.Z;
  18906. // set the parameters for ComputeNormals()
  18907. this._facetParameters.facetNormals = this.getFacetLocalNormals();
  18908. this._facetParameters.facetPositions = this.getFacetLocalPositions();
  18909. this._facetParameters.facetPartitioning = this.getFacetLocalPartitioning();
  18910. this._facetParameters.bInfo = bInfo;
  18911. this._facetParameters.bbSize = this._bbSize;
  18912. this._facetParameters.subDiv = this._subDiv;
  18913. this._facetParameters.ratio = this.partitioningBBoxRatio;
  18914. this._facetParameters.depthSort = this._facetDepthSort;
  18915. if (this._facetDepthSort && this._facetDepthSortEnabled) {
  18916. this.computeWorldMatrix(true);
  18917. this._worldMatrix.invertToRef(this._invertedMatrix);
  18918. BABYLON.Vector3.TransformCoordinatesToRef(this._facetDepthSortFrom, this._invertedMatrix, this._facetDepthSortOrigin);
  18919. this._facetParameters.distanceTo = this._facetDepthSortOrigin;
  18920. }
  18921. this._facetParameters.depthSortedFacets = this._depthSortedFacets;
  18922. BABYLON.VertexData.ComputeNormals(positions, indices, normals, this._facetParameters);
  18923. if (this._facetDepthSort && this._facetDepthSortEnabled) {
  18924. this._depthSortedFacets.sort(this._facetDepthSortFunction);
  18925. var l = (this._depthSortedIndices.length / 3) | 0;
  18926. for (var f = 0; f < l; f++) {
  18927. var sind = this._depthSortedFacets[f].ind;
  18928. this._depthSortedIndices[f * 3] = indices[sind];
  18929. this._depthSortedIndices[f * 3 + 1] = indices[sind + 1];
  18930. this._depthSortedIndices[f * 3 + 2] = indices[sind + 2];
  18931. }
  18932. this.updateIndices(this._depthSortedIndices);
  18933. }
  18934. return this;
  18935. };
  18936. /**
  18937. * Returns the facetLocalNormals array.
  18938. * The normals are expressed in the mesh local space.
  18939. */
  18940. AbstractMesh.prototype.getFacetLocalNormals = function () {
  18941. if (!this._facetNormals) {
  18942. this.updateFacetData();
  18943. }
  18944. return this._facetNormals;
  18945. };
  18946. /**
  18947. * Returns the facetLocalPositions array.
  18948. * The facet positions are expressed in the mesh local space.
  18949. */
  18950. AbstractMesh.prototype.getFacetLocalPositions = function () {
  18951. if (!this._facetPositions) {
  18952. this.updateFacetData();
  18953. }
  18954. return this._facetPositions;
  18955. };
  18956. /**
  18957. * Returns the facetLocalPartioning array.
  18958. */
  18959. AbstractMesh.prototype.getFacetLocalPartitioning = function () {
  18960. if (!this._facetPartitioning) {
  18961. this.updateFacetData();
  18962. }
  18963. return this._facetPartitioning;
  18964. };
  18965. /**
  18966. * Returns the i-th facet position in the world system.
  18967. * This method allocates a new Vector3 per call.
  18968. */
  18969. AbstractMesh.prototype.getFacetPosition = function (i) {
  18970. var pos = BABYLON.Vector3.Zero();
  18971. this.getFacetPositionToRef(i, pos);
  18972. return pos;
  18973. };
  18974. /**
  18975. * Sets the reference Vector3 with the i-th facet position in the world system.
  18976. * Returns the AbstractMesh.
  18977. */
  18978. AbstractMesh.prototype.getFacetPositionToRef = function (i, ref) {
  18979. var localPos = (this.getFacetLocalPositions())[i];
  18980. var world = this.getWorldMatrix();
  18981. BABYLON.Vector3.TransformCoordinatesToRef(localPos, world, ref);
  18982. return this;
  18983. };
  18984. /**
  18985. * Returns the i-th facet normal in the world system.
  18986. * This method allocates a new Vector3 per call.
  18987. */
  18988. AbstractMesh.prototype.getFacetNormal = function (i) {
  18989. var norm = BABYLON.Vector3.Zero();
  18990. this.getFacetNormalToRef(i, norm);
  18991. return norm;
  18992. };
  18993. /**
  18994. * Sets the reference Vector3 with the i-th facet normal in the world system.
  18995. * Returns the AbstractMesh.
  18996. */
  18997. AbstractMesh.prototype.getFacetNormalToRef = function (i, ref) {
  18998. var localNorm = (this.getFacetLocalNormals())[i];
  18999. BABYLON.Vector3.TransformNormalToRef(localNorm, this.getWorldMatrix(), ref);
  19000. return this;
  19001. };
  19002. /**
  19003. * 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).
  19004. */
  19005. AbstractMesh.prototype.getFacetsAtLocalCoordinates = function (x, y, z) {
  19006. var bInfo = this.getBoundingInfo();
  19007. var ox = Math.floor((x - bInfo.minimum.x * this._partitioningBBoxRatio) * this._subDiv.X * this._partitioningBBoxRatio / this._bbSize.x);
  19008. var oy = Math.floor((y - bInfo.minimum.y * this._partitioningBBoxRatio) * this._subDiv.Y * this._partitioningBBoxRatio / this._bbSize.y);
  19009. var oz = Math.floor((z - bInfo.minimum.z * this._partitioningBBoxRatio) * this._subDiv.Z * this._partitioningBBoxRatio / this._bbSize.z);
  19010. if (ox < 0 || ox > this._subDiv.max || oy < 0 || oy > this._subDiv.max || oz < 0 || oz > this._subDiv.max) {
  19011. return null;
  19012. }
  19013. return this._facetPartitioning[ox + this._subDiv.max * oy + this._subDiv.max * this._subDiv.max * oz];
  19014. };
  19015. /**
  19016. * Returns the closest mesh facet index at (x,y,z) World coordinates, null if not found.
  19017. * If the parameter projected (vector3) is passed, it is set as the (x,y,z) World projection on the facet.
  19018. * If checkFace is 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.
  19019. * If facing and checkFace are true, only the facet "facing" to (x, y, z) are returned : positive dot (x, y, z) * facet position.
  19020. * 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.
  19021. */
  19022. AbstractMesh.prototype.getClosestFacetAtCoordinates = function (x, y, z, projected, checkFace, facing) {
  19023. if (checkFace === void 0) { checkFace = false; }
  19024. if (facing === void 0) { facing = true; }
  19025. var world = this.getWorldMatrix();
  19026. var invMat = BABYLON.Tmp.Matrix[5];
  19027. world.invertToRef(invMat);
  19028. var invVect = BABYLON.Tmp.Vector3[8];
  19029. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, y, z, invMat, invVect); // transform (x,y,z) to coordinates in the mesh local space
  19030. var closest = this.getClosestFacetAtLocalCoordinates(invVect.x, invVect.y, invVect.z, projected, checkFace, facing);
  19031. if (projected) {
  19032. // tranform the local computed projected vector to world coordinates
  19033. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(projected.x, projected.y, projected.z, world, projected);
  19034. }
  19035. return closest;
  19036. };
  19037. /**
  19038. * Returns the closest mesh facet index at (x,y,z) local coordinates, null if not found.
  19039. * If the parameter projected (vector3) is passed, it is set as the (x,y,z) local projection on the facet.
  19040. * If checkFace is 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.
  19041. * If facing and checkFace are true, only the facet "facing" to (x, y, z) are returned : positive dot (x, y, z) * facet position.
  19042. * 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.
  19043. */
  19044. AbstractMesh.prototype.getClosestFacetAtLocalCoordinates = function (x, y, z, projected, checkFace, facing) {
  19045. if (checkFace === void 0) { checkFace = false; }
  19046. if (facing === void 0) { facing = true; }
  19047. var closest = null;
  19048. var tmpx = 0.0;
  19049. var tmpy = 0.0;
  19050. var tmpz = 0.0;
  19051. var d = 0.0; // tmp dot facet normal * facet position
  19052. var t0 = 0.0;
  19053. var projx = 0.0;
  19054. var projy = 0.0;
  19055. var projz = 0.0;
  19056. // Get all the facets in the same partitioning block than (x, y, z)
  19057. var facetPositions = this.getFacetLocalPositions();
  19058. var facetNormals = this.getFacetLocalNormals();
  19059. var facetsInBlock = this.getFacetsAtLocalCoordinates(x, y, z);
  19060. if (!facetsInBlock) {
  19061. return null;
  19062. }
  19063. // Get the closest facet to (x, y, z)
  19064. var shortest = Number.MAX_VALUE; // init distance vars
  19065. var tmpDistance = shortest;
  19066. var fib; // current facet in the block
  19067. var norm; // current facet normal
  19068. var p0; // current facet barycenter position
  19069. // loop on all the facets in the current partitioning block
  19070. for (var idx = 0; idx < facetsInBlock.length; idx++) {
  19071. fib = facetsInBlock[idx];
  19072. norm = facetNormals[fib];
  19073. p0 = facetPositions[fib];
  19074. d = (x - p0.x) * norm.x + (y - p0.y) * norm.y + (z - p0.z) * norm.z;
  19075. if (!checkFace || (checkFace && facing && d >= 0.0) || (checkFace && !facing && d <= 0.0)) {
  19076. // compute (x,y,z) projection on the facet = (projx, projy, projz)
  19077. d = norm.x * p0.x + norm.y * p0.y + norm.z * p0.z;
  19078. t0 = -(norm.x * x + norm.y * y + norm.z * z - d) / (norm.x * norm.x + norm.y * norm.y + norm.z * norm.z);
  19079. projx = x + norm.x * t0;
  19080. projy = y + norm.y * t0;
  19081. projz = z + norm.z * t0;
  19082. tmpx = projx - x;
  19083. tmpy = projy - y;
  19084. tmpz = projz - z;
  19085. tmpDistance = tmpx * tmpx + tmpy * tmpy + tmpz * tmpz; // compute length between (x, y, z) and its projection on the facet
  19086. if (tmpDistance < shortest) {
  19087. shortest = tmpDistance;
  19088. closest = fib;
  19089. if (projected) {
  19090. projected.x = projx;
  19091. projected.y = projy;
  19092. projected.z = projz;
  19093. }
  19094. }
  19095. }
  19096. }
  19097. return closest;
  19098. };
  19099. /**
  19100. * Returns the object "parameter" set with all the expected parameters for facetData computation by ComputeNormals()
  19101. */
  19102. AbstractMesh.prototype.getFacetDataParameters = function () {
  19103. return this._facetParameters;
  19104. };
  19105. /**
  19106. * Disables the feature FacetData and frees the related memory.
  19107. * Returns the AbstractMesh.
  19108. */
  19109. AbstractMesh.prototype.disableFacetData = function () {
  19110. if (this._facetDataEnabled) {
  19111. this._facetDataEnabled = false;
  19112. this._facetPositions = new Array();
  19113. this._facetNormals = new Array();
  19114. this._facetPartitioning = new Array();
  19115. this._facetParameters = null;
  19116. this._depthSortedIndices = new Uint32Array(0);
  19117. }
  19118. return this;
  19119. };
  19120. /**
  19121. * Updates the AbstractMesh indices array. Actually, used by the Mesh object.
  19122. * Returns the mesh.
  19123. */
  19124. AbstractMesh.prototype.updateIndices = function (indices) {
  19125. return this;
  19126. };
  19127. /**
  19128. * The mesh Geometry. Actually used by the Mesh object.
  19129. * Returns a blank geometry object.
  19130. */
  19131. /**
  19132. * Creates new normals data for the mesh.
  19133. * @param updatable.
  19134. */
  19135. AbstractMesh.prototype.createNormals = function (updatable) {
  19136. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  19137. var indices = this.getIndices();
  19138. var normals;
  19139. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  19140. normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  19141. }
  19142. else {
  19143. normals = [];
  19144. }
  19145. BABYLON.VertexData.ComputeNormals(positions, indices, normals, { useRightHandedSystem: this.getScene().useRightHandedSystem });
  19146. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals, updatable);
  19147. };
  19148. /**
  19149. * Align the mesh with a normal.
  19150. * Returns the mesh.
  19151. */
  19152. AbstractMesh.prototype.alignWithNormal = function (normal, upDirection) {
  19153. if (!upDirection) {
  19154. upDirection = BABYLON.Axis.Y;
  19155. }
  19156. var axisX = BABYLON.Tmp.Vector3[0];
  19157. var axisZ = BABYLON.Tmp.Vector3[1];
  19158. BABYLON.Vector3.CrossToRef(upDirection, normal, axisZ);
  19159. BABYLON.Vector3.CrossToRef(normal, axisZ, axisX);
  19160. if (this.rotationQuaternion) {
  19161. BABYLON.Quaternion.RotationQuaternionFromAxisToRef(axisX, normal, axisZ, this.rotationQuaternion);
  19162. }
  19163. else {
  19164. BABYLON.Vector3.RotationFromAxisToRef(axisX, normal, axisZ, this.rotation);
  19165. }
  19166. return this;
  19167. };
  19168. AbstractMesh.prototype.checkOcclusionQuery = function () {
  19169. var engine = this.getEngine();
  19170. if (engine.webGLVersion < 2 || this.occlusionType === AbstractMesh.OCCLUSION_TYPE_NONE) {
  19171. this._isOccluded = false;
  19172. return;
  19173. }
  19174. if (this.isOcclusionQueryInProgress && this._occlusionQuery) {
  19175. var isOcclusionQueryAvailable = engine.isQueryResultAvailable(this._occlusionQuery);
  19176. if (isOcclusionQueryAvailable) {
  19177. var occlusionQueryResult = engine.getQueryResult(this._occlusionQuery);
  19178. this._isOcclusionQueryInProgress = false;
  19179. this._occlusionInternalRetryCounter = 0;
  19180. this._isOccluded = occlusionQueryResult === 1 ? false : true;
  19181. }
  19182. else {
  19183. this._occlusionInternalRetryCounter++;
  19184. if (this.occlusionRetryCount !== -1 && this._occlusionInternalRetryCounter > this.occlusionRetryCount) {
  19185. this._isOcclusionQueryInProgress = false;
  19186. this._occlusionInternalRetryCounter = 0;
  19187. // if optimistic set isOccluded to false regardless of the status of isOccluded. (Render in the current render loop)
  19188. // if strict continue the last state of the object.
  19189. this._isOccluded = this.occlusionType === AbstractMesh.OCCLUSION_TYPE_OPTIMISTIC ? false : this._isOccluded;
  19190. }
  19191. else {
  19192. return;
  19193. }
  19194. }
  19195. }
  19196. var scene = this.getScene();
  19197. var occlusionBoundingBoxRenderer = scene.getBoundingBoxRenderer();
  19198. if (!this._occlusionQuery) {
  19199. this._occlusionQuery = engine.createQuery();
  19200. }
  19201. engine.beginOcclusionQuery(this.occlusionQueryAlgorithmType, this._occlusionQuery);
  19202. occlusionBoundingBoxRenderer.renderOcclusionBoundingBox(this);
  19203. engine.endOcclusionQuery(this.occlusionQueryAlgorithmType);
  19204. this._isOcclusionQueryInProgress = true;
  19205. };
  19206. AbstractMesh.OCCLUSION_TYPE_NONE = 0;
  19207. AbstractMesh.OCCLUSION_TYPE_OPTIMISTIC = 1;
  19208. AbstractMesh.OCCLUSION_TYPE_STRICT = 2;
  19209. AbstractMesh.OCCLUSION_ALGORITHM_TYPE_ACCURATE = 0;
  19210. AbstractMesh.OCCLUSION_ALGORITHM_TYPE_CONSERVATIVE = 1;
  19211. return AbstractMesh;
  19212. }(BABYLON.TransformNode));
  19213. BABYLON.AbstractMesh = AbstractMesh;
  19214. })(BABYLON || (BABYLON = {}));
  19215. //# sourceMappingURL=babylon.abstractMesh.js.map
  19216. "use strict";
  19217. var BABYLON;
  19218. (function (BABYLON) {
  19219. /**
  19220. * Base class of all the lights in Babylon. It groups all the generic information about lights.
  19221. * Lights are used, as you would expect, to affect how meshes are seen, in terms of both illumination and colour.
  19222. * 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.
  19223. */
  19224. var Light = /** @class */ (function (_super) {
  19225. __extends(Light, _super);
  19226. /**
  19227. * Creates a Light object in the scene.
  19228. * Documentation : http://doc.babylonjs.com/tutorials/lights
  19229. * @param name The firendly name of the light
  19230. * @param scene The scene the light belongs too
  19231. */
  19232. function Light(name, scene) {
  19233. var _this = _super.call(this, name, scene) || this;
  19234. /**
  19235. * Diffuse gives the basic color to an object.
  19236. */
  19237. _this.diffuse = new BABYLON.Color3(1.0, 1.0, 1.0);
  19238. /**
  19239. * Specular produces a highlight color on an object.
  19240. * Note: This is note affecting PBR materials.
  19241. */
  19242. _this.specular = new BABYLON.Color3(1.0, 1.0, 1.0);
  19243. /**
  19244. * Strength of the light.
  19245. * Note: By default it is define in the framework own unit.
  19246. * Note: In PBR materials the intensityMode can be use to chose what unit the intensity is defined in.
  19247. */
  19248. _this.intensity = 1.0;
  19249. /**
  19250. * Defines how far from the source the light is impacting in scene units.
  19251. * Note: Unused in PBR material as the distance light falloff is defined following the inverse squared falloff.
  19252. */
  19253. _this.range = Number.MAX_VALUE;
  19254. /**
  19255. * Cached photometric scale default to 1.0 as the automatic intensity mode defaults to 1.0 for every type
  19256. * of light.
  19257. */
  19258. _this._photometricScale = 1.0;
  19259. _this._intensityMode = Light.INTENSITYMODE_AUTOMATIC;
  19260. _this._radius = 0.00001;
  19261. /**
  19262. * Defines the rendering priority of the lights. It can help in case of fallback or number of lights
  19263. * exceeding the number allowed of the materials.
  19264. */
  19265. _this.renderPriority = 0;
  19266. /**
  19267. * Defines wether or not the shadows are enabled for this light. This can help turning off/on shadow without detaching
  19268. * the current shadow generator.
  19269. */
  19270. _this.shadowEnabled = true;
  19271. _this._excludeWithLayerMask = 0;
  19272. _this._includeOnlyWithLayerMask = 0;
  19273. _this._lightmapMode = 0;
  19274. /**
  19275. * @ignore Internal use only.
  19276. */
  19277. _this._excludedMeshesIds = new Array();
  19278. /**
  19279. * @ignore Internal use only.
  19280. */
  19281. _this._includedOnlyMeshesIds = new Array();
  19282. _this.getScene().addLight(_this);
  19283. _this._uniformBuffer = new BABYLON.UniformBuffer(_this.getScene().getEngine());
  19284. _this._buildUniformLayout();
  19285. _this.includedOnlyMeshes = new Array();
  19286. _this.excludedMeshes = new Array();
  19287. _this._resyncMeshes();
  19288. return _this;
  19289. }
  19290. Object.defineProperty(Light, "LIGHTMAP_DEFAULT", {
  19291. /**
  19292. * If every light affecting the material is in this lightmapMode,
  19293. * material.lightmapTexture adds or multiplies
  19294. * (depends on material.useLightmapAsShadowmap)
  19295. * after every other light calculations.
  19296. */
  19297. get: function () {
  19298. return Light._LIGHTMAP_DEFAULT;
  19299. },
  19300. enumerable: true,
  19301. configurable: true
  19302. });
  19303. Object.defineProperty(Light, "LIGHTMAP_SPECULAR", {
  19304. /**
  19305. * material.lightmapTexture as only diffuse lighting from this light
  19306. * adds only specular lighting from this light
  19307. * adds dynamic shadows
  19308. */
  19309. get: function () {
  19310. return Light._LIGHTMAP_SPECULAR;
  19311. },
  19312. enumerable: true,
  19313. configurable: true
  19314. });
  19315. Object.defineProperty(Light, "LIGHTMAP_SHADOWSONLY", {
  19316. /**
  19317. * material.lightmapTexture as only lighting
  19318. * no light calculation from this light
  19319. * only adds dynamic shadows from this light
  19320. */
  19321. get: function () {
  19322. return Light._LIGHTMAP_SHADOWSONLY;
  19323. },
  19324. enumerable: true,
  19325. configurable: true
  19326. });
  19327. Object.defineProperty(Light, "INTENSITYMODE_AUTOMATIC", {
  19328. /**
  19329. * Each light type uses the default quantity according to its type:
  19330. * point/spot lights use luminous intensity
  19331. * directional lights use illuminance
  19332. */
  19333. get: function () {
  19334. return Light._INTENSITYMODE_AUTOMATIC;
  19335. },
  19336. enumerable: true,
  19337. configurable: true
  19338. });
  19339. Object.defineProperty(Light, "INTENSITYMODE_LUMINOUSPOWER", {
  19340. /**
  19341. * lumen (lm)
  19342. */
  19343. get: function () {
  19344. return Light._INTENSITYMODE_LUMINOUSPOWER;
  19345. },
  19346. enumerable: true,
  19347. configurable: true
  19348. });
  19349. Object.defineProperty(Light, "INTENSITYMODE_LUMINOUSINTENSITY", {
  19350. /**
  19351. * candela (lm/sr)
  19352. */
  19353. get: function () {
  19354. return Light._INTENSITYMODE_LUMINOUSINTENSITY;
  19355. },
  19356. enumerable: true,
  19357. configurable: true
  19358. });
  19359. Object.defineProperty(Light, "INTENSITYMODE_ILLUMINANCE", {
  19360. /**
  19361. * lux (lm/m^2)
  19362. */
  19363. get: function () {
  19364. return Light._INTENSITYMODE_ILLUMINANCE;
  19365. },
  19366. enumerable: true,
  19367. configurable: true
  19368. });
  19369. Object.defineProperty(Light, "INTENSITYMODE_LUMINANCE", {
  19370. /**
  19371. * nit (cd/m^2)
  19372. */
  19373. get: function () {
  19374. return Light._INTENSITYMODE_LUMINANCE;
  19375. },
  19376. enumerable: true,
  19377. configurable: true
  19378. });
  19379. Object.defineProperty(Light, "LIGHTTYPEID_POINTLIGHT", {
  19380. /**
  19381. * Light type const id of the point light.
  19382. */
  19383. get: function () {
  19384. return Light._LIGHTTYPEID_POINTLIGHT;
  19385. },
  19386. enumerable: true,
  19387. configurable: true
  19388. });
  19389. Object.defineProperty(Light, "LIGHTTYPEID_DIRECTIONALLIGHT", {
  19390. /**
  19391. * Light type const id of the directional light.
  19392. */
  19393. get: function () {
  19394. return Light._LIGHTTYPEID_DIRECTIONALLIGHT;
  19395. },
  19396. enumerable: true,
  19397. configurable: true
  19398. });
  19399. Object.defineProperty(Light, "LIGHTTYPEID_SPOTLIGHT", {
  19400. /**
  19401. * Light type const id of the spot light.
  19402. */
  19403. get: function () {
  19404. return Light._LIGHTTYPEID_SPOTLIGHT;
  19405. },
  19406. enumerable: true,
  19407. configurable: true
  19408. });
  19409. Object.defineProperty(Light, "LIGHTTYPEID_HEMISPHERICLIGHT", {
  19410. /**
  19411. * Light type const id of the hemispheric light.
  19412. */
  19413. get: function () {
  19414. return Light._LIGHTTYPEID_HEMISPHERICLIGHT;
  19415. },
  19416. enumerable: true,
  19417. configurable: true
  19418. });
  19419. Object.defineProperty(Light.prototype, "intensityMode", {
  19420. /**
  19421. * Gets the photometric scale used to interpret the intensity.
  19422. * This is only relevant with PBR Materials where the light intensity can be defined in a physical way.
  19423. */
  19424. get: function () {
  19425. return this._intensityMode;
  19426. },
  19427. /**
  19428. * Sets the photometric scale used to interpret the intensity.
  19429. * This is only relevant with PBR Materials where the light intensity can be defined in a physical way.
  19430. */
  19431. set: function (value) {
  19432. this._intensityMode = value;
  19433. this._computePhotometricScale();
  19434. },
  19435. enumerable: true,
  19436. configurable: true
  19437. });
  19438. ;
  19439. ;
  19440. Object.defineProperty(Light.prototype, "radius", {
  19441. /**
  19442. * Gets the light radius used by PBR Materials to simulate soft area lights.
  19443. */
  19444. get: function () {
  19445. return this._radius;
  19446. },
  19447. /**
  19448. * sets the light radius used by PBR Materials to simulate soft area lights.
  19449. */
  19450. set: function (value) {
  19451. this._radius = value;
  19452. this._computePhotometricScale();
  19453. },
  19454. enumerable: true,
  19455. configurable: true
  19456. });
  19457. ;
  19458. ;
  19459. Object.defineProperty(Light.prototype, "includedOnlyMeshes", {
  19460. /**
  19461. * Gets the only meshes impacted by this light.
  19462. */
  19463. get: function () {
  19464. return this._includedOnlyMeshes;
  19465. },
  19466. /**
  19467. * Sets the only meshes impacted by this light.
  19468. */
  19469. set: function (value) {
  19470. this._includedOnlyMeshes = value;
  19471. this._hookArrayForIncludedOnly(value);
  19472. },
  19473. enumerable: true,
  19474. configurable: true
  19475. });
  19476. Object.defineProperty(Light.prototype, "excludedMeshes", {
  19477. /**
  19478. * Gets the meshes not impacted by this light.
  19479. */
  19480. get: function () {
  19481. return this._excludedMeshes;
  19482. },
  19483. /**
  19484. * Sets the meshes not impacted by this light.
  19485. */
  19486. set: function (value) {
  19487. this._excludedMeshes = value;
  19488. this._hookArrayForExcluded(value);
  19489. },
  19490. enumerable: true,
  19491. configurable: true
  19492. });
  19493. Object.defineProperty(Light.prototype, "excludeWithLayerMask", {
  19494. /**
  19495. * Gets the layer id use to find what meshes are not impacted by the light.
  19496. * Inactive if 0
  19497. */
  19498. get: function () {
  19499. return this._excludeWithLayerMask;
  19500. },
  19501. /**
  19502. * Sets the layer id use to find what meshes are not impacted by the light.
  19503. * Inactive if 0
  19504. */
  19505. set: function (value) {
  19506. this._excludeWithLayerMask = value;
  19507. this._resyncMeshes();
  19508. },
  19509. enumerable: true,
  19510. configurable: true
  19511. });
  19512. Object.defineProperty(Light.prototype, "includeOnlyWithLayerMask", {
  19513. /**
  19514. * Gets the layer id use to find what meshes are impacted by the light.
  19515. * Inactive if 0
  19516. */
  19517. get: function () {
  19518. return this._includeOnlyWithLayerMask;
  19519. },
  19520. /**
  19521. * Sets the layer id use to find what meshes are impacted by the light.
  19522. * Inactive if 0
  19523. */
  19524. set: function (value) {
  19525. this._includeOnlyWithLayerMask = value;
  19526. this._resyncMeshes();
  19527. },
  19528. enumerable: true,
  19529. configurable: true
  19530. });
  19531. Object.defineProperty(Light.prototype, "lightmapMode", {
  19532. /**
  19533. * Gets the lightmap mode of this light (should be one of the constants defined by Light.LIGHTMAP_x)
  19534. */
  19535. get: function () {
  19536. return this._lightmapMode;
  19537. },
  19538. /**
  19539. * Sets the lightmap mode of this light (should be one of the constants defined by Light.LIGHTMAP_x)
  19540. */
  19541. set: function (value) {
  19542. if (this._lightmapMode === value) {
  19543. return;
  19544. }
  19545. this._lightmapMode = value;
  19546. this._markMeshesAsLightDirty();
  19547. },
  19548. enumerable: true,
  19549. configurable: true
  19550. });
  19551. /**
  19552. * Returns the string "Light".
  19553. * @returns the class name
  19554. */
  19555. Light.prototype.getClassName = function () {
  19556. return "Light";
  19557. };
  19558. /**
  19559. * Converts the light information to a readable string for debug purpose.
  19560. * @param fullDetails Supports for multiple levels of logging within scene loading
  19561. * @returns the human readable light info
  19562. */
  19563. Light.prototype.toString = function (fullDetails) {
  19564. var ret = "Name: " + this.name;
  19565. ret += ", type: " + (["Point", "Directional", "Spot", "Hemispheric"])[this.getTypeID()];
  19566. if (this.animations) {
  19567. for (var i = 0; i < this.animations.length; i++) {
  19568. ret += ", animation[0]: " + this.animations[i].toString(fullDetails);
  19569. }
  19570. }
  19571. if (fullDetails) {
  19572. }
  19573. return ret;
  19574. };
  19575. /**
  19576. * Set the enabled state of this node.
  19577. * @param value - the new enabled state
  19578. */
  19579. Light.prototype.setEnabled = function (value) {
  19580. _super.prototype.setEnabled.call(this, value);
  19581. this._resyncMeshes();
  19582. };
  19583. /**
  19584. * Returns the Light associated shadow generator if any.
  19585. * @return the associated shadow generator.
  19586. */
  19587. Light.prototype.getShadowGenerator = function () {
  19588. return this._shadowGenerator;
  19589. };
  19590. /**
  19591. * Returns a Vector3, the absolute light position in the World.
  19592. * @returns the world space position of the light
  19593. */
  19594. Light.prototype.getAbsolutePosition = function () {
  19595. return BABYLON.Vector3.Zero();
  19596. };
  19597. /**
  19598. * Specifies if the light will affect the passed mesh.
  19599. * @param mesh The mesh to test against the light
  19600. * @return true the mesh is affected otherwise, false.
  19601. */
  19602. Light.prototype.canAffectMesh = function (mesh) {
  19603. if (!mesh) {
  19604. return true;
  19605. }
  19606. if (this.includedOnlyMeshes && this.includedOnlyMeshes.length > 0 && this.includedOnlyMeshes.indexOf(mesh) === -1) {
  19607. return false;
  19608. }
  19609. if (this.excludedMeshes && this.excludedMeshes.length > 0 && this.excludedMeshes.indexOf(mesh) !== -1) {
  19610. return false;
  19611. }
  19612. if (this.includeOnlyWithLayerMask !== 0 && (this.includeOnlyWithLayerMask & mesh.layerMask) === 0) {
  19613. return false;
  19614. }
  19615. if (this.excludeWithLayerMask !== 0 && this.excludeWithLayerMask & mesh.layerMask) {
  19616. return false;
  19617. }
  19618. return true;
  19619. };
  19620. /**
  19621. * Computes and Returns the light World matrix.
  19622. * @returns the world matrix
  19623. */
  19624. Light.prototype.getWorldMatrix = function () {
  19625. this._currentRenderId = this.getScene().getRenderId();
  19626. var worldMatrix = this._getWorldMatrix();
  19627. if (this.parent && this.parent.getWorldMatrix) {
  19628. if (!this._parentedWorldMatrix) {
  19629. this._parentedWorldMatrix = BABYLON.Matrix.Identity();
  19630. }
  19631. worldMatrix.multiplyToRef(this.parent.getWorldMatrix(), this._parentedWorldMatrix);
  19632. this._markSyncedWithParent();
  19633. return this._parentedWorldMatrix;
  19634. }
  19635. return worldMatrix;
  19636. };
  19637. /**
  19638. * Sort function to order lights for rendering.
  19639. * @param a First Light object to compare to second.
  19640. * @param b Second Light object to compare first.
  19641. * @return -1 to reduce's a's index relative to be, 0 for no change, 1 to increase a's index relative to b.
  19642. */
  19643. Light.CompareLightsPriority = function (a, b) {
  19644. //shadow-casting lights have priority over non-shadow-casting lights
  19645. //the renderPrioirty is a secondary sort criterion
  19646. if (a.shadowEnabled !== b.shadowEnabled) {
  19647. return (b.shadowEnabled ? 1 : 0) - (a.shadowEnabled ? 1 : 0);
  19648. }
  19649. return b.renderPriority - a.renderPriority;
  19650. };
  19651. /**
  19652. * Releases resources associated with this node.
  19653. * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default)
  19654. * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default)
  19655. */
  19656. Light.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  19657. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  19658. if (this._shadowGenerator) {
  19659. this._shadowGenerator.dispose();
  19660. this._shadowGenerator = null;
  19661. }
  19662. // Animations
  19663. this.getScene().stopAnimation(this);
  19664. // Remove from meshes
  19665. for (var _i = 0, _a = this.getScene().meshes; _i < _a.length; _i++) {
  19666. var mesh = _a[_i];
  19667. mesh._removeLightSource(this);
  19668. }
  19669. this._uniformBuffer.dispose();
  19670. // Remove from scene
  19671. this.getScene().removeLight(this);
  19672. _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
  19673. };
  19674. /**
  19675. * Returns the light type ID (integer).
  19676. * @returns The light Type id as a constant defines in Light.LIGHTTYPEID_x
  19677. */
  19678. Light.prototype.getTypeID = function () {
  19679. return 0;
  19680. };
  19681. /**
  19682. * Returns the intensity scaled by the Photometric Scale according to the light type and intensity mode.
  19683. * @returns the scaled intensity in intensity mode unit
  19684. */
  19685. Light.prototype.getScaledIntensity = function () {
  19686. return this._photometricScale * this.intensity;
  19687. };
  19688. /**
  19689. * Returns a new Light object, named "name", from the current one.
  19690. * @param name The name of the cloned light
  19691. * @returns the new created light
  19692. */
  19693. Light.prototype.clone = function (name) {
  19694. var constructor = Light.GetConstructorFromName(this.getTypeID(), name, this.getScene());
  19695. if (!constructor) {
  19696. return null;
  19697. }
  19698. return BABYLON.SerializationHelper.Clone(constructor, this);
  19699. };
  19700. /**
  19701. * Serializes the current light into a Serialization object.
  19702. * @returns the serialized object.
  19703. */
  19704. Light.prototype.serialize = function () {
  19705. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  19706. // Type
  19707. serializationObject.type = this.getTypeID();
  19708. // Parent
  19709. if (this.parent) {
  19710. serializationObject.parentId = this.parent.id;
  19711. }
  19712. // Inclusion / exclusions
  19713. if (this.excludedMeshes.length > 0) {
  19714. serializationObject.excludedMeshesIds = [];
  19715. this.excludedMeshes.forEach(function (mesh) {
  19716. serializationObject.excludedMeshesIds.push(mesh.id);
  19717. });
  19718. }
  19719. if (this.includedOnlyMeshes.length > 0) {
  19720. serializationObject.includedOnlyMeshesIds = [];
  19721. this.includedOnlyMeshes.forEach(function (mesh) {
  19722. serializationObject.includedOnlyMeshesIds.push(mesh.id);
  19723. });
  19724. }
  19725. // Animations
  19726. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  19727. serializationObject.ranges = this.serializeAnimationRanges();
  19728. return serializationObject;
  19729. };
  19730. /**
  19731. * Creates a new typed light from the passed type (integer) : point light = 0, directional light = 1, spot light = 2, hemispheric light = 3.
  19732. * This new light is named "name" and added to the passed scene.
  19733. * @param type Type according to the types available in Light.LIGHTTYPEID_x
  19734. * @param name The friendly name of the light
  19735. * @param scene The scene the new light will belong to
  19736. * @returns the constructor function
  19737. */
  19738. Light.GetConstructorFromName = function (type, name, scene) {
  19739. switch (type) {
  19740. case 0:
  19741. return function () { return new BABYLON.PointLight(name, BABYLON.Vector3.Zero(), scene); };
  19742. case 1:
  19743. return function () { return new BABYLON.DirectionalLight(name, BABYLON.Vector3.Zero(), scene); };
  19744. case 2:
  19745. return function () { return new BABYLON.SpotLight(name, BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), 0, 0, scene); };
  19746. case 3:
  19747. return function () { return new BABYLON.HemisphericLight(name, BABYLON.Vector3.Zero(), scene); };
  19748. }
  19749. return null;
  19750. };
  19751. /**
  19752. * Parses the passed "parsedLight" and returns a new instanced Light from this parsing.
  19753. * @param parsedLight The JSON representation of the light
  19754. * @param scene The scene to create the parsed light in
  19755. * @returns the created light after parsing
  19756. */
  19757. Light.Parse = function (parsedLight, scene) {
  19758. var constructor = Light.GetConstructorFromName(parsedLight.type, parsedLight.name, scene);
  19759. if (!constructor) {
  19760. return null;
  19761. }
  19762. var light = BABYLON.SerializationHelper.Parse(constructor, parsedLight, scene);
  19763. // Inclusion / exclusions
  19764. if (parsedLight.excludedMeshesIds) {
  19765. light._excludedMeshesIds = parsedLight.excludedMeshesIds;
  19766. }
  19767. if (parsedLight.includedOnlyMeshesIds) {
  19768. light._includedOnlyMeshesIds = parsedLight.includedOnlyMeshesIds;
  19769. }
  19770. // Parent
  19771. if (parsedLight.parentId) {
  19772. light._waitingParentId = parsedLight.parentId;
  19773. }
  19774. // Animations
  19775. if (parsedLight.animations) {
  19776. for (var animationIndex = 0; animationIndex < parsedLight.animations.length; animationIndex++) {
  19777. var parsedAnimation = parsedLight.animations[animationIndex];
  19778. light.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  19779. }
  19780. BABYLON.Node.ParseAnimationRanges(light, parsedLight, scene);
  19781. }
  19782. if (parsedLight.autoAnimate) {
  19783. scene.beginAnimation(light, parsedLight.autoAnimateFrom, parsedLight.autoAnimateTo, parsedLight.autoAnimateLoop, parsedLight.autoAnimateSpeed || 1.0);
  19784. }
  19785. return light;
  19786. };
  19787. Light.prototype._hookArrayForExcluded = function (array) {
  19788. var _this = this;
  19789. var oldPush = array.push;
  19790. array.push = function () {
  19791. var items = [];
  19792. for (var _i = 0; _i < arguments.length; _i++) {
  19793. items[_i] = arguments[_i];
  19794. }
  19795. var result = oldPush.apply(array, items);
  19796. for (var _a = 0, items_1 = items; _a < items_1.length; _a++) {
  19797. var item = items_1[_a];
  19798. item._resyncLighSource(_this);
  19799. }
  19800. return result;
  19801. };
  19802. var oldSplice = array.splice;
  19803. array.splice = function (index, deleteCount) {
  19804. var deleted = oldSplice.apply(array, [index, deleteCount]);
  19805. for (var _i = 0, deleted_1 = deleted; _i < deleted_1.length; _i++) {
  19806. var item = deleted_1[_i];
  19807. item._resyncLighSource(_this);
  19808. }
  19809. return deleted;
  19810. };
  19811. for (var _i = 0, array_1 = array; _i < array_1.length; _i++) {
  19812. var item = array_1[_i];
  19813. item._resyncLighSource(this);
  19814. }
  19815. };
  19816. Light.prototype._hookArrayForIncludedOnly = function (array) {
  19817. var _this = this;
  19818. var oldPush = array.push;
  19819. array.push = function () {
  19820. var items = [];
  19821. for (var _i = 0; _i < arguments.length; _i++) {
  19822. items[_i] = arguments[_i];
  19823. }
  19824. var result = oldPush.apply(array, items);
  19825. _this._resyncMeshes();
  19826. return result;
  19827. };
  19828. var oldSplice = array.splice;
  19829. array.splice = function (index, deleteCount) {
  19830. var deleted = oldSplice.apply(array, [index, deleteCount]);
  19831. _this._resyncMeshes();
  19832. return deleted;
  19833. };
  19834. this._resyncMeshes();
  19835. };
  19836. Light.prototype._resyncMeshes = function () {
  19837. for (var _i = 0, _a = this.getScene().meshes; _i < _a.length; _i++) {
  19838. var mesh = _a[_i];
  19839. mesh._resyncLighSource(this);
  19840. }
  19841. };
  19842. /**
  19843. * Forces the meshes to update their light related information in their rendering used effects
  19844. * @ignore Internal Use Only
  19845. */
  19846. Light.prototype._markMeshesAsLightDirty = function () {
  19847. for (var _i = 0, _a = this.getScene().meshes; _i < _a.length; _i++) {
  19848. var mesh = _a[_i];
  19849. if (mesh._lightSources.indexOf(this) !== -1) {
  19850. mesh._markSubMeshesAsLightDirty();
  19851. }
  19852. }
  19853. };
  19854. /**
  19855. * Recomputes the cached photometric scale if needed.
  19856. */
  19857. Light.prototype._computePhotometricScale = function () {
  19858. this._photometricScale = this._getPhotometricScale();
  19859. this.getScene().resetCachedMaterial();
  19860. };
  19861. /**
  19862. * Returns the Photometric Scale according to the light type and intensity mode.
  19863. */
  19864. Light.prototype._getPhotometricScale = function () {
  19865. var photometricScale = 0.0;
  19866. var lightTypeID = this.getTypeID();
  19867. //get photometric mode
  19868. var photometricMode = this.intensityMode;
  19869. if (photometricMode === Light.INTENSITYMODE_AUTOMATIC) {
  19870. if (lightTypeID === Light.LIGHTTYPEID_DIRECTIONALLIGHT) {
  19871. photometricMode = Light.INTENSITYMODE_ILLUMINANCE;
  19872. }
  19873. else {
  19874. photometricMode = Light.INTENSITYMODE_LUMINOUSINTENSITY;
  19875. }
  19876. }
  19877. //compute photometric scale
  19878. switch (lightTypeID) {
  19879. case Light.LIGHTTYPEID_POINTLIGHT:
  19880. case Light.LIGHTTYPEID_SPOTLIGHT:
  19881. switch (photometricMode) {
  19882. case Light.INTENSITYMODE_LUMINOUSPOWER:
  19883. photometricScale = 1.0 / (4.0 * Math.PI);
  19884. break;
  19885. case Light.INTENSITYMODE_LUMINOUSINTENSITY:
  19886. photometricScale = 1.0;
  19887. break;
  19888. case Light.INTENSITYMODE_LUMINANCE:
  19889. photometricScale = this.radius * this.radius;
  19890. break;
  19891. }
  19892. break;
  19893. case Light.LIGHTTYPEID_DIRECTIONALLIGHT:
  19894. switch (photometricMode) {
  19895. case Light.INTENSITYMODE_ILLUMINANCE:
  19896. photometricScale = 1.0;
  19897. break;
  19898. case Light.INTENSITYMODE_LUMINANCE:
  19899. // When radius (and therefore solid angle) is non-zero a directional lights brightness can be specified via central (peak) luminance.
  19900. // For a directional light the 'radius' defines the angular radius (in radians) rather than world-space radius (e.g. in metres).
  19901. var apexAngleRadians = this.radius;
  19902. // Impose a minimum light angular size to avoid the light becoming an infinitely small angular light source (i.e. a dirac delta function).
  19903. apexAngleRadians = Math.max(apexAngleRadians, 0.001);
  19904. var solidAngle = 2.0 * Math.PI * (1.0 - Math.cos(apexAngleRadians));
  19905. photometricScale = solidAngle;
  19906. break;
  19907. }
  19908. break;
  19909. case Light.LIGHTTYPEID_HEMISPHERICLIGHT:
  19910. // No fall off in hemisperic light.
  19911. photometricScale = 1.0;
  19912. break;
  19913. }
  19914. return photometricScale;
  19915. };
  19916. /**
  19917. * Reorder the light in the scene according to their defined priority.
  19918. * @ignore Internal Use Only
  19919. */
  19920. Light.prototype._reorderLightsInScene = function () {
  19921. var scene = this.getScene();
  19922. if (this._renderPriority != 0) {
  19923. scene.requireLightSorting = true;
  19924. }
  19925. this.getScene().sortLightsByPriority();
  19926. };
  19927. //lightmapMode Consts
  19928. Light._LIGHTMAP_DEFAULT = 0;
  19929. Light._LIGHTMAP_SPECULAR = 1;
  19930. Light._LIGHTMAP_SHADOWSONLY = 2;
  19931. // Intensity Mode Consts
  19932. Light._INTENSITYMODE_AUTOMATIC = 0;
  19933. Light._INTENSITYMODE_LUMINOUSPOWER = 1;
  19934. Light._INTENSITYMODE_LUMINOUSINTENSITY = 2;
  19935. Light._INTENSITYMODE_ILLUMINANCE = 3;
  19936. Light._INTENSITYMODE_LUMINANCE = 4;
  19937. // Light types ids const.
  19938. Light._LIGHTTYPEID_POINTLIGHT = 0;
  19939. Light._LIGHTTYPEID_DIRECTIONALLIGHT = 1;
  19940. Light._LIGHTTYPEID_SPOTLIGHT = 2;
  19941. Light._LIGHTTYPEID_HEMISPHERICLIGHT = 3;
  19942. __decorate([
  19943. BABYLON.serializeAsColor3()
  19944. ], Light.prototype, "diffuse", void 0);
  19945. __decorate([
  19946. BABYLON.serializeAsColor3()
  19947. ], Light.prototype, "specular", void 0);
  19948. __decorate([
  19949. BABYLON.serialize()
  19950. ], Light.prototype, "intensity", void 0);
  19951. __decorate([
  19952. BABYLON.serialize()
  19953. ], Light.prototype, "range", void 0);
  19954. __decorate([
  19955. BABYLON.serialize()
  19956. ], Light.prototype, "intensityMode", null);
  19957. __decorate([
  19958. BABYLON.serialize()
  19959. ], Light.prototype, "radius", null);
  19960. __decorate([
  19961. BABYLON.serialize()
  19962. ], Light.prototype, "_renderPriority", void 0);
  19963. __decorate([
  19964. BABYLON.expandToProperty("_reorderLightsInScene")
  19965. ], Light.prototype, "renderPriority", void 0);
  19966. __decorate([
  19967. BABYLON.serialize()
  19968. ], Light.prototype, "shadowEnabled", void 0);
  19969. __decorate([
  19970. BABYLON.serialize("excludeWithLayerMask")
  19971. ], Light.prototype, "_excludeWithLayerMask", void 0);
  19972. __decorate([
  19973. BABYLON.serialize("includeOnlyWithLayerMask")
  19974. ], Light.prototype, "_includeOnlyWithLayerMask", void 0);
  19975. __decorate([
  19976. BABYLON.serialize("lightmapMode")
  19977. ], Light.prototype, "_lightmapMode", void 0);
  19978. return Light;
  19979. }(BABYLON.Node));
  19980. BABYLON.Light = Light;
  19981. })(BABYLON || (BABYLON = {}));
  19982. //# sourceMappingURL=babylon.light.js.map
  19983. "use strict";
  19984. var BABYLON;
  19985. (function (BABYLON) {
  19986. var Camera = /** @class */ (function (_super) {
  19987. __extends(Camera, _super);
  19988. function Camera(name, position, scene) {
  19989. var _this = _super.call(this, name, scene) || this;
  19990. /**
  19991. * The vector the camera should consider as up.
  19992. * (default is Vector3(0, 1, 0) aka Vector3.Up())
  19993. */
  19994. _this.upVector = BABYLON.Vector3.Up();
  19995. _this.orthoLeft = null;
  19996. _this.orthoRight = null;
  19997. _this.orthoBottom = null;
  19998. _this.orthoTop = null;
  19999. /**
  20000. * FOV is set in Radians. (default is 0.8)
  20001. */
  20002. _this.fov = 0.8;
  20003. _this.minZ = 1;
  20004. _this.maxZ = 10000.0;
  20005. _this.inertia = 0.9;
  20006. _this.mode = Camera.PERSPECTIVE_CAMERA;
  20007. _this.isIntermediate = false;
  20008. _this.viewport = new BABYLON.Viewport(0, 0, 1.0, 1.0);
  20009. /**
  20010. * Restricts the camera to viewing objects with the same layerMask.
  20011. * A camera with a layerMask of 1 will render mesh.layerMask & camera.layerMask!== 0
  20012. */
  20013. _this.layerMask = 0x0FFFFFFF;
  20014. /**
  20015. * fovMode sets the camera frustum bounds to the viewport bounds. (default is FOVMODE_VERTICAL_FIXED)
  20016. */
  20017. _this.fovMode = Camera.FOVMODE_VERTICAL_FIXED;
  20018. // Camera rig members
  20019. _this.cameraRigMode = Camera.RIG_MODE_NONE;
  20020. _this._rigCameras = new Array();
  20021. _this._webvrViewMatrix = BABYLON.Matrix.Identity();
  20022. _this._skipRendering = false;
  20023. _this.customRenderTargets = new Array();
  20024. // Observables
  20025. _this.onViewMatrixChangedObservable = new BABYLON.Observable();
  20026. _this.onProjectionMatrixChangedObservable = new BABYLON.Observable();
  20027. _this.onAfterCheckInputsObservable = new BABYLON.Observable();
  20028. _this.onRestoreStateObservable = new BABYLON.Observable();
  20029. // Cache
  20030. _this._computedViewMatrix = BABYLON.Matrix.Identity();
  20031. _this._projectionMatrix = new BABYLON.Matrix();
  20032. _this._doNotComputeProjectionMatrix = false;
  20033. _this._postProcesses = new Array();
  20034. _this._transformMatrix = BABYLON.Matrix.Zero();
  20035. _this._activeMeshes = new BABYLON.SmartArray(256);
  20036. _this._globalPosition = BABYLON.Vector3.Zero();
  20037. _this._refreshFrustumPlanes = true;
  20038. _this.getScene().addCamera(_this);
  20039. if (!_this.getScene().activeCamera) {
  20040. _this.getScene().activeCamera = _this;
  20041. }
  20042. _this.position = position;
  20043. return _this;
  20044. }
  20045. Object.defineProperty(Camera, "PERSPECTIVE_CAMERA", {
  20046. get: function () {
  20047. return Camera._PERSPECTIVE_CAMERA;
  20048. },
  20049. enumerable: true,
  20050. configurable: true
  20051. });
  20052. Object.defineProperty(Camera, "ORTHOGRAPHIC_CAMERA", {
  20053. get: function () {
  20054. return Camera._ORTHOGRAPHIC_CAMERA;
  20055. },
  20056. enumerable: true,
  20057. configurable: true
  20058. });
  20059. Object.defineProperty(Camera, "FOVMODE_VERTICAL_FIXED", {
  20060. /**
  20061. * This is the default FOV mode for perspective cameras.
  20062. * This setting aligns the upper and lower bounds of the viewport to the upper and lower bounds of the camera frustum.
  20063. *
  20064. */
  20065. get: function () {
  20066. return Camera._FOVMODE_VERTICAL_FIXED;
  20067. },
  20068. enumerable: true,
  20069. configurable: true
  20070. });
  20071. Object.defineProperty(Camera, "FOVMODE_HORIZONTAL_FIXED", {
  20072. /**
  20073. * This setting aligns the left and right bounds of the viewport to the left and right bounds of the camera frustum.
  20074. *
  20075. */
  20076. get: function () {
  20077. return Camera._FOVMODE_HORIZONTAL_FIXED;
  20078. },
  20079. enumerable: true,
  20080. configurable: true
  20081. });
  20082. Object.defineProperty(Camera, "RIG_MODE_NONE", {
  20083. get: function () {
  20084. return Camera._RIG_MODE_NONE;
  20085. },
  20086. enumerable: true,
  20087. configurable: true
  20088. });
  20089. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_ANAGLYPH", {
  20090. get: function () {
  20091. return Camera._RIG_MODE_STEREOSCOPIC_ANAGLYPH;
  20092. },
  20093. enumerable: true,
  20094. configurable: true
  20095. });
  20096. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL", {
  20097. get: function () {
  20098. return Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL;
  20099. },
  20100. enumerable: true,
  20101. configurable: true
  20102. });
  20103. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED", {
  20104. get: function () {
  20105. return Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED;
  20106. },
  20107. enumerable: true,
  20108. configurable: true
  20109. });
  20110. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_OVERUNDER", {
  20111. get: function () {
  20112. return Camera._RIG_MODE_STEREOSCOPIC_OVERUNDER;
  20113. },
  20114. enumerable: true,
  20115. configurable: true
  20116. });
  20117. Object.defineProperty(Camera, "RIG_MODE_VR", {
  20118. get: function () {
  20119. return Camera._RIG_MODE_VR;
  20120. },
  20121. enumerable: true,
  20122. configurable: true
  20123. });
  20124. Object.defineProperty(Camera, "RIG_MODE_WEBVR", {
  20125. get: function () {
  20126. return Camera._RIG_MODE_WEBVR;
  20127. },
  20128. enumerable: true,
  20129. configurable: true
  20130. });
  20131. /**
  20132. * Store current camera state (fov, position, etc..)
  20133. */
  20134. Camera.prototype.storeState = function () {
  20135. this._stateStored = true;
  20136. this._storedFov = this.fov;
  20137. return this;
  20138. };
  20139. /**
  20140. * Restores the camera state values if it has been stored. You must call storeState() first
  20141. */
  20142. Camera.prototype._restoreStateValues = function () {
  20143. if (!this._stateStored) {
  20144. return false;
  20145. }
  20146. this.fov = this._storedFov;
  20147. return true;
  20148. };
  20149. /**
  20150. * Restored camera state. You must call storeState() first
  20151. */
  20152. Camera.prototype.restoreState = function () {
  20153. if (this._restoreStateValues()) {
  20154. this.onRestoreStateObservable.notifyObservers(this);
  20155. return true;
  20156. }
  20157. return false;
  20158. };
  20159. Camera.prototype.getClassName = function () {
  20160. return "Camera";
  20161. };
  20162. /**
  20163. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  20164. */
  20165. Camera.prototype.toString = function (fullDetails) {
  20166. var ret = "Name: " + this.name;
  20167. ret += ", type: " + this.getClassName();
  20168. if (this.animations) {
  20169. for (var i = 0; i < this.animations.length; i++) {
  20170. ret += ", animation[0]: " + this.animations[i].toString(fullDetails);
  20171. }
  20172. }
  20173. if (fullDetails) {
  20174. }
  20175. return ret;
  20176. };
  20177. Object.defineProperty(Camera.prototype, "globalPosition", {
  20178. get: function () {
  20179. return this._globalPosition;
  20180. },
  20181. enumerable: true,
  20182. configurable: true
  20183. });
  20184. Camera.prototype.getActiveMeshes = function () {
  20185. return this._activeMeshes;
  20186. };
  20187. Camera.prototype.isActiveMesh = function (mesh) {
  20188. return (this._activeMeshes.indexOf(mesh) !== -1);
  20189. };
  20190. /**
  20191. * Is this camera ready to be used/rendered
  20192. * @param completeCheck defines if a complete check (including post processes) has to be done (false by default)
  20193. * @return true if the camera is ready
  20194. */
  20195. Camera.prototype.isReady = function (completeCheck) {
  20196. if (completeCheck === void 0) { completeCheck = false; }
  20197. if (completeCheck) {
  20198. for (var _i = 0, _a = this._postProcesses; _i < _a.length; _i++) {
  20199. var pp = _a[_i];
  20200. if (pp && !pp.isReady()) {
  20201. return false;
  20202. }
  20203. }
  20204. }
  20205. return _super.prototype.isReady.call(this, completeCheck);
  20206. };
  20207. //Cache
  20208. Camera.prototype._initCache = function () {
  20209. _super.prototype._initCache.call(this);
  20210. this._cache.position = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  20211. this._cache.upVector = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  20212. this._cache.mode = undefined;
  20213. this._cache.minZ = undefined;
  20214. this._cache.maxZ = undefined;
  20215. this._cache.fov = undefined;
  20216. this._cache.fovMode = undefined;
  20217. this._cache.aspectRatio = undefined;
  20218. this._cache.orthoLeft = undefined;
  20219. this._cache.orthoRight = undefined;
  20220. this._cache.orthoBottom = undefined;
  20221. this._cache.orthoTop = undefined;
  20222. this._cache.renderWidth = undefined;
  20223. this._cache.renderHeight = undefined;
  20224. };
  20225. Camera.prototype._updateCache = function (ignoreParentClass) {
  20226. if (!ignoreParentClass) {
  20227. _super.prototype._updateCache.call(this);
  20228. }
  20229. this._cache.position.copyFrom(this.position);
  20230. this._cache.upVector.copyFrom(this.upVector);
  20231. };
  20232. // Synchronized
  20233. Camera.prototype._isSynchronized = function () {
  20234. return this._isSynchronizedViewMatrix() && this._isSynchronizedProjectionMatrix();
  20235. };
  20236. Camera.prototype._isSynchronizedViewMatrix = function () {
  20237. if (!_super.prototype._isSynchronized.call(this))
  20238. return false;
  20239. return this._cache.position.equals(this.position)
  20240. && this._cache.upVector.equals(this.upVector)
  20241. && this.isSynchronizedWithParent();
  20242. };
  20243. Camera.prototype._isSynchronizedProjectionMatrix = function () {
  20244. var check = this._cache.mode === this.mode
  20245. && this._cache.minZ === this.minZ
  20246. && this._cache.maxZ === this.maxZ;
  20247. if (!check) {
  20248. return false;
  20249. }
  20250. var engine = this.getEngine();
  20251. if (this.mode === Camera.PERSPECTIVE_CAMERA) {
  20252. check = this._cache.fov === this.fov
  20253. && this._cache.fovMode === this.fovMode
  20254. && this._cache.aspectRatio === engine.getAspectRatio(this);
  20255. }
  20256. else {
  20257. check = this._cache.orthoLeft === this.orthoLeft
  20258. && this._cache.orthoRight === this.orthoRight
  20259. && this._cache.orthoBottom === this.orthoBottom
  20260. && this._cache.orthoTop === this.orthoTop
  20261. && this._cache.renderWidth === engine.getRenderWidth()
  20262. && this._cache.renderHeight === engine.getRenderHeight();
  20263. }
  20264. return check;
  20265. };
  20266. // Controls
  20267. Camera.prototype.attachControl = function (element, noPreventDefault) {
  20268. };
  20269. Camera.prototype.detachControl = function (element) {
  20270. };
  20271. Camera.prototype.update = function () {
  20272. this._checkInputs();
  20273. if (this.cameraRigMode !== Camera.RIG_MODE_NONE) {
  20274. this._updateRigCameras();
  20275. }
  20276. };
  20277. Camera.prototype._checkInputs = function () {
  20278. this.onAfterCheckInputsObservable.notifyObservers(this);
  20279. };
  20280. Object.defineProperty(Camera.prototype, "rigCameras", {
  20281. get: function () {
  20282. return this._rigCameras;
  20283. },
  20284. enumerable: true,
  20285. configurable: true
  20286. });
  20287. Object.defineProperty(Camera.prototype, "rigPostProcess", {
  20288. get: function () {
  20289. return this._rigPostProcess;
  20290. },
  20291. enumerable: true,
  20292. configurable: true
  20293. });
  20294. /**
  20295. * Internal, gets the first post proces.
  20296. * @returns the first post process to be run on this camera.
  20297. */
  20298. Camera.prototype._getFirstPostProcess = function () {
  20299. for (var pp in this._postProcesses) {
  20300. if (this._postProcesses[pp] !== null) {
  20301. return this._postProcesses[pp];
  20302. }
  20303. }
  20304. return null;
  20305. };
  20306. Camera.prototype._cascadePostProcessesToRigCams = function () {
  20307. // invalidate framebuffer
  20308. var firstPostProcess = this._getFirstPostProcess();
  20309. if (firstPostProcess) {
  20310. firstPostProcess.markTextureDirty();
  20311. }
  20312. // glue the rigPostProcess to the end of the user postprocesses & assign to each sub-camera
  20313. for (var i = 0, len = this._rigCameras.length; i < len; i++) {
  20314. var cam = this._rigCameras[i];
  20315. var rigPostProcess = cam._rigPostProcess;
  20316. // for VR rig, there does not have to be a post process
  20317. if (rigPostProcess) {
  20318. var isPass = rigPostProcess instanceof BABYLON.PassPostProcess;
  20319. if (isPass) {
  20320. // any rig which has a PassPostProcess for rig[0], cannot be isIntermediate when there are also user postProcesses
  20321. cam.isIntermediate = this._postProcesses.length === 0;
  20322. }
  20323. cam._postProcesses = this._postProcesses.slice(0).concat(rigPostProcess);
  20324. rigPostProcess.markTextureDirty();
  20325. }
  20326. else {
  20327. cam._postProcesses = this._postProcesses.slice(0);
  20328. }
  20329. }
  20330. };
  20331. Camera.prototype.attachPostProcess = function (postProcess, insertAt) {
  20332. if (insertAt === void 0) { insertAt = null; }
  20333. if (!postProcess.isReusable() && this._postProcesses.indexOf(postProcess) > -1) {
  20334. BABYLON.Tools.Error("You're trying to reuse a post process not defined as reusable.");
  20335. return 0;
  20336. }
  20337. if (insertAt == null || insertAt < 0) {
  20338. this._postProcesses.push(postProcess);
  20339. }
  20340. else if (this._postProcesses[insertAt] === null) {
  20341. this._postProcesses[insertAt] = postProcess;
  20342. }
  20343. else {
  20344. this._postProcesses.splice(insertAt, 0, postProcess);
  20345. }
  20346. this._cascadePostProcessesToRigCams(); // also ensures framebuffer invalidated
  20347. return this._postProcesses.indexOf(postProcess);
  20348. };
  20349. Camera.prototype.detachPostProcess = function (postProcess) {
  20350. var idx = this._postProcesses.indexOf(postProcess);
  20351. if (idx !== -1) {
  20352. this._postProcesses[idx] = null;
  20353. }
  20354. this._cascadePostProcessesToRigCams(); // also ensures framebuffer invalidated
  20355. };
  20356. Camera.prototype.getWorldMatrix = function () {
  20357. if (!this._worldMatrix) {
  20358. this._worldMatrix = BABYLON.Matrix.Identity();
  20359. }
  20360. var viewMatrix = this.getViewMatrix();
  20361. viewMatrix.invertToRef(this._worldMatrix);
  20362. return this._worldMatrix;
  20363. };
  20364. Camera.prototype._getViewMatrix = function () {
  20365. return BABYLON.Matrix.Identity();
  20366. };
  20367. Camera.prototype.getViewMatrix = function (force) {
  20368. if (!force && this._isSynchronizedViewMatrix()) {
  20369. return this._computedViewMatrix;
  20370. }
  20371. this.updateCache();
  20372. this._computedViewMatrix = this._getViewMatrix();
  20373. this._currentRenderId = this.getScene().getRenderId();
  20374. this._refreshFrustumPlanes = true;
  20375. if (!this.parent || !this.parent.getWorldMatrix) {
  20376. this._globalPosition.copyFrom(this.position);
  20377. }
  20378. else {
  20379. if (!this._worldMatrix) {
  20380. this._worldMatrix = BABYLON.Matrix.Identity();
  20381. }
  20382. this._computedViewMatrix.invertToRef(this._worldMatrix);
  20383. this._worldMatrix.multiplyToRef(this.parent.getWorldMatrix(), this._computedViewMatrix);
  20384. this._globalPosition.copyFromFloats(this._computedViewMatrix.m[12], this._computedViewMatrix.m[13], this._computedViewMatrix.m[14]);
  20385. this._computedViewMatrix.invert();
  20386. this._markSyncedWithParent();
  20387. }
  20388. if (this._cameraRigParams && this._cameraRigParams.vrPreViewMatrix) {
  20389. this._computedViewMatrix.multiplyToRef(this._cameraRigParams.vrPreViewMatrix, this._computedViewMatrix);
  20390. }
  20391. this.onViewMatrixChangedObservable.notifyObservers(this);
  20392. return this._computedViewMatrix;
  20393. };
  20394. Camera.prototype.freezeProjectionMatrix = function (projection) {
  20395. this._doNotComputeProjectionMatrix = true;
  20396. if (projection !== undefined) {
  20397. this._projectionMatrix = projection;
  20398. }
  20399. };
  20400. ;
  20401. Camera.prototype.unfreezeProjectionMatrix = function () {
  20402. this._doNotComputeProjectionMatrix = false;
  20403. };
  20404. ;
  20405. Camera.prototype.getProjectionMatrix = function (force) {
  20406. if (this._doNotComputeProjectionMatrix || (!force && this._isSynchronizedProjectionMatrix())) {
  20407. return this._projectionMatrix;
  20408. }
  20409. // Cache
  20410. this._cache.mode = this.mode;
  20411. this._cache.minZ = this.minZ;
  20412. this._cache.maxZ = this.maxZ;
  20413. // Matrix
  20414. this._refreshFrustumPlanes = true;
  20415. var engine = this.getEngine();
  20416. var scene = this.getScene();
  20417. if (this.mode === Camera.PERSPECTIVE_CAMERA) {
  20418. this._cache.fov = this.fov;
  20419. this._cache.fovMode = this.fovMode;
  20420. this._cache.aspectRatio = engine.getAspectRatio(this);
  20421. if (this.minZ <= 0) {
  20422. this.minZ = 0.1;
  20423. }
  20424. if (scene.useRightHandedSystem) {
  20425. BABYLON.Matrix.PerspectiveFovRHToRef(this.fov, engine.getAspectRatio(this), this.minZ, this.maxZ, this._projectionMatrix, this.fovMode === Camera.FOVMODE_VERTICAL_FIXED);
  20426. }
  20427. else {
  20428. BABYLON.Matrix.PerspectiveFovLHToRef(this.fov, engine.getAspectRatio(this), this.minZ, this.maxZ, this._projectionMatrix, this.fovMode === Camera.FOVMODE_VERTICAL_FIXED);
  20429. }
  20430. }
  20431. else {
  20432. var halfWidth = engine.getRenderWidth() / 2.0;
  20433. var halfHeight = engine.getRenderHeight() / 2.0;
  20434. if (scene.useRightHandedSystem) {
  20435. BABYLON.Matrix.OrthoOffCenterRHToRef(this.orthoLeft || -halfWidth, this.orthoRight || halfWidth, this.orthoBottom || -halfHeight, this.orthoTop || halfHeight, this.minZ, this.maxZ, this._projectionMatrix);
  20436. }
  20437. else {
  20438. BABYLON.Matrix.OrthoOffCenterLHToRef(this.orthoLeft || -halfWidth, this.orthoRight || halfWidth, this.orthoBottom || -halfHeight, this.orthoTop || halfHeight, this.minZ, this.maxZ, this._projectionMatrix);
  20439. }
  20440. this._cache.orthoLeft = this.orthoLeft;
  20441. this._cache.orthoRight = this.orthoRight;
  20442. this._cache.orthoBottom = this.orthoBottom;
  20443. this._cache.orthoTop = this.orthoTop;
  20444. this._cache.renderWidth = engine.getRenderWidth();
  20445. this._cache.renderHeight = engine.getRenderHeight();
  20446. }
  20447. this.onProjectionMatrixChangedObservable.notifyObservers(this);
  20448. return this._projectionMatrix;
  20449. };
  20450. Camera.prototype.getTranformationMatrix = function () {
  20451. this._computedViewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  20452. return this._transformMatrix;
  20453. };
  20454. Camera.prototype.updateFrustumPlanes = function () {
  20455. if (!this._refreshFrustumPlanes) {
  20456. return;
  20457. }
  20458. this.getTranformationMatrix();
  20459. if (!this._frustumPlanes) {
  20460. this._frustumPlanes = BABYLON.Frustum.GetPlanes(this._transformMatrix);
  20461. }
  20462. else {
  20463. BABYLON.Frustum.GetPlanesToRef(this._transformMatrix, this._frustumPlanes);
  20464. }
  20465. this._refreshFrustumPlanes = false;
  20466. };
  20467. Camera.prototype.isInFrustum = function (target) {
  20468. this.updateFrustumPlanes();
  20469. return target.isInFrustum(this._frustumPlanes);
  20470. };
  20471. Camera.prototype.isCompletelyInFrustum = function (target) {
  20472. this.updateFrustumPlanes();
  20473. return target.isCompletelyInFrustum(this._frustumPlanes);
  20474. };
  20475. Camera.prototype.getForwardRay = function (length, transform, origin) {
  20476. if (length === void 0) { length = 100; }
  20477. if (!transform) {
  20478. transform = this.getWorldMatrix();
  20479. }
  20480. if (!origin) {
  20481. origin = this.position;
  20482. }
  20483. var forward = new BABYLON.Vector3(0, 0, 1);
  20484. var forwardWorld = BABYLON.Vector3.TransformNormal(forward, transform);
  20485. var direction = BABYLON.Vector3.Normalize(forwardWorld);
  20486. return new BABYLON.Ray(origin, direction, length);
  20487. };
  20488. /**
  20489. * Releases resources associated with this node.
  20490. * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default)
  20491. * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default)
  20492. */
  20493. Camera.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  20494. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  20495. // Observables
  20496. this.onViewMatrixChangedObservable.clear();
  20497. this.onProjectionMatrixChangedObservable.clear();
  20498. this.onAfterCheckInputsObservable.clear();
  20499. this.onRestoreStateObservable.clear();
  20500. // Inputs
  20501. if (this.inputs) {
  20502. this.inputs.clear();
  20503. }
  20504. // Animations
  20505. this.getScene().stopAnimation(this);
  20506. // Remove from scene
  20507. this.getScene().removeCamera(this);
  20508. while (this._rigCameras.length > 0) {
  20509. var camera = this._rigCameras.pop();
  20510. if (camera) {
  20511. camera.dispose();
  20512. }
  20513. }
  20514. // Postprocesses
  20515. if (this._rigPostProcess) {
  20516. this._rigPostProcess.dispose(this);
  20517. this._rigPostProcess = null;
  20518. this._postProcesses = [];
  20519. }
  20520. else if (this.cameraRigMode !== Camera.RIG_MODE_NONE) {
  20521. this._rigPostProcess = null;
  20522. this._postProcesses = [];
  20523. }
  20524. else {
  20525. var i = this._postProcesses.length;
  20526. while (--i >= 0) {
  20527. var postProcess = this._postProcesses[i];
  20528. if (postProcess) {
  20529. postProcess.dispose(this);
  20530. }
  20531. }
  20532. }
  20533. // Render targets
  20534. var i = this.customRenderTargets.length;
  20535. while (--i >= 0) {
  20536. this.customRenderTargets[i].dispose();
  20537. }
  20538. this.customRenderTargets = [];
  20539. // Active Meshes
  20540. this._activeMeshes.dispose();
  20541. _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
  20542. };
  20543. Object.defineProperty(Camera.prototype, "leftCamera", {
  20544. // ---- Camera rigs section ----
  20545. get: function () {
  20546. if (this._rigCameras.length < 1) {
  20547. return null;
  20548. }
  20549. return this._rigCameras[0];
  20550. },
  20551. enumerable: true,
  20552. configurable: true
  20553. });
  20554. Object.defineProperty(Camera.prototype, "rightCamera", {
  20555. get: function () {
  20556. if (this._rigCameras.length < 2) {
  20557. return null;
  20558. }
  20559. return this._rigCameras[1];
  20560. },
  20561. enumerable: true,
  20562. configurable: true
  20563. });
  20564. Camera.prototype.getLeftTarget = function () {
  20565. if (this._rigCameras.length < 1) {
  20566. return null;
  20567. }
  20568. return this._rigCameras[0].getTarget();
  20569. };
  20570. Camera.prototype.getRightTarget = function () {
  20571. if (this._rigCameras.length < 2) {
  20572. return null;
  20573. }
  20574. return this._rigCameras[1].getTarget();
  20575. };
  20576. Camera.prototype.setCameraRigMode = function (mode, rigParams) {
  20577. if (this.cameraRigMode === mode) {
  20578. return;
  20579. }
  20580. while (this._rigCameras.length > 0) {
  20581. var camera = this._rigCameras.pop();
  20582. if (camera) {
  20583. camera.dispose();
  20584. }
  20585. }
  20586. this.cameraRigMode = mode;
  20587. this._cameraRigParams = {};
  20588. //we have to implement stereo camera calcultating left and right viewpoints from interaxialDistance and target,
  20589. //not from a given angle as it is now, but until that complete code rewriting provisional stereoHalfAngle value is introduced
  20590. this._cameraRigParams.interaxialDistance = rigParams.interaxialDistance || 0.0637;
  20591. this._cameraRigParams.stereoHalfAngle = BABYLON.Tools.ToRadians(this._cameraRigParams.interaxialDistance / 0.0637);
  20592. // create the rig cameras, unless none
  20593. if (this.cameraRigMode !== Camera.RIG_MODE_NONE) {
  20594. var leftCamera = this.createRigCamera(this.name + "_L", 0);
  20595. var rightCamera = this.createRigCamera(this.name + "_R", 1);
  20596. if (leftCamera && rightCamera) {
  20597. this._rigCameras.push(leftCamera);
  20598. this._rigCameras.push(rightCamera);
  20599. }
  20600. }
  20601. switch (this.cameraRigMode) {
  20602. case Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  20603. this._rigCameras[0]._rigPostProcess = new BABYLON.PassPostProcess(this.name + "_passthru", 1.0, this._rigCameras[0]);
  20604. this._rigCameras[1]._rigPostProcess = new BABYLON.AnaglyphPostProcess(this.name + "_anaglyph", 1.0, this._rigCameras);
  20605. break;
  20606. case Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  20607. case Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  20608. case Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  20609. var isStereoscopicHoriz = this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL || this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED;
  20610. this._rigCameras[0]._rigPostProcess = new BABYLON.PassPostProcess(this.name + "_passthru", 1.0, this._rigCameras[0]);
  20611. this._rigCameras[1]._rigPostProcess = new BABYLON.StereoscopicInterlacePostProcess(this.name + "_stereoInterlace", this._rigCameras, isStereoscopicHoriz);
  20612. break;
  20613. case Camera.RIG_MODE_VR:
  20614. var metrics = rigParams.vrCameraMetrics || BABYLON.VRCameraMetrics.GetDefault();
  20615. this._rigCameras[0]._cameraRigParams.vrMetrics = metrics;
  20616. this._rigCameras[0].viewport = new BABYLON.Viewport(0, 0, 0.5, 1.0);
  20617. this._rigCameras[0]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  20618. this._rigCameras[0]._cameraRigParams.vrHMatrix = metrics.leftHMatrix;
  20619. this._rigCameras[0]._cameraRigParams.vrPreViewMatrix = metrics.leftPreViewMatrix;
  20620. this._rigCameras[0].getProjectionMatrix = this._rigCameras[0]._getVRProjectionMatrix;
  20621. this._rigCameras[1]._cameraRigParams.vrMetrics = metrics;
  20622. this._rigCameras[1].viewport = new BABYLON.Viewport(0.5, 0, 0.5, 1.0);
  20623. this._rigCameras[1]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  20624. this._rigCameras[1]._cameraRigParams.vrHMatrix = metrics.rightHMatrix;
  20625. this._rigCameras[1]._cameraRigParams.vrPreViewMatrix = metrics.rightPreViewMatrix;
  20626. this._rigCameras[1].getProjectionMatrix = this._rigCameras[1]._getVRProjectionMatrix;
  20627. if (metrics.compensateDistortion) {
  20628. this._rigCameras[0]._rigPostProcess = new BABYLON.VRDistortionCorrectionPostProcess("VR_Distort_Compensation_Left", this._rigCameras[0], false, metrics);
  20629. this._rigCameras[1]._rigPostProcess = new BABYLON.VRDistortionCorrectionPostProcess("VR_Distort_Compensation_Right", this._rigCameras[1], true, metrics);
  20630. }
  20631. break;
  20632. case Camera.RIG_MODE_WEBVR:
  20633. if (rigParams.vrDisplay) {
  20634. var leftEye = rigParams.vrDisplay.getEyeParameters('left');
  20635. var rightEye = rigParams.vrDisplay.getEyeParameters('right');
  20636. //Left eye
  20637. this._rigCameras[0].viewport = new BABYLON.Viewport(0, 0, 0.5, 1.0);
  20638. this._rigCameras[0].setCameraRigParameter("left", true);
  20639. //leaving this for future reference
  20640. this._rigCameras[0].setCameraRigParameter("specs", rigParams.specs);
  20641. this._rigCameras[0].setCameraRigParameter("eyeParameters", leftEye);
  20642. this._rigCameras[0].setCameraRigParameter("frameData", rigParams.frameData);
  20643. this._rigCameras[0].setCameraRigParameter("parentCamera", rigParams.parentCamera);
  20644. this._rigCameras[0]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  20645. this._rigCameras[0].getProjectionMatrix = this._getWebVRProjectionMatrix;
  20646. this._rigCameras[0].parent = this;
  20647. this._rigCameras[0]._getViewMatrix = this._getWebVRViewMatrix;
  20648. //Right eye
  20649. this._rigCameras[1].viewport = new BABYLON.Viewport(0.5, 0, 0.5, 1.0);
  20650. this._rigCameras[1].setCameraRigParameter('eyeParameters', rightEye);
  20651. this._rigCameras[1].setCameraRigParameter("specs", rigParams.specs);
  20652. this._rigCameras[1].setCameraRigParameter("frameData", rigParams.frameData);
  20653. this._rigCameras[1].setCameraRigParameter("parentCamera", rigParams.parentCamera);
  20654. this._rigCameras[1]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  20655. this._rigCameras[1].getProjectionMatrix = this._getWebVRProjectionMatrix;
  20656. this._rigCameras[1].parent = this;
  20657. this._rigCameras[1]._getViewMatrix = this._getWebVRViewMatrix;
  20658. if (Camera.UseAlternateWebVRRendering) {
  20659. this._rigCameras[1]._skipRendering = true;
  20660. this._rigCameras[0]._alternateCamera = this._rigCameras[1];
  20661. }
  20662. }
  20663. break;
  20664. }
  20665. this._cascadePostProcessesToRigCams();
  20666. this.update();
  20667. };
  20668. Camera.prototype._getVRProjectionMatrix = function () {
  20669. BABYLON.Matrix.PerspectiveFovLHToRef(this._cameraRigParams.vrMetrics.aspectRatioFov, this._cameraRigParams.vrMetrics.aspectRatio, this.minZ, this.maxZ, this._cameraRigParams.vrWorkMatrix);
  20670. this._cameraRigParams.vrWorkMatrix.multiplyToRef(this._cameraRigParams.vrHMatrix, this._projectionMatrix);
  20671. return this._projectionMatrix;
  20672. };
  20673. Camera.prototype._updateCameraRotationMatrix = function () {
  20674. //Here for WebVR
  20675. };
  20676. Camera.prototype._updateWebVRCameraRotationMatrix = function () {
  20677. //Here for WebVR
  20678. };
  20679. /**
  20680. * This function MUST be overwritten by the different WebVR cameras available.
  20681. * The context in which it is running is the RIG camera. So 'this' is the TargetCamera, left or right.
  20682. */
  20683. Camera.prototype._getWebVRProjectionMatrix = function () {
  20684. return BABYLON.Matrix.Identity();
  20685. };
  20686. /**
  20687. * This function MUST be overwritten by the different WebVR cameras available.
  20688. * The context in which it is running is the RIG camera. So 'this' is the TargetCamera, left or right.
  20689. */
  20690. Camera.prototype._getWebVRViewMatrix = function () {
  20691. return BABYLON.Matrix.Identity();
  20692. };
  20693. Camera.prototype.setCameraRigParameter = function (name, value) {
  20694. if (!this._cameraRigParams) {
  20695. this._cameraRigParams = {};
  20696. }
  20697. this._cameraRigParams[name] = value;
  20698. //provisionnally:
  20699. if (name === "interaxialDistance") {
  20700. this._cameraRigParams.stereoHalfAngle = BABYLON.Tools.ToRadians(value / 0.0637);
  20701. }
  20702. };
  20703. /**
  20704. * needs to be overridden by children so sub has required properties to be copied
  20705. */
  20706. Camera.prototype.createRigCamera = function (name, cameraIndex) {
  20707. return null;
  20708. };
  20709. /**
  20710. * May need to be overridden by children
  20711. */
  20712. Camera.prototype._updateRigCameras = function () {
  20713. for (var i = 0; i < this._rigCameras.length; i++) {
  20714. this._rigCameras[i].minZ = this.minZ;
  20715. this._rigCameras[i].maxZ = this.maxZ;
  20716. this._rigCameras[i].fov = this.fov;
  20717. }
  20718. // only update viewport when ANAGLYPH
  20719. if (this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH) {
  20720. this._rigCameras[0].viewport = this._rigCameras[1].viewport = this.viewport;
  20721. }
  20722. };
  20723. Camera.prototype._setupInputs = function () {
  20724. };
  20725. Camera.prototype.serialize = function () {
  20726. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  20727. // Type
  20728. serializationObject.type = this.getClassName();
  20729. // Parent
  20730. if (this.parent) {
  20731. serializationObject.parentId = this.parent.id;
  20732. }
  20733. if (this.inputs) {
  20734. this.inputs.serialize(serializationObject);
  20735. }
  20736. // Animations
  20737. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  20738. serializationObject.ranges = this.serializeAnimationRanges();
  20739. return serializationObject;
  20740. };
  20741. Camera.prototype.clone = function (name) {
  20742. return BABYLON.SerializationHelper.Clone(Camera.GetConstructorFromName(this.getClassName(), name, this.getScene(), this.interaxialDistance, this.isStereoscopicSideBySide), this);
  20743. };
  20744. Camera.prototype.getDirection = function (localAxis) {
  20745. var result = BABYLON.Vector3.Zero();
  20746. this.getDirectionToRef(localAxis, result);
  20747. return result;
  20748. };
  20749. Camera.prototype.getDirectionToRef = function (localAxis, result) {
  20750. BABYLON.Vector3.TransformNormalToRef(localAxis, this.getWorldMatrix(), result);
  20751. };
  20752. Camera.GetConstructorFromName = function (type, name, scene, interaxial_distance, isStereoscopicSideBySide) {
  20753. if (interaxial_distance === void 0) { interaxial_distance = 0; }
  20754. if (isStereoscopicSideBySide === void 0) { isStereoscopicSideBySide = true; }
  20755. switch (type) {
  20756. case "ArcRotateCamera":
  20757. return function () { return new BABYLON.ArcRotateCamera(name, 0, 0, 1.0, BABYLON.Vector3.Zero(), scene); };
  20758. case "DeviceOrientationCamera":
  20759. return function () { return new BABYLON.DeviceOrientationCamera(name, BABYLON.Vector3.Zero(), scene); };
  20760. case "FollowCamera":
  20761. return function () { return new BABYLON.FollowCamera(name, BABYLON.Vector3.Zero(), scene); };
  20762. case "ArcFollowCamera":
  20763. return function () { return new BABYLON.ArcFollowCamera(name, 0, 0, 1.0, null, scene); };
  20764. case "GamepadCamera":
  20765. return function () { return new BABYLON.GamepadCamera(name, BABYLON.Vector3.Zero(), scene); };
  20766. case "TouchCamera":
  20767. return function () { return new BABYLON.TouchCamera(name, BABYLON.Vector3.Zero(), scene); };
  20768. case "VirtualJoysticksCamera":
  20769. return function () { return new BABYLON.VirtualJoysticksCamera(name, BABYLON.Vector3.Zero(), scene); };
  20770. case "WebVRFreeCamera":
  20771. return function () { return new BABYLON.WebVRFreeCamera(name, BABYLON.Vector3.Zero(), scene); };
  20772. case "WebVRGamepadCamera":
  20773. return function () { return new BABYLON.WebVRFreeCamera(name, BABYLON.Vector3.Zero(), scene); };
  20774. case "VRDeviceOrientationFreeCamera":
  20775. return function () { return new BABYLON.VRDeviceOrientationFreeCamera(name, BABYLON.Vector3.Zero(), scene); };
  20776. case "VRDeviceOrientationGamepadCamera":
  20777. return function () { return new BABYLON.VRDeviceOrientationGamepadCamera(name, BABYLON.Vector3.Zero(), scene); };
  20778. case "AnaglyphArcRotateCamera":
  20779. return function () { return new BABYLON.AnaglyphArcRotateCamera(name, 0, 0, 1.0, BABYLON.Vector3.Zero(), interaxial_distance, scene); };
  20780. case "AnaglyphFreeCamera":
  20781. return function () { return new BABYLON.AnaglyphFreeCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, scene); };
  20782. case "AnaglyphGamepadCamera":
  20783. return function () { return new BABYLON.AnaglyphGamepadCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, scene); };
  20784. case "AnaglyphUniversalCamera":
  20785. return function () { return new BABYLON.AnaglyphUniversalCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, scene); };
  20786. case "StereoscopicArcRotateCamera":
  20787. return function () { return new BABYLON.StereoscopicArcRotateCamera(name, 0, 0, 1.0, BABYLON.Vector3.Zero(), interaxial_distance, isStereoscopicSideBySide, scene); };
  20788. case "StereoscopicFreeCamera":
  20789. return function () { return new BABYLON.StereoscopicFreeCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, isStereoscopicSideBySide, scene); };
  20790. case "StereoscopicGamepadCamera":
  20791. return function () { return new BABYLON.StereoscopicGamepadCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, isStereoscopicSideBySide, scene); };
  20792. case "StereoscopicUniversalCamera":
  20793. return function () { return new BABYLON.StereoscopicUniversalCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, isStereoscopicSideBySide, scene); };
  20794. case "FreeCamera":// Forcing Universal here
  20795. return function () { return new BABYLON.UniversalCamera(name, BABYLON.Vector3.Zero(), scene); };
  20796. default:// Universal Camera is the default value
  20797. return function () { return new BABYLON.UniversalCamera(name, BABYLON.Vector3.Zero(), scene); };
  20798. }
  20799. };
  20800. Camera.prototype.computeWorldMatrix = function () {
  20801. return this.getWorldMatrix();
  20802. };
  20803. Camera.Parse = function (parsedCamera, scene) {
  20804. var type = parsedCamera.type;
  20805. var construct = Camera.GetConstructorFromName(type, parsedCamera.name, scene, parsedCamera.interaxial_distance, parsedCamera.isStereoscopicSideBySide);
  20806. var camera = BABYLON.SerializationHelper.Parse(construct, parsedCamera, scene);
  20807. // Parent
  20808. if (parsedCamera.parentId) {
  20809. camera._waitingParentId = parsedCamera.parentId;
  20810. }
  20811. //If camera has an input manager, let it parse inputs settings
  20812. if (camera.inputs) {
  20813. camera.inputs.parse(parsedCamera);
  20814. camera._setupInputs();
  20815. }
  20816. if (camera.setPosition) {
  20817. camera.position.copyFromFloats(0, 0, 0);
  20818. camera.setPosition(BABYLON.Vector3.FromArray(parsedCamera.position));
  20819. }
  20820. // Target
  20821. if (parsedCamera.target) {
  20822. if (camera.setTarget) {
  20823. camera.setTarget(BABYLON.Vector3.FromArray(parsedCamera.target));
  20824. }
  20825. }
  20826. // Apply 3d rig, when found
  20827. if (parsedCamera.cameraRigMode) {
  20828. var rigParams = (parsedCamera.interaxial_distance) ? { interaxialDistance: parsedCamera.interaxial_distance } : {};
  20829. camera.setCameraRigMode(parsedCamera.cameraRigMode, rigParams);
  20830. }
  20831. // Animations
  20832. if (parsedCamera.animations) {
  20833. for (var animationIndex = 0; animationIndex < parsedCamera.animations.length; animationIndex++) {
  20834. var parsedAnimation = parsedCamera.animations[animationIndex];
  20835. camera.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  20836. }
  20837. BABYLON.Node.ParseAnimationRanges(camera, parsedCamera, scene);
  20838. }
  20839. if (parsedCamera.autoAnimate) {
  20840. scene.beginAnimation(camera, parsedCamera.autoAnimateFrom, parsedCamera.autoAnimateTo, parsedCamera.autoAnimateLoop, parsedCamera.autoAnimateSpeed || 1.0);
  20841. }
  20842. return camera;
  20843. };
  20844. // Statics
  20845. Camera._PERSPECTIVE_CAMERA = 0;
  20846. Camera._ORTHOGRAPHIC_CAMERA = 1;
  20847. Camera._FOVMODE_VERTICAL_FIXED = 0;
  20848. Camera._FOVMODE_HORIZONTAL_FIXED = 1;
  20849. Camera._RIG_MODE_NONE = 0;
  20850. Camera._RIG_MODE_STEREOSCOPIC_ANAGLYPH = 10;
  20851. Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL = 11;
  20852. Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED = 12;
  20853. Camera._RIG_MODE_STEREOSCOPIC_OVERUNDER = 13;
  20854. Camera._RIG_MODE_VR = 20;
  20855. Camera._RIG_MODE_WEBVR = 21;
  20856. Camera.ForceAttachControlToAlwaysPreventDefault = false;
  20857. Camera.UseAlternateWebVRRendering = false;
  20858. __decorate([
  20859. BABYLON.serializeAsVector3()
  20860. ], Camera.prototype, "position", void 0);
  20861. __decorate([
  20862. BABYLON.serializeAsVector3()
  20863. ], Camera.prototype, "upVector", void 0);
  20864. __decorate([
  20865. BABYLON.serialize()
  20866. ], Camera.prototype, "orthoLeft", void 0);
  20867. __decorate([
  20868. BABYLON.serialize()
  20869. ], Camera.prototype, "orthoRight", void 0);
  20870. __decorate([
  20871. BABYLON.serialize()
  20872. ], Camera.prototype, "orthoBottom", void 0);
  20873. __decorate([
  20874. BABYLON.serialize()
  20875. ], Camera.prototype, "orthoTop", void 0);
  20876. __decorate([
  20877. BABYLON.serialize()
  20878. ], Camera.prototype, "fov", void 0);
  20879. __decorate([
  20880. BABYLON.serialize()
  20881. ], Camera.prototype, "minZ", void 0);
  20882. __decorate([
  20883. BABYLON.serialize()
  20884. ], Camera.prototype, "maxZ", void 0);
  20885. __decorate([
  20886. BABYLON.serialize()
  20887. ], Camera.prototype, "inertia", void 0);
  20888. __decorate([
  20889. BABYLON.serialize()
  20890. ], Camera.prototype, "mode", void 0);
  20891. __decorate([
  20892. BABYLON.serialize()
  20893. ], Camera.prototype, "layerMask", void 0);
  20894. __decorate([
  20895. BABYLON.serialize()
  20896. ], Camera.prototype, "fovMode", void 0);
  20897. __decorate([
  20898. BABYLON.serialize()
  20899. ], Camera.prototype, "cameraRigMode", void 0);
  20900. __decorate([
  20901. BABYLON.serialize()
  20902. ], Camera.prototype, "interaxialDistance", void 0);
  20903. __decorate([
  20904. BABYLON.serialize()
  20905. ], Camera.prototype, "isStereoscopicSideBySide", void 0);
  20906. return Camera;
  20907. }(BABYLON.Node));
  20908. BABYLON.Camera = Camera;
  20909. })(BABYLON || (BABYLON = {}));
  20910. //# sourceMappingURL=babylon.camera.js.map
  20911. "use strict";
  20912. var BABYLON;
  20913. (function (BABYLON) {
  20914. var RenderingManager = /** @class */ (function () {
  20915. function RenderingManager(scene) {
  20916. this._renderingGroups = new Array();
  20917. this._autoClearDepthStencil = {};
  20918. this._customOpaqueSortCompareFn = {};
  20919. this._customAlphaTestSortCompareFn = {};
  20920. this._customTransparentSortCompareFn = {};
  20921. this._renderinGroupInfo = null;
  20922. this._scene = scene;
  20923. for (var i = RenderingManager.MIN_RENDERINGGROUPS; i < RenderingManager.MAX_RENDERINGGROUPS; i++) {
  20924. this._autoClearDepthStencil[i] = { autoClear: true, depth: true, stencil: true };
  20925. }
  20926. }
  20927. RenderingManager.prototype._clearDepthStencilBuffer = function (depth, stencil) {
  20928. if (depth === void 0) { depth = true; }
  20929. if (stencil === void 0) { stencil = true; }
  20930. if (this._depthStencilBufferAlreadyCleaned) {
  20931. return;
  20932. }
  20933. this._scene.getEngine().clear(null, false, depth, stencil);
  20934. this._depthStencilBufferAlreadyCleaned = true;
  20935. };
  20936. RenderingManager.prototype.render = function (customRenderFunction, activeMeshes, renderParticles, renderSprites) {
  20937. // Check if there's at least on observer on the onRenderingGroupObservable and initialize things to fire it
  20938. var observable = this._scene.onRenderingGroupObservable.hasObservers() ? this._scene.onRenderingGroupObservable : null;
  20939. var info = null;
  20940. if (observable) {
  20941. if (!this._renderinGroupInfo) {
  20942. this._renderinGroupInfo = new BABYLON.RenderingGroupInfo();
  20943. }
  20944. info = this._renderinGroupInfo;
  20945. info.scene = this._scene;
  20946. info.camera = this._scene.activeCamera;
  20947. }
  20948. // Dispatch sprites
  20949. if (renderSprites) {
  20950. for (var index = 0; index < this._scene.spriteManagers.length; index++) {
  20951. var manager = this._scene.spriteManagers[index];
  20952. this.dispatchSprites(manager);
  20953. }
  20954. }
  20955. // Render
  20956. for (var index = RenderingManager.MIN_RENDERINGGROUPS; index < RenderingManager.MAX_RENDERINGGROUPS; index++) {
  20957. this._depthStencilBufferAlreadyCleaned = index === RenderingManager.MIN_RENDERINGGROUPS;
  20958. var renderingGroup = this._renderingGroups[index];
  20959. if (!renderingGroup && !observable)
  20960. continue;
  20961. var renderingGroupMask = 0;
  20962. // Fire PRECLEAR stage
  20963. if (observable && info) {
  20964. renderingGroupMask = Math.pow(2, index);
  20965. info.renderStage = BABYLON.RenderingGroupInfo.STAGE_PRECLEAR;
  20966. info.renderingGroupId = index;
  20967. observable.notifyObservers(info, renderingGroupMask);
  20968. }
  20969. // Clear depth/stencil if needed
  20970. if (RenderingManager.AUTOCLEAR) {
  20971. var autoClear = this._autoClearDepthStencil[index];
  20972. if (autoClear && autoClear.autoClear) {
  20973. this._clearDepthStencilBuffer(autoClear.depth, autoClear.stencil);
  20974. }
  20975. }
  20976. if (observable && info) {
  20977. // Fire PREOPAQUE stage
  20978. info.renderStage = BABYLON.RenderingGroupInfo.STAGE_PREOPAQUE;
  20979. observable.notifyObservers(info, renderingGroupMask);
  20980. // Fire PRETRANSPARENT stage
  20981. info.renderStage = BABYLON.RenderingGroupInfo.STAGE_PRETRANSPARENT;
  20982. observable.notifyObservers(info, renderingGroupMask);
  20983. }
  20984. if (renderingGroup)
  20985. renderingGroup.render(customRenderFunction, renderSprites, renderParticles, activeMeshes);
  20986. // Fire POSTTRANSPARENT stage
  20987. if (observable && info) {
  20988. info.renderStage = BABYLON.RenderingGroupInfo.STAGE_POSTTRANSPARENT;
  20989. observable.notifyObservers(info, renderingGroupMask);
  20990. }
  20991. }
  20992. };
  20993. RenderingManager.prototype.reset = function () {
  20994. for (var index = RenderingManager.MIN_RENDERINGGROUPS; index < RenderingManager.MAX_RENDERINGGROUPS; index++) {
  20995. var renderingGroup = this._renderingGroups[index];
  20996. if (renderingGroup) {
  20997. renderingGroup.prepare();
  20998. }
  20999. }
  21000. };
  21001. RenderingManager.prototype.dispose = function () {
  21002. this.freeRenderingGroups();
  21003. this._renderingGroups.length = 0;
  21004. };
  21005. /**
  21006. * Clear the info related to rendering groups preventing retention points during dispose.
  21007. */
  21008. RenderingManager.prototype.freeRenderingGroups = function () {
  21009. for (var index = RenderingManager.MIN_RENDERINGGROUPS; index < RenderingManager.MAX_RENDERINGGROUPS; index++) {
  21010. var renderingGroup = this._renderingGroups[index];
  21011. if (renderingGroup) {
  21012. renderingGroup.dispose();
  21013. }
  21014. }
  21015. };
  21016. RenderingManager.prototype._prepareRenderingGroup = function (renderingGroupId) {
  21017. if (this._renderingGroups[renderingGroupId] === undefined) {
  21018. this._renderingGroups[renderingGroupId] = new BABYLON.RenderingGroup(renderingGroupId, this._scene, this._customOpaqueSortCompareFn[renderingGroupId], this._customAlphaTestSortCompareFn[renderingGroupId], this._customTransparentSortCompareFn[renderingGroupId]);
  21019. }
  21020. };
  21021. RenderingManager.prototype.dispatchSprites = function (spriteManager) {
  21022. var renderingGroupId = spriteManager.renderingGroupId || 0;
  21023. this._prepareRenderingGroup(renderingGroupId);
  21024. this._renderingGroups[renderingGroupId].dispatchSprites(spriteManager);
  21025. };
  21026. RenderingManager.prototype.dispatchParticles = function (particleSystem) {
  21027. var renderingGroupId = particleSystem.renderingGroupId || 0;
  21028. this._prepareRenderingGroup(renderingGroupId);
  21029. this._renderingGroups[renderingGroupId].dispatchParticles(particleSystem);
  21030. };
  21031. /**
  21032. * @param subMesh The submesh to dispatch
  21033. * @param [mesh] Optional reference to the submeshes's mesh. Provide if you have an exiting reference to improve performance.
  21034. * @param [material] Optional reference to the submeshes's material. Provide if you have an exiting reference to improve performance.
  21035. */
  21036. RenderingManager.prototype.dispatch = function (subMesh, mesh, material) {
  21037. if (mesh === undefined) {
  21038. mesh = subMesh.getMesh();
  21039. }
  21040. var renderingGroupId = mesh.renderingGroupId || 0;
  21041. this._prepareRenderingGroup(renderingGroupId);
  21042. this._renderingGroups[renderingGroupId].dispatch(subMesh, mesh, material);
  21043. };
  21044. /**
  21045. * Overrides the default sort function applied in the renderging group to prepare the meshes.
  21046. * This allowed control for front to back rendering or reversly depending of the special needs.
  21047. *
  21048. * @param renderingGroupId The rendering group id corresponding to its index
  21049. * @param opaqueSortCompareFn The opaque queue comparison function use to sort.
  21050. * @param alphaTestSortCompareFn The alpha test queue comparison function use to sort.
  21051. * @param transparentSortCompareFn The transparent queue comparison function use to sort.
  21052. */
  21053. RenderingManager.prototype.setRenderingOrder = function (renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  21054. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  21055. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  21056. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  21057. this._customOpaqueSortCompareFn[renderingGroupId] = opaqueSortCompareFn;
  21058. this._customAlphaTestSortCompareFn[renderingGroupId] = alphaTestSortCompareFn;
  21059. this._customTransparentSortCompareFn[renderingGroupId] = transparentSortCompareFn;
  21060. if (this._renderingGroups[renderingGroupId]) {
  21061. var group = this._renderingGroups[renderingGroupId];
  21062. group.opaqueSortCompareFn = this._customOpaqueSortCompareFn[renderingGroupId];
  21063. group.alphaTestSortCompareFn = this._customAlphaTestSortCompareFn[renderingGroupId];
  21064. group.transparentSortCompareFn = this._customTransparentSortCompareFn[renderingGroupId];
  21065. }
  21066. };
  21067. /**
  21068. * Specifies whether or not the stencil and depth buffer are cleared between two rendering groups.
  21069. *
  21070. * @param renderingGroupId The rendering group id corresponding to its index
  21071. * @param autoClearDepthStencil Automatically clears depth and stencil between groups if true.
  21072. * @param depth Automatically clears depth between groups if true and autoClear is true.
  21073. * @param stencil Automatically clears stencil between groups if true and autoClear is true.
  21074. */
  21075. RenderingManager.prototype.setRenderingAutoClearDepthStencil = function (renderingGroupId, autoClearDepthStencil, depth, stencil) {
  21076. if (depth === void 0) { depth = true; }
  21077. if (stencil === void 0) { stencil = true; }
  21078. this._autoClearDepthStencil[renderingGroupId] = {
  21079. autoClear: autoClearDepthStencil,
  21080. depth: depth,
  21081. stencil: stencil
  21082. };
  21083. };
  21084. /**
  21085. * The max id used for rendering groups (not included)
  21086. */
  21087. RenderingManager.MAX_RENDERINGGROUPS = 4;
  21088. /**
  21089. * The min id used for rendering groups (included)
  21090. */
  21091. RenderingManager.MIN_RENDERINGGROUPS = 0;
  21092. /**
  21093. * Used to globally prevent autoclearing scenes.
  21094. */
  21095. RenderingManager.AUTOCLEAR = true;
  21096. return RenderingManager;
  21097. }());
  21098. BABYLON.RenderingManager = RenderingManager;
  21099. })(BABYLON || (BABYLON = {}));
  21100. //# sourceMappingURL=babylon.renderingManager.js.map
  21101. "use strict";
  21102. var BABYLON;
  21103. (function (BABYLON) {
  21104. var RenderingGroup = /** @class */ (function () {
  21105. /**
  21106. * Creates a new rendering group.
  21107. * @param index The rendering group index
  21108. * @param opaqueSortCompareFn The opaque sort comparison function. If null no order is applied
  21109. * @param alphaTestSortCompareFn The alpha test sort comparison function. If null no order is applied
  21110. * @param transparentSortCompareFn The transparent sort comparison function. If null back to front + alpha index sort is applied
  21111. */
  21112. function RenderingGroup(index, scene, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  21113. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  21114. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  21115. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  21116. this.index = index;
  21117. this._opaqueSubMeshes = new BABYLON.SmartArray(256);
  21118. this._transparentSubMeshes = new BABYLON.SmartArray(256);
  21119. this._alphaTestSubMeshes = new BABYLON.SmartArray(256);
  21120. this._depthOnlySubMeshes = new BABYLON.SmartArray(256);
  21121. this._particleSystems = new BABYLON.SmartArray(256);
  21122. this._spriteManagers = new BABYLON.SmartArray(256);
  21123. this._edgesRenderers = new BABYLON.SmartArray(16);
  21124. this._scene = scene;
  21125. this.opaqueSortCompareFn = opaqueSortCompareFn;
  21126. this.alphaTestSortCompareFn = alphaTestSortCompareFn;
  21127. this.transparentSortCompareFn = transparentSortCompareFn;
  21128. }
  21129. Object.defineProperty(RenderingGroup.prototype, "opaqueSortCompareFn", {
  21130. /**
  21131. * Set the opaque sort comparison function.
  21132. * If null the sub meshes will be render in the order they were created
  21133. */
  21134. set: function (value) {
  21135. this._opaqueSortCompareFn = value;
  21136. if (value) {
  21137. this._renderOpaque = this.renderOpaqueSorted;
  21138. }
  21139. else {
  21140. this._renderOpaque = RenderingGroup.renderUnsorted;
  21141. }
  21142. },
  21143. enumerable: true,
  21144. configurable: true
  21145. });
  21146. Object.defineProperty(RenderingGroup.prototype, "alphaTestSortCompareFn", {
  21147. /**
  21148. * Set the alpha test sort comparison function.
  21149. * If null the sub meshes will be render in the order they were created
  21150. */
  21151. set: function (value) {
  21152. this._alphaTestSortCompareFn = value;
  21153. if (value) {
  21154. this._renderAlphaTest = this.renderAlphaTestSorted;
  21155. }
  21156. else {
  21157. this._renderAlphaTest = RenderingGroup.renderUnsorted;
  21158. }
  21159. },
  21160. enumerable: true,
  21161. configurable: true
  21162. });
  21163. Object.defineProperty(RenderingGroup.prototype, "transparentSortCompareFn", {
  21164. /**
  21165. * Set the transparent sort comparison function.
  21166. * If null the sub meshes will be render in the order they were created
  21167. */
  21168. set: function (value) {
  21169. if (value) {
  21170. this._transparentSortCompareFn = value;
  21171. }
  21172. else {
  21173. this._transparentSortCompareFn = RenderingGroup.defaultTransparentSortCompare;
  21174. }
  21175. this._renderTransparent = this.renderTransparentSorted;
  21176. },
  21177. enumerable: true,
  21178. configurable: true
  21179. });
  21180. /**
  21181. * Render all the sub meshes contained in the group.
  21182. * @param customRenderFunction Used to override the default render behaviour of the group.
  21183. * @returns true if rendered some submeshes.
  21184. */
  21185. RenderingGroup.prototype.render = function (customRenderFunction, renderSprites, renderParticles, activeMeshes) {
  21186. if (customRenderFunction) {
  21187. customRenderFunction(this._opaqueSubMeshes, this._alphaTestSubMeshes, this._transparentSubMeshes, this._depthOnlySubMeshes);
  21188. return;
  21189. }
  21190. var engine = this._scene.getEngine();
  21191. // Depth only
  21192. if (this._depthOnlySubMeshes.length !== 0) {
  21193. engine.setColorWrite(false);
  21194. this._renderAlphaTest(this._depthOnlySubMeshes);
  21195. engine.setColorWrite(true);
  21196. }
  21197. // Opaque
  21198. if (this._opaqueSubMeshes.length !== 0) {
  21199. this._renderOpaque(this._opaqueSubMeshes);
  21200. }
  21201. // Alpha test
  21202. if (this._alphaTestSubMeshes.length !== 0) {
  21203. this._renderAlphaTest(this._alphaTestSubMeshes);
  21204. }
  21205. var stencilState = engine.getStencilBuffer();
  21206. engine.setStencilBuffer(false);
  21207. // Sprites
  21208. if (renderSprites) {
  21209. this._renderSprites();
  21210. }
  21211. // Particles
  21212. if (renderParticles) {
  21213. this._renderParticles(activeMeshes);
  21214. }
  21215. if (this.onBeforeTransparentRendering) {
  21216. this.onBeforeTransparentRendering();
  21217. }
  21218. // Transparent
  21219. if (this._transparentSubMeshes.length !== 0) {
  21220. this._renderTransparent(this._transparentSubMeshes);
  21221. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  21222. }
  21223. // Set back stencil to false in case it changes before the edge renderer.
  21224. engine.setStencilBuffer(false);
  21225. // Edges
  21226. for (var edgesRendererIndex = 0; edgesRendererIndex < this._edgesRenderers.length; edgesRendererIndex++) {
  21227. this._edgesRenderers.data[edgesRendererIndex].render();
  21228. }
  21229. // Restore Stencil state.
  21230. engine.setStencilBuffer(stencilState);
  21231. };
  21232. /**
  21233. * Renders the opaque submeshes in the order from the opaqueSortCompareFn.
  21234. * @param subMeshes The submeshes to render
  21235. */
  21236. RenderingGroup.prototype.renderOpaqueSorted = function (subMeshes) {
  21237. return RenderingGroup.renderSorted(subMeshes, this._opaqueSortCompareFn, this._scene.activeCamera, false);
  21238. };
  21239. /**
  21240. * Renders the opaque submeshes in the order from the alphatestSortCompareFn.
  21241. * @param subMeshes The submeshes to render
  21242. */
  21243. RenderingGroup.prototype.renderAlphaTestSorted = function (subMeshes) {
  21244. return RenderingGroup.renderSorted(subMeshes, this._alphaTestSortCompareFn, this._scene.activeCamera, false);
  21245. };
  21246. /**
  21247. * Renders the opaque submeshes in the order from the transparentSortCompareFn.
  21248. * @param subMeshes The submeshes to render
  21249. */
  21250. RenderingGroup.prototype.renderTransparentSorted = function (subMeshes) {
  21251. return RenderingGroup.renderSorted(subMeshes, this._transparentSortCompareFn, this._scene.activeCamera, true);
  21252. };
  21253. /**
  21254. * Renders the submeshes in a specified order.
  21255. * @param subMeshes The submeshes to sort before render
  21256. * @param sortCompareFn The comparison function use to sort
  21257. * @param cameraPosition The camera position use to preprocess the submeshes to help sorting
  21258. * @param transparent Specifies to activate blending if true
  21259. */
  21260. RenderingGroup.renderSorted = function (subMeshes, sortCompareFn, camera, transparent) {
  21261. var subIndex = 0;
  21262. var subMesh;
  21263. var cameraPosition = camera ? camera.globalPosition : BABYLON.Vector3.Zero();
  21264. for (; subIndex < subMeshes.length; subIndex++) {
  21265. subMesh = subMeshes.data[subIndex];
  21266. subMesh._alphaIndex = subMesh.getMesh().alphaIndex;
  21267. subMesh._distanceToCamera = subMesh.getBoundingInfo().boundingSphere.centerWorld.subtract(cameraPosition).length();
  21268. }
  21269. var sortedArray = subMeshes.data.slice(0, subMeshes.length);
  21270. if (sortCompareFn) {
  21271. sortedArray.sort(sortCompareFn);
  21272. }
  21273. for (subIndex = 0; subIndex < sortedArray.length; subIndex++) {
  21274. subMesh = sortedArray[subIndex];
  21275. if (transparent) {
  21276. var material = subMesh.getMaterial();
  21277. if (material && material.needDepthPrePass) {
  21278. var engine = material.getScene().getEngine();
  21279. engine.setColorWrite(false);
  21280. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  21281. subMesh.render(false);
  21282. engine.setColorWrite(true);
  21283. }
  21284. }
  21285. subMesh.render(transparent);
  21286. }
  21287. };
  21288. /**
  21289. * Renders the submeshes in the order they were dispatched (no sort applied).
  21290. * @param subMeshes The submeshes to render
  21291. */
  21292. RenderingGroup.renderUnsorted = function (subMeshes) {
  21293. for (var subIndex = 0; subIndex < subMeshes.length; subIndex++) {
  21294. var submesh = subMeshes.data[subIndex];
  21295. submesh.render(false);
  21296. }
  21297. };
  21298. /**
  21299. * Build in function which can be applied to ensure meshes of a special queue (opaque, alpha test, transparent)
  21300. * are rendered back to front if in the same alpha index.
  21301. *
  21302. * @param a The first submesh
  21303. * @param b The second submesh
  21304. * @returns The result of the comparison
  21305. */
  21306. RenderingGroup.defaultTransparentSortCompare = function (a, b) {
  21307. // Alpha index first
  21308. if (a._alphaIndex > b._alphaIndex) {
  21309. return 1;
  21310. }
  21311. if (a._alphaIndex < b._alphaIndex) {
  21312. return -1;
  21313. }
  21314. // Then distance to camera
  21315. return RenderingGroup.backToFrontSortCompare(a, b);
  21316. };
  21317. /**
  21318. * Build in function which can be applied to ensure meshes of a special queue (opaque, alpha test, transparent)
  21319. * are rendered back to front.
  21320. *
  21321. * @param a The first submesh
  21322. * @param b The second submesh
  21323. * @returns The result of the comparison
  21324. */
  21325. RenderingGroup.backToFrontSortCompare = function (a, b) {
  21326. // Then distance to camera
  21327. if (a._distanceToCamera < b._distanceToCamera) {
  21328. return 1;
  21329. }
  21330. if (a._distanceToCamera > b._distanceToCamera) {
  21331. return -1;
  21332. }
  21333. return 0;
  21334. };
  21335. /**
  21336. * Build in function which can be applied to ensure meshes of a special queue (opaque, alpha test, transparent)
  21337. * are rendered front to back (prevent overdraw).
  21338. *
  21339. * @param a The first submesh
  21340. * @param b The second submesh
  21341. * @returns The result of the comparison
  21342. */
  21343. RenderingGroup.frontToBackSortCompare = function (a, b) {
  21344. // Then distance to camera
  21345. if (a._distanceToCamera < b._distanceToCamera) {
  21346. return -1;
  21347. }
  21348. if (a._distanceToCamera > b._distanceToCamera) {
  21349. return 1;
  21350. }
  21351. return 0;
  21352. };
  21353. /**
  21354. * Resets the different lists of submeshes to prepare a new frame.
  21355. */
  21356. RenderingGroup.prototype.prepare = function () {
  21357. this._opaqueSubMeshes.reset();
  21358. this._transparentSubMeshes.reset();
  21359. this._alphaTestSubMeshes.reset();
  21360. this._depthOnlySubMeshes.reset();
  21361. this._particleSystems.reset();
  21362. this._spriteManagers.reset();
  21363. this._edgesRenderers.reset();
  21364. };
  21365. RenderingGroup.prototype.dispose = function () {
  21366. this._opaqueSubMeshes.dispose();
  21367. this._transparentSubMeshes.dispose();
  21368. this._alphaTestSubMeshes.dispose();
  21369. this._depthOnlySubMeshes.dispose();
  21370. this._particleSystems.dispose();
  21371. this._spriteManagers.dispose();
  21372. this._edgesRenderers.dispose();
  21373. };
  21374. /**
  21375. * Inserts the submesh in its correct queue depending on its material.
  21376. * @param subMesh The submesh to dispatch
  21377. * @param [mesh] Optional reference to the submeshes's mesh. Provide if you have an exiting reference to improve performance.
  21378. * @param [material] Optional reference to the submeshes's material. Provide if you have an exiting reference to improve performance.
  21379. */
  21380. RenderingGroup.prototype.dispatch = function (subMesh, mesh, material) {
  21381. // Get mesh and materials if not provided
  21382. if (mesh === undefined) {
  21383. mesh = subMesh.getMesh();
  21384. }
  21385. if (material === undefined) {
  21386. material = subMesh.getMaterial();
  21387. }
  21388. if (material === null || material === undefined) {
  21389. return;
  21390. }
  21391. if (material.needAlphaBlendingForMesh(mesh)) {
  21392. this._transparentSubMeshes.push(subMesh);
  21393. }
  21394. else if (material.needAlphaTesting()) {
  21395. if (material.needDepthPrePass) {
  21396. this._depthOnlySubMeshes.push(subMesh);
  21397. }
  21398. this._alphaTestSubMeshes.push(subMesh);
  21399. }
  21400. else {
  21401. if (material.needDepthPrePass) {
  21402. this._depthOnlySubMeshes.push(subMesh);
  21403. }
  21404. this._opaqueSubMeshes.push(subMesh); // Opaque
  21405. }
  21406. if (mesh._edgesRenderer !== null && mesh._edgesRenderer !== undefined) {
  21407. this._edgesRenderers.push(mesh._edgesRenderer);
  21408. }
  21409. };
  21410. RenderingGroup.prototype.dispatchSprites = function (spriteManager) {
  21411. this._spriteManagers.push(spriteManager);
  21412. };
  21413. RenderingGroup.prototype.dispatchParticles = function (particleSystem) {
  21414. this._particleSystems.push(particleSystem);
  21415. };
  21416. RenderingGroup.prototype._renderParticles = function (activeMeshes) {
  21417. if (this._particleSystems.length === 0) {
  21418. return;
  21419. }
  21420. // Particles
  21421. var activeCamera = this._scene.activeCamera;
  21422. this._scene.onBeforeParticlesRenderingObservable.notifyObservers(this._scene);
  21423. for (var particleIndex = 0; particleIndex < this._particleSystems.length; particleIndex++) {
  21424. var particleSystem = this._particleSystems.data[particleIndex];
  21425. if ((activeCamera && activeCamera.layerMask & particleSystem.layerMask) === 0) {
  21426. continue;
  21427. }
  21428. var emitter = particleSystem.emitter;
  21429. if (!emitter.position || !activeMeshes || activeMeshes.indexOf(emitter) !== -1) {
  21430. this._scene._activeParticles.addCount(particleSystem.render(), false);
  21431. }
  21432. }
  21433. this._scene.onAfterParticlesRenderingObservable.notifyObservers(this._scene);
  21434. };
  21435. RenderingGroup.prototype._renderSprites = function () {
  21436. if (!this._scene.spritesEnabled || this._spriteManagers.length === 0) {
  21437. return;
  21438. }
  21439. // Sprites
  21440. var activeCamera = this._scene.activeCamera;
  21441. this._scene.onBeforeSpritesRenderingObservable.notifyObservers(this._scene);
  21442. for (var id = 0; id < this._spriteManagers.length; id++) {
  21443. var spriteManager = this._spriteManagers.data[id];
  21444. if (((activeCamera && activeCamera.layerMask & spriteManager.layerMask) !== 0)) {
  21445. spriteManager.render();
  21446. }
  21447. }
  21448. this._scene.onAfterSpritesRenderingObservable.notifyObservers(this._scene);
  21449. };
  21450. return RenderingGroup;
  21451. }());
  21452. BABYLON.RenderingGroup = RenderingGroup;
  21453. })(BABYLON || (BABYLON = {}));
  21454. //# sourceMappingURL=babylon.renderingGroup.js.map
  21455. "use strict";
  21456. var BABYLON;
  21457. (function (BABYLON) {
  21458. var ClickInfo = /** @class */ (function () {
  21459. function ClickInfo() {
  21460. this._singleClick = false;
  21461. this._doubleClick = false;
  21462. this._hasSwiped = false;
  21463. this._ignore = false;
  21464. }
  21465. Object.defineProperty(ClickInfo.prototype, "singleClick", {
  21466. get: function () {
  21467. return this._singleClick;
  21468. },
  21469. set: function (b) {
  21470. this._singleClick = b;
  21471. },
  21472. enumerable: true,
  21473. configurable: true
  21474. });
  21475. Object.defineProperty(ClickInfo.prototype, "doubleClick", {
  21476. get: function () {
  21477. return this._doubleClick;
  21478. },
  21479. set: function (b) {
  21480. this._doubleClick = b;
  21481. },
  21482. enumerable: true,
  21483. configurable: true
  21484. });
  21485. Object.defineProperty(ClickInfo.prototype, "hasSwiped", {
  21486. get: function () {
  21487. return this._hasSwiped;
  21488. },
  21489. set: function (b) {
  21490. this._hasSwiped = b;
  21491. },
  21492. enumerable: true,
  21493. configurable: true
  21494. });
  21495. Object.defineProperty(ClickInfo.prototype, "ignore", {
  21496. get: function () {
  21497. return this._ignore;
  21498. },
  21499. set: function (b) {
  21500. this._ignore = b;
  21501. },
  21502. enumerable: true,
  21503. configurable: true
  21504. });
  21505. return ClickInfo;
  21506. }());
  21507. /**
  21508. * This class is used by the onRenderingGroupObservable
  21509. */
  21510. var RenderingGroupInfo = /** @class */ (function () {
  21511. function RenderingGroupInfo() {
  21512. }
  21513. /**
  21514. * Stage corresponding to the very first hook in the renderingGroup phase: before the render buffer may be cleared
  21515. * This stage will be fired no matter what
  21516. */
  21517. RenderingGroupInfo.STAGE_PRECLEAR = 1;
  21518. /**
  21519. * Called before opaque object are rendered.
  21520. * This stage will be fired only if there's 3D Opaque content to render
  21521. */
  21522. RenderingGroupInfo.STAGE_PREOPAQUE = 2;
  21523. /**
  21524. * Called after the opaque objects are rendered and before the transparent ones
  21525. * This stage will be fired only if there's 3D transparent content to render
  21526. */
  21527. RenderingGroupInfo.STAGE_PRETRANSPARENT = 3;
  21528. /**
  21529. * Called after the transparent object are rendered, last hook of the renderingGroup phase
  21530. * This stage will be fired no matter what
  21531. */
  21532. RenderingGroupInfo.STAGE_POSTTRANSPARENT = 4;
  21533. return RenderingGroupInfo;
  21534. }());
  21535. BABYLON.RenderingGroupInfo = RenderingGroupInfo;
  21536. /**
  21537. * Represents a scene to be rendered by the engine.
  21538. * @see http://doc.babylonjs.com/features/scene
  21539. */
  21540. var Scene = /** @class */ (function () {
  21541. /**
  21542. * @constructor
  21543. * @param {BABYLON.Engine} engine - the engine to be used to render this scene.
  21544. */
  21545. function Scene(engine) {
  21546. // Members
  21547. this.autoClear = true;
  21548. this.autoClearDepthAndStencil = true;
  21549. this.clearColor = new BABYLON.Color4(0.2, 0.2, 0.3, 1.0);
  21550. this.ambientColor = new BABYLON.Color3(0, 0, 0);
  21551. this._forceWireframe = false;
  21552. this._forcePointsCloud = false;
  21553. this.forceShowBoundingBoxes = false;
  21554. this.animationsEnabled = true;
  21555. this.useConstantAnimationDeltaTime = false;
  21556. this.constantlyUpdateMeshUnderPointer = false;
  21557. this.hoverCursor = "pointer";
  21558. this.defaultCursor = "";
  21559. /**
  21560. * This is used to call preventDefault() on pointer down
  21561. * in order to block unwanted artifacts like system double clicks
  21562. */
  21563. this.preventDefaultOnPointerDown = true;
  21564. // Metadata
  21565. this.metadata = null;
  21566. /**
  21567. * Use this array to add regular expressions used to disable offline support for specific urls
  21568. */
  21569. this.disableOfflineSupportExceptionRules = new Array();
  21570. /**
  21571. * An event triggered when the scene is disposed.
  21572. */
  21573. this.onDisposeObservable = new BABYLON.Observable();
  21574. this._onDisposeObserver = null;
  21575. /**
  21576. * An event triggered before rendering the scene (right after animations and physics)
  21577. */
  21578. this.onBeforeRenderObservable = new BABYLON.Observable();
  21579. this._onBeforeRenderObserver = null;
  21580. /**
  21581. * An event triggered after rendering the scene
  21582. */
  21583. this.onAfterRenderObservable = new BABYLON.Observable();
  21584. this._onAfterRenderObserver = null;
  21585. /**
  21586. * An event triggered before animating the scene
  21587. */
  21588. this.onBeforeAnimationsObservable = new BABYLON.Observable();
  21589. /**
  21590. * An event triggered after animations processing
  21591. */
  21592. this.onAfterAnimationsObservable = new BABYLON.Observable();
  21593. /**
  21594. * An event triggered before draw calls are ready to be sent
  21595. */
  21596. this.onBeforeDrawPhaseObservable = new BABYLON.Observable();
  21597. /**
  21598. * An event triggered after draw calls have been sent
  21599. */
  21600. this.onAfterDrawPhaseObservable = new BABYLON.Observable();
  21601. /**
  21602. * An event triggered when physic simulation is about to be run
  21603. */
  21604. this.onBeforePhysicsObservable = new BABYLON.Observable();
  21605. /**
  21606. * An event triggered when physic simulation has been done
  21607. */
  21608. this.onAfterPhysicsObservable = new BABYLON.Observable();
  21609. /**
  21610. * An event triggered when the scene is ready
  21611. */
  21612. this.onReadyObservable = new BABYLON.Observable();
  21613. /**
  21614. * An event triggered before rendering a camera
  21615. */
  21616. this.onBeforeCameraRenderObservable = new BABYLON.Observable();
  21617. this._onBeforeCameraRenderObserver = null;
  21618. /**
  21619. * An event triggered after rendering a camera
  21620. */
  21621. this.onAfterCameraRenderObservable = new BABYLON.Observable();
  21622. this._onAfterCameraRenderObserver = null;
  21623. /**
  21624. * An event triggered when active meshes evaluation is about to start
  21625. */
  21626. this.onBeforeActiveMeshesEvaluationObservable = new BABYLON.Observable();
  21627. /**
  21628. * An event triggered when active meshes evaluation is done
  21629. */
  21630. this.onAfterActiveMeshesEvaluationObservable = new BABYLON.Observable();
  21631. /**
  21632. * An event triggered when particles rendering is about to start
  21633. * Note: This event can be trigger more than once per frame (because particles can be rendered by render target textures as well)
  21634. */
  21635. this.onBeforeParticlesRenderingObservable = new BABYLON.Observable();
  21636. /**
  21637. * An event triggered when particles rendering is done
  21638. * Note: This event can be trigger more than once per frame (because particles can be rendered by render target textures as well)
  21639. */
  21640. this.onAfterParticlesRenderingObservable = new BABYLON.Observable();
  21641. /**
  21642. * An event triggered when sprites rendering is about to start
  21643. * Note: This event can be trigger more than once per frame (because sprites can be rendered by render target textures as well)
  21644. */
  21645. this.onBeforeSpritesRenderingObservable = new BABYLON.Observable();
  21646. /**
  21647. * An event triggered when sprites rendering is done
  21648. * Note: This event can be trigger more than once per frame (because sprites can be rendered by render target textures as well)
  21649. */
  21650. this.onAfterSpritesRenderingObservable = new BABYLON.Observable();
  21651. /**
  21652. * An event triggered when SceneLoader.Append or SceneLoader.Load or SceneLoader.ImportMesh were successfully executed
  21653. */
  21654. this.onDataLoadedObservable = new BABYLON.Observable();
  21655. /**
  21656. * An event triggered when a camera is created
  21657. */
  21658. this.onNewCameraAddedObservable = new BABYLON.Observable();
  21659. /**
  21660. * An event triggered when a camera is removed
  21661. */
  21662. this.onCameraRemovedObservable = new BABYLON.Observable();
  21663. /**
  21664. * An event triggered when a light is created
  21665. */
  21666. this.onNewLightAddedObservable = new BABYLON.Observable();
  21667. /**
  21668. * An event triggered when a light is removed
  21669. */
  21670. this.onLightRemovedObservable = new BABYLON.Observable();
  21671. /**
  21672. * An event triggered when a geometry is created
  21673. */
  21674. this.onNewGeometryAddedObservable = new BABYLON.Observable();
  21675. /**
  21676. * An event triggered when a geometry is removed
  21677. */
  21678. this.onGeometryRemovedObservable = new BABYLON.Observable();
  21679. /**
  21680. * An event triggered when a transform node is created
  21681. */
  21682. this.onNewTransformNodeAddedObservable = new BABYLON.Observable();
  21683. /**
  21684. * An event triggered when a transform node is removed
  21685. */
  21686. this.onTransformNodeRemovedObservable = new BABYLON.Observable();
  21687. /**
  21688. * An event triggered when a mesh is created
  21689. */
  21690. this.onNewMeshAddedObservable = new BABYLON.Observable();
  21691. /**
  21692. * An event triggered when a mesh is removed
  21693. */
  21694. this.onMeshRemovedObservable = new BABYLON.Observable();
  21695. /**
  21696. * An event triggered when render targets are about to be rendered
  21697. * Can happen multiple times per frame.
  21698. */
  21699. this.OnBeforeRenderTargetsRenderObservable = new BABYLON.Observable();
  21700. /**
  21701. * An event triggered when render targets were rendered.
  21702. * Can happen multiple times per frame.
  21703. */
  21704. this.OnAfterRenderTargetsRenderObservable = new BABYLON.Observable();
  21705. /**
  21706. * An event triggered before calculating deterministic simulation step
  21707. */
  21708. this.onBeforeStepObservable = new BABYLON.Observable();
  21709. /**
  21710. * An event triggered after calculating deterministic simulation step
  21711. */
  21712. this.onAfterStepObservable = new BABYLON.Observable();
  21713. /**
  21714. * This Observable will be triggered for each stage of each renderingGroup of each rendered camera.
  21715. * The RenderinGroupInfo class contains all the information about the context in which the observable is called
  21716. * 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)
  21717. */
  21718. this.onRenderingGroupObservable = new BABYLON.Observable();
  21719. // Animations
  21720. this.animations = [];
  21721. this._registeredForLateAnimationBindings = new BABYLON.SmartArrayNoDuplicate(256);
  21722. /**
  21723. * 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).
  21724. * You have the possibility to skip the process and the call to onPointerObservable by setting PointerInfoPre.skipOnPointerObservable to true
  21725. */
  21726. this.onPrePointerObservable = new BABYLON.Observable();
  21727. /**
  21728. * Observable event triggered each time an input event is received from the rendering canvas
  21729. */
  21730. this.onPointerObservable = new BABYLON.Observable();
  21731. this._meshPickProceed = false;
  21732. this._currentPickResult = null;
  21733. this._previousPickResult = null;
  21734. this._totalPointersPressed = 0;
  21735. this._doubleClickOccured = false;
  21736. /** Define this parameter if you are using multiple cameras and you want to specify which one should be used for pointer position */
  21737. this.cameraToUseForPointers = null;
  21738. this._startingPointerPosition = new BABYLON.Vector2(0, 0);
  21739. this._previousStartingPointerPosition = new BABYLON.Vector2(0, 0);
  21740. this._startingPointerTime = 0;
  21741. this._previousStartingPointerTime = 0;
  21742. // Deterministic lockstep
  21743. this._timeAccumulator = 0;
  21744. this._currentStepId = 0;
  21745. this._currentInternalStep = 0;
  21746. // Keyboard
  21747. /**
  21748. * This observable event is triggered when any keyboard event si raised and registered during Scene.attachControl()
  21749. * You have the possibility to skip the process and the call to onKeyboardObservable by setting KeyboardInfoPre.skipOnPointerObservable to true
  21750. */
  21751. this.onPreKeyboardObservable = new BABYLON.Observable();
  21752. /**
  21753. * Observable event triggered each time an keyboard event is received from the hosting window
  21754. */
  21755. this.onKeyboardObservable = new BABYLON.Observable();
  21756. // Coordinate system
  21757. /**
  21758. * use right-handed coordinate system on this scene.
  21759. */
  21760. this._useRightHandedSystem = false;
  21761. // Fog
  21762. this._fogEnabled = true;
  21763. this._fogMode = Scene.FOGMODE_NONE;
  21764. this.fogColor = new BABYLON.Color3(0.2, 0.2, 0.3);
  21765. this.fogDensity = 0.1;
  21766. this.fogStart = 0;
  21767. this.fogEnd = 1000.0;
  21768. // Lights
  21769. /**
  21770. * is shadow enabled on this scene.
  21771. */
  21772. this._shadowsEnabled = true;
  21773. /**
  21774. * is light enabled on this scene.
  21775. */
  21776. this._lightsEnabled = true;
  21777. /**
  21778. * All of the lights added to this scene.
  21779. */
  21780. this.lights = new Array();
  21781. // Cameras
  21782. /** All of the cameras added to this scene. */
  21783. this.cameras = new Array();
  21784. /** All of the active cameras added to this scene. */
  21785. this.activeCameras = new Array();
  21786. // Meshes
  21787. /**
  21788. * All of the tranform nodes added to this scene.
  21789. */
  21790. this.transformNodes = new Array();
  21791. /**
  21792. * All of the (abstract) meshes added to this scene.
  21793. */
  21794. this.meshes = new Array();
  21795. /**
  21796. * All of the animation groups added to this scene.
  21797. */
  21798. this.animationGroups = new Array();
  21799. // Geometries
  21800. this._geometries = new Array();
  21801. this.materials = new Array();
  21802. this.multiMaterials = new Array();
  21803. // Textures
  21804. this._texturesEnabled = true;
  21805. this.textures = new Array();
  21806. // Particles
  21807. this.particlesEnabled = true;
  21808. this.particleSystems = new Array();
  21809. // Sprites
  21810. this.spritesEnabled = true;
  21811. this.spriteManagers = new Array();
  21812. /**
  21813. * The list of layers (background and foreground) of the scene.
  21814. */
  21815. this.layers = new Array();
  21816. /**
  21817. * The list of effect layers (highlights/glow) contained in the scene.
  21818. */
  21819. this.effectLayers = new Array();
  21820. // Skeletons
  21821. this._skeletonsEnabled = true;
  21822. this.skeletons = new Array();
  21823. // Morph targets
  21824. this.morphTargetManagers = new Array();
  21825. // Lens flares
  21826. this.lensFlaresEnabled = true;
  21827. this.lensFlareSystems = new Array();
  21828. // Collisions
  21829. this.collisionsEnabled = true;
  21830. /** Defines the gravity applied to this scene */
  21831. this.gravity = new BABYLON.Vector3(0, -9.807, 0);
  21832. // Postprocesses
  21833. this.postProcesses = new Array();
  21834. this.postProcessesEnabled = true;
  21835. // Customs render targets
  21836. this.renderTargetsEnabled = true;
  21837. this.dumpNextRenderTargets = false;
  21838. this.customRenderTargets = new Array();
  21839. // Imported meshes
  21840. this.importedMeshesFiles = new Array();
  21841. // Probes
  21842. this.probesEnabled = true;
  21843. this.reflectionProbes = new Array();
  21844. this._actionManagers = new Array();
  21845. this._meshesForIntersections = new BABYLON.SmartArrayNoDuplicate(256);
  21846. // Procedural textures
  21847. this.proceduralTexturesEnabled = true;
  21848. this._proceduralTextures = new Array();
  21849. this.soundTracks = new Array();
  21850. this._audioEnabled = true;
  21851. this._headphone = false;
  21852. // Performance counters
  21853. this._totalVertices = new BABYLON.PerfCounter();
  21854. this._activeIndices = new BABYLON.PerfCounter();
  21855. this._activeParticles = new BABYLON.PerfCounter();
  21856. this._activeBones = new BABYLON.PerfCounter();
  21857. this._animationTime = 0;
  21858. this.animationTimeScale = 1;
  21859. this._renderId = 0;
  21860. this._executeWhenReadyTimeoutId = -1;
  21861. this._intermediateRendering = false;
  21862. this._viewUpdateFlag = -1;
  21863. this._projectionUpdateFlag = -1;
  21864. this._alternateViewUpdateFlag = -1;
  21865. this._alternateProjectionUpdateFlag = -1;
  21866. this._toBeDisposed = new BABYLON.SmartArray(256);
  21867. this._activeRequests = new Array();
  21868. this._pendingData = new Array();
  21869. this._isDisposed = false;
  21870. this.dispatchAllSubMeshesOfActiveMeshes = false;
  21871. this._activeMeshes = new BABYLON.SmartArray(256);
  21872. this._processedMaterials = new BABYLON.SmartArray(256);
  21873. this._renderTargets = new BABYLON.SmartArrayNoDuplicate(256);
  21874. this._activeParticleSystems = new BABYLON.SmartArray(256);
  21875. this._activeSkeletons = new BABYLON.SmartArrayNoDuplicate(32);
  21876. this._softwareSkinnedMeshes = new BABYLON.SmartArrayNoDuplicate(32);
  21877. this._activeAnimatables = new Array();
  21878. this._transformMatrix = BABYLON.Matrix.Zero();
  21879. this._useAlternateCameraConfiguration = false;
  21880. this._alternateRendering = false;
  21881. this.requireLightSorting = false;
  21882. this._depthRenderer = {};
  21883. this._activeMeshesFrozen = false;
  21884. this._tempPickingRay = BABYLON.Ray ? BABYLON.Ray.Zero() : null;
  21885. this._engine = engine || BABYLON.Engine.LastCreatedEngine;
  21886. this._engine.scenes.push(this);
  21887. this._uid = null;
  21888. this._renderingManager = new BABYLON.RenderingManager(this);
  21889. this.postProcessManager = new BABYLON.PostProcessManager(this);
  21890. if (BABYLON.OutlineRenderer) {
  21891. this._outlineRenderer = new BABYLON.OutlineRenderer(this);
  21892. }
  21893. if (BABYLON.Tools.IsWindowObjectExist()) {
  21894. this.attachControl();
  21895. }
  21896. //simplification queue
  21897. if (BABYLON.SimplificationQueue) {
  21898. this.simplificationQueue = new BABYLON.SimplificationQueue();
  21899. }
  21900. //collision coordinator initialization. For now legacy per default.
  21901. this.workerCollisions = false; //(!!Worker && (!!BABYLON.CollisionWorker || BABYLON.WorkerIncluded));
  21902. // Uniform Buffer
  21903. this._createUbo();
  21904. // Default Image processing definition.
  21905. this._imageProcessingConfiguration = new BABYLON.ImageProcessingConfiguration();
  21906. }
  21907. Object.defineProperty(Scene, "FOGMODE_NONE", {
  21908. /** The fog is deactivated */
  21909. get: function () {
  21910. return Scene._FOGMODE_NONE;
  21911. },
  21912. enumerable: true,
  21913. configurable: true
  21914. });
  21915. Object.defineProperty(Scene, "FOGMODE_EXP", {
  21916. /** The fog density is following an exponential function */
  21917. get: function () {
  21918. return Scene._FOGMODE_EXP;
  21919. },
  21920. enumerable: true,
  21921. configurable: true
  21922. });
  21923. Object.defineProperty(Scene, "FOGMODE_EXP2", {
  21924. /** The fog density is following an exponential function faster than FOGMODE_EXP */
  21925. get: function () {
  21926. return Scene._FOGMODE_EXP2;
  21927. },
  21928. enumerable: true,
  21929. configurable: true
  21930. });
  21931. Object.defineProperty(Scene, "FOGMODE_LINEAR", {
  21932. /** The fog density is following a linear function. */
  21933. get: function () {
  21934. return Scene._FOGMODE_LINEAR;
  21935. },
  21936. enumerable: true,
  21937. configurable: true
  21938. });
  21939. Object.defineProperty(Scene.prototype, "environmentTexture", {
  21940. /**
  21941. * Texture used in all pbr material as the reflection texture.
  21942. * As in the majority of the scene they are the same (exception for multi room and so on),
  21943. * this is easier to reference from here than from all the materials.
  21944. */
  21945. get: function () {
  21946. return this._environmentTexture;
  21947. },
  21948. /**
  21949. * Texture used in all pbr material as the reflection texture.
  21950. * As in the majority of the scene they are the same (exception for multi room and so on),
  21951. * this is easier to set here than in all the materials.
  21952. */
  21953. set: function (value) {
  21954. if (this._environmentTexture === value) {
  21955. return;
  21956. }
  21957. this._environmentTexture = value;
  21958. this.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  21959. },
  21960. enumerable: true,
  21961. configurable: true
  21962. });
  21963. Object.defineProperty(Scene.prototype, "imageProcessingConfiguration", {
  21964. /**
  21965. * Default image processing configuration used either in the rendering
  21966. * Forward main pass or through the imageProcessingPostProcess if present.
  21967. * As in the majority of the scene they are the same (exception for multi camera),
  21968. * this is easier to reference from here than from all the materials and post process.
  21969. *
  21970. * No setter as we it is a shared configuration, you can set the values instead.
  21971. */
  21972. get: function () {
  21973. return this._imageProcessingConfiguration;
  21974. },
  21975. enumerable: true,
  21976. configurable: true
  21977. });
  21978. Object.defineProperty(Scene.prototype, "forceWireframe", {
  21979. get: function () {
  21980. return this._forceWireframe;
  21981. },
  21982. set: function (value) {
  21983. if (this._forceWireframe === value) {
  21984. return;
  21985. }
  21986. this._forceWireframe = value;
  21987. this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
  21988. },
  21989. enumerable: true,
  21990. configurable: true
  21991. });
  21992. Object.defineProperty(Scene.prototype, "forcePointsCloud", {
  21993. get: function () {
  21994. return this._forcePointsCloud;
  21995. },
  21996. set: function (value) {
  21997. if (this._forcePointsCloud === value) {
  21998. return;
  21999. }
  22000. this._forcePointsCloud = value;
  22001. this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
  22002. },
  22003. enumerable: true,
  22004. configurable: true
  22005. });
  22006. Object.defineProperty(Scene.prototype, "onDispose", {
  22007. /** A function to be executed when this scene is disposed. */
  22008. set: function (callback) {
  22009. if (this._onDisposeObserver) {
  22010. this.onDisposeObservable.remove(this._onDisposeObserver);
  22011. }
  22012. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  22013. },
  22014. enumerable: true,
  22015. configurable: true
  22016. });
  22017. Object.defineProperty(Scene.prototype, "beforeRender", {
  22018. /** A function to be executed before rendering this scene */
  22019. set: function (callback) {
  22020. if (this._onBeforeRenderObserver) {
  22021. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  22022. }
  22023. if (callback) {
  22024. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  22025. }
  22026. },
  22027. enumerable: true,
  22028. configurable: true
  22029. });
  22030. Object.defineProperty(Scene.prototype, "afterRender", {
  22031. /** A function to be executed after rendering this scene */
  22032. set: function (callback) {
  22033. if (this._onAfterRenderObserver) {
  22034. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  22035. }
  22036. if (callback) {
  22037. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  22038. }
  22039. },
  22040. enumerable: true,
  22041. configurable: true
  22042. });
  22043. Object.defineProperty(Scene.prototype, "beforeCameraRender", {
  22044. set: function (callback) {
  22045. if (this._onBeforeCameraRenderObserver) {
  22046. this.onBeforeCameraRenderObservable.remove(this._onBeforeCameraRenderObserver);
  22047. }
  22048. this._onBeforeCameraRenderObserver = this.onBeforeCameraRenderObservable.add(callback);
  22049. },
  22050. enumerable: true,
  22051. configurable: true
  22052. });
  22053. Object.defineProperty(Scene.prototype, "afterCameraRender", {
  22054. set: function (callback) {
  22055. if (this._onAfterCameraRenderObserver) {
  22056. this.onAfterCameraRenderObservable.remove(this._onAfterCameraRenderObserver);
  22057. }
  22058. this._onAfterCameraRenderObserver = this.onAfterCameraRenderObservable.add(callback);
  22059. },
  22060. enumerable: true,
  22061. configurable: true
  22062. });
  22063. Object.defineProperty(Scene.prototype, "gamepadManager", {
  22064. get: function () {
  22065. if (!this._gamepadManager) {
  22066. this._gamepadManager = new BABYLON.GamepadManager(this);
  22067. }
  22068. return this._gamepadManager;
  22069. },
  22070. enumerable: true,
  22071. configurable: true
  22072. });
  22073. Object.defineProperty(Scene.prototype, "unTranslatedPointer", {
  22074. get: function () {
  22075. return new BABYLON.Vector2(this._unTranslatedPointerX, this._unTranslatedPointerY);
  22076. },
  22077. enumerable: true,
  22078. configurable: true
  22079. });
  22080. Object.defineProperty(Scene.prototype, "useRightHandedSystem", {
  22081. get: function () {
  22082. return this._useRightHandedSystem;
  22083. },
  22084. set: function (value) {
  22085. if (this._useRightHandedSystem === value) {
  22086. return;
  22087. }
  22088. this._useRightHandedSystem = value;
  22089. this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
  22090. },
  22091. enumerable: true,
  22092. configurable: true
  22093. });
  22094. Scene.prototype.setStepId = function (newStepId) {
  22095. this._currentStepId = newStepId;
  22096. };
  22097. ;
  22098. Scene.prototype.getStepId = function () {
  22099. return this._currentStepId;
  22100. };
  22101. ;
  22102. Scene.prototype.getInternalStep = function () {
  22103. return this._currentInternalStep;
  22104. };
  22105. ;
  22106. Object.defineProperty(Scene.prototype, "fogEnabled", {
  22107. get: function () {
  22108. return this._fogEnabled;
  22109. },
  22110. /**
  22111. * is fog enabled on this scene.
  22112. */
  22113. set: function (value) {
  22114. if (this._fogEnabled === value) {
  22115. return;
  22116. }
  22117. this._fogEnabled = value;
  22118. this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
  22119. },
  22120. enumerable: true,
  22121. configurable: true
  22122. });
  22123. Object.defineProperty(Scene.prototype, "fogMode", {
  22124. get: function () {
  22125. return this._fogMode;
  22126. },
  22127. set: function (value) {
  22128. if (this._fogMode === value) {
  22129. return;
  22130. }
  22131. this._fogMode = value;
  22132. this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
  22133. },
  22134. enumerable: true,
  22135. configurable: true
  22136. });
  22137. Object.defineProperty(Scene.prototype, "shadowsEnabled", {
  22138. get: function () {
  22139. return this._shadowsEnabled;
  22140. },
  22141. set: function (value) {
  22142. if (this._shadowsEnabled === value) {
  22143. return;
  22144. }
  22145. this._shadowsEnabled = value;
  22146. this.markAllMaterialsAsDirty(BABYLON.Material.LightDirtyFlag);
  22147. },
  22148. enumerable: true,
  22149. configurable: true
  22150. });
  22151. Object.defineProperty(Scene.prototype, "lightsEnabled", {
  22152. get: function () {
  22153. return this._lightsEnabled;
  22154. },
  22155. set: function (value) {
  22156. if (this._lightsEnabled === value) {
  22157. return;
  22158. }
  22159. this._lightsEnabled = value;
  22160. this.markAllMaterialsAsDirty(BABYLON.Material.LightDirtyFlag);
  22161. },
  22162. enumerable: true,
  22163. configurable: true
  22164. });
  22165. Object.defineProperty(Scene.prototype, "defaultMaterial", {
  22166. /** The default material used on meshes when no material is affected */
  22167. get: function () {
  22168. if (!this._defaultMaterial) {
  22169. this._defaultMaterial = new BABYLON.StandardMaterial("default material", this);
  22170. }
  22171. return this._defaultMaterial;
  22172. },
  22173. /** The default material used on meshes when no material is affected */
  22174. set: function (value) {
  22175. this._defaultMaterial = value;
  22176. },
  22177. enumerable: true,
  22178. configurable: true
  22179. });
  22180. Object.defineProperty(Scene.prototype, "texturesEnabled", {
  22181. get: function () {
  22182. return this._texturesEnabled;
  22183. },
  22184. set: function (value) {
  22185. if (this._texturesEnabled === value) {
  22186. return;
  22187. }
  22188. this._texturesEnabled = value;
  22189. this.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  22190. },
  22191. enumerable: true,
  22192. configurable: true
  22193. });
  22194. Object.defineProperty(Scene.prototype, "skeletonsEnabled", {
  22195. get: function () {
  22196. return this._skeletonsEnabled;
  22197. },
  22198. set: function (value) {
  22199. if (this._skeletonsEnabled === value) {
  22200. return;
  22201. }
  22202. this._skeletonsEnabled = value;
  22203. this.markAllMaterialsAsDirty(BABYLON.Material.AttributesDirtyFlag);
  22204. },
  22205. enumerable: true,
  22206. configurable: true
  22207. });
  22208. Object.defineProperty(Scene.prototype, "postProcessRenderPipelineManager", {
  22209. get: function () {
  22210. if (!this._postProcessRenderPipelineManager) {
  22211. this._postProcessRenderPipelineManager = new BABYLON.PostProcessRenderPipelineManager();
  22212. }
  22213. return this._postProcessRenderPipelineManager;
  22214. },
  22215. enumerable: true,
  22216. configurable: true
  22217. });
  22218. Object.defineProperty(Scene.prototype, "mainSoundTrack", {
  22219. get: function () {
  22220. if (!this._mainSoundTrack) {
  22221. this._mainSoundTrack = new BABYLON.SoundTrack(this, { mainTrack: true });
  22222. }
  22223. return this._mainSoundTrack;
  22224. },
  22225. enumerable: true,
  22226. configurable: true
  22227. });
  22228. Object.defineProperty(Scene.prototype, "_isAlternateRenderingEnabled", {
  22229. get: function () {
  22230. return this._alternateRendering;
  22231. },
  22232. enumerable: true,
  22233. configurable: true
  22234. });
  22235. Object.defineProperty(Scene.prototype, "frustumPlanes", {
  22236. get: function () {
  22237. return this._frustumPlanes;
  22238. },
  22239. enumerable: true,
  22240. configurable: true
  22241. });
  22242. Object.defineProperty(Scene.prototype, "geometryBufferRenderer", {
  22243. /**
  22244. * Gets the current geometry buffer associated to the scene.
  22245. */
  22246. get: function () {
  22247. return this._geometryBufferRenderer;
  22248. },
  22249. /**
  22250. * Sets the current geometry buffer for the scene.
  22251. */
  22252. set: function (geometryBufferRenderer) {
  22253. if (geometryBufferRenderer && geometryBufferRenderer.isSupported) {
  22254. this._geometryBufferRenderer = geometryBufferRenderer;
  22255. }
  22256. },
  22257. enumerable: true,
  22258. configurable: true
  22259. });
  22260. Object.defineProperty(Scene.prototype, "debugLayer", {
  22261. // Properties
  22262. get: function () {
  22263. if (!this._debugLayer) {
  22264. this._debugLayer = new BABYLON.DebugLayer(this);
  22265. }
  22266. return this._debugLayer;
  22267. },
  22268. enumerable: true,
  22269. configurable: true
  22270. });
  22271. Object.defineProperty(Scene.prototype, "workerCollisions", {
  22272. get: function () {
  22273. return this._workerCollisions;
  22274. },
  22275. set: function (enabled) {
  22276. if (!BABYLON.CollisionCoordinatorLegacy) {
  22277. return;
  22278. }
  22279. enabled = (enabled && !!Worker && !!BABYLON.CollisionWorker);
  22280. this._workerCollisions = enabled;
  22281. if (this.collisionCoordinator) {
  22282. this.collisionCoordinator.destroy();
  22283. }
  22284. this.collisionCoordinator = enabled ? new BABYLON.CollisionCoordinatorWorker() : new BABYLON.CollisionCoordinatorLegacy();
  22285. this.collisionCoordinator.init(this);
  22286. },
  22287. enumerable: true,
  22288. configurable: true
  22289. });
  22290. Object.defineProperty(Scene.prototype, "selectionOctree", {
  22291. get: function () {
  22292. return this._selectionOctree;
  22293. },
  22294. enumerable: true,
  22295. configurable: true
  22296. });
  22297. Object.defineProperty(Scene.prototype, "meshUnderPointer", {
  22298. /**
  22299. * The mesh that is currently under the pointer.
  22300. * @return {BABYLON.AbstractMesh} mesh under the pointer/mouse cursor or null if none.
  22301. */
  22302. get: function () {
  22303. return this._pointerOverMesh;
  22304. },
  22305. enumerable: true,
  22306. configurable: true
  22307. });
  22308. Object.defineProperty(Scene.prototype, "pointerX", {
  22309. /**
  22310. * Current on-screen X position of the pointer
  22311. * @return {number} X position of the pointer
  22312. */
  22313. get: function () {
  22314. return this._pointerX;
  22315. },
  22316. enumerable: true,
  22317. configurable: true
  22318. });
  22319. Object.defineProperty(Scene.prototype, "pointerY", {
  22320. /**
  22321. * Current on-screen Y position of the pointer
  22322. * @return {number} Y position of the pointer
  22323. */
  22324. get: function () {
  22325. return this._pointerY;
  22326. },
  22327. enumerable: true,
  22328. configurable: true
  22329. });
  22330. Scene.prototype.getCachedMaterial = function () {
  22331. return this._cachedMaterial;
  22332. };
  22333. Scene.prototype.getCachedEffect = function () {
  22334. return this._cachedEffect;
  22335. };
  22336. Scene.prototype.getCachedVisibility = function () {
  22337. return this._cachedVisibility;
  22338. };
  22339. Scene.prototype.isCachedMaterialInvalid = function (material, effect, visibility) {
  22340. if (visibility === void 0) { visibility = 1; }
  22341. return this._cachedEffect !== effect || this._cachedMaterial !== material || this._cachedVisibility !== visibility;
  22342. };
  22343. Scene.prototype.getBoundingBoxRenderer = function () {
  22344. if (!this._boundingBoxRenderer) {
  22345. this._boundingBoxRenderer = new BABYLON.BoundingBoxRenderer(this);
  22346. }
  22347. return this._boundingBoxRenderer;
  22348. };
  22349. Scene.prototype.getOutlineRenderer = function () {
  22350. return this._outlineRenderer;
  22351. };
  22352. Scene.prototype.getEngine = function () {
  22353. return this._engine;
  22354. };
  22355. Scene.prototype.getTotalVertices = function () {
  22356. return this._totalVertices.current;
  22357. };
  22358. Object.defineProperty(Scene.prototype, "totalVerticesPerfCounter", {
  22359. get: function () {
  22360. return this._totalVertices;
  22361. },
  22362. enumerable: true,
  22363. configurable: true
  22364. });
  22365. Scene.prototype.getActiveIndices = function () {
  22366. return this._activeIndices.current;
  22367. };
  22368. Object.defineProperty(Scene.prototype, "totalActiveIndicesPerfCounter", {
  22369. get: function () {
  22370. return this._activeIndices;
  22371. },
  22372. enumerable: true,
  22373. configurable: true
  22374. });
  22375. Scene.prototype.getActiveParticles = function () {
  22376. return this._activeParticles.current;
  22377. };
  22378. Object.defineProperty(Scene.prototype, "activeParticlesPerfCounter", {
  22379. get: function () {
  22380. return this._activeParticles;
  22381. },
  22382. enumerable: true,
  22383. configurable: true
  22384. });
  22385. Scene.prototype.getActiveBones = function () {
  22386. return this._activeBones.current;
  22387. };
  22388. Object.defineProperty(Scene.prototype, "activeBonesPerfCounter", {
  22389. get: function () {
  22390. return this._activeBones;
  22391. },
  22392. enumerable: true,
  22393. configurable: true
  22394. });
  22395. // Stats
  22396. Scene.prototype.getInterFramePerfCounter = function () {
  22397. BABYLON.Tools.Warn("getInterFramePerfCounter is deprecated. Please use SceneInstrumentation class");
  22398. return 0;
  22399. };
  22400. Object.defineProperty(Scene.prototype, "interFramePerfCounter", {
  22401. get: function () {
  22402. BABYLON.Tools.Warn("interFramePerfCounter is deprecated. Please use SceneInstrumentation class");
  22403. return null;
  22404. },
  22405. enumerable: true,
  22406. configurable: true
  22407. });
  22408. Scene.prototype.getLastFrameDuration = function () {
  22409. BABYLON.Tools.Warn("getLastFrameDuration is deprecated. Please use SceneInstrumentation class");
  22410. return 0;
  22411. };
  22412. Object.defineProperty(Scene.prototype, "lastFramePerfCounter", {
  22413. get: function () {
  22414. BABYLON.Tools.Warn("lastFramePerfCounter is deprecated. Please use SceneInstrumentation class");
  22415. return null;
  22416. },
  22417. enumerable: true,
  22418. configurable: true
  22419. });
  22420. Scene.prototype.getEvaluateActiveMeshesDuration = function () {
  22421. BABYLON.Tools.Warn("getEvaluateActiveMeshesDuration is deprecated. Please use SceneInstrumentation class");
  22422. return 0;
  22423. };
  22424. Object.defineProperty(Scene.prototype, "evaluateActiveMeshesDurationPerfCounter", {
  22425. get: function () {
  22426. BABYLON.Tools.Warn("evaluateActiveMeshesDurationPerfCounter is deprecated. Please use SceneInstrumentation class");
  22427. return null;
  22428. },
  22429. enumerable: true,
  22430. configurable: true
  22431. });
  22432. Scene.prototype.getActiveMeshes = function () {
  22433. return this._activeMeshes;
  22434. };
  22435. Scene.prototype.getRenderTargetsDuration = function () {
  22436. BABYLON.Tools.Warn("getRenderTargetsDuration is deprecated. Please use SceneInstrumentation class");
  22437. return 0;
  22438. };
  22439. Scene.prototype.getRenderDuration = function () {
  22440. BABYLON.Tools.Warn("getRenderDuration is deprecated. Please use SceneInstrumentation class");
  22441. return 0;
  22442. };
  22443. Object.defineProperty(Scene.prototype, "renderDurationPerfCounter", {
  22444. get: function () {
  22445. BABYLON.Tools.Warn("renderDurationPerfCounter is deprecated. Please use SceneInstrumentation class");
  22446. return null;
  22447. },
  22448. enumerable: true,
  22449. configurable: true
  22450. });
  22451. Scene.prototype.getParticlesDuration = function () {
  22452. BABYLON.Tools.Warn("getParticlesDuration is deprecated. Please use SceneInstrumentation class");
  22453. return 0;
  22454. };
  22455. Object.defineProperty(Scene.prototype, "particlesDurationPerfCounter", {
  22456. get: function () {
  22457. BABYLON.Tools.Warn("particlesDurationPerfCounter is deprecated. Please use SceneInstrumentation class");
  22458. return null;
  22459. },
  22460. enumerable: true,
  22461. configurable: true
  22462. });
  22463. Scene.prototype.getSpritesDuration = function () {
  22464. BABYLON.Tools.Warn("getSpritesDuration is deprecated. Please use SceneInstrumentation class");
  22465. return 0;
  22466. };
  22467. Object.defineProperty(Scene.prototype, "spriteDuractionPerfCounter", {
  22468. get: function () {
  22469. BABYLON.Tools.Warn("spriteDuractionPerfCounter is deprecated. Please use SceneInstrumentation class");
  22470. return null;
  22471. },
  22472. enumerable: true,
  22473. configurable: true
  22474. });
  22475. Scene.prototype.getAnimationRatio = function () {
  22476. return this._animationRatio;
  22477. };
  22478. Scene.prototype.getRenderId = function () {
  22479. return this._renderId;
  22480. };
  22481. Scene.prototype.incrementRenderId = function () {
  22482. this._renderId++;
  22483. };
  22484. Scene.prototype._updatePointerPosition = function (evt) {
  22485. var canvasRect = this._engine.getRenderingCanvasClientRect();
  22486. if (!canvasRect) {
  22487. return;
  22488. }
  22489. this._pointerX = evt.clientX - canvasRect.left;
  22490. this._pointerY = evt.clientY - canvasRect.top;
  22491. this._unTranslatedPointerX = this._pointerX;
  22492. this._unTranslatedPointerY = this._pointerY;
  22493. };
  22494. Scene.prototype._createUbo = function () {
  22495. this._sceneUbo = new BABYLON.UniformBuffer(this._engine, undefined, true);
  22496. this._sceneUbo.addUniform("viewProjection", 16);
  22497. this._sceneUbo.addUniform("view", 16);
  22498. };
  22499. Scene.prototype._createAlternateUbo = function () {
  22500. this._alternateSceneUbo = new BABYLON.UniformBuffer(this._engine, undefined, true);
  22501. this._alternateSceneUbo.addUniform("viewProjection", 16);
  22502. this._alternateSceneUbo.addUniform("view", 16);
  22503. };
  22504. // Pointers handling
  22505. /**
  22506. * Use this method to simulate a pointer move on a mesh
  22507. * The pickResult parameter can be obtained from a scene.pick or scene.pickWithRay
  22508. * @param pickResult pickingInfo of the object wished to simulate pointer event on
  22509. * @param pointerEventInit pointer event state to be used when simulating the pointer event (eg. pointer id for multitouch)
  22510. */
  22511. Scene.prototype.simulatePointerMove = function (pickResult, pointerEventInit) {
  22512. var evt = new PointerEvent("pointermove", pointerEventInit);
  22513. return this._processPointerMove(pickResult, evt);
  22514. };
  22515. Scene.prototype._processPointerMove = function (pickResult, evt) {
  22516. var canvas = this._engine.getRenderingCanvas();
  22517. if (!canvas) {
  22518. return this;
  22519. }
  22520. if (pickResult && pickResult.hit && pickResult.pickedMesh) {
  22521. this.setPointerOverSprite(null);
  22522. this.setPointerOverMesh(pickResult.pickedMesh);
  22523. if (this._pointerOverMesh && this._pointerOverMesh.actionManager && this._pointerOverMesh.actionManager.hasPointerTriggers) {
  22524. if (this._pointerOverMesh.actionManager.hoverCursor) {
  22525. canvas.style.cursor = this._pointerOverMesh.actionManager.hoverCursor;
  22526. }
  22527. else {
  22528. canvas.style.cursor = this.hoverCursor;
  22529. }
  22530. }
  22531. else {
  22532. canvas.style.cursor = this.defaultCursor;
  22533. }
  22534. }
  22535. else {
  22536. this.setPointerOverMesh(null);
  22537. // Sprites
  22538. pickResult = this.pickSprite(this._unTranslatedPointerX, this._unTranslatedPointerY, this._spritePredicate, false, this.cameraToUseForPointers || undefined);
  22539. if (pickResult && pickResult.hit && pickResult.pickedSprite) {
  22540. this.setPointerOverSprite(pickResult.pickedSprite);
  22541. if (this._pointerOverSprite && this._pointerOverSprite.actionManager && this._pointerOverSprite.actionManager.hoverCursor) {
  22542. canvas.style.cursor = this._pointerOverSprite.actionManager.hoverCursor;
  22543. }
  22544. else {
  22545. canvas.style.cursor = this.hoverCursor;
  22546. }
  22547. }
  22548. else {
  22549. this.setPointerOverSprite(null);
  22550. // Restore pointer
  22551. canvas.style.cursor = this.defaultCursor;
  22552. }
  22553. }
  22554. if (pickResult) {
  22555. var type = evt.type === "mousewheel" || evt.type === "DOMMouseScroll" ? BABYLON.PointerEventTypes.POINTERWHEEL : BABYLON.PointerEventTypes.POINTERMOVE;
  22556. if (this.onPointerMove) {
  22557. this.onPointerMove(evt, pickResult, type);
  22558. }
  22559. if (this.onPointerObservable.hasObservers()) {
  22560. var pi = new BABYLON.PointerInfo(type, evt, pickResult);
  22561. this.onPointerObservable.notifyObservers(pi, type);
  22562. }
  22563. }
  22564. return this;
  22565. };
  22566. /**
  22567. * Use this method to simulate a pointer down on a mesh
  22568. * The pickResult parameter can be obtained from a scene.pick or scene.pickWithRay
  22569. * @param pickResult pickingInfo of the object wished to simulate pointer event on
  22570. * @param pointerEventInit pointer event state to be used when simulating the pointer event (eg. pointer id for multitouch)
  22571. */
  22572. Scene.prototype.simulatePointerDown = function (pickResult, pointerEventInit) {
  22573. var evt = new PointerEvent("pointerdown", pointerEventInit);
  22574. return this._processPointerDown(pickResult, evt);
  22575. };
  22576. Scene.prototype._processPointerDown = function (pickResult, evt) {
  22577. var _this = this;
  22578. if (pickResult && pickResult.hit && pickResult.pickedMesh) {
  22579. this._pickedDownMesh = pickResult.pickedMesh;
  22580. var actionManager = pickResult.pickedMesh.actionManager;
  22581. if (actionManager) {
  22582. if (actionManager.hasPickTriggers) {
  22583. actionManager.processTrigger(BABYLON.ActionManager.OnPickDownTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  22584. switch (evt.button) {
  22585. case 0:
  22586. actionManager.processTrigger(BABYLON.ActionManager.OnLeftPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  22587. break;
  22588. case 1:
  22589. actionManager.processTrigger(BABYLON.ActionManager.OnCenterPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  22590. break;
  22591. case 2:
  22592. actionManager.processTrigger(BABYLON.ActionManager.OnRightPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  22593. break;
  22594. }
  22595. }
  22596. if (actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnLongPressTrigger)) {
  22597. window.setTimeout(function () {
  22598. 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);
  22599. if (pickResult && pickResult.hit && pickResult.pickedMesh && actionManager) {
  22600. if (_this._totalPointersPressed !== 0 &&
  22601. ((new Date().getTime() - _this._startingPointerTime) > Scene.LongPressDelay) &&
  22602. (Math.abs(_this._startingPointerPosition.x - _this._pointerX) < Scene.DragMovementThreshold &&
  22603. Math.abs(_this._startingPointerPosition.y - _this._pointerY) < Scene.DragMovementThreshold)) {
  22604. _this._startingPointerTime = 0;
  22605. actionManager.processTrigger(BABYLON.ActionManager.OnLongPressTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  22606. }
  22607. }
  22608. }, Scene.LongPressDelay);
  22609. }
  22610. }
  22611. }
  22612. if (pickResult) {
  22613. var type = BABYLON.PointerEventTypes.POINTERDOWN;
  22614. if (this.onPointerDown) {
  22615. this.onPointerDown(evt, pickResult, type);
  22616. }
  22617. if (this.onPointerObservable.hasObservers()) {
  22618. var pi = new BABYLON.PointerInfo(type, evt, pickResult);
  22619. this.onPointerObservable.notifyObservers(pi, type);
  22620. }
  22621. }
  22622. return this;
  22623. };
  22624. /**
  22625. * Use this method to simulate a pointer up on a mesh
  22626. * The pickResult parameter can be obtained from a scene.pick or scene.pickWithRay
  22627. * @param pickResult pickingInfo of the object wished to simulate pointer event on
  22628. * @param pointerEventInit pointer event state to be used when simulating the pointer event (eg. pointer id for multitouch)
  22629. */
  22630. Scene.prototype.simulatePointerUp = function (pickResult, pointerEventInit) {
  22631. var evt = new PointerEvent("pointerup", pointerEventInit);
  22632. var clickInfo = new ClickInfo();
  22633. clickInfo.singleClick = true;
  22634. clickInfo.ignore = true;
  22635. return this._processPointerUp(pickResult, evt, clickInfo);
  22636. };
  22637. Scene.prototype._processPointerUp = function (pickResult, evt, clickInfo) {
  22638. if (pickResult && pickResult && pickResult.pickedMesh) {
  22639. this._pickedUpMesh = pickResult.pickedMesh;
  22640. if (this._pickedDownMesh === this._pickedUpMesh) {
  22641. if (this.onPointerPick) {
  22642. this.onPointerPick(evt, pickResult);
  22643. }
  22644. if (clickInfo.singleClick && !clickInfo.ignore && this.onPointerObservable.hasObservers()) {
  22645. var type_1 = BABYLON.PointerEventTypes.POINTERPICK;
  22646. var pi = new BABYLON.PointerInfo(type_1, evt, pickResult);
  22647. this.onPointerObservable.notifyObservers(pi, type_1);
  22648. }
  22649. }
  22650. if (pickResult.pickedMesh.actionManager) {
  22651. if (clickInfo.ignore) {
  22652. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickUpTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  22653. }
  22654. if (!clickInfo.hasSwiped && !clickInfo.ignore && clickInfo.singleClick) {
  22655. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  22656. }
  22657. if (clickInfo.doubleClick && !clickInfo.ignore && pickResult.pickedMesh.actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger)) {
  22658. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnDoublePickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  22659. }
  22660. }
  22661. }
  22662. if (this._pickedDownMesh &&
  22663. this._pickedDownMesh.actionManager &&
  22664. this._pickedDownMesh.actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnPickOutTrigger) &&
  22665. this._pickedDownMesh !== this._pickedUpMesh) {
  22666. this._pickedDownMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickOutTrigger, BABYLON.ActionEvent.CreateNew(this._pickedDownMesh, evt));
  22667. }
  22668. var type = BABYLON.PointerEventTypes.POINTERUP;
  22669. if (this.onPointerObservable.hasObservers()) {
  22670. if (!clickInfo.ignore) {
  22671. if (!clickInfo.hasSwiped) {
  22672. if (clickInfo.singleClick && this.onPointerObservable.hasSpecificMask(BABYLON.PointerEventTypes.POINTERTAP)) {
  22673. var type_2 = BABYLON.PointerEventTypes.POINTERTAP;
  22674. var pi = new BABYLON.PointerInfo(type_2, evt, pickResult);
  22675. this.onPointerObservable.notifyObservers(pi, type_2);
  22676. }
  22677. if (clickInfo.doubleClick && this.onPointerObservable.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP)) {
  22678. var type_3 = BABYLON.PointerEventTypes.POINTERDOUBLETAP;
  22679. var pi = new BABYLON.PointerInfo(type_3, evt, pickResult);
  22680. this.onPointerObservable.notifyObservers(pi, type_3);
  22681. }
  22682. }
  22683. }
  22684. else {
  22685. var pi = new BABYLON.PointerInfo(type, evt, pickResult);
  22686. this.onPointerObservable.notifyObservers(pi, type);
  22687. }
  22688. }
  22689. if (this.onPointerUp) {
  22690. this.onPointerUp(evt, pickResult, type);
  22691. }
  22692. return this;
  22693. };
  22694. /**
  22695. * Attach events to the canvas (To handle actionManagers triggers and raise onPointerMove, onPointerDown and onPointerUp
  22696. * @param attachUp defines if you want to attach events to pointerup
  22697. * @param attachDown defines if you want to attach events to pointerdown
  22698. * @param attachMove defines if you want to attach events to pointermove
  22699. */
  22700. Scene.prototype.attachControl = function (attachUp, attachDown, attachMove) {
  22701. var _this = this;
  22702. if (attachUp === void 0) { attachUp = true; }
  22703. if (attachDown === void 0) { attachDown = true; }
  22704. if (attachMove === void 0) { attachMove = true; }
  22705. this._initActionManager = function (act, clickInfo) {
  22706. if (!_this._meshPickProceed) {
  22707. var pickResult = _this.pick(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this.pointerDownPredicate, false, _this.cameraToUseForPointers);
  22708. _this._currentPickResult = pickResult;
  22709. if (pickResult) {
  22710. act = (pickResult.hit && pickResult.pickedMesh) ? pickResult.pickedMesh.actionManager : null;
  22711. }
  22712. _this._meshPickProceed = true;
  22713. }
  22714. return act;
  22715. };
  22716. this._delayedSimpleClick = function (btn, clickInfo, cb) {
  22717. // double click delay is over and that no double click has been raised since, or the 2 consecutive keys pressed are different
  22718. if ((new Date().getTime() - _this._previousStartingPointerTime > Scene.DoubleClickDelay && !_this._doubleClickOccured) ||
  22719. btn !== _this._previousButtonPressed) {
  22720. _this._doubleClickOccured = false;
  22721. clickInfo.singleClick = true;
  22722. clickInfo.ignore = false;
  22723. cb(clickInfo, _this._currentPickResult);
  22724. }
  22725. };
  22726. this._initClickEvent = function (obs1, obs2, evt, cb) {
  22727. var clickInfo = new ClickInfo();
  22728. _this._currentPickResult = null;
  22729. var act = null;
  22730. var checkPicking = obs1.hasSpecificMask(BABYLON.PointerEventTypes.POINTERPICK) || obs2.hasSpecificMask(BABYLON.PointerEventTypes.POINTERPICK)
  22731. || obs1.hasSpecificMask(BABYLON.PointerEventTypes.POINTERTAP) || obs2.hasSpecificMask(BABYLON.PointerEventTypes.POINTERTAP)
  22732. || obs1.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP) || obs2.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP);
  22733. if (!checkPicking && BABYLON.ActionManager && BABYLON.ActionManager.HasPickTriggers) {
  22734. act = _this._initActionManager(act, clickInfo);
  22735. if (act)
  22736. checkPicking = act.hasPickTriggers;
  22737. }
  22738. if (checkPicking) {
  22739. var btn = evt.button;
  22740. clickInfo.hasSwiped = Math.abs(_this._startingPointerPosition.x - _this._pointerX) > Scene.DragMovementThreshold ||
  22741. Math.abs(_this._startingPointerPosition.y - _this._pointerY) > Scene.DragMovementThreshold;
  22742. if (!clickInfo.hasSwiped) {
  22743. var checkSingleClickImmediately = !Scene.ExclusiveDoubleClickMode;
  22744. if (!checkSingleClickImmediately) {
  22745. checkSingleClickImmediately = !obs1.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP) &&
  22746. !obs2.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP);
  22747. if (checkSingleClickImmediately && !BABYLON.ActionManager.HasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger)) {
  22748. act = _this._initActionManager(act, clickInfo);
  22749. if (act)
  22750. checkSingleClickImmediately = !act.hasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger);
  22751. }
  22752. }
  22753. if (checkSingleClickImmediately) {
  22754. // single click detected if double click delay is over or two different successive keys pressed without exclusive double click or no double click required
  22755. if (new Date().getTime() - _this._previousStartingPointerTime > Scene.DoubleClickDelay ||
  22756. btn !== _this._previousButtonPressed) {
  22757. clickInfo.singleClick = true;
  22758. cb(clickInfo, _this._currentPickResult);
  22759. }
  22760. }
  22761. else {
  22762. // wait that no double click has been raised during the double click delay
  22763. _this._previousDelayedSimpleClickTimeout = _this._delayedSimpleClickTimeout;
  22764. _this._delayedSimpleClickTimeout = window.setTimeout(_this._delayedSimpleClick.bind(_this, btn, clickInfo, cb), Scene.DoubleClickDelay);
  22765. }
  22766. var checkDoubleClick = obs1.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP) ||
  22767. obs2.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP);
  22768. if (!checkDoubleClick && BABYLON.ActionManager.HasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger)) {
  22769. act = _this._initActionManager(act, clickInfo);
  22770. if (act)
  22771. checkDoubleClick = act.hasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger);
  22772. }
  22773. if (checkDoubleClick) {
  22774. // two successive keys pressed are equal, double click delay is not over and double click has not just occurred
  22775. if (btn === _this._previousButtonPressed &&
  22776. new Date().getTime() - _this._previousStartingPointerTime < Scene.DoubleClickDelay &&
  22777. !_this._doubleClickOccured) {
  22778. // pointer has not moved for 2 clicks, it's a double click
  22779. if (!clickInfo.hasSwiped &&
  22780. Math.abs(_this._previousStartingPointerPosition.x - _this._startingPointerPosition.x) < Scene.DragMovementThreshold &&
  22781. Math.abs(_this._previousStartingPointerPosition.y - _this._startingPointerPosition.y) < Scene.DragMovementThreshold) {
  22782. _this._previousStartingPointerTime = 0;
  22783. _this._doubleClickOccured = true;
  22784. clickInfo.doubleClick = true;
  22785. clickInfo.ignore = false;
  22786. if (Scene.ExclusiveDoubleClickMode && _this._previousDelayedSimpleClickTimeout) {
  22787. clearTimeout(_this._previousDelayedSimpleClickTimeout);
  22788. }
  22789. _this._previousDelayedSimpleClickTimeout = _this._delayedSimpleClickTimeout;
  22790. cb(clickInfo, _this._currentPickResult);
  22791. }
  22792. else {
  22793. _this._doubleClickOccured = false;
  22794. _this._previousStartingPointerTime = _this._startingPointerTime;
  22795. _this._previousStartingPointerPosition.x = _this._startingPointerPosition.x;
  22796. _this._previousStartingPointerPosition.y = _this._startingPointerPosition.y;
  22797. _this._previousButtonPressed = btn;
  22798. if (Scene.ExclusiveDoubleClickMode) {
  22799. if (_this._previousDelayedSimpleClickTimeout) {
  22800. clearTimeout(_this._previousDelayedSimpleClickTimeout);
  22801. }
  22802. _this._previousDelayedSimpleClickTimeout = _this._delayedSimpleClickTimeout;
  22803. cb(clickInfo, _this._previousPickResult);
  22804. }
  22805. else {
  22806. cb(clickInfo, _this._currentPickResult);
  22807. }
  22808. }
  22809. }
  22810. else {
  22811. _this._doubleClickOccured = false;
  22812. _this._previousStartingPointerTime = _this._startingPointerTime;
  22813. _this._previousStartingPointerPosition.x = _this._startingPointerPosition.x;
  22814. _this._previousStartingPointerPosition.y = _this._startingPointerPosition.y;
  22815. _this._previousButtonPressed = btn;
  22816. }
  22817. }
  22818. }
  22819. }
  22820. clickInfo.ignore = true;
  22821. cb(clickInfo, _this._currentPickResult);
  22822. };
  22823. this._spritePredicate = function (sprite) {
  22824. return sprite.isPickable && sprite.actionManager && sprite.actionManager.hasPointerTriggers;
  22825. };
  22826. this._onPointerMove = function (evt) {
  22827. _this._updatePointerPosition(evt);
  22828. // PreObservable support
  22829. if (_this.onPrePointerObservable.hasObservers()) {
  22830. var type = evt.type === "mousewheel" || evt.type === "DOMMouseScroll" ? BABYLON.PointerEventTypes.POINTERWHEEL : BABYLON.PointerEventTypes.POINTERMOVE;
  22831. var pi = new BABYLON.PointerInfoPre(type, evt, _this._unTranslatedPointerX, _this._unTranslatedPointerY);
  22832. _this.onPrePointerObservable.notifyObservers(pi, type);
  22833. if (pi.skipOnPointerObservable) {
  22834. return;
  22835. }
  22836. }
  22837. if (!_this.cameraToUseForPointers && !_this.activeCamera) {
  22838. return;
  22839. }
  22840. if (!_this.pointerMovePredicate) {
  22841. _this.pointerMovePredicate = function (mesh) { return mesh.isPickable && mesh.isVisible && mesh.isReady() && mesh.isEnabled() && (mesh.enablePointerMoveEvents || _this.constantlyUpdateMeshUnderPointer || (mesh.actionManager !== null && mesh.actionManager !== undefined)); };
  22842. }
  22843. // Meshes
  22844. var pickResult = _this.pick(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this.pointerMovePredicate, false, _this.cameraToUseForPointers);
  22845. _this._processPointerMove(pickResult, evt);
  22846. };
  22847. this._onPointerDown = function (evt) {
  22848. _this._totalPointersPressed++;
  22849. _this._pickedDownMesh = null;
  22850. _this._meshPickProceed = false;
  22851. _this._updatePointerPosition(evt);
  22852. if (_this.preventDefaultOnPointerDown && canvas) {
  22853. evt.preventDefault();
  22854. canvas.focus();
  22855. }
  22856. // PreObservable support
  22857. if (_this.onPrePointerObservable.hasObservers()) {
  22858. var type = BABYLON.PointerEventTypes.POINTERDOWN;
  22859. var pi = new BABYLON.PointerInfoPre(type, evt, _this._unTranslatedPointerX, _this._unTranslatedPointerY);
  22860. _this.onPrePointerObservable.notifyObservers(pi, type);
  22861. if (pi.skipOnPointerObservable) {
  22862. return;
  22863. }
  22864. }
  22865. if (!_this.cameraToUseForPointers && !_this.activeCamera) {
  22866. return;
  22867. }
  22868. _this._startingPointerPosition.x = _this._pointerX;
  22869. _this._startingPointerPosition.y = _this._pointerY;
  22870. _this._startingPointerTime = new Date().getTime();
  22871. if (!_this.pointerDownPredicate) {
  22872. _this.pointerDownPredicate = function (mesh) {
  22873. return mesh.isPickable && mesh.isVisible && mesh.isReady() && mesh.isEnabled();
  22874. };
  22875. }
  22876. // Meshes
  22877. _this._pickedDownMesh = null;
  22878. var pickResult = _this.pick(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this.pointerDownPredicate, false, _this.cameraToUseForPointers);
  22879. _this._processPointerDown(pickResult, evt);
  22880. // Sprites
  22881. _this._pickedDownSprite = null;
  22882. if (_this.spriteManagers.length > 0) {
  22883. pickResult = _this.pickSprite(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this._spritePredicate, false, _this.cameraToUseForPointers || undefined);
  22884. if (pickResult && pickResult.hit && pickResult.pickedSprite) {
  22885. if (pickResult.pickedSprite.actionManager) {
  22886. _this._pickedDownSprite = pickResult.pickedSprite;
  22887. switch (evt.button) {
  22888. case 0:
  22889. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnLeftPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  22890. break;
  22891. case 1:
  22892. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnCenterPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  22893. break;
  22894. case 2:
  22895. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnRightPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  22896. break;
  22897. }
  22898. if (pickResult.pickedSprite.actionManager) {
  22899. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickDownTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  22900. }
  22901. }
  22902. }
  22903. }
  22904. };
  22905. this._onPointerUp = function (evt) {
  22906. if (_this._totalPointersPressed === 0) {
  22907. return; // So we need to test it the pointer down was pressed before.
  22908. }
  22909. _this._totalPointersPressed--;
  22910. _this._pickedUpMesh = null;
  22911. _this._meshPickProceed = false;
  22912. _this._updatePointerPosition(evt);
  22913. _this._initClickEvent(_this.onPrePointerObservable, _this.onPointerObservable, evt, function (clickInfo, pickResult) {
  22914. // PreObservable support
  22915. if (_this.onPrePointerObservable.hasObservers()) {
  22916. if (!clickInfo.ignore) {
  22917. if (!clickInfo.hasSwiped) {
  22918. if (clickInfo.singleClick && _this.onPrePointerObservable.hasSpecificMask(BABYLON.PointerEventTypes.POINTERTAP)) {
  22919. var type = BABYLON.PointerEventTypes.POINTERTAP;
  22920. var pi = new BABYLON.PointerInfoPre(type, evt, _this._unTranslatedPointerX, _this._unTranslatedPointerY);
  22921. _this.onPrePointerObservable.notifyObservers(pi, type);
  22922. if (pi.skipOnPointerObservable) {
  22923. return;
  22924. }
  22925. }
  22926. if (clickInfo.doubleClick && _this.onPrePointerObservable.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP)) {
  22927. var type = BABYLON.PointerEventTypes.POINTERDOUBLETAP;
  22928. var pi = new BABYLON.PointerInfoPre(type, evt, _this._unTranslatedPointerX, _this._unTranslatedPointerY);
  22929. _this.onPrePointerObservable.notifyObservers(pi, type);
  22930. if (pi.skipOnPointerObservable) {
  22931. return;
  22932. }
  22933. }
  22934. }
  22935. }
  22936. else {
  22937. var type = BABYLON.PointerEventTypes.POINTERUP;
  22938. var pi = new BABYLON.PointerInfoPre(type, evt, _this._unTranslatedPointerX, _this._unTranslatedPointerY);
  22939. _this.onPrePointerObservable.notifyObservers(pi, type);
  22940. if (pi.skipOnPointerObservable) {
  22941. return;
  22942. }
  22943. }
  22944. }
  22945. if (!_this.cameraToUseForPointers && !_this.activeCamera) {
  22946. return;
  22947. }
  22948. if (!_this.pointerUpPredicate) {
  22949. _this.pointerUpPredicate = function (mesh) {
  22950. return mesh.isPickable && mesh.isVisible && mesh.isReady() && mesh.isEnabled();
  22951. };
  22952. }
  22953. // Meshes
  22954. if (!_this._meshPickProceed && (BABYLON.ActionManager && BABYLON.ActionManager.HasTriggers || _this.onPointerObservable.hasObservers())) {
  22955. _this._initActionManager(null, clickInfo);
  22956. }
  22957. if (!pickResult) {
  22958. pickResult = _this._currentPickResult;
  22959. }
  22960. _this._processPointerUp(pickResult, evt, clickInfo);
  22961. // Sprites
  22962. if (_this.spriteManagers.length > 0) {
  22963. var spritePickResult = _this.pickSprite(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this._spritePredicate, false, _this.cameraToUseForPointers || undefined);
  22964. if (spritePickResult) {
  22965. if (spritePickResult.hit && spritePickResult.pickedSprite) {
  22966. if (spritePickResult.pickedSprite.actionManager) {
  22967. spritePickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickUpTrigger, BABYLON.ActionEvent.CreateNewFromSprite(spritePickResult.pickedSprite, _this, evt));
  22968. if (spritePickResult.pickedSprite.actionManager) {
  22969. if (Math.abs(_this._startingPointerPosition.x - _this._pointerX) < Scene.DragMovementThreshold && Math.abs(_this._startingPointerPosition.y - _this._pointerY) < Scene.DragMovementThreshold) {
  22970. spritePickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(spritePickResult.pickedSprite, _this, evt));
  22971. }
  22972. }
  22973. }
  22974. }
  22975. if (_this._pickedDownSprite && _this._pickedDownSprite.actionManager && _this._pickedDownSprite !== spritePickResult.pickedSprite) {
  22976. _this._pickedDownSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickOutTrigger, BABYLON.ActionEvent.CreateNewFromSprite(_this._pickedDownSprite, _this, evt));
  22977. }
  22978. }
  22979. }
  22980. _this._previousPickResult = _this._currentPickResult;
  22981. });
  22982. };
  22983. this._onKeyDown = function (evt) {
  22984. var type = BABYLON.KeyboardEventTypes.KEYDOWN;
  22985. if (_this.onPreKeyboardObservable.hasObservers()) {
  22986. var pi = new BABYLON.KeyboardInfoPre(type, evt);
  22987. _this.onPreKeyboardObservable.notifyObservers(pi, type);
  22988. if (pi.skipOnPointerObservable) {
  22989. return;
  22990. }
  22991. }
  22992. if (_this.onKeyboardObservable.hasObservers()) {
  22993. var pi = new BABYLON.KeyboardInfo(type, evt);
  22994. _this.onKeyboardObservable.notifyObservers(pi, type);
  22995. }
  22996. if (_this.actionManager) {
  22997. _this.actionManager.processTrigger(BABYLON.ActionManager.OnKeyDownTrigger, BABYLON.ActionEvent.CreateNewFromScene(_this, evt));
  22998. }
  22999. };
  23000. this._onKeyUp = function (evt) {
  23001. var type = BABYLON.KeyboardEventTypes.KEYUP;
  23002. if (_this.onPreKeyboardObservable.hasObservers()) {
  23003. var pi = new BABYLON.KeyboardInfoPre(type, evt);
  23004. _this.onPreKeyboardObservable.notifyObservers(pi, type);
  23005. if (pi.skipOnPointerObservable) {
  23006. return;
  23007. }
  23008. }
  23009. if (_this.onKeyboardObservable.hasObservers()) {
  23010. var pi = new BABYLON.KeyboardInfo(type, evt);
  23011. _this.onKeyboardObservable.notifyObservers(pi, type);
  23012. }
  23013. if (_this.actionManager) {
  23014. _this.actionManager.processTrigger(BABYLON.ActionManager.OnKeyUpTrigger, BABYLON.ActionEvent.CreateNewFromScene(_this, evt));
  23015. }
  23016. };
  23017. var engine = this.getEngine();
  23018. this._onCanvasFocusObserver = engine.onCanvasFocusObservable.add(function () {
  23019. if (!canvas) {
  23020. return;
  23021. }
  23022. canvas.addEventListener("keydown", _this._onKeyDown, false);
  23023. canvas.addEventListener("keyup", _this._onKeyUp, false);
  23024. });
  23025. this._onCanvasBlurObserver = engine.onCanvasBlurObservable.add(function () {
  23026. if (!canvas) {
  23027. return;
  23028. }
  23029. canvas.removeEventListener("keydown", _this._onKeyDown);
  23030. canvas.removeEventListener("keyup", _this._onKeyUp);
  23031. });
  23032. var eventPrefix = BABYLON.Tools.GetPointerPrefix();
  23033. var canvas = this._engine.getRenderingCanvas();
  23034. if (!canvas) {
  23035. return;
  23036. }
  23037. if (attachMove) {
  23038. canvas.addEventListener(eventPrefix + "move", this._onPointerMove, false);
  23039. // Wheel
  23040. canvas.addEventListener('mousewheel', this._onPointerMove, false);
  23041. canvas.addEventListener('DOMMouseScroll', this._onPointerMove, false);
  23042. }
  23043. if (attachDown) {
  23044. canvas.addEventListener(eventPrefix + "down", this._onPointerDown, false);
  23045. }
  23046. if (attachUp) {
  23047. window.addEventListener(eventPrefix + "up", this._onPointerUp, false);
  23048. }
  23049. canvas.tabIndex = 1;
  23050. };
  23051. Scene.prototype.detachControl = function () {
  23052. var engine = this.getEngine();
  23053. var eventPrefix = BABYLON.Tools.GetPointerPrefix();
  23054. var canvas = engine.getRenderingCanvas();
  23055. if (!canvas) {
  23056. return;
  23057. }
  23058. canvas.removeEventListener(eventPrefix + "move", this._onPointerMove);
  23059. canvas.removeEventListener(eventPrefix + "down", this._onPointerDown);
  23060. window.removeEventListener(eventPrefix + "up", this._onPointerUp);
  23061. if (this._onCanvasBlurObserver) {
  23062. engine.onCanvasBlurObservable.remove(this._onCanvasBlurObserver);
  23063. }
  23064. if (this._onCanvasFocusObserver) {
  23065. engine.onCanvasFocusObservable.remove(this._onCanvasFocusObserver);
  23066. }
  23067. // Wheel
  23068. canvas.removeEventListener('mousewheel', this._onPointerMove);
  23069. canvas.removeEventListener('DOMMouseScroll', this._onPointerMove);
  23070. // Keyboard
  23071. canvas.removeEventListener("keydown", this._onKeyDown);
  23072. canvas.removeEventListener("keyup", this._onKeyUp);
  23073. // Observables
  23074. this.onKeyboardObservable.clear();
  23075. this.onPreKeyboardObservable.clear();
  23076. this.onPointerObservable.clear();
  23077. this.onPrePointerObservable.clear();
  23078. };
  23079. /**
  23080. * This function will check if the scene can be rendered (textures are loaded, shaders are compiled)
  23081. * Delay loaded resources are not taking in account
  23082. * @return true if all required resources are ready
  23083. */
  23084. Scene.prototype.isReady = function () {
  23085. if (this._isDisposed) {
  23086. return false;
  23087. }
  23088. if (this._pendingData.length > 0) {
  23089. return false;
  23090. }
  23091. var index;
  23092. var engine = this.getEngine();
  23093. // Geometries
  23094. for (index = 0; index < this._geometries.length; index++) {
  23095. var geometry = this._geometries[index];
  23096. if (geometry.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  23097. return false;
  23098. }
  23099. }
  23100. // Meshes
  23101. for (index = 0; index < this.meshes.length; index++) {
  23102. var mesh = this.meshes[index];
  23103. if (!mesh.isEnabled()) {
  23104. continue;
  23105. }
  23106. if (!mesh.subMeshes || mesh.subMeshes.length === 0) {
  23107. continue;
  23108. }
  23109. if (!mesh.isReady(true)) {
  23110. return false;
  23111. }
  23112. // Effect layers
  23113. var hardwareInstancedRendering = mesh.getClassName() === "InstancedMesh" || engine.getCaps().instancedArrays && mesh.instances.length > 0;
  23114. for (var _i = 0, _a = this.effectLayers; _i < _a.length; _i++) {
  23115. var layer = _a[_i];
  23116. if (!layer.hasMesh(mesh)) {
  23117. continue;
  23118. }
  23119. for (var _b = 0, _c = mesh.subMeshes; _b < _c.length; _b++) {
  23120. var subMesh = _c[_b];
  23121. if (!layer.isReady(subMesh, hardwareInstancedRendering)) {
  23122. return false;
  23123. }
  23124. }
  23125. }
  23126. }
  23127. // Post-processes
  23128. if (this.activeCameras && this.activeCameras.length > 0) {
  23129. for (var _d = 0, _e = this.activeCameras; _d < _e.length; _d++) {
  23130. var camera = _e[_d];
  23131. if (!camera.isReady(true)) {
  23132. return false;
  23133. }
  23134. }
  23135. }
  23136. else if (this.activeCamera) {
  23137. if (!this.activeCamera.isReady(true)) {
  23138. return false;
  23139. }
  23140. }
  23141. // Particles
  23142. for (var _f = 0, _g = this.particleSystems; _f < _g.length; _f++) {
  23143. var particleSystem = _g[_f];
  23144. if (!particleSystem.isReady()) {
  23145. return false;
  23146. }
  23147. }
  23148. return true;
  23149. };
  23150. Scene.prototype.resetCachedMaterial = function () {
  23151. this._cachedMaterial = null;
  23152. this._cachedEffect = null;
  23153. this._cachedVisibility = null;
  23154. };
  23155. Scene.prototype.registerBeforeRender = function (func) {
  23156. this.onBeforeRenderObservable.add(func);
  23157. };
  23158. Scene.prototype.unregisterBeforeRender = function (func) {
  23159. this.onBeforeRenderObservable.removeCallback(func);
  23160. };
  23161. Scene.prototype.registerAfterRender = function (func) {
  23162. this.onAfterRenderObservable.add(func);
  23163. };
  23164. Scene.prototype.unregisterAfterRender = function (func) {
  23165. this.onAfterRenderObservable.removeCallback(func);
  23166. };
  23167. Scene.prototype._executeOnceBeforeRender = function (func) {
  23168. var _this = this;
  23169. var execFunc = function () {
  23170. func();
  23171. setTimeout(function () {
  23172. _this.unregisterBeforeRender(execFunc);
  23173. });
  23174. };
  23175. this.registerBeforeRender(execFunc);
  23176. };
  23177. /**
  23178. * The provided function will run before render once and will be disposed afterwards.
  23179. * A timeout delay can be provided so that the function will be executed in N ms.
  23180. * The timeout is using the browser's native setTimeout so time percision cannot be guaranteed.
  23181. * @param func The function to be executed.
  23182. * @param timeout optional delay in ms
  23183. */
  23184. Scene.prototype.executeOnceBeforeRender = function (func, timeout) {
  23185. var _this = this;
  23186. if (timeout !== undefined) {
  23187. setTimeout(function () {
  23188. _this._executeOnceBeforeRender(func);
  23189. }, timeout);
  23190. }
  23191. else {
  23192. this._executeOnceBeforeRender(func);
  23193. }
  23194. };
  23195. Scene.prototype._addPendingData = function (data) {
  23196. this._pendingData.push(data);
  23197. };
  23198. Scene.prototype._removePendingData = function (data) {
  23199. var wasLoading = this.isLoading;
  23200. var index = this._pendingData.indexOf(data);
  23201. if (index !== -1) {
  23202. this._pendingData.splice(index, 1);
  23203. }
  23204. if (wasLoading && !this.isLoading) {
  23205. this.onDataLoadedObservable.notifyObservers(this);
  23206. }
  23207. };
  23208. Scene.prototype.getWaitingItemsCount = function () {
  23209. return this._pendingData.length;
  23210. };
  23211. Object.defineProperty(Scene.prototype, "isLoading", {
  23212. get: function () {
  23213. return this._pendingData.length > 0;
  23214. },
  23215. enumerable: true,
  23216. configurable: true
  23217. });
  23218. /**
  23219. * Registers a function to be executed when the scene is ready.
  23220. * @param {Function} func - the function to be executed.
  23221. */
  23222. Scene.prototype.executeWhenReady = function (func) {
  23223. var _this = this;
  23224. this.onReadyObservable.add(func);
  23225. if (this._executeWhenReadyTimeoutId !== -1) {
  23226. return;
  23227. }
  23228. this._executeWhenReadyTimeoutId = setTimeout(function () {
  23229. _this._checkIsReady();
  23230. }, 150);
  23231. };
  23232. /**
  23233. * Returns a promise that resolves when the scene is ready.
  23234. * @returns A promise that resolves when the scene is ready.
  23235. */
  23236. Scene.prototype.whenReadyAsync = function () {
  23237. var _this = this;
  23238. return new Promise(function (resolve) {
  23239. _this.executeWhenReady(function () {
  23240. resolve();
  23241. });
  23242. });
  23243. };
  23244. Scene.prototype._checkIsReady = function () {
  23245. var _this = this;
  23246. if (this.isReady()) {
  23247. this.onReadyObservable.notifyObservers(this);
  23248. this.onReadyObservable.clear();
  23249. this._executeWhenReadyTimeoutId = -1;
  23250. return;
  23251. }
  23252. this._executeWhenReadyTimeoutId = setTimeout(function () {
  23253. _this._checkIsReady();
  23254. }, 150);
  23255. };
  23256. // Animations
  23257. /**
  23258. * Will start the animation sequence of a given target
  23259. * @param target defines the target
  23260. * @param from defines from which frame should animation start
  23261. * @param to defines until which frame should animation run.
  23262. * @param weight defines the weight to apply to the animation (1.0 by default)
  23263. * @param loop defines if the animation loops
  23264. * @param speedRatio defines the speed in which to run the animation (1.0 by default)
  23265. * @param onAnimationEnd defines the function to be executed when the animation ends
  23266. * @param animatable defines an animatable object. If not provided a new one will be created from the given params
  23267. * @returns the animatable object created for this animation
  23268. */
  23269. Scene.prototype.beginWeightedAnimation = function (target, from, to, weight, loop, speedRatio, onAnimationEnd, animatable) {
  23270. if (weight === void 0) { weight = 1.0; }
  23271. if (speedRatio === void 0) { speedRatio = 1.0; }
  23272. var returnedAnimatable = this.beginAnimation(target, from, to, loop, speedRatio, onAnimationEnd, animatable, false);
  23273. returnedAnimatable.weight = weight;
  23274. return returnedAnimatable;
  23275. };
  23276. /**
  23277. * Will start the animation sequence of a given target
  23278. * @param target defines the target
  23279. * @param from defines from which frame should animation start
  23280. * @param to defines until which frame should animation run.
  23281. * @param loop defines if the animation loops
  23282. * @param speedRatio defines the speed in which to run the animation (1.0 by default)
  23283. * @param onAnimationEnd defines the function to be executed when the animation ends
  23284. * @param animatable defines an animatable object. If not provided a new one will be created from the given params
  23285. * @param stopCurrent defines if the current animations must be stopped first (true by default)
  23286. * @returns the animatable object created for this animation
  23287. */
  23288. Scene.prototype.beginAnimation = function (target, from, to, loop, speedRatio, onAnimationEnd, animatable, stopCurrent) {
  23289. if (speedRatio === void 0) { speedRatio = 1.0; }
  23290. if (stopCurrent === void 0) { stopCurrent = true; }
  23291. if (from > to && speedRatio > 0) {
  23292. speedRatio *= -1;
  23293. }
  23294. if (stopCurrent) {
  23295. this.stopAnimation(target);
  23296. }
  23297. if (!animatable) {
  23298. animatable = new BABYLON.Animatable(this, target, from, to, loop, speedRatio, onAnimationEnd);
  23299. }
  23300. // Local animations
  23301. if (target.animations) {
  23302. animatable.appendAnimations(target, target.animations);
  23303. }
  23304. // Children animations
  23305. if (target.getAnimatables) {
  23306. var animatables = target.getAnimatables();
  23307. for (var index = 0; index < animatables.length; index++) {
  23308. this.beginAnimation(animatables[index], from, to, loop, speedRatio, onAnimationEnd, animatable, stopCurrent);
  23309. }
  23310. }
  23311. animatable.reset();
  23312. return animatable;
  23313. };
  23314. /**
  23315. * Begin a new animation on a given node
  23316. * @param {BABYLON.Node} node defines the root node where the animation will take place
  23317. * @param {BABYLON.Animation[]} defines the list of animations to start
  23318. * @param {number} from defines the initial value
  23319. * @param {number} to defines the final value
  23320. * @param {boolean} loop defines if you want animation to loop (off by default)
  23321. * @param {number} speedRatio defines the speed ratio to apply to all animations
  23322. * @param onAnimationEnd defines the callback to call when an animation ends (will be called once per node)
  23323. * @returns the list of created animatables
  23324. */
  23325. Scene.prototype.beginDirectAnimation = function (target, animations, from, to, loop, speedRatio, onAnimationEnd) {
  23326. if (speedRatio === undefined) {
  23327. speedRatio = 1.0;
  23328. }
  23329. var animatable = new BABYLON.Animatable(this, target, from, to, loop, speedRatio, onAnimationEnd, animations);
  23330. return animatable;
  23331. };
  23332. /**
  23333. * Begin a new animation on a given node and its hierarchy
  23334. * @param {BABYLON.Node} node defines the root node where the animation will take place
  23335. * @param {boolean} 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.
  23336. * @param {BABYLON.Animation[]} defines the list of animations to start
  23337. * @param {number} from defines the initial value
  23338. * @param {number} to defines the final value
  23339. * @param {boolean} loop defines if you want animation to loop (off by default)
  23340. * @param {number} speedRatio defines the speed ratio to apply to all animations
  23341. * @param onAnimationEnd defines the callback to call when an animation ends (will be called once per node)
  23342. * @returns the list of animatables created for all nodes
  23343. */
  23344. Scene.prototype.beginDirectHierarchyAnimation = function (target, directDescendantsOnly, animations, from, to, loop, speedRatio, onAnimationEnd) {
  23345. var children = target.getDescendants(directDescendantsOnly);
  23346. var result = [];
  23347. for (var _i = 0, children_1 = children; _i < children_1.length; _i++) {
  23348. var child = children_1[_i];
  23349. result.push(this.beginDirectAnimation(child, animations, from, to, loop, speedRatio, onAnimationEnd));
  23350. }
  23351. return result;
  23352. };
  23353. Scene.prototype.getAnimatableByTarget = function (target) {
  23354. for (var index = 0; index < this._activeAnimatables.length; index++) {
  23355. if (this._activeAnimatables[index].target === target) {
  23356. return this._activeAnimatables[index];
  23357. }
  23358. }
  23359. return null;
  23360. };
  23361. /**
  23362. * Gets all animatables associated with a given target
  23363. * @param target defines the target to look animatables for
  23364. * @returns an array of Animatables
  23365. */
  23366. Scene.prototype.getAllAnimatablesByTarget = function (target) {
  23367. var result = [];
  23368. for (var index = 0; index < this._activeAnimatables.length; index++) {
  23369. if (this._activeAnimatables[index].target === target) {
  23370. result.push(this._activeAnimatables[index]);
  23371. }
  23372. }
  23373. return result;
  23374. };
  23375. Object.defineProperty(Scene.prototype, "animatables", {
  23376. get: function () {
  23377. return this._activeAnimatables;
  23378. },
  23379. enumerable: true,
  23380. configurable: true
  23381. });
  23382. /**
  23383. * Will stop the animation of the given target
  23384. * @param target - the target
  23385. * @param animationName - the name of the animation to stop (all animations will be stopped if empty)
  23386. */
  23387. Scene.prototype.stopAnimation = function (target, animationName) {
  23388. var animatables = this.getAllAnimatablesByTarget(target);
  23389. for (var _i = 0, animatables_1 = animatables; _i < animatables_1.length; _i++) {
  23390. var animatable = animatables_1[_i];
  23391. animatable.stop(animationName);
  23392. }
  23393. };
  23394. /**
  23395. * Stops and removes all animations that have been applied to the scene
  23396. */
  23397. Scene.prototype.stopAllAnimations = function () {
  23398. if (this._activeAnimatables) {
  23399. for (var i = 0; i < this._activeAnimatables.length; i++) {
  23400. this._activeAnimatables[i].stop();
  23401. }
  23402. this._activeAnimatables = [];
  23403. }
  23404. };
  23405. Scene.prototype._animate = function () {
  23406. if (!this.animationsEnabled || this._activeAnimatables.length === 0) {
  23407. return;
  23408. }
  23409. // Getting time
  23410. var now = BABYLON.Tools.Now;
  23411. if (!this._animationTimeLast) {
  23412. if (this._pendingData.length > 0) {
  23413. return;
  23414. }
  23415. this._animationTimeLast = now;
  23416. }
  23417. var deltaTime = this.useConstantAnimationDeltaTime ? 16.0 : (now - this._animationTimeLast) * this.animationTimeScale;
  23418. this._animationTime += deltaTime;
  23419. this._animationTimeLast = now;
  23420. for (var index = 0; index < this._activeAnimatables.length; index++) {
  23421. this._activeAnimatables[index]._animate(this._animationTime);
  23422. }
  23423. // Late animation bindings
  23424. this._processLateAnimationBindings();
  23425. };
  23426. /** @ignore */
  23427. Scene.prototype._registerTargetForLateAnimationBinding = function (runtimeAnimation) {
  23428. var target = runtimeAnimation.target;
  23429. this._registeredForLateAnimationBindings.pushNoDuplicate(target);
  23430. if (!target._lateAnimationHolders) {
  23431. target._lateAnimationHolders = {};
  23432. }
  23433. if (!target._lateAnimationHolders[runtimeAnimation.targetPath]) {
  23434. target._lateAnimationHolders[runtimeAnimation.targetPath] = {
  23435. totalWeight: 0,
  23436. animations: []
  23437. };
  23438. }
  23439. target._lateAnimationHolders[runtimeAnimation.targetPath].animations.push(runtimeAnimation);
  23440. target._lateAnimationHolders[runtimeAnimation.targetPath].totalWeight += runtimeAnimation.weight;
  23441. };
  23442. Scene.prototype._processLateAnimationBindings = function () {
  23443. if (!this._registeredForLateAnimationBindings.length) {
  23444. return;
  23445. }
  23446. for (var index = 0; index < this._registeredForLateAnimationBindings.length; index++) {
  23447. var target = this._registeredForLateAnimationBindings.data[index];
  23448. for (var path in target._lateAnimationHolders) {
  23449. var holder = target._lateAnimationHolders[path];
  23450. // Sanity check
  23451. if (!holder.animations[0].originalValue.scaleAndAddToRef) {
  23452. continue;
  23453. }
  23454. var normalizer = 1.0;
  23455. var finalValue = void 0;
  23456. if (holder.totalWeight < 1.0) {
  23457. // We need to mix the original value in
  23458. var originalValue = holder.animations[0].originalValue;
  23459. finalValue = originalValue.scale(1.0 - holder.totalWeight);
  23460. }
  23461. else {
  23462. // We need to normalize the weights
  23463. normalizer = holder.totalWeight;
  23464. }
  23465. for (var animIndex = 0; animIndex < holder.animations.length; animIndex++) {
  23466. var runtimeAnimation = holder.animations[animIndex];
  23467. if (finalValue) {
  23468. runtimeAnimation.currentValue.scaleAndAddToRef(runtimeAnimation.weight / normalizer, finalValue);
  23469. }
  23470. else {
  23471. finalValue = runtimeAnimation.currentValue.scale(runtimeAnimation.weight / normalizer);
  23472. }
  23473. }
  23474. runtimeAnimation.target[path] = finalValue;
  23475. }
  23476. target._lateAnimationHolders = {};
  23477. }
  23478. this._registeredForLateAnimationBindings.reset();
  23479. };
  23480. // Matrix
  23481. Scene.prototype._switchToAlternateCameraConfiguration = function (active) {
  23482. this._useAlternateCameraConfiguration = active;
  23483. };
  23484. Scene.prototype.getViewMatrix = function () {
  23485. return this._useAlternateCameraConfiguration ? this._alternateViewMatrix : this._viewMatrix;
  23486. };
  23487. Scene.prototype.getProjectionMatrix = function () {
  23488. return this._useAlternateCameraConfiguration ? this._alternateProjectionMatrix : this._projectionMatrix;
  23489. };
  23490. Scene.prototype.getTransformMatrix = function () {
  23491. return this._useAlternateCameraConfiguration ? this._alternateTransformMatrix : this._transformMatrix;
  23492. };
  23493. Scene.prototype.setTransformMatrix = function (view, projection) {
  23494. if (this._viewUpdateFlag === view.updateFlag && this._projectionUpdateFlag === projection.updateFlag) {
  23495. return;
  23496. }
  23497. this._viewUpdateFlag = view.updateFlag;
  23498. this._projectionUpdateFlag = projection.updateFlag;
  23499. this._viewMatrix = view;
  23500. this._projectionMatrix = projection;
  23501. this._viewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  23502. // Update frustum
  23503. if (!this._frustumPlanes) {
  23504. this._frustumPlanes = BABYLON.Frustum.GetPlanes(this._transformMatrix);
  23505. }
  23506. else {
  23507. BABYLON.Frustum.GetPlanesToRef(this._transformMatrix, this._frustumPlanes);
  23508. }
  23509. if (this.activeCamera && this.activeCamera._alternateCamera) {
  23510. var otherCamera = this.activeCamera._alternateCamera;
  23511. otherCamera.getViewMatrix().multiplyToRef(otherCamera.getProjectionMatrix(), BABYLON.Tmp.Matrix[0]);
  23512. BABYLON.Frustum.GetRightPlaneToRef(BABYLON.Tmp.Matrix[0], this._frustumPlanes[3]); // Replace right plane by second camera right plane
  23513. }
  23514. if (this._sceneUbo.useUbo) {
  23515. this._sceneUbo.updateMatrix("viewProjection", this._transformMatrix);
  23516. this._sceneUbo.updateMatrix("view", this._viewMatrix);
  23517. this._sceneUbo.update();
  23518. }
  23519. };
  23520. Scene.prototype._setAlternateTransformMatrix = function (view, projection) {
  23521. if (this._alternateViewUpdateFlag === view.updateFlag && this._alternateProjectionUpdateFlag === projection.updateFlag) {
  23522. return;
  23523. }
  23524. this._alternateViewUpdateFlag = view.updateFlag;
  23525. this._alternateProjectionUpdateFlag = projection.updateFlag;
  23526. this._alternateViewMatrix = view;
  23527. this._alternateProjectionMatrix = projection;
  23528. if (!this._alternateTransformMatrix) {
  23529. this._alternateTransformMatrix = BABYLON.Matrix.Zero();
  23530. }
  23531. this._alternateViewMatrix.multiplyToRef(this._alternateProjectionMatrix, this._alternateTransformMatrix);
  23532. if (!this._alternateSceneUbo) {
  23533. this._createAlternateUbo();
  23534. }
  23535. if (this._alternateSceneUbo.useUbo) {
  23536. this._alternateSceneUbo.updateMatrix("viewProjection", this._alternateTransformMatrix);
  23537. this._alternateSceneUbo.updateMatrix("view", this._alternateViewMatrix);
  23538. this._alternateSceneUbo.update();
  23539. }
  23540. };
  23541. Scene.prototype.getSceneUniformBuffer = function () {
  23542. return this._useAlternateCameraConfiguration ? this._alternateSceneUbo : this._sceneUbo;
  23543. };
  23544. // Methods
  23545. Scene.prototype.getUniqueId = function () {
  23546. var result = Scene._uniqueIdCounter;
  23547. Scene._uniqueIdCounter++;
  23548. return result;
  23549. };
  23550. Scene.prototype.addMesh = function (newMesh) {
  23551. this.meshes.push(newMesh);
  23552. //notify the collision coordinator
  23553. if (this.collisionCoordinator) {
  23554. this.collisionCoordinator.onMeshAdded(newMesh);
  23555. }
  23556. newMesh._resyncLightSources();
  23557. this.onNewMeshAddedObservable.notifyObservers(newMesh);
  23558. };
  23559. Scene.prototype.removeMesh = function (toRemove) {
  23560. var index = this.meshes.indexOf(toRemove);
  23561. if (index !== -1) {
  23562. // Remove from the scene if mesh found
  23563. this.meshes.splice(index, 1);
  23564. }
  23565. this.onMeshRemovedObservable.notifyObservers(toRemove);
  23566. return index;
  23567. };
  23568. Scene.prototype.addTransformNode = function (newTransformNode) {
  23569. this.transformNodes.push(newTransformNode);
  23570. this.onNewTransformNodeAddedObservable.notifyObservers(newTransformNode);
  23571. };
  23572. Scene.prototype.removeTransformNode = function (toRemove) {
  23573. var index = this.transformNodes.indexOf(toRemove);
  23574. if (index !== -1) {
  23575. // Remove from the scene if found
  23576. this.transformNodes.splice(index, 1);
  23577. }
  23578. this.onTransformNodeRemovedObservable.notifyObservers(toRemove);
  23579. return index;
  23580. };
  23581. Scene.prototype.removeSkeleton = function (toRemove) {
  23582. var index = this.skeletons.indexOf(toRemove);
  23583. if (index !== -1) {
  23584. // Remove from the scene if found
  23585. this.skeletons.splice(index, 1);
  23586. }
  23587. return index;
  23588. };
  23589. Scene.prototype.removeMorphTargetManager = function (toRemove) {
  23590. var index = this.morphTargetManagers.indexOf(toRemove);
  23591. if (index !== -1) {
  23592. // Remove from the scene if found
  23593. this.morphTargetManagers.splice(index, 1);
  23594. }
  23595. return index;
  23596. };
  23597. Scene.prototype.removeLight = function (toRemove) {
  23598. var index = this.lights.indexOf(toRemove);
  23599. if (index !== -1) {
  23600. // Remove from meshes
  23601. for (var _i = 0, _a = this.meshes; _i < _a.length; _i++) {
  23602. var mesh = _a[_i];
  23603. mesh._removeLightSource(toRemove);
  23604. }
  23605. // Remove from the scene if mesh found
  23606. this.lights.splice(index, 1);
  23607. this.sortLightsByPriority();
  23608. }
  23609. this.onLightRemovedObservable.notifyObservers(toRemove);
  23610. return index;
  23611. };
  23612. Scene.prototype.removeCamera = function (toRemove) {
  23613. var index = this.cameras.indexOf(toRemove);
  23614. if (index !== -1) {
  23615. // Remove from the scene if mesh found
  23616. this.cameras.splice(index, 1);
  23617. }
  23618. // Remove from activeCameras
  23619. var index2 = this.activeCameras.indexOf(toRemove);
  23620. if (index2 !== -1) {
  23621. // Remove from the scene if mesh found
  23622. this.activeCameras.splice(index2, 1);
  23623. }
  23624. // Reset the activeCamera
  23625. if (this.activeCamera === toRemove) {
  23626. if (this.cameras.length > 0) {
  23627. this.activeCamera = this.cameras[0];
  23628. }
  23629. else {
  23630. this.activeCamera = null;
  23631. }
  23632. }
  23633. this.onCameraRemovedObservable.notifyObservers(toRemove);
  23634. return index;
  23635. };
  23636. Scene.prototype.removeParticleSystem = function (toRemove) {
  23637. var index = this.particleSystems.indexOf(toRemove);
  23638. if (index !== -1) {
  23639. this.particleSystems.splice(index, 1);
  23640. }
  23641. return index;
  23642. };
  23643. ;
  23644. Scene.prototype.removeAnimation = function (toRemove) {
  23645. var index = this.animations.indexOf(toRemove);
  23646. if (index !== -1) {
  23647. this.animations.splice(index, 1);
  23648. }
  23649. return index;
  23650. };
  23651. ;
  23652. Scene.prototype.removeMultiMaterial = function (toRemove) {
  23653. var index = this.multiMaterials.indexOf(toRemove);
  23654. if (index !== -1) {
  23655. this.multiMaterials.splice(index, 1);
  23656. }
  23657. return index;
  23658. };
  23659. ;
  23660. Scene.prototype.removeMaterial = function (toRemove) {
  23661. var index = this.materials.indexOf(toRemove);
  23662. if (index !== -1) {
  23663. this.materials.splice(index, 1);
  23664. }
  23665. return index;
  23666. };
  23667. ;
  23668. Scene.prototype.removeLensFlareSystem = function (toRemove) {
  23669. var index = this.lensFlareSystems.indexOf(toRemove);
  23670. if (index !== -1) {
  23671. this.lensFlareSystems.splice(index, 1);
  23672. }
  23673. return index;
  23674. };
  23675. ;
  23676. Scene.prototype.removeActionManager = function (toRemove) {
  23677. var index = this._actionManagers.indexOf(toRemove);
  23678. if (index !== -1) {
  23679. this._actionManagers.splice(index, 1);
  23680. }
  23681. return index;
  23682. };
  23683. ;
  23684. Scene.prototype.addLight = function (newLight) {
  23685. this.lights.push(newLight);
  23686. this.sortLightsByPriority();
  23687. // Add light to all meshes (To support if the light is removed and then readded)
  23688. for (var _i = 0, _a = this.meshes; _i < _a.length; _i++) {
  23689. var mesh = _a[_i];
  23690. if (mesh._lightSources.indexOf(newLight) === -1) {
  23691. mesh._lightSources.push(newLight);
  23692. mesh._resyncLightSources();
  23693. }
  23694. }
  23695. this.onNewLightAddedObservable.notifyObservers(newLight);
  23696. };
  23697. Scene.prototype.sortLightsByPriority = function () {
  23698. if (this.requireLightSorting) {
  23699. this.lights.sort(BABYLON.Light.CompareLightsPriority);
  23700. }
  23701. };
  23702. Scene.prototype.addCamera = function (newCamera) {
  23703. this.cameras.push(newCamera);
  23704. this.onNewCameraAddedObservable.notifyObservers(newCamera);
  23705. };
  23706. Scene.prototype.addSkeleton = function (newSkeleton) {
  23707. this.skeletons.push(newSkeleton);
  23708. };
  23709. Scene.prototype.addParticleSystem = function (newParticleSystem) {
  23710. this.particleSystems.push(newParticleSystem);
  23711. };
  23712. Scene.prototype.addAnimation = function (newAnimation) {
  23713. this.animations.push(newAnimation);
  23714. };
  23715. Scene.prototype.addMultiMaterial = function (newMultiMaterial) {
  23716. this.multiMaterials.push(newMultiMaterial);
  23717. };
  23718. Scene.prototype.addMaterial = function (newMaterial) {
  23719. this.materials.push(newMaterial);
  23720. };
  23721. Scene.prototype.addMorphTargetManager = function (newMorphTargetManager) {
  23722. this.morphTargetManagers.push(newMorphTargetManager);
  23723. };
  23724. Scene.prototype.addGeometry = function (newGeometrie) {
  23725. this._geometries.push(newGeometrie);
  23726. };
  23727. Scene.prototype.addLensFlareSystem = function (newLensFlareSystem) {
  23728. this.lensFlareSystems.push(newLensFlareSystem);
  23729. };
  23730. Scene.prototype.addActionManager = function (newActionManager) {
  23731. this._actionManagers.push(newActionManager);
  23732. };
  23733. /**
  23734. * Switch active camera
  23735. * @param {Camera} newCamera - new active camera
  23736. * @param {boolean} attachControl - call attachControl for the new active camera (default: true)
  23737. */
  23738. Scene.prototype.switchActiveCamera = function (newCamera, attachControl) {
  23739. if (attachControl === void 0) { attachControl = true; }
  23740. var canvas = this._engine.getRenderingCanvas();
  23741. if (!canvas) {
  23742. return;
  23743. }
  23744. if (this.activeCamera) {
  23745. this.activeCamera.detachControl(canvas);
  23746. }
  23747. this.activeCamera = newCamera;
  23748. if (attachControl) {
  23749. newCamera.attachControl(canvas);
  23750. }
  23751. };
  23752. /**
  23753. * sets the active camera of the scene using its ID
  23754. * @param {string} id - the camera's ID
  23755. * @return {BABYLON.Camera|null} the new active camera or null if none found.
  23756. */
  23757. Scene.prototype.setActiveCameraByID = function (id) {
  23758. var camera = this.getCameraByID(id);
  23759. if (camera) {
  23760. this.activeCamera = camera;
  23761. return camera;
  23762. }
  23763. return null;
  23764. };
  23765. /**
  23766. * sets the active camera of the scene using its name
  23767. * @param {string} name - the camera's name
  23768. * @return {BABYLON.Camera|null} the new active camera or null if none found.
  23769. */
  23770. Scene.prototype.setActiveCameraByName = function (name) {
  23771. var camera = this.getCameraByName(name);
  23772. if (camera) {
  23773. this.activeCamera = camera;
  23774. return camera;
  23775. }
  23776. return null;
  23777. };
  23778. /**
  23779. * get an animation group using its name
  23780. * @param {string} the material's name
  23781. * @return {BABYLON.AnimationGroup|null} the animation group or null if none found.
  23782. */
  23783. Scene.prototype.getAnimationGroupByName = function (name) {
  23784. for (var index = 0; index < this.animationGroups.length; index++) {
  23785. if (this.animationGroups[index].name === name) {
  23786. return this.animationGroups[index];
  23787. }
  23788. }
  23789. return null;
  23790. };
  23791. /**
  23792. * get a material using its id
  23793. * @param {string} the material's ID
  23794. * @return {BABYLON.Material|null} the material or null if none found.
  23795. */
  23796. Scene.prototype.getMaterialByID = function (id) {
  23797. for (var index = 0; index < this.materials.length; index++) {
  23798. if (this.materials[index].id === id) {
  23799. return this.materials[index];
  23800. }
  23801. }
  23802. return null;
  23803. };
  23804. /**
  23805. * get a material using its name
  23806. * @param {string} the material's name
  23807. * @return {BABYLON.Material|null} the material or null if none found.
  23808. */
  23809. Scene.prototype.getMaterialByName = function (name) {
  23810. for (var index = 0; index < this.materials.length; index++) {
  23811. if (this.materials[index].name === name) {
  23812. return this.materials[index];
  23813. }
  23814. }
  23815. return null;
  23816. };
  23817. Scene.prototype.getLensFlareSystemByName = function (name) {
  23818. for (var index = 0; index < this.lensFlareSystems.length; index++) {
  23819. if (this.lensFlareSystems[index].name === name) {
  23820. return this.lensFlareSystems[index];
  23821. }
  23822. }
  23823. return null;
  23824. };
  23825. Scene.prototype.getLensFlareSystemByID = function (id) {
  23826. for (var index = 0; index < this.lensFlareSystems.length; index++) {
  23827. if (this.lensFlareSystems[index].id === id) {
  23828. return this.lensFlareSystems[index];
  23829. }
  23830. }
  23831. return null;
  23832. };
  23833. Scene.prototype.getCameraByID = function (id) {
  23834. for (var index = 0; index < this.cameras.length; index++) {
  23835. if (this.cameras[index].id === id) {
  23836. return this.cameras[index];
  23837. }
  23838. }
  23839. return null;
  23840. };
  23841. Scene.prototype.getCameraByUniqueID = function (uniqueId) {
  23842. for (var index = 0; index < this.cameras.length; index++) {
  23843. if (this.cameras[index].uniqueId === uniqueId) {
  23844. return this.cameras[index];
  23845. }
  23846. }
  23847. return null;
  23848. };
  23849. /**
  23850. * get a camera using its name
  23851. * @param {string} the camera's name
  23852. * @return {BABYLON.Camera|null} the camera or null if none found.
  23853. */
  23854. Scene.prototype.getCameraByName = function (name) {
  23855. for (var index = 0; index < this.cameras.length; index++) {
  23856. if (this.cameras[index].name === name) {
  23857. return this.cameras[index];
  23858. }
  23859. }
  23860. return null;
  23861. };
  23862. /**
  23863. * get a bone using its id
  23864. * @param {string} the bone's id
  23865. * @return {BABYLON.Bone|null} the bone or null if not found
  23866. */
  23867. Scene.prototype.getBoneByID = function (id) {
  23868. for (var skeletonIndex = 0; skeletonIndex < this.skeletons.length; skeletonIndex++) {
  23869. var skeleton = this.skeletons[skeletonIndex];
  23870. for (var boneIndex = 0; boneIndex < skeleton.bones.length; boneIndex++) {
  23871. if (skeleton.bones[boneIndex].id === id) {
  23872. return skeleton.bones[boneIndex];
  23873. }
  23874. }
  23875. }
  23876. return null;
  23877. };
  23878. /**
  23879. * get a bone using its id
  23880. * @param {string} the bone's name
  23881. * @return {BABYLON.Bone|null} the bone or null if not found
  23882. */
  23883. Scene.prototype.getBoneByName = function (name) {
  23884. for (var skeletonIndex = 0; skeletonIndex < this.skeletons.length; skeletonIndex++) {
  23885. var skeleton = this.skeletons[skeletonIndex];
  23886. for (var boneIndex = 0; boneIndex < skeleton.bones.length; boneIndex++) {
  23887. if (skeleton.bones[boneIndex].name === name) {
  23888. return skeleton.bones[boneIndex];
  23889. }
  23890. }
  23891. }
  23892. return null;
  23893. };
  23894. /**
  23895. * get a light node using its name
  23896. * @param {string} the light's name
  23897. * @return {BABYLON.Light|null} the light or null if none found.
  23898. */
  23899. Scene.prototype.getLightByName = function (name) {
  23900. for (var index = 0; index < this.lights.length; index++) {
  23901. if (this.lights[index].name === name) {
  23902. return this.lights[index];
  23903. }
  23904. }
  23905. return null;
  23906. };
  23907. /**
  23908. * get a light node using its ID
  23909. * @param {string} the light's id
  23910. * @return {BABYLON.Light|null} the light or null if none found.
  23911. */
  23912. Scene.prototype.getLightByID = function (id) {
  23913. for (var index = 0; index < this.lights.length; index++) {
  23914. if (this.lights[index].id === id) {
  23915. return this.lights[index];
  23916. }
  23917. }
  23918. return null;
  23919. };
  23920. /**
  23921. * get a light node using its scene-generated unique ID
  23922. * @param {number} the light's unique id
  23923. * @return {BABYLON.Light|null} the light or null if none found.
  23924. */
  23925. Scene.prototype.getLightByUniqueID = function (uniqueId) {
  23926. for (var index = 0; index < this.lights.length; index++) {
  23927. if (this.lights[index].uniqueId === uniqueId) {
  23928. return this.lights[index];
  23929. }
  23930. }
  23931. return null;
  23932. };
  23933. /**
  23934. * get a particle system by id
  23935. * @param id {number} the particle system id
  23936. * @return {BABYLON.IParticleSystem|null} the corresponding system or null if none found.
  23937. */
  23938. Scene.prototype.getParticleSystemByID = function (id) {
  23939. for (var index = 0; index < this.particleSystems.length; index++) {
  23940. if (this.particleSystems[index].id === id) {
  23941. return this.particleSystems[index];
  23942. }
  23943. }
  23944. return null;
  23945. };
  23946. /**
  23947. * get a geometry using its ID
  23948. * @param {string} the geometry's id
  23949. * @return {BABYLON.Geometry|null} the geometry or null if none found.
  23950. */
  23951. Scene.prototype.getGeometryByID = function (id) {
  23952. for (var index = 0; index < this._geometries.length; index++) {
  23953. if (this._geometries[index].id === id) {
  23954. return this._geometries[index];
  23955. }
  23956. }
  23957. return null;
  23958. };
  23959. /**
  23960. * add a new geometry to this scene.
  23961. * @param {BABYLON.Geometry} geometry - the geometry to be added to the scene.
  23962. * @param {boolean} [force] - force addition, even if a geometry with this ID already exists
  23963. * @return {boolean} was the geometry added or not
  23964. */
  23965. Scene.prototype.pushGeometry = function (geometry, force) {
  23966. if (!force && this.getGeometryByID(geometry.id)) {
  23967. return false;
  23968. }
  23969. this._geometries.push(geometry);
  23970. //notify the collision coordinator
  23971. if (this.collisionCoordinator) {
  23972. this.collisionCoordinator.onGeometryAdded(geometry);
  23973. }
  23974. this.onNewGeometryAddedObservable.notifyObservers(geometry);
  23975. return true;
  23976. };
  23977. /**
  23978. * Removes an existing geometry
  23979. * @param {BABYLON.Geometry} geometry - the geometry to be removed from the scene.
  23980. * @return {boolean} was the geometry removed or not
  23981. */
  23982. Scene.prototype.removeGeometry = function (geometry) {
  23983. var index = this._geometries.indexOf(geometry);
  23984. if (index > -1) {
  23985. this._geometries.splice(index, 1);
  23986. //notify the collision coordinator
  23987. if (this.collisionCoordinator) {
  23988. this.collisionCoordinator.onGeometryDeleted(geometry);
  23989. }
  23990. this.onGeometryRemovedObservable.notifyObservers(geometry);
  23991. return true;
  23992. }
  23993. return false;
  23994. };
  23995. Scene.prototype.getGeometries = function () {
  23996. return this._geometries;
  23997. };
  23998. /**
  23999. * Get the first added mesh found of a given ID
  24000. * @param {string} id - the id to search for
  24001. * @return {BABYLON.AbstractMesh|null} the mesh found or null if not found at all.
  24002. */
  24003. Scene.prototype.getMeshByID = function (id) {
  24004. for (var index = 0; index < this.meshes.length; index++) {
  24005. if (this.meshes[index].id === id) {
  24006. return this.meshes[index];
  24007. }
  24008. }
  24009. return null;
  24010. };
  24011. Scene.prototype.getMeshesByID = function (id) {
  24012. return this.meshes.filter(function (m) {
  24013. return m.id === id;
  24014. });
  24015. };
  24016. /**
  24017. * Get the first added transform node found of a given ID
  24018. * @param {string} id - the id to search for
  24019. * @return {BABYLON.TransformNode|null} the transform node found or null if not found at all.
  24020. */
  24021. Scene.prototype.getTransformNodeByID = function (id) {
  24022. for (var index = 0; index < this.transformNodes.length; index++) {
  24023. if (this.transformNodes[index].id === id) {
  24024. return this.transformNodes[index];
  24025. }
  24026. }
  24027. return null;
  24028. };
  24029. Scene.prototype.getTransformNodesByID = function (id) {
  24030. return this.transformNodes.filter(function (m) {
  24031. return m.id === id;
  24032. });
  24033. };
  24034. /**
  24035. * Get a mesh with its auto-generated unique id
  24036. * @param {number} uniqueId - the unique id to search for
  24037. * @return {BABYLON.AbstractMesh|null} the mesh found or null if not found at all.
  24038. */
  24039. Scene.prototype.getMeshByUniqueID = function (uniqueId) {
  24040. for (var index = 0; index < this.meshes.length; index++) {
  24041. if (this.meshes[index].uniqueId === uniqueId) {
  24042. return this.meshes[index];
  24043. }
  24044. }
  24045. return null;
  24046. };
  24047. /**
  24048. * Get a the last added mesh found of a given ID
  24049. * @param {string} id - the id to search for
  24050. * @return {BABYLON.AbstractMesh|null} the mesh found or null if not found at all.
  24051. */
  24052. Scene.prototype.getLastMeshByID = function (id) {
  24053. for (var index = this.meshes.length - 1; index >= 0; index--) {
  24054. if (this.meshes[index].id === id) {
  24055. return this.meshes[index];
  24056. }
  24057. }
  24058. return null;
  24059. };
  24060. /**
  24061. * Get a the last added node (Mesh, Camera, Light) found of a given ID
  24062. * @param {string} id - the id to search for
  24063. * @return {BABYLON.Node|null} the node found or null if not found at all.
  24064. */
  24065. Scene.prototype.getLastEntryByID = function (id) {
  24066. var index;
  24067. for (index = this.meshes.length - 1; index >= 0; index--) {
  24068. if (this.meshes[index].id === id) {
  24069. return this.meshes[index];
  24070. }
  24071. }
  24072. for (index = this.transformNodes.length - 1; index >= 0; index--) {
  24073. if (this.transformNodes[index].id === id) {
  24074. return this.transformNodes[index];
  24075. }
  24076. }
  24077. for (index = this.cameras.length - 1; index >= 0; index--) {
  24078. if (this.cameras[index].id === id) {
  24079. return this.cameras[index];
  24080. }
  24081. }
  24082. for (index = this.lights.length - 1; index >= 0; index--) {
  24083. if (this.lights[index].id === id) {
  24084. return this.lights[index];
  24085. }
  24086. }
  24087. return null;
  24088. };
  24089. Scene.prototype.getNodeByID = function (id) {
  24090. var mesh = this.getMeshByID(id);
  24091. if (mesh) {
  24092. return mesh;
  24093. }
  24094. var light = this.getLightByID(id);
  24095. if (light) {
  24096. return light;
  24097. }
  24098. var camera = this.getCameraByID(id);
  24099. if (camera) {
  24100. return camera;
  24101. }
  24102. var bone = this.getBoneByID(id);
  24103. return bone;
  24104. };
  24105. Scene.prototype.getNodeByName = function (name) {
  24106. var mesh = this.getMeshByName(name);
  24107. if (mesh) {
  24108. return mesh;
  24109. }
  24110. var light = this.getLightByName(name);
  24111. if (light) {
  24112. return light;
  24113. }
  24114. var camera = this.getCameraByName(name);
  24115. if (camera) {
  24116. return camera;
  24117. }
  24118. var bone = this.getBoneByName(name);
  24119. return bone;
  24120. };
  24121. Scene.prototype.getMeshByName = function (name) {
  24122. for (var index = 0; index < this.meshes.length; index++) {
  24123. if (this.meshes[index].name === name) {
  24124. return this.meshes[index];
  24125. }
  24126. }
  24127. return null;
  24128. };
  24129. Scene.prototype.getTransformNodeByName = function (name) {
  24130. for (var index = 0; index < this.transformNodes.length; index++) {
  24131. if (this.transformNodes[index].name === name) {
  24132. return this.transformNodes[index];
  24133. }
  24134. }
  24135. return null;
  24136. };
  24137. Scene.prototype.getSoundByName = function (name) {
  24138. var index;
  24139. if (BABYLON.AudioEngine) {
  24140. for (index = 0; index < this.mainSoundTrack.soundCollection.length; index++) {
  24141. if (this.mainSoundTrack.soundCollection[index].name === name) {
  24142. return this.mainSoundTrack.soundCollection[index];
  24143. }
  24144. }
  24145. for (var sdIndex = 0; sdIndex < this.soundTracks.length; sdIndex++) {
  24146. for (index = 0; index < this.soundTracks[sdIndex].soundCollection.length; index++) {
  24147. if (this.soundTracks[sdIndex].soundCollection[index].name === name) {
  24148. return this.soundTracks[sdIndex].soundCollection[index];
  24149. }
  24150. }
  24151. }
  24152. }
  24153. return null;
  24154. };
  24155. Scene.prototype.getLastSkeletonByID = function (id) {
  24156. for (var index = this.skeletons.length - 1; index >= 0; index--) {
  24157. if (this.skeletons[index].id === id) {
  24158. return this.skeletons[index];
  24159. }
  24160. }
  24161. return null;
  24162. };
  24163. Scene.prototype.getSkeletonById = function (id) {
  24164. for (var index = 0; index < this.skeletons.length; index++) {
  24165. if (this.skeletons[index].id === id) {
  24166. return this.skeletons[index];
  24167. }
  24168. }
  24169. return null;
  24170. };
  24171. Scene.prototype.getSkeletonByName = function (name) {
  24172. for (var index = 0; index < this.skeletons.length; index++) {
  24173. if (this.skeletons[index].name === name) {
  24174. return this.skeletons[index];
  24175. }
  24176. }
  24177. return null;
  24178. };
  24179. Scene.prototype.getMorphTargetManagerById = function (id) {
  24180. for (var index = 0; index < this.morphTargetManagers.length; index++) {
  24181. if (this.morphTargetManagers[index].uniqueId === id) {
  24182. return this.morphTargetManagers[index];
  24183. }
  24184. }
  24185. return null;
  24186. };
  24187. Scene.prototype.isActiveMesh = function (mesh) {
  24188. return (this._activeMeshes.indexOf(mesh) !== -1);
  24189. };
  24190. /**
  24191. * Return a the first highlight layer of the scene with a given name.
  24192. * @param name The name of the highlight layer to look for.
  24193. * @return The highlight layer if found otherwise null.
  24194. */
  24195. Scene.prototype.getHighlightLayerByName = function (name) {
  24196. for (var index = 0; index < this.effectLayers.length; index++) {
  24197. if (this.effectLayers[index].name === name && this.effectLayers[index].getEffectName() === BABYLON.HighlightLayer.EffectName) {
  24198. return this.effectLayers[index];
  24199. }
  24200. }
  24201. return null;
  24202. };
  24203. /**
  24204. * Return a the first highlight layer of the scene with a given name.
  24205. * @param name The name of the highlight layer to look for.
  24206. * @return The highlight layer if found otherwise null.
  24207. */
  24208. Scene.prototype.getGlowLayerByName = function (name) {
  24209. for (var index = 0; index < this.effectLayers.length; index++) {
  24210. if (this.effectLayers[index].name === name && this.effectLayers[index].getEffectName() === BABYLON.GlowLayer.EffectName) {
  24211. return this.effectLayers[index];
  24212. }
  24213. }
  24214. return null;
  24215. };
  24216. Object.defineProperty(Scene.prototype, "uid", {
  24217. /**
  24218. * Return a unique id as a string which can serve as an identifier for the scene
  24219. */
  24220. get: function () {
  24221. if (!this._uid) {
  24222. this._uid = BABYLON.Tools.RandomId();
  24223. }
  24224. return this._uid;
  24225. },
  24226. enumerable: true,
  24227. configurable: true
  24228. });
  24229. /**
  24230. * Add an externaly attached data from its key.
  24231. * This method call will fail and return false, if such key already exists.
  24232. * If you don't care and just want to get the data no matter what, use the more convenient getOrAddExternalDataWithFactory() method.
  24233. * @param key the unique key that identifies the data
  24234. * @param data the data object to associate to the key for this Engine instance
  24235. * @return true if no such key were already present and the data was added successfully, false otherwise
  24236. */
  24237. Scene.prototype.addExternalData = function (key, data) {
  24238. if (!this._externalData) {
  24239. this._externalData = new BABYLON.StringDictionary();
  24240. }
  24241. return this._externalData.add(key, data);
  24242. };
  24243. /**
  24244. * Get an externaly attached data from its key
  24245. * @param key the unique key that identifies the data
  24246. * @return the associated data, if present (can be null), or undefined if not present
  24247. */
  24248. Scene.prototype.getExternalData = function (key) {
  24249. if (!this._externalData) {
  24250. return null;
  24251. }
  24252. return this._externalData.get(key);
  24253. };
  24254. /**
  24255. * Get an externaly attached data from its key, create it using a factory if it's not already present
  24256. * @param key the unique key that identifies the data
  24257. * @param factory the factory that will be called to create the instance if and only if it doesn't exists
  24258. * @return the associated data, can be null if the factory returned null.
  24259. */
  24260. Scene.prototype.getOrAddExternalDataWithFactory = function (key, factory) {
  24261. if (!this._externalData) {
  24262. this._externalData = new BABYLON.StringDictionary();
  24263. }
  24264. return this._externalData.getOrAddWithFactory(key, factory);
  24265. };
  24266. /**
  24267. * Remove an externaly attached data from the Engine instance
  24268. * @param key the unique key that identifies the data
  24269. * @return true if the data was successfully removed, false if it doesn't exist
  24270. */
  24271. Scene.prototype.removeExternalData = function (key) {
  24272. return this._externalData.remove(key);
  24273. };
  24274. Scene.prototype._evaluateSubMesh = function (subMesh, mesh) {
  24275. if (this.dispatchAllSubMeshesOfActiveMeshes || mesh.alwaysSelectAsActiveMesh || mesh.subMeshes.length === 1 || subMesh.isInFrustum(this._frustumPlanes)) {
  24276. if (mesh.showSubMeshesBoundingBox) {
  24277. var boundingInfo = subMesh.getBoundingInfo();
  24278. if (boundingInfo !== null && boundingInfo !== undefined) {
  24279. this.getBoundingBoxRenderer().renderList.push(boundingInfo.boundingBox);
  24280. }
  24281. }
  24282. var material = subMesh.getMaterial();
  24283. if (material !== null && material !== undefined) {
  24284. // Render targets
  24285. if (material.getRenderTargetTextures !== undefined) {
  24286. if (this._processedMaterials.indexOf(material) === -1) {
  24287. this._processedMaterials.push(material);
  24288. this._renderTargets.concatWithNoDuplicate(material.getRenderTargetTextures());
  24289. }
  24290. }
  24291. // Dispatch
  24292. this._activeIndices.addCount(subMesh.indexCount, false);
  24293. this._renderingManager.dispatch(subMesh, mesh, material);
  24294. }
  24295. }
  24296. };
  24297. /**
  24298. * Clear the processed materials smart array preventing retention point in material dispose.
  24299. */
  24300. Scene.prototype.freeProcessedMaterials = function () {
  24301. this._processedMaterials.dispose();
  24302. };
  24303. /**
  24304. * Clear the active meshes smart array preventing retention point in mesh dispose.
  24305. */
  24306. Scene.prototype.freeActiveMeshes = function () {
  24307. this._activeMeshes.dispose();
  24308. if (this.activeCamera && this.activeCamera._activeMeshes) {
  24309. this.activeCamera._activeMeshes.dispose();
  24310. }
  24311. if (this.activeCameras) {
  24312. for (var i = 0; i < this.activeCameras.length; i++) {
  24313. var activeCamera = this.activeCameras[i];
  24314. if (activeCamera && activeCamera._activeMeshes) {
  24315. activeCamera._activeMeshes.dispose();
  24316. }
  24317. }
  24318. }
  24319. };
  24320. /**
  24321. * Clear the info related to rendering groups preventing retention points during dispose.
  24322. */
  24323. Scene.prototype.freeRenderingGroups = function () {
  24324. if (this._renderingManager) {
  24325. this._renderingManager.freeRenderingGroups();
  24326. }
  24327. if (this.textures) {
  24328. for (var i = 0; i < this.textures.length; i++) {
  24329. var texture = this.textures[i];
  24330. if (texture && texture.renderList) {
  24331. texture.freeRenderingGroups();
  24332. }
  24333. }
  24334. }
  24335. };
  24336. Scene.prototype._isInIntermediateRendering = function () {
  24337. return this._intermediateRendering;
  24338. };
  24339. Scene.prototype.setActiveMeshCandidateProvider = function (provider) {
  24340. this._activeMeshCandidateProvider = provider;
  24341. };
  24342. Scene.prototype.getActiveMeshCandidateProvider = function () {
  24343. return this._activeMeshCandidateProvider;
  24344. };
  24345. /**
  24346. * Use this function to stop evaluating active meshes. The current list will be keep alive between frames
  24347. */
  24348. Scene.prototype.freezeActiveMeshes = function () {
  24349. if (!this.activeCamera) {
  24350. return this;
  24351. }
  24352. if (!this._frustumPlanes) {
  24353. this.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix());
  24354. }
  24355. this._evaluateActiveMeshes();
  24356. this._activeMeshesFrozen = true;
  24357. return this;
  24358. };
  24359. /**
  24360. * Use this function to restart evaluating active meshes on every frame
  24361. */
  24362. Scene.prototype.unfreezeActiveMeshes = function () {
  24363. this._activeMeshesFrozen = false;
  24364. return this;
  24365. };
  24366. Scene.prototype._evaluateActiveMeshes = function () {
  24367. if (this._activeMeshesFrozen && this._activeMeshes.length) {
  24368. return;
  24369. }
  24370. if (!this.activeCamera) {
  24371. return;
  24372. }
  24373. this.onBeforeActiveMeshesEvaluationObservable.notifyObservers(this);
  24374. this.activeCamera._activeMeshes.reset();
  24375. this._activeMeshes.reset();
  24376. this._renderingManager.reset();
  24377. this._processedMaterials.reset();
  24378. this._activeParticleSystems.reset();
  24379. this._activeSkeletons.reset();
  24380. this._softwareSkinnedMeshes.reset();
  24381. if (this._boundingBoxRenderer) {
  24382. this._boundingBoxRenderer.reset();
  24383. }
  24384. // Meshes
  24385. var meshes;
  24386. var len;
  24387. var checkIsEnabled = true;
  24388. // Determine mesh candidates
  24389. if (this._activeMeshCandidateProvider !== undefined) {
  24390. // Use _activeMeshCandidateProvider
  24391. meshes = this._activeMeshCandidateProvider.getMeshes(this);
  24392. checkIsEnabled = this._activeMeshCandidateProvider.checksIsEnabled === false;
  24393. if (meshes !== undefined) {
  24394. len = meshes.length;
  24395. }
  24396. else {
  24397. len = 0;
  24398. }
  24399. }
  24400. else if (this._selectionOctree !== undefined) {
  24401. // Octree
  24402. var selection = this._selectionOctree.select(this._frustumPlanes);
  24403. meshes = selection.data;
  24404. len = selection.length;
  24405. }
  24406. else {
  24407. // Full scene traversal
  24408. len = this.meshes.length;
  24409. meshes = this.meshes;
  24410. }
  24411. // Check each mesh
  24412. for (var meshIndex = 0, mesh, meshLOD; meshIndex < len; meshIndex++) {
  24413. mesh = meshes[meshIndex];
  24414. if (mesh.isBlocked) {
  24415. continue;
  24416. }
  24417. this._totalVertices.addCount(mesh.getTotalVertices(), false);
  24418. if (!mesh.isReady() || (checkIsEnabled && !mesh.isEnabled())) {
  24419. continue;
  24420. }
  24421. mesh.computeWorldMatrix();
  24422. // Intersections
  24423. if (mesh.actionManager && mesh.actionManager.hasSpecificTriggers([BABYLON.ActionManager.OnIntersectionEnterTrigger, BABYLON.ActionManager.OnIntersectionExitTrigger])) {
  24424. this._meshesForIntersections.pushNoDuplicate(mesh);
  24425. }
  24426. // Switch to current LOD
  24427. meshLOD = mesh.getLOD(this.activeCamera);
  24428. if (meshLOD === undefined || meshLOD === null) {
  24429. continue;
  24430. }
  24431. mesh._preActivate();
  24432. if (mesh.alwaysSelectAsActiveMesh || mesh.isVisible && mesh.visibility > 0 && ((mesh.layerMask & this.activeCamera.layerMask) !== 0) && mesh.isInFrustum(this._frustumPlanes)) {
  24433. this._activeMeshes.push(mesh);
  24434. this.activeCamera._activeMeshes.push(mesh);
  24435. mesh._activate(this._renderId);
  24436. if (meshLOD !== mesh) {
  24437. meshLOD._activate(this._renderId);
  24438. }
  24439. this._activeMesh(mesh, meshLOD);
  24440. }
  24441. }
  24442. this.onAfterActiveMeshesEvaluationObservable.notifyObservers(this);
  24443. // Particle systems
  24444. if (this.particlesEnabled) {
  24445. this.onBeforeParticlesRenderingObservable.notifyObservers(this);
  24446. for (var particleIndex = 0; particleIndex < this.particleSystems.length; particleIndex++) {
  24447. var particleSystem = this.particleSystems[particleIndex];
  24448. if (!particleSystem.isStarted() || !particleSystem.emitter) {
  24449. continue;
  24450. }
  24451. var emitter = particleSystem.emitter;
  24452. if (!emitter.position || emitter.isEnabled()) {
  24453. this._activeParticleSystems.push(particleSystem);
  24454. particleSystem.animate();
  24455. this._renderingManager.dispatchParticles(particleSystem);
  24456. }
  24457. }
  24458. this.onAfterParticlesRenderingObservable.notifyObservers(this);
  24459. }
  24460. };
  24461. Scene.prototype._activeMesh = function (sourceMesh, mesh) {
  24462. if (this.skeletonsEnabled && mesh.skeleton !== null && mesh.skeleton !== undefined) {
  24463. if (this._activeSkeletons.pushNoDuplicate(mesh.skeleton)) {
  24464. mesh.skeleton.prepare();
  24465. }
  24466. if (!mesh.computeBonesUsingShaders) {
  24467. this._softwareSkinnedMeshes.pushNoDuplicate(mesh);
  24468. }
  24469. }
  24470. if (sourceMesh.showBoundingBox || this.forceShowBoundingBoxes) {
  24471. var boundingInfo = sourceMesh.getBoundingInfo();
  24472. this.getBoundingBoxRenderer().renderList.push(boundingInfo.boundingBox);
  24473. }
  24474. if (mesh !== undefined && mesh !== null
  24475. && mesh.subMeshes !== undefined && mesh.subMeshes !== null && mesh.subMeshes.length > 0) {
  24476. // Submeshes Octrees
  24477. var len;
  24478. var subMeshes;
  24479. if (mesh.useOctreeForRenderingSelection && mesh._submeshesOctree !== undefined && mesh._submeshesOctree !== null) {
  24480. var intersections = mesh._submeshesOctree.select(this._frustumPlanes);
  24481. len = intersections.length;
  24482. subMeshes = intersections.data;
  24483. }
  24484. else {
  24485. subMeshes = mesh.subMeshes;
  24486. len = subMeshes.length;
  24487. }
  24488. for (var subIndex = 0, subMesh; subIndex < len; subIndex++) {
  24489. subMesh = subMeshes[subIndex];
  24490. this._evaluateSubMesh(subMesh, mesh);
  24491. }
  24492. }
  24493. };
  24494. Scene.prototype.updateTransformMatrix = function (force) {
  24495. if (!this.activeCamera) {
  24496. return;
  24497. }
  24498. this.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix(force));
  24499. };
  24500. Scene.prototype.updateAlternateTransformMatrix = function (alternateCamera) {
  24501. this._setAlternateTransformMatrix(alternateCamera.getViewMatrix(), alternateCamera.getProjectionMatrix());
  24502. };
  24503. Scene.prototype._renderForCamera = function (camera, rigParent) {
  24504. if (camera && camera._skipRendering) {
  24505. return;
  24506. }
  24507. var engine = this._engine;
  24508. this.activeCamera = camera;
  24509. if (!this.activeCamera)
  24510. throw new Error("Active camera not set");
  24511. BABYLON.Tools.StartPerformanceCounter("Rendering camera " + this.activeCamera.name);
  24512. // Viewport
  24513. engine.setViewport(this.activeCamera.viewport);
  24514. // Camera
  24515. this.resetCachedMaterial();
  24516. this._renderId++;
  24517. this.updateTransformMatrix();
  24518. if (camera._alternateCamera) {
  24519. this.updateAlternateTransformMatrix(camera._alternateCamera);
  24520. this._alternateRendering = true;
  24521. }
  24522. this.onBeforeCameraRenderObservable.notifyObservers(this.activeCamera);
  24523. // Meshes
  24524. this._evaluateActiveMeshes();
  24525. // Software skinning
  24526. for (var softwareSkinnedMeshIndex = 0; softwareSkinnedMeshIndex < this._softwareSkinnedMeshes.length; softwareSkinnedMeshIndex++) {
  24527. var mesh = this._softwareSkinnedMeshes.data[softwareSkinnedMeshIndex];
  24528. mesh.applySkeleton(mesh.skeleton);
  24529. }
  24530. // Render targets
  24531. this.OnBeforeRenderTargetsRenderObservable.notifyObservers(this);
  24532. var needsRestoreFrameBuffer = false;
  24533. if (camera.customRenderTargets && camera.customRenderTargets.length > 0) {
  24534. this._renderTargets.concatWithNoDuplicate(camera.customRenderTargets);
  24535. }
  24536. if (rigParent && rigParent.customRenderTargets && rigParent.customRenderTargets.length > 0) {
  24537. this._renderTargets.concatWithNoDuplicate(rigParent.customRenderTargets);
  24538. }
  24539. if (this.renderTargetsEnabled && this._renderTargets.length > 0) {
  24540. this._intermediateRendering = true;
  24541. BABYLON.Tools.StartPerformanceCounter("Render targets", this._renderTargets.length > 0);
  24542. for (var renderIndex = 0; renderIndex < this._renderTargets.length; renderIndex++) {
  24543. var renderTarget = this._renderTargets.data[renderIndex];
  24544. if (renderTarget._shouldRender()) {
  24545. this._renderId++;
  24546. var hasSpecialRenderTargetCamera = renderTarget.activeCamera && renderTarget.activeCamera !== this.activeCamera;
  24547. renderTarget.render(hasSpecialRenderTargetCamera, this.dumpNextRenderTargets);
  24548. }
  24549. }
  24550. BABYLON.Tools.EndPerformanceCounter("Render targets", this._renderTargets.length > 0);
  24551. this._intermediateRendering = false;
  24552. this._renderId++;
  24553. needsRestoreFrameBuffer = true; // Restore back buffer
  24554. }
  24555. // Render EffecttLayer Texture
  24556. var stencilState = this._engine.getStencilBuffer();
  24557. var renderEffects = false;
  24558. var needStencil = false;
  24559. if (this.renderTargetsEnabled && this.effectLayers && this.effectLayers.length > 0) {
  24560. this._intermediateRendering = true;
  24561. for (var i = 0; i < this.effectLayers.length; i++) {
  24562. var effectLayer = this.effectLayers[i];
  24563. if (effectLayer.shouldRender() &&
  24564. (!effectLayer.camera ||
  24565. (effectLayer.camera.cameraRigMode === BABYLON.Camera.RIG_MODE_NONE && camera === effectLayer.camera) ||
  24566. (effectLayer.camera.cameraRigMode !== BABYLON.Camera.RIG_MODE_NONE && effectLayer.camera._rigCameras.indexOf(camera) > -1))) {
  24567. renderEffects = true;
  24568. needStencil = needStencil || effectLayer.needStencil();
  24569. var renderTarget = effectLayer._mainTexture;
  24570. if (renderTarget._shouldRender()) {
  24571. this._renderId++;
  24572. renderTarget.render(false, false);
  24573. needsRestoreFrameBuffer = true;
  24574. }
  24575. }
  24576. }
  24577. this._intermediateRendering = false;
  24578. this._renderId++;
  24579. }
  24580. if (needsRestoreFrameBuffer) {
  24581. engine.restoreDefaultFramebuffer(); // Restore back buffer
  24582. }
  24583. this.OnAfterRenderTargetsRenderObservable.notifyObservers(this);
  24584. // Prepare Frame
  24585. this.postProcessManager._prepareFrame();
  24586. // Backgrounds
  24587. var layerIndex;
  24588. var layer;
  24589. if (this.layers.length) {
  24590. engine.setDepthBuffer(false);
  24591. for (layerIndex = 0; layerIndex < this.layers.length; layerIndex++) {
  24592. layer = this.layers[layerIndex];
  24593. if (layer.isBackground && ((layer.layerMask & this.activeCamera.layerMask) !== 0)) {
  24594. layer.render();
  24595. }
  24596. }
  24597. engine.setDepthBuffer(true);
  24598. }
  24599. // Activate effect Layer stencil
  24600. if (needStencil) {
  24601. this._engine.setStencilBuffer(true);
  24602. }
  24603. // Render
  24604. this.onBeforeDrawPhaseObservable.notifyObservers(this);
  24605. this._renderingManager.render(null, null, true, true);
  24606. this.onAfterDrawPhaseObservable.notifyObservers(this);
  24607. // Restore effect Layer stencil
  24608. if (needStencil) {
  24609. this._engine.setStencilBuffer(stencilState);
  24610. }
  24611. // Bounding boxes
  24612. if (this._boundingBoxRenderer) {
  24613. this._boundingBoxRenderer.render();
  24614. }
  24615. // Lens flares
  24616. if (this.lensFlaresEnabled) {
  24617. BABYLON.Tools.StartPerformanceCounter("Lens flares", this.lensFlareSystems.length > 0);
  24618. for (var lensFlareSystemIndex = 0; lensFlareSystemIndex < this.lensFlareSystems.length; lensFlareSystemIndex++) {
  24619. var lensFlareSystem = this.lensFlareSystems[lensFlareSystemIndex];
  24620. if ((camera.layerMask & lensFlareSystem.layerMask) !== 0) {
  24621. lensFlareSystem.render();
  24622. }
  24623. }
  24624. BABYLON.Tools.EndPerformanceCounter("Lens flares", this.lensFlareSystems.length > 0);
  24625. }
  24626. // Foregrounds
  24627. if (this.layers.length) {
  24628. engine.setDepthBuffer(false);
  24629. for (layerIndex = 0; layerIndex < this.layers.length; layerIndex++) {
  24630. layer = this.layers[layerIndex];
  24631. if (!layer.isBackground && ((layer.layerMask & this.activeCamera.layerMask) !== 0)) {
  24632. layer.render();
  24633. }
  24634. }
  24635. engine.setDepthBuffer(true);
  24636. }
  24637. // Effect Layer
  24638. if (renderEffects) {
  24639. engine.setDepthBuffer(false);
  24640. for (var i = 0; i < this.effectLayers.length; i++) {
  24641. if (this.effectLayers[i].shouldRender()) {
  24642. this.effectLayers[i].render();
  24643. }
  24644. }
  24645. engine.setDepthBuffer(true);
  24646. }
  24647. // Finalize frame
  24648. this.postProcessManager._finalizeFrame(camera.isIntermediate);
  24649. // Reset some special arrays
  24650. this._renderTargets.reset();
  24651. this._alternateRendering = false;
  24652. this.onAfterCameraRenderObservable.notifyObservers(this.activeCamera);
  24653. BABYLON.Tools.EndPerformanceCounter("Rendering camera " + this.activeCamera.name);
  24654. };
  24655. Scene.prototype._processSubCameras = function (camera) {
  24656. if (camera.cameraRigMode === BABYLON.Camera.RIG_MODE_NONE) {
  24657. this._renderForCamera(camera);
  24658. return;
  24659. }
  24660. // rig cameras
  24661. for (var index = 0; index < camera._rigCameras.length; index++) {
  24662. this._renderForCamera(camera._rigCameras[index], camera);
  24663. }
  24664. this.activeCamera = camera;
  24665. this.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix());
  24666. };
  24667. Scene.prototype._checkIntersections = function () {
  24668. for (var index = 0; index < this._meshesForIntersections.length; index++) {
  24669. var sourceMesh = this._meshesForIntersections.data[index];
  24670. if (!sourceMesh.actionManager) {
  24671. continue;
  24672. }
  24673. for (var actionIndex = 0; actionIndex < sourceMesh.actionManager.actions.length; actionIndex++) {
  24674. var action = sourceMesh.actionManager.actions[actionIndex];
  24675. if (action.trigger === BABYLON.ActionManager.OnIntersectionEnterTrigger || action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  24676. var parameters = action.getTriggerParameter();
  24677. var otherMesh = parameters instanceof BABYLON.AbstractMesh ? parameters : parameters.mesh;
  24678. var areIntersecting = otherMesh.intersectsMesh(sourceMesh, parameters.usePreciseIntersection);
  24679. var currentIntersectionInProgress = sourceMesh._intersectionsInProgress.indexOf(otherMesh);
  24680. if (areIntersecting && currentIntersectionInProgress === -1) {
  24681. if (action.trigger === BABYLON.ActionManager.OnIntersectionEnterTrigger) {
  24682. action._executeCurrent(BABYLON.ActionEvent.CreateNew(sourceMesh, undefined, otherMesh));
  24683. sourceMesh._intersectionsInProgress.push(otherMesh);
  24684. }
  24685. else if (action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  24686. sourceMesh._intersectionsInProgress.push(otherMesh);
  24687. }
  24688. }
  24689. else if (!areIntersecting && currentIntersectionInProgress > -1) {
  24690. //They intersected, and now they don't.
  24691. //is this trigger an exit trigger? execute an event.
  24692. if (action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  24693. action._executeCurrent(BABYLON.ActionEvent.CreateNew(sourceMesh, undefined, otherMesh));
  24694. }
  24695. //if this is an exit trigger, or no exit trigger exists, remove the id from the intersection in progress array.
  24696. if (!sourceMesh.actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnIntersectionExitTrigger) || action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  24697. sourceMesh._intersectionsInProgress.splice(currentIntersectionInProgress, 1);
  24698. }
  24699. }
  24700. }
  24701. }
  24702. }
  24703. };
  24704. Scene.prototype.render = function () {
  24705. if (this.isDisposed) {
  24706. return;
  24707. }
  24708. this._activeParticles.fetchNewFrame();
  24709. this._totalVertices.fetchNewFrame();
  24710. this._activeIndices.fetchNewFrame();
  24711. this._activeBones.fetchNewFrame();
  24712. this._meshesForIntersections.reset();
  24713. this.resetCachedMaterial();
  24714. this.onBeforeAnimationsObservable.notifyObservers(this);
  24715. // Actions
  24716. if (this.actionManager) {
  24717. this.actionManager.processTrigger(BABYLON.ActionManager.OnEveryFrameTrigger);
  24718. }
  24719. //Simplification Queue
  24720. if (this.simplificationQueue && !this.simplificationQueue.running) {
  24721. this.simplificationQueue.executeNext();
  24722. }
  24723. if (this._engine.isDeterministicLockStep()) {
  24724. var deltaTime = Math.max(Scene.MinDeltaTime, Math.min(this._engine.getDeltaTime(), Scene.MaxDeltaTime)) + this._timeAccumulator;
  24725. var defaultFPS = (60.0 / 1000.0);
  24726. var defaultFrameTime = 1000 / 60; // frame time in MS
  24727. if (this._physicsEngine) {
  24728. defaultFrameTime = this._physicsEngine.getTimeStep() * 1000;
  24729. }
  24730. var stepsTaken = 0;
  24731. var maxSubSteps = this._engine.getLockstepMaxSteps();
  24732. var internalSteps = Math.floor(deltaTime / (1000 * defaultFPS));
  24733. internalSteps = Math.min(internalSteps, maxSubSteps);
  24734. do {
  24735. this.onBeforeStepObservable.notifyObservers(this);
  24736. // Animations
  24737. this._animationRatio = defaultFrameTime * defaultFPS;
  24738. this._animate();
  24739. this.onAfterAnimationsObservable.notifyObservers(this);
  24740. // Physics
  24741. if (this._physicsEngine) {
  24742. this.onBeforePhysicsObservable.notifyObservers(this);
  24743. this._physicsEngine._step(defaultFrameTime / 1000);
  24744. this.onAfterPhysicsObservable.notifyObservers(this);
  24745. }
  24746. this.onAfterStepObservable.notifyObservers(this);
  24747. this._currentStepId++;
  24748. stepsTaken++;
  24749. deltaTime -= defaultFrameTime;
  24750. } while (deltaTime > 0 && stepsTaken < internalSteps);
  24751. this._timeAccumulator = deltaTime < 0 ? 0 : deltaTime;
  24752. }
  24753. else {
  24754. // Animations
  24755. var deltaTime = this.useConstantAnimationDeltaTime ? 16 : Math.max(Scene.MinDeltaTime, Math.min(this._engine.getDeltaTime(), Scene.MaxDeltaTime));
  24756. this._animationRatio = deltaTime * (60.0 / 1000.0);
  24757. this._animate();
  24758. this.onAfterAnimationsObservable.notifyObservers(this);
  24759. // Physics
  24760. if (this._physicsEngine) {
  24761. this.onBeforePhysicsObservable.notifyObservers(this);
  24762. this._physicsEngine._step(deltaTime / 1000.0);
  24763. this.onAfterPhysicsObservable.notifyObservers(this);
  24764. }
  24765. }
  24766. // update gamepad manager
  24767. if (this._gamepadManager && this._gamepadManager._isMonitoring) {
  24768. this._gamepadManager._checkGamepadsStatus();
  24769. }
  24770. // Update Cameras
  24771. if (this.activeCameras.length > 0) {
  24772. for (var cameraIndex = 0; cameraIndex < this.activeCameras.length; cameraIndex++) {
  24773. var camera = this.activeCameras[cameraIndex];
  24774. camera.update();
  24775. if (camera.cameraRigMode !== BABYLON.Camera.RIG_MODE_NONE) {
  24776. // rig cameras
  24777. for (var index = 0; index < camera._rigCameras.length; index++) {
  24778. camera._rigCameras[index].update();
  24779. }
  24780. }
  24781. }
  24782. }
  24783. else if (this.activeCamera) {
  24784. this.activeCamera.update();
  24785. if (this.activeCamera.cameraRigMode !== BABYLON.Camera.RIG_MODE_NONE) {
  24786. // rig cameras
  24787. for (var index = 0; index < this.activeCamera._rigCameras.length; index++) {
  24788. this.activeCamera._rigCameras[index].update();
  24789. }
  24790. }
  24791. }
  24792. // Before render
  24793. this.onBeforeRenderObservable.notifyObservers(this);
  24794. // Customs render targets
  24795. this.OnBeforeRenderTargetsRenderObservable.notifyObservers(this);
  24796. var engine = this.getEngine();
  24797. var currentActiveCamera = this.activeCamera;
  24798. if (this.renderTargetsEnabled) {
  24799. BABYLON.Tools.StartPerformanceCounter("Custom render targets", this.customRenderTargets.length > 0);
  24800. this._intermediateRendering = true;
  24801. for (var customIndex = 0; customIndex < this.customRenderTargets.length; customIndex++) {
  24802. var renderTarget = this.customRenderTargets[customIndex];
  24803. if (renderTarget._shouldRender()) {
  24804. this._renderId++;
  24805. this.activeCamera = renderTarget.activeCamera || this.activeCamera;
  24806. if (!this.activeCamera)
  24807. throw new Error("Active camera not set");
  24808. // Viewport
  24809. engine.setViewport(this.activeCamera.viewport);
  24810. // Camera
  24811. this.updateTransformMatrix();
  24812. renderTarget.render(currentActiveCamera !== this.activeCamera, this.dumpNextRenderTargets);
  24813. }
  24814. }
  24815. BABYLON.Tools.EndPerformanceCounter("Custom render targets", this.customRenderTargets.length > 0);
  24816. this._intermediateRendering = false;
  24817. this._renderId++;
  24818. }
  24819. // Restore back buffer
  24820. if (this.customRenderTargets.length > 0) {
  24821. engine.restoreDefaultFramebuffer();
  24822. }
  24823. this.OnAfterRenderTargetsRenderObservable.notifyObservers(this);
  24824. this.activeCamera = currentActiveCamera;
  24825. // Procedural textures
  24826. if (this.proceduralTexturesEnabled) {
  24827. BABYLON.Tools.StartPerformanceCounter("Procedural textures", this._proceduralTextures.length > 0);
  24828. for (var proceduralIndex = 0; proceduralIndex < this._proceduralTextures.length; proceduralIndex++) {
  24829. var proceduralTexture = this._proceduralTextures[proceduralIndex];
  24830. if (proceduralTexture._shouldRender()) {
  24831. proceduralTexture.render();
  24832. }
  24833. }
  24834. BABYLON.Tools.EndPerformanceCounter("Procedural textures", this._proceduralTextures.length > 0);
  24835. }
  24836. // Clear
  24837. if (this.autoClearDepthAndStencil || this.autoClear) {
  24838. this._engine.clear(this.clearColor, this.autoClear || this.forceWireframe || this.forcePointsCloud, this.autoClearDepthAndStencil, this.autoClearDepthAndStencil);
  24839. }
  24840. // Shadows
  24841. if (this.shadowsEnabled) {
  24842. for (var lightIndex = 0; lightIndex < this.lights.length; lightIndex++) {
  24843. var light = this.lights[lightIndex];
  24844. var shadowGenerator = light.getShadowGenerator();
  24845. if (light.isEnabled() && light.shadowEnabled && shadowGenerator) {
  24846. var shadowMap = (shadowGenerator.getShadowMap());
  24847. if (this.textures.indexOf(shadowMap) !== -1) {
  24848. this._renderTargets.push(shadowMap);
  24849. }
  24850. }
  24851. }
  24852. }
  24853. // Depth renderer
  24854. for (var key in this._depthRenderer) {
  24855. this._renderTargets.push(this._depthRenderer[key].getDepthMap());
  24856. }
  24857. // Geometry renderer
  24858. if (this._geometryBufferRenderer) {
  24859. this._renderTargets.push(this._geometryBufferRenderer.getGBuffer());
  24860. }
  24861. // RenderPipeline
  24862. if (this._postProcessRenderPipelineManager) {
  24863. this._postProcessRenderPipelineManager.update();
  24864. }
  24865. // Multi-cameras?
  24866. if (this.activeCameras.length > 0) {
  24867. for (var cameraIndex = 0; cameraIndex < this.activeCameras.length; cameraIndex++) {
  24868. if (cameraIndex > 0) {
  24869. this._engine.clear(null, false, true, true);
  24870. }
  24871. this._processSubCameras(this.activeCameras[cameraIndex]);
  24872. }
  24873. }
  24874. else {
  24875. if (!this.activeCamera) {
  24876. throw new Error("No camera defined");
  24877. }
  24878. this._processSubCameras(this.activeCamera);
  24879. }
  24880. // Intersection checks
  24881. this._checkIntersections();
  24882. // Update the audio listener attached to the camera
  24883. if (BABYLON.AudioEngine) {
  24884. this._updateAudioParameters();
  24885. }
  24886. // After render
  24887. if (this.afterRender) {
  24888. this.afterRender();
  24889. }
  24890. this.onAfterRenderObservable.notifyObservers(this);
  24891. // Cleaning
  24892. for (var index = 0; index < this._toBeDisposed.length; index++) {
  24893. var data = this._toBeDisposed.data[index];
  24894. if (data) {
  24895. data.dispose();
  24896. }
  24897. this._toBeDisposed[index] = null;
  24898. }
  24899. this._toBeDisposed.reset();
  24900. if (this.dumpNextRenderTargets) {
  24901. this.dumpNextRenderTargets = false;
  24902. }
  24903. this._activeBones.addCount(0, true);
  24904. this._activeIndices.addCount(0, true);
  24905. this._activeParticles.addCount(0, true);
  24906. };
  24907. Scene.prototype._updateAudioParameters = function () {
  24908. if (!this.audioEnabled || !this._mainSoundTrack || (this._mainSoundTrack.soundCollection.length === 0 && this.soundTracks.length === 1)) {
  24909. return;
  24910. }
  24911. var listeningCamera;
  24912. var audioEngine = BABYLON.Engine.audioEngine;
  24913. if (this.activeCameras.length > 0) {
  24914. listeningCamera = this.activeCameras[0];
  24915. }
  24916. else {
  24917. listeningCamera = this.activeCamera;
  24918. }
  24919. if (listeningCamera && audioEngine.canUseWebAudio && audioEngine.audioContext) {
  24920. audioEngine.audioContext.listener.setPosition(listeningCamera.position.x, listeningCamera.position.y, listeningCamera.position.z);
  24921. // for VR cameras
  24922. if (listeningCamera.rigCameras && listeningCamera.rigCameras.length > 0) {
  24923. listeningCamera = listeningCamera.rigCameras[0];
  24924. }
  24925. var mat = BABYLON.Matrix.Invert(listeningCamera.getViewMatrix());
  24926. var cameraDirection = BABYLON.Vector3.TransformNormal(new BABYLON.Vector3(0, 0, -1), mat);
  24927. cameraDirection.normalize();
  24928. // To avoid some errors on GearVR
  24929. if (!isNaN(cameraDirection.x) && !isNaN(cameraDirection.y) && !isNaN(cameraDirection.z)) {
  24930. audioEngine.audioContext.listener.setOrientation(cameraDirection.x, cameraDirection.y, cameraDirection.z, 0, 1, 0);
  24931. }
  24932. var i;
  24933. for (i = 0; i < this.mainSoundTrack.soundCollection.length; i++) {
  24934. var sound = this.mainSoundTrack.soundCollection[i];
  24935. if (sound.useCustomAttenuation) {
  24936. sound.updateDistanceFromListener();
  24937. }
  24938. }
  24939. for (i = 0; i < this.soundTracks.length; i++) {
  24940. for (var j = 0; j < this.soundTracks[i].soundCollection.length; j++) {
  24941. sound = this.soundTracks[i].soundCollection[j];
  24942. if (sound.useCustomAttenuation) {
  24943. sound.updateDistanceFromListener();
  24944. }
  24945. }
  24946. }
  24947. }
  24948. };
  24949. Object.defineProperty(Scene.prototype, "audioEnabled", {
  24950. // Audio
  24951. get: function () {
  24952. return this._audioEnabled;
  24953. },
  24954. set: function (value) {
  24955. this._audioEnabled = value;
  24956. if (BABYLON.AudioEngine) {
  24957. if (this._audioEnabled) {
  24958. this._enableAudio();
  24959. }
  24960. else {
  24961. this._disableAudio();
  24962. }
  24963. }
  24964. },
  24965. enumerable: true,
  24966. configurable: true
  24967. });
  24968. Scene.prototype._disableAudio = function () {
  24969. var i;
  24970. for (i = 0; i < this.mainSoundTrack.soundCollection.length; i++) {
  24971. this.mainSoundTrack.soundCollection[i].pause();
  24972. }
  24973. for (i = 0; i < this.soundTracks.length; i++) {
  24974. for (var j = 0; j < this.soundTracks[i].soundCollection.length; j++) {
  24975. this.soundTracks[i].soundCollection[j].pause();
  24976. }
  24977. }
  24978. };
  24979. Scene.prototype._enableAudio = function () {
  24980. var i;
  24981. for (i = 0; i < this.mainSoundTrack.soundCollection.length; i++) {
  24982. if (this.mainSoundTrack.soundCollection[i].isPaused) {
  24983. this.mainSoundTrack.soundCollection[i].play();
  24984. }
  24985. }
  24986. for (i = 0; i < this.soundTracks.length; i++) {
  24987. for (var j = 0; j < this.soundTracks[i].soundCollection.length; j++) {
  24988. if (this.soundTracks[i].soundCollection[j].isPaused) {
  24989. this.soundTracks[i].soundCollection[j].play();
  24990. }
  24991. }
  24992. }
  24993. };
  24994. Object.defineProperty(Scene.prototype, "headphone", {
  24995. get: function () {
  24996. return this._headphone;
  24997. },
  24998. set: function (value) {
  24999. this._headphone = value;
  25000. if (BABYLON.AudioEngine) {
  25001. if (this._headphone) {
  25002. this._switchAudioModeForHeadphones();
  25003. }
  25004. else {
  25005. this._switchAudioModeForNormalSpeakers();
  25006. }
  25007. }
  25008. },
  25009. enumerable: true,
  25010. configurable: true
  25011. });
  25012. Scene.prototype._switchAudioModeForHeadphones = function () {
  25013. this.mainSoundTrack.switchPanningModelToHRTF();
  25014. for (var i = 0; i < this.soundTracks.length; i++) {
  25015. this.soundTracks[i].switchPanningModelToHRTF();
  25016. }
  25017. };
  25018. Scene.prototype._switchAudioModeForNormalSpeakers = function () {
  25019. this.mainSoundTrack.switchPanningModelToEqualPower();
  25020. for (var i = 0; i < this.soundTracks.length; i++) {
  25021. this.soundTracks[i].switchPanningModelToEqualPower();
  25022. }
  25023. };
  25024. /**
  25025. * Creates a depth renderer a given camera which contains a depth map which can be used for post processing.
  25026. * @param camera The camera to create the depth renderer on (default: scene's active camera)
  25027. * @returns the created depth renderer
  25028. */
  25029. Scene.prototype.enableDepthRenderer = function (camera) {
  25030. camera = camera || this.activeCamera;
  25031. if (!camera) {
  25032. throw "No camera available to enable depth renderer";
  25033. }
  25034. if (!this._depthRenderer[camera.id]) {
  25035. var textureType = 0;
  25036. if (this._engine.getCaps().textureHalfFloatRender) {
  25037. textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  25038. }
  25039. else if (this._engine.getCaps().textureFloatRender) {
  25040. textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  25041. }
  25042. else {
  25043. throw "Depth renderer does not support int texture type";
  25044. }
  25045. this._depthRenderer[camera.id] = new BABYLON.DepthRenderer(this, textureType, camera);
  25046. }
  25047. return this._depthRenderer[camera.id];
  25048. };
  25049. /**
  25050. * Disables a depth renderer for a given camera
  25051. * @param camera The camera to disable the depth renderer on (default: scene's active camera)
  25052. */
  25053. Scene.prototype.disableDepthRenderer = function (camera) {
  25054. camera = camera || this.activeCamera;
  25055. if (!camera || !this._depthRenderer[camera.id]) {
  25056. return;
  25057. }
  25058. this._depthRenderer[camera.id].dispose();
  25059. delete this._depthRenderer[camera.id];
  25060. };
  25061. Scene.prototype.enableGeometryBufferRenderer = function (ratio) {
  25062. if (ratio === void 0) { ratio = 1; }
  25063. if (this._geometryBufferRenderer) {
  25064. return this._geometryBufferRenderer;
  25065. }
  25066. this._geometryBufferRenderer = new BABYLON.GeometryBufferRenderer(this, ratio);
  25067. if (!this._geometryBufferRenderer.isSupported) {
  25068. this._geometryBufferRenderer = null;
  25069. }
  25070. return this._geometryBufferRenderer;
  25071. };
  25072. Scene.prototype.disableGeometryBufferRenderer = function () {
  25073. if (!this._geometryBufferRenderer) {
  25074. return;
  25075. }
  25076. this._geometryBufferRenderer.dispose();
  25077. this._geometryBufferRenderer = null;
  25078. };
  25079. Scene.prototype.freezeMaterials = function () {
  25080. for (var i = 0; i < this.materials.length; i++) {
  25081. this.materials[i].freeze();
  25082. }
  25083. };
  25084. Scene.prototype.unfreezeMaterials = function () {
  25085. for (var i = 0; i < this.materials.length; i++) {
  25086. this.materials[i].unfreeze();
  25087. }
  25088. };
  25089. Scene.prototype.dispose = function () {
  25090. this.beforeRender = null;
  25091. this.afterRender = null;
  25092. this.skeletons = [];
  25093. this.morphTargetManagers = [];
  25094. this.importedMeshesFiles = new Array();
  25095. this.stopAllAnimations();
  25096. this.resetCachedMaterial();
  25097. for (var key in this._depthRenderer) {
  25098. this._depthRenderer[key].dispose();
  25099. }
  25100. if (this._gamepadManager) {
  25101. this._gamepadManager.dispose();
  25102. this._gamepadManager = null;
  25103. }
  25104. // Smart arrays
  25105. if (this.activeCamera) {
  25106. this.activeCamera._activeMeshes.dispose();
  25107. this.activeCamera = null;
  25108. }
  25109. this._activeMeshes.dispose();
  25110. this._renderingManager.dispose();
  25111. this._processedMaterials.dispose();
  25112. this._activeParticleSystems.dispose();
  25113. this._activeSkeletons.dispose();
  25114. this._softwareSkinnedMeshes.dispose();
  25115. this._renderTargets.dispose();
  25116. this._registeredForLateAnimationBindings.dispose();
  25117. if (this._boundingBoxRenderer) {
  25118. this._boundingBoxRenderer.dispose();
  25119. }
  25120. this._meshesForIntersections.dispose();
  25121. this._toBeDisposed.dispose();
  25122. // Abort active requests
  25123. for (var _i = 0, _a = this._activeRequests; _i < _a.length; _i++) {
  25124. var request = _a[_i];
  25125. request.abort();
  25126. }
  25127. // Debug layer
  25128. if (this._debugLayer) {
  25129. this._debugLayer.hide();
  25130. }
  25131. // Events
  25132. this.onDisposeObservable.notifyObservers(this);
  25133. this.onDisposeObservable.clear();
  25134. this.onBeforeRenderObservable.clear();
  25135. this.onAfterRenderObservable.clear();
  25136. this.OnBeforeRenderTargetsRenderObservable.clear();
  25137. this.OnAfterRenderTargetsRenderObservable.clear();
  25138. this.onAfterStepObservable.clear();
  25139. this.onBeforeStepObservable.clear();
  25140. this.onBeforeActiveMeshesEvaluationObservable.clear();
  25141. this.onAfterActiveMeshesEvaluationObservable.clear();
  25142. this.onBeforeParticlesRenderingObservable.clear();
  25143. this.onAfterParticlesRenderingObservable.clear();
  25144. this.onBeforeSpritesRenderingObservable.clear();
  25145. this.onAfterSpritesRenderingObservable.clear();
  25146. this.onBeforeDrawPhaseObservable.clear();
  25147. this.onAfterDrawPhaseObservable.clear();
  25148. this.onBeforePhysicsObservable.clear();
  25149. this.onAfterPhysicsObservable.clear();
  25150. this.onBeforeAnimationsObservable.clear();
  25151. this.onAfterAnimationsObservable.clear();
  25152. this.onDataLoadedObservable.clear();
  25153. this.detachControl();
  25154. // Release sounds & sounds tracks
  25155. if (BABYLON.AudioEngine) {
  25156. this.disposeSounds();
  25157. }
  25158. // VR Helper
  25159. if (this.VRHelper) {
  25160. this.VRHelper.dispose();
  25161. }
  25162. // Detach cameras
  25163. var canvas = this._engine.getRenderingCanvas();
  25164. if (canvas) {
  25165. var index;
  25166. for (index = 0; index < this.cameras.length; index++) {
  25167. this.cameras[index].detachControl(canvas);
  25168. }
  25169. }
  25170. // Release animation groups
  25171. while (this.animationGroups.length) {
  25172. this.animationGroups[0].dispose();
  25173. }
  25174. // Release lights
  25175. while (this.lights.length) {
  25176. this.lights[0].dispose();
  25177. }
  25178. // Release meshes
  25179. while (this.meshes.length) {
  25180. this.meshes[0].dispose(true);
  25181. }
  25182. while (this.transformNodes.length) {
  25183. this.removeTransformNode(this.transformNodes[0]);
  25184. }
  25185. // Release cameras
  25186. while (this.cameras.length) {
  25187. this.cameras[0].dispose();
  25188. }
  25189. // Release materials
  25190. if (this.defaultMaterial) {
  25191. this.defaultMaterial.dispose();
  25192. }
  25193. while (this.multiMaterials.length) {
  25194. this.multiMaterials[0].dispose();
  25195. }
  25196. while (this.materials.length) {
  25197. this.materials[0].dispose();
  25198. }
  25199. // Release particles
  25200. while (this.particleSystems.length) {
  25201. this.particleSystems[0].dispose();
  25202. }
  25203. // Release sprites
  25204. while (this.spriteManagers.length) {
  25205. this.spriteManagers[0].dispose();
  25206. }
  25207. // Release postProcesses
  25208. while (this.postProcesses.length) {
  25209. this.postProcesses[0].dispose();
  25210. }
  25211. // Release layers
  25212. while (this.layers.length) {
  25213. this.layers[0].dispose();
  25214. }
  25215. while (this.effectLayers.length) {
  25216. this.effectLayers[0].dispose();
  25217. }
  25218. // Release textures
  25219. while (this.textures.length) {
  25220. this.textures[0].dispose();
  25221. }
  25222. // Release UBO
  25223. this._sceneUbo.dispose();
  25224. if (this._alternateSceneUbo) {
  25225. this._alternateSceneUbo.dispose();
  25226. }
  25227. // Post-processes
  25228. this.postProcessManager.dispose();
  25229. if (this._postProcessRenderPipelineManager) {
  25230. this._postProcessRenderPipelineManager.dispose();
  25231. }
  25232. // Physics
  25233. if (this._physicsEngine) {
  25234. this.disablePhysicsEngine();
  25235. }
  25236. // Remove from engine
  25237. index = this._engine.scenes.indexOf(this);
  25238. if (index > -1) {
  25239. this._engine.scenes.splice(index, 1);
  25240. }
  25241. this._engine.wipeCaches(true);
  25242. this._isDisposed = true;
  25243. };
  25244. Object.defineProperty(Scene.prototype, "isDisposed", {
  25245. get: function () {
  25246. return this._isDisposed;
  25247. },
  25248. enumerable: true,
  25249. configurable: true
  25250. });
  25251. // Release sounds & sounds tracks
  25252. Scene.prototype.disposeSounds = function () {
  25253. if (!this._mainSoundTrack) {
  25254. return;
  25255. }
  25256. this.mainSoundTrack.dispose();
  25257. for (var scIndex = 0; scIndex < this.soundTracks.length; scIndex++) {
  25258. this.soundTracks[scIndex].dispose();
  25259. }
  25260. };
  25261. // Octrees
  25262. /**
  25263. * Get the world extend vectors with an optional filter
  25264. *
  25265. * @param filterPredicate the predicate - which meshes should be included when calculating the world size
  25266. * @returns {{ min: Vector3; max: Vector3 }} min and max vectors
  25267. */
  25268. Scene.prototype.getWorldExtends = function (filterPredicate) {
  25269. var min = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  25270. var max = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  25271. filterPredicate = filterPredicate || (function () { return true; });
  25272. this.meshes.filter(filterPredicate).forEach(function (mesh) {
  25273. mesh.computeWorldMatrix(true);
  25274. if (!mesh.subMeshes || mesh.subMeshes.length === 0 || mesh.infiniteDistance) {
  25275. return;
  25276. }
  25277. var boundingInfo = mesh.getBoundingInfo();
  25278. var minBox = boundingInfo.boundingBox.minimumWorld;
  25279. var maxBox = boundingInfo.boundingBox.maximumWorld;
  25280. BABYLON.Tools.CheckExtends(minBox, min, max);
  25281. BABYLON.Tools.CheckExtends(maxBox, min, max);
  25282. });
  25283. return {
  25284. min: min,
  25285. max: max
  25286. };
  25287. };
  25288. Scene.prototype.createOrUpdateSelectionOctree = function (maxCapacity, maxDepth) {
  25289. if (maxCapacity === void 0) { maxCapacity = 64; }
  25290. if (maxDepth === void 0) { maxDepth = 2; }
  25291. if (!this._selectionOctree) {
  25292. this._selectionOctree = new BABYLON.Octree(BABYLON.Octree.CreationFuncForMeshes, maxCapacity, maxDepth);
  25293. }
  25294. var worldExtends = this.getWorldExtends();
  25295. // Update octree
  25296. this._selectionOctree.update(worldExtends.min, worldExtends.max, this.meshes);
  25297. return this._selectionOctree;
  25298. };
  25299. // Picking
  25300. Scene.prototype.createPickingRay = function (x, y, world, camera, cameraViewSpace) {
  25301. if (cameraViewSpace === void 0) { cameraViewSpace = false; }
  25302. var result = BABYLON.Ray.Zero();
  25303. this.createPickingRayToRef(x, y, world, result, camera, cameraViewSpace);
  25304. return result;
  25305. };
  25306. Scene.prototype.createPickingRayToRef = function (x, y, world, result, camera, cameraViewSpace) {
  25307. if (cameraViewSpace === void 0) { cameraViewSpace = false; }
  25308. var engine = this._engine;
  25309. if (!camera) {
  25310. if (!this.activeCamera)
  25311. throw new Error("Active camera not set");
  25312. camera = this.activeCamera;
  25313. }
  25314. var cameraViewport = camera.viewport;
  25315. var viewport = cameraViewport.toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  25316. // Moving coordinates to local viewport world
  25317. x = x / this._engine.getHardwareScalingLevel() - viewport.x;
  25318. y = y / this._engine.getHardwareScalingLevel() - (this._engine.getRenderHeight() - viewport.y - viewport.height);
  25319. result.update(x, y, viewport.width, viewport.height, world ? world : BABYLON.Matrix.Identity(), cameraViewSpace ? BABYLON.Matrix.Identity() : camera.getViewMatrix(), camera.getProjectionMatrix());
  25320. return this;
  25321. };
  25322. Scene.prototype.createPickingRayInCameraSpace = function (x, y, camera) {
  25323. var result = BABYLON.Ray.Zero();
  25324. this.createPickingRayInCameraSpaceToRef(x, y, result, camera);
  25325. return result;
  25326. };
  25327. Scene.prototype.createPickingRayInCameraSpaceToRef = function (x, y, result, camera) {
  25328. if (!BABYLON.PickingInfo) {
  25329. return this;
  25330. }
  25331. var engine = this._engine;
  25332. if (!camera) {
  25333. if (!this.activeCamera)
  25334. throw new Error("Active camera not set");
  25335. camera = this.activeCamera;
  25336. }
  25337. var cameraViewport = camera.viewport;
  25338. var viewport = cameraViewport.toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  25339. var identity = BABYLON.Matrix.Identity();
  25340. // Moving coordinates to local viewport world
  25341. x = x / this._engine.getHardwareScalingLevel() - viewport.x;
  25342. y = y / this._engine.getHardwareScalingLevel() - (this._engine.getRenderHeight() - viewport.y - viewport.height);
  25343. result.update(x, y, viewport.width, viewport.height, identity, identity, camera.getProjectionMatrix());
  25344. return this;
  25345. };
  25346. Scene.prototype._internalPick = function (rayFunction, predicate, fastCheck) {
  25347. if (!BABYLON.PickingInfo) {
  25348. return null;
  25349. }
  25350. var pickingInfo = null;
  25351. for (var meshIndex = 0; meshIndex < this.meshes.length; meshIndex++) {
  25352. var mesh = this.meshes[meshIndex];
  25353. if (predicate) {
  25354. if (!predicate(mesh)) {
  25355. continue;
  25356. }
  25357. }
  25358. else if (!mesh.isEnabled() || !mesh.isVisible || !mesh.isPickable) {
  25359. continue;
  25360. }
  25361. var world = mesh.getWorldMatrix();
  25362. var ray = rayFunction(world);
  25363. var result = mesh.intersects(ray, fastCheck);
  25364. if (!result || !result.hit)
  25365. continue;
  25366. if (!fastCheck && pickingInfo != null && result.distance >= pickingInfo.distance)
  25367. continue;
  25368. pickingInfo = result;
  25369. if (fastCheck) {
  25370. break;
  25371. }
  25372. }
  25373. return pickingInfo || new BABYLON.PickingInfo();
  25374. };
  25375. Scene.prototype._internalMultiPick = function (rayFunction, predicate) {
  25376. if (!BABYLON.PickingInfo) {
  25377. return null;
  25378. }
  25379. var pickingInfos = new Array();
  25380. for (var meshIndex = 0; meshIndex < this.meshes.length; meshIndex++) {
  25381. var mesh = this.meshes[meshIndex];
  25382. if (predicate) {
  25383. if (!predicate(mesh)) {
  25384. continue;
  25385. }
  25386. }
  25387. else if (!mesh.isEnabled() || !mesh.isVisible || !mesh.isPickable) {
  25388. continue;
  25389. }
  25390. var world = mesh.getWorldMatrix();
  25391. var ray = rayFunction(world);
  25392. var result = mesh.intersects(ray, false);
  25393. if (!result || !result.hit)
  25394. continue;
  25395. pickingInfos.push(result);
  25396. }
  25397. return pickingInfos;
  25398. };
  25399. Scene.prototype._internalPickSprites = function (ray, predicate, fastCheck, camera) {
  25400. if (!BABYLON.PickingInfo) {
  25401. return null;
  25402. }
  25403. var pickingInfo = null;
  25404. if (!camera) {
  25405. if (!this.activeCamera) {
  25406. return null;
  25407. }
  25408. camera = this.activeCamera;
  25409. }
  25410. if (this.spriteManagers.length > 0) {
  25411. for (var spriteIndex = 0; spriteIndex < this.spriteManagers.length; spriteIndex++) {
  25412. var spriteManager = this.spriteManagers[spriteIndex];
  25413. if (!spriteManager.isPickable) {
  25414. continue;
  25415. }
  25416. var result = spriteManager.intersects(ray, camera, predicate, fastCheck);
  25417. if (!result || !result.hit)
  25418. continue;
  25419. if (!fastCheck && pickingInfo != null && result.distance >= pickingInfo.distance)
  25420. continue;
  25421. pickingInfo = result;
  25422. if (fastCheck) {
  25423. break;
  25424. }
  25425. }
  25426. }
  25427. return pickingInfo || new BABYLON.PickingInfo();
  25428. };
  25429. /** Launch a ray to try to pick a mesh in the scene
  25430. * @param x position on screen
  25431. * @param y position on screen
  25432. * @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
  25433. * @param fastCheck Launch a fast check only using the bounding boxes. Can be set to null.
  25434. * @param camera to use for computing the picking ray. Can be set to null. In this case, the scene.activeCamera will be used
  25435. */
  25436. Scene.prototype.pick = function (x, y, predicate, fastCheck, camera) {
  25437. var _this = this;
  25438. if (!BABYLON.PickingInfo) {
  25439. return null;
  25440. }
  25441. return this._internalPick(function (world) {
  25442. _this.createPickingRayToRef(x, y, world, _this._tempPickingRay, camera || null);
  25443. return _this._tempPickingRay;
  25444. }, predicate, fastCheck);
  25445. };
  25446. /** Launch a ray to try to pick a sprite in the scene
  25447. * @param x position on screen
  25448. * @param y position on screen
  25449. * @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
  25450. * @param fastCheck Launch a fast check only using the bounding boxes. Can be set to null.
  25451. * @param camera camera to use for computing the picking ray. Can be set to null. In this case, the scene.activeCamera will be used
  25452. */
  25453. Scene.prototype.pickSprite = function (x, y, predicate, fastCheck, camera) {
  25454. this.createPickingRayInCameraSpaceToRef(x, y, this._tempPickingRay, camera);
  25455. return this._internalPickSprites(this._tempPickingRay, predicate, fastCheck, camera);
  25456. };
  25457. /** Use the given ray to pick a mesh in the scene
  25458. * @param ray The ray to use to pick meshes
  25459. * @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
  25460. * @param fastCheck Launch a fast check only using the bounding boxes. Can be set to null.
  25461. */
  25462. Scene.prototype.pickWithRay = function (ray, predicate, fastCheck) {
  25463. var _this = this;
  25464. return this._internalPick(function (world) {
  25465. if (!_this._pickWithRayInverseMatrix) {
  25466. _this._pickWithRayInverseMatrix = BABYLON.Matrix.Identity();
  25467. }
  25468. world.invertToRef(_this._pickWithRayInverseMatrix);
  25469. if (!_this._cachedRayForTransform) {
  25470. _this._cachedRayForTransform = BABYLON.Ray.Zero();
  25471. }
  25472. BABYLON.Ray.TransformToRef(ray, _this._pickWithRayInverseMatrix, _this._cachedRayForTransform);
  25473. return _this._cachedRayForTransform;
  25474. }, predicate, fastCheck);
  25475. };
  25476. /**
  25477. * Launch a ray to try to pick a mesh in the scene
  25478. * @param x X position on screen
  25479. * @param y Y position on screen
  25480. * @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
  25481. * @param camera camera to use for computing the picking ray. Can be set to null. In this case, the scene.activeCamera will be used
  25482. */
  25483. Scene.prototype.multiPick = function (x, y, predicate, camera) {
  25484. var _this = this;
  25485. return this._internalMultiPick(function (world) { return _this.createPickingRay(x, y, world, camera || null); }, predicate);
  25486. };
  25487. /**
  25488. * Launch a ray to try to pick a mesh in the scene
  25489. * @param ray Ray to use
  25490. * @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
  25491. */
  25492. Scene.prototype.multiPickWithRay = function (ray, predicate) {
  25493. var _this = this;
  25494. return this._internalMultiPick(function (world) {
  25495. if (!_this._pickWithRayInverseMatrix) {
  25496. _this._pickWithRayInverseMatrix = BABYLON.Matrix.Identity();
  25497. }
  25498. world.invertToRef(_this._pickWithRayInverseMatrix);
  25499. if (!_this._cachedRayForTransform) {
  25500. _this._cachedRayForTransform = BABYLON.Ray.Zero();
  25501. }
  25502. BABYLON.Ray.TransformToRef(ray, _this._pickWithRayInverseMatrix, _this._cachedRayForTransform);
  25503. return _this._cachedRayForTransform;
  25504. }, predicate);
  25505. };
  25506. Scene.prototype.setPointerOverMesh = function (mesh) {
  25507. if (this._pointerOverMesh === mesh) {
  25508. return;
  25509. }
  25510. if (this._pointerOverMesh && this._pointerOverMesh.actionManager) {
  25511. this._pointerOverMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOutTrigger, BABYLON.ActionEvent.CreateNew(this._pointerOverMesh));
  25512. }
  25513. this._pointerOverMesh = mesh;
  25514. if (this._pointerOverMesh && this._pointerOverMesh.actionManager) {
  25515. this._pointerOverMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOverTrigger, BABYLON.ActionEvent.CreateNew(this._pointerOverMesh));
  25516. }
  25517. };
  25518. Scene.prototype.getPointerOverMesh = function () {
  25519. return this._pointerOverMesh;
  25520. };
  25521. Scene.prototype.setPointerOverSprite = function (sprite) {
  25522. if (this._pointerOverSprite === sprite) {
  25523. return;
  25524. }
  25525. if (this._pointerOverSprite && this._pointerOverSprite.actionManager) {
  25526. this._pointerOverSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOutTrigger, BABYLON.ActionEvent.CreateNewFromSprite(this._pointerOverSprite, this));
  25527. }
  25528. this._pointerOverSprite = sprite;
  25529. if (this._pointerOverSprite && this._pointerOverSprite.actionManager) {
  25530. this._pointerOverSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOverTrigger, BABYLON.ActionEvent.CreateNewFromSprite(this._pointerOverSprite, this));
  25531. }
  25532. };
  25533. Scene.prototype.getPointerOverSprite = function () {
  25534. return this._pointerOverSprite;
  25535. };
  25536. // Physics
  25537. Scene.prototype.getPhysicsEngine = function () {
  25538. return this._physicsEngine;
  25539. };
  25540. /**
  25541. * Enables physics to the current scene
  25542. * @param {BABYLON.Vector3} [gravity] - the scene's gravity for the physics engine
  25543. * @param {BABYLON.IPhysicsEnginePlugin} [plugin] - The physics engine to be used. defaults to OimoJS.
  25544. * @return {boolean} was the physics engine initialized
  25545. */
  25546. Scene.prototype.enablePhysics = function (gravity, plugin) {
  25547. if (gravity === void 0) { gravity = null; }
  25548. if (this._physicsEngine) {
  25549. return true;
  25550. }
  25551. try {
  25552. this._physicsEngine = new BABYLON.PhysicsEngine(gravity, plugin);
  25553. return true;
  25554. }
  25555. catch (e) {
  25556. BABYLON.Tools.Error(e.message);
  25557. return false;
  25558. }
  25559. };
  25560. Scene.prototype.disablePhysicsEngine = function () {
  25561. if (!this._physicsEngine) {
  25562. return;
  25563. }
  25564. this._physicsEngine.dispose();
  25565. this._physicsEngine = null;
  25566. };
  25567. Scene.prototype.isPhysicsEnabled = function () {
  25568. return this._physicsEngine !== undefined;
  25569. };
  25570. Scene.prototype.deleteCompoundImpostor = function (compound) {
  25571. var mesh = compound.parts[0].mesh;
  25572. if (mesh.physicsImpostor) {
  25573. mesh.physicsImpostor.dispose();
  25574. mesh.physicsImpostor = null;
  25575. }
  25576. };
  25577. // Misc.
  25578. Scene.prototype._rebuildGeometries = function () {
  25579. for (var _i = 0, _a = this._geometries; _i < _a.length; _i++) {
  25580. var geometry = _a[_i];
  25581. geometry._rebuild();
  25582. }
  25583. for (var _b = 0, _c = this.meshes; _b < _c.length; _b++) {
  25584. var mesh = _c[_b];
  25585. mesh._rebuild();
  25586. }
  25587. if (this.postProcessManager) {
  25588. this.postProcessManager._rebuild();
  25589. }
  25590. for (var _d = 0, _e = this.layers; _d < _e.length; _d++) {
  25591. var layer = _e[_d];
  25592. layer._rebuild();
  25593. }
  25594. for (var _f = 0, _g = this.effectLayers; _f < _g.length; _f++) {
  25595. var effectLayer = _g[_f];
  25596. effectLayer._rebuild();
  25597. }
  25598. if (this._boundingBoxRenderer) {
  25599. this._boundingBoxRenderer._rebuild();
  25600. }
  25601. for (var _h = 0, _j = this.particleSystems; _h < _j.length; _h++) {
  25602. var system = _j[_h];
  25603. system.rebuild();
  25604. }
  25605. if (this._postProcessRenderPipelineManager) {
  25606. this._postProcessRenderPipelineManager._rebuild();
  25607. }
  25608. };
  25609. Scene.prototype._rebuildTextures = function () {
  25610. for (var _i = 0, _a = this.textures; _i < _a.length; _i++) {
  25611. var texture = _a[_i];
  25612. texture._rebuild();
  25613. }
  25614. this.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  25615. };
  25616. /**
  25617. * Creates a default light for the scene.
  25618. * @param replace Whether to replace the existing lights in the scene.
  25619. */
  25620. Scene.prototype.createDefaultLight = function (replace) {
  25621. if (replace === void 0) { replace = false; }
  25622. // Dispose existing light in replace mode.
  25623. if (replace) {
  25624. if (this.lights) {
  25625. for (var i = 0; i < this.lights.length; i++) {
  25626. this.lights[i].dispose();
  25627. }
  25628. }
  25629. }
  25630. // Light
  25631. if (this.lights.length === 0) {
  25632. new BABYLON.HemisphericLight("default light", BABYLON.Vector3.Up(), this);
  25633. }
  25634. };
  25635. /**
  25636. * Creates a default camera for the scene.
  25637. * @param createArcRotateCamera Whether to create an arc rotate or a free camera.
  25638. * @param replace Whether to replace the existing active camera in the scene.
  25639. * @param attachCameraControls Whether to attach camera controls to the canvas.
  25640. */
  25641. Scene.prototype.createDefaultCamera = function (createArcRotateCamera, replace, attachCameraControls) {
  25642. if (createArcRotateCamera === void 0) { createArcRotateCamera = false; }
  25643. if (replace === void 0) { replace = false; }
  25644. if (attachCameraControls === void 0) { attachCameraControls = false; }
  25645. // Dispose existing camera in replace mode.
  25646. if (replace) {
  25647. if (this.activeCamera) {
  25648. this.activeCamera.dispose();
  25649. this.activeCamera = null;
  25650. }
  25651. }
  25652. // Camera
  25653. if (!this.activeCamera) {
  25654. var worldExtends = this.getWorldExtends();
  25655. var worldSize = worldExtends.max.subtract(worldExtends.min);
  25656. var worldCenter = worldExtends.min.add(worldSize.scale(0.5));
  25657. var camera;
  25658. var radius = worldSize.length() * 1.5;
  25659. // empty scene scenario!
  25660. if (!isFinite(radius)) {
  25661. radius = 1;
  25662. worldCenter.copyFromFloats(0, 0, 0);
  25663. }
  25664. if (createArcRotateCamera) {
  25665. var arcRotateCamera = new BABYLON.ArcRotateCamera("default camera", -(Math.PI / 2), Math.PI / 2, radius, worldCenter, this);
  25666. arcRotateCamera.lowerRadiusLimit = radius * 0.01;
  25667. arcRotateCamera.wheelPrecision = 100 / radius;
  25668. camera = arcRotateCamera;
  25669. }
  25670. else {
  25671. var freeCamera = new BABYLON.FreeCamera("default camera", new BABYLON.Vector3(worldCenter.x, worldCenter.y, -radius), this);
  25672. freeCamera.setTarget(worldCenter);
  25673. camera = freeCamera;
  25674. }
  25675. camera.minZ = radius * 0.01;
  25676. camera.maxZ = radius * 1000;
  25677. camera.speed = radius * 0.2;
  25678. this.activeCamera = camera;
  25679. var canvas = this.getEngine().getRenderingCanvas();
  25680. if (attachCameraControls && canvas) {
  25681. camera.attachControl(canvas);
  25682. }
  25683. }
  25684. };
  25685. Scene.prototype.createDefaultCameraOrLight = function (createArcRotateCamera, replace, attachCameraControls) {
  25686. if (createArcRotateCamera === void 0) { createArcRotateCamera = false; }
  25687. if (replace === void 0) { replace = false; }
  25688. if (attachCameraControls === void 0) { attachCameraControls = false; }
  25689. this.createDefaultLight(replace);
  25690. this.createDefaultCamera(createArcRotateCamera, replace, attachCameraControls);
  25691. };
  25692. Scene.prototype.createDefaultSkybox = function (environmentTexture, pbr, scale, blur) {
  25693. if (pbr === void 0) { pbr = false; }
  25694. if (scale === void 0) { scale = 1000; }
  25695. if (blur === void 0) { blur = 0; }
  25696. if (environmentTexture) {
  25697. this.environmentTexture = environmentTexture;
  25698. }
  25699. if (!this.environmentTexture) {
  25700. BABYLON.Tools.Warn("Can not create default skybox without environment texture.");
  25701. return null;
  25702. }
  25703. // Skybox
  25704. var hdrSkybox = BABYLON.Mesh.CreateBox("hdrSkyBox", scale, this);
  25705. if (pbr) {
  25706. var hdrSkyboxMaterial = new BABYLON.PBRMaterial("skyBox", this);
  25707. hdrSkyboxMaterial.backFaceCulling = false;
  25708. hdrSkyboxMaterial.reflectionTexture = this.environmentTexture.clone();
  25709. if (hdrSkyboxMaterial.reflectionTexture) {
  25710. hdrSkyboxMaterial.reflectionTexture.coordinatesMode = BABYLON.Texture.SKYBOX_MODE;
  25711. }
  25712. hdrSkyboxMaterial.microSurface = 1.0 - blur;
  25713. hdrSkyboxMaterial.disableLighting = true;
  25714. hdrSkyboxMaterial.twoSidedLighting = true;
  25715. hdrSkybox.infiniteDistance = true;
  25716. hdrSkybox.material = hdrSkyboxMaterial;
  25717. }
  25718. else {
  25719. var skyboxMaterial = new BABYLON.StandardMaterial("skyBox", this);
  25720. skyboxMaterial.backFaceCulling = false;
  25721. skyboxMaterial.reflectionTexture = this.environmentTexture.clone();
  25722. if (skyboxMaterial.reflectionTexture) {
  25723. skyboxMaterial.reflectionTexture.coordinatesMode = BABYLON.Texture.SKYBOX_MODE;
  25724. }
  25725. skyboxMaterial.disableLighting = true;
  25726. hdrSkybox.infiniteDistance = true;
  25727. hdrSkybox.material = skyboxMaterial;
  25728. }
  25729. return hdrSkybox;
  25730. };
  25731. Scene.prototype.createDefaultEnvironment = function (options) {
  25732. if (BABYLON.EnvironmentHelper) {
  25733. return new BABYLON.EnvironmentHelper(options, this);
  25734. }
  25735. return null;
  25736. };
  25737. Scene.prototype.createDefaultVRExperience = function (webVROptions) {
  25738. if (webVROptions === void 0) { webVROptions = {}; }
  25739. return new BABYLON.VRExperienceHelper(this, webVROptions);
  25740. };
  25741. // Tags
  25742. Scene.prototype._getByTags = function (list, tagsQuery, forEach) {
  25743. if (tagsQuery === undefined) {
  25744. // returns the complete list (could be done with BABYLON.Tags.MatchesQuery but no need to have a for-loop here)
  25745. return list;
  25746. }
  25747. var listByTags = [];
  25748. forEach = forEach || (function (item) { return; });
  25749. for (var i in list) {
  25750. var item = list[i];
  25751. if (BABYLON.Tags && BABYLON.Tags.MatchesQuery(item, tagsQuery)) {
  25752. listByTags.push(item);
  25753. forEach(item);
  25754. }
  25755. }
  25756. return listByTags;
  25757. };
  25758. Scene.prototype.getMeshesByTags = function (tagsQuery, forEach) {
  25759. return this._getByTags(this.meshes, tagsQuery, forEach);
  25760. };
  25761. Scene.prototype.getCamerasByTags = function (tagsQuery, forEach) {
  25762. return this._getByTags(this.cameras, tagsQuery, forEach);
  25763. };
  25764. Scene.prototype.getLightsByTags = function (tagsQuery, forEach) {
  25765. return this._getByTags(this.lights, tagsQuery, forEach);
  25766. };
  25767. Scene.prototype.getMaterialByTags = function (tagsQuery, forEach) {
  25768. return this._getByTags(this.materials, tagsQuery, forEach).concat(this._getByTags(this.multiMaterials, tagsQuery, forEach));
  25769. };
  25770. /**
  25771. * Overrides the default sort function applied in the renderging group to prepare the meshes.
  25772. * This allowed control for front to back rendering or reversly depending of the special needs.
  25773. *
  25774. * @param renderingGroupId The rendering group id corresponding to its index
  25775. * @param opaqueSortCompareFn The opaque queue comparison function use to sort.
  25776. * @param alphaTestSortCompareFn The alpha test queue comparison function use to sort.
  25777. * @param transparentSortCompareFn The transparent queue comparison function use to sort.
  25778. */
  25779. Scene.prototype.setRenderingOrder = function (renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  25780. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  25781. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  25782. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  25783. this._renderingManager.setRenderingOrder(renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn);
  25784. };
  25785. /**
  25786. * Specifies whether or not the stencil and depth buffer are cleared between two rendering groups.
  25787. *
  25788. * @param renderingGroupId The rendering group id corresponding to its index
  25789. * @param autoClearDepthStencil Automatically clears depth and stencil between groups if true.
  25790. * @param depth Automatically clears depth between groups if true and autoClear is true.
  25791. * @param stencil Automatically clears stencil between groups if true and autoClear is true.
  25792. */
  25793. Scene.prototype.setRenderingAutoClearDepthStencil = function (renderingGroupId, autoClearDepthStencil, depth, stencil) {
  25794. if (depth === void 0) { depth = true; }
  25795. if (stencil === void 0) { stencil = true; }
  25796. this._renderingManager.setRenderingAutoClearDepthStencil(renderingGroupId, autoClearDepthStencil, depth, stencil);
  25797. };
  25798. /**
  25799. * Will flag all materials as dirty to trigger new shader compilation
  25800. * @param predicate If not null, it will be used to specifiy if a material has to be marked as dirty
  25801. */
  25802. Scene.prototype.markAllMaterialsAsDirty = function (flag, predicate) {
  25803. for (var _i = 0, _a = this.materials; _i < _a.length; _i++) {
  25804. var material = _a[_i];
  25805. if (predicate && !predicate(material)) {
  25806. continue;
  25807. }
  25808. material.markAsDirty(flag);
  25809. }
  25810. };
  25811. Scene.prototype._loadFile = function (url, onSuccess, onProgress, useDatabase, useArrayBuffer, onError) {
  25812. var _this = this;
  25813. var request = BABYLON.Tools.LoadFile(url, onSuccess, onProgress, useDatabase ? this.database : undefined, useArrayBuffer, onError);
  25814. this._activeRequests.push(request);
  25815. request.onCompleteObservable.add(function (request) {
  25816. _this._activeRequests.splice(_this._activeRequests.indexOf(request), 1);
  25817. });
  25818. return request;
  25819. };
  25820. /** @ignore */
  25821. Scene.prototype._loadFileAsync = function (url, useDatabase, useArrayBuffer) {
  25822. var _this = this;
  25823. return new Promise(function (resolve, reject) {
  25824. _this._loadFile(url, function (data) {
  25825. resolve(data);
  25826. }, undefined, useDatabase, useArrayBuffer, function (request, exception) {
  25827. reject(exception);
  25828. });
  25829. });
  25830. };
  25831. // Statics
  25832. Scene._FOGMODE_NONE = 0;
  25833. Scene._FOGMODE_EXP = 1;
  25834. Scene._FOGMODE_EXP2 = 2;
  25835. Scene._FOGMODE_LINEAR = 3;
  25836. Scene._uniqueIdCounter = 0;
  25837. Scene.MinDeltaTime = 1.0;
  25838. Scene.MaxDeltaTime = 1000.0;
  25839. /** The distance in pixel that you have to move to prevent some events */
  25840. Scene.DragMovementThreshold = 10; // in pixels
  25841. /** Time in milliseconds to wait to raise long press events if button is still pressed */
  25842. Scene.LongPressDelay = 500; // in milliseconds
  25843. /** Time in milliseconds with two consecutive clicks will be considered as a double click */
  25844. Scene.DoubleClickDelay = 300; // in milliseconds
  25845. /** If you need to check double click without raising a single click at first click, enable this flag */
  25846. Scene.ExclusiveDoubleClickMode = false;
  25847. return Scene;
  25848. }());
  25849. BABYLON.Scene = Scene;
  25850. })(BABYLON || (BABYLON = {}));
  25851. //# sourceMappingURL=babylon.scene.js.map
  25852. "use strict";
  25853. var BABYLON;
  25854. (function (BABYLON) {
  25855. /**
  25856. * Set of assets to keep when moving a scene into an asset container.
  25857. */
  25858. var KeepAssets = /** @class */ (function () {
  25859. function KeepAssets() {
  25860. /**
  25861. * Cameras to keep.
  25862. */
  25863. this.cameras = new Array();
  25864. /**
  25865. * Lights to keep.
  25866. */
  25867. this.lights = new Array();
  25868. /**
  25869. * Meshes to keep.
  25870. */
  25871. this.meshes = new Array();
  25872. /**
  25873. * Skeletons to keep.
  25874. */
  25875. this.skeletons = new Array();
  25876. /**
  25877. * ParticleSystems to keep.
  25878. */
  25879. this.particleSystems = new Array();
  25880. /**
  25881. * Animations to keep.
  25882. */
  25883. this.animations = new Array();
  25884. /**
  25885. * MultiMaterials to keep.
  25886. */
  25887. this.multiMaterials = new Array();
  25888. /**
  25889. * Materials to keep.
  25890. */
  25891. this.materials = new Array();
  25892. /**
  25893. * MorphTargetManagers to keep.
  25894. */
  25895. this.morphTargetManagers = new Array();
  25896. /**
  25897. * Geometries to keep.
  25898. */
  25899. this.geometries = new Array();
  25900. /**
  25901. * TransformNodes to keep.
  25902. */
  25903. this.transformNodes = new Array();
  25904. /**
  25905. * LensFlareSystems to keep.
  25906. */
  25907. this.lensFlareSystems = new Array();
  25908. /**
  25909. * ShadowGenerators to keep.
  25910. */
  25911. this.shadowGenerators = new Array();
  25912. /**
  25913. * ActionManagers to keep.
  25914. */
  25915. this.actionManagers = new Array();
  25916. /**
  25917. * Sounds to keep.
  25918. */
  25919. this.sounds = new Array();
  25920. }
  25921. return KeepAssets;
  25922. }());
  25923. BABYLON.KeepAssets = KeepAssets;
  25924. /**
  25925. * Container with a set of assets that can be added or removed from a scene.
  25926. */
  25927. var AssetContainer = /** @class */ (function () {
  25928. /**
  25929. * Instantiates an AssetContainer.
  25930. * @param scene The scene the AssetContainer belongs to.
  25931. */
  25932. function AssetContainer(scene) {
  25933. // Objects
  25934. /**
  25935. * Cameras populated in the container.
  25936. */
  25937. this.cameras = new Array();
  25938. /**
  25939. * Lights populated in the container.
  25940. */
  25941. this.lights = new Array();
  25942. /**
  25943. * Meshes populated in the container.
  25944. */
  25945. this.meshes = new Array();
  25946. /**
  25947. * Skeletons populated in the container.
  25948. */
  25949. this.skeletons = new Array();
  25950. /**
  25951. * ParticleSystems populated in the container.
  25952. */
  25953. this.particleSystems = new Array();
  25954. /**
  25955. * Animations populated in the container.
  25956. */
  25957. this.animations = new Array();
  25958. /**
  25959. * MultiMaterials populated in the container.
  25960. */
  25961. this.multiMaterials = new Array();
  25962. /**
  25963. * Materials populated in the container.
  25964. */
  25965. this.materials = new Array();
  25966. /**
  25967. * MorphTargetManagers populated in the container.
  25968. */
  25969. this.morphTargetManagers = new Array();
  25970. /**
  25971. * Geometries populated in the container.
  25972. */
  25973. this.geometries = new Array();
  25974. /**
  25975. * TransformNodes populated in the container.
  25976. */
  25977. this.transformNodes = new Array();
  25978. /**
  25979. * LensFlareSystems populated in the container.
  25980. */
  25981. this.lensFlareSystems = new Array();
  25982. /**
  25983. * ShadowGenerators populated in the container.
  25984. */
  25985. this.shadowGenerators = new Array();
  25986. /**
  25987. * ActionManagers populated in the container.
  25988. */
  25989. this.actionManagers = new Array();
  25990. /**
  25991. * Sounds populated in the container.
  25992. */
  25993. this.sounds = new Array();
  25994. this.scene = scene;
  25995. }
  25996. /**
  25997. * Adds all the assets from the container to the scene.
  25998. */
  25999. AssetContainer.prototype.addAllToScene = function () {
  26000. var _this = this;
  26001. this.cameras.forEach(function (o) {
  26002. _this.scene.addCamera(o);
  26003. });
  26004. this.lights.forEach(function (o) {
  26005. _this.scene.addLight(o);
  26006. });
  26007. this.meshes.forEach(function (o) {
  26008. _this.scene.addMesh(o);
  26009. });
  26010. this.skeletons.forEach(function (o) {
  26011. _this.scene.addSkeleton(o);
  26012. });
  26013. this.particleSystems.forEach(function (o) {
  26014. _this.scene.addParticleSystem(o);
  26015. });
  26016. this.animations.forEach(function (o) {
  26017. _this.scene.addAnimation(o);
  26018. });
  26019. this.multiMaterials.forEach(function (o) {
  26020. _this.scene.addMultiMaterial(o);
  26021. });
  26022. this.materials.forEach(function (o) {
  26023. _this.scene.addMaterial(o);
  26024. });
  26025. this.morphTargetManagers.forEach(function (o) {
  26026. _this.scene.addMorphTargetManager(o);
  26027. });
  26028. this.geometries.forEach(function (o) {
  26029. _this.scene.addGeometry(o);
  26030. });
  26031. this.transformNodes.forEach(function (o) {
  26032. _this.scene.addTransformNode(o);
  26033. });
  26034. this.lensFlareSystems.forEach(function (o) {
  26035. _this.scene.addLensFlareSystem(o);
  26036. });
  26037. this.actionManagers.forEach(function (o) {
  26038. _this.scene.addActionManager(o);
  26039. });
  26040. this.sounds.forEach(function (o) {
  26041. o.play();
  26042. o.autoplay = true;
  26043. _this.scene.mainSoundTrack.AddSound(o);
  26044. });
  26045. };
  26046. /**
  26047. * Removes all the assets in the container from the scene
  26048. */
  26049. AssetContainer.prototype.removeAllFromScene = function () {
  26050. var _this = this;
  26051. this.cameras.forEach(function (o) {
  26052. _this.scene.removeCamera(o);
  26053. });
  26054. this.lights.forEach(function (o) {
  26055. _this.scene.removeLight(o);
  26056. });
  26057. this.meshes.forEach(function (o) {
  26058. _this.scene.removeMesh(o);
  26059. });
  26060. this.skeletons.forEach(function (o) {
  26061. _this.scene.removeSkeleton(o);
  26062. });
  26063. this.particleSystems.forEach(function (o) {
  26064. _this.scene.removeParticleSystem(o);
  26065. });
  26066. this.animations.forEach(function (o) {
  26067. _this.scene.removeAnimation(o);
  26068. });
  26069. this.multiMaterials.forEach(function (o) {
  26070. _this.scene.removeMultiMaterial(o);
  26071. });
  26072. this.materials.forEach(function (o) {
  26073. _this.scene.removeMaterial(o);
  26074. });
  26075. this.morphTargetManagers.forEach(function (o) {
  26076. _this.scene.removeMorphTargetManager(o);
  26077. });
  26078. this.geometries.forEach(function (o) {
  26079. _this.scene.removeGeometry(o);
  26080. });
  26081. this.transformNodes.forEach(function (o) {
  26082. _this.scene.removeTransformNode(o);
  26083. });
  26084. this.lensFlareSystems.forEach(function (o) {
  26085. _this.scene.removeLensFlareSystem(o);
  26086. });
  26087. this.actionManagers.forEach(function (o) {
  26088. _this.scene.removeActionManager(o);
  26089. });
  26090. this.sounds.forEach(function (o) {
  26091. o.stop();
  26092. o.autoplay = false;
  26093. _this.scene.mainSoundTrack.RemoveSound(o);
  26094. });
  26095. };
  26096. AssetContainer.prototype._moveAssets = function (sourceAssets, targetAssets, keepAssets) {
  26097. for (var _i = 0, sourceAssets_1 = sourceAssets; _i < sourceAssets_1.length; _i++) {
  26098. var asset = sourceAssets_1[_i];
  26099. var move = true;
  26100. for (var _a = 0, keepAssets_1 = keepAssets; _a < keepAssets_1.length; _a++) {
  26101. var keepAsset = keepAssets_1[_a];
  26102. if (asset === keepAsset) {
  26103. move = false;
  26104. break;
  26105. }
  26106. }
  26107. if (move) {
  26108. targetAssets.push(asset);
  26109. }
  26110. }
  26111. };
  26112. /**
  26113. * Removes all the assets contained in the scene and adds them to the container.
  26114. * @param keepAssets Set of assets to keep in the scene. (default: empty)
  26115. */
  26116. AssetContainer.prototype.moveAllFromScene = function (keepAssets) {
  26117. if (keepAssets === undefined) {
  26118. keepAssets = new KeepAssets();
  26119. }
  26120. this._moveAssets(this.scene.cameras, this.cameras, keepAssets.cameras);
  26121. this._moveAssets(this.scene.meshes, this.meshes, keepAssets.meshes);
  26122. this._moveAssets(this.scene.getGeometries(), this.geometries, keepAssets.geometries);
  26123. this._moveAssets(this.scene.materials, this.materials, keepAssets.materials);
  26124. this._moveAssets(this.scene._actionManagers, this.actionManagers, keepAssets.actionManagers);
  26125. this._moveAssets(this.scene.animations, this.animations, keepAssets.animations);
  26126. this._moveAssets(this.scene.lensFlareSystems, this.lensFlareSystems, keepAssets.lensFlareSystems);
  26127. this._moveAssets(this.scene.lights, this.lights, keepAssets.lights);
  26128. this._moveAssets(this.scene.morphTargetManagers, this.morphTargetManagers, keepAssets.morphTargetManagers);
  26129. this._moveAssets(this.scene.multiMaterials, this.multiMaterials, keepAssets.multiMaterials);
  26130. this._moveAssets(this.scene.skeletons, this.skeletons, keepAssets.skeletons);
  26131. this._moveAssets(this.scene.particleSystems, this.particleSystems, keepAssets.particleSystems);
  26132. this._moveAssets(this.scene.mainSoundTrack.soundCollection, this.sounds, keepAssets.sounds);
  26133. this._moveAssets(this.scene.transformNodes, this.transformNodes, keepAssets.transformNodes);
  26134. this.removeAllFromScene();
  26135. };
  26136. return AssetContainer;
  26137. }());
  26138. BABYLON.AssetContainer = AssetContainer;
  26139. })(BABYLON || (BABYLON = {}));
  26140. //# sourceMappingURL=babylon.assetContainer.js.map
  26141. "use strict";
  26142. var BABYLON;
  26143. (function (BABYLON) {
  26144. var Buffer = /** @class */ (function () {
  26145. function Buffer(engine, data, updatable, stride, postponeInternalCreation, instanced) {
  26146. if (instanced === void 0) { instanced = false; }
  26147. if (engine instanceof BABYLON.Mesh) {
  26148. this._engine = engine.getScene().getEngine();
  26149. }
  26150. else {
  26151. this._engine = engine;
  26152. }
  26153. this._updatable = updatable;
  26154. this._instanced = instanced;
  26155. this._data = data;
  26156. this._strideSize = stride;
  26157. if (!postponeInternalCreation) {
  26158. this.create();
  26159. }
  26160. }
  26161. /**
  26162. * Create a new {BABYLON.VertexBuffer} based on the current buffer
  26163. * @param kind defines the vertex buffer kind (position, normal, etc.)
  26164. * @param offset defines offset in the buffer (0 by default)
  26165. * @param size defines the size in floats of attributes (position is 3 for instance)
  26166. * @param stride defines the stride size in floats in the buffer (the offset to apply to reach next value when data is interleaved)
  26167. * @param instanced defines if the vertex buffer contains indexed data
  26168. * @returns the new vertex buffer
  26169. */
  26170. Buffer.prototype.createVertexBuffer = function (kind, offset, size, stride, instanced) {
  26171. // a lot of these parameters are ignored as they are overriden by the buffer
  26172. return new BABYLON.VertexBuffer(this._engine, this, kind, this._updatable, true, stride ? stride : this._strideSize, instanced === undefined ? this._instanced : instanced, offset, size);
  26173. };
  26174. // Properties
  26175. Buffer.prototype.isUpdatable = function () {
  26176. return this._updatable;
  26177. };
  26178. Buffer.prototype.getData = function () {
  26179. return this._data;
  26180. };
  26181. Buffer.prototype.getBuffer = function () {
  26182. return this._buffer;
  26183. };
  26184. Buffer.prototype.getStrideSize = function () {
  26185. return this._strideSize;
  26186. };
  26187. // public getIsInstanced(): boolean {
  26188. // return this._instanced;
  26189. // }
  26190. // public get instanceDivisor(): number {
  26191. // return this._instanceDivisor;
  26192. // }
  26193. // public set instanceDivisor(value: number) {
  26194. // this._instanceDivisor = value;
  26195. // if (value == 0) {
  26196. // this._instanced = false;
  26197. // } else {
  26198. // this._instanced = true;
  26199. // }
  26200. // }
  26201. // Methods
  26202. Buffer.prototype.create = function (data) {
  26203. if (data === void 0) { data = null; }
  26204. if (!data && this._buffer) {
  26205. return; // nothing to do
  26206. }
  26207. data = data || this._data;
  26208. if (!data) {
  26209. return;
  26210. }
  26211. if (!this._buffer) {
  26212. if (this._updatable) {
  26213. this._buffer = this._engine.createDynamicVertexBuffer(data);
  26214. this._data = data;
  26215. }
  26216. else {
  26217. this._buffer = this._engine.createVertexBuffer(data);
  26218. }
  26219. }
  26220. else if (this._updatable) {
  26221. this._engine.updateDynamicVertexBuffer(this._buffer, data);
  26222. this._data = data;
  26223. }
  26224. };
  26225. Buffer.prototype._rebuild = function () {
  26226. this._buffer = null;
  26227. this.create(this._data);
  26228. };
  26229. Buffer.prototype.update = function (data) {
  26230. this.create(data);
  26231. };
  26232. Buffer.prototype.updateDirectly = function (data, offset, vertexCount) {
  26233. if (!this._buffer) {
  26234. return;
  26235. }
  26236. if (this._updatable) {
  26237. this._engine.updateDynamicVertexBuffer(this._buffer, data, offset, (vertexCount ? vertexCount * this.getStrideSize() : undefined));
  26238. this._data = null;
  26239. }
  26240. };
  26241. Buffer.prototype.dispose = function () {
  26242. if (!this._buffer) {
  26243. return;
  26244. }
  26245. if (this._engine._releaseBuffer(this._buffer)) {
  26246. this._buffer = null;
  26247. }
  26248. };
  26249. return Buffer;
  26250. }());
  26251. BABYLON.Buffer = Buffer;
  26252. })(BABYLON || (BABYLON = {}));
  26253. //# sourceMappingURL=babylon.buffer.js.map
  26254. "use strict";
  26255. var BABYLON;
  26256. (function (BABYLON) {
  26257. var VertexBuffer = /** @class */ (function () {
  26258. function VertexBuffer(engine, data, kind, updatable, postponeInternalCreation, stride, instanced, offset, size) {
  26259. if (data instanceof BABYLON.Buffer) {
  26260. if (!stride) {
  26261. stride = data.getStrideSize();
  26262. }
  26263. this._buffer = data;
  26264. this._ownsBuffer = false;
  26265. }
  26266. else {
  26267. if (!stride) {
  26268. stride = VertexBuffer.DeduceStride(kind);
  26269. }
  26270. this._buffer = new BABYLON.Buffer(engine, data, updatable, stride, postponeInternalCreation, instanced);
  26271. this._ownsBuffer = true;
  26272. }
  26273. this._stride = stride;
  26274. this._instanced = instanced !== undefined ? instanced : false;
  26275. this._instanceDivisor = instanced ? 1 : 0;
  26276. this._offset = offset ? offset : 0;
  26277. this._size = size ? size : stride;
  26278. this._kind = kind;
  26279. }
  26280. Object.defineProperty(VertexBuffer.prototype, "instanceDivisor", {
  26281. /**
  26282. * Gets or sets the instance divisor when in instanced mode
  26283. */
  26284. get: function () {
  26285. return this._instanceDivisor;
  26286. },
  26287. set: function (value) {
  26288. this._instanceDivisor = value;
  26289. if (value == 0) {
  26290. this._instanced = false;
  26291. }
  26292. else {
  26293. this._instanced = true;
  26294. }
  26295. },
  26296. enumerable: true,
  26297. configurable: true
  26298. });
  26299. VertexBuffer.prototype._rebuild = function () {
  26300. if (!this._buffer) {
  26301. return;
  26302. }
  26303. this._buffer._rebuild();
  26304. };
  26305. /**
  26306. * Returns the kind of the VertexBuffer (string).
  26307. */
  26308. VertexBuffer.prototype.getKind = function () {
  26309. return this._kind;
  26310. };
  26311. // Properties
  26312. /**
  26313. * Boolean : is the VertexBuffer updatable ?
  26314. */
  26315. VertexBuffer.prototype.isUpdatable = function () {
  26316. return this._buffer.isUpdatable();
  26317. };
  26318. /**
  26319. * Returns an array of numbers or a Float32Array containing the VertexBuffer data.
  26320. */
  26321. VertexBuffer.prototype.getData = function () {
  26322. return this._buffer.getData();
  26323. };
  26324. /**
  26325. * Returns the WebGLBuffer associated to the VertexBuffer.
  26326. */
  26327. VertexBuffer.prototype.getBuffer = function () {
  26328. return this._buffer.getBuffer();
  26329. };
  26330. /**
  26331. * Returns the stride of the VertexBuffer (integer).
  26332. */
  26333. VertexBuffer.prototype.getStrideSize = function () {
  26334. return this._stride;
  26335. };
  26336. /**
  26337. * Returns the offset (integer).
  26338. */
  26339. VertexBuffer.prototype.getOffset = function () {
  26340. return this._offset;
  26341. };
  26342. /**
  26343. * Returns the VertexBuffer total size (integer).
  26344. */
  26345. VertexBuffer.prototype.getSize = function () {
  26346. return this._size;
  26347. };
  26348. /**
  26349. * Boolean : is the WebGLBuffer of the VertexBuffer instanced now ?
  26350. */
  26351. VertexBuffer.prototype.getIsInstanced = function () {
  26352. return this._instanced;
  26353. };
  26354. /**
  26355. * Returns the instancing divisor, zero for non-instanced (integer).
  26356. */
  26357. VertexBuffer.prototype.getInstanceDivisor = function () {
  26358. return this._instanceDivisor;
  26359. };
  26360. // Methods
  26361. /**
  26362. * Creates the underlying WebGLBuffer from the passed numeric array or Float32Array.
  26363. * Returns the created WebGLBuffer.
  26364. */
  26365. VertexBuffer.prototype.create = function (data) {
  26366. return this._buffer.create(data);
  26367. };
  26368. /**
  26369. * Updates the underlying WebGLBuffer according to the passed numeric array or Float32Array.
  26370. * This function will create a new buffer if the current one is not updatable
  26371. * Returns the updated WebGLBuffer.
  26372. */
  26373. VertexBuffer.prototype.update = function (data) {
  26374. return this._buffer.update(data);
  26375. };
  26376. /**
  26377. * Updates directly the underlying WebGLBuffer according to the passed numeric array or Float32Array.
  26378. * Returns the directly updated WebGLBuffer.
  26379. */
  26380. VertexBuffer.prototype.updateDirectly = function (data, offset) {
  26381. return this._buffer.updateDirectly(data, offset);
  26382. };
  26383. /**
  26384. * Disposes the VertexBuffer and the underlying WebGLBuffer.
  26385. */
  26386. VertexBuffer.prototype.dispose = function () {
  26387. if (this._ownsBuffer) {
  26388. this._buffer.dispose();
  26389. }
  26390. };
  26391. Object.defineProperty(VertexBuffer, "PositionKind", {
  26392. get: function () {
  26393. return VertexBuffer._PositionKind;
  26394. },
  26395. enumerable: true,
  26396. configurable: true
  26397. });
  26398. Object.defineProperty(VertexBuffer, "NormalKind", {
  26399. get: function () {
  26400. return VertexBuffer._NormalKind;
  26401. },
  26402. enumerable: true,
  26403. configurable: true
  26404. });
  26405. Object.defineProperty(VertexBuffer, "TangentKind", {
  26406. get: function () {
  26407. return VertexBuffer._TangentKind;
  26408. },
  26409. enumerable: true,
  26410. configurable: true
  26411. });
  26412. Object.defineProperty(VertexBuffer, "UVKind", {
  26413. get: function () {
  26414. return VertexBuffer._UVKind;
  26415. },
  26416. enumerable: true,
  26417. configurable: true
  26418. });
  26419. Object.defineProperty(VertexBuffer, "UV2Kind", {
  26420. get: function () {
  26421. return VertexBuffer._UV2Kind;
  26422. },
  26423. enumerable: true,
  26424. configurable: true
  26425. });
  26426. Object.defineProperty(VertexBuffer, "UV3Kind", {
  26427. get: function () {
  26428. return VertexBuffer._UV3Kind;
  26429. },
  26430. enumerable: true,
  26431. configurable: true
  26432. });
  26433. Object.defineProperty(VertexBuffer, "UV4Kind", {
  26434. get: function () {
  26435. return VertexBuffer._UV4Kind;
  26436. },
  26437. enumerable: true,
  26438. configurable: true
  26439. });
  26440. Object.defineProperty(VertexBuffer, "UV5Kind", {
  26441. get: function () {
  26442. return VertexBuffer._UV5Kind;
  26443. },
  26444. enumerable: true,
  26445. configurable: true
  26446. });
  26447. Object.defineProperty(VertexBuffer, "UV6Kind", {
  26448. get: function () {
  26449. return VertexBuffer._UV6Kind;
  26450. },
  26451. enumerable: true,
  26452. configurable: true
  26453. });
  26454. Object.defineProperty(VertexBuffer, "ColorKind", {
  26455. get: function () {
  26456. return VertexBuffer._ColorKind;
  26457. },
  26458. enumerable: true,
  26459. configurable: true
  26460. });
  26461. Object.defineProperty(VertexBuffer, "MatricesIndicesKind", {
  26462. get: function () {
  26463. return VertexBuffer._MatricesIndicesKind;
  26464. },
  26465. enumerable: true,
  26466. configurable: true
  26467. });
  26468. Object.defineProperty(VertexBuffer, "MatricesWeightsKind", {
  26469. get: function () {
  26470. return VertexBuffer._MatricesWeightsKind;
  26471. },
  26472. enumerable: true,
  26473. configurable: true
  26474. });
  26475. Object.defineProperty(VertexBuffer, "MatricesIndicesExtraKind", {
  26476. get: function () {
  26477. return VertexBuffer._MatricesIndicesExtraKind;
  26478. },
  26479. enumerable: true,
  26480. configurable: true
  26481. });
  26482. Object.defineProperty(VertexBuffer, "MatricesWeightsExtraKind", {
  26483. get: function () {
  26484. return VertexBuffer._MatricesWeightsExtraKind;
  26485. },
  26486. enumerable: true,
  26487. configurable: true
  26488. });
  26489. /**
  26490. * Deduces the stride given a kind.
  26491. * @param kind The kind string to deduce
  26492. * @returns The deduced stride
  26493. */
  26494. VertexBuffer.DeduceStride = function (kind) {
  26495. switch (kind) {
  26496. case VertexBuffer.UVKind:
  26497. case VertexBuffer.UV2Kind:
  26498. case VertexBuffer.UV3Kind:
  26499. case VertexBuffer.UV4Kind:
  26500. case VertexBuffer.UV5Kind:
  26501. case VertexBuffer.UV6Kind:
  26502. return 2;
  26503. case VertexBuffer.NormalKind:
  26504. case VertexBuffer.PositionKind:
  26505. return 3;
  26506. case VertexBuffer.ColorKind:
  26507. case VertexBuffer.MatricesIndicesKind:
  26508. case VertexBuffer.MatricesIndicesExtraKind:
  26509. case VertexBuffer.MatricesWeightsKind:
  26510. case VertexBuffer.MatricesWeightsExtraKind:
  26511. case VertexBuffer.TangentKind:
  26512. return 4;
  26513. default:
  26514. throw new Error("Invalid kind '" + kind + "'");
  26515. }
  26516. };
  26517. // Enums
  26518. VertexBuffer._PositionKind = "position";
  26519. VertexBuffer._NormalKind = "normal";
  26520. VertexBuffer._TangentKind = "tangent";
  26521. VertexBuffer._UVKind = "uv";
  26522. VertexBuffer._UV2Kind = "uv2";
  26523. VertexBuffer._UV3Kind = "uv3";
  26524. VertexBuffer._UV4Kind = "uv4";
  26525. VertexBuffer._UV5Kind = "uv5";
  26526. VertexBuffer._UV6Kind = "uv6";
  26527. VertexBuffer._ColorKind = "color";
  26528. VertexBuffer._MatricesIndicesKind = "matricesIndices";
  26529. VertexBuffer._MatricesWeightsKind = "matricesWeights";
  26530. VertexBuffer._MatricesIndicesExtraKind = "matricesIndicesExtra";
  26531. VertexBuffer._MatricesWeightsExtraKind = "matricesWeightsExtra";
  26532. return VertexBuffer;
  26533. }());
  26534. BABYLON.VertexBuffer = VertexBuffer;
  26535. })(BABYLON || (BABYLON = {}));
  26536. //# sourceMappingURL=babylon.vertexBuffer.js.map
  26537. "use strict";
  26538. var BABYLON;
  26539. (function (BABYLON) {
  26540. /**
  26541. * Internal class used by the engine to get list of {BABYLON.InternalTexture} already bound to the GL context
  26542. */
  26543. var DummyInternalTextureTracker = /** @class */ (function () {
  26544. function DummyInternalTextureTracker() {
  26545. /**
  26546. * Gets or set the previous tracker in the list
  26547. */
  26548. this.previous = null;
  26549. /**
  26550. * Gets or set the next tracker in the list
  26551. */
  26552. this.next = null;
  26553. }
  26554. return DummyInternalTextureTracker;
  26555. }());
  26556. BABYLON.DummyInternalTextureTracker = DummyInternalTextureTracker;
  26557. })(BABYLON || (BABYLON = {}));
  26558. //# sourceMappingURL=babylon.internalTextureTracker.js.map
  26559. "use strict";
  26560. var BABYLON;
  26561. (function (BABYLON) {
  26562. /**
  26563. * Class used to store data associated with WebGL texture data for the engine
  26564. * This class should not be used directly
  26565. */
  26566. var InternalTexture = /** @class */ (function () {
  26567. /**
  26568. * Creates a new InternalTexture
  26569. * @param engine defines the engine to use
  26570. * @param dataSource defines the type of data that will be used
  26571. */
  26572. function InternalTexture(engine, dataSource) {
  26573. /**
  26574. * Observable called when the texture is loaded
  26575. */
  26576. this.onLoadedObservable = new BABYLON.Observable();
  26577. /**
  26578. * Gets or set the previous tracker in the list
  26579. */
  26580. this.previous = null;
  26581. /**
  26582. * Gets or set the next tracker in the list
  26583. */
  26584. this.next = null;
  26585. // Private
  26586. /** @ignore */
  26587. this._initialSlot = -1;
  26588. /** @ignore */
  26589. this._designatedSlot = -1;
  26590. /** @ignore */
  26591. this._dataSource = InternalTexture.DATASOURCE_UNKNOWN;
  26592. /** @ignore */
  26593. this._comparisonFunction = 0;
  26594. /** @ignore */
  26595. this._references = 1;
  26596. this._engine = engine;
  26597. this._dataSource = dataSource;
  26598. this._webGLTexture = engine._createTexture();
  26599. }
  26600. Object.defineProperty(InternalTexture.prototype, "dataSource", {
  26601. /**
  26602. * Gets the data source type of the texture (can be one of the BABYLON.InternalTexture.DATASOURCE_XXXX)
  26603. */
  26604. get: function () {
  26605. return this._dataSource;
  26606. },
  26607. enumerable: true,
  26608. configurable: true
  26609. });
  26610. /**
  26611. * Increments the number of references (ie. the number of {BABYLON.Texture} that point to it)
  26612. */
  26613. InternalTexture.prototype.incrementReferences = function () {
  26614. this._references++;
  26615. };
  26616. /**
  26617. * Change the size of the texture (not the size of the content)
  26618. * @param width defines the new width
  26619. * @param height defines the new height
  26620. * @param depth defines the new depth (1 by default)
  26621. */
  26622. InternalTexture.prototype.updateSize = function (width, height, depth) {
  26623. if (depth === void 0) { depth = 1; }
  26624. this.width = width;
  26625. this.height = height;
  26626. this.depth = depth;
  26627. this.baseWidth = width;
  26628. this.baseHeight = height;
  26629. this.baseDepth = depth;
  26630. this._size = width * height * depth;
  26631. };
  26632. /** @ignore */
  26633. InternalTexture.prototype._rebuild = function () {
  26634. var _this = this;
  26635. var proxy;
  26636. this.isReady = false;
  26637. this._cachedCoordinatesMode = null;
  26638. this._cachedWrapU = null;
  26639. this._cachedWrapV = null;
  26640. this._cachedAnisotropicFilteringLevel = null;
  26641. switch (this._dataSource) {
  26642. case InternalTexture.DATASOURCE_TEMP:
  26643. return;
  26644. case InternalTexture.DATASOURCE_URL:
  26645. proxy = this._engine.createTexture(this.url, !this.generateMipMaps, this.invertY, null, this.samplingMode, function () {
  26646. _this.isReady = true;
  26647. }, null, this._buffer, undefined, this.format);
  26648. proxy._swapAndDie(this);
  26649. return;
  26650. case InternalTexture.DATASOURCE_RAW:
  26651. proxy = this._engine.createRawTexture(this._bufferView, this.baseWidth, this.baseHeight, this.format, this.generateMipMaps, this.invertY, this.samplingMode, this._compression);
  26652. proxy._swapAndDie(this);
  26653. this.isReady = true;
  26654. return;
  26655. case InternalTexture.DATASOURCE_RAW3D:
  26656. proxy = this._engine.createRawTexture3D(this._bufferView, this.baseWidth, this.baseHeight, this.baseDepth, this.format, this.generateMipMaps, this.invertY, this.samplingMode, this._compression);
  26657. proxy._swapAndDie(this);
  26658. this.isReady = true;
  26659. return;
  26660. case InternalTexture.DATASOURCE_DYNAMIC:
  26661. proxy = this._engine.createDynamicTexture(this.baseWidth, this.baseHeight, this.generateMipMaps, this.samplingMode);
  26662. proxy._swapAndDie(this);
  26663. // The engine will make sure to update content so no need to flag it as isReady = true
  26664. return;
  26665. case InternalTexture.DATASOURCE_RENDERTARGET:
  26666. var options = new BABYLON.RenderTargetCreationOptions();
  26667. options.generateDepthBuffer = this._generateDepthBuffer;
  26668. options.generateMipMaps = this.generateMipMaps;
  26669. options.generateStencilBuffer = this._generateStencilBuffer;
  26670. options.samplingMode = this.samplingMode;
  26671. options.type = this.type;
  26672. if (this.isCube) {
  26673. proxy = this._engine.createRenderTargetCubeTexture(this.width, options);
  26674. }
  26675. else {
  26676. var size = {
  26677. width: this.width,
  26678. height: this.height
  26679. };
  26680. proxy = this._engine.createRenderTargetTexture(size, options);
  26681. }
  26682. proxy._swapAndDie(this);
  26683. this.isReady = true;
  26684. return;
  26685. case InternalTexture.DATASOURCE_DEPTHTEXTURE:
  26686. var depthTextureOptions = {
  26687. bilinearFiltering: this.samplingMode !== BABYLON.Texture.BILINEAR_SAMPLINGMODE,
  26688. comparisonFunction: this._comparisonFunction,
  26689. generateStencil: this._generateStencilBuffer,
  26690. isCube: this.isCube
  26691. };
  26692. proxy = this._engine.createDepthStencilTexture({ width: this.width, height: this.height }, depthTextureOptions);
  26693. proxy._swapAndDie(this);
  26694. this.isReady = true;
  26695. return;
  26696. case InternalTexture.DATASOURCE_CUBE:
  26697. proxy = this._engine.createCubeTexture(this.url, null, this._files, !this.generateMipMaps, function () {
  26698. _this.isReady = true;
  26699. }, null, this.format, this._extension);
  26700. proxy._swapAndDie(this);
  26701. return;
  26702. case InternalTexture.DATASOURCE_CUBERAW:
  26703. proxy = this._engine.createRawCubeTexture(this._bufferViewArray, this.width, this.format, this.type, this.generateMipMaps, this.invertY, this.samplingMode, this._compression);
  26704. proxy._swapAndDie(this);
  26705. this.isReady = true;
  26706. return;
  26707. case InternalTexture.DATASOURCE_CUBEPREFILTERED:
  26708. proxy = this._engine.createPrefilteredCubeTexture(this.url, null, this._lodGenerationScale, this._lodGenerationOffset, function (proxy) {
  26709. if (proxy) {
  26710. proxy._swapAndDie(_this);
  26711. }
  26712. _this.isReady = true;
  26713. }, null, this.format, this._extension);
  26714. return;
  26715. }
  26716. };
  26717. InternalTexture.prototype._swapAndDie = function (target) {
  26718. target._webGLTexture = this._webGLTexture;
  26719. if (this._framebuffer) {
  26720. target._framebuffer = this._framebuffer;
  26721. }
  26722. if (this._depthStencilBuffer) {
  26723. target._depthStencilBuffer = this._depthStencilBuffer;
  26724. }
  26725. if (this._lodTextureHigh) {
  26726. if (target._lodTextureHigh) {
  26727. target._lodTextureHigh.dispose();
  26728. }
  26729. target._lodTextureHigh = this._lodTextureHigh;
  26730. }
  26731. if (this._lodTextureMid) {
  26732. if (target._lodTextureMid) {
  26733. target._lodTextureMid.dispose();
  26734. }
  26735. target._lodTextureMid = this._lodTextureMid;
  26736. }
  26737. if (this._lodTextureLow) {
  26738. if (target._lodTextureLow) {
  26739. target._lodTextureLow.dispose();
  26740. }
  26741. target._lodTextureLow = this._lodTextureLow;
  26742. }
  26743. var cache = this._engine.getLoadedTexturesCache();
  26744. var index = cache.indexOf(this);
  26745. if (index !== -1) {
  26746. cache.splice(index, 1);
  26747. }
  26748. };
  26749. /**
  26750. * Dispose the current allocated resources
  26751. */
  26752. InternalTexture.prototype.dispose = function () {
  26753. if (!this._webGLTexture) {
  26754. return;
  26755. }
  26756. this._references--;
  26757. if (this._references === 0) {
  26758. this._engine._releaseTexture(this);
  26759. this._webGLTexture = null;
  26760. this.previous = null;
  26761. this.next = null;
  26762. }
  26763. };
  26764. /**
  26765. * The source of the texture data is unknown
  26766. */
  26767. InternalTexture.DATASOURCE_UNKNOWN = 0;
  26768. /**
  26769. * Texture data comes from an URL
  26770. */
  26771. InternalTexture.DATASOURCE_URL = 1;
  26772. /**
  26773. * Texture data is only used for temporary storage
  26774. */
  26775. InternalTexture.DATASOURCE_TEMP = 2;
  26776. /**
  26777. * Texture data comes from raw data (ArrayBuffer)
  26778. */
  26779. InternalTexture.DATASOURCE_RAW = 3;
  26780. /**
  26781. * Texture content is dynamic (video or dynamic texture)
  26782. */
  26783. InternalTexture.DATASOURCE_DYNAMIC = 4;
  26784. /**
  26785. * Texture content is generated by rendering to it
  26786. */
  26787. InternalTexture.DATASOURCE_RENDERTARGET = 5;
  26788. /**
  26789. * Texture content is part of a multi render target process
  26790. */
  26791. InternalTexture.DATASOURCE_MULTIRENDERTARGET = 6;
  26792. /**
  26793. * Texture data comes from a cube data file
  26794. */
  26795. InternalTexture.DATASOURCE_CUBE = 7;
  26796. /**
  26797. * Texture data comes from a raw cube data
  26798. */
  26799. InternalTexture.DATASOURCE_CUBERAW = 8;
  26800. /**
  26801. * Texture data come from a prefiltered cube data file
  26802. */
  26803. InternalTexture.DATASOURCE_CUBEPREFILTERED = 9;
  26804. /**
  26805. * Texture content is raw 3D data
  26806. */
  26807. InternalTexture.DATASOURCE_RAW3D = 10;
  26808. /**
  26809. * Texture content is a depth texture
  26810. */
  26811. InternalTexture.DATASOURCE_DEPTHTEXTURE = 11;
  26812. return InternalTexture;
  26813. }());
  26814. BABYLON.InternalTexture = InternalTexture;
  26815. })(BABYLON || (BABYLON = {}));
  26816. //# sourceMappingURL=babylon.internalTexture.js.map
  26817. "use strict";
  26818. var BABYLON;
  26819. (function (BABYLON) {
  26820. var BaseTexture = /** @class */ (function () {
  26821. function BaseTexture(scene) {
  26822. this._hasAlpha = false;
  26823. this.getAlphaFromRGB = false;
  26824. this.level = 1;
  26825. this.coordinatesIndex = 0;
  26826. this._coordinatesMode = BABYLON.Texture.EXPLICIT_MODE;
  26827. /**
  26828. * | Value | Type | Description |
  26829. * | ----- | ------------------ | ----------- |
  26830. * | 0 | CLAMP_ADDRESSMODE | |
  26831. * | 1 | WRAP_ADDRESSMODE | |
  26832. * | 2 | MIRROR_ADDRESSMODE | |
  26833. */
  26834. this.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  26835. /**
  26836. * | Value | Type | Description |
  26837. * | ----- | ------------------ | ----------- |
  26838. * | 0 | CLAMP_ADDRESSMODE | |
  26839. * | 1 | WRAP_ADDRESSMODE | |
  26840. * | 2 | MIRROR_ADDRESSMODE | |
  26841. */
  26842. this.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  26843. /**
  26844. * | Value | Type | Description |
  26845. * | ----- | ------------------ | ----------- |
  26846. * | 0 | CLAMP_ADDRESSMODE | |
  26847. * | 1 | WRAP_ADDRESSMODE | |
  26848. * | 2 | MIRROR_ADDRESSMODE | |
  26849. */
  26850. this.wrapR = BABYLON.Texture.WRAP_ADDRESSMODE;
  26851. this.anisotropicFilteringLevel = BaseTexture.DEFAULT_ANISOTROPIC_FILTERING_LEVEL;
  26852. this.isCube = false;
  26853. this.is3D = false;
  26854. this.gammaSpace = true;
  26855. this.invertZ = false;
  26856. this.lodLevelInAlpha = false;
  26857. this.lodGenerationOffset = 0.0;
  26858. this.lodGenerationScale = 0.8;
  26859. this.isRenderTarget = false;
  26860. this.animations = new Array();
  26861. /**
  26862. * An event triggered when the texture is disposed.
  26863. */
  26864. this.onDisposeObservable = new BABYLON.Observable();
  26865. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  26866. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  26867. if (this._scene) {
  26868. this._scene.textures.push(this);
  26869. }
  26870. this._uid = null;
  26871. }
  26872. Object.defineProperty(BaseTexture.prototype, "hasAlpha", {
  26873. get: function () {
  26874. return this._hasAlpha;
  26875. },
  26876. set: function (value) {
  26877. if (this._hasAlpha === value) {
  26878. return;
  26879. }
  26880. this._hasAlpha = value;
  26881. if (this._scene) {
  26882. this._scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag | BABYLON.Material.MiscDirtyFlag);
  26883. }
  26884. },
  26885. enumerable: true,
  26886. configurable: true
  26887. });
  26888. Object.defineProperty(BaseTexture.prototype, "coordinatesMode", {
  26889. get: function () {
  26890. return this._coordinatesMode;
  26891. },
  26892. /**
  26893. * How a texture is mapped.
  26894. *
  26895. * | Value | Type | Description |
  26896. * | ----- | ----------------------------------- | ----------- |
  26897. * | 0 | EXPLICIT_MODE | |
  26898. * | 1 | SPHERICAL_MODE | |
  26899. * | 2 | PLANAR_MODE | |
  26900. * | 3 | CUBIC_MODE | |
  26901. * | 4 | PROJECTION_MODE | |
  26902. * | 5 | SKYBOX_MODE | |
  26903. * | 6 | INVCUBIC_MODE | |
  26904. * | 7 | EQUIRECTANGULAR_MODE | |
  26905. * | 8 | FIXED_EQUIRECTANGULAR_MODE | |
  26906. * | 9 | FIXED_EQUIRECTANGULAR_MIRRORED_MODE | |
  26907. */
  26908. set: function (value) {
  26909. if (this._coordinatesMode === value) {
  26910. return;
  26911. }
  26912. this._coordinatesMode = value;
  26913. if (this._scene) {
  26914. this._scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  26915. }
  26916. },
  26917. enumerable: true,
  26918. configurable: true
  26919. });
  26920. Object.defineProperty(BaseTexture.prototype, "uid", {
  26921. get: function () {
  26922. if (!this._uid) {
  26923. this._uid = BABYLON.Tools.RandomId();
  26924. }
  26925. return this._uid;
  26926. },
  26927. enumerable: true,
  26928. configurable: true
  26929. });
  26930. BaseTexture.prototype.toString = function () {
  26931. return this.name;
  26932. };
  26933. BaseTexture.prototype.getClassName = function () {
  26934. return "BaseTexture";
  26935. };
  26936. Object.defineProperty(BaseTexture.prototype, "onDispose", {
  26937. set: function (callback) {
  26938. if (this._onDisposeObserver) {
  26939. this.onDisposeObservable.remove(this._onDisposeObserver);
  26940. }
  26941. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  26942. },
  26943. enumerable: true,
  26944. configurable: true
  26945. });
  26946. Object.defineProperty(BaseTexture.prototype, "isBlocking", {
  26947. get: function () {
  26948. return true;
  26949. },
  26950. enumerable: true,
  26951. configurable: true
  26952. });
  26953. BaseTexture.prototype.getScene = function () {
  26954. return this._scene;
  26955. };
  26956. BaseTexture.prototype.getTextureMatrix = function () {
  26957. return BABYLON.Matrix.IdentityReadOnly;
  26958. };
  26959. BaseTexture.prototype.getReflectionTextureMatrix = function () {
  26960. return BABYLON.Matrix.IdentityReadOnly;
  26961. };
  26962. BaseTexture.prototype.getInternalTexture = function () {
  26963. return this._texture;
  26964. };
  26965. BaseTexture.prototype.isReadyOrNotBlocking = function () {
  26966. return !this.isBlocking || this.isReady();
  26967. };
  26968. BaseTexture.prototype.isReady = function () {
  26969. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  26970. this.delayLoad();
  26971. return false;
  26972. }
  26973. if (this._texture) {
  26974. return this._texture.isReady;
  26975. }
  26976. return false;
  26977. };
  26978. BaseTexture.prototype.getSize = function () {
  26979. if (this._texture && this._texture.width) {
  26980. return new BABYLON.Size(this._texture.width, this._texture.height);
  26981. }
  26982. if (this._texture && this._texture._size) {
  26983. return new BABYLON.Size(this._texture._size, this._texture._size);
  26984. }
  26985. return BABYLON.Size.Zero();
  26986. };
  26987. BaseTexture.prototype.getBaseSize = function () {
  26988. if (!this.isReady() || !this._texture)
  26989. return BABYLON.Size.Zero();
  26990. if (this._texture._size) {
  26991. return new BABYLON.Size(this._texture._size, this._texture._size);
  26992. }
  26993. return new BABYLON.Size(this._texture.baseWidth, this._texture.baseHeight);
  26994. };
  26995. BaseTexture.prototype.scale = function (ratio) {
  26996. };
  26997. Object.defineProperty(BaseTexture.prototype, "canRescale", {
  26998. get: function () {
  26999. return false;
  27000. },
  27001. enumerable: true,
  27002. configurable: true
  27003. });
  27004. BaseTexture.prototype._getFromCache = function (url, noMipmap, sampling) {
  27005. if (!this._scene) {
  27006. return null;
  27007. }
  27008. var texturesCache = this._scene.getEngine().getLoadedTexturesCache();
  27009. for (var index = 0; index < texturesCache.length; index++) {
  27010. var texturesCacheEntry = texturesCache[index];
  27011. if (texturesCacheEntry.url === url && texturesCacheEntry.generateMipMaps === !noMipmap) {
  27012. if (!sampling || sampling === texturesCacheEntry.samplingMode) {
  27013. texturesCacheEntry.incrementReferences();
  27014. return texturesCacheEntry;
  27015. }
  27016. }
  27017. }
  27018. return null;
  27019. };
  27020. BaseTexture.prototype._rebuild = function () {
  27021. };
  27022. BaseTexture.prototype.delayLoad = function () {
  27023. };
  27024. BaseTexture.prototype.clone = function () {
  27025. return null;
  27026. };
  27027. Object.defineProperty(BaseTexture.prototype, "textureType", {
  27028. get: function () {
  27029. if (!this._texture) {
  27030. return BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  27031. }
  27032. return (this._texture.type !== undefined) ? this._texture.type : BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  27033. },
  27034. enumerable: true,
  27035. configurable: true
  27036. });
  27037. Object.defineProperty(BaseTexture.prototype, "textureFormat", {
  27038. get: function () {
  27039. if (!this._texture) {
  27040. return BABYLON.Engine.TEXTUREFORMAT_RGBA;
  27041. }
  27042. return (this._texture.format !== undefined) ? this._texture.format : BABYLON.Engine.TEXTUREFORMAT_RGBA;
  27043. },
  27044. enumerable: true,
  27045. configurable: true
  27046. });
  27047. BaseTexture.prototype.readPixels = function (faceIndex) {
  27048. if (faceIndex === void 0) { faceIndex = 0; }
  27049. if (!this._texture) {
  27050. return null;
  27051. }
  27052. var size = this.getSize();
  27053. var scene = this.getScene();
  27054. if (!scene) {
  27055. return null;
  27056. }
  27057. var engine = scene.getEngine();
  27058. if (this._texture.isCube) {
  27059. return engine._readTexturePixels(this._texture, size.width, size.height, faceIndex);
  27060. }
  27061. return engine._readTexturePixels(this._texture, size.width, size.height, -1);
  27062. };
  27063. BaseTexture.prototype.releaseInternalTexture = function () {
  27064. if (this._texture) {
  27065. this._texture.dispose();
  27066. this._texture = null;
  27067. }
  27068. };
  27069. Object.defineProperty(BaseTexture.prototype, "sphericalPolynomial", {
  27070. get: function () {
  27071. if (!this._texture || !BABYLON.CubeMapToSphericalPolynomialTools || !this.isReady()) {
  27072. return null;
  27073. }
  27074. if (!this._texture._sphericalPolynomial) {
  27075. this._texture._sphericalPolynomial =
  27076. BABYLON.CubeMapToSphericalPolynomialTools.ConvertCubeMapTextureToSphericalPolynomial(this);
  27077. }
  27078. return this._texture._sphericalPolynomial;
  27079. },
  27080. set: function (value) {
  27081. if (this._texture) {
  27082. this._texture._sphericalPolynomial = value;
  27083. }
  27084. },
  27085. enumerable: true,
  27086. configurable: true
  27087. });
  27088. Object.defineProperty(BaseTexture.prototype, "_lodTextureHigh", {
  27089. get: function () {
  27090. if (this._texture) {
  27091. return this._texture._lodTextureHigh;
  27092. }
  27093. return null;
  27094. },
  27095. enumerable: true,
  27096. configurable: true
  27097. });
  27098. Object.defineProperty(BaseTexture.prototype, "_lodTextureMid", {
  27099. get: function () {
  27100. if (this._texture) {
  27101. return this._texture._lodTextureMid;
  27102. }
  27103. return null;
  27104. },
  27105. enumerable: true,
  27106. configurable: true
  27107. });
  27108. Object.defineProperty(BaseTexture.prototype, "_lodTextureLow", {
  27109. get: function () {
  27110. if (this._texture) {
  27111. return this._texture._lodTextureLow;
  27112. }
  27113. return null;
  27114. },
  27115. enumerable: true,
  27116. configurable: true
  27117. });
  27118. BaseTexture.prototype.dispose = function () {
  27119. if (!this._scene) {
  27120. return;
  27121. }
  27122. // Animations
  27123. this._scene.stopAnimation(this);
  27124. // Remove from scene
  27125. this._scene._removePendingData(this);
  27126. var index = this._scene.textures.indexOf(this);
  27127. if (index >= 0) {
  27128. this._scene.textures.splice(index, 1);
  27129. }
  27130. if (this._texture === undefined) {
  27131. return;
  27132. }
  27133. // Release
  27134. this.releaseInternalTexture();
  27135. // Callback
  27136. this.onDisposeObservable.notifyObservers(this);
  27137. this.onDisposeObservable.clear();
  27138. };
  27139. BaseTexture.prototype.serialize = function () {
  27140. if (!this.name) {
  27141. return null;
  27142. }
  27143. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  27144. // Animations
  27145. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  27146. return serializationObject;
  27147. };
  27148. BaseTexture.WhenAllReady = function (textures, callback) {
  27149. var numRemaining = textures.length;
  27150. if (numRemaining === 0) {
  27151. callback();
  27152. return;
  27153. }
  27154. var _loop_1 = function () {
  27155. texture = textures[i];
  27156. if (texture.isReady()) {
  27157. if (--numRemaining === 0) {
  27158. callback();
  27159. }
  27160. }
  27161. else {
  27162. onLoadObservable = texture.onLoadObservable;
  27163. var onLoadCallback_1 = function () {
  27164. onLoadObservable.removeCallback(onLoadCallback_1);
  27165. if (--numRemaining === 0) {
  27166. callback();
  27167. }
  27168. };
  27169. onLoadObservable.add(onLoadCallback_1);
  27170. }
  27171. };
  27172. var texture, onLoadObservable;
  27173. for (var i = 0; i < textures.length; i++) {
  27174. _loop_1();
  27175. }
  27176. };
  27177. BaseTexture.DEFAULT_ANISOTROPIC_FILTERING_LEVEL = 4;
  27178. __decorate([
  27179. BABYLON.serialize()
  27180. ], BaseTexture.prototype, "name", void 0);
  27181. __decorate([
  27182. BABYLON.serialize("hasAlpha")
  27183. ], BaseTexture.prototype, "_hasAlpha", void 0);
  27184. __decorate([
  27185. BABYLON.serialize()
  27186. ], BaseTexture.prototype, "getAlphaFromRGB", void 0);
  27187. __decorate([
  27188. BABYLON.serialize()
  27189. ], BaseTexture.prototype, "level", void 0);
  27190. __decorate([
  27191. BABYLON.serialize()
  27192. ], BaseTexture.prototype, "coordinatesIndex", void 0);
  27193. __decorate([
  27194. BABYLON.serialize("coordinatesMode")
  27195. ], BaseTexture.prototype, "_coordinatesMode", void 0);
  27196. __decorate([
  27197. BABYLON.serialize()
  27198. ], BaseTexture.prototype, "wrapU", void 0);
  27199. __decorate([
  27200. BABYLON.serialize()
  27201. ], BaseTexture.prototype, "wrapV", void 0);
  27202. __decorate([
  27203. BABYLON.serialize()
  27204. ], BaseTexture.prototype, "wrapR", void 0);
  27205. __decorate([
  27206. BABYLON.serialize()
  27207. ], BaseTexture.prototype, "anisotropicFilteringLevel", void 0);
  27208. __decorate([
  27209. BABYLON.serialize()
  27210. ], BaseTexture.prototype, "isCube", void 0);
  27211. __decorate([
  27212. BABYLON.serialize()
  27213. ], BaseTexture.prototype, "is3D", void 0);
  27214. __decorate([
  27215. BABYLON.serialize()
  27216. ], BaseTexture.prototype, "gammaSpace", void 0);
  27217. __decorate([
  27218. BABYLON.serialize()
  27219. ], BaseTexture.prototype, "invertZ", void 0);
  27220. __decorate([
  27221. BABYLON.serialize()
  27222. ], BaseTexture.prototype, "lodLevelInAlpha", void 0);
  27223. __decorate([
  27224. BABYLON.serialize()
  27225. ], BaseTexture.prototype, "lodGenerationOffset", void 0);
  27226. __decorate([
  27227. BABYLON.serialize()
  27228. ], BaseTexture.prototype, "lodGenerationScale", void 0);
  27229. __decorate([
  27230. BABYLON.serialize()
  27231. ], BaseTexture.prototype, "isRenderTarget", void 0);
  27232. return BaseTexture;
  27233. }());
  27234. BABYLON.BaseTexture = BaseTexture;
  27235. })(BABYLON || (BABYLON = {}));
  27236. //# sourceMappingURL=babylon.baseTexture.js.map
  27237. "use strict";
  27238. var BABYLON;
  27239. (function (BABYLON) {
  27240. var Texture = /** @class */ (function (_super) {
  27241. __extends(Texture, _super);
  27242. function Texture(url, scene, noMipmap, invertY, samplingMode, onLoad, onError, buffer, deleteBuffer, format) {
  27243. if (noMipmap === void 0) { noMipmap = false; }
  27244. if (invertY === void 0) { invertY = true; }
  27245. if (samplingMode === void 0) { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; }
  27246. if (onLoad === void 0) { onLoad = null; }
  27247. if (onError === void 0) { onError = null; }
  27248. if (buffer === void 0) { buffer = null; }
  27249. if (deleteBuffer === void 0) { deleteBuffer = false; }
  27250. var _this = _super.call(this, scene) || this;
  27251. _this.uOffset = 0;
  27252. _this.vOffset = 0;
  27253. _this.uScale = 1.0;
  27254. _this.vScale = 1.0;
  27255. _this.uAng = 0;
  27256. _this.vAng = 0;
  27257. _this.wAng = 0;
  27258. _this._isBlocking = true;
  27259. _this.name = url || "";
  27260. _this.url = url;
  27261. _this._noMipmap = noMipmap;
  27262. _this._invertY = invertY;
  27263. _this._samplingMode = samplingMode;
  27264. _this._buffer = buffer;
  27265. _this._deleteBuffer = deleteBuffer;
  27266. if (format) {
  27267. _this._format = format;
  27268. }
  27269. scene = _this.getScene();
  27270. if (!scene) {
  27271. return _this;
  27272. }
  27273. scene.getEngine().onBeforeTextureInitObservable.notifyObservers(_this);
  27274. var load = function () {
  27275. if (_this._onLoadObservable && _this._onLoadObservable.hasObservers()) {
  27276. _this.onLoadObservable.notifyObservers(_this);
  27277. }
  27278. if (onLoad) {
  27279. onLoad();
  27280. }
  27281. if (!_this.isBlocking && scene) {
  27282. scene.resetCachedMaterial();
  27283. }
  27284. };
  27285. if (!_this.url) {
  27286. _this._delayedOnLoad = load;
  27287. _this._delayedOnError = onError;
  27288. return _this;
  27289. }
  27290. _this._texture = _this._getFromCache(_this.url, noMipmap, samplingMode);
  27291. if (!_this._texture) {
  27292. if (!scene.useDelayedTextureLoading) {
  27293. _this._texture = scene.getEngine().createTexture(_this.url, noMipmap, invertY, scene, _this._samplingMode, load, onError, _this._buffer, undefined, _this._format);
  27294. if (deleteBuffer) {
  27295. delete _this._buffer;
  27296. }
  27297. }
  27298. else {
  27299. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  27300. _this._delayedOnLoad = load;
  27301. _this._delayedOnError = onError;
  27302. }
  27303. }
  27304. else {
  27305. if (_this._texture.isReady) {
  27306. BABYLON.Tools.SetImmediate(function () { return load(); });
  27307. }
  27308. else {
  27309. _this._texture.onLoadedObservable.add(load);
  27310. }
  27311. }
  27312. return _this;
  27313. }
  27314. Object.defineProperty(Texture.prototype, "noMipmap", {
  27315. get: function () {
  27316. return this._noMipmap;
  27317. },
  27318. enumerable: true,
  27319. configurable: true
  27320. });
  27321. Object.defineProperty(Texture.prototype, "isBlocking", {
  27322. get: function () {
  27323. return this._isBlocking;
  27324. },
  27325. set: function (value) {
  27326. this._isBlocking = value;
  27327. },
  27328. enumerable: true,
  27329. configurable: true
  27330. });
  27331. Object.defineProperty(Texture.prototype, "samplingMode", {
  27332. get: function () {
  27333. return this._samplingMode;
  27334. },
  27335. enumerable: true,
  27336. configurable: true
  27337. });
  27338. Texture.prototype.updateURL = function (url) {
  27339. this.url = url;
  27340. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  27341. this.delayLoad();
  27342. };
  27343. Texture.prototype.delayLoad = function () {
  27344. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  27345. return;
  27346. }
  27347. var scene = this.getScene();
  27348. if (!scene) {
  27349. return;
  27350. }
  27351. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  27352. this._texture = this._getFromCache(this.url, this._noMipmap, this._samplingMode);
  27353. if (!this._texture) {
  27354. this._texture = scene.getEngine().createTexture(this.url, this._noMipmap, this._invertY, scene, this._samplingMode, this._delayedOnLoad, this._delayedOnError, this._buffer, null, this._format);
  27355. if (this._deleteBuffer) {
  27356. delete this._buffer;
  27357. }
  27358. }
  27359. else {
  27360. if (this._delayedOnLoad) {
  27361. if (this._texture.isReady) {
  27362. BABYLON.Tools.SetImmediate(this._delayedOnLoad);
  27363. }
  27364. else {
  27365. this._texture.onLoadedObservable.add(this._delayedOnLoad);
  27366. }
  27367. }
  27368. }
  27369. this._delayedOnLoad = null;
  27370. this._delayedOnError = null;
  27371. };
  27372. Texture.prototype.updateSamplingMode = function (samplingMode) {
  27373. if (!this._texture) {
  27374. return;
  27375. }
  27376. var scene = this.getScene();
  27377. if (!scene) {
  27378. return;
  27379. }
  27380. this._samplingMode = samplingMode;
  27381. scene.getEngine().updateTextureSamplingMode(samplingMode, this._texture);
  27382. };
  27383. Texture.prototype._prepareRowForTextureGeneration = function (x, y, z, t) {
  27384. x *= this.uScale;
  27385. y *= this.vScale;
  27386. x -= 0.5 * this.uScale;
  27387. y -= 0.5 * this.vScale;
  27388. z -= 0.5;
  27389. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, y, z, this._rowGenerationMatrix, t);
  27390. t.x += 0.5 * this.uScale + this.uOffset;
  27391. t.y += 0.5 * this.vScale + this.vOffset;
  27392. t.z += 0.5;
  27393. };
  27394. Texture.prototype.getTextureMatrix = function () {
  27395. var _this = this;
  27396. if (this.uOffset === this._cachedUOffset &&
  27397. this.vOffset === this._cachedVOffset &&
  27398. this.uScale === this._cachedUScale &&
  27399. this.vScale === this._cachedVScale &&
  27400. this.uAng === this._cachedUAng &&
  27401. this.vAng === this._cachedVAng &&
  27402. this.wAng === this._cachedWAng) {
  27403. return this._cachedTextureMatrix;
  27404. }
  27405. this._cachedUOffset = this.uOffset;
  27406. this._cachedVOffset = this.vOffset;
  27407. this._cachedUScale = this.uScale;
  27408. this._cachedVScale = this.vScale;
  27409. this._cachedUAng = this.uAng;
  27410. this._cachedVAng = this.vAng;
  27411. this._cachedWAng = this.wAng;
  27412. if (!this._cachedTextureMatrix) {
  27413. this._cachedTextureMatrix = BABYLON.Matrix.Zero();
  27414. this._rowGenerationMatrix = new BABYLON.Matrix();
  27415. this._t0 = BABYLON.Vector3.Zero();
  27416. this._t1 = BABYLON.Vector3.Zero();
  27417. this._t2 = BABYLON.Vector3.Zero();
  27418. }
  27419. BABYLON.Matrix.RotationYawPitchRollToRef(this.vAng, this.uAng, this.wAng, this._rowGenerationMatrix);
  27420. this._prepareRowForTextureGeneration(0, 0, 0, this._t0);
  27421. this._prepareRowForTextureGeneration(1.0, 0, 0, this._t1);
  27422. this._prepareRowForTextureGeneration(0, 1.0, 0, this._t2);
  27423. this._t1.subtractInPlace(this._t0);
  27424. this._t2.subtractInPlace(this._t0);
  27425. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  27426. this._cachedTextureMatrix.m[0] = this._t1.x;
  27427. this._cachedTextureMatrix.m[1] = this._t1.y;
  27428. this._cachedTextureMatrix.m[2] = this._t1.z;
  27429. this._cachedTextureMatrix.m[4] = this._t2.x;
  27430. this._cachedTextureMatrix.m[5] = this._t2.y;
  27431. this._cachedTextureMatrix.m[6] = this._t2.z;
  27432. this._cachedTextureMatrix.m[8] = this._t0.x;
  27433. this._cachedTextureMatrix.m[9] = this._t0.y;
  27434. this._cachedTextureMatrix.m[10] = this._t0.z;
  27435. var scene = this.getScene();
  27436. if (!scene) {
  27437. return this._cachedTextureMatrix;
  27438. }
  27439. scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag, function (mat) {
  27440. return mat.hasTexture(_this);
  27441. });
  27442. return this._cachedTextureMatrix;
  27443. };
  27444. Texture.prototype.getReflectionTextureMatrix = function () {
  27445. var _this = this;
  27446. var scene = this.getScene();
  27447. if (!scene) {
  27448. return this._cachedTextureMatrix;
  27449. }
  27450. if (this.uOffset === this._cachedUOffset &&
  27451. this.vOffset === this._cachedVOffset &&
  27452. this.uScale === this._cachedUScale &&
  27453. this.vScale === this._cachedVScale &&
  27454. this.coordinatesMode === this._cachedCoordinatesMode) {
  27455. if (this.coordinatesMode === Texture.PROJECTION_MODE) {
  27456. if (this._cachedProjectionMatrixId === scene.getProjectionMatrix().updateFlag) {
  27457. return this._cachedTextureMatrix;
  27458. }
  27459. }
  27460. else {
  27461. return this._cachedTextureMatrix;
  27462. }
  27463. }
  27464. if (!this._cachedTextureMatrix) {
  27465. this._cachedTextureMatrix = BABYLON.Matrix.Zero();
  27466. }
  27467. if (!this._projectionModeMatrix) {
  27468. this._projectionModeMatrix = BABYLON.Matrix.Zero();
  27469. }
  27470. this._cachedUOffset = this.uOffset;
  27471. this._cachedVOffset = this.vOffset;
  27472. this._cachedUScale = this.uScale;
  27473. this._cachedVScale = this.vScale;
  27474. this._cachedCoordinatesMode = this.coordinatesMode;
  27475. switch (this.coordinatesMode) {
  27476. case Texture.PLANAR_MODE:
  27477. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  27478. this._cachedTextureMatrix[0] = this.uScale;
  27479. this._cachedTextureMatrix[5] = this.vScale;
  27480. this._cachedTextureMatrix[12] = this.uOffset;
  27481. this._cachedTextureMatrix[13] = this.vOffset;
  27482. break;
  27483. case Texture.PROJECTION_MODE:
  27484. BABYLON.Matrix.IdentityToRef(this._projectionModeMatrix);
  27485. this._projectionModeMatrix.m[0] = 0.5;
  27486. this._projectionModeMatrix.m[5] = -0.5;
  27487. this._projectionModeMatrix.m[10] = 0.0;
  27488. this._projectionModeMatrix.m[12] = 0.5;
  27489. this._projectionModeMatrix.m[13] = 0.5;
  27490. this._projectionModeMatrix.m[14] = 1.0;
  27491. this._projectionModeMatrix.m[15] = 1.0;
  27492. var projectionMatrix = scene.getProjectionMatrix();
  27493. this._cachedProjectionMatrixId = projectionMatrix.updateFlag;
  27494. projectionMatrix.multiplyToRef(this._projectionModeMatrix, this._cachedTextureMatrix);
  27495. break;
  27496. default:
  27497. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  27498. break;
  27499. }
  27500. scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag, function (mat) {
  27501. return (mat.getActiveTextures().indexOf(_this) !== -1);
  27502. });
  27503. return this._cachedTextureMatrix;
  27504. };
  27505. Texture.prototype.clone = function () {
  27506. var _this = this;
  27507. return BABYLON.SerializationHelper.Clone(function () {
  27508. return new Texture(_this._texture ? _this._texture.url : null, _this.getScene(), _this._noMipmap, _this._invertY, _this._samplingMode);
  27509. }, this);
  27510. };
  27511. Object.defineProperty(Texture.prototype, "onLoadObservable", {
  27512. get: function () {
  27513. if (!this._onLoadObservable) {
  27514. this._onLoadObservable = new BABYLON.Observable();
  27515. }
  27516. return this._onLoadObservable;
  27517. },
  27518. enumerable: true,
  27519. configurable: true
  27520. });
  27521. Texture.prototype.serialize = function () {
  27522. var serializationObject = _super.prototype.serialize.call(this);
  27523. if (typeof this._buffer === "string" && this._buffer.substr(0, 5) === "data:") {
  27524. serializationObject.base64String = this._buffer;
  27525. serializationObject.name = serializationObject.name.replace("data:", "");
  27526. }
  27527. return serializationObject;
  27528. };
  27529. Texture.prototype.getClassName = function () {
  27530. return "Texture";
  27531. };
  27532. Texture.prototype.dispose = function () {
  27533. _super.prototype.dispose.call(this);
  27534. if (this.onLoadObservable) {
  27535. this.onLoadObservable.clear();
  27536. this._onLoadObservable = null;
  27537. }
  27538. this._delayedOnLoad = null;
  27539. this._delayedOnError = null;
  27540. };
  27541. // Statics
  27542. Texture.CreateFromBase64String = function (data, name, scene, noMipmap, invertY, samplingMode, onLoad, onError, format) {
  27543. if (samplingMode === void 0) { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; }
  27544. if (onLoad === void 0) { onLoad = null; }
  27545. if (onError === void 0) { onError = null; }
  27546. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  27547. return new Texture("data:" + name, scene, noMipmap, invertY, samplingMode, onLoad, onError, data, false, format);
  27548. };
  27549. Texture.Parse = function (parsedTexture, scene, rootUrl) {
  27550. if (parsedTexture.customType) {
  27551. var customTexture = BABYLON.Tools.Instantiate(parsedTexture.customType);
  27552. // Update Sampling Mode
  27553. var parsedCustomTexture = customTexture.Parse(parsedTexture, scene, rootUrl);
  27554. if (parsedTexture.samplingMode && parsedCustomTexture.updateSamplingMode && parsedCustomTexture._samplingMode) {
  27555. if (parsedCustomTexture._samplingMode !== parsedTexture.samplingMode) {
  27556. parsedCustomTexture.updateSamplingMode(parsedTexture.samplingMode);
  27557. }
  27558. }
  27559. return parsedCustomTexture;
  27560. }
  27561. if (parsedTexture.isCube) {
  27562. return BABYLON.CubeTexture.Parse(parsedTexture, scene, rootUrl);
  27563. }
  27564. if (!parsedTexture.name && !parsedTexture.isRenderTarget) {
  27565. return null;
  27566. }
  27567. var texture = BABYLON.SerializationHelper.Parse(function () {
  27568. var generateMipMaps = true;
  27569. if (parsedTexture.noMipmap) {
  27570. generateMipMaps = false;
  27571. }
  27572. if (parsedTexture.mirrorPlane) {
  27573. var mirrorTexture = new BABYLON.MirrorTexture(parsedTexture.name, parsedTexture.renderTargetSize, scene, generateMipMaps);
  27574. mirrorTexture._waitingRenderList = parsedTexture.renderList;
  27575. mirrorTexture.mirrorPlane = BABYLON.Plane.FromArray(parsedTexture.mirrorPlane);
  27576. return mirrorTexture;
  27577. }
  27578. else if (parsedTexture.isRenderTarget) {
  27579. var renderTargetTexture = new BABYLON.RenderTargetTexture(parsedTexture.name, parsedTexture.renderTargetSize, scene, generateMipMaps);
  27580. renderTargetTexture._waitingRenderList = parsedTexture.renderList;
  27581. return renderTargetTexture;
  27582. }
  27583. else {
  27584. var texture;
  27585. if (parsedTexture.base64String) {
  27586. texture = Texture.CreateFromBase64String(parsedTexture.base64String, parsedTexture.name, scene, !generateMipMaps);
  27587. }
  27588. else {
  27589. var url = rootUrl + parsedTexture.name;
  27590. if (Texture.UseSerializedUrlIfAny && parsedTexture.url) {
  27591. url = parsedTexture.url;
  27592. }
  27593. texture = new Texture(url, scene, !generateMipMaps);
  27594. }
  27595. return texture;
  27596. }
  27597. }, parsedTexture, scene);
  27598. // Update Sampling Mode
  27599. if (parsedTexture.samplingMode) {
  27600. var sampling = parsedTexture.samplingMode;
  27601. if (texture._samplingMode !== sampling) {
  27602. texture.updateSamplingMode(sampling);
  27603. }
  27604. }
  27605. // Animations
  27606. if (parsedTexture.animations) {
  27607. for (var animationIndex = 0; animationIndex < parsedTexture.animations.length; animationIndex++) {
  27608. var parsedAnimation = parsedTexture.animations[animationIndex];
  27609. texture.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  27610. }
  27611. }
  27612. return texture;
  27613. };
  27614. Texture.LoadFromDataString = function (name, buffer, scene, deleteBuffer, noMipmap, invertY, samplingMode, onLoad, onError, format) {
  27615. if (deleteBuffer === void 0) { deleteBuffer = false; }
  27616. if (noMipmap === void 0) { noMipmap = false; }
  27617. if (invertY === void 0) { invertY = true; }
  27618. if (samplingMode === void 0) { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; }
  27619. if (onLoad === void 0) { onLoad = null; }
  27620. if (onError === void 0) { onError = null; }
  27621. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  27622. if (name.substr(0, 5) !== "data:") {
  27623. name = "data:" + name;
  27624. }
  27625. return new Texture(name, scene, noMipmap, invertY, samplingMode, onLoad, onError, buffer, deleteBuffer, format);
  27626. };
  27627. // Constants
  27628. Texture.NEAREST_SAMPLINGMODE = 1;
  27629. Texture.NEAREST_NEAREST_MIPLINEAR = 1; // nearest is mag = nearest and min = nearest and mip = linear
  27630. Texture.BILINEAR_SAMPLINGMODE = 2;
  27631. Texture.LINEAR_LINEAR_MIPNEAREST = 2; // Bilinear is mag = linear and min = linear and mip = nearest
  27632. Texture.TRILINEAR_SAMPLINGMODE = 3;
  27633. Texture.LINEAR_LINEAR_MIPLINEAR = 3; // Trilinear is mag = linear and min = linear and mip = linear
  27634. Texture.NEAREST_NEAREST_MIPNEAREST = 4;
  27635. Texture.NEAREST_LINEAR_MIPNEAREST = 5;
  27636. Texture.NEAREST_LINEAR_MIPLINEAR = 6;
  27637. Texture.NEAREST_LINEAR = 7;
  27638. Texture.NEAREST_NEAREST = 8;
  27639. Texture.LINEAR_NEAREST_MIPNEAREST = 9;
  27640. Texture.LINEAR_NEAREST_MIPLINEAR = 10;
  27641. Texture.LINEAR_LINEAR = 11;
  27642. Texture.LINEAR_NEAREST = 12;
  27643. Texture.EXPLICIT_MODE = 0;
  27644. Texture.SPHERICAL_MODE = 1;
  27645. Texture.PLANAR_MODE = 2;
  27646. Texture.CUBIC_MODE = 3;
  27647. Texture.PROJECTION_MODE = 4;
  27648. Texture.SKYBOX_MODE = 5;
  27649. Texture.INVCUBIC_MODE = 6;
  27650. Texture.EQUIRECTANGULAR_MODE = 7;
  27651. Texture.FIXED_EQUIRECTANGULAR_MODE = 8;
  27652. Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE = 9;
  27653. Texture.CLAMP_ADDRESSMODE = 0;
  27654. Texture.WRAP_ADDRESSMODE = 1;
  27655. Texture.MIRROR_ADDRESSMODE = 2;
  27656. /**
  27657. * 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
  27658. */
  27659. Texture.UseSerializedUrlIfAny = false;
  27660. __decorate([
  27661. BABYLON.serialize()
  27662. ], Texture.prototype, "url", void 0);
  27663. __decorate([
  27664. BABYLON.serialize()
  27665. ], Texture.prototype, "uOffset", void 0);
  27666. __decorate([
  27667. BABYLON.serialize()
  27668. ], Texture.prototype, "vOffset", void 0);
  27669. __decorate([
  27670. BABYLON.serialize()
  27671. ], Texture.prototype, "uScale", void 0);
  27672. __decorate([
  27673. BABYLON.serialize()
  27674. ], Texture.prototype, "vScale", void 0);
  27675. __decorate([
  27676. BABYLON.serialize()
  27677. ], Texture.prototype, "uAng", void 0);
  27678. __decorate([
  27679. BABYLON.serialize()
  27680. ], Texture.prototype, "vAng", void 0);
  27681. __decorate([
  27682. BABYLON.serialize()
  27683. ], Texture.prototype, "wAng", void 0);
  27684. __decorate([
  27685. BABYLON.serialize()
  27686. ], Texture.prototype, "isBlocking", null);
  27687. return Texture;
  27688. }(BABYLON.BaseTexture));
  27689. BABYLON.Texture = Texture;
  27690. })(BABYLON || (BABYLON = {}));
  27691. //# sourceMappingURL=babylon.texture.js.map
  27692. "use strict";
  27693. var BABYLON;
  27694. (function (BABYLON) {
  27695. var _InstancesBatch = /** @class */ (function () {
  27696. function _InstancesBatch() {
  27697. this.mustReturn = false;
  27698. this.visibleInstances = new Array();
  27699. this.renderSelf = new Array();
  27700. }
  27701. return _InstancesBatch;
  27702. }());
  27703. BABYLON._InstancesBatch = _InstancesBatch;
  27704. var Mesh = /** @class */ (function (_super) {
  27705. __extends(Mesh, _super);
  27706. /**
  27707. * @constructor
  27708. * @param {string} name The value used by scene.getMeshByName() to do a lookup.
  27709. * @param {Scene} scene The scene to add this mesh to.
  27710. * @param {Node} parent The parent of this mesh, if it has one
  27711. * @param {Mesh} source An optional Mesh from which geometry is shared, cloned.
  27712. * @param {boolean} doNotCloneChildren When cloning, skip cloning child meshes of source, default False.
  27713. * When false, achieved by calling a clone(), also passing False.
  27714. * This will make creation of children, recursive.
  27715. * @param {boolean} clonePhysicsImpostor When cloning, include cloning mesh physics impostor, default True.
  27716. */
  27717. function Mesh(name, scene, parent, source, doNotCloneChildren, clonePhysicsImpostor) {
  27718. if (scene === void 0) { scene = null; }
  27719. if (parent === void 0) { parent = null; }
  27720. if (source === void 0) { source = null; }
  27721. if (clonePhysicsImpostor === void 0) { clonePhysicsImpostor = true; }
  27722. var _this = _super.call(this, name, scene) || this;
  27723. // Events
  27724. /**
  27725. * An event triggered before rendering the mesh
  27726. */
  27727. _this.onBeforeRenderObservable = new BABYLON.Observable();
  27728. /**
  27729. * An event triggered after rendering the mesh
  27730. */
  27731. _this.onAfterRenderObservable = new BABYLON.Observable();
  27732. /**
  27733. * An event triggered before drawing the mesh
  27734. */
  27735. _this.onBeforeDrawObservable = new BABYLON.Observable();
  27736. // Members
  27737. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  27738. _this.instances = new Array();
  27739. _this._LODLevels = new Array();
  27740. _this._visibleInstances = {};
  27741. _this._renderIdForInstances = new Array();
  27742. _this._batchCache = new _InstancesBatch();
  27743. _this._instancesBufferSize = 32 * 16 * 4; // let's start with a maximum of 32 instances
  27744. // Use by builder only to know what orientation were the mesh build in.
  27745. _this._originalBuilderSideOrientation = Mesh._DEFAULTSIDE;
  27746. _this.overrideMaterialSideOrientation = null;
  27747. _this._areNormalsFrozen = false; // Will be used by ribbons mainly
  27748. // Will be used to save a source mesh reference, If any
  27749. _this._source = null;
  27750. scene = _this.getScene();
  27751. if (source) {
  27752. // Source mesh
  27753. _this._source = source;
  27754. // Geometry
  27755. if (source._geometry) {
  27756. source._geometry.applyToMesh(_this);
  27757. }
  27758. // Deep copy
  27759. BABYLON.Tools.DeepCopy(source, _this, ["name", "material", "skeleton", "instances", "parent", "uniqueId",
  27760. "source", "metadata", "hasLODLevels", "geometry", "isBlocked", "areNormalsFrozen"], ["_poseMatrix", "_source"]);
  27761. // Metadata
  27762. if (source.metadata && source.metadata.clone) {
  27763. _this.metadata = source.metadata.clone();
  27764. }
  27765. else {
  27766. _this.metadata = source.metadata;
  27767. }
  27768. // Tags
  27769. if (BABYLON.Tags && BABYLON.Tags.HasTags(source)) {
  27770. BABYLON.Tags.AddTagsTo(_this, BABYLON.Tags.GetTags(source, true));
  27771. }
  27772. // Parent
  27773. _this.parent = source.parent;
  27774. // Pivot
  27775. _this.setPivotMatrix(source.getPivotMatrix());
  27776. _this.id = name + "." + source.id;
  27777. // Material
  27778. _this.material = source.material;
  27779. var index;
  27780. if (!doNotCloneChildren) {
  27781. // Children
  27782. var directDescendants = source.getDescendants(true);
  27783. for (var index_1 = 0; index_1 < directDescendants.length; index_1++) {
  27784. var child = directDescendants[index_1];
  27785. if (child.clone) {
  27786. child.clone(name + "." + child.name, _this);
  27787. }
  27788. }
  27789. }
  27790. // Physics clone
  27791. var physicsEngine = _this.getScene().getPhysicsEngine();
  27792. if (clonePhysicsImpostor && physicsEngine) {
  27793. var impostor = physicsEngine.getImpostorForPhysicsObject(source);
  27794. if (impostor) {
  27795. _this.physicsImpostor = impostor.clone(_this);
  27796. }
  27797. }
  27798. // Particles
  27799. for (index = 0; index < scene.particleSystems.length; index++) {
  27800. var system = scene.particleSystems[index];
  27801. if (system.emitter === source) {
  27802. system.clone(system.name, _this);
  27803. }
  27804. }
  27805. _this.computeWorldMatrix(true);
  27806. }
  27807. // Parent
  27808. if (parent !== null) {
  27809. _this.parent = parent;
  27810. }
  27811. return _this;
  27812. }
  27813. Object.defineProperty(Mesh, "FRONTSIDE", {
  27814. /**
  27815. * Mesh side orientation : usually the external or front surface
  27816. */
  27817. get: function () {
  27818. return Mesh._FRONTSIDE;
  27819. },
  27820. enumerable: true,
  27821. configurable: true
  27822. });
  27823. Object.defineProperty(Mesh, "BACKSIDE", {
  27824. /**
  27825. * Mesh side orientation : usually the internal or back surface
  27826. */
  27827. get: function () {
  27828. return Mesh._BACKSIDE;
  27829. },
  27830. enumerable: true,
  27831. configurable: true
  27832. });
  27833. Object.defineProperty(Mesh, "DOUBLESIDE", {
  27834. /**
  27835. * Mesh side orientation : both internal and external or front and back surfaces
  27836. */
  27837. get: function () {
  27838. return Mesh._DOUBLESIDE;
  27839. },
  27840. enumerable: true,
  27841. configurable: true
  27842. });
  27843. Object.defineProperty(Mesh, "DEFAULTSIDE", {
  27844. /**
  27845. * Mesh side orientation : by default, `FRONTSIDE`
  27846. */
  27847. get: function () {
  27848. return Mesh._DEFAULTSIDE;
  27849. },
  27850. enumerable: true,
  27851. configurable: true
  27852. });
  27853. Object.defineProperty(Mesh, "NO_CAP", {
  27854. /**
  27855. * Mesh cap setting : no cap
  27856. */
  27857. get: function () {
  27858. return Mesh._NO_CAP;
  27859. },
  27860. enumerable: true,
  27861. configurable: true
  27862. });
  27863. Object.defineProperty(Mesh, "CAP_START", {
  27864. /**
  27865. * Mesh cap setting : one cap at the beginning of the mesh
  27866. */
  27867. get: function () {
  27868. return Mesh._CAP_START;
  27869. },
  27870. enumerable: true,
  27871. configurable: true
  27872. });
  27873. Object.defineProperty(Mesh, "CAP_END", {
  27874. /**
  27875. * Mesh cap setting : one cap at the end of the mesh
  27876. */
  27877. get: function () {
  27878. return Mesh._CAP_END;
  27879. },
  27880. enumerable: true,
  27881. configurable: true
  27882. });
  27883. Object.defineProperty(Mesh, "CAP_ALL", {
  27884. /**
  27885. * Mesh cap setting : two caps, one at the beginning and one at the end of the mesh
  27886. */
  27887. get: function () {
  27888. return Mesh._CAP_ALL;
  27889. },
  27890. enumerable: true,
  27891. configurable: true
  27892. });
  27893. Object.defineProperty(Mesh.prototype, "onBeforeDraw", {
  27894. set: function (callback) {
  27895. if (this._onBeforeDrawObserver) {
  27896. this.onBeforeDrawObservable.remove(this._onBeforeDrawObserver);
  27897. }
  27898. this._onBeforeDrawObserver = this.onBeforeDrawObservable.add(callback);
  27899. },
  27900. enumerable: true,
  27901. configurable: true
  27902. });
  27903. Object.defineProperty(Mesh.prototype, "morphTargetManager", {
  27904. get: function () {
  27905. return this._morphTargetManager;
  27906. },
  27907. set: function (value) {
  27908. if (this._morphTargetManager === value) {
  27909. return;
  27910. }
  27911. this._morphTargetManager = value;
  27912. this._syncGeometryWithMorphTargetManager();
  27913. },
  27914. enumerable: true,
  27915. configurable: true
  27916. });
  27917. Object.defineProperty(Mesh.prototype, "source", {
  27918. get: function () {
  27919. return this._source;
  27920. },
  27921. enumerable: true,
  27922. configurable: true
  27923. });
  27924. Object.defineProperty(Mesh.prototype, "isUnIndexed", {
  27925. get: function () {
  27926. return this._unIndexed;
  27927. },
  27928. set: function (value) {
  27929. if (this._unIndexed !== value) {
  27930. this._unIndexed = value;
  27931. this._markSubMeshesAsAttributesDirty();
  27932. }
  27933. },
  27934. enumerable: true,
  27935. configurable: true
  27936. });
  27937. // Methods
  27938. /**
  27939. * Returns the string "Mesh".
  27940. */
  27941. Mesh.prototype.getClassName = function () {
  27942. return "Mesh";
  27943. };
  27944. /**
  27945. * Returns a string.
  27946. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  27947. */
  27948. Mesh.prototype.toString = function (fullDetails) {
  27949. var ret = _super.prototype.toString.call(this, fullDetails);
  27950. ret += ", n vertices: " + this.getTotalVertices();
  27951. ret += ", parent: " + (this._waitingParentId ? this._waitingParentId : (this.parent ? this.parent.name : "NONE"));
  27952. if (this.animations) {
  27953. for (var i = 0; i < this.animations.length; i++) {
  27954. ret += ", animation[0]: " + this.animations[i].toString(fullDetails);
  27955. }
  27956. }
  27957. if (fullDetails) {
  27958. if (this._geometry) {
  27959. var ib = this.getIndices();
  27960. var vb = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  27961. if (vb && ib) {
  27962. ret += ", flat shading: " + (vb.length / 3 === ib.length ? "YES" : "NO");
  27963. }
  27964. }
  27965. else {
  27966. ret += ", flat shading: UNKNOWN";
  27967. }
  27968. }
  27969. return ret;
  27970. };
  27971. Object.defineProperty(Mesh.prototype, "hasLODLevels", {
  27972. /**
  27973. * True if the mesh has some Levels Of Details (LOD).
  27974. * Returns a boolean.
  27975. */
  27976. get: function () {
  27977. return this._LODLevels.length > 0;
  27978. },
  27979. enumerable: true,
  27980. configurable: true
  27981. });
  27982. /**
  27983. * Gets the list of {BABYLON.MeshLODLevel} associated with the current mesh
  27984. * @returns an array of {BABYLON.MeshLODLevel}
  27985. */
  27986. Mesh.prototype.getLODLevels = function () {
  27987. return this._LODLevels;
  27988. };
  27989. Mesh.prototype._sortLODLevels = function () {
  27990. this._LODLevels.sort(function (a, b) {
  27991. if (a.distance < b.distance) {
  27992. return 1;
  27993. }
  27994. if (a.distance > b.distance) {
  27995. return -1;
  27996. }
  27997. return 0;
  27998. });
  27999. };
  28000. /**
  28001. * Add a mesh as LOD level triggered at the given distance.
  28002. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_LOD
  28003. * @param {number} distance The distance from the center of the object to show this level
  28004. * @param {Mesh} mesh The mesh to be added as LOD level
  28005. * @return {Mesh} This mesh (for chaining)
  28006. */
  28007. Mesh.prototype.addLODLevel = function (distance, mesh) {
  28008. if (mesh && mesh._masterMesh) {
  28009. BABYLON.Tools.Warn("You cannot use a mesh as LOD level twice");
  28010. return this;
  28011. }
  28012. var level = new BABYLON.MeshLODLevel(distance, mesh);
  28013. this._LODLevels.push(level);
  28014. if (mesh) {
  28015. mesh._masterMesh = this;
  28016. }
  28017. this._sortLODLevels();
  28018. return this;
  28019. };
  28020. /**
  28021. * Returns the LOD level mesh at the passed distance or null if not found.
  28022. * It is related to the method `addLODLevel(distance, mesh)`.
  28023. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_LOD
  28024. * Returns an object Mesh or `null`.
  28025. */
  28026. Mesh.prototype.getLODLevelAtDistance = function (distance) {
  28027. for (var index = 0; index < this._LODLevels.length; index++) {
  28028. var level = this._LODLevels[index];
  28029. if (level.distance === distance) {
  28030. return level.mesh;
  28031. }
  28032. }
  28033. return null;
  28034. };
  28035. /**
  28036. * Remove a mesh from the LOD array
  28037. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_LOD
  28038. * @param {Mesh} mesh The mesh to be removed.
  28039. * @return {Mesh} This mesh (for chaining)
  28040. */
  28041. Mesh.prototype.removeLODLevel = function (mesh) {
  28042. for (var index = 0; index < this._LODLevels.length; index++) {
  28043. if (this._LODLevels[index].mesh === mesh) {
  28044. this._LODLevels.splice(index, 1);
  28045. if (mesh) {
  28046. mesh._masterMesh = null;
  28047. }
  28048. }
  28049. }
  28050. this._sortLODLevels();
  28051. return this;
  28052. };
  28053. /**
  28054. * Returns the registered LOD mesh distant from the parameter `camera` position if any, else returns the current mesh.
  28055. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_LOD
  28056. */
  28057. Mesh.prototype.getLOD = function (camera, boundingSphere) {
  28058. if (!this._LODLevels || this._LODLevels.length === 0) {
  28059. return this;
  28060. }
  28061. var bSphere;
  28062. if (boundingSphere) {
  28063. bSphere = boundingSphere;
  28064. }
  28065. else {
  28066. var boundingInfo = this.getBoundingInfo();
  28067. bSphere = boundingInfo.boundingSphere;
  28068. }
  28069. var distanceToCamera = bSphere.centerWorld.subtract(camera.globalPosition).length();
  28070. if (this._LODLevels[this._LODLevels.length - 1].distance > distanceToCamera) {
  28071. if (this.onLODLevelSelection) {
  28072. this.onLODLevelSelection(distanceToCamera, this, this._LODLevels[this._LODLevels.length - 1].mesh);
  28073. }
  28074. return this;
  28075. }
  28076. for (var index = 0; index < this._LODLevels.length; index++) {
  28077. var level = this._LODLevels[index];
  28078. if (level.distance < distanceToCamera) {
  28079. if (level.mesh) {
  28080. level.mesh._preActivate();
  28081. level.mesh._updateSubMeshesBoundingInfo(this.worldMatrixFromCache);
  28082. }
  28083. if (this.onLODLevelSelection) {
  28084. this.onLODLevelSelection(distanceToCamera, this, level.mesh);
  28085. }
  28086. return level.mesh;
  28087. }
  28088. }
  28089. if (this.onLODLevelSelection) {
  28090. this.onLODLevelSelection(distanceToCamera, this, this);
  28091. }
  28092. return this;
  28093. };
  28094. Object.defineProperty(Mesh.prototype, "geometry", {
  28095. /**
  28096. * Returns the mesh internal Geometry object.
  28097. */
  28098. get: function () {
  28099. return this._geometry;
  28100. },
  28101. enumerable: true,
  28102. configurable: true
  28103. });
  28104. /**
  28105. * Returns a positive integer : the total number of vertices within the mesh geometry or zero if the mesh has no geometry.
  28106. */
  28107. Mesh.prototype.getTotalVertices = function () {
  28108. if (this._geometry === null || this._geometry === undefined) {
  28109. return 0;
  28110. }
  28111. return this._geometry.getTotalVertices();
  28112. };
  28113. /**
  28114. * Returns an array of integers or floats, or a Float32Array, depending on the requested `kind` (positions, indices, normals, etc).
  28115. * 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.
  28116. * You can force the copy with forceCopy === true
  28117. * Returns null if the mesh has no geometry or no vertex buffer.
  28118. * Possible `kind` values :
  28119. * - BABYLON.VertexBuffer.PositionKind
  28120. * - BABYLON.VertexBuffer.UVKind
  28121. * - BABYLON.VertexBuffer.UV2Kind
  28122. * - BABYLON.VertexBuffer.UV3Kind
  28123. * - BABYLON.VertexBuffer.UV4Kind
  28124. * - BABYLON.VertexBuffer.UV5Kind
  28125. * - BABYLON.VertexBuffer.UV6Kind
  28126. * - BABYLON.VertexBuffer.ColorKind
  28127. * - BABYLON.VertexBuffer.MatricesIndicesKind
  28128. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  28129. * - BABYLON.VertexBuffer.MatricesWeightsKind
  28130. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  28131. */
  28132. Mesh.prototype.getVerticesData = function (kind, copyWhenShared, forceCopy) {
  28133. if (!this._geometry) {
  28134. return null;
  28135. }
  28136. return this._geometry.getVerticesData(kind, copyWhenShared, forceCopy);
  28137. };
  28138. /**
  28139. * Returns the mesh VertexBuffer object from the requested `kind` : positions, indices, normals, etc.
  28140. * Returns `null` if the mesh has no geometry.
  28141. * Possible `kind` values :
  28142. * - BABYLON.VertexBuffer.PositionKind
  28143. * - BABYLON.VertexBuffer.UVKind
  28144. * - BABYLON.VertexBuffer.UV2Kind
  28145. * - BABYLON.VertexBuffer.UV3Kind
  28146. * - BABYLON.VertexBuffer.UV4Kind
  28147. * - BABYLON.VertexBuffer.UV5Kind
  28148. * - BABYLON.VertexBuffer.UV6Kind
  28149. * - BABYLON.VertexBuffer.ColorKind
  28150. * - BABYLON.VertexBuffer.MatricesIndicesKind
  28151. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  28152. * - BABYLON.VertexBuffer.MatricesWeightsKind
  28153. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  28154. */
  28155. Mesh.prototype.getVertexBuffer = function (kind) {
  28156. if (!this._geometry) {
  28157. return null;
  28158. }
  28159. return this._geometry.getVertexBuffer(kind);
  28160. };
  28161. /**
  28162. * Returns a boolean depending on the existence of the Vertex Data for the requested `kind`.
  28163. * Possible `kind` values :
  28164. * - BABYLON.VertexBuffer.PositionKind
  28165. * - BABYLON.VertexBuffer.UVKind
  28166. * - BABYLON.VertexBuffer.UV2Kind
  28167. * - BABYLON.VertexBuffer.UV3Kind
  28168. * - BABYLON.VertexBuffer.UV4Kind
  28169. * - BABYLON.VertexBuffer.UV5Kind
  28170. * - BABYLON.VertexBuffer.UV6Kind
  28171. * - BABYLON.VertexBuffer.ColorKind
  28172. * - BABYLON.VertexBuffer.MatricesIndicesKind
  28173. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  28174. * - BABYLON.VertexBuffer.MatricesWeightsKind
  28175. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  28176. */
  28177. Mesh.prototype.isVerticesDataPresent = function (kind) {
  28178. if (!this._geometry) {
  28179. if (this._delayInfo) {
  28180. return this._delayInfo.indexOf(kind) !== -1;
  28181. }
  28182. return false;
  28183. }
  28184. return this._geometry.isVerticesDataPresent(kind);
  28185. };
  28186. /**
  28187. * Returns a boolean defining if the vertex data for the requested `kind` is updatable.
  28188. * Possible `kind` values :
  28189. * - BABYLON.VertexBuffer.PositionKind
  28190. * - BABYLON.VertexBuffer.UVKind
  28191. * - BABYLON.VertexBuffer.UV2Kind
  28192. * - BABYLON.VertexBuffer.UV3Kind
  28193. * - BABYLON.VertexBuffer.UV4Kind
  28194. * - BABYLON.VertexBuffer.UV5Kind
  28195. * - BABYLON.VertexBuffer.UV6Kind
  28196. * - BABYLON.VertexBuffer.ColorKind
  28197. * - BABYLON.VertexBuffer.MatricesIndicesKind
  28198. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  28199. * - BABYLON.VertexBuffer.MatricesWeightsKind
  28200. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  28201. */
  28202. Mesh.prototype.isVertexBufferUpdatable = function (kind) {
  28203. if (!this._geometry) {
  28204. if (this._delayInfo) {
  28205. return this._delayInfo.indexOf(kind) !== -1;
  28206. }
  28207. return false;
  28208. }
  28209. return this._geometry.isVertexBufferUpdatable(kind);
  28210. };
  28211. /**
  28212. * Returns a string : the list of existing `kinds` of Vertex Data for this mesh.
  28213. * Possible `kind` values :
  28214. * - BABYLON.VertexBuffer.PositionKind
  28215. * - BABYLON.VertexBuffer.UVKind
  28216. * - BABYLON.VertexBuffer.UV2Kind
  28217. * - BABYLON.VertexBuffer.UV3Kind
  28218. * - BABYLON.VertexBuffer.UV4Kind
  28219. * - BABYLON.VertexBuffer.UV5Kind
  28220. * - BABYLON.VertexBuffer.UV6Kind
  28221. * - BABYLON.VertexBuffer.ColorKind
  28222. * - BABYLON.VertexBuffer.MatricesIndicesKind
  28223. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  28224. * - BABYLON.VertexBuffer.MatricesWeightsKind
  28225. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  28226. */
  28227. Mesh.prototype.getVerticesDataKinds = function () {
  28228. if (!this._geometry) {
  28229. var result = new Array();
  28230. if (this._delayInfo) {
  28231. this._delayInfo.forEach(function (kind, index, array) {
  28232. result.push(kind);
  28233. });
  28234. }
  28235. return result;
  28236. }
  28237. return this._geometry.getVerticesDataKinds();
  28238. };
  28239. /**
  28240. * Returns a positive integer : the total number of indices in this mesh geometry.
  28241. * Returns zero if the mesh has no geometry.
  28242. */
  28243. Mesh.prototype.getTotalIndices = function () {
  28244. if (!this._geometry) {
  28245. return 0;
  28246. }
  28247. return this._geometry.getTotalIndices();
  28248. };
  28249. /**
  28250. * Returns an array of integers or a typed array (Int32Array, Uint32Array, Uint16Array) populated with the mesh indices.
  28251. * 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.
  28252. * Returns an empty array if the mesh has no geometry.
  28253. */
  28254. Mesh.prototype.getIndices = function (copyWhenShared) {
  28255. if (!this._geometry) {
  28256. return [];
  28257. }
  28258. return this._geometry.getIndices(copyWhenShared);
  28259. };
  28260. Object.defineProperty(Mesh.prototype, "isBlocked", {
  28261. get: function () {
  28262. return this._masterMesh !== null && this._masterMesh !== undefined;
  28263. },
  28264. enumerable: true,
  28265. configurable: true
  28266. });
  28267. /**
  28268. * Determine if the current mesh is ready to be rendered
  28269. * @param completeCheck defines if a complete check (including materials and lights) has to be done (false by default)
  28270. * @param forceInstanceSupport will check if the mesh will be ready when used with instances (false by default)
  28271. * @returns true if all associated assets are ready (material, textures, shaders)
  28272. */
  28273. Mesh.prototype.isReady = function (completeCheck, forceInstanceSupport) {
  28274. if (completeCheck === void 0) { completeCheck = false; }
  28275. if (forceInstanceSupport === void 0) { forceInstanceSupport = false; }
  28276. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  28277. return false;
  28278. }
  28279. if (!_super.prototype.isReady.call(this, completeCheck)) {
  28280. return false;
  28281. }
  28282. if (!this.subMeshes || this.subMeshes.length === 0) {
  28283. return true;
  28284. }
  28285. if (!completeCheck) {
  28286. return true;
  28287. }
  28288. var engine = this.getEngine();
  28289. var scene = this.getScene();
  28290. var hardwareInstancedRendering = forceInstanceSupport || engine.getCaps().instancedArrays && this.instances.length > 0;
  28291. this.computeWorldMatrix();
  28292. var mat = this.material || scene.defaultMaterial;
  28293. if (mat) {
  28294. if (mat.storeEffectOnSubMeshes) {
  28295. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  28296. var subMesh = _a[_i];
  28297. var effectiveMaterial = subMesh.getMaterial();
  28298. if (effectiveMaterial) {
  28299. if (!effectiveMaterial.isReadyForSubMesh(this, subMesh, hardwareInstancedRendering)) {
  28300. return false;
  28301. }
  28302. }
  28303. }
  28304. }
  28305. else {
  28306. if (!mat.isReady(this, hardwareInstancedRendering)) {
  28307. return false;
  28308. }
  28309. }
  28310. }
  28311. // Shadows
  28312. for (var _b = 0, _c = this._lightSources; _b < _c.length; _b++) {
  28313. var light = _c[_b];
  28314. var generator = light.getShadowGenerator();
  28315. if (generator) {
  28316. for (var _d = 0, _e = this.subMeshes; _d < _e.length; _d++) {
  28317. var subMesh = _e[_d];
  28318. if (!generator.isReady(subMesh, hardwareInstancedRendering)) {
  28319. return false;
  28320. }
  28321. }
  28322. }
  28323. }
  28324. // LOD
  28325. for (var _f = 0, _g = this._LODLevels; _f < _g.length; _f++) {
  28326. var lod = _g[_f];
  28327. if (lod.mesh && !lod.mesh.isReady(hardwareInstancedRendering)) {
  28328. return false;
  28329. }
  28330. }
  28331. return true;
  28332. };
  28333. Object.defineProperty(Mesh.prototype, "areNormalsFrozen", {
  28334. /**
  28335. * Boolean : true if the normals aren't to be recomputed on next mesh `positions` array update.
  28336. * This property is pertinent only for updatable parametric shapes.
  28337. */
  28338. get: function () {
  28339. return this._areNormalsFrozen;
  28340. },
  28341. enumerable: true,
  28342. configurable: true
  28343. });
  28344. /**
  28345. * This function affects parametric shapes on vertex position update only : ribbons, tubes, etc.
  28346. * It has no effect at all on other shapes.
  28347. * It prevents the mesh normals from being recomputed on next `positions` array update.
  28348. * Returns the Mesh.
  28349. */
  28350. Mesh.prototype.freezeNormals = function () {
  28351. this._areNormalsFrozen = true;
  28352. return this;
  28353. };
  28354. /**
  28355. * This function affects parametric shapes on vertex position update only : ribbons, tubes, etc.
  28356. * It has no effect at all on other shapes.
  28357. * It reactivates the mesh normals computation if it was previously frozen.
  28358. * Returns the Mesh.
  28359. */
  28360. Mesh.prototype.unfreezeNormals = function () {
  28361. this._areNormalsFrozen = false;
  28362. return this;
  28363. };
  28364. Object.defineProperty(Mesh.prototype, "overridenInstanceCount", {
  28365. /**
  28366. * Overrides instance count. Only applicable when custom instanced InterleavedVertexBuffer are used rather than InstancedMeshs
  28367. */
  28368. set: function (count) {
  28369. this._overridenInstanceCount = count;
  28370. },
  28371. enumerable: true,
  28372. configurable: true
  28373. });
  28374. // Methods
  28375. Mesh.prototype._preActivate = function () {
  28376. var sceneRenderId = this.getScene().getRenderId();
  28377. if (this._preActivateId === sceneRenderId) {
  28378. return this;
  28379. }
  28380. this._preActivateId = sceneRenderId;
  28381. this._visibleInstances = null;
  28382. return this;
  28383. };
  28384. Mesh.prototype._preActivateForIntermediateRendering = function (renderId) {
  28385. if (this._visibleInstances) {
  28386. this._visibleInstances.intermediateDefaultRenderId = renderId;
  28387. }
  28388. return this;
  28389. };
  28390. Mesh.prototype._registerInstanceForRenderId = function (instance, renderId) {
  28391. if (!this._visibleInstances) {
  28392. this._visibleInstances = {};
  28393. this._visibleInstances.defaultRenderId = renderId;
  28394. this._visibleInstances.selfDefaultRenderId = this._renderId;
  28395. }
  28396. if (!this._visibleInstances[renderId]) {
  28397. this._visibleInstances[renderId] = new Array();
  28398. }
  28399. this._visibleInstances[renderId].push(instance);
  28400. return this;
  28401. };
  28402. /**
  28403. * This method recomputes and sets a new BoundingInfo to the mesh unless it is locked.
  28404. * This means the mesh underlying bounding box and sphere are recomputed.
  28405. * Returns the Mesh.
  28406. */
  28407. Mesh.prototype.refreshBoundingInfo = function () {
  28408. return this._refreshBoundingInfo(false);
  28409. };
  28410. Mesh.prototype._refreshBoundingInfo = function (applySkeleton) {
  28411. if (this._boundingInfo && this._boundingInfo.isLocked) {
  28412. return this;
  28413. }
  28414. var data = this._getPositionData(applySkeleton);
  28415. if (data) {
  28416. var extend = BABYLON.Tools.ExtractMinAndMax(data, 0, this.getTotalVertices());
  28417. this._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  28418. }
  28419. if (this.subMeshes) {
  28420. for (var index = 0; index < this.subMeshes.length; index++) {
  28421. this.subMeshes[index].refreshBoundingInfo();
  28422. }
  28423. }
  28424. this._updateBoundingInfo();
  28425. return this;
  28426. };
  28427. Mesh.prototype._getPositionData = function (applySkeleton) {
  28428. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  28429. if (data && applySkeleton && this.skeleton) {
  28430. data = BABYLON.Tools.Slice(data);
  28431. var matricesIndicesData = this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind);
  28432. var matricesWeightsData = this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind);
  28433. if (matricesWeightsData && matricesIndicesData) {
  28434. var needExtras = this.numBoneInfluencers > 4;
  28435. var matricesIndicesExtraData = needExtras ? this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind) : null;
  28436. var matricesWeightsExtraData = needExtras ? this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind) : null;
  28437. var skeletonMatrices = this.skeleton.getTransformMatrices(this);
  28438. var tempVector = BABYLON.Tmp.Vector3[0];
  28439. var finalMatrix = BABYLON.Tmp.Matrix[0];
  28440. var tempMatrix = BABYLON.Tmp.Matrix[1];
  28441. var matWeightIdx = 0;
  28442. for (var index = 0; index < data.length; index += 3, matWeightIdx += 4) {
  28443. finalMatrix.reset();
  28444. var inf;
  28445. var weight;
  28446. for (inf = 0; inf < 4; inf++) {
  28447. weight = matricesWeightsData[matWeightIdx + inf];
  28448. if (weight <= 0)
  28449. break;
  28450. BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, Math.floor(matricesIndicesData[matWeightIdx + inf] * 16), weight, tempMatrix);
  28451. finalMatrix.addToSelf(tempMatrix);
  28452. }
  28453. if (needExtras) {
  28454. for (inf = 0; inf < 4; inf++) {
  28455. weight = matricesWeightsExtraData[matWeightIdx + inf];
  28456. if (weight <= 0)
  28457. break;
  28458. BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, Math.floor(matricesIndicesExtraData[matWeightIdx + inf] * 16), weight, tempMatrix);
  28459. finalMatrix.addToSelf(tempMatrix);
  28460. }
  28461. }
  28462. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(data[index], data[index + 1], data[index + 2], finalMatrix, tempVector);
  28463. tempVector.toArray(data, index);
  28464. }
  28465. }
  28466. }
  28467. return data;
  28468. };
  28469. Mesh.prototype._createGlobalSubMesh = function (force) {
  28470. var totalVertices = this.getTotalVertices();
  28471. if (!totalVertices || !this.getIndices()) {
  28472. return null;
  28473. }
  28474. // Check if we need to recreate the submeshes
  28475. if (this.subMeshes && this.subMeshes.length > 0) {
  28476. var ib = this.getIndices();
  28477. if (!ib) {
  28478. return null;
  28479. }
  28480. var totalIndices = ib.length;
  28481. var needToRecreate = false;
  28482. if (force) {
  28483. needToRecreate = true;
  28484. }
  28485. else {
  28486. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  28487. var submesh = _a[_i];
  28488. if (submesh.indexStart + submesh.indexCount >= totalIndices) {
  28489. needToRecreate = true;
  28490. break;
  28491. }
  28492. if (submesh.verticesStart + submesh.verticesCount >= totalVertices) {
  28493. needToRecreate = true;
  28494. break;
  28495. }
  28496. }
  28497. }
  28498. if (!needToRecreate) {
  28499. return this.subMeshes[0];
  28500. }
  28501. }
  28502. this.releaseSubMeshes();
  28503. return new BABYLON.SubMesh(0, 0, totalVertices, 0, this.getTotalIndices(), this);
  28504. };
  28505. Mesh.prototype.subdivide = function (count) {
  28506. if (count < 1) {
  28507. return;
  28508. }
  28509. var totalIndices = this.getTotalIndices();
  28510. var subdivisionSize = (totalIndices / count) | 0;
  28511. var offset = 0;
  28512. // Ensure that subdivisionSize is a multiple of 3
  28513. while (subdivisionSize % 3 !== 0) {
  28514. subdivisionSize++;
  28515. }
  28516. this.releaseSubMeshes();
  28517. for (var index = 0; index < count; index++) {
  28518. if (offset >= totalIndices) {
  28519. break;
  28520. }
  28521. BABYLON.SubMesh.CreateFromIndices(0, offset, Math.min(subdivisionSize, totalIndices - offset), this);
  28522. offset += subdivisionSize;
  28523. }
  28524. this.synchronizeInstances();
  28525. };
  28526. /**
  28527. * Sets the vertex data of the mesh geometry for the requested `kind`.
  28528. * If the mesh has no geometry, a new Geometry object is set to the mesh and then passed this vertex data.
  28529. * The `data` are either a numeric array either a Float32Array.
  28530. * The parameter `updatable` is passed as is to the underlying Geometry object constructor (if initianilly none) or updater.
  28531. * 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).
  28532. * Note that a new underlying VertexBuffer object is created each call.
  28533. * If the `kind` is the `PositionKind`, the mesh BoundingInfo is renewed, so the bounding box and sphere, and the mesh World Matrix is recomputed.
  28534. *
  28535. * Possible `kind` values :
  28536. * - BABYLON.VertexBuffer.PositionKind
  28537. * - BABYLON.VertexBuffer.UVKind
  28538. * - BABYLON.VertexBuffer.UV2Kind
  28539. * - BABYLON.VertexBuffer.UV3Kind
  28540. * - BABYLON.VertexBuffer.UV4Kind
  28541. * - BABYLON.VertexBuffer.UV5Kind
  28542. * - BABYLON.VertexBuffer.UV6Kind
  28543. * - BABYLON.VertexBuffer.ColorKind
  28544. * - BABYLON.VertexBuffer.MatricesIndicesKind
  28545. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  28546. * - BABYLON.VertexBuffer.MatricesWeightsKind
  28547. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  28548. *
  28549. * Returns the Mesh.
  28550. */
  28551. Mesh.prototype.setVerticesData = function (kind, data, updatable, stride) {
  28552. if (updatable === void 0) { updatable = false; }
  28553. if (!this._geometry) {
  28554. var vertexData = new BABYLON.VertexData();
  28555. vertexData.set(data, kind);
  28556. var scene = this.getScene();
  28557. new BABYLON.Geometry(BABYLON.Geometry.RandomId(), scene, vertexData, updatable, this);
  28558. }
  28559. else {
  28560. this._geometry.setVerticesData(kind, data, updatable, stride);
  28561. }
  28562. return this;
  28563. };
  28564. Mesh.prototype.markVerticesDataAsUpdatable = function (kind, updatable) {
  28565. if (updatable === void 0) { updatable = true; }
  28566. var vb = this.getVertexBuffer(kind);
  28567. if (!vb || vb.isUpdatable() === updatable) {
  28568. return;
  28569. }
  28570. this.setVerticesData(kind, this.getVerticesData(kind), updatable);
  28571. };
  28572. /**
  28573. * Sets the mesh VertexBuffer.
  28574. * Returns the Mesh.
  28575. */
  28576. Mesh.prototype.setVerticesBuffer = function (buffer) {
  28577. if (!this._geometry) {
  28578. this._geometry = BABYLON.Geometry.CreateGeometryForMesh(this);
  28579. }
  28580. this._geometry.setVerticesBuffer(buffer);
  28581. return this;
  28582. };
  28583. /**
  28584. * Updates the existing vertex data of the mesh geometry for the requested `kind`.
  28585. * If the mesh has no geometry, it is simply returned as it is.
  28586. * The `data` are either a numeric array either a Float32Array.
  28587. * No new underlying VertexBuffer object is created.
  28588. * 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.
  28589. * If the parameter `makeItUnique` is true, a new global geometry is created from this positions and is set to the mesh.
  28590. *
  28591. * Possible `kind` values :
  28592. * - BABYLON.VertexBuffer.PositionKind
  28593. * - BABYLON.VertexBuffer.UVKind
  28594. * - BABYLON.VertexBuffer.UV2Kind
  28595. * - BABYLON.VertexBuffer.UV3Kind
  28596. * - BABYLON.VertexBuffer.UV4Kind
  28597. * - BABYLON.VertexBuffer.UV5Kind
  28598. * - BABYLON.VertexBuffer.UV6Kind
  28599. * - BABYLON.VertexBuffer.ColorKind
  28600. * - BABYLON.VertexBuffer.MatricesIndicesKind
  28601. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  28602. * - BABYLON.VertexBuffer.MatricesWeightsKind
  28603. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  28604. *
  28605. * Returns the Mesh.
  28606. */
  28607. Mesh.prototype.updateVerticesData = function (kind, data, updateExtends, makeItUnique) {
  28608. if (!this._geometry) {
  28609. return this;
  28610. }
  28611. if (!makeItUnique) {
  28612. this._geometry.updateVerticesData(kind, data, updateExtends);
  28613. }
  28614. else {
  28615. this.makeGeometryUnique();
  28616. this.updateVerticesData(kind, data, updateExtends, false);
  28617. }
  28618. return this;
  28619. };
  28620. /**
  28621. * This method updates the vertex positions of an updatable mesh according to the `positionFunction` returned values.
  28622. * tuto : http://doc.babylonjs.com/tutorials/How_to_dynamically_morph_a_mesh#other-shapes-updatemeshpositions
  28623. * The parameter `positionFunction` is a simple JS function what is passed the mesh `positions` array. It doesn't need to return anything.
  28624. * The parameter `computeNormals` is a boolean (default true) to enable/disable the mesh normal recomputation after the vertex position update.
  28625. * Returns the Mesh.
  28626. */
  28627. Mesh.prototype.updateMeshPositions = function (positionFunction, computeNormals) {
  28628. if (computeNormals === void 0) { computeNormals = true; }
  28629. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  28630. if (!positions) {
  28631. return this;
  28632. }
  28633. positionFunction(positions);
  28634. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions, false, false);
  28635. if (computeNormals) {
  28636. var indices = this.getIndices();
  28637. var normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  28638. if (!normals) {
  28639. return this;
  28640. }
  28641. BABYLON.VertexData.ComputeNormals(positions, indices, normals);
  28642. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals, false, false);
  28643. }
  28644. return this;
  28645. };
  28646. /**
  28647. * Creates a un-shared specific occurence of the geometry for the mesh.
  28648. * Returns the Mesh.
  28649. */
  28650. Mesh.prototype.makeGeometryUnique = function () {
  28651. if (!this._geometry) {
  28652. return this;
  28653. }
  28654. var oldGeometry = this._geometry;
  28655. var geometry = this._geometry.copy(BABYLON.Geometry.RandomId());
  28656. oldGeometry.releaseForMesh(this, true);
  28657. geometry.applyToMesh(this);
  28658. return this;
  28659. };
  28660. /**
  28661. * Sets the mesh indices.
  28662. * Expects an array populated with integers or a typed array (Int32Array, Uint32Array, Uint16Array).
  28663. * Type is Uint16Array by default unless the mesh has more than 65536 vertices.
  28664. * If the mesh has no geometry, a new Geometry object is created and set to the mesh.
  28665. * This method creates a new index buffer each call.
  28666. * Returns the Mesh.
  28667. */
  28668. Mesh.prototype.setIndices = function (indices, totalVertices, updatable) {
  28669. if (totalVertices === void 0) { totalVertices = null; }
  28670. if (updatable === void 0) { updatable = false; }
  28671. if (!this._geometry) {
  28672. var vertexData = new BABYLON.VertexData();
  28673. vertexData.indices = indices;
  28674. var scene = this.getScene();
  28675. new BABYLON.Geometry(BABYLON.Geometry.RandomId(), scene, vertexData, updatable, this);
  28676. }
  28677. else {
  28678. this._geometry.setIndices(indices, totalVertices, updatable);
  28679. }
  28680. return this;
  28681. };
  28682. /**
  28683. * Update the current index buffer
  28684. * Expects an array populated with integers or a typed array (Int32Array, Uint32Array, Uint16Array)
  28685. * Returns the Mesh.
  28686. */
  28687. Mesh.prototype.updateIndices = function (indices, offset) {
  28688. if (!this._geometry) {
  28689. return this;
  28690. }
  28691. this._geometry.updateIndices(indices, offset);
  28692. return this;
  28693. };
  28694. /**
  28695. * Invert the geometry to move from a right handed system to a left handed one.
  28696. * Returns the Mesh.
  28697. */
  28698. Mesh.prototype.toLeftHanded = function () {
  28699. if (!this._geometry) {
  28700. return this;
  28701. }
  28702. this._geometry.toLeftHanded();
  28703. return this;
  28704. };
  28705. Mesh.prototype._bind = function (subMesh, effect, fillMode) {
  28706. if (!this._geometry) {
  28707. return this;
  28708. }
  28709. var engine = this.getScene().getEngine();
  28710. // Wireframe
  28711. var indexToBind;
  28712. if (this._unIndexed) {
  28713. indexToBind = null;
  28714. }
  28715. else {
  28716. switch (fillMode) {
  28717. case BABYLON.Material.PointFillMode:
  28718. indexToBind = null;
  28719. break;
  28720. case BABYLON.Material.WireFrameFillMode:
  28721. indexToBind = subMesh.getLinesIndexBuffer(this.getIndices(), engine);
  28722. break;
  28723. default:
  28724. case BABYLON.Material.TriangleFillMode:
  28725. indexToBind = this._unIndexed ? null : this._geometry.getIndexBuffer();
  28726. break;
  28727. }
  28728. }
  28729. // VBOs
  28730. this._geometry._bind(effect, indexToBind);
  28731. return this;
  28732. };
  28733. Mesh.prototype._draw = function (subMesh, fillMode, instancesCount, alternate) {
  28734. if (alternate === void 0) { alternate = false; }
  28735. if (!this._geometry || !this._geometry.getVertexBuffers() || !this._geometry.getIndexBuffer()) {
  28736. return this;
  28737. }
  28738. this.onBeforeDrawObservable.notifyObservers(this);
  28739. var scene = this.getScene();
  28740. var engine = scene.getEngine();
  28741. if (this._unIndexed || fillMode == BABYLON.Material.PointFillMode) {
  28742. // or triangles as points
  28743. engine.drawArraysType(fillMode, subMesh.verticesStart, subMesh.verticesCount, instancesCount);
  28744. }
  28745. else if (fillMode == BABYLON.Material.WireFrameFillMode) {
  28746. // Triangles as wireframe
  28747. engine.drawElementsType(fillMode, 0, subMesh.linesIndexCount, instancesCount);
  28748. }
  28749. else {
  28750. engine.drawElementsType(fillMode, subMesh.indexStart, subMesh.indexCount, instancesCount);
  28751. }
  28752. if (scene._isAlternateRenderingEnabled && !alternate) {
  28753. var effect = subMesh.effect || this._effectiveMaterial.getEffect();
  28754. if (!effect || !scene.activeCamera) {
  28755. return this;
  28756. }
  28757. scene._switchToAlternateCameraConfiguration(true);
  28758. this._effectiveMaterial.bindView(effect);
  28759. this._effectiveMaterial.bindViewProjection(effect);
  28760. engine.setViewport(scene.activeCamera._alternateCamera.viewport);
  28761. this._draw(subMesh, fillMode, instancesCount, true);
  28762. engine.setViewport(scene.activeCamera.viewport);
  28763. scene._switchToAlternateCameraConfiguration(false);
  28764. this._effectiveMaterial.bindView(effect);
  28765. this._effectiveMaterial.bindViewProjection(effect);
  28766. }
  28767. return this;
  28768. };
  28769. /**
  28770. * Registers for this mesh a javascript function called just before the rendering process.
  28771. * This function is passed the current mesh.
  28772. * Return the Mesh.
  28773. */
  28774. Mesh.prototype.registerBeforeRender = function (func) {
  28775. this.onBeforeRenderObservable.add(func);
  28776. return this;
  28777. };
  28778. /**
  28779. * Disposes a previously registered javascript function called before the rendering.
  28780. * This function is passed the current mesh.
  28781. * Returns the Mesh.
  28782. */
  28783. Mesh.prototype.unregisterBeforeRender = function (func) {
  28784. this.onBeforeRenderObservable.removeCallback(func);
  28785. return this;
  28786. };
  28787. /**
  28788. * Registers for this mesh a javascript function called just after the rendering is complete.
  28789. * This function is passed the current mesh.
  28790. * Returns the Mesh.
  28791. */
  28792. Mesh.prototype.registerAfterRender = function (func) {
  28793. this.onAfterRenderObservable.add(func);
  28794. return this;
  28795. };
  28796. /**
  28797. * Disposes a previously registered javascript function called after the rendering.
  28798. * This function is passed the current mesh.
  28799. * Return the Mesh.
  28800. */
  28801. Mesh.prototype.unregisterAfterRender = function (func) {
  28802. this.onAfterRenderObservable.removeCallback(func);
  28803. return this;
  28804. };
  28805. Mesh.prototype._getInstancesRenderList = function (subMeshId) {
  28806. var scene = this.getScene();
  28807. this._batchCache.mustReturn = false;
  28808. this._batchCache.renderSelf[subMeshId] = this.isEnabled() && this.isVisible;
  28809. this._batchCache.visibleInstances[subMeshId] = null;
  28810. if (this._visibleInstances) {
  28811. var currentRenderId = scene.getRenderId();
  28812. var defaultRenderId = (scene._isInIntermediateRendering() ? this._visibleInstances.intermediateDefaultRenderId : this._visibleInstances.defaultRenderId);
  28813. this._batchCache.visibleInstances[subMeshId] = this._visibleInstances[currentRenderId];
  28814. var selfRenderId = this._renderId;
  28815. if (!this._batchCache.visibleInstances[subMeshId] && defaultRenderId) {
  28816. this._batchCache.visibleInstances[subMeshId] = this._visibleInstances[defaultRenderId];
  28817. currentRenderId = Math.max(defaultRenderId, currentRenderId);
  28818. selfRenderId = Math.max(this._visibleInstances.selfDefaultRenderId, currentRenderId);
  28819. }
  28820. var visibleInstancesForSubMesh = this._batchCache.visibleInstances[subMeshId];
  28821. if (visibleInstancesForSubMesh && visibleInstancesForSubMesh.length) {
  28822. if (this._renderIdForInstances[subMeshId] === currentRenderId) {
  28823. this._batchCache.mustReturn = true;
  28824. return this._batchCache;
  28825. }
  28826. if (currentRenderId !== selfRenderId) {
  28827. this._batchCache.renderSelf[subMeshId] = false;
  28828. }
  28829. }
  28830. this._renderIdForInstances[subMeshId] = currentRenderId;
  28831. }
  28832. return this._batchCache;
  28833. };
  28834. Mesh.prototype._renderWithInstances = function (subMesh, fillMode, batch, effect, engine) {
  28835. var visibleInstances = batch.visibleInstances[subMesh._id];
  28836. if (!visibleInstances) {
  28837. return this;
  28838. }
  28839. var matricesCount = visibleInstances.length + 1;
  28840. var bufferSize = matricesCount * 16 * 4;
  28841. var currentInstancesBufferSize = this._instancesBufferSize;
  28842. var instancesBuffer = this._instancesBuffer;
  28843. while (this._instancesBufferSize < bufferSize) {
  28844. this._instancesBufferSize *= 2;
  28845. }
  28846. if (!this._instancesData || currentInstancesBufferSize != this._instancesBufferSize) {
  28847. this._instancesData = new Float32Array(this._instancesBufferSize / 4);
  28848. }
  28849. var offset = 0;
  28850. var instancesCount = 0;
  28851. var world = this.getWorldMatrix();
  28852. if (batch.renderSelf[subMesh._id]) {
  28853. world.copyToArray(this._instancesData, offset);
  28854. offset += 16;
  28855. instancesCount++;
  28856. }
  28857. if (visibleInstances) {
  28858. for (var instanceIndex = 0; instanceIndex < visibleInstances.length; instanceIndex++) {
  28859. var instance = visibleInstances[instanceIndex];
  28860. instance.getWorldMatrix().copyToArray(this._instancesData, offset);
  28861. offset += 16;
  28862. instancesCount++;
  28863. }
  28864. }
  28865. if (!instancesBuffer || currentInstancesBufferSize != this._instancesBufferSize) {
  28866. if (instancesBuffer) {
  28867. instancesBuffer.dispose();
  28868. }
  28869. instancesBuffer = new BABYLON.Buffer(engine, this._instancesData, true, 16, false, true);
  28870. this._instancesBuffer = instancesBuffer;
  28871. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world0", 0, 4));
  28872. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world1", 4, 4));
  28873. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world2", 8, 4));
  28874. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world3", 12, 4));
  28875. }
  28876. else {
  28877. instancesBuffer.updateDirectly(this._instancesData, 0, instancesCount);
  28878. }
  28879. this._bind(subMesh, effect, fillMode);
  28880. this._draw(subMesh, fillMode, instancesCount);
  28881. engine.unbindInstanceAttributes();
  28882. return this;
  28883. };
  28884. Mesh.prototype._processRendering = function (subMesh, effect, fillMode, batch, hardwareInstancedRendering, onBeforeDraw, effectiveMaterial) {
  28885. var scene = this.getScene();
  28886. var engine = scene.getEngine();
  28887. if (hardwareInstancedRendering) {
  28888. this._renderWithInstances(subMesh, fillMode, batch, effect, engine);
  28889. }
  28890. else {
  28891. if (batch.renderSelf[subMesh._id]) {
  28892. // Draw
  28893. if (onBeforeDraw) {
  28894. onBeforeDraw(false, this.getWorldMatrix(), effectiveMaterial);
  28895. }
  28896. this._draw(subMesh, fillMode, this._overridenInstanceCount);
  28897. }
  28898. var visibleInstancesForSubMesh = batch.visibleInstances[subMesh._id];
  28899. if (visibleInstancesForSubMesh) {
  28900. for (var instanceIndex = 0; instanceIndex < visibleInstancesForSubMesh.length; instanceIndex++) {
  28901. var instance = visibleInstancesForSubMesh[instanceIndex];
  28902. // World
  28903. var world = instance.getWorldMatrix();
  28904. if (onBeforeDraw) {
  28905. onBeforeDraw(true, world, effectiveMaterial);
  28906. }
  28907. // Draw
  28908. this._draw(subMesh, fillMode);
  28909. }
  28910. }
  28911. }
  28912. return this;
  28913. };
  28914. /**
  28915. * Triggers the draw call for the mesh.
  28916. * Usually, you don't need to call this method by your own because the mesh rendering is handled by the scene rendering manager.
  28917. * Returns the Mesh.
  28918. */
  28919. Mesh.prototype.render = function (subMesh, enableAlphaMode) {
  28920. this.checkOcclusionQuery();
  28921. if (this._isOccluded) {
  28922. return this;
  28923. }
  28924. var scene = this.getScene();
  28925. // Managing instances
  28926. var batch = this._getInstancesRenderList(subMesh._id);
  28927. if (batch.mustReturn) {
  28928. return this;
  28929. }
  28930. // Checking geometry state
  28931. if (!this._geometry || !this._geometry.getVertexBuffers() || !this._geometry.getIndexBuffer()) {
  28932. return this;
  28933. }
  28934. this.onBeforeRenderObservable.notifyObservers(this);
  28935. var engine = scene.getEngine();
  28936. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  28937. // Material
  28938. var material = subMesh.getMaterial();
  28939. if (!material) {
  28940. return this;
  28941. }
  28942. this._effectiveMaterial = material;
  28943. if (this._effectiveMaterial.storeEffectOnSubMeshes) {
  28944. if (!this._effectiveMaterial.isReadyForSubMesh(this, subMesh, hardwareInstancedRendering)) {
  28945. return this;
  28946. }
  28947. }
  28948. else if (!this._effectiveMaterial.isReady(this, hardwareInstancedRendering)) {
  28949. return this;
  28950. }
  28951. // Alpha mode
  28952. if (enableAlphaMode) {
  28953. engine.setAlphaMode(this._effectiveMaterial.alphaMode);
  28954. }
  28955. // Outline - step 1
  28956. var savedDepthWrite = engine.getDepthWrite();
  28957. if (this.renderOutline) {
  28958. engine.setDepthWrite(false);
  28959. scene.getOutlineRenderer().render(subMesh, batch);
  28960. engine.setDepthWrite(savedDepthWrite);
  28961. }
  28962. var effect;
  28963. if (this._effectiveMaterial.storeEffectOnSubMeshes) {
  28964. effect = subMesh.effect;
  28965. }
  28966. else {
  28967. effect = this._effectiveMaterial.getEffect();
  28968. }
  28969. if (!effect) {
  28970. return this;
  28971. }
  28972. var sideOrientation = this.overrideMaterialSideOrientation;
  28973. if (sideOrientation == null) {
  28974. sideOrientation = this._effectiveMaterial.sideOrientation;
  28975. if (this._getWorldMatrixDeterminant() < 0) {
  28976. sideOrientation = (sideOrientation === BABYLON.Material.ClockWiseSideOrientation ? BABYLON.Material.CounterClockWiseSideOrientation : BABYLON.Material.ClockWiseSideOrientation);
  28977. }
  28978. }
  28979. var reverse = this._effectiveMaterial._preBind(effect, sideOrientation);
  28980. if (this._effectiveMaterial.forceDepthWrite) {
  28981. engine.setDepthWrite(true);
  28982. }
  28983. // Bind
  28984. var fillMode = scene.forcePointsCloud ? BABYLON.Material.PointFillMode : (scene.forceWireframe ? BABYLON.Material.WireFrameFillMode : this._effectiveMaterial.fillMode);
  28985. if (!hardwareInstancedRendering) {
  28986. this._bind(subMesh, effect, fillMode);
  28987. }
  28988. var world = this.getWorldMatrix();
  28989. if (this._effectiveMaterial.storeEffectOnSubMeshes) {
  28990. this._effectiveMaterial.bindForSubMesh(world, this, subMesh);
  28991. }
  28992. else {
  28993. this._effectiveMaterial.bind(world, this);
  28994. }
  28995. if (!this._effectiveMaterial.backFaceCulling && this._effectiveMaterial.separateCullingPass) {
  28996. engine.setState(true, this._effectiveMaterial.zOffset, false, !reverse);
  28997. this._processRendering(subMesh, effect, fillMode, batch, hardwareInstancedRendering, this._onBeforeDraw, this._effectiveMaterial);
  28998. engine.setState(true, this._effectiveMaterial.zOffset, false, reverse);
  28999. }
  29000. // Draw
  29001. this._processRendering(subMesh, effect, fillMode, batch, hardwareInstancedRendering, this._onBeforeDraw, this._effectiveMaterial);
  29002. // Unbind
  29003. this._effectiveMaterial.unbind();
  29004. // Outline - step 2
  29005. if (this.renderOutline && savedDepthWrite) {
  29006. engine.setDepthWrite(true);
  29007. engine.setColorWrite(false);
  29008. scene.getOutlineRenderer().render(subMesh, batch);
  29009. engine.setColorWrite(true);
  29010. }
  29011. // Overlay
  29012. if (this.renderOverlay) {
  29013. var currentMode = engine.getAlphaMode();
  29014. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  29015. scene.getOutlineRenderer().render(subMesh, batch, true);
  29016. engine.setAlphaMode(currentMode);
  29017. }
  29018. this.onAfterRenderObservable.notifyObservers(this);
  29019. return this;
  29020. };
  29021. Mesh.prototype._onBeforeDraw = function (isInstance, world, effectiveMaterial) {
  29022. if (isInstance && effectiveMaterial) {
  29023. effectiveMaterial.bindOnlyWorldMatrix(world);
  29024. }
  29025. };
  29026. /**
  29027. * Returns an array populated with ParticleSystem objects whose the mesh is the emitter.
  29028. */
  29029. Mesh.prototype.getEmittedParticleSystems = function () {
  29030. var results = new Array();
  29031. for (var index = 0; index < this.getScene().particleSystems.length; index++) {
  29032. var particleSystem = this.getScene().particleSystems[index];
  29033. if (particleSystem.emitter === this) {
  29034. results.push(particleSystem);
  29035. }
  29036. }
  29037. return results;
  29038. };
  29039. /**
  29040. * Returns an array populated with ParticleSystem objects whose the mesh or its children are the emitter.
  29041. */
  29042. Mesh.prototype.getHierarchyEmittedParticleSystems = function () {
  29043. var results = new Array();
  29044. var descendants = this.getDescendants();
  29045. descendants.push(this);
  29046. for (var index = 0; index < this.getScene().particleSystems.length; index++) {
  29047. var particleSystem = this.getScene().particleSystems[index];
  29048. var emitter = particleSystem.emitter;
  29049. if (emitter.position && descendants.indexOf(emitter) !== -1) {
  29050. results.push(particleSystem);
  29051. }
  29052. }
  29053. return results;
  29054. };
  29055. Mesh.prototype._checkDelayState = function () {
  29056. var scene = this.getScene();
  29057. if (this._geometry) {
  29058. this._geometry.load(scene);
  29059. }
  29060. else if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  29061. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADING;
  29062. this._queueLoad(scene);
  29063. }
  29064. return this;
  29065. };
  29066. Mesh.prototype._queueLoad = function (scene) {
  29067. var _this = this;
  29068. scene._addPendingData(this);
  29069. var getBinaryData = (this.delayLoadingFile.indexOf(".babylonbinarymeshdata") !== -1);
  29070. BABYLON.Tools.LoadFile(this.delayLoadingFile, function (data) {
  29071. if (data instanceof ArrayBuffer) {
  29072. _this._delayLoadingFunction(data, _this);
  29073. }
  29074. else {
  29075. _this._delayLoadingFunction(JSON.parse(data), _this);
  29076. }
  29077. _this.instances.forEach(function (instance) {
  29078. instance._syncSubMeshes();
  29079. });
  29080. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  29081. scene._removePendingData(_this);
  29082. }, function () { }, scene.database, getBinaryData);
  29083. return this;
  29084. };
  29085. /**
  29086. * Boolean, true is the mesh in the frustum defined by the Plane objects from the `frustumPlanes` array parameter.
  29087. */
  29088. Mesh.prototype.isInFrustum = function (frustumPlanes) {
  29089. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  29090. return false;
  29091. }
  29092. if (!_super.prototype.isInFrustum.call(this, frustumPlanes)) {
  29093. return false;
  29094. }
  29095. this._checkDelayState();
  29096. return true;
  29097. };
  29098. /**
  29099. * Sets the mesh material by the material or multiMaterial `id` property.
  29100. * The material `id` is a string identifying the material or the multiMaterial.
  29101. * This method returns the Mesh.
  29102. */
  29103. Mesh.prototype.setMaterialByID = function (id) {
  29104. var materials = this.getScene().materials;
  29105. var index;
  29106. for (index = materials.length - 1; index > -1; index--) {
  29107. if (materials[index].id === id) {
  29108. this.material = materials[index];
  29109. return this;
  29110. }
  29111. }
  29112. // Multi
  29113. var multiMaterials = this.getScene().multiMaterials;
  29114. for (index = multiMaterials.length - 1; index > -1; index--) {
  29115. if (multiMaterials[index].id === id) {
  29116. this.material = multiMaterials[index];
  29117. return this;
  29118. }
  29119. }
  29120. return this;
  29121. };
  29122. /**
  29123. * Returns as a new array populated with the mesh material and/or skeleton, if any.
  29124. */
  29125. Mesh.prototype.getAnimatables = function () {
  29126. var results = new Array();
  29127. if (this.material) {
  29128. results.push(this.material);
  29129. }
  29130. if (this.skeleton) {
  29131. results.push(this.skeleton);
  29132. }
  29133. return results;
  29134. };
  29135. /**
  29136. * Modifies the mesh geometry according to the passed transformation matrix.
  29137. * This method returns nothing but it really modifies the mesh even if it's originally not set as updatable.
  29138. * The mesh normals are modified accordingly the same transformation.
  29139. * tuto : http://doc.babylonjs.com/tutorials/How_Rotations_and_Translations_Work#baking-transform
  29140. * Note that, under the hood, this method sets a new VertexBuffer each call.
  29141. * Returns the Mesh.
  29142. */
  29143. Mesh.prototype.bakeTransformIntoVertices = function (transform) {
  29144. // Position
  29145. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  29146. return this;
  29147. }
  29148. var submeshes = this.subMeshes.splice(0);
  29149. this._resetPointsArrayCache();
  29150. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  29151. var temp = new Array();
  29152. var index;
  29153. for (index = 0; index < data.length; index += 3) {
  29154. BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.FromArray(data, index), transform).toArray(temp, index);
  29155. }
  29156. this.setVerticesData(BABYLON.VertexBuffer.PositionKind, temp, this.getVertexBuffer(BABYLON.VertexBuffer.PositionKind).isUpdatable());
  29157. // Normals
  29158. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  29159. return this;
  29160. }
  29161. data = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  29162. temp = [];
  29163. for (index = 0; index < data.length; index += 3) {
  29164. BABYLON.Vector3.TransformNormal(BABYLON.Vector3.FromArray(data, index), transform).normalize().toArray(temp, index);
  29165. }
  29166. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, temp, this.getVertexBuffer(BABYLON.VertexBuffer.NormalKind).isUpdatable());
  29167. // flip faces?
  29168. if (transform.m[0] * transform.m[5] * transform.m[10] < 0) {
  29169. this.flipFaces();
  29170. }
  29171. // Restore submeshes
  29172. this.releaseSubMeshes();
  29173. this.subMeshes = submeshes;
  29174. return this;
  29175. };
  29176. /**
  29177. * Modifies the mesh geometry according to its own current World Matrix.
  29178. * The mesh World Matrix is then reset.
  29179. * This method returns nothing but really modifies the mesh even if it's originally not set as updatable.
  29180. * tuto : tuto : http://doc.babylonjs.com/resources/baking_transformations
  29181. * Note that, under the hood, this method sets a new VertexBuffer each call.
  29182. * Returns the Mesh.
  29183. */
  29184. Mesh.prototype.bakeCurrentTransformIntoVertices = function () {
  29185. this.bakeTransformIntoVertices(this.computeWorldMatrix(true));
  29186. this.scaling.copyFromFloats(1, 1, 1);
  29187. this.position.copyFromFloats(0, 0, 0);
  29188. this.rotation.copyFromFloats(0, 0, 0);
  29189. //only if quaternion is already set
  29190. if (this.rotationQuaternion) {
  29191. this.rotationQuaternion = BABYLON.Quaternion.Identity();
  29192. }
  29193. this._worldMatrix = BABYLON.Matrix.Identity();
  29194. return this;
  29195. };
  29196. Object.defineProperty(Mesh.prototype, "_positions", {
  29197. // Cache
  29198. get: function () {
  29199. if (this._geometry) {
  29200. return this._geometry._positions;
  29201. }
  29202. return null;
  29203. },
  29204. enumerable: true,
  29205. configurable: true
  29206. });
  29207. Mesh.prototype._resetPointsArrayCache = function () {
  29208. if (this._geometry) {
  29209. this._geometry._resetPointsArrayCache();
  29210. }
  29211. return this;
  29212. };
  29213. Mesh.prototype._generatePointsArray = function () {
  29214. if (this._geometry) {
  29215. return this._geometry._generatePointsArray();
  29216. }
  29217. return false;
  29218. };
  29219. /**
  29220. * Returns a new Mesh object generated from the current mesh properties.
  29221. * This method must not get confused with createInstance().
  29222. * The parameter `name` is a string, the name given to the new mesh.
  29223. * The optional parameter `newParent` can be any Node object (default `null`).
  29224. * The optional parameter `doNotCloneChildren` (default `false`) allows/denies the recursive cloning of the original mesh children if any.
  29225. * 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.
  29226. */
  29227. Mesh.prototype.clone = function (name, newParent, doNotCloneChildren, clonePhysicsImpostor) {
  29228. if (clonePhysicsImpostor === void 0) { clonePhysicsImpostor = true; }
  29229. return new Mesh(name, this.getScene(), newParent, this, doNotCloneChildren, clonePhysicsImpostor);
  29230. };
  29231. /**
  29232. * Releases resources associated with this mesh.
  29233. * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default)
  29234. * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default)
  29235. */
  29236. Mesh.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  29237. var _this = this;
  29238. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  29239. this.morphTargetManager = null;
  29240. if (this._geometry) {
  29241. this._geometry.releaseForMesh(this, true);
  29242. }
  29243. // Sources
  29244. var meshes = this.getScene().meshes;
  29245. meshes.forEach(function (abstractMesh) {
  29246. var mesh = abstractMesh;
  29247. if (mesh._source && mesh._source === _this) {
  29248. mesh._source = null;
  29249. }
  29250. });
  29251. this._source = null;
  29252. // Instances
  29253. if (this._instancesBuffer) {
  29254. this._instancesBuffer.dispose();
  29255. this._instancesBuffer = null;
  29256. }
  29257. while (this.instances.length) {
  29258. this.instances[0].dispose();
  29259. }
  29260. // Effect layers.
  29261. var effectLayers = this.getScene().effectLayers;
  29262. for (var i = 0; i < effectLayers.length; i++) {
  29263. var effectLayer = effectLayers[i];
  29264. if (effectLayer) {
  29265. effectLayer._disposeMesh(this);
  29266. }
  29267. }
  29268. _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
  29269. };
  29270. /**
  29271. * Modifies the mesh geometry according to a displacement map.
  29272. * 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.
  29273. * The mesh must be set as updatable. Its internal geometry is directly modified, no new buffer are allocated.
  29274. * This method returns nothing.
  29275. * The parameter `url` is a string, the URL from the image file is to be downloaded.
  29276. * The parameters `minHeight` and `maxHeight` are the lower and upper limits of the displacement.
  29277. * 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.
  29278. * The parameter `uvOffset` is an optional vector2 used to offset UV.
  29279. * The parameter `uvScale` is an optional vector2 used to scale UV.
  29280. *
  29281. * Returns the Mesh.
  29282. */
  29283. Mesh.prototype.applyDisplacementMap = function (url, minHeight, maxHeight, onSuccess, uvOffset, uvScale) {
  29284. var _this = this;
  29285. var scene = this.getScene();
  29286. var onload = function (img) {
  29287. // Getting height map data
  29288. var canvas = document.createElement("canvas");
  29289. var context = canvas.getContext("2d");
  29290. var heightMapWidth = img.width;
  29291. var heightMapHeight = img.height;
  29292. canvas.width = heightMapWidth;
  29293. canvas.height = heightMapHeight;
  29294. context.drawImage(img, 0, 0);
  29295. // Create VertexData from map data
  29296. //Cast is due to wrong definition in lib.d.ts from ts 1.3 - https://github.com/Microsoft/TypeScript/issues/949
  29297. var buffer = context.getImageData(0, 0, heightMapWidth, heightMapHeight).data;
  29298. _this.applyDisplacementMapFromBuffer(buffer, heightMapWidth, heightMapHeight, minHeight, maxHeight, uvOffset, uvScale);
  29299. //execute success callback, if set
  29300. if (onSuccess) {
  29301. onSuccess(_this);
  29302. }
  29303. };
  29304. BABYLON.Tools.LoadImage(url, onload, function () { }, scene.database);
  29305. return this;
  29306. };
  29307. /**
  29308. * Modifies the mesh geometry according to a displacementMap buffer.
  29309. * 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.
  29310. * The mesh must be set as updatable. Its internal geometry is directly modified, no new buffer are allocated.
  29311. * This method returns nothing.
  29312. * 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.
  29313. * The parameters `heightMapWidth` and `heightMapHeight` are positive integers to set the width and height of the buffer image.
  29314. * The parameters `minHeight` and `maxHeight` are the lower and upper limits of the displacement.
  29315. * The parameter `uvOffset` is an optional vector2 used to offset UV.
  29316. * The parameter `uvScale` is an optional vector2 used to scale UV.
  29317. *
  29318. * Returns the Mesh.
  29319. */
  29320. Mesh.prototype.applyDisplacementMapFromBuffer = function (buffer, heightMapWidth, heightMapHeight, minHeight, maxHeight, uvOffset, uvScale) {
  29321. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)
  29322. || !this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)
  29323. || !this.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  29324. BABYLON.Tools.Warn("Cannot call applyDisplacementMap: Given mesh is not complete. Position, Normal or UV are missing");
  29325. return this;
  29326. }
  29327. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  29328. var normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  29329. var uvs = this.getVerticesData(BABYLON.VertexBuffer.UVKind);
  29330. var position = BABYLON.Vector3.Zero();
  29331. var normal = BABYLON.Vector3.Zero();
  29332. var uv = BABYLON.Vector2.Zero();
  29333. uvOffset = uvOffset || BABYLON.Vector2.Zero();
  29334. uvScale = uvScale || new BABYLON.Vector2(1, 1);
  29335. for (var index = 0; index < positions.length; index += 3) {
  29336. BABYLON.Vector3.FromArrayToRef(positions, index, position);
  29337. BABYLON.Vector3.FromArrayToRef(normals, index, normal);
  29338. BABYLON.Vector2.FromArrayToRef(uvs, (index / 3) * 2, uv);
  29339. // Compute height
  29340. var u = ((Math.abs(uv.x * uvScale.x + uvOffset.x) * heightMapWidth) % heightMapWidth) | 0;
  29341. var v = ((Math.abs(uv.y * uvScale.y + uvOffset.y) * heightMapHeight) % heightMapHeight) | 0;
  29342. var pos = (u + v * heightMapWidth) * 4;
  29343. var r = buffer[pos] / 255.0;
  29344. var g = buffer[pos + 1] / 255.0;
  29345. var b = buffer[pos + 2] / 255.0;
  29346. var gradient = r * 0.3 + g * 0.59 + b * 0.11;
  29347. normal.normalize();
  29348. normal.scaleInPlace(minHeight + (maxHeight - minHeight) * gradient);
  29349. position = position.add(normal);
  29350. position.toArray(positions, index);
  29351. }
  29352. BABYLON.VertexData.ComputeNormals(positions, this.getIndices(), normals);
  29353. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions);
  29354. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals);
  29355. return this;
  29356. };
  29357. /**
  29358. * Modify the mesh to get a flat shading rendering.
  29359. * This means each mesh facet will then have its own normals. Usually new vertices are added in the mesh geometry to get this result.
  29360. * This method returns the Mesh.
  29361. * Warning : the mesh is really modified even if not set originally as updatable and, under the hood, a new VertexBuffer is allocated.
  29362. */
  29363. Mesh.prototype.convertToFlatShadedMesh = function () {
  29364. /// <summary>Update normals and vertices to get a flat shading rendering.</summary>
  29365. /// <summary>Warning: This may imply adding vertices to the mesh in order to get exactly 3 vertices per face</summary>
  29366. var kinds = this.getVerticesDataKinds();
  29367. var vbs = {};
  29368. var data = {};
  29369. var newdata = {};
  29370. var updatableNormals = false;
  29371. var kindIndex;
  29372. var kind;
  29373. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  29374. kind = kinds[kindIndex];
  29375. var vertexBuffer = this.getVertexBuffer(kind);
  29376. if (kind === BABYLON.VertexBuffer.NormalKind) {
  29377. updatableNormals = vertexBuffer.isUpdatable();
  29378. kinds.splice(kindIndex, 1);
  29379. kindIndex--;
  29380. continue;
  29381. }
  29382. vbs[kind] = vertexBuffer;
  29383. data[kind] = vbs[kind].getData();
  29384. newdata[kind] = [];
  29385. }
  29386. // Save previous submeshes
  29387. var previousSubmeshes = this.subMeshes.slice(0);
  29388. var indices = this.getIndices();
  29389. var totalIndices = this.getTotalIndices();
  29390. // Generating unique vertices per face
  29391. var index;
  29392. for (index = 0; index < totalIndices; index++) {
  29393. var vertexIndex = indices[index];
  29394. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  29395. kind = kinds[kindIndex];
  29396. var stride = vbs[kind].getStrideSize();
  29397. for (var offset = 0; offset < stride; offset++) {
  29398. newdata[kind].push(data[kind][vertexIndex * stride + offset]);
  29399. }
  29400. }
  29401. }
  29402. // Updating faces & normal
  29403. var normals = [];
  29404. var positions = newdata[BABYLON.VertexBuffer.PositionKind];
  29405. for (index = 0; index < totalIndices; index += 3) {
  29406. indices[index] = index;
  29407. indices[index + 1] = index + 1;
  29408. indices[index + 2] = index + 2;
  29409. var p1 = BABYLON.Vector3.FromArray(positions, index * 3);
  29410. var p2 = BABYLON.Vector3.FromArray(positions, (index + 1) * 3);
  29411. var p3 = BABYLON.Vector3.FromArray(positions, (index + 2) * 3);
  29412. var p1p2 = p1.subtract(p2);
  29413. var p3p2 = p3.subtract(p2);
  29414. var normal = BABYLON.Vector3.Normalize(BABYLON.Vector3.Cross(p1p2, p3p2));
  29415. // Store same normals for every vertex
  29416. for (var localIndex = 0; localIndex < 3; localIndex++) {
  29417. normals.push(normal.x);
  29418. normals.push(normal.y);
  29419. normals.push(normal.z);
  29420. }
  29421. }
  29422. this.setIndices(indices);
  29423. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals, updatableNormals);
  29424. // Updating vertex buffers
  29425. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  29426. kind = kinds[kindIndex];
  29427. this.setVerticesData(kind, newdata[kind], vbs[kind].isUpdatable());
  29428. }
  29429. // Updating submeshes
  29430. this.releaseSubMeshes();
  29431. for (var submeshIndex = 0; submeshIndex < previousSubmeshes.length; submeshIndex++) {
  29432. var previousOne = previousSubmeshes[submeshIndex];
  29433. BABYLON.SubMesh.AddToMesh(previousOne.materialIndex, previousOne.indexStart, previousOne.indexCount, previousOne.indexStart, previousOne.indexCount, this);
  29434. }
  29435. this.synchronizeInstances();
  29436. return this;
  29437. };
  29438. /**
  29439. * This method removes all the mesh indices and add new vertices (duplication) in order to unfold facets into buffers.
  29440. * In other words, more vertices, no more indices and a single bigger VBO.
  29441. * The mesh is really modified even if not set originally as updatable. Under the hood, a new VertexBuffer is allocated.
  29442. * Returns the Mesh.
  29443. */
  29444. Mesh.prototype.convertToUnIndexedMesh = function () {
  29445. /// <summary>Remove indices by unfolding faces into buffers</summary>
  29446. /// <summary>Warning: This implies adding vertices to the mesh in order to get exactly 3 vertices per face</summary>
  29447. var kinds = this.getVerticesDataKinds();
  29448. var vbs = {};
  29449. var data = {};
  29450. var newdata = {};
  29451. var kindIndex;
  29452. var kind;
  29453. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  29454. kind = kinds[kindIndex];
  29455. var vertexBuffer = this.getVertexBuffer(kind);
  29456. vbs[kind] = vertexBuffer;
  29457. data[kind] = vbs[kind].getData();
  29458. newdata[kind] = [];
  29459. }
  29460. // Save previous submeshes
  29461. var previousSubmeshes = this.subMeshes.slice(0);
  29462. var indices = this.getIndices();
  29463. var totalIndices = this.getTotalIndices();
  29464. // Generating unique vertices per face
  29465. var index;
  29466. for (index = 0; index < totalIndices; index++) {
  29467. var vertexIndex = indices[index];
  29468. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  29469. kind = kinds[kindIndex];
  29470. var stride = vbs[kind].getStrideSize();
  29471. for (var offset = 0; offset < stride; offset++) {
  29472. newdata[kind].push(data[kind][vertexIndex * stride + offset]);
  29473. }
  29474. }
  29475. }
  29476. // Updating indices
  29477. for (index = 0; index < totalIndices; index += 3) {
  29478. indices[index] = index;
  29479. indices[index + 1] = index + 1;
  29480. indices[index + 2] = index + 2;
  29481. }
  29482. this.setIndices(indices);
  29483. // Updating vertex buffers
  29484. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  29485. kind = kinds[kindIndex];
  29486. this.setVerticesData(kind, newdata[kind], vbs[kind].isUpdatable());
  29487. }
  29488. // Updating submeshes
  29489. this.releaseSubMeshes();
  29490. for (var submeshIndex = 0; submeshIndex < previousSubmeshes.length; submeshIndex++) {
  29491. var previousOne = previousSubmeshes[submeshIndex];
  29492. BABYLON.SubMesh.AddToMesh(previousOne.materialIndex, previousOne.indexStart, previousOne.indexCount, previousOne.indexStart, previousOne.indexCount, this);
  29493. }
  29494. this._unIndexed = true;
  29495. this.synchronizeInstances();
  29496. return this;
  29497. };
  29498. /**
  29499. * Inverses facet orientations and inverts also the normals with `flipNormals` (default `false`) if true.
  29500. * This method returns the Mesh.
  29501. * Warning : the mesh is really modified even if not set originally as updatable. A new VertexBuffer is created under the hood each call.
  29502. */
  29503. Mesh.prototype.flipFaces = function (flipNormals) {
  29504. if (flipNormals === void 0) { flipNormals = false; }
  29505. var vertex_data = BABYLON.VertexData.ExtractFromMesh(this);
  29506. var i;
  29507. if (flipNormals && this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind) && vertex_data.normals) {
  29508. for (i = 0; i < vertex_data.normals.length; i++) {
  29509. vertex_data.normals[i] *= -1;
  29510. }
  29511. }
  29512. if (vertex_data.indices) {
  29513. var temp;
  29514. for (i = 0; i < vertex_data.indices.length; i += 3) {
  29515. // reassign indices
  29516. temp = vertex_data.indices[i + 1];
  29517. vertex_data.indices[i + 1] = vertex_data.indices[i + 2];
  29518. vertex_data.indices[i + 2] = temp;
  29519. }
  29520. }
  29521. vertex_data.applyToMesh(this);
  29522. return this;
  29523. };
  29524. // Instances
  29525. /**
  29526. * Creates a new InstancedMesh object from the mesh model.
  29527. * An instance shares the same properties and the same material than its model.
  29528. * Only these properties of each instance can then be set individually :
  29529. * - position
  29530. * - rotation
  29531. * - rotationQuaternion
  29532. * - setPivotMatrix
  29533. * - scaling
  29534. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_Instances
  29535. * Warning : this method is not supported for Line mesh and LineSystem
  29536. */
  29537. Mesh.prototype.createInstance = function (name) {
  29538. return new BABYLON.InstancedMesh(name, this);
  29539. };
  29540. /**
  29541. * Synchronises all the mesh instance submeshes to the current mesh submeshes, if any.
  29542. * After this call, all the mesh instances have the same submeshes than the current mesh.
  29543. * This method returns the Mesh.
  29544. */
  29545. Mesh.prototype.synchronizeInstances = function () {
  29546. for (var instanceIndex = 0; instanceIndex < this.instances.length; instanceIndex++) {
  29547. var instance = this.instances[instanceIndex];
  29548. instance._syncSubMeshes();
  29549. }
  29550. return this;
  29551. };
  29552. /**
  29553. * Simplify the mesh according to the given array of settings.
  29554. * Function will return immediately and will simplify async. It returns the Mesh.
  29555. * @param settings a collection of simplification settings.
  29556. * @param parallelProcessing should all levels calculate parallel or one after the other.
  29557. * @param type the type of simplification to run.
  29558. * @param successCallback optional success callback to be called after the simplification finished processing all settings.
  29559. */
  29560. Mesh.prototype.simplify = function (settings, parallelProcessing, simplificationType, successCallback) {
  29561. if (parallelProcessing === void 0) { parallelProcessing = true; }
  29562. if (simplificationType === void 0) { simplificationType = BABYLON.SimplificationType.QUADRATIC; }
  29563. this.getScene().simplificationQueue.addTask({
  29564. settings: settings,
  29565. parallelProcessing: parallelProcessing,
  29566. mesh: this,
  29567. simplificationType: simplificationType,
  29568. successCallback: successCallback
  29569. });
  29570. return this;
  29571. };
  29572. /**
  29573. * Optimization of the mesh's indices, in case a mesh has duplicated vertices.
  29574. * The function will only reorder the indices and will not remove unused vertices to avoid problems with submeshes.
  29575. * This should be used together with the simplification to avoid disappearing triangles.
  29576. * Returns the Mesh.
  29577. * @param successCallback an optional success callback to be called after the optimization finished.
  29578. */
  29579. Mesh.prototype.optimizeIndices = function (successCallback) {
  29580. var _this = this;
  29581. var indices = this.getIndices();
  29582. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  29583. if (!positions || !indices) {
  29584. return this;
  29585. }
  29586. var vectorPositions = new Array();
  29587. for (var pos = 0; pos < positions.length; pos = pos + 3) {
  29588. vectorPositions.push(BABYLON.Vector3.FromArray(positions, pos));
  29589. }
  29590. var dupes = new Array();
  29591. BABYLON.AsyncLoop.SyncAsyncForLoop(vectorPositions.length, 40, function (iteration) {
  29592. var realPos = vectorPositions.length - 1 - iteration;
  29593. var testedPosition = vectorPositions[realPos];
  29594. for (var j = 0; j < realPos; ++j) {
  29595. var againstPosition = vectorPositions[j];
  29596. if (testedPosition.equals(againstPosition)) {
  29597. dupes[realPos] = j;
  29598. break;
  29599. }
  29600. }
  29601. }, function () {
  29602. for (var i = 0; i < indices.length; ++i) {
  29603. indices[i] = dupes[indices[i]] || indices[i];
  29604. }
  29605. //indices are now reordered
  29606. var originalSubMeshes = _this.subMeshes.slice(0);
  29607. _this.setIndices(indices);
  29608. _this.subMeshes = originalSubMeshes;
  29609. if (successCallback) {
  29610. successCallback(_this);
  29611. }
  29612. });
  29613. return this;
  29614. };
  29615. Mesh.prototype.serialize = function (serializationObject) {
  29616. serializationObject.name = this.name;
  29617. serializationObject.id = this.id;
  29618. serializationObject.type = this.getClassName();
  29619. if (BABYLON.Tags && BABYLON.Tags.HasTags(this)) {
  29620. serializationObject.tags = BABYLON.Tags.GetTags(this);
  29621. }
  29622. serializationObject.position = this.position.asArray();
  29623. if (this.rotationQuaternion) {
  29624. serializationObject.rotationQuaternion = this.rotationQuaternion.asArray();
  29625. }
  29626. else if (this.rotation) {
  29627. serializationObject.rotation = this.rotation.asArray();
  29628. }
  29629. serializationObject.scaling = this.scaling.asArray();
  29630. serializationObject.localMatrix = this.getPivotMatrix().asArray();
  29631. serializationObject.isEnabled = this.isEnabled(false);
  29632. serializationObject.isVisible = this.isVisible;
  29633. serializationObject.infiniteDistance = this.infiniteDistance;
  29634. serializationObject.pickable = this.isPickable;
  29635. serializationObject.receiveShadows = this.receiveShadows;
  29636. serializationObject.billboardMode = this.billboardMode;
  29637. serializationObject.visibility = this.visibility;
  29638. serializationObject.checkCollisions = this.checkCollisions;
  29639. serializationObject.isBlocker = this.isBlocker;
  29640. // Parent
  29641. if (this.parent) {
  29642. serializationObject.parentId = this.parent.id;
  29643. }
  29644. // Geometry
  29645. serializationObject.isUnIndexed = this.isUnIndexed;
  29646. var geometry = this._geometry;
  29647. if (geometry) {
  29648. var geometryId = geometry.id;
  29649. serializationObject.geometryId = geometryId;
  29650. // SubMeshes
  29651. serializationObject.subMeshes = [];
  29652. for (var subIndex = 0; subIndex < this.subMeshes.length; subIndex++) {
  29653. var subMesh = this.subMeshes[subIndex];
  29654. serializationObject.subMeshes.push({
  29655. materialIndex: subMesh.materialIndex,
  29656. verticesStart: subMesh.verticesStart,
  29657. verticesCount: subMesh.verticesCount,
  29658. indexStart: subMesh.indexStart,
  29659. indexCount: subMesh.indexCount
  29660. });
  29661. }
  29662. }
  29663. // Material
  29664. if (this.material) {
  29665. serializationObject.materialId = this.material.id;
  29666. }
  29667. else {
  29668. this.material = null;
  29669. }
  29670. // Morph targets
  29671. if (this.morphTargetManager) {
  29672. serializationObject.morphTargetManagerId = this.morphTargetManager.uniqueId;
  29673. }
  29674. // Skeleton
  29675. if (this.skeleton) {
  29676. serializationObject.skeletonId = this.skeleton.id;
  29677. }
  29678. // Physics
  29679. //TODO implement correct serialization for physics impostors.
  29680. var impostor = this.getPhysicsImpostor();
  29681. if (impostor) {
  29682. serializationObject.physicsMass = impostor.getParam("mass");
  29683. serializationObject.physicsFriction = impostor.getParam("friction");
  29684. serializationObject.physicsRestitution = impostor.getParam("mass");
  29685. serializationObject.physicsImpostor = impostor.type;
  29686. }
  29687. // Metadata
  29688. if (this.metadata) {
  29689. serializationObject.metadata = this.metadata;
  29690. }
  29691. // Instances
  29692. serializationObject.instances = [];
  29693. for (var index = 0; index < this.instances.length; index++) {
  29694. var instance = this.instances[index];
  29695. var serializationInstance = {
  29696. name: instance.name,
  29697. id: instance.id,
  29698. position: instance.position.asArray(),
  29699. scaling: instance.scaling.asArray()
  29700. };
  29701. if (instance.rotationQuaternion) {
  29702. serializationInstance.rotationQuaternion = instance.rotationQuaternion.asArray();
  29703. }
  29704. else if (instance.rotation) {
  29705. serializationInstance.rotation = instance.rotation.asArray();
  29706. }
  29707. serializationObject.instances.push(serializationInstance);
  29708. // Animations
  29709. BABYLON.Animation.AppendSerializedAnimations(instance, serializationInstance);
  29710. serializationInstance.ranges = instance.serializeAnimationRanges();
  29711. }
  29712. //
  29713. // Animations
  29714. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  29715. serializationObject.ranges = this.serializeAnimationRanges();
  29716. // Layer mask
  29717. serializationObject.layerMask = this.layerMask;
  29718. // Alpha
  29719. serializationObject.alphaIndex = this.alphaIndex;
  29720. serializationObject.hasVertexAlpha = this.hasVertexAlpha;
  29721. // Overlay
  29722. serializationObject.overlayAlpha = this.overlayAlpha;
  29723. serializationObject.overlayColor = this.overlayColor.asArray();
  29724. serializationObject.renderOverlay = this.renderOverlay;
  29725. // Fog
  29726. serializationObject.applyFog = this.applyFog;
  29727. // Action Manager
  29728. if (this.actionManager) {
  29729. serializationObject.actions = this.actionManager.serialize(this.name);
  29730. }
  29731. };
  29732. Mesh.prototype._syncGeometryWithMorphTargetManager = function () {
  29733. if (!this.geometry) {
  29734. return;
  29735. }
  29736. this._markSubMeshesAsAttributesDirty();
  29737. var morphTargetManager = this._morphTargetManager;
  29738. if (morphTargetManager && morphTargetManager.vertexCount) {
  29739. if (morphTargetManager.vertexCount !== this.getTotalVertices()) {
  29740. BABYLON.Tools.Error("Mesh is incompatible with morph targets. Targets and mesh must all have the same vertices count.");
  29741. this.morphTargetManager = null;
  29742. return;
  29743. }
  29744. for (var index = 0; index < morphTargetManager.numInfluencers; index++) {
  29745. var morphTarget = morphTargetManager.getActiveTarget(index);
  29746. var positions = morphTarget.getPositions();
  29747. if (!positions) {
  29748. BABYLON.Tools.Error("Invalid morph target. Target must have positions.");
  29749. return;
  29750. }
  29751. this.geometry.setVerticesData(BABYLON.VertexBuffer.PositionKind + index, positions, false, 3);
  29752. var normals = morphTarget.getNormals();
  29753. if (normals) {
  29754. this.geometry.setVerticesData(BABYLON.VertexBuffer.NormalKind + index, normals, false, 3);
  29755. }
  29756. var tangents = morphTarget.getTangents();
  29757. if (tangents) {
  29758. this.geometry.setVerticesData(BABYLON.VertexBuffer.TangentKind + index, tangents, false, 3);
  29759. }
  29760. }
  29761. }
  29762. else {
  29763. var index = 0;
  29764. // Positions
  29765. while (this.geometry.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind + index)) {
  29766. this.geometry.removeVerticesData(BABYLON.VertexBuffer.PositionKind + index);
  29767. if (this.geometry.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind + index)) {
  29768. this.geometry.removeVerticesData(BABYLON.VertexBuffer.NormalKind + index);
  29769. }
  29770. if (this.geometry.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind + index)) {
  29771. this.geometry.removeVerticesData(BABYLON.VertexBuffer.TangentKind + index);
  29772. }
  29773. index++;
  29774. }
  29775. }
  29776. };
  29777. // Statics
  29778. /**
  29779. * Returns a new Mesh object parsed from the source provided.
  29780. * The parameter `parsedMesh` is the source.
  29781. * The parameter `rootUrl` is a string, it's the root URL to prefix the `delayLoadingFile` property with
  29782. */
  29783. Mesh.Parse = function (parsedMesh, scene, rootUrl) {
  29784. var mesh;
  29785. if (parsedMesh.type && parsedMesh.type === "GroundMesh") {
  29786. mesh = BABYLON.GroundMesh.Parse(parsedMesh, scene);
  29787. }
  29788. else {
  29789. mesh = new Mesh(parsedMesh.name, scene);
  29790. }
  29791. mesh.id = parsedMesh.id;
  29792. if (BABYLON.Tags) {
  29793. BABYLON.Tags.AddTagsTo(mesh, parsedMesh.tags);
  29794. }
  29795. mesh.position = BABYLON.Vector3.FromArray(parsedMesh.position);
  29796. if (parsedMesh.metadata !== undefined) {
  29797. mesh.metadata = parsedMesh.metadata;
  29798. }
  29799. if (parsedMesh.rotationQuaternion) {
  29800. mesh.rotationQuaternion = BABYLON.Quaternion.FromArray(parsedMesh.rotationQuaternion);
  29801. }
  29802. else if (parsedMesh.rotation) {
  29803. mesh.rotation = BABYLON.Vector3.FromArray(parsedMesh.rotation);
  29804. }
  29805. mesh.scaling = BABYLON.Vector3.FromArray(parsedMesh.scaling);
  29806. if (parsedMesh.localMatrix) {
  29807. mesh.setPreTransformMatrix(BABYLON.Matrix.FromArray(parsedMesh.localMatrix));
  29808. }
  29809. else if (parsedMesh.pivotMatrix) {
  29810. mesh.setPivotMatrix(BABYLON.Matrix.FromArray(parsedMesh.pivotMatrix));
  29811. }
  29812. mesh.setEnabled(parsedMesh.isEnabled);
  29813. mesh.isVisible = parsedMesh.isVisible;
  29814. mesh.infiniteDistance = parsedMesh.infiniteDistance;
  29815. mesh.showBoundingBox = parsedMesh.showBoundingBox;
  29816. mesh.showSubMeshesBoundingBox = parsedMesh.showSubMeshesBoundingBox;
  29817. if (parsedMesh.applyFog !== undefined) {
  29818. mesh.applyFog = parsedMesh.applyFog;
  29819. }
  29820. if (parsedMesh.pickable !== undefined) {
  29821. mesh.isPickable = parsedMesh.pickable;
  29822. }
  29823. if (parsedMesh.alphaIndex !== undefined) {
  29824. mesh.alphaIndex = parsedMesh.alphaIndex;
  29825. }
  29826. mesh.receiveShadows = parsedMesh.receiveShadows;
  29827. mesh.billboardMode = parsedMesh.billboardMode;
  29828. if (parsedMesh.visibility !== undefined) {
  29829. mesh.visibility = parsedMesh.visibility;
  29830. }
  29831. mesh.checkCollisions = parsedMesh.checkCollisions;
  29832. if (parsedMesh.isBlocker !== undefined) {
  29833. mesh.isBlocker = parsedMesh.isBlocker;
  29834. }
  29835. mesh._shouldGenerateFlatShading = parsedMesh.useFlatShading;
  29836. // freezeWorldMatrix
  29837. if (parsedMesh.freezeWorldMatrix) {
  29838. mesh._waitingFreezeWorldMatrix = parsedMesh.freezeWorldMatrix;
  29839. }
  29840. // Parent
  29841. if (parsedMesh.parentId) {
  29842. mesh._waitingParentId = parsedMesh.parentId;
  29843. }
  29844. // Actions
  29845. if (parsedMesh.actions !== undefined) {
  29846. mesh._waitingActions = parsedMesh.actions;
  29847. }
  29848. // Overlay
  29849. if (parsedMesh.overlayAlpha !== undefined) {
  29850. mesh.overlayAlpha = parsedMesh.overlayAlpha;
  29851. }
  29852. if (parsedMesh.overlayColor !== undefined) {
  29853. mesh.overlayColor = BABYLON.Color3.FromArray(parsedMesh.overlayColor);
  29854. }
  29855. if (parsedMesh.renderOverlay !== undefined) {
  29856. mesh.renderOverlay = parsedMesh.renderOverlay;
  29857. }
  29858. // Geometry
  29859. mesh.isUnIndexed = !!parsedMesh.isUnIndexed;
  29860. mesh.hasVertexAlpha = parsedMesh.hasVertexAlpha;
  29861. if (parsedMesh.delayLoadingFile) {
  29862. mesh.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  29863. mesh.delayLoadingFile = rootUrl + parsedMesh.delayLoadingFile;
  29864. mesh._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Vector3.FromArray(parsedMesh.boundingBoxMinimum), BABYLON.Vector3.FromArray(parsedMesh.boundingBoxMaximum));
  29865. if (parsedMesh._binaryInfo) {
  29866. mesh._binaryInfo = parsedMesh._binaryInfo;
  29867. }
  29868. mesh._delayInfo = [];
  29869. if (parsedMesh.hasUVs) {
  29870. mesh._delayInfo.push(BABYLON.VertexBuffer.UVKind);
  29871. }
  29872. if (parsedMesh.hasUVs2) {
  29873. mesh._delayInfo.push(BABYLON.VertexBuffer.UV2Kind);
  29874. }
  29875. if (parsedMesh.hasUVs3) {
  29876. mesh._delayInfo.push(BABYLON.VertexBuffer.UV3Kind);
  29877. }
  29878. if (parsedMesh.hasUVs4) {
  29879. mesh._delayInfo.push(BABYLON.VertexBuffer.UV4Kind);
  29880. }
  29881. if (parsedMesh.hasUVs5) {
  29882. mesh._delayInfo.push(BABYLON.VertexBuffer.UV5Kind);
  29883. }
  29884. if (parsedMesh.hasUVs6) {
  29885. mesh._delayInfo.push(BABYLON.VertexBuffer.UV6Kind);
  29886. }
  29887. if (parsedMesh.hasColors) {
  29888. mesh._delayInfo.push(BABYLON.VertexBuffer.ColorKind);
  29889. }
  29890. if (parsedMesh.hasMatricesIndices) {
  29891. mesh._delayInfo.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  29892. }
  29893. if (parsedMesh.hasMatricesWeights) {
  29894. mesh._delayInfo.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  29895. }
  29896. mesh._delayLoadingFunction = BABYLON.Geometry._ImportGeometry;
  29897. if (BABYLON.SceneLoader.ForceFullSceneLoadingForIncremental) {
  29898. mesh._checkDelayState();
  29899. }
  29900. }
  29901. else {
  29902. BABYLON.Geometry._ImportGeometry(parsedMesh, mesh);
  29903. }
  29904. // Material
  29905. if (parsedMesh.materialId) {
  29906. mesh.setMaterialByID(parsedMesh.materialId);
  29907. }
  29908. else {
  29909. mesh.material = null;
  29910. }
  29911. // Morph targets
  29912. if (parsedMesh.morphTargetManagerId > -1) {
  29913. mesh.morphTargetManager = scene.getMorphTargetManagerById(parsedMesh.morphTargetManagerId);
  29914. }
  29915. // Skeleton
  29916. if (parsedMesh.skeletonId > -1) {
  29917. mesh.skeleton = scene.getLastSkeletonByID(parsedMesh.skeletonId);
  29918. if (parsedMesh.numBoneInfluencers) {
  29919. mesh.numBoneInfluencers = parsedMesh.numBoneInfluencers;
  29920. }
  29921. }
  29922. // Animations
  29923. if (parsedMesh.animations) {
  29924. for (var animationIndex = 0; animationIndex < parsedMesh.animations.length; animationIndex++) {
  29925. var parsedAnimation = parsedMesh.animations[animationIndex];
  29926. mesh.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  29927. }
  29928. BABYLON.Node.ParseAnimationRanges(mesh, parsedMesh, scene);
  29929. }
  29930. if (parsedMesh.autoAnimate) {
  29931. scene.beginAnimation(mesh, parsedMesh.autoAnimateFrom, parsedMesh.autoAnimateTo, parsedMesh.autoAnimateLoop, parsedMesh.autoAnimateSpeed || 1.0);
  29932. }
  29933. // Layer Mask
  29934. if (parsedMesh.layerMask && (!isNaN(parsedMesh.layerMask))) {
  29935. mesh.layerMask = Math.abs(parseInt(parsedMesh.layerMask));
  29936. }
  29937. else {
  29938. mesh.layerMask = 0x0FFFFFFF;
  29939. }
  29940. // Physics
  29941. if (parsedMesh.physicsImpostor) {
  29942. mesh.physicsImpostor = new BABYLON.PhysicsImpostor(mesh, parsedMesh.physicsImpostor, {
  29943. mass: parsedMesh.physicsMass,
  29944. friction: parsedMesh.physicsFriction,
  29945. restitution: parsedMesh.physicsRestitution
  29946. }, scene);
  29947. }
  29948. // Instances
  29949. if (parsedMesh.instances) {
  29950. for (var index = 0; index < parsedMesh.instances.length; index++) {
  29951. var parsedInstance = parsedMesh.instances[index];
  29952. var instance = mesh.createInstance(parsedInstance.name);
  29953. if (parsedInstance.id) {
  29954. instance.id = parsedInstance.id;
  29955. }
  29956. if (BABYLON.Tags) {
  29957. BABYLON.Tags.AddTagsTo(instance, parsedInstance.tags);
  29958. }
  29959. instance.position = BABYLON.Vector3.FromArray(parsedInstance.position);
  29960. if (parsedInstance.parentId) {
  29961. instance._waitingParentId = parsedInstance.parentId;
  29962. }
  29963. if (parsedInstance.rotationQuaternion) {
  29964. instance.rotationQuaternion = BABYLON.Quaternion.FromArray(parsedInstance.rotationQuaternion);
  29965. }
  29966. else if (parsedInstance.rotation) {
  29967. instance.rotation = BABYLON.Vector3.FromArray(parsedInstance.rotation);
  29968. }
  29969. instance.scaling = BABYLON.Vector3.FromArray(parsedInstance.scaling);
  29970. instance.checkCollisions = mesh.checkCollisions;
  29971. if (parsedMesh.animations) {
  29972. for (animationIndex = 0; animationIndex < parsedMesh.animations.length; animationIndex++) {
  29973. parsedAnimation = parsedMesh.animations[animationIndex];
  29974. instance.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  29975. }
  29976. BABYLON.Node.ParseAnimationRanges(instance, parsedMesh, scene);
  29977. }
  29978. }
  29979. }
  29980. return mesh;
  29981. };
  29982. /**
  29983. * Creates a ribbon mesh.
  29984. * Please consider using the same method from the MeshBuilder class instead.
  29985. * 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.
  29986. *
  29987. * Please read this full tutorial to understand how to design a ribbon : http://doc.babylonjs.com/tutorials/Ribbon_Tutorial
  29988. * The parameter `pathArray` is a required array of paths, what are each an array of successive Vector3. The pathArray parameter depicts the ribbon geometry.
  29989. * The parameter `closeArray` (boolean, default false) creates a seam between the first and the last paths of the path array.
  29990. * The parameter `closePath` (boolean, default false) creates a seam between the first and the last points of each path of the path array.
  29991. * 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.
  29992. * 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.
  29993. * 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
  29994. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  29995. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  29996. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  29997. */
  29998. Mesh.CreateRibbon = function (name, pathArray, closeArray, closePath, offset, scene, updatable, sideOrientation, instance) {
  29999. if (closeArray === void 0) { closeArray = false; }
  30000. if (updatable === void 0) { updatable = false; }
  30001. return BABYLON.MeshBuilder.CreateRibbon(name, {
  30002. pathArray: pathArray,
  30003. closeArray: closeArray,
  30004. closePath: closePath,
  30005. offset: offset,
  30006. updatable: updatable,
  30007. sideOrientation: sideOrientation,
  30008. instance: instance
  30009. }, scene);
  30010. };
  30011. /**
  30012. * Creates a plane polygonal mesh. By default, this is a disc.
  30013. * Please consider using the same method from the MeshBuilder class instead.
  30014. * The parameter `radius` sets the radius size (float) of the polygon (default 0.5).
  30015. * 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.
  30016. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  30017. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  30018. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  30019. */
  30020. Mesh.CreateDisc = function (name, radius, tessellation, scene, updatable, sideOrientation) {
  30021. if (scene === void 0) { scene = null; }
  30022. var options = {
  30023. radius: radius,
  30024. tessellation: tessellation,
  30025. sideOrientation: sideOrientation,
  30026. updatable: updatable
  30027. };
  30028. return BABYLON.MeshBuilder.CreateDisc(name, options, scene);
  30029. };
  30030. /**
  30031. * Creates a box mesh.
  30032. * Please consider using the same method from the MeshBuilder class instead.
  30033. * The parameter `size` sets the size (float) of each box side (default 1).
  30034. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  30035. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  30036. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  30037. */
  30038. Mesh.CreateBox = function (name, size, scene, updatable, sideOrientation) {
  30039. if (scene === void 0) { scene = null; }
  30040. var options = {
  30041. size: size,
  30042. sideOrientation: sideOrientation,
  30043. updatable: updatable
  30044. };
  30045. return BABYLON.MeshBuilder.CreateBox(name, options, scene);
  30046. };
  30047. /**
  30048. * Creates a sphere mesh.
  30049. * Please consider using the same method from the MeshBuilder class instead.
  30050. * The parameter `diameter` sets the diameter size (float) of the sphere (default 1).
  30051. * The parameter `segments` sets the sphere number of horizontal stripes (positive integer, default 32).
  30052. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  30053. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  30054. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  30055. */
  30056. Mesh.CreateSphere = function (name, segments, diameter, scene, updatable, sideOrientation) {
  30057. var options = {
  30058. segments: segments,
  30059. diameterX: diameter,
  30060. diameterY: diameter,
  30061. diameterZ: diameter,
  30062. sideOrientation: sideOrientation,
  30063. updatable: updatable
  30064. };
  30065. return BABYLON.MeshBuilder.CreateSphere(name, options, scene);
  30066. };
  30067. /**
  30068. * Creates a cylinder or a cone mesh.
  30069. * Please consider using the same method from the MeshBuilder class instead.
  30070. * The parameter `height` sets the height size (float) of the cylinder/cone (float, default 2).
  30071. * The parameter `diameter` sets the diameter of the top and bottom cap at once (float, default 1).
  30072. * 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.
  30073. * The parameter `tessellation` sets the number of cylinder sides (positive integer, default 24). Set it to 3 to get a prism for instance.
  30074. * The parameter `subdivisions` sets the number of rings along the cylinder height (positive integer, default 1).
  30075. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  30076. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  30077. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  30078. */
  30079. Mesh.CreateCylinder = function (name, height, diameterTop, diameterBottom, tessellation, subdivisions, scene, updatable, sideOrientation) {
  30080. if (scene === undefined || !(scene instanceof BABYLON.Scene)) {
  30081. if (scene !== undefined) {
  30082. sideOrientation = updatable || Mesh.DEFAULTSIDE;
  30083. updatable = scene;
  30084. }
  30085. scene = subdivisions;
  30086. subdivisions = 1;
  30087. }
  30088. var options = {
  30089. height: height,
  30090. diameterTop: diameterTop,
  30091. diameterBottom: diameterBottom,
  30092. tessellation: tessellation,
  30093. subdivisions: subdivisions,
  30094. sideOrientation: sideOrientation,
  30095. updatable: updatable
  30096. };
  30097. return BABYLON.MeshBuilder.CreateCylinder(name, options, scene);
  30098. };
  30099. // Torus (Code from SharpDX.org)
  30100. /**
  30101. * Creates a torus mesh.
  30102. * Please consider using the same method from the MeshBuilder class instead.
  30103. * The parameter `diameter` sets the diameter size (float) of the torus (default 1).
  30104. * The parameter `thickness` sets the diameter size of the tube of the torus (float, default 0.5).
  30105. * The parameter `tessellation` sets the number of torus sides (postive integer, default 16).
  30106. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  30107. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  30108. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  30109. */
  30110. Mesh.CreateTorus = function (name, diameter, thickness, tessellation, scene, updatable, sideOrientation) {
  30111. var options = {
  30112. diameter: diameter,
  30113. thickness: thickness,
  30114. tessellation: tessellation,
  30115. sideOrientation: sideOrientation,
  30116. updatable: updatable
  30117. };
  30118. return BABYLON.MeshBuilder.CreateTorus(name, options, scene);
  30119. };
  30120. /**
  30121. * Creates a torus knot mesh.
  30122. * Please consider using the same method from the MeshBuilder class instead.
  30123. * The parameter `radius` sets the global radius size (float) of the torus knot (default 2).
  30124. * The parameter `radialSegments` sets the number of sides on each tube segments (positive integer, default 32).
  30125. * The parameter `tubularSegments` sets the number of tubes to decompose the knot into (positive integer, default 32).
  30126. * The parameters `p` and `q` are the number of windings on each axis (positive integers, default 2 and 3).
  30127. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  30128. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  30129. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  30130. */
  30131. Mesh.CreateTorusKnot = function (name, radius, tube, radialSegments, tubularSegments, p, q, scene, updatable, sideOrientation) {
  30132. var options = {
  30133. radius: radius,
  30134. tube: tube,
  30135. radialSegments: radialSegments,
  30136. tubularSegments: tubularSegments,
  30137. p: p,
  30138. q: q,
  30139. sideOrientation: sideOrientation,
  30140. updatable: updatable
  30141. };
  30142. return BABYLON.MeshBuilder.CreateTorusKnot(name, options, scene);
  30143. };
  30144. /**
  30145. * Creates a line mesh.
  30146. * Please consider using the same method from the MeshBuilder class instead.
  30147. * 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.
  30148. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function.
  30149. * The parameter `points` is an array successive Vector3.
  30150. * 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
  30151. * When updating an instance, remember that only point positions can change, not the number of points.
  30152. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  30153. */
  30154. Mesh.CreateLines = function (name, points, scene, updatable, instance) {
  30155. if (scene === void 0) { scene = null; }
  30156. if (updatable === void 0) { updatable = false; }
  30157. if (instance === void 0) { instance = null; }
  30158. var options = {
  30159. points: points,
  30160. updatable: updatable,
  30161. instance: instance
  30162. };
  30163. return BABYLON.MeshBuilder.CreateLines(name, options, scene);
  30164. };
  30165. /**
  30166. * Creates a dashed line mesh.
  30167. * Please consider using the same method from the MeshBuilder class instead.
  30168. * 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.
  30169. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function.
  30170. * The parameter `points` is an array successive Vector3.
  30171. * The parameter `dashNb` is the intended total number of dashes (positive integer, default 200).
  30172. * The parameter `dashSize` is the size of the dashes relatively the dash number (positive float, default 3).
  30173. * The parameter `gapSize` is the size of the gap between two successive dashes relatively the dash number (positive float, default 1).
  30174. * 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
  30175. * When updating an instance, remember that only point positions can change, not the number of points.
  30176. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  30177. */
  30178. Mesh.CreateDashedLines = function (name, points, dashSize, gapSize, dashNb, scene, updatable, instance) {
  30179. if (scene === void 0) { scene = null; }
  30180. var options = {
  30181. points: points,
  30182. dashSize: dashSize,
  30183. gapSize: gapSize,
  30184. dashNb: dashNb,
  30185. updatable: updatable,
  30186. instance: instance
  30187. };
  30188. return BABYLON.MeshBuilder.CreateDashedLines(name, options, scene);
  30189. };
  30190. /**
  30191. * Creates a polygon mesh.
  30192. * Please consider using the same method from the MeshBuilder class instead.
  30193. * The polygon's shape will depend on the input parameters and is constructed parallel to a ground mesh.
  30194. * 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.
  30195. * You can set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  30196. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  30197. * Remember you can only change the shape positions, not their number when updating a polygon.
  30198. */
  30199. Mesh.CreatePolygon = function (name, shape, scene, holes, updatable, sideOrientation) {
  30200. var options = {
  30201. shape: shape,
  30202. holes: holes,
  30203. updatable: updatable,
  30204. sideOrientation: sideOrientation
  30205. };
  30206. return BABYLON.MeshBuilder.CreatePolygon(name, options, scene);
  30207. };
  30208. /**
  30209. * Creates an extruded polygon mesh, with depth in the Y direction.
  30210. * Please consider using the same method from the MeshBuilder class instead.
  30211. */
  30212. Mesh.ExtrudePolygon = function (name, shape, depth, scene, holes, updatable, sideOrientation) {
  30213. var options = {
  30214. shape: shape,
  30215. holes: holes,
  30216. depth: depth,
  30217. updatable: updatable,
  30218. sideOrientation: sideOrientation
  30219. };
  30220. return BABYLON.MeshBuilder.ExtrudePolygon(name, options, scene);
  30221. };
  30222. /**
  30223. * Creates an extruded shape mesh.
  30224. * 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.
  30225. * Please consider using the same method from the MeshBuilder class instead.
  30226. *
  30227. * Please read this full tutorial to understand how to design an extruded shape : http://doc.babylonjs.com/tutorials/Parametric_Shapes#extrusion
  30228. * 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
  30229. * extruded along the Z axis.
  30230. * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  30231. * 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.
  30232. * The parameter `scale` (float, default 1) is the value to scale the shape.
  30233. * 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
  30234. * 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
  30235. * Remember you can only change the shape or path point positions, not their number when updating an extruded shape.
  30236. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  30237. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  30238. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  30239. */
  30240. Mesh.ExtrudeShape = function (name, shape, path, scale, rotation, cap, scene, updatable, sideOrientation, instance) {
  30241. if (scene === void 0) { scene = null; }
  30242. var options = {
  30243. shape: shape,
  30244. path: path,
  30245. scale: scale,
  30246. rotation: rotation,
  30247. cap: (cap === 0) ? 0 : cap || Mesh.NO_CAP,
  30248. sideOrientation: sideOrientation,
  30249. instance: instance,
  30250. updatable: updatable
  30251. };
  30252. return BABYLON.MeshBuilder.ExtrudeShape(name, options, scene);
  30253. };
  30254. /**
  30255. * Creates an custom extruded shape mesh.
  30256. * 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.
  30257. * Please consider using the same method from the MeshBuilder class instead.
  30258. *
  30259. * Please read this full tutorial to understand how to design a custom extruded shape : http://doc.babylonjs.com/tutorials/Parametric_Shapes#extrusion
  30260. * 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
  30261. * extruded along the Z axis.
  30262. * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  30263. * 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
  30264. * and the distance of this point from the begining of the path :
  30265. * ```javascript
  30266. * var rotationFunction = function(i, distance) {
  30267. * // do things
  30268. * return rotationValue; }
  30269. * ```
  30270. * It must returns a float value that will be the rotation in radians applied to the shape on each path point.
  30271. * 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
  30272. * and the distance of this point from the begining of the path :
  30273. * ```javascript
  30274. * var scaleFunction = function(i, distance) {
  30275. * // do things
  30276. * return scaleValue;}
  30277. * ```
  30278. * It must returns a float value that will be the scale value applied to the shape on each path point.
  30279. * The parameter `ribbonClosePath` (boolean, default false) forces the extrusion underlying ribbon to close all the paths in its `pathArray`.
  30280. * The parameter `ribbonCloseArray` (boolean, default false) forces the extrusion underlying ribbon to close its `pathArray`.
  30281. * 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
  30282. * 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
  30283. * Remember you can only change the shape or path point positions, not their number when updating an extruded shape.
  30284. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  30285. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  30286. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  30287. */
  30288. Mesh.ExtrudeShapeCustom = function (name, shape, path, scaleFunction, rotationFunction, ribbonCloseArray, ribbonClosePath, cap, scene, updatable, sideOrientation, instance) {
  30289. var options = {
  30290. shape: shape,
  30291. path: path,
  30292. scaleFunction: scaleFunction,
  30293. rotationFunction: rotationFunction,
  30294. ribbonCloseArray: ribbonCloseArray,
  30295. ribbonClosePath: ribbonClosePath,
  30296. cap: (cap === 0) ? 0 : cap || Mesh.NO_CAP,
  30297. sideOrientation: sideOrientation,
  30298. instance: instance,
  30299. updatable: updatable
  30300. };
  30301. return BABYLON.MeshBuilder.ExtrudeShapeCustom(name, options, scene);
  30302. };
  30303. /**
  30304. * Creates lathe mesh.
  30305. * The lathe is a shape with a symetry axis : a 2D model shape is rotated around this axis to design the lathe.
  30306. * Please consider using the same method from the MeshBuilder class instead.
  30307. * 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
  30308. * rotated around the Y axis. It's usually a 2D shape, so the Vector3 z coordinates are often set to zero.
  30309. * The parameter `radius` (positive float, default 1) is the radius value of the lathe.
  30310. * The parameter `tessellation` (positive integer, default 64) is the side number of the lathe.
  30311. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  30312. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  30313. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  30314. */
  30315. Mesh.CreateLathe = function (name, shape, radius, tessellation, scene, updatable, sideOrientation) {
  30316. var options = {
  30317. shape: shape,
  30318. radius: radius,
  30319. tessellation: tessellation,
  30320. sideOrientation: sideOrientation,
  30321. updatable: updatable
  30322. };
  30323. return BABYLON.MeshBuilder.CreateLathe(name, options, scene);
  30324. };
  30325. /**
  30326. * Creates a plane mesh.
  30327. * Please consider using the same method from the MeshBuilder class instead.
  30328. * The parameter `size` sets the size (float) of both sides of the plane at once (default 1).
  30329. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  30330. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  30331. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  30332. */
  30333. Mesh.CreatePlane = function (name, size, scene, updatable, sideOrientation) {
  30334. var options = {
  30335. size: size,
  30336. width: size,
  30337. height: size,
  30338. sideOrientation: sideOrientation,
  30339. updatable: updatable
  30340. };
  30341. return BABYLON.MeshBuilder.CreatePlane(name, options, scene);
  30342. };
  30343. /**
  30344. * Creates a ground mesh.
  30345. * Please consider using the same method from the MeshBuilder class instead.
  30346. * The parameters `width` and `height` (floats, default 1) set the width and height sizes of the ground.
  30347. * The parameter `subdivisions` (positive integer) sets the number of subdivisions per side.
  30348. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  30349. */
  30350. Mesh.CreateGround = function (name, width, height, subdivisions, scene, updatable) {
  30351. var options = {
  30352. width: width,
  30353. height: height,
  30354. subdivisions: subdivisions,
  30355. updatable: updatable
  30356. };
  30357. return BABYLON.MeshBuilder.CreateGround(name, options, scene);
  30358. };
  30359. /**
  30360. * Creates a tiled ground mesh.
  30361. * Please consider using the same method from the MeshBuilder class instead.
  30362. * The parameters `xmin` and `xmax` (floats, default -1 and 1) set the ground minimum and maximum X coordinates.
  30363. * The parameters `zmin` and `zmax` (floats, default -1 and 1) set the ground minimum and maximum Z coordinates.
  30364. * The parameter `subdivisions` is a javascript object `{w: positive integer, h: positive integer}` (default `{w: 6, h: 6}`). `w` and `h` are the
  30365. * numbers of subdivisions on the ground width and height. Each subdivision is called a tile.
  30366. * The parameter `precision` is a javascript object `{w: positive integer, h: positive integer}` (default `{w: 2, h: 2}`). `w` and `h` are the
  30367. * numbers of subdivisions on the ground width and height of each tile.
  30368. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  30369. */
  30370. Mesh.CreateTiledGround = function (name, xmin, zmin, xmax, zmax, subdivisions, precision, scene, updatable) {
  30371. var options = {
  30372. xmin: xmin,
  30373. zmin: zmin,
  30374. xmax: xmax,
  30375. zmax: zmax,
  30376. subdivisions: subdivisions,
  30377. precision: precision,
  30378. updatable: updatable
  30379. };
  30380. return BABYLON.MeshBuilder.CreateTiledGround(name, options, scene);
  30381. };
  30382. /**
  30383. * Creates a ground mesh from a height map.
  30384. * tuto : http://doc.babylonjs.com/tutorials/14._Height_Map
  30385. * Please consider using the same method from the MeshBuilder class instead.
  30386. * The parameter `url` sets the URL of the height map image resource.
  30387. * The parameters `width` and `height` (positive floats, default 10) set the ground width and height sizes.
  30388. * The parameter `subdivisions` (positive integer, default 1) sets the number of subdivision per side.
  30389. * The parameter `minHeight` (float, default 0) is the minimum altitude on the ground.
  30390. * The parameter `maxHeight` (float, default 1) is the maximum altitude on the ground.
  30391. * 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).
  30392. * This function is passed the newly built mesh :
  30393. * ```javascript
  30394. * function(mesh) { // do things
  30395. * return; }
  30396. * ```
  30397. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  30398. */
  30399. Mesh.CreateGroundFromHeightMap = function (name, url, width, height, subdivisions, minHeight, maxHeight, scene, updatable, onReady) {
  30400. var options = {
  30401. width: width,
  30402. height: height,
  30403. subdivisions: subdivisions,
  30404. minHeight: minHeight,
  30405. maxHeight: maxHeight,
  30406. updatable: updatable,
  30407. onReady: onReady
  30408. };
  30409. return BABYLON.MeshBuilder.CreateGroundFromHeightMap(name, url, options, scene);
  30410. };
  30411. /**
  30412. * Creates a tube mesh.
  30413. * 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.
  30414. * Please consider using the same method from the MeshBuilder class instead.
  30415. * The parameter `path` is a required array of successive Vector3. It is the curve used as the axis of the tube.
  30416. * The parameter `radius` (positive float, default 1) sets the tube radius size.
  30417. * The parameter `tessellation` (positive float, default 64) is the number of sides on the tubular surface.
  30418. * The parameter `radiusFunction` (javascript function, default null) is a vanilla javascript function. If it is not null, it overwrittes the parameter `radius`.
  30419. * 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.
  30420. * It must return a radius value (positive float) :
  30421. * ```javascript
  30422. * var radiusFunction = function(i, distance) {
  30423. * // do things
  30424. * return radius; }
  30425. * ```
  30426. * 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
  30427. * 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
  30428. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  30429. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  30430. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  30431. */
  30432. Mesh.CreateTube = function (name, path, radius, tessellation, radiusFunction, cap, scene, updatable, sideOrientation, instance) {
  30433. var options = {
  30434. path: path,
  30435. radius: radius,
  30436. tessellation: tessellation,
  30437. radiusFunction: radiusFunction,
  30438. arc: 1,
  30439. cap: cap,
  30440. updatable: updatable,
  30441. sideOrientation: sideOrientation,
  30442. instance: instance
  30443. };
  30444. return BABYLON.MeshBuilder.CreateTube(name, options, scene);
  30445. };
  30446. /**
  30447. * Creates a polyhedron mesh.
  30448. * Please consider using the same method from the MeshBuilder class instead.
  30449. * 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
  30450. * to choose the wanted type.
  30451. * The parameter `size` (positive float, default 1) sets the polygon size.
  30452. * You can overwrite the `size` on each dimension bu using the parameters `sizeX`, `sizeY` or `sizeZ` (positive floats, default to `size` value).
  30453. * 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`.
  30454. * 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
  30455. * 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)`).
  30456. * 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
  30457. * 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.
  30458. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  30459. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  30460. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  30461. */
  30462. Mesh.CreatePolyhedron = function (name, options, scene) {
  30463. return BABYLON.MeshBuilder.CreatePolyhedron(name, options, scene);
  30464. };
  30465. /**
  30466. * Creates a sphere based upon an icosahedron with 20 triangular faces which can be subdivided.
  30467. * Please consider using the same method from the MeshBuilder class instead.
  30468. * The parameter `radius` sets the radius size (float) of the icosphere (default 1).
  30469. * 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`).
  30470. * The parameter `subdivisions` sets the number of subdivisions (postive integer, default 4). The more subdivisions, the more faces on the icosphere whatever its size.
  30471. * 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.
  30472. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  30473. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  30474. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  30475. */
  30476. Mesh.CreateIcoSphere = function (name, options, scene) {
  30477. return BABYLON.MeshBuilder.CreateIcoSphere(name, options, scene);
  30478. };
  30479. /**
  30480. * Creates a decal mesh.
  30481. * Please consider using the same method from the MeshBuilder class instead.
  30482. * 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.
  30483. * The parameter `position` (Vector3, default `(0, 0, 0)`) sets the position of the decal in World coordinates.
  30484. * The parameter `normal` (Vector3, default Vector3.Up) sets the normal of the mesh where the decal is applied onto in World coordinates.
  30485. * The parameter `size` (Vector3, default `(1, 1, 1)`) sets the decal scaling.
  30486. * The parameter `angle` (float in radian, default 0) sets the angle to rotate the decal.
  30487. */
  30488. Mesh.CreateDecal = function (name, sourceMesh, position, normal, size, angle) {
  30489. var options = {
  30490. position: position,
  30491. normal: normal,
  30492. size: size,
  30493. angle: angle
  30494. };
  30495. return BABYLON.MeshBuilder.CreateDecal(name, sourceMesh, options);
  30496. };
  30497. // Skeletons
  30498. /**
  30499. * @returns original positions used for CPU skinning. Useful for integrating Morphing with skeletons in same mesh.
  30500. */
  30501. Mesh.prototype.setPositionsForCPUSkinning = function () {
  30502. if (!this._sourcePositions) {
  30503. var source = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  30504. if (!source) {
  30505. return this._sourcePositions;
  30506. }
  30507. this._sourcePositions = new Float32Array(source);
  30508. if (!this.isVertexBufferUpdatable(BABYLON.VertexBuffer.PositionKind)) {
  30509. this.setVerticesData(BABYLON.VertexBuffer.PositionKind, source, true);
  30510. }
  30511. }
  30512. return this._sourcePositions;
  30513. };
  30514. /**
  30515. * @returns original normals used for CPU skinning. Useful for integrating Morphing with skeletons in same mesh.
  30516. */
  30517. Mesh.prototype.setNormalsForCPUSkinning = function () {
  30518. if (!this._sourceNormals) {
  30519. var source = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  30520. if (!source) {
  30521. return this._sourceNormals;
  30522. }
  30523. this._sourceNormals = new Float32Array(source);
  30524. if (!this.isVertexBufferUpdatable(BABYLON.VertexBuffer.NormalKind)) {
  30525. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, source, true);
  30526. }
  30527. }
  30528. return this._sourceNormals;
  30529. };
  30530. /**
  30531. * Updates the vertex buffer by applying transformation from the bones.
  30532. * Returns the Mesh.
  30533. *
  30534. * @param {skeleton} skeleton to apply
  30535. */
  30536. Mesh.prototype.applySkeleton = function (skeleton) {
  30537. if (!this.geometry) {
  30538. return this;
  30539. }
  30540. if (this.geometry._softwareSkinningRenderId == this.getScene().getRenderId()) {
  30541. return this;
  30542. }
  30543. this.geometry._softwareSkinningRenderId = this.getScene().getRenderId();
  30544. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  30545. return this;
  30546. }
  30547. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  30548. return this;
  30549. }
  30550. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  30551. return this;
  30552. }
  30553. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  30554. return this;
  30555. }
  30556. if (!this._sourcePositions) {
  30557. var submeshes = this.subMeshes.slice();
  30558. this.setPositionsForCPUSkinning();
  30559. this.subMeshes = submeshes;
  30560. }
  30561. if (!this._sourceNormals) {
  30562. this.setNormalsForCPUSkinning();
  30563. }
  30564. // positionsData checks for not being Float32Array will only pass at most once
  30565. var positionsData = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  30566. if (!positionsData) {
  30567. return this;
  30568. }
  30569. if (!(positionsData instanceof Float32Array)) {
  30570. positionsData = new Float32Array(positionsData);
  30571. }
  30572. // normalsData checks for not being Float32Array will only pass at most once
  30573. var normalsData = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  30574. if (!normalsData) {
  30575. return this;
  30576. }
  30577. if (!(normalsData instanceof Float32Array)) {
  30578. normalsData = new Float32Array(normalsData);
  30579. }
  30580. var matricesIndicesData = this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind);
  30581. var matricesWeightsData = this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind);
  30582. if (!matricesWeightsData || !matricesIndicesData) {
  30583. return this;
  30584. }
  30585. var needExtras = this.numBoneInfluencers > 4;
  30586. var matricesIndicesExtraData = needExtras ? this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind) : null;
  30587. var matricesWeightsExtraData = needExtras ? this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind) : null;
  30588. var skeletonMatrices = skeleton.getTransformMatrices(this);
  30589. var tempVector3 = BABYLON.Vector3.Zero();
  30590. var finalMatrix = new BABYLON.Matrix();
  30591. var tempMatrix = new BABYLON.Matrix();
  30592. var matWeightIdx = 0;
  30593. var inf;
  30594. for (var index = 0; index < positionsData.length; index += 3, matWeightIdx += 4) {
  30595. var weight;
  30596. for (inf = 0; inf < 4; inf++) {
  30597. weight = matricesWeightsData[matWeightIdx + inf];
  30598. if (weight > 0) {
  30599. BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, Math.floor(matricesIndicesData[matWeightIdx + inf] * 16), weight, tempMatrix);
  30600. finalMatrix.addToSelf(tempMatrix);
  30601. }
  30602. else
  30603. break;
  30604. }
  30605. if (needExtras) {
  30606. for (inf = 0; inf < 4; inf++) {
  30607. weight = matricesWeightsExtraData[matWeightIdx + inf];
  30608. if (weight > 0) {
  30609. BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, Math.floor(matricesIndicesExtraData[matWeightIdx + inf] * 16), weight, tempMatrix);
  30610. finalMatrix.addToSelf(tempMatrix);
  30611. }
  30612. else
  30613. break;
  30614. }
  30615. }
  30616. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(this._sourcePositions[index], this._sourcePositions[index + 1], this._sourcePositions[index + 2], finalMatrix, tempVector3);
  30617. tempVector3.toArray(positionsData, index);
  30618. BABYLON.Vector3.TransformNormalFromFloatsToRef(this._sourceNormals[index], this._sourceNormals[index + 1], this._sourceNormals[index + 2], finalMatrix, tempVector3);
  30619. tempVector3.toArray(normalsData, index);
  30620. finalMatrix.reset();
  30621. }
  30622. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positionsData);
  30623. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normalsData);
  30624. return this;
  30625. };
  30626. // Tools
  30627. /**
  30628. * Returns an object `{min:` Vector3`, max:` Vector3`}`
  30629. * This min and max Vector3 are the minimum and maximum vectors of each mesh bounding box from the passed array, in the World system
  30630. */
  30631. Mesh.MinMax = function (meshes) {
  30632. var minVector = null;
  30633. var maxVector = null;
  30634. meshes.forEach(function (mesh, index, array) {
  30635. var boundingInfo = mesh.getBoundingInfo();
  30636. var boundingBox = boundingInfo.boundingBox;
  30637. if (!minVector || !maxVector) {
  30638. minVector = boundingBox.minimumWorld;
  30639. maxVector = boundingBox.maximumWorld;
  30640. }
  30641. else {
  30642. minVector.minimizeInPlace(boundingBox.minimumWorld);
  30643. maxVector.maximizeInPlace(boundingBox.maximumWorld);
  30644. }
  30645. });
  30646. if (!minVector || !maxVector) {
  30647. return {
  30648. min: BABYLON.Vector3.Zero(),
  30649. max: BABYLON.Vector3.Zero()
  30650. };
  30651. }
  30652. return {
  30653. min: minVector,
  30654. max: maxVector
  30655. };
  30656. };
  30657. /**
  30658. * Returns a Vector3, the center of the `{min:` Vector3`, max:` Vector3`}` or the center of MinMax vector3 computed from a mesh array.
  30659. */
  30660. Mesh.Center = function (meshesOrMinMaxVector) {
  30661. var minMaxVector = (meshesOrMinMaxVector instanceof Array) ? Mesh.MinMax(meshesOrMinMaxVector) : meshesOrMinMaxVector;
  30662. return BABYLON.Vector3.Center(minMaxVector.min, minMaxVector.max);
  30663. };
  30664. /**
  30665. * Merge the array of meshes into a single mesh for performance reasons.
  30666. * @param {Array<Mesh>} meshes - The vertices source. They should all be of the same material. Entries can empty
  30667. * @param {boolean} disposeSource - When true (default), dispose of the vertices from the source meshes
  30668. * @param {boolean} allow32BitsIndices - When the sum of the vertices > 64k, this must be set to true.
  30669. * @param {Mesh} meshSubclass - When set, vertices inserted into this Mesh. Meshes can then be merged into a Mesh sub-class.
  30670. * @param {boolean} subdivideWithSubMeshes - When true (false default), subdivide mesh to his subMesh array with meshes source.
  30671. */
  30672. Mesh.MergeMeshes = function (meshes, disposeSource, allow32BitsIndices, meshSubclass, subdivideWithSubMeshes) {
  30673. if (disposeSource === void 0) { disposeSource = true; }
  30674. var index;
  30675. if (!allow32BitsIndices) {
  30676. var totalVertices = 0;
  30677. // Counting vertices
  30678. for (index = 0; index < meshes.length; index++) {
  30679. if (meshes[index]) {
  30680. totalVertices += meshes[index].getTotalVertices();
  30681. if (totalVertices > 65536) {
  30682. BABYLON.Tools.Warn("Cannot merge meshes because resulting mesh will have more than 65536 vertices. Please use allow32BitsIndices = true to use 32 bits indices");
  30683. return null;
  30684. }
  30685. }
  30686. }
  30687. }
  30688. // Merge
  30689. var vertexData = null;
  30690. var otherVertexData;
  30691. var indiceArray = new Array();
  30692. var source = null;
  30693. for (index = 0; index < meshes.length; index++) {
  30694. if (meshes[index]) {
  30695. meshes[index].computeWorldMatrix(true);
  30696. otherVertexData = BABYLON.VertexData.ExtractFromMesh(meshes[index], true);
  30697. otherVertexData.transform(meshes[index].getWorldMatrix());
  30698. if (vertexData) {
  30699. vertexData.merge(otherVertexData);
  30700. }
  30701. else {
  30702. vertexData = otherVertexData;
  30703. source = meshes[index];
  30704. }
  30705. if (subdivideWithSubMeshes) {
  30706. indiceArray.push(meshes[index].getTotalIndices());
  30707. }
  30708. }
  30709. }
  30710. source = source;
  30711. if (!meshSubclass) {
  30712. meshSubclass = new Mesh(source.name + "_merged", source.getScene());
  30713. }
  30714. vertexData.applyToMesh(meshSubclass);
  30715. // Setting properties
  30716. meshSubclass.material = source.material;
  30717. meshSubclass.checkCollisions = source.checkCollisions;
  30718. // Cleaning
  30719. if (disposeSource) {
  30720. for (index = 0; index < meshes.length; index++) {
  30721. if (meshes[index]) {
  30722. meshes[index].dispose();
  30723. }
  30724. }
  30725. }
  30726. // Subdivide
  30727. if (subdivideWithSubMeshes) {
  30728. //-- Suppresions du submesh global
  30729. meshSubclass.releaseSubMeshes();
  30730. index = 0;
  30731. var offset = 0;
  30732. //-- aplique la subdivision en fonction du tableau d'indices
  30733. while (index < indiceArray.length) {
  30734. BABYLON.SubMesh.CreateFromIndices(0, offset, indiceArray[index], meshSubclass);
  30735. offset += indiceArray[index];
  30736. index++;
  30737. }
  30738. }
  30739. return meshSubclass;
  30740. };
  30741. // Consts
  30742. Mesh._FRONTSIDE = 0;
  30743. Mesh._BACKSIDE = 1;
  30744. Mesh._DOUBLESIDE = 2;
  30745. Mesh._DEFAULTSIDE = 0;
  30746. Mesh._NO_CAP = 0;
  30747. Mesh._CAP_START = 1;
  30748. Mesh._CAP_END = 2;
  30749. Mesh._CAP_ALL = 3;
  30750. return Mesh;
  30751. }(BABYLON.AbstractMesh));
  30752. BABYLON.Mesh = Mesh;
  30753. })(BABYLON || (BABYLON = {}));
  30754. //# sourceMappingURL=babylon.mesh.js.map
  30755. "use strict";
  30756. var BABYLON;
  30757. (function (BABYLON) {
  30758. var BaseSubMesh = /** @class */ (function () {
  30759. function BaseSubMesh() {
  30760. }
  30761. Object.defineProperty(BaseSubMesh.prototype, "effect", {
  30762. get: function () {
  30763. return this._materialEffect;
  30764. },
  30765. enumerable: true,
  30766. configurable: true
  30767. });
  30768. BaseSubMesh.prototype.setEffect = function (effect, defines) {
  30769. if (defines === void 0) { defines = null; }
  30770. if (this._materialEffect === effect) {
  30771. if (!effect) {
  30772. this._materialDefines = null;
  30773. }
  30774. return;
  30775. }
  30776. this._materialDefines = defines;
  30777. this._materialEffect = effect;
  30778. };
  30779. return BaseSubMesh;
  30780. }());
  30781. BABYLON.BaseSubMesh = BaseSubMesh;
  30782. var SubMesh = /** @class */ (function (_super) {
  30783. __extends(SubMesh, _super);
  30784. function SubMesh(materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh, renderingMesh, createBoundingBox) {
  30785. if (createBoundingBox === void 0) { createBoundingBox = true; }
  30786. var _this = _super.call(this) || this;
  30787. _this.materialIndex = materialIndex;
  30788. _this.verticesStart = verticesStart;
  30789. _this.verticesCount = verticesCount;
  30790. _this.indexStart = indexStart;
  30791. _this.indexCount = indexCount;
  30792. _this._renderId = 0;
  30793. _this._mesh = mesh;
  30794. _this._renderingMesh = renderingMesh || mesh;
  30795. mesh.subMeshes.push(_this);
  30796. _this._trianglePlanes = [];
  30797. _this._id = mesh.subMeshes.length - 1;
  30798. if (createBoundingBox) {
  30799. _this.refreshBoundingInfo();
  30800. mesh.computeWorldMatrix(true);
  30801. }
  30802. return _this;
  30803. }
  30804. SubMesh.AddToMesh = function (materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh, renderingMesh, createBoundingBox) {
  30805. if (createBoundingBox === void 0) { createBoundingBox = true; }
  30806. return new SubMesh(materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh, renderingMesh, createBoundingBox);
  30807. };
  30808. Object.defineProperty(SubMesh.prototype, "IsGlobal", {
  30809. get: function () {
  30810. return (this.verticesStart === 0 && this.verticesCount == this._mesh.getTotalVertices());
  30811. },
  30812. enumerable: true,
  30813. configurable: true
  30814. });
  30815. /**
  30816. * Returns the submesh BoudingInfo object.
  30817. */
  30818. SubMesh.prototype.getBoundingInfo = function () {
  30819. if (this.IsGlobal) {
  30820. return this._mesh.getBoundingInfo();
  30821. }
  30822. return this._boundingInfo;
  30823. };
  30824. /**
  30825. * Sets the submesh BoundingInfo.
  30826. * Return the SubMesh.
  30827. */
  30828. SubMesh.prototype.setBoundingInfo = function (boundingInfo) {
  30829. this._boundingInfo = boundingInfo;
  30830. return this;
  30831. };
  30832. /**
  30833. * Returns the mesh of the current submesh.
  30834. */
  30835. SubMesh.prototype.getMesh = function () {
  30836. return this._mesh;
  30837. };
  30838. /**
  30839. * Returns the rendering mesh of the submesh.
  30840. */
  30841. SubMesh.prototype.getRenderingMesh = function () {
  30842. return this._renderingMesh;
  30843. };
  30844. /**
  30845. * Returns the submesh material.
  30846. */
  30847. SubMesh.prototype.getMaterial = function () {
  30848. var rootMaterial = this._renderingMesh.material;
  30849. if (rootMaterial === null || rootMaterial === undefined) {
  30850. return this._mesh.getScene().defaultMaterial;
  30851. }
  30852. else if (rootMaterial.getSubMaterial) {
  30853. var multiMaterial = rootMaterial;
  30854. var effectiveMaterial = multiMaterial.getSubMaterial(this.materialIndex);
  30855. if (this._currentMaterial !== effectiveMaterial) {
  30856. this._currentMaterial = effectiveMaterial;
  30857. this._materialDefines = null;
  30858. }
  30859. return effectiveMaterial;
  30860. }
  30861. return rootMaterial;
  30862. };
  30863. // Methods
  30864. /**
  30865. * Sets a new updated BoundingInfo object to the submesh.
  30866. * Returns the SubMesh.
  30867. */
  30868. SubMesh.prototype.refreshBoundingInfo = function () {
  30869. this._lastColliderWorldVertices = null;
  30870. if (this.IsGlobal || !this._renderingMesh || !this._renderingMesh.geometry) {
  30871. return this;
  30872. }
  30873. var data = this._renderingMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  30874. if (!data) {
  30875. this._boundingInfo = this._mesh.getBoundingInfo();
  30876. return this;
  30877. }
  30878. var indices = this._renderingMesh.getIndices();
  30879. var extend;
  30880. //is this the only submesh?
  30881. if (this.indexStart === 0 && this.indexCount === indices.length) {
  30882. var boundingInfo = this._renderingMesh.getBoundingInfo();
  30883. //the rendering mesh's bounding info can be used, it is the standard submesh for all indices.
  30884. extend = { minimum: boundingInfo.minimum.clone(), maximum: boundingInfo.maximum.clone() };
  30885. }
  30886. else {
  30887. extend = BABYLON.Tools.ExtractMinAndMaxIndexed(data, indices, this.indexStart, this.indexCount, this._renderingMesh.geometry.boundingBias);
  30888. }
  30889. this._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  30890. return this;
  30891. };
  30892. SubMesh.prototype._checkCollision = function (collider) {
  30893. var boundingInfo = this.getBoundingInfo();
  30894. return boundingInfo._checkCollision(collider);
  30895. };
  30896. /**
  30897. * Updates the submesh BoundingInfo.
  30898. * Returns the Submesh.
  30899. */
  30900. SubMesh.prototype.updateBoundingInfo = function (world) {
  30901. var boundingInfo = this.getBoundingInfo();
  30902. if (!boundingInfo) {
  30903. this.refreshBoundingInfo();
  30904. boundingInfo = this.getBoundingInfo();
  30905. }
  30906. boundingInfo.update(world);
  30907. return this;
  30908. };
  30909. /**
  30910. * True is the submesh bounding box intersects the frustum defined by the passed array of planes.
  30911. * Boolean returned.
  30912. */
  30913. SubMesh.prototype.isInFrustum = function (frustumPlanes) {
  30914. var boundingInfo = this.getBoundingInfo();
  30915. if (!boundingInfo) {
  30916. return false;
  30917. }
  30918. return boundingInfo.isInFrustum(frustumPlanes);
  30919. };
  30920. /**
  30921. * True is the submesh bounding box is completely inside the frustum defined by the passed array of planes.
  30922. * Boolean returned.
  30923. */
  30924. SubMesh.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  30925. var boundingInfo = this.getBoundingInfo();
  30926. if (!boundingInfo) {
  30927. return false;
  30928. }
  30929. return boundingInfo.isCompletelyInFrustum(frustumPlanes);
  30930. };
  30931. /**
  30932. * Renders the submesh.
  30933. * Returns it.
  30934. */
  30935. SubMesh.prototype.render = function (enableAlphaMode) {
  30936. this._renderingMesh.render(this, enableAlphaMode);
  30937. return this;
  30938. };
  30939. /**
  30940. * Returns a new Index Buffer.
  30941. * Type returned : WebGLBuffer.
  30942. */
  30943. SubMesh.prototype.getLinesIndexBuffer = function (indices, engine) {
  30944. if (!this._linesIndexBuffer) {
  30945. var linesIndices = [];
  30946. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 3) {
  30947. linesIndices.push(indices[index], indices[index + 1], indices[index + 1], indices[index + 2], indices[index + 2], indices[index]);
  30948. }
  30949. this._linesIndexBuffer = engine.createIndexBuffer(linesIndices);
  30950. this.linesIndexCount = linesIndices.length;
  30951. }
  30952. return this._linesIndexBuffer;
  30953. };
  30954. /**
  30955. * True is the passed Ray intersects the submesh bounding box.
  30956. * Boolean returned.
  30957. */
  30958. SubMesh.prototype.canIntersects = function (ray) {
  30959. var boundingInfo = this.getBoundingInfo();
  30960. if (!boundingInfo) {
  30961. return false;
  30962. }
  30963. return ray.intersectsBox(boundingInfo.boundingBox);
  30964. };
  30965. /**
  30966. * Returns an object IntersectionInfo.
  30967. */
  30968. SubMesh.prototype.intersects = function (ray, positions, indices, fastCheck) {
  30969. var intersectInfo = null;
  30970. var material = this.getMaterial();
  30971. if (!material) {
  30972. return null;
  30973. }
  30974. switch (material.fillMode) {
  30975. case BABYLON.Material.PointListDrawMode:
  30976. case BABYLON.Material.LineListDrawMode:
  30977. case BABYLON.Material.LineLoopDrawMode:
  30978. case BABYLON.Material.LineStripDrawMode:
  30979. case BABYLON.Material.TriangleFanDrawMode:
  30980. case BABYLON.Material.TriangleStripDrawMode:
  30981. return null;
  30982. }
  30983. // LineMesh first as it's also a Mesh...
  30984. if (BABYLON.LinesMesh && this._mesh instanceof BABYLON.LinesMesh) {
  30985. var lineMesh = this._mesh;
  30986. // Line test
  30987. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 2) {
  30988. var p0 = positions[indices[index]];
  30989. var p1 = positions[indices[index + 1]];
  30990. var length = ray.intersectionSegment(p0, p1, lineMesh.intersectionThreshold);
  30991. if (length < 0) {
  30992. continue;
  30993. }
  30994. if (fastCheck || !intersectInfo || length < intersectInfo.distance) {
  30995. intersectInfo = new BABYLON.IntersectionInfo(null, null, length);
  30996. if (fastCheck) {
  30997. break;
  30998. }
  30999. }
  31000. }
  31001. }
  31002. else {
  31003. // Triangles test
  31004. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 3) {
  31005. var p0 = positions[indices[index]];
  31006. var p1 = positions[indices[index + 1]];
  31007. var p2 = positions[indices[index + 2]];
  31008. var currentIntersectInfo = ray.intersectsTriangle(p0, p1, p2);
  31009. if (currentIntersectInfo) {
  31010. if (currentIntersectInfo.distance < 0) {
  31011. continue;
  31012. }
  31013. if (fastCheck || !intersectInfo || currentIntersectInfo.distance < intersectInfo.distance) {
  31014. intersectInfo = currentIntersectInfo;
  31015. intersectInfo.faceId = index / 3;
  31016. if (fastCheck) {
  31017. break;
  31018. }
  31019. }
  31020. }
  31021. }
  31022. }
  31023. return intersectInfo;
  31024. };
  31025. SubMesh.prototype._rebuild = function () {
  31026. if (this._linesIndexBuffer) {
  31027. this._linesIndexBuffer = null;
  31028. }
  31029. };
  31030. // Clone
  31031. /**
  31032. * Creates a new Submesh from the passed Mesh.
  31033. */
  31034. SubMesh.prototype.clone = function (newMesh, newRenderingMesh) {
  31035. var result = new SubMesh(this.materialIndex, this.verticesStart, this.verticesCount, this.indexStart, this.indexCount, newMesh, newRenderingMesh, false);
  31036. if (!this.IsGlobal) {
  31037. var boundingInfo = this.getBoundingInfo();
  31038. if (!boundingInfo) {
  31039. return result;
  31040. }
  31041. result._boundingInfo = new BABYLON.BoundingInfo(boundingInfo.minimum, boundingInfo.maximum);
  31042. }
  31043. return result;
  31044. };
  31045. // Dispose
  31046. /**
  31047. * Disposes the Submesh.
  31048. * Returns nothing.
  31049. */
  31050. SubMesh.prototype.dispose = function () {
  31051. if (this._linesIndexBuffer) {
  31052. this._mesh.getScene().getEngine()._releaseBuffer(this._linesIndexBuffer);
  31053. this._linesIndexBuffer = null;
  31054. }
  31055. // Remove from mesh
  31056. var index = this._mesh.subMeshes.indexOf(this);
  31057. this._mesh.subMeshes.splice(index, 1);
  31058. };
  31059. // Statics
  31060. /**
  31061. * Creates a new Submesh from the passed parameters :
  31062. * - materialIndex (integer) : the index of the main mesh material.
  31063. * - startIndex (integer) : the index where to start the copy in the mesh indices array.
  31064. * - indexCount (integer) : the number of indices to copy then from the startIndex.
  31065. * - mesh (Mesh) : the main mesh to create the submesh from.
  31066. * - renderingMesh (optional Mesh) : rendering mesh.
  31067. */
  31068. SubMesh.CreateFromIndices = function (materialIndex, startIndex, indexCount, mesh, renderingMesh) {
  31069. var minVertexIndex = Number.MAX_VALUE;
  31070. var maxVertexIndex = -Number.MAX_VALUE;
  31071. renderingMesh = (renderingMesh || mesh);
  31072. var indices = renderingMesh.getIndices();
  31073. for (var index = startIndex; index < startIndex + indexCount; index++) {
  31074. var vertexIndex = indices[index];
  31075. if (vertexIndex < minVertexIndex)
  31076. minVertexIndex = vertexIndex;
  31077. if (vertexIndex > maxVertexIndex)
  31078. maxVertexIndex = vertexIndex;
  31079. }
  31080. return new SubMesh(materialIndex, minVertexIndex, maxVertexIndex - minVertexIndex + 1, startIndex, indexCount, mesh, renderingMesh);
  31081. };
  31082. return SubMesh;
  31083. }(BaseSubMesh));
  31084. BABYLON.SubMesh = SubMesh;
  31085. })(BABYLON || (BABYLON = {}));
  31086. //# sourceMappingURL=babylon.subMesh.js.map
  31087. "use strict";
  31088. var __assign = (this && this.__assign) || Object.assign || function(t) {
  31089. for (var s, i = 1, n = arguments.length; i < n; i++) {
  31090. s = arguments[i];
  31091. for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
  31092. t[p] = s[p];
  31093. }
  31094. return t;
  31095. };
  31096. var BABYLON;
  31097. (function (BABYLON) {
  31098. /**
  31099. * Manages the defines for the Material.
  31100. */
  31101. var MaterialDefines = /** @class */ (function () {
  31102. function MaterialDefines() {
  31103. this._isDirty = true;
  31104. this._areLightsDirty = true;
  31105. this._areAttributesDirty = true;
  31106. this._areTexturesDirty = true;
  31107. this._areFresnelDirty = true;
  31108. this._areMiscDirty = true;
  31109. this._areImageProcessingDirty = true;
  31110. this._normals = false;
  31111. this._uvs = false;
  31112. this._needNormals = false;
  31113. this._needUVs = false;
  31114. }
  31115. Object.defineProperty(MaterialDefines.prototype, "isDirty", {
  31116. /**
  31117. * Specifies if the material needs to be re-calculated.
  31118. */
  31119. get: function () {
  31120. return this._isDirty;
  31121. },
  31122. enumerable: true,
  31123. configurable: true
  31124. });
  31125. /**
  31126. * Marks the material to indicate that it has been re-calculated.
  31127. */
  31128. MaterialDefines.prototype.markAsProcessed = function () {
  31129. this._isDirty = false;
  31130. this._areAttributesDirty = false;
  31131. this._areTexturesDirty = false;
  31132. this._areFresnelDirty = false;
  31133. this._areLightsDirty = false;
  31134. this._areMiscDirty = false;
  31135. this._areImageProcessingDirty = false;
  31136. };
  31137. /**
  31138. * Marks the material to indicate that it needs to be re-calculated.
  31139. */
  31140. MaterialDefines.prototype.markAsUnprocessed = function () {
  31141. this._isDirty = true;
  31142. };
  31143. /**
  31144. * Marks the material to indicate all of its defines need to be re-calculated.
  31145. */
  31146. MaterialDefines.prototype.markAllAsDirty = function () {
  31147. this._areTexturesDirty = true;
  31148. this._areAttributesDirty = true;
  31149. this._areLightsDirty = true;
  31150. this._areFresnelDirty = true;
  31151. this._areMiscDirty = true;
  31152. this._areImageProcessingDirty = true;
  31153. this._isDirty = true;
  31154. };
  31155. /**
  31156. * Marks the material to indicate that image processing needs to be re-calculated.
  31157. */
  31158. MaterialDefines.prototype.markAsImageProcessingDirty = function () {
  31159. this._areImageProcessingDirty = true;
  31160. this._isDirty = true;
  31161. };
  31162. /**
  31163. * Marks the material to indicate the lights need to be re-calculated.
  31164. */
  31165. MaterialDefines.prototype.markAsLightDirty = function () {
  31166. this._areLightsDirty = true;
  31167. this._isDirty = true;
  31168. };
  31169. /**
  31170. * Marks the attribute state as changed.
  31171. */
  31172. MaterialDefines.prototype.markAsAttributesDirty = function () {
  31173. this._areAttributesDirty = true;
  31174. this._isDirty = true;
  31175. };
  31176. /**
  31177. * Marks the texture state as changed.
  31178. */
  31179. MaterialDefines.prototype.markAsTexturesDirty = function () {
  31180. this._areTexturesDirty = true;
  31181. this._isDirty = true;
  31182. };
  31183. /**
  31184. * Marks the fresnel state as changed.
  31185. */
  31186. MaterialDefines.prototype.markAsFresnelDirty = function () {
  31187. this._areFresnelDirty = true;
  31188. this._isDirty = true;
  31189. };
  31190. /**
  31191. * Marks the misc state as changed.
  31192. */
  31193. MaterialDefines.prototype.markAsMiscDirty = function () {
  31194. this._areMiscDirty = true;
  31195. this._isDirty = true;
  31196. };
  31197. /**
  31198. * Rebuilds the material defines.
  31199. */
  31200. MaterialDefines.prototype.rebuild = function () {
  31201. if (this._keys) {
  31202. delete this._keys;
  31203. }
  31204. this._keys = [];
  31205. for (var _i = 0, _a = Object.keys(this); _i < _a.length; _i++) {
  31206. var key = _a[_i];
  31207. if (key[0] === "_") {
  31208. continue;
  31209. }
  31210. this._keys.push(key);
  31211. }
  31212. };
  31213. /**
  31214. * Specifies if two material defines are equal.
  31215. * @param other - A material define instance to compare to.
  31216. * @returns - Boolean indicating if the material defines are equal (true) or not (false).
  31217. */
  31218. MaterialDefines.prototype.isEqual = function (other) {
  31219. if (this._keys.length !== other._keys.length) {
  31220. return false;
  31221. }
  31222. for (var index = 0; index < this._keys.length; index++) {
  31223. var prop = this._keys[index];
  31224. if (this[prop] !== other[prop]) {
  31225. return false;
  31226. }
  31227. }
  31228. return true;
  31229. };
  31230. /**
  31231. * Clones this instance's defines to another instance.
  31232. * @param other - material defines to clone values to.
  31233. */
  31234. MaterialDefines.prototype.cloneTo = function (other) {
  31235. if (this._keys.length !== other._keys.length) {
  31236. other._keys = this._keys.slice(0);
  31237. }
  31238. for (var index = 0; index < this._keys.length; index++) {
  31239. var prop = this._keys[index];
  31240. other[prop] = this[prop];
  31241. }
  31242. };
  31243. /**
  31244. * Resets the material define values.
  31245. */
  31246. MaterialDefines.prototype.reset = function () {
  31247. for (var index = 0; index < this._keys.length; index++) {
  31248. var prop = this._keys[index];
  31249. var type = typeof this[prop];
  31250. switch (type) {
  31251. case "number":
  31252. this[prop] = 0;
  31253. break;
  31254. case "string":
  31255. this[prop] = "";
  31256. break;
  31257. default:
  31258. this[prop] = false;
  31259. break;
  31260. }
  31261. }
  31262. };
  31263. /**
  31264. * Converts the material define values to a string.
  31265. * @returns - String of material define information.
  31266. */
  31267. MaterialDefines.prototype.toString = function () {
  31268. var result = "";
  31269. for (var index = 0; index < this._keys.length; index++) {
  31270. var prop = this._keys[index];
  31271. var value = this[prop];
  31272. var type = typeof value;
  31273. switch (type) {
  31274. case "number":
  31275. case "string":
  31276. result += "#define " + prop + " " + value + "\n";
  31277. break;
  31278. default:
  31279. if (value) {
  31280. result += "#define " + prop + "\n";
  31281. }
  31282. break;
  31283. }
  31284. }
  31285. return result;
  31286. };
  31287. return MaterialDefines;
  31288. }());
  31289. BABYLON.MaterialDefines = MaterialDefines;
  31290. /**
  31291. * This offers the main features of a material in BJS.
  31292. */
  31293. var Material = /** @class */ (function () {
  31294. /**
  31295. * Creates a material instance.
  31296. * @param name - The name of the material.
  31297. * @param scene - The BJS scene to reference.
  31298. * @param doNotAdd - Specifies if the material should be added to the scene.
  31299. */
  31300. function Material(name, scene, doNotAdd) {
  31301. /**
  31302. * Specifies if the ready state should be checked on each call.
  31303. */
  31304. this.checkReadyOnEveryCall = false;
  31305. /**
  31306. * Specifies if the ready state should be checked once.
  31307. */
  31308. this.checkReadyOnlyOnce = false;
  31309. /**
  31310. * The state of the material.
  31311. */
  31312. this.state = "";
  31313. /**
  31314. * The alpha value of the material.
  31315. */
  31316. this._alpha = 1.0;
  31317. /**
  31318. * Specifies if back face culling is enabled.
  31319. */
  31320. this._backFaceCulling = true;
  31321. /**
  31322. * Specifies if the material should be serialized.
  31323. */
  31324. this.doNotSerialize = false;
  31325. /**
  31326. * Specifies if the effect should be stored on sub meshes.
  31327. */
  31328. this.storeEffectOnSubMeshes = false;
  31329. /**
  31330. * An event triggered when the material is disposed.
  31331. */
  31332. this.onDisposeObservable = new BABYLON.Observable();
  31333. /**
  31334. * An event triggered when the material is bound.
  31335. */
  31336. this.onBindObservable = new BABYLON.Observable();
  31337. /**
  31338. * An event triggered when the material is unbound.
  31339. */
  31340. this.onUnBindObservable = new BABYLON.Observable();
  31341. /**
  31342. * Stores the value of the alpha mode.
  31343. */
  31344. this._alphaMode = BABYLON.Engine.ALPHA_COMBINE;
  31345. /**
  31346. * Stores the state of the need depth pre-pass value.
  31347. */
  31348. this._needDepthPrePass = false;
  31349. /**
  31350. * Specifies if depth writing should be disabled.
  31351. */
  31352. this.disableDepthWrite = false;
  31353. /**
  31354. * Specifies if depth writing should be forced.
  31355. */
  31356. this.forceDepthWrite = false;
  31357. /**
  31358. * Specifies if there should be a separate pass for culling.
  31359. */
  31360. this.separateCullingPass = false;
  31361. /**
  31362. * Stores the state specifing if fog should be enabled.
  31363. */
  31364. this._fogEnabled = true;
  31365. /**
  31366. * Stores the size of points.
  31367. */
  31368. this.pointSize = 1.0;
  31369. /**
  31370. * Stores the z offset value.
  31371. */
  31372. this.zOffset = 0;
  31373. /**
  31374. * Specifies if the material was previously ready.
  31375. */
  31376. this._wasPreviouslyReady = false;
  31377. /**
  31378. * Stores the fill mode state.
  31379. */
  31380. this._fillMode = Material.TriangleFillMode;
  31381. this.name = name;
  31382. this.id = name || BABYLON.Tools.RandomId();
  31383. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  31384. if (this._scene.useRightHandedSystem) {
  31385. this.sideOrientation = Material.ClockWiseSideOrientation;
  31386. }
  31387. else {
  31388. this.sideOrientation = Material.CounterClockWiseSideOrientation;
  31389. }
  31390. this._uniformBuffer = new BABYLON.UniformBuffer(this._scene.getEngine());
  31391. this._useUBO = this.getScene().getEngine().supportsUniformBuffers;
  31392. if (!doNotAdd) {
  31393. this._scene.materials.push(this);
  31394. }
  31395. }
  31396. Object.defineProperty(Material, "TriangleFillMode", {
  31397. /**
  31398. * Returns the triangle fill mode.
  31399. */
  31400. get: function () {
  31401. return Material._TriangleFillMode;
  31402. },
  31403. enumerable: true,
  31404. configurable: true
  31405. });
  31406. Object.defineProperty(Material, "WireFrameFillMode", {
  31407. /**
  31408. * Returns the wireframe mode.
  31409. */
  31410. get: function () {
  31411. return Material._WireFrameFillMode;
  31412. },
  31413. enumerable: true,
  31414. configurable: true
  31415. });
  31416. Object.defineProperty(Material, "PointFillMode", {
  31417. /**
  31418. * Returns the point fill mode.
  31419. */
  31420. get: function () {
  31421. return Material._PointFillMode;
  31422. },
  31423. enumerable: true,
  31424. configurable: true
  31425. });
  31426. Object.defineProperty(Material, "PointListDrawMode", {
  31427. /**
  31428. * Returns the point list draw mode.
  31429. */
  31430. get: function () {
  31431. return Material._PointListDrawMode;
  31432. },
  31433. enumerable: true,
  31434. configurable: true
  31435. });
  31436. Object.defineProperty(Material, "LineListDrawMode", {
  31437. /**
  31438. * Returns the line list draw mode.
  31439. */
  31440. get: function () {
  31441. return Material._LineListDrawMode;
  31442. },
  31443. enumerable: true,
  31444. configurable: true
  31445. });
  31446. Object.defineProperty(Material, "LineLoopDrawMode", {
  31447. /**
  31448. * Returns the line loop draw mode.
  31449. */
  31450. get: function () {
  31451. return Material._LineLoopDrawMode;
  31452. },
  31453. enumerable: true,
  31454. configurable: true
  31455. });
  31456. Object.defineProperty(Material, "LineStripDrawMode", {
  31457. /**
  31458. * Returns the line strip draw mode.
  31459. */
  31460. get: function () {
  31461. return Material._LineStripDrawMode;
  31462. },
  31463. enumerable: true,
  31464. configurable: true
  31465. });
  31466. Object.defineProperty(Material, "TriangleStripDrawMode", {
  31467. /**
  31468. * Returns the triangle strip draw mode.
  31469. */
  31470. get: function () {
  31471. return Material._TriangleStripDrawMode;
  31472. },
  31473. enumerable: true,
  31474. configurable: true
  31475. });
  31476. Object.defineProperty(Material, "TriangleFanDrawMode", {
  31477. /**
  31478. * Returns the triangle fan draw mode.
  31479. */
  31480. get: function () {
  31481. return Material._TriangleFanDrawMode;
  31482. },
  31483. enumerable: true,
  31484. configurable: true
  31485. });
  31486. Object.defineProperty(Material, "ClockWiseSideOrientation", {
  31487. /**
  31488. * Returns the clock-wise side orientation.
  31489. */
  31490. get: function () {
  31491. return Material._ClockWiseSideOrientation;
  31492. },
  31493. enumerable: true,
  31494. configurable: true
  31495. });
  31496. Object.defineProperty(Material, "CounterClockWiseSideOrientation", {
  31497. /**
  31498. * Returns the counter clock-wise side orientation.
  31499. */
  31500. get: function () {
  31501. return Material._CounterClockWiseSideOrientation;
  31502. },
  31503. enumerable: true,
  31504. configurable: true
  31505. });
  31506. Object.defineProperty(Material, "TextureDirtyFlag", {
  31507. /**
  31508. * Returns the dirty texture flag value.
  31509. */
  31510. get: function () {
  31511. return Material._TextureDirtyFlag;
  31512. },
  31513. enumerable: true,
  31514. configurable: true
  31515. });
  31516. Object.defineProperty(Material, "LightDirtyFlag", {
  31517. /**
  31518. * Returns the dirty light flag value.
  31519. */
  31520. get: function () {
  31521. return Material._LightDirtyFlag;
  31522. },
  31523. enumerable: true,
  31524. configurable: true
  31525. });
  31526. Object.defineProperty(Material, "FresnelDirtyFlag", {
  31527. /**
  31528. * Returns the dirty fresnel flag value.
  31529. */
  31530. get: function () {
  31531. return Material._FresnelDirtyFlag;
  31532. },
  31533. enumerable: true,
  31534. configurable: true
  31535. });
  31536. Object.defineProperty(Material, "AttributesDirtyFlag", {
  31537. /**
  31538. * Returns the dirty attributes flag value.
  31539. */
  31540. get: function () {
  31541. return Material._AttributesDirtyFlag;
  31542. },
  31543. enumerable: true,
  31544. configurable: true
  31545. });
  31546. Object.defineProperty(Material, "MiscDirtyFlag", {
  31547. /**
  31548. * Returns the dirty misc flag value.
  31549. */
  31550. get: function () {
  31551. return Material._MiscDirtyFlag;
  31552. },
  31553. enumerable: true,
  31554. configurable: true
  31555. });
  31556. Object.defineProperty(Material.prototype, "alpha", {
  31557. /**
  31558. * Gets the alpha value of the material.
  31559. */
  31560. get: function () {
  31561. return this._alpha;
  31562. },
  31563. /**
  31564. * Sets the alpha value of the material.
  31565. */
  31566. set: function (value) {
  31567. if (this._alpha === value) {
  31568. return;
  31569. }
  31570. this._alpha = value;
  31571. this.markAsDirty(Material.MiscDirtyFlag);
  31572. },
  31573. enumerable: true,
  31574. configurable: true
  31575. });
  31576. Object.defineProperty(Material.prototype, "backFaceCulling", {
  31577. /**
  31578. * Gets the back-face culling state.
  31579. */
  31580. get: function () {
  31581. return this._backFaceCulling;
  31582. },
  31583. /**
  31584. * Sets the back-face culling state.
  31585. */
  31586. set: function (value) {
  31587. if (this._backFaceCulling === value) {
  31588. return;
  31589. }
  31590. this._backFaceCulling = value;
  31591. this.markAsDirty(Material.TextureDirtyFlag);
  31592. },
  31593. enumerable: true,
  31594. configurable: true
  31595. });
  31596. Object.defineProperty(Material.prototype, "onDispose", {
  31597. /**
  31598. * Called during a dispose event.
  31599. */
  31600. set: function (callback) {
  31601. if (this._onDisposeObserver) {
  31602. this.onDisposeObservable.remove(this._onDisposeObserver);
  31603. }
  31604. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  31605. },
  31606. enumerable: true,
  31607. configurable: true
  31608. });
  31609. Object.defineProperty(Material.prototype, "onBind", {
  31610. /**
  31611. * Called during a bind event.
  31612. */
  31613. set: function (callback) {
  31614. if (this._onBindObserver) {
  31615. this.onBindObservable.remove(this._onBindObserver);
  31616. }
  31617. this._onBindObserver = this.onBindObservable.add(callback);
  31618. },
  31619. enumerable: true,
  31620. configurable: true
  31621. });
  31622. Object.defineProperty(Material.prototype, "alphaMode", {
  31623. /**
  31624. * Gets the value of the alpha mode.
  31625. */
  31626. get: function () {
  31627. return this._alphaMode;
  31628. },
  31629. /**
  31630. * Sets the value of the alpha mode.
  31631. *
  31632. * | Value | Type | Description |
  31633. * | --- | --- | --- |
  31634. * | 0 | ALPHA_DISABLE | |
  31635. * | 1 | ALPHA_ADD | |
  31636. * | 2 | ALPHA_COMBINE | |
  31637. * | 3 | ALPHA_SUBTRACT | |
  31638. * | 4 | ALPHA_MULTIPLY | |
  31639. * | 5 | ALPHA_MAXIMIZED | |
  31640. * | 6 | ALPHA_ONEONE | |
  31641. * | 7 | ALPHA_PREMULTIPLIED | |
  31642. * | 8 | ALPHA_PREMULTIPLIED_PORTERDUFF | |
  31643. * | 9 | ALPHA_INTERPOLATE | |
  31644. * | 10 | ALPHA_SCREENMODE | |
  31645. *
  31646. */
  31647. set: function (value) {
  31648. if (this._alphaMode === value) {
  31649. return;
  31650. }
  31651. this._alphaMode = value;
  31652. this.markAsDirty(Material.TextureDirtyFlag);
  31653. },
  31654. enumerable: true,
  31655. configurable: true
  31656. });
  31657. Object.defineProperty(Material.prototype, "needDepthPrePass", {
  31658. /**
  31659. * Gets the depth pre-pass value.
  31660. */
  31661. get: function () {
  31662. return this._needDepthPrePass;
  31663. },
  31664. /**
  31665. * Sets the need depth pre-pass value.
  31666. */
  31667. set: function (value) {
  31668. if (this._needDepthPrePass === value) {
  31669. return;
  31670. }
  31671. this._needDepthPrePass = value;
  31672. if (this._needDepthPrePass) {
  31673. this.checkReadyOnEveryCall = true;
  31674. }
  31675. },
  31676. enumerable: true,
  31677. configurable: true
  31678. });
  31679. Object.defineProperty(Material.prototype, "fogEnabled", {
  31680. /**
  31681. * Gets the value of the fog enabled state.
  31682. */
  31683. get: function () {
  31684. return this._fogEnabled;
  31685. },
  31686. /**
  31687. * Sets the state for enabling fog.
  31688. */
  31689. set: function (value) {
  31690. if (this._fogEnabled === value) {
  31691. return;
  31692. }
  31693. this._fogEnabled = value;
  31694. this.markAsDirty(Material.MiscDirtyFlag);
  31695. },
  31696. enumerable: true,
  31697. configurable: true
  31698. });
  31699. Object.defineProperty(Material.prototype, "wireframe", {
  31700. /**
  31701. * Gets a value specifying if wireframe mode is enabled.
  31702. */
  31703. get: function () {
  31704. switch (this._fillMode) {
  31705. case Material.WireFrameFillMode:
  31706. case Material.LineListDrawMode:
  31707. case Material.LineLoopDrawMode:
  31708. case Material.LineStripDrawMode:
  31709. return true;
  31710. }
  31711. return this._scene.forceWireframe;
  31712. },
  31713. /**
  31714. * Sets the state of wireframe mode.
  31715. */
  31716. set: function (value) {
  31717. this.fillMode = (value ? Material.WireFrameFillMode : Material.TriangleFillMode);
  31718. },
  31719. enumerable: true,
  31720. configurable: true
  31721. });
  31722. Object.defineProperty(Material.prototype, "pointsCloud", {
  31723. /**
  31724. * Gets the value specifying if point clouds are enabled.
  31725. */
  31726. get: function () {
  31727. switch (this._fillMode) {
  31728. case Material.PointFillMode:
  31729. case Material.PointListDrawMode:
  31730. return true;
  31731. }
  31732. return this._scene.forcePointsCloud;
  31733. },
  31734. /**
  31735. * Sets the state of point cloud mode.
  31736. */
  31737. set: function (value) {
  31738. this.fillMode = (value ? Material.PointFillMode : Material.TriangleFillMode);
  31739. },
  31740. enumerable: true,
  31741. configurable: true
  31742. });
  31743. Object.defineProperty(Material.prototype, "fillMode", {
  31744. /**
  31745. * Gets the material fill mode.
  31746. */
  31747. get: function () {
  31748. return this._fillMode;
  31749. },
  31750. /**
  31751. * Sets the material fill mode.
  31752. */
  31753. set: function (value) {
  31754. if (this._fillMode === value) {
  31755. return;
  31756. }
  31757. this._fillMode = value;
  31758. this.markAsDirty(Material.MiscDirtyFlag);
  31759. },
  31760. enumerable: true,
  31761. configurable: true
  31762. });
  31763. /**
  31764. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  31765. * subclasses should override adding information pertainent to themselves.
  31766. * @returns - String with material information.
  31767. */
  31768. Material.prototype.toString = function (fullDetails) {
  31769. var ret = "Name: " + this.name;
  31770. if (fullDetails) {
  31771. }
  31772. return ret;
  31773. };
  31774. /**
  31775. * Gets the class name of the material.
  31776. * @returns - String with the class name of the material.
  31777. */
  31778. Material.prototype.getClassName = function () {
  31779. return "Material";
  31780. };
  31781. Object.defineProperty(Material.prototype, "isFrozen", {
  31782. /**
  31783. * Specifies if updates for the material been locked.
  31784. */
  31785. get: function () {
  31786. return this.checkReadyOnlyOnce;
  31787. },
  31788. enumerable: true,
  31789. configurable: true
  31790. });
  31791. /**
  31792. * Locks updates for the material.
  31793. */
  31794. Material.prototype.freeze = function () {
  31795. this.checkReadyOnlyOnce = true;
  31796. };
  31797. /**
  31798. * Unlocks updates for the material.
  31799. */
  31800. Material.prototype.unfreeze = function () {
  31801. this.checkReadyOnlyOnce = false;
  31802. };
  31803. /**
  31804. * Specifies if the material is ready to be used.
  31805. * @param mesh - BJS mesh.
  31806. * @param useInstances - Specifies if instances should be used.
  31807. * @returns - Boolean indicating if the material is ready to be used.
  31808. */
  31809. Material.prototype.isReady = function (mesh, useInstances) {
  31810. return true;
  31811. };
  31812. /**
  31813. * Specifies that the submesh is ready to be used.
  31814. * @param mesh - BJS mesh.
  31815. * @param subMesh - A submesh of the BJS mesh. Used to check if it is ready.
  31816. * @param useInstances - Specifies that instances should be used.
  31817. * @returns - boolean indicating that the submesh is ready or not.
  31818. */
  31819. Material.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  31820. return false;
  31821. };
  31822. /**
  31823. * Returns the material effect.
  31824. * @returns - Nullable material effect.
  31825. */
  31826. Material.prototype.getEffect = function () {
  31827. return this._effect;
  31828. };
  31829. /**
  31830. * Returns the BJS scene.
  31831. * @returns - BJS Scene.
  31832. */
  31833. Material.prototype.getScene = function () {
  31834. return this._scene;
  31835. };
  31836. /**
  31837. * Specifies if the material will require alpha blending
  31838. * @returns - Boolean specifying if alpha blending is needed.
  31839. */
  31840. Material.prototype.needAlphaBlending = function () {
  31841. return (this.alpha < 1.0);
  31842. };
  31843. /**
  31844. * Specifies if the mesh will require alpha blending.
  31845. * @param mesh - BJS mesh.
  31846. * @returns - Boolean specifying if alpha blending is needed for the mesh.
  31847. */
  31848. Material.prototype.needAlphaBlendingForMesh = function (mesh) {
  31849. return this.needAlphaBlending() || (mesh.visibility < 1.0) || mesh.hasVertexAlpha;
  31850. };
  31851. /**
  31852. * Specifies if this material should be rendered in alpha test mode.
  31853. * @returns - Boolean specifying if an alpha test is needed.
  31854. */
  31855. Material.prototype.needAlphaTesting = function () {
  31856. return false;
  31857. };
  31858. /**
  31859. * Gets the texture used for the alpha test.
  31860. * @returns - Nullable alpha test texture.
  31861. */
  31862. Material.prototype.getAlphaTestTexture = function () {
  31863. return null;
  31864. };
  31865. /**
  31866. * Marks the material to indicate that it needs to be re-calculated.
  31867. */
  31868. Material.prototype.markDirty = function () {
  31869. this._wasPreviouslyReady = false;
  31870. };
  31871. Material.prototype._preBind = function (effect, overrideOrientation) {
  31872. if (overrideOrientation === void 0) { overrideOrientation = null; }
  31873. var engine = this._scene.getEngine();
  31874. var orientation = (overrideOrientation == null) ? this.sideOrientation : overrideOrientation;
  31875. var reverse = orientation === Material.ClockWiseSideOrientation;
  31876. engine.enableEffect(effect ? effect : this._effect);
  31877. engine.setState(this.backFaceCulling, this.zOffset, false, reverse);
  31878. return reverse;
  31879. };
  31880. /**
  31881. * Binds the material to the mesh.
  31882. * @param world - World transformation matrix.
  31883. * @param mesh - Mesh to bind the material to.
  31884. */
  31885. Material.prototype.bind = function (world, mesh) {
  31886. };
  31887. /**
  31888. * Binds the submesh to the material.
  31889. * @param world - World transformation matrix.
  31890. * @param mesh - Mesh containing the submesh.
  31891. * @param subMesh - Submesh to bind the material to.
  31892. */
  31893. Material.prototype.bindForSubMesh = function (world, mesh, subMesh) {
  31894. };
  31895. /**
  31896. * Binds the world matrix to the material.
  31897. * @param world - World transformation matrix.
  31898. */
  31899. Material.prototype.bindOnlyWorldMatrix = function (world) {
  31900. };
  31901. /**
  31902. * Binds the scene's uniform buffer to the effect.
  31903. * @param effect - Effect to bind to the scene uniform buffer.
  31904. * @param sceneUbo - Scene uniform buffer.
  31905. */
  31906. Material.prototype.bindSceneUniformBuffer = function (effect, sceneUbo) {
  31907. sceneUbo.bindToEffect(effect, "Scene");
  31908. };
  31909. /**
  31910. * Binds the view matrix to the effect.
  31911. * @param effect - Effect to bind the view matrix to.
  31912. */
  31913. Material.prototype.bindView = function (effect) {
  31914. if (!this._useUBO) {
  31915. effect.setMatrix("view", this.getScene().getViewMatrix());
  31916. }
  31917. else {
  31918. this.bindSceneUniformBuffer(effect, this.getScene().getSceneUniformBuffer());
  31919. }
  31920. };
  31921. /**
  31922. * Binds the view projection matrix to the effect.
  31923. * @param effect - Effect to bind the view projection matrix to.
  31924. */
  31925. Material.prototype.bindViewProjection = function (effect) {
  31926. if (!this._useUBO) {
  31927. effect.setMatrix("viewProjection", this.getScene().getTransformMatrix());
  31928. }
  31929. else {
  31930. this.bindSceneUniformBuffer(effect, this.getScene().getSceneUniformBuffer());
  31931. }
  31932. };
  31933. /**
  31934. * Specifies if material alpha testing should be turned on for the mesh.
  31935. * @param mesh - BJS mesh.
  31936. */
  31937. Material.prototype._shouldTurnAlphaTestOn = function (mesh) {
  31938. return (!this.needAlphaBlendingForMesh(mesh) && this.needAlphaTesting());
  31939. };
  31940. /**
  31941. * Processes to execute after binding the material to a mesh.
  31942. * @param mesh - BJS mesh.
  31943. */
  31944. Material.prototype._afterBind = function (mesh) {
  31945. this._scene._cachedMaterial = this;
  31946. if (mesh) {
  31947. this._scene._cachedVisibility = mesh.visibility;
  31948. }
  31949. else {
  31950. this._scene._cachedVisibility = 1;
  31951. }
  31952. if (mesh) {
  31953. this.onBindObservable.notifyObservers(mesh);
  31954. }
  31955. if (this.disableDepthWrite) {
  31956. var engine = this._scene.getEngine();
  31957. this._cachedDepthWriteState = engine.getDepthWrite();
  31958. engine.setDepthWrite(false);
  31959. }
  31960. };
  31961. /**
  31962. * Unbinds the material from the mesh.
  31963. */
  31964. Material.prototype.unbind = function () {
  31965. this.onUnBindObservable.notifyObservers(this);
  31966. if (this.disableDepthWrite) {
  31967. var engine = this._scene.getEngine();
  31968. engine.setDepthWrite(this._cachedDepthWriteState);
  31969. }
  31970. };
  31971. /**
  31972. * Gets the active textures from the material.
  31973. * @returns - Array of textures.
  31974. */
  31975. Material.prototype.getActiveTextures = function () {
  31976. return [];
  31977. };
  31978. /**
  31979. * Specifies if the material uses a texture.
  31980. * @param texture - Texture to check against the material.
  31981. * @returns - Boolean specifying if the material uses the texture.
  31982. */
  31983. Material.prototype.hasTexture = function (texture) {
  31984. return false;
  31985. };
  31986. /**
  31987. * Makes a duplicate of the material, and gives it a new name.
  31988. * @param name - Name to call the duplicated material.
  31989. * @returns - Nullable cloned material
  31990. */
  31991. Material.prototype.clone = function (name) {
  31992. return null;
  31993. };
  31994. /**
  31995. * Gets the meshes bound to the material.
  31996. * @returns - Array of meshes bound to the material.
  31997. */
  31998. Material.prototype.getBindedMeshes = function () {
  31999. var result = new Array();
  32000. for (var index = 0; index < this._scene.meshes.length; index++) {
  32001. var mesh = this._scene.meshes[index];
  32002. if (mesh.material === this) {
  32003. result.push(mesh);
  32004. }
  32005. }
  32006. return result;
  32007. };
  32008. /**
  32009. * Force shader compilation
  32010. * @param mesh - BJS mesh.
  32011. * @param onCompiled - function to execute once the material is compiled.
  32012. * @param options - options to pass to this function.
  32013. */
  32014. Material.prototype.forceCompilation = function (mesh, onCompiled, options) {
  32015. var _this = this;
  32016. var localOptions = __assign({ clipPlane: false }, options);
  32017. var subMesh = new BABYLON.BaseSubMesh();
  32018. var scene = this.getScene();
  32019. var checkReady = function () {
  32020. if (!_this._scene || !_this._scene.getEngine()) {
  32021. return;
  32022. }
  32023. if (subMesh._materialDefines) {
  32024. subMesh._materialDefines._renderId = -1;
  32025. }
  32026. var clipPlaneState = scene.clipPlane;
  32027. if (localOptions.clipPlane) {
  32028. scene.clipPlane = new BABYLON.Plane(0, 0, 0, 1);
  32029. }
  32030. if (_this.storeEffectOnSubMeshes) {
  32031. if (_this.isReadyForSubMesh(mesh, subMesh)) {
  32032. if (onCompiled) {
  32033. onCompiled(_this);
  32034. }
  32035. }
  32036. else {
  32037. setTimeout(checkReady, 16);
  32038. }
  32039. }
  32040. else {
  32041. if (_this.isReady(mesh)) {
  32042. if (onCompiled) {
  32043. onCompiled(_this);
  32044. }
  32045. }
  32046. else {
  32047. setTimeout(checkReady, 16);
  32048. }
  32049. }
  32050. if (localOptions.clipPlane) {
  32051. scene.clipPlane = clipPlaneState;
  32052. }
  32053. };
  32054. checkReady();
  32055. };
  32056. /**
  32057. * Force shader compilation.
  32058. * @param mesh The mesh that will use this material
  32059. * @param options Additional options for compiling the shaders
  32060. * @returns A promise that resolves when the compilation completes
  32061. */
  32062. Material.prototype.forceCompilationAsync = function (mesh, options) {
  32063. var _this = this;
  32064. return new Promise(function (resolve) {
  32065. _this.forceCompilation(mesh, function () {
  32066. resolve();
  32067. }, options);
  32068. });
  32069. };
  32070. /**
  32071. * Marks a define in the material to indicate that it needs to be re-computed.
  32072. * @param flag - Material define flag.
  32073. */
  32074. Material.prototype.markAsDirty = function (flag) {
  32075. if (flag & Material.TextureDirtyFlag) {
  32076. this._markAllSubMeshesAsTexturesDirty();
  32077. }
  32078. if (flag & Material.LightDirtyFlag) {
  32079. this._markAllSubMeshesAsLightsDirty();
  32080. }
  32081. if (flag & Material.FresnelDirtyFlag) {
  32082. this._markAllSubMeshesAsFresnelDirty();
  32083. }
  32084. if (flag & Material.AttributesDirtyFlag) {
  32085. this._markAllSubMeshesAsAttributesDirty();
  32086. }
  32087. if (flag & Material.MiscDirtyFlag) {
  32088. this._markAllSubMeshesAsMiscDirty();
  32089. }
  32090. this.getScene().resetCachedMaterial();
  32091. };
  32092. /**
  32093. * Marks all submeshes of a material to indicate that their material defines need to be re-calculated.
  32094. * @param func - function which checks material defines against the submeshes.
  32095. */
  32096. Material.prototype._markAllSubMeshesAsDirty = function (func) {
  32097. for (var _i = 0, _a = this.getScene().meshes; _i < _a.length; _i++) {
  32098. var mesh = _a[_i];
  32099. if (!mesh.subMeshes) {
  32100. continue;
  32101. }
  32102. for (var _b = 0, _c = mesh.subMeshes; _b < _c.length; _b++) {
  32103. var subMesh = _c[_b];
  32104. if (subMesh.getMaterial() !== this) {
  32105. continue;
  32106. }
  32107. if (!subMesh._materialDefines) {
  32108. continue;
  32109. }
  32110. func(subMesh._materialDefines);
  32111. }
  32112. }
  32113. };
  32114. /**
  32115. * Indicates that image processing needs to be re-calculated for all submeshes.
  32116. */
  32117. Material.prototype._markAllSubMeshesAsImageProcessingDirty = function () {
  32118. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsImageProcessingDirty(); });
  32119. };
  32120. /**
  32121. * Indicates that textures need to be re-calculated for all submeshes.
  32122. */
  32123. Material.prototype._markAllSubMeshesAsTexturesDirty = function () {
  32124. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsTexturesDirty(); });
  32125. };
  32126. /**
  32127. * Indicates that fresnel needs to be re-calculated for all submeshes.
  32128. */
  32129. Material.prototype._markAllSubMeshesAsFresnelDirty = function () {
  32130. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsFresnelDirty(); });
  32131. };
  32132. /**
  32133. * Indicates that fresnel and misc need to be re-calculated for all submeshes.
  32134. */
  32135. Material.prototype._markAllSubMeshesAsFresnelAndMiscDirty = function () {
  32136. this._markAllSubMeshesAsDirty(function (defines) {
  32137. defines.markAsFresnelDirty();
  32138. defines.markAsMiscDirty();
  32139. });
  32140. };
  32141. /**
  32142. * Indicates that lights need to be re-calculated for all submeshes.
  32143. */
  32144. Material.prototype._markAllSubMeshesAsLightsDirty = function () {
  32145. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsLightDirty(); });
  32146. };
  32147. /**
  32148. * Indicates that attributes need to be re-calculated for all submeshes.
  32149. */
  32150. Material.prototype._markAllSubMeshesAsAttributesDirty = function () {
  32151. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsAttributesDirty(); });
  32152. };
  32153. /**
  32154. * Indicates that misc needs to be re-calculated for all submeshes.
  32155. */
  32156. Material.prototype._markAllSubMeshesAsMiscDirty = function () {
  32157. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsMiscDirty(); });
  32158. };
  32159. /**
  32160. * Indicates that textures and misc need to be re-calculated for all submeshes.
  32161. */
  32162. Material.prototype._markAllSubMeshesAsTexturesAndMiscDirty = function () {
  32163. this._markAllSubMeshesAsDirty(function (defines) {
  32164. defines.markAsTexturesDirty();
  32165. defines.markAsMiscDirty();
  32166. });
  32167. };
  32168. /**
  32169. * Disposes the material.
  32170. * @param forceDisposeEffect - Specifies if effects should be force disposed.
  32171. * @param forceDisposeTextures - Specifies if textures should be force disposed.
  32172. */
  32173. Material.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  32174. // Animations
  32175. this.getScene().stopAnimation(this);
  32176. this.getScene().freeProcessedMaterials();
  32177. // Remove from scene
  32178. var index = this._scene.materials.indexOf(this);
  32179. if (index >= 0) {
  32180. this._scene.materials.splice(index, 1);
  32181. }
  32182. // Remove from meshes
  32183. for (index = 0; index < this._scene.meshes.length; index++) {
  32184. var mesh = this._scene.meshes[index];
  32185. if (mesh.material === this) {
  32186. mesh.material = null;
  32187. if (mesh.geometry) {
  32188. var geometry = (mesh.geometry);
  32189. if (this.storeEffectOnSubMeshes) {
  32190. for (var _i = 0, _a = mesh.subMeshes; _i < _a.length; _i++) {
  32191. var subMesh = _a[_i];
  32192. geometry._releaseVertexArrayObject(subMesh._materialEffect);
  32193. if (forceDisposeEffect && subMesh._materialEffect) {
  32194. this._scene.getEngine()._releaseEffect(subMesh._materialEffect);
  32195. }
  32196. }
  32197. }
  32198. else {
  32199. geometry._releaseVertexArrayObject(this._effect);
  32200. }
  32201. }
  32202. }
  32203. }
  32204. this._uniformBuffer.dispose();
  32205. // Shader are kept in cache for further use but we can get rid of this by using forceDisposeEffect
  32206. if (forceDisposeEffect && this._effect) {
  32207. if (!this.storeEffectOnSubMeshes) {
  32208. this._scene.getEngine()._releaseEffect(this._effect);
  32209. }
  32210. this._effect = null;
  32211. }
  32212. // Callback
  32213. this.onDisposeObservable.notifyObservers(this);
  32214. this.onDisposeObservable.clear();
  32215. this.onBindObservable.clear();
  32216. this.onUnBindObservable.clear();
  32217. };
  32218. /**
  32219. * Serializes this material.
  32220. * @returns - serialized material object.
  32221. */
  32222. Material.prototype.serialize = function () {
  32223. return BABYLON.SerializationHelper.Serialize(this);
  32224. };
  32225. /**
  32226. * Creates a MultiMaterial from parse MultiMaterial data.
  32227. * @param parsedMultiMaterial - Parsed MultiMaterial data.
  32228. * @param scene - BJS scene.
  32229. * @returns - MultiMaterial.
  32230. */
  32231. Material.ParseMultiMaterial = function (parsedMultiMaterial, scene) {
  32232. var multiMaterial = new BABYLON.MultiMaterial(parsedMultiMaterial.name, scene);
  32233. multiMaterial.id = parsedMultiMaterial.id;
  32234. if (BABYLON.Tags) {
  32235. BABYLON.Tags.AddTagsTo(multiMaterial, parsedMultiMaterial.tags);
  32236. }
  32237. for (var matIndex = 0; matIndex < parsedMultiMaterial.materials.length; matIndex++) {
  32238. var subMatId = parsedMultiMaterial.materials[matIndex];
  32239. if (subMatId) {
  32240. multiMaterial.subMaterials.push(scene.getMaterialByID(subMatId));
  32241. }
  32242. else {
  32243. multiMaterial.subMaterials.push(null);
  32244. }
  32245. }
  32246. return multiMaterial;
  32247. };
  32248. /**
  32249. * Creates a material from parsed material data.
  32250. * @param parsedMaterial - Parsed material data.
  32251. * @param scene - BJS scene.
  32252. * @param rootUrl - Root URL containing the material information.
  32253. * @returns - Parsed material.
  32254. */
  32255. Material.Parse = function (parsedMaterial, scene, rootUrl) {
  32256. if (!parsedMaterial.customType || parsedMaterial.customType === "BABYLON.StandardMaterial") {
  32257. return BABYLON.StandardMaterial.Parse(parsedMaterial, scene, rootUrl);
  32258. }
  32259. if (parsedMaterial.customType === "BABYLON.PBRMaterial" && parsedMaterial.overloadedAlbedo) {
  32260. parsedMaterial.customType = "BABYLON.LegacyPBRMaterial";
  32261. if (!BABYLON.LegacyPBRMaterial) {
  32262. BABYLON.Tools.Error("Your scene is trying to load a legacy version of the PBRMaterial, please, include it from the materials library.");
  32263. return;
  32264. }
  32265. }
  32266. var materialType = BABYLON.Tools.Instantiate(parsedMaterial.customType);
  32267. return materialType.Parse(parsedMaterial, scene, rootUrl);
  32268. ;
  32269. };
  32270. // Triangle views
  32271. Material._TriangleFillMode = 0;
  32272. Material._WireFrameFillMode = 1;
  32273. Material._PointFillMode = 2;
  32274. // Draw modes
  32275. Material._PointListDrawMode = 3;
  32276. Material._LineListDrawMode = 4;
  32277. Material._LineLoopDrawMode = 5;
  32278. Material._LineStripDrawMode = 6;
  32279. Material._TriangleStripDrawMode = 7;
  32280. Material._TriangleFanDrawMode = 8;
  32281. /**
  32282. * Stores the clock-wise side orientation.
  32283. */
  32284. Material._ClockWiseSideOrientation = 0;
  32285. /**
  32286. * Stores the counter clock-wise side orientation.
  32287. */
  32288. Material._CounterClockWiseSideOrientation = 1;
  32289. /**
  32290. * The dirty texture flag value.
  32291. */
  32292. Material._TextureDirtyFlag = 1;
  32293. /**
  32294. * The dirty light flag value.
  32295. */
  32296. Material._LightDirtyFlag = 2;
  32297. /**
  32298. * The dirty fresnel flag value.
  32299. */
  32300. Material._FresnelDirtyFlag = 4;
  32301. /**
  32302. * The dirty attribute flag value.
  32303. */
  32304. Material._AttributesDirtyFlag = 8;
  32305. /**
  32306. * The dirty misc flag value.
  32307. */
  32308. Material._MiscDirtyFlag = 16;
  32309. __decorate([
  32310. BABYLON.serialize()
  32311. ], Material.prototype, "id", void 0);
  32312. __decorate([
  32313. BABYLON.serialize()
  32314. ], Material.prototype, "name", void 0);
  32315. __decorate([
  32316. BABYLON.serialize()
  32317. ], Material.prototype, "checkReadyOnEveryCall", void 0);
  32318. __decorate([
  32319. BABYLON.serialize()
  32320. ], Material.prototype, "checkReadyOnlyOnce", void 0);
  32321. __decorate([
  32322. BABYLON.serialize()
  32323. ], Material.prototype, "state", void 0);
  32324. __decorate([
  32325. BABYLON.serialize("alpha")
  32326. ], Material.prototype, "_alpha", void 0);
  32327. __decorate([
  32328. BABYLON.serialize("backFaceCulling")
  32329. ], Material.prototype, "_backFaceCulling", void 0);
  32330. __decorate([
  32331. BABYLON.serialize()
  32332. ], Material.prototype, "sideOrientation", void 0);
  32333. __decorate([
  32334. BABYLON.serialize("alphaMode")
  32335. ], Material.prototype, "_alphaMode", void 0);
  32336. __decorate([
  32337. BABYLON.serialize()
  32338. ], Material.prototype, "_needDepthPrePass", void 0);
  32339. __decorate([
  32340. BABYLON.serialize()
  32341. ], Material.prototype, "disableDepthWrite", void 0);
  32342. __decorate([
  32343. BABYLON.serialize()
  32344. ], Material.prototype, "forceDepthWrite", void 0);
  32345. __decorate([
  32346. BABYLON.serialize()
  32347. ], Material.prototype, "separateCullingPass", void 0);
  32348. __decorate([
  32349. BABYLON.serialize("fogEnabled")
  32350. ], Material.prototype, "_fogEnabled", void 0);
  32351. __decorate([
  32352. BABYLON.serialize()
  32353. ], Material.prototype, "pointSize", void 0);
  32354. __decorate([
  32355. BABYLON.serialize()
  32356. ], Material.prototype, "zOffset", void 0);
  32357. __decorate([
  32358. BABYLON.serialize()
  32359. ], Material.prototype, "wireframe", null);
  32360. __decorate([
  32361. BABYLON.serialize()
  32362. ], Material.prototype, "pointsCloud", null);
  32363. __decorate([
  32364. BABYLON.serialize()
  32365. ], Material.prototype, "fillMode", null);
  32366. return Material;
  32367. }());
  32368. BABYLON.Material = Material;
  32369. })(BABYLON || (BABYLON = {}));
  32370. //# sourceMappingURL=babylon.material.js.map
  32371. "use strict";
  32372. var BABYLON;
  32373. (function (BABYLON) {
  32374. var UniformBuffer = /** @class */ (function () {
  32375. /**
  32376. * Uniform buffer objects.
  32377. *
  32378. * Handles blocks of uniform on the GPU.
  32379. *
  32380. * If WebGL 2 is not available, this class falls back on traditionnal setUniformXXX calls.
  32381. *
  32382. * For more information, please refer to :
  32383. * https://www.khronos.org/opengl/wiki/Uniform_Buffer_Object
  32384. */
  32385. function UniformBuffer(engine, data, dynamic) {
  32386. this._engine = engine;
  32387. this._noUBO = !engine.supportsUniformBuffers;
  32388. this._dynamic = dynamic;
  32389. this._data = data || [];
  32390. this._uniformLocations = {};
  32391. this._uniformSizes = {};
  32392. this._uniformLocationPointer = 0;
  32393. this._needSync = false;
  32394. if (this._noUBO) {
  32395. this.updateMatrix3x3 = this._updateMatrix3x3ForEffect;
  32396. this.updateMatrix2x2 = this._updateMatrix2x2ForEffect;
  32397. this.updateFloat = this._updateFloatForEffect;
  32398. this.updateFloat2 = this._updateFloat2ForEffect;
  32399. this.updateFloat3 = this._updateFloat3ForEffect;
  32400. this.updateFloat4 = this._updateFloat4ForEffect;
  32401. this.updateMatrix = this._updateMatrixForEffect;
  32402. this.updateVector3 = this._updateVector3ForEffect;
  32403. this.updateVector4 = this._updateVector4ForEffect;
  32404. this.updateColor3 = this._updateColor3ForEffect;
  32405. this.updateColor4 = this._updateColor4ForEffect;
  32406. }
  32407. else {
  32408. this._engine._uniformBuffers.push(this);
  32409. this.updateMatrix3x3 = this._updateMatrix3x3ForUniform;
  32410. this.updateMatrix2x2 = this._updateMatrix2x2ForUniform;
  32411. this.updateFloat = this._updateFloatForUniform;
  32412. this.updateFloat2 = this._updateFloat2ForUniform;
  32413. this.updateFloat3 = this._updateFloat3ForUniform;
  32414. this.updateFloat4 = this._updateFloat4ForUniform;
  32415. this.updateMatrix = this._updateMatrixForUniform;
  32416. this.updateVector3 = this._updateVector3ForUniform;
  32417. this.updateVector4 = this._updateVector4ForUniform;
  32418. this.updateColor3 = this._updateColor3ForUniform;
  32419. this.updateColor4 = this._updateColor4ForUniform;
  32420. }
  32421. }
  32422. Object.defineProperty(UniformBuffer.prototype, "useUbo", {
  32423. // Properties
  32424. /**
  32425. * Indicates if the buffer is using the WebGL2 UBO implementation,
  32426. * or just falling back on setUniformXXX calls.
  32427. */
  32428. get: function () {
  32429. return !this._noUBO;
  32430. },
  32431. enumerable: true,
  32432. configurable: true
  32433. });
  32434. Object.defineProperty(UniformBuffer.prototype, "isSync", {
  32435. /**
  32436. * Indicates if the WebGL underlying uniform buffer is in sync
  32437. * with the javascript cache data.
  32438. */
  32439. get: function () {
  32440. return !this._needSync;
  32441. },
  32442. enumerable: true,
  32443. configurable: true
  32444. });
  32445. /**
  32446. * Indicates if the WebGL underlying uniform buffer is dynamic.
  32447. * Also, a dynamic UniformBuffer will disable cache verification and always
  32448. * update the underlying WebGL uniform buffer to the GPU.
  32449. */
  32450. UniformBuffer.prototype.isDynamic = function () {
  32451. return this._dynamic !== undefined;
  32452. };
  32453. /**
  32454. * The data cache on JS side.
  32455. */
  32456. UniformBuffer.prototype.getData = function () {
  32457. return this._bufferData;
  32458. };
  32459. /**
  32460. * The underlying WebGL Uniform buffer.
  32461. */
  32462. UniformBuffer.prototype.getBuffer = function () {
  32463. return this._buffer;
  32464. };
  32465. /**
  32466. * std140 layout specifies how to align data within an UBO structure.
  32467. * See https://khronos.org/registry/OpenGL/specs/gl/glspec45.core.pdf#page=159
  32468. * for specs.
  32469. */
  32470. UniformBuffer.prototype._fillAlignment = function (size) {
  32471. // This code has been simplified because we only use floats, vectors of 1, 2, 3, 4 components
  32472. // and 4x4 matrices
  32473. // TODO : change if other types are used
  32474. var alignment;
  32475. if (size <= 2) {
  32476. alignment = size;
  32477. }
  32478. else {
  32479. alignment = 4;
  32480. }
  32481. if ((this._uniformLocationPointer % alignment) !== 0) {
  32482. var oldPointer = this._uniformLocationPointer;
  32483. this._uniformLocationPointer += alignment - (this._uniformLocationPointer % alignment);
  32484. var diff = this._uniformLocationPointer - oldPointer;
  32485. for (var i = 0; i < diff; i++) {
  32486. this._data.push(0);
  32487. }
  32488. }
  32489. };
  32490. /**
  32491. * Adds an uniform in the buffer.
  32492. * Warning : the subsequents calls of this function must be in the same order as declared in the shader
  32493. * for the layout to be correct !
  32494. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  32495. * @param {number|number[]} size Data size, or data directly.
  32496. */
  32497. UniformBuffer.prototype.addUniform = function (name, size) {
  32498. if (this._noUBO) {
  32499. return;
  32500. }
  32501. if (this._uniformLocations[name] !== undefined) {
  32502. // Already existing uniform
  32503. return;
  32504. }
  32505. // This function must be called in the order of the shader layout !
  32506. // size can be the size of the uniform, or data directly
  32507. var data;
  32508. if (size instanceof Array) {
  32509. data = size;
  32510. size = data.length;
  32511. }
  32512. else {
  32513. size = size;
  32514. data = [];
  32515. // Fill with zeros
  32516. for (var i = 0; i < size; i++) {
  32517. data.push(0);
  32518. }
  32519. }
  32520. this._fillAlignment(size);
  32521. this._uniformSizes[name] = size;
  32522. this._uniformLocations[name] = this._uniformLocationPointer;
  32523. this._uniformLocationPointer += size;
  32524. for (var i = 0; i < size; i++) {
  32525. this._data.push(data[i]);
  32526. }
  32527. this._needSync = true;
  32528. };
  32529. /**
  32530. * Wrapper for addUniform.
  32531. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  32532. * @param {Matrix} mat A 4x4 matrix.
  32533. */
  32534. UniformBuffer.prototype.addMatrix = function (name, mat) {
  32535. this.addUniform(name, Array.prototype.slice.call(mat.toArray()));
  32536. };
  32537. /**
  32538. * Wrapper for addUniform.
  32539. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  32540. * @param {number} x
  32541. * @param {number} y
  32542. */
  32543. UniformBuffer.prototype.addFloat2 = function (name, x, y) {
  32544. var temp = [x, y];
  32545. this.addUniform(name, temp);
  32546. };
  32547. /**
  32548. * Wrapper for addUniform.
  32549. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  32550. * @param {number} x
  32551. * @param {number} y
  32552. * @param {number} z
  32553. */
  32554. UniformBuffer.prototype.addFloat3 = function (name, x, y, z) {
  32555. var temp = [x, y, z];
  32556. this.addUniform(name, temp);
  32557. };
  32558. /**
  32559. * Wrapper for addUniform.
  32560. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  32561. * @param {Color3} color
  32562. */
  32563. UniformBuffer.prototype.addColor3 = function (name, color) {
  32564. var temp = new Array();
  32565. color.toArray(temp);
  32566. this.addUniform(name, temp);
  32567. };
  32568. /**
  32569. * Wrapper for addUniform.
  32570. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  32571. * @param {Color3} color
  32572. * @param {number} alpha
  32573. */
  32574. UniformBuffer.prototype.addColor4 = function (name, color, alpha) {
  32575. var temp = new Array();
  32576. color.toArray(temp);
  32577. temp.push(alpha);
  32578. this.addUniform(name, temp);
  32579. };
  32580. /**
  32581. * Wrapper for addUniform.
  32582. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  32583. * @param {Vector3} vector
  32584. */
  32585. UniformBuffer.prototype.addVector3 = function (name, vector) {
  32586. var temp = new Array();
  32587. vector.toArray(temp);
  32588. this.addUniform(name, temp);
  32589. };
  32590. /**
  32591. * Wrapper for addUniform.
  32592. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  32593. */
  32594. UniformBuffer.prototype.addMatrix3x3 = function (name) {
  32595. this.addUniform(name, 12);
  32596. };
  32597. /**
  32598. * Wrapper for addUniform.
  32599. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  32600. */
  32601. UniformBuffer.prototype.addMatrix2x2 = function (name) {
  32602. this.addUniform(name, 8);
  32603. };
  32604. /**
  32605. * Effectively creates the WebGL Uniform Buffer, once layout is completed with `addUniform`.
  32606. */
  32607. UniformBuffer.prototype.create = function () {
  32608. if (this._noUBO) {
  32609. return;
  32610. }
  32611. if (this._buffer) {
  32612. return; // nothing to do
  32613. }
  32614. // See spec, alignment must be filled as a vec4
  32615. this._fillAlignment(4);
  32616. this._bufferData = new Float32Array(this._data);
  32617. this._rebuild();
  32618. this._needSync = true;
  32619. };
  32620. UniformBuffer.prototype._rebuild = function () {
  32621. if (this._noUBO) {
  32622. return;
  32623. }
  32624. if (this._dynamic) {
  32625. this._buffer = this._engine.createDynamicUniformBuffer(this._bufferData);
  32626. }
  32627. else {
  32628. this._buffer = this._engine.createUniformBuffer(this._bufferData);
  32629. }
  32630. };
  32631. /**
  32632. * Updates the WebGL Uniform Buffer on the GPU.
  32633. * If the `dynamic` flag is set to true, no cache comparison is done.
  32634. * Otherwise, the buffer will be updated only if the cache differs.
  32635. */
  32636. UniformBuffer.prototype.update = function () {
  32637. if (!this._buffer) {
  32638. this.create();
  32639. return;
  32640. }
  32641. if (!this._dynamic && !this._needSync) {
  32642. return;
  32643. }
  32644. this._engine.updateUniformBuffer(this._buffer, this._bufferData);
  32645. this._needSync = false;
  32646. };
  32647. /**
  32648. * Updates the value of an uniform. The `update` method must be called afterwards to make it effective in the GPU.
  32649. * @param {string} uniformName Name of the uniform, as used in the uniform block in the shader.
  32650. * @param {number[]|Float32Array} data Flattened data
  32651. * @param {number} size Size of the data.
  32652. */
  32653. UniformBuffer.prototype.updateUniform = function (uniformName, data, size) {
  32654. var location = this._uniformLocations[uniformName];
  32655. if (location === undefined) {
  32656. if (this._buffer) {
  32657. // Cannot add an uniform if the buffer is already created
  32658. BABYLON.Tools.Error("Cannot add an uniform after UBO has been created.");
  32659. return;
  32660. }
  32661. this.addUniform(uniformName, size);
  32662. location = this._uniformLocations[uniformName];
  32663. }
  32664. if (!this._buffer) {
  32665. this.create();
  32666. }
  32667. if (!this._dynamic) {
  32668. // Cache for static uniform buffers
  32669. var changed = false;
  32670. for (var i = 0; i < size; i++) {
  32671. if (this._bufferData[location + i] !== data[i]) {
  32672. changed = true;
  32673. this._bufferData[location + i] = data[i];
  32674. }
  32675. }
  32676. this._needSync = this._needSync || changed;
  32677. }
  32678. else {
  32679. // No cache for dynamic
  32680. for (var i = 0; i < size; i++) {
  32681. this._bufferData[location + i] = data[i];
  32682. }
  32683. }
  32684. };
  32685. // Update methods
  32686. UniformBuffer.prototype._updateMatrix3x3ForUniform = function (name, matrix) {
  32687. // To match std140, matrix must be realigned
  32688. for (var i = 0; i < 3; i++) {
  32689. UniformBuffer._tempBuffer[i * 4] = matrix[i * 3];
  32690. UniformBuffer._tempBuffer[i * 4 + 1] = matrix[i * 3 + 1];
  32691. UniformBuffer._tempBuffer[i * 4 + 2] = matrix[i * 3 + 2];
  32692. UniformBuffer._tempBuffer[i * 4 + 3] = 0.0;
  32693. }
  32694. this.updateUniform(name, UniformBuffer._tempBuffer, 12);
  32695. };
  32696. UniformBuffer.prototype._updateMatrix3x3ForEffect = function (name, matrix) {
  32697. this._currentEffect.setMatrix3x3(name, matrix);
  32698. };
  32699. UniformBuffer.prototype._updateMatrix2x2ForEffect = function (name, matrix) {
  32700. this._currentEffect.setMatrix2x2(name, matrix);
  32701. };
  32702. UniformBuffer.prototype._updateMatrix2x2ForUniform = function (name, matrix) {
  32703. // To match std140, matrix must be realigned
  32704. for (var i = 0; i < 2; i++) {
  32705. UniformBuffer._tempBuffer[i * 4] = matrix[i * 2];
  32706. UniformBuffer._tempBuffer[i * 4 + 1] = matrix[i * 2 + 1];
  32707. UniformBuffer._tempBuffer[i * 4 + 2] = 0.0;
  32708. UniformBuffer._tempBuffer[i * 4 + 3] = 0.0;
  32709. }
  32710. this.updateUniform(name, UniformBuffer._tempBuffer, 8);
  32711. };
  32712. UniformBuffer.prototype._updateFloatForEffect = function (name, x) {
  32713. this._currentEffect.setFloat(name, x);
  32714. };
  32715. UniformBuffer.prototype._updateFloatForUniform = function (name, x) {
  32716. UniformBuffer._tempBuffer[0] = x;
  32717. this.updateUniform(name, UniformBuffer._tempBuffer, 1);
  32718. };
  32719. UniformBuffer.prototype._updateFloat2ForEffect = function (name, x, y, suffix) {
  32720. if (suffix === void 0) { suffix = ""; }
  32721. this._currentEffect.setFloat2(name + suffix, x, y);
  32722. };
  32723. UniformBuffer.prototype._updateFloat2ForUniform = function (name, x, y, suffix) {
  32724. if (suffix === void 0) { suffix = ""; }
  32725. UniformBuffer._tempBuffer[0] = x;
  32726. UniformBuffer._tempBuffer[1] = y;
  32727. this.updateUniform(name, UniformBuffer._tempBuffer, 2);
  32728. };
  32729. UniformBuffer.prototype._updateFloat3ForEffect = function (name, x, y, z, suffix) {
  32730. if (suffix === void 0) { suffix = ""; }
  32731. this._currentEffect.setFloat3(name + suffix, x, y, z);
  32732. };
  32733. UniformBuffer.prototype._updateFloat3ForUniform = function (name, x, y, z, suffix) {
  32734. if (suffix === void 0) { suffix = ""; }
  32735. UniformBuffer._tempBuffer[0] = x;
  32736. UniformBuffer._tempBuffer[1] = y;
  32737. UniformBuffer._tempBuffer[2] = z;
  32738. this.updateUniform(name, UniformBuffer._tempBuffer, 3);
  32739. };
  32740. UniformBuffer.prototype._updateFloat4ForEffect = function (name, x, y, z, w, suffix) {
  32741. if (suffix === void 0) { suffix = ""; }
  32742. this._currentEffect.setFloat4(name + suffix, x, y, z, w);
  32743. };
  32744. UniformBuffer.prototype._updateFloat4ForUniform = function (name, x, y, z, w, suffix) {
  32745. if (suffix === void 0) { suffix = ""; }
  32746. UniformBuffer._tempBuffer[0] = x;
  32747. UniformBuffer._tempBuffer[1] = y;
  32748. UniformBuffer._tempBuffer[2] = z;
  32749. UniformBuffer._tempBuffer[3] = w;
  32750. this.updateUniform(name, UniformBuffer._tempBuffer, 4);
  32751. };
  32752. UniformBuffer.prototype._updateMatrixForEffect = function (name, mat) {
  32753. this._currentEffect.setMatrix(name, mat);
  32754. };
  32755. UniformBuffer.prototype._updateMatrixForUniform = function (name, mat) {
  32756. this.updateUniform(name, mat.toArray(), 16);
  32757. };
  32758. UniformBuffer.prototype._updateVector3ForEffect = function (name, vector) {
  32759. this._currentEffect.setVector3(name, vector);
  32760. };
  32761. UniformBuffer.prototype._updateVector3ForUniform = function (name, vector) {
  32762. vector.toArray(UniformBuffer._tempBuffer);
  32763. this.updateUniform(name, UniformBuffer._tempBuffer, 3);
  32764. };
  32765. UniformBuffer.prototype._updateVector4ForEffect = function (name, vector) {
  32766. this._currentEffect.setVector4(name, vector);
  32767. };
  32768. UniformBuffer.prototype._updateVector4ForUniform = function (name, vector) {
  32769. vector.toArray(UniformBuffer._tempBuffer);
  32770. this.updateUniform(name, UniformBuffer._tempBuffer, 4);
  32771. };
  32772. UniformBuffer.prototype._updateColor3ForEffect = function (name, color, suffix) {
  32773. if (suffix === void 0) { suffix = ""; }
  32774. this._currentEffect.setColor3(name + suffix, color);
  32775. };
  32776. UniformBuffer.prototype._updateColor3ForUniform = function (name, color, suffix) {
  32777. if (suffix === void 0) { suffix = ""; }
  32778. color.toArray(UniformBuffer._tempBuffer);
  32779. this.updateUniform(name, UniformBuffer._tempBuffer, 3);
  32780. };
  32781. UniformBuffer.prototype._updateColor4ForEffect = function (name, color, alpha, suffix) {
  32782. if (suffix === void 0) { suffix = ""; }
  32783. this._currentEffect.setColor4(name + suffix, color, alpha);
  32784. };
  32785. UniformBuffer.prototype._updateColor4ForUniform = function (name, color, alpha, suffix) {
  32786. if (suffix === void 0) { suffix = ""; }
  32787. color.toArray(UniformBuffer._tempBuffer);
  32788. UniformBuffer._tempBuffer[3] = alpha;
  32789. this.updateUniform(name, UniformBuffer._tempBuffer, 4);
  32790. };
  32791. /**
  32792. * Sets a sampler uniform on the effect.
  32793. * @param {string} name Name of the sampler.
  32794. * @param {Texture} texture
  32795. */
  32796. UniformBuffer.prototype.setTexture = function (name, texture) {
  32797. this._currentEffect.setTexture(name, texture);
  32798. };
  32799. /**
  32800. * Directly updates the value of the uniform in the cache AND on the GPU.
  32801. * @param {string} uniformName Name of the uniform, as used in the uniform block in the shader.
  32802. * @param {number[]|Float32Array} data Flattened data
  32803. */
  32804. UniformBuffer.prototype.updateUniformDirectly = function (uniformName, data) {
  32805. this.updateUniform(uniformName, data, data.length);
  32806. this.update();
  32807. };
  32808. /**
  32809. * Binds this uniform buffer to an effect.
  32810. * @param {Effect} effect
  32811. * @param {string} name Name of the uniform block in the shader.
  32812. */
  32813. UniformBuffer.prototype.bindToEffect = function (effect, name) {
  32814. this._currentEffect = effect;
  32815. if (this._noUBO || !this._buffer) {
  32816. return;
  32817. }
  32818. effect.bindUniformBuffer(this._buffer, name);
  32819. };
  32820. /**
  32821. * Disposes the uniform buffer.
  32822. */
  32823. UniformBuffer.prototype.dispose = function () {
  32824. if (this._noUBO) {
  32825. return;
  32826. }
  32827. var index = this._engine._uniformBuffers.indexOf(this);
  32828. if (index !== -1) {
  32829. this._engine._uniformBuffers.splice(index, 1);
  32830. }
  32831. if (!this._buffer) {
  32832. return;
  32833. }
  32834. if (this._engine._releaseBuffer(this._buffer)) {
  32835. this._buffer = null;
  32836. }
  32837. };
  32838. // Pool for avoiding memory leaks
  32839. UniformBuffer._MAX_UNIFORM_SIZE = 256;
  32840. UniformBuffer._tempBuffer = new Float32Array(UniformBuffer._MAX_UNIFORM_SIZE);
  32841. return UniformBuffer;
  32842. }());
  32843. BABYLON.UniformBuffer = UniformBuffer;
  32844. })(BABYLON || (BABYLON = {}));
  32845. //# sourceMappingURL=babylon.uniformBuffer.js.map
  32846. "use strict";
  32847. var BABYLON;
  32848. (function (BABYLON) {
  32849. var VertexData = /** @class */ (function () {
  32850. function VertexData() {
  32851. }
  32852. VertexData.prototype.set = function (data, kind) {
  32853. switch (kind) {
  32854. case BABYLON.VertexBuffer.PositionKind:
  32855. this.positions = data;
  32856. break;
  32857. case BABYLON.VertexBuffer.NormalKind:
  32858. this.normals = data;
  32859. break;
  32860. case BABYLON.VertexBuffer.TangentKind:
  32861. this.tangents = data;
  32862. break;
  32863. case BABYLON.VertexBuffer.UVKind:
  32864. this.uvs = data;
  32865. break;
  32866. case BABYLON.VertexBuffer.UV2Kind:
  32867. this.uvs2 = data;
  32868. break;
  32869. case BABYLON.VertexBuffer.UV3Kind:
  32870. this.uvs3 = data;
  32871. break;
  32872. case BABYLON.VertexBuffer.UV4Kind:
  32873. this.uvs4 = data;
  32874. break;
  32875. case BABYLON.VertexBuffer.UV5Kind:
  32876. this.uvs5 = data;
  32877. break;
  32878. case BABYLON.VertexBuffer.UV6Kind:
  32879. this.uvs6 = data;
  32880. break;
  32881. case BABYLON.VertexBuffer.ColorKind:
  32882. this.colors = data;
  32883. break;
  32884. case BABYLON.VertexBuffer.MatricesIndicesKind:
  32885. this.matricesIndices = data;
  32886. break;
  32887. case BABYLON.VertexBuffer.MatricesWeightsKind:
  32888. this.matricesWeights = data;
  32889. break;
  32890. case BABYLON.VertexBuffer.MatricesIndicesExtraKind:
  32891. this.matricesIndicesExtra = data;
  32892. break;
  32893. case BABYLON.VertexBuffer.MatricesWeightsExtraKind:
  32894. this.matricesWeightsExtra = data;
  32895. break;
  32896. }
  32897. };
  32898. /**
  32899. * Associates the vertexData to the passed Mesh.
  32900. * Sets it as updatable or not (default `false`).
  32901. * Returns the VertexData.
  32902. */
  32903. VertexData.prototype.applyToMesh = function (mesh, updatable) {
  32904. this._applyTo(mesh, updatable);
  32905. return this;
  32906. };
  32907. /**
  32908. * Associates the vertexData to the passed Geometry.
  32909. * Sets it as updatable or not (default `false`).
  32910. * Returns the VertexData.
  32911. */
  32912. VertexData.prototype.applyToGeometry = function (geometry, updatable) {
  32913. this._applyTo(geometry, updatable);
  32914. return this;
  32915. };
  32916. /**
  32917. * Updates the associated mesh.
  32918. * Returns the VertexData.
  32919. */
  32920. VertexData.prototype.updateMesh = function (mesh, updateExtends, makeItUnique) {
  32921. this._update(mesh);
  32922. return this;
  32923. };
  32924. /**
  32925. * Updates the associated geometry.
  32926. * Returns the VertexData.
  32927. */
  32928. VertexData.prototype.updateGeometry = function (geometry, updateExtends, makeItUnique) {
  32929. this._update(geometry);
  32930. return this;
  32931. };
  32932. VertexData.prototype._applyTo = function (meshOrGeometry, updatable) {
  32933. if (updatable === void 0) { updatable = false; }
  32934. if (this.positions) {
  32935. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.PositionKind, this.positions, updatable);
  32936. }
  32937. if (this.normals) {
  32938. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.NormalKind, this.normals, updatable);
  32939. }
  32940. if (this.tangents) {
  32941. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.TangentKind, this.tangents, updatable);
  32942. }
  32943. if (this.uvs) {
  32944. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UVKind, this.uvs, updatable);
  32945. }
  32946. if (this.uvs2) {
  32947. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV2Kind, this.uvs2, updatable);
  32948. }
  32949. if (this.uvs3) {
  32950. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV3Kind, this.uvs3, updatable);
  32951. }
  32952. if (this.uvs4) {
  32953. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV4Kind, this.uvs4, updatable);
  32954. }
  32955. if (this.uvs5) {
  32956. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV5Kind, this.uvs5, updatable);
  32957. }
  32958. if (this.uvs6) {
  32959. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV6Kind, this.uvs6, updatable);
  32960. }
  32961. if (this.colors) {
  32962. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.ColorKind, this.colors, updatable);
  32963. }
  32964. if (this.matricesIndices) {
  32965. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, this.matricesIndices, updatable);
  32966. }
  32967. if (this.matricesWeights) {
  32968. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, this.matricesWeights, updatable);
  32969. }
  32970. if (this.matricesIndicesExtra) {
  32971. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, this.matricesIndicesExtra, updatable);
  32972. }
  32973. if (this.matricesWeightsExtra) {
  32974. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, this.matricesWeightsExtra, updatable);
  32975. }
  32976. if (this.indices) {
  32977. meshOrGeometry.setIndices(this.indices, null, updatable);
  32978. }
  32979. return this;
  32980. };
  32981. VertexData.prototype._update = function (meshOrGeometry, updateExtends, makeItUnique) {
  32982. if (this.positions) {
  32983. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.PositionKind, this.positions, updateExtends, makeItUnique);
  32984. }
  32985. if (this.normals) {
  32986. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.NormalKind, this.normals, updateExtends, makeItUnique);
  32987. }
  32988. if (this.tangents) {
  32989. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.TangentKind, this.tangents, updateExtends, makeItUnique);
  32990. }
  32991. if (this.uvs) {
  32992. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UVKind, this.uvs, updateExtends, makeItUnique);
  32993. }
  32994. if (this.uvs2) {
  32995. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV2Kind, this.uvs2, updateExtends, makeItUnique);
  32996. }
  32997. if (this.uvs3) {
  32998. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV3Kind, this.uvs3, updateExtends, makeItUnique);
  32999. }
  33000. if (this.uvs4) {
  33001. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV4Kind, this.uvs4, updateExtends, makeItUnique);
  33002. }
  33003. if (this.uvs5) {
  33004. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV5Kind, this.uvs5, updateExtends, makeItUnique);
  33005. }
  33006. if (this.uvs6) {
  33007. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV6Kind, this.uvs6, updateExtends, makeItUnique);
  33008. }
  33009. if (this.colors) {
  33010. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.ColorKind, this.colors, updateExtends, makeItUnique);
  33011. }
  33012. if (this.matricesIndices) {
  33013. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, this.matricesIndices, updateExtends, makeItUnique);
  33014. }
  33015. if (this.matricesWeights) {
  33016. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, this.matricesWeights, updateExtends, makeItUnique);
  33017. }
  33018. if (this.matricesIndicesExtra) {
  33019. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, this.matricesIndicesExtra, updateExtends, makeItUnique);
  33020. }
  33021. if (this.matricesWeightsExtra) {
  33022. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, this.matricesWeightsExtra, updateExtends, makeItUnique);
  33023. }
  33024. if (this.indices) {
  33025. meshOrGeometry.setIndices(this.indices, null);
  33026. }
  33027. return this;
  33028. };
  33029. /**
  33030. * Transforms each position and each normal of the vertexData according to the passed Matrix.
  33031. * Returns the VertexData.
  33032. */
  33033. VertexData.prototype.transform = function (matrix) {
  33034. var transformed = BABYLON.Vector3.Zero();
  33035. var index;
  33036. if (this.positions) {
  33037. var position = BABYLON.Vector3.Zero();
  33038. for (index = 0; index < this.positions.length; index += 3) {
  33039. BABYLON.Vector3.FromArrayToRef(this.positions, index, position);
  33040. BABYLON.Vector3.TransformCoordinatesToRef(position, matrix, transformed);
  33041. this.positions[index] = transformed.x;
  33042. this.positions[index + 1] = transformed.y;
  33043. this.positions[index + 2] = transformed.z;
  33044. }
  33045. }
  33046. if (this.normals) {
  33047. var normal = BABYLON.Vector3.Zero();
  33048. for (index = 0; index < this.normals.length; index += 3) {
  33049. BABYLON.Vector3.FromArrayToRef(this.normals, index, normal);
  33050. BABYLON.Vector3.TransformNormalToRef(normal, matrix, transformed);
  33051. this.normals[index] = transformed.x;
  33052. this.normals[index + 1] = transformed.y;
  33053. this.normals[index + 2] = transformed.z;
  33054. }
  33055. }
  33056. if (this.tangents) {
  33057. var tangent = BABYLON.Vector4.Zero();
  33058. var tangentTransformed = BABYLON.Vector4.Zero();
  33059. for (index = 0; index < this.tangents.length; index += 4) {
  33060. BABYLON.Vector4.FromArrayToRef(this.tangents, index, tangent);
  33061. BABYLON.Vector4.TransformNormalToRef(tangent, matrix, tangentTransformed);
  33062. this.tangents[index] = tangentTransformed.x;
  33063. this.tangents[index + 1] = tangentTransformed.y;
  33064. this.tangents[index + 2] = tangentTransformed.z;
  33065. this.tangents[index + 3] = tangentTransformed.w;
  33066. }
  33067. }
  33068. return this;
  33069. };
  33070. /**
  33071. * Merges the passed VertexData into the current one.
  33072. * Returns the modified VertexData.
  33073. */
  33074. VertexData.prototype.merge = function (other) {
  33075. this._validate();
  33076. other._validate();
  33077. if (!this.normals !== !other.normals ||
  33078. !this.tangents !== !other.tangents ||
  33079. !this.uvs !== !other.uvs ||
  33080. !this.uvs2 !== !other.uvs2 ||
  33081. !this.uvs3 !== !other.uvs3 ||
  33082. !this.uvs4 !== !other.uvs4 ||
  33083. !this.uvs5 !== !other.uvs5 ||
  33084. !this.uvs6 !== !other.uvs6 ||
  33085. !this.colors !== !other.colors ||
  33086. !this.matricesIndices !== !other.matricesIndices ||
  33087. !this.matricesWeights !== !other.matricesWeights ||
  33088. !this.matricesIndicesExtra !== !other.matricesIndicesExtra ||
  33089. !this.matricesWeightsExtra !== !other.matricesWeightsExtra) {
  33090. throw new Error("Cannot merge vertex data that do not have the same set of attributes");
  33091. }
  33092. if (other.indices) {
  33093. if (!this.indices) {
  33094. this.indices = [];
  33095. }
  33096. var offset = this.positions ? this.positions.length / 3 : 0;
  33097. for (var index = 0; index < other.indices.length; index++) {
  33098. //TODO check type - if Int32Array | Uint32Array | Uint16Array!
  33099. this.indices.push(other.indices[index] + offset);
  33100. }
  33101. }
  33102. this.positions = this._mergeElement(this.positions, other.positions);
  33103. this.normals = this._mergeElement(this.normals, other.normals);
  33104. this.tangents = this._mergeElement(this.tangents, other.tangents);
  33105. this.uvs = this._mergeElement(this.uvs, other.uvs);
  33106. this.uvs2 = this._mergeElement(this.uvs2, other.uvs2);
  33107. this.uvs3 = this._mergeElement(this.uvs3, other.uvs3);
  33108. this.uvs4 = this._mergeElement(this.uvs4, other.uvs4);
  33109. this.uvs5 = this._mergeElement(this.uvs5, other.uvs5);
  33110. this.uvs6 = this._mergeElement(this.uvs6, other.uvs6);
  33111. this.colors = this._mergeElement(this.colors, other.colors);
  33112. this.matricesIndices = this._mergeElement(this.matricesIndices, other.matricesIndices);
  33113. this.matricesWeights = this._mergeElement(this.matricesWeights, other.matricesWeights);
  33114. this.matricesIndicesExtra = this._mergeElement(this.matricesIndicesExtra, other.matricesIndicesExtra);
  33115. this.matricesWeightsExtra = this._mergeElement(this.matricesWeightsExtra, other.matricesWeightsExtra);
  33116. return this;
  33117. };
  33118. VertexData.prototype._mergeElement = function (source, other) {
  33119. if (!source) {
  33120. return other;
  33121. }
  33122. if (!other) {
  33123. return source;
  33124. }
  33125. var len = other.length + source.length;
  33126. var isSrcTypedArray = source instanceof Float32Array;
  33127. var isOthTypedArray = other instanceof Float32Array;
  33128. // use non-loop method when the source is Float32Array
  33129. if (isSrcTypedArray) {
  33130. var ret32 = new Float32Array(len);
  33131. ret32.set(source);
  33132. ret32.set(other, source.length);
  33133. return ret32;
  33134. // source is number[], when other is also use concat
  33135. }
  33136. else if (!isOthTypedArray) {
  33137. return source.concat(other);
  33138. // source is a number[], but other is a Float32Array, loop required
  33139. }
  33140. else {
  33141. var ret = source.slice(0); // copy source to a separate array
  33142. for (var i = 0, len = other.length; i < len; i++) {
  33143. ret.push(other[i]);
  33144. }
  33145. return ret;
  33146. }
  33147. };
  33148. VertexData.prototype._validate = function () {
  33149. if (!this.positions) {
  33150. throw new Error("Positions are required");
  33151. }
  33152. var getElementCount = function (kind, values) {
  33153. var stride = BABYLON.VertexBuffer.DeduceStride(kind);
  33154. if ((values.length % stride) !== 0) {
  33155. throw new Error("The " + kind + "s array count must be a multiple of " + stride);
  33156. }
  33157. return values.length / stride;
  33158. };
  33159. var positionsElementCount = getElementCount(BABYLON.VertexBuffer.PositionKind, this.positions);
  33160. var validateElementCount = function (kind, values) {
  33161. var elementCount = getElementCount(kind, values);
  33162. if (elementCount !== positionsElementCount) {
  33163. throw new Error("The " + kind + "s element count (" + elementCount + ") does not match the positions count (" + positionsElementCount + ")");
  33164. }
  33165. };
  33166. if (this.normals)
  33167. validateElementCount(BABYLON.VertexBuffer.NormalKind, this.normals);
  33168. if (this.tangents)
  33169. validateElementCount(BABYLON.VertexBuffer.TangentKind, this.tangents);
  33170. if (this.uvs)
  33171. validateElementCount(BABYLON.VertexBuffer.UVKind, this.uvs);
  33172. if (this.uvs2)
  33173. validateElementCount(BABYLON.VertexBuffer.UV2Kind, this.uvs2);
  33174. if (this.uvs3)
  33175. validateElementCount(BABYLON.VertexBuffer.UV3Kind, this.uvs3);
  33176. if (this.uvs4)
  33177. validateElementCount(BABYLON.VertexBuffer.UV4Kind, this.uvs4);
  33178. if (this.uvs5)
  33179. validateElementCount(BABYLON.VertexBuffer.UV5Kind, this.uvs5);
  33180. if (this.uvs6)
  33181. validateElementCount(BABYLON.VertexBuffer.UV6Kind, this.uvs6);
  33182. if (this.colors)
  33183. validateElementCount(BABYLON.VertexBuffer.ColorKind, this.colors);
  33184. if (this.matricesIndices)
  33185. validateElementCount(BABYLON.VertexBuffer.MatricesIndicesKind, this.matricesIndices);
  33186. if (this.matricesWeights)
  33187. validateElementCount(BABYLON.VertexBuffer.MatricesWeightsKind, this.matricesWeights);
  33188. if (this.matricesIndicesExtra)
  33189. validateElementCount(BABYLON.VertexBuffer.MatricesIndicesExtraKind, this.matricesIndicesExtra);
  33190. if (this.matricesWeightsExtra)
  33191. validateElementCount(BABYLON.VertexBuffer.MatricesWeightsExtraKind, this.matricesWeightsExtra);
  33192. };
  33193. /**
  33194. * Serializes the VertexData.
  33195. * Returns a serialized object.
  33196. */
  33197. VertexData.prototype.serialize = function () {
  33198. var serializationObject = this.serialize();
  33199. if (this.positions) {
  33200. serializationObject.positions = this.positions;
  33201. }
  33202. if (this.normals) {
  33203. serializationObject.normals = this.normals;
  33204. }
  33205. if (this.tangents) {
  33206. serializationObject.tangents = this.tangents;
  33207. }
  33208. if (this.uvs) {
  33209. serializationObject.uvs = this.uvs;
  33210. }
  33211. if (this.uvs2) {
  33212. serializationObject.uvs2 = this.uvs2;
  33213. }
  33214. if (this.uvs3) {
  33215. serializationObject.uvs3 = this.uvs3;
  33216. }
  33217. if (this.uvs4) {
  33218. serializationObject.uvs4 = this.uvs4;
  33219. }
  33220. if (this.uvs5) {
  33221. serializationObject.uvs5 = this.uvs5;
  33222. }
  33223. if (this.uvs6) {
  33224. serializationObject.uvs6 = this.uvs6;
  33225. }
  33226. if (this.colors) {
  33227. serializationObject.colors = this.colors;
  33228. }
  33229. if (this.matricesIndices) {
  33230. serializationObject.matricesIndices = this.matricesIndices;
  33231. serializationObject.matricesIndices._isExpanded = true;
  33232. }
  33233. if (this.matricesWeights) {
  33234. serializationObject.matricesWeights = this.matricesWeights;
  33235. }
  33236. if (this.matricesIndicesExtra) {
  33237. serializationObject.matricesIndicesExtra = this.matricesIndicesExtra;
  33238. serializationObject.matricesIndicesExtra._isExpanded = true;
  33239. }
  33240. if (this.matricesWeightsExtra) {
  33241. serializationObject.matricesWeightsExtra = this.matricesWeightsExtra;
  33242. }
  33243. serializationObject.indices = this.indices;
  33244. return serializationObject;
  33245. };
  33246. // Statics
  33247. /**
  33248. * Returns the object VertexData associated to the passed mesh.
  33249. */
  33250. VertexData.ExtractFromMesh = function (mesh, copyWhenShared, forceCopy) {
  33251. return VertexData._ExtractFrom(mesh, copyWhenShared, forceCopy);
  33252. };
  33253. /**
  33254. * Returns the object VertexData associated to the passed geometry.
  33255. */
  33256. VertexData.ExtractFromGeometry = function (geometry, copyWhenShared, forceCopy) {
  33257. return VertexData._ExtractFrom(geometry, copyWhenShared, forceCopy);
  33258. };
  33259. VertexData._ExtractFrom = function (meshOrGeometry, copyWhenShared, forceCopy) {
  33260. var result = new VertexData();
  33261. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  33262. result.positions = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.PositionKind, copyWhenShared, forceCopy);
  33263. }
  33264. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  33265. result.normals = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.NormalKind, copyWhenShared, forceCopy);
  33266. }
  33267. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind)) {
  33268. result.tangents = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.TangentKind, copyWhenShared, forceCopy);
  33269. }
  33270. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  33271. result.uvs = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UVKind, copyWhenShared, forceCopy);
  33272. }
  33273. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  33274. result.uvs2 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV2Kind, copyWhenShared, forceCopy);
  33275. }
  33276. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV3Kind)) {
  33277. result.uvs3 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV3Kind, copyWhenShared, forceCopy);
  33278. }
  33279. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV4Kind)) {
  33280. result.uvs4 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV4Kind, copyWhenShared, forceCopy);
  33281. }
  33282. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV5Kind)) {
  33283. result.uvs5 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV5Kind, copyWhenShared, forceCopy);
  33284. }
  33285. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV6Kind)) {
  33286. result.uvs6 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV6Kind, copyWhenShared, forceCopy);
  33287. }
  33288. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  33289. result.colors = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.ColorKind, copyWhenShared, forceCopy);
  33290. }
  33291. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  33292. result.matricesIndices = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, copyWhenShared, forceCopy);
  33293. }
  33294. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  33295. result.matricesWeights = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, copyWhenShared, forceCopy);
  33296. }
  33297. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesExtraKind)) {
  33298. result.matricesIndicesExtra = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, copyWhenShared, forceCopy);
  33299. }
  33300. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsExtraKind)) {
  33301. result.matricesWeightsExtra = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, copyWhenShared, forceCopy);
  33302. }
  33303. result.indices = meshOrGeometry.getIndices(copyWhenShared);
  33304. return result;
  33305. };
  33306. /**
  33307. * Creates the vertexData of the Ribbon.
  33308. */
  33309. VertexData.CreateRibbon = function (options) {
  33310. var pathArray = options.pathArray;
  33311. var closeArray = options.closeArray || false;
  33312. var closePath = options.closePath || false;
  33313. var invertUV = options.invertUV || false;
  33314. var defaultOffset = Math.floor(pathArray[0].length / 2);
  33315. var offset = options.offset || defaultOffset;
  33316. offset = offset > defaultOffset ? defaultOffset : Math.floor(offset); // offset max allowed : defaultOffset
  33317. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  33318. var customUV = options.uvs;
  33319. var customColors = options.colors;
  33320. var positions = [];
  33321. var indices = [];
  33322. var normals = [];
  33323. var uvs = [];
  33324. var us = []; // us[path_id] = [uDist1, uDist2, uDist3 ... ] distances between points on path path_id
  33325. var vs = []; // vs[i] = [vDist1, vDist2, vDist3, ... ] distances between points i of consecutives paths from pathArray
  33326. var uTotalDistance = []; // uTotalDistance[p] : total distance of path p
  33327. var vTotalDistance = []; // vTotalDistance[i] : total distance between points i of first and last path from pathArray
  33328. var minlg; // minimal length among all paths from pathArray
  33329. var lg = []; // array of path lengths : nb of vertex per path
  33330. var idx = []; // array of path indexes : index of each path (first vertex) in the total vertex number
  33331. var p; // path iterator
  33332. var i; // point iterator
  33333. var j; // point iterator
  33334. // if single path in pathArray
  33335. if (pathArray.length < 2) {
  33336. var ar1 = [];
  33337. var ar2 = [];
  33338. for (i = 0; i < pathArray[0].length - offset; i++) {
  33339. ar1.push(pathArray[0][i]);
  33340. ar2.push(pathArray[0][i + offset]);
  33341. }
  33342. pathArray = [ar1, ar2];
  33343. }
  33344. // positions and horizontal distances (u)
  33345. var idc = 0;
  33346. var closePathCorr = (closePath) ? 1 : 0; // the final index will be +1 if closePath
  33347. var path;
  33348. var l;
  33349. minlg = pathArray[0].length;
  33350. var vectlg;
  33351. var dist;
  33352. for (p = 0; p < pathArray.length; p++) {
  33353. uTotalDistance[p] = 0;
  33354. us[p] = [0];
  33355. path = pathArray[p];
  33356. l = path.length;
  33357. minlg = (minlg < l) ? minlg : l;
  33358. j = 0;
  33359. while (j < l) {
  33360. positions.push(path[j].x, path[j].y, path[j].z);
  33361. if (j > 0) {
  33362. vectlg = path[j].subtract(path[j - 1]).length();
  33363. dist = vectlg + uTotalDistance[p];
  33364. us[p].push(dist);
  33365. uTotalDistance[p] = dist;
  33366. }
  33367. j++;
  33368. }
  33369. if (closePath) {
  33370. j--;
  33371. positions.push(path[0].x, path[0].y, path[0].z);
  33372. vectlg = path[j].subtract(path[0]).length();
  33373. dist = vectlg + uTotalDistance[p];
  33374. us[p].push(dist);
  33375. uTotalDistance[p] = dist;
  33376. }
  33377. lg[p] = l + closePathCorr;
  33378. idx[p] = idc;
  33379. idc += (l + closePathCorr);
  33380. }
  33381. // vertical distances (v)
  33382. var path1;
  33383. var path2;
  33384. var vertex1 = null;
  33385. var vertex2 = null;
  33386. for (i = 0; i < minlg + closePathCorr; i++) {
  33387. vTotalDistance[i] = 0;
  33388. vs[i] = [0];
  33389. for (p = 0; p < pathArray.length - 1; p++) {
  33390. path1 = pathArray[p];
  33391. path2 = pathArray[p + 1];
  33392. if (i === minlg) {
  33393. vertex1 = path1[0];
  33394. vertex2 = path2[0];
  33395. }
  33396. else {
  33397. vertex1 = path1[i];
  33398. vertex2 = path2[i];
  33399. }
  33400. vectlg = vertex2.subtract(vertex1).length();
  33401. dist = vectlg + vTotalDistance[i];
  33402. vs[i].push(dist);
  33403. vTotalDistance[i] = dist;
  33404. }
  33405. if (closeArray && vertex2 && vertex1) {
  33406. path1 = pathArray[p];
  33407. path2 = pathArray[0];
  33408. if (i === minlg) {
  33409. vertex2 = path2[0];
  33410. }
  33411. vectlg = vertex2.subtract(vertex1).length();
  33412. dist = vectlg + vTotalDistance[i];
  33413. vTotalDistance[i] = dist;
  33414. }
  33415. }
  33416. // uvs
  33417. var u;
  33418. var v;
  33419. if (customUV) {
  33420. for (p = 0; p < customUV.length; p++) {
  33421. uvs.push(customUV[p].x, customUV[p].y);
  33422. }
  33423. }
  33424. else {
  33425. for (p = 0; p < pathArray.length; p++) {
  33426. for (i = 0; i < minlg + closePathCorr; i++) {
  33427. u = (uTotalDistance[p] != 0.0) ? us[p][i] / uTotalDistance[p] : 0.0;
  33428. v = (vTotalDistance[i] != 0.0) ? vs[i][p] / vTotalDistance[i] : 0.0;
  33429. if (invertUV) {
  33430. uvs.push(v, u);
  33431. }
  33432. else {
  33433. uvs.push(u, v);
  33434. }
  33435. }
  33436. }
  33437. }
  33438. // indices
  33439. p = 0; // path index
  33440. var pi = 0; // positions array index
  33441. var l1 = lg[p] - 1; // path1 length
  33442. var l2 = lg[p + 1] - 1; // path2 length
  33443. var min = (l1 < l2) ? l1 : l2; // current path stop index
  33444. var shft = idx[1] - idx[0]; // shift
  33445. var path1nb = closeArray ? lg.length : lg.length - 1; // number of path1 to iterate on
  33446. while (pi <= min && p < path1nb) {
  33447. // 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
  33448. indices.push(pi, pi + shft, pi + 1);
  33449. indices.push(pi + shft + 1, pi + 1, pi + shft);
  33450. pi += 1;
  33451. if (pi === min) {
  33452. p++;
  33453. if (p === lg.length - 1) {
  33454. shft = idx[0] - idx[p];
  33455. l1 = lg[p] - 1;
  33456. l2 = lg[0] - 1;
  33457. }
  33458. else {
  33459. shft = idx[p + 1] - idx[p];
  33460. l1 = lg[p] - 1;
  33461. l2 = lg[p + 1] - 1;
  33462. }
  33463. pi = idx[p];
  33464. min = (l1 < l2) ? l1 + pi : l2 + pi;
  33465. }
  33466. }
  33467. // normals
  33468. VertexData.ComputeNormals(positions, indices, normals);
  33469. if (closePath) {
  33470. var indexFirst = 0;
  33471. var indexLast = 0;
  33472. for (p = 0; p < pathArray.length; p++) {
  33473. indexFirst = idx[p] * 3;
  33474. if (p + 1 < pathArray.length) {
  33475. indexLast = (idx[p + 1] - 1) * 3;
  33476. }
  33477. else {
  33478. indexLast = normals.length - 3;
  33479. }
  33480. normals[indexFirst] = (normals[indexFirst] + normals[indexLast]) * 0.5;
  33481. normals[indexFirst + 1] = (normals[indexFirst + 1] + normals[indexLast + 1]) * 0.5;
  33482. normals[indexFirst + 2] = (normals[indexFirst + 2] + normals[indexLast + 2]) * 0.5;
  33483. normals[indexLast] = normals[indexFirst];
  33484. normals[indexLast + 1] = normals[indexFirst + 1];
  33485. normals[indexLast + 2] = normals[indexFirst + 2];
  33486. }
  33487. }
  33488. // sides
  33489. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  33490. // Colors
  33491. var colors = null;
  33492. if (customColors) {
  33493. colors = new Float32Array(customColors.length * 4);
  33494. for (var c = 0; c < customColors.length; c++) {
  33495. colors[c * 4] = customColors[c].r;
  33496. colors[c * 4 + 1] = customColors[c].g;
  33497. colors[c * 4 + 2] = customColors[c].b;
  33498. colors[c * 4 + 3] = customColors[c].a;
  33499. }
  33500. }
  33501. // Result
  33502. var vertexData = new VertexData();
  33503. var positions32 = new Float32Array(positions);
  33504. var normals32 = new Float32Array(normals);
  33505. var uvs32 = new Float32Array(uvs);
  33506. vertexData.indices = indices;
  33507. vertexData.positions = positions32;
  33508. vertexData.normals = normals32;
  33509. vertexData.uvs = uvs32;
  33510. if (colors) {
  33511. vertexData.set(colors, BABYLON.VertexBuffer.ColorKind);
  33512. }
  33513. if (closePath) {
  33514. vertexData._idx = idx;
  33515. }
  33516. return vertexData;
  33517. };
  33518. /**
  33519. * Creates the VertexData of the Box.
  33520. */
  33521. VertexData.CreateBox = function (options) {
  33522. var normalsSource = [
  33523. new BABYLON.Vector3(0, 0, 1),
  33524. new BABYLON.Vector3(0, 0, -1),
  33525. new BABYLON.Vector3(1, 0, 0),
  33526. new BABYLON.Vector3(-1, 0, 0),
  33527. new BABYLON.Vector3(0, 1, 0),
  33528. new BABYLON.Vector3(0, -1, 0)
  33529. ];
  33530. var indices = [];
  33531. var positions = [];
  33532. var normals = [];
  33533. var uvs = [];
  33534. var width = options.width || options.size || 1;
  33535. var height = options.height || options.size || 1;
  33536. var depth = options.depth || options.size || 1;
  33537. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  33538. var faceUV = options.faceUV || new Array(6);
  33539. var faceColors = options.faceColors;
  33540. var colors = [];
  33541. // default face colors and UV if undefined
  33542. for (var f = 0; f < 6; f++) {
  33543. if (faceUV[f] === undefined) {
  33544. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  33545. }
  33546. if (faceColors && faceColors[f] === undefined) {
  33547. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  33548. }
  33549. }
  33550. var scaleVector = new BABYLON.Vector3(width / 2, height / 2, depth / 2);
  33551. // Create each face in turn.
  33552. for (var index = 0; index < normalsSource.length; index++) {
  33553. var normal = normalsSource[index];
  33554. // Get two vectors perpendicular to the face normal and to each other.
  33555. var side1 = new BABYLON.Vector3(normal.y, normal.z, normal.x);
  33556. var side2 = BABYLON.Vector3.Cross(normal, side1);
  33557. // Six indices (two triangles) per face.
  33558. var verticesLength = positions.length / 3;
  33559. indices.push(verticesLength);
  33560. indices.push(verticesLength + 1);
  33561. indices.push(verticesLength + 2);
  33562. indices.push(verticesLength);
  33563. indices.push(verticesLength + 2);
  33564. indices.push(verticesLength + 3);
  33565. // Four vertices per face.
  33566. var vertex = normal.subtract(side1).subtract(side2).multiply(scaleVector);
  33567. positions.push(vertex.x, vertex.y, vertex.z);
  33568. normals.push(normal.x, normal.y, normal.z);
  33569. uvs.push(faceUV[index].z, faceUV[index].w);
  33570. if (faceColors) {
  33571. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  33572. }
  33573. vertex = normal.subtract(side1).add(side2).multiply(scaleVector);
  33574. positions.push(vertex.x, vertex.y, vertex.z);
  33575. normals.push(normal.x, normal.y, normal.z);
  33576. uvs.push(faceUV[index].x, faceUV[index].w);
  33577. if (faceColors) {
  33578. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  33579. }
  33580. vertex = normal.add(side1).add(side2).multiply(scaleVector);
  33581. positions.push(vertex.x, vertex.y, vertex.z);
  33582. normals.push(normal.x, normal.y, normal.z);
  33583. uvs.push(faceUV[index].x, faceUV[index].y);
  33584. if (faceColors) {
  33585. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  33586. }
  33587. vertex = normal.add(side1).subtract(side2).multiply(scaleVector);
  33588. positions.push(vertex.x, vertex.y, vertex.z);
  33589. normals.push(normal.x, normal.y, normal.z);
  33590. uvs.push(faceUV[index].z, faceUV[index].y);
  33591. if (faceColors) {
  33592. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  33593. }
  33594. }
  33595. // sides
  33596. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  33597. // Result
  33598. var vertexData = new VertexData();
  33599. vertexData.indices = indices;
  33600. vertexData.positions = positions;
  33601. vertexData.normals = normals;
  33602. vertexData.uvs = uvs;
  33603. if (faceColors) {
  33604. var totalColors = (sideOrientation === BABYLON.Mesh.DOUBLESIDE) ? colors.concat(colors) : colors;
  33605. vertexData.colors = totalColors;
  33606. }
  33607. return vertexData;
  33608. };
  33609. /**
  33610. * Creates the VertexData of the Sphere.
  33611. */
  33612. VertexData.CreateSphere = function (options) {
  33613. var segments = options.segments || 32;
  33614. var diameterX = options.diameterX || options.diameter || 1;
  33615. var diameterY = options.diameterY || options.diameter || 1;
  33616. var diameterZ = options.diameterZ || options.diameter || 1;
  33617. var arc = options.arc && (options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc || 1.0;
  33618. var slice = options.slice && (options.slice <= 0) ? 1.0 : options.slice || 1.0;
  33619. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  33620. var radius = new BABYLON.Vector3(diameterX / 2, diameterY / 2, diameterZ / 2);
  33621. var totalZRotationSteps = 2 + segments;
  33622. var totalYRotationSteps = 2 * totalZRotationSteps;
  33623. var indices = [];
  33624. var positions = [];
  33625. var normals = [];
  33626. var uvs = [];
  33627. for (var zRotationStep = 0; zRotationStep <= totalZRotationSteps; zRotationStep++) {
  33628. var normalizedZ = zRotationStep / totalZRotationSteps;
  33629. var angleZ = normalizedZ * Math.PI * slice;
  33630. for (var yRotationStep = 0; yRotationStep <= totalYRotationSteps; yRotationStep++) {
  33631. var normalizedY = yRotationStep / totalYRotationSteps;
  33632. var angleY = normalizedY * Math.PI * 2 * arc;
  33633. var rotationZ = BABYLON.Matrix.RotationZ(-angleZ);
  33634. var rotationY = BABYLON.Matrix.RotationY(angleY);
  33635. var afterRotZ = BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.Up(), rotationZ);
  33636. var complete = BABYLON.Vector3.TransformCoordinates(afterRotZ, rotationY);
  33637. var vertex = complete.multiply(radius);
  33638. var normal = complete.divide(radius).normalize();
  33639. positions.push(vertex.x, vertex.y, vertex.z);
  33640. normals.push(normal.x, normal.y, normal.z);
  33641. uvs.push(normalizedY, normalizedZ);
  33642. }
  33643. if (zRotationStep > 0) {
  33644. var verticesCount = positions.length / 3;
  33645. for (var firstIndex = verticesCount - 2 * (totalYRotationSteps + 1); (firstIndex + totalYRotationSteps + 2) < verticesCount; firstIndex++) {
  33646. indices.push((firstIndex));
  33647. indices.push((firstIndex + 1));
  33648. indices.push(firstIndex + totalYRotationSteps + 1);
  33649. indices.push((firstIndex + totalYRotationSteps + 1));
  33650. indices.push((firstIndex + 1));
  33651. indices.push((firstIndex + totalYRotationSteps + 2));
  33652. }
  33653. }
  33654. }
  33655. // Sides
  33656. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  33657. // Result
  33658. var vertexData = new VertexData();
  33659. vertexData.indices = indices;
  33660. vertexData.positions = positions;
  33661. vertexData.normals = normals;
  33662. vertexData.uvs = uvs;
  33663. return vertexData;
  33664. };
  33665. /**
  33666. * Creates the VertexData of the Cylinder or Cone.
  33667. */
  33668. VertexData.CreateCylinder = function (options) {
  33669. var height = options.height || 2;
  33670. var diameterTop = (options.diameterTop === 0) ? 0 : options.diameterTop || options.diameter || 1;
  33671. var diameterBottom = (options.diameterBottom === 0) ? 0 : options.diameterBottom || options.diameter || 1;
  33672. var tessellation = options.tessellation || 24;
  33673. var subdivisions = options.subdivisions || 1;
  33674. var hasRings = options.hasRings ? true : false;
  33675. var enclose = options.enclose ? true : false;
  33676. var arc = options.arc && (options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc || 1.0;
  33677. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  33678. var faceUV = options.faceUV || new Array(3);
  33679. var faceColors = options.faceColors;
  33680. // default face colors and UV if undefined
  33681. var quadNb = (arc !== 1 && enclose) ? 2 : 0;
  33682. var ringNb = (hasRings) ? subdivisions : 1;
  33683. var surfaceNb = 2 + (1 + quadNb) * ringNb;
  33684. var f;
  33685. for (f = 0; f < surfaceNb; f++) {
  33686. if (faceColors && faceColors[f] === undefined) {
  33687. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  33688. }
  33689. }
  33690. for (f = 0; f < surfaceNb; f++) {
  33691. if (faceUV && faceUV[f] === undefined) {
  33692. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  33693. }
  33694. }
  33695. var indices = new Array();
  33696. var positions = new Array();
  33697. var normals = new Array();
  33698. var uvs = new Array();
  33699. var colors = new Array();
  33700. var angle_step = Math.PI * 2 * arc / tessellation;
  33701. var angle;
  33702. var h;
  33703. var radius;
  33704. var tan = (diameterBottom - diameterTop) / 2 / height;
  33705. var ringVertex = BABYLON.Vector3.Zero();
  33706. var ringNormal = BABYLON.Vector3.Zero();
  33707. var ringFirstVertex = BABYLON.Vector3.Zero();
  33708. var ringFirstNormal = BABYLON.Vector3.Zero();
  33709. var quadNormal = BABYLON.Vector3.Zero();
  33710. var Y = BABYLON.Axis.Y;
  33711. // positions, normals, uvs
  33712. var i;
  33713. var j;
  33714. var r;
  33715. var ringIdx = 1;
  33716. var s = 1; // surface index
  33717. var cs = 0;
  33718. var v = 0;
  33719. for (i = 0; i <= subdivisions; i++) {
  33720. h = i / subdivisions;
  33721. radius = (h * (diameterTop - diameterBottom) + diameterBottom) / 2;
  33722. ringIdx = (hasRings && i !== 0 && i !== subdivisions) ? 2 : 1;
  33723. for (r = 0; r < ringIdx; r++) {
  33724. if (hasRings) {
  33725. s += r;
  33726. }
  33727. if (enclose) {
  33728. s += 2 * r;
  33729. }
  33730. for (j = 0; j <= tessellation; j++) {
  33731. angle = j * angle_step;
  33732. // position
  33733. ringVertex.x = Math.cos(-angle) * radius;
  33734. ringVertex.y = -height / 2 + h * height;
  33735. ringVertex.z = Math.sin(-angle) * radius;
  33736. // normal
  33737. if (diameterTop === 0 && i === subdivisions) {
  33738. // if no top cap, reuse former normals
  33739. ringNormal.x = normals[normals.length - (tessellation + 1) * 3];
  33740. ringNormal.y = normals[normals.length - (tessellation + 1) * 3 + 1];
  33741. ringNormal.z = normals[normals.length - (tessellation + 1) * 3 + 2];
  33742. }
  33743. else {
  33744. ringNormal.x = ringVertex.x;
  33745. ringNormal.z = ringVertex.z;
  33746. ringNormal.y = Math.sqrt(ringNormal.x * ringNormal.x + ringNormal.z * ringNormal.z) * tan;
  33747. ringNormal.normalize();
  33748. }
  33749. // keep first ring vertex values for enclose
  33750. if (j === 0) {
  33751. ringFirstVertex.copyFrom(ringVertex);
  33752. ringFirstNormal.copyFrom(ringNormal);
  33753. }
  33754. positions.push(ringVertex.x, ringVertex.y, ringVertex.z);
  33755. normals.push(ringNormal.x, ringNormal.y, ringNormal.z);
  33756. if (hasRings) {
  33757. v = (cs !== s) ? faceUV[s].y : faceUV[s].w;
  33758. }
  33759. else {
  33760. v = faceUV[s].y + (faceUV[s].w - faceUV[s].y) * h;
  33761. }
  33762. uvs.push(faceUV[s].x + (faceUV[s].z - faceUV[s].x) * j / tessellation, v);
  33763. if (faceColors) {
  33764. colors.push(faceColors[s].r, faceColors[s].g, faceColors[s].b, faceColors[s].a);
  33765. }
  33766. }
  33767. // if enclose, add four vertices and their dedicated normals
  33768. if (arc !== 1 && enclose) {
  33769. positions.push(ringVertex.x, ringVertex.y, ringVertex.z);
  33770. positions.push(0, ringVertex.y, 0);
  33771. positions.push(0, ringVertex.y, 0);
  33772. positions.push(ringFirstVertex.x, ringFirstVertex.y, ringFirstVertex.z);
  33773. BABYLON.Vector3.CrossToRef(Y, ringNormal, quadNormal);
  33774. quadNormal.normalize();
  33775. normals.push(quadNormal.x, quadNormal.y, quadNormal.z, quadNormal.x, quadNormal.y, quadNormal.z);
  33776. BABYLON.Vector3.CrossToRef(ringFirstNormal, Y, quadNormal);
  33777. quadNormal.normalize();
  33778. normals.push(quadNormal.x, quadNormal.y, quadNormal.z, quadNormal.x, quadNormal.y, quadNormal.z);
  33779. if (hasRings) {
  33780. v = (cs !== s) ? faceUV[s + 1].y : faceUV[s + 1].w;
  33781. }
  33782. else {
  33783. v = faceUV[s + 1].y + (faceUV[s + 1].w - faceUV[s + 1].y) * h;
  33784. }
  33785. uvs.push(faceUV[s + 1].x, v);
  33786. uvs.push(faceUV[s + 1].z, v);
  33787. if (hasRings) {
  33788. v = (cs !== s) ? faceUV[s + 2].y : faceUV[s + 2].w;
  33789. }
  33790. else {
  33791. v = faceUV[s + 2].y + (faceUV[s + 2].w - faceUV[s + 2].y) * h;
  33792. }
  33793. uvs.push(faceUV[s + 2].x, v);
  33794. uvs.push(faceUV[s + 2].z, v);
  33795. if (faceColors) {
  33796. colors.push(faceColors[s + 1].r, faceColors[s + 1].g, faceColors[s + 1].b, faceColors[s + 1].a);
  33797. colors.push(faceColors[s + 1].r, faceColors[s + 1].g, faceColors[s + 1].b, faceColors[s + 1].a);
  33798. colors.push(faceColors[s + 2].r, faceColors[s + 2].g, faceColors[s + 2].b, faceColors[s + 2].a);
  33799. colors.push(faceColors[s + 2].r, faceColors[s + 2].g, faceColors[s + 2].b, faceColors[s + 2].a);
  33800. }
  33801. }
  33802. if (cs !== s) {
  33803. cs = s;
  33804. }
  33805. }
  33806. }
  33807. // indices
  33808. var e = (arc !== 1 && enclose) ? tessellation + 4 : tessellation; // correction of number of iteration if enclose
  33809. var s;
  33810. i = 0;
  33811. for (s = 0; s < subdivisions; s++) {
  33812. var i0 = 0;
  33813. var i1 = 0;
  33814. var i2 = 0;
  33815. var i3 = 0;
  33816. for (j = 0; j < tessellation; j++) {
  33817. i0 = i * (e + 1) + j;
  33818. i1 = (i + 1) * (e + 1) + j;
  33819. i2 = i * (e + 1) + (j + 1);
  33820. i3 = (i + 1) * (e + 1) + (j + 1);
  33821. indices.push(i0, i1, i2);
  33822. indices.push(i3, i2, i1);
  33823. }
  33824. if (arc !== 1 && enclose) {
  33825. indices.push(i0 + 2, i1 + 2, i2 + 2);
  33826. indices.push(i3 + 2, i2 + 2, i1 + 2);
  33827. indices.push(i0 + 4, i1 + 4, i2 + 4);
  33828. indices.push(i3 + 4, i2 + 4, i1 + 4);
  33829. }
  33830. i = (hasRings) ? (i + 2) : (i + 1);
  33831. }
  33832. // Caps
  33833. var createCylinderCap = function (isTop) {
  33834. var radius = isTop ? diameterTop / 2 : diameterBottom / 2;
  33835. if (radius === 0) {
  33836. return;
  33837. }
  33838. // Cap positions, normals & uvs
  33839. var angle;
  33840. var circleVector;
  33841. var i;
  33842. var u = (isTop) ? faceUV[surfaceNb - 1] : faceUV[0];
  33843. var c = null;
  33844. if (faceColors) {
  33845. c = (isTop) ? faceColors[surfaceNb - 1] : faceColors[0];
  33846. }
  33847. // cap center
  33848. var vbase = positions.length / 3;
  33849. var offset = isTop ? height / 2 : -height / 2;
  33850. var center = new BABYLON.Vector3(0, offset, 0);
  33851. positions.push(center.x, center.y, center.z);
  33852. normals.push(0, isTop ? 1 : -1, 0);
  33853. uvs.push(u.x + (u.z - u.x) * 0.5, u.y + (u.w - u.y) * 0.5);
  33854. if (c) {
  33855. colors.push(c.r, c.g, c.b, c.a);
  33856. }
  33857. var textureScale = new BABYLON.Vector2(0.5, 0.5);
  33858. for (i = 0; i <= tessellation; i++) {
  33859. angle = Math.PI * 2 * i * arc / tessellation;
  33860. var cos = Math.cos(-angle);
  33861. var sin = Math.sin(-angle);
  33862. circleVector = new BABYLON.Vector3(cos * radius, offset, sin * radius);
  33863. var textureCoordinate = new BABYLON.Vector2(cos * textureScale.x + 0.5, sin * textureScale.y + 0.5);
  33864. positions.push(circleVector.x, circleVector.y, circleVector.z);
  33865. normals.push(0, isTop ? 1 : -1, 0);
  33866. uvs.push(u.x + (u.z - u.x) * textureCoordinate.x, u.y + (u.w - u.y) * textureCoordinate.y);
  33867. if (c) {
  33868. colors.push(c.r, c.g, c.b, c.a);
  33869. }
  33870. }
  33871. // Cap indices
  33872. for (i = 0; i < tessellation; i++) {
  33873. if (!isTop) {
  33874. indices.push(vbase);
  33875. indices.push(vbase + (i + 1));
  33876. indices.push(vbase + (i + 2));
  33877. }
  33878. else {
  33879. indices.push(vbase);
  33880. indices.push(vbase + (i + 2));
  33881. indices.push(vbase + (i + 1));
  33882. }
  33883. }
  33884. };
  33885. // add caps to geometry
  33886. createCylinderCap(false);
  33887. createCylinderCap(true);
  33888. // Sides
  33889. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  33890. var vertexData = new VertexData();
  33891. vertexData.indices = indices;
  33892. vertexData.positions = positions;
  33893. vertexData.normals = normals;
  33894. vertexData.uvs = uvs;
  33895. if (faceColors) {
  33896. vertexData.colors = colors;
  33897. }
  33898. return vertexData;
  33899. };
  33900. /**
  33901. * Creates the VertexData of the Torus.
  33902. */
  33903. VertexData.CreateTorus = function (options) {
  33904. var indices = [];
  33905. var positions = [];
  33906. var normals = [];
  33907. var uvs = [];
  33908. var diameter = options.diameter || 1;
  33909. var thickness = options.thickness || 0.5;
  33910. var tessellation = options.tessellation || 16;
  33911. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  33912. var stride = tessellation + 1;
  33913. for (var i = 0; i <= tessellation; i++) {
  33914. var u = i / tessellation;
  33915. var outerAngle = i * Math.PI * 2.0 / tessellation - Math.PI / 2.0;
  33916. var transform = BABYLON.Matrix.Translation(diameter / 2.0, 0, 0).multiply(BABYLON.Matrix.RotationY(outerAngle));
  33917. for (var j = 0; j <= tessellation; j++) {
  33918. var v = 1 - j / tessellation;
  33919. var innerAngle = j * Math.PI * 2.0 / tessellation + Math.PI;
  33920. var dx = Math.cos(innerAngle);
  33921. var dy = Math.sin(innerAngle);
  33922. // Create a vertex.
  33923. var normal = new BABYLON.Vector3(dx, dy, 0);
  33924. var position = normal.scale(thickness / 2);
  33925. var textureCoordinate = new BABYLON.Vector2(u, v);
  33926. position = BABYLON.Vector3.TransformCoordinates(position, transform);
  33927. normal = BABYLON.Vector3.TransformNormal(normal, transform);
  33928. positions.push(position.x, position.y, position.z);
  33929. normals.push(normal.x, normal.y, normal.z);
  33930. uvs.push(textureCoordinate.x, textureCoordinate.y);
  33931. // And create indices for two triangles.
  33932. var nextI = (i + 1) % stride;
  33933. var nextJ = (j + 1) % stride;
  33934. indices.push(i * stride + j);
  33935. indices.push(i * stride + nextJ);
  33936. indices.push(nextI * stride + j);
  33937. indices.push(i * stride + nextJ);
  33938. indices.push(nextI * stride + nextJ);
  33939. indices.push(nextI * stride + j);
  33940. }
  33941. }
  33942. // Sides
  33943. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  33944. // Result
  33945. var vertexData = new VertexData();
  33946. vertexData.indices = indices;
  33947. vertexData.positions = positions;
  33948. vertexData.normals = normals;
  33949. vertexData.uvs = uvs;
  33950. return vertexData;
  33951. };
  33952. /**
  33953. * Creates the VertexData of the LineSystem.
  33954. */
  33955. VertexData.CreateLineSystem = function (options) {
  33956. var indices = [];
  33957. var positions = [];
  33958. var lines = options.lines;
  33959. var colors = options.colors;
  33960. var vertexColors = [];
  33961. var idx = 0;
  33962. for (var l = 0; l < lines.length; l++) {
  33963. var points = lines[l];
  33964. for (var index = 0; index < points.length; index++) {
  33965. positions.push(points[index].x, points[index].y, points[index].z);
  33966. if (colors) {
  33967. var color = colors[l];
  33968. vertexColors.push(color[index].r, color[index].g, color[index].b, color[index].a);
  33969. }
  33970. if (index > 0) {
  33971. indices.push(idx - 1);
  33972. indices.push(idx);
  33973. }
  33974. idx++;
  33975. }
  33976. }
  33977. var vertexData = new VertexData();
  33978. vertexData.indices = indices;
  33979. vertexData.positions = positions;
  33980. if (colors) {
  33981. vertexData.colors = vertexColors;
  33982. }
  33983. return vertexData;
  33984. };
  33985. /**
  33986. * Create the VertexData of the DashedLines.
  33987. */
  33988. VertexData.CreateDashedLines = function (options) {
  33989. var dashSize = options.dashSize || 3;
  33990. var gapSize = options.gapSize || 1;
  33991. var dashNb = options.dashNb || 200;
  33992. var points = options.points;
  33993. var positions = new Array();
  33994. var indices = new Array();
  33995. var curvect = BABYLON.Vector3.Zero();
  33996. var lg = 0;
  33997. var nb = 0;
  33998. var shft = 0;
  33999. var dashshft = 0;
  34000. var curshft = 0;
  34001. var idx = 0;
  34002. var i = 0;
  34003. for (i = 0; i < points.length - 1; i++) {
  34004. points[i + 1].subtractToRef(points[i], curvect);
  34005. lg += curvect.length();
  34006. }
  34007. shft = lg / dashNb;
  34008. dashshft = dashSize * shft / (dashSize + gapSize);
  34009. for (i = 0; i < points.length - 1; i++) {
  34010. points[i + 1].subtractToRef(points[i], curvect);
  34011. nb = Math.floor(curvect.length() / shft);
  34012. curvect.normalize();
  34013. for (var j = 0; j < nb; j++) {
  34014. curshft = shft * j;
  34015. positions.push(points[i].x + curshft * curvect.x, points[i].y + curshft * curvect.y, points[i].z + curshft * curvect.z);
  34016. positions.push(points[i].x + (curshft + dashshft) * curvect.x, points[i].y + (curshft + dashshft) * curvect.y, points[i].z + (curshft + dashshft) * curvect.z);
  34017. indices.push(idx, idx + 1);
  34018. idx += 2;
  34019. }
  34020. }
  34021. // Result
  34022. var vertexData = new VertexData();
  34023. vertexData.positions = positions;
  34024. vertexData.indices = indices;
  34025. return vertexData;
  34026. };
  34027. /**
  34028. * Creates the VertexData of the Ground.
  34029. */
  34030. VertexData.CreateGround = function (options) {
  34031. var indices = [];
  34032. var positions = [];
  34033. var normals = [];
  34034. var uvs = [];
  34035. var row, col;
  34036. var width = options.width || 1;
  34037. var height = options.height || 1;
  34038. var subdivisionsX = options.subdivisionsX || options.subdivisions || 1;
  34039. var subdivisionsY = options.subdivisionsY || options.subdivisions || 1;
  34040. for (row = 0; row <= subdivisionsY; row++) {
  34041. for (col = 0; col <= subdivisionsX; col++) {
  34042. var position = new BABYLON.Vector3((col * width) / subdivisionsX - (width / 2.0), 0, ((subdivisionsY - row) * height) / subdivisionsY - (height / 2.0));
  34043. var normal = new BABYLON.Vector3(0, 1.0, 0);
  34044. positions.push(position.x, position.y, position.z);
  34045. normals.push(normal.x, normal.y, normal.z);
  34046. uvs.push(col / subdivisionsX, 1.0 - row / subdivisionsY);
  34047. }
  34048. }
  34049. for (row = 0; row < subdivisionsY; row++) {
  34050. for (col = 0; col < subdivisionsX; col++) {
  34051. indices.push(col + 1 + (row + 1) * (subdivisionsX + 1));
  34052. indices.push(col + 1 + row * (subdivisionsX + 1));
  34053. indices.push(col + row * (subdivisionsX + 1));
  34054. indices.push(col + (row + 1) * (subdivisionsX + 1));
  34055. indices.push(col + 1 + (row + 1) * (subdivisionsX + 1));
  34056. indices.push(col + row * (subdivisionsX + 1));
  34057. }
  34058. }
  34059. // Result
  34060. var vertexData = new VertexData();
  34061. vertexData.indices = indices;
  34062. vertexData.positions = positions;
  34063. vertexData.normals = normals;
  34064. vertexData.uvs = uvs;
  34065. return vertexData;
  34066. };
  34067. /**
  34068. * Creates the VertexData of the TiledGround.
  34069. */
  34070. VertexData.CreateTiledGround = function (options) {
  34071. var xmin = (options.xmin !== undefined && options.xmin !== null) ? options.xmin : -1.0;
  34072. var zmin = (options.zmin !== undefined && options.zmin !== null) ? options.zmin : -1.0;
  34073. var xmax = (options.xmax !== undefined && options.xmax !== null) ? options.xmax : 1.0;
  34074. var zmax = (options.zmax !== undefined && options.zmax !== null) ? options.zmax : 1.0;
  34075. var subdivisions = options.subdivisions || { w: 1, h: 1 };
  34076. var precision = options.precision || { w: 1, h: 1 };
  34077. var indices = new Array();
  34078. var positions = new Array();
  34079. var normals = new Array();
  34080. var uvs = new Array();
  34081. var row, col, tileRow, tileCol;
  34082. subdivisions.h = (subdivisions.h < 1) ? 1 : subdivisions.h;
  34083. subdivisions.w = (subdivisions.w < 1) ? 1 : subdivisions.w;
  34084. precision.w = (precision.w < 1) ? 1 : precision.w;
  34085. precision.h = (precision.h < 1) ? 1 : precision.h;
  34086. var tileSize = {
  34087. 'w': (xmax - xmin) / subdivisions.w,
  34088. 'h': (zmax - zmin) / subdivisions.h
  34089. };
  34090. function applyTile(xTileMin, zTileMin, xTileMax, zTileMax) {
  34091. // Indices
  34092. var base = positions.length / 3;
  34093. var rowLength = precision.w + 1;
  34094. for (row = 0; row < precision.h; row++) {
  34095. for (col = 0; col < precision.w; col++) {
  34096. var square = [
  34097. base + col + row * rowLength,
  34098. base + (col + 1) + row * rowLength,
  34099. base + (col + 1) + (row + 1) * rowLength,
  34100. base + col + (row + 1) * rowLength
  34101. ];
  34102. indices.push(square[1]);
  34103. indices.push(square[2]);
  34104. indices.push(square[3]);
  34105. indices.push(square[0]);
  34106. indices.push(square[1]);
  34107. indices.push(square[3]);
  34108. }
  34109. }
  34110. // Position, normals and uvs
  34111. var position = BABYLON.Vector3.Zero();
  34112. var normal = new BABYLON.Vector3(0, 1.0, 0);
  34113. for (row = 0; row <= precision.h; row++) {
  34114. position.z = (row * (zTileMax - zTileMin)) / precision.h + zTileMin;
  34115. for (col = 0; col <= precision.w; col++) {
  34116. position.x = (col * (xTileMax - xTileMin)) / precision.w + xTileMin;
  34117. position.y = 0;
  34118. positions.push(position.x, position.y, position.z);
  34119. normals.push(normal.x, normal.y, normal.z);
  34120. uvs.push(col / precision.w, row / precision.h);
  34121. }
  34122. }
  34123. }
  34124. for (tileRow = 0; tileRow < subdivisions.h; tileRow++) {
  34125. for (tileCol = 0; tileCol < subdivisions.w; tileCol++) {
  34126. applyTile(xmin + tileCol * tileSize.w, zmin + tileRow * tileSize.h, xmin + (tileCol + 1) * tileSize.w, zmin + (tileRow + 1) * tileSize.h);
  34127. }
  34128. }
  34129. // Result
  34130. var vertexData = new VertexData();
  34131. vertexData.indices = indices;
  34132. vertexData.positions = positions;
  34133. vertexData.normals = normals;
  34134. vertexData.uvs = uvs;
  34135. return vertexData;
  34136. };
  34137. /**
  34138. * Creates the VertexData of the Ground designed from a heightmap.
  34139. */
  34140. VertexData.CreateGroundFromHeightMap = function (options) {
  34141. var indices = [];
  34142. var positions = [];
  34143. var normals = [];
  34144. var uvs = [];
  34145. var row, col;
  34146. var filter = options.colorFilter || new BABYLON.Color3(0.3, 0.59, 0.11);
  34147. // Vertices
  34148. for (row = 0; row <= options.subdivisions; row++) {
  34149. for (col = 0; col <= options.subdivisions; col++) {
  34150. 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));
  34151. // Compute height
  34152. var heightMapX = (((position.x + options.width / 2) / options.width) * (options.bufferWidth - 1)) | 0;
  34153. var heightMapY = ((1.0 - (position.z + options.height / 2) / options.height) * (options.bufferHeight - 1)) | 0;
  34154. var pos = (heightMapX + heightMapY * options.bufferWidth) * 4;
  34155. var r = options.buffer[pos] / 255.0;
  34156. var g = options.buffer[pos + 1] / 255.0;
  34157. var b = options.buffer[pos + 2] / 255.0;
  34158. var gradient = r * filter.r + g * filter.g + b * filter.b;
  34159. position.y = options.minHeight + (options.maxHeight - options.minHeight) * gradient;
  34160. // Add vertex
  34161. positions.push(position.x, position.y, position.z);
  34162. normals.push(0, 0, 0);
  34163. uvs.push(col / options.subdivisions, 1.0 - row / options.subdivisions);
  34164. }
  34165. }
  34166. // Indices
  34167. for (row = 0; row < options.subdivisions; row++) {
  34168. for (col = 0; col < options.subdivisions; col++) {
  34169. indices.push(col + 1 + (row + 1) * (options.subdivisions + 1));
  34170. indices.push(col + 1 + row * (options.subdivisions + 1));
  34171. indices.push(col + row * (options.subdivisions + 1));
  34172. indices.push(col + (row + 1) * (options.subdivisions + 1));
  34173. indices.push(col + 1 + (row + 1) * (options.subdivisions + 1));
  34174. indices.push(col + row * (options.subdivisions + 1));
  34175. }
  34176. }
  34177. // Normals
  34178. VertexData.ComputeNormals(positions, indices, normals);
  34179. // Result
  34180. var vertexData = new VertexData();
  34181. vertexData.indices = indices;
  34182. vertexData.positions = positions;
  34183. vertexData.normals = normals;
  34184. vertexData.uvs = uvs;
  34185. return vertexData;
  34186. };
  34187. /**
  34188. * Creates the VertexData of the Plane.
  34189. */
  34190. VertexData.CreatePlane = function (options) {
  34191. var indices = [];
  34192. var positions = [];
  34193. var normals = [];
  34194. var uvs = [];
  34195. var width = options.width || options.size || 1;
  34196. var height = options.height || options.size || 1;
  34197. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  34198. // Vertices
  34199. var halfWidth = width / 2.0;
  34200. var halfHeight = height / 2.0;
  34201. positions.push(-halfWidth, -halfHeight, 0);
  34202. normals.push(0, 0, -1.0);
  34203. uvs.push(0.0, 0.0);
  34204. positions.push(halfWidth, -halfHeight, 0);
  34205. normals.push(0, 0, -1.0);
  34206. uvs.push(1.0, 0.0);
  34207. positions.push(halfWidth, halfHeight, 0);
  34208. normals.push(0, 0, -1.0);
  34209. uvs.push(1.0, 1.0);
  34210. positions.push(-halfWidth, halfHeight, 0);
  34211. normals.push(0, 0, -1.0);
  34212. uvs.push(0.0, 1.0);
  34213. // Indices
  34214. indices.push(0);
  34215. indices.push(1);
  34216. indices.push(2);
  34217. indices.push(0);
  34218. indices.push(2);
  34219. indices.push(3);
  34220. // Sides
  34221. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  34222. // Result
  34223. var vertexData = new VertexData();
  34224. vertexData.indices = indices;
  34225. vertexData.positions = positions;
  34226. vertexData.normals = normals;
  34227. vertexData.uvs = uvs;
  34228. return vertexData;
  34229. };
  34230. /**
  34231. * Creates the VertexData of the Disc or regular Polygon.
  34232. */
  34233. VertexData.CreateDisc = function (options) {
  34234. var positions = new Array();
  34235. var indices = new Array();
  34236. var normals = new Array();
  34237. var uvs = new Array();
  34238. var radius = options.radius || 0.5;
  34239. var tessellation = options.tessellation || 64;
  34240. var arc = options.arc && (options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc || 1.0;
  34241. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  34242. // positions and uvs
  34243. positions.push(0, 0, 0); // disc center first
  34244. uvs.push(0.5, 0.5);
  34245. var theta = Math.PI * 2 * arc;
  34246. var step = theta / tessellation;
  34247. for (var a = 0; a < theta; a += step) {
  34248. var x = Math.cos(a);
  34249. var y = Math.sin(a);
  34250. var u = (x + 1) / 2;
  34251. var v = (1 - y) / 2;
  34252. positions.push(radius * x, radius * y, 0);
  34253. uvs.push(u, v);
  34254. }
  34255. if (arc === 1) {
  34256. positions.push(positions[3], positions[4], positions[5]); // close the circle
  34257. uvs.push(uvs[2], uvs[3]);
  34258. }
  34259. //indices
  34260. var vertexNb = positions.length / 3;
  34261. for (var i = 1; i < vertexNb - 1; i++) {
  34262. indices.push(i + 1, 0, i);
  34263. }
  34264. // result
  34265. VertexData.ComputeNormals(positions, indices, normals);
  34266. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  34267. var vertexData = new VertexData();
  34268. vertexData.indices = indices;
  34269. vertexData.positions = positions;
  34270. vertexData.normals = normals;
  34271. vertexData.uvs = uvs;
  34272. return vertexData;
  34273. };
  34274. /**
  34275. * Re-creates the VertexData of the Polygon for sideOrientation.
  34276. */
  34277. VertexData.CreatePolygon = function (polygon, sideOrientation, fUV, fColors, frontUVs, backUVs) {
  34278. var faceUV = fUV || new Array(3);
  34279. var faceColors = fColors;
  34280. var colors = [];
  34281. // default face colors and UV if undefined
  34282. for (var f = 0; f < 3; f++) {
  34283. if (faceUV[f] === undefined) {
  34284. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  34285. }
  34286. if (faceColors && faceColors[f] === undefined) {
  34287. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  34288. }
  34289. }
  34290. var positions = polygon.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  34291. var normals = polygon.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  34292. var uvs = polygon.getVerticesData(BABYLON.VertexBuffer.UVKind);
  34293. var indices = polygon.getIndices();
  34294. // set face colours and textures
  34295. var idx = 0;
  34296. var face = 0;
  34297. for (var index = 0; index < normals.length; index += 3) {
  34298. //Edge Face no. 1
  34299. if (Math.abs(normals[index + 1]) < 0.001) {
  34300. face = 1;
  34301. }
  34302. //Top Face no. 0
  34303. if (Math.abs(normals[index + 1] - 1) < 0.001) {
  34304. face = 0;
  34305. }
  34306. //Bottom Face no. 2
  34307. if (Math.abs(normals[index + 1] + 1) < 0.001) {
  34308. face = 2;
  34309. }
  34310. idx = index / 3;
  34311. uvs[2 * idx] = (1 - uvs[2 * idx]) * faceUV[face].x + uvs[2 * idx] * faceUV[face].z;
  34312. uvs[2 * idx + 1] = (1 - uvs[2 * idx + 1]) * faceUV[face].y + uvs[2 * idx + 1] * faceUV[face].w;
  34313. if (faceColors) {
  34314. colors.push(faceColors[face].r, faceColors[face].g, faceColors[face].b, faceColors[face].a);
  34315. }
  34316. }
  34317. // sides
  34318. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, frontUVs, backUVs);
  34319. // Result
  34320. var vertexData = new VertexData();
  34321. vertexData.indices = indices;
  34322. vertexData.positions = positions;
  34323. vertexData.normals = normals;
  34324. vertexData.uvs = uvs;
  34325. if (faceColors) {
  34326. var totalColors = (sideOrientation === BABYLON.Mesh.DOUBLESIDE) ? colors.concat(colors) : colors;
  34327. vertexData.colors = totalColors;
  34328. }
  34329. return vertexData;
  34330. };
  34331. /**
  34332. * Creates the VertexData of the IcoSphere.
  34333. */
  34334. VertexData.CreateIcoSphere = function (options) {
  34335. var sideOrientation = options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  34336. var radius = options.radius || 1;
  34337. var flat = (options.flat === undefined) ? true : options.flat;
  34338. var subdivisions = options.subdivisions || 4;
  34339. var radiusX = options.radiusX || radius;
  34340. var radiusY = options.radiusY || radius;
  34341. var radiusZ = options.radiusZ || radius;
  34342. var t = (1 + Math.sqrt(5)) / 2;
  34343. // 12 vertex x,y,z
  34344. var ico_vertices = [
  34345. -1, t, -0, 1, t, 0, -1, -t, 0, 1, -t, 0,
  34346. 0, -1, -t, 0, 1, -t, 0, -1, t, 0, 1, t,
  34347. t, 0, 1, t, 0, -1, -t, 0, 1, -t, 0, -1 // v8-11
  34348. ];
  34349. // index of 3 vertex makes a face of icopshere
  34350. var ico_indices = [
  34351. 0, 11, 5, 0, 5, 1, 0, 1, 7, 0, 7, 10, 12, 22, 23,
  34352. 1, 5, 20, 5, 11, 4, 23, 22, 13, 22, 18, 6, 7, 1, 8,
  34353. 14, 21, 4, 14, 4, 2, 16, 13, 6, 15, 6, 19, 3, 8, 9,
  34354. 4, 21, 5, 13, 17, 23, 6, 13, 22, 19, 6, 18, 9, 8, 1
  34355. ];
  34356. // vertex for uv have aliased position, not for UV
  34357. var vertices_unalias_id = [
  34358. 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11,
  34359. // vertex alias
  34360. 0,
  34361. 2,
  34362. 3,
  34363. 3,
  34364. 3,
  34365. 4,
  34366. 7,
  34367. 8,
  34368. 9,
  34369. 9,
  34370. 10,
  34371. 11 // 23: B + 12
  34372. ];
  34373. // uv as integer step (not pixels !)
  34374. var ico_vertexuv = [
  34375. 5, 1, 3, 1, 6, 4, 0, 0,
  34376. 5, 3, 4, 2, 2, 2, 4, 0,
  34377. 2, 0, 1, 1, 6, 0, 6, 2,
  34378. // vertex alias (for same vertex on different faces)
  34379. 0, 4,
  34380. 3, 3,
  34381. 4, 4,
  34382. 3, 1,
  34383. 4, 2,
  34384. 4, 4,
  34385. 0, 2,
  34386. 1, 1,
  34387. 2, 2,
  34388. 3, 3,
  34389. 1, 3,
  34390. 2, 4 // 23: B + 12
  34391. ];
  34392. // Vertices[0, 1, ...9, A, B] : position on UV plane
  34393. // '+' indicate duplicate position to be fixed (3,9:0,2,3,4,7,8,A,B)
  34394. // First island of uv mapping
  34395. // v = 4h 3+ 2
  34396. // v = 3h 9+ 4
  34397. // v = 2h 9+ 5 B
  34398. // v = 1h 9 1 0
  34399. // v = 0h 3 8 7 A
  34400. // u = 0 1 2 3 4 5 6 *a
  34401. // Second island of uv mapping
  34402. // v = 4h 0+ B+ 4+
  34403. // v = 3h A+ 2+
  34404. // v = 2h 7+ 6 3+
  34405. // v = 1h 8+ 3+
  34406. // v = 0h
  34407. // u = 0 1 2 3 4 5 6 *a
  34408. // Face layout on texture UV mapping
  34409. // ============
  34410. // \ 4 /\ 16 / ======
  34411. // \ / \ / /\ 11 /
  34412. // \/ 7 \/ / \ /
  34413. // ======= / 10 \/
  34414. // /\ 17 /\ =======
  34415. // / \ / \ \ 15 /\
  34416. // / 8 \/ 12 \ \ / \
  34417. // ============ \/ 6 \
  34418. // \ 18 /\ ============
  34419. // \ / \ \ 5 /\ 0 /
  34420. // \/ 13 \ \ / \ /
  34421. // ======= \/ 1 \/
  34422. // =============
  34423. // /\ 19 /\ 2 /\
  34424. // / \ / \ / \
  34425. // / 14 \/ 9 \/ 3 \
  34426. // ===================
  34427. // uv step is u:1 or 0.5, v:cos(30)=sqrt(3)/2, ratio approx is 84/97
  34428. var ustep = 138 / 1024;
  34429. var vstep = 239 / 1024;
  34430. var uoffset = 60 / 1024;
  34431. var voffset = 26 / 1024;
  34432. // Second island should have margin, not to touch the first island
  34433. // avoid any borderline artefact in pixel rounding
  34434. var island_u_offset = -40 / 1024;
  34435. var island_v_offset = +20 / 1024;
  34436. // face is either island 0 or 1 :
  34437. // second island is for faces : [4, 7, 8, 12, 13, 16, 17, 18]
  34438. var island = [
  34439. 0, 0, 0, 0, 1,
  34440. 0, 0, 1, 1, 0,
  34441. 0, 0, 1, 1, 0,
  34442. 0, 1, 1, 1, 0 // 15 - 19
  34443. ];
  34444. var indices = new Array();
  34445. var positions = new Array();
  34446. var normals = new Array();
  34447. var uvs = new Array();
  34448. var current_indice = 0;
  34449. // prepare array of 3 vector (empty) (to be worked in place, shared for each face)
  34450. var face_vertex_pos = new Array(3);
  34451. var face_vertex_uv = new Array(3);
  34452. var v012;
  34453. for (v012 = 0; v012 < 3; v012++) {
  34454. face_vertex_pos[v012] = BABYLON.Vector3.Zero();
  34455. face_vertex_uv[v012] = BABYLON.Vector2.Zero();
  34456. }
  34457. // create all with normals
  34458. for (var face = 0; face < 20; face++) {
  34459. // 3 vertex per face
  34460. for (v012 = 0; v012 < 3; v012++) {
  34461. // look up vertex 0,1,2 to its index in 0 to 11 (or 23 including alias)
  34462. var v_id = ico_indices[3 * face + v012];
  34463. // vertex have 3D position (x,y,z)
  34464. 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]);
  34465. // Normalize to get normal, then scale to radius
  34466. face_vertex_pos[v012].normalize().scaleInPlace(radius);
  34467. // uv Coordinates from vertex ID
  34468. 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);
  34469. }
  34470. // Subdivide the face (interpolate pos, norm, uv)
  34471. // - pos is linear interpolation, then projected to sphere (converge polyhedron to sphere)
  34472. // - norm is linear interpolation of vertex corner normal
  34473. // (to be checked if better to re-calc from face vertex, or if approximation is OK ??? )
  34474. // - uv is linear interpolation
  34475. //
  34476. // Topology is as below for sub-divide by 2
  34477. // vertex shown as v0,v1,v2
  34478. // interp index is i1 to progress in range [v0,v1[
  34479. // interp index is i2 to progress in range [v0,v2[
  34480. // face index as (i1,i2) for /\ : (i1,i2),(i1+1,i2),(i1,i2+1)
  34481. // and (i1,i2)' for \/ : (i1+1,i2),(i1+1,i2+1),(i1,i2+1)
  34482. //
  34483. //
  34484. // i2 v2
  34485. // ^ ^
  34486. // / / \
  34487. // / / \
  34488. // / / \
  34489. // / / (0,1) \
  34490. // / #---------\
  34491. // / / \ (0,0)'/ \
  34492. // / / \ / \
  34493. // / / \ / \
  34494. // / / (0,0) \ / (1,0) \
  34495. // / #---------#---------\
  34496. // v0 v1
  34497. //
  34498. // --------------------> i1
  34499. //
  34500. // interp of (i1,i2):
  34501. // along i2 : x0=lerp(v0,v2, i2/S) <---> x1=lerp(v1,v2, i2/S)
  34502. // along i1 : lerp(x0,x1, i1/(S-i2))
  34503. //
  34504. // centroid of triangle is needed to get help normal computation
  34505. // (c1,c2) are used for centroid location
  34506. var interp_vertex = function (i1, i2, c1, c2) {
  34507. // vertex is interpolated from
  34508. // - face_vertex_pos[0..2]
  34509. // - face_vertex_uv[0..2]
  34510. var pos_x0 = BABYLON.Vector3.Lerp(face_vertex_pos[0], face_vertex_pos[2], i2 / subdivisions);
  34511. var pos_x1 = BABYLON.Vector3.Lerp(face_vertex_pos[1], face_vertex_pos[2], i2 / subdivisions);
  34512. var pos_interp = (subdivisions === i2) ? face_vertex_pos[2] : BABYLON.Vector3.Lerp(pos_x0, pos_x1, i1 / (subdivisions - i2));
  34513. pos_interp.normalize();
  34514. var vertex_normal;
  34515. if (flat) {
  34516. // in flat mode, recalculate normal as face centroid normal
  34517. var centroid_x0 = BABYLON.Vector3.Lerp(face_vertex_pos[0], face_vertex_pos[2], c2 / subdivisions);
  34518. var centroid_x1 = BABYLON.Vector3.Lerp(face_vertex_pos[1], face_vertex_pos[2], c2 / subdivisions);
  34519. vertex_normal = BABYLON.Vector3.Lerp(centroid_x0, centroid_x1, c1 / (subdivisions - c2));
  34520. }
  34521. else {
  34522. // in smooth mode, recalculate normal from each single vertex position
  34523. vertex_normal = new BABYLON.Vector3(pos_interp.x, pos_interp.y, pos_interp.z);
  34524. }
  34525. // Vertex normal need correction due to X,Y,Z radius scaling
  34526. vertex_normal.x /= radiusX;
  34527. vertex_normal.y /= radiusY;
  34528. vertex_normal.z /= radiusZ;
  34529. vertex_normal.normalize();
  34530. var uv_x0 = BABYLON.Vector2.Lerp(face_vertex_uv[0], face_vertex_uv[2], i2 / subdivisions);
  34531. var uv_x1 = BABYLON.Vector2.Lerp(face_vertex_uv[1], face_vertex_uv[2], i2 / subdivisions);
  34532. var uv_interp = (subdivisions === i2) ? face_vertex_uv[2] : BABYLON.Vector2.Lerp(uv_x0, uv_x1, i1 / (subdivisions - i2));
  34533. positions.push(pos_interp.x * radiusX, pos_interp.y * radiusY, pos_interp.z * radiusZ);
  34534. normals.push(vertex_normal.x, vertex_normal.y, vertex_normal.z);
  34535. uvs.push(uv_interp.x, uv_interp.y);
  34536. // push each vertex has member of a face
  34537. // Same vertex can bleong to multiple face, it is pushed multiple time (duplicate vertex are present)
  34538. indices.push(current_indice);
  34539. current_indice++;
  34540. };
  34541. for (var i2 = 0; i2 < subdivisions; i2++) {
  34542. for (var i1 = 0; i1 + i2 < subdivisions; i1++) {
  34543. // face : (i1,i2) for /\ :
  34544. // interp for : (i1,i2),(i1+1,i2),(i1,i2+1)
  34545. interp_vertex(i1, i2, i1 + 1.0 / 3, i2 + 1.0 / 3);
  34546. interp_vertex(i1 + 1, i2, i1 + 1.0 / 3, i2 + 1.0 / 3);
  34547. interp_vertex(i1, i2 + 1, i1 + 1.0 / 3, i2 + 1.0 / 3);
  34548. if (i1 + i2 + 1 < subdivisions) {
  34549. // face : (i1,i2)' for \/ :
  34550. // interp for (i1+1,i2),(i1+1,i2+1),(i1,i2+1)
  34551. interp_vertex(i1 + 1, i2, i1 + 2.0 / 3, i2 + 2.0 / 3);
  34552. interp_vertex(i1 + 1, i2 + 1, i1 + 2.0 / 3, i2 + 2.0 / 3);
  34553. interp_vertex(i1, i2 + 1, i1 + 2.0 / 3, i2 + 2.0 / 3);
  34554. }
  34555. }
  34556. }
  34557. }
  34558. // Sides
  34559. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  34560. // Result
  34561. var vertexData = new VertexData();
  34562. vertexData.indices = indices;
  34563. vertexData.positions = positions;
  34564. vertexData.normals = normals;
  34565. vertexData.uvs = uvs;
  34566. return vertexData;
  34567. };
  34568. // inspired from // http://stemkoski.github.io/Three.js/Polyhedra.html
  34569. /**
  34570. * Creates the VertexData of the Polyhedron.
  34571. */
  34572. VertexData.CreatePolyhedron = function (options) {
  34573. // provided polyhedron types :
  34574. // 0 : Tetrahedron, 1 : Octahedron, 2 : Dodecahedron, 3 : Icosahedron, 4 : Rhombicuboctahedron, 5 : Triangular Prism, 6 : Pentagonal Prism, 7 : Hexagonal Prism, 8 : Square Pyramid (J1)
  34575. // 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)
  34576. var polyhedra = [];
  34577. 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]] };
  34578. 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]] };
  34579. polyhedra[2] = {
  34580. 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]],
  34581. 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]]
  34582. };
  34583. polyhedra[3] = {
  34584. 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]],
  34585. 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]]
  34586. };
  34587. polyhedra[4] = {
  34588. 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]],
  34589. 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]]
  34590. };
  34591. 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]] };
  34592. 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]] };
  34593. 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]] };
  34594. 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]] };
  34595. 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]] };
  34596. 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]] };
  34597. 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]] };
  34598. 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]] };
  34599. 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]] };
  34600. polyhedra[14] = {
  34601. 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]],
  34602. 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]]
  34603. };
  34604. var type = options.type && (options.type < 0 || options.type >= polyhedra.length) ? 0 : options.type || 0;
  34605. var size = options.size;
  34606. var sizeX = options.sizeX || size || 1;
  34607. var sizeY = options.sizeY || size || 1;
  34608. var sizeZ = options.sizeZ || size || 1;
  34609. var data = options.custom || polyhedra[type];
  34610. var nbfaces = data.face.length;
  34611. var faceUV = options.faceUV || new Array(nbfaces);
  34612. var faceColors = options.faceColors;
  34613. var flat = (options.flat === undefined) ? true : options.flat;
  34614. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  34615. var positions = new Array();
  34616. var indices = new Array();
  34617. var normals = new Array();
  34618. var uvs = new Array();
  34619. var colors = new Array();
  34620. var index = 0;
  34621. var faceIdx = 0; // face cursor in the array "indexes"
  34622. var indexes = new Array();
  34623. var i = 0;
  34624. var f = 0;
  34625. var u, v, ang, x, y, tmp;
  34626. // default face colors and UV if undefined
  34627. if (flat) {
  34628. for (f = 0; f < nbfaces; f++) {
  34629. if (faceColors && faceColors[f] === undefined) {
  34630. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  34631. }
  34632. if (faceUV && faceUV[f] === undefined) {
  34633. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  34634. }
  34635. }
  34636. }
  34637. if (!flat) {
  34638. for (i = 0; i < data.vertex.length; i++) {
  34639. positions.push(data.vertex[i][0] * sizeX, data.vertex[i][1] * sizeY, data.vertex[i][2] * sizeZ);
  34640. uvs.push(0, 0);
  34641. }
  34642. for (f = 0; f < nbfaces; f++) {
  34643. for (i = 0; i < data.face[f].length - 2; i++) {
  34644. indices.push(data.face[f][0], data.face[f][i + 2], data.face[f][i + 1]);
  34645. }
  34646. }
  34647. }
  34648. else {
  34649. for (f = 0; f < nbfaces; f++) {
  34650. var fl = data.face[f].length; // number of vertices of the current face
  34651. ang = 2 * Math.PI / fl;
  34652. x = 0.5 * Math.tan(ang / 2);
  34653. y = 0.5;
  34654. // positions, uvs, colors
  34655. for (i = 0; i < fl; i++) {
  34656. // positions
  34657. 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);
  34658. indexes.push(index);
  34659. index++;
  34660. // uvs
  34661. u = faceUV[f].x + (faceUV[f].z - faceUV[f].x) * (0.5 + x);
  34662. v = faceUV[f].y + (faceUV[f].w - faceUV[f].y) * (y - 0.5);
  34663. uvs.push(u, v);
  34664. tmp = x * Math.cos(ang) - y * Math.sin(ang);
  34665. y = x * Math.sin(ang) + y * Math.cos(ang);
  34666. x = tmp;
  34667. // colors
  34668. if (faceColors) {
  34669. colors.push(faceColors[f].r, faceColors[f].g, faceColors[f].b, faceColors[f].a);
  34670. }
  34671. }
  34672. // indices from indexes
  34673. for (i = 0; i < fl - 2; i++) {
  34674. indices.push(indexes[0 + faceIdx], indexes[i + 2 + faceIdx], indexes[i + 1 + faceIdx]);
  34675. }
  34676. faceIdx += fl;
  34677. }
  34678. }
  34679. VertexData.ComputeNormals(positions, indices, normals);
  34680. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  34681. var vertexData = new VertexData();
  34682. vertexData.positions = positions;
  34683. vertexData.indices = indices;
  34684. vertexData.normals = normals;
  34685. vertexData.uvs = uvs;
  34686. if (faceColors && flat) {
  34687. vertexData.colors = colors;
  34688. }
  34689. return vertexData;
  34690. };
  34691. // based on http://code.google.com/p/away3d/source/browse/trunk/fp10/Away3D/src/away3d/primitives/TorusKnot.as?spec=svn2473&r=2473
  34692. /**
  34693. * Creates the VertexData of the Torus Knot.
  34694. */
  34695. VertexData.CreateTorusKnot = function (options) {
  34696. var indices = new Array();
  34697. var positions = new Array();
  34698. var normals = new Array();
  34699. var uvs = new Array();
  34700. var radius = options.radius || 2;
  34701. var tube = options.tube || 0.5;
  34702. var radialSegments = options.radialSegments || 32;
  34703. var tubularSegments = options.tubularSegments || 32;
  34704. var p = options.p || 2;
  34705. var q = options.q || 3;
  34706. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  34707. // Helper
  34708. var getPos = function (angle) {
  34709. var cu = Math.cos(angle);
  34710. var su = Math.sin(angle);
  34711. var quOverP = q / p * angle;
  34712. var cs = Math.cos(quOverP);
  34713. var tx = radius * (2 + cs) * 0.5 * cu;
  34714. var ty = radius * (2 + cs) * su * 0.5;
  34715. var tz = radius * Math.sin(quOverP) * 0.5;
  34716. return new BABYLON.Vector3(tx, ty, tz);
  34717. };
  34718. // Vertices
  34719. var i;
  34720. var j;
  34721. for (i = 0; i <= radialSegments; i++) {
  34722. var modI = i % radialSegments;
  34723. var u = modI / radialSegments * 2 * p * Math.PI;
  34724. var p1 = getPos(u);
  34725. var p2 = getPos(u + 0.01);
  34726. var tang = p2.subtract(p1);
  34727. var n = p2.add(p1);
  34728. var bitan = BABYLON.Vector3.Cross(tang, n);
  34729. n = BABYLON.Vector3.Cross(bitan, tang);
  34730. bitan.normalize();
  34731. n.normalize();
  34732. for (j = 0; j < tubularSegments; j++) {
  34733. var modJ = j % tubularSegments;
  34734. var v = modJ / tubularSegments * 2 * Math.PI;
  34735. var cx = -tube * Math.cos(v);
  34736. var cy = tube * Math.sin(v);
  34737. positions.push(p1.x + cx * n.x + cy * bitan.x);
  34738. positions.push(p1.y + cx * n.y + cy * bitan.y);
  34739. positions.push(p1.z + cx * n.z + cy * bitan.z);
  34740. uvs.push(i / radialSegments);
  34741. uvs.push(j / tubularSegments);
  34742. }
  34743. }
  34744. for (i = 0; i < radialSegments; i++) {
  34745. for (j = 0; j < tubularSegments; j++) {
  34746. var jNext = (j + 1) % tubularSegments;
  34747. var a = i * tubularSegments + j;
  34748. var b = (i + 1) * tubularSegments + j;
  34749. var c = (i + 1) * tubularSegments + jNext;
  34750. var d = i * tubularSegments + jNext;
  34751. indices.push(d);
  34752. indices.push(b);
  34753. indices.push(a);
  34754. indices.push(d);
  34755. indices.push(c);
  34756. indices.push(b);
  34757. }
  34758. }
  34759. // Normals
  34760. VertexData.ComputeNormals(positions, indices, normals);
  34761. // Sides
  34762. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  34763. // Result
  34764. var vertexData = new VertexData();
  34765. vertexData.indices = indices;
  34766. vertexData.positions = positions;
  34767. vertexData.normals = normals;
  34768. vertexData.uvs = uvs;
  34769. return vertexData;
  34770. };
  34771. // Tools
  34772. /**
  34773. * @param {any} - positions (number[] or Float32Array)
  34774. * @param {any} - indices (number[] or Uint16Array)
  34775. * @param {any} - normals (number[] or Float32Array)
  34776. * options (optional) :
  34777. * facetPositions : optional array of facet positions (vector3)
  34778. * facetNormals : optional array of facet normals (vector3)
  34779. * facetPartitioning : optional partitioning array. facetPositions is required for facetPartitioning computation
  34780. * subDiv : optional partitioning data about subdivsions on each axis (int), required for facetPartitioning computation
  34781. * ratio : optional partitioning ratio / bounding box, required for facetPartitioning computation
  34782. * bbSize : optional bounding box size data, required for facetPartitioning computation
  34783. * bInfo : optional bounding info, required for facetPartitioning computation
  34784. * useRightHandedSystem: optional boolean to for right handed system computation
  34785. * depthSort : optional boolean to enable the facet depth sort computation
  34786. * distanceTo : optional Vector3 to compute the facet depth from this location
  34787. * depthSortedFacets : optional array of depthSortedFacets to store the facet distances from the reference location
  34788. */
  34789. VertexData.ComputeNormals = function (positions, indices, normals, options) {
  34790. // temporary scalar variables
  34791. var index = 0; // facet index
  34792. var p1p2x = 0.0; // p1p2 vector x coordinate
  34793. var p1p2y = 0.0; // p1p2 vector y coordinate
  34794. var p1p2z = 0.0; // p1p2 vector z coordinate
  34795. var p3p2x = 0.0; // p3p2 vector x coordinate
  34796. var p3p2y = 0.0; // p3p2 vector y coordinate
  34797. var p3p2z = 0.0; // p3p2 vector z coordinate
  34798. var faceNormalx = 0.0; // facet normal x coordinate
  34799. var faceNormaly = 0.0; // facet normal y coordinate
  34800. var faceNormalz = 0.0; // facet normal z coordinate
  34801. var length = 0.0; // facet normal length before normalization
  34802. var v1x = 0; // vector1 x index in the positions array
  34803. var v1y = 0; // vector1 y index in the positions array
  34804. var v1z = 0; // vector1 z index in the positions array
  34805. var v2x = 0; // vector2 x index in the positions array
  34806. var v2y = 0; // vector2 y index in the positions array
  34807. var v2z = 0; // vector2 z index in the positions array
  34808. var v3x = 0; // vector3 x index in the positions array
  34809. var v3y = 0; // vector3 y index in the positions array
  34810. var v3z = 0; // vector3 z index in the positions array
  34811. var computeFacetNormals = false;
  34812. var computeFacetPositions = false;
  34813. var computeFacetPartitioning = false;
  34814. var computeDepthSort = false;
  34815. var faceNormalSign = 1;
  34816. var ratio = 0;
  34817. var distanceTo = null;
  34818. if (options) {
  34819. computeFacetNormals = (options.facetNormals) ? true : false;
  34820. computeFacetPositions = (options.facetPositions) ? true : false;
  34821. computeFacetPartitioning = (options.facetPartitioning) ? true : false;
  34822. faceNormalSign = (options.useRightHandedSystem === true) ? -1 : 1;
  34823. ratio = options.ratio || 0;
  34824. computeDepthSort = (options.depthSort) ? true : false;
  34825. distanceTo = (options.distanceTo);
  34826. if (computeDepthSort) {
  34827. if (distanceTo === undefined) {
  34828. distanceTo = BABYLON.Vector3.Zero();
  34829. }
  34830. var depthSortedFacets = options.depthSortedFacets;
  34831. }
  34832. }
  34833. // facetPartitioning reinit if needed
  34834. var xSubRatio = 0;
  34835. var ySubRatio = 0;
  34836. var zSubRatio = 0;
  34837. var subSq = 0;
  34838. if (computeFacetPartitioning && options && options.bbSize) {
  34839. var ox = 0; // X partitioning index for facet position
  34840. var oy = 0; // Y partinioning index for facet position
  34841. var oz = 0; // Z partinioning index for facet position
  34842. var b1x = 0; // X partitioning index for facet v1 vertex
  34843. var b1y = 0; // Y partitioning index for facet v1 vertex
  34844. var b1z = 0; // z partitioning index for facet v1 vertex
  34845. var b2x = 0; // X partitioning index for facet v2 vertex
  34846. var b2y = 0; // Y partitioning index for facet v2 vertex
  34847. var b2z = 0; // Z partitioning index for facet v2 vertex
  34848. var b3x = 0; // X partitioning index for facet v3 vertex
  34849. var b3y = 0; // Y partitioning index for facet v3 vertex
  34850. var b3z = 0; // Z partitioning index for facet v3 vertex
  34851. var block_idx_o = 0; // facet barycenter block index
  34852. var block_idx_v1 = 0; // v1 vertex block index
  34853. var block_idx_v2 = 0; // v2 vertex block index
  34854. var block_idx_v3 = 0; // v3 vertex block index
  34855. var bbSizeMax = (options.bbSize.x > options.bbSize.y) ? options.bbSize.x : options.bbSize.y;
  34856. bbSizeMax = (bbSizeMax > options.bbSize.z) ? bbSizeMax : options.bbSize.z;
  34857. xSubRatio = options.subDiv.X * ratio / options.bbSize.x;
  34858. ySubRatio = options.subDiv.Y * ratio / options.bbSize.y;
  34859. zSubRatio = options.subDiv.Z * ratio / options.bbSize.z;
  34860. subSq = options.subDiv.max * options.subDiv.max;
  34861. options.facetPartitioning.length = 0;
  34862. }
  34863. // reset the normals
  34864. for (index = 0; index < positions.length; index++) {
  34865. normals[index] = 0.0;
  34866. }
  34867. // Loop : 1 indice triplet = 1 facet
  34868. var nbFaces = (indices.length / 3) | 0;
  34869. for (index = 0; index < nbFaces; index++) {
  34870. // get the indexes of the coordinates of each vertex of the facet
  34871. v1x = indices[index * 3] * 3;
  34872. v1y = v1x + 1;
  34873. v1z = v1x + 2;
  34874. v2x = indices[index * 3 + 1] * 3;
  34875. v2y = v2x + 1;
  34876. v2z = v2x + 2;
  34877. v3x = indices[index * 3 + 2] * 3;
  34878. v3y = v3x + 1;
  34879. v3z = v3x + 2;
  34880. p1p2x = positions[v1x] - positions[v2x]; // compute two vectors per facet : p1p2 and p3p2
  34881. p1p2y = positions[v1y] - positions[v2y];
  34882. p1p2z = positions[v1z] - positions[v2z];
  34883. p3p2x = positions[v3x] - positions[v2x];
  34884. p3p2y = positions[v3y] - positions[v2y];
  34885. p3p2z = positions[v3z] - positions[v2z];
  34886. // compute the face normal with the cross product
  34887. faceNormalx = faceNormalSign * (p1p2y * p3p2z - p1p2z * p3p2y);
  34888. faceNormaly = faceNormalSign * (p1p2z * p3p2x - p1p2x * p3p2z);
  34889. faceNormalz = faceNormalSign * (p1p2x * p3p2y - p1p2y * p3p2x);
  34890. // normalize this normal and store it in the array facetData
  34891. length = Math.sqrt(faceNormalx * faceNormalx + faceNormaly * faceNormaly + faceNormalz * faceNormalz);
  34892. length = (length === 0) ? 1.0 : length;
  34893. faceNormalx /= length;
  34894. faceNormaly /= length;
  34895. faceNormalz /= length;
  34896. if (computeFacetNormals && options) {
  34897. options.facetNormals[index].x = faceNormalx;
  34898. options.facetNormals[index].y = faceNormaly;
  34899. options.facetNormals[index].z = faceNormalz;
  34900. }
  34901. if (computeFacetPositions && options) {
  34902. // compute and the facet barycenter coordinates in the array facetPositions
  34903. options.facetPositions[index].x = (positions[v1x] + positions[v2x] + positions[v3x]) / 3.0;
  34904. options.facetPositions[index].y = (positions[v1y] + positions[v2y] + positions[v3y]) / 3.0;
  34905. options.facetPositions[index].z = (positions[v1z] + positions[v2z] + positions[v3z]) / 3.0;
  34906. }
  34907. if (computeFacetPartitioning && options) {
  34908. // store the facet indexes in arrays in the main facetPartitioning array :
  34909. // compute each facet vertex (+ facet barycenter) index in the partiniong array
  34910. ox = Math.floor((options.facetPositions[index].x - options.bInfo.minimum.x * ratio) * xSubRatio);
  34911. oy = Math.floor((options.facetPositions[index].y - options.bInfo.minimum.y * ratio) * ySubRatio);
  34912. oz = Math.floor((options.facetPositions[index].z - options.bInfo.minimum.z * ratio) * zSubRatio);
  34913. b1x = Math.floor((positions[v1x] - options.bInfo.minimum.x * ratio) * xSubRatio);
  34914. b1y = Math.floor((positions[v1y] - options.bInfo.minimum.y * ratio) * ySubRatio);
  34915. b1z = Math.floor((positions[v1z] - options.bInfo.minimum.z * ratio) * zSubRatio);
  34916. b2x = Math.floor((positions[v2x] - options.bInfo.minimum.x * ratio) * xSubRatio);
  34917. b2y = Math.floor((positions[v2y] - options.bInfo.minimum.y * ratio) * ySubRatio);
  34918. b2z = Math.floor((positions[v2z] - options.bInfo.minimum.z * ratio) * zSubRatio);
  34919. b3x = Math.floor((positions[v3x] - options.bInfo.minimum.x * ratio) * xSubRatio);
  34920. b3y = Math.floor((positions[v3y] - options.bInfo.minimum.y * ratio) * ySubRatio);
  34921. b3z = Math.floor((positions[v3z] - options.bInfo.minimum.z * ratio) * zSubRatio);
  34922. block_idx_v1 = b1x + options.subDiv.max * b1y + subSq * b1z;
  34923. block_idx_v2 = b2x + options.subDiv.max * b2y + subSq * b2z;
  34924. block_idx_v3 = b3x + options.subDiv.max * b3y + subSq * b3z;
  34925. block_idx_o = ox + options.subDiv.max * oy + subSq * oz;
  34926. options.facetPartitioning[block_idx_o] = options.facetPartitioning[block_idx_o] ? options.facetPartitioning[block_idx_o] : new Array();
  34927. options.facetPartitioning[block_idx_v1] = options.facetPartitioning[block_idx_v1] ? options.facetPartitioning[block_idx_v1] : new Array();
  34928. options.facetPartitioning[block_idx_v2] = options.facetPartitioning[block_idx_v2] ? options.facetPartitioning[block_idx_v2] : new Array();
  34929. options.facetPartitioning[block_idx_v3] = options.facetPartitioning[block_idx_v3] ? options.facetPartitioning[block_idx_v3] : new Array();
  34930. // push each facet index in each block containing the vertex
  34931. options.facetPartitioning[block_idx_v1].push(index);
  34932. if (block_idx_v2 != block_idx_v1) {
  34933. options.facetPartitioning[block_idx_v2].push(index);
  34934. }
  34935. if (!(block_idx_v3 == block_idx_v2 || block_idx_v3 == block_idx_v1)) {
  34936. options.facetPartitioning[block_idx_v3].push(index);
  34937. }
  34938. if (!(block_idx_o == block_idx_v1 || block_idx_o == block_idx_v2 || block_idx_o == block_idx_v3)) {
  34939. options.facetPartitioning[block_idx_o].push(index);
  34940. }
  34941. }
  34942. if (computeDepthSort && options && options.facetPositions) {
  34943. var dsf = depthSortedFacets[index];
  34944. dsf.ind = index * 3;
  34945. dsf.sqDistance = BABYLON.Vector3.DistanceSquared(options.facetPositions[index], distanceTo);
  34946. }
  34947. // compute the normals anyway
  34948. normals[v1x] += faceNormalx; // accumulate all the normals per face
  34949. normals[v1y] += faceNormaly;
  34950. normals[v1z] += faceNormalz;
  34951. normals[v2x] += faceNormalx;
  34952. normals[v2y] += faceNormaly;
  34953. normals[v2z] += faceNormalz;
  34954. normals[v3x] += faceNormalx;
  34955. normals[v3y] += faceNormaly;
  34956. normals[v3z] += faceNormalz;
  34957. }
  34958. // last normalization of each normal
  34959. for (index = 0; index < normals.length / 3; index++) {
  34960. faceNormalx = normals[index * 3];
  34961. faceNormaly = normals[index * 3 + 1];
  34962. faceNormalz = normals[index * 3 + 2];
  34963. length = Math.sqrt(faceNormalx * faceNormalx + faceNormaly * faceNormaly + faceNormalz * faceNormalz);
  34964. length = (length === 0) ? 1.0 : length;
  34965. faceNormalx /= length;
  34966. faceNormaly /= length;
  34967. faceNormalz /= length;
  34968. normals[index * 3] = faceNormalx;
  34969. normals[index * 3 + 1] = faceNormaly;
  34970. normals[index * 3 + 2] = faceNormalz;
  34971. }
  34972. };
  34973. VertexData._ComputeSides = function (sideOrientation, positions, indices, normals, uvs, frontUVs, backUVs) {
  34974. var li = indices.length;
  34975. var ln = normals.length;
  34976. var i;
  34977. var n;
  34978. sideOrientation = sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  34979. switch (sideOrientation) {
  34980. case BABYLON.Mesh.FRONTSIDE:
  34981. // nothing changed
  34982. break;
  34983. case BABYLON.Mesh.BACKSIDE:
  34984. var tmp;
  34985. // indices
  34986. for (i = 0; i < li; i += 3) {
  34987. tmp = indices[i];
  34988. indices[i] = indices[i + 2];
  34989. indices[i + 2] = tmp;
  34990. }
  34991. // normals
  34992. for (n = 0; n < ln; n++) {
  34993. normals[n] = -normals[n];
  34994. }
  34995. break;
  34996. case BABYLON.Mesh.DOUBLESIDE:
  34997. // positions
  34998. var lp = positions.length;
  34999. var l = lp / 3;
  35000. for (var p = 0; p < lp; p++) {
  35001. positions[lp + p] = positions[p];
  35002. }
  35003. // indices
  35004. for (i = 0; i < li; i += 3) {
  35005. indices[i + li] = indices[i + 2] + l;
  35006. indices[i + 1 + li] = indices[i + 1] + l;
  35007. indices[i + 2 + li] = indices[i] + l;
  35008. }
  35009. // normals
  35010. for (n = 0; n < ln; n++) {
  35011. normals[ln + n] = -normals[n];
  35012. }
  35013. // uvs
  35014. var lu = uvs.length;
  35015. var u = 0;
  35016. for (u = 0; u < lu; u++) {
  35017. uvs[u + lu] = uvs[u];
  35018. }
  35019. frontUVs = frontUVs ? frontUVs : new BABYLON.Vector4(0.0, 0.0, 1.0, 1.0);
  35020. backUVs = backUVs ? backUVs : new BABYLON.Vector4(0.0, 0.0, 1.0, 1.0);
  35021. u = 0;
  35022. for (i = 0; i < lu / 2; i++) {
  35023. uvs[u] = frontUVs.x + (frontUVs.z - frontUVs.x) * uvs[u];
  35024. uvs[u + 1] = frontUVs.y + (frontUVs.w - frontUVs.y) * uvs[u + 1];
  35025. uvs[u + lu] = backUVs.x + (backUVs.z - backUVs.x) * uvs[u + lu];
  35026. uvs[u + lu + 1] = backUVs.y + (backUVs.w - backUVs.y) * uvs[u + lu + 1];
  35027. u += 2;
  35028. }
  35029. break;
  35030. }
  35031. };
  35032. /**
  35033. * Creates a new VertexData from the imported parameters.
  35034. */
  35035. VertexData.ImportVertexData = function (parsedVertexData, geometry) {
  35036. var vertexData = new VertexData();
  35037. // positions
  35038. var positions = parsedVertexData.positions;
  35039. if (positions) {
  35040. vertexData.set(positions, BABYLON.VertexBuffer.PositionKind);
  35041. }
  35042. // normals
  35043. var normals = parsedVertexData.normals;
  35044. if (normals) {
  35045. vertexData.set(normals, BABYLON.VertexBuffer.NormalKind);
  35046. }
  35047. // tangents
  35048. var tangents = parsedVertexData.tangents;
  35049. if (tangents) {
  35050. vertexData.set(tangents, BABYLON.VertexBuffer.TangentKind);
  35051. }
  35052. // uvs
  35053. var uvs = parsedVertexData.uvs;
  35054. if (uvs) {
  35055. vertexData.set(uvs, BABYLON.VertexBuffer.UVKind);
  35056. }
  35057. // uv2s
  35058. var uv2s = parsedVertexData.uv2s;
  35059. if (uv2s) {
  35060. vertexData.set(uv2s, BABYLON.VertexBuffer.UV2Kind);
  35061. }
  35062. // uv3s
  35063. var uv3s = parsedVertexData.uv3s;
  35064. if (uv3s) {
  35065. vertexData.set(uv3s, BABYLON.VertexBuffer.UV3Kind);
  35066. }
  35067. // uv4s
  35068. var uv4s = parsedVertexData.uv4s;
  35069. if (uv4s) {
  35070. vertexData.set(uv4s, BABYLON.VertexBuffer.UV4Kind);
  35071. }
  35072. // uv5s
  35073. var uv5s = parsedVertexData.uv5s;
  35074. if (uv5s) {
  35075. vertexData.set(uv5s, BABYLON.VertexBuffer.UV5Kind);
  35076. }
  35077. // uv6s
  35078. var uv6s = parsedVertexData.uv6s;
  35079. if (uv6s) {
  35080. vertexData.set(uv6s, BABYLON.VertexBuffer.UV6Kind);
  35081. }
  35082. // colors
  35083. var colors = parsedVertexData.colors;
  35084. if (colors) {
  35085. vertexData.set(BABYLON.Color4.CheckColors4(colors, positions.length / 3), BABYLON.VertexBuffer.ColorKind);
  35086. }
  35087. // matricesIndices
  35088. var matricesIndices = parsedVertexData.matricesIndices;
  35089. if (matricesIndices) {
  35090. vertexData.set(matricesIndices, BABYLON.VertexBuffer.MatricesIndicesKind);
  35091. }
  35092. // matricesWeights
  35093. var matricesWeights = parsedVertexData.matricesWeights;
  35094. if (matricesWeights) {
  35095. vertexData.set(matricesWeights, BABYLON.VertexBuffer.MatricesWeightsKind);
  35096. }
  35097. // indices
  35098. var indices = parsedVertexData.indices;
  35099. if (indices) {
  35100. vertexData.indices = indices;
  35101. }
  35102. geometry.setAllVerticesData(vertexData, parsedVertexData.updatable);
  35103. };
  35104. return VertexData;
  35105. }());
  35106. BABYLON.VertexData = VertexData;
  35107. })(BABYLON || (BABYLON = {}));
  35108. //# sourceMappingURL=babylon.mesh.vertexData.js.map
  35109. "use strict";
  35110. var BABYLON;
  35111. (function (BABYLON) {
  35112. /**
  35113. * Class used to store geometry data (vertex buffers + index buffer)
  35114. */
  35115. var Geometry = /** @class */ (function () {
  35116. /**
  35117. * Creates a new geometry
  35118. * @param id defines the unique ID
  35119. * @param scene defines the hosting scene
  35120. * @param vertexData defines the {BABYLON.VertexData} used to get geometry data
  35121. * @param updatable defines if geometry must be updatable (false by default)
  35122. * @param mesh defines the mesh that will be associated with the geometry
  35123. */
  35124. function Geometry(id, scene, vertexData, updatable, mesh) {
  35125. if (updatable === void 0) { updatable = false; }
  35126. if (mesh === void 0) { mesh = null; }
  35127. /**
  35128. * Gets the delay loading state of the geometry (none by default which means not delayed)
  35129. */
  35130. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  35131. this._totalVertices = 0;
  35132. this._isDisposed = false;
  35133. this._indexBufferIsUpdatable = false;
  35134. this.id = id;
  35135. this._engine = scene.getEngine();
  35136. this._meshes = [];
  35137. this._scene = scene;
  35138. //Init vertex buffer cache
  35139. this._vertexBuffers = {};
  35140. this._indices = [];
  35141. this._updatable = updatable;
  35142. // vertexData
  35143. if (vertexData) {
  35144. this.setAllVerticesData(vertexData, updatable);
  35145. }
  35146. else {
  35147. this._totalVertices = 0;
  35148. this._indices = [];
  35149. }
  35150. if (this._engine.getCaps().vertexArrayObject) {
  35151. this._vertexArrayObjects = {};
  35152. }
  35153. // applyToMesh
  35154. if (mesh) {
  35155. if (mesh.getClassName() === "LinesMesh") {
  35156. this.boundingBias = new BABYLON.Vector2(0, mesh.intersectionThreshold);
  35157. this.updateExtend();
  35158. }
  35159. this.applyToMesh(mesh);
  35160. mesh.computeWorldMatrix(true);
  35161. }
  35162. }
  35163. Object.defineProperty(Geometry.prototype, "boundingBias", {
  35164. /**
  35165. * 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
  35166. */
  35167. get: function () {
  35168. return this._boundingBias;
  35169. },
  35170. /**
  35171. * 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
  35172. */
  35173. set: function (value) {
  35174. if (this._boundingBias && this._boundingBias.equals(value)) {
  35175. return;
  35176. }
  35177. this._boundingBias = value.clone();
  35178. this.updateBoundingInfo(true, null);
  35179. },
  35180. enumerable: true,
  35181. configurable: true
  35182. });
  35183. /**
  35184. * Static function used to attach a new empty geometry to a mesh
  35185. * @param mesh defines the mesh to attach the geometry to
  35186. * @returns the new {BABYLON.Geometry}
  35187. */
  35188. Geometry.CreateGeometryForMesh = function (mesh) {
  35189. var geometry = new Geometry(Geometry.RandomId(), mesh.getScene());
  35190. geometry.applyToMesh(mesh);
  35191. return geometry;
  35192. };
  35193. Object.defineProperty(Geometry.prototype, "extend", {
  35194. /**
  35195. * Gets the current extend of the geometry
  35196. */
  35197. get: function () {
  35198. return this._extend;
  35199. },
  35200. enumerable: true,
  35201. configurable: true
  35202. });
  35203. /**
  35204. * Gets the hosting scene
  35205. * @returns the hosting {BABYLON.Scene}
  35206. */
  35207. Geometry.prototype.getScene = function () {
  35208. return this._scene;
  35209. };
  35210. /**
  35211. * Gets the hosting engine
  35212. * @returns the hosting {BABYLON.Engine}
  35213. */
  35214. Geometry.prototype.getEngine = function () {
  35215. return this._engine;
  35216. };
  35217. /**
  35218. * Defines if the geometry is ready to use
  35219. * @returns true if the geometry is ready to be used
  35220. */
  35221. Geometry.prototype.isReady = function () {
  35222. return this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE;
  35223. };
  35224. Object.defineProperty(Geometry.prototype, "doNotSerialize", {
  35225. /**
  35226. * Gets a value indicating that the geometry should not be serialized
  35227. */
  35228. get: function () {
  35229. for (var index = 0; index < this._meshes.length; index++) {
  35230. if (!this._meshes[index].doNotSerialize) {
  35231. return false;
  35232. }
  35233. }
  35234. return true;
  35235. },
  35236. enumerable: true,
  35237. configurable: true
  35238. });
  35239. /** @ignore */
  35240. Geometry.prototype._rebuild = function () {
  35241. if (this._vertexArrayObjects) {
  35242. this._vertexArrayObjects = {};
  35243. }
  35244. // Index buffer
  35245. if (this._meshes.length !== 0 && this._indices) {
  35246. this._indexBuffer = this._engine.createIndexBuffer(this._indices);
  35247. }
  35248. // Vertex buffers
  35249. for (var key in this._vertexBuffers) {
  35250. var vertexBuffer = this._vertexBuffers[key];
  35251. vertexBuffer._rebuild();
  35252. }
  35253. };
  35254. /**
  35255. * Affects all gemetry data in one call
  35256. * @param vertexData defines the geometry data
  35257. * @param updatable defines if the geometry must be flagged as updatable (false as default)
  35258. */
  35259. Geometry.prototype.setAllVerticesData = function (vertexData, updatable) {
  35260. vertexData.applyToGeometry(this, updatable);
  35261. this.notifyUpdate();
  35262. };
  35263. /**
  35264. * Set specific vertex data
  35265. * @param kind defines the data kind (Position, normal, etc...)
  35266. * @param data defines the vertex data to use
  35267. * @param updatable defines if the vertex must be flagged as updatable (false as default)
  35268. * @param stride defines the stride to use (0 by default). This value is deduced from the kind value if not specified
  35269. */
  35270. Geometry.prototype.setVerticesData = function (kind, data, updatable, stride) {
  35271. if (updatable === void 0) { updatable = false; }
  35272. var buffer = new BABYLON.VertexBuffer(this._engine, data, kind, updatable, this._meshes.length === 0, stride);
  35273. this.setVerticesBuffer(buffer);
  35274. };
  35275. /**
  35276. * Removes a specific vertex data
  35277. * @param kind defines the data kind (Position, normal, etc...)
  35278. */
  35279. Geometry.prototype.removeVerticesData = function (kind) {
  35280. if (this._vertexBuffers[kind]) {
  35281. this._vertexBuffers[kind].dispose();
  35282. delete this._vertexBuffers[kind];
  35283. }
  35284. };
  35285. /**
  35286. * Affect a vertex buffer to the geometry. the vertexBuffer.getKind() function is used to determine where to store the data
  35287. * @param buffer defines the vertex buffer to use
  35288. */
  35289. Geometry.prototype.setVerticesBuffer = function (buffer) {
  35290. var kind = buffer.getKind();
  35291. if (this._vertexBuffers[kind]) {
  35292. this._vertexBuffers[kind].dispose();
  35293. }
  35294. this._vertexBuffers[kind] = buffer;
  35295. if (kind === BABYLON.VertexBuffer.PositionKind) {
  35296. var data = buffer.getData();
  35297. var stride = buffer.getStrideSize();
  35298. this._totalVertices = data.length / stride;
  35299. this.updateExtend(data, stride);
  35300. this._resetPointsArrayCache();
  35301. var meshes = this._meshes;
  35302. var numOfMeshes = meshes.length;
  35303. for (var index = 0; index < numOfMeshes; index++) {
  35304. var mesh = meshes[index];
  35305. mesh._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  35306. mesh._createGlobalSubMesh(false);
  35307. mesh.computeWorldMatrix(true);
  35308. }
  35309. }
  35310. this.notifyUpdate(kind);
  35311. if (this._vertexArrayObjects) {
  35312. this._disposeVertexArrayObjects();
  35313. this._vertexArrayObjects = {}; // Will trigger a rebuild of the VAO if supported
  35314. }
  35315. };
  35316. /**
  35317. * Update a specific vertex buffer
  35318. * This function will directly update the underlying WebGLBuffer according to the passed numeric array or Float32Array
  35319. * It will do nothing if the buffer is not updatable
  35320. * @param kind defines the data kind (Position, normal, etc...)
  35321. * @param data defines the data to use
  35322. * @param offset defines the offset in the target buffer where to store the data
  35323. */
  35324. Geometry.prototype.updateVerticesDataDirectly = function (kind, data, offset) {
  35325. var vertexBuffer = this.getVertexBuffer(kind);
  35326. if (!vertexBuffer) {
  35327. return;
  35328. }
  35329. vertexBuffer.updateDirectly(data, offset);
  35330. this.notifyUpdate(kind);
  35331. };
  35332. /**
  35333. * Update a specific vertex buffer
  35334. * This function will create a new buffer if the current one is not updatable
  35335. * @param kind defines the data kind (Position, normal, etc...)
  35336. * @param data defines the data to use
  35337. * @param updateExtends defines if the geometry extends must be recomputed (false by default)
  35338. */
  35339. Geometry.prototype.updateVerticesData = function (kind, data, updateExtends) {
  35340. if (updateExtends === void 0) { updateExtends = false; }
  35341. var vertexBuffer = this.getVertexBuffer(kind);
  35342. if (!vertexBuffer) {
  35343. return;
  35344. }
  35345. vertexBuffer.update(data);
  35346. if (kind === BABYLON.VertexBuffer.PositionKind) {
  35347. var stride = vertexBuffer.getStrideSize();
  35348. this._totalVertices = data.length / stride;
  35349. this.updateBoundingInfo(updateExtends, data);
  35350. }
  35351. this.notifyUpdate(kind);
  35352. };
  35353. Geometry.prototype.updateBoundingInfo = function (updateExtends, data) {
  35354. if (updateExtends) {
  35355. this.updateExtend(data);
  35356. }
  35357. var meshes = this._meshes;
  35358. var numOfMeshes = meshes.length;
  35359. this._resetPointsArrayCache();
  35360. for (var index = 0; index < numOfMeshes; index++) {
  35361. var mesh = meshes[index];
  35362. if (updateExtends) {
  35363. mesh._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  35364. for (var subIndex = 0; subIndex < mesh.subMeshes.length; subIndex++) {
  35365. var subMesh = mesh.subMeshes[subIndex];
  35366. subMesh.refreshBoundingInfo();
  35367. }
  35368. }
  35369. }
  35370. };
  35371. /** @ignore */
  35372. Geometry.prototype._bind = function (effect, indexToBind) {
  35373. if (!effect) {
  35374. return;
  35375. }
  35376. if (indexToBind === undefined) {
  35377. indexToBind = this._indexBuffer;
  35378. }
  35379. var vbs = this.getVertexBuffers();
  35380. if (!vbs) {
  35381. return;
  35382. }
  35383. if (indexToBind != this._indexBuffer || !this._vertexArrayObjects) {
  35384. this._engine.bindBuffers(vbs, indexToBind, effect);
  35385. return;
  35386. }
  35387. // Using VAO
  35388. if (!this._vertexArrayObjects[effect.key]) {
  35389. this._vertexArrayObjects[effect.key] = this._engine.recordVertexArrayObject(vbs, indexToBind, effect);
  35390. }
  35391. this._engine.bindVertexArrayObject(this._vertexArrayObjects[effect.key], indexToBind);
  35392. };
  35393. /**
  35394. * Gets total number of vertices
  35395. * @returns the total number of vertices
  35396. */
  35397. Geometry.prototype.getTotalVertices = function () {
  35398. if (!this.isReady()) {
  35399. return 0;
  35400. }
  35401. return this._totalVertices;
  35402. };
  35403. /**
  35404. * Gets a specific vertex data attached to this geometry
  35405. * @param kind defines the data kind (Position, normal, etc...)
  35406. * @param copyWhenShared defines if the returned array must be cloned upon returning it if the current geometry is shared between multiple meshes
  35407. * @param forceCopy defines a boolean indicating that the returned array must be cloned upon returning it
  35408. * @returns a float array containing vertex data
  35409. */
  35410. Geometry.prototype.getVerticesData = function (kind, copyWhenShared, forceCopy) {
  35411. var vertexBuffer = this.getVertexBuffer(kind);
  35412. if (!vertexBuffer) {
  35413. return null;
  35414. }
  35415. var orig = vertexBuffer.getData();
  35416. if (!forceCopy && (!copyWhenShared || this._meshes.length === 1)) {
  35417. return orig;
  35418. }
  35419. else {
  35420. var len = orig.length;
  35421. var copy = [];
  35422. for (var i = 0; i < len; i++) {
  35423. copy.push(orig[i]);
  35424. }
  35425. return copy;
  35426. }
  35427. };
  35428. /**
  35429. * Returns a boolean defining if the vertex data for the requested `kind` is updatable
  35430. * @param kind defines the data kind (Position, normal, etc...)
  35431. * @returns true if the vertex buffer with the specified kind is updatable
  35432. */
  35433. Geometry.prototype.isVertexBufferUpdatable = function (kind) {
  35434. var vb = this._vertexBuffers[kind];
  35435. if (!vb) {
  35436. return false;
  35437. }
  35438. return vb.isUpdatable();
  35439. };
  35440. /**
  35441. * Gets a specific vertex buffer
  35442. * @param kind defines the data kind (Position, normal, etc...)
  35443. * @returns a {BABYLON.VertexBuffer}
  35444. */
  35445. Geometry.prototype.getVertexBuffer = function (kind) {
  35446. if (!this.isReady()) {
  35447. return null;
  35448. }
  35449. return this._vertexBuffers[kind];
  35450. };
  35451. /**
  35452. * Returns all vertex buffers
  35453. * @return an object holding all vertex buffers indexed by kind
  35454. */
  35455. Geometry.prototype.getVertexBuffers = function () {
  35456. if (!this.isReady()) {
  35457. return null;
  35458. }
  35459. return this._vertexBuffers;
  35460. };
  35461. /**
  35462. * Gets a boolean indicating if specific vertex buffer is present
  35463. * @param kind defines the data kind (Position, normal, etc...)
  35464. * @returns true if data is present
  35465. */
  35466. Geometry.prototype.isVerticesDataPresent = function (kind) {
  35467. if (!this._vertexBuffers) {
  35468. if (this._delayInfo) {
  35469. return this._delayInfo.indexOf(kind) !== -1;
  35470. }
  35471. return false;
  35472. }
  35473. return this._vertexBuffers[kind] !== undefined;
  35474. };
  35475. /**
  35476. * Gets a list of all attached data kinds (Position, normal, etc...)
  35477. * @returns a list of string containing all kinds
  35478. */
  35479. Geometry.prototype.getVerticesDataKinds = function () {
  35480. var result = [];
  35481. var kind;
  35482. if (!this._vertexBuffers && this._delayInfo) {
  35483. for (kind in this._delayInfo) {
  35484. result.push(kind);
  35485. }
  35486. }
  35487. else {
  35488. for (kind in this._vertexBuffers) {
  35489. result.push(kind);
  35490. }
  35491. }
  35492. return result;
  35493. };
  35494. /**
  35495. * Update index buffer
  35496. * @param indices defines the indices to store in the index buffer
  35497. * @param offset defines the offset in the target buffer where to store the data
  35498. */
  35499. Geometry.prototype.updateIndices = function (indices, offset) {
  35500. if (!this._indexBuffer) {
  35501. return;
  35502. }
  35503. if (!this._indexBufferIsUpdatable) {
  35504. this.setIndices(indices, null, true);
  35505. }
  35506. else {
  35507. this._engine.updateDynamicIndexBuffer(this._indexBuffer, indices, offset);
  35508. }
  35509. };
  35510. /**
  35511. * Creates a new index buffer
  35512. * @param indices defines the indices to store in the index buffer
  35513. * @param totalVertices defines the total number of vertices (could be null)
  35514. * @param updatable defines if the index buffer must be flagged as updatable (false by default)
  35515. */
  35516. Geometry.prototype.setIndices = function (indices, totalVertices, updatable) {
  35517. if (totalVertices === void 0) { totalVertices = null; }
  35518. if (updatable === void 0) { updatable = false; }
  35519. if (this._indexBuffer) {
  35520. this._engine._releaseBuffer(this._indexBuffer);
  35521. }
  35522. this._disposeVertexArrayObjects();
  35523. this._indices = indices;
  35524. this._indexBufferIsUpdatable = updatable;
  35525. if (this._meshes.length !== 0 && this._indices) {
  35526. this._indexBuffer = this._engine.createIndexBuffer(this._indices, updatable);
  35527. }
  35528. if (totalVertices != undefined) {
  35529. this._totalVertices = totalVertices;
  35530. }
  35531. var meshes = this._meshes;
  35532. var numOfMeshes = meshes.length;
  35533. for (var index = 0; index < numOfMeshes; index++) {
  35534. meshes[index]._createGlobalSubMesh(true);
  35535. }
  35536. this.notifyUpdate();
  35537. };
  35538. /**
  35539. * Return the total number of indices
  35540. * @returns the total number of indices
  35541. */
  35542. Geometry.prototype.getTotalIndices = function () {
  35543. if (!this.isReady()) {
  35544. return 0;
  35545. }
  35546. return this._indices.length;
  35547. };
  35548. /**
  35549. * Gets the index buffer array
  35550. * @param copyWhenShared defines if the returned array must be cloned upon returning it if the current geometry is shared between multiple meshes
  35551. * @returns the index buffer array
  35552. */
  35553. Geometry.prototype.getIndices = function (copyWhenShared) {
  35554. if (!this.isReady()) {
  35555. return null;
  35556. }
  35557. var orig = this._indices;
  35558. if (!copyWhenShared || this._meshes.length === 1) {
  35559. return orig;
  35560. }
  35561. else {
  35562. var len = orig.length;
  35563. var copy = [];
  35564. for (var i = 0; i < len; i++) {
  35565. copy.push(orig[i]);
  35566. }
  35567. return copy;
  35568. }
  35569. };
  35570. /**
  35571. * Gets the index buffer
  35572. * @return the index buffer
  35573. */
  35574. Geometry.prototype.getIndexBuffer = function () {
  35575. if (!this.isReady()) {
  35576. return null;
  35577. }
  35578. return this._indexBuffer;
  35579. };
  35580. /** @ignore */
  35581. Geometry.prototype._releaseVertexArrayObject = function (effect) {
  35582. if (effect === void 0) { effect = null; }
  35583. if (!effect || !this._vertexArrayObjects) {
  35584. return;
  35585. }
  35586. if (this._vertexArrayObjects[effect.key]) {
  35587. this._engine.releaseVertexArrayObject(this._vertexArrayObjects[effect.key]);
  35588. delete this._vertexArrayObjects[effect.key];
  35589. }
  35590. };
  35591. /**
  35592. * Release the associated resources for a specific mesh
  35593. * @param mesh defines the source mesh
  35594. * @param shouldDispose defines if the geometry must be disposed if there is no more mesh pointing to it
  35595. */
  35596. Geometry.prototype.releaseForMesh = function (mesh, shouldDispose) {
  35597. var meshes = this._meshes;
  35598. var index = meshes.indexOf(mesh);
  35599. if (index === -1) {
  35600. return;
  35601. }
  35602. meshes.splice(index, 1);
  35603. mesh._geometry = null;
  35604. if (meshes.length === 0 && shouldDispose) {
  35605. this.dispose();
  35606. }
  35607. };
  35608. /**
  35609. * Apply current geometry to a given mesh
  35610. * @param mesh defines the mesh to apply geometry to
  35611. */
  35612. Geometry.prototype.applyToMesh = function (mesh) {
  35613. if (mesh._geometry === this) {
  35614. return;
  35615. }
  35616. var previousGeometry = mesh._geometry;
  35617. if (previousGeometry) {
  35618. previousGeometry.releaseForMesh(mesh);
  35619. }
  35620. var meshes = this._meshes;
  35621. // must be done before setting vertexBuffers because of mesh._createGlobalSubMesh()
  35622. mesh._geometry = this;
  35623. this._scene.pushGeometry(this);
  35624. meshes.push(mesh);
  35625. if (this.isReady()) {
  35626. this._applyToMesh(mesh);
  35627. }
  35628. else {
  35629. mesh._boundingInfo = this._boundingInfo;
  35630. }
  35631. };
  35632. Geometry.prototype.updateExtend = function (data, stride) {
  35633. if (data === void 0) { data = null; }
  35634. if (!data) {
  35635. data = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind].getData();
  35636. }
  35637. this._extend = BABYLON.Tools.ExtractMinAndMax(data, 0, this._totalVertices, this.boundingBias, stride);
  35638. };
  35639. Geometry.prototype._applyToMesh = function (mesh) {
  35640. var numOfMeshes = this._meshes.length;
  35641. // vertexBuffers
  35642. for (var kind in this._vertexBuffers) {
  35643. if (numOfMeshes === 1) {
  35644. this._vertexBuffers[kind].create();
  35645. }
  35646. var buffer = this._vertexBuffers[kind].getBuffer();
  35647. if (buffer)
  35648. buffer.references = numOfMeshes;
  35649. if (kind === BABYLON.VertexBuffer.PositionKind) {
  35650. if (!this._extend) {
  35651. this.updateExtend(this._vertexBuffers[kind].getData());
  35652. }
  35653. mesh._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  35654. mesh._createGlobalSubMesh(false);
  35655. //bounding info was just created again, world matrix should be applied again.
  35656. mesh._updateBoundingInfo();
  35657. }
  35658. }
  35659. // indexBuffer
  35660. if (numOfMeshes === 1 && this._indices && this._indices.length > 0) {
  35661. this._indexBuffer = this._engine.createIndexBuffer(this._indices);
  35662. }
  35663. if (this._indexBuffer) {
  35664. this._indexBuffer.references = numOfMeshes;
  35665. }
  35666. };
  35667. Geometry.prototype.notifyUpdate = function (kind) {
  35668. if (this.onGeometryUpdated) {
  35669. this.onGeometryUpdated(this, kind);
  35670. }
  35671. for (var _i = 0, _a = this._meshes; _i < _a.length; _i++) {
  35672. var mesh = _a[_i];
  35673. mesh._markSubMeshesAsAttributesDirty();
  35674. }
  35675. };
  35676. /**
  35677. * Load the geometry if it was flagged as delay loaded
  35678. * @param scene defines the hosting scene
  35679. * @param onLoaded defines a callback called when the geometry is loaded
  35680. */
  35681. Geometry.prototype.load = function (scene, onLoaded) {
  35682. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  35683. return;
  35684. }
  35685. if (this.isReady()) {
  35686. if (onLoaded) {
  35687. onLoaded();
  35688. }
  35689. return;
  35690. }
  35691. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADING;
  35692. this._queueLoad(scene, onLoaded);
  35693. };
  35694. Geometry.prototype._queueLoad = function (scene, onLoaded) {
  35695. var _this = this;
  35696. if (!this.delayLoadingFile) {
  35697. return;
  35698. }
  35699. scene._addPendingData(this);
  35700. scene._loadFile(this.delayLoadingFile, function (data) {
  35701. if (!_this._delayLoadingFunction) {
  35702. return;
  35703. }
  35704. _this._delayLoadingFunction(JSON.parse(data), _this);
  35705. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  35706. _this._delayInfo = [];
  35707. scene._removePendingData(_this);
  35708. var meshes = _this._meshes;
  35709. var numOfMeshes = meshes.length;
  35710. for (var index = 0; index < numOfMeshes; index++) {
  35711. _this._applyToMesh(meshes[index]);
  35712. }
  35713. if (onLoaded) {
  35714. onLoaded();
  35715. }
  35716. }, undefined, true);
  35717. };
  35718. /**
  35719. * Invert the geometry to move from a right handed system to a left handed one.
  35720. */
  35721. Geometry.prototype.toLeftHanded = function () {
  35722. // Flip faces
  35723. var tIndices = this.getIndices(false);
  35724. if (tIndices != null && tIndices.length > 0) {
  35725. for (var i = 0; i < tIndices.length; i += 3) {
  35726. var tTemp = tIndices[i + 0];
  35727. tIndices[i + 0] = tIndices[i + 2];
  35728. tIndices[i + 2] = tTemp;
  35729. }
  35730. this.setIndices(tIndices);
  35731. }
  35732. // Negate position.z
  35733. var tPositions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind, false);
  35734. if (tPositions != null && tPositions.length > 0) {
  35735. for (var i = 0; i < tPositions.length; i += 3) {
  35736. tPositions[i + 2] = -tPositions[i + 2];
  35737. }
  35738. this.setVerticesData(BABYLON.VertexBuffer.PositionKind, tPositions, false);
  35739. }
  35740. // Negate normal.z
  35741. var tNormals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind, false);
  35742. if (tNormals != null && tNormals.length > 0) {
  35743. for (var i = 0; i < tNormals.length; i += 3) {
  35744. tNormals[i + 2] = -tNormals[i + 2];
  35745. }
  35746. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, tNormals, false);
  35747. }
  35748. };
  35749. // Cache
  35750. /** @ignore */
  35751. Geometry.prototype._resetPointsArrayCache = function () {
  35752. this._positions = null;
  35753. };
  35754. /** @ignore */
  35755. Geometry.prototype._generatePointsArray = function () {
  35756. if (this._positions)
  35757. return true;
  35758. this._positions = [];
  35759. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  35760. if (!data) {
  35761. return false;
  35762. }
  35763. for (var index = 0; index < data.length; index += 3) {
  35764. this._positions.push(BABYLON.Vector3.FromArray(data, index));
  35765. }
  35766. return true;
  35767. };
  35768. /**
  35769. * Gets a value indicating if the geometry is disposed
  35770. * @returns true if the geometry was disposed
  35771. */
  35772. Geometry.prototype.isDisposed = function () {
  35773. return this._isDisposed;
  35774. };
  35775. Geometry.prototype._disposeVertexArrayObjects = function () {
  35776. if (this._vertexArrayObjects) {
  35777. for (var kind in this._vertexArrayObjects) {
  35778. this._engine.releaseVertexArrayObject(this._vertexArrayObjects[kind]);
  35779. }
  35780. this._vertexArrayObjects = {};
  35781. }
  35782. };
  35783. /**
  35784. * Free all associated resources
  35785. */
  35786. Geometry.prototype.dispose = function () {
  35787. var meshes = this._meshes;
  35788. var numOfMeshes = meshes.length;
  35789. var index;
  35790. for (index = 0; index < numOfMeshes; index++) {
  35791. this.releaseForMesh(meshes[index]);
  35792. }
  35793. this._meshes = [];
  35794. this._disposeVertexArrayObjects();
  35795. for (var kind in this._vertexBuffers) {
  35796. this._vertexBuffers[kind].dispose();
  35797. }
  35798. this._vertexBuffers = {};
  35799. this._totalVertices = 0;
  35800. if (this._indexBuffer) {
  35801. this._engine._releaseBuffer(this._indexBuffer);
  35802. }
  35803. this._indexBuffer = null;
  35804. this._indices = [];
  35805. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  35806. this.delayLoadingFile = null;
  35807. this._delayLoadingFunction = null;
  35808. this._delayInfo = [];
  35809. this._boundingInfo = null;
  35810. this._scene.removeGeometry(this);
  35811. this._isDisposed = true;
  35812. };
  35813. /**
  35814. * Clone the current geometry into a new geometry
  35815. * @param id defines the unique ID of the new geometry
  35816. * @returns a new geometry object
  35817. */
  35818. Geometry.prototype.copy = function (id) {
  35819. var vertexData = new BABYLON.VertexData();
  35820. vertexData.indices = [];
  35821. var indices = this.getIndices();
  35822. if (indices) {
  35823. for (var index = 0; index < indices.length; index++) {
  35824. vertexData.indices.push(indices[index]);
  35825. }
  35826. }
  35827. var updatable = false;
  35828. var stopChecking = false;
  35829. var kind;
  35830. for (kind in this._vertexBuffers) {
  35831. // using slice() to make a copy of the array and not just reference it
  35832. var data = this.getVerticesData(kind);
  35833. if (data instanceof Float32Array) {
  35834. vertexData.set(new Float32Array(data), kind);
  35835. }
  35836. else {
  35837. vertexData.set(data.slice(0), kind);
  35838. }
  35839. if (!stopChecking) {
  35840. var vb = this.getVertexBuffer(kind);
  35841. if (vb) {
  35842. updatable = vb.isUpdatable();
  35843. stopChecking = !updatable;
  35844. }
  35845. }
  35846. }
  35847. var geometry = new Geometry(id, this._scene, vertexData, updatable);
  35848. geometry.delayLoadState = this.delayLoadState;
  35849. geometry.delayLoadingFile = this.delayLoadingFile;
  35850. geometry._delayLoadingFunction = this._delayLoadingFunction;
  35851. for (kind in this._delayInfo) {
  35852. geometry._delayInfo = geometry._delayInfo || [];
  35853. geometry._delayInfo.push(kind);
  35854. }
  35855. // Bounding info
  35856. geometry._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  35857. return geometry;
  35858. };
  35859. /**
  35860. * Serialize the current geometry info (and not the vertices data) into a JSON object
  35861. * @return a JSON representation of the current geometry data (without the vertices data)
  35862. */
  35863. Geometry.prototype.serialize = function () {
  35864. var serializationObject = {};
  35865. serializationObject.id = this.id;
  35866. serializationObject.updatable = this._updatable;
  35867. if (BABYLON.Tags && BABYLON.Tags.HasTags(this)) {
  35868. serializationObject.tags = BABYLON.Tags.GetTags(this);
  35869. }
  35870. return serializationObject;
  35871. };
  35872. Geometry.prototype.toNumberArray = function (origin) {
  35873. if (Array.isArray(origin)) {
  35874. return origin;
  35875. }
  35876. else {
  35877. return Array.prototype.slice.call(origin);
  35878. }
  35879. };
  35880. /**
  35881. * Serialize all vertices data into a JSON oject
  35882. * @returns a JSON representation of the current geometry data
  35883. */
  35884. Geometry.prototype.serializeVerticeData = function () {
  35885. var serializationObject = this.serialize();
  35886. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  35887. serializationObject.positions = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.PositionKind));
  35888. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.PositionKind)) {
  35889. serializationObject.positions._updatable = true;
  35890. }
  35891. }
  35892. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  35893. serializationObject.normals = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.NormalKind));
  35894. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.NormalKind)) {
  35895. serializationObject.normals._updatable = true;
  35896. }
  35897. }
  35898. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind)) {
  35899. serializationObject.tangets = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.TangentKind));
  35900. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.TangentKind)) {
  35901. serializationObject.tangets._updatable = true;
  35902. }
  35903. }
  35904. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  35905. serializationObject.uvs = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UVKind));
  35906. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UVKind)) {
  35907. serializationObject.uvs._updatable = true;
  35908. }
  35909. }
  35910. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  35911. serializationObject.uv2s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV2Kind));
  35912. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UV2Kind)) {
  35913. serializationObject.uv2s._updatable = true;
  35914. }
  35915. }
  35916. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV3Kind)) {
  35917. serializationObject.uv3s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV3Kind));
  35918. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UV3Kind)) {
  35919. serializationObject.uv3s._updatable = true;
  35920. }
  35921. }
  35922. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV4Kind)) {
  35923. serializationObject.uv4s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV4Kind));
  35924. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UV4Kind)) {
  35925. serializationObject.uv4s._updatable = true;
  35926. }
  35927. }
  35928. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV5Kind)) {
  35929. serializationObject.uv5s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV5Kind));
  35930. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UV5Kind)) {
  35931. serializationObject.uv5s._updatable = true;
  35932. }
  35933. }
  35934. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV6Kind)) {
  35935. serializationObject.uv6s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV6Kind));
  35936. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UV6Kind)) {
  35937. serializationObject.uv6s._updatable = true;
  35938. }
  35939. }
  35940. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  35941. serializationObject.colors = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.ColorKind));
  35942. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.ColorKind)) {
  35943. serializationObject.colors._updatable = true;
  35944. }
  35945. }
  35946. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  35947. serializationObject.matricesIndices = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind));
  35948. serializationObject.matricesIndices._isExpanded = true;
  35949. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  35950. serializationObject.matricesIndices._updatable = true;
  35951. }
  35952. }
  35953. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  35954. serializationObject.matricesWeights = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind));
  35955. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  35956. serializationObject.matricesWeights._updatable = true;
  35957. }
  35958. }
  35959. serializationObject.indices = this.toNumberArray(this.getIndices());
  35960. return serializationObject;
  35961. };
  35962. // Statics
  35963. /**
  35964. * Extracts a clone of a mesh geometry
  35965. * @param mesh defines the source mesh
  35966. * @param id defines the unique ID of the new geometry object
  35967. * @returns the new geometry object
  35968. */
  35969. Geometry.ExtractFromMesh = function (mesh, id) {
  35970. var geometry = mesh._geometry;
  35971. if (!geometry) {
  35972. return null;
  35973. }
  35974. return geometry.copy(id);
  35975. };
  35976. /**
  35977. * You should now use Tools.RandomId(), this method is still here for legacy reasons.
  35978. * Implementation from http://stackoverflow.com/questions/105034/how-to-create-a-guid-uuid-in-javascript/2117523#answer-2117523
  35979. * Be aware Math.random() could cause collisions, but:
  35980. * "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"
  35981. * @returns a string containing a new GUID
  35982. */
  35983. Geometry.RandomId = function () {
  35984. return BABYLON.Tools.RandomId();
  35985. };
  35986. /** @ignore */
  35987. Geometry._ImportGeometry = function (parsedGeometry, mesh) {
  35988. var scene = mesh.getScene();
  35989. // Geometry
  35990. var geometryId = parsedGeometry.geometryId;
  35991. if (geometryId) {
  35992. var geometry = scene.getGeometryByID(geometryId);
  35993. if (geometry) {
  35994. geometry.applyToMesh(mesh);
  35995. }
  35996. }
  35997. else if (parsedGeometry instanceof ArrayBuffer) {
  35998. var binaryInfo = mesh._binaryInfo;
  35999. if (binaryInfo.positionsAttrDesc && binaryInfo.positionsAttrDesc.count > 0) {
  36000. var positionsData = new Float32Array(parsedGeometry, binaryInfo.positionsAttrDesc.offset, binaryInfo.positionsAttrDesc.count);
  36001. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, positionsData, false);
  36002. }
  36003. if (binaryInfo.normalsAttrDesc && binaryInfo.normalsAttrDesc.count > 0) {
  36004. var normalsData = new Float32Array(parsedGeometry, binaryInfo.normalsAttrDesc.offset, binaryInfo.normalsAttrDesc.count);
  36005. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, normalsData, false);
  36006. }
  36007. if (binaryInfo.tangetsAttrDesc && binaryInfo.tangetsAttrDesc.count > 0) {
  36008. var tangentsData = new Float32Array(parsedGeometry, binaryInfo.tangetsAttrDesc.offset, binaryInfo.tangetsAttrDesc.count);
  36009. mesh.setVerticesData(BABYLON.VertexBuffer.TangentKind, tangentsData, false);
  36010. }
  36011. if (binaryInfo.uvsAttrDesc && binaryInfo.uvsAttrDesc.count > 0) {
  36012. var uvsData = new Float32Array(parsedGeometry, binaryInfo.uvsAttrDesc.offset, binaryInfo.uvsAttrDesc.count);
  36013. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, uvsData, false);
  36014. }
  36015. if (binaryInfo.uvs2AttrDesc && binaryInfo.uvs2AttrDesc.count > 0) {
  36016. var uvs2Data = new Float32Array(parsedGeometry, binaryInfo.uvs2AttrDesc.offset, binaryInfo.uvs2AttrDesc.count);
  36017. mesh.setVerticesData(BABYLON.VertexBuffer.UV2Kind, uvs2Data, false);
  36018. }
  36019. if (binaryInfo.uvs3AttrDesc && binaryInfo.uvs3AttrDesc.count > 0) {
  36020. var uvs3Data = new Float32Array(parsedGeometry, binaryInfo.uvs3AttrDesc.offset, binaryInfo.uvs3AttrDesc.count);
  36021. mesh.setVerticesData(BABYLON.VertexBuffer.UV3Kind, uvs3Data, false);
  36022. }
  36023. if (binaryInfo.uvs4AttrDesc && binaryInfo.uvs4AttrDesc.count > 0) {
  36024. var uvs4Data = new Float32Array(parsedGeometry, binaryInfo.uvs4AttrDesc.offset, binaryInfo.uvs4AttrDesc.count);
  36025. mesh.setVerticesData(BABYLON.VertexBuffer.UV4Kind, uvs4Data, false);
  36026. }
  36027. if (binaryInfo.uvs5AttrDesc && binaryInfo.uvs5AttrDesc.count > 0) {
  36028. var uvs5Data = new Float32Array(parsedGeometry, binaryInfo.uvs5AttrDesc.offset, binaryInfo.uvs5AttrDesc.count);
  36029. mesh.setVerticesData(BABYLON.VertexBuffer.UV5Kind, uvs5Data, false);
  36030. }
  36031. if (binaryInfo.uvs6AttrDesc && binaryInfo.uvs6AttrDesc.count > 0) {
  36032. var uvs6Data = new Float32Array(parsedGeometry, binaryInfo.uvs6AttrDesc.offset, binaryInfo.uvs6AttrDesc.count);
  36033. mesh.setVerticesData(BABYLON.VertexBuffer.UV6Kind, uvs6Data, false);
  36034. }
  36035. if (binaryInfo.colorsAttrDesc && binaryInfo.colorsAttrDesc.count > 0) {
  36036. var colorsData = new Float32Array(parsedGeometry, binaryInfo.colorsAttrDesc.offset, binaryInfo.colorsAttrDesc.count);
  36037. mesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, colorsData, false, binaryInfo.colorsAttrDesc.stride);
  36038. }
  36039. if (binaryInfo.matricesIndicesAttrDesc && binaryInfo.matricesIndicesAttrDesc.count > 0) {
  36040. var matricesIndicesData = new Int32Array(parsedGeometry, binaryInfo.matricesIndicesAttrDesc.offset, binaryInfo.matricesIndicesAttrDesc.count);
  36041. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, matricesIndicesData, false);
  36042. }
  36043. if (binaryInfo.matricesWeightsAttrDesc && binaryInfo.matricesWeightsAttrDesc.count > 0) {
  36044. var matricesWeightsData = new Float32Array(parsedGeometry, binaryInfo.matricesWeightsAttrDesc.offset, binaryInfo.matricesWeightsAttrDesc.count);
  36045. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, matricesWeightsData, false);
  36046. }
  36047. if (binaryInfo.indicesAttrDesc && binaryInfo.indicesAttrDesc.count > 0) {
  36048. var indicesData = new Int32Array(parsedGeometry, binaryInfo.indicesAttrDesc.offset, binaryInfo.indicesAttrDesc.count);
  36049. mesh.setIndices(indicesData, null);
  36050. }
  36051. if (binaryInfo.subMeshesAttrDesc && binaryInfo.subMeshesAttrDesc.count > 0) {
  36052. var subMeshesData = new Int32Array(parsedGeometry, binaryInfo.subMeshesAttrDesc.offset, binaryInfo.subMeshesAttrDesc.count * 5);
  36053. mesh.subMeshes = [];
  36054. for (var i = 0; i < binaryInfo.subMeshesAttrDesc.count; i++) {
  36055. var materialIndex = subMeshesData[(i * 5) + 0];
  36056. var verticesStart = subMeshesData[(i * 5) + 1];
  36057. var verticesCount = subMeshesData[(i * 5) + 2];
  36058. var indexStart = subMeshesData[(i * 5) + 3];
  36059. var indexCount = subMeshesData[(i * 5) + 4];
  36060. BABYLON.SubMesh.AddToMesh(materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh);
  36061. }
  36062. }
  36063. }
  36064. else if (parsedGeometry.positions && parsedGeometry.normals && parsedGeometry.indices) {
  36065. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, parsedGeometry.positions, parsedGeometry.positions._updatable);
  36066. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, parsedGeometry.normals, parsedGeometry.normals._updatable);
  36067. if (parsedGeometry.tangents) {
  36068. mesh.setVerticesData(BABYLON.VertexBuffer.TangentKind, parsedGeometry.tangents, parsedGeometry.tangents._updatable);
  36069. }
  36070. if (parsedGeometry.uvs) {
  36071. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, parsedGeometry.uvs, parsedGeometry.uvs._updatable);
  36072. }
  36073. if (parsedGeometry.uvs2) {
  36074. mesh.setVerticesData(BABYLON.VertexBuffer.UV2Kind, parsedGeometry.uvs2, parsedGeometry.uvs2._updatable);
  36075. }
  36076. if (parsedGeometry.uvs3) {
  36077. mesh.setVerticesData(BABYLON.VertexBuffer.UV3Kind, parsedGeometry.uvs3, parsedGeometry.uvs3._updatable);
  36078. }
  36079. if (parsedGeometry.uvs4) {
  36080. mesh.setVerticesData(BABYLON.VertexBuffer.UV4Kind, parsedGeometry.uvs4, parsedGeometry.uvs4._updatable);
  36081. }
  36082. if (parsedGeometry.uvs5) {
  36083. mesh.setVerticesData(BABYLON.VertexBuffer.UV5Kind, parsedGeometry.uvs5, parsedGeometry.uvs5._updatable);
  36084. }
  36085. if (parsedGeometry.uvs6) {
  36086. mesh.setVerticesData(BABYLON.VertexBuffer.UV6Kind, parsedGeometry.uvs6, parsedGeometry.uvs6._updatable);
  36087. }
  36088. if (parsedGeometry.colors) {
  36089. mesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, BABYLON.Color4.CheckColors4(parsedGeometry.colors, parsedGeometry.positions.length / 3), parsedGeometry.colors._updatable);
  36090. }
  36091. if (parsedGeometry.matricesIndices) {
  36092. if (!parsedGeometry.matricesIndices._isExpanded) {
  36093. var floatIndices = [];
  36094. for (var i = 0; i < parsedGeometry.matricesIndices.length; i++) {
  36095. var matricesIndex = parsedGeometry.matricesIndices[i];
  36096. floatIndices.push(matricesIndex & 0x000000FF);
  36097. floatIndices.push((matricesIndex & 0x0000FF00) >> 8);
  36098. floatIndices.push((matricesIndex & 0x00FF0000) >> 16);
  36099. floatIndices.push(matricesIndex >> 24);
  36100. }
  36101. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, floatIndices, parsedGeometry.matricesIndices._updatable);
  36102. }
  36103. else {
  36104. delete parsedGeometry.matricesIndices._isExpanded;
  36105. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, parsedGeometry.matricesIndices, parsedGeometry.matricesIndices._updatable);
  36106. }
  36107. }
  36108. if (parsedGeometry.matricesIndicesExtra) {
  36109. if (!parsedGeometry.matricesIndicesExtra._isExpanded) {
  36110. var floatIndices = [];
  36111. for (var i = 0; i < parsedGeometry.matricesIndicesExtra.length; i++) {
  36112. var matricesIndex = parsedGeometry.matricesIndicesExtra[i];
  36113. floatIndices.push(matricesIndex & 0x000000FF);
  36114. floatIndices.push((matricesIndex & 0x0000FF00) >> 8);
  36115. floatIndices.push((matricesIndex & 0x00FF0000) >> 16);
  36116. floatIndices.push(matricesIndex >> 24);
  36117. }
  36118. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, floatIndices, parsedGeometry.matricesIndicesExtra._updatable);
  36119. }
  36120. else {
  36121. delete parsedGeometry.matricesIndices._isExpanded;
  36122. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, parsedGeometry.matricesIndicesExtra, parsedGeometry.matricesIndicesExtra._updatable);
  36123. }
  36124. }
  36125. if (parsedGeometry.matricesWeights) {
  36126. Geometry._CleanMatricesWeights(parsedGeometry, mesh);
  36127. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, parsedGeometry.matricesWeights, parsedGeometry.matricesWeights._updatable);
  36128. }
  36129. if (parsedGeometry.matricesWeightsExtra) {
  36130. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, parsedGeometry.matricesWeightsExtra, parsedGeometry.matricesWeights._updatable);
  36131. }
  36132. mesh.setIndices(parsedGeometry.indices, null);
  36133. }
  36134. // SubMeshes
  36135. if (parsedGeometry.subMeshes) {
  36136. mesh.subMeshes = [];
  36137. for (var subIndex = 0; subIndex < parsedGeometry.subMeshes.length; subIndex++) {
  36138. var parsedSubMesh = parsedGeometry.subMeshes[subIndex];
  36139. BABYLON.SubMesh.AddToMesh(parsedSubMesh.materialIndex, parsedSubMesh.verticesStart, parsedSubMesh.verticesCount, parsedSubMesh.indexStart, parsedSubMesh.indexCount, mesh);
  36140. }
  36141. }
  36142. // Flat shading
  36143. if (mesh._shouldGenerateFlatShading) {
  36144. mesh.convertToFlatShadedMesh();
  36145. delete mesh._shouldGenerateFlatShading;
  36146. }
  36147. // Update
  36148. mesh.computeWorldMatrix(true);
  36149. // Octree
  36150. var sceneOctree = scene.selectionOctree;
  36151. if (sceneOctree !== undefined && sceneOctree !== null) {
  36152. sceneOctree.addMesh(mesh);
  36153. }
  36154. };
  36155. Geometry._CleanMatricesWeights = function (parsedGeometry, mesh) {
  36156. var epsilon = 1e-3;
  36157. if (!BABYLON.SceneLoader.CleanBoneMatrixWeights) {
  36158. return;
  36159. }
  36160. var noInfluenceBoneIndex = 0.0;
  36161. if (parsedGeometry.skeletonId > -1) {
  36162. var skeleton = mesh.getScene().getLastSkeletonByID(parsedGeometry.skeletonId);
  36163. if (!skeleton) {
  36164. return;
  36165. }
  36166. noInfluenceBoneIndex = skeleton.bones.length;
  36167. }
  36168. else {
  36169. return;
  36170. }
  36171. var matricesIndices = mesh.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind);
  36172. var matricesIndicesExtra = mesh.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  36173. var matricesWeights = parsedGeometry.matricesWeights;
  36174. var matricesWeightsExtra = parsedGeometry.matricesWeightsExtra;
  36175. var influencers = parsedGeometry.numBoneInfluencer;
  36176. var size = matricesWeights.length;
  36177. for (var i = 0; i < size; i += 4) {
  36178. var weight = 0.0;
  36179. var firstZeroWeight = -1;
  36180. for (var j = 0; j < 4; j++) {
  36181. var w = matricesWeights[i + j];
  36182. weight += w;
  36183. if (w < epsilon && firstZeroWeight < 0) {
  36184. firstZeroWeight = j;
  36185. }
  36186. }
  36187. if (matricesWeightsExtra) {
  36188. for (var j = 0; j < 4; j++) {
  36189. var w = matricesWeightsExtra[i + j];
  36190. weight += w;
  36191. if (w < epsilon && firstZeroWeight < 0) {
  36192. firstZeroWeight = j + 4;
  36193. }
  36194. }
  36195. }
  36196. if (firstZeroWeight < 0 || firstZeroWeight > (influencers - 1)) {
  36197. firstZeroWeight = influencers - 1;
  36198. }
  36199. if (weight > epsilon) {
  36200. var mweight = 1.0 / weight;
  36201. for (var j = 0; j < 4; j++) {
  36202. matricesWeights[i + j] *= mweight;
  36203. }
  36204. if (matricesWeightsExtra) {
  36205. for (var j = 0; j < 4; j++) {
  36206. matricesWeightsExtra[i + j] *= mweight;
  36207. }
  36208. }
  36209. }
  36210. else {
  36211. if (firstZeroWeight >= 4) {
  36212. matricesWeightsExtra[i + firstZeroWeight - 4] = 1.0 - weight;
  36213. matricesIndicesExtra[i + firstZeroWeight - 4] = noInfluenceBoneIndex;
  36214. }
  36215. else {
  36216. matricesWeights[i + firstZeroWeight] = 1.0 - weight;
  36217. matricesIndices[i + firstZeroWeight] = noInfluenceBoneIndex;
  36218. }
  36219. }
  36220. }
  36221. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, matricesIndices);
  36222. if (parsedGeometry.matricesWeightsExtra) {
  36223. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, matricesIndicesExtra);
  36224. }
  36225. };
  36226. /**
  36227. * Create a new geometry from persisted data (Using .babylon file format)
  36228. * @param parsedVertexData defines the persisted data
  36229. * @param scene defines the hosting scene
  36230. * @param rootUrl defines the root url to use to load assets (like delayed data)
  36231. * @returns the new geometry object
  36232. */
  36233. Geometry.Parse = function (parsedVertexData, scene, rootUrl) {
  36234. if (scene.getGeometryByID(parsedVertexData.id)) {
  36235. return null; // null since geometry could be something else than a box...
  36236. }
  36237. var geometry = new Geometry(parsedVertexData.id, scene, undefined, parsedVertexData.updatable);
  36238. if (BABYLON.Tags) {
  36239. BABYLON.Tags.AddTagsTo(geometry, parsedVertexData.tags);
  36240. }
  36241. if (parsedVertexData.delayLoadingFile) {
  36242. geometry.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  36243. geometry.delayLoadingFile = rootUrl + parsedVertexData.delayLoadingFile;
  36244. geometry._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Vector3.FromArray(parsedVertexData.boundingBoxMinimum), BABYLON.Vector3.FromArray(parsedVertexData.boundingBoxMaximum));
  36245. geometry._delayInfo = [];
  36246. if (parsedVertexData.hasUVs) {
  36247. geometry._delayInfo.push(BABYLON.VertexBuffer.UVKind);
  36248. }
  36249. if (parsedVertexData.hasUVs2) {
  36250. geometry._delayInfo.push(BABYLON.VertexBuffer.UV2Kind);
  36251. }
  36252. if (parsedVertexData.hasUVs3) {
  36253. geometry._delayInfo.push(BABYLON.VertexBuffer.UV3Kind);
  36254. }
  36255. if (parsedVertexData.hasUVs4) {
  36256. geometry._delayInfo.push(BABYLON.VertexBuffer.UV4Kind);
  36257. }
  36258. if (parsedVertexData.hasUVs5) {
  36259. geometry._delayInfo.push(BABYLON.VertexBuffer.UV5Kind);
  36260. }
  36261. if (parsedVertexData.hasUVs6) {
  36262. geometry._delayInfo.push(BABYLON.VertexBuffer.UV6Kind);
  36263. }
  36264. if (parsedVertexData.hasColors) {
  36265. geometry._delayInfo.push(BABYLON.VertexBuffer.ColorKind);
  36266. }
  36267. if (parsedVertexData.hasMatricesIndices) {
  36268. geometry._delayInfo.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  36269. }
  36270. if (parsedVertexData.hasMatricesWeights) {
  36271. geometry._delayInfo.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  36272. }
  36273. geometry._delayLoadingFunction = BABYLON.VertexData.ImportVertexData;
  36274. }
  36275. else {
  36276. BABYLON.VertexData.ImportVertexData(parsedVertexData, geometry);
  36277. }
  36278. scene.pushGeometry(geometry, true);
  36279. return geometry;
  36280. };
  36281. return Geometry;
  36282. }());
  36283. BABYLON.Geometry = Geometry;
  36284. // Primitives
  36285. /// Abstract class
  36286. /**
  36287. * Abstract class used to provide common services for all typed geometries
  36288. */
  36289. var _PrimitiveGeometry = /** @class */ (function (_super) {
  36290. __extends(_PrimitiveGeometry, _super);
  36291. /**
  36292. * Creates a new typed geometry
  36293. * @param id defines the unique ID of the geometry
  36294. * @param scene defines the hosting scene
  36295. * @param _canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  36296. * @param mesh defines the hosting mesh (can be null)
  36297. */
  36298. function _PrimitiveGeometry(id, scene, _canBeRegenerated, mesh) {
  36299. if (_canBeRegenerated === void 0) { _canBeRegenerated = false; }
  36300. if (mesh === void 0) { mesh = null; }
  36301. var _this = _super.call(this, id, scene, undefined, false, mesh) || this;
  36302. _this._canBeRegenerated = _canBeRegenerated;
  36303. _this._beingRegenerated = true;
  36304. _this.regenerate();
  36305. _this._beingRegenerated = false;
  36306. return _this;
  36307. }
  36308. /**
  36309. * Gets a value indicating if the geometry supports being regenerated with new parameters (false by default)
  36310. * @returns true if the geometry can be regenerated
  36311. */
  36312. _PrimitiveGeometry.prototype.canBeRegenerated = function () {
  36313. return this._canBeRegenerated;
  36314. };
  36315. /**
  36316. * If the geometry supports regeneration, the function will recreates the geometry with updated parameter values
  36317. */
  36318. _PrimitiveGeometry.prototype.regenerate = function () {
  36319. if (!this._canBeRegenerated) {
  36320. return;
  36321. }
  36322. this._beingRegenerated = true;
  36323. this.setAllVerticesData(this._regenerateVertexData(), false);
  36324. this._beingRegenerated = false;
  36325. };
  36326. /**
  36327. * Clone the geometry
  36328. * @param id defines the unique ID of the new geometry
  36329. * @returns the new geometry
  36330. */
  36331. _PrimitiveGeometry.prototype.asNewGeometry = function (id) {
  36332. return _super.prototype.copy.call(this, id);
  36333. };
  36334. // overrides
  36335. _PrimitiveGeometry.prototype.setAllVerticesData = function (vertexData, updatable) {
  36336. if (!this._beingRegenerated) {
  36337. return;
  36338. }
  36339. _super.prototype.setAllVerticesData.call(this, vertexData, false);
  36340. };
  36341. _PrimitiveGeometry.prototype.setVerticesData = function (kind, data, updatable) {
  36342. if (!this._beingRegenerated) {
  36343. return;
  36344. }
  36345. _super.prototype.setVerticesData.call(this, kind, data, false);
  36346. };
  36347. // to override
  36348. /** @ignore */
  36349. _PrimitiveGeometry.prototype._regenerateVertexData = function () {
  36350. throw new Error("Abstract method");
  36351. };
  36352. _PrimitiveGeometry.prototype.copy = function (id) {
  36353. throw new Error("Must be overriden in sub-classes.");
  36354. };
  36355. _PrimitiveGeometry.prototype.serialize = function () {
  36356. var serializationObject = _super.prototype.serialize.call(this);
  36357. serializationObject.canBeRegenerated = this.canBeRegenerated();
  36358. return serializationObject;
  36359. };
  36360. return _PrimitiveGeometry;
  36361. }(Geometry));
  36362. BABYLON._PrimitiveGeometry = _PrimitiveGeometry;
  36363. /**
  36364. * Creates a ribbon geometry
  36365. * @description See http://doc.babylonjs.com/how_to/ribbon_tutorial, http://doc.babylonjs.com/resources/maths_make_ribbons
  36366. */
  36367. var RibbonGeometry = /** @class */ (function (_super) {
  36368. __extends(RibbonGeometry, _super);
  36369. /**
  36370. * Creates a ribbon geometry
  36371. * @param id defines the unique ID of the geometry
  36372. * @param scene defines the hosting scene
  36373. * @param pathArray defines the array of paths to use
  36374. * @param closeArray defines if the last path and the first path must be joined
  36375. * @param closePath defines if the last and first points of each path in your pathArray must be joined
  36376. * @param offset defines the offset between points
  36377. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  36378. * @param mesh defines the hosting mesh (can be null)
  36379. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  36380. */
  36381. function RibbonGeometry(id, scene,
  36382. /**
  36383. * Defines the array of paths to use
  36384. */
  36385. pathArray,
  36386. /**
  36387. * Defines if the last and first points of each path in your pathArray must be joined
  36388. */
  36389. closeArray,
  36390. /**
  36391. * Defines if the last and first points of each path in your pathArray must be joined
  36392. */
  36393. closePath,
  36394. /**
  36395. * Defines the offset between points
  36396. */
  36397. offset, canBeRegenerated, mesh,
  36398. /**
  36399. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  36400. */
  36401. side) {
  36402. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  36403. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  36404. _this.pathArray = pathArray;
  36405. _this.closeArray = closeArray;
  36406. _this.closePath = closePath;
  36407. _this.offset = offset;
  36408. _this.side = side;
  36409. return _this;
  36410. }
  36411. /** @ignore */
  36412. RibbonGeometry.prototype._regenerateVertexData = function () {
  36413. return BABYLON.VertexData.CreateRibbon({ pathArray: this.pathArray, closeArray: this.closeArray, closePath: this.closePath, offset: this.offset, sideOrientation: this.side });
  36414. };
  36415. RibbonGeometry.prototype.copy = function (id) {
  36416. return new RibbonGeometry(id, this.getScene(), this.pathArray, this.closeArray, this.closePath, this.offset, this.canBeRegenerated(), undefined, this.side);
  36417. };
  36418. return RibbonGeometry;
  36419. }(_PrimitiveGeometry));
  36420. BABYLON.RibbonGeometry = RibbonGeometry;
  36421. /**
  36422. * Creates a box geometry
  36423. * @description see http://doc.babylonjs.com/how_to/set_shapes#box
  36424. */
  36425. var BoxGeometry = /** @class */ (function (_super) {
  36426. __extends(BoxGeometry, _super);
  36427. /**
  36428. * Creates a box geometry
  36429. * @param id defines the unique ID of the geometry
  36430. * @param scene defines the hosting scene
  36431. * @param size defines the zise of the box (width, height and depth are the same)
  36432. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  36433. * @param mesh defines the hosting mesh (can be null)
  36434. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  36435. */
  36436. function BoxGeometry(id, scene,
  36437. /**
  36438. * Defines the zise of the box (width, height and depth are the same)
  36439. */
  36440. size, canBeRegenerated, mesh,
  36441. /**
  36442. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  36443. */
  36444. side) {
  36445. if (mesh === void 0) { mesh = null; }
  36446. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  36447. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  36448. _this.size = size;
  36449. _this.side = side;
  36450. return _this;
  36451. }
  36452. BoxGeometry.prototype._regenerateVertexData = function () {
  36453. return BABYLON.VertexData.CreateBox({ size: this.size, sideOrientation: this.side });
  36454. };
  36455. BoxGeometry.prototype.copy = function (id) {
  36456. return new BoxGeometry(id, this.getScene(), this.size, this.canBeRegenerated(), undefined, this.side);
  36457. };
  36458. BoxGeometry.prototype.serialize = function () {
  36459. var serializationObject = _super.prototype.serialize.call(this);
  36460. serializationObject.size = this.size;
  36461. return serializationObject;
  36462. };
  36463. BoxGeometry.Parse = function (parsedBox, scene) {
  36464. if (scene.getGeometryByID(parsedBox.id)) {
  36465. return null; // null since geometry could be something else than a box...
  36466. }
  36467. var box = new BoxGeometry(parsedBox.id, scene, parsedBox.size, parsedBox.canBeRegenerated, null);
  36468. if (BABYLON.Tags) {
  36469. BABYLON.Tags.AddTagsTo(box, parsedBox.tags);
  36470. }
  36471. scene.pushGeometry(box, true);
  36472. return box;
  36473. };
  36474. return BoxGeometry;
  36475. }(_PrimitiveGeometry));
  36476. BABYLON.BoxGeometry = BoxGeometry;
  36477. /**
  36478. * Creates a sphere geometry
  36479. * @description see http://doc.babylonjs.com/how_to/set_shapes#sphere
  36480. */
  36481. var SphereGeometry = /** @class */ (function (_super) {
  36482. __extends(SphereGeometry, _super);
  36483. /**
  36484. * Create a new sphere geometry
  36485. * @param id defines the unique ID of the geometry
  36486. * @param scene defines the hosting scene
  36487. * @param segments defines the number of segments to use to create the sphere
  36488. * @param diameter defines the diameter of the sphere
  36489. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  36490. * @param mesh defines the hosting mesh (can be null)
  36491. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  36492. */
  36493. function SphereGeometry(id, scene,
  36494. /**
  36495. * Defines the number of segments to use to create the sphere
  36496. */
  36497. segments,
  36498. /**
  36499. * Defines the diameter of the sphere
  36500. */
  36501. diameter, canBeRegenerated, mesh,
  36502. /**
  36503. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  36504. */
  36505. side) {
  36506. if (mesh === void 0) { mesh = null; }
  36507. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  36508. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  36509. _this.segments = segments;
  36510. _this.diameter = diameter;
  36511. _this.side = side;
  36512. return _this;
  36513. }
  36514. SphereGeometry.prototype._regenerateVertexData = function () {
  36515. return BABYLON.VertexData.CreateSphere({ segments: this.segments, diameter: this.diameter, sideOrientation: this.side });
  36516. };
  36517. SphereGeometry.prototype.copy = function (id) {
  36518. return new SphereGeometry(id, this.getScene(), this.segments, this.diameter, this.canBeRegenerated(), null, this.side);
  36519. };
  36520. SphereGeometry.prototype.serialize = function () {
  36521. var serializationObject = _super.prototype.serialize.call(this);
  36522. serializationObject.segments = this.segments;
  36523. serializationObject.diameter = this.diameter;
  36524. return serializationObject;
  36525. };
  36526. SphereGeometry.Parse = function (parsedSphere, scene) {
  36527. if (scene.getGeometryByID(parsedSphere.id)) {
  36528. return null; // null since geometry could be something else than a sphere...
  36529. }
  36530. var sphere = new SphereGeometry(parsedSphere.id, scene, parsedSphere.segments, parsedSphere.diameter, parsedSphere.canBeRegenerated, null);
  36531. if (BABYLON.Tags) {
  36532. BABYLON.Tags.AddTagsTo(sphere, parsedSphere.tags);
  36533. }
  36534. scene.pushGeometry(sphere, true);
  36535. return sphere;
  36536. };
  36537. return SphereGeometry;
  36538. }(_PrimitiveGeometry));
  36539. BABYLON.SphereGeometry = SphereGeometry;
  36540. /**
  36541. * Creates a disc geometry
  36542. * @description see http://doc.babylonjs.com/how_to/set_shapes#disc-or-regular-polygon
  36543. */
  36544. var DiscGeometry = /** @class */ (function (_super) {
  36545. __extends(DiscGeometry, _super);
  36546. /**
  36547. * Creates a new disc geometry
  36548. * @param id defines the unique ID of the geometry
  36549. * @param scene defines the hosting scene
  36550. * @param radius defines the radius of the disc
  36551. * @param tessellation defines the tesselation factor to apply to the disc
  36552. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  36553. * @param mesh defines the hosting mesh (can be null)
  36554. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  36555. */
  36556. function DiscGeometry(id, scene,
  36557. /**
  36558. * Defines the radius of the disc
  36559. */
  36560. radius,
  36561. /**
  36562. * Defines the tesselation factor to apply to the disc
  36563. */
  36564. tessellation, canBeRegenerated, mesh,
  36565. /**
  36566. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  36567. */
  36568. side) {
  36569. if (mesh === void 0) { mesh = null; }
  36570. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  36571. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  36572. _this.radius = radius;
  36573. _this.tessellation = tessellation;
  36574. _this.side = side;
  36575. return _this;
  36576. }
  36577. DiscGeometry.prototype._regenerateVertexData = function () {
  36578. return BABYLON.VertexData.CreateDisc({ radius: this.radius, tessellation: this.tessellation, sideOrientation: this.side });
  36579. };
  36580. DiscGeometry.prototype.copy = function (id) {
  36581. return new DiscGeometry(id, this.getScene(), this.radius, this.tessellation, this.canBeRegenerated(), null, this.side);
  36582. };
  36583. return DiscGeometry;
  36584. }(_PrimitiveGeometry));
  36585. BABYLON.DiscGeometry = DiscGeometry;
  36586. /**
  36587. * Creates a new cylinder geometry
  36588. * @description see http://doc.babylonjs.com/how_to/set_shapes#cylinder-or-cone
  36589. */
  36590. var CylinderGeometry = /** @class */ (function (_super) {
  36591. __extends(CylinderGeometry, _super);
  36592. /**
  36593. * Creates a new cylinder geometry
  36594. * @param id defines the unique ID of the geometry
  36595. * @param scene defines the hosting scene
  36596. * @param height defines the height of the cylinder
  36597. * @param diameterTop defines the diameter of the cylinder's top cap
  36598. * @param diameterBottom defines the diameter of the cylinder's bottom cap
  36599. * @param tessellation defines the tessellation factor to apply to the cylinder (number of radial sides)
  36600. * @param subdivisions defines the number of subdivisions to apply to the cylinder (number of rings) (1 by default)
  36601. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  36602. * @param mesh defines the hosting mesh (can be null)
  36603. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  36604. */
  36605. function CylinderGeometry(id, scene,
  36606. /**
  36607. * Defines the height of the cylinder
  36608. */
  36609. height,
  36610. /**
  36611. * Defines the diameter of the cylinder's top cap
  36612. */
  36613. diameterTop,
  36614. /**
  36615. * Defines the diameter of the cylinder's bottom cap
  36616. */
  36617. diameterBottom,
  36618. /**
  36619. * Defines the tessellation factor to apply to the cylinder
  36620. */
  36621. tessellation,
  36622. /**
  36623. * Defines the number of subdivisions to apply to the cylinder (1 by default)
  36624. */
  36625. subdivisions, canBeRegenerated, mesh,
  36626. /**
  36627. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  36628. */
  36629. side) {
  36630. if (subdivisions === void 0) { subdivisions = 1; }
  36631. if (mesh === void 0) { mesh = null; }
  36632. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  36633. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  36634. _this.height = height;
  36635. _this.diameterTop = diameterTop;
  36636. _this.diameterBottom = diameterBottom;
  36637. _this.tessellation = tessellation;
  36638. _this.subdivisions = subdivisions;
  36639. _this.side = side;
  36640. return _this;
  36641. }
  36642. CylinderGeometry.prototype._regenerateVertexData = function () {
  36643. return BABYLON.VertexData.CreateCylinder({ height: this.height, diameterTop: this.diameterTop, diameterBottom: this.diameterBottom, tessellation: this.tessellation, subdivisions: this.subdivisions, sideOrientation: this.side });
  36644. };
  36645. CylinderGeometry.prototype.copy = function (id) {
  36646. return new CylinderGeometry(id, this.getScene(), this.height, this.diameterTop, this.diameterBottom, this.tessellation, this.subdivisions, this.canBeRegenerated(), null, this.side);
  36647. };
  36648. CylinderGeometry.prototype.serialize = function () {
  36649. var serializationObject = _super.prototype.serialize.call(this);
  36650. serializationObject.height = this.height;
  36651. serializationObject.diameterTop = this.diameterTop;
  36652. serializationObject.diameterBottom = this.diameterBottom;
  36653. serializationObject.tessellation = this.tessellation;
  36654. return serializationObject;
  36655. };
  36656. CylinderGeometry.Parse = function (parsedCylinder, scene) {
  36657. if (scene.getGeometryByID(parsedCylinder.id)) {
  36658. return null; // null since geometry could be something else than a cylinder...
  36659. }
  36660. var cylinder = new CylinderGeometry(parsedCylinder.id, scene, parsedCylinder.height, parsedCylinder.diameterTop, parsedCylinder.diameterBottom, parsedCylinder.tessellation, parsedCylinder.subdivisions, parsedCylinder.canBeRegenerated, null);
  36661. if (BABYLON.Tags) {
  36662. BABYLON.Tags.AddTagsTo(cylinder, parsedCylinder.tags);
  36663. }
  36664. scene.pushGeometry(cylinder, true);
  36665. return cylinder;
  36666. };
  36667. return CylinderGeometry;
  36668. }(_PrimitiveGeometry));
  36669. BABYLON.CylinderGeometry = CylinderGeometry;
  36670. /**
  36671. * Creates a new torus geometry
  36672. * @description see http://doc.babylonjs.com/how_to/set_shapes#torus
  36673. */
  36674. var TorusGeometry = /** @class */ (function (_super) {
  36675. __extends(TorusGeometry, _super);
  36676. /**
  36677. * Creates a new torus geometry
  36678. * @param id defines the unique ID of the geometry
  36679. * @param scene defines the hosting scene
  36680. * @param diameter defines the diameter of the torus
  36681. * @param thickness defines the thickness of the torus (ie. internal diameter)
  36682. * @param tessellation defines the tesselation factor to apply to the torus (number of segments along the circle)
  36683. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  36684. * @param mesh defines the hosting mesh (can be null)
  36685. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  36686. */
  36687. function TorusGeometry(id, scene,
  36688. /**
  36689. * Defines the diameter of the torus
  36690. */
  36691. diameter,
  36692. /**
  36693. * Defines the thickness of the torus (ie. internal diameter)
  36694. */
  36695. thickness,
  36696. /**
  36697. * Defines the tesselation factor to apply to the torus
  36698. */
  36699. tessellation, canBeRegenerated, mesh,
  36700. /**
  36701. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  36702. */
  36703. side) {
  36704. if (mesh === void 0) { mesh = null; }
  36705. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  36706. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  36707. _this.diameter = diameter;
  36708. _this.thickness = thickness;
  36709. _this.tessellation = tessellation;
  36710. _this.side = side;
  36711. return _this;
  36712. }
  36713. TorusGeometry.prototype._regenerateVertexData = function () {
  36714. return BABYLON.VertexData.CreateTorus({ diameter: this.diameter, thickness: this.thickness, tessellation: this.tessellation, sideOrientation: this.side });
  36715. };
  36716. TorusGeometry.prototype.copy = function (id) {
  36717. return new TorusGeometry(id, this.getScene(), this.diameter, this.thickness, this.tessellation, this.canBeRegenerated(), null, this.side);
  36718. };
  36719. TorusGeometry.prototype.serialize = function () {
  36720. var serializationObject = _super.prototype.serialize.call(this);
  36721. serializationObject.diameter = this.diameter;
  36722. serializationObject.thickness = this.thickness;
  36723. serializationObject.tessellation = this.tessellation;
  36724. return serializationObject;
  36725. };
  36726. TorusGeometry.Parse = function (parsedTorus, scene) {
  36727. if (scene.getGeometryByID(parsedTorus.id)) {
  36728. return null; // null since geometry could be something else than a torus...
  36729. }
  36730. var torus = new TorusGeometry(parsedTorus.id, scene, parsedTorus.diameter, parsedTorus.thickness, parsedTorus.tessellation, parsedTorus.canBeRegenerated, null);
  36731. if (BABYLON.Tags) {
  36732. BABYLON.Tags.AddTagsTo(torus, parsedTorus.tags);
  36733. }
  36734. scene.pushGeometry(torus, true);
  36735. return torus;
  36736. };
  36737. return TorusGeometry;
  36738. }(_PrimitiveGeometry));
  36739. BABYLON.TorusGeometry = TorusGeometry;
  36740. /**
  36741. * Creates a new ground geometry
  36742. * @description see http://doc.babylonjs.com/how_to/set_shapes#ground
  36743. */
  36744. var GroundGeometry = /** @class */ (function (_super) {
  36745. __extends(GroundGeometry, _super);
  36746. /**
  36747. * Creates a new ground geometry
  36748. * @param id defines the unique ID of the geometry
  36749. * @param scene defines the hosting scene
  36750. * @param width defines the width of the ground
  36751. * @param height defines the height of the ground
  36752. * @param subdivisions defines the subdivisions to apply to the ground
  36753. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  36754. * @param mesh defines the hosting mesh (can be null)
  36755. */
  36756. function GroundGeometry(id, scene,
  36757. /**
  36758. * Defines the width of the ground
  36759. */
  36760. width,
  36761. /**
  36762. * Defines the height of the ground
  36763. */
  36764. height,
  36765. /**
  36766. * Defines the subdivisions to apply to the ground
  36767. */
  36768. subdivisions, canBeRegenerated, mesh) {
  36769. if (mesh === void 0) { mesh = null; }
  36770. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  36771. _this.width = width;
  36772. _this.height = height;
  36773. _this.subdivisions = subdivisions;
  36774. return _this;
  36775. }
  36776. GroundGeometry.prototype._regenerateVertexData = function () {
  36777. return BABYLON.VertexData.CreateGround({ width: this.width, height: this.height, subdivisions: this.subdivisions });
  36778. };
  36779. GroundGeometry.prototype.copy = function (id) {
  36780. return new GroundGeometry(id, this.getScene(), this.width, this.height, this.subdivisions, this.canBeRegenerated(), null);
  36781. };
  36782. GroundGeometry.prototype.serialize = function () {
  36783. var serializationObject = _super.prototype.serialize.call(this);
  36784. serializationObject.width = this.width;
  36785. serializationObject.height = this.height;
  36786. serializationObject.subdivisions = this.subdivisions;
  36787. return serializationObject;
  36788. };
  36789. GroundGeometry.Parse = function (parsedGround, scene) {
  36790. if (scene.getGeometryByID(parsedGround.id)) {
  36791. return null; // null since geometry could be something else than a ground...
  36792. }
  36793. var ground = new GroundGeometry(parsedGround.id, scene, parsedGround.width, parsedGround.height, parsedGround.subdivisions, parsedGround.canBeRegenerated, null);
  36794. if (BABYLON.Tags) {
  36795. BABYLON.Tags.AddTagsTo(ground, parsedGround.tags);
  36796. }
  36797. scene.pushGeometry(ground, true);
  36798. return ground;
  36799. };
  36800. return GroundGeometry;
  36801. }(_PrimitiveGeometry));
  36802. BABYLON.GroundGeometry = GroundGeometry;
  36803. /**
  36804. * Creates a tiled ground geometry
  36805. * @description see http://doc.babylonjs.com/how_to/set_shapes#tiled-ground
  36806. */
  36807. var TiledGroundGeometry = /** @class */ (function (_super) {
  36808. __extends(TiledGroundGeometry, _super);
  36809. /**
  36810. * Creates a tiled ground geometry
  36811. * @param id defines the unique ID of the geometry
  36812. * @param scene defines the hosting scene
  36813. * @param xmin defines the minimum value on X axis
  36814. * @param zmin defines the minimum value on Z axis
  36815. * @param xmax defines the maximum value on X axis
  36816. * @param zmax defines the maximum value on Z axis
  36817. * @param subdivisions defines the subdivisions to apply to the ground (number of subdivisions (tiles) on the height and the width of the map)
  36818. * @param precision defines the precision to use when computing the tiles
  36819. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  36820. * @param mesh defines the hosting mesh (can be null)
  36821. */
  36822. function TiledGroundGeometry(id, scene,
  36823. /**
  36824. * Defines the minimum value on X axis
  36825. */
  36826. xmin,
  36827. /**
  36828. * Defines the minimum value on Z axis
  36829. */
  36830. zmin,
  36831. /**
  36832. * Defines the maximum value on X axis
  36833. */
  36834. xmax,
  36835. /**
  36836. * Defines the maximum value on Z axis
  36837. */
  36838. zmax,
  36839. /**
  36840. * Defines the subdivisions to apply to the ground
  36841. */
  36842. subdivisions,
  36843. /**
  36844. * Defines the precision to use when computing the tiles
  36845. */
  36846. precision, canBeRegenerated, mesh) {
  36847. if (mesh === void 0) { mesh = null; }
  36848. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  36849. _this.xmin = xmin;
  36850. _this.zmin = zmin;
  36851. _this.xmax = xmax;
  36852. _this.zmax = zmax;
  36853. _this.subdivisions = subdivisions;
  36854. _this.precision = precision;
  36855. return _this;
  36856. }
  36857. TiledGroundGeometry.prototype._regenerateVertexData = function () {
  36858. return BABYLON.VertexData.CreateTiledGround({ xmin: this.xmin, zmin: this.zmin, xmax: this.xmax, zmax: this.zmax, subdivisions: this.subdivisions, precision: this.precision });
  36859. };
  36860. TiledGroundGeometry.prototype.copy = function (id) {
  36861. return new TiledGroundGeometry(id, this.getScene(), this.xmin, this.zmin, this.xmax, this.zmax, this.subdivisions, this.precision, this.canBeRegenerated(), null);
  36862. };
  36863. return TiledGroundGeometry;
  36864. }(_PrimitiveGeometry));
  36865. BABYLON.TiledGroundGeometry = TiledGroundGeometry;
  36866. /**
  36867. * Creates a plane geometry
  36868. * @description see http://doc.babylonjs.com/how_to/set_shapes#plane
  36869. */
  36870. var PlaneGeometry = /** @class */ (function (_super) {
  36871. __extends(PlaneGeometry, _super);
  36872. /**
  36873. * Creates a plane geometry
  36874. * @param id defines the unique ID of the geometry
  36875. * @param scene defines the hosting scene
  36876. * @param size defines the size of the plane (width === height)
  36877. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  36878. * @param mesh defines the hosting mesh (can be null)
  36879. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  36880. */
  36881. function PlaneGeometry(id, scene,
  36882. /**
  36883. * Defines the size of the plane (width === height)
  36884. */
  36885. size, canBeRegenerated, mesh,
  36886. /**
  36887. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  36888. */
  36889. side) {
  36890. if (mesh === void 0) { mesh = null; }
  36891. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  36892. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  36893. _this.size = size;
  36894. _this.side = side;
  36895. return _this;
  36896. }
  36897. PlaneGeometry.prototype._regenerateVertexData = function () {
  36898. return BABYLON.VertexData.CreatePlane({ size: this.size, sideOrientation: this.side });
  36899. };
  36900. PlaneGeometry.prototype.copy = function (id) {
  36901. return new PlaneGeometry(id, this.getScene(), this.size, this.canBeRegenerated(), null, this.side);
  36902. };
  36903. PlaneGeometry.prototype.serialize = function () {
  36904. var serializationObject = _super.prototype.serialize.call(this);
  36905. serializationObject.size = this.size;
  36906. return serializationObject;
  36907. };
  36908. PlaneGeometry.Parse = function (parsedPlane, scene) {
  36909. if (scene.getGeometryByID(parsedPlane.id)) {
  36910. return null; // null since geometry could be something else than a ground...
  36911. }
  36912. var plane = new PlaneGeometry(parsedPlane.id, scene, parsedPlane.size, parsedPlane.canBeRegenerated, null);
  36913. if (BABYLON.Tags) {
  36914. BABYLON.Tags.AddTagsTo(plane, parsedPlane.tags);
  36915. }
  36916. scene.pushGeometry(plane, true);
  36917. return plane;
  36918. };
  36919. return PlaneGeometry;
  36920. }(_PrimitiveGeometry));
  36921. BABYLON.PlaneGeometry = PlaneGeometry;
  36922. /**
  36923. * Creates a torus knot geometry
  36924. * @description see http://doc.babylonjs.com/how_to/set_shapes#torus-knot
  36925. */
  36926. var TorusKnotGeometry = /** @class */ (function (_super) {
  36927. __extends(TorusKnotGeometry, _super);
  36928. /**
  36929. * Creates a torus knot geometry
  36930. * @param id defines the unique ID of the geometry
  36931. * @param scene defines the hosting scene
  36932. * @param radius defines the radius of the torus knot
  36933. * @param tube defines the thickness of the torus knot tube
  36934. * @param radialSegments defines the number of radial segments
  36935. * @param tubularSegments defines the number of tubular segments
  36936. * @param p defines the first number of windings
  36937. * @param q defines the second number of windings
  36938. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  36939. * @param mesh defines the hosting mesh (can be null)
  36940. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  36941. */
  36942. function TorusKnotGeometry(id, scene,
  36943. /**
  36944. * Defines the radius of the torus knot
  36945. */
  36946. radius,
  36947. /**
  36948. * Defines the thickness of the torus knot tube
  36949. */
  36950. tube,
  36951. /**
  36952. * Defines the number of radial segments
  36953. */
  36954. radialSegments,
  36955. /**
  36956. * Defines the number of tubular segments
  36957. */
  36958. tubularSegments,
  36959. /**
  36960. * Defines the first number of windings
  36961. */
  36962. p,
  36963. /**
  36964. * Defines the second number of windings
  36965. */
  36966. q, canBeRegenerated, mesh,
  36967. /**
  36968. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  36969. */
  36970. side) {
  36971. if (mesh === void 0) { mesh = null; }
  36972. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  36973. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  36974. _this.radius = radius;
  36975. _this.tube = tube;
  36976. _this.radialSegments = radialSegments;
  36977. _this.tubularSegments = tubularSegments;
  36978. _this.p = p;
  36979. _this.q = q;
  36980. _this.side = side;
  36981. return _this;
  36982. }
  36983. TorusKnotGeometry.prototype._regenerateVertexData = function () {
  36984. 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 });
  36985. };
  36986. TorusKnotGeometry.prototype.copy = function (id) {
  36987. return new TorusKnotGeometry(id, this.getScene(), this.radius, this.tube, this.radialSegments, this.tubularSegments, this.p, this.q, this.canBeRegenerated(), null, this.side);
  36988. };
  36989. TorusKnotGeometry.prototype.serialize = function () {
  36990. var serializationObject = _super.prototype.serialize.call(this);
  36991. serializationObject.radius = this.radius;
  36992. serializationObject.tube = this.tube;
  36993. serializationObject.radialSegments = this.radialSegments;
  36994. serializationObject.tubularSegments = this.tubularSegments;
  36995. serializationObject.p = this.p;
  36996. serializationObject.q = this.q;
  36997. return serializationObject;
  36998. };
  36999. ;
  37000. TorusKnotGeometry.Parse = function (parsedTorusKnot, scene) {
  37001. if (scene.getGeometryByID(parsedTorusKnot.id)) {
  37002. return null; // null since geometry could be something else than a ground...
  37003. }
  37004. var torusKnot = new TorusKnotGeometry(parsedTorusKnot.id, scene, parsedTorusKnot.radius, parsedTorusKnot.tube, parsedTorusKnot.radialSegments, parsedTorusKnot.tubularSegments, parsedTorusKnot.p, parsedTorusKnot.q, parsedTorusKnot.canBeRegenerated, null);
  37005. if (BABYLON.Tags) {
  37006. BABYLON.Tags.AddTagsTo(torusKnot, parsedTorusKnot.tags);
  37007. }
  37008. scene.pushGeometry(torusKnot, true);
  37009. return torusKnot;
  37010. };
  37011. return TorusKnotGeometry;
  37012. }(_PrimitiveGeometry));
  37013. BABYLON.TorusKnotGeometry = TorusKnotGeometry;
  37014. //}
  37015. })(BABYLON || (BABYLON = {}));
  37016. //# sourceMappingURL=babylon.geometry.js.map
  37017. "use strict";
  37018. var BABYLON;
  37019. (function (BABYLON) {
  37020. /**
  37021. * PostProcessManager is used to manage one or more post processes or post process pipelines
  37022. * See https://doc.babylonjs.com/how_to/how_to_use_postprocesses
  37023. */
  37024. var PostProcessManager = /** @class */ (function () {
  37025. /**
  37026. * Creates a new instance PostProcess
  37027. * @param scene The scene that the post process is associated with.
  37028. */
  37029. function PostProcessManager(scene) {
  37030. this._vertexBuffers = {};
  37031. this._scene = scene;
  37032. }
  37033. PostProcessManager.prototype._prepareBuffers = function () {
  37034. if (this._vertexBuffers[BABYLON.VertexBuffer.PositionKind]) {
  37035. return;
  37036. }
  37037. // VBO
  37038. var vertices = [];
  37039. vertices.push(1, 1);
  37040. vertices.push(-1, 1);
  37041. vertices.push(-1, -1);
  37042. vertices.push(1, -1);
  37043. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(this._scene.getEngine(), vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  37044. this._buildIndexBuffer();
  37045. };
  37046. PostProcessManager.prototype._buildIndexBuffer = function () {
  37047. // Indices
  37048. var indices = [];
  37049. indices.push(0);
  37050. indices.push(1);
  37051. indices.push(2);
  37052. indices.push(0);
  37053. indices.push(2);
  37054. indices.push(3);
  37055. this._indexBuffer = this._scene.getEngine().createIndexBuffer(indices);
  37056. };
  37057. /**
  37058. * Rebuilds the vertex buffers of the manager.
  37059. */
  37060. PostProcessManager.prototype._rebuild = function () {
  37061. var vb = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  37062. if (!vb) {
  37063. return;
  37064. }
  37065. vb._rebuild();
  37066. this._buildIndexBuffer();
  37067. };
  37068. // Methods
  37069. /**
  37070. * Prepares a frame to be run through a post process.
  37071. * @param sourceTexture The input texture to the post procesess. (default: null)
  37072. * @param postProcesses An array of post processes to be run. (default: null)
  37073. * @returns True if the post processes were able to be run.
  37074. */
  37075. PostProcessManager.prototype._prepareFrame = function (sourceTexture, postProcesses) {
  37076. if (sourceTexture === void 0) { sourceTexture = null; }
  37077. if (postProcesses === void 0) { postProcesses = null; }
  37078. var camera = this._scene.activeCamera;
  37079. if (!camera) {
  37080. return false;
  37081. }
  37082. var postProcesses = postProcesses || camera._postProcesses.filter(function (pp) { return pp != null; });
  37083. if (!postProcesses || postProcesses.length === 0 || !this._scene.postProcessesEnabled) {
  37084. return false;
  37085. }
  37086. postProcesses[0].activate(camera, sourceTexture, postProcesses !== null && postProcesses !== undefined);
  37087. return true;
  37088. };
  37089. /**
  37090. * Manually render a set of post processes to a texture.
  37091. * @param postProcesses An array of post processes to be run.
  37092. * @param targetTexture The target texture to render to.
  37093. * @param forceFullscreenViewport force gl.viewport to be full screen eg. 0,0,textureWidth,textureHeight
  37094. */
  37095. PostProcessManager.prototype.directRender = function (postProcesses, targetTexture, forceFullscreenViewport) {
  37096. if (targetTexture === void 0) { targetTexture = null; }
  37097. if (forceFullscreenViewport === void 0) { forceFullscreenViewport = false; }
  37098. var engine = this._scene.getEngine();
  37099. for (var index = 0; index < postProcesses.length; index++) {
  37100. if (index < postProcesses.length - 1) {
  37101. postProcesses[index + 1].activate(this._scene.activeCamera, targetTexture);
  37102. }
  37103. else {
  37104. if (targetTexture) {
  37105. engine.bindFramebuffer(targetTexture, 0, undefined, undefined, forceFullscreenViewport);
  37106. }
  37107. else {
  37108. engine.restoreDefaultFramebuffer();
  37109. }
  37110. }
  37111. var pp = postProcesses[index];
  37112. var effect = pp.apply();
  37113. if (effect) {
  37114. pp.onBeforeRenderObservable.notifyObservers(effect);
  37115. // VBOs
  37116. this._prepareBuffers();
  37117. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  37118. // Draw order
  37119. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  37120. pp.onAfterRenderObservable.notifyObservers(effect);
  37121. }
  37122. }
  37123. // Restore depth buffer
  37124. engine.setDepthBuffer(true);
  37125. engine.setDepthWrite(true);
  37126. };
  37127. /**
  37128. * Finalize the result of the output of the postprocesses.
  37129. * @param doNotPresent If true the result will not be displayed to the screen.
  37130. * @param targetTexture The target texture to render to.
  37131. * @param faceIndex The index of the face to bind the target texture to.
  37132. * @param postProcesses The array of post processes to render.
  37133. * @param forceFullscreenViewport force gl.viewport to be full screen eg. 0,0,textureWidth,textureHeight (default: false)
  37134. */
  37135. PostProcessManager.prototype._finalizeFrame = function (doNotPresent, targetTexture, faceIndex, postProcesses, forceFullscreenViewport) {
  37136. if (forceFullscreenViewport === void 0) { forceFullscreenViewport = false; }
  37137. var camera = this._scene.activeCamera;
  37138. if (!camera) {
  37139. return;
  37140. }
  37141. postProcesses = postProcesses || camera._postProcesses.filter(function (pp) { return pp != null; });
  37142. if (postProcesses.length === 0 || !this._scene.postProcessesEnabled) {
  37143. return;
  37144. }
  37145. var engine = this._scene.getEngine();
  37146. for (var index = 0, len = postProcesses.length; index < len; index++) {
  37147. var pp = postProcesses[index];
  37148. if (index < len - 1) {
  37149. pp._outputTexture = postProcesses[index + 1].activate(camera, targetTexture);
  37150. }
  37151. else {
  37152. if (targetTexture) {
  37153. engine.bindFramebuffer(targetTexture, faceIndex, undefined, undefined, forceFullscreenViewport);
  37154. }
  37155. else {
  37156. engine.restoreDefaultFramebuffer();
  37157. }
  37158. }
  37159. if (doNotPresent) {
  37160. break;
  37161. }
  37162. var effect = pp.apply();
  37163. if (effect) {
  37164. pp.onBeforeRenderObservable.notifyObservers(effect);
  37165. // VBOs
  37166. this._prepareBuffers();
  37167. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  37168. // Draw order
  37169. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  37170. pp.onAfterRenderObservable.notifyObservers(effect);
  37171. }
  37172. }
  37173. // Restore states
  37174. engine.setDepthBuffer(true);
  37175. engine.setDepthWrite(true);
  37176. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  37177. };
  37178. /**
  37179. * Disposes of the post process manager.
  37180. */
  37181. PostProcessManager.prototype.dispose = function () {
  37182. var buffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  37183. if (buffer) {
  37184. buffer.dispose();
  37185. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  37186. }
  37187. if (this._indexBuffer) {
  37188. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  37189. this._indexBuffer = null;
  37190. }
  37191. };
  37192. return PostProcessManager;
  37193. }());
  37194. BABYLON.PostProcessManager = PostProcessManager;
  37195. })(BABYLON || (BABYLON = {}));
  37196. //# sourceMappingURL=babylon.postProcessManager.js.map
  37197. "use strict";
  37198. var BABYLON;
  37199. (function (BABYLON) {
  37200. /**
  37201. * Performance monitor tracks rolling average frame-time and frame-time variance over a user defined sliding-window
  37202. */
  37203. var PerformanceMonitor = /** @class */ (function () {
  37204. /**
  37205. * constructor
  37206. * @param frameSampleSize The number of samples required to saturate the sliding window
  37207. */
  37208. function PerformanceMonitor(frameSampleSize) {
  37209. if (frameSampleSize === void 0) { frameSampleSize = 30; }
  37210. this._enabled = true;
  37211. this._rollingFrameTime = new RollingAverage(frameSampleSize);
  37212. }
  37213. /**
  37214. * Samples current frame
  37215. * @param timeMs A timestamp in milliseconds of the current frame to compare with other frames
  37216. */
  37217. PerformanceMonitor.prototype.sampleFrame = function (timeMs) {
  37218. if (timeMs === void 0) { timeMs = BABYLON.Tools.Now; }
  37219. if (!this._enabled)
  37220. return;
  37221. if (this._lastFrameTimeMs != null) {
  37222. var dt = timeMs - this._lastFrameTimeMs;
  37223. this._rollingFrameTime.add(dt);
  37224. }
  37225. this._lastFrameTimeMs = timeMs;
  37226. };
  37227. Object.defineProperty(PerformanceMonitor.prototype, "averageFrameTime", {
  37228. /**
  37229. * Returns the average frame time in milliseconds over the sliding window (or the subset of frames sampled so far)
  37230. * @return Average frame time in milliseconds
  37231. */
  37232. get: function () {
  37233. return this._rollingFrameTime.average;
  37234. },
  37235. enumerable: true,
  37236. configurable: true
  37237. });
  37238. Object.defineProperty(PerformanceMonitor.prototype, "averageFrameTimeVariance", {
  37239. /**
  37240. * Returns the variance frame time in milliseconds over the sliding window (or the subset of frames sampled so far)
  37241. * @return Frame time variance in milliseconds squared
  37242. */
  37243. get: function () {
  37244. return this._rollingFrameTime.variance;
  37245. },
  37246. enumerable: true,
  37247. configurable: true
  37248. });
  37249. Object.defineProperty(PerformanceMonitor.prototype, "instantaneousFrameTime", {
  37250. /**
  37251. * Returns the frame time of the most recent frame
  37252. * @return Frame time in milliseconds
  37253. */
  37254. get: function () {
  37255. return this._rollingFrameTime.history(0);
  37256. },
  37257. enumerable: true,
  37258. configurable: true
  37259. });
  37260. Object.defineProperty(PerformanceMonitor.prototype, "averageFPS", {
  37261. /**
  37262. * Returns the average framerate in frames per second over the sliding window (or the subset of frames sampled so far)
  37263. * @return Framerate in frames per second
  37264. */
  37265. get: function () {
  37266. return 1000.0 / this._rollingFrameTime.average;
  37267. },
  37268. enumerable: true,
  37269. configurable: true
  37270. });
  37271. Object.defineProperty(PerformanceMonitor.prototype, "instantaneousFPS", {
  37272. /**
  37273. * Returns the average framerate in frames per second using the most recent frame time
  37274. * @return Framerate in frames per second
  37275. */
  37276. get: function () {
  37277. var history = this._rollingFrameTime.history(0);
  37278. if (history === 0) {
  37279. return 0;
  37280. }
  37281. return 1000.0 / history;
  37282. },
  37283. enumerable: true,
  37284. configurable: true
  37285. });
  37286. Object.defineProperty(PerformanceMonitor.prototype, "isSaturated", {
  37287. /**
  37288. * Returns true if enough samples have been taken to completely fill the sliding window
  37289. * @return true if saturated
  37290. */
  37291. get: function () {
  37292. return this._rollingFrameTime.isSaturated();
  37293. },
  37294. enumerable: true,
  37295. configurable: true
  37296. });
  37297. /**
  37298. * Enables contributions to the sliding window sample set
  37299. */
  37300. PerformanceMonitor.prototype.enable = function () {
  37301. this._enabled = true;
  37302. };
  37303. /**
  37304. * Disables contributions to the sliding window sample set
  37305. * Samples will not be interpolated over the disabled period
  37306. */
  37307. PerformanceMonitor.prototype.disable = function () {
  37308. this._enabled = false;
  37309. //clear last sample to avoid interpolating over the disabled period when next enabled
  37310. this._lastFrameTimeMs = null;
  37311. };
  37312. Object.defineProperty(PerformanceMonitor.prototype, "isEnabled", {
  37313. /**
  37314. * Returns true if sampling is enabled
  37315. * @return true if enabled
  37316. */
  37317. get: function () {
  37318. return this._enabled;
  37319. },
  37320. enumerable: true,
  37321. configurable: true
  37322. });
  37323. /**
  37324. * Resets performance monitor
  37325. */
  37326. PerformanceMonitor.prototype.reset = function () {
  37327. //clear last sample to avoid interpolating over the disabled period when next enabled
  37328. this._lastFrameTimeMs = null;
  37329. //wipe record
  37330. this._rollingFrameTime.reset();
  37331. };
  37332. return PerformanceMonitor;
  37333. }());
  37334. BABYLON.PerformanceMonitor = PerformanceMonitor;
  37335. /**
  37336. * RollingAverage
  37337. *
  37338. * Utility to efficiently compute the rolling average and variance over a sliding window of samples
  37339. */
  37340. var RollingAverage = /** @class */ (function () {
  37341. /**
  37342. * constructor
  37343. * @param length The number of samples required to saturate the sliding window
  37344. */
  37345. function RollingAverage(length) {
  37346. this._samples = new Array(length);
  37347. this.reset();
  37348. }
  37349. /**
  37350. * Adds a sample to the sample set
  37351. * @param v The sample value
  37352. */
  37353. RollingAverage.prototype.add = function (v) {
  37354. //http://en.wikipedia.org/wiki/Algorithms_for_calculating_variance
  37355. var delta;
  37356. //we need to check if we've already wrapped round
  37357. if (this.isSaturated()) {
  37358. //remove bottom of stack from mean
  37359. var bottomValue = this._samples[this._pos];
  37360. delta = bottomValue - this.average;
  37361. this.average -= delta / (this._sampleCount - 1);
  37362. this._m2 -= delta * (bottomValue - this.average);
  37363. }
  37364. else {
  37365. this._sampleCount++;
  37366. }
  37367. //add new value to mean
  37368. delta = v - this.average;
  37369. this.average += delta / (this._sampleCount);
  37370. this._m2 += delta * (v - this.average);
  37371. //set the new variance
  37372. this.variance = this._m2 / (this._sampleCount - 1);
  37373. this._samples[this._pos] = v;
  37374. this._pos++;
  37375. this._pos %= this._samples.length; //positive wrap around
  37376. };
  37377. /**
  37378. * Returns previously added values or null if outside of history or outside the sliding window domain
  37379. * @param i Index in history. For example, pass 0 for the most recent value and 1 for the value before that
  37380. * @return Value previously recorded with add() or null if outside of range
  37381. */
  37382. RollingAverage.prototype.history = function (i) {
  37383. if ((i >= this._sampleCount) || (i >= this._samples.length)) {
  37384. return 0;
  37385. }
  37386. var i0 = this._wrapPosition(this._pos - 1.0);
  37387. return this._samples[this._wrapPosition(i0 - i)];
  37388. };
  37389. /**
  37390. * Returns true if enough samples have been taken to completely fill the sliding window
  37391. * @return true if sample-set saturated
  37392. */
  37393. RollingAverage.prototype.isSaturated = function () {
  37394. return this._sampleCount >= this._samples.length;
  37395. };
  37396. /**
  37397. * Resets the rolling average (equivalent to 0 samples taken so far)
  37398. */
  37399. RollingAverage.prototype.reset = function () {
  37400. this.average = 0;
  37401. this.variance = 0;
  37402. this._sampleCount = 0;
  37403. this._pos = 0;
  37404. this._m2 = 0;
  37405. };
  37406. /**
  37407. * Wraps a value around the sample range boundaries
  37408. * @param i Position in sample range, for example if the sample length is 5, and i is -3, then 2 will be returned.
  37409. * @return Wrapped position in sample range
  37410. */
  37411. RollingAverage.prototype._wrapPosition = function (i) {
  37412. var max = this._samples.length;
  37413. return ((i % max) + max) % max;
  37414. };
  37415. return RollingAverage;
  37416. }());
  37417. BABYLON.RollingAverage = RollingAverage;
  37418. })(BABYLON || (BABYLON = {}));
  37419. //# sourceMappingURL=babylon.performanceMonitor.js.map
  37420. "use strict";
  37421. var BABYLON;
  37422. (function (BABYLON) {
  37423. /**
  37424. * This groups together the common properties used for image processing either in direct forward pass
  37425. * or through post processing effect depending on the use of the image processing pipeline in your scene
  37426. * or not.
  37427. */
  37428. var ImageProcessingConfiguration = /** @class */ (function () {
  37429. function ImageProcessingConfiguration() {
  37430. /**
  37431. * Color curves setup used in the effect if colorCurvesEnabled is set to true
  37432. */
  37433. this.colorCurves = new BABYLON.ColorCurves();
  37434. this._colorCurvesEnabled = false;
  37435. this._colorGradingEnabled = false;
  37436. this._colorGradingWithGreenDepth = true;
  37437. this._colorGradingBGR = true;
  37438. this._exposure = 1.0;
  37439. this._toneMappingEnabled = false;
  37440. this._contrast = 1.0;
  37441. /**
  37442. * Vignette stretch size.
  37443. */
  37444. this.vignetteStretch = 0;
  37445. /**
  37446. * Vignette centre X Offset.
  37447. */
  37448. this.vignetteCentreX = 0;
  37449. /**
  37450. * Vignette centre Y Offset.
  37451. */
  37452. this.vignetteCentreY = 0;
  37453. /**
  37454. * Vignette weight or intensity of the vignette effect.
  37455. */
  37456. this.vignetteWeight = 1.5;
  37457. /**
  37458. * Color of the vignette applied on the screen through the chosen blend mode (vignetteBlendMode)
  37459. * if vignetteEnabled is set to true.
  37460. */
  37461. this.vignetteColor = new BABYLON.Color4(0, 0, 0, 0);
  37462. /**
  37463. * Camera field of view used by the Vignette effect.
  37464. */
  37465. this.vignetteCameraFov = 0.5;
  37466. this._vignetteBlendMode = ImageProcessingConfiguration.VIGNETTEMODE_MULTIPLY;
  37467. this._vignetteEnabled = false;
  37468. this._applyByPostProcess = false;
  37469. this._isEnabled = true;
  37470. /**
  37471. * An event triggered when the configuration changes and requires Shader to Update some parameters.
  37472. */
  37473. this.onUpdateParameters = new BABYLON.Observable();
  37474. }
  37475. Object.defineProperty(ImageProcessingConfiguration.prototype, "colorCurvesEnabled", {
  37476. /**
  37477. * Gets wether the color curves effect is enabled.
  37478. */
  37479. get: function () {
  37480. return this._colorCurvesEnabled;
  37481. },
  37482. /**
  37483. * Sets wether the color curves effect is enabled.
  37484. */
  37485. set: function (value) {
  37486. if (this._colorCurvesEnabled === value) {
  37487. return;
  37488. }
  37489. this._colorCurvesEnabled = value;
  37490. this._updateParameters();
  37491. },
  37492. enumerable: true,
  37493. configurable: true
  37494. });
  37495. Object.defineProperty(ImageProcessingConfiguration.prototype, "colorGradingEnabled", {
  37496. /**
  37497. * Gets wether the color grading effect is enabled.
  37498. */
  37499. get: function () {
  37500. return this._colorGradingEnabled;
  37501. },
  37502. /**
  37503. * Sets wether the color grading effect is enabled.
  37504. */
  37505. set: function (value) {
  37506. if (this._colorGradingEnabled === value) {
  37507. return;
  37508. }
  37509. this._colorGradingEnabled = value;
  37510. this._updateParameters();
  37511. },
  37512. enumerable: true,
  37513. configurable: true
  37514. });
  37515. Object.defineProperty(ImageProcessingConfiguration.prototype, "colorGradingWithGreenDepth", {
  37516. /**
  37517. * Gets wether the color grading effect is using a green depth for the 3d Texture.
  37518. */
  37519. get: function () {
  37520. return this._colorGradingWithGreenDepth;
  37521. },
  37522. /**
  37523. * Sets wether the color grading effect is using a green depth for the 3d Texture.
  37524. */
  37525. set: function (value) {
  37526. if (this._colorGradingWithGreenDepth === value) {
  37527. return;
  37528. }
  37529. this._colorGradingWithGreenDepth = value;
  37530. this._updateParameters();
  37531. },
  37532. enumerable: true,
  37533. configurable: true
  37534. });
  37535. Object.defineProperty(ImageProcessingConfiguration.prototype, "colorGradingBGR", {
  37536. /**
  37537. * Gets wether the color grading texture contains BGR values.
  37538. */
  37539. get: function () {
  37540. return this._colorGradingBGR;
  37541. },
  37542. /**
  37543. * Sets wether the color grading texture contains BGR values.
  37544. */
  37545. set: function (value) {
  37546. if (this._colorGradingBGR === value) {
  37547. return;
  37548. }
  37549. this._colorGradingBGR = value;
  37550. this._updateParameters();
  37551. },
  37552. enumerable: true,
  37553. configurable: true
  37554. });
  37555. Object.defineProperty(ImageProcessingConfiguration.prototype, "exposure", {
  37556. /**
  37557. * Gets the Exposure used in the effect.
  37558. */
  37559. get: function () {
  37560. return this._exposure;
  37561. },
  37562. /**
  37563. * Sets the Exposure used in the effect.
  37564. */
  37565. set: function (value) {
  37566. if (this._exposure === value) {
  37567. return;
  37568. }
  37569. this._exposure = value;
  37570. this._updateParameters();
  37571. },
  37572. enumerable: true,
  37573. configurable: true
  37574. });
  37575. Object.defineProperty(ImageProcessingConfiguration.prototype, "toneMappingEnabled", {
  37576. /**
  37577. * Gets wether the tone mapping effect is enabled.
  37578. */
  37579. get: function () {
  37580. return this._toneMappingEnabled;
  37581. },
  37582. /**
  37583. * Sets wether the tone mapping effect is enabled.
  37584. */
  37585. set: function (value) {
  37586. if (this._toneMappingEnabled === value) {
  37587. return;
  37588. }
  37589. this._toneMappingEnabled = value;
  37590. this._updateParameters();
  37591. },
  37592. enumerable: true,
  37593. configurable: true
  37594. });
  37595. Object.defineProperty(ImageProcessingConfiguration.prototype, "contrast", {
  37596. /**
  37597. * Gets the contrast used in the effect.
  37598. */
  37599. get: function () {
  37600. return this._contrast;
  37601. },
  37602. /**
  37603. * Sets the contrast used in the effect.
  37604. */
  37605. set: function (value) {
  37606. if (this._contrast === value) {
  37607. return;
  37608. }
  37609. this._contrast = value;
  37610. this._updateParameters();
  37611. },
  37612. enumerable: true,
  37613. configurable: true
  37614. });
  37615. Object.defineProperty(ImageProcessingConfiguration.prototype, "vignetteBlendMode", {
  37616. /**
  37617. * Gets the vignette blend mode allowing different kind of effect.
  37618. */
  37619. get: function () {
  37620. return this._vignetteBlendMode;
  37621. },
  37622. /**
  37623. * Sets the vignette blend mode allowing different kind of effect.
  37624. */
  37625. set: function (value) {
  37626. if (this._vignetteBlendMode === value) {
  37627. return;
  37628. }
  37629. this._vignetteBlendMode = value;
  37630. this._updateParameters();
  37631. },
  37632. enumerable: true,
  37633. configurable: true
  37634. });
  37635. Object.defineProperty(ImageProcessingConfiguration.prototype, "vignetteEnabled", {
  37636. /**
  37637. * Gets wether the vignette effect is enabled.
  37638. */
  37639. get: function () {
  37640. return this._vignetteEnabled;
  37641. },
  37642. /**
  37643. * Sets wether the vignette effect is enabled.
  37644. */
  37645. set: function (value) {
  37646. if (this._vignetteEnabled === value) {
  37647. return;
  37648. }
  37649. this._vignetteEnabled = value;
  37650. this._updateParameters();
  37651. },
  37652. enumerable: true,
  37653. configurable: true
  37654. });
  37655. Object.defineProperty(ImageProcessingConfiguration.prototype, "applyByPostProcess", {
  37656. /**
  37657. * Gets wether the image processing is applied through a post process or not.
  37658. */
  37659. get: function () {
  37660. return this._applyByPostProcess;
  37661. },
  37662. /**
  37663. * Sets wether the image processing is applied through a post process or not.
  37664. */
  37665. set: function (value) {
  37666. if (this._applyByPostProcess === value) {
  37667. return;
  37668. }
  37669. this._applyByPostProcess = value;
  37670. this._updateParameters();
  37671. },
  37672. enumerable: true,
  37673. configurable: true
  37674. });
  37675. Object.defineProperty(ImageProcessingConfiguration.prototype, "isEnabled", {
  37676. /**
  37677. * Gets wether the image processing is enabled or not.
  37678. */
  37679. get: function () {
  37680. return this._isEnabled;
  37681. },
  37682. /**
  37683. * Sets wether the image processing is enabled or not.
  37684. */
  37685. set: function (value) {
  37686. if (this._isEnabled === value) {
  37687. return;
  37688. }
  37689. this._isEnabled = value;
  37690. this._updateParameters();
  37691. },
  37692. enumerable: true,
  37693. configurable: true
  37694. });
  37695. /**
  37696. * Method called each time the image processing information changes requires to recompile the effect.
  37697. */
  37698. ImageProcessingConfiguration.prototype._updateParameters = function () {
  37699. this.onUpdateParameters.notifyObservers(this);
  37700. };
  37701. ImageProcessingConfiguration.prototype.getClassName = function () {
  37702. return "ImageProcessingConfiguration";
  37703. };
  37704. /**
  37705. * Prepare the list of uniforms associated with the Image Processing effects.
  37706. * @param uniformsList The list of uniforms used in the effect
  37707. * @param defines the list of defines currently in use
  37708. */
  37709. ImageProcessingConfiguration.PrepareUniforms = function (uniforms, defines) {
  37710. if (defines.EXPOSURE) {
  37711. uniforms.push("exposureLinear");
  37712. }
  37713. if (defines.CONTRAST) {
  37714. uniforms.push("contrast");
  37715. }
  37716. if (defines.COLORGRADING) {
  37717. uniforms.push("colorTransformSettings");
  37718. }
  37719. if (defines.VIGNETTE) {
  37720. uniforms.push("vInverseScreenSize");
  37721. uniforms.push("vignetteSettings1");
  37722. uniforms.push("vignetteSettings2");
  37723. }
  37724. if (defines.COLORCURVES) {
  37725. BABYLON.ColorCurves.PrepareUniforms(uniforms);
  37726. }
  37727. };
  37728. /**
  37729. * Prepare the list of samplers associated with the Image Processing effects.
  37730. * @param uniformsList The list of uniforms used in the effect
  37731. * @param defines the list of defines currently in use
  37732. */
  37733. ImageProcessingConfiguration.PrepareSamplers = function (samplersList, defines) {
  37734. if (defines.COLORGRADING) {
  37735. samplersList.push("txColorTransform");
  37736. }
  37737. };
  37738. /**
  37739. * Prepare the list of defines associated to the shader.
  37740. * @param defines the list of defines to complete
  37741. */
  37742. ImageProcessingConfiguration.prototype.prepareDefines = function (defines, forPostProcess) {
  37743. if (forPostProcess === void 0) { forPostProcess = false; }
  37744. if (forPostProcess !== this.applyByPostProcess || !this._isEnabled) {
  37745. defines.VIGNETTE = false;
  37746. defines.TONEMAPPING = false;
  37747. defines.CONTRAST = false;
  37748. defines.EXPOSURE = false;
  37749. defines.COLORCURVES = false;
  37750. defines.COLORGRADING = false;
  37751. defines.COLORGRADING3D = false;
  37752. defines.IMAGEPROCESSING = false;
  37753. defines.IMAGEPROCESSINGPOSTPROCESS = this.applyByPostProcess && this._isEnabled;
  37754. return;
  37755. }
  37756. defines.VIGNETTE = this.vignetteEnabled;
  37757. defines.VIGNETTEBLENDMODEMULTIPLY = (this.vignetteBlendMode === ImageProcessingConfiguration._VIGNETTEMODE_MULTIPLY);
  37758. defines.VIGNETTEBLENDMODEOPAQUE = !defines.VIGNETTEBLENDMODEMULTIPLY;
  37759. defines.TONEMAPPING = this.toneMappingEnabled;
  37760. defines.CONTRAST = (this.contrast !== 1.0);
  37761. defines.EXPOSURE = (this.exposure !== 1.0);
  37762. defines.COLORCURVES = (this.colorCurvesEnabled && !!this.colorCurves);
  37763. defines.COLORGRADING = (this.colorGradingEnabled && !!this.colorGradingTexture);
  37764. if (defines.COLORGRADING) {
  37765. defines.COLORGRADING3D = this.colorGradingTexture.is3D;
  37766. }
  37767. else {
  37768. defines.COLORGRADING3D = false;
  37769. }
  37770. defines.SAMPLER3DGREENDEPTH = this.colorGradingWithGreenDepth;
  37771. defines.SAMPLER3DBGRMAP = this.colorGradingBGR;
  37772. defines.IMAGEPROCESSINGPOSTPROCESS = this.applyByPostProcess;
  37773. defines.IMAGEPROCESSING = defines.VIGNETTE || defines.TONEMAPPING || defines.CONTRAST || defines.EXPOSURE || defines.COLORCURVES || defines.COLORGRADING;
  37774. };
  37775. /**
  37776. * Returns true if all the image processing information are ready.
  37777. */
  37778. ImageProcessingConfiguration.prototype.isReady = function () {
  37779. // Color Grading texure can not be none blocking.
  37780. return !this.colorGradingEnabled || !this.colorGradingTexture || this.colorGradingTexture.isReady();
  37781. };
  37782. /**
  37783. * Binds the image processing to the shader.
  37784. * @param effect The effect to bind to
  37785. */
  37786. ImageProcessingConfiguration.prototype.bind = function (effect, aspectRatio) {
  37787. if (aspectRatio === void 0) { aspectRatio = 1; }
  37788. // Color Curves
  37789. if (this._colorCurvesEnabled && this.colorCurves) {
  37790. BABYLON.ColorCurves.Bind(this.colorCurves, effect);
  37791. }
  37792. // Vignette
  37793. if (this._vignetteEnabled) {
  37794. var inverseWidth = 1 / effect.getEngine().getRenderWidth();
  37795. var inverseHeight = 1 / effect.getEngine().getRenderHeight();
  37796. effect.setFloat2("vInverseScreenSize", inverseWidth, inverseHeight);
  37797. var vignetteScaleY = Math.tan(this.vignetteCameraFov * 0.5);
  37798. var vignetteScaleX = vignetteScaleY * aspectRatio;
  37799. var vignetteScaleGeometricMean = Math.sqrt(vignetteScaleX * vignetteScaleY);
  37800. vignetteScaleX = BABYLON.Tools.Mix(vignetteScaleX, vignetteScaleGeometricMean, this.vignetteStretch);
  37801. vignetteScaleY = BABYLON.Tools.Mix(vignetteScaleY, vignetteScaleGeometricMean, this.vignetteStretch);
  37802. effect.setFloat4("vignetteSettings1", vignetteScaleX, vignetteScaleY, -vignetteScaleX * this.vignetteCentreX, -vignetteScaleY * this.vignetteCentreY);
  37803. var vignettePower = -2.0 * this.vignetteWeight;
  37804. effect.setFloat4("vignetteSettings2", this.vignetteColor.r, this.vignetteColor.g, this.vignetteColor.b, vignettePower);
  37805. }
  37806. // Exposure
  37807. effect.setFloat("exposureLinear", this.exposure);
  37808. // Contrast
  37809. effect.setFloat("contrast", this.contrast);
  37810. // Color transform settings
  37811. if (this.colorGradingTexture) {
  37812. effect.setTexture("txColorTransform", this.colorGradingTexture);
  37813. var textureSize = this.colorGradingTexture.getSize().height;
  37814. effect.setFloat4("colorTransformSettings", (textureSize - 1) / textureSize, // textureScale
  37815. 0.5 / textureSize, // textureOffset
  37816. textureSize, // textureSize
  37817. this.colorGradingTexture.level // weight
  37818. );
  37819. }
  37820. };
  37821. /**
  37822. * Clones the current image processing instance.
  37823. * @return The cloned image processing
  37824. */
  37825. ImageProcessingConfiguration.prototype.clone = function () {
  37826. return BABYLON.SerializationHelper.Clone(function () { return new ImageProcessingConfiguration(); }, this);
  37827. };
  37828. /**
  37829. * Serializes the current image processing instance to a json representation.
  37830. * @return a JSON representation
  37831. */
  37832. ImageProcessingConfiguration.prototype.serialize = function () {
  37833. return BABYLON.SerializationHelper.Serialize(this);
  37834. };
  37835. /**
  37836. * Parses the image processing from a json representation.
  37837. * @param source the JSON source to parse
  37838. * @return The parsed image processing
  37839. */
  37840. ImageProcessingConfiguration.Parse = function (source) {
  37841. return BABYLON.SerializationHelper.Parse(function () { return new ImageProcessingConfiguration(); }, source, null, null);
  37842. };
  37843. Object.defineProperty(ImageProcessingConfiguration, "VIGNETTEMODE_MULTIPLY", {
  37844. /**
  37845. * Used to apply the vignette as a mix with the pixel color.
  37846. */
  37847. get: function () {
  37848. return this._VIGNETTEMODE_MULTIPLY;
  37849. },
  37850. enumerable: true,
  37851. configurable: true
  37852. });
  37853. Object.defineProperty(ImageProcessingConfiguration, "VIGNETTEMODE_OPAQUE", {
  37854. /**
  37855. * Used to apply the vignette as a replacement of the pixel color.
  37856. */
  37857. get: function () {
  37858. return this._VIGNETTEMODE_OPAQUE;
  37859. },
  37860. enumerable: true,
  37861. configurable: true
  37862. });
  37863. // Static constants associated to the image processing.
  37864. ImageProcessingConfiguration._VIGNETTEMODE_MULTIPLY = 0;
  37865. ImageProcessingConfiguration._VIGNETTEMODE_OPAQUE = 1;
  37866. __decorate([
  37867. BABYLON.serializeAsColorCurves()
  37868. ], ImageProcessingConfiguration.prototype, "colorCurves", void 0);
  37869. __decorate([
  37870. BABYLON.serialize()
  37871. ], ImageProcessingConfiguration.prototype, "_colorCurvesEnabled", void 0);
  37872. __decorate([
  37873. BABYLON.serializeAsTexture()
  37874. ], ImageProcessingConfiguration.prototype, "colorGradingTexture", void 0);
  37875. __decorate([
  37876. BABYLON.serialize()
  37877. ], ImageProcessingConfiguration.prototype, "_colorGradingEnabled", void 0);
  37878. __decorate([
  37879. BABYLON.serialize()
  37880. ], ImageProcessingConfiguration.prototype, "_colorGradingWithGreenDepth", void 0);
  37881. __decorate([
  37882. BABYLON.serialize()
  37883. ], ImageProcessingConfiguration.prototype, "_colorGradingBGR", void 0);
  37884. __decorate([
  37885. BABYLON.serialize()
  37886. ], ImageProcessingConfiguration.prototype, "_exposure", void 0);
  37887. __decorate([
  37888. BABYLON.serialize()
  37889. ], ImageProcessingConfiguration.prototype, "_toneMappingEnabled", void 0);
  37890. __decorate([
  37891. BABYLON.serialize()
  37892. ], ImageProcessingConfiguration.prototype, "_contrast", void 0);
  37893. __decorate([
  37894. BABYLON.serialize()
  37895. ], ImageProcessingConfiguration.prototype, "vignetteStretch", void 0);
  37896. __decorate([
  37897. BABYLON.serialize()
  37898. ], ImageProcessingConfiguration.prototype, "vignetteCentreX", void 0);
  37899. __decorate([
  37900. BABYLON.serialize()
  37901. ], ImageProcessingConfiguration.prototype, "vignetteCentreY", void 0);
  37902. __decorate([
  37903. BABYLON.serialize()
  37904. ], ImageProcessingConfiguration.prototype, "vignetteWeight", void 0);
  37905. __decorate([
  37906. BABYLON.serializeAsColor4()
  37907. ], ImageProcessingConfiguration.prototype, "vignetteColor", void 0);
  37908. __decorate([
  37909. BABYLON.serialize()
  37910. ], ImageProcessingConfiguration.prototype, "vignetteCameraFov", void 0);
  37911. __decorate([
  37912. BABYLON.serialize()
  37913. ], ImageProcessingConfiguration.prototype, "_vignetteBlendMode", void 0);
  37914. __decorate([
  37915. BABYLON.serialize()
  37916. ], ImageProcessingConfiguration.prototype, "_vignetteEnabled", void 0);
  37917. __decorate([
  37918. BABYLON.serialize()
  37919. ], ImageProcessingConfiguration.prototype, "_applyByPostProcess", void 0);
  37920. __decorate([
  37921. BABYLON.serialize()
  37922. ], ImageProcessingConfiguration.prototype, "_isEnabled", void 0);
  37923. return ImageProcessingConfiguration;
  37924. }());
  37925. BABYLON.ImageProcessingConfiguration = ImageProcessingConfiguration;
  37926. })(BABYLON || (BABYLON = {}));
  37927. //# sourceMappingURL=babylon.imageProcessingConfiguration.js.map
  37928. "use strict";
  37929. var BABYLON;
  37930. (function (BABYLON) {
  37931. /**
  37932. * This represents a color grading texture. This acts as a lookup table LUT, useful during post process
  37933. * It can help converting any input color in a desired output one. This can then be used to create effects
  37934. * from sepia, black and white to sixties or futuristic rendering...
  37935. *
  37936. * The only supported format is currently 3dl.
  37937. * More information on LUT: https://en.wikipedia.org/wiki/3D_lookup_table/
  37938. */
  37939. var ColorGradingTexture = /** @class */ (function (_super) {
  37940. __extends(ColorGradingTexture, _super);
  37941. /**
  37942. * Instantiates a ColorGradingTexture from the following parameters.
  37943. *
  37944. * @param url The location of the color gradind data (currently only supporting 3dl)
  37945. * @param scene The scene the texture will be used in
  37946. */
  37947. function ColorGradingTexture(url, scene) {
  37948. var _this = _super.call(this, scene) || this;
  37949. if (!url) {
  37950. return _this;
  37951. }
  37952. _this._engine = scene.getEngine();
  37953. _this._textureMatrix = BABYLON.Matrix.Identity();
  37954. _this.name = url;
  37955. _this.url = url;
  37956. _this.hasAlpha = false;
  37957. _this.isCube = false;
  37958. _this.is3D = _this._engine.webGLVersion > 1;
  37959. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  37960. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  37961. _this.wrapR = BABYLON.Texture.CLAMP_ADDRESSMODE;
  37962. _this.anisotropicFilteringLevel = 1;
  37963. _this._texture = _this._getFromCache(url, true);
  37964. if (!_this._texture) {
  37965. if (!scene.useDelayedTextureLoading) {
  37966. _this.loadTexture();
  37967. }
  37968. else {
  37969. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  37970. }
  37971. }
  37972. return _this;
  37973. }
  37974. /**
  37975. * Returns the texture matrix used in most of the material.
  37976. * This is not used in color grading but keep for troubleshooting purpose (easily swap diffuse by colorgrading to look in).
  37977. */
  37978. ColorGradingTexture.prototype.getTextureMatrix = function () {
  37979. return this._textureMatrix;
  37980. };
  37981. /**
  37982. * Occurs when the file being loaded is a .3dl LUT file.
  37983. */
  37984. ColorGradingTexture.prototype.load3dlTexture = function () {
  37985. var engine = this._engine;
  37986. var texture;
  37987. if (engine.webGLVersion === 1) {
  37988. texture = engine.createRawTexture(null, 1, 1, BABYLON.Engine.TEXTUREFORMAT_RGBA, false, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  37989. }
  37990. else {
  37991. texture = engine.createRawTexture3D(null, 1, 1, 1, BABYLON.Engine.TEXTUREFORMAT_RGBA, false, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  37992. }
  37993. this._texture = texture;
  37994. var callback = function (text) {
  37995. if (typeof text !== "string") {
  37996. return;
  37997. }
  37998. var data = null;
  37999. var tempData = null;
  38000. var line;
  38001. var lines = text.split('\n');
  38002. var size = 0, pixelIndexW = 0, pixelIndexH = 0, pixelIndexSlice = 0;
  38003. var maxColor = 0;
  38004. for (var i = 0; i < lines.length; i++) {
  38005. line = lines[i];
  38006. if (!ColorGradingTexture._noneEmptyLineRegex.test(line))
  38007. continue;
  38008. if (line.indexOf('#') === 0)
  38009. continue;
  38010. var words = line.split(" ");
  38011. if (size === 0) {
  38012. // Number of space + one
  38013. size = words.length;
  38014. data = new Uint8Array(size * size * size * 4); // volume texture of side size and rgb 8
  38015. tempData = new Float32Array(size * size * size * 4);
  38016. continue;
  38017. }
  38018. if (size != 0) {
  38019. var r = Math.max(parseInt(words[0]), 0);
  38020. var g = Math.max(parseInt(words[1]), 0);
  38021. var b = Math.max(parseInt(words[2]), 0);
  38022. maxColor = Math.max(r, maxColor);
  38023. maxColor = Math.max(g, maxColor);
  38024. maxColor = Math.max(b, maxColor);
  38025. var pixelStorageIndex = (pixelIndexW + pixelIndexSlice * size + pixelIndexH * size * size) * 4;
  38026. if (tempData) {
  38027. tempData[pixelStorageIndex + 0] = r;
  38028. tempData[pixelStorageIndex + 1] = g;
  38029. tempData[pixelStorageIndex + 2] = b;
  38030. }
  38031. pixelIndexSlice++;
  38032. if (pixelIndexSlice % size == 0) {
  38033. pixelIndexH++;
  38034. pixelIndexSlice = 0;
  38035. if (pixelIndexH % size == 0) {
  38036. pixelIndexW++;
  38037. pixelIndexH = 0;
  38038. }
  38039. }
  38040. }
  38041. }
  38042. if (tempData && data) {
  38043. for (var i = 0; i < tempData.length; i++) {
  38044. if (i > 0 && (i + 1) % 4 === 0) {
  38045. data[i] = 255;
  38046. }
  38047. else {
  38048. var value = tempData[i];
  38049. data[i] = (value / maxColor * 255);
  38050. }
  38051. }
  38052. }
  38053. if (texture.is3D) {
  38054. texture.updateSize(size, size, size);
  38055. engine.updateRawTexture3D(texture, data, BABYLON.Engine.TEXTUREFORMAT_RGBA, false);
  38056. }
  38057. else {
  38058. texture.updateSize(size * size, size);
  38059. engine.updateRawTexture(texture, data, BABYLON.Engine.TEXTUREFORMAT_RGBA, false);
  38060. }
  38061. };
  38062. var scene = this.getScene();
  38063. if (scene) {
  38064. scene._loadFile(this.url, callback);
  38065. }
  38066. else {
  38067. this._engine._loadFile(this.url, callback);
  38068. }
  38069. return this._texture;
  38070. };
  38071. /**
  38072. * Starts the loading process of the texture.
  38073. */
  38074. ColorGradingTexture.prototype.loadTexture = function () {
  38075. if (this.url && this.url.toLocaleLowerCase().indexOf(".3dl") == (this.url.length - 4)) {
  38076. this.load3dlTexture();
  38077. }
  38078. };
  38079. /**
  38080. * Clones the color gradind texture.
  38081. */
  38082. ColorGradingTexture.prototype.clone = function () {
  38083. var newTexture = new ColorGradingTexture(this.url, this.getScene());
  38084. // Base texture
  38085. newTexture.level = this.level;
  38086. return newTexture;
  38087. };
  38088. /**
  38089. * Called during delayed load for textures.
  38090. */
  38091. ColorGradingTexture.prototype.delayLoad = function () {
  38092. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  38093. return;
  38094. }
  38095. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  38096. this._texture = this._getFromCache(this.url, true);
  38097. if (!this._texture) {
  38098. this.loadTexture();
  38099. }
  38100. };
  38101. /**
  38102. * Parses a color grading texture serialized by Babylon.
  38103. * @param parsedTexture The texture information being parsedTexture
  38104. * @param scene The scene to load the texture in
  38105. * @param rootUrl The root url of the data assets to load
  38106. * @return A color gradind texture
  38107. */
  38108. ColorGradingTexture.Parse = function (parsedTexture, scene, rootUrl) {
  38109. var texture = null;
  38110. if (parsedTexture.name && !parsedTexture.isRenderTarget) {
  38111. texture = new ColorGradingTexture(parsedTexture.name, scene);
  38112. texture.name = parsedTexture.name;
  38113. texture.level = parsedTexture.level;
  38114. }
  38115. return texture;
  38116. };
  38117. /**
  38118. * Serializes the LUT texture to json format.
  38119. */
  38120. ColorGradingTexture.prototype.serialize = function () {
  38121. if (!this.name) {
  38122. return null;
  38123. }
  38124. var serializationObject = {};
  38125. serializationObject.name = this.name;
  38126. serializationObject.level = this.level;
  38127. serializationObject.customType = "BABYLON.ColorGradingTexture";
  38128. return serializationObject;
  38129. };
  38130. /**
  38131. * Empty line regex stored for GC.
  38132. */
  38133. ColorGradingTexture._noneEmptyLineRegex = /\S+/;
  38134. return ColorGradingTexture;
  38135. }(BABYLON.BaseTexture));
  38136. BABYLON.ColorGradingTexture = ColorGradingTexture;
  38137. })(BABYLON || (BABYLON = {}));
  38138. //# sourceMappingURL=babylon.colorGradingTexture.js.map
  38139. "use strict";
  38140. var BABYLON;
  38141. (function (BABYLON) {
  38142. /**
  38143. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  38144. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  38145. * 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;
  38146. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  38147. */
  38148. var ColorCurves = /** @class */ (function () {
  38149. function ColorCurves() {
  38150. this._dirty = true;
  38151. this._tempColor = new BABYLON.Color4(0, 0, 0, 0);
  38152. this._globalCurve = new BABYLON.Color4(0, 0, 0, 0);
  38153. this._highlightsCurve = new BABYLON.Color4(0, 0, 0, 0);
  38154. this._midtonesCurve = new BABYLON.Color4(0, 0, 0, 0);
  38155. this._shadowsCurve = new BABYLON.Color4(0, 0, 0, 0);
  38156. this._positiveCurve = new BABYLON.Color4(0, 0, 0, 0);
  38157. this._negativeCurve = new BABYLON.Color4(0, 0, 0, 0);
  38158. this._globalHue = 30;
  38159. this._globalDensity = 0;
  38160. this._globalSaturation = 0;
  38161. this._globalExposure = 0;
  38162. this._highlightsHue = 30;
  38163. this._highlightsDensity = 0;
  38164. this._highlightsSaturation = 0;
  38165. this._highlightsExposure = 0;
  38166. this._midtonesHue = 30;
  38167. this._midtonesDensity = 0;
  38168. this._midtonesSaturation = 0;
  38169. this._midtonesExposure = 0;
  38170. this._shadowsHue = 30;
  38171. this._shadowsDensity = 0;
  38172. this._shadowsSaturation = 0;
  38173. this._shadowsExposure = 0;
  38174. }
  38175. Object.defineProperty(ColorCurves.prototype, "globalHue", {
  38176. /**
  38177. * Gets the global Hue value.
  38178. * 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).
  38179. */
  38180. get: function () {
  38181. return this._globalHue;
  38182. },
  38183. /**
  38184. * Sets the global Hue value.
  38185. * 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).
  38186. */
  38187. set: function (value) {
  38188. this._globalHue = value;
  38189. this._dirty = true;
  38190. },
  38191. enumerable: true,
  38192. configurable: true
  38193. });
  38194. Object.defineProperty(ColorCurves.prototype, "globalDensity", {
  38195. /**
  38196. * Gets the global Density value.
  38197. * 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.
  38198. * Values less than zero provide a filter of opposite hue.
  38199. */
  38200. get: function () {
  38201. return this._globalDensity;
  38202. },
  38203. /**
  38204. * Sets the global Density value.
  38205. * 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.
  38206. * Values less than zero provide a filter of opposite hue.
  38207. */
  38208. set: function (value) {
  38209. this._globalDensity = value;
  38210. this._dirty = true;
  38211. },
  38212. enumerable: true,
  38213. configurable: true
  38214. });
  38215. Object.defineProperty(ColorCurves.prototype, "globalSaturation", {
  38216. /**
  38217. * Gets the global Saturation value.
  38218. * 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.
  38219. */
  38220. get: function () {
  38221. return this._globalSaturation;
  38222. },
  38223. /**
  38224. * Sets the global Saturation value.
  38225. * 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.
  38226. */
  38227. set: function (value) {
  38228. this._globalSaturation = value;
  38229. this._dirty = true;
  38230. },
  38231. enumerable: true,
  38232. configurable: true
  38233. });
  38234. Object.defineProperty(ColorCurves.prototype, "highlightsHue", {
  38235. /**
  38236. * Gets the highlights Hue value.
  38237. * 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).
  38238. */
  38239. get: function () {
  38240. return this._highlightsHue;
  38241. },
  38242. /**
  38243. * Sets the highlights Hue value.
  38244. * 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).
  38245. */
  38246. set: function (value) {
  38247. this._highlightsHue = value;
  38248. this._dirty = true;
  38249. },
  38250. enumerable: true,
  38251. configurable: true
  38252. });
  38253. Object.defineProperty(ColorCurves.prototype, "highlightsDensity", {
  38254. /**
  38255. * Gets the highlights Density value.
  38256. * 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.
  38257. * Values less than zero provide a filter of opposite hue.
  38258. */
  38259. get: function () {
  38260. return this._highlightsDensity;
  38261. },
  38262. /**
  38263. * Sets the highlights Density value.
  38264. * 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.
  38265. * Values less than zero provide a filter of opposite hue.
  38266. */
  38267. set: function (value) {
  38268. this._highlightsDensity = value;
  38269. this._dirty = true;
  38270. },
  38271. enumerable: true,
  38272. configurable: true
  38273. });
  38274. Object.defineProperty(ColorCurves.prototype, "highlightsSaturation", {
  38275. /**
  38276. * Gets the highlights Saturation value.
  38277. * 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.
  38278. */
  38279. get: function () {
  38280. return this._highlightsSaturation;
  38281. },
  38282. /**
  38283. * Sets the highlights Saturation value.
  38284. * 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.
  38285. */
  38286. set: function (value) {
  38287. this._highlightsSaturation = value;
  38288. this._dirty = true;
  38289. },
  38290. enumerable: true,
  38291. configurable: true
  38292. });
  38293. Object.defineProperty(ColorCurves.prototype, "highlightsExposure", {
  38294. /**
  38295. * Gets the highlights Exposure value.
  38296. * 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.
  38297. */
  38298. get: function () {
  38299. return this._highlightsExposure;
  38300. },
  38301. /**
  38302. * Sets the highlights Exposure value.
  38303. * 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.
  38304. */
  38305. set: function (value) {
  38306. this._highlightsExposure = value;
  38307. this._dirty = true;
  38308. },
  38309. enumerable: true,
  38310. configurable: true
  38311. });
  38312. Object.defineProperty(ColorCurves.prototype, "midtonesHue", {
  38313. /**
  38314. * Gets the midtones Hue value.
  38315. * 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).
  38316. */
  38317. get: function () {
  38318. return this._midtonesHue;
  38319. },
  38320. /**
  38321. * Sets the midtones Hue value.
  38322. * 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).
  38323. */
  38324. set: function (value) {
  38325. this._midtonesHue = value;
  38326. this._dirty = true;
  38327. },
  38328. enumerable: true,
  38329. configurable: true
  38330. });
  38331. Object.defineProperty(ColorCurves.prototype, "midtonesDensity", {
  38332. /**
  38333. * Gets the midtones Density value.
  38334. * 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.
  38335. * Values less than zero provide a filter of opposite hue.
  38336. */
  38337. get: function () {
  38338. return this._midtonesDensity;
  38339. },
  38340. /**
  38341. * Sets the midtones Density value.
  38342. * 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.
  38343. * Values less than zero provide a filter of opposite hue.
  38344. */
  38345. set: function (value) {
  38346. this._midtonesDensity = value;
  38347. this._dirty = true;
  38348. },
  38349. enumerable: true,
  38350. configurable: true
  38351. });
  38352. Object.defineProperty(ColorCurves.prototype, "midtonesSaturation", {
  38353. /**
  38354. * Gets the midtones Saturation value.
  38355. * 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.
  38356. */
  38357. get: function () {
  38358. return this._midtonesSaturation;
  38359. },
  38360. /**
  38361. * Sets the midtones Saturation value.
  38362. * 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.
  38363. */
  38364. set: function (value) {
  38365. this._midtonesSaturation = value;
  38366. this._dirty = true;
  38367. },
  38368. enumerable: true,
  38369. configurable: true
  38370. });
  38371. Object.defineProperty(ColorCurves.prototype, "midtonesExposure", {
  38372. /**
  38373. * Gets the midtones Exposure value.
  38374. * 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.
  38375. */
  38376. get: function () {
  38377. return this._midtonesExposure;
  38378. },
  38379. /**
  38380. * Sets the midtones Exposure value.
  38381. * 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.
  38382. */
  38383. set: function (value) {
  38384. this._midtonesExposure = value;
  38385. this._dirty = true;
  38386. },
  38387. enumerable: true,
  38388. configurable: true
  38389. });
  38390. Object.defineProperty(ColorCurves.prototype, "shadowsHue", {
  38391. /**
  38392. * Gets the shadows Hue value.
  38393. * 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).
  38394. */
  38395. get: function () {
  38396. return this._shadowsHue;
  38397. },
  38398. /**
  38399. * Sets the shadows Hue value.
  38400. * 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).
  38401. */
  38402. set: function (value) {
  38403. this._shadowsHue = value;
  38404. this._dirty = true;
  38405. },
  38406. enumerable: true,
  38407. configurable: true
  38408. });
  38409. Object.defineProperty(ColorCurves.prototype, "shadowsDensity", {
  38410. /**
  38411. * Gets the shadows Density value.
  38412. * 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.
  38413. * Values less than zero provide a filter of opposite hue.
  38414. */
  38415. get: function () {
  38416. return this._shadowsDensity;
  38417. },
  38418. /**
  38419. * Sets the shadows Density value.
  38420. * 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.
  38421. * Values less than zero provide a filter of opposite hue.
  38422. */
  38423. set: function (value) {
  38424. this._shadowsDensity = value;
  38425. this._dirty = true;
  38426. },
  38427. enumerable: true,
  38428. configurable: true
  38429. });
  38430. Object.defineProperty(ColorCurves.prototype, "shadowsSaturation", {
  38431. /**
  38432. * Gets the shadows Saturation value.
  38433. * 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.
  38434. */
  38435. get: function () {
  38436. return this._shadowsSaturation;
  38437. },
  38438. /**
  38439. * Sets the shadows Saturation value.
  38440. * 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.
  38441. */
  38442. set: function (value) {
  38443. this._shadowsSaturation = value;
  38444. this._dirty = true;
  38445. },
  38446. enumerable: true,
  38447. configurable: true
  38448. });
  38449. Object.defineProperty(ColorCurves.prototype, "shadowsExposure", {
  38450. /**
  38451. * Gets the shadows Exposure value.
  38452. * 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.
  38453. */
  38454. get: function () {
  38455. return this._shadowsExposure;
  38456. },
  38457. /**
  38458. * Sets the shadows Exposure value.
  38459. * 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.
  38460. */
  38461. set: function (value) {
  38462. this._shadowsExposure = value;
  38463. this._dirty = true;
  38464. },
  38465. enumerable: true,
  38466. configurable: true
  38467. });
  38468. ColorCurves.prototype.getClassName = function () {
  38469. return "ColorCurves";
  38470. };
  38471. /**
  38472. * Binds the color curves to the shader.
  38473. * @param colorCurves The color curve to bind
  38474. * @param effect The effect to bind to
  38475. */
  38476. ColorCurves.Bind = function (colorCurves, effect, positiveUniform, neutralUniform, negativeUniform) {
  38477. if (positiveUniform === void 0) { positiveUniform = "vCameraColorCurvePositive"; }
  38478. if (neutralUniform === void 0) { neutralUniform = "vCameraColorCurveNeutral"; }
  38479. if (negativeUniform === void 0) { negativeUniform = "vCameraColorCurveNegative"; }
  38480. if (colorCurves._dirty) {
  38481. colorCurves._dirty = false;
  38482. // Fill in global info.
  38483. colorCurves.getColorGradingDataToRef(colorCurves._globalHue, colorCurves._globalDensity, colorCurves._globalSaturation, colorCurves._globalExposure, colorCurves._globalCurve);
  38484. // Compute highlights info.
  38485. colorCurves.getColorGradingDataToRef(colorCurves._highlightsHue, colorCurves._highlightsDensity, colorCurves._highlightsSaturation, colorCurves._highlightsExposure, colorCurves._tempColor);
  38486. colorCurves._tempColor.multiplyToRef(colorCurves._globalCurve, colorCurves._highlightsCurve);
  38487. // Compute midtones info.
  38488. colorCurves.getColorGradingDataToRef(colorCurves._midtonesHue, colorCurves._midtonesDensity, colorCurves._midtonesSaturation, colorCurves._midtonesExposure, colorCurves._tempColor);
  38489. colorCurves._tempColor.multiplyToRef(colorCurves._globalCurve, colorCurves._midtonesCurve);
  38490. // Compute shadows info.
  38491. colorCurves.getColorGradingDataToRef(colorCurves._shadowsHue, colorCurves._shadowsDensity, colorCurves._shadowsSaturation, colorCurves._shadowsExposure, colorCurves._tempColor);
  38492. colorCurves._tempColor.multiplyToRef(colorCurves._globalCurve, colorCurves._shadowsCurve);
  38493. // Compute deltas (neutral is midtones).
  38494. colorCurves._highlightsCurve.subtractToRef(colorCurves._midtonesCurve, colorCurves._positiveCurve);
  38495. colorCurves._midtonesCurve.subtractToRef(colorCurves._shadowsCurve, colorCurves._negativeCurve);
  38496. }
  38497. if (effect) {
  38498. effect.setFloat4(positiveUniform, colorCurves._positiveCurve.r, colorCurves._positiveCurve.g, colorCurves._positiveCurve.b, colorCurves._positiveCurve.a);
  38499. effect.setFloat4(neutralUniform, colorCurves._midtonesCurve.r, colorCurves._midtonesCurve.g, colorCurves._midtonesCurve.b, colorCurves._midtonesCurve.a);
  38500. effect.setFloat4(negativeUniform, colorCurves._negativeCurve.r, colorCurves._negativeCurve.g, colorCurves._negativeCurve.b, colorCurves._negativeCurve.a);
  38501. }
  38502. };
  38503. /**
  38504. * Prepare the list of uniforms associated with the ColorCurves effects.
  38505. * @param uniformsList The list of uniforms used in the effect
  38506. */
  38507. ColorCurves.PrepareUniforms = function (uniformsList) {
  38508. uniformsList.push("vCameraColorCurveNeutral", "vCameraColorCurvePositive", "vCameraColorCurveNegative");
  38509. };
  38510. /**
  38511. * Returns color grading data based on a hue, density, saturation and exposure value.
  38512. * @param filterHue The hue of the color filter.
  38513. * @param filterDensity The density of the color filter.
  38514. * @param saturation The saturation.
  38515. * @param exposure The exposure.
  38516. * @param result The result data container.
  38517. */
  38518. ColorCurves.prototype.getColorGradingDataToRef = function (hue, density, saturation, exposure, result) {
  38519. if (hue == null) {
  38520. return;
  38521. }
  38522. hue = ColorCurves.clamp(hue, 0, 360);
  38523. density = ColorCurves.clamp(density, -100, 100);
  38524. saturation = ColorCurves.clamp(saturation, -100, 100);
  38525. exposure = ColorCurves.clamp(exposure, -100, 100);
  38526. // Remap the slider/config filter density with non-linear mapping and also scale by half
  38527. // so that the maximum filter density is only 50% control. This provides fine control
  38528. // for small values and reasonable range.
  38529. density = ColorCurves.applyColorGradingSliderNonlinear(density);
  38530. density *= 0.5;
  38531. exposure = ColorCurves.applyColorGradingSliderNonlinear(exposure);
  38532. if (density < 0) {
  38533. density *= -1;
  38534. hue = (hue + 180) % 360;
  38535. }
  38536. ColorCurves.fromHSBToRef(hue, density, 50 + 0.25 * exposure, result);
  38537. result.scaleToRef(2, result);
  38538. result.a = 1 + 0.01 * saturation;
  38539. };
  38540. /**
  38541. * Takes an input slider value and returns an adjusted value that provides extra control near the centre.
  38542. * @param value The input slider value in range [-100,100].
  38543. * @returns Adjusted value.
  38544. */
  38545. ColorCurves.applyColorGradingSliderNonlinear = function (value) {
  38546. value /= 100;
  38547. var x = Math.abs(value);
  38548. x = Math.pow(x, 2);
  38549. if (value < 0) {
  38550. x *= -1;
  38551. }
  38552. x *= 100;
  38553. return x;
  38554. };
  38555. /**
  38556. * Returns an RGBA Color4 based on Hue, Saturation and Brightness (also referred to as value, HSV).
  38557. * @param hue The hue (H) input.
  38558. * @param saturation The saturation (S) input.
  38559. * @param brightness The brightness (B) input.
  38560. * @result An RGBA color represented as Vector4.
  38561. */
  38562. ColorCurves.fromHSBToRef = function (hue, saturation, brightness, result) {
  38563. var h = ColorCurves.clamp(hue, 0, 360);
  38564. var s = ColorCurves.clamp(saturation / 100, 0, 1);
  38565. var v = ColorCurves.clamp(brightness / 100, 0, 1);
  38566. if (s === 0) {
  38567. result.r = v;
  38568. result.g = v;
  38569. result.b = v;
  38570. }
  38571. else {
  38572. // sector 0 to 5
  38573. h /= 60;
  38574. var i = Math.floor(h);
  38575. // fractional part of h
  38576. var f = h - i;
  38577. var p = v * (1 - s);
  38578. var q = v * (1 - s * f);
  38579. var t = v * (1 - s * (1 - f));
  38580. switch (i) {
  38581. case 0:
  38582. result.r = v;
  38583. result.g = t;
  38584. result.b = p;
  38585. break;
  38586. case 1:
  38587. result.r = q;
  38588. result.g = v;
  38589. result.b = p;
  38590. break;
  38591. case 2:
  38592. result.r = p;
  38593. result.g = v;
  38594. result.b = t;
  38595. break;
  38596. case 3:
  38597. result.r = p;
  38598. result.g = q;
  38599. result.b = v;
  38600. break;
  38601. case 4:
  38602. result.r = t;
  38603. result.g = p;
  38604. result.b = v;
  38605. break;
  38606. default:// case 5:
  38607. result.r = v;
  38608. result.g = p;
  38609. result.b = q;
  38610. break;
  38611. }
  38612. }
  38613. result.a = 1;
  38614. };
  38615. /**
  38616. * Returns a value clamped between min and max
  38617. * @param value The value to clamp
  38618. * @param min The minimum of value
  38619. * @param max The maximum of value
  38620. * @returns The clamped value.
  38621. */
  38622. ColorCurves.clamp = function (value, min, max) {
  38623. return Math.min(Math.max(value, min), max);
  38624. };
  38625. /**
  38626. * Clones the current color curve instance.
  38627. * @return The cloned curves
  38628. */
  38629. ColorCurves.prototype.clone = function () {
  38630. return BABYLON.SerializationHelper.Clone(function () { return new ColorCurves(); }, this);
  38631. };
  38632. /**
  38633. * Serializes the current color curve instance to a json representation.
  38634. * @return a JSON representation
  38635. */
  38636. ColorCurves.prototype.serialize = function () {
  38637. return BABYLON.SerializationHelper.Serialize(this);
  38638. };
  38639. /**
  38640. * Parses the color curve from a json representation.
  38641. * @param source the JSON source to parse
  38642. * @return The parsed curves
  38643. */
  38644. ColorCurves.Parse = function (source) {
  38645. return BABYLON.SerializationHelper.Parse(function () { return new ColorCurves(); }, source, null, null);
  38646. };
  38647. __decorate([
  38648. BABYLON.serialize()
  38649. ], ColorCurves.prototype, "_globalHue", void 0);
  38650. __decorate([
  38651. BABYLON.serialize()
  38652. ], ColorCurves.prototype, "_globalDensity", void 0);
  38653. __decorate([
  38654. BABYLON.serialize()
  38655. ], ColorCurves.prototype, "_globalSaturation", void 0);
  38656. __decorate([
  38657. BABYLON.serialize()
  38658. ], ColorCurves.prototype, "_globalExposure", void 0);
  38659. __decorate([
  38660. BABYLON.serialize()
  38661. ], ColorCurves.prototype, "_highlightsHue", void 0);
  38662. __decorate([
  38663. BABYLON.serialize()
  38664. ], ColorCurves.prototype, "_highlightsDensity", void 0);
  38665. __decorate([
  38666. BABYLON.serialize()
  38667. ], ColorCurves.prototype, "_highlightsSaturation", void 0);
  38668. __decorate([
  38669. BABYLON.serialize()
  38670. ], ColorCurves.prototype, "_highlightsExposure", void 0);
  38671. __decorate([
  38672. BABYLON.serialize()
  38673. ], ColorCurves.prototype, "_midtonesHue", void 0);
  38674. __decorate([
  38675. BABYLON.serialize()
  38676. ], ColorCurves.prototype, "_midtonesDensity", void 0);
  38677. __decorate([
  38678. BABYLON.serialize()
  38679. ], ColorCurves.prototype, "_midtonesSaturation", void 0);
  38680. __decorate([
  38681. BABYLON.serialize()
  38682. ], ColorCurves.prototype, "_midtonesExposure", void 0);
  38683. return ColorCurves;
  38684. }());
  38685. BABYLON.ColorCurves = ColorCurves;
  38686. })(BABYLON || (BABYLON = {}));
  38687. //# sourceMappingURL=babylon.colorCurves.js.map
  38688. "use strict";
  38689. //# sourceMappingURL=babylon.behavior.js.map
  38690. "use strict";
  38691. var BABYLON;
  38692. (function (BABYLON) {
  38693. /**
  38694. * "Static Class" containing the most commonly used helper while dealing with material for
  38695. * rendering purpose.
  38696. *
  38697. * It contains the basic tools to help defining defines, binding uniform for the common part of the materials.
  38698. *
  38699. * This works by convention in BabylonJS but is meant to be use only with shader following the in place naming rules and conventions.
  38700. */
  38701. var MaterialHelper = /** @class */ (function () {
  38702. function MaterialHelper() {
  38703. }
  38704. /**
  38705. * Bind the current view position to an effect.
  38706. * @param effect The effect to be bound
  38707. * @param scene The scene the eyes position is used from
  38708. */
  38709. MaterialHelper.BindEyePosition = function (effect, scene) {
  38710. if (scene._forcedViewPosition) {
  38711. effect.setVector3("vEyePosition", scene._forcedViewPosition);
  38712. return;
  38713. }
  38714. effect.setVector3("vEyePosition", scene._mirroredCameraPosition ? scene._mirroredCameraPosition : scene.activeCamera.globalPosition);
  38715. };
  38716. /**
  38717. * Helps preparing the defines values about the UVs in used in the effect.
  38718. * UVs are shared as much as we can accross chanels in the shaders.
  38719. * @param texture The texture we are preparing the UVs for
  38720. * @param defines The defines to update
  38721. * @param key The chanel key "diffuse", "specular"... used in the shader
  38722. */
  38723. MaterialHelper.PrepareDefinesForMergedUV = function (texture, defines, key) {
  38724. defines._needUVs = true;
  38725. defines[key] = true;
  38726. if (texture.getTextureMatrix().isIdentity(true)) {
  38727. defines[key + "DIRECTUV"] = texture.coordinatesIndex + 1;
  38728. if (texture.coordinatesIndex === 0) {
  38729. defines["MAINUV1"] = true;
  38730. }
  38731. else {
  38732. defines["MAINUV2"] = true;
  38733. }
  38734. }
  38735. else {
  38736. defines[key + "DIRECTUV"] = 0;
  38737. }
  38738. };
  38739. /**
  38740. * Binds a texture matrix value to its corrsponding uniform
  38741. * @param texture The texture to bind the matrix for
  38742. * @param uniformBuffer The uniform buffer receivin the data
  38743. * @param key The chanel key "diffuse", "specular"... used in the shader
  38744. */
  38745. MaterialHelper.BindTextureMatrix = function (texture, uniformBuffer, key) {
  38746. var matrix = texture.getTextureMatrix();
  38747. if (!matrix.isIdentity(true)) {
  38748. uniformBuffer.updateMatrix(key + "Matrix", matrix);
  38749. }
  38750. };
  38751. /**
  38752. * Helper used to prepare the list of defines associated with misc. values for shader compilation
  38753. * @param mesh defines the current mesh
  38754. * @param scene defines the current scene
  38755. * @param useLogarithmicDepth defines if logarithmic depth has to be turned on
  38756. * @param pointsCloud defines if point cloud rendering has to be turned on
  38757. * @param fogEnabled defines if fog has to be turned on
  38758. * @param alphaTest defines if alpha testing has to be turned on
  38759. * @param defines defines the current list of defines
  38760. */
  38761. MaterialHelper.PrepareDefinesForMisc = function (mesh, scene, useLogarithmicDepth, pointsCloud, fogEnabled, alphaTest, defines) {
  38762. if (defines._areMiscDirty) {
  38763. defines["LOGARITHMICDEPTH"] = useLogarithmicDepth;
  38764. defines["POINTSIZE"] = pointsCloud;
  38765. defines["FOG"] = (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && fogEnabled);
  38766. defines["NONUNIFORMSCALING"] = mesh.nonUniformScaling;
  38767. defines["ALPHATEST"] = alphaTest;
  38768. }
  38769. };
  38770. /**
  38771. * Helper used to prepare the list of defines associated with frame values for shader compilation
  38772. * @param scene defines the current scene
  38773. * @param engine defines the current engine
  38774. * @param defines specifies the list of active defines
  38775. * @param useInstances defines if instances have to be turned on
  38776. * @param useClipPlane defines if clip plane have to be turned on
  38777. */
  38778. MaterialHelper.PrepareDefinesForFrameBoundValues = function (scene, engine, defines, useInstances, useClipPlane) {
  38779. if (useClipPlane === void 0) { useClipPlane = null; }
  38780. var changed = false;
  38781. if (useClipPlane == null) {
  38782. useClipPlane = (scene.clipPlane !== undefined && scene.clipPlane !== null);
  38783. }
  38784. if (defines["CLIPPLANE"] !== useClipPlane) {
  38785. defines["CLIPPLANE"] = useClipPlane;
  38786. changed = true;
  38787. }
  38788. if (defines["DEPTHPREPASS"] !== !engine.getColorWrite()) {
  38789. defines["DEPTHPREPASS"] = !defines["DEPTHPREPASS"];
  38790. changed = true;
  38791. }
  38792. if (defines["INSTANCES"] !== useInstances) {
  38793. defines["INSTANCES"] = useInstances;
  38794. changed = true;
  38795. }
  38796. if (changed) {
  38797. defines.markAsUnprocessed();
  38798. }
  38799. };
  38800. /**
  38801. * Prepares the defines used in the shader depending on the attributes data available in the mesh
  38802. * @param mesh The mesh containing the geometry data we will draw
  38803. * @param defines The defines to update
  38804. * @param useVertexColor Precise whether vertex colors should be used or not (override mesh info)
  38805. * @param useBones Precise whether bones should be used or not (override mesh info)
  38806. * @param useMorphTargets Precise whether morph targets should be used or not (override mesh info)
  38807. * @param useVertexAlpha Precise whether vertex alpha should be used or not (override mesh info)
  38808. * @returns false if defines are considered not dirty and have not been checked
  38809. */
  38810. MaterialHelper.PrepareDefinesForAttributes = function (mesh, defines, useVertexColor, useBones, useMorphTargets, useVertexAlpha) {
  38811. if (useMorphTargets === void 0) { useMorphTargets = false; }
  38812. if (useVertexAlpha === void 0) { useVertexAlpha = true; }
  38813. if (!defines._areAttributesDirty && defines._needNormals === defines._normals && defines._needUVs === defines._uvs) {
  38814. return false;
  38815. }
  38816. defines._normals = defines._needNormals;
  38817. defines._uvs = defines._needUVs;
  38818. defines["NORMAL"] = (defines._needNormals && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind));
  38819. if (defines._needNormals && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind)) {
  38820. defines["TANGENT"] = true;
  38821. }
  38822. if (defines._needUVs) {
  38823. defines["UV1"] = mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind);
  38824. defines["UV2"] = mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind);
  38825. }
  38826. else {
  38827. defines["UV1"] = false;
  38828. defines["UV2"] = false;
  38829. }
  38830. if (useVertexColor) {
  38831. var hasVertexColors = mesh.useVertexColors && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind);
  38832. defines["VERTEXCOLOR"] = hasVertexColors;
  38833. defines["VERTEXALPHA"] = mesh.hasVertexAlpha && hasVertexColors && useVertexAlpha;
  38834. }
  38835. if (useBones) {
  38836. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  38837. defines["NUM_BONE_INFLUENCERS"] = mesh.numBoneInfluencers;
  38838. defines["BonesPerMesh"] = (mesh.skeleton.bones.length + 1);
  38839. }
  38840. else {
  38841. defines["NUM_BONE_INFLUENCERS"] = 0;
  38842. defines["BonesPerMesh"] = 0;
  38843. }
  38844. }
  38845. if (useMorphTargets) {
  38846. var manager = mesh.morphTargetManager;
  38847. if (manager) {
  38848. defines["MORPHTARGETS_TANGENT"] = manager.supportsTangents && defines["TANGENT"];
  38849. defines["MORPHTARGETS_NORMAL"] = manager.supportsNormals && defines["NORMAL"];
  38850. defines["MORPHTARGETS"] = (manager.numInfluencers > 0);
  38851. defines["NUM_MORPH_INFLUENCERS"] = manager.numInfluencers;
  38852. }
  38853. else {
  38854. defines["MORPHTARGETS_TANGENT"] = false;
  38855. defines["MORPHTARGETS_NORMAL"] = false;
  38856. defines["MORPHTARGETS"] = false;
  38857. defines["NUM_MORPH_INFLUENCERS"] = 0;
  38858. }
  38859. }
  38860. return true;
  38861. };
  38862. /**
  38863. * Prepares the defines related to the light information passed in parameter
  38864. * @param scene The scene we are intending to draw
  38865. * @param mesh The mesh the effect is compiling for
  38866. * @param defines The defines to update
  38867. * @param specularSupported Specifies whether specular is supported or not (override lights data)
  38868. * @param maxSimultaneousLights Specfies how manuy lights can be added to the effect at max
  38869. * @param disableLighting Specifies whether the lighting is disabled (override scene and light)
  38870. * @returns true if normals will be required for the rest of the effect
  38871. */
  38872. MaterialHelper.PrepareDefinesForLights = function (scene, mesh, defines, specularSupported, maxSimultaneousLights, disableLighting) {
  38873. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  38874. if (disableLighting === void 0) { disableLighting = false; }
  38875. if (!defines._areLightsDirty) {
  38876. return defines._needNormals;
  38877. }
  38878. var lightIndex = 0;
  38879. var needNormals = false;
  38880. var needRebuild = false;
  38881. var lightmapMode = false;
  38882. var shadowEnabled = false;
  38883. var specularEnabled = false;
  38884. if (scene.lightsEnabled && !disableLighting) {
  38885. for (var _i = 0, _a = mesh._lightSources; _i < _a.length; _i++) {
  38886. var light = _a[_i];
  38887. needNormals = true;
  38888. if (defines["LIGHT" + lightIndex] === undefined) {
  38889. needRebuild = true;
  38890. }
  38891. defines["LIGHT" + lightIndex] = true;
  38892. defines["SPOTLIGHT" + lightIndex] = false;
  38893. defines["HEMILIGHT" + lightIndex] = false;
  38894. defines["POINTLIGHT" + lightIndex] = false;
  38895. defines["DIRLIGHT" + lightIndex] = false;
  38896. var type;
  38897. if (light.getTypeID() === BABYLON.Light.LIGHTTYPEID_SPOTLIGHT) {
  38898. type = "SPOTLIGHT" + lightIndex;
  38899. var spotLight = light;
  38900. defines["PROJECTEDLIGHTTEXTURE" + lightIndex] = spotLight.projectionTexture ? spotLight.projectionTexture.isReady() : false;
  38901. }
  38902. else if (light.getTypeID() === BABYLON.Light.LIGHTTYPEID_HEMISPHERICLIGHT) {
  38903. type = "HEMILIGHT" + lightIndex;
  38904. }
  38905. else if (light.getTypeID() === BABYLON.Light.LIGHTTYPEID_POINTLIGHT) {
  38906. type = "POINTLIGHT" + lightIndex;
  38907. }
  38908. else {
  38909. type = "DIRLIGHT" + lightIndex;
  38910. }
  38911. defines[type] = true;
  38912. // Specular
  38913. if (specularSupported && !light.specular.equalsFloats(0, 0, 0)) {
  38914. specularEnabled = true;
  38915. }
  38916. // Shadows
  38917. defines["SHADOW" + lightIndex] = false;
  38918. defines["SHADOWPCF" + lightIndex] = false;
  38919. defines["SHADOWPCSS" + lightIndex] = false;
  38920. defines["SHADOWPOISSON" + lightIndex] = false;
  38921. defines["SHADOWESM" + lightIndex] = false;
  38922. defines["SHADOWCUBE" + lightIndex] = false;
  38923. defines["SHADOWLOWQUALITY" + lightIndex] = false;
  38924. defines["SHADOWMEDIUMQUALITY" + lightIndex] = false;
  38925. if (mesh && mesh.receiveShadows && scene.shadowsEnabled && light.shadowEnabled) {
  38926. var shadowGenerator = light.getShadowGenerator();
  38927. if (shadowGenerator) {
  38928. shadowEnabled = true;
  38929. shadowGenerator.prepareDefines(defines, lightIndex);
  38930. }
  38931. }
  38932. if (light.lightmapMode != BABYLON.Light.LIGHTMAP_DEFAULT) {
  38933. lightmapMode = true;
  38934. defines["LIGHTMAPEXCLUDED" + lightIndex] = true;
  38935. defines["LIGHTMAPNOSPECULAR" + lightIndex] = (light.lightmapMode == BABYLON.Light.LIGHTMAP_SHADOWSONLY);
  38936. }
  38937. else {
  38938. defines["LIGHTMAPEXCLUDED" + lightIndex] = false;
  38939. defines["LIGHTMAPNOSPECULAR" + lightIndex] = false;
  38940. }
  38941. lightIndex++;
  38942. if (lightIndex === maxSimultaneousLights)
  38943. break;
  38944. }
  38945. }
  38946. defines["SPECULARTERM"] = specularEnabled;
  38947. defines["SHADOWS"] = shadowEnabled;
  38948. // Resetting all other lights if any
  38949. for (var index = lightIndex; index < maxSimultaneousLights; index++) {
  38950. if (defines["LIGHT" + index] !== undefined) {
  38951. defines["LIGHT" + index] = false;
  38952. defines["HEMILIGHT" + lightIndex] = false;
  38953. defines["POINTLIGHT" + lightIndex] = false;
  38954. defines["DIRLIGHT" + lightIndex] = false;
  38955. defines["SPOTLIGHT" + lightIndex] = false;
  38956. defines["SHADOW" + lightIndex] = false;
  38957. }
  38958. }
  38959. var caps = scene.getEngine().getCaps();
  38960. if (defines["SHADOWFLOAT"] === undefined) {
  38961. needRebuild = true;
  38962. }
  38963. defines["SHADOWFLOAT"] = shadowEnabled &&
  38964. ((caps.textureFloatRender && caps.textureFloatLinearFiltering) ||
  38965. (caps.textureHalfFloatRender && caps.textureHalfFloatLinearFiltering));
  38966. defines["LIGHTMAPEXCLUDED"] = lightmapMode;
  38967. if (needRebuild) {
  38968. defines.rebuild();
  38969. }
  38970. return needNormals;
  38971. };
  38972. /**
  38973. * Prepares the uniforms and samplers list to be used in the effect. This can automatically remove from the list uniforms
  38974. * that won t be acctive due to defines being turned off.
  38975. * @param uniformsListOrOptions The uniform names to prepare or an EffectCreationOptions containing the liist and extra information
  38976. * @param samplersList The samplers list
  38977. * @param defines The defines helping in the list generation
  38978. * @param maxSimultaneousLights The maximum number of simultanous light allowed in the effect
  38979. */
  38980. MaterialHelper.PrepareUniformsAndSamplersList = function (uniformsListOrOptions, samplersList, defines, maxSimultaneousLights) {
  38981. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  38982. var uniformsList;
  38983. var uniformBuffersList = null;
  38984. if (uniformsListOrOptions.uniformsNames) {
  38985. var options = uniformsListOrOptions;
  38986. uniformsList = options.uniformsNames;
  38987. uniformBuffersList = options.uniformBuffersNames;
  38988. samplersList = options.samplers;
  38989. defines = options.defines;
  38990. maxSimultaneousLights = options.maxSimultaneousLights;
  38991. }
  38992. else {
  38993. uniformsList = uniformsListOrOptions;
  38994. if (!samplersList) {
  38995. samplersList = [];
  38996. }
  38997. }
  38998. for (var lightIndex = 0; lightIndex < maxSimultaneousLights; lightIndex++) {
  38999. if (!defines["LIGHT" + lightIndex]) {
  39000. break;
  39001. }
  39002. uniformsList.push("vLightData" + lightIndex, "vLightDiffuse" + lightIndex, "vLightSpecular" + lightIndex, "vLightDirection" + lightIndex, "vLightGround" + lightIndex, "lightMatrix" + lightIndex, "shadowsInfo" + lightIndex, "depthValues" + lightIndex);
  39003. if (uniformBuffersList) {
  39004. uniformBuffersList.push("Light" + lightIndex);
  39005. }
  39006. samplersList.push("shadowSampler" + lightIndex);
  39007. samplersList.push("depthSampler" + lightIndex);
  39008. if (defines["PROJECTEDLIGHTTEXTURE" + lightIndex]) {
  39009. samplersList.push("projectionLightSampler" + lightIndex);
  39010. uniformsList.push("textureProjectionMatrix" + lightIndex);
  39011. }
  39012. }
  39013. if (defines["NUM_MORPH_INFLUENCERS"]) {
  39014. uniformsList.push("morphTargetInfluences");
  39015. }
  39016. };
  39017. /**
  39018. * This helps decreasing rank by rank the shadow quality (0 being the highest rank and quality)
  39019. * @param defines The defines to update while falling back
  39020. * @param fallbacks The authorized effect fallbacks
  39021. * @param maxSimultaneousLights The maximum number of lights allowed
  39022. * @param rank the current rank of the Effect
  39023. * @returns The newly affected rank
  39024. */
  39025. MaterialHelper.HandleFallbacksForShadows = function (defines, fallbacks, maxSimultaneousLights, rank) {
  39026. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  39027. if (rank === void 0) { rank = 0; }
  39028. var lightFallbackRank = 0;
  39029. for (var lightIndex = 0; lightIndex < maxSimultaneousLights; lightIndex++) {
  39030. if (!defines["LIGHT" + lightIndex]) {
  39031. break;
  39032. }
  39033. if (lightIndex > 0) {
  39034. lightFallbackRank = rank + lightIndex;
  39035. fallbacks.addFallback(lightFallbackRank, "LIGHT" + lightIndex);
  39036. }
  39037. if (!defines["SHADOWS"]) {
  39038. if (defines["SHADOW" + lightIndex]) {
  39039. fallbacks.addFallback(rank, "SHADOW" + lightIndex);
  39040. }
  39041. if (defines["SHADOWPCF" + lightIndex]) {
  39042. fallbacks.addFallback(rank, "SHADOWPCF" + lightIndex);
  39043. }
  39044. if (defines["SHADOWPCSS" + lightIndex]) {
  39045. fallbacks.addFallback(rank, "SHADOWPCSS" + lightIndex);
  39046. }
  39047. if (defines["SHADOWPOISSON" + lightIndex]) {
  39048. fallbacks.addFallback(rank, "SHADOWPOISSON" + lightIndex);
  39049. }
  39050. if (defines["SHADOWESM" + lightIndex]) {
  39051. fallbacks.addFallback(rank, "SHADOWESM" + lightIndex);
  39052. }
  39053. }
  39054. }
  39055. return lightFallbackRank++;
  39056. };
  39057. /**
  39058. * Prepares the list of attributes required for morph targets according to the effect defines.
  39059. * @param attribs The current list of supported attribs
  39060. * @param mesh The mesh to prepare the morph targets attributes for
  39061. * @param defines The current Defines of the effect
  39062. */
  39063. MaterialHelper.PrepareAttributesForMorphTargets = function (attribs, mesh, defines) {
  39064. var influencers = defines["NUM_MORPH_INFLUENCERS"];
  39065. if (influencers > 0 && BABYLON.Engine.LastCreatedEngine) {
  39066. var maxAttributesCount = BABYLON.Engine.LastCreatedEngine.getCaps().maxVertexAttribs;
  39067. var manager = mesh.morphTargetManager;
  39068. var normal = manager && manager.supportsNormals && defines["NORMAL"];
  39069. var tangent = manager && manager.supportsTangents && defines["TANGENT"];
  39070. for (var index = 0; index < influencers; index++) {
  39071. attribs.push(BABYLON.VertexBuffer.PositionKind + index);
  39072. if (normal) {
  39073. attribs.push(BABYLON.VertexBuffer.NormalKind + index);
  39074. }
  39075. if (tangent) {
  39076. attribs.push(BABYLON.VertexBuffer.TangentKind + index);
  39077. }
  39078. if (attribs.length > maxAttributesCount) {
  39079. BABYLON.Tools.Error("Cannot add more vertex attributes for mesh " + mesh.name);
  39080. }
  39081. }
  39082. }
  39083. };
  39084. /**
  39085. * Prepares the list of attributes required for bones according to the effect defines.
  39086. * @param attribs The current list of supported attribs
  39087. * @param mesh The mesh to prepare the bones attributes for
  39088. * @param defines The current Defines of the effect
  39089. * @param fallbacks The current efffect fallback strategy
  39090. */
  39091. MaterialHelper.PrepareAttributesForBones = function (attribs, mesh, defines, fallbacks) {
  39092. if (defines["NUM_BONE_INFLUENCERS"] > 0) {
  39093. fallbacks.addCPUSkinningFallback(0, mesh);
  39094. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  39095. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  39096. if (defines["NUM_BONE_INFLUENCERS"] > 4) {
  39097. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  39098. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  39099. }
  39100. }
  39101. };
  39102. /**
  39103. * Prepares the list of attributes required for instances according to the effect defines.
  39104. * @param attribs The current list of supported attribs
  39105. * @param defines The current Defines of the effect
  39106. */
  39107. MaterialHelper.PrepareAttributesForInstances = function (attribs, defines) {
  39108. if (defines["INSTANCES"]) {
  39109. attribs.push("world0");
  39110. attribs.push("world1");
  39111. attribs.push("world2");
  39112. attribs.push("world3");
  39113. }
  39114. };
  39115. /**
  39116. * Binds the light shadow information to the effect for the given mesh.
  39117. * @param light The light containing the generator
  39118. * @param scene The scene the lights belongs to
  39119. * @param mesh The mesh we are binding the information to render
  39120. * @param lightIndex The light index in the effect used to render the mesh
  39121. * @param effect The effect we are binding the data to
  39122. */
  39123. MaterialHelper.BindLightShadow = function (light, scene, mesh, lightIndex, effect) {
  39124. if (light.shadowEnabled && mesh.receiveShadows) {
  39125. var shadowGenerator = light.getShadowGenerator();
  39126. if (shadowGenerator) {
  39127. shadowGenerator.bindShadowLight(lightIndex, effect);
  39128. }
  39129. }
  39130. };
  39131. /**
  39132. * Binds the light information to the effect.
  39133. * @param light The light containing the generator
  39134. * @param effect The effect we are binding the data to
  39135. * @param lightIndex The light index in the effect used to render
  39136. */
  39137. MaterialHelper.BindLightProperties = function (light, effect, lightIndex) {
  39138. light.transferToEffect(effect, lightIndex + "");
  39139. };
  39140. /**
  39141. * Binds the lights information from the scene to the effect for the given mesh.
  39142. * @param scene The scene the lights belongs to
  39143. * @param mesh The mesh we are binding the information to render
  39144. * @param effect The effect we are binding the data to
  39145. * @param defines The generated defines for the effect
  39146. * @param maxSimultaneousLights The maximum number of light that can be bound to the effect
  39147. * @param usePhysicalLightFalloff Specifies whether the light falloff is defined physically or not
  39148. */
  39149. MaterialHelper.BindLights = function (scene, mesh, effect, defines, maxSimultaneousLights, usePhysicalLightFalloff) {
  39150. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  39151. if (usePhysicalLightFalloff === void 0) { usePhysicalLightFalloff = false; }
  39152. var len = Math.min(mesh._lightSources.length, maxSimultaneousLights);
  39153. for (var i = 0; i < len; i++) {
  39154. var light = mesh._lightSources[i];
  39155. var iAsString = i.toString();
  39156. var scaledIntensity = light.getScaledIntensity();
  39157. light._uniformBuffer.bindToEffect(effect, "Light" + i);
  39158. MaterialHelper.BindLightProperties(light, effect, i);
  39159. light.diffuse.scaleToRef(scaledIntensity, BABYLON.Tmp.Color3[0]);
  39160. light._uniformBuffer.updateColor4("vLightDiffuse", BABYLON.Tmp.Color3[0], usePhysicalLightFalloff ? light.radius : light.range, iAsString);
  39161. if (defines["SPECULARTERM"]) {
  39162. light.specular.scaleToRef(scaledIntensity, BABYLON.Tmp.Color3[1]);
  39163. light._uniformBuffer.updateColor3("vLightSpecular", BABYLON.Tmp.Color3[1], iAsString);
  39164. }
  39165. // Shadows
  39166. if (scene.shadowsEnabled) {
  39167. this.BindLightShadow(light, scene, mesh, iAsString, effect);
  39168. }
  39169. light._uniformBuffer.update();
  39170. }
  39171. };
  39172. /**
  39173. * Binds the fog information from the scene to the effect for the given mesh.
  39174. * @param scene The scene the lights belongs to
  39175. * @param mesh The mesh we are binding the information to render
  39176. * @param effect The effect we are binding the data to
  39177. */
  39178. MaterialHelper.BindFogParameters = function (scene, mesh, effect) {
  39179. if (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE) {
  39180. effect.setFloat4("vFogInfos", scene.fogMode, scene.fogStart, scene.fogEnd, scene.fogDensity);
  39181. effect.setColor3("vFogColor", scene.fogColor);
  39182. }
  39183. };
  39184. /**
  39185. * Binds the bones information from the mesh to the effect.
  39186. * @param mesh The mesh we are binding the information to render
  39187. * @param effect The effect we are binding the data to
  39188. */
  39189. MaterialHelper.BindBonesParameters = function (mesh, effect) {
  39190. if (mesh && mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  39191. var matrices = mesh.skeleton.getTransformMatrices(mesh);
  39192. if (matrices && effect) {
  39193. effect.setMatrices("mBones", matrices);
  39194. }
  39195. }
  39196. };
  39197. /**
  39198. * Binds the morph targets information from the mesh to the effect.
  39199. * @param abstractMesh The mesh we are binding the information to render
  39200. * @param effect The effect we are binding the data to
  39201. */
  39202. MaterialHelper.BindMorphTargetParameters = function (abstractMesh, effect) {
  39203. var manager = abstractMesh.morphTargetManager;
  39204. if (!abstractMesh || !manager) {
  39205. return;
  39206. }
  39207. effect.setFloatArray("morphTargetInfluences", manager.influences);
  39208. };
  39209. /**
  39210. * Binds the logarithmic depth information from the scene to the effect for the given defines.
  39211. * @param defines The generated defines used in the effect
  39212. * @param effect The effect we are binding the data to
  39213. * @param scene The scene we are willing to render with logarithmic scale for
  39214. */
  39215. MaterialHelper.BindLogDepth = function (defines, effect, scene) {
  39216. if (defines["LOGARITHMICDEPTH"]) {
  39217. effect.setFloat("logarithmicDepthConstant", 2.0 / (Math.log(scene.activeCamera.maxZ + 1.0) / Math.LN2));
  39218. }
  39219. };
  39220. /**
  39221. * Binds the clip plane information from the scene to the effect.
  39222. * @param scene The scene the clip plane information are extracted from
  39223. * @param effect The effect we are binding the data to
  39224. */
  39225. MaterialHelper.BindClipPlane = function (effect, scene) {
  39226. if (scene.clipPlane) {
  39227. var clipPlane = scene.clipPlane;
  39228. effect.setFloat4("vClipPlane", clipPlane.normal.x, clipPlane.normal.y, clipPlane.normal.z, clipPlane.d);
  39229. }
  39230. };
  39231. return MaterialHelper;
  39232. }());
  39233. BABYLON.MaterialHelper = MaterialHelper;
  39234. })(BABYLON || (BABYLON = {}));
  39235. //# sourceMappingURL=babylon.materialHelper.js.map
  39236. "use strict";
  39237. var BABYLON;
  39238. (function (BABYLON) {
  39239. var PushMaterial = /** @class */ (function (_super) {
  39240. __extends(PushMaterial, _super);
  39241. function PushMaterial(name, scene) {
  39242. var _this = _super.call(this, name, scene) || this;
  39243. _this._normalMatrix = new BABYLON.Matrix();
  39244. _this.storeEffectOnSubMeshes = true;
  39245. return _this;
  39246. }
  39247. PushMaterial.prototype.getEffect = function () {
  39248. return this._activeEffect;
  39249. };
  39250. PushMaterial.prototype.isReady = function (mesh, useInstances) {
  39251. if (!mesh) {
  39252. return false;
  39253. }
  39254. if (!mesh.subMeshes || mesh.subMeshes.length === 0) {
  39255. return true;
  39256. }
  39257. return this.isReadyForSubMesh(mesh, mesh.subMeshes[0], useInstances);
  39258. };
  39259. /**
  39260. * Binds the given world matrix to the active effect
  39261. *
  39262. * @param world the matrix to bind
  39263. */
  39264. PushMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  39265. this._activeEffect.setMatrix("world", world);
  39266. };
  39267. /**
  39268. * Binds the given normal matrix to the active effect
  39269. *
  39270. * @param normalMatrix the matrix to bind
  39271. */
  39272. PushMaterial.prototype.bindOnlyNormalMatrix = function (normalMatrix) {
  39273. this._activeEffect.setMatrix("normalMatrix", normalMatrix);
  39274. };
  39275. PushMaterial.prototype.bind = function (world, mesh) {
  39276. if (!mesh) {
  39277. return;
  39278. }
  39279. this.bindForSubMesh(world, mesh, mesh.subMeshes[0]);
  39280. };
  39281. PushMaterial.prototype._afterBind = function (mesh, effect) {
  39282. if (effect === void 0) { effect = null; }
  39283. _super.prototype._afterBind.call(this, mesh);
  39284. this.getScene()._cachedEffect = effect;
  39285. };
  39286. PushMaterial.prototype._mustRebind = function (scene, effect, visibility) {
  39287. if (visibility === void 0) { visibility = 1; }
  39288. return scene.isCachedMaterialInvalid(this, effect, visibility);
  39289. };
  39290. return PushMaterial;
  39291. }(BABYLON.Material));
  39292. BABYLON.PushMaterial = PushMaterial;
  39293. })(BABYLON || (BABYLON = {}));
  39294. //# sourceMappingURL=babylon.pushMaterial.js.map
  39295. "use strict";
  39296. var BABYLON;
  39297. (function (BABYLON) {
  39298. /** @ignore */
  39299. var StandardMaterialDefines = /** @class */ (function (_super) {
  39300. __extends(StandardMaterialDefines, _super);
  39301. function StandardMaterialDefines() {
  39302. var _this = _super.call(this) || this;
  39303. _this.MAINUV1 = false;
  39304. _this.MAINUV2 = false;
  39305. _this.DIFFUSE = false;
  39306. _this.DIFFUSEDIRECTUV = 0;
  39307. _this.AMBIENT = false;
  39308. _this.AMBIENTDIRECTUV = 0;
  39309. _this.OPACITY = false;
  39310. _this.OPACITYDIRECTUV = 0;
  39311. _this.OPACITYRGB = false;
  39312. _this.REFLECTION = false;
  39313. _this.EMISSIVE = false;
  39314. _this.EMISSIVEDIRECTUV = 0;
  39315. _this.SPECULAR = false;
  39316. _this.SPECULARDIRECTUV = 0;
  39317. _this.BUMP = false;
  39318. _this.BUMPDIRECTUV = 0;
  39319. _this.PARALLAX = false;
  39320. _this.PARALLAXOCCLUSION = false;
  39321. _this.SPECULAROVERALPHA = false;
  39322. _this.CLIPPLANE = false;
  39323. _this.ALPHATEST = false;
  39324. _this.DEPTHPREPASS = false;
  39325. _this.ALPHAFROMDIFFUSE = false;
  39326. _this.POINTSIZE = false;
  39327. _this.FOG = false;
  39328. _this.SPECULARTERM = false;
  39329. _this.DIFFUSEFRESNEL = false;
  39330. _this.OPACITYFRESNEL = false;
  39331. _this.REFLECTIONFRESNEL = false;
  39332. _this.REFRACTIONFRESNEL = false;
  39333. _this.EMISSIVEFRESNEL = false;
  39334. _this.FRESNEL = false;
  39335. _this.NORMAL = false;
  39336. _this.UV1 = false;
  39337. _this.UV2 = false;
  39338. _this.VERTEXCOLOR = false;
  39339. _this.VERTEXALPHA = false;
  39340. _this.NUM_BONE_INFLUENCERS = 0;
  39341. _this.BonesPerMesh = 0;
  39342. _this.INSTANCES = false;
  39343. _this.GLOSSINESS = false;
  39344. _this.ROUGHNESS = false;
  39345. _this.EMISSIVEASILLUMINATION = false;
  39346. _this.LINKEMISSIVEWITHDIFFUSE = false;
  39347. _this.REFLECTIONFRESNELFROMSPECULAR = false;
  39348. _this.LIGHTMAP = false;
  39349. _this.LIGHTMAPDIRECTUV = 0;
  39350. _this.OBJECTSPACE_NORMALMAP = false;
  39351. _this.USELIGHTMAPASSHADOWMAP = false;
  39352. _this.REFLECTIONMAP_3D = false;
  39353. _this.REFLECTIONMAP_SPHERICAL = false;
  39354. _this.REFLECTIONMAP_PLANAR = false;
  39355. _this.REFLECTIONMAP_CUBIC = false;
  39356. _this.USE_LOCAL_REFLECTIONMAP_CUBIC = false;
  39357. _this.REFLECTIONMAP_PROJECTION = false;
  39358. _this.REFLECTIONMAP_SKYBOX = false;
  39359. _this.REFLECTIONMAP_EXPLICIT = false;
  39360. _this.REFLECTIONMAP_EQUIRECTANGULAR = false;
  39361. _this.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  39362. _this.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  39363. _this.INVERTCUBICMAP = false;
  39364. _this.LOGARITHMICDEPTH = false;
  39365. _this.REFRACTION = false;
  39366. _this.REFRACTIONMAP_3D = false;
  39367. _this.REFLECTIONOVERALPHA = false;
  39368. _this.TWOSIDEDLIGHTING = false;
  39369. _this.SHADOWFLOAT = false;
  39370. _this.MORPHTARGETS = false;
  39371. _this.MORPHTARGETS_NORMAL = false;
  39372. _this.MORPHTARGETS_TANGENT = false;
  39373. _this.NUM_MORPH_INFLUENCERS = 0;
  39374. _this.NONUNIFORMSCALING = false; // https://playground.babylonjs.com#V6DWIH
  39375. _this.PREMULTIPLYALPHA = false; // https://playground.babylonjs.com#LNVJJ7
  39376. _this.IMAGEPROCESSING = false;
  39377. _this.VIGNETTE = false;
  39378. _this.VIGNETTEBLENDMODEMULTIPLY = false;
  39379. _this.VIGNETTEBLENDMODEOPAQUE = false;
  39380. _this.TONEMAPPING = false;
  39381. _this.CONTRAST = false;
  39382. _this.COLORCURVES = false;
  39383. _this.COLORGRADING = false;
  39384. _this.COLORGRADING3D = false;
  39385. _this.SAMPLER3DGREENDEPTH = false;
  39386. _this.SAMPLER3DBGRMAP = false;
  39387. _this.IMAGEPROCESSINGPOSTPROCESS = false;
  39388. _this.EXPOSURE = false;
  39389. _this.rebuild();
  39390. return _this;
  39391. }
  39392. StandardMaterialDefines.prototype.setReflectionMode = function (modeToEnable) {
  39393. var modes = [
  39394. "REFLECTIONMAP_CUBIC", "REFLECTIONMAP_EXPLICIT", "REFLECTIONMAP_PLANAR",
  39395. "REFLECTIONMAP_PROJECTION", "REFLECTIONMAP_PROJECTION", "REFLECTIONMAP_SKYBOX",
  39396. "REFLECTIONMAP_SPHERICAL", "REFLECTIONMAP_EQUIRECTANGULAR", "REFLECTIONMAP_EQUIRECTANGULAR_FIXED",
  39397. "REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED"
  39398. ];
  39399. for (var _i = 0, modes_1 = modes; _i < modes_1.length; _i++) {
  39400. var mode = modes_1[_i];
  39401. this[mode] = (mode === modeToEnable);
  39402. }
  39403. };
  39404. return StandardMaterialDefines;
  39405. }(BABYLON.MaterialDefines));
  39406. BABYLON.StandardMaterialDefines = StandardMaterialDefines;
  39407. var StandardMaterial = /** @class */ (function (_super) {
  39408. __extends(StandardMaterial, _super);
  39409. function StandardMaterial(name, scene) {
  39410. var _this = _super.call(this, name, scene) || this;
  39411. _this.ambientColor = new BABYLON.Color3(0, 0, 0);
  39412. _this.diffuseColor = new BABYLON.Color3(1, 1, 1);
  39413. _this.specularColor = new BABYLON.Color3(1, 1, 1);
  39414. _this.emissiveColor = new BABYLON.Color3(0, 0, 0);
  39415. _this.specularPower = 64;
  39416. _this._useAlphaFromDiffuseTexture = false;
  39417. _this._useEmissiveAsIllumination = false;
  39418. _this._linkEmissiveWithDiffuse = false;
  39419. _this._useSpecularOverAlpha = false;
  39420. _this._useReflectionOverAlpha = false;
  39421. _this._disableLighting = false;
  39422. _this._useObjectSpaceNormalMap = false;
  39423. _this._useParallax = false;
  39424. _this._useParallaxOcclusion = false;
  39425. _this.parallaxScaleBias = 0.05;
  39426. _this._roughness = 0;
  39427. _this.indexOfRefraction = 0.98;
  39428. _this.invertRefractionY = true;
  39429. _this._useLightmapAsShadowmap = false;
  39430. _this._useReflectionFresnelFromSpecular = false;
  39431. _this._useGlossinessFromSpecularMapAlpha = false;
  39432. _this._maxSimultaneousLights = 4;
  39433. /**
  39434. * If sets to true, x component of normal map value will invert (x = 1.0 - x).
  39435. */
  39436. _this._invertNormalMapX = false;
  39437. /**
  39438. * If sets to true, y component of normal map value will invert (y = 1.0 - y).
  39439. */
  39440. _this._invertNormalMapY = false;
  39441. /**
  39442. * If sets to true and backfaceCulling is false, normals will be flipped on the backside.
  39443. */
  39444. _this._twoSidedLighting = false;
  39445. _this._renderTargets = new BABYLON.SmartArray(16);
  39446. _this._worldViewProjectionMatrix = BABYLON.Matrix.Zero();
  39447. _this._globalAmbientColor = new BABYLON.Color3(0, 0, 0);
  39448. // Setup the default processing configuration to the scene.
  39449. _this._attachImageProcessingConfiguration(null);
  39450. _this.getRenderTargetTextures = function () {
  39451. _this._renderTargets.reset();
  39452. if (StandardMaterial.ReflectionTextureEnabled && _this._reflectionTexture && _this._reflectionTexture.isRenderTarget) {
  39453. _this._renderTargets.push(_this._reflectionTexture);
  39454. }
  39455. if (StandardMaterial.RefractionTextureEnabled && _this._refractionTexture && _this._refractionTexture.isRenderTarget) {
  39456. _this._renderTargets.push(_this._refractionTexture);
  39457. }
  39458. return _this._renderTargets;
  39459. };
  39460. return _this;
  39461. }
  39462. ;
  39463. ;
  39464. ;
  39465. ;
  39466. ;
  39467. ;
  39468. ;
  39469. ;
  39470. ;
  39471. ;
  39472. ;
  39473. ;
  39474. ;
  39475. ;
  39476. ;
  39477. ;
  39478. ;
  39479. Object.defineProperty(StandardMaterial.prototype, "imageProcessingConfiguration", {
  39480. /**
  39481. * Gets the image processing configuration used either in this material.
  39482. */
  39483. get: function () {
  39484. return this._imageProcessingConfiguration;
  39485. },
  39486. /**
  39487. * Sets the Default image processing configuration used either in the this material.
  39488. *
  39489. * If sets to null, the scene one is in use.
  39490. */
  39491. set: function (value) {
  39492. this._attachImageProcessingConfiguration(value);
  39493. // Ensure the effect will be rebuilt.
  39494. this._markAllSubMeshesAsTexturesDirty();
  39495. },
  39496. enumerable: true,
  39497. configurable: true
  39498. });
  39499. /**
  39500. * Attaches a new image processing configuration to the Standard Material.
  39501. * @param configuration
  39502. */
  39503. StandardMaterial.prototype._attachImageProcessingConfiguration = function (configuration) {
  39504. var _this = this;
  39505. if (configuration === this._imageProcessingConfiguration) {
  39506. return;
  39507. }
  39508. // Detaches observer.
  39509. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  39510. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  39511. }
  39512. // Pick the scene configuration if needed.
  39513. if (!configuration) {
  39514. this._imageProcessingConfiguration = this.getScene().imageProcessingConfiguration;
  39515. }
  39516. else {
  39517. this._imageProcessingConfiguration = configuration;
  39518. }
  39519. // Attaches observer.
  39520. this._imageProcessingObserver = this._imageProcessingConfiguration.onUpdateParameters.add(function (conf) {
  39521. _this._markAllSubMeshesAsImageProcessingDirty();
  39522. });
  39523. };
  39524. Object.defineProperty(StandardMaterial.prototype, "cameraColorCurvesEnabled", {
  39525. /**
  39526. * Gets wether the color curves effect is enabled.
  39527. */
  39528. get: function () {
  39529. return this.imageProcessingConfiguration.colorCurvesEnabled;
  39530. },
  39531. /**
  39532. * Sets wether the color curves effect is enabled.
  39533. */
  39534. set: function (value) {
  39535. this.imageProcessingConfiguration.colorCurvesEnabled = value;
  39536. },
  39537. enumerable: true,
  39538. configurable: true
  39539. });
  39540. Object.defineProperty(StandardMaterial.prototype, "cameraColorGradingEnabled", {
  39541. /**
  39542. * Gets wether the color grading effect is enabled.
  39543. */
  39544. get: function () {
  39545. return this.imageProcessingConfiguration.colorGradingEnabled;
  39546. },
  39547. /**
  39548. * Gets wether the color grading effect is enabled.
  39549. */
  39550. set: function (value) {
  39551. this.imageProcessingConfiguration.colorGradingEnabled = value;
  39552. },
  39553. enumerable: true,
  39554. configurable: true
  39555. });
  39556. Object.defineProperty(StandardMaterial.prototype, "cameraToneMappingEnabled", {
  39557. /**
  39558. * Gets wether tonemapping is enabled or not.
  39559. */
  39560. get: function () {
  39561. return this._imageProcessingConfiguration.toneMappingEnabled;
  39562. },
  39563. /**
  39564. * Sets wether tonemapping is enabled or not
  39565. */
  39566. set: function (value) {
  39567. this._imageProcessingConfiguration.toneMappingEnabled = value;
  39568. },
  39569. enumerable: true,
  39570. configurable: true
  39571. });
  39572. ;
  39573. ;
  39574. Object.defineProperty(StandardMaterial.prototype, "cameraExposure", {
  39575. /**
  39576. * The camera exposure used on this material.
  39577. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  39578. * This corresponds to a photographic exposure.
  39579. */
  39580. get: function () {
  39581. return this._imageProcessingConfiguration.exposure;
  39582. },
  39583. /**
  39584. * The camera exposure used on this material.
  39585. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  39586. * This corresponds to a photographic exposure.
  39587. */
  39588. set: function (value) {
  39589. this._imageProcessingConfiguration.exposure = value;
  39590. },
  39591. enumerable: true,
  39592. configurable: true
  39593. });
  39594. ;
  39595. ;
  39596. Object.defineProperty(StandardMaterial.prototype, "cameraContrast", {
  39597. /**
  39598. * Gets The camera contrast used on this material.
  39599. */
  39600. get: function () {
  39601. return this._imageProcessingConfiguration.contrast;
  39602. },
  39603. /**
  39604. * Sets The camera contrast used on this material.
  39605. */
  39606. set: function (value) {
  39607. this._imageProcessingConfiguration.contrast = value;
  39608. },
  39609. enumerable: true,
  39610. configurable: true
  39611. });
  39612. Object.defineProperty(StandardMaterial.prototype, "cameraColorGradingTexture", {
  39613. /**
  39614. * Gets the Color Grading 2D Lookup Texture.
  39615. */
  39616. get: function () {
  39617. return this._imageProcessingConfiguration.colorGradingTexture;
  39618. },
  39619. /**
  39620. * Sets the Color Grading 2D Lookup Texture.
  39621. */
  39622. set: function (value) {
  39623. this._imageProcessingConfiguration.colorGradingTexture = value;
  39624. },
  39625. enumerable: true,
  39626. configurable: true
  39627. });
  39628. Object.defineProperty(StandardMaterial.prototype, "cameraColorCurves", {
  39629. /**
  39630. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  39631. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  39632. * 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;
  39633. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  39634. */
  39635. get: function () {
  39636. return this._imageProcessingConfiguration.colorCurves;
  39637. },
  39638. /**
  39639. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  39640. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  39641. * 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;
  39642. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  39643. */
  39644. set: function (value) {
  39645. this._imageProcessingConfiguration.colorCurves = value;
  39646. },
  39647. enumerable: true,
  39648. configurable: true
  39649. });
  39650. StandardMaterial.prototype.getClassName = function () {
  39651. return "StandardMaterial";
  39652. };
  39653. Object.defineProperty(StandardMaterial.prototype, "useLogarithmicDepth", {
  39654. get: function () {
  39655. return this._useLogarithmicDepth;
  39656. },
  39657. set: function (value) {
  39658. this._useLogarithmicDepth = value && this.getScene().getEngine().getCaps().fragmentDepthSupported;
  39659. this._markAllSubMeshesAsMiscDirty();
  39660. },
  39661. enumerable: true,
  39662. configurable: true
  39663. });
  39664. StandardMaterial.prototype.needAlphaBlending = function () {
  39665. return (this.alpha < 1.0) || (this._opacityTexture != null) || this._shouldUseAlphaFromDiffuseTexture() || this._opacityFresnelParameters && this._opacityFresnelParameters.isEnabled;
  39666. };
  39667. StandardMaterial.prototype.needAlphaTesting = function () {
  39668. return this._diffuseTexture != null && this._diffuseTexture.hasAlpha;
  39669. };
  39670. StandardMaterial.prototype._shouldUseAlphaFromDiffuseTexture = function () {
  39671. return this._diffuseTexture != null && this._diffuseTexture.hasAlpha && this._useAlphaFromDiffuseTexture;
  39672. };
  39673. StandardMaterial.prototype.getAlphaTestTexture = function () {
  39674. return this._diffuseTexture;
  39675. };
  39676. /**
  39677. * Child classes can use it to update shaders
  39678. */
  39679. StandardMaterial.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  39680. if (useInstances === void 0) { useInstances = false; }
  39681. if (subMesh.effect && this.isFrozen) {
  39682. if (this._wasPreviouslyReady && subMesh.effect) {
  39683. return true;
  39684. }
  39685. }
  39686. if (!subMesh._materialDefines) {
  39687. subMesh._materialDefines = new StandardMaterialDefines();
  39688. }
  39689. var scene = this.getScene();
  39690. var defines = subMesh._materialDefines;
  39691. if (!this.checkReadyOnEveryCall && subMesh.effect) {
  39692. if (defines._renderId === scene.getRenderId()) {
  39693. return true;
  39694. }
  39695. }
  39696. var engine = scene.getEngine();
  39697. // Lights
  39698. defines._needNormals = BABYLON.MaterialHelper.PrepareDefinesForLights(scene, mesh, defines, true, this._maxSimultaneousLights, this._disableLighting);
  39699. // Textures
  39700. if (defines._areTexturesDirty) {
  39701. defines._needUVs = false;
  39702. defines.MAINUV1 = false;
  39703. defines.MAINUV2 = false;
  39704. if (scene.texturesEnabled) {
  39705. if (this._diffuseTexture && StandardMaterial.DiffuseTextureEnabled) {
  39706. if (!this._diffuseTexture.isReadyOrNotBlocking()) {
  39707. return false;
  39708. }
  39709. else {
  39710. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._diffuseTexture, defines, "DIFFUSE");
  39711. }
  39712. }
  39713. else {
  39714. defines.DIFFUSE = false;
  39715. }
  39716. if (this._ambientTexture && StandardMaterial.AmbientTextureEnabled) {
  39717. if (!this._ambientTexture.isReadyOrNotBlocking()) {
  39718. return false;
  39719. }
  39720. else {
  39721. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._ambientTexture, defines, "AMBIENT");
  39722. }
  39723. }
  39724. else {
  39725. defines.AMBIENT = false;
  39726. }
  39727. if (this._opacityTexture && StandardMaterial.OpacityTextureEnabled) {
  39728. if (!this._opacityTexture.isReadyOrNotBlocking()) {
  39729. return false;
  39730. }
  39731. else {
  39732. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._opacityTexture, defines, "OPACITY");
  39733. defines.OPACITYRGB = this._opacityTexture.getAlphaFromRGB;
  39734. }
  39735. }
  39736. else {
  39737. defines.OPACITY = false;
  39738. }
  39739. if (this._reflectionTexture && StandardMaterial.ReflectionTextureEnabled) {
  39740. if (!this._reflectionTexture.isReadyOrNotBlocking()) {
  39741. return false;
  39742. }
  39743. else {
  39744. defines._needNormals = true;
  39745. defines.REFLECTION = true;
  39746. defines.ROUGHNESS = (this._roughness > 0);
  39747. defines.REFLECTIONOVERALPHA = this._useReflectionOverAlpha;
  39748. defines.INVERTCUBICMAP = (this._reflectionTexture.coordinatesMode === BABYLON.Texture.INVCUBIC_MODE);
  39749. defines.REFLECTIONMAP_3D = this._reflectionTexture.isCube;
  39750. switch (this._reflectionTexture.coordinatesMode) {
  39751. case BABYLON.Texture.CUBIC_MODE:
  39752. case BABYLON.Texture.INVCUBIC_MODE:
  39753. defines.setReflectionMode("REFLECTIONMAP_CUBIC");
  39754. break;
  39755. case BABYLON.Texture.EXPLICIT_MODE:
  39756. defines.setReflectionMode("REFLECTIONMAP_EXPLICIT");
  39757. break;
  39758. case BABYLON.Texture.PLANAR_MODE:
  39759. defines.setReflectionMode("REFLECTIONMAP_PLANAR");
  39760. break;
  39761. case BABYLON.Texture.PROJECTION_MODE:
  39762. defines.setReflectionMode("REFLECTIONMAP_PROJECTION");
  39763. break;
  39764. case BABYLON.Texture.SKYBOX_MODE:
  39765. defines.setReflectionMode("REFLECTIONMAP_SKYBOX");
  39766. break;
  39767. case BABYLON.Texture.SPHERICAL_MODE:
  39768. defines.setReflectionMode("REFLECTIONMAP_SPHERICAL");
  39769. break;
  39770. case BABYLON.Texture.EQUIRECTANGULAR_MODE:
  39771. defines.setReflectionMode("REFLECTIONMAP_EQUIRECTANGULAR");
  39772. break;
  39773. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MODE:
  39774. defines.setReflectionMode("REFLECTIONMAP_EQUIRECTANGULAR_FIXED");
  39775. break;
  39776. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE:
  39777. defines.setReflectionMode("REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED");
  39778. break;
  39779. }
  39780. defines.USE_LOCAL_REFLECTIONMAP_CUBIC = this._reflectionTexture.boundingBoxSize ? true : false;
  39781. }
  39782. }
  39783. else {
  39784. defines.REFLECTION = false;
  39785. }
  39786. if (this._emissiveTexture && StandardMaterial.EmissiveTextureEnabled) {
  39787. if (!this._emissiveTexture.isReadyOrNotBlocking()) {
  39788. return false;
  39789. }
  39790. else {
  39791. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._emissiveTexture, defines, "EMISSIVE");
  39792. }
  39793. }
  39794. else {
  39795. defines.EMISSIVE = false;
  39796. }
  39797. if (this._lightmapTexture && StandardMaterial.LightmapTextureEnabled) {
  39798. if (!this._lightmapTexture.isReadyOrNotBlocking()) {
  39799. return false;
  39800. }
  39801. else {
  39802. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._lightmapTexture, defines, "LIGHTMAP");
  39803. defines.USELIGHTMAPASSHADOWMAP = this._useLightmapAsShadowmap;
  39804. }
  39805. }
  39806. else {
  39807. defines.LIGHTMAP = false;
  39808. }
  39809. if (this._specularTexture && StandardMaterial.SpecularTextureEnabled) {
  39810. if (!this._specularTexture.isReadyOrNotBlocking()) {
  39811. return false;
  39812. }
  39813. else {
  39814. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._specularTexture, defines, "SPECULAR");
  39815. defines.GLOSSINESS = this._useGlossinessFromSpecularMapAlpha;
  39816. }
  39817. }
  39818. else {
  39819. defines.SPECULAR = false;
  39820. }
  39821. if (scene.getEngine().getCaps().standardDerivatives && this._bumpTexture && StandardMaterial.BumpTextureEnabled) {
  39822. // Bump texure can not be not blocking.
  39823. if (!this._bumpTexture.isReady()) {
  39824. return false;
  39825. }
  39826. else {
  39827. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._bumpTexture, defines, "BUMP");
  39828. defines.PARALLAX = this._useParallax;
  39829. defines.PARALLAXOCCLUSION = this._useParallaxOcclusion;
  39830. }
  39831. defines.OBJECTSPACE_NORMALMAP = this._useObjectSpaceNormalMap;
  39832. }
  39833. else {
  39834. defines.BUMP = false;
  39835. }
  39836. if (this._refractionTexture && StandardMaterial.RefractionTextureEnabled) {
  39837. if (!this._refractionTexture.isReadyOrNotBlocking()) {
  39838. return false;
  39839. }
  39840. else {
  39841. defines._needUVs = true;
  39842. defines.REFRACTION = true;
  39843. defines.REFRACTIONMAP_3D = this._refractionTexture.isCube;
  39844. }
  39845. }
  39846. else {
  39847. defines.REFRACTION = false;
  39848. }
  39849. defines.TWOSIDEDLIGHTING = !this._backFaceCulling && this._twoSidedLighting;
  39850. }
  39851. else {
  39852. defines.DIFFUSE = false;
  39853. defines.AMBIENT = false;
  39854. defines.OPACITY = false;
  39855. defines.REFLECTION = false;
  39856. defines.EMISSIVE = false;
  39857. defines.LIGHTMAP = false;
  39858. defines.BUMP = false;
  39859. defines.REFRACTION = false;
  39860. }
  39861. defines.ALPHAFROMDIFFUSE = this._shouldUseAlphaFromDiffuseTexture();
  39862. defines.EMISSIVEASILLUMINATION = this._useEmissiveAsIllumination;
  39863. defines.LINKEMISSIVEWITHDIFFUSE = this._linkEmissiveWithDiffuse;
  39864. defines.SPECULAROVERALPHA = this._useSpecularOverAlpha;
  39865. defines.PREMULTIPLYALPHA = (this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED || this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED_PORTERDUFF);
  39866. }
  39867. if (defines._areImageProcessingDirty) {
  39868. if (!this._imageProcessingConfiguration.isReady()) {
  39869. return false;
  39870. }
  39871. this._imageProcessingConfiguration.prepareDefines(defines);
  39872. }
  39873. if (defines._areFresnelDirty) {
  39874. if (StandardMaterial.FresnelEnabled) {
  39875. // Fresnel
  39876. if (this._diffuseFresnelParameters || this._opacityFresnelParameters ||
  39877. this._emissiveFresnelParameters || this._refractionFresnelParameters ||
  39878. this._reflectionFresnelParameters) {
  39879. defines.DIFFUSEFRESNEL = (this._diffuseFresnelParameters && this._diffuseFresnelParameters.isEnabled);
  39880. defines.OPACITYFRESNEL = (this._opacityFresnelParameters && this._opacityFresnelParameters.isEnabled);
  39881. defines.REFLECTIONFRESNEL = (this._reflectionFresnelParameters && this._reflectionFresnelParameters.isEnabled);
  39882. defines.REFLECTIONFRESNELFROMSPECULAR = this._useReflectionFresnelFromSpecular;
  39883. defines.REFRACTIONFRESNEL = (this._refractionFresnelParameters && this._refractionFresnelParameters.isEnabled);
  39884. defines.EMISSIVEFRESNEL = (this._emissiveFresnelParameters && this._emissiveFresnelParameters.isEnabled);
  39885. defines._needNormals = true;
  39886. defines.FRESNEL = true;
  39887. }
  39888. }
  39889. else {
  39890. defines.FRESNEL = false;
  39891. }
  39892. }
  39893. // Misc.
  39894. BABYLON.MaterialHelper.PrepareDefinesForMisc(mesh, scene, this._useLogarithmicDepth, this.pointsCloud, this.fogEnabled, this._shouldTurnAlphaTestOn(mesh), defines);
  39895. // Attribs
  39896. BABYLON.MaterialHelper.PrepareDefinesForAttributes(mesh, defines, true, true, true);
  39897. // Values that need to be evaluated on every frame
  39898. BABYLON.MaterialHelper.PrepareDefinesForFrameBoundValues(scene, engine, defines, useInstances);
  39899. // Get correct effect
  39900. if (defines.isDirty) {
  39901. defines.markAsProcessed();
  39902. scene.resetCachedMaterial();
  39903. // Fallbacks
  39904. var fallbacks = new BABYLON.EffectFallbacks();
  39905. if (defines.REFLECTION) {
  39906. fallbacks.addFallback(0, "REFLECTION");
  39907. }
  39908. if (defines.SPECULAR) {
  39909. fallbacks.addFallback(0, "SPECULAR");
  39910. }
  39911. if (defines.BUMP) {
  39912. fallbacks.addFallback(0, "BUMP");
  39913. }
  39914. if (defines.PARALLAX) {
  39915. fallbacks.addFallback(1, "PARALLAX");
  39916. }
  39917. if (defines.PARALLAXOCCLUSION) {
  39918. fallbacks.addFallback(0, "PARALLAXOCCLUSION");
  39919. }
  39920. if (defines.SPECULAROVERALPHA) {
  39921. fallbacks.addFallback(0, "SPECULAROVERALPHA");
  39922. }
  39923. if (defines.FOG) {
  39924. fallbacks.addFallback(1, "FOG");
  39925. }
  39926. if (defines.POINTSIZE) {
  39927. fallbacks.addFallback(0, "POINTSIZE");
  39928. }
  39929. if (defines.LOGARITHMICDEPTH) {
  39930. fallbacks.addFallback(0, "LOGARITHMICDEPTH");
  39931. }
  39932. BABYLON.MaterialHelper.HandleFallbacksForShadows(defines, fallbacks, this._maxSimultaneousLights);
  39933. if (defines.SPECULARTERM) {
  39934. fallbacks.addFallback(0, "SPECULARTERM");
  39935. }
  39936. if (defines.DIFFUSEFRESNEL) {
  39937. fallbacks.addFallback(1, "DIFFUSEFRESNEL");
  39938. }
  39939. if (defines.OPACITYFRESNEL) {
  39940. fallbacks.addFallback(2, "OPACITYFRESNEL");
  39941. }
  39942. if (defines.REFLECTIONFRESNEL) {
  39943. fallbacks.addFallback(3, "REFLECTIONFRESNEL");
  39944. }
  39945. if (defines.EMISSIVEFRESNEL) {
  39946. fallbacks.addFallback(4, "EMISSIVEFRESNEL");
  39947. }
  39948. if (defines.FRESNEL) {
  39949. fallbacks.addFallback(4, "FRESNEL");
  39950. }
  39951. //Attributes
  39952. var attribs = [BABYLON.VertexBuffer.PositionKind];
  39953. if (defines.NORMAL) {
  39954. attribs.push(BABYLON.VertexBuffer.NormalKind);
  39955. }
  39956. if (defines.UV1) {
  39957. attribs.push(BABYLON.VertexBuffer.UVKind);
  39958. }
  39959. if (defines.UV2) {
  39960. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  39961. }
  39962. if (defines.VERTEXCOLOR) {
  39963. attribs.push(BABYLON.VertexBuffer.ColorKind);
  39964. }
  39965. BABYLON.MaterialHelper.PrepareAttributesForBones(attribs, mesh, defines, fallbacks);
  39966. BABYLON.MaterialHelper.PrepareAttributesForInstances(attribs, defines);
  39967. BABYLON.MaterialHelper.PrepareAttributesForMorphTargets(attribs, mesh, defines);
  39968. var shaderName = "default";
  39969. var uniforms = ["world", "view", "viewProjection", "vEyePosition", "vLightsType", "vAmbientColor", "vDiffuseColor", "vSpecularColor", "vEmissiveColor",
  39970. "vFogInfos", "vFogColor", "pointSize",
  39971. "vDiffuseInfos", "vAmbientInfos", "vOpacityInfos", "vReflectionInfos", "vEmissiveInfos", "vSpecularInfos", "vBumpInfos", "vLightmapInfos", "vRefractionInfos",
  39972. "mBones",
  39973. "vClipPlane", "diffuseMatrix", "ambientMatrix", "opacityMatrix", "reflectionMatrix", "emissiveMatrix", "specularMatrix", "bumpMatrix", "normalMatrix", "lightmapMatrix", "refractionMatrix",
  39974. "diffuseLeftColor", "diffuseRightColor", "opacityParts", "reflectionLeftColor", "reflectionRightColor", "emissiveLeftColor", "emissiveRightColor", "refractionLeftColor", "refractionRightColor",
  39975. "vReflectionPosition", "vReflectionSize",
  39976. "logarithmicDepthConstant", "vTangentSpaceParams"
  39977. ];
  39978. var samplers = ["diffuseSampler", "ambientSampler", "opacitySampler", "reflectionCubeSampler", "reflection2DSampler", "emissiveSampler", "specularSampler", "bumpSampler", "lightmapSampler", "refractionCubeSampler", "refraction2DSampler"];
  39979. var uniformBuffers = ["Material", "Scene"];
  39980. BABYLON.ImageProcessingConfiguration.PrepareUniforms(uniforms, defines);
  39981. BABYLON.ImageProcessingConfiguration.PrepareSamplers(samplers, defines);
  39982. BABYLON.MaterialHelper.PrepareUniformsAndSamplersList({
  39983. uniformsNames: uniforms,
  39984. uniformBuffersNames: uniformBuffers,
  39985. samplers: samplers,
  39986. defines: defines,
  39987. maxSimultaneousLights: this._maxSimultaneousLights
  39988. });
  39989. if (this.customShaderNameResolve) {
  39990. shaderName = this.customShaderNameResolve(shaderName, uniforms, uniformBuffers, samplers, defines);
  39991. }
  39992. var join = defines.toString();
  39993. subMesh.setEffect(scene.getEngine().createEffect(shaderName, {
  39994. attributes: attribs,
  39995. uniformsNames: uniforms,
  39996. uniformBuffersNames: uniformBuffers,
  39997. samplers: samplers,
  39998. defines: join,
  39999. fallbacks: fallbacks,
  40000. onCompiled: this.onCompiled,
  40001. onError: this.onError,
  40002. indexParameters: { maxSimultaneousLights: this._maxSimultaneousLights, maxSimultaneousMorphTargets: defines.NUM_MORPH_INFLUENCERS }
  40003. }, engine), defines);
  40004. this.buildUniformLayout();
  40005. }
  40006. if (!subMesh.effect || !subMesh.effect.isReady()) {
  40007. return false;
  40008. }
  40009. defines._renderId = scene.getRenderId();
  40010. this._wasPreviouslyReady = true;
  40011. return true;
  40012. };
  40013. StandardMaterial.prototype.buildUniformLayout = function () {
  40014. // Order is important !
  40015. this._uniformBuffer.addUniform("diffuseLeftColor", 4);
  40016. this._uniformBuffer.addUniform("diffuseRightColor", 4);
  40017. this._uniformBuffer.addUniform("opacityParts", 4);
  40018. this._uniformBuffer.addUniform("reflectionLeftColor", 4);
  40019. this._uniformBuffer.addUniform("reflectionRightColor", 4);
  40020. this._uniformBuffer.addUniform("refractionLeftColor", 4);
  40021. this._uniformBuffer.addUniform("refractionRightColor", 4);
  40022. this._uniformBuffer.addUniform("emissiveLeftColor", 4);
  40023. this._uniformBuffer.addUniform("emissiveRightColor", 4);
  40024. this._uniformBuffer.addUniform("vDiffuseInfos", 2);
  40025. this._uniformBuffer.addUniform("vAmbientInfos", 2);
  40026. this._uniformBuffer.addUniform("vOpacityInfos", 2);
  40027. this._uniformBuffer.addUniform("vReflectionInfos", 2);
  40028. this._uniformBuffer.addUniform("vReflectionPosition", 3);
  40029. this._uniformBuffer.addUniform("vReflectionSize", 3);
  40030. this._uniformBuffer.addUniform("vEmissiveInfos", 2);
  40031. this._uniformBuffer.addUniform("vLightmapInfos", 2);
  40032. this._uniformBuffer.addUniform("vSpecularInfos", 2);
  40033. this._uniformBuffer.addUniform("vBumpInfos", 3);
  40034. this._uniformBuffer.addUniform("diffuseMatrix", 16);
  40035. this._uniformBuffer.addUniform("ambientMatrix", 16);
  40036. this._uniformBuffer.addUniform("opacityMatrix", 16);
  40037. this._uniformBuffer.addUniform("reflectionMatrix", 16);
  40038. this._uniformBuffer.addUniform("emissiveMatrix", 16);
  40039. this._uniformBuffer.addUniform("lightmapMatrix", 16);
  40040. this._uniformBuffer.addUniform("specularMatrix", 16);
  40041. this._uniformBuffer.addUniform("bumpMatrix", 16);
  40042. this._uniformBuffer.addUniform("vTangentSpaceParams", 2);
  40043. this._uniformBuffer.addUniform("refractionMatrix", 16);
  40044. this._uniformBuffer.addUniform("vRefractionInfos", 4);
  40045. this._uniformBuffer.addUniform("vSpecularColor", 4);
  40046. this._uniformBuffer.addUniform("vEmissiveColor", 3);
  40047. this._uniformBuffer.addUniform("vDiffuseColor", 4);
  40048. this._uniformBuffer.addUniform("pointSize", 1);
  40049. this._uniformBuffer.create();
  40050. };
  40051. StandardMaterial.prototype.unbind = function () {
  40052. if (this._activeEffect) {
  40053. if (this._reflectionTexture && this._reflectionTexture.isRenderTarget) {
  40054. this._activeEffect.setTexture("reflection2DSampler", null);
  40055. }
  40056. if (this._refractionTexture && this._refractionTexture.isRenderTarget) {
  40057. this._activeEffect.setTexture("refraction2DSampler", null);
  40058. }
  40059. }
  40060. _super.prototype.unbind.call(this);
  40061. };
  40062. StandardMaterial.prototype.bindForSubMesh = function (world, mesh, subMesh) {
  40063. var scene = this.getScene();
  40064. var defines = subMesh._materialDefines;
  40065. if (!defines) {
  40066. return;
  40067. }
  40068. var effect = subMesh.effect;
  40069. if (!effect) {
  40070. return;
  40071. }
  40072. this._activeEffect = effect;
  40073. // Matrices
  40074. this.bindOnlyWorldMatrix(world);
  40075. // Normal Matrix
  40076. if (defines.OBJECTSPACE_NORMALMAP) {
  40077. world.toNormalMatrix(this._normalMatrix);
  40078. this.bindOnlyNormalMatrix(this._normalMatrix);
  40079. }
  40080. var mustRebind = this._mustRebind(scene, effect, mesh.visibility);
  40081. // Bones
  40082. BABYLON.MaterialHelper.BindBonesParameters(mesh, effect);
  40083. if (mustRebind) {
  40084. this._uniformBuffer.bindToEffect(effect, "Material");
  40085. this.bindViewProjection(effect);
  40086. if (!this._uniformBuffer.useUbo || !this.isFrozen || !this._uniformBuffer.isSync) {
  40087. if (StandardMaterial.FresnelEnabled && defines.FRESNEL) {
  40088. // Fresnel
  40089. if (this.diffuseFresnelParameters && this.diffuseFresnelParameters.isEnabled) {
  40090. this._uniformBuffer.updateColor4("diffuseLeftColor", this.diffuseFresnelParameters.leftColor, this.diffuseFresnelParameters.power);
  40091. this._uniformBuffer.updateColor4("diffuseRightColor", this.diffuseFresnelParameters.rightColor, this.diffuseFresnelParameters.bias);
  40092. }
  40093. if (this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled) {
  40094. this._uniformBuffer.updateColor4("opacityParts", new BABYLON.Color3(this.opacityFresnelParameters.leftColor.toLuminance(), this.opacityFresnelParameters.rightColor.toLuminance(), this.opacityFresnelParameters.bias), this.opacityFresnelParameters.power);
  40095. }
  40096. if (this.reflectionFresnelParameters && this.reflectionFresnelParameters.isEnabled) {
  40097. this._uniformBuffer.updateColor4("reflectionLeftColor", this.reflectionFresnelParameters.leftColor, this.reflectionFresnelParameters.power);
  40098. this._uniformBuffer.updateColor4("reflectionRightColor", this.reflectionFresnelParameters.rightColor, this.reflectionFresnelParameters.bias);
  40099. }
  40100. if (this.refractionFresnelParameters && this.refractionFresnelParameters.isEnabled) {
  40101. this._uniformBuffer.updateColor4("refractionLeftColor", this.refractionFresnelParameters.leftColor, this.refractionFresnelParameters.power);
  40102. this._uniformBuffer.updateColor4("refractionRightColor", this.refractionFresnelParameters.rightColor, this.refractionFresnelParameters.bias);
  40103. }
  40104. if (this.emissiveFresnelParameters && this.emissiveFresnelParameters.isEnabled) {
  40105. this._uniformBuffer.updateColor4("emissiveLeftColor", this.emissiveFresnelParameters.leftColor, this.emissiveFresnelParameters.power);
  40106. this._uniformBuffer.updateColor4("emissiveRightColor", this.emissiveFresnelParameters.rightColor, this.emissiveFresnelParameters.bias);
  40107. }
  40108. }
  40109. // Textures
  40110. if (scene.texturesEnabled) {
  40111. if (this._diffuseTexture && StandardMaterial.DiffuseTextureEnabled) {
  40112. this._uniformBuffer.updateFloat2("vDiffuseInfos", this._diffuseTexture.coordinatesIndex, this._diffuseTexture.level);
  40113. BABYLON.MaterialHelper.BindTextureMatrix(this._diffuseTexture, this._uniformBuffer, "diffuse");
  40114. }
  40115. if (this._ambientTexture && StandardMaterial.AmbientTextureEnabled) {
  40116. this._uniformBuffer.updateFloat2("vAmbientInfos", this._ambientTexture.coordinatesIndex, this._ambientTexture.level);
  40117. BABYLON.MaterialHelper.BindTextureMatrix(this._ambientTexture, this._uniformBuffer, "ambient");
  40118. }
  40119. if (this._opacityTexture && StandardMaterial.OpacityTextureEnabled) {
  40120. this._uniformBuffer.updateFloat2("vOpacityInfos", this._opacityTexture.coordinatesIndex, this._opacityTexture.level);
  40121. BABYLON.MaterialHelper.BindTextureMatrix(this._opacityTexture, this._uniformBuffer, "opacity");
  40122. }
  40123. if (this._reflectionTexture && StandardMaterial.ReflectionTextureEnabled) {
  40124. this._uniformBuffer.updateFloat2("vReflectionInfos", this._reflectionTexture.level, this.roughness);
  40125. this._uniformBuffer.updateMatrix("reflectionMatrix", this._reflectionTexture.getReflectionTextureMatrix());
  40126. if (this._reflectionTexture.boundingBoxSize) {
  40127. var cubeTexture = this._reflectionTexture;
  40128. this._uniformBuffer.updateVector3("vReflectionPosition", cubeTexture.boundingBoxPosition);
  40129. this._uniformBuffer.updateVector3("vReflectionSize", cubeTexture.boundingBoxSize);
  40130. }
  40131. }
  40132. if (this._emissiveTexture && StandardMaterial.EmissiveTextureEnabled) {
  40133. this._uniformBuffer.updateFloat2("vEmissiveInfos", this._emissiveTexture.coordinatesIndex, this._emissiveTexture.level);
  40134. BABYLON.MaterialHelper.BindTextureMatrix(this._emissiveTexture, this._uniformBuffer, "emissive");
  40135. }
  40136. if (this._lightmapTexture && StandardMaterial.LightmapTextureEnabled) {
  40137. this._uniformBuffer.updateFloat2("vLightmapInfos", this._lightmapTexture.coordinatesIndex, this._lightmapTexture.level);
  40138. BABYLON.MaterialHelper.BindTextureMatrix(this._lightmapTexture, this._uniformBuffer, "lightmap");
  40139. }
  40140. if (this._specularTexture && StandardMaterial.SpecularTextureEnabled) {
  40141. this._uniformBuffer.updateFloat2("vSpecularInfos", this._specularTexture.coordinatesIndex, this._specularTexture.level);
  40142. BABYLON.MaterialHelper.BindTextureMatrix(this._specularTexture, this._uniformBuffer, "specular");
  40143. }
  40144. if (this._bumpTexture && scene.getEngine().getCaps().standardDerivatives && StandardMaterial.BumpTextureEnabled) {
  40145. this._uniformBuffer.updateFloat3("vBumpInfos", this._bumpTexture.coordinatesIndex, 1.0 / this._bumpTexture.level, this.parallaxScaleBias);
  40146. BABYLON.MaterialHelper.BindTextureMatrix(this._bumpTexture, this._uniformBuffer, "bump");
  40147. if (scene._mirroredCameraPosition) {
  40148. this._uniformBuffer.updateFloat2("vTangentSpaceParams", this._invertNormalMapX ? 1.0 : -1.0, this._invertNormalMapY ? 1.0 : -1.0);
  40149. }
  40150. else {
  40151. this._uniformBuffer.updateFloat2("vTangentSpaceParams", this._invertNormalMapX ? -1.0 : 1.0, this._invertNormalMapY ? -1.0 : 1.0);
  40152. }
  40153. }
  40154. if (this._refractionTexture && StandardMaterial.RefractionTextureEnabled) {
  40155. var depth = 1.0;
  40156. if (!this._refractionTexture.isCube) {
  40157. this._uniformBuffer.updateMatrix("refractionMatrix", this._refractionTexture.getReflectionTextureMatrix());
  40158. if (this._refractionTexture.depth) {
  40159. depth = this._refractionTexture.depth;
  40160. }
  40161. }
  40162. this._uniformBuffer.updateFloat4("vRefractionInfos", this._refractionTexture.level, this.indexOfRefraction, depth, this.invertRefractionY ? -1 : 1);
  40163. }
  40164. }
  40165. // Point size
  40166. if (this.pointsCloud) {
  40167. this._uniformBuffer.updateFloat("pointSize", this.pointSize);
  40168. }
  40169. if (defines.SPECULARTERM) {
  40170. this._uniformBuffer.updateColor4("vSpecularColor", this.specularColor, this.specularPower);
  40171. }
  40172. this._uniformBuffer.updateColor3("vEmissiveColor", this.emissiveColor);
  40173. // Diffuse
  40174. this._uniformBuffer.updateColor4("vDiffuseColor", this.diffuseColor, this.alpha * mesh.visibility);
  40175. }
  40176. // Textures
  40177. if (scene.texturesEnabled) {
  40178. if (this._diffuseTexture && StandardMaterial.DiffuseTextureEnabled) {
  40179. effect.setTexture("diffuseSampler", this._diffuseTexture);
  40180. }
  40181. if (this._ambientTexture && StandardMaterial.AmbientTextureEnabled) {
  40182. effect.setTexture("ambientSampler", this._ambientTexture);
  40183. }
  40184. if (this._opacityTexture && StandardMaterial.OpacityTextureEnabled) {
  40185. effect.setTexture("opacitySampler", this._opacityTexture);
  40186. }
  40187. if (this._reflectionTexture && StandardMaterial.ReflectionTextureEnabled) {
  40188. if (this._reflectionTexture.isCube) {
  40189. effect.setTexture("reflectionCubeSampler", this._reflectionTexture);
  40190. }
  40191. else {
  40192. effect.setTexture("reflection2DSampler", this._reflectionTexture);
  40193. }
  40194. }
  40195. if (this._emissiveTexture && StandardMaterial.EmissiveTextureEnabled) {
  40196. effect.setTexture("emissiveSampler", this._emissiveTexture);
  40197. }
  40198. if (this._lightmapTexture && StandardMaterial.LightmapTextureEnabled) {
  40199. effect.setTexture("lightmapSampler", this._lightmapTexture);
  40200. }
  40201. if (this._specularTexture && StandardMaterial.SpecularTextureEnabled) {
  40202. effect.setTexture("specularSampler", this._specularTexture);
  40203. }
  40204. if (this._bumpTexture && scene.getEngine().getCaps().standardDerivatives && StandardMaterial.BumpTextureEnabled) {
  40205. effect.setTexture("bumpSampler", this._bumpTexture);
  40206. }
  40207. if (this._refractionTexture && StandardMaterial.RefractionTextureEnabled) {
  40208. var depth = 1.0;
  40209. if (this._refractionTexture.isCube) {
  40210. effect.setTexture("refractionCubeSampler", this._refractionTexture);
  40211. }
  40212. else {
  40213. effect.setTexture("refraction2DSampler", this._refractionTexture);
  40214. }
  40215. }
  40216. }
  40217. // Clip plane
  40218. BABYLON.MaterialHelper.BindClipPlane(effect, scene);
  40219. // Colors
  40220. scene.ambientColor.multiplyToRef(this.ambientColor, this._globalAmbientColor);
  40221. BABYLON.MaterialHelper.BindEyePosition(effect, scene);
  40222. effect.setColor3("vAmbientColor", this._globalAmbientColor);
  40223. }
  40224. if (mustRebind || !this.isFrozen) {
  40225. // Lights
  40226. if (scene.lightsEnabled && !this._disableLighting) {
  40227. BABYLON.MaterialHelper.BindLights(scene, mesh, effect, defines, this._maxSimultaneousLights);
  40228. }
  40229. // View
  40230. if (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE || this._reflectionTexture || this._refractionTexture) {
  40231. this.bindView(effect);
  40232. }
  40233. // Fog
  40234. BABYLON.MaterialHelper.BindFogParameters(scene, mesh, effect);
  40235. // Morph targets
  40236. if (defines.NUM_MORPH_INFLUENCERS) {
  40237. BABYLON.MaterialHelper.BindMorphTargetParameters(mesh, effect);
  40238. }
  40239. // Log. depth
  40240. BABYLON.MaterialHelper.BindLogDepth(defines, effect, scene);
  40241. // image processing
  40242. if (!this._imageProcessingConfiguration.applyByPostProcess) {
  40243. this._imageProcessingConfiguration.bind(this._activeEffect);
  40244. }
  40245. }
  40246. this._uniformBuffer.update();
  40247. this._afterBind(mesh, this._activeEffect);
  40248. };
  40249. StandardMaterial.prototype.getAnimatables = function () {
  40250. var results = [];
  40251. if (this._diffuseTexture && this._diffuseTexture.animations && this._diffuseTexture.animations.length > 0) {
  40252. results.push(this._diffuseTexture);
  40253. }
  40254. if (this._ambientTexture && this._ambientTexture.animations && this._ambientTexture.animations.length > 0) {
  40255. results.push(this._ambientTexture);
  40256. }
  40257. if (this._opacityTexture && this._opacityTexture.animations && this._opacityTexture.animations.length > 0) {
  40258. results.push(this._opacityTexture);
  40259. }
  40260. if (this._reflectionTexture && this._reflectionTexture.animations && this._reflectionTexture.animations.length > 0) {
  40261. results.push(this._reflectionTexture);
  40262. }
  40263. if (this._emissiveTexture && this._emissiveTexture.animations && this._emissiveTexture.animations.length > 0) {
  40264. results.push(this._emissiveTexture);
  40265. }
  40266. if (this._specularTexture && this._specularTexture.animations && this._specularTexture.animations.length > 0) {
  40267. results.push(this._specularTexture);
  40268. }
  40269. if (this._bumpTexture && this._bumpTexture.animations && this._bumpTexture.animations.length > 0) {
  40270. results.push(this._bumpTexture);
  40271. }
  40272. if (this._lightmapTexture && this._lightmapTexture.animations && this._lightmapTexture.animations.length > 0) {
  40273. results.push(this._lightmapTexture);
  40274. }
  40275. if (this._refractionTexture && this._refractionTexture.animations && this._refractionTexture.animations.length > 0) {
  40276. results.push(this._refractionTexture);
  40277. }
  40278. return results;
  40279. };
  40280. StandardMaterial.prototype.getActiveTextures = function () {
  40281. var activeTextures = _super.prototype.getActiveTextures.call(this);
  40282. if (this._diffuseTexture) {
  40283. activeTextures.push(this._diffuseTexture);
  40284. }
  40285. if (this._ambientTexture) {
  40286. activeTextures.push(this._ambientTexture);
  40287. }
  40288. if (this._opacityTexture) {
  40289. activeTextures.push(this._opacityTexture);
  40290. }
  40291. if (this._reflectionTexture) {
  40292. activeTextures.push(this._reflectionTexture);
  40293. }
  40294. if (this._emissiveTexture) {
  40295. activeTextures.push(this._emissiveTexture);
  40296. }
  40297. if (this._specularTexture) {
  40298. activeTextures.push(this._specularTexture);
  40299. }
  40300. if (this._bumpTexture) {
  40301. activeTextures.push(this._bumpTexture);
  40302. }
  40303. if (this._lightmapTexture) {
  40304. activeTextures.push(this._lightmapTexture);
  40305. }
  40306. if (this._refractionTexture) {
  40307. activeTextures.push(this._refractionTexture);
  40308. }
  40309. return activeTextures;
  40310. };
  40311. StandardMaterial.prototype.hasTexture = function (texture) {
  40312. if (_super.prototype.hasTexture.call(this, texture)) {
  40313. return true;
  40314. }
  40315. if (this._diffuseTexture === texture) {
  40316. return true;
  40317. }
  40318. if (this._ambientTexture === texture) {
  40319. return true;
  40320. }
  40321. if (this._opacityTexture === texture) {
  40322. return true;
  40323. }
  40324. if (this._reflectionTexture === texture) {
  40325. return true;
  40326. }
  40327. if (this._emissiveTexture === texture) {
  40328. return true;
  40329. }
  40330. if (this._specularTexture === texture) {
  40331. return true;
  40332. }
  40333. if (this._bumpTexture === texture) {
  40334. return true;
  40335. }
  40336. if (this._lightmapTexture === texture) {
  40337. return true;
  40338. }
  40339. if (this._refractionTexture === texture) {
  40340. return true;
  40341. }
  40342. return false;
  40343. };
  40344. StandardMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  40345. if (forceDisposeTextures) {
  40346. if (this._diffuseTexture) {
  40347. this._diffuseTexture.dispose();
  40348. }
  40349. if (this._ambientTexture) {
  40350. this._ambientTexture.dispose();
  40351. }
  40352. if (this._opacityTexture) {
  40353. this._opacityTexture.dispose();
  40354. }
  40355. if (this._reflectionTexture) {
  40356. this._reflectionTexture.dispose();
  40357. }
  40358. if (this._emissiveTexture) {
  40359. this._emissiveTexture.dispose();
  40360. }
  40361. if (this._specularTexture) {
  40362. this._specularTexture.dispose();
  40363. }
  40364. if (this._bumpTexture) {
  40365. this._bumpTexture.dispose();
  40366. }
  40367. if (this._lightmapTexture) {
  40368. this._lightmapTexture.dispose();
  40369. }
  40370. if (this._refractionTexture) {
  40371. this._refractionTexture.dispose();
  40372. }
  40373. }
  40374. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  40375. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  40376. }
  40377. _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);
  40378. };
  40379. StandardMaterial.prototype.clone = function (name) {
  40380. var _this = this;
  40381. var result = BABYLON.SerializationHelper.Clone(function () { return new StandardMaterial(name, _this.getScene()); }, this);
  40382. result.name = name;
  40383. result.id = name;
  40384. return result;
  40385. };
  40386. StandardMaterial.prototype.serialize = function () {
  40387. return BABYLON.SerializationHelper.Serialize(this);
  40388. };
  40389. // Statics
  40390. StandardMaterial.Parse = function (source, scene, rootUrl) {
  40391. return BABYLON.SerializationHelper.Parse(function () { return new StandardMaterial(source.name, scene); }, source, scene, rootUrl);
  40392. };
  40393. Object.defineProperty(StandardMaterial, "DiffuseTextureEnabled", {
  40394. get: function () {
  40395. return StandardMaterial._DiffuseTextureEnabled;
  40396. },
  40397. set: function (value) {
  40398. if (StandardMaterial._DiffuseTextureEnabled === value) {
  40399. return;
  40400. }
  40401. StandardMaterial._DiffuseTextureEnabled = value;
  40402. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  40403. },
  40404. enumerable: true,
  40405. configurable: true
  40406. });
  40407. Object.defineProperty(StandardMaterial, "AmbientTextureEnabled", {
  40408. get: function () {
  40409. return StandardMaterial._AmbientTextureEnabled;
  40410. },
  40411. set: function (value) {
  40412. if (StandardMaterial._AmbientTextureEnabled === value) {
  40413. return;
  40414. }
  40415. StandardMaterial._AmbientTextureEnabled = value;
  40416. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  40417. },
  40418. enumerable: true,
  40419. configurable: true
  40420. });
  40421. Object.defineProperty(StandardMaterial, "OpacityTextureEnabled", {
  40422. get: function () {
  40423. return StandardMaterial._OpacityTextureEnabled;
  40424. },
  40425. set: function (value) {
  40426. if (StandardMaterial._OpacityTextureEnabled === value) {
  40427. return;
  40428. }
  40429. StandardMaterial._OpacityTextureEnabled = value;
  40430. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  40431. },
  40432. enumerable: true,
  40433. configurable: true
  40434. });
  40435. Object.defineProperty(StandardMaterial, "ReflectionTextureEnabled", {
  40436. get: function () {
  40437. return StandardMaterial._ReflectionTextureEnabled;
  40438. },
  40439. set: function (value) {
  40440. if (StandardMaterial._ReflectionTextureEnabled === value) {
  40441. return;
  40442. }
  40443. StandardMaterial._ReflectionTextureEnabled = value;
  40444. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  40445. },
  40446. enumerable: true,
  40447. configurable: true
  40448. });
  40449. Object.defineProperty(StandardMaterial, "EmissiveTextureEnabled", {
  40450. get: function () {
  40451. return StandardMaterial._EmissiveTextureEnabled;
  40452. },
  40453. set: function (value) {
  40454. if (StandardMaterial._EmissiveTextureEnabled === value) {
  40455. return;
  40456. }
  40457. StandardMaterial._EmissiveTextureEnabled = value;
  40458. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  40459. },
  40460. enumerable: true,
  40461. configurable: true
  40462. });
  40463. Object.defineProperty(StandardMaterial, "SpecularTextureEnabled", {
  40464. get: function () {
  40465. return StandardMaterial._SpecularTextureEnabled;
  40466. },
  40467. set: function (value) {
  40468. if (StandardMaterial._SpecularTextureEnabled === value) {
  40469. return;
  40470. }
  40471. StandardMaterial._SpecularTextureEnabled = value;
  40472. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  40473. },
  40474. enumerable: true,
  40475. configurable: true
  40476. });
  40477. Object.defineProperty(StandardMaterial, "BumpTextureEnabled", {
  40478. get: function () {
  40479. return StandardMaterial._BumpTextureEnabled;
  40480. },
  40481. set: function (value) {
  40482. if (StandardMaterial._BumpTextureEnabled === value) {
  40483. return;
  40484. }
  40485. StandardMaterial._BumpTextureEnabled = value;
  40486. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  40487. },
  40488. enumerable: true,
  40489. configurable: true
  40490. });
  40491. Object.defineProperty(StandardMaterial, "LightmapTextureEnabled", {
  40492. get: function () {
  40493. return StandardMaterial._LightmapTextureEnabled;
  40494. },
  40495. set: function (value) {
  40496. if (StandardMaterial._LightmapTextureEnabled === value) {
  40497. return;
  40498. }
  40499. StandardMaterial._LightmapTextureEnabled = value;
  40500. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  40501. },
  40502. enumerable: true,
  40503. configurable: true
  40504. });
  40505. Object.defineProperty(StandardMaterial, "RefractionTextureEnabled", {
  40506. get: function () {
  40507. return StandardMaterial._RefractionTextureEnabled;
  40508. },
  40509. set: function (value) {
  40510. if (StandardMaterial._RefractionTextureEnabled === value) {
  40511. return;
  40512. }
  40513. StandardMaterial._RefractionTextureEnabled = value;
  40514. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  40515. },
  40516. enumerable: true,
  40517. configurable: true
  40518. });
  40519. Object.defineProperty(StandardMaterial, "ColorGradingTextureEnabled", {
  40520. get: function () {
  40521. return StandardMaterial._ColorGradingTextureEnabled;
  40522. },
  40523. set: function (value) {
  40524. if (StandardMaterial._ColorGradingTextureEnabled === value) {
  40525. return;
  40526. }
  40527. StandardMaterial._ColorGradingTextureEnabled = value;
  40528. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  40529. },
  40530. enumerable: true,
  40531. configurable: true
  40532. });
  40533. Object.defineProperty(StandardMaterial, "FresnelEnabled", {
  40534. get: function () {
  40535. return StandardMaterial._FresnelEnabled;
  40536. },
  40537. set: function (value) {
  40538. if (StandardMaterial._FresnelEnabled === value) {
  40539. return;
  40540. }
  40541. StandardMaterial._FresnelEnabled = value;
  40542. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.FresnelDirtyFlag);
  40543. },
  40544. enumerable: true,
  40545. configurable: true
  40546. });
  40547. // Flags used to enable or disable a type of texture for all Standard Materials
  40548. StandardMaterial._DiffuseTextureEnabled = true;
  40549. StandardMaterial._AmbientTextureEnabled = true;
  40550. StandardMaterial._OpacityTextureEnabled = true;
  40551. StandardMaterial._ReflectionTextureEnabled = true;
  40552. StandardMaterial._EmissiveTextureEnabled = true;
  40553. StandardMaterial._SpecularTextureEnabled = true;
  40554. StandardMaterial._BumpTextureEnabled = true;
  40555. StandardMaterial._LightmapTextureEnabled = true;
  40556. StandardMaterial._RefractionTextureEnabled = true;
  40557. StandardMaterial._ColorGradingTextureEnabled = true;
  40558. StandardMaterial._FresnelEnabled = true;
  40559. __decorate([
  40560. BABYLON.serializeAsTexture("diffuseTexture")
  40561. ], StandardMaterial.prototype, "_diffuseTexture", void 0);
  40562. __decorate([
  40563. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesAndMiscDirty")
  40564. ], StandardMaterial.prototype, "diffuseTexture", void 0);
  40565. __decorate([
  40566. BABYLON.serializeAsTexture("ambientTexture")
  40567. ], StandardMaterial.prototype, "_ambientTexture", void 0);
  40568. __decorate([
  40569. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  40570. ], StandardMaterial.prototype, "ambientTexture", void 0);
  40571. __decorate([
  40572. BABYLON.serializeAsTexture("opacityTexture")
  40573. ], StandardMaterial.prototype, "_opacityTexture", void 0);
  40574. __decorate([
  40575. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesAndMiscDirty")
  40576. ], StandardMaterial.prototype, "opacityTexture", void 0);
  40577. __decorate([
  40578. BABYLON.serializeAsTexture("reflectionTexture")
  40579. ], StandardMaterial.prototype, "_reflectionTexture", void 0);
  40580. __decorate([
  40581. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  40582. ], StandardMaterial.prototype, "reflectionTexture", void 0);
  40583. __decorate([
  40584. BABYLON.serializeAsTexture("emissiveTexture")
  40585. ], StandardMaterial.prototype, "_emissiveTexture", void 0);
  40586. __decorate([
  40587. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  40588. ], StandardMaterial.prototype, "emissiveTexture", void 0);
  40589. __decorate([
  40590. BABYLON.serializeAsTexture("specularTexture")
  40591. ], StandardMaterial.prototype, "_specularTexture", void 0);
  40592. __decorate([
  40593. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  40594. ], StandardMaterial.prototype, "specularTexture", void 0);
  40595. __decorate([
  40596. BABYLON.serializeAsTexture("bumpTexture")
  40597. ], StandardMaterial.prototype, "_bumpTexture", void 0);
  40598. __decorate([
  40599. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  40600. ], StandardMaterial.prototype, "bumpTexture", void 0);
  40601. __decorate([
  40602. BABYLON.serializeAsTexture("lightmapTexture")
  40603. ], StandardMaterial.prototype, "_lightmapTexture", void 0);
  40604. __decorate([
  40605. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  40606. ], StandardMaterial.prototype, "lightmapTexture", void 0);
  40607. __decorate([
  40608. BABYLON.serializeAsTexture("refractionTexture")
  40609. ], StandardMaterial.prototype, "_refractionTexture", void 0);
  40610. __decorate([
  40611. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  40612. ], StandardMaterial.prototype, "refractionTexture", void 0);
  40613. __decorate([
  40614. BABYLON.serializeAsColor3("ambient")
  40615. ], StandardMaterial.prototype, "ambientColor", void 0);
  40616. __decorate([
  40617. BABYLON.serializeAsColor3("diffuse")
  40618. ], StandardMaterial.prototype, "diffuseColor", void 0);
  40619. __decorate([
  40620. BABYLON.serializeAsColor3("specular")
  40621. ], StandardMaterial.prototype, "specularColor", void 0);
  40622. __decorate([
  40623. BABYLON.serializeAsColor3("emissive")
  40624. ], StandardMaterial.prototype, "emissiveColor", void 0);
  40625. __decorate([
  40626. BABYLON.serialize()
  40627. ], StandardMaterial.prototype, "specularPower", void 0);
  40628. __decorate([
  40629. BABYLON.serialize("useAlphaFromDiffuseTexture")
  40630. ], StandardMaterial.prototype, "_useAlphaFromDiffuseTexture", void 0);
  40631. __decorate([
  40632. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  40633. ], StandardMaterial.prototype, "useAlphaFromDiffuseTexture", void 0);
  40634. __decorate([
  40635. BABYLON.serialize("useEmissiveAsIllumination")
  40636. ], StandardMaterial.prototype, "_useEmissiveAsIllumination", void 0);
  40637. __decorate([
  40638. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  40639. ], StandardMaterial.prototype, "useEmissiveAsIllumination", void 0);
  40640. __decorate([
  40641. BABYLON.serialize("linkEmissiveWithDiffuse")
  40642. ], StandardMaterial.prototype, "_linkEmissiveWithDiffuse", void 0);
  40643. __decorate([
  40644. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  40645. ], StandardMaterial.prototype, "linkEmissiveWithDiffuse", void 0);
  40646. __decorate([
  40647. BABYLON.serialize("useSpecularOverAlpha")
  40648. ], StandardMaterial.prototype, "_useSpecularOverAlpha", void 0);
  40649. __decorate([
  40650. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  40651. ], StandardMaterial.prototype, "useSpecularOverAlpha", void 0);
  40652. __decorate([
  40653. BABYLON.serialize("useReflectionOverAlpha")
  40654. ], StandardMaterial.prototype, "_useReflectionOverAlpha", void 0);
  40655. __decorate([
  40656. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  40657. ], StandardMaterial.prototype, "useReflectionOverAlpha", void 0);
  40658. __decorate([
  40659. BABYLON.serialize("disableLighting")
  40660. ], StandardMaterial.prototype, "_disableLighting", void 0);
  40661. __decorate([
  40662. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  40663. ], StandardMaterial.prototype, "disableLighting", void 0);
  40664. __decorate([
  40665. BABYLON.serialize("useObjectSpaceNormalMap")
  40666. ], StandardMaterial.prototype, "_useObjectSpaceNormalMap", void 0);
  40667. __decorate([
  40668. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  40669. ], StandardMaterial.prototype, "useObjectSpaceNormalMap", void 0);
  40670. __decorate([
  40671. BABYLON.serialize("useParallax")
  40672. ], StandardMaterial.prototype, "_useParallax", void 0);
  40673. __decorate([
  40674. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  40675. ], StandardMaterial.prototype, "useParallax", void 0);
  40676. __decorate([
  40677. BABYLON.serialize("useParallaxOcclusion")
  40678. ], StandardMaterial.prototype, "_useParallaxOcclusion", void 0);
  40679. __decorate([
  40680. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  40681. ], StandardMaterial.prototype, "useParallaxOcclusion", void 0);
  40682. __decorate([
  40683. BABYLON.serialize()
  40684. ], StandardMaterial.prototype, "parallaxScaleBias", void 0);
  40685. __decorate([
  40686. BABYLON.serialize("roughness")
  40687. ], StandardMaterial.prototype, "_roughness", void 0);
  40688. __decorate([
  40689. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  40690. ], StandardMaterial.prototype, "roughness", void 0);
  40691. __decorate([
  40692. BABYLON.serialize()
  40693. ], StandardMaterial.prototype, "indexOfRefraction", void 0);
  40694. __decorate([
  40695. BABYLON.serialize()
  40696. ], StandardMaterial.prototype, "invertRefractionY", void 0);
  40697. __decorate([
  40698. BABYLON.serialize("useLightmapAsShadowmap")
  40699. ], StandardMaterial.prototype, "_useLightmapAsShadowmap", void 0);
  40700. __decorate([
  40701. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  40702. ], StandardMaterial.prototype, "useLightmapAsShadowmap", void 0);
  40703. __decorate([
  40704. BABYLON.serializeAsFresnelParameters("diffuseFresnelParameters")
  40705. ], StandardMaterial.prototype, "_diffuseFresnelParameters", void 0);
  40706. __decorate([
  40707. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  40708. ], StandardMaterial.prototype, "diffuseFresnelParameters", void 0);
  40709. __decorate([
  40710. BABYLON.serializeAsFresnelParameters("opacityFresnelParameters")
  40711. ], StandardMaterial.prototype, "_opacityFresnelParameters", void 0);
  40712. __decorate([
  40713. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelAndMiscDirty")
  40714. ], StandardMaterial.prototype, "opacityFresnelParameters", void 0);
  40715. __decorate([
  40716. BABYLON.serializeAsFresnelParameters("reflectionFresnelParameters")
  40717. ], StandardMaterial.prototype, "_reflectionFresnelParameters", void 0);
  40718. __decorate([
  40719. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  40720. ], StandardMaterial.prototype, "reflectionFresnelParameters", void 0);
  40721. __decorate([
  40722. BABYLON.serializeAsFresnelParameters("refractionFresnelParameters")
  40723. ], StandardMaterial.prototype, "_refractionFresnelParameters", void 0);
  40724. __decorate([
  40725. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  40726. ], StandardMaterial.prototype, "refractionFresnelParameters", void 0);
  40727. __decorate([
  40728. BABYLON.serializeAsFresnelParameters("emissiveFresnelParameters")
  40729. ], StandardMaterial.prototype, "_emissiveFresnelParameters", void 0);
  40730. __decorate([
  40731. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  40732. ], StandardMaterial.prototype, "emissiveFresnelParameters", void 0);
  40733. __decorate([
  40734. BABYLON.serialize("useReflectionFresnelFromSpecular")
  40735. ], StandardMaterial.prototype, "_useReflectionFresnelFromSpecular", void 0);
  40736. __decorate([
  40737. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  40738. ], StandardMaterial.prototype, "useReflectionFresnelFromSpecular", void 0);
  40739. __decorate([
  40740. BABYLON.serialize("useGlossinessFromSpecularMapAlpha")
  40741. ], StandardMaterial.prototype, "_useGlossinessFromSpecularMapAlpha", void 0);
  40742. __decorate([
  40743. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  40744. ], StandardMaterial.prototype, "useGlossinessFromSpecularMapAlpha", void 0);
  40745. __decorate([
  40746. BABYLON.serialize("maxSimultaneousLights")
  40747. ], StandardMaterial.prototype, "_maxSimultaneousLights", void 0);
  40748. __decorate([
  40749. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  40750. ], StandardMaterial.prototype, "maxSimultaneousLights", void 0);
  40751. __decorate([
  40752. BABYLON.serialize("invertNormalMapX")
  40753. ], StandardMaterial.prototype, "_invertNormalMapX", void 0);
  40754. __decorate([
  40755. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  40756. ], StandardMaterial.prototype, "invertNormalMapX", void 0);
  40757. __decorate([
  40758. BABYLON.serialize("invertNormalMapY")
  40759. ], StandardMaterial.prototype, "_invertNormalMapY", void 0);
  40760. __decorate([
  40761. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  40762. ], StandardMaterial.prototype, "invertNormalMapY", void 0);
  40763. __decorate([
  40764. BABYLON.serialize("twoSidedLighting")
  40765. ], StandardMaterial.prototype, "_twoSidedLighting", void 0);
  40766. __decorate([
  40767. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  40768. ], StandardMaterial.prototype, "twoSidedLighting", void 0);
  40769. __decorate([
  40770. BABYLON.serialize()
  40771. ], StandardMaterial.prototype, "useLogarithmicDepth", null);
  40772. return StandardMaterial;
  40773. }(BABYLON.PushMaterial));
  40774. BABYLON.StandardMaterial = StandardMaterial;
  40775. })(BABYLON || (BABYLON = {}));
  40776. //# sourceMappingURL=babylon.standardMaterial.js.map
  40777. "use strict";
  40778. var BABYLON;
  40779. (function (BABYLON) {
  40780. /**
  40781. * Manages the defines for the PBR Material.
  40782. */
  40783. var PBRMaterialDefines = /** @class */ (function (_super) {
  40784. __extends(PBRMaterialDefines, _super);
  40785. /**
  40786. * Initializes the PBR Material defines.
  40787. */
  40788. function PBRMaterialDefines() {
  40789. var _this = _super.call(this) || this;
  40790. _this.PBR = true;
  40791. _this.MAINUV1 = false;
  40792. _this.MAINUV2 = false;
  40793. _this.UV1 = false;
  40794. _this.UV2 = false;
  40795. _this.ALBEDO = false;
  40796. _this.ALBEDODIRECTUV = 0;
  40797. _this.VERTEXCOLOR = false;
  40798. _this.AMBIENT = false;
  40799. _this.AMBIENTDIRECTUV = 0;
  40800. _this.AMBIENTINGRAYSCALE = false;
  40801. _this.OPACITY = false;
  40802. _this.VERTEXALPHA = false;
  40803. _this.OPACITYDIRECTUV = 0;
  40804. _this.OPACITYRGB = false;
  40805. _this.ALPHATEST = false;
  40806. _this.DEPTHPREPASS = false;
  40807. _this.ALPHABLEND = false;
  40808. _this.ALPHAFROMALBEDO = false;
  40809. _this.ALPHATESTVALUE = "0.5";
  40810. _this.SPECULAROVERALPHA = false;
  40811. _this.RADIANCEOVERALPHA = false;
  40812. _this.ALPHAFRESNEL = false;
  40813. _this.LINEARALPHAFRESNEL = false;
  40814. _this.PREMULTIPLYALPHA = false;
  40815. _this.EMISSIVE = false;
  40816. _this.EMISSIVEDIRECTUV = 0;
  40817. _this.REFLECTIVITY = false;
  40818. _this.REFLECTIVITYDIRECTUV = 0;
  40819. _this.SPECULARTERM = false;
  40820. _this.MICROSURFACEFROMREFLECTIVITYMAP = false;
  40821. _this.MICROSURFACEAUTOMATIC = false;
  40822. _this.LODBASEDMICROSFURACE = false;
  40823. _this.MICROSURFACEMAP = false;
  40824. _this.MICROSURFACEMAPDIRECTUV = 0;
  40825. _this.METALLICWORKFLOW = false;
  40826. _this.ROUGHNESSSTOREINMETALMAPALPHA = false;
  40827. _this.ROUGHNESSSTOREINMETALMAPGREEN = false;
  40828. _this.METALLNESSSTOREINMETALMAPBLUE = false;
  40829. _this.AOSTOREINMETALMAPRED = false;
  40830. _this.ENVIRONMENTBRDF = false;
  40831. _this.NORMAL = false;
  40832. _this.TANGENT = false;
  40833. _this.BUMP = false;
  40834. _this.BUMPDIRECTUV = 0;
  40835. _this.OBJECTSPACE_NORMALMAP = false;
  40836. _this.PARALLAX = false;
  40837. _this.PARALLAXOCCLUSION = false;
  40838. _this.NORMALXYSCALE = true;
  40839. _this.LIGHTMAP = false;
  40840. _this.LIGHTMAPDIRECTUV = 0;
  40841. _this.USELIGHTMAPASSHADOWMAP = false;
  40842. _this.GAMMALIGHTMAP = false;
  40843. _this.REFLECTION = false;
  40844. _this.REFLECTIONMAP_3D = false;
  40845. _this.REFLECTIONMAP_SPHERICAL = false;
  40846. _this.REFLECTIONMAP_PLANAR = false;
  40847. _this.REFLECTIONMAP_CUBIC = false;
  40848. _this.USE_LOCAL_REFLECTIONMAP_CUBIC = false;
  40849. _this.REFLECTIONMAP_PROJECTION = false;
  40850. _this.REFLECTIONMAP_SKYBOX = false;
  40851. _this.REFLECTIONMAP_EXPLICIT = false;
  40852. _this.REFLECTIONMAP_EQUIRECTANGULAR = false;
  40853. _this.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  40854. _this.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  40855. _this.INVERTCUBICMAP = false;
  40856. _this.USESPHERICALFROMREFLECTIONMAP = false;
  40857. _this.USESPHERICALINVERTEX = false;
  40858. _this.REFLECTIONMAP_OPPOSITEZ = false;
  40859. _this.LODINREFLECTIONALPHA = false;
  40860. _this.GAMMAREFLECTION = false;
  40861. _this.RADIANCEOCCLUSION = false;
  40862. _this.HORIZONOCCLUSION = false;
  40863. _this.REFRACTION = false;
  40864. _this.REFRACTIONMAP_3D = false;
  40865. _this.REFRACTIONMAP_OPPOSITEZ = false;
  40866. _this.LODINREFRACTIONALPHA = false;
  40867. _this.GAMMAREFRACTION = false;
  40868. _this.LINKREFRACTIONTOTRANSPARENCY = false;
  40869. _this.INSTANCES = false;
  40870. _this.NUM_BONE_INFLUENCERS = 0;
  40871. _this.BonesPerMesh = 0;
  40872. _this.NONUNIFORMSCALING = false;
  40873. _this.MORPHTARGETS = false;
  40874. _this.MORPHTARGETS_NORMAL = false;
  40875. _this.MORPHTARGETS_TANGENT = false;
  40876. _this.NUM_MORPH_INFLUENCERS = 0;
  40877. _this.IMAGEPROCESSING = false;
  40878. _this.VIGNETTE = false;
  40879. _this.VIGNETTEBLENDMODEMULTIPLY = false;
  40880. _this.VIGNETTEBLENDMODEOPAQUE = false;
  40881. _this.TONEMAPPING = false;
  40882. _this.CONTRAST = false;
  40883. _this.COLORCURVES = false;
  40884. _this.COLORGRADING = false;
  40885. _this.COLORGRADING3D = false;
  40886. _this.SAMPLER3DGREENDEPTH = false;
  40887. _this.SAMPLER3DBGRMAP = false;
  40888. _this.IMAGEPROCESSINGPOSTPROCESS = false;
  40889. _this.EXPOSURE = false;
  40890. _this.USEPHYSICALLIGHTFALLOFF = false;
  40891. _this.TWOSIDEDLIGHTING = false;
  40892. _this.SHADOWFLOAT = false;
  40893. _this.CLIPPLANE = false;
  40894. _this.POINTSIZE = false;
  40895. _this.FOG = false;
  40896. _this.LOGARITHMICDEPTH = false;
  40897. _this.FORCENORMALFORWARD = false;
  40898. _this.UNLIT = false;
  40899. _this.rebuild();
  40900. return _this;
  40901. }
  40902. /**
  40903. * Resets the PBR Material defines.
  40904. */
  40905. PBRMaterialDefines.prototype.reset = function () {
  40906. _super.prototype.reset.call(this);
  40907. this.ALPHATESTVALUE = "0.5";
  40908. this.PBR = true;
  40909. };
  40910. return PBRMaterialDefines;
  40911. }(BABYLON.MaterialDefines));
  40912. /**
  40913. * The Physically based material base class of BJS.
  40914. *
  40915. * This offers the main features of a standard PBR material.
  40916. * For more information, please refer to the documentation :
  40917. * http://doc.babylonjs.com/extensions/Physically_Based_Rendering
  40918. */
  40919. var PBRBaseMaterial = /** @class */ (function (_super) {
  40920. __extends(PBRBaseMaterial, _super);
  40921. /**
  40922. * Instantiates a new PBRMaterial instance.
  40923. *
  40924. * @param name The material name
  40925. * @param scene The scene the material will be use in.
  40926. */
  40927. function PBRBaseMaterial(name, scene) {
  40928. var _this = _super.call(this, name, scene) || this;
  40929. /**
  40930. * Intensity of the direct lights e.g. the four lights available in your scene.
  40931. * This impacts both the direct diffuse and specular highlights.
  40932. */
  40933. _this._directIntensity = 1.0;
  40934. /**
  40935. * Intensity of the emissive part of the material.
  40936. * This helps controlling the emissive effect without modifying the emissive color.
  40937. */
  40938. _this._emissiveIntensity = 1.0;
  40939. /**
  40940. * Intensity of the environment e.g. how much the environment will light the object
  40941. * either through harmonics for rough material or through the refelction for shiny ones.
  40942. */
  40943. _this._environmentIntensity = 1.0;
  40944. /**
  40945. * This is a special control allowing the reduction of the specular highlights coming from the
  40946. * four lights of the scene. Those highlights may not be needed in full environment lighting.
  40947. */
  40948. _this._specularIntensity = 1.0;
  40949. /**
  40950. * This stores the direct, emissive, environment, and specular light intensities into a Vector4.
  40951. */
  40952. _this._lightingInfos = new BABYLON.Vector4(_this._directIntensity, _this._emissiveIntensity, _this._environmentIntensity, _this._specularIntensity);
  40953. /**
  40954. * Debug Control allowing disabling the bump map on this material.
  40955. */
  40956. _this._disableBumpMap = false;
  40957. /**
  40958. * AKA Occlusion Texture Intensity in other nomenclature.
  40959. */
  40960. _this._ambientTextureStrength = 1.0;
  40961. /**
  40962. * The color of a material in ambient lighting.
  40963. */
  40964. _this._ambientColor = new BABYLON.Color3(0, 0, 0);
  40965. /**
  40966. * AKA Diffuse Color in other nomenclature.
  40967. */
  40968. _this._albedoColor = new BABYLON.Color3(1, 1, 1);
  40969. /**
  40970. * AKA Specular Color in other nomenclature.
  40971. */
  40972. _this._reflectivityColor = new BABYLON.Color3(1, 1, 1);
  40973. /**
  40974. * The color applied when light is reflected from a material.
  40975. */
  40976. _this._reflectionColor = new BABYLON.Color3(1, 1, 1);
  40977. /**
  40978. * The color applied when light is emitted from a material.
  40979. */
  40980. _this._emissiveColor = new BABYLON.Color3(0, 0, 0);
  40981. /**
  40982. * AKA Glossiness in other nomenclature.
  40983. */
  40984. _this._microSurface = 0.9;
  40985. /**
  40986. * source material index of refraction (IOR)' / 'destination material IOR.
  40987. */
  40988. _this._indexOfRefraction = 0.66;
  40989. /**
  40990. * Controls if refraction needs to be inverted on Y. This could be usefull for procedural texture.
  40991. */
  40992. _this._invertRefractionY = false;
  40993. /**
  40994. * This parameters will make the material used its opacity to control how much it is refracting aginst not.
  40995. * Materials half opaque for instance using refraction could benefit from this control.
  40996. */
  40997. _this._linkRefractionWithTransparency = false;
  40998. /**
  40999. * Specifies that the material will use the light map as a show map.
  41000. */
  41001. _this._useLightmapAsShadowmap = false;
  41002. /**
  41003. * This parameters will enable/disable Horizon occlusion to prevent normal maps to look shiny when the normal
  41004. * makes the reflect vector face the model (under horizon).
  41005. */
  41006. _this._useHorizonOcclusion = true;
  41007. /**
  41008. * This parameters will enable/disable radiance occlusion by preventing the radiance to lit
  41009. * too much the area relying on ambient texture to define their ambient occlusion.
  41010. */
  41011. _this._useRadianceOcclusion = true;
  41012. /**
  41013. * Specifies that the alpha is coming form the albedo channel alpha channel for alpha blending.
  41014. */
  41015. _this._useAlphaFromAlbedoTexture = false;
  41016. /**
  41017. * Specifies that the material will keeps the specular highlights over a transparent surface (only the most limunous ones).
  41018. * A car glass is a good exemple of that. When sun reflects on it you can not see what is behind.
  41019. */
  41020. _this._useSpecularOverAlpha = true;
  41021. /**
  41022. * Specifies if the reflectivity texture contains the glossiness information in its alpha channel.
  41023. */
  41024. _this._useMicroSurfaceFromReflectivityMapAlpha = false;
  41025. /**
  41026. * Specifies if the metallic texture contains the roughness information in its alpha channel.
  41027. */
  41028. _this._useRoughnessFromMetallicTextureAlpha = true;
  41029. /**
  41030. * Specifies if the metallic texture contains the roughness information in its green channel.
  41031. */
  41032. _this._useRoughnessFromMetallicTextureGreen = false;
  41033. /**
  41034. * Specifies if the metallic texture contains the metallness information in its blue channel.
  41035. */
  41036. _this._useMetallnessFromMetallicTextureBlue = false;
  41037. /**
  41038. * Specifies if the metallic texture contains the ambient occlusion information in its red channel.
  41039. */
  41040. _this._useAmbientOcclusionFromMetallicTextureRed = false;
  41041. /**
  41042. * Specifies if the ambient texture contains the ambient occlusion information in its red channel only.
  41043. */
  41044. _this._useAmbientInGrayScale = false;
  41045. /**
  41046. * In case the reflectivity map does not contain the microsurface information in its alpha channel,
  41047. * The material will try to infer what glossiness each pixel should be.
  41048. */
  41049. _this._useAutoMicroSurfaceFromReflectivityMap = false;
  41050. /**
  41051. * BJS is using an harcoded light falloff based on a manually sets up range.
  41052. * In PBR, one way to represents the fallof is to use the inverse squared root algorythm.
  41053. * This parameter can help you switch back to the BJS mode in order to create scenes using both materials.
  41054. */
  41055. _this._usePhysicalLightFalloff = true;
  41056. /**
  41057. * Specifies that the material will keeps the reflection highlights over a transparent surface (only the most limunous ones).
  41058. * A car glass is a good exemple of that. When the street lights reflects on it you can not see what is behind.
  41059. */
  41060. _this._useRadianceOverAlpha = true;
  41061. /**
  41062. * Allows using an object space normal map (instead of tangent space).
  41063. */
  41064. _this._useObjectSpaceNormalMap = false;
  41065. /**
  41066. * Allows using the bump map in parallax mode.
  41067. */
  41068. _this._useParallax = false;
  41069. /**
  41070. * Allows using the bump map in parallax occlusion mode.
  41071. */
  41072. _this._useParallaxOcclusion = false;
  41073. /**
  41074. * Controls the scale bias of the parallax mode.
  41075. */
  41076. _this._parallaxScaleBias = 0.05;
  41077. /**
  41078. * If sets to true, disables all the lights affecting the material.
  41079. */
  41080. _this._disableLighting = false;
  41081. /**
  41082. * Number of Simultaneous lights allowed on the material.
  41083. */
  41084. _this._maxSimultaneousLights = 4;
  41085. /**
  41086. * If sets to true, x component of normal map value will be inverted (x = 1.0 - x).
  41087. */
  41088. _this._invertNormalMapX = false;
  41089. /**
  41090. * If sets to true, y component of normal map value will be inverted (y = 1.0 - y).
  41091. */
  41092. _this._invertNormalMapY = false;
  41093. /**
  41094. * If sets to true and backfaceCulling is false, normals will be flipped on the backside.
  41095. */
  41096. _this._twoSidedLighting = false;
  41097. /**
  41098. * Defines the alpha limits in alpha test mode.
  41099. */
  41100. _this._alphaCutOff = 0.4;
  41101. /**
  41102. * Enforces alpha test in opaque or blend mode in order to improve the performances of some situations.
  41103. */
  41104. _this._forceAlphaTest = false;
  41105. /**
  41106. * A fresnel is applied to the alpha of the model to ensure grazing angles edges are not alpha tested.
  41107. * And/Or occlude the blended part. (alpha is converted to gamma to compute the fresnel)
  41108. */
  41109. _this._useAlphaFresnel = false;
  41110. /**
  41111. * A fresnel is applied to the alpha of the model to ensure grazing angles edges are not alpha tested.
  41112. * And/Or occlude the blended part. (alpha stays linear to compute the fresnel)
  41113. */
  41114. _this._useLinearAlphaFresnel = false;
  41115. /**
  41116. * The transparency mode of the material.
  41117. */
  41118. _this._transparencyMode = null;
  41119. /**
  41120. * Specifies the environment BRDF texture used to comput the scale and offset roughness values
  41121. * from cos thetav and roughness:
  41122. * http://blog.selfshadow.com/publications/s2013-shading-course/karis/s2013_pbs_epic_notes_v2.pdf
  41123. */
  41124. _this._environmentBRDFTexture = null;
  41125. /**
  41126. * Force the shader to compute irradiance in the fragment shader in order to take bump in account.
  41127. */
  41128. _this._forceIrradianceInFragment = false;
  41129. /**
  41130. * Force normal to face away from face.
  41131. */
  41132. _this._forceNormalForward = false;
  41133. /**
  41134. * Stores the available render targets.
  41135. */
  41136. _this._renderTargets = new BABYLON.SmartArray(16);
  41137. /**
  41138. * Sets the global ambient color for the material used in lighting calculations.
  41139. */
  41140. _this._globalAmbientColor = new BABYLON.Color3(0, 0, 0);
  41141. /**
  41142. * If set to true, no lighting calculations will be applied.
  41143. */
  41144. _this._unlit = false;
  41145. // Setup the default processing configuration to the scene.
  41146. _this._attachImageProcessingConfiguration(null);
  41147. _this.getRenderTargetTextures = function () {
  41148. _this._renderTargets.reset();
  41149. if (BABYLON.StandardMaterial.ReflectionTextureEnabled && _this._reflectionTexture && _this._reflectionTexture.isRenderTarget) {
  41150. _this._renderTargets.push(_this._reflectionTexture);
  41151. }
  41152. if (BABYLON.StandardMaterial.RefractionTextureEnabled && _this._refractionTexture && _this._refractionTexture.isRenderTarget) {
  41153. _this._renderTargets.push(_this._refractionTexture);
  41154. }
  41155. return _this._renderTargets;
  41156. };
  41157. _this._environmentBRDFTexture = BABYLON.TextureTools.GetEnvironmentBRDFTexture(scene);
  41158. return _this;
  41159. }
  41160. /**
  41161. * Attaches a new image processing configuration to the PBR Material.
  41162. * @param configuration
  41163. */
  41164. PBRBaseMaterial.prototype._attachImageProcessingConfiguration = function (configuration) {
  41165. var _this = this;
  41166. if (configuration === this._imageProcessingConfiguration) {
  41167. return;
  41168. }
  41169. // Detaches observer.
  41170. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  41171. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  41172. }
  41173. // Pick the scene configuration if needed.
  41174. if (!configuration) {
  41175. this._imageProcessingConfiguration = this.getScene().imageProcessingConfiguration;
  41176. }
  41177. else {
  41178. this._imageProcessingConfiguration = configuration;
  41179. }
  41180. // Attaches observer.
  41181. this._imageProcessingObserver = this._imageProcessingConfiguration.onUpdateParameters.add(function (conf) {
  41182. _this._markAllSubMeshesAsImageProcessingDirty();
  41183. });
  41184. };
  41185. /**
  41186. * Gets the name of the material class.
  41187. */
  41188. PBRBaseMaterial.prototype.getClassName = function () {
  41189. return "PBRBaseMaterial";
  41190. };
  41191. Object.defineProperty(PBRBaseMaterial.prototype, "useLogarithmicDepth", {
  41192. /**
  41193. * Enabled the use of logarithmic depth buffers, which is good for wide depth buffers.
  41194. */
  41195. get: function () {
  41196. return this._useLogarithmicDepth;
  41197. },
  41198. /**
  41199. * Enabled the use of logarithmic depth buffers, which is good for wide depth buffers.
  41200. */
  41201. set: function (value) {
  41202. this._useLogarithmicDepth = value && this.getScene().getEngine().getCaps().fragmentDepthSupported;
  41203. },
  41204. enumerable: true,
  41205. configurable: true
  41206. });
  41207. Object.defineProperty(PBRBaseMaterial.prototype, "transparencyMode", {
  41208. /**
  41209. * Gets the current transparency mode.
  41210. */
  41211. get: function () {
  41212. return this._transparencyMode;
  41213. },
  41214. /**
  41215. * Sets the transparency mode of the material.
  41216. */
  41217. set: function (value) {
  41218. if (this._transparencyMode === value) {
  41219. return;
  41220. }
  41221. this._transparencyMode = value;
  41222. this._forceAlphaTest = (value === BABYLON.PBRMaterial.PBRMATERIAL_ALPHATESTANDBLEND);
  41223. this._markAllSubMeshesAsTexturesAndMiscDirty();
  41224. },
  41225. enumerable: true,
  41226. configurable: true
  41227. });
  41228. Object.defineProperty(PBRBaseMaterial.prototype, "_disableAlphaBlending", {
  41229. /**
  41230. * Returns true if alpha blending should be disabled.
  41231. */
  41232. get: function () {
  41233. return (this._linkRefractionWithTransparency ||
  41234. this._transparencyMode === BABYLON.PBRMaterial.PBRMATERIAL_OPAQUE ||
  41235. this._transparencyMode === BABYLON.PBRMaterial.PBRMATERIAL_ALPHATEST);
  41236. },
  41237. enumerable: true,
  41238. configurable: true
  41239. });
  41240. /**
  41241. * Specifies whether or not this material should be rendered in alpha blend mode.
  41242. */
  41243. PBRBaseMaterial.prototype.needAlphaBlending = function () {
  41244. if (this._disableAlphaBlending) {
  41245. return false;
  41246. }
  41247. return (this.alpha < 1.0) || (this._opacityTexture != null) || this._shouldUseAlphaFromAlbedoTexture();
  41248. };
  41249. /**
  41250. * Specifies if the mesh will require alpha blending.
  41251. * @param mesh - BJS mesh.
  41252. */
  41253. PBRBaseMaterial.prototype.needAlphaBlendingForMesh = function (mesh) {
  41254. if (this._disableAlphaBlending) {
  41255. return false;
  41256. }
  41257. return _super.prototype.needAlphaBlendingForMesh.call(this, mesh);
  41258. };
  41259. /**
  41260. * Specifies whether or not this material should be rendered in alpha test mode.
  41261. */
  41262. PBRBaseMaterial.prototype.needAlphaTesting = function () {
  41263. if (this._forceAlphaTest) {
  41264. return true;
  41265. }
  41266. if (this._linkRefractionWithTransparency) {
  41267. return false;
  41268. }
  41269. return this._albedoTexture != null && this._albedoTexture.hasAlpha && (this._transparencyMode == null || this._transparencyMode === BABYLON.PBRMaterial.PBRMATERIAL_ALPHATEST);
  41270. };
  41271. /**
  41272. * Specifies whether or not the alpha value of the albedo texture should be used for alpha blending.
  41273. */
  41274. PBRBaseMaterial.prototype._shouldUseAlphaFromAlbedoTexture = function () {
  41275. return this._albedoTexture != null && this._albedoTexture.hasAlpha && this._useAlphaFromAlbedoTexture && this._transparencyMode !== BABYLON.PBRMaterial.PBRMATERIAL_OPAQUE;
  41276. };
  41277. /**
  41278. * Gets the texture used for the alpha test.
  41279. */
  41280. PBRBaseMaterial.prototype.getAlphaTestTexture = function () {
  41281. return this._albedoTexture;
  41282. };
  41283. /**
  41284. * Specifies that the submesh is ready to be used.
  41285. * @param mesh - BJS mesh.
  41286. * @param subMesh - A submesh of the BJS mesh. Used to check if it is ready.
  41287. * @param useInstances - Specifies that instances should be used.
  41288. * @returns - boolean indicating that the submesh is ready or not.
  41289. */
  41290. PBRBaseMaterial.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  41291. if (subMesh.effect && this.isFrozen) {
  41292. if (this._wasPreviouslyReady) {
  41293. return true;
  41294. }
  41295. }
  41296. if (!subMesh._materialDefines) {
  41297. subMesh._materialDefines = new PBRMaterialDefines();
  41298. }
  41299. var defines = subMesh._materialDefines;
  41300. if (!this.checkReadyOnEveryCall && subMesh.effect) {
  41301. if (defines._renderId === this.getScene().getRenderId()) {
  41302. return true;
  41303. }
  41304. }
  41305. var scene = this.getScene();
  41306. var engine = scene.getEngine();
  41307. if (defines._areTexturesDirty) {
  41308. if (scene.texturesEnabled) {
  41309. if (this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  41310. if (!this._albedoTexture.isReadyOrNotBlocking()) {
  41311. return false;
  41312. }
  41313. }
  41314. if (this._ambientTexture && BABYLON.StandardMaterial.AmbientTextureEnabled) {
  41315. if (!this._ambientTexture.isReadyOrNotBlocking()) {
  41316. return false;
  41317. }
  41318. }
  41319. if (this._opacityTexture && BABYLON.StandardMaterial.OpacityTextureEnabled) {
  41320. if (!this._opacityTexture.isReadyOrNotBlocking()) {
  41321. return false;
  41322. }
  41323. }
  41324. var reflectionTexture = this._getReflectionTexture();
  41325. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  41326. if (!reflectionTexture.isReadyOrNotBlocking()) {
  41327. return false;
  41328. }
  41329. }
  41330. if (this._lightmapTexture && BABYLON.StandardMaterial.LightmapTextureEnabled) {
  41331. if (!this._lightmapTexture.isReadyOrNotBlocking()) {
  41332. return false;
  41333. }
  41334. }
  41335. if (this._emissiveTexture && BABYLON.StandardMaterial.EmissiveTextureEnabled) {
  41336. if (!this._emissiveTexture.isReadyOrNotBlocking()) {
  41337. return false;
  41338. }
  41339. }
  41340. if (BABYLON.StandardMaterial.SpecularTextureEnabled) {
  41341. if (this._metallicTexture) {
  41342. if (!this._metallicTexture.isReadyOrNotBlocking()) {
  41343. return false;
  41344. }
  41345. }
  41346. else if (this._reflectivityTexture) {
  41347. if (!this._reflectivityTexture.isReadyOrNotBlocking()) {
  41348. return false;
  41349. }
  41350. }
  41351. if (this._microSurfaceTexture) {
  41352. if (!this._microSurfaceTexture.isReadyOrNotBlocking()) {
  41353. return false;
  41354. }
  41355. }
  41356. }
  41357. if (engine.getCaps().standardDerivatives && this._bumpTexture && BABYLON.StandardMaterial.BumpTextureEnabled && !this._disableBumpMap) {
  41358. // Bump texture cannot be not blocking.
  41359. if (!this._bumpTexture.isReady()) {
  41360. return false;
  41361. }
  41362. }
  41363. var refractionTexture = this._getRefractionTexture();
  41364. if (refractionTexture && BABYLON.StandardMaterial.RefractionTextureEnabled) {
  41365. if (!refractionTexture.isReadyOrNotBlocking()) {
  41366. return false;
  41367. }
  41368. }
  41369. if (this._environmentBRDFTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  41370. // This is blocking.
  41371. if (!this._environmentBRDFTexture.isReady()) {
  41372. return false;
  41373. }
  41374. }
  41375. }
  41376. }
  41377. if (defines._areImageProcessingDirty) {
  41378. if (!this._imageProcessingConfiguration.isReady()) {
  41379. return false;
  41380. }
  41381. }
  41382. if (!engine.getCaps().standardDerivatives && !mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  41383. mesh.createNormals(true);
  41384. BABYLON.Tools.Warn("PBRMaterial: Normals have been created for the mesh: " + mesh.name);
  41385. }
  41386. var effect = this._prepareEffect(mesh, defines, this.onCompiled, this.onError, useInstances);
  41387. if (effect) {
  41388. scene.resetCachedMaterial();
  41389. subMesh.setEffect(effect, defines);
  41390. this.buildUniformLayout();
  41391. }
  41392. if (!subMesh.effect || !subMesh.effect.isReady()) {
  41393. return false;
  41394. }
  41395. defines._renderId = scene.getRenderId();
  41396. this._wasPreviouslyReady = true;
  41397. return true;
  41398. };
  41399. /**
  41400. * Specifies if the material uses metallic roughness workflow.
  41401. * @returns boolean specifiying if the material uses metallic roughness workflow.
  41402. */
  41403. PBRBaseMaterial.prototype.isMetallicWorkflow = function () {
  41404. if (this._metallic != null || this._roughness != null || this._metallicTexture) {
  41405. return true;
  41406. }
  41407. return false;
  41408. };
  41409. PBRBaseMaterial.prototype._prepareEffect = function (mesh, defines, onCompiled, onError, useInstances, useClipPlane) {
  41410. if (onCompiled === void 0) { onCompiled = null; }
  41411. if (onError === void 0) { onError = null; }
  41412. if (useInstances === void 0) { useInstances = null; }
  41413. if (useClipPlane === void 0) { useClipPlane = null; }
  41414. this._prepareDefines(mesh, defines, useInstances, useClipPlane);
  41415. if (!defines.isDirty) {
  41416. return null;
  41417. }
  41418. defines.markAsProcessed();
  41419. var scene = this.getScene();
  41420. var engine = scene.getEngine();
  41421. // Fallbacks
  41422. var fallbacks = new BABYLON.EffectFallbacks();
  41423. var fallbackRank = 0;
  41424. if (defines.USESPHERICALINVERTEX) {
  41425. fallbacks.addFallback(fallbackRank++, "USESPHERICALINVERTEX");
  41426. }
  41427. if (defines.FOG) {
  41428. fallbacks.addFallback(fallbackRank, "FOG");
  41429. }
  41430. if (defines.POINTSIZE) {
  41431. fallbacks.addFallback(fallbackRank, "POINTSIZE");
  41432. }
  41433. if (defines.LOGARITHMICDEPTH) {
  41434. fallbacks.addFallback(fallbackRank, "LOGARITHMICDEPTH");
  41435. }
  41436. if (defines.PARALLAX) {
  41437. fallbacks.addFallback(fallbackRank, "PARALLAX");
  41438. }
  41439. if (defines.PARALLAXOCCLUSION) {
  41440. fallbacks.addFallback(fallbackRank++, "PARALLAXOCCLUSION");
  41441. }
  41442. if (defines.ENVIRONMENTBRDF) {
  41443. fallbacks.addFallback(fallbackRank++, "ENVIRONMENTBRDF");
  41444. }
  41445. if (defines.TANGENT) {
  41446. fallbacks.addFallback(fallbackRank++, "TANGENT");
  41447. }
  41448. if (defines.BUMP) {
  41449. fallbacks.addFallback(fallbackRank++, "BUMP");
  41450. }
  41451. fallbackRank = BABYLON.MaterialHelper.HandleFallbacksForShadows(defines, fallbacks, this._maxSimultaneousLights, fallbackRank++);
  41452. if (defines.SPECULARTERM) {
  41453. fallbacks.addFallback(fallbackRank++, "SPECULARTERM");
  41454. }
  41455. if (defines.USESPHERICALFROMREFLECTIONMAP) {
  41456. fallbacks.addFallback(fallbackRank++, "USESPHERICALFROMREFLECTIONMAP");
  41457. }
  41458. if (defines.LIGHTMAP) {
  41459. fallbacks.addFallback(fallbackRank++, "LIGHTMAP");
  41460. }
  41461. if (defines.NORMAL) {
  41462. fallbacks.addFallback(fallbackRank++, "NORMAL");
  41463. }
  41464. if (defines.AMBIENT) {
  41465. fallbacks.addFallback(fallbackRank++, "AMBIENT");
  41466. }
  41467. if (defines.EMISSIVE) {
  41468. fallbacks.addFallback(fallbackRank++, "EMISSIVE");
  41469. }
  41470. if (defines.VERTEXCOLOR) {
  41471. fallbacks.addFallback(fallbackRank++, "VERTEXCOLOR");
  41472. }
  41473. if (defines.NUM_BONE_INFLUENCERS > 0) {
  41474. fallbacks.addCPUSkinningFallback(fallbackRank++, mesh);
  41475. }
  41476. if (defines.MORPHTARGETS) {
  41477. fallbacks.addFallback(fallbackRank++, "MORPHTARGETS");
  41478. }
  41479. //Attributes
  41480. var attribs = [BABYLON.VertexBuffer.PositionKind];
  41481. if (defines.NORMAL) {
  41482. attribs.push(BABYLON.VertexBuffer.NormalKind);
  41483. }
  41484. if (defines.TANGENT) {
  41485. attribs.push(BABYLON.VertexBuffer.TangentKind);
  41486. }
  41487. if (defines.UV1) {
  41488. attribs.push(BABYLON.VertexBuffer.UVKind);
  41489. }
  41490. if (defines.UV2) {
  41491. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  41492. }
  41493. if (defines.VERTEXCOLOR) {
  41494. attribs.push(BABYLON.VertexBuffer.ColorKind);
  41495. }
  41496. BABYLON.MaterialHelper.PrepareAttributesForBones(attribs, mesh, defines, fallbacks);
  41497. BABYLON.MaterialHelper.PrepareAttributesForInstances(attribs, defines);
  41498. BABYLON.MaterialHelper.PrepareAttributesForMorphTargets(attribs, mesh, defines);
  41499. var uniforms = ["world", "view", "viewProjection", "vEyePosition", "vLightsType", "vAmbientColor", "vAlbedoColor", "vReflectivityColor", "vEmissiveColor", "vReflectionColor",
  41500. "vFogInfos", "vFogColor", "pointSize",
  41501. "vAlbedoInfos", "vAmbientInfos", "vOpacityInfos", "vReflectionInfos", "vReflectionPosition", "vReflectionSize", "vEmissiveInfos", "vReflectivityInfos",
  41502. "vMicroSurfaceSamplerInfos", "vBumpInfos", "vLightmapInfos", "vRefractionInfos",
  41503. "mBones",
  41504. "vClipPlane", "albedoMatrix", "ambientMatrix", "opacityMatrix", "reflectionMatrix", "emissiveMatrix", "reflectivityMatrix", "normalMatrix", "microSurfaceSamplerMatrix", "bumpMatrix", "lightmapMatrix", "refractionMatrix",
  41505. "vLightingIntensity",
  41506. "logarithmicDepthConstant",
  41507. "vSphericalX", "vSphericalY", "vSphericalZ",
  41508. "vSphericalXX", "vSphericalYY", "vSphericalZZ",
  41509. "vSphericalXY", "vSphericalYZ", "vSphericalZX",
  41510. "vReflectionMicrosurfaceInfos", "vRefractionMicrosurfaceInfos",
  41511. "vTangentSpaceParams"
  41512. ];
  41513. var samplers = ["albedoSampler", "reflectivitySampler", "ambientSampler", "emissiveSampler",
  41514. "bumpSampler", "lightmapSampler", "opacitySampler",
  41515. "refractionSampler", "refractionSamplerLow", "refractionSamplerHigh",
  41516. "reflectionSampler", "reflectionSamplerLow", "reflectionSamplerHigh",
  41517. "microSurfaceSampler", "environmentBrdfSampler"];
  41518. var uniformBuffers = ["Material", "Scene"];
  41519. BABYLON.ImageProcessingConfiguration.PrepareUniforms(uniforms, defines);
  41520. BABYLON.ImageProcessingConfiguration.PrepareSamplers(samplers, defines);
  41521. BABYLON.MaterialHelper.PrepareUniformsAndSamplersList({
  41522. uniformsNames: uniforms,
  41523. uniformBuffersNames: uniformBuffers,
  41524. samplers: samplers,
  41525. defines: defines,
  41526. maxSimultaneousLights: this._maxSimultaneousLights
  41527. });
  41528. var join = defines.toString();
  41529. return engine.createEffect("pbr", {
  41530. attributes: attribs,
  41531. uniformsNames: uniforms,
  41532. uniformBuffersNames: uniformBuffers,
  41533. samplers: samplers,
  41534. defines: join,
  41535. fallbacks: fallbacks,
  41536. onCompiled: onCompiled,
  41537. onError: onError,
  41538. indexParameters: { maxSimultaneousLights: this._maxSimultaneousLights, maxSimultaneousMorphTargets: defines.NUM_MORPH_INFLUENCERS }
  41539. }, engine);
  41540. };
  41541. PBRBaseMaterial.prototype._prepareDefines = function (mesh, defines, useInstances, useClipPlane) {
  41542. if (useInstances === void 0) { useInstances = null; }
  41543. if (useClipPlane === void 0) { useClipPlane = null; }
  41544. var scene = this.getScene();
  41545. var engine = scene.getEngine();
  41546. // Lights
  41547. BABYLON.MaterialHelper.PrepareDefinesForLights(scene, mesh, defines, true, this._maxSimultaneousLights, this._disableLighting);
  41548. defines._needNormals = true;
  41549. // Textures
  41550. defines.METALLICWORKFLOW = this.isMetallicWorkflow();
  41551. if (defines._areTexturesDirty) {
  41552. defines._needUVs = false;
  41553. if (scene.texturesEnabled) {
  41554. if (scene.getEngine().getCaps().textureLOD) {
  41555. defines.LODBASEDMICROSFURACE = true;
  41556. }
  41557. if (this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  41558. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._albedoTexture, defines, "ALBEDO");
  41559. }
  41560. else {
  41561. defines.ALBEDO = false;
  41562. }
  41563. if (this._ambientTexture && BABYLON.StandardMaterial.AmbientTextureEnabled) {
  41564. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._ambientTexture, defines, "AMBIENT");
  41565. defines.AMBIENTINGRAYSCALE = this._useAmbientInGrayScale;
  41566. }
  41567. else {
  41568. defines.AMBIENT = false;
  41569. }
  41570. if (this._opacityTexture && BABYLON.StandardMaterial.OpacityTextureEnabled) {
  41571. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._opacityTexture, defines, "OPACITY");
  41572. defines.OPACITYRGB = this._opacityTexture.getAlphaFromRGB;
  41573. }
  41574. else {
  41575. defines.OPACITY = false;
  41576. }
  41577. var reflectionTexture = this._getReflectionTexture();
  41578. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  41579. defines.REFLECTION = true;
  41580. defines.GAMMAREFLECTION = reflectionTexture.gammaSpace;
  41581. defines.REFLECTIONMAP_OPPOSITEZ = this.getScene().useRightHandedSystem ? !reflectionTexture.invertZ : reflectionTexture.invertZ;
  41582. defines.LODINREFLECTIONALPHA = reflectionTexture.lodLevelInAlpha;
  41583. if (reflectionTexture.coordinatesMode === BABYLON.Texture.INVCUBIC_MODE) {
  41584. defines.INVERTCUBICMAP = true;
  41585. }
  41586. defines.REFLECTIONMAP_3D = reflectionTexture.isCube;
  41587. switch (reflectionTexture.coordinatesMode) {
  41588. case BABYLON.Texture.CUBIC_MODE:
  41589. case BABYLON.Texture.INVCUBIC_MODE:
  41590. defines.REFLECTIONMAP_CUBIC = true;
  41591. defines.USE_LOCAL_REFLECTIONMAP_CUBIC = reflectionTexture.boundingBoxSize ? true : false;
  41592. break;
  41593. case BABYLON.Texture.EXPLICIT_MODE:
  41594. defines.REFLECTIONMAP_EXPLICIT = true;
  41595. break;
  41596. case BABYLON.Texture.PLANAR_MODE:
  41597. defines.REFLECTIONMAP_PLANAR = true;
  41598. break;
  41599. case BABYLON.Texture.PROJECTION_MODE:
  41600. defines.REFLECTIONMAP_PROJECTION = true;
  41601. break;
  41602. case BABYLON.Texture.SKYBOX_MODE:
  41603. defines.REFLECTIONMAP_SKYBOX = true;
  41604. break;
  41605. case BABYLON.Texture.SPHERICAL_MODE:
  41606. defines.REFLECTIONMAP_SPHERICAL = true;
  41607. break;
  41608. case BABYLON.Texture.EQUIRECTANGULAR_MODE:
  41609. defines.REFLECTIONMAP_EQUIRECTANGULAR = true;
  41610. break;
  41611. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MODE:
  41612. defines.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = true;
  41613. break;
  41614. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE:
  41615. defines.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = true;
  41616. break;
  41617. }
  41618. if (reflectionTexture.coordinatesMode !== BABYLON.Texture.SKYBOX_MODE) {
  41619. if (reflectionTexture.sphericalPolynomial) {
  41620. defines.USESPHERICALFROMREFLECTIONMAP = true;
  41621. if (this._forceIrradianceInFragment || scene.getEngine().getCaps().maxVaryingVectors <= 8) {
  41622. defines.USESPHERICALINVERTEX = false;
  41623. }
  41624. else {
  41625. defines.USESPHERICALINVERTEX = true;
  41626. }
  41627. }
  41628. }
  41629. }
  41630. else {
  41631. defines.REFLECTION = false;
  41632. defines.REFLECTIONMAP_3D = false;
  41633. defines.REFLECTIONMAP_SPHERICAL = false;
  41634. defines.REFLECTIONMAP_PLANAR = false;
  41635. defines.REFLECTIONMAP_CUBIC = false;
  41636. defines.USE_LOCAL_REFLECTIONMAP_CUBIC = false;
  41637. defines.REFLECTIONMAP_PROJECTION = false;
  41638. defines.REFLECTIONMAP_SKYBOX = false;
  41639. defines.REFLECTIONMAP_EXPLICIT = false;
  41640. defines.REFLECTIONMAP_EQUIRECTANGULAR = false;
  41641. defines.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  41642. defines.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  41643. defines.INVERTCUBICMAP = false;
  41644. defines.USESPHERICALFROMREFLECTIONMAP = false;
  41645. defines.USESPHERICALINVERTEX = false;
  41646. defines.REFLECTIONMAP_OPPOSITEZ = false;
  41647. defines.LODINREFLECTIONALPHA = false;
  41648. defines.GAMMAREFLECTION = false;
  41649. }
  41650. if (this._lightmapTexture && BABYLON.StandardMaterial.LightmapTextureEnabled) {
  41651. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._lightmapTexture, defines, "LIGHTMAP");
  41652. defines.USELIGHTMAPASSHADOWMAP = this._useLightmapAsShadowmap;
  41653. defines.GAMMALIGHTMAP = this._lightmapTexture.gammaSpace;
  41654. }
  41655. else {
  41656. defines.LIGHTMAP = false;
  41657. }
  41658. if (this._emissiveTexture && BABYLON.StandardMaterial.EmissiveTextureEnabled) {
  41659. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._emissiveTexture, defines, "EMISSIVE");
  41660. }
  41661. else {
  41662. defines.EMISSIVE = false;
  41663. }
  41664. if (BABYLON.StandardMaterial.SpecularTextureEnabled) {
  41665. if (this._metallicTexture) {
  41666. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._metallicTexture, defines, "REFLECTIVITY");
  41667. defines.ROUGHNESSSTOREINMETALMAPALPHA = this._useRoughnessFromMetallicTextureAlpha;
  41668. defines.ROUGHNESSSTOREINMETALMAPGREEN = !this._useRoughnessFromMetallicTextureAlpha && this._useRoughnessFromMetallicTextureGreen;
  41669. defines.METALLNESSSTOREINMETALMAPBLUE = this._useMetallnessFromMetallicTextureBlue;
  41670. defines.AOSTOREINMETALMAPRED = this._useAmbientOcclusionFromMetallicTextureRed;
  41671. }
  41672. else if (this._reflectivityTexture) {
  41673. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._reflectivityTexture, defines, "REFLECTIVITY");
  41674. defines.MICROSURFACEFROMREFLECTIVITYMAP = this._useMicroSurfaceFromReflectivityMapAlpha;
  41675. defines.MICROSURFACEAUTOMATIC = this._useAutoMicroSurfaceFromReflectivityMap;
  41676. }
  41677. else {
  41678. defines.REFLECTIVITY = false;
  41679. }
  41680. if (this._microSurfaceTexture) {
  41681. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._microSurfaceTexture, defines, "MICROSURFACEMAP");
  41682. }
  41683. else {
  41684. defines.MICROSURFACEMAP = false;
  41685. }
  41686. }
  41687. else {
  41688. defines.REFLECTIVITY = false;
  41689. defines.MICROSURFACEMAP = false;
  41690. }
  41691. if (scene.getEngine().getCaps().standardDerivatives && this._bumpTexture && BABYLON.StandardMaterial.BumpTextureEnabled && !this._disableBumpMap) {
  41692. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._bumpTexture, defines, "BUMP");
  41693. if (this._useParallax && this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  41694. defines.PARALLAX = true;
  41695. defines.PARALLAXOCCLUSION = !!this._useParallaxOcclusion;
  41696. }
  41697. else {
  41698. defines.PARALLAX = false;
  41699. }
  41700. defines.OBJECTSPACE_NORMALMAP = this._useObjectSpaceNormalMap;
  41701. }
  41702. else {
  41703. defines.BUMP = false;
  41704. }
  41705. var refractionTexture = this._getRefractionTexture();
  41706. if (refractionTexture && BABYLON.StandardMaterial.RefractionTextureEnabled) {
  41707. defines.REFRACTION = true;
  41708. defines.REFRACTIONMAP_3D = refractionTexture.isCube;
  41709. defines.GAMMAREFRACTION = refractionTexture.gammaSpace;
  41710. defines.REFRACTIONMAP_OPPOSITEZ = refractionTexture.invertZ;
  41711. defines.LODINREFRACTIONALPHA = refractionTexture.lodLevelInAlpha;
  41712. if (this._linkRefractionWithTransparency) {
  41713. defines.LINKREFRACTIONTOTRANSPARENCY = true;
  41714. }
  41715. }
  41716. else {
  41717. defines.REFRACTION = false;
  41718. }
  41719. if (this._environmentBRDFTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  41720. defines.ENVIRONMENTBRDF = true;
  41721. }
  41722. else {
  41723. defines.ENVIRONMENTBRDF = false;
  41724. }
  41725. if (this._shouldUseAlphaFromAlbedoTexture()) {
  41726. defines.ALPHAFROMALBEDO = true;
  41727. }
  41728. else {
  41729. defines.ALPHAFROMALBEDO = false;
  41730. }
  41731. }
  41732. defines.SPECULAROVERALPHA = this._useSpecularOverAlpha;
  41733. defines.USEPHYSICALLIGHTFALLOFF = this._usePhysicalLightFalloff;
  41734. defines.RADIANCEOVERALPHA = this._useRadianceOverAlpha;
  41735. if (!this.backFaceCulling && this._twoSidedLighting) {
  41736. defines.TWOSIDEDLIGHTING = true;
  41737. }
  41738. else {
  41739. defines.TWOSIDEDLIGHTING = false;
  41740. }
  41741. defines.ALPHATESTVALUE = "" + this._alphaCutOff + (this._alphaCutOff % 1 === 0 ? "." : "");
  41742. defines.PREMULTIPLYALPHA = (this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED || this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED_PORTERDUFF);
  41743. defines.ALPHABLEND = this.needAlphaBlendingForMesh(mesh);
  41744. defines.ALPHAFRESNEL = this._useAlphaFresnel || this._useLinearAlphaFresnel;
  41745. defines.LINEARALPHAFRESNEL = this._useLinearAlphaFresnel;
  41746. }
  41747. if (defines._areImageProcessingDirty) {
  41748. this._imageProcessingConfiguration.prepareDefines(defines);
  41749. }
  41750. defines.FORCENORMALFORWARD = this._forceNormalForward;
  41751. defines.RADIANCEOCCLUSION = this._useRadianceOcclusion;
  41752. defines.HORIZONOCCLUSION = this._useHorizonOcclusion;
  41753. // Misc.
  41754. if (defines._areMiscDirty) {
  41755. BABYLON.MaterialHelper.PrepareDefinesForMisc(mesh, scene, this._useLogarithmicDepth, this.pointsCloud, this.fogEnabled, this._shouldTurnAlphaTestOn(mesh) || this._forceAlphaTest, defines);
  41756. defines.UNLIT = this._unlit || ((this.pointsCloud || this.wireframe) && !mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind));
  41757. }
  41758. // Values that need to be evaluated on every frame
  41759. BABYLON.MaterialHelper.PrepareDefinesForFrameBoundValues(scene, engine, defines, useInstances ? true : false, useClipPlane);
  41760. // Attribs
  41761. BABYLON.MaterialHelper.PrepareDefinesForAttributes(mesh, defines, true, true, true, this._transparencyMode !== BABYLON.PBRMaterial.PBRMATERIAL_OPAQUE);
  41762. };
  41763. /**
  41764. * Force shader compilation
  41765. */
  41766. PBRBaseMaterial.prototype.forceCompilation = function (mesh, onCompiled, options) {
  41767. var _this = this;
  41768. var localOptions = __assign({ clipPlane: false }, options);
  41769. var defines = new PBRMaterialDefines();
  41770. var effect = this._prepareEffect(mesh, defines, undefined, undefined, undefined, localOptions.clipPlane);
  41771. if (effect.isReady()) {
  41772. if (onCompiled) {
  41773. onCompiled(this);
  41774. }
  41775. }
  41776. else {
  41777. effect.onCompileObservable.add(function () {
  41778. if (onCompiled) {
  41779. onCompiled(_this);
  41780. }
  41781. });
  41782. }
  41783. };
  41784. /**
  41785. * Initializes the uniform buffer layout for the shader.
  41786. */
  41787. PBRBaseMaterial.prototype.buildUniformLayout = function () {
  41788. // Order is important !
  41789. this._uniformBuffer.addUniform("vAlbedoInfos", 2);
  41790. this._uniformBuffer.addUniform("vAmbientInfos", 3);
  41791. this._uniformBuffer.addUniform("vOpacityInfos", 2);
  41792. this._uniformBuffer.addUniform("vEmissiveInfos", 2);
  41793. this._uniformBuffer.addUniform("vLightmapInfos", 2);
  41794. this._uniformBuffer.addUniform("vReflectivityInfos", 3);
  41795. this._uniformBuffer.addUniform("vMicroSurfaceSamplerInfos", 2);
  41796. this._uniformBuffer.addUniform("vRefractionInfos", 4);
  41797. this._uniformBuffer.addUniform("vReflectionInfos", 2);
  41798. this._uniformBuffer.addUniform("vReflectionPosition", 3);
  41799. this._uniformBuffer.addUniform("vReflectionSize", 3);
  41800. this._uniformBuffer.addUniform("vBumpInfos", 3);
  41801. this._uniformBuffer.addUniform("albedoMatrix", 16);
  41802. this._uniformBuffer.addUniform("ambientMatrix", 16);
  41803. this._uniformBuffer.addUniform("opacityMatrix", 16);
  41804. this._uniformBuffer.addUniform("emissiveMatrix", 16);
  41805. this._uniformBuffer.addUniform("lightmapMatrix", 16);
  41806. this._uniformBuffer.addUniform("reflectivityMatrix", 16);
  41807. this._uniformBuffer.addUniform("microSurfaceSamplerMatrix", 16);
  41808. this._uniformBuffer.addUniform("bumpMatrix", 16);
  41809. this._uniformBuffer.addUniform("vTangentSpaceParams", 2);
  41810. this._uniformBuffer.addUniform("refractionMatrix", 16);
  41811. this._uniformBuffer.addUniform("reflectionMatrix", 16);
  41812. this._uniformBuffer.addUniform("vReflectionColor", 3);
  41813. this._uniformBuffer.addUniform("vAlbedoColor", 4);
  41814. this._uniformBuffer.addUniform("vLightingIntensity", 4);
  41815. this._uniformBuffer.addUniform("vRefractionMicrosurfaceInfos", 3);
  41816. this._uniformBuffer.addUniform("vReflectionMicrosurfaceInfos", 3);
  41817. this._uniformBuffer.addUniform("vReflectivityColor", 4);
  41818. this._uniformBuffer.addUniform("vEmissiveColor", 3);
  41819. this._uniformBuffer.addUniform("pointSize", 1);
  41820. this._uniformBuffer.create();
  41821. };
  41822. /**
  41823. * Unbinds the textures.
  41824. */
  41825. PBRBaseMaterial.prototype.unbind = function () {
  41826. if (this._reflectionTexture && this._reflectionTexture.isRenderTarget) {
  41827. this._uniformBuffer.setTexture("reflectionSampler", null);
  41828. }
  41829. if (this._refractionTexture && this._refractionTexture.isRenderTarget) {
  41830. this._uniformBuffer.setTexture("refractionSampler", null);
  41831. }
  41832. _super.prototype.unbind.call(this);
  41833. };
  41834. /**
  41835. * Binds the submesh data.
  41836. * @param world - The world matrix.
  41837. * @param mesh - The BJS mesh.
  41838. * @param subMesh - A submesh of the BJS mesh.
  41839. */
  41840. PBRBaseMaterial.prototype.bindForSubMesh = function (world, mesh, subMesh) {
  41841. var scene = this.getScene();
  41842. var defines = subMesh._materialDefines;
  41843. if (!defines) {
  41844. return;
  41845. }
  41846. var effect = subMesh.effect;
  41847. if (!effect) {
  41848. return;
  41849. }
  41850. this._activeEffect = effect;
  41851. // Matrices
  41852. this.bindOnlyWorldMatrix(world);
  41853. // Normal Matrix
  41854. if (defines.OBJECTSPACE_NORMALMAP) {
  41855. world.toNormalMatrix(this._normalMatrix);
  41856. this.bindOnlyNormalMatrix(this._normalMatrix);
  41857. }
  41858. var mustRebind = this._mustRebind(scene, effect, mesh.visibility);
  41859. // Bones
  41860. BABYLON.MaterialHelper.BindBonesParameters(mesh, this._activeEffect);
  41861. var reflectionTexture = null;
  41862. if (mustRebind) {
  41863. this._uniformBuffer.bindToEffect(effect, "Material");
  41864. this.bindViewProjection(effect);
  41865. reflectionTexture = this._getReflectionTexture();
  41866. var refractionTexture = this._getRefractionTexture();
  41867. if (!this._uniformBuffer.useUbo || !this.isFrozen || !this._uniformBuffer.isSync) {
  41868. // Texture uniforms
  41869. if (scene.texturesEnabled) {
  41870. if (this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  41871. this._uniformBuffer.updateFloat2("vAlbedoInfos", this._albedoTexture.coordinatesIndex, this._albedoTexture.level);
  41872. BABYLON.MaterialHelper.BindTextureMatrix(this._albedoTexture, this._uniformBuffer, "albedo");
  41873. }
  41874. if (this._ambientTexture && BABYLON.StandardMaterial.AmbientTextureEnabled) {
  41875. this._uniformBuffer.updateFloat3("vAmbientInfos", this._ambientTexture.coordinatesIndex, this._ambientTexture.level, this._ambientTextureStrength);
  41876. BABYLON.MaterialHelper.BindTextureMatrix(this._ambientTexture, this._uniformBuffer, "ambient");
  41877. }
  41878. if (this._opacityTexture && BABYLON.StandardMaterial.OpacityTextureEnabled) {
  41879. this._uniformBuffer.updateFloat2("vOpacityInfos", this._opacityTexture.coordinatesIndex, this._opacityTexture.level);
  41880. BABYLON.MaterialHelper.BindTextureMatrix(this._opacityTexture, this._uniformBuffer, "opacity");
  41881. }
  41882. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  41883. this._uniformBuffer.updateMatrix("reflectionMatrix", reflectionTexture.getReflectionTextureMatrix());
  41884. this._uniformBuffer.updateFloat2("vReflectionInfos", reflectionTexture.level, 0);
  41885. if (reflectionTexture.boundingBoxSize) {
  41886. var cubeTexture = reflectionTexture;
  41887. this._uniformBuffer.updateVector3("vReflectionPosition", cubeTexture.boundingBoxPosition);
  41888. this._uniformBuffer.updateVector3("vReflectionSize", cubeTexture.boundingBoxSize);
  41889. }
  41890. var polynomials = reflectionTexture.sphericalPolynomial;
  41891. if (defines.USESPHERICALFROMREFLECTIONMAP && polynomials) {
  41892. this._activeEffect.setFloat3("vSphericalX", polynomials.x.x, polynomials.x.y, polynomials.x.z);
  41893. this._activeEffect.setFloat3("vSphericalY", polynomials.y.x, polynomials.y.y, polynomials.y.z);
  41894. this._activeEffect.setFloat3("vSphericalZ", polynomials.z.x, polynomials.z.y, polynomials.z.z);
  41895. this._activeEffect.setFloat3("vSphericalXX_ZZ", polynomials.xx.x - polynomials.zz.x, polynomials.xx.y - polynomials.zz.y, polynomials.xx.z - polynomials.zz.z);
  41896. this._activeEffect.setFloat3("vSphericalYY_ZZ", polynomials.yy.x - polynomials.zz.x, polynomials.yy.y - polynomials.zz.y, polynomials.yy.z - polynomials.zz.z);
  41897. this._activeEffect.setFloat3("vSphericalZZ", polynomials.zz.x, polynomials.zz.y, polynomials.zz.z);
  41898. this._activeEffect.setFloat3("vSphericalXY", polynomials.xy.x, polynomials.xy.y, polynomials.xy.z);
  41899. this._activeEffect.setFloat3("vSphericalYZ", polynomials.yz.x, polynomials.yz.y, polynomials.yz.z);
  41900. this._activeEffect.setFloat3("vSphericalZX", polynomials.zx.x, polynomials.zx.y, polynomials.zx.z);
  41901. }
  41902. this._uniformBuffer.updateFloat3("vReflectionMicrosurfaceInfos", reflectionTexture.getSize().width, reflectionTexture.lodGenerationScale, reflectionTexture.lodGenerationOffset);
  41903. }
  41904. if (this._emissiveTexture && BABYLON.StandardMaterial.EmissiveTextureEnabled) {
  41905. this._uniformBuffer.updateFloat2("vEmissiveInfos", this._emissiveTexture.coordinatesIndex, this._emissiveTexture.level);
  41906. BABYLON.MaterialHelper.BindTextureMatrix(this._emissiveTexture, this._uniformBuffer, "emissive");
  41907. }
  41908. if (this._lightmapTexture && BABYLON.StandardMaterial.LightmapTextureEnabled) {
  41909. this._uniformBuffer.updateFloat2("vLightmapInfos", this._lightmapTexture.coordinatesIndex, this._lightmapTexture.level);
  41910. BABYLON.MaterialHelper.BindTextureMatrix(this._lightmapTexture, this._uniformBuffer, "lightmap");
  41911. }
  41912. if (BABYLON.StandardMaterial.SpecularTextureEnabled) {
  41913. if (this._metallicTexture) {
  41914. this._uniformBuffer.updateFloat3("vReflectivityInfos", this._metallicTexture.coordinatesIndex, this._metallicTexture.level, this._ambientTextureStrength);
  41915. BABYLON.MaterialHelper.BindTextureMatrix(this._metallicTexture, this._uniformBuffer, "reflectivity");
  41916. }
  41917. else if (this._reflectivityTexture) {
  41918. this._uniformBuffer.updateFloat3("vReflectivityInfos", this._reflectivityTexture.coordinatesIndex, this._reflectivityTexture.level, 1.0);
  41919. BABYLON.MaterialHelper.BindTextureMatrix(this._reflectivityTexture, this._uniformBuffer, "reflectivity");
  41920. }
  41921. if (this._microSurfaceTexture) {
  41922. this._uniformBuffer.updateFloat2("vMicroSurfaceSamplerInfos", this._microSurfaceTexture.coordinatesIndex, this._microSurfaceTexture.level);
  41923. BABYLON.MaterialHelper.BindTextureMatrix(this._microSurfaceTexture, this._uniformBuffer, "microSurfaceSampler");
  41924. }
  41925. }
  41926. if (this._bumpTexture && scene.getEngine().getCaps().standardDerivatives && BABYLON.StandardMaterial.BumpTextureEnabled && !this._disableBumpMap) {
  41927. this._uniformBuffer.updateFloat3("vBumpInfos", this._bumpTexture.coordinatesIndex, this._bumpTexture.level, this._parallaxScaleBias);
  41928. BABYLON.MaterialHelper.BindTextureMatrix(this._bumpTexture, this._uniformBuffer, "bump");
  41929. if (scene._mirroredCameraPosition) {
  41930. this._uniformBuffer.updateFloat2("vTangentSpaceParams", this._invertNormalMapX ? 1.0 : -1.0, this._invertNormalMapY ? 1.0 : -1.0);
  41931. }
  41932. else {
  41933. this._uniformBuffer.updateFloat2("vTangentSpaceParams", this._invertNormalMapX ? -1.0 : 1.0, this._invertNormalMapY ? -1.0 : 1.0);
  41934. }
  41935. }
  41936. if (refractionTexture && BABYLON.StandardMaterial.RefractionTextureEnabled) {
  41937. this._uniformBuffer.updateMatrix("refractionMatrix", refractionTexture.getReflectionTextureMatrix());
  41938. var depth = 1.0;
  41939. if (!refractionTexture.isCube) {
  41940. if (refractionTexture.depth) {
  41941. depth = refractionTexture.depth;
  41942. }
  41943. }
  41944. this._uniformBuffer.updateFloat4("vRefractionInfos", refractionTexture.level, this._indexOfRefraction, depth, this._invertRefractionY ? -1 : 1);
  41945. this._uniformBuffer.updateFloat3("vRefractionMicrosurfaceInfos", refractionTexture.getSize().width, refractionTexture.lodGenerationScale, refractionTexture.lodGenerationOffset);
  41946. }
  41947. }
  41948. // Point size
  41949. if (this.pointsCloud) {
  41950. this._uniformBuffer.updateFloat("pointSize", this.pointSize);
  41951. }
  41952. // Colors
  41953. if (defines.METALLICWORKFLOW) {
  41954. BABYLON.PBRMaterial._scaledReflectivity.r = (this._metallic === undefined || this._metallic === null) ? 1 : this._metallic;
  41955. BABYLON.PBRMaterial._scaledReflectivity.g = (this._roughness === undefined || this._roughness === null) ? 1 : this._roughness;
  41956. this._uniformBuffer.updateColor4("vReflectivityColor", BABYLON.PBRMaterial._scaledReflectivity, 0);
  41957. }
  41958. else {
  41959. this._uniformBuffer.updateColor4("vReflectivityColor", this._reflectivityColor, this._microSurface);
  41960. }
  41961. this._uniformBuffer.updateColor3("vEmissiveColor", this._emissiveColor);
  41962. this._uniformBuffer.updateColor3("vReflectionColor", this._reflectionColor);
  41963. this._uniformBuffer.updateColor4("vAlbedoColor", this._albedoColor, this.alpha * mesh.visibility);
  41964. // Misc
  41965. this._lightingInfos.x = this._directIntensity;
  41966. this._lightingInfos.y = this._emissiveIntensity;
  41967. this._lightingInfos.z = this._environmentIntensity;
  41968. this._lightingInfos.w = this._specularIntensity;
  41969. this._uniformBuffer.updateVector4("vLightingIntensity", this._lightingInfos);
  41970. }
  41971. // Textures
  41972. if (scene.texturesEnabled) {
  41973. if (this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  41974. this._uniformBuffer.setTexture("albedoSampler", this._albedoTexture);
  41975. }
  41976. if (this._ambientTexture && BABYLON.StandardMaterial.AmbientTextureEnabled) {
  41977. this._uniformBuffer.setTexture("ambientSampler", this._ambientTexture);
  41978. }
  41979. if (this._opacityTexture && BABYLON.StandardMaterial.OpacityTextureEnabled) {
  41980. this._uniformBuffer.setTexture("opacitySampler", this._opacityTexture);
  41981. }
  41982. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  41983. if (defines.LODBASEDMICROSFURACE) {
  41984. this._uniformBuffer.setTexture("reflectionSampler", reflectionTexture);
  41985. }
  41986. else {
  41987. this._uniformBuffer.setTexture("reflectionSampler", reflectionTexture._lodTextureMid || reflectionTexture);
  41988. this._uniformBuffer.setTexture("reflectionSamplerLow", reflectionTexture._lodTextureLow || reflectionTexture);
  41989. this._uniformBuffer.setTexture("reflectionSamplerHigh", reflectionTexture._lodTextureHigh || reflectionTexture);
  41990. }
  41991. }
  41992. if (defines.ENVIRONMENTBRDF) {
  41993. this._uniformBuffer.setTexture("environmentBrdfSampler", this._environmentBRDFTexture);
  41994. }
  41995. if (refractionTexture && BABYLON.StandardMaterial.RefractionTextureEnabled) {
  41996. if (defines.LODBASEDMICROSFURACE) {
  41997. this._uniformBuffer.setTexture("refractionSampler", refractionTexture);
  41998. }
  41999. else {
  42000. this._uniformBuffer.setTexture("refractionSampler", refractionTexture._lodTextureMid || refractionTexture);
  42001. this._uniformBuffer.setTexture("refractionSamplerLow", refractionTexture._lodTextureLow || refractionTexture);
  42002. this._uniformBuffer.setTexture("refractionSamplerHigh", refractionTexture._lodTextureHigh || refractionTexture);
  42003. }
  42004. }
  42005. if (this._emissiveTexture && BABYLON.StandardMaterial.EmissiveTextureEnabled) {
  42006. this._uniformBuffer.setTexture("emissiveSampler", this._emissiveTexture);
  42007. }
  42008. if (this._lightmapTexture && BABYLON.StandardMaterial.LightmapTextureEnabled) {
  42009. this._uniformBuffer.setTexture("lightmapSampler", this._lightmapTexture);
  42010. }
  42011. if (BABYLON.StandardMaterial.SpecularTextureEnabled) {
  42012. if (this._metallicTexture) {
  42013. this._uniformBuffer.setTexture("reflectivitySampler", this._metallicTexture);
  42014. }
  42015. else if (this._reflectivityTexture) {
  42016. this._uniformBuffer.setTexture("reflectivitySampler", this._reflectivityTexture);
  42017. }
  42018. if (this._microSurfaceTexture) {
  42019. this._uniformBuffer.setTexture("microSurfaceSampler", this._microSurfaceTexture);
  42020. }
  42021. }
  42022. if (this._bumpTexture && scene.getEngine().getCaps().standardDerivatives && BABYLON.StandardMaterial.BumpTextureEnabled && !this._disableBumpMap) {
  42023. this._uniformBuffer.setTexture("bumpSampler", this._bumpTexture);
  42024. }
  42025. }
  42026. // Clip plane
  42027. BABYLON.MaterialHelper.BindClipPlane(this._activeEffect, scene);
  42028. // Colors
  42029. scene.ambientColor.multiplyToRef(this._ambientColor, this._globalAmbientColor);
  42030. var eyePosition = scene._forcedViewPosition ? scene._forcedViewPosition : (scene._mirroredCameraPosition ? scene._mirroredCameraPosition : scene.activeCamera.globalPosition);
  42031. var invertNormal = (scene.useRightHandedSystem === (scene._mirroredCameraPosition != null));
  42032. effect.setFloat4("vEyePosition", eyePosition.x, eyePosition.y, eyePosition.z, invertNormal ? -1 : 1);
  42033. effect.setColor3("vAmbientColor", this._globalAmbientColor);
  42034. }
  42035. if (mustRebind || !this.isFrozen) {
  42036. // Lights
  42037. if (scene.lightsEnabled && !this._disableLighting) {
  42038. BABYLON.MaterialHelper.BindLights(scene, mesh, this._activeEffect, defines, this._maxSimultaneousLights, this._usePhysicalLightFalloff);
  42039. }
  42040. // View
  42041. if (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE || reflectionTexture) {
  42042. this.bindView(effect);
  42043. }
  42044. // Fog
  42045. BABYLON.MaterialHelper.BindFogParameters(scene, mesh, this._activeEffect);
  42046. // Morph targets
  42047. if (defines.NUM_MORPH_INFLUENCERS) {
  42048. BABYLON.MaterialHelper.BindMorphTargetParameters(mesh, this._activeEffect);
  42049. }
  42050. // image processing
  42051. this._imageProcessingConfiguration.bind(this._activeEffect);
  42052. // Log. depth
  42053. BABYLON.MaterialHelper.BindLogDepth(defines, this._activeEffect, scene);
  42054. }
  42055. this._uniformBuffer.update();
  42056. this._afterBind(mesh);
  42057. };
  42058. /**
  42059. * Returns the animatable textures.
  42060. * @returns - Array of animatable textures.
  42061. */
  42062. PBRBaseMaterial.prototype.getAnimatables = function () {
  42063. var results = [];
  42064. if (this._albedoTexture && this._albedoTexture.animations && this._albedoTexture.animations.length > 0) {
  42065. results.push(this._albedoTexture);
  42066. }
  42067. if (this._ambientTexture && this._ambientTexture.animations && this._ambientTexture.animations.length > 0) {
  42068. results.push(this._ambientTexture);
  42069. }
  42070. if (this._opacityTexture && this._opacityTexture.animations && this._opacityTexture.animations.length > 0) {
  42071. results.push(this._opacityTexture);
  42072. }
  42073. if (this._reflectionTexture && this._reflectionTexture.animations && this._reflectionTexture.animations.length > 0) {
  42074. results.push(this._reflectionTexture);
  42075. }
  42076. if (this._emissiveTexture && this._emissiveTexture.animations && this._emissiveTexture.animations.length > 0) {
  42077. results.push(this._emissiveTexture);
  42078. }
  42079. if (this._metallicTexture && this._metallicTexture.animations && this._metallicTexture.animations.length > 0) {
  42080. results.push(this._metallicTexture);
  42081. }
  42082. else if (this._reflectivityTexture && this._reflectivityTexture.animations && this._reflectivityTexture.animations.length > 0) {
  42083. results.push(this._reflectivityTexture);
  42084. }
  42085. if (this._bumpTexture && this._bumpTexture.animations && this._bumpTexture.animations.length > 0) {
  42086. results.push(this._bumpTexture);
  42087. }
  42088. if (this._lightmapTexture && this._lightmapTexture.animations && this._lightmapTexture.animations.length > 0) {
  42089. results.push(this._lightmapTexture);
  42090. }
  42091. if (this._refractionTexture && this._refractionTexture.animations && this._refractionTexture.animations.length > 0) {
  42092. results.push(this._refractionTexture);
  42093. }
  42094. return results;
  42095. };
  42096. /**
  42097. * Returns the texture used for reflections.
  42098. * @returns - Reflection texture if present. Otherwise, returns the environment texture.
  42099. */
  42100. PBRBaseMaterial.prototype._getReflectionTexture = function () {
  42101. if (this._reflectionTexture) {
  42102. return this._reflectionTexture;
  42103. }
  42104. return this.getScene().environmentTexture;
  42105. };
  42106. /**
  42107. * Returns the texture used for refraction or null if none is used.
  42108. * @returns - Refection texture if present. If no refraction texture and refraction
  42109. * is linked with transparency, returns environment texture. Otherwise, returns null.
  42110. */
  42111. PBRBaseMaterial.prototype._getRefractionTexture = function () {
  42112. if (this._refractionTexture) {
  42113. return this._refractionTexture;
  42114. }
  42115. if (this._linkRefractionWithTransparency) {
  42116. return this.getScene().environmentTexture;
  42117. }
  42118. return null;
  42119. };
  42120. /**
  42121. * Disposes the resources of the material.
  42122. * @param forceDisposeEffect - Forces the disposal of effects.
  42123. * @param forceDisposeTextures - Forces the disposal of all textures.
  42124. */
  42125. PBRBaseMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  42126. if (forceDisposeTextures) {
  42127. if (this._albedoTexture) {
  42128. this._albedoTexture.dispose();
  42129. }
  42130. if (this._ambientTexture) {
  42131. this._ambientTexture.dispose();
  42132. }
  42133. if (this._opacityTexture) {
  42134. this._opacityTexture.dispose();
  42135. }
  42136. if (this._reflectionTexture) {
  42137. this._reflectionTexture.dispose();
  42138. }
  42139. if (this._environmentBRDFTexture && this.getScene()._environmentBRDFTexture !== this._environmentBRDFTexture) {
  42140. this._environmentBRDFTexture.dispose();
  42141. }
  42142. if (this._emissiveTexture) {
  42143. this._emissiveTexture.dispose();
  42144. }
  42145. if (this._metallicTexture) {
  42146. this._metallicTexture.dispose();
  42147. }
  42148. if (this._reflectivityTexture) {
  42149. this._reflectivityTexture.dispose();
  42150. }
  42151. if (this._bumpTexture) {
  42152. this._bumpTexture.dispose();
  42153. }
  42154. if (this._lightmapTexture) {
  42155. this._lightmapTexture.dispose();
  42156. }
  42157. if (this._refractionTexture) {
  42158. this._refractionTexture.dispose();
  42159. }
  42160. }
  42161. this._renderTargets.dispose();
  42162. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  42163. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  42164. }
  42165. _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);
  42166. };
  42167. /**
  42168. * Stores the reflectivity values based on metallic roughness workflow.
  42169. */
  42170. PBRBaseMaterial._scaledReflectivity = new BABYLON.Color3();
  42171. __decorate([
  42172. BABYLON.serializeAsImageProcessingConfiguration()
  42173. ], PBRBaseMaterial.prototype, "_imageProcessingConfiguration", void 0);
  42174. __decorate([
  42175. BABYLON.serialize()
  42176. ], PBRBaseMaterial.prototype, "useLogarithmicDepth", null);
  42177. __decorate([
  42178. BABYLON.serialize()
  42179. ], PBRBaseMaterial.prototype, "transparencyMode", null);
  42180. return PBRBaseMaterial;
  42181. }(BABYLON.PushMaterial));
  42182. BABYLON.PBRBaseMaterial = PBRBaseMaterial;
  42183. })(BABYLON || (BABYLON = {}));
  42184. //# sourceMappingURL=babylon.pbrBaseMaterial.js.map
  42185. "use strict";
  42186. var BABYLON;
  42187. (function (BABYLON) {
  42188. /**
  42189. * The Physically based simple base material of BJS.
  42190. *
  42191. * This enables better naming and convention enforcements on top of the pbrMaterial.
  42192. * It is used as the base class for both the specGloss and metalRough conventions.
  42193. */
  42194. var PBRBaseSimpleMaterial = /** @class */ (function (_super) {
  42195. __extends(PBRBaseSimpleMaterial, _super);
  42196. /**
  42197. * Instantiates a new PBRMaterial instance.
  42198. *
  42199. * @param name The material name
  42200. * @param scene The scene the material will be use in.
  42201. */
  42202. function PBRBaseSimpleMaterial(name, scene) {
  42203. var _this = _super.call(this, name, scene) || this;
  42204. /**
  42205. * Number of Simultaneous lights allowed on the material.
  42206. */
  42207. _this.maxSimultaneousLights = 4;
  42208. /**
  42209. * If sets to true, disables all the lights affecting the material.
  42210. */
  42211. _this.disableLighting = false;
  42212. /**
  42213. * If sets to true, x component of normal map value will invert (x = 1.0 - x).
  42214. */
  42215. _this.invertNormalMapX = false;
  42216. /**
  42217. * If sets to true, y component of normal map value will invert (y = 1.0 - y).
  42218. */
  42219. _this.invertNormalMapY = false;
  42220. /**
  42221. * Emissivie color used to self-illuminate the model.
  42222. */
  42223. _this.emissiveColor = new BABYLON.Color3(0, 0, 0);
  42224. /**
  42225. * Occlusion Channel Strenght.
  42226. */
  42227. _this.occlusionStrength = 1.0;
  42228. _this.useLightmapAsShadowmap = false;
  42229. _this._useAlphaFromAlbedoTexture = true;
  42230. _this._useAmbientInGrayScale = true;
  42231. return _this;
  42232. }
  42233. Object.defineProperty(PBRBaseSimpleMaterial.prototype, "doubleSided", {
  42234. /**
  42235. * Gets the current double sided mode.
  42236. */
  42237. get: function () {
  42238. return this._twoSidedLighting;
  42239. },
  42240. /**
  42241. * If sets to true and backfaceCulling is false, normals will be flipped on the backside.
  42242. */
  42243. set: function (value) {
  42244. if (this._twoSidedLighting === value) {
  42245. return;
  42246. }
  42247. this._twoSidedLighting = value;
  42248. this.backFaceCulling = !value;
  42249. this._markAllSubMeshesAsTexturesDirty();
  42250. },
  42251. enumerable: true,
  42252. configurable: true
  42253. });
  42254. /**
  42255. * Return the active textures of the material.
  42256. */
  42257. PBRBaseSimpleMaterial.prototype.getActiveTextures = function () {
  42258. var activeTextures = _super.prototype.getActiveTextures.call(this);
  42259. if (this.environmentTexture) {
  42260. activeTextures.push(this.environmentTexture);
  42261. }
  42262. if (this.normalTexture) {
  42263. activeTextures.push(this.normalTexture);
  42264. }
  42265. if (this.emissiveTexture) {
  42266. activeTextures.push(this.emissiveTexture);
  42267. }
  42268. if (this.occlusionTexture) {
  42269. activeTextures.push(this.occlusionTexture);
  42270. }
  42271. if (this.lightmapTexture) {
  42272. activeTextures.push(this.lightmapTexture);
  42273. }
  42274. return activeTextures;
  42275. };
  42276. PBRBaseSimpleMaterial.prototype.hasTexture = function (texture) {
  42277. if (_super.prototype.hasTexture.call(this, texture)) {
  42278. return true;
  42279. }
  42280. if (this.lightmapTexture === texture) {
  42281. return true;
  42282. }
  42283. return false;
  42284. };
  42285. PBRBaseSimpleMaterial.prototype.getClassName = function () {
  42286. return "PBRBaseSimpleMaterial";
  42287. };
  42288. __decorate([
  42289. BABYLON.serialize(),
  42290. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  42291. ], PBRBaseSimpleMaterial.prototype, "maxSimultaneousLights", void 0);
  42292. __decorate([
  42293. BABYLON.serialize(),
  42294. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  42295. ], PBRBaseSimpleMaterial.prototype, "disableLighting", void 0);
  42296. __decorate([
  42297. BABYLON.serializeAsTexture(),
  42298. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_reflectionTexture")
  42299. ], PBRBaseSimpleMaterial.prototype, "environmentTexture", void 0);
  42300. __decorate([
  42301. BABYLON.serialize(),
  42302. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42303. ], PBRBaseSimpleMaterial.prototype, "invertNormalMapX", void 0);
  42304. __decorate([
  42305. BABYLON.serialize(),
  42306. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42307. ], PBRBaseSimpleMaterial.prototype, "invertNormalMapY", void 0);
  42308. __decorate([
  42309. BABYLON.serializeAsTexture(),
  42310. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_bumpTexture")
  42311. ], PBRBaseSimpleMaterial.prototype, "normalTexture", void 0);
  42312. __decorate([
  42313. BABYLON.serializeAsColor3("emissive"),
  42314. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42315. ], PBRBaseSimpleMaterial.prototype, "emissiveColor", void 0);
  42316. __decorate([
  42317. BABYLON.serializeAsTexture(),
  42318. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42319. ], PBRBaseSimpleMaterial.prototype, "emissiveTexture", void 0);
  42320. __decorate([
  42321. BABYLON.serialize(),
  42322. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_ambientTextureStrength")
  42323. ], PBRBaseSimpleMaterial.prototype, "occlusionStrength", void 0);
  42324. __decorate([
  42325. BABYLON.serializeAsTexture(),
  42326. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_ambientTexture")
  42327. ], PBRBaseSimpleMaterial.prototype, "occlusionTexture", void 0);
  42328. __decorate([
  42329. BABYLON.serialize(),
  42330. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_alphaCutOff")
  42331. ], PBRBaseSimpleMaterial.prototype, "alphaCutOff", void 0);
  42332. __decorate([
  42333. BABYLON.serialize()
  42334. ], PBRBaseSimpleMaterial.prototype, "doubleSided", null);
  42335. __decorate([
  42336. BABYLON.serializeAsTexture(),
  42337. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", null)
  42338. ], PBRBaseSimpleMaterial.prototype, "lightmapTexture", void 0);
  42339. __decorate([
  42340. BABYLON.serialize(),
  42341. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42342. ], PBRBaseSimpleMaterial.prototype, "useLightmapAsShadowmap", void 0);
  42343. return PBRBaseSimpleMaterial;
  42344. }(BABYLON.PBRBaseMaterial));
  42345. BABYLON.PBRBaseSimpleMaterial = PBRBaseSimpleMaterial;
  42346. })(BABYLON || (BABYLON = {}));
  42347. //# sourceMappingURL=babylon.pbrBaseSimpleMaterial.js.map
  42348. "use strict";
  42349. var BABYLON;
  42350. (function (BABYLON) {
  42351. /**
  42352. * The Physically based material of BJS.
  42353. *
  42354. * This offers the main features of a standard PBR material.
  42355. * For more information, please refer to the documentation :
  42356. * http://doc.babylonjs.com/extensions/Physically_Based_Rendering
  42357. */
  42358. var PBRMaterial = /** @class */ (function (_super) {
  42359. __extends(PBRMaterial, _super);
  42360. /**
  42361. * Instantiates a new PBRMaterial instance.
  42362. *
  42363. * @param name The material name
  42364. * @param scene The scene the material will be use in.
  42365. */
  42366. function PBRMaterial(name, scene) {
  42367. var _this = _super.call(this, name, scene) || this;
  42368. /**
  42369. * Intensity of the direct lights e.g. the four lights available in your scene.
  42370. * This impacts both the direct diffuse and specular highlights.
  42371. */
  42372. _this.directIntensity = 1.0;
  42373. /**
  42374. * Intensity of the emissive part of the material.
  42375. * This helps controlling the emissive effect without modifying the emissive color.
  42376. */
  42377. _this.emissiveIntensity = 1.0;
  42378. /**
  42379. * Intensity of the environment e.g. how much the environment will light the object
  42380. * either through harmonics for rough material or through the refelction for shiny ones.
  42381. */
  42382. _this.environmentIntensity = 1.0;
  42383. /**
  42384. * This is a special control allowing the reduction of the specular highlights coming from the
  42385. * four lights of the scene. Those highlights may not be needed in full environment lighting.
  42386. */
  42387. _this.specularIntensity = 1.0;
  42388. /**
  42389. * Debug Control allowing disabling the bump map on this material.
  42390. */
  42391. _this.disableBumpMap = false;
  42392. /**
  42393. * AKA Occlusion Texture Intensity in other nomenclature.
  42394. */
  42395. _this.ambientTextureStrength = 1.0;
  42396. /**
  42397. * The color of a material in ambient lighting.
  42398. */
  42399. _this.ambientColor = new BABYLON.Color3(0, 0, 0);
  42400. /**
  42401. * AKA Diffuse Color in other nomenclature.
  42402. */
  42403. _this.albedoColor = new BABYLON.Color3(1, 1, 1);
  42404. /**
  42405. * AKA Specular Color in other nomenclature.
  42406. */
  42407. _this.reflectivityColor = new BABYLON.Color3(1, 1, 1);
  42408. /**
  42409. * The color reflected from the material.
  42410. */
  42411. _this.reflectionColor = new BABYLON.Color3(1.0, 1.0, 1.0);
  42412. /**
  42413. * The color emitted from the material.
  42414. */
  42415. _this.emissiveColor = new BABYLON.Color3(0, 0, 0);
  42416. /**
  42417. * AKA Glossiness in other nomenclature.
  42418. */
  42419. _this.microSurface = 1.0;
  42420. /**
  42421. * source material index of refraction (IOR)' / 'destination material IOR.
  42422. */
  42423. _this.indexOfRefraction = 0.66;
  42424. /**
  42425. * Controls if refraction needs to be inverted on Y. This could be usefull for procedural texture.
  42426. */
  42427. _this.invertRefractionY = false;
  42428. /**
  42429. * This parameters will make the material used its opacity to control how much it is refracting aginst not.
  42430. * Materials half opaque for instance using refraction could benefit from this control.
  42431. */
  42432. _this.linkRefractionWithTransparency = false;
  42433. _this.useLightmapAsShadowmap = false;
  42434. /**
  42435. * Specifies that the alpha is coming form the albedo channel alpha channel for alpha blending.
  42436. */
  42437. _this.useAlphaFromAlbedoTexture = false;
  42438. /**
  42439. * Enforces alpha test in opaque or blend mode in order to improve the performances of some situations.
  42440. */
  42441. _this.forceAlphaTest = false;
  42442. /**
  42443. * Defines the alpha limits in alpha test mode.
  42444. */
  42445. _this.alphaCutOff = 0.4;
  42446. /**
  42447. * Specifies that the material will keeps the specular highlights over a transparent surface (only the most limunous ones).
  42448. * A car glass is a good exemple of that. When sun reflects on it you can not see what is behind.
  42449. */
  42450. _this.useSpecularOverAlpha = true;
  42451. /**
  42452. * Specifies if the reflectivity texture contains the glossiness information in its alpha channel.
  42453. */
  42454. _this.useMicroSurfaceFromReflectivityMapAlpha = false;
  42455. /**
  42456. * Specifies if the metallic texture contains the roughness information in its alpha channel.
  42457. */
  42458. _this.useRoughnessFromMetallicTextureAlpha = true;
  42459. /**
  42460. * Specifies if the metallic texture contains the roughness information in its green channel.
  42461. */
  42462. _this.useRoughnessFromMetallicTextureGreen = false;
  42463. /**
  42464. * Specifies if the metallic texture contains the metallness information in its blue channel.
  42465. */
  42466. _this.useMetallnessFromMetallicTextureBlue = false;
  42467. /**
  42468. * Specifies if the metallic texture contains the ambient occlusion information in its red channel.
  42469. */
  42470. _this.useAmbientOcclusionFromMetallicTextureRed = false;
  42471. /**
  42472. * Specifies if the ambient texture contains the ambient occlusion information in its red channel only.
  42473. */
  42474. _this.useAmbientInGrayScale = false;
  42475. /**
  42476. * In case the reflectivity map does not contain the microsurface information in its alpha channel,
  42477. * The material will try to infer what glossiness each pixel should be.
  42478. */
  42479. _this.useAutoMicroSurfaceFromReflectivityMap = false;
  42480. /**
  42481. * BJS is using an harcoded light falloff based on a manually sets up range.
  42482. * In PBR, one way to represents the fallof is to use the inverse squared root algorythm.
  42483. * This parameter can help you switch back to the BJS mode in order to create scenes using both materials.
  42484. */
  42485. _this.usePhysicalLightFalloff = true;
  42486. /**
  42487. * Specifies that the material will keeps the reflection highlights over a transparent surface (only the most limunous ones).
  42488. * A car glass is a good exemple of that. When the street lights reflects on it you can not see what is behind.
  42489. */
  42490. _this.useRadianceOverAlpha = true;
  42491. /**
  42492. * Allows using an object space normal map (instead of tangent space).
  42493. */
  42494. _this.useObjectSpaceNormalMap = false;
  42495. /**
  42496. * Allows using the bump map in parallax mode.
  42497. */
  42498. _this.useParallax = false;
  42499. /**
  42500. * Allows using the bump map in parallax occlusion mode.
  42501. */
  42502. _this.useParallaxOcclusion = false;
  42503. /**
  42504. * Controls the scale bias of the parallax mode.
  42505. */
  42506. _this.parallaxScaleBias = 0.05;
  42507. /**
  42508. * If sets to true, disables all the lights affecting the material.
  42509. */
  42510. _this.disableLighting = false;
  42511. /**
  42512. * Force the shader to compute irradiance in the fragment shader in order to take bump in account.
  42513. */
  42514. _this.forceIrradianceInFragment = false;
  42515. /**
  42516. * Number of Simultaneous lights allowed on the material.
  42517. */
  42518. _this.maxSimultaneousLights = 4;
  42519. /**
  42520. * If sets to true, x component of normal map value will invert (x = 1.0 - x).
  42521. */
  42522. _this.invertNormalMapX = false;
  42523. /**
  42524. * If sets to true, y component of normal map value will invert (y = 1.0 - y).
  42525. */
  42526. _this.invertNormalMapY = false;
  42527. /**
  42528. * If sets to true and backfaceCulling is false, normals will be flipped on the backside.
  42529. */
  42530. _this.twoSidedLighting = false;
  42531. /**
  42532. * A fresnel is applied to the alpha of the model to ensure grazing angles edges are not alpha tested.
  42533. * And/Or occlude the blended part. (alpha is converted to gamma to compute the fresnel)
  42534. */
  42535. _this.useAlphaFresnel = false;
  42536. /**
  42537. * A fresnel is applied to the alpha of the model to ensure grazing angles edges are not alpha tested.
  42538. * And/Or occlude the blended part. (alpha stays linear to compute the fresnel)
  42539. */
  42540. _this.useLinearAlphaFresnel = false;
  42541. /**
  42542. * A fresnel is applied to the alpha of the model to ensure grazing angles edges are not alpha tested.
  42543. * And/Or occlude the blended part.
  42544. */
  42545. _this.environmentBRDFTexture = null;
  42546. /**
  42547. * Force normal to face away from face.
  42548. */
  42549. _this.forceNormalForward = false;
  42550. /**
  42551. * This parameters will enable/disable Horizon occlusion to prevent normal maps to look shiny when the normal
  42552. * makes the reflect vector face the model (under horizon).
  42553. */
  42554. _this.useHorizonOcclusion = true;
  42555. /**
  42556. * This parameters will enable/disable radiance occlusion by preventing the radiance to lit
  42557. * too much the area relying on ambient texture to define their ambient occlusion.
  42558. */
  42559. _this.useRadianceOcclusion = true;
  42560. /**
  42561. * If set to true, no lighting calculations will be applied.
  42562. */
  42563. _this.unlit = false;
  42564. _this._environmentBRDFTexture = BABYLON.TextureTools.GetEnvironmentBRDFTexture(scene);
  42565. return _this;
  42566. }
  42567. Object.defineProperty(PBRMaterial, "PBRMATERIAL_OPAQUE", {
  42568. /**
  42569. * PBRMaterialTransparencyMode: No transparency mode, Alpha channel is not use.
  42570. */
  42571. get: function () {
  42572. return this._PBRMATERIAL_OPAQUE;
  42573. },
  42574. enumerable: true,
  42575. configurable: true
  42576. });
  42577. Object.defineProperty(PBRMaterial, "PBRMATERIAL_ALPHATEST", {
  42578. /**
  42579. * PBRMaterialTransparencyMode: Alpha Test mode, pixel are discarded below a certain threshold defined by the alpha cutoff value.
  42580. */
  42581. get: function () {
  42582. return this._PBRMATERIAL_ALPHATEST;
  42583. },
  42584. enumerable: true,
  42585. configurable: true
  42586. });
  42587. Object.defineProperty(PBRMaterial, "PBRMATERIAL_ALPHABLEND", {
  42588. /**
  42589. * PBRMaterialTransparencyMode: Pixels are blended (according to the alpha mode) with the already drawn pixels in the current frame buffer.
  42590. */
  42591. get: function () {
  42592. return this._PBRMATERIAL_ALPHABLEND;
  42593. },
  42594. enumerable: true,
  42595. configurable: true
  42596. });
  42597. Object.defineProperty(PBRMaterial, "PBRMATERIAL_ALPHATESTANDBLEND", {
  42598. /**
  42599. * PBRMaterialTransparencyMode: Pixels are blended (according to the alpha mode) with the already drawn pixels in the current frame buffer.
  42600. * They are also discarded below the alpha cutoff threshold to improve performances.
  42601. */
  42602. get: function () {
  42603. return this._PBRMATERIAL_ALPHATESTANDBLEND;
  42604. },
  42605. enumerable: true,
  42606. configurable: true
  42607. });
  42608. Object.defineProperty(PBRMaterial.prototype, "imageProcessingConfiguration", {
  42609. /**
  42610. * Gets the image processing configuration used either in this material.
  42611. */
  42612. get: function () {
  42613. return this._imageProcessingConfiguration;
  42614. },
  42615. /**
  42616. * Sets the Default image processing configuration used either in the this material.
  42617. *
  42618. * If sets to null, the scene one is in use.
  42619. */
  42620. set: function (value) {
  42621. this._attachImageProcessingConfiguration(value);
  42622. // Ensure the effect will be rebuilt.
  42623. this._markAllSubMeshesAsTexturesDirty();
  42624. },
  42625. enumerable: true,
  42626. configurable: true
  42627. });
  42628. Object.defineProperty(PBRMaterial.prototype, "cameraColorCurvesEnabled", {
  42629. /**
  42630. * Gets wether the color curves effect is enabled.
  42631. */
  42632. get: function () {
  42633. return this.imageProcessingConfiguration.colorCurvesEnabled;
  42634. },
  42635. /**
  42636. * Sets wether the color curves effect is enabled.
  42637. */
  42638. set: function (value) {
  42639. this.imageProcessingConfiguration.colorCurvesEnabled = value;
  42640. },
  42641. enumerable: true,
  42642. configurable: true
  42643. });
  42644. Object.defineProperty(PBRMaterial.prototype, "cameraColorGradingEnabled", {
  42645. /**
  42646. * Gets wether the color grading effect is enabled.
  42647. */
  42648. get: function () {
  42649. return this.imageProcessingConfiguration.colorGradingEnabled;
  42650. },
  42651. /**
  42652. * Gets wether the color grading effect is enabled.
  42653. */
  42654. set: function (value) {
  42655. this.imageProcessingConfiguration.colorGradingEnabled = value;
  42656. },
  42657. enumerable: true,
  42658. configurable: true
  42659. });
  42660. Object.defineProperty(PBRMaterial.prototype, "cameraToneMappingEnabled", {
  42661. /**
  42662. * Gets wether tonemapping is enabled or not.
  42663. */
  42664. get: function () {
  42665. return this._imageProcessingConfiguration.toneMappingEnabled;
  42666. },
  42667. /**
  42668. * Sets wether tonemapping is enabled or not
  42669. */
  42670. set: function (value) {
  42671. this._imageProcessingConfiguration.toneMappingEnabled = value;
  42672. },
  42673. enumerable: true,
  42674. configurable: true
  42675. });
  42676. ;
  42677. ;
  42678. Object.defineProperty(PBRMaterial.prototype, "cameraExposure", {
  42679. /**
  42680. * The camera exposure used on this material.
  42681. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  42682. * This corresponds to a photographic exposure.
  42683. */
  42684. get: function () {
  42685. return this._imageProcessingConfiguration.exposure;
  42686. },
  42687. /**
  42688. * The camera exposure used on this material.
  42689. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  42690. * This corresponds to a photographic exposure.
  42691. */
  42692. set: function (value) {
  42693. this._imageProcessingConfiguration.exposure = value;
  42694. },
  42695. enumerable: true,
  42696. configurable: true
  42697. });
  42698. ;
  42699. ;
  42700. Object.defineProperty(PBRMaterial.prototype, "cameraContrast", {
  42701. /**
  42702. * Gets The camera contrast used on this material.
  42703. */
  42704. get: function () {
  42705. return this._imageProcessingConfiguration.contrast;
  42706. },
  42707. /**
  42708. * Sets The camera contrast used on this material.
  42709. */
  42710. set: function (value) {
  42711. this._imageProcessingConfiguration.contrast = value;
  42712. },
  42713. enumerable: true,
  42714. configurable: true
  42715. });
  42716. Object.defineProperty(PBRMaterial.prototype, "cameraColorGradingTexture", {
  42717. /**
  42718. * Gets the Color Grading 2D Lookup Texture.
  42719. */
  42720. get: function () {
  42721. return this._imageProcessingConfiguration.colorGradingTexture;
  42722. },
  42723. /**
  42724. * Sets the Color Grading 2D Lookup Texture.
  42725. */
  42726. set: function (value) {
  42727. this._imageProcessingConfiguration.colorGradingTexture = value;
  42728. },
  42729. enumerable: true,
  42730. configurable: true
  42731. });
  42732. Object.defineProperty(PBRMaterial.prototype, "cameraColorCurves", {
  42733. /**
  42734. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  42735. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  42736. * 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;
  42737. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  42738. */
  42739. get: function () {
  42740. return this._imageProcessingConfiguration.colorCurves;
  42741. },
  42742. /**
  42743. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  42744. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  42745. * 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;
  42746. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  42747. */
  42748. set: function (value) {
  42749. this._imageProcessingConfiguration.colorCurves = value;
  42750. },
  42751. enumerable: true,
  42752. configurable: true
  42753. });
  42754. /**
  42755. * Returns the name of this material class.
  42756. */
  42757. PBRMaterial.prototype.getClassName = function () {
  42758. return "PBRMaterial";
  42759. };
  42760. /**
  42761. * Returns an array of the actively used textures.
  42762. * @returns - Array of BaseTextures
  42763. */
  42764. PBRMaterial.prototype.getActiveTextures = function () {
  42765. var activeTextures = _super.prototype.getActiveTextures.call(this);
  42766. if (this._albedoTexture) {
  42767. activeTextures.push(this._albedoTexture);
  42768. }
  42769. if (this._ambientTexture) {
  42770. activeTextures.push(this._ambientTexture);
  42771. }
  42772. if (this._opacityTexture) {
  42773. activeTextures.push(this._opacityTexture);
  42774. }
  42775. if (this._reflectionTexture) {
  42776. activeTextures.push(this._reflectionTexture);
  42777. }
  42778. if (this._emissiveTexture) {
  42779. activeTextures.push(this._emissiveTexture);
  42780. }
  42781. if (this._reflectivityTexture) {
  42782. activeTextures.push(this._reflectivityTexture);
  42783. }
  42784. if (this._metallicTexture) {
  42785. activeTextures.push(this._metallicTexture);
  42786. }
  42787. if (this._microSurfaceTexture) {
  42788. activeTextures.push(this._microSurfaceTexture);
  42789. }
  42790. if (this._bumpTexture) {
  42791. activeTextures.push(this._bumpTexture);
  42792. }
  42793. if (this._lightmapTexture) {
  42794. activeTextures.push(this._lightmapTexture);
  42795. }
  42796. if (this._refractionTexture) {
  42797. activeTextures.push(this._refractionTexture);
  42798. }
  42799. return activeTextures;
  42800. };
  42801. /**
  42802. * Checks to see if a texture is used in the material.
  42803. * @param texture - Base texture to use.
  42804. * @returns - Boolean specifying if a texture is used in the material.
  42805. */
  42806. PBRMaterial.prototype.hasTexture = function (texture) {
  42807. if (_super.prototype.hasTexture.call(this, texture)) {
  42808. return true;
  42809. }
  42810. if (this._albedoTexture === texture) {
  42811. return true;
  42812. }
  42813. if (this._ambientTexture === texture) {
  42814. return true;
  42815. }
  42816. if (this._opacityTexture === texture) {
  42817. return true;
  42818. }
  42819. if (this._reflectionTexture === texture) {
  42820. return true;
  42821. }
  42822. if (this._reflectivityTexture === texture) {
  42823. return true;
  42824. }
  42825. if (this._metallicTexture === texture) {
  42826. return true;
  42827. }
  42828. if (this._microSurfaceTexture === texture) {
  42829. return true;
  42830. }
  42831. if (this._bumpTexture === texture) {
  42832. return true;
  42833. }
  42834. if (this._lightmapTexture === texture) {
  42835. return true;
  42836. }
  42837. if (this._refractionTexture === texture) {
  42838. return true;
  42839. }
  42840. return false;
  42841. };
  42842. /**
  42843. * Makes a duplicate of the current material.
  42844. * @param name - name to use for the new material.
  42845. */
  42846. PBRMaterial.prototype.clone = function (name) {
  42847. var _this = this;
  42848. var clone = BABYLON.SerializationHelper.Clone(function () { return new PBRMaterial(name, _this.getScene()); }, this);
  42849. clone.id = name;
  42850. clone.name = name;
  42851. return clone;
  42852. };
  42853. /**
  42854. * Serializes this PBR Material.
  42855. * @returns - An object with the serialized material.
  42856. */
  42857. PBRMaterial.prototype.serialize = function () {
  42858. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  42859. serializationObject.customType = "BABYLON.PBRMaterial";
  42860. return serializationObject;
  42861. };
  42862. // Statics
  42863. /**
  42864. * Parses a PBR Material from a serialized object.
  42865. * @param source - Serialized object.
  42866. * @param scene - BJS scene instance.
  42867. * @param rootUrl - url for the scene object
  42868. * @returns - PBRMaterial
  42869. */
  42870. PBRMaterial.Parse = function (source, scene, rootUrl) {
  42871. return BABYLON.SerializationHelper.Parse(function () { return new PBRMaterial(source.name, scene); }, source, scene, rootUrl);
  42872. };
  42873. PBRMaterial._PBRMATERIAL_OPAQUE = 0;
  42874. /**
  42875. * Alpha Test mode, pixel are discarded below a certain threshold defined by the alpha cutoff value.
  42876. */
  42877. PBRMaterial._PBRMATERIAL_ALPHATEST = 1;
  42878. /**
  42879. * Represents the value for Alpha Blend. Pixels are blended (according to the alpha mode) with the already drawn pixels in the current frame buffer.
  42880. */
  42881. PBRMaterial._PBRMATERIAL_ALPHABLEND = 2;
  42882. /**
  42883. * 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.
  42884. * They are also discarded below the alpha cutoff threshold to improve performances.
  42885. */
  42886. PBRMaterial._PBRMATERIAL_ALPHATESTANDBLEND = 3;
  42887. __decorate([
  42888. BABYLON.serialize(),
  42889. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42890. ], PBRMaterial.prototype, "directIntensity", void 0);
  42891. __decorate([
  42892. BABYLON.serialize(),
  42893. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42894. ], PBRMaterial.prototype, "emissiveIntensity", void 0);
  42895. __decorate([
  42896. BABYLON.serialize(),
  42897. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42898. ], PBRMaterial.prototype, "environmentIntensity", void 0);
  42899. __decorate([
  42900. BABYLON.serialize(),
  42901. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42902. ], PBRMaterial.prototype, "specularIntensity", void 0);
  42903. __decorate([
  42904. BABYLON.serialize(),
  42905. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42906. ], PBRMaterial.prototype, "disableBumpMap", void 0);
  42907. __decorate([
  42908. BABYLON.serializeAsTexture(),
  42909. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42910. ], PBRMaterial.prototype, "albedoTexture", void 0);
  42911. __decorate([
  42912. BABYLON.serializeAsTexture(),
  42913. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42914. ], PBRMaterial.prototype, "ambientTexture", void 0);
  42915. __decorate([
  42916. BABYLON.serialize(),
  42917. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42918. ], PBRMaterial.prototype, "ambientTextureStrength", void 0);
  42919. __decorate([
  42920. BABYLON.serializeAsTexture(),
  42921. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesAndMiscDirty")
  42922. ], PBRMaterial.prototype, "opacityTexture", void 0);
  42923. __decorate([
  42924. BABYLON.serializeAsTexture(),
  42925. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42926. ], PBRMaterial.prototype, "reflectionTexture", void 0);
  42927. __decorate([
  42928. BABYLON.serializeAsTexture(),
  42929. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42930. ], PBRMaterial.prototype, "emissiveTexture", void 0);
  42931. __decorate([
  42932. BABYLON.serializeAsTexture(),
  42933. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42934. ], PBRMaterial.prototype, "reflectivityTexture", void 0);
  42935. __decorate([
  42936. BABYLON.serializeAsTexture(),
  42937. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42938. ], PBRMaterial.prototype, "metallicTexture", void 0);
  42939. __decorate([
  42940. BABYLON.serialize(),
  42941. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42942. ], PBRMaterial.prototype, "metallic", void 0);
  42943. __decorate([
  42944. BABYLON.serialize(),
  42945. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42946. ], PBRMaterial.prototype, "roughness", void 0);
  42947. __decorate([
  42948. BABYLON.serializeAsTexture(),
  42949. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42950. ], PBRMaterial.prototype, "microSurfaceTexture", void 0);
  42951. __decorate([
  42952. BABYLON.serializeAsTexture(),
  42953. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42954. ], PBRMaterial.prototype, "bumpTexture", void 0);
  42955. __decorate([
  42956. BABYLON.serializeAsTexture(),
  42957. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", null)
  42958. ], PBRMaterial.prototype, "lightmapTexture", void 0);
  42959. __decorate([
  42960. BABYLON.serializeAsTexture(),
  42961. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42962. ], PBRMaterial.prototype, "refractionTexture", void 0);
  42963. __decorate([
  42964. BABYLON.serializeAsColor3("ambient"),
  42965. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42966. ], PBRMaterial.prototype, "ambientColor", void 0);
  42967. __decorate([
  42968. BABYLON.serializeAsColor3("albedo"),
  42969. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42970. ], PBRMaterial.prototype, "albedoColor", void 0);
  42971. __decorate([
  42972. BABYLON.serializeAsColor3("reflectivity"),
  42973. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42974. ], PBRMaterial.prototype, "reflectivityColor", void 0);
  42975. __decorate([
  42976. BABYLON.serializeAsColor3("reflection"),
  42977. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42978. ], PBRMaterial.prototype, "reflectionColor", void 0);
  42979. __decorate([
  42980. BABYLON.serializeAsColor3("emissive"),
  42981. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42982. ], PBRMaterial.prototype, "emissiveColor", void 0);
  42983. __decorate([
  42984. BABYLON.serialize(),
  42985. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42986. ], PBRMaterial.prototype, "microSurface", void 0);
  42987. __decorate([
  42988. BABYLON.serialize(),
  42989. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42990. ], PBRMaterial.prototype, "indexOfRefraction", void 0);
  42991. __decorate([
  42992. BABYLON.serialize(),
  42993. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42994. ], PBRMaterial.prototype, "invertRefractionY", void 0);
  42995. __decorate([
  42996. BABYLON.serialize(),
  42997. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42998. ], PBRMaterial.prototype, "linkRefractionWithTransparency", void 0);
  42999. __decorate([
  43000. BABYLON.serialize(),
  43001. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43002. ], PBRMaterial.prototype, "useLightmapAsShadowmap", void 0);
  43003. __decorate([
  43004. BABYLON.serialize(),
  43005. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesAndMiscDirty")
  43006. ], PBRMaterial.prototype, "useAlphaFromAlbedoTexture", void 0);
  43007. __decorate([
  43008. BABYLON.serialize(),
  43009. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesAndMiscDirty")
  43010. ], PBRMaterial.prototype, "forceAlphaTest", void 0);
  43011. __decorate([
  43012. BABYLON.serialize(),
  43013. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesAndMiscDirty")
  43014. ], PBRMaterial.prototype, "alphaCutOff", void 0);
  43015. __decorate([
  43016. BABYLON.serialize(),
  43017. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43018. ], PBRMaterial.prototype, "useSpecularOverAlpha", void 0);
  43019. __decorate([
  43020. BABYLON.serialize(),
  43021. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43022. ], PBRMaterial.prototype, "useMicroSurfaceFromReflectivityMapAlpha", void 0);
  43023. __decorate([
  43024. BABYLON.serialize(),
  43025. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43026. ], PBRMaterial.prototype, "useRoughnessFromMetallicTextureAlpha", void 0);
  43027. __decorate([
  43028. BABYLON.serialize(),
  43029. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43030. ], PBRMaterial.prototype, "useRoughnessFromMetallicTextureGreen", void 0);
  43031. __decorate([
  43032. BABYLON.serialize(),
  43033. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43034. ], PBRMaterial.prototype, "useMetallnessFromMetallicTextureBlue", void 0);
  43035. __decorate([
  43036. BABYLON.serialize(),
  43037. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43038. ], PBRMaterial.prototype, "useAmbientOcclusionFromMetallicTextureRed", void 0);
  43039. __decorate([
  43040. BABYLON.serialize(),
  43041. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43042. ], PBRMaterial.prototype, "useAmbientInGrayScale", void 0);
  43043. __decorate([
  43044. BABYLON.serialize(),
  43045. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43046. ], PBRMaterial.prototype, "useAutoMicroSurfaceFromReflectivityMap", void 0);
  43047. __decorate([
  43048. BABYLON.serialize(),
  43049. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43050. ], PBRMaterial.prototype, "usePhysicalLightFalloff", void 0);
  43051. __decorate([
  43052. BABYLON.serialize(),
  43053. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43054. ], PBRMaterial.prototype, "useRadianceOverAlpha", void 0);
  43055. __decorate([
  43056. BABYLON.serialize(),
  43057. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43058. ], PBRMaterial.prototype, "useObjectSpaceNormalMap", void 0);
  43059. __decorate([
  43060. BABYLON.serialize(),
  43061. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43062. ], PBRMaterial.prototype, "useParallax", void 0);
  43063. __decorate([
  43064. BABYLON.serialize(),
  43065. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43066. ], PBRMaterial.prototype, "useParallaxOcclusion", void 0);
  43067. __decorate([
  43068. BABYLON.serialize(),
  43069. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43070. ], PBRMaterial.prototype, "parallaxScaleBias", void 0);
  43071. __decorate([
  43072. BABYLON.serialize(),
  43073. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  43074. ], PBRMaterial.prototype, "disableLighting", void 0);
  43075. __decorate([
  43076. BABYLON.serialize(),
  43077. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43078. ], PBRMaterial.prototype, "forceIrradianceInFragment", void 0);
  43079. __decorate([
  43080. BABYLON.serialize(),
  43081. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  43082. ], PBRMaterial.prototype, "maxSimultaneousLights", void 0);
  43083. __decorate([
  43084. BABYLON.serialize(),
  43085. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43086. ], PBRMaterial.prototype, "invertNormalMapX", void 0);
  43087. __decorate([
  43088. BABYLON.serialize(),
  43089. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43090. ], PBRMaterial.prototype, "invertNormalMapY", void 0);
  43091. __decorate([
  43092. BABYLON.serialize(),
  43093. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43094. ], PBRMaterial.prototype, "twoSidedLighting", void 0);
  43095. __decorate([
  43096. BABYLON.serialize(),
  43097. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43098. ], PBRMaterial.prototype, "useAlphaFresnel", void 0);
  43099. __decorate([
  43100. BABYLON.serialize(),
  43101. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43102. ], PBRMaterial.prototype, "useLinearAlphaFresnel", void 0);
  43103. __decorate([
  43104. BABYLON.serializeAsTexture(),
  43105. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43106. ], PBRMaterial.prototype, "environmentBRDFTexture", void 0);
  43107. __decorate([
  43108. BABYLON.serialize(),
  43109. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43110. ], PBRMaterial.prototype, "forceNormalForward", void 0);
  43111. __decorate([
  43112. BABYLON.serialize(),
  43113. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43114. ], PBRMaterial.prototype, "useHorizonOcclusion", void 0);
  43115. __decorate([
  43116. BABYLON.serialize(),
  43117. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43118. ], PBRMaterial.prototype, "useRadianceOcclusion", void 0);
  43119. __decorate([
  43120. BABYLON.serialize(),
  43121. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  43122. ], PBRMaterial.prototype, "unlit", void 0);
  43123. return PBRMaterial;
  43124. }(BABYLON.PBRBaseMaterial));
  43125. BABYLON.PBRMaterial = PBRMaterial;
  43126. })(BABYLON || (BABYLON = {}));
  43127. //# sourceMappingURL=babylon.pbrMaterial.js.map
  43128. "use strict";
  43129. var BABYLON;
  43130. (function (BABYLON) {
  43131. /**
  43132. * The PBR material of BJS following the metal roughness convention.
  43133. *
  43134. * This fits to the PBR convention in the GLTF definition:
  43135. * https://github.com/KhronosGroup/glTF/tree/2.0/specification/2.0
  43136. */
  43137. var PBRMetallicRoughnessMaterial = /** @class */ (function (_super) {
  43138. __extends(PBRMetallicRoughnessMaterial, _super);
  43139. /**
  43140. * Instantiates a new PBRMetalRoughnessMaterial instance.
  43141. *
  43142. * @param name The material name
  43143. * @param scene The scene the material will be use in.
  43144. */
  43145. function PBRMetallicRoughnessMaterial(name, scene) {
  43146. var _this = _super.call(this, name, scene) || this;
  43147. _this._useRoughnessFromMetallicTextureAlpha = false;
  43148. _this._useRoughnessFromMetallicTextureGreen = true;
  43149. _this._useMetallnessFromMetallicTextureBlue = true;
  43150. _this.metallic = 1.0;
  43151. _this.roughness = 1.0;
  43152. return _this;
  43153. }
  43154. /**
  43155. * Return the currrent class name of the material.
  43156. */
  43157. PBRMetallicRoughnessMaterial.prototype.getClassName = function () {
  43158. return "PBRMetallicRoughnessMaterial";
  43159. };
  43160. /**
  43161. * Return the active textures of the material.
  43162. */
  43163. PBRMetallicRoughnessMaterial.prototype.getActiveTextures = function () {
  43164. var activeTextures = _super.prototype.getActiveTextures.call(this);
  43165. if (this.baseTexture) {
  43166. activeTextures.push(this.baseTexture);
  43167. }
  43168. if (this.metallicRoughnessTexture) {
  43169. activeTextures.push(this.metallicRoughnessTexture);
  43170. }
  43171. return activeTextures;
  43172. };
  43173. /**
  43174. * Checks to see if a texture is used in the material.
  43175. * @param texture - Base texture to use.
  43176. * @returns - Boolean specifying if a texture is used in the material.
  43177. */
  43178. PBRMetallicRoughnessMaterial.prototype.hasTexture = function (texture) {
  43179. if (_super.prototype.hasTexture.call(this, texture)) {
  43180. return true;
  43181. }
  43182. if (this.baseTexture === texture) {
  43183. return true;
  43184. }
  43185. if (this.metallicRoughnessTexture === texture) {
  43186. return true;
  43187. }
  43188. return false;
  43189. };
  43190. /**
  43191. * Makes a duplicate of the current material.
  43192. * @param name - name to use for the new material.
  43193. */
  43194. PBRMetallicRoughnessMaterial.prototype.clone = function (name) {
  43195. var _this = this;
  43196. var clone = BABYLON.SerializationHelper.Clone(function () { return new PBRMetallicRoughnessMaterial(name, _this.getScene()); }, this);
  43197. clone.id = name;
  43198. clone.name = name;
  43199. return clone;
  43200. };
  43201. /**
  43202. * Serialize the material to a parsable JSON object.
  43203. */
  43204. PBRMetallicRoughnessMaterial.prototype.serialize = function () {
  43205. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  43206. serializationObject.customType = "BABYLON.PBRMetallicRoughnessMaterial";
  43207. return serializationObject;
  43208. };
  43209. /**
  43210. * Parses a JSON object correponding to the serialize function.
  43211. */
  43212. PBRMetallicRoughnessMaterial.Parse = function (source, scene, rootUrl) {
  43213. return BABYLON.SerializationHelper.Parse(function () { return new PBRMetallicRoughnessMaterial(source.name, scene); }, source, scene, rootUrl);
  43214. };
  43215. __decorate([
  43216. BABYLON.serializeAsColor3(),
  43217. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_albedoColor")
  43218. ], PBRMetallicRoughnessMaterial.prototype, "baseColor", void 0);
  43219. __decorate([
  43220. BABYLON.serializeAsTexture(),
  43221. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_albedoTexture")
  43222. ], PBRMetallicRoughnessMaterial.prototype, "baseTexture", void 0);
  43223. __decorate([
  43224. BABYLON.serialize(),
  43225. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43226. ], PBRMetallicRoughnessMaterial.prototype, "metallic", void 0);
  43227. __decorate([
  43228. BABYLON.serialize(),
  43229. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43230. ], PBRMetallicRoughnessMaterial.prototype, "roughness", void 0);
  43231. __decorate([
  43232. BABYLON.serializeAsTexture(),
  43233. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_metallicTexture")
  43234. ], PBRMetallicRoughnessMaterial.prototype, "metallicRoughnessTexture", void 0);
  43235. return PBRMetallicRoughnessMaterial;
  43236. }(BABYLON.PBRBaseSimpleMaterial));
  43237. BABYLON.PBRMetallicRoughnessMaterial = PBRMetallicRoughnessMaterial;
  43238. })(BABYLON || (BABYLON = {}));
  43239. //# sourceMappingURL=babylon.pbrMetallicRoughnessMaterial.js.map
  43240. "use strict";
  43241. var BABYLON;
  43242. (function (BABYLON) {
  43243. /**
  43244. * The PBR material of BJS following the specular glossiness convention.
  43245. *
  43246. * This fits to the PBR convention in the GLTF definition:
  43247. * https://github.com/KhronosGroup/glTF/tree/2.0/extensions/Khronos/KHR_materials_pbrSpecularGlossiness
  43248. */
  43249. var PBRSpecularGlossinessMaterial = /** @class */ (function (_super) {
  43250. __extends(PBRSpecularGlossinessMaterial, _super);
  43251. /**
  43252. * Instantiates a new PBRSpecularGlossinessMaterial instance.
  43253. *
  43254. * @param name The material name
  43255. * @param scene The scene the material will be use in.
  43256. */
  43257. function PBRSpecularGlossinessMaterial(name, scene) {
  43258. var _this = _super.call(this, name, scene) || this;
  43259. _this._useMicroSurfaceFromReflectivityMapAlpha = true;
  43260. return _this;
  43261. }
  43262. /**
  43263. * Return the currrent class name of the material.
  43264. */
  43265. PBRSpecularGlossinessMaterial.prototype.getClassName = function () {
  43266. return "PBRSpecularGlossinessMaterial";
  43267. };
  43268. /**
  43269. * Return the active textures of the material.
  43270. */
  43271. PBRSpecularGlossinessMaterial.prototype.getActiveTextures = function () {
  43272. var activeTextures = _super.prototype.getActiveTextures.call(this);
  43273. if (this.diffuseTexture) {
  43274. activeTextures.push(this.diffuseTexture);
  43275. }
  43276. if (this.specularGlossinessTexture) {
  43277. activeTextures.push(this.specularGlossinessTexture);
  43278. }
  43279. return activeTextures;
  43280. };
  43281. /**
  43282. * Checks to see if a texture is used in the material.
  43283. * @param texture - Base texture to use.
  43284. * @returns - Boolean specifying if a texture is used in the material.
  43285. */
  43286. PBRSpecularGlossinessMaterial.prototype.hasTexture = function (texture) {
  43287. if (_super.prototype.hasTexture.call(this, texture)) {
  43288. return true;
  43289. }
  43290. if (this.diffuseTexture === texture) {
  43291. return true;
  43292. }
  43293. if (this.specularGlossinessTexture === texture) {
  43294. return true;
  43295. }
  43296. return false;
  43297. };
  43298. /**
  43299. * Makes a duplicate of the current material.
  43300. * @param name - name to use for the new material.
  43301. */
  43302. PBRSpecularGlossinessMaterial.prototype.clone = function (name) {
  43303. var _this = this;
  43304. var clone = BABYLON.SerializationHelper.Clone(function () { return new PBRSpecularGlossinessMaterial(name, _this.getScene()); }, this);
  43305. clone.id = name;
  43306. clone.name = name;
  43307. return clone;
  43308. };
  43309. /**
  43310. * Serialize the material to a parsable JSON object.
  43311. */
  43312. PBRSpecularGlossinessMaterial.prototype.serialize = function () {
  43313. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  43314. serializationObject.customType = "BABYLON.PBRSpecularGlossinessMaterial";
  43315. return serializationObject;
  43316. };
  43317. /**
  43318. * Parses a JSON object correponding to the serialize function.
  43319. */
  43320. PBRSpecularGlossinessMaterial.Parse = function (source, scene, rootUrl) {
  43321. return BABYLON.SerializationHelper.Parse(function () { return new PBRSpecularGlossinessMaterial(source.name, scene); }, source, scene, rootUrl);
  43322. };
  43323. __decorate([
  43324. BABYLON.serializeAsColor3("diffuse"),
  43325. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_albedoColor")
  43326. ], PBRSpecularGlossinessMaterial.prototype, "diffuseColor", void 0);
  43327. __decorate([
  43328. BABYLON.serializeAsTexture(),
  43329. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_albedoTexture")
  43330. ], PBRSpecularGlossinessMaterial.prototype, "diffuseTexture", void 0);
  43331. __decorate([
  43332. BABYLON.serializeAsColor3("specular"),
  43333. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_reflectivityColor")
  43334. ], PBRSpecularGlossinessMaterial.prototype, "specularColor", void 0);
  43335. __decorate([
  43336. BABYLON.serialize(),
  43337. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_microSurface")
  43338. ], PBRSpecularGlossinessMaterial.prototype, "glossiness", void 0);
  43339. __decorate([
  43340. BABYLON.serializeAsTexture(),
  43341. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_reflectivityTexture")
  43342. ], PBRSpecularGlossinessMaterial.prototype, "specularGlossinessTexture", void 0);
  43343. return PBRSpecularGlossinessMaterial;
  43344. }(BABYLON.PBRBaseSimpleMaterial));
  43345. BABYLON.PBRSpecularGlossinessMaterial = PBRSpecularGlossinessMaterial;
  43346. })(BABYLON || (BABYLON = {}));
  43347. //# sourceMappingURL=babylon.pbrSpecularGlossinessMaterial.js.map
  43348. "use strict";
  43349. var BABYLON;
  43350. (function (BABYLON) {
  43351. BABYLON.CameraInputTypes = {};
  43352. var CameraInputsManager = /** @class */ (function () {
  43353. function CameraInputsManager(camera) {
  43354. this.attached = {};
  43355. this.camera = camera;
  43356. this.checkInputs = function () { };
  43357. }
  43358. /**
  43359. * Add an input method to a camera.
  43360. * builtin inputs example: camera.inputs.addGamepad();
  43361. * custom inputs example: camera.inputs.add(new BABYLON.FreeCameraGamepadInput());
  43362. * @param input camera input method
  43363. */
  43364. CameraInputsManager.prototype.add = function (input) {
  43365. var type = input.getSimpleName();
  43366. if (this.attached[type]) {
  43367. BABYLON.Tools.Warn("camera input of type " + type + " already exists on camera");
  43368. return;
  43369. }
  43370. this.attached[type] = input;
  43371. input.camera = this.camera;
  43372. //for checkInputs, we are dynamically creating a function
  43373. //the goal is to avoid the performance penalty of looping for inputs in the render loop
  43374. if (input.checkInputs) {
  43375. this.checkInputs = this._addCheckInputs(input.checkInputs.bind(input));
  43376. }
  43377. if (this.attachedElement) {
  43378. input.attachControl(this.attachedElement);
  43379. }
  43380. };
  43381. /**
  43382. * Remove a specific input method from a camera
  43383. * example: camera.inputs.remove(camera.inputs.attached.mouse);
  43384. * @param inputToRemove camera input method
  43385. */
  43386. CameraInputsManager.prototype.remove = function (inputToRemove) {
  43387. for (var cam in this.attached) {
  43388. var input = this.attached[cam];
  43389. if (input === inputToRemove) {
  43390. input.detachControl(this.attachedElement);
  43391. input.camera = null;
  43392. delete this.attached[cam];
  43393. this.rebuildInputCheck();
  43394. }
  43395. }
  43396. };
  43397. CameraInputsManager.prototype.removeByType = function (inputType) {
  43398. for (var cam in this.attached) {
  43399. var input = this.attached[cam];
  43400. if (input.getClassName() === inputType) {
  43401. input.detachControl(this.attachedElement);
  43402. input.camera = null;
  43403. delete this.attached[cam];
  43404. this.rebuildInputCheck();
  43405. }
  43406. }
  43407. };
  43408. CameraInputsManager.prototype._addCheckInputs = function (fn) {
  43409. var current = this.checkInputs;
  43410. return function () {
  43411. current();
  43412. fn();
  43413. };
  43414. };
  43415. CameraInputsManager.prototype.attachInput = function (input) {
  43416. if (this.attachedElement) {
  43417. input.attachControl(this.attachedElement, this.noPreventDefault);
  43418. }
  43419. };
  43420. CameraInputsManager.prototype.attachElement = function (element, noPreventDefault) {
  43421. if (noPreventDefault === void 0) { noPreventDefault = false; }
  43422. if (this.attachedElement) {
  43423. return;
  43424. }
  43425. noPreventDefault = BABYLON.Camera.ForceAttachControlToAlwaysPreventDefault ? false : noPreventDefault;
  43426. this.attachedElement = element;
  43427. this.noPreventDefault = noPreventDefault;
  43428. for (var cam in this.attached) {
  43429. this.attached[cam].attachControl(element, noPreventDefault);
  43430. }
  43431. };
  43432. CameraInputsManager.prototype.detachElement = function (element, disconnect) {
  43433. if (disconnect === void 0) { disconnect = false; }
  43434. if (this.attachedElement !== element) {
  43435. return;
  43436. }
  43437. for (var cam in this.attached) {
  43438. this.attached[cam].detachControl(element);
  43439. if (disconnect) {
  43440. this.attached[cam].camera = null;
  43441. }
  43442. }
  43443. this.attachedElement = null;
  43444. };
  43445. CameraInputsManager.prototype.rebuildInputCheck = function () {
  43446. this.checkInputs = function () { };
  43447. for (var cam in this.attached) {
  43448. var input = this.attached[cam];
  43449. if (input.checkInputs) {
  43450. this.checkInputs = this._addCheckInputs(input.checkInputs.bind(input));
  43451. }
  43452. }
  43453. };
  43454. /**
  43455. * Remove all attached input methods from a camera
  43456. */
  43457. CameraInputsManager.prototype.clear = function () {
  43458. if (this.attachedElement) {
  43459. this.detachElement(this.attachedElement, true);
  43460. }
  43461. this.attached = {};
  43462. this.attachedElement = null;
  43463. this.checkInputs = function () { };
  43464. };
  43465. CameraInputsManager.prototype.serialize = function (serializedCamera) {
  43466. var inputs = {};
  43467. for (var cam in this.attached) {
  43468. var input = this.attached[cam];
  43469. var res = BABYLON.SerializationHelper.Serialize(input);
  43470. inputs[input.getClassName()] = res;
  43471. }
  43472. serializedCamera.inputsmgr = inputs;
  43473. };
  43474. CameraInputsManager.prototype.parse = function (parsedCamera) {
  43475. var parsedInputs = parsedCamera.inputsmgr;
  43476. if (parsedInputs) {
  43477. this.clear();
  43478. for (var n in parsedInputs) {
  43479. var construct = BABYLON.CameraInputTypes[n];
  43480. if (construct) {
  43481. var parsedinput = parsedInputs[n];
  43482. var input = BABYLON.SerializationHelper.Parse(function () { return new construct(); }, parsedinput, null);
  43483. this.add(input);
  43484. }
  43485. }
  43486. }
  43487. else {
  43488. //2016-03-08 this part is for managing backward compatibility
  43489. for (var n in this.attached) {
  43490. var construct = BABYLON.CameraInputTypes[this.attached[n].getClassName()];
  43491. if (construct) {
  43492. var input = BABYLON.SerializationHelper.Parse(function () { return new construct(); }, parsedCamera, null);
  43493. this.remove(this.attached[n]);
  43494. this.add(input);
  43495. }
  43496. }
  43497. }
  43498. };
  43499. return CameraInputsManager;
  43500. }());
  43501. BABYLON.CameraInputsManager = CameraInputsManager;
  43502. })(BABYLON || (BABYLON = {}));
  43503. //# sourceMappingURL=babylon.cameraInputsManager.js.map
  43504. "use strict";
  43505. var BABYLON;
  43506. (function (BABYLON) {
  43507. var TargetCamera = /** @class */ (function (_super) {
  43508. __extends(TargetCamera, _super);
  43509. function TargetCamera(name, position, scene) {
  43510. var _this = _super.call(this, name, position, scene) || this;
  43511. _this.cameraDirection = new BABYLON.Vector3(0, 0, 0);
  43512. _this.cameraRotation = new BABYLON.Vector2(0, 0);
  43513. _this.rotation = new BABYLON.Vector3(0, 0, 0);
  43514. _this.speed = 2.0;
  43515. _this.noRotationConstraint = false;
  43516. _this.lockedTarget = null;
  43517. _this._currentTarget = BABYLON.Vector3.Zero();
  43518. _this._viewMatrix = BABYLON.Matrix.Zero();
  43519. _this._camMatrix = BABYLON.Matrix.Zero();
  43520. _this._cameraTransformMatrix = BABYLON.Matrix.Zero();
  43521. _this._cameraRotationMatrix = BABYLON.Matrix.Zero();
  43522. _this._referencePoint = new BABYLON.Vector3(0, 0, 1);
  43523. _this._currentUpVector = new BABYLON.Vector3(0, 1, 0);
  43524. _this._transformedReferencePoint = BABYLON.Vector3.Zero();
  43525. _this._lookAtTemp = BABYLON.Matrix.Zero();
  43526. _this._tempMatrix = BABYLON.Matrix.Zero();
  43527. return _this;
  43528. }
  43529. TargetCamera.prototype.getFrontPosition = function (distance) {
  43530. this.getWorldMatrix();
  43531. var direction = this.getTarget().subtract(this.position);
  43532. direction.normalize();
  43533. direction.scaleInPlace(distance);
  43534. return this.globalPosition.add(direction);
  43535. };
  43536. TargetCamera.prototype._getLockedTargetPosition = function () {
  43537. if (!this.lockedTarget) {
  43538. return null;
  43539. }
  43540. if (this.lockedTarget.absolutePosition) {
  43541. this.lockedTarget.computeWorldMatrix();
  43542. }
  43543. return this.lockedTarget.absolutePosition || this.lockedTarget;
  43544. };
  43545. TargetCamera.prototype.storeState = function () {
  43546. this._storedPosition = this.position.clone();
  43547. this._storedRotation = this.rotation.clone();
  43548. if (this.rotationQuaternion) {
  43549. this._storedRotationQuaternion = this.rotationQuaternion.clone();
  43550. }
  43551. return _super.prototype.storeState.call(this);
  43552. };
  43553. /**
  43554. * Restored camera state. You must call storeState() first
  43555. */
  43556. TargetCamera.prototype._restoreStateValues = function () {
  43557. if (!_super.prototype._restoreStateValues.call(this)) {
  43558. return false;
  43559. }
  43560. this.position = this._storedPosition.clone();
  43561. this.rotation = this._storedRotation.clone();
  43562. if (this.rotationQuaternion) {
  43563. this.rotationQuaternion = this._storedRotationQuaternion.clone();
  43564. }
  43565. this.cameraDirection.copyFromFloats(0, 0, 0);
  43566. this.cameraRotation.copyFromFloats(0, 0);
  43567. return true;
  43568. };
  43569. // Cache
  43570. TargetCamera.prototype._initCache = function () {
  43571. _super.prototype._initCache.call(this);
  43572. this._cache.lockedTarget = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  43573. this._cache.rotation = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  43574. this._cache.rotationQuaternion = new BABYLON.Quaternion(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  43575. };
  43576. TargetCamera.prototype._updateCache = function (ignoreParentClass) {
  43577. if (!ignoreParentClass) {
  43578. _super.prototype._updateCache.call(this);
  43579. }
  43580. var lockedTargetPosition = this._getLockedTargetPosition();
  43581. if (!lockedTargetPosition) {
  43582. this._cache.lockedTarget = null;
  43583. }
  43584. else {
  43585. if (!this._cache.lockedTarget) {
  43586. this._cache.lockedTarget = lockedTargetPosition.clone();
  43587. }
  43588. else {
  43589. this._cache.lockedTarget.copyFrom(lockedTargetPosition);
  43590. }
  43591. }
  43592. this._cache.rotation.copyFrom(this.rotation);
  43593. if (this.rotationQuaternion)
  43594. this._cache.rotationQuaternion.copyFrom(this.rotationQuaternion);
  43595. };
  43596. // Synchronized
  43597. TargetCamera.prototype._isSynchronizedViewMatrix = function () {
  43598. if (!_super.prototype._isSynchronizedViewMatrix.call(this)) {
  43599. return false;
  43600. }
  43601. var lockedTargetPosition = this._getLockedTargetPosition();
  43602. return (this._cache.lockedTarget ? this._cache.lockedTarget.equals(lockedTargetPosition) : !lockedTargetPosition)
  43603. && (this.rotationQuaternion ? this.rotationQuaternion.equals(this._cache.rotationQuaternion) : this._cache.rotation.equals(this.rotation));
  43604. };
  43605. // Methods
  43606. TargetCamera.prototype._computeLocalCameraSpeed = function () {
  43607. var engine = this.getEngine();
  43608. return this.speed * Math.sqrt((engine.getDeltaTime() / (engine.getFps() * 100.0)));
  43609. };
  43610. // Target
  43611. TargetCamera.prototype.setTarget = function (target) {
  43612. this.upVector.normalize();
  43613. BABYLON.Matrix.LookAtLHToRef(this.position, target, this.upVector, this._camMatrix);
  43614. this._camMatrix.invert();
  43615. this.rotation.x = Math.atan(this._camMatrix.m[6] / this._camMatrix.m[10]);
  43616. var vDir = target.subtract(this.position);
  43617. if (vDir.x >= 0.0) {
  43618. this.rotation.y = (-Math.atan(vDir.z / vDir.x) + Math.PI / 2.0);
  43619. }
  43620. else {
  43621. this.rotation.y = (-Math.atan(vDir.z / vDir.x) - Math.PI / 2.0);
  43622. }
  43623. this.rotation.z = 0;
  43624. if (isNaN(this.rotation.x)) {
  43625. this.rotation.x = 0;
  43626. }
  43627. if (isNaN(this.rotation.y)) {
  43628. this.rotation.y = 0;
  43629. }
  43630. if (isNaN(this.rotation.z)) {
  43631. this.rotation.z = 0;
  43632. }
  43633. if (this.rotationQuaternion) {
  43634. BABYLON.Quaternion.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this.rotationQuaternion);
  43635. }
  43636. };
  43637. /**
  43638. * Return the current target position of the camera. This value is expressed in local space.
  43639. */
  43640. TargetCamera.prototype.getTarget = function () {
  43641. return this._currentTarget;
  43642. };
  43643. TargetCamera.prototype._decideIfNeedsToMove = function () {
  43644. return Math.abs(this.cameraDirection.x) > 0 || Math.abs(this.cameraDirection.y) > 0 || Math.abs(this.cameraDirection.z) > 0;
  43645. };
  43646. TargetCamera.prototype._updatePosition = function () {
  43647. if (this.parent) {
  43648. this.parent.getWorldMatrix().invertToRef(BABYLON.Tmp.Matrix[0]);
  43649. BABYLON.Vector3.TransformNormalToRef(this.cameraDirection, BABYLON.Tmp.Matrix[0], BABYLON.Tmp.Vector3[0]);
  43650. this.position.addInPlace(BABYLON.Tmp.Vector3[0]);
  43651. return;
  43652. }
  43653. this.position.addInPlace(this.cameraDirection);
  43654. };
  43655. TargetCamera.prototype._checkInputs = function () {
  43656. var needToMove = this._decideIfNeedsToMove();
  43657. var needToRotate = Math.abs(this.cameraRotation.x) > 0 || Math.abs(this.cameraRotation.y) > 0;
  43658. // Move
  43659. if (needToMove) {
  43660. this._updatePosition();
  43661. }
  43662. // Rotate
  43663. if (needToRotate) {
  43664. this.rotation.x += this.cameraRotation.x;
  43665. this.rotation.y += this.cameraRotation.y;
  43666. //rotate, if quaternion is set and rotation was used
  43667. if (this.rotationQuaternion) {
  43668. var len = this.rotation.lengthSquared();
  43669. if (len) {
  43670. BABYLON.Quaternion.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this.rotationQuaternion);
  43671. }
  43672. }
  43673. if (!this.noRotationConstraint) {
  43674. var limit = (Math.PI / 2) * 0.95;
  43675. if (this.rotation.x > limit)
  43676. this.rotation.x = limit;
  43677. if (this.rotation.x < -limit)
  43678. this.rotation.x = -limit;
  43679. }
  43680. }
  43681. // Inertia
  43682. if (needToMove) {
  43683. if (Math.abs(this.cameraDirection.x) < this.speed * BABYLON.Epsilon) {
  43684. this.cameraDirection.x = 0;
  43685. }
  43686. if (Math.abs(this.cameraDirection.y) < this.speed * BABYLON.Epsilon) {
  43687. this.cameraDirection.y = 0;
  43688. }
  43689. if (Math.abs(this.cameraDirection.z) < this.speed * BABYLON.Epsilon) {
  43690. this.cameraDirection.z = 0;
  43691. }
  43692. this.cameraDirection.scaleInPlace(this.inertia);
  43693. }
  43694. if (needToRotate) {
  43695. if (Math.abs(this.cameraRotation.x) < this.speed * BABYLON.Epsilon) {
  43696. this.cameraRotation.x = 0;
  43697. }
  43698. if (Math.abs(this.cameraRotation.y) < this.speed * BABYLON.Epsilon) {
  43699. this.cameraRotation.y = 0;
  43700. }
  43701. this.cameraRotation.scaleInPlace(this.inertia);
  43702. }
  43703. _super.prototype._checkInputs.call(this);
  43704. };
  43705. TargetCamera.prototype._updateCameraRotationMatrix = function () {
  43706. if (this.rotationQuaternion) {
  43707. this.rotationQuaternion.toRotationMatrix(this._cameraRotationMatrix);
  43708. }
  43709. else {
  43710. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this._cameraRotationMatrix);
  43711. }
  43712. //update the up vector!
  43713. BABYLON.Vector3.TransformNormalToRef(this.upVector, this._cameraRotationMatrix, this._currentUpVector);
  43714. };
  43715. TargetCamera.prototype._getViewMatrix = function () {
  43716. if (this.lockedTarget) {
  43717. this.setTarget(this._getLockedTargetPosition());
  43718. }
  43719. // Compute
  43720. this._updateCameraRotationMatrix();
  43721. BABYLON.Vector3.TransformCoordinatesToRef(this._referencePoint, this._cameraRotationMatrix, this._transformedReferencePoint);
  43722. // Computing target and final matrix
  43723. this.position.addToRef(this._transformedReferencePoint, this._currentTarget);
  43724. if (this.getScene().useRightHandedSystem) {
  43725. BABYLON.Matrix.LookAtRHToRef(this.position, this._currentTarget, this._currentUpVector, this._viewMatrix);
  43726. }
  43727. else {
  43728. BABYLON.Matrix.LookAtLHToRef(this.position, this._currentTarget, this._currentUpVector, this._viewMatrix);
  43729. }
  43730. return this._viewMatrix;
  43731. };
  43732. /**
  43733. * @override
  43734. * Override Camera.createRigCamera
  43735. */
  43736. TargetCamera.prototype.createRigCamera = function (name, cameraIndex) {
  43737. if (this.cameraRigMode !== BABYLON.Camera.RIG_MODE_NONE) {
  43738. var rigCamera = new TargetCamera(name, this.position.clone(), this.getScene());
  43739. if (this.cameraRigMode === BABYLON.Camera.RIG_MODE_VR || this.cameraRigMode === BABYLON.Camera.RIG_MODE_WEBVR) {
  43740. if (!this.rotationQuaternion) {
  43741. this.rotationQuaternion = new BABYLON.Quaternion();
  43742. }
  43743. rigCamera._cameraRigParams = {};
  43744. rigCamera.rotationQuaternion = new BABYLON.Quaternion();
  43745. }
  43746. return rigCamera;
  43747. }
  43748. return null;
  43749. };
  43750. /**
  43751. * @override
  43752. * Override Camera._updateRigCameras
  43753. */
  43754. TargetCamera.prototype._updateRigCameras = function () {
  43755. var camLeft = this._rigCameras[0];
  43756. var camRight = this._rigCameras[1];
  43757. switch (this.cameraRigMode) {
  43758. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  43759. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  43760. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  43761. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  43762. //provisionnaly using _cameraRigParams.stereoHalfAngle instead of calculations based on _cameraRigParams.interaxialDistance:
  43763. var leftSign = (this.cameraRigMode === BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED) ? 1 : -1;
  43764. var rightSign = (this.cameraRigMode === BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED) ? -1 : 1;
  43765. this._getRigCamPosition(this._cameraRigParams.stereoHalfAngle * leftSign, camLeft.position);
  43766. this._getRigCamPosition(this._cameraRigParams.stereoHalfAngle * rightSign, camRight.position);
  43767. camLeft.setTarget(this.getTarget());
  43768. camRight.setTarget(this.getTarget());
  43769. break;
  43770. case BABYLON.Camera.RIG_MODE_VR:
  43771. if (camLeft.rotationQuaternion) {
  43772. camLeft.rotationQuaternion.copyFrom(this.rotationQuaternion);
  43773. camRight.rotationQuaternion.copyFrom(this.rotationQuaternion);
  43774. }
  43775. else {
  43776. camLeft.rotation.copyFrom(this.rotation);
  43777. camRight.rotation.copyFrom(this.rotation);
  43778. }
  43779. camLeft.position.copyFrom(this.position);
  43780. camRight.position.copyFrom(this.position);
  43781. break;
  43782. }
  43783. _super.prototype._updateRigCameras.call(this);
  43784. };
  43785. TargetCamera.prototype._getRigCamPosition = function (halfSpace, result) {
  43786. if (!this._rigCamTransformMatrix) {
  43787. this._rigCamTransformMatrix = new BABYLON.Matrix();
  43788. }
  43789. var target = this.getTarget();
  43790. BABYLON.Matrix.Translation(-target.x, -target.y, -target.z).multiplyToRef(BABYLON.Matrix.RotationY(halfSpace), this._rigCamTransformMatrix);
  43791. this._rigCamTransformMatrix = this._rigCamTransformMatrix.multiply(BABYLON.Matrix.Translation(target.x, target.y, target.z));
  43792. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this._rigCamTransformMatrix, result);
  43793. };
  43794. TargetCamera.prototype.getClassName = function () {
  43795. return "TargetCamera";
  43796. };
  43797. __decorate([
  43798. BABYLON.serializeAsVector3()
  43799. ], TargetCamera.prototype, "rotation", void 0);
  43800. __decorate([
  43801. BABYLON.serialize()
  43802. ], TargetCamera.prototype, "speed", void 0);
  43803. __decorate([
  43804. BABYLON.serializeAsMeshReference("lockedTargetId")
  43805. ], TargetCamera.prototype, "lockedTarget", void 0);
  43806. return TargetCamera;
  43807. }(BABYLON.Camera));
  43808. BABYLON.TargetCamera = TargetCamera;
  43809. })(BABYLON || (BABYLON = {}));
  43810. //# sourceMappingURL=babylon.targetCamera.js.map
  43811. "use strict";
  43812. var BABYLON;
  43813. (function (BABYLON) {
  43814. var FreeCameraMouseInput = /** @class */ (function () {
  43815. function FreeCameraMouseInput(touchEnabled) {
  43816. if (touchEnabled === void 0) { touchEnabled = true; }
  43817. this.touchEnabled = touchEnabled;
  43818. this.buttons = [0, 1, 2];
  43819. this.angularSensibility = 2000.0;
  43820. this.previousPosition = null;
  43821. }
  43822. FreeCameraMouseInput.prototype.attachControl = function (element, noPreventDefault) {
  43823. var _this = this;
  43824. var engine = this.camera.getEngine();
  43825. if (!this._pointerInput) {
  43826. this._pointerInput = function (p, s) {
  43827. var evt = p.event;
  43828. if (engine.isInVRExclusivePointerMode) {
  43829. return;
  43830. }
  43831. if (!_this.touchEnabled && evt.pointerType === "touch") {
  43832. return;
  43833. }
  43834. if (p.type !== BABYLON.PointerEventTypes.POINTERMOVE && _this.buttons.indexOf(evt.button) === -1) {
  43835. return;
  43836. }
  43837. var srcElement = (evt.srcElement || evt.target);
  43838. if (p.type === BABYLON.PointerEventTypes.POINTERDOWN && srcElement) {
  43839. try {
  43840. srcElement.setPointerCapture(evt.pointerId);
  43841. }
  43842. catch (e) {
  43843. //Nothing to do with the error. Execution will continue.
  43844. }
  43845. _this.previousPosition = {
  43846. x: evt.clientX,
  43847. y: evt.clientY
  43848. };
  43849. if (!noPreventDefault) {
  43850. evt.preventDefault();
  43851. element.focus();
  43852. }
  43853. }
  43854. else if (p.type === BABYLON.PointerEventTypes.POINTERUP && srcElement) {
  43855. try {
  43856. srcElement.releasePointerCapture(evt.pointerId);
  43857. }
  43858. catch (e) {
  43859. //Nothing to do with the error.
  43860. }
  43861. _this.previousPosition = null;
  43862. if (!noPreventDefault) {
  43863. evt.preventDefault();
  43864. }
  43865. }
  43866. else if (p.type === BABYLON.PointerEventTypes.POINTERMOVE) {
  43867. if (!_this.previousPosition || engine.isPointerLock) {
  43868. return;
  43869. }
  43870. var offsetX = evt.clientX - _this.previousPosition.x;
  43871. var offsetY = evt.clientY - _this.previousPosition.y;
  43872. if (_this.camera.getScene().useRightHandedSystem) {
  43873. _this.camera.cameraRotation.y -= offsetX / _this.angularSensibility;
  43874. }
  43875. else {
  43876. _this.camera.cameraRotation.y += offsetX / _this.angularSensibility;
  43877. }
  43878. _this.camera.cameraRotation.x += offsetY / _this.angularSensibility;
  43879. _this.previousPosition = {
  43880. x: evt.clientX,
  43881. y: evt.clientY
  43882. };
  43883. if (!noPreventDefault) {
  43884. evt.preventDefault();
  43885. }
  43886. }
  43887. };
  43888. }
  43889. this._onMouseMove = function (evt) {
  43890. if (!engine.isPointerLock) {
  43891. return;
  43892. }
  43893. if (engine.isInVRExclusivePointerMode) {
  43894. return;
  43895. }
  43896. var offsetX = evt.movementX || evt.mozMovementX || evt.webkitMovementX || evt.msMovementX || 0;
  43897. var offsetY = evt.movementY || evt.mozMovementY || evt.webkitMovementY || evt.msMovementY || 0;
  43898. if (_this.camera.getScene().useRightHandedSystem) {
  43899. _this.camera.cameraRotation.y -= offsetX / _this.angularSensibility;
  43900. }
  43901. else {
  43902. _this.camera.cameraRotation.y += offsetX / _this.angularSensibility;
  43903. }
  43904. _this.camera.cameraRotation.x += offsetY / _this.angularSensibility;
  43905. _this.previousPosition = null;
  43906. if (!noPreventDefault) {
  43907. evt.preventDefault();
  43908. }
  43909. };
  43910. this._observer = this.camera.getScene().onPointerObservable.add(this._pointerInput, BABYLON.PointerEventTypes.POINTERDOWN | BABYLON.PointerEventTypes.POINTERUP | BABYLON.PointerEventTypes.POINTERMOVE);
  43911. element.addEventListener("mousemove", this._onMouseMove, false);
  43912. };
  43913. FreeCameraMouseInput.prototype.detachControl = function (element) {
  43914. if (this._observer && element) {
  43915. this.camera.getScene().onPointerObservable.remove(this._observer);
  43916. if (this._onMouseMove) {
  43917. element.removeEventListener("mousemove", this._onMouseMove);
  43918. }
  43919. this._observer = null;
  43920. this._onMouseMove = null;
  43921. this.previousPosition = null;
  43922. }
  43923. };
  43924. FreeCameraMouseInput.prototype.getClassName = function () {
  43925. return "FreeCameraMouseInput";
  43926. };
  43927. FreeCameraMouseInput.prototype.getSimpleName = function () {
  43928. return "mouse";
  43929. };
  43930. __decorate([
  43931. BABYLON.serialize()
  43932. ], FreeCameraMouseInput.prototype, "buttons", void 0);
  43933. __decorate([
  43934. BABYLON.serialize()
  43935. ], FreeCameraMouseInput.prototype, "angularSensibility", void 0);
  43936. return FreeCameraMouseInput;
  43937. }());
  43938. BABYLON.FreeCameraMouseInput = FreeCameraMouseInput;
  43939. BABYLON.CameraInputTypes["FreeCameraMouseInput"] = FreeCameraMouseInput;
  43940. })(BABYLON || (BABYLON = {}));
  43941. //# sourceMappingURL=babylon.freeCameraMouseInput.js.map
  43942. "use strict";
  43943. var BABYLON;
  43944. (function (BABYLON) {
  43945. var FreeCameraKeyboardMoveInput = /** @class */ (function () {
  43946. function FreeCameraKeyboardMoveInput() {
  43947. this._keys = new Array();
  43948. this.keysUp = [38];
  43949. this.keysDown = [40];
  43950. this.keysLeft = [37];
  43951. this.keysRight = [39];
  43952. }
  43953. FreeCameraKeyboardMoveInput.prototype.attachControl = function (element, noPreventDefault) {
  43954. var _this = this;
  43955. if (this._onCanvasBlurObserver) {
  43956. return;
  43957. }
  43958. this._scene = this.camera.getScene();
  43959. this._engine = this._scene.getEngine();
  43960. this._onCanvasBlurObserver = this._engine.onCanvasBlurObservable.add(function () {
  43961. _this._keys = [];
  43962. });
  43963. this._onKeyboardObserver = this._scene.onKeyboardObservable.add(function (info) {
  43964. var evt = info.event;
  43965. if (info.type === BABYLON.KeyboardEventTypes.KEYDOWN) {
  43966. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  43967. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  43968. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  43969. _this.keysRight.indexOf(evt.keyCode) !== -1) {
  43970. var index = _this._keys.indexOf(evt.keyCode);
  43971. if (index === -1) {
  43972. _this._keys.push(evt.keyCode);
  43973. }
  43974. if (!noPreventDefault) {
  43975. evt.preventDefault();
  43976. }
  43977. }
  43978. }
  43979. else {
  43980. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  43981. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  43982. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  43983. _this.keysRight.indexOf(evt.keyCode) !== -1) {
  43984. var index = _this._keys.indexOf(evt.keyCode);
  43985. if (index >= 0) {
  43986. _this._keys.splice(index, 1);
  43987. }
  43988. if (!noPreventDefault) {
  43989. evt.preventDefault();
  43990. }
  43991. }
  43992. }
  43993. });
  43994. };
  43995. FreeCameraKeyboardMoveInput.prototype.detachControl = function (element) {
  43996. if (this._scene) {
  43997. if (this._onKeyboardObserver) {
  43998. this._scene.onKeyboardObservable.remove(this._onKeyboardObserver);
  43999. }
  44000. if (this._onCanvasBlurObserver) {
  44001. this._engine.onCanvasBlurObservable.remove(this._onCanvasBlurObserver);
  44002. }
  44003. this._onKeyboardObserver = null;
  44004. this._onCanvasBlurObserver = null;
  44005. }
  44006. this._keys = [];
  44007. };
  44008. FreeCameraKeyboardMoveInput.prototype.checkInputs = function () {
  44009. if (this._onKeyboardObserver) {
  44010. var camera = this.camera;
  44011. // Keyboard
  44012. for (var index = 0; index < this._keys.length; index++) {
  44013. var keyCode = this._keys[index];
  44014. var speed = camera._computeLocalCameraSpeed();
  44015. if (this.keysLeft.indexOf(keyCode) !== -1) {
  44016. camera._localDirection.copyFromFloats(-speed, 0, 0);
  44017. }
  44018. else if (this.keysUp.indexOf(keyCode) !== -1) {
  44019. camera._localDirection.copyFromFloats(0, 0, speed);
  44020. }
  44021. else if (this.keysRight.indexOf(keyCode) !== -1) {
  44022. camera._localDirection.copyFromFloats(speed, 0, 0);
  44023. }
  44024. else if (this.keysDown.indexOf(keyCode) !== -1) {
  44025. camera._localDirection.copyFromFloats(0, 0, -speed);
  44026. }
  44027. if (camera.getScene().useRightHandedSystem) {
  44028. camera._localDirection.z *= -1;
  44029. }
  44030. camera.getViewMatrix().invertToRef(camera._cameraTransformMatrix);
  44031. BABYLON.Vector3.TransformNormalToRef(camera._localDirection, camera._cameraTransformMatrix, camera._transformedDirection);
  44032. camera.cameraDirection.addInPlace(camera._transformedDirection);
  44033. }
  44034. }
  44035. };
  44036. FreeCameraKeyboardMoveInput.prototype.getClassName = function () {
  44037. return "FreeCameraKeyboardMoveInput";
  44038. };
  44039. FreeCameraKeyboardMoveInput.prototype._onLostFocus = function (e) {
  44040. this._keys = [];
  44041. };
  44042. FreeCameraKeyboardMoveInput.prototype.getSimpleName = function () {
  44043. return "keyboard";
  44044. };
  44045. __decorate([
  44046. BABYLON.serialize()
  44047. ], FreeCameraKeyboardMoveInput.prototype, "keysUp", void 0);
  44048. __decorate([
  44049. BABYLON.serialize()
  44050. ], FreeCameraKeyboardMoveInput.prototype, "keysDown", void 0);
  44051. __decorate([
  44052. BABYLON.serialize()
  44053. ], FreeCameraKeyboardMoveInput.prototype, "keysLeft", void 0);
  44054. __decorate([
  44055. BABYLON.serialize()
  44056. ], FreeCameraKeyboardMoveInput.prototype, "keysRight", void 0);
  44057. return FreeCameraKeyboardMoveInput;
  44058. }());
  44059. BABYLON.FreeCameraKeyboardMoveInput = FreeCameraKeyboardMoveInput;
  44060. BABYLON.CameraInputTypes["FreeCameraKeyboardMoveInput"] = FreeCameraKeyboardMoveInput;
  44061. })(BABYLON || (BABYLON = {}));
  44062. //# sourceMappingURL=babylon.freeCameraKeyboardMoveInput.js.map
  44063. "use strict";
  44064. var BABYLON;
  44065. (function (BABYLON) {
  44066. var FreeCameraInputsManager = /** @class */ (function (_super) {
  44067. __extends(FreeCameraInputsManager, _super);
  44068. function FreeCameraInputsManager(camera) {
  44069. return _super.call(this, camera) || this;
  44070. }
  44071. FreeCameraInputsManager.prototype.addKeyboard = function () {
  44072. this.add(new BABYLON.FreeCameraKeyboardMoveInput());
  44073. return this;
  44074. };
  44075. FreeCameraInputsManager.prototype.addMouse = function (touchEnabled) {
  44076. if (touchEnabled === void 0) { touchEnabled = true; }
  44077. this.add(new BABYLON.FreeCameraMouseInput(touchEnabled));
  44078. return this;
  44079. };
  44080. FreeCameraInputsManager.prototype.addGamepad = function () {
  44081. this.add(new BABYLON.FreeCameraGamepadInput());
  44082. return this;
  44083. };
  44084. FreeCameraInputsManager.prototype.addDeviceOrientation = function () {
  44085. this.add(new BABYLON.FreeCameraDeviceOrientationInput());
  44086. return this;
  44087. };
  44088. FreeCameraInputsManager.prototype.addTouch = function () {
  44089. this.add(new BABYLON.FreeCameraTouchInput());
  44090. return this;
  44091. };
  44092. FreeCameraInputsManager.prototype.addVirtualJoystick = function () {
  44093. this.add(new BABYLON.FreeCameraVirtualJoystickInput());
  44094. return this;
  44095. };
  44096. return FreeCameraInputsManager;
  44097. }(BABYLON.CameraInputsManager));
  44098. BABYLON.FreeCameraInputsManager = FreeCameraInputsManager;
  44099. })(BABYLON || (BABYLON = {}));
  44100. //# sourceMappingURL=babylon.freeCameraInputsManager.js.map
  44101. "use strict";
  44102. var BABYLON;
  44103. (function (BABYLON) {
  44104. var FreeCamera = /** @class */ (function (_super) {
  44105. __extends(FreeCamera, _super);
  44106. function FreeCamera(name, position, scene) {
  44107. var _this = _super.call(this, name, position, scene) || this;
  44108. _this.ellipsoid = new BABYLON.Vector3(0.5, 1, 0.5);
  44109. _this.ellipsoidOffset = new BABYLON.Vector3(0, 0, 0);
  44110. _this.checkCollisions = false;
  44111. _this.applyGravity = false;
  44112. _this._needMoveForGravity = false;
  44113. _this._oldPosition = BABYLON.Vector3.Zero();
  44114. _this._diffPosition = BABYLON.Vector3.Zero();
  44115. _this._newPosition = BABYLON.Vector3.Zero();
  44116. // Collisions
  44117. _this._collisionMask = -1;
  44118. _this._onCollisionPositionChange = function (collisionId, newPosition, collidedMesh) {
  44119. if (collidedMesh === void 0) { collidedMesh = null; }
  44120. //TODO move this to the collision coordinator!
  44121. if (_this.getScene().workerCollisions)
  44122. newPosition.multiplyInPlace(_this._collider._radius);
  44123. var updatePosition = function (newPos) {
  44124. _this._newPosition.copyFrom(newPos);
  44125. _this._newPosition.subtractToRef(_this._oldPosition, _this._diffPosition);
  44126. if (_this._diffPosition.length() > BABYLON.Engine.CollisionsEpsilon) {
  44127. _this.position.addInPlace(_this._diffPosition);
  44128. if (_this.onCollide && collidedMesh) {
  44129. _this.onCollide(collidedMesh);
  44130. }
  44131. }
  44132. };
  44133. updatePosition(newPosition);
  44134. };
  44135. _this.inputs = new BABYLON.FreeCameraInputsManager(_this);
  44136. _this.inputs.addKeyboard().addMouse();
  44137. return _this;
  44138. }
  44139. Object.defineProperty(FreeCamera.prototype, "angularSensibility", {
  44140. //-- begin properties for backward compatibility for inputs
  44141. /**
  44142. * Gets the input sensibility for a mouse input. (default is 2000.0)
  44143. * Higher values reduce sensitivity.
  44144. */
  44145. get: function () {
  44146. var mouse = this.inputs.attached["mouse"];
  44147. if (mouse)
  44148. return mouse.angularSensibility;
  44149. return 0;
  44150. },
  44151. /**
  44152. * Sets the input sensibility for a mouse input. (default is 2000.0)
  44153. * Higher values reduce sensitivity.
  44154. */
  44155. set: function (value) {
  44156. var mouse = this.inputs.attached["mouse"];
  44157. if (mouse)
  44158. mouse.angularSensibility = value;
  44159. },
  44160. enumerable: true,
  44161. configurable: true
  44162. });
  44163. Object.defineProperty(FreeCamera.prototype, "keysUp", {
  44164. get: function () {
  44165. var keyboard = this.inputs.attached["keyboard"];
  44166. if (keyboard)
  44167. return keyboard.keysUp;
  44168. return [];
  44169. },
  44170. set: function (value) {
  44171. var keyboard = this.inputs.attached["keyboard"];
  44172. if (keyboard)
  44173. keyboard.keysUp = value;
  44174. },
  44175. enumerable: true,
  44176. configurable: true
  44177. });
  44178. Object.defineProperty(FreeCamera.prototype, "keysDown", {
  44179. get: function () {
  44180. var keyboard = this.inputs.attached["keyboard"];
  44181. if (keyboard)
  44182. return keyboard.keysDown;
  44183. return [];
  44184. },
  44185. set: function (value) {
  44186. var keyboard = this.inputs.attached["keyboard"];
  44187. if (keyboard)
  44188. keyboard.keysDown = value;
  44189. },
  44190. enumerable: true,
  44191. configurable: true
  44192. });
  44193. Object.defineProperty(FreeCamera.prototype, "keysLeft", {
  44194. get: function () {
  44195. var keyboard = this.inputs.attached["keyboard"];
  44196. if (keyboard)
  44197. return keyboard.keysLeft;
  44198. return [];
  44199. },
  44200. set: function (value) {
  44201. var keyboard = this.inputs.attached["keyboard"];
  44202. if (keyboard)
  44203. keyboard.keysLeft = value;
  44204. },
  44205. enumerable: true,
  44206. configurable: true
  44207. });
  44208. Object.defineProperty(FreeCamera.prototype, "keysRight", {
  44209. get: function () {
  44210. var keyboard = this.inputs.attached["keyboard"];
  44211. if (keyboard)
  44212. return keyboard.keysRight;
  44213. return [];
  44214. },
  44215. set: function (value) {
  44216. var keyboard = this.inputs.attached["keyboard"];
  44217. if (keyboard)
  44218. keyboard.keysRight = value;
  44219. },
  44220. enumerable: true,
  44221. configurable: true
  44222. });
  44223. // Controls
  44224. FreeCamera.prototype.attachControl = function (element, noPreventDefault) {
  44225. this.inputs.attachElement(element, noPreventDefault);
  44226. };
  44227. FreeCamera.prototype.detachControl = function (element) {
  44228. this.inputs.detachElement(element);
  44229. this.cameraDirection = new BABYLON.Vector3(0, 0, 0);
  44230. this.cameraRotation = new BABYLON.Vector2(0, 0);
  44231. };
  44232. Object.defineProperty(FreeCamera.prototype, "collisionMask", {
  44233. get: function () {
  44234. return this._collisionMask;
  44235. },
  44236. set: function (mask) {
  44237. this._collisionMask = !isNaN(mask) ? mask : -1;
  44238. },
  44239. enumerable: true,
  44240. configurable: true
  44241. });
  44242. FreeCamera.prototype._collideWithWorld = function (displacement) {
  44243. var globalPosition;
  44244. if (this.parent) {
  44245. globalPosition = BABYLON.Vector3.TransformCoordinates(this.position, this.parent.getWorldMatrix());
  44246. }
  44247. else {
  44248. globalPosition = this.position;
  44249. }
  44250. globalPosition.subtractFromFloatsToRef(0, this.ellipsoid.y, 0, this._oldPosition);
  44251. this._oldPosition.addInPlace(this.ellipsoidOffset);
  44252. if (!this._collider) {
  44253. this._collider = new BABYLON.Collider();
  44254. }
  44255. this._collider._radius = this.ellipsoid;
  44256. this._collider.collisionMask = this._collisionMask;
  44257. //no need for clone, as long as gravity is not on.
  44258. var actualDisplacement = displacement;
  44259. //add gravity to the direction to prevent the dual-collision checking
  44260. if (this.applyGravity) {
  44261. //this prevents mending with cameraDirection, a global variable of the free camera class.
  44262. actualDisplacement = displacement.add(this.getScene().gravity);
  44263. }
  44264. this.getScene().collisionCoordinator.getNewPosition(this._oldPosition, actualDisplacement, this._collider, 3, null, this._onCollisionPositionChange, this.uniqueId);
  44265. };
  44266. FreeCamera.prototype._checkInputs = function () {
  44267. if (!this._localDirection) {
  44268. this._localDirection = BABYLON.Vector3.Zero();
  44269. this._transformedDirection = BABYLON.Vector3.Zero();
  44270. }
  44271. this.inputs.checkInputs();
  44272. _super.prototype._checkInputs.call(this);
  44273. };
  44274. FreeCamera.prototype._decideIfNeedsToMove = function () {
  44275. return this._needMoveForGravity || Math.abs(this.cameraDirection.x) > 0 || Math.abs(this.cameraDirection.y) > 0 || Math.abs(this.cameraDirection.z) > 0;
  44276. };
  44277. FreeCamera.prototype._updatePosition = function () {
  44278. if (this.checkCollisions && this.getScene().collisionsEnabled) {
  44279. this._collideWithWorld(this.cameraDirection);
  44280. }
  44281. else {
  44282. _super.prototype._updatePosition.call(this);
  44283. }
  44284. };
  44285. FreeCamera.prototype.dispose = function () {
  44286. this.inputs.clear();
  44287. _super.prototype.dispose.call(this);
  44288. };
  44289. FreeCamera.prototype.getClassName = function () {
  44290. return "FreeCamera";
  44291. };
  44292. __decorate([
  44293. BABYLON.serializeAsVector3()
  44294. ], FreeCamera.prototype, "ellipsoid", void 0);
  44295. __decorate([
  44296. BABYLON.serializeAsVector3()
  44297. ], FreeCamera.prototype, "ellipsoidOffset", void 0);
  44298. __decorate([
  44299. BABYLON.serialize()
  44300. ], FreeCamera.prototype, "checkCollisions", void 0);
  44301. __decorate([
  44302. BABYLON.serialize()
  44303. ], FreeCamera.prototype, "applyGravity", void 0);
  44304. return FreeCamera;
  44305. }(BABYLON.TargetCamera));
  44306. BABYLON.FreeCamera = FreeCamera;
  44307. })(BABYLON || (BABYLON = {}));
  44308. //# sourceMappingURL=babylon.freeCamera.js.map
  44309. "use strict";
  44310. var BABYLON;
  44311. (function (BABYLON) {
  44312. var ArcRotateCameraKeyboardMoveInput = /** @class */ (function () {
  44313. function ArcRotateCameraKeyboardMoveInput() {
  44314. this._keys = new Array();
  44315. this.keysUp = [38];
  44316. this.keysDown = [40];
  44317. this.keysLeft = [37];
  44318. this.keysRight = [39];
  44319. this.keysReset = [220];
  44320. this.panningSensibility = 50.0;
  44321. this.zoomingSensibility = 25.0;
  44322. this.useAltToZoom = true;
  44323. }
  44324. ArcRotateCameraKeyboardMoveInput.prototype.attachControl = function (element, noPreventDefault) {
  44325. var _this = this;
  44326. if (this._onCanvasBlurObserver) {
  44327. return;
  44328. }
  44329. this._scene = this.camera.getScene();
  44330. this._engine = this._scene.getEngine();
  44331. this._onCanvasBlurObserver = this._engine.onCanvasBlurObservable.add(function () {
  44332. _this._keys = [];
  44333. });
  44334. this._onKeyboardObserver = this._scene.onKeyboardObservable.add(function (info) {
  44335. var evt = info.event;
  44336. if (info.type === BABYLON.KeyboardEventTypes.KEYDOWN) {
  44337. _this._ctrlPressed = evt.ctrlKey;
  44338. _this._altPressed = evt.altKey;
  44339. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  44340. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  44341. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  44342. _this.keysRight.indexOf(evt.keyCode) !== -1 ||
  44343. _this.keysReset.indexOf(evt.keyCode) !== -1) {
  44344. var index = _this._keys.indexOf(evt.keyCode);
  44345. if (index === -1) {
  44346. _this._keys.push(evt.keyCode);
  44347. }
  44348. if (evt.preventDefault) {
  44349. if (!noPreventDefault) {
  44350. evt.preventDefault();
  44351. }
  44352. }
  44353. }
  44354. }
  44355. else {
  44356. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  44357. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  44358. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  44359. _this.keysRight.indexOf(evt.keyCode) !== -1 ||
  44360. _this.keysReset.indexOf(evt.keyCode) !== -1) {
  44361. var index = _this._keys.indexOf(evt.keyCode);
  44362. if (index >= 0) {
  44363. _this._keys.splice(index, 1);
  44364. }
  44365. if (evt.preventDefault) {
  44366. if (!noPreventDefault) {
  44367. evt.preventDefault();
  44368. }
  44369. }
  44370. }
  44371. }
  44372. });
  44373. };
  44374. ArcRotateCameraKeyboardMoveInput.prototype.detachControl = function (element) {
  44375. if (this._scene) {
  44376. if (this._onKeyboardObserver) {
  44377. this._scene.onKeyboardObservable.remove(this._onKeyboardObserver);
  44378. }
  44379. if (this._onCanvasBlurObserver) {
  44380. this._engine.onCanvasBlurObservable.remove(this._onCanvasBlurObserver);
  44381. }
  44382. this._onKeyboardObserver = null;
  44383. this._onCanvasBlurObserver = null;
  44384. }
  44385. this._keys = [];
  44386. };
  44387. ArcRotateCameraKeyboardMoveInput.prototype.checkInputs = function () {
  44388. if (this._onKeyboardObserver) {
  44389. var camera = this.camera;
  44390. for (var index = 0; index < this._keys.length; index++) {
  44391. var keyCode = this._keys[index];
  44392. if (this.keysLeft.indexOf(keyCode) !== -1) {
  44393. if (this._ctrlPressed && this.camera._useCtrlForPanning) {
  44394. camera.inertialPanningX -= 1 / this.panningSensibility;
  44395. }
  44396. else {
  44397. camera.inertialAlphaOffset -= 0.01;
  44398. }
  44399. }
  44400. else if (this.keysUp.indexOf(keyCode) !== -1) {
  44401. if (this._ctrlPressed && this.camera._useCtrlForPanning) {
  44402. camera.inertialPanningY += 1 / this.panningSensibility;
  44403. }
  44404. else if (this._altPressed && this.useAltToZoom) {
  44405. camera.inertialRadiusOffset += 1 / this.zoomingSensibility;
  44406. }
  44407. else {
  44408. camera.inertialBetaOffset -= 0.01;
  44409. }
  44410. }
  44411. else if (this.keysRight.indexOf(keyCode) !== -1) {
  44412. if (this._ctrlPressed && this.camera._useCtrlForPanning) {
  44413. camera.inertialPanningX += 1 / this.panningSensibility;
  44414. }
  44415. else {
  44416. camera.inertialAlphaOffset += 0.01;
  44417. }
  44418. }
  44419. else if (this.keysDown.indexOf(keyCode) !== -1) {
  44420. if (this._ctrlPressed && this.camera._useCtrlForPanning) {
  44421. camera.inertialPanningY -= 1 / this.panningSensibility;
  44422. }
  44423. else if (this._altPressed && this.useAltToZoom) {
  44424. camera.inertialRadiusOffset -= 1 / this.zoomingSensibility;
  44425. }
  44426. else {
  44427. camera.inertialBetaOffset += 0.01;
  44428. }
  44429. }
  44430. else if (this.keysReset.indexOf(keyCode) !== -1) {
  44431. camera.restoreState();
  44432. }
  44433. }
  44434. }
  44435. };
  44436. ArcRotateCameraKeyboardMoveInput.prototype.getClassName = function () {
  44437. return "ArcRotateCameraKeyboardMoveInput";
  44438. };
  44439. ArcRotateCameraKeyboardMoveInput.prototype.getSimpleName = function () {
  44440. return "keyboard";
  44441. };
  44442. __decorate([
  44443. BABYLON.serialize()
  44444. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysUp", void 0);
  44445. __decorate([
  44446. BABYLON.serialize()
  44447. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysDown", void 0);
  44448. __decorate([
  44449. BABYLON.serialize()
  44450. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysLeft", void 0);
  44451. __decorate([
  44452. BABYLON.serialize()
  44453. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysRight", void 0);
  44454. __decorate([
  44455. BABYLON.serialize()
  44456. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysReset", void 0);
  44457. __decorate([
  44458. BABYLON.serialize()
  44459. ], ArcRotateCameraKeyboardMoveInput.prototype, "panningSensibility", void 0);
  44460. __decorate([
  44461. BABYLON.serialize()
  44462. ], ArcRotateCameraKeyboardMoveInput.prototype, "zoomingSensibility", void 0);
  44463. __decorate([
  44464. BABYLON.serialize()
  44465. ], ArcRotateCameraKeyboardMoveInput.prototype, "useAltToZoom", void 0);
  44466. return ArcRotateCameraKeyboardMoveInput;
  44467. }());
  44468. BABYLON.ArcRotateCameraKeyboardMoveInput = ArcRotateCameraKeyboardMoveInput;
  44469. BABYLON.CameraInputTypes["ArcRotateCameraKeyboardMoveInput"] = ArcRotateCameraKeyboardMoveInput;
  44470. })(BABYLON || (BABYLON = {}));
  44471. //# sourceMappingURL=babylon.arcRotateCameraKeyboardMoveInput.js.map
  44472. "use strict";
  44473. var BABYLON;
  44474. (function (BABYLON) {
  44475. var ArcRotateCameraMouseWheelInput = /** @class */ (function () {
  44476. function ArcRotateCameraMouseWheelInput() {
  44477. this.wheelPrecision = 3.0;
  44478. /**
  44479. * wheelDeltaPercentage will be used instead of wheelPrecision if different from 0.
  44480. * It defines the percentage of current camera.radius to use as delta when wheel is used.
  44481. */
  44482. this.wheelDeltaPercentage = 0;
  44483. }
  44484. ArcRotateCameraMouseWheelInput.prototype.attachControl = function (element, noPreventDefault) {
  44485. var _this = this;
  44486. this._wheel = function (p, s) {
  44487. //sanity check - this should be a PointerWheel event.
  44488. if (p.type !== BABYLON.PointerEventTypes.POINTERWHEEL)
  44489. return;
  44490. var event = p.event;
  44491. var delta = 0;
  44492. if (event.wheelDelta) {
  44493. if (_this.wheelDeltaPercentage) {
  44494. var wheelDelta = (event.wheelDelta * 0.01 * _this.wheelDeltaPercentage) * _this.camera.radius;
  44495. if (event.wheelDelta > 0) {
  44496. delta = wheelDelta / (1.0 + _this.wheelDeltaPercentage);
  44497. }
  44498. else {
  44499. delta = wheelDelta * (1.0 + _this.wheelDeltaPercentage);
  44500. }
  44501. }
  44502. else {
  44503. delta = event.wheelDelta / (_this.wheelPrecision * 40);
  44504. }
  44505. }
  44506. else if (event.detail) {
  44507. delta = -event.detail / _this.wheelPrecision;
  44508. }
  44509. if (delta)
  44510. _this.camera.inertialRadiusOffset += delta;
  44511. if (event.preventDefault) {
  44512. if (!noPreventDefault) {
  44513. event.preventDefault();
  44514. }
  44515. }
  44516. };
  44517. this._observer = this.camera.getScene().onPointerObservable.add(this._wheel, BABYLON.PointerEventTypes.POINTERWHEEL);
  44518. };
  44519. ArcRotateCameraMouseWheelInput.prototype.detachControl = function (element) {
  44520. if (this._observer && element) {
  44521. this.camera.getScene().onPointerObservable.remove(this._observer);
  44522. this._observer = null;
  44523. this._wheel = null;
  44524. }
  44525. };
  44526. ArcRotateCameraMouseWheelInput.prototype.getClassName = function () {
  44527. return "ArcRotateCameraMouseWheelInput";
  44528. };
  44529. ArcRotateCameraMouseWheelInput.prototype.getSimpleName = function () {
  44530. return "mousewheel";
  44531. };
  44532. __decorate([
  44533. BABYLON.serialize()
  44534. ], ArcRotateCameraMouseWheelInput.prototype, "wheelPrecision", void 0);
  44535. __decorate([
  44536. BABYLON.serialize()
  44537. ], ArcRotateCameraMouseWheelInput.prototype, "wheelDeltaPercentage", void 0);
  44538. return ArcRotateCameraMouseWheelInput;
  44539. }());
  44540. BABYLON.ArcRotateCameraMouseWheelInput = ArcRotateCameraMouseWheelInput;
  44541. BABYLON.CameraInputTypes["ArcRotateCameraMouseWheelInput"] = ArcRotateCameraMouseWheelInput;
  44542. })(BABYLON || (BABYLON = {}));
  44543. //# sourceMappingURL=babylon.arcRotateCameraMouseWheelInput.js.map
  44544. "use strict";
  44545. var BABYLON;
  44546. (function (BABYLON) {
  44547. var ArcRotateCameraPointersInput = /** @class */ (function () {
  44548. function ArcRotateCameraPointersInput() {
  44549. this.buttons = [0, 1, 2];
  44550. this.angularSensibilityX = 1000.0;
  44551. this.angularSensibilityY = 1000.0;
  44552. this.pinchPrecision = 12.0;
  44553. /**
  44554. * pinchDeltaPercentage will be used instead of pinchPrecision if different from 0.
  44555. * It defines the percentage of current camera.radius to use as delta when pinch zoom is used.
  44556. */
  44557. this.pinchDeltaPercentage = 0;
  44558. this.panningSensibility = 1000.0;
  44559. this.multiTouchPanning = true;
  44560. this.multiTouchPanAndZoom = true;
  44561. this._isPanClick = false;
  44562. this.pinchInwards = true;
  44563. }
  44564. ArcRotateCameraPointersInput.prototype.attachControl = function (element, noPreventDefault) {
  44565. var _this = this;
  44566. var engine = this.camera.getEngine();
  44567. var cacheSoloPointer; // cache pointer object for better perf on camera rotation
  44568. var pointA = null;
  44569. var pointB = null;
  44570. var previousPinchSquaredDistance = 0;
  44571. var initialDistance = 0;
  44572. var twoFingerActivityCount = 0;
  44573. var previousMultiTouchPanPosition = { x: 0, y: 0, isPaning: false, isPinching: false };
  44574. this._pointerInput = function (p, s) {
  44575. var evt = p.event;
  44576. var isTouch = p.event.pointerType === "touch";
  44577. if (engine.isInVRExclusivePointerMode) {
  44578. return;
  44579. }
  44580. if (p.type !== BABYLON.PointerEventTypes.POINTERMOVE && _this.buttons.indexOf(evt.button) === -1) {
  44581. return;
  44582. }
  44583. var srcElement = (evt.srcElement || evt.target);
  44584. if (p.type === BABYLON.PointerEventTypes.POINTERDOWN && srcElement) {
  44585. try {
  44586. srcElement.setPointerCapture(evt.pointerId);
  44587. }
  44588. catch (e) {
  44589. //Nothing to do with the error. Execution will continue.
  44590. }
  44591. // Manage panning with pan button click
  44592. _this._isPanClick = evt.button === _this.camera._panningMouseButton;
  44593. // manage pointers
  44594. cacheSoloPointer = { x: evt.clientX, y: evt.clientY, pointerId: evt.pointerId, type: evt.pointerType };
  44595. if (pointA === null) {
  44596. pointA = cacheSoloPointer;
  44597. }
  44598. else if (pointB === null) {
  44599. pointB = cacheSoloPointer;
  44600. }
  44601. if (!noPreventDefault) {
  44602. evt.preventDefault();
  44603. element.focus();
  44604. }
  44605. }
  44606. else if (p.type === BABYLON.PointerEventTypes.POINTERDOUBLETAP) {
  44607. _this.camera.restoreState();
  44608. }
  44609. else if (p.type === BABYLON.PointerEventTypes.POINTERUP && srcElement) {
  44610. try {
  44611. srcElement.releasePointerCapture(evt.pointerId);
  44612. }
  44613. catch (e) {
  44614. //Nothing to do with the error.
  44615. }
  44616. cacheSoloPointer = null;
  44617. previousPinchSquaredDistance = 0;
  44618. previousMultiTouchPanPosition.isPaning = false;
  44619. previousMultiTouchPanPosition.isPinching = false;
  44620. twoFingerActivityCount = 0;
  44621. initialDistance = 0;
  44622. if (!isTouch) {
  44623. pointB = null; // Mouse and pen are mono pointer
  44624. }
  44625. //would be better to use pointers.remove(evt.pointerId) for multitouch gestures,
  44626. //but emptying completly pointers collection is required to fix a bug on iPhone :
  44627. //when changing orientation while pinching camera, one pointer stay pressed forever if we don't release all pointers
  44628. //will be ok to put back pointers.remove(evt.pointerId); when iPhone bug corrected
  44629. if (engine.badOS) {
  44630. pointA = pointB = null;
  44631. }
  44632. else {
  44633. //only remove the impacted pointer in case of multitouch allowing on most
  44634. //platforms switching from rotate to zoom and pan seamlessly.
  44635. if (pointB && pointA && pointA.pointerId == evt.pointerId) {
  44636. pointA = pointB;
  44637. pointB = null;
  44638. cacheSoloPointer = { x: pointA.x, y: pointA.y, pointerId: pointA.pointerId, type: evt.pointerType };
  44639. }
  44640. else if (pointA && pointB && pointB.pointerId == evt.pointerId) {
  44641. pointB = null;
  44642. cacheSoloPointer = { x: pointA.x, y: pointA.y, pointerId: pointA.pointerId, type: evt.pointerType };
  44643. }
  44644. else {
  44645. pointA = pointB = null;
  44646. }
  44647. }
  44648. if (!noPreventDefault) {
  44649. evt.preventDefault();
  44650. }
  44651. }
  44652. else if (p.type === BABYLON.PointerEventTypes.POINTERMOVE) {
  44653. if (!noPreventDefault) {
  44654. evt.preventDefault();
  44655. }
  44656. // One button down
  44657. if (pointA && pointB === null && cacheSoloPointer) {
  44658. if (_this.panningSensibility !== 0 &&
  44659. ((evt.ctrlKey && _this.camera._useCtrlForPanning) || _this._isPanClick)) {
  44660. _this.camera.inertialPanningX += -(evt.clientX - cacheSoloPointer.x) / _this.panningSensibility;
  44661. _this.camera.inertialPanningY += (evt.clientY - cacheSoloPointer.y) / _this.panningSensibility;
  44662. }
  44663. else {
  44664. var offsetX = evt.clientX - cacheSoloPointer.x;
  44665. var offsetY = evt.clientY - cacheSoloPointer.y;
  44666. _this.camera.inertialAlphaOffset -= offsetX / _this.angularSensibilityX;
  44667. _this.camera.inertialBetaOffset -= offsetY / _this.angularSensibilityY;
  44668. }
  44669. cacheSoloPointer.x = evt.clientX;
  44670. cacheSoloPointer.y = evt.clientY;
  44671. }
  44672. else if (pointA && pointB) {
  44673. //if (noPreventDefault) { evt.preventDefault(); } //if pinch gesture, could be useful to force preventDefault to avoid html page scroll/zoom in some mobile browsers
  44674. var ed = (pointA.pointerId === evt.pointerId) ? pointA : pointB;
  44675. ed.x = evt.clientX;
  44676. ed.y = evt.clientY;
  44677. var direction = _this.pinchInwards ? 1 : -1;
  44678. var distX = pointA.x - pointB.x;
  44679. var distY = pointA.y - pointB.y;
  44680. var pinchSquaredDistance = (distX * distX) + (distY * distY);
  44681. var pinchDistance = Math.sqrt(pinchSquaredDistance);
  44682. if (previousPinchSquaredDistance === 0) {
  44683. initialDistance = pinchDistance;
  44684. previousPinchSquaredDistance = pinchSquaredDistance;
  44685. previousMultiTouchPanPosition.x = (pointA.x + pointB.x) / 2;
  44686. previousMultiTouchPanPosition.y = (pointA.y + pointB.y) / 2;
  44687. return;
  44688. }
  44689. if (_this.multiTouchPanAndZoom) {
  44690. if (_this.pinchDeltaPercentage) {
  44691. _this.camera.inertialRadiusOffset += ((pinchSquaredDistance - previousPinchSquaredDistance) * 0.001) * _this.camera.radius * _this.pinchDeltaPercentage;
  44692. }
  44693. else {
  44694. _this.camera.inertialRadiusOffset += (pinchSquaredDistance - previousPinchSquaredDistance) /
  44695. (_this.pinchPrecision *
  44696. ((_this.angularSensibilityX + _this.angularSensibilityY) / 2) *
  44697. direction);
  44698. }
  44699. if (_this.panningSensibility !== 0) {
  44700. var pointersCenterX = (pointA.x + pointB.x) / 2;
  44701. var pointersCenterY = (pointA.y + pointB.y) / 2;
  44702. var pointersCenterDistX = pointersCenterX - previousMultiTouchPanPosition.x;
  44703. var pointersCenterDistY = pointersCenterY - previousMultiTouchPanPosition.y;
  44704. previousMultiTouchPanPosition.x = pointersCenterX;
  44705. previousMultiTouchPanPosition.y = pointersCenterY;
  44706. _this.camera.inertialPanningX += -(pointersCenterDistX) / (_this.panningSensibility);
  44707. _this.camera.inertialPanningY += (pointersCenterDistY) / (_this.panningSensibility);
  44708. }
  44709. }
  44710. else {
  44711. twoFingerActivityCount++;
  44712. if (previousMultiTouchPanPosition.isPinching || (twoFingerActivityCount < 20 && Math.abs(pinchDistance - initialDistance) > _this.camera.pinchToPanMaxDistance)) {
  44713. if (_this.pinchDeltaPercentage) {
  44714. _this.camera.inertialRadiusOffset += ((pinchSquaredDistance - previousPinchSquaredDistance) * 0.001) * _this.camera.radius * _this.pinchDeltaPercentage;
  44715. }
  44716. else {
  44717. _this.camera.inertialRadiusOffset += (pinchSquaredDistance - previousPinchSquaredDistance) /
  44718. (_this.pinchPrecision *
  44719. ((_this.angularSensibilityX + _this.angularSensibilityY) / 2) *
  44720. direction);
  44721. }
  44722. previousMultiTouchPanPosition.isPaning = false;
  44723. previousMultiTouchPanPosition.isPinching = true;
  44724. }
  44725. else {
  44726. if (cacheSoloPointer && cacheSoloPointer.pointerId === ed.pointerId && _this.panningSensibility !== 0 && _this.multiTouchPanning) {
  44727. if (!previousMultiTouchPanPosition.isPaning) {
  44728. previousMultiTouchPanPosition.isPaning = true;
  44729. previousMultiTouchPanPosition.isPinching = false;
  44730. previousMultiTouchPanPosition.x = ed.x;
  44731. previousMultiTouchPanPosition.y = ed.y;
  44732. return;
  44733. }
  44734. _this.camera.inertialPanningX += -(ed.x - previousMultiTouchPanPosition.x) / (_this.panningSensibility);
  44735. _this.camera.inertialPanningY += (ed.y - previousMultiTouchPanPosition.y) / (_this.panningSensibility);
  44736. }
  44737. }
  44738. if (cacheSoloPointer && cacheSoloPointer.pointerId === evt.pointerId) {
  44739. previousMultiTouchPanPosition.x = ed.x;
  44740. previousMultiTouchPanPosition.y = ed.y;
  44741. }
  44742. }
  44743. previousPinchSquaredDistance = pinchSquaredDistance;
  44744. }
  44745. }
  44746. };
  44747. this._observer = this.camera.getScene().onPointerObservable.add(this._pointerInput, BABYLON.PointerEventTypes.POINTERDOWN | BABYLON.PointerEventTypes.POINTERUP | BABYLON.PointerEventTypes.POINTERMOVE | BABYLON.PointerEventTypes._POINTERDOUBLETAP);
  44748. this._onContextMenu = function (evt) {
  44749. evt.preventDefault();
  44750. };
  44751. if (!this.camera._useCtrlForPanning) {
  44752. element.addEventListener("contextmenu", this._onContextMenu, false);
  44753. }
  44754. this._onLostFocus = function () {
  44755. //this._keys = [];
  44756. pointA = pointB = null;
  44757. previousPinchSquaredDistance = 0;
  44758. previousMultiTouchPanPosition.isPaning = false;
  44759. previousMultiTouchPanPosition.isPinching = false;
  44760. twoFingerActivityCount = 0;
  44761. cacheSoloPointer = null;
  44762. initialDistance = 0;
  44763. };
  44764. this._onMouseMove = function (evt) {
  44765. if (!engine.isPointerLock) {
  44766. return;
  44767. }
  44768. var offsetX = evt.movementX || evt.mozMovementX || evt.webkitMovementX || evt.msMovementX || 0;
  44769. var offsetY = evt.movementY || evt.mozMovementY || evt.webkitMovementY || evt.msMovementY || 0;
  44770. _this.camera.inertialAlphaOffset -= offsetX / _this.angularSensibilityX;
  44771. _this.camera.inertialBetaOffset -= offsetY / _this.angularSensibilityY;
  44772. if (!noPreventDefault) {
  44773. evt.preventDefault();
  44774. }
  44775. };
  44776. this._onGestureStart = function (e) {
  44777. if (window.MSGesture === undefined) {
  44778. return;
  44779. }
  44780. if (!_this._MSGestureHandler) {
  44781. _this._MSGestureHandler = new MSGesture();
  44782. _this._MSGestureHandler.target = element;
  44783. }
  44784. _this._MSGestureHandler.addPointer(e.pointerId);
  44785. };
  44786. this._onGesture = function (e) {
  44787. _this.camera.radius *= e.scale;
  44788. if (e.preventDefault) {
  44789. if (!noPreventDefault) {
  44790. e.stopPropagation();
  44791. e.preventDefault();
  44792. }
  44793. }
  44794. };
  44795. element.addEventListener("mousemove", this._onMouseMove, false);
  44796. element.addEventListener("MSPointerDown", this._onGestureStart, false);
  44797. element.addEventListener("MSGestureChange", this._onGesture, false);
  44798. BABYLON.Tools.RegisterTopRootEvents([
  44799. { name: "blur", handler: this._onLostFocus }
  44800. ]);
  44801. };
  44802. ArcRotateCameraPointersInput.prototype.detachControl = function (element) {
  44803. if (this._onLostFocus) {
  44804. BABYLON.Tools.UnregisterTopRootEvents([
  44805. { name: "blur", handler: this._onLostFocus }
  44806. ]);
  44807. }
  44808. if (element && this._observer) {
  44809. this.camera.getScene().onPointerObservable.remove(this._observer);
  44810. this._observer = null;
  44811. if (this._onContextMenu) {
  44812. element.removeEventListener("contextmenu", this._onContextMenu);
  44813. }
  44814. if (this._onMouseMove) {
  44815. element.removeEventListener("mousemove", this._onMouseMove);
  44816. }
  44817. if (this._onGestureStart) {
  44818. element.removeEventListener("MSPointerDown", this._onGestureStart);
  44819. }
  44820. if (this._onGesture) {
  44821. element.removeEventListener("MSGestureChange", this._onGesture);
  44822. }
  44823. this._isPanClick = false;
  44824. this.pinchInwards = true;
  44825. this._onMouseMove = null;
  44826. this._onGestureStart = null;
  44827. this._onGesture = null;
  44828. this._MSGestureHandler = null;
  44829. this._onLostFocus = null;
  44830. this._onContextMenu = null;
  44831. }
  44832. };
  44833. ArcRotateCameraPointersInput.prototype.getClassName = function () {
  44834. return "ArcRotateCameraPointersInput";
  44835. };
  44836. ArcRotateCameraPointersInput.prototype.getSimpleName = function () {
  44837. return "pointers";
  44838. };
  44839. __decorate([
  44840. BABYLON.serialize()
  44841. ], ArcRotateCameraPointersInput.prototype, "buttons", void 0);
  44842. __decorate([
  44843. BABYLON.serialize()
  44844. ], ArcRotateCameraPointersInput.prototype, "angularSensibilityX", void 0);
  44845. __decorate([
  44846. BABYLON.serialize()
  44847. ], ArcRotateCameraPointersInput.prototype, "angularSensibilityY", void 0);
  44848. __decorate([
  44849. BABYLON.serialize()
  44850. ], ArcRotateCameraPointersInput.prototype, "pinchPrecision", void 0);
  44851. __decorate([
  44852. BABYLON.serialize()
  44853. ], ArcRotateCameraPointersInput.prototype, "pinchDeltaPercentage", void 0);
  44854. __decorate([
  44855. BABYLON.serialize()
  44856. ], ArcRotateCameraPointersInput.prototype, "panningSensibility", void 0);
  44857. __decorate([
  44858. BABYLON.serialize()
  44859. ], ArcRotateCameraPointersInput.prototype, "multiTouchPanning", void 0);
  44860. __decorate([
  44861. BABYLON.serialize()
  44862. ], ArcRotateCameraPointersInput.prototype, "multiTouchPanAndZoom", void 0);
  44863. return ArcRotateCameraPointersInput;
  44864. }());
  44865. BABYLON.ArcRotateCameraPointersInput = ArcRotateCameraPointersInput;
  44866. BABYLON.CameraInputTypes["ArcRotateCameraPointersInput"] = ArcRotateCameraPointersInput;
  44867. })(BABYLON || (BABYLON = {}));
  44868. //# sourceMappingURL=babylon.arcRotateCameraPointersInput.js.map
  44869. "use strict";
  44870. var BABYLON;
  44871. (function (BABYLON) {
  44872. var ArcRotateCameraInputsManager = /** @class */ (function (_super) {
  44873. __extends(ArcRotateCameraInputsManager, _super);
  44874. function ArcRotateCameraInputsManager(camera) {
  44875. return _super.call(this, camera) || this;
  44876. }
  44877. ArcRotateCameraInputsManager.prototype.addMouseWheel = function () {
  44878. this.add(new BABYLON.ArcRotateCameraMouseWheelInput());
  44879. return this;
  44880. };
  44881. ArcRotateCameraInputsManager.prototype.addPointers = function () {
  44882. this.add(new BABYLON.ArcRotateCameraPointersInput());
  44883. return this;
  44884. };
  44885. ArcRotateCameraInputsManager.prototype.addKeyboard = function () {
  44886. this.add(new BABYLON.ArcRotateCameraKeyboardMoveInput());
  44887. return this;
  44888. };
  44889. ArcRotateCameraInputsManager.prototype.addGamepad = function () {
  44890. this.add(new BABYLON.ArcRotateCameraGamepadInput());
  44891. return this;
  44892. };
  44893. ArcRotateCameraInputsManager.prototype.addVRDeviceOrientation = function () {
  44894. this.add(new BABYLON.ArcRotateCameraVRDeviceOrientationInput());
  44895. return this;
  44896. };
  44897. return ArcRotateCameraInputsManager;
  44898. }(BABYLON.CameraInputsManager));
  44899. BABYLON.ArcRotateCameraInputsManager = ArcRotateCameraInputsManager;
  44900. })(BABYLON || (BABYLON = {}));
  44901. //# sourceMappingURL=babylon.arcRotateCameraInputsManager.js.map
  44902. "use strict";
  44903. var BABYLON;
  44904. (function (BABYLON) {
  44905. var ArcRotateCamera = /** @class */ (function (_super) {
  44906. __extends(ArcRotateCamera, _super);
  44907. function ArcRotateCamera(name, alpha, beta, radius, target, scene) {
  44908. var _this = _super.call(this, name, BABYLON.Vector3.Zero(), scene) || this;
  44909. _this.inertialAlphaOffset = 0;
  44910. _this.inertialBetaOffset = 0;
  44911. _this.inertialRadiusOffset = 0;
  44912. _this.lowerAlphaLimit = null;
  44913. _this.upperAlphaLimit = null;
  44914. _this.lowerBetaLimit = 0.01;
  44915. _this.upperBetaLimit = Math.PI;
  44916. _this.lowerRadiusLimit = null;
  44917. _this.upperRadiusLimit = null;
  44918. _this.inertialPanningX = 0;
  44919. _this.inertialPanningY = 0;
  44920. _this.pinchToPanMaxDistance = 20;
  44921. _this.panningDistanceLimit = null;
  44922. _this.panningOriginTarget = BABYLON.Vector3.Zero();
  44923. _this.panningInertia = 0.9;
  44924. //-- end properties for backward compatibility for inputs
  44925. _this.zoomOnFactor = 1;
  44926. _this.targetScreenOffset = BABYLON.Vector2.Zero();
  44927. _this.allowUpsideDown = true;
  44928. _this._viewMatrix = new BABYLON.Matrix();
  44929. // Panning
  44930. _this.panningAxis = new BABYLON.Vector3(1, 1, 0);
  44931. _this.onMeshTargetChangedObservable = new BABYLON.Observable();
  44932. _this.checkCollisions = false;
  44933. _this.collisionRadius = new BABYLON.Vector3(0.5, 0.5, 0.5);
  44934. _this._previousPosition = BABYLON.Vector3.Zero();
  44935. _this._collisionVelocity = BABYLON.Vector3.Zero();
  44936. _this._newPosition = BABYLON.Vector3.Zero();
  44937. _this._computationVector = BABYLON.Vector3.Zero();
  44938. _this._onCollisionPositionChange = function (collisionId, newPosition, collidedMesh) {
  44939. if (collidedMesh === void 0) { collidedMesh = null; }
  44940. if (_this.getScene().workerCollisions && _this.checkCollisions) {
  44941. newPosition.multiplyInPlace(_this._collider._radius);
  44942. }
  44943. if (!collidedMesh) {
  44944. _this._previousPosition.copyFrom(_this.position);
  44945. }
  44946. else {
  44947. _this.setPosition(newPosition);
  44948. if (_this.onCollide) {
  44949. _this.onCollide(collidedMesh);
  44950. }
  44951. }
  44952. // Recompute because of constraints
  44953. var cosa = Math.cos(_this.alpha);
  44954. var sina = Math.sin(_this.alpha);
  44955. var cosb = Math.cos(_this.beta);
  44956. var sinb = Math.sin(_this.beta);
  44957. if (sinb === 0) {
  44958. sinb = 0.0001;
  44959. }
  44960. var target = _this._getTargetPosition();
  44961. _this._computationVector.copyFromFloats(_this.radius * cosa * sinb, _this.radius * cosb, _this.radius * sina * sinb);
  44962. target.addToRef(_this._computationVector, _this._newPosition);
  44963. _this.position.copyFrom(_this._newPosition);
  44964. var up = _this.upVector;
  44965. if (_this.allowUpsideDown && _this.beta < 0) {
  44966. up = up.clone();
  44967. up = up.negate();
  44968. }
  44969. BABYLON.Matrix.LookAtLHToRef(_this.position, target, up, _this._viewMatrix);
  44970. _this._viewMatrix.m[12] += _this.targetScreenOffset.x;
  44971. _this._viewMatrix.m[13] += _this.targetScreenOffset.y;
  44972. _this._collisionTriggered = false;
  44973. };
  44974. _this._target = BABYLON.Vector3.Zero();
  44975. if (target) {
  44976. _this.setTarget(target);
  44977. }
  44978. _this.alpha = alpha;
  44979. _this.beta = beta;
  44980. _this.radius = radius;
  44981. _this.getViewMatrix();
  44982. _this.inputs = new BABYLON.ArcRotateCameraInputsManager(_this);
  44983. _this.inputs.addKeyboard().addMouseWheel().addPointers();
  44984. return _this;
  44985. }
  44986. Object.defineProperty(ArcRotateCamera.prototype, "target", {
  44987. get: function () {
  44988. return this._target;
  44989. },
  44990. set: function (value) {
  44991. this.setTarget(value);
  44992. },
  44993. enumerable: true,
  44994. configurable: true
  44995. });
  44996. Object.defineProperty(ArcRotateCamera.prototype, "angularSensibilityX", {
  44997. //-- begin properties for backward compatibility for inputs
  44998. get: function () {
  44999. var pointers = this.inputs.attached["pointers"];
  45000. if (pointers)
  45001. return pointers.angularSensibilityX;
  45002. return 0;
  45003. },
  45004. set: function (value) {
  45005. var pointers = this.inputs.attached["pointers"];
  45006. if (pointers) {
  45007. pointers.angularSensibilityX = value;
  45008. }
  45009. },
  45010. enumerable: true,
  45011. configurable: true
  45012. });
  45013. Object.defineProperty(ArcRotateCamera.prototype, "angularSensibilityY", {
  45014. get: function () {
  45015. var pointers = this.inputs.attached["pointers"];
  45016. if (pointers)
  45017. return pointers.angularSensibilityY;
  45018. return 0;
  45019. },
  45020. set: function (value) {
  45021. var pointers = this.inputs.attached["pointers"];
  45022. if (pointers) {
  45023. pointers.angularSensibilityY = value;
  45024. }
  45025. },
  45026. enumerable: true,
  45027. configurable: true
  45028. });
  45029. Object.defineProperty(ArcRotateCamera.prototype, "pinchPrecision", {
  45030. get: function () {
  45031. var pointers = this.inputs.attached["pointers"];
  45032. if (pointers)
  45033. return pointers.pinchPrecision;
  45034. return 0;
  45035. },
  45036. set: function (value) {
  45037. var pointers = this.inputs.attached["pointers"];
  45038. if (pointers) {
  45039. pointers.pinchPrecision = value;
  45040. }
  45041. },
  45042. enumerable: true,
  45043. configurable: true
  45044. });
  45045. Object.defineProperty(ArcRotateCamera.prototype, "pinchDeltaPercentage", {
  45046. get: function () {
  45047. var pointers = this.inputs.attached["pointers"];
  45048. if (pointers)
  45049. return pointers.pinchDeltaPercentage;
  45050. return 0;
  45051. },
  45052. set: function (value) {
  45053. var pointers = this.inputs.attached["pointers"];
  45054. if (pointers) {
  45055. pointers.pinchDeltaPercentage = value;
  45056. }
  45057. },
  45058. enumerable: true,
  45059. configurable: true
  45060. });
  45061. Object.defineProperty(ArcRotateCamera.prototype, "panningSensibility", {
  45062. get: function () {
  45063. var pointers = this.inputs.attached["pointers"];
  45064. if (pointers)
  45065. return pointers.panningSensibility;
  45066. return 0;
  45067. },
  45068. set: function (value) {
  45069. var pointers = this.inputs.attached["pointers"];
  45070. if (pointers) {
  45071. pointers.panningSensibility = value;
  45072. }
  45073. },
  45074. enumerable: true,
  45075. configurable: true
  45076. });
  45077. Object.defineProperty(ArcRotateCamera.prototype, "keysUp", {
  45078. get: function () {
  45079. var keyboard = this.inputs.attached["keyboard"];
  45080. if (keyboard)
  45081. return keyboard.keysUp;
  45082. return [];
  45083. },
  45084. set: function (value) {
  45085. var keyboard = this.inputs.attached["keyboard"];
  45086. if (keyboard)
  45087. keyboard.keysUp = value;
  45088. },
  45089. enumerable: true,
  45090. configurable: true
  45091. });
  45092. Object.defineProperty(ArcRotateCamera.prototype, "keysDown", {
  45093. get: function () {
  45094. var keyboard = this.inputs.attached["keyboard"];
  45095. if (keyboard)
  45096. return keyboard.keysDown;
  45097. return [];
  45098. },
  45099. set: function (value) {
  45100. var keyboard = this.inputs.attached["keyboard"];
  45101. if (keyboard)
  45102. keyboard.keysDown = value;
  45103. },
  45104. enumerable: true,
  45105. configurable: true
  45106. });
  45107. Object.defineProperty(ArcRotateCamera.prototype, "keysLeft", {
  45108. get: function () {
  45109. var keyboard = this.inputs.attached["keyboard"];
  45110. if (keyboard)
  45111. return keyboard.keysLeft;
  45112. return [];
  45113. },
  45114. set: function (value) {
  45115. var keyboard = this.inputs.attached["keyboard"];
  45116. if (keyboard)
  45117. keyboard.keysLeft = value;
  45118. },
  45119. enumerable: true,
  45120. configurable: true
  45121. });
  45122. Object.defineProperty(ArcRotateCamera.prototype, "keysRight", {
  45123. get: function () {
  45124. var keyboard = this.inputs.attached["keyboard"];
  45125. if (keyboard)
  45126. return keyboard.keysRight;
  45127. return [];
  45128. },
  45129. set: function (value) {
  45130. var keyboard = this.inputs.attached["keyboard"];
  45131. if (keyboard)
  45132. keyboard.keysRight = value;
  45133. },
  45134. enumerable: true,
  45135. configurable: true
  45136. });
  45137. Object.defineProperty(ArcRotateCamera.prototype, "wheelPrecision", {
  45138. get: function () {
  45139. var mousewheel = this.inputs.attached["mousewheel"];
  45140. if (mousewheel)
  45141. return mousewheel.wheelPrecision;
  45142. return 0;
  45143. },
  45144. set: function (value) {
  45145. var mousewheel = this.inputs.attached["mousewheel"];
  45146. if (mousewheel)
  45147. mousewheel.wheelPrecision = value;
  45148. },
  45149. enumerable: true,
  45150. configurable: true
  45151. });
  45152. Object.defineProperty(ArcRotateCamera.prototype, "wheelDeltaPercentage", {
  45153. get: function () {
  45154. var mousewheel = this.inputs.attached["mousewheel"];
  45155. if (mousewheel)
  45156. return mousewheel.wheelDeltaPercentage;
  45157. return 0;
  45158. },
  45159. set: function (value) {
  45160. var mousewheel = this.inputs.attached["mousewheel"];
  45161. if (mousewheel)
  45162. mousewheel.wheelDeltaPercentage = value;
  45163. },
  45164. enumerable: true,
  45165. configurable: true
  45166. });
  45167. Object.defineProperty(ArcRotateCamera.prototype, "bouncingBehavior", {
  45168. get: function () {
  45169. return this._bouncingBehavior;
  45170. },
  45171. enumerable: true,
  45172. configurable: true
  45173. });
  45174. Object.defineProperty(ArcRotateCamera.prototype, "useBouncingBehavior", {
  45175. get: function () {
  45176. return this._bouncingBehavior != null;
  45177. },
  45178. set: function (value) {
  45179. if (value === this.useBouncingBehavior) {
  45180. return;
  45181. }
  45182. if (value) {
  45183. this._bouncingBehavior = new BABYLON.BouncingBehavior();
  45184. this.addBehavior(this._bouncingBehavior);
  45185. }
  45186. else if (this._bouncingBehavior) {
  45187. this.removeBehavior(this._bouncingBehavior);
  45188. this._bouncingBehavior = null;
  45189. }
  45190. },
  45191. enumerable: true,
  45192. configurable: true
  45193. });
  45194. Object.defineProperty(ArcRotateCamera.prototype, "framingBehavior", {
  45195. get: function () {
  45196. return this._framingBehavior;
  45197. },
  45198. enumerable: true,
  45199. configurable: true
  45200. });
  45201. Object.defineProperty(ArcRotateCamera.prototype, "useFramingBehavior", {
  45202. get: function () {
  45203. return this._framingBehavior != null;
  45204. },
  45205. set: function (value) {
  45206. if (value === this.useFramingBehavior) {
  45207. return;
  45208. }
  45209. if (value) {
  45210. this._framingBehavior = new BABYLON.FramingBehavior();
  45211. this.addBehavior(this._framingBehavior);
  45212. }
  45213. else if (this._framingBehavior) {
  45214. this.removeBehavior(this._framingBehavior);
  45215. this._framingBehavior = null;
  45216. }
  45217. },
  45218. enumerable: true,
  45219. configurable: true
  45220. });
  45221. Object.defineProperty(ArcRotateCamera.prototype, "autoRotationBehavior", {
  45222. get: function () {
  45223. return this._autoRotationBehavior;
  45224. },
  45225. enumerable: true,
  45226. configurable: true
  45227. });
  45228. Object.defineProperty(ArcRotateCamera.prototype, "useAutoRotationBehavior", {
  45229. get: function () {
  45230. return this._autoRotationBehavior != null;
  45231. },
  45232. set: function (value) {
  45233. if (value === this.useAutoRotationBehavior) {
  45234. return;
  45235. }
  45236. if (value) {
  45237. this._autoRotationBehavior = new BABYLON.AutoRotationBehavior();
  45238. this.addBehavior(this._autoRotationBehavior);
  45239. }
  45240. else if (this._autoRotationBehavior) {
  45241. this.removeBehavior(this._autoRotationBehavior);
  45242. this._autoRotationBehavior = null;
  45243. }
  45244. },
  45245. enumerable: true,
  45246. configurable: true
  45247. });
  45248. // Cache
  45249. ArcRotateCamera.prototype._initCache = function () {
  45250. _super.prototype._initCache.call(this);
  45251. this._cache._target = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  45252. this._cache.alpha = undefined;
  45253. this._cache.beta = undefined;
  45254. this._cache.radius = undefined;
  45255. this._cache.targetScreenOffset = BABYLON.Vector2.Zero();
  45256. };
  45257. ArcRotateCamera.prototype._updateCache = function (ignoreParentClass) {
  45258. if (!ignoreParentClass) {
  45259. _super.prototype._updateCache.call(this);
  45260. }
  45261. this._cache._target.copyFrom(this._getTargetPosition());
  45262. this._cache.alpha = this.alpha;
  45263. this._cache.beta = this.beta;
  45264. this._cache.radius = this.radius;
  45265. this._cache.targetScreenOffset.copyFrom(this.targetScreenOffset);
  45266. };
  45267. ArcRotateCamera.prototype._getTargetPosition = function () {
  45268. if (this._targetHost && this._targetHost.getAbsolutePosition) {
  45269. var pos = this._targetHost.getAbsolutePosition();
  45270. if (this._targetBoundingCenter) {
  45271. pos.addToRef(this._targetBoundingCenter, this._target);
  45272. }
  45273. else {
  45274. this._target.copyFrom(pos);
  45275. }
  45276. }
  45277. var lockedTargetPosition = this._getLockedTargetPosition();
  45278. if (lockedTargetPosition) {
  45279. return lockedTargetPosition;
  45280. }
  45281. return this._target;
  45282. };
  45283. ArcRotateCamera.prototype.storeState = function () {
  45284. this._storedAlpha = this.alpha;
  45285. this._storedBeta = this.beta;
  45286. this._storedRadius = this.radius;
  45287. this._storedTarget = this._getTargetPosition().clone();
  45288. return _super.prototype.storeState.call(this);
  45289. };
  45290. /**
  45291. * Restored camera state. You must call storeState() first
  45292. */
  45293. ArcRotateCamera.prototype._restoreStateValues = function () {
  45294. if (!_super.prototype._restoreStateValues.call(this)) {
  45295. return false;
  45296. }
  45297. this.alpha = this._storedAlpha;
  45298. this.beta = this._storedBeta;
  45299. this.radius = this._storedRadius;
  45300. this.setTarget(this._storedTarget.clone());
  45301. this.inertialAlphaOffset = 0;
  45302. this.inertialBetaOffset = 0;
  45303. this.inertialRadiusOffset = 0;
  45304. this.inertialPanningX = 0;
  45305. this.inertialPanningY = 0;
  45306. return true;
  45307. };
  45308. // Synchronized
  45309. ArcRotateCamera.prototype._isSynchronizedViewMatrix = function () {
  45310. if (!_super.prototype._isSynchronizedViewMatrix.call(this))
  45311. return false;
  45312. return this._cache._target.equals(this._getTargetPosition())
  45313. && this._cache.alpha === this.alpha
  45314. && this._cache.beta === this.beta
  45315. && this._cache.radius === this.radius
  45316. && this._cache.targetScreenOffset.equals(this.targetScreenOffset);
  45317. };
  45318. // Methods
  45319. ArcRotateCamera.prototype.attachControl = function (element, noPreventDefault, useCtrlForPanning, panningMouseButton) {
  45320. var _this = this;
  45321. if (useCtrlForPanning === void 0) { useCtrlForPanning = true; }
  45322. if (panningMouseButton === void 0) { panningMouseButton = 2; }
  45323. this._useCtrlForPanning = useCtrlForPanning;
  45324. this._panningMouseButton = panningMouseButton;
  45325. this.inputs.attachElement(element, noPreventDefault);
  45326. this._reset = function () {
  45327. _this.inertialAlphaOffset = 0;
  45328. _this.inertialBetaOffset = 0;
  45329. _this.inertialRadiusOffset = 0;
  45330. _this.inertialPanningX = 0;
  45331. _this.inertialPanningY = 0;
  45332. };
  45333. };
  45334. ArcRotateCamera.prototype.detachControl = function (element) {
  45335. this.inputs.detachElement(element);
  45336. if (this._reset) {
  45337. this._reset();
  45338. }
  45339. };
  45340. ArcRotateCamera.prototype._checkInputs = function () {
  45341. //if (async) collision inspection was triggered, don't update the camera's position - until the collision callback was called.
  45342. if (this._collisionTriggered) {
  45343. return;
  45344. }
  45345. this.inputs.checkInputs();
  45346. // Inertia
  45347. if (this.inertialAlphaOffset !== 0 || this.inertialBetaOffset !== 0 || this.inertialRadiusOffset !== 0) {
  45348. if (this.getScene().useRightHandedSystem) {
  45349. this.alpha -= this.beta <= 0 ? -this.inertialAlphaOffset : this.inertialAlphaOffset;
  45350. }
  45351. else {
  45352. this.alpha += this.beta <= 0 ? -this.inertialAlphaOffset : this.inertialAlphaOffset;
  45353. }
  45354. this.beta += this.inertialBetaOffset;
  45355. this.radius -= this.inertialRadiusOffset;
  45356. this.inertialAlphaOffset *= this.inertia;
  45357. this.inertialBetaOffset *= this.inertia;
  45358. this.inertialRadiusOffset *= this.inertia;
  45359. if (Math.abs(this.inertialAlphaOffset) < BABYLON.Epsilon)
  45360. this.inertialAlphaOffset = 0;
  45361. if (Math.abs(this.inertialBetaOffset) < BABYLON.Epsilon)
  45362. this.inertialBetaOffset = 0;
  45363. if (Math.abs(this.inertialRadiusOffset) < this.speed * BABYLON.Epsilon)
  45364. this.inertialRadiusOffset = 0;
  45365. }
  45366. // Panning inertia
  45367. if (this.inertialPanningX !== 0 || this.inertialPanningY !== 0) {
  45368. if (!this._localDirection) {
  45369. this._localDirection = BABYLON.Vector3.Zero();
  45370. this._transformedDirection = BABYLON.Vector3.Zero();
  45371. }
  45372. this._localDirection.copyFromFloats(this.inertialPanningX, this.inertialPanningY, this.inertialPanningY);
  45373. this._localDirection.multiplyInPlace(this.panningAxis);
  45374. this._viewMatrix.invertToRef(this._cameraTransformMatrix);
  45375. BABYLON.Vector3.TransformNormalToRef(this._localDirection, this._cameraTransformMatrix, this._transformedDirection);
  45376. //Eliminate y if map panning is enabled (panningAxis == 1,0,1)
  45377. if (!this.panningAxis.y) {
  45378. this._transformedDirection.y = 0;
  45379. }
  45380. if (!this._targetHost) {
  45381. if (this.panningDistanceLimit) {
  45382. this._transformedDirection.addInPlace(this._target);
  45383. var distanceSquared = BABYLON.Vector3.DistanceSquared(this._transformedDirection, this.panningOriginTarget);
  45384. if (distanceSquared <= (this.panningDistanceLimit * this.panningDistanceLimit)) {
  45385. this._target.copyFrom(this._transformedDirection);
  45386. }
  45387. }
  45388. else {
  45389. this._target.addInPlace(this._transformedDirection);
  45390. }
  45391. }
  45392. this.inertialPanningX *= this.panningInertia;
  45393. this.inertialPanningY *= this.panningInertia;
  45394. if (Math.abs(this.inertialPanningX) < this.speed * BABYLON.Epsilon)
  45395. this.inertialPanningX = 0;
  45396. if (Math.abs(this.inertialPanningY) < this.speed * BABYLON.Epsilon)
  45397. this.inertialPanningY = 0;
  45398. }
  45399. // Limits
  45400. this._checkLimits();
  45401. _super.prototype._checkInputs.call(this);
  45402. };
  45403. ArcRotateCamera.prototype._checkLimits = function () {
  45404. if (this.lowerBetaLimit === null || this.lowerBetaLimit === undefined) {
  45405. if (this.allowUpsideDown && this.beta > Math.PI) {
  45406. this.beta = this.beta - (2 * Math.PI);
  45407. }
  45408. }
  45409. else {
  45410. if (this.beta < this.lowerBetaLimit) {
  45411. this.beta = this.lowerBetaLimit;
  45412. }
  45413. }
  45414. if (this.upperBetaLimit === null || this.upperBetaLimit === undefined) {
  45415. if (this.allowUpsideDown && this.beta < -Math.PI) {
  45416. this.beta = this.beta + (2 * Math.PI);
  45417. }
  45418. }
  45419. else {
  45420. if (this.beta > this.upperBetaLimit) {
  45421. this.beta = this.upperBetaLimit;
  45422. }
  45423. }
  45424. if (this.lowerAlphaLimit && this.alpha < this.lowerAlphaLimit) {
  45425. this.alpha = this.lowerAlphaLimit;
  45426. }
  45427. if (this.upperAlphaLimit && this.alpha > this.upperAlphaLimit) {
  45428. this.alpha = this.upperAlphaLimit;
  45429. }
  45430. if (this.lowerRadiusLimit && this.radius < this.lowerRadiusLimit) {
  45431. this.radius = this.lowerRadiusLimit;
  45432. }
  45433. if (this.upperRadiusLimit && this.radius > this.upperRadiusLimit) {
  45434. this.radius = this.upperRadiusLimit;
  45435. }
  45436. };
  45437. ArcRotateCamera.prototype.rebuildAnglesAndRadius = function () {
  45438. this.position.subtractToRef(this._getTargetPosition(), this._computationVector);
  45439. this.radius = this._computationVector.length();
  45440. if (this.radius === 0) {
  45441. this.radius = 0.0001; // Just to avoid division by zero
  45442. }
  45443. // Alpha
  45444. this.alpha = Math.acos(this._computationVector.x / Math.sqrt(Math.pow(this._computationVector.x, 2) + Math.pow(this._computationVector.z, 2)));
  45445. if (this._computationVector.z < 0) {
  45446. this.alpha = 2 * Math.PI - this.alpha;
  45447. }
  45448. // Beta
  45449. this.beta = Math.acos(this._computationVector.y / this.radius);
  45450. this._checkLimits();
  45451. };
  45452. ArcRotateCamera.prototype.setPosition = function (position) {
  45453. if (this.position.equals(position)) {
  45454. return;
  45455. }
  45456. this.position.copyFrom(position);
  45457. this.rebuildAnglesAndRadius();
  45458. };
  45459. ArcRotateCamera.prototype.setTarget = function (target, toBoundingCenter, allowSamePosition) {
  45460. if (toBoundingCenter === void 0) { toBoundingCenter = false; }
  45461. if (allowSamePosition === void 0) { allowSamePosition = false; }
  45462. if (target.getBoundingInfo) {
  45463. if (toBoundingCenter) {
  45464. this._targetBoundingCenter = target.getBoundingInfo().boundingBox.centerWorld.clone();
  45465. }
  45466. else {
  45467. this._targetBoundingCenter = null;
  45468. }
  45469. this._targetHost = target;
  45470. this._target = this._getTargetPosition();
  45471. this.onMeshTargetChangedObservable.notifyObservers(this._targetHost);
  45472. }
  45473. else {
  45474. var newTarget = target;
  45475. var currentTarget = this._getTargetPosition();
  45476. if (currentTarget && !allowSamePosition && currentTarget.equals(newTarget)) {
  45477. return;
  45478. }
  45479. this._targetHost = null;
  45480. this._target = newTarget;
  45481. this._targetBoundingCenter = null;
  45482. this.onMeshTargetChangedObservable.notifyObservers(null);
  45483. }
  45484. this.rebuildAnglesAndRadius();
  45485. };
  45486. ArcRotateCamera.prototype._getViewMatrix = function () {
  45487. // Compute
  45488. var cosa = Math.cos(this.alpha);
  45489. var sina = Math.sin(this.alpha);
  45490. var cosb = Math.cos(this.beta);
  45491. var sinb = Math.sin(this.beta);
  45492. if (sinb === 0) {
  45493. sinb = 0.0001;
  45494. }
  45495. var target = this._getTargetPosition();
  45496. this._computationVector.copyFromFloats(this.radius * cosa * sinb, this.radius * cosb, this.radius * sina * sinb);
  45497. target.addToRef(this._computationVector, this._newPosition);
  45498. if (this.getScene().collisionsEnabled && this.checkCollisions) {
  45499. if (!this._collider) {
  45500. this._collider = new BABYLON.Collider();
  45501. }
  45502. this._collider._radius = this.collisionRadius;
  45503. this._newPosition.subtractToRef(this.position, this._collisionVelocity);
  45504. this._collisionTriggered = true;
  45505. this.getScene().collisionCoordinator.getNewPosition(this.position, this._collisionVelocity, this._collider, 3, null, this._onCollisionPositionChange, this.uniqueId);
  45506. }
  45507. else {
  45508. this.position.copyFrom(this._newPosition);
  45509. var up = this.upVector;
  45510. if (this.allowUpsideDown && sinb < 0) {
  45511. up = up.clone();
  45512. up = up.negate();
  45513. }
  45514. if (this.getScene().useRightHandedSystem) {
  45515. BABYLON.Matrix.LookAtRHToRef(this.position, target, up, this._viewMatrix);
  45516. }
  45517. else {
  45518. BABYLON.Matrix.LookAtLHToRef(this.position, target, up, this._viewMatrix);
  45519. }
  45520. this._viewMatrix.m[12] += this.targetScreenOffset.x;
  45521. this._viewMatrix.m[13] += this.targetScreenOffset.y;
  45522. }
  45523. this._currentTarget = target;
  45524. return this._viewMatrix;
  45525. };
  45526. ArcRotateCamera.prototype.zoomOn = function (meshes, doNotUpdateMaxZ) {
  45527. if (doNotUpdateMaxZ === void 0) { doNotUpdateMaxZ = false; }
  45528. meshes = meshes || this.getScene().meshes;
  45529. var minMaxVector = BABYLON.Mesh.MinMax(meshes);
  45530. var distance = BABYLON.Vector3.Distance(minMaxVector.min, minMaxVector.max);
  45531. this.radius = distance * this.zoomOnFactor;
  45532. this.focusOn({ min: minMaxVector.min, max: minMaxVector.max, distance: distance }, doNotUpdateMaxZ);
  45533. };
  45534. ArcRotateCamera.prototype.focusOn = function (meshesOrMinMaxVectorAndDistance, doNotUpdateMaxZ) {
  45535. if (doNotUpdateMaxZ === void 0) { doNotUpdateMaxZ = false; }
  45536. var meshesOrMinMaxVector;
  45537. var distance;
  45538. if (meshesOrMinMaxVectorAndDistance.min === undefined) {
  45539. var meshes = meshesOrMinMaxVectorAndDistance || this.getScene().meshes;
  45540. meshesOrMinMaxVector = BABYLON.Mesh.MinMax(meshes);
  45541. distance = BABYLON.Vector3.Distance(meshesOrMinMaxVector.min, meshesOrMinMaxVector.max);
  45542. }
  45543. else {
  45544. var minMaxVectorAndDistance = meshesOrMinMaxVectorAndDistance;
  45545. meshesOrMinMaxVector = minMaxVectorAndDistance;
  45546. distance = minMaxVectorAndDistance.distance;
  45547. }
  45548. this._target = BABYLON.Mesh.Center(meshesOrMinMaxVector);
  45549. if (!doNotUpdateMaxZ) {
  45550. this.maxZ = distance * 2;
  45551. }
  45552. };
  45553. /**
  45554. * @override
  45555. * Override Camera.createRigCamera
  45556. */
  45557. ArcRotateCamera.prototype.createRigCamera = function (name, cameraIndex) {
  45558. var alphaShift = 0;
  45559. switch (this.cameraRigMode) {
  45560. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  45561. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  45562. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  45563. case BABYLON.Camera.RIG_MODE_VR:
  45564. alphaShift = this._cameraRigParams.stereoHalfAngle * (cameraIndex === 0 ? 1 : -1);
  45565. break;
  45566. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  45567. alphaShift = this._cameraRigParams.stereoHalfAngle * (cameraIndex === 0 ? -1 : 1);
  45568. break;
  45569. }
  45570. var rigCam = new ArcRotateCamera(name, this.alpha + alphaShift, this.beta, this.radius, this._target, this.getScene());
  45571. rigCam._cameraRigParams = {};
  45572. return rigCam;
  45573. };
  45574. /**
  45575. * @override
  45576. * Override Camera._updateRigCameras
  45577. */
  45578. ArcRotateCamera.prototype._updateRigCameras = function () {
  45579. var camLeft = this._rigCameras[0];
  45580. var camRight = this._rigCameras[1];
  45581. camLeft.beta = camRight.beta = this.beta;
  45582. camLeft.radius = camRight.radius = this.radius;
  45583. switch (this.cameraRigMode) {
  45584. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  45585. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  45586. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  45587. case BABYLON.Camera.RIG_MODE_VR:
  45588. camLeft.alpha = this.alpha - this._cameraRigParams.stereoHalfAngle;
  45589. camRight.alpha = this.alpha + this._cameraRigParams.stereoHalfAngle;
  45590. break;
  45591. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  45592. camLeft.alpha = this.alpha + this._cameraRigParams.stereoHalfAngle;
  45593. camRight.alpha = this.alpha - this._cameraRigParams.stereoHalfAngle;
  45594. break;
  45595. }
  45596. _super.prototype._updateRigCameras.call(this);
  45597. };
  45598. ArcRotateCamera.prototype.dispose = function () {
  45599. this.inputs.clear();
  45600. _super.prototype.dispose.call(this);
  45601. };
  45602. ArcRotateCamera.prototype.getClassName = function () {
  45603. return "ArcRotateCamera";
  45604. };
  45605. __decorate([
  45606. BABYLON.serialize()
  45607. ], ArcRotateCamera.prototype, "alpha", void 0);
  45608. __decorate([
  45609. BABYLON.serialize()
  45610. ], ArcRotateCamera.prototype, "beta", void 0);
  45611. __decorate([
  45612. BABYLON.serialize()
  45613. ], ArcRotateCamera.prototype, "radius", void 0);
  45614. __decorate([
  45615. BABYLON.serializeAsVector3("target")
  45616. ], ArcRotateCamera.prototype, "_target", void 0);
  45617. __decorate([
  45618. BABYLON.serialize()
  45619. ], ArcRotateCamera.prototype, "inertialAlphaOffset", void 0);
  45620. __decorate([
  45621. BABYLON.serialize()
  45622. ], ArcRotateCamera.prototype, "inertialBetaOffset", void 0);
  45623. __decorate([
  45624. BABYLON.serialize()
  45625. ], ArcRotateCamera.prototype, "inertialRadiusOffset", void 0);
  45626. __decorate([
  45627. BABYLON.serialize()
  45628. ], ArcRotateCamera.prototype, "lowerAlphaLimit", void 0);
  45629. __decorate([
  45630. BABYLON.serialize()
  45631. ], ArcRotateCamera.prototype, "upperAlphaLimit", void 0);
  45632. __decorate([
  45633. BABYLON.serialize()
  45634. ], ArcRotateCamera.prototype, "lowerBetaLimit", void 0);
  45635. __decorate([
  45636. BABYLON.serialize()
  45637. ], ArcRotateCamera.prototype, "upperBetaLimit", void 0);
  45638. __decorate([
  45639. BABYLON.serialize()
  45640. ], ArcRotateCamera.prototype, "lowerRadiusLimit", void 0);
  45641. __decorate([
  45642. BABYLON.serialize()
  45643. ], ArcRotateCamera.prototype, "upperRadiusLimit", void 0);
  45644. __decorate([
  45645. BABYLON.serialize()
  45646. ], ArcRotateCamera.prototype, "inertialPanningX", void 0);
  45647. __decorate([
  45648. BABYLON.serialize()
  45649. ], ArcRotateCamera.prototype, "inertialPanningY", void 0);
  45650. __decorate([
  45651. BABYLON.serialize()
  45652. ], ArcRotateCamera.prototype, "pinchToPanMaxDistance", void 0);
  45653. __decorate([
  45654. BABYLON.serialize()
  45655. ], ArcRotateCamera.prototype, "panningDistanceLimit", void 0);
  45656. __decorate([
  45657. BABYLON.serializeAsVector3()
  45658. ], ArcRotateCamera.prototype, "panningOriginTarget", void 0);
  45659. __decorate([
  45660. BABYLON.serialize()
  45661. ], ArcRotateCamera.prototype, "panningInertia", void 0);
  45662. __decorate([
  45663. BABYLON.serialize()
  45664. ], ArcRotateCamera.prototype, "zoomOnFactor", void 0);
  45665. __decorate([
  45666. BABYLON.serialize()
  45667. ], ArcRotateCamera.prototype, "allowUpsideDown", void 0);
  45668. return ArcRotateCamera;
  45669. }(BABYLON.TargetCamera));
  45670. BABYLON.ArcRotateCamera = ArcRotateCamera;
  45671. })(BABYLON || (BABYLON = {}));
  45672. //# sourceMappingURL=babylon.arcRotateCamera.js.map
  45673. "use strict";
  45674. var BABYLON;
  45675. (function (BABYLON) {
  45676. /**
  45677. * The HemisphericLight simulates the ambient environment light,
  45678. * so the passed direction is the light reflection direction, not the incoming direction.
  45679. */
  45680. var HemisphericLight = /** @class */ (function (_super) {
  45681. __extends(HemisphericLight, _super);
  45682. /**
  45683. * Creates a HemisphericLight object in the scene according to the passed direction (Vector3).
  45684. * The HemisphericLight simulates the ambient environment light, so the passed direction is the light reflection direction, not the incoming direction.
  45685. * The HemisphericLight can't cast shadows.
  45686. * Documentation : http://doc.babylonjs.com/tutorials/lights
  45687. * @param name The friendly name of the light
  45688. * @param direction The direction of the light reflection
  45689. * @param scene The scene the light belongs to
  45690. */
  45691. function HemisphericLight(name, direction, scene) {
  45692. var _this = _super.call(this, name, scene) || this;
  45693. /**
  45694. * The groundColor is the light in the opposite direction to the one specified during creation.
  45695. * 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.
  45696. */
  45697. _this.groundColor = new BABYLON.Color3(0.0, 0.0, 0.0);
  45698. _this.direction = direction || BABYLON.Vector3.Up();
  45699. return _this;
  45700. }
  45701. HemisphericLight.prototype._buildUniformLayout = function () {
  45702. this._uniformBuffer.addUniform("vLightData", 4);
  45703. this._uniformBuffer.addUniform("vLightDiffuse", 4);
  45704. this._uniformBuffer.addUniform("vLightSpecular", 3);
  45705. this._uniformBuffer.addUniform("vLightGround", 3);
  45706. this._uniformBuffer.addUniform("shadowsInfo", 3);
  45707. this._uniformBuffer.addUniform("depthValues", 2);
  45708. this._uniformBuffer.create();
  45709. };
  45710. /**
  45711. * Returns the string "HemisphericLight".
  45712. * @return The class name
  45713. */
  45714. HemisphericLight.prototype.getClassName = function () {
  45715. return "HemisphericLight";
  45716. };
  45717. /**
  45718. * Sets the HemisphericLight direction towards the passed target (Vector3).
  45719. * Returns the updated direction.
  45720. * @param target The target the direction should point to
  45721. * @return The computed direction
  45722. */
  45723. HemisphericLight.prototype.setDirectionToTarget = function (target) {
  45724. this.direction = BABYLON.Vector3.Normalize(target.subtract(BABYLON.Vector3.Zero()));
  45725. return this.direction;
  45726. };
  45727. /**
  45728. * Returns the shadow generator associated to the light.
  45729. * @returns Always null for hemispheric lights because it does not support shadows.
  45730. */
  45731. HemisphericLight.prototype.getShadowGenerator = function () {
  45732. return null;
  45733. };
  45734. /**
  45735. * Sets the passed Effect object with the HemisphericLight normalized direction and color and the passed name (string).
  45736. * @param effect The effect to update
  45737. * @param lightIndex The index of the light in the effect to update
  45738. * @returns The hemispheric light
  45739. */
  45740. HemisphericLight.prototype.transferToEffect = function (effect, lightIndex) {
  45741. var normalizeDirection = BABYLON.Vector3.Normalize(this.direction);
  45742. this._uniformBuffer.updateFloat4("vLightData", normalizeDirection.x, normalizeDirection.y, normalizeDirection.z, 0.0, lightIndex);
  45743. this._uniformBuffer.updateColor3("vLightGround", this.groundColor.scale(this.intensity), lightIndex);
  45744. return this;
  45745. };
  45746. /**
  45747. * @ignore internal use only.
  45748. */
  45749. HemisphericLight.prototype._getWorldMatrix = function () {
  45750. if (!this._worldMatrix) {
  45751. this._worldMatrix = BABYLON.Matrix.Identity();
  45752. }
  45753. return this._worldMatrix;
  45754. };
  45755. /**
  45756. * Returns the integer 3.
  45757. * @return The light Type id as a constant defines in Light.LIGHTTYPEID_x
  45758. */
  45759. HemisphericLight.prototype.getTypeID = function () {
  45760. return BABYLON.Light.LIGHTTYPEID_HEMISPHERICLIGHT;
  45761. };
  45762. __decorate([
  45763. BABYLON.serializeAsColor3()
  45764. ], HemisphericLight.prototype, "groundColor", void 0);
  45765. __decorate([
  45766. BABYLON.serializeAsVector3()
  45767. ], HemisphericLight.prototype, "direction", void 0);
  45768. return HemisphericLight;
  45769. }(BABYLON.Light));
  45770. BABYLON.HemisphericLight = HemisphericLight;
  45771. })(BABYLON || (BABYLON = {}));
  45772. //# sourceMappingURL=babylon.hemisphericLight.js.map
  45773. "use strict";
  45774. var BABYLON;
  45775. (function (BABYLON) {
  45776. /**
  45777. * Base implementation IShadowLight
  45778. * It groups all the common behaviour in order to reduce dupplication and better follow the DRY pattern.
  45779. */
  45780. var ShadowLight = /** @class */ (function (_super) {
  45781. __extends(ShadowLight, _super);
  45782. function ShadowLight() {
  45783. var _this = _super !== null && _super.apply(this, arguments) || this;
  45784. _this._needProjectionMatrixCompute = true;
  45785. return _this;
  45786. }
  45787. ShadowLight.prototype._setPosition = function (value) {
  45788. this._position = value;
  45789. };
  45790. Object.defineProperty(ShadowLight.prototype, "position", {
  45791. /**
  45792. * Sets the position the shadow will be casted from. Also use as the light position for both
  45793. * point and spot lights.
  45794. */
  45795. get: function () {
  45796. return this._position;
  45797. },
  45798. /**
  45799. * Sets the position the shadow will be casted from. Also use as the light position for both
  45800. * point and spot lights.
  45801. */
  45802. set: function (value) {
  45803. this._setPosition(value);
  45804. },
  45805. enumerable: true,
  45806. configurable: true
  45807. });
  45808. ShadowLight.prototype._setDirection = function (value) {
  45809. this._direction = value;
  45810. };
  45811. Object.defineProperty(ShadowLight.prototype, "direction", {
  45812. /**
  45813. * In 2d mode (needCube being false), gets the direction used to cast the shadow.
  45814. * Also use as the light direction on spot and directional lights.
  45815. */
  45816. get: function () {
  45817. return this._direction;
  45818. },
  45819. /**
  45820. * In 2d mode (needCube being false), sets the direction used to cast the shadow.
  45821. * Also use as the light direction on spot and directional lights.
  45822. */
  45823. set: function (value) {
  45824. this._setDirection(value);
  45825. },
  45826. enumerable: true,
  45827. configurable: true
  45828. });
  45829. Object.defineProperty(ShadowLight.prototype, "shadowMinZ", {
  45830. /**
  45831. * Gets the shadow projection clipping minimum z value.
  45832. */
  45833. get: function () {
  45834. return this._shadowMinZ;
  45835. },
  45836. /**
  45837. * Sets the shadow projection clipping minimum z value.
  45838. */
  45839. set: function (value) {
  45840. this._shadowMinZ = value;
  45841. this.forceProjectionMatrixCompute();
  45842. },
  45843. enumerable: true,
  45844. configurable: true
  45845. });
  45846. Object.defineProperty(ShadowLight.prototype, "shadowMaxZ", {
  45847. /**
  45848. * Sets the shadow projection clipping maximum z value.
  45849. */
  45850. get: function () {
  45851. return this._shadowMaxZ;
  45852. },
  45853. /**
  45854. * Gets the shadow projection clipping maximum z value.
  45855. */
  45856. set: function (value) {
  45857. this._shadowMaxZ = value;
  45858. this.forceProjectionMatrixCompute();
  45859. },
  45860. enumerable: true,
  45861. configurable: true
  45862. });
  45863. /**
  45864. * Computes the transformed information (transformedPosition and transformedDirection in World space) of the current light
  45865. * @returns true if the information has been computed, false if it does not need to (no parenting)
  45866. */
  45867. ShadowLight.prototype.computeTransformedInformation = function () {
  45868. if (this.parent && this.parent.getWorldMatrix) {
  45869. if (!this.transformedPosition) {
  45870. this.transformedPosition = BABYLON.Vector3.Zero();
  45871. }
  45872. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this.parent.getWorldMatrix(), this.transformedPosition);
  45873. // In case the direction is present.
  45874. if (this.direction) {
  45875. if (!this.transformedDirection) {
  45876. this.transformedDirection = BABYLON.Vector3.Zero();
  45877. }
  45878. BABYLON.Vector3.TransformNormalToRef(this.direction, this.parent.getWorldMatrix(), this.transformedDirection);
  45879. }
  45880. return true;
  45881. }
  45882. return false;
  45883. };
  45884. /**
  45885. * Return the depth scale used for the shadow map.
  45886. * @returns the depth scale.
  45887. */
  45888. ShadowLight.prototype.getDepthScale = function () {
  45889. return 50.0;
  45890. };
  45891. /**
  45892. * Get the direction to use to render the shadow map. In case of cube texture, the face index can be passed.
  45893. * @param faceIndex The index of the face we are computed the direction to generate shadow
  45894. * @returns The set direction in 2d mode otherwise the direction to the cubemap face if needCube() is true
  45895. */
  45896. ShadowLight.prototype.getShadowDirection = function (faceIndex) {
  45897. return this.transformedDirection ? this.transformedDirection : this.direction;
  45898. };
  45899. /**
  45900. * Returns the ShadowLight absolute position in the World.
  45901. * @returns the position vector in world space
  45902. */
  45903. ShadowLight.prototype.getAbsolutePosition = function () {
  45904. return this.transformedPosition ? this.transformedPosition : this.position;
  45905. };
  45906. /**
  45907. * Sets the ShadowLight direction toward the passed target.
  45908. * @param target The point tot target in local space
  45909. * @returns the updated ShadowLight direction
  45910. */
  45911. ShadowLight.prototype.setDirectionToTarget = function (target) {
  45912. this.direction = BABYLON.Vector3.Normalize(target.subtract(this.position));
  45913. return this.direction;
  45914. };
  45915. /**
  45916. * Returns the light rotation in euler definition.
  45917. * @returns the x y z rotation in local space.
  45918. */
  45919. ShadowLight.prototype.getRotation = function () {
  45920. this.direction.normalize();
  45921. var xaxis = BABYLON.Vector3.Cross(this.direction, BABYLON.Axis.Y);
  45922. var yaxis = BABYLON.Vector3.Cross(xaxis, this.direction);
  45923. return BABYLON.Vector3.RotationFromAxis(xaxis, yaxis, this.direction);
  45924. };
  45925. /**
  45926. * Returns whether or not the shadow generation require a cube texture or a 2d texture.
  45927. * @returns true if a cube texture needs to be use
  45928. */
  45929. ShadowLight.prototype.needCube = function () {
  45930. return false;
  45931. };
  45932. /**
  45933. * Detects if the projection matrix requires to be recomputed this frame.
  45934. * @returns true if it requires to be recomputed otherwise, false.
  45935. */
  45936. ShadowLight.prototype.needProjectionMatrixCompute = function () {
  45937. return this._needProjectionMatrixCompute;
  45938. };
  45939. /**
  45940. * Forces the shadow generator to recompute the projection matrix even if position and direction did not changed.
  45941. */
  45942. ShadowLight.prototype.forceProjectionMatrixCompute = function () {
  45943. this._needProjectionMatrixCompute = true;
  45944. };
  45945. /**
  45946. * Get the world matrix of the sahdow lights.
  45947. * @ignore Internal Use Only
  45948. */
  45949. ShadowLight.prototype._getWorldMatrix = function () {
  45950. if (!this._worldMatrix) {
  45951. this._worldMatrix = BABYLON.Matrix.Identity();
  45952. }
  45953. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, this._worldMatrix);
  45954. return this._worldMatrix;
  45955. };
  45956. /**
  45957. * Gets the minZ used for shadow according to both the scene and the light.
  45958. * @param activeCamera The camera we are returning the min for
  45959. * @returns the depth min z
  45960. */
  45961. ShadowLight.prototype.getDepthMinZ = function (activeCamera) {
  45962. return this.shadowMinZ !== undefined ? this.shadowMinZ : activeCamera.minZ;
  45963. };
  45964. /**
  45965. * Gets the maxZ used for shadow according to both the scene and the light.
  45966. * @param activeCamera The camera we are returning the max for
  45967. * @returns the depth max z
  45968. */
  45969. ShadowLight.prototype.getDepthMaxZ = function (activeCamera) {
  45970. return this.shadowMaxZ !== undefined ? this.shadowMaxZ : activeCamera.maxZ;
  45971. };
  45972. /**
  45973. * Sets the shadow projection matrix in parameter to the generated projection matrix.
  45974. * @param matrix The materix to updated with the projection information
  45975. * @param viewMatrix The transform matrix of the light
  45976. * @param renderList The list of mesh to render in the map
  45977. * @returns The current light
  45978. */
  45979. ShadowLight.prototype.setShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  45980. if (this.customProjectionMatrixBuilder) {
  45981. this.customProjectionMatrixBuilder(viewMatrix, renderList, matrix);
  45982. }
  45983. else {
  45984. this._setDefaultShadowProjectionMatrix(matrix, viewMatrix, renderList);
  45985. }
  45986. return this;
  45987. };
  45988. __decorate([
  45989. BABYLON.serializeAsVector3()
  45990. ], ShadowLight.prototype, "position", null);
  45991. __decorate([
  45992. BABYLON.serializeAsVector3()
  45993. ], ShadowLight.prototype, "direction", null);
  45994. __decorate([
  45995. BABYLON.serialize()
  45996. ], ShadowLight.prototype, "shadowMinZ", null);
  45997. __decorate([
  45998. BABYLON.serialize()
  45999. ], ShadowLight.prototype, "shadowMaxZ", null);
  46000. return ShadowLight;
  46001. }(BABYLON.Light));
  46002. BABYLON.ShadowLight = ShadowLight;
  46003. })(BABYLON || (BABYLON = {}));
  46004. //# sourceMappingURL=babylon.shadowLight.js.map
  46005. "use strict";
  46006. var BABYLON;
  46007. (function (BABYLON) {
  46008. /**
  46009. * A point light is a light defined by an unique point in world space.
  46010. * The light is emitted in every direction from this point.
  46011. * A good example of a point light is a standard light bulb.
  46012. * Documentation: https://doc.babylonjs.com/babylon101/lights
  46013. */
  46014. var PointLight = /** @class */ (function (_super) {
  46015. __extends(PointLight, _super);
  46016. /**
  46017. * Creates a PointLight object from the passed name and position (Vector3) and adds it in the scene.
  46018. * A PointLight emits the light in every direction.
  46019. * It can cast shadows.
  46020. * If the scene camera is already defined and you want to set your PointLight at the camera position, just set it :
  46021. * ```javascript
  46022. * var pointLight = new BABYLON.PointLight("pl", camera.position, scene);
  46023. * ```
  46024. * Documentation : http://doc.babylonjs.com/tutorials/lights
  46025. * @param name The light friendly name
  46026. * @param position The position of the point light in the scene
  46027. * @param scene The scene the lights belongs to
  46028. */
  46029. function PointLight(name, position, scene) {
  46030. var _this = _super.call(this, name, scene) || this;
  46031. _this._shadowAngle = Math.PI / 2;
  46032. _this.position = position;
  46033. return _this;
  46034. }
  46035. Object.defineProperty(PointLight.prototype, "shadowAngle", {
  46036. /**
  46037. * Getter: In case of direction provided, the shadow will not use a cube texture but simulate a spot shadow as a fallback
  46038. * This specifies what angle the shadow will use to be created.
  46039. *
  46040. * It default to 90 degrees to work nicely with the cube texture generation for point lights shadow maps.
  46041. */
  46042. get: function () {
  46043. return this._shadowAngle;
  46044. },
  46045. /**
  46046. * Setter: In case of direction provided, the shadow will not use a cube texture but simulate a spot shadow as a fallback
  46047. * This specifies what angle the shadow will use to be created.
  46048. *
  46049. * It default to 90 degrees to work nicely with the cube texture generation for point lights shadow maps.
  46050. */
  46051. set: function (value) {
  46052. this._shadowAngle = value;
  46053. this.forceProjectionMatrixCompute();
  46054. },
  46055. enumerable: true,
  46056. configurable: true
  46057. });
  46058. Object.defineProperty(PointLight.prototype, "direction", {
  46059. /**
  46060. * Gets the direction if it has been set.
  46061. * In case of direction provided, the shadow will not use a cube texture but simulate a spot shadow as a fallback
  46062. */
  46063. get: function () {
  46064. return this._direction;
  46065. },
  46066. /**
  46067. * In case of direction provided, the shadow will not use a cube texture but simulate a spot shadow as a fallback
  46068. */
  46069. set: function (value) {
  46070. var previousNeedCube = this.needCube();
  46071. this._direction = value;
  46072. if (this.needCube() !== previousNeedCube && this._shadowGenerator) {
  46073. this._shadowGenerator.recreateShadowMap();
  46074. }
  46075. },
  46076. enumerable: true,
  46077. configurable: true
  46078. });
  46079. /**
  46080. * Returns the string "PointLight"
  46081. * @returns the class name
  46082. */
  46083. PointLight.prototype.getClassName = function () {
  46084. return "PointLight";
  46085. };
  46086. /**
  46087. * Returns the integer 0.
  46088. * @returns The light Type id as a constant defines in Light.LIGHTTYPEID_x
  46089. */
  46090. PointLight.prototype.getTypeID = function () {
  46091. return BABYLON.Light.LIGHTTYPEID_POINTLIGHT;
  46092. };
  46093. /**
  46094. * Specifies wether or not the shadowmap should be a cube texture.
  46095. * @returns true if the shadowmap needs to be a cube texture.
  46096. */
  46097. PointLight.prototype.needCube = function () {
  46098. return !this.direction;
  46099. };
  46100. /**
  46101. * Returns a new Vector3 aligned with the PointLight cube system according to the passed cube face index (integer).
  46102. * @param faceIndex The index of the face we are computed the direction to generate shadow
  46103. * @returns The set direction in 2d mode otherwise the direction to the cubemap face if needCube() is true
  46104. */
  46105. PointLight.prototype.getShadowDirection = function (faceIndex) {
  46106. if (this.direction) {
  46107. return _super.prototype.getShadowDirection.call(this, faceIndex);
  46108. }
  46109. else {
  46110. switch (faceIndex) {
  46111. case 0:
  46112. return new BABYLON.Vector3(1.0, 0.0, 0.0);
  46113. case 1:
  46114. return new BABYLON.Vector3(-1.0, 0.0, 0.0);
  46115. case 2:
  46116. return new BABYLON.Vector3(0.0, -1.0, 0.0);
  46117. case 3:
  46118. return new BABYLON.Vector3(0.0, 1.0, 0.0);
  46119. case 4:
  46120. return new BABYLON.Vector3(0.0, 0.0, 1.0);
  46121. case 5:
  46122. return new BABYLON.Vector3(0.0, 0.0, -1.0);
  46123. }
  46124. }
  46125. return BABYLON.Vector3.Zero();
  46126. };
  46127. /**
  46128. * Sets the passed matrix "matrix" as a left-handed perspective projection matrix with the following settings :
  46129. * - fov = PI / 2
  46130. * - aspect ratio : 1.0
  46131. * - z-near and far equal to the active camera minZ and maxZ.
  46132. * Returns the PointLight.
  46133. */
  46134. PointLight.prototype._setDefaultShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  46135. var activeCamera = this.getScene().activeCamera;
  46136. if (!activeCamera) {
  46137. return;
  46138. }
  46139. BABYLON.Matrix.PerspectiveFovLHToRef(this.shadowAngle, 1.0, this.getDepthMinZ(activeCamera), this.getDepthMaxZ(activeCamera), matrix);
  46140. };
  46141. PointLight.prototype._buildUniformLayout = function () {
  46142. this._uniformBuffer.addUniform("vLightData", 4);
  46143. this._uniformBuffer.addUniform("vLightDiffuse", 4);
  46144. this._uniformBuffer.addUniform("vLightSpecular", 3);
  46145. this._uniformBuffer.addUniform("shadowsInfo", 3);
  46146. this._uniformBuffer.addUniform("depthValues", 2);
  46147. this._uniformBuffer.create();
  46148. };
  46149. /**
  46150. * Sets the passed Effect "effect" with the PointLight transformed position (or position, if none) and passed name (string).
  46151. * @param effect The effect to update
  46152. * @param lightIndex The index of the light in the effect to update
  46153. * @returns The point light
  46154. */
  46155. PointLight.prototype.transferToEffect = function (effect, lightIndex) {
  46156. if (this.computeTransformedInformation()) {
  46157. this._uniformBuffer.updateFloat4("vLightData", this.transformedPosition.x, this.transformedPosition.y, this.transformedPosition.z, 0.0, lightIndex);
  46158. return this;
  46159. }
  46160. this._uniformBuffer.updateFloat4("vLightData", this.position.x, this.position.y, this.position.z, 0, lightIndex);
  46161. return this;
  46162. };
  46163. __decorate([
  46164. BABYLON.serialize()
  46165. ], PointLight.prototype, "shadowAngle", null);
  46166. return PointLight;
  46167. }(BABYLON.ShadowLight));
  46168. BABYLON.PointLight = PointLight;
  46169. })(BABYLON || (BABYLON = {}));
  46170. //# sourceMappingURL=babylon.pointLight.js.map
  46171. "use strict";
  46172. var BABYLON;
  46173. (function (BABYLON) {
  46174. /**
  46175. * A directional light is defined by a direction (what a surprise!).
  46176. * The light is emitted from everywhere in the specified direction, and has an infinite range.
  46177. * 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.
  46178. * Documentation: https://doc.babylonjs.com/babylon101/lights
  46179. */
  46180. var DirectionalLight = /** @class */ (function (_super) {
  46181. __extends(DirectionalLight, _super);
  46182. /**
  46183. * Creates a DirectionalLight object in the scene, oriented towards the passed direction (Vector3).
  46184. * The directional light is emitted from everywhere in the given direction.
  46185. * It can cast shawdows.
  46186. * Documentation : http://doc.babylonjs.com/tutorials/lights
  46187. * @param name The friendly name of the light
  46188. * @param direction The direction of the light
  46189. * @param scene The scene the light belongs to
  46190. */
  46191. function DirectionalLight(name, direction, scene) {
  46192. var _this = _super.call(this, name, scene) || this;
  46193. _this._shadowFrustumSize = 0;
  46194. _this._shadowOrthoScale = 0.1;
  46195. /**
  46196. * Automatically compute the projection matrix to best fit (including all the casters)
  46197. * on each frame.
  46198. */
  46199. _this.autoUpdateExtends = true;
  46200. // Cache
  46201. _this._orthoLeft = Number.MAX_VALUE;
  46202. _this._orthoRight = Number.MIN_VALUE;
  46203. _this._orthoTop = Number.MIN_VALUE;
  46204. _this._orthoBottom = Number.MAX_VALUE;
  46205. _this.position = direction.scale(-1.0);
  46206. _this.direction = direction;
  46207. return _this;
  46208. }
  46209. Object.defineProperty(DirectionalLight.prototype, "shadowFrustumSize", {
  46210. /**
  46211. * Fix frustum size for the shadow generation. This is disabled if the value is 0.
  46212. */
  46213. get: function () {
  46214. return this._shadowFrustumSize;
  46215. },
  46216. /**
  46217. * Specifies a fix frustum size for the shadow generation.
  46218. */
  46219. set: function (value) {
  46220. this._shadowFrustumSize = value;
  46221. this.forceProjectionMatrixCompute();
  46222. },
  46223. enumerable: true,
  46224. configurable: true
  46225. });
  46226. Object.defineProperty(DirectionalLight.prototype, "shadowOrthoScale", {
  46227. /**
  46228. * Gets the shadow projection scale against the optimal computed one.
  46229. * 0.1 by default which means that the projection window is increase by 10% from the optimal size.
  46230. * This does not impact in fixed frustum size (shadowFrustumSize being set)
  46231. */
  46232. get: function () {
  46233. return this._shadowOrthoScale;
  46234. },
  46235. /**
  46236. * Sets the shadow projection scale against the optimal computed one.
  46237. * 0.1 by default which means that the projection window is increase by 10% from the optimal size.
  46238. * This does not impact in fixed frustum size (shadowFrustumSize being set)
  46239. */
  46240. set: function (value) {
  46241. this._shadowOrthoScale = value;
  46242. this.forceProjectionMatrixCompute();
  46243. },
  46244. enumerable: true,
  46245. configurable: true
  46246. });
  46247. /**
  46248. * Returns the string "DirectionalLight".
  46249. * @return The class name
  46250. */
  46251. DirectionalLight.prototype.getClassName = function () {
  46252. return "DirectionalLight";
  46253. };
  46254. /**
  46255. * Returns the integer 1.
  46256. * @return The light Type id as a constant defines in Light.LIGHTTYPEID_x
  46257. */
  46258. DirectionalLight.prototype.getTypeID = function () {
  46259. return BABYLON.Light.LIGHTTYPEID_DIRECTIONALLIGHT;
  46260. };
  46261. /**
  46262. * Sets the passed matrix "matrix" as projection matrix for the shadows cast by the light according to the passed view matrix.
  46263. * Returns the DirectionalLight Shadow projection matrix.
  46264. */
  46265. DirectionalLight.prototype._setDefaultShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  46266. if (this.shadowFrustumSize > 0) {
  46267. this._setDefaultFixedFrustumShadowProjectionMatrix(matrix, viewMatrix);
  46268. }
  46269. else {
  46270. this._setDefaultAutoExtendShadowProjectionMatrix(matrix, viewMatrix, renderList);
  46271. }
  46272. };
  46273. /**
  46274. * Sets the passed matrix "matrix" as fixed frustum projection matrix for the shadows cast by the light according to the passed view matrix.
  46275. * Returns the DirectionalLight Shadow projection matrix.
  46276. */
  46277. DirectionalLight.prototype._setDefaultFixedFrustumShadowProjectionMatrix = function (matrix, viewMatrix) {
  46278. var activeCamera = this.getScene().activeCamera;
  46279. if (!activeCamera) {
  46280. return;
  46281. }
  46282. BABYLON.Matrix.OrthoLHToRef(this.shadowFrustumSize, this.shadowFrustumSize, this.shadowMinZ !== undefined ? this.shadowMinZ : activeCamera.minZ, this.shadowMaxZ !== undefined ? this.shadowMaxZ : activeCamera.maxZ, matrix);
  46283. };
  46284. /**
  46285. * Sets the passed matrix "matrix" as auto extend projection matrix for the shadows cast by the light according to the passed view matrix.
  46286. * Returns the DirectionalLight Shadow projection matrix.
  46287. */
  46288. DirectionalLight.prototype._setDefaultAutoExtendShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  46289. var activeCamera = this.getScene().activeCamera;
  46290. if (!activeCamera) {
  46291. return;
  46292. }
  46293. // Check extends
  46294. if (this.autoUpdateExtends || this._orthoLeft === Number.MAX_VALUE) {
  46295. var tempVector3 = BABYLON.Vector3.Zero();
  46296. this._orthoLeft = Number.MAX_VALUE;
  46297. this._orthoRight = Number.MIN_VALUE;
  46298. this._orthoTop = Number.MIN_VALUE;
  46299. this._orthoBottom = Number.MAX_VALUE;
  46300. for (var meshIndex = 0; meshIndex < renderList.length; meshIndex++) {
  46301. var mesh = renderList[meshIndex];
  46302. if (!mesh) {
  46303. continue;
  46304. }
  46305. var boundingInfo = mesh.getBoundingInfo();
  46306. var boundingBox = boundingInfo.boundingBox;
  46307. for (var index = 0; index < boundingBox.vectorsWorld.length; index++) {
  46308. BABYLON.Vector3.TransformCoordinatesToRef(boundingBox.vectorsWorld[index], viewMatrix, tempVector3);
  46309. if (tempVector3.x < this._orthoLeft)
  46310. this._orthoLeft = tempVector3.x;
  46311. if (tempVector3.y < this._orthoBottom)
  46312. this._orthoBottom = tempVector3.y;
  46313. if (tempVector3.x > this._orthoRight)
  46314. this._orthoRight = tempVector3.x;
  46315. if (tempVector3.y > this._orthoTop)
  46316. this._orthoTop = tempVector3.y;
  46317. }
  46318. }
  46319. }
  46320. var xOffset = this._orthoRight - this._orthoLeft;
  46321. var yOffset = this._orthoTop - this._orthoBottom;
  46322. 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);
  46323. };
  46324. DirectionalLight.prototype._buildUniformLayout = function () {
  46325. this._uniformBuffer.addUniform("vLightData", 4);
  46326. this._uniformBuffer.addUniform("vLightDiffuse", 4);
  46327. this._uniformBuffer.addUniform("vLightSpecular", 3);
  46328. this._uniformBuffer.addUniform("shadowsInfo", 3);
  46329. this._uniformBuffer.addUniform("depthValues", 2);
  46330. this._uniformBuffer.create();
  46331. };
  46332. /**
  46333. * Sets the passed Effect object with the DirectionalLight transformed position (or position if not parented) and the passed name.
  46334. * @param effect The effect to update
  46335. * @param lightIndex The index of the light in the effect to update
  46336. * @returns The directional light
  46337. */
  46338. DirectionalLight.prototype.transferToEffect = function (effect, lightIndex) {
  46339. if (this.computeTransformedInformation()) {
  46340. this._uniformBuffer.updateFloat4("vLightData", this.transformedDirection.x, this.transformedDirection.y, this.transformedDirection.z, 1, lightIndex);
  46341. return this;
  46342. }
  46343. this._uniformBuffer.updateFloat4("vLightData", this.direction.x, this.direction.y, this.direction.z, 1, lightIndex);
  46344. return this;
  46345. };
  46346. /**
  46347. * Gets the minZ used for shadow according to both the scene and the light.
  46348. *
  46349. * Values are fixed on directional lights as it relies on an ortho projection hence the need to convert being
  46350. * -1 and 1 to 0 and 1 doing (depth + min) / (min + max) -> (depth + 1) / (1 + 1) -> (depth * 0.5) + 0.5.
  46351. * @param activeCamera The camera we are returning the min for
  46352. * @returns the depth min z
  46353. */
  46354. DirectionalLight.prototype.getDepthMinZ = function (activeCamera) {
  46355. return 1;
  46356. };
  46357. /**
  46358. * Gets the maxZ used for shadow according to both the scene and the light.
  46359. *
  46360. * Values are fixed on directional lights as it relies on an ortho projection hence the need to convert being
  46361. * -1 and 1 to 0 and 1 doing (depth + min) / (min + max) -> (depth + 1) / (1 + 1) -> (depth * 0.5) + 0.5.
  46362. * @param activeCamera The camera we are returning the max for
  46363. * @returns the depth max z
  46364. */
  46365. DirectionalLight.prototype.getDepthMaxZ = function (activeCamera) {
  46366. return 1;
  46367. };
  46368. __decorate([
  46369. BABYLON.serialize()
  46370. ], DirectionalLight.prototype, "shadowFrustumSize", null);
  46371. __decorate([
  46372. BABYLON.serialize()
  46373. ], DirectionalLight.prototype, "shadowOrthoScale", null);
  46374. __decorate([
  46375. BABYLON.serialize()
  46376. ], DirectionalLight.prototype, "autoUpdateExtends", void 0);
  46377. return DirectionalLight;
  46378. }(BABYLON.ShadowLight));
  46379. BABYLON.DirectionalLight = DirectionalLight;
  46380. })(BABYLON || (BABYLON = {}));
  46381. //# sourceMappingURL=babylon.directionalLight.js.map
  46382. "use strict";
  46383. var BABYLON;
  46384. (function (BABYLON) {
  46385. /**
  46386. * A spot light is defined by a position, a direction, an angle, and an exponent.
  46387. * These values define a cone of light starting from the position, emitting toward the direction.
  46388. * The angle, in radians, defines the size (field of illumination) of the spotlight's conical beam,
  46389. * and the exponent defines the speed of the decay of the light with distance (reach).
  46390. * Documentation: https://doc.babylonjs.com/babylon101/lights
  46391. */
  46392. var SpotLight = /** @class */ (function (_super) {
  46393. __extends(SpotLight, _super);
  46394. /**
  46395. * Creates a SpotLight object in the scene. A spot light is a simply light oriented cone.
  46396. * It can cast shadows.
  46397. * Documentation : http://doc.babylonjs.com/tutorials/lights
  46398. * @param name The light friendly name
  46399. * @param position The position of the spot light in the scene
  46400. * @param direction The direction of the light in the scene
  46401. * @param angle The cone angle of the light in Radians
  46402. * @param exponent The light decay speed with the distance from the emission spot
  46403. * @param scene The scene the lights belongs to
  46404. */
  46405. function SpotLight(name, position, direction, angle, exponent, scene) {
  46406. var _this = _super.call(this, name, scene) || this;
  46407. _this._projectionTextureMatrix = BABYLON.Matrix.Zero();
  46408. _this._projectionTextureLightNear = 1e-6;
  46409. _this._projectionTextureLightFar = 1000.0;
  46410. _this._projectionTextureUpDirection = BABYLON.Vector3.Up();
  46411. _this._projectionTextureViewLightDirty = true;
  46412. _this._projectionTextureProjectionLightDirty = true;
  46413. _this._projectionTextureDirty = true;
  46414. _this._projectionTextureViewTargetVector = BABYLON.Vector3.Zero();
  46415. _this._projectionTextureViewLightMatrix = BABYLON.Matrix.Zero();
  46416. _this._projectionTextureProjectionLightMatrix = BABYLON.Matrix.Zero();
  46417. _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);
  46418. _this.position = position;
  46419. _this.direction = direction;
  46420. _this.angle = angle;
  46421. _this.exponent = exponent;
  46422. return _this;
  46423. }
  46424. Object.defineProperty(SpotLight.prototype, "angle", {
  46425. /**
  46426. * Gets the cone angle of the spot light in Radians.
  46427. */
  46428. get: function () {
  46429. return this._angle;
  46430. },
  46431. /**
  46432. * Sets the cone angle of the spot light in Radians.
  46433. */
  46434. set: function (value) {
  46435. this._angle = value;
  46436. this._projectionTextureProjectionLightDirty = true;
  46437. this.forceProjectionMatrixCompute();
  46438. },
  46439. enumerable: true,
  46440. configurable: true
  46441. });
  46442. Object.defineProperty(SpotLight.prototype, "shadowAngleScale", {
  46443. /**
  46444. * Allows scaling the angle of the light for shadow generation only.
  46445. */
  46446. get: function () {
  46447. return this._shadowAngleScale;
  46448. },
  46449. /**
  46450. * Allows scaling the angle of the light for shadow generation only.
  46451. */
  46452. set: function (value) {
  46453. this._shadowAngleScale = value;
  46454. this.forceProjectionMatrixCompute();
  46455. },
  46456. enumerable: true,
  46457. configurable: true
  46458. });
  46459. Object.defineProperty(SpotLight.prototype, "projectionTextureMatrix", {
  46460. /**
  46461. * Allows reading the projecton texture
  46462. */
  46463. get: function () {
  46464. return this._projectionTextureMatrix;
  46465. },
  46466. enumerable: true,
  46467. configurable: true
  46468. });
  46469. ;
  46470. Object.defineProperty(SpotLight.prototype, "projectionTextureLightNear", {
  46471. /**
  46472. * Gets the near clip of the Spotlight for texture projection.
  46473. */
  46474. get: function () {
  46475. return this._projectionTextureLightNear;
  46476. },
  46477. /**
  46478. * Sets the near clip of the Spotlight for texture projection.
  46479. */
  46480. set: function (value) {
  46481. this._projectionTextureLightNear = value;
  46482. this._projectionTextureProjectionLightDirty = true;
  46483. },
  46484. enumerable: true,
  46485. configurable: true
  46486. });
  46487. Object.defineProperty(SpotLight.prototype, "projectionTextureLightFar", {
  46488. /**
  46489. * Gets the far clip of the Spotlight for texture projection.
  46490. */
  46491. get: function () {
  46492. return this._projectionTextureLightFar;
  46493. },
  46494. /**
  46495. * Sets the far clip of the Spotlight for texture projection.
  46496. */
  46497. set: function (value) {
  46498. this._projectionTextureLightFar = value;
  46499. this._projectionTextureProjectionLightDirty = true;
  46500. },
  46501. enumerable: true,
  46502. configurable: true
  46503. });
  46504. Object.defineProperty(SpotLight.prototype, "projectionTextureUpDirection", {
  46505. /**
  46506. * Gets the Up vector of the Spotlight for texture projection.
  46507. */
  46508. get: function () {
  46509. return this._projectionTextureUpDirection;
  46510. },
  46511. /**
  46512. * Sets the Up vector of the Spotlight for texture projection.
  46513. */
  46514. set: function (value) {
  46515. this._projectionTextureUpDirection = value;
  46516. this._projectionTextureProjectionLightDirty = true;
  46517. },
  46518. enumerable: true,
  46519. configurable: true
  46520. });
  46521. ;
  46522. Object.defineProperty(SpotLight.prototype, "projectionTexture", {
  46523. /**
  46524. * Gets the projection texture of the light.
  46525. */
  46526. get: function () {
  46527. return this._projectionTexture;
  46528. },
  46529. /**
  46530. * Sets the projection texture of the light.
  46531. */
  46532. set: function (value) {
  46533. this._projectionTexture = value;
  46534. this._projectionTextureDirty = true;
  46535. },
  46536. enumerable: true,
  46537. configurable: true
  46538. });
  46539. /**
  46540. * Returns the string "SpotLight".
  46541. * @returns the class name
  46542. */
  46543. SpotLight.prototype.getClassName = function () {
  46544. return "SpotLight";
  46545. };
  46546. /**
  46547. * Returns the integer 2.
  46548. * @returns The light Type id as a constant defines in Light.LIGHTTYPEID_x
  46549. */
  46550. SpotLight.prototype.getTypeID = function () {
  46551. return BABYLON.Light.LIGHTTYPEID_SPOTLIGHT;
  46552. };
  46553. /**
  46554. * Overrides the direction setter to recompute the projection texture view light Matrix.
  46555. */
  46556. SpotLight.prototype._setDirection = function (value) {
  46557. _super.prototype._setDirection.call(this, value);
  46558. this._projectionTextureViewLightDirty = true;
  46559. };
  46560. /**
  46561. * Overrides the position setter to recompute the projection texture view light Matrix.
  46562. */
  46563. SpotLight.prototype._setPosition = function (value) {
  46564. _super.prototype._setPosition.call(this, value);
  46565. this._projectionTextureViewLightDirty = true;
  46566. };
  46567. /**
  46568. * 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.
  46569. * Returns the SpotLight.
  46570. */
  46571. SpotLight.prototype._setDefaultShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  46572. var activeCamera = this.getScene().activeCamera;
  46573. if (!activeCamera) {
  46574. return;
  46575. }
  46576. this._shadowAngleScale = this._shadowAngleScale || 1;
  46577. var angle = this._shadowAngleScale * this._angle;
  46578. BABYLON.Matrix.PerspectiveFovLHToRef(angle, 1.0, this.getDepthMinZ(activeCamera), this.getDepthMaxZ(activeCamera), matrix);
  46579. };
  46580. SpotLight.prototype._computeProjectionTextureViewLightMatrix = function () {
  46581. this._projectionTextureViewLightDirty = false;
  46582. this._projectionTextureDirty = true;
  46583. this.position.addToRef(this.direction, this._projectionTextureViewTargetVector);
  46584. BABYLON.Matrix.LookAtLHToRef(this.position, this._projectionTextureViewTargetVector, this._projectionTextureUpDirection, this._projectionTextureViewLightMatrix);
  46585. };
  46586. SpotLight.prototype._computeProjectionTextureProjectionLightMatrix = function () {
  46587. this._projectionTextureProjectionLightDirty = false;
  46588. this._projectionTextureDirty = true;
  46589. var light_far = this.projectionTextureLightFar;
  46590. var light_near = this.projectionTextureLightNear;
  46591. var P = light_far / (light_far - light_near);
  46592. var Q = -P * light_near;
  46593. var S = 1.0 / Math.tan(this._angle / 2.0);
  46594. var A = 1.0;
  46595. 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);
  46596. };
  46597. /**
  46598. * Main function for light texture projection matrix computing.
  46599. */
  46600. SpotLight.prototype._computeProjectionTextureMatrix = function () {
  46601. this._projectionTextureDirty = false;
  46602. this._projectionTextureViewLightMatrix.multiplyToRef(this._projectionTextureProjectionLightMatrix, this._projectionTextureMatrix);
  46603. this._projectionTextureMatrix.multiplyToRef(this._projectionTextureScalingMatrix, this._projectionTextureMatrix);
  46604. };
  46605. SpotLight.prototype._buildUniformLayout = function () {
  46606. this._uniformBuffer.addUniform("vLightData", 4);
  46607. this._uniformBuffer.addUniform("vLightDiffuse", 4);
  46608. this._uniformBuffer.addUniform("vLightSpecular", 3);
  46609. this._uniformBuffer.addUniform("vLightDirection", 3);
  46610. this._uniformBuffer.addUniform("shadowsInfo", 3);
  46611. this._uniformBuffer.addUniform("depthValues", 2);
  46612. this._uniformBuffer.create();
  46613. };
  46614. /**
  46615. * Sets the passed Effect object with the SpotLight transfomed position (or position if not parented) and normalized direction.
  46616. * @param effect The effect to update
  46617. * @param lightIndex The index of the light in the effect to update
  46618. * @returns The spot light
  46619. */
  46620. SpotLight.prototype.transferToEffect = function (effect, lightIndex) {
  46621. var normalizeDirection;
  46622. if (this.computeTransformedInformation()) {
  46623. this._uniformBuffer.updateFloat4("vLightData", this.transformedPosition.x, this.transformedPosition.y, this.transformedPosition.z, this.exponent, lightIndex);
  46624. normalizeDirection = BABYLON.Vector3.Normalize(this.transformedDirection);
  46625. }
  46626. else {
  46627. this._uniformBuffer.updateFloat4("vLightData", this.position.x, this.position.y, this.position.z, this.exponent, lightIndex);
  46628. normalizeDirection = BABYLON.Vector3.Normalize(this.direction);
  46629. }
  46630. this._uniformBuffer.updateFloat4("vLightDirection", normalizeDirection.x, normalizeDirection.y, normalizeDirection.z, Math.cos(this.angle * 0.5), lightIndex);
  46631. if (this.projectionTexture && this.projectionTexture.isReady()) {
  46632. if (this._projectionTextureViewLightDirty) {
  46633. this._computeProjectionTextureViewLightMatrix();
  46634. }
  46635. if (this._projectionTextureProjectionLightDirty) {
  46636. this._computeProjectionTextureProjectionLightMatrix();
  46637. }
  46638. if (this._projectionTextureDirty) {
  46639. this._computeProjectionTextureMatrix();
  46640. }
  46641. effect.setMatrix("textureProjectionMatrix" + lightIndex, this._projectionTextureMatrix);
  46642. effect.setTexture("projectionLightSampler" + lightIndex, this.projectionTexture);
  46643. }
  46644. return this;
  46645. };
  46646. /**
  46647. * Disposes the light and the associated resources.
  46648. */
  46649. SpotLight.prototype.dispose = function () {
  46650. _super.prototype.dispose.call(this);
  46651. if (this._projectionTexture) {
  46652. this._projectionTexture.dispose();
  46653. }
  46654. };
  46655. __decorate([
  46656. BABYLON.serialize()
  46657. ], SpotLight.prototype, "angle", null);
  46658. __decorate([
  46659. BABYLON.serialize()
  46660. ], SpotLight.prototype, "shadowAngleScale", null);
  46661. __decorate([
  46662. BABYLON.serialize()
  46663. ], SpotLight.prototype, "exponent", void 0);
  46664. __decorate([
  46665. BABYLON.serialize()
  46666. ], SpotLight.prototype, "projectionTextureLightNear", null);
  46667. __decorate([
  46668. BABYLON.serialize()
  46669. ], SpotLight.prototype, "projectionTextureLightFar", null);
  46670. __decorate([
  46671. BABYLON.serialize()
  46672. ], SpotLight.prototype, "projectionTextureUpDirection", null);
  46673. __decorate([
  46674. BABYLON.serializeAsTexture("projectedLightTexture")
  46675. ], SpotLight.prototype, "_projectionTexture", void 0);
  46676. return SpotLight;
  46677. }(BABYLON.ShadowLight));
  46678. BABYLON.SpotLight = SpotLight;
  46679. })(BABYLON || (BABYLON = {}));
  46680. //# sourceMappingURL=babylon.spotLight.js.map
  46681. "use strict";
  46682. var BABYLON;
  46683. (function (BABYLON) {
  46684. /**
  46685. * Class used to override all child animations of a given target
  46686. */
  46687. var AnimationPropertiesOverride = /** @class */ (function () {
  46688. function AnimationPropertiesOverride() {
  46689. /**
  46690. * Gets or sets a value indicating if animation blending must be used
  46691. */
  46692. this.enableBlending = false;
  46693. /**
  46694. * Gets or sets the blending speed to use when enableBlending is true
  46695. */
  46696. this.blendingSpeed = 0.01;
  46697. /**
  46698. * Gets or sets the default loop mode to use
  46699. */
  46700. this.loopMode = BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE;
  46701. }
  46702. return AnimationPropertiesOverride;
  46703. }());
  46704. BABYLON.AnimationPropertiesOverride = AnimationPropertiesOverride;
  46705. })(BABYLON || (BABYLON = {}));
  46706. //# sourceMappingURL=babylon.animationPropertiesOverride.js.map
  46707. "use strict";
  46708. var BABYLON;
  46709. (function (BABYLON) {
  46710. var AnimationRange = /** @class */ (function () {
  46711. function AnimationRange(name, from, to) {
  46712. this.name = name;
  46713. this.from = from;
  46714. this.to = to;
  46715. }
  46716. AnimationRange.prototype.clone = function () {
  46717. return new AnimationRange(this.name, this.from, this.to);
  46718. };
  46719. return AnimationRange;
  46720. }());
  46721. BABYLON.AnimationRange = AnimationRange;
  46722. /**
  46723. * Composed of a frame, and an action function
  46724. */
  46725. var AnimationEvent = /** @class */ (function () {
  46726. function AnimationEvent(frame, action, onlyOnce) {
  46727. this.frame = frame;
  46728. this.action = action;
  46729. this.onlyOnce = onlyOnce;
  46730. this.isDone = false;
  46731. }
  46732. return AnimationEvent;
  46733. }());
  46734. BABYLON.AnimationEvent = AnimationEvent;
  46735. var PathCursor = /** @class */ (function () {
  46736. function PathCursor(path) {
  46737. this.path = path;
  46738. this._onchange = new Array();
  46739. this.value = 0;
  46740. this.animations = new Array();
  46741. }
  46742. PathCursor.prototype.getPoint = function () {
  46743. var point = this.path.getPointAtLengthPosition(this.value);
  46744. return new BABYLON.Vector3(point.x, 0, point.y);
  46745. };
  46746. PathCursor.prototype.moveAhead = function (step) {
  46747. if (step === void 0) { step = 0.002; }
  46748. this.move(step);
  46749. return this;
  46750. };
  46751. PathCursor.prototype.moveBack = function (step) {
  46752. if (step === void 0) { step = 0.002; }
  46753. this.move(-step);
  46754. return this;
  46755. };
  46756. PathCursor.prototype.move = function (step) {
  46757. if (Math.abs(step) > 1) {
  46758. throw "step size should be less than 1.";
  46759. }
  46760. this.value += step;
  46761. this.ensureLimits();
  46762. this.raiseOnChange();
  46763. return this;
  46764. };
  46765. PathCursor.prototype.ensureLimits = function () {
  46766. while (this.value > 1) {
  46767. this.value -= 1;
  46768. }
  46769. while (this.value < 0) {
  46770. this.value += 1;
  46771. }
  46772. return this;
  46773. };
  46774. // used by animation engine
  46775. PathCursor.prototype.raiseOnChange = function () {
  46776. var _this = this;
  46777. this._onchange.forEach(function (f) { return f(_this); });
  46778. return this;
  46779. };
  46780. PathCursor.prototype.onchange = function (f) {
  46781. this._onchange.push(f);
  46782. return this;
  46783. };
  46784. return PathCursor;
  46785. }());
  46786. BABYLON.PathCursor = PathCursor;
  46787. var AnimationKeyInterpolation;
  46788. (function (AnimationKeyInterpolation) {
  46789. /**
  46790. * Do not interpolate between keys and use the start key value only. Tangents are ignored.
  46791. */
  46792. AnimationKeyInterpolation[AnimationKeyInterpolation["STEP"] = 1] = "STEP";
  46793. })(AnimationKeyInterpolation = BABYLON.AnimationKeyInterpolation || (BABYLON.AnimationKeyInterpolation = {}));
  46794. var Animation = /** @class */ (function () {
  46795. function Animation(name, targetProperty, framePerSecond, dataType, loopMode, enableBlending) {
  46796. this.name = name;
  46797. this.targetProperty = targetProperty;
  46798. this.framePerSecond = framePerSecond;
  46799. this.dataType = dataType;
  46800. this.loopMode = loopMode;
  46801. this.enableBlending = enableBlending;
  46802. this._runtimeAnimations = new Array();
  46803. // The set of event that will be linked to this animation
  46804. this._events = new Array();
  46805. this.blendingSpeed = 0.01;
  46806. this._ranges = {};
  46807. this.targetPropertyPath = targetProperty.split(".");
  46808. this.dataType = dataType;
  46809. this.loopMode = loopMode === undefined ? Animation.ANIMATIONLOOPMODE_CYCLE : loopMode;
  46810. }
  46811. Animation._PrepareAnimation = function (name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction) {
  46812. var dataType = undefined;
  46813. if (!isNaN(parseFloat(from)) && isFinite(from)) {
  46814. dataType = Animation.ANIMATIONTYPE_FLOAT;
  46815. }
  46816. else if (from instanceof BABYLON.Quaternion) {
  46817. dataType = Animation.ANIMATIONTYPE_QUATERNION;
  46818. }
  46819. else if (from instanceof BABYLON.Vector3) {
  46820. dataType = Animation.ANIMATIONTYPE_VECTOR3;
  46821. }
  46822. else if (from instanceof BABYLON.Vector2) {
  46823. dataType = Animation.ANIMATIONTYPE_VECTOR2;
  46824. }
  46825. else if (from instanceof BABYLON.Color3) {
  46826. dataType = Animation.ANIMATIONTYPE_COLOR3;
  46827. }
  46828. else if (from instanceof BABYLON.Size) {
  46829. dataType = Animation.ANIMATIONTYPE_SIZE;
  46830. }
  46831. if (dataType == undefined) {
  46832. return null;
  46833. }
  46834. var animation = new Animation(name, targetProperty, framePerSecond, dataType, loopMode);
  46835. var keys = [{ frame: 0, value: from }, { frame: totalFrame, value: to }];
  46836. animation.setKeys(keys);
  46837. if (easingFunction !== undefined) {
  46838. animation.setEasingFunction(easingFunction);
  46839. }
  46840. return animation;
  46841. };
  46842. /**
  46843. * Sets up an animation.
  46844. * @param property the property to animate
  46845. * @param animationType the animation type to apply
  46846. * @param easingFunction the easing function used in the animation
  46847. * @returns The created animation
  46848. */
  46849. Animation.CreateAnimation = function (property, animationType, framePerSecond, easingFunction) {
  46850. var animation = new Animation(property + "Animation", property, framePerSecond, animationType, Animation.ANIMATIONLOOPMODE_CONSTANT);
  46851. animation.setEasingFunction(easingFunction);
  46852. return animation;
  46853. };
  46854. /**
  46855. * Create and start an animation on a node
  46856. * @param {string} name defines the name of the global animation that will be run on all nodes
  46857. * @param {BABYLON.Node} node defines the root node where the animation will take place
  46858. * @param {string} targetProperty defines property to animate
  46859. * @param {number} framePerSecond defines the number of frame per second yo use
  46860. * @param {number} totalFrame defines the number of frames in total
  46861. * @param {any} from defines the initial value
  46862. * @param {any} to defines the final value
  46863. * @param {number} loopMode defines which loop mode you want to use (off by default)
  46864. * @param {BABYLON.EasingFunction} easingFunction defines the easing function to use (linear by default)
  46865. * @param onAnimationEnd defines the callback to call when animation end
  46866. * @returns the animatable created for this animation
  46867. */
  46868. Animation.CreateAndStartAnimation = function (name, node, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction, onAnimationEnd) {
  46869. var animation = Animation._PrepareAnimation(name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction);
  46870. if (!animation) {
  46871. return null;
  46872. }
  46873. return node.getScene().beginDirectAnimation(node, [animation], 0, totalFrame, (animation.loopMode === 1), 1.0, onAnimationEnd);
  46874. };
  46875. /**
  46876. * Create and start an animation on a node and its descendants
  46877. * @param {string} name defines the name of the global animation that will be run on all nodes
  46878. * @param {BABYLON.Node} node defines the root node where the animation will take place
  46879. * @param {boolean} 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.
  46880. * @param {string} targetProperty defines property to animate
  46881. * @param {number} framePerSecond defines the number of frame per second yo use
  46882. * @param {number} totalFrame defines the number of frames in total
  46883. * @param {any} from defines the initial value
  46884. * @param {any} to defines the final value
  46885. * @param {number} loopMode defines which loop mode you want to use (off by default)
  46886. * @param {BABYLON.EasingFunction} easingFunction defines the easing function to use (linear by default)
  46887. * @param onAnimationEnd defines the callback to call when an animation ends (will be called once per node)
  46888. * @returns the list of animatables created for all nodes
  46889. * @example https://www.babylonjs-playground.com/#MH0VLI
  46890. */
  46891. Animation.CreateAndStartHierarchyAnimation = function (name, node, directDescendantsOnly, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction, onAnimationEnd) {
  46892. var animation = Animation._PrepareAnimation(name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction);
  46893. if (!animation) {
  46894. return null;
  46895. }
  46896. var scene = node.getScene();
  46897. return scene.beginDirectHierarchyAnimation(node, directDescendantsOnly, [animation], 0, totalFrame, (animation.loopMode === 1), 1.0, onAnimationEnd);
  46898. };
  46899. Animation.CreateMergeAndStartAnimation = function (name, node, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction, onAnimationEnd) {
  46900. var animation = Animation._PrepareAnimation(name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction);
  46901. if (!animation) {
  46902. return null;
  46903. }
  46904. node.animations.push(animation);
  46905. return node.getScene().beginAnimation(node, 0, totalFrame, (animation.loopMode === 1), 1.0, onAnimationEnd);
  46906. };
  46907. /**
  46908. * Transition property of the Camera to the target Value.
  46909. * @param property The property to transition
  46910. * @param targetValue The target Value of the property
  46911. * @param host The object where the property to animate belongs
  46912. * @param scene Scene used to run the animation
  46913. * @param frameRate Framerate (in frame/s) to use
  46914. * @param transition The transition type we want to use
  46915. * @param duration The duration of the animation, in milliseconds
  46916. * @param onAnimationEnd Call back trigger at the end of the animation.
  46917. */
  46918. Animation.TransitionTo = function (property, targetValue, host, scene, frameRate, transition, duration, onAnimationEnd) {
  46919. if (onAnimationEnd === void 0) { onAnimationEnd = null; }
  46920. if (duration <= 0) {
  46921. host[property] = targetValue;
  46922. if (onAnimationEnd) {
  46923. onAnimationEnd();
  46924. }
  46925. return null;
  46926. }
  46927. var endFrame = frameRate * (duration / 1000);
  46928. transition.setKeys([{
  46929. frame: 0,
  46930. value: host[property].clone ? host[property].clone() : host[property]
  46931. },
  46932. {
  46933. frame: endFrame,
  46934. value: targetValue
  46935. }]);
  46936. if (!host.animations) {
  46937. host.animations = [];
  46938. }
  46939. host.animations.push(transition);
  46940. var animation = scene.beginAnimation(host, 0, endFrame, false);
  46941. animation.onAnimationEnd = onAnimationEnd;
  46942. return animation;
  46943. };
  46944. Object.defineProperty(Animation.prototype, "runtimeAnimations", {
  46945. /**
  46946. * Return the array of runtime animations currently using this animation
  46947. */
  46948. get: function () {
  46949. return this._runtimeAnimations;
  46950. },
  46951. enumerable: true,
  46952. configurable: true
  46953. });
  46954. Object.defineProperty(Animation.prototype, "hasRunningRuntimeAnimations", {
  46955. get: function () {
  46956. for (var _i = 0, _a = this._runtimeAnimations; _i < _a.length; _i++) {
  46957. var runtimeAnimation = _a[_i];
  46958. if (!runtimeAnimation.isStopped) {
  46959. return true;
  46960. }
  46961. }
  46962. return false;
  46963. },
  46964. enumerable: true,
  46965. configurable: true
  46966. });
  46967. // Methods
  46968. /**
  46969. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  46970. */
  46971. Animation.prototype.toString = function (fullDetails) {
  46972. var ret = "Name: " + this.name + ", property: " + this.targetProperty;
  46973. ret += ", datatype: " + (["Float", "Vector3", "Quaternion", "Matrix", "Color3", "Vector2"])[this.dataType];
  46974. ret += ", nKeys: " + (this._keys ? this._keys.length : "none");
  46975. ret += ", nRanges: " + (this._ranges ? Object.keys(this._ranges).length : "none");
  46976. if (fullDetails) {
  46977. ret += ", Ranges: {";
  46978. var first = true;
  46979. for (var name in this._ranges) {
  46980. if (first) {
  46981. ret += ", ";
  46982. first = false;
  46983. }
  46984. ret += name;
  46985. }
  46986. ret += "}";
  46987. }
  46988. return ret;
  46989. };
  46990. /**
  46991. * Add an event to this animation.
  46992. */
  46993. Animation.prototype.addEvent = function (event) {
  46994. this._events.push(event);
  46995. };
  46996. /**
  46997. * Remove all events found at the given frame
  46998. * @param frame
  46999. */
  47000. Animation.prototype.removeEvents = function (frame) {
  47001. for (var index = 0; index < this._events.length; index++) {
  47002. if (this._events[index].frame === frame) {
  47003. this._events.splice(index, 1);
  47004. index--;
  47005. }
  47006. }
  47007. };
  47008. Animation.prototype.getEvents = function () {
  47009. return this._events;
  47010. };
  47011. Animation.prototype.createRange = function (name, from, to) {
  47012. // check name not already in use; could happen for bones after serialized
  47013. if (!this._ranges[name]) {
  47014. this._ranges[name] = new AnimationRange(name, from, to);
  47015. }
  47016. };
  47017. Animation.prototype.deleteRange = function (name, deleteFrames) {
  47018. if (deleteFrames === void 0) { deleteFrames = true; }
  47019. var range = this._ranges[name];
  47020. if (!range) {
  47021. return;
  47022. }
  47023. if (deleteFrames) {
  47024. var from = range.from;
  47025. var to = range.to;
  47026. // this loop MUST go high to low for multiple splices to work
  47027. for (var key = this._keys.length - 1; key >= 0; key--) {
  47028. if (this._keys[key].frame >= from && this._keys[key].frame <= to) {
  47029. this._keys.splice(key, 1);
  47030. }
  47031. }
  47032. }
  47033. this._ranges[name] = null; // said much faster than 'delete this._range[name]'
  47034. };
  47035. Animation.prototype.getRange = function (name) {
  47036. return this._ranges[name];
  47037. };
  47038. Animation.prototype.getKeys = function () {
  47039. return this._keys;
  47040. };
  47041. Animation.prototype.getHighestFrame = function () {
  47042. var ret = 0;
  47043. for (var key = 0, nKeys = this._keys.length; key < nKeys; key++) {
  47044. if (ret < this._keys[key].frame) {
  47045. ret = this._keys[key].frame;
  47046. }
  47047. }
  47048. return ret;
  47049. };
  47050. Animation.prototype.getEasingFunction = function () {
  47051. return this._easingFunction;
  47052. };
  47053. Animation.prototype.setEasingFunction = function (easingFunction) {
  47054. this._easingFunction = easingFunction;
  47055. };
  47056. Animation.prototype.floatInterpolateFunction = function (startValue, endValue, gradient) {
  47057. return BABYLON.Scalar.Lerp(startValue, endValue, gradient);
  47058. };
  47059. Animation.prototype.floatInterpolateFunctionWithTangents = function (startValue, outTangent, endValue, inTangent, gradient) {
  47060. return BABYLON.Scalar.Hermite(startValue, outTangent, endValue, inTangent, gradient);
  47061. };
  47062. Animation.prototype.quaternionInterpolateFunction = function (startValue, endValue, gradient) {
  47063. return BABYLON.Quaternion.Slerp(startValue, endValue, gradient);
  47064. };
  47065. Animation.prototype.quaternionInterpolateFunctionWithTangents = function (startValue, outTangent, endValue, inTangent, gradient) {
  47066. return BABYLON.Quaternion.Hermite(startValue, outTangent, endValue, inTangent, gradient).normalize();
  47067. };
  47068. Animation.prototype.vector3InterpolateFunction = function (startValue, endValue, gradient) {
  47069. return BABYLON.Vector3.Lerp(startValue, endValue, gradient);
  47070. };
  47071. Animation.prototype.vector3InterpolateFunctionWithTangents = function (startValue, outTangent, endValue, inTangent, gradient) {
  47072. return BABYLON.Vector3.Hermite(startValue, outTangent, endValue, inTangent, gradient);
  47073. };
  47074. Animation.prototype.vector2InterpolateFunction = function (startValue, endValue, gradient) {
  47075. return BABYLON.Vector2.Lerp(startValue, endValue, gradient);
  47076. };
  47077. Animation.prototype.vector2InterpolateFunctionWithTangents = function (startValue, outTangent, endValue, inTangent, gradient) {
  47078. return BABYLON.Vector2.Hermite(startValue, outTangent, endValue, inTangent, gradient);
  47079. };
  47080. Animation.prototype.sizeInterpolateFunction = function (startValue, endValue, gradient) {
  47081. return BABYLON.Size.Lerp(startValue, endValue, gradient);
  47082. };
  47083. Animation.prototype.color3InterpolateFunction = function (startValue, endValue, gradient) {
  47084. return BABYLON.Color3.Lerp(startValue, endValue, gradient);
  47085. };
  47086. Animation.prototype.matrixInterpolateFunction = function (startValue, endValue, gradient) {
  47087. return BABYLON.Matrix.Lerp(startValue, endValue, gradient);
  47088. };
  47089. Animation.prototype.clone = function () {
  47090. var clone = new Animation(this.name, this.targetPropertyPath.join("."), this.framePerSecond, this.dataType, this.loopMode);
  47091. clone.enableBlending = this.enableBlending;
  47092. clone.blendingSpeed = this.blendingSpeed;
  47093. if (this._keys) {
  47094. clone.setKeys(this._keys);
  47095. }
  47096. if (this._ranges) {
  47097. clone._ranges = {};
  47098. for (var name in this._ranges) {
  47099. var range = this._ranges[name];
  47100. if (!range) {
  47101. continue;
  47102. }
  47103. clone._ranges[name] = range.clone();
  47104. }
  47105. }
  47106. return clone;
  47107. };
  47108. Animation.prototype.setKeys = function (values) {
  47109. this._keys = values.slice(0);
  47110. };
  47111. Animation.prototype.serialize = function () {
  47112. var serializationObject = {};
  47113. serializationObject.name = this.name;
  47114. serializationObject.property = this.targetProperty;
  47115. serializationObject.framePerSecond = this.framePerSecond;
  47116. serializationObject.dataType = this.dataType;
  47117. serializationObject.loopBehavior = this.loopMode;
  47118. serializationObject.enableBlending = this.enableBlending;
  47119. serializationObject.blendingSpeed = this.blendingSpeed;
  47120. var dataType = this.dataType;
  47121. serializationObject.keys = [];
  47122. var keys = this.getKeys();
  47123. for (var index = 0; index < keys.length; index++) {
  47124. var animationKey = keys[index];
  47125. var key = {};
  47126. key.frame = animationKey.frame;
  47127. switch (dataType) {
  47128. case Animation.ANIMATIONTYPE_FLOAT:
  47129. key.values = [animationKey.value];
  47130. break;
  47131. case Animation.ANIMATIONTYPE_QUATERNION:
  47132. case Animation.ANIMATIONTYPE_MATRIX:
  47133. case Animation.ANIMATIONTYPE_VECTOR3:
  47134. case Animation.ANIMATIONTYPE_COLOR3:
  47135. key.values = animationKey.value.asArray();
  47136. break;
  47137. }
  47138. serializationObject.keys.push(key);
  47139. }
  47140. serializationObject.ranges = [];
  47141. for (var name in this._ranges) {
  47142. var source = this._ranges[name];
  47143. if (!source) {
  47144. continue;
  47145. }
  47146. var range = {};
  47147. range.name = name;
  47148. range.from = source.from;
  47149. range.to = source.to;
  47150. serializationObject.ranges.push(range);
  47151. }
  47152. return serializationObject;
  47153. };
  47154. Object.defineProperty(Animation, "ANIMATIONTYPE_FLOAT", {
  47155. get: function () {
  47156. return Animation._ANIMATIONTYPE_FLOAT;
  47157. },
  47158. enumerable: true,
  47159. configurable: true
  47160. });
  47161. Object.defineProperty(Animation, "ANIMATIONTYPE_VECTOR3", {
  47162. get: function () {
  47163. return Animation._ANIMATIONTYPE_VECTOR3;
  47164. },
  47165. enumerable: true,
  47166. configurable: true
  47167. });
  47168. Object.defineProperty(Animation, "ANIMATIONTYPE_VECTOR2", {
  47169. get: function () {
  47170. return Animation._ANIMATIONTYPE_VECTOR2;
  47171. },
  47172. enumerable: true,
  47173. configurable: true
  47174. });
  47175. Object.defineProperty(Animation, "ANIMATIONTYPE_SIZE", {
  47176. get: function () {
  47177. return Animation._ANIMATIONTYPE_SIZE;
  47178. },
  47179. enumerable: true,
  47180. configurable: true
  47181. });
  47182. Object.defineProperty(Animation, "ANIMATIONTYPE_QUATERNION", {
  47183. get: function () {
  47184. return Animation._ANIMATIONTYPE_QUATERNION;
  47185. },
  47186. enumerable: true,
  47187. configurable: true
  47188. });
  47189. Object.defineProperty(Animation, "ANIMATIONTYPE_MATRIX", {
  47190. get: function () {
  47191. return Animation._ANIMATIONTYPE_MATRIX;
  47192. },
  47193. enumerable: true,
  47194. configurable: true
  47195. });
  47196. Object.defineProperty(Animation, "ANIMATIONTYPE_COLOR3", {
  47197. get: function () {
  47198. return Animation._ANIMATIONTYPE_COLOR3;
  47199. },
  47200. enumerable: true,
  47201. configurable: true
  47202. });
  47203. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_RELATIVE", {
  47204. get: function () {
  47205. return Animation._ANIMATIONLOOPMODE_RELATIVE;
  47206. },
  47207. enumerable: true,
  47208. configurable: true
  47209. });
  47210. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_CYCLE", {
  47211. get: function () {
  47212. return Animation._ANIMATIONLOOPMODE_CYCLE;
  47213. },
  47214. enumerable: true,
  47215. configurable: true
  47216. });
  47217. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_CONSTANT", {
  47218. get: function () {
  47219. return Animation._ANIMATIONLOOPMODE_CONSTANT;
  47220. },
  47221. enumerable: true,
  47222. configurable: true
  47223. });
  47224. Animation.Parse = function (parsedAnimation) {
  47225. var animation = new Animation(parsedAnimation.name, parsedAnimation.property, parsedAnimation.framePerSecond, parsedAnimation.dataType, parsedAnimation.loopBehavior);
  47226. var dataType = parsedAnimation.dataType;
  47227. var keys = [];
  47228. var data;
  47229. var index;
  47230. if (parsedAnimation.enableBlending) {
  47231. animation.enableBlending = parsedAnimation.enableBlending;
  47232. }
  47233. if (parsedAnimation.blendingSpeed) {
  47234. animation.blendingSpeed = parsedAnimation.blendingSpeed;
  47235. }
  47236. for (index = 0; index < parsedAnimation.keys.length; index++) {
  47237. var key = parsedAnimation.keys[index];
  47238. var inTangent;
  47239. var outTangent;
  47240. switch (dataType) {
  47241. case Animation.ANIMATIONTYPE_FLOAT:
  47242. data = key.values[0];
  47243. if (key.values.length >= 1) {
  47244. inTangent = key.values[1];
  47245. }
  47246. if (key.values.length >= 2) {
  47247. outTangent = key.values[2];
  47248. }
  47249. break;
  47250. case Animation.ANIMATIONTYPE_QUATERNION:
  47251. data = BABYLON.Quaternion.FromArray(key.values);
  47252. if (key.values.length >= 8) {
  47253. var _inTangent = BABYLON.Quaternion.FromArray(key.values.slice(4, 8));
  47254. if (!_inTangent.equals(BABYLON.Quaternion.Zero())) {
  47255. inTangent = _inTangent;
  47256. }
  47257. }
  47258. if (key.values.length >= 12) {
  47259. var _outTangent = BABYLON.Quaternion.FromArray(key.values.slice(8, 12));
  47260. if (!_outTangent.equals(BABYLON.Quaternion.Zero())) {
  47261. outTangent = _outTangent;
  47262. }
  47263. }
  47264. break;
  47265. case Animation.ANIMATIONTYPE_MATRIX:
  47266. data = BABYLON.Matrix.FromArray(key.values);
  47267. break;
  47268. case Animation.ANIMATIONTYPE_COLOR3:
  47269. data = BABYLON.Color3.FromArray(key.values);
  47270. break;
  47271. case Animation.ANIMATIONTYPE_VECTOR3:
  47272. default:
  47273. data = BABYLON.Vector3.FromArray(key.values);
  47274. break;
  47275. }
  47276. var keyData = {};
  47277. keyData.frame = key.frame;
  47278. keyData.value = data;
  47279. if (inTangent != undefined) {
  47280. keyData.inTangent = inTangent;
  47281. }
  47282. if (outTangent != undefined) {
  47283. keyData.outTangent = outTangent;
  47284. }
  47285. keys.push(keyData);
  47286. }
  47287. animation.setKeys(keys);
  47288. if (parsedAnimation.ranges) {
  47289. for (index = 0; index < parsedAnimation.ranges.length; index++) {
  47290. data = parsedAnimation.ranges[index];
  47291. animation.createRange(data.name, data.from, data.to);
  47292. }
  47293. }
  47294. return animation;
  47295. };
  47296. Animation.AppendSerializedAnimations = function (source, destination) {
  47297. if (source.animations) {
  47298. destination.animations = [];
  47299. for (var animationIndex = 0; animationIndex < source.animations.length; animationIndex++) {
  47300. var animation = source.animations[animationIndex];
  47301. destination.animations.push(animation.serialize());
  47302. }
  47303. }
  47304. };
  47305. Animation.AllowMatricesInterpolation = false;
  47306. // Statics
  47307. Animation._ANIMATIONTYPE_FLOAT = 0;
  47308. Animation._ANIMATIONTYPE_VECTOR3 = 1;
  47309. Animation._ANIMATIONTYPE_QUATERNION = 2;
  47310. Animation._ANIMATIONTYPE_MATRIX = 3;
  47311. Animation._ANIMATIONTYPE_COLOR3 = 4;
  47312. Animation._ANIMATIONTYPE_VECTOR2 = 5;
  47313. Animation._ANIMATIONTYPE_SIZE = 6;
  47314. Animation._ANIMATIONLOOPMODE_RELATIVE = 0;
  47315. Animation._ANIMATIONLOOPMODE_CYCLE = 1;
  47316. Animation._ANIMATIONLOOPMODE_CONSTANT = 2;
  47317. return Animation;
  47318. }());
  47319. BABYLON.Animation = Animation;
  47320. })(BABYLON || (BABYLON = {}));
  47321. //# sourceMappingURL=babylon.animation.js.map
  47322. "use strict";
  47323. var BABYLON;
  47324. (function (BABYLON) {
  47325. /**
  47326. * This class defines the direct association between an animation and a target
  47327. */
  47328. var TargetedAnimation = /** @class */ (function () {
  47329. function TargetedAnimation() {
  47330. }
  47331. return TargetedAnimation;
  47332. }());
  47333. BABYLON.TargetedAnimation = TargetedAnimation;
  47334. /**
  47335. * Use this class to create coordinated animations on multiple targets
  47336. */
  47337. var AnimationGroup = /** @class */ (function () {
  47338. function AnimationGroup(name, scene) {
  47339. if (scene === void 0) { scene = null; }
  47340. this.name = name;
  47341. this._targetedAnimations = new Array();
  47342. this._animatables = new Array();
  47343. this._from = Number.MAX_VALUE;
  47344. this._to = -Number.MAX_VALUE;
  47345. this._speedRatio = 1;
  47346. this.onAnimationEndObservable = new BABYLON.Observable();
  47347. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  47348. this._scene.animationGroups.push(this);
  47349. }
  47350. Object.defineProperty(AnimationGroup.prototype, "isStarted", {
  47351. /**
  47352. * Define if the animations are started
  47353. */
  47354. get: function () {
  47355. return this._isStarted;
  47356. },
  47357. enumerable: true,
  47358. configurable: true
  47359. });
  47360. Object.defineProperty(AnimationGroup.prototype, "speedRatio", {
  47361. /**
  47362. * Gets or sets the speed ratio to use for all animations
  47363. */
  47364. get: function () {
  47365. return this._speedRatio;
  47366. },
  47367. /**
  47368. * Gets or sets the speed ratio to use for all animations
  47369. */
  47370. set: function (value) {
  47371. if (this._speedRatio === value) {
  47372. return;
  47373. }
  47374. this._speedRatio = value;
  47375. for (var index = 0; index < this._animatables.length; index++) {
  47376. var animatable = this._animatables[index];
  47377. animatable.speedRatio = this._speedRatio;
  47378. }
  47379. },
  47380. enumerable: true,
  47381. configurable: true
  47382. });
  47383. Object.defineProperty(AnimationGroup.prototype, "targetedAnimations", {
  47384. /**
  47385. * Gets the targeted animations for this animation group
  47386. */
  47387. get: function () {
  47388. return this._targetedAnimations;
  47389. },
  47390. enumerable: true,
  47391. configurable: true
  47392. });
  47393. Object.defineProperty(AnimationGroup.prototype, "animatables", {
  47394. /**
  47395. * returning the list of animatables controlled by this animation group.
  47396. */
  47397. get: function () {
  47398. return this._animatables;
  47399. },
  47400. enumerable: true,
  47401. configurable: true
  47402. });
  47403. /**
  47404. * Add an animation (with its target) in the group
  47405. * @param animation defines the animation we want to add
  47406. * @param target defines the target of the animation
  47407. * @returns the {BABYLON.TargetedAnimation} object
  47408. */
  47409. AnimationGroup.prototype.addTargetedAnimation = function (animation, target) {
  47410. var targetedAnimation = {
  47411. animation: animation,
  47412. target: target
  47413. };
  47414. var keys = animation.getKeys();
  47415. if (this._from > keys[0].frame) {
  47416. this._from = keys[0].frame;
  47417. }
  47418. if (this._to < keys[keys.length - 1].frame) {
  47419. this._to = keys[keys.length - 1].frame;
  47420. }
  47421. this._targetedAnimations.push(targetedAnimation);
  47422. return targetedAnimation;
  47423. };
  47424. /**
  47425. * This function will normalize every animation in the group to make sure they all go from beginFrame to endFrame
  47426. * It can add constant keys at begin or end
  47427. * @param beginFrame defines the new begin frame for all animations. It can't be bigger than the smallest begin frame of all animations
  47428. * @param endFrame defines the new end frame for all animations. It can't be smaller than the largest end frame of all animations
  47429. */
  47430. AnimationGroup.prototype.normalize = function (beginFrame, endFrame) {
  47431. if (beginFrame === void 0) { beginFrame = -Number.MAX_VALUE; }
  47432. if (endFrame === void 0) { endFrame = Number.MAX_VALUE; }
  47433. beginFrame = Math.max(beginFrame, this._from);
  47434. endFrame = Math.min(endFrame, this._to);
  47435. for (var index = 0; index < this._targetedAnimations.length; index++) {
  47436. var targetedAnimation = this._targetedAnimations[index];
  47437. var keys = targetedAnimation.animation.getKeys();
  47438. var startKey = keys[0];
  47439. var endKey = keys[keys.length - 1];
  47440. if (startKey.frame > beginFrame) {
  47441. var newKey = {
  47442. frame: beginFrame,
  47443. value: startKey.value,
  47444. inTangent: startKey.inTangent,
  47445. outTangent: startKey.outTangent,
  47446. interpolation: startKey.interpolation
  47447. };
  47448. keys.splice(0, 0, newKey);
  47449. }
  47450. if (endKey.frame < endFrame) {
  47451. var newKey = {
  47452. frame: endFrame,
  47453. value: endKey.value,
  47454. inTangent: endKey.outTangent,
  47455. outTangent: endKey.outTangent,
  47456. interpolation: endKey.interpolation
  47457. };
  47458. keys.push(newKey);
  47459. }
  47460. }
  47461. return this;
  47462. };
  47463. /**
  47464. * Start all animations on given targets
  47465. * @param loop defines if animations must loop
  47466. * @param speedRatio defines the ratio to apply to animation speed (1 by default)
  47467. * @param from defines the from key (optional)
  47468. * @param to defines the to key (optional)
  47469. * @returns the current animation group
  47470. */
  47471. AnimationGroup.prototype.start = function (loop, speedRatio, from, to) {
  47472. var _this = this;
  47473. if (loop === void 0) { loop = false; }
  47474. if (speedRatio === void 0) { speedRatio = 1; }
  47475. if (this._isStarted || this._targetedAnimations.length === 0) {
  47476. return this;
  47477. }
  47478. var _loop_1 = function () {
  47479. var targetedAnimation = this_1._targetedAnimations[index];
  47480. if (!targetedAnimation.target.animations) {
  47481. targetedAnimation.target.animations = [];
  47482. }
  47483. if (targetedAnimation.target.animations.indexOf(targetedAnimation.animation) === -1) {
  47484. targetedAnimation.target.animations.push(targetedAnimation.animation);
  47485. }
  47486. 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 () {
  47487. _this.onAnimationEndObservable.notifyObservers(targetedAnimation);
  47488. }));
  47489. };
  47490. var this_1 = this;
  47491. for (var index = 0; index < this._targetedAnimations.length; index++) {
  47492. _loop_1();
  47493. }
  47494. this._speedRatio = speedRatio;
  47495. this._isStarted = true;
  47496. return this;
  47497. };
  47498. /**
  47499. * Pause all animations
  47500. */
  47501. AnimationGroup.prototype.pause = function () {
  47502. if (!this._isStarted) {
  47503. return this;
  47504. }
  47505. for (var index = 0; index < this._animatables.length; index++) {
  47506. var animatable = this._animatables[index];
  47507. animatable.pause();
  47508. }
  47509. return this;
  47510. };
  47511. /**
  47512. * Play all animations to initial state
  47513. * This function will start() the animations if they were not started or will restart() them if they were paused
  47514. * @param loop defines if animations must loop
  47515. */
  47516. AnimationGroup.prototype.play = function (loop) {
  47517. if (this.isStarted) {
  47518. if (loop !== undefined) {
  47519. for (var index = 0; index < this._animatables.length; index++) {
  47520. var animatable = this._animatables[index];
  47521. animatable.loopAnimation = loop;
  47522. }
  47523. }
  47524. this.restart();
  47525. }
  47526. else {
  47527. this.start(loop, this._speedRatio);
  47528. }
  47529. return this;
  47530. };
  47531. /**
  47532. * Reset all animations to initial state
  47533. */
  47534. AnimationGroup.prototype.reset = function () {
  47535. if (!this._isStarted) {
  47536. return this;
  47537. }
  47538. for (var index = 0; index < this._animatables.length; index++) {
  47539. var animatable = this._animatables[index];
  47540. animatable.reset();
  47541. }
  47542. return this;
  47543. };
  47544. /**
  47545. * Restart animations from key 0
  47546. */
  47547. AnimationGroup.prototype.restart = function () {
  47548. if (!this._isStarted) {
  47549. return this;
  47550. }
  47551. for (var index = 0; index < this._animatables.length; index++) {
  47552. var animatable = this._animatables[index];
  47553. animatable.restart();
  47554. }
  47555. return this;
  47556. };
  47557. /**
  47558. * Stop all animations
  47559. */
  47560. AnimationGroup.prototype.stop = function () {
  47561. if (!this._isStarted) {
  47562. return this;
  47563. }
  47564. for (var index = 0; index < this._animatables.length; index++) {
  47565. var animatable = this._animatables[index];
  47566. animatable.stop();
  47567. }
  47568. this._isStarted = false;
  47569. return this;
  47570. };
  47571. /**
  47572. * Goes to a specific frame in this animation group
  47573. *
  47574. * @param frame the frame number to go to
  47575. * @return the animationGroup
  47576. */
  47577. AnimationGroup.prototype.goToFrame = function (frame) {
  47578. if (!this._isStarted) {
  47579. return this;
  47580. }
  47581. for (var index = 0; index < this._animatables.length; index++) {
  47582. var animatable = this._animatables[index];
  47583. animatable.goToFrame(frame);
  47584. }
  47585. return this;
  47586. };
  47587. /**
  47588. * Dispose all associated resources
  47589. */
  47590. AnimationGroup.prototype.dispose = function () {
  47591. this._targetedAnimations = [];
  47592. this._animatables = [];
  47593. var index = this._scene.animationGroups.indexOf(this);
  47594. if (index > -1) {
  47595. this._scene.animationGroups.splice(index, 1);
  47596. }
  47597. };
  47598. return AnimationGroup;
  47599. }());
  47600. BABYLON.AnimationGroup = AnimationGroup;
  47601. })(BABYLON || (BABYLON = {}));
  47602. //# sourceMappingURL=babylon.animationGroup.js.map
  47603. "use strict";
  47604. var BABYLON;
  47605. (function (BABYLON) {
  47606. var RuntimeAnimation = /** @class */ (function () {
  47607. /**
  47608. * Create a new RuntimeAnimation object
  47609. * @param target defines the target of the animation
  47610. * @param animation defines the source {BABYLON.Animation} object
  47611. * @param scene defines the hosting scene
  47612. * @param host defines the initiating Animatable
  47613. */
  47614. function RuntimeAnimation(target, animation, scene, host) {
  47615. this._currentFrame = 0;
  47616. this._offsetsCache = {};
  47617. this._highLimitsCache = {};
  47618. this._stopped = false;
  47619. this._blendingFactor = 0;
  47620. this._targetPath = "";
  47621. this._weight = 1.0;
  47622. this._ratioOffset = 0;
  47623. this._previousDelay = 0;
  47624. this._previousRatio = 0;
  47625. this._animation = animation;
  47626. this._target = target;
  47627. this._scene = scene;
  47628. this._host = host;
  47629. animation._runtimeAnimations.push(this);
  47630. }
  47631. Object.defineProperty(RuntimeAnimation.prototype, "currentFrame", {
  47632. /**
  47633. * Gets the current frame
  47634. */
  47635. get: function () {
  47636. return this._currentFrame;
  47637. },
  47638. enumerable: true,
  47639. configurable: true
  47640. });
  47641. Object.defineProperty(RuntimeAnimation.prototype, "weight", {
  47642. /**
  47643. * Gets the weight of the runtime animation
  47644. */
  47645. get: function () {
  47646. return this._weight;
  47647. },
  47648. enumerable: true,
  47649. configurable: true
  47650. });
  47651. Object.defineProperty(RuntimeAnimation.prototype, "originalValue", {
  47652. /**
  47653. * Gets the original value of the runtime animation
  47654. */
  47655. get: function () {
  47656. return this._originalValue;
  47657. },
  47658. enumerable: true,
  47659. configurable: true
  47660. });
  47661. Object.defineProperty(RuntimeAnimation.prototype, "currentValue", {
  47662. /**
  47663. * Gets the current value of the runtime animation
  47664. */
  47665. get: function () {
  47666. return this._currentValue;
  47667. },
  47668. enumerable: true,
  47669. configurable: true
  47670. });
  47671. Object.defineProperty(RuntimeAnimation.prototype, "targetPath", {
  47672. /**
  47673. * Gets the path where to store the animated value in the target
  47674. */
  47675. get: function () {
  47676. return this._targetPath;
  47677. },
  47678. enumerable: true,
  47679. configurable: true
  47680. });
  47681. Object.defineProperty(RuntimeAnimation.prototype, "target", {
  47682. /**
  47683. * Gets the actual target of the runtime animation
  47684. */
  47685. get: function () {
  47686. return this._activeTarget;
  47687. },
  47688. enumerable: true,
  47689. configurable: true
  47690. });
  47691. Object.defineProperty(RuntimeAnimation.prototype, "animation", {
  47692. get: function () {
  47693. return this._animation;
  47694. },
  47695. enumerable: true,
  47696. configurable: true
  47697. });
  47698. RuntimeAnimation.prototype.reset = function () {
  47699. this._offsetsCache = {};
  47700. this._highLimitsCache = {};
  47701. this._currentFrame = 0;
  47702. this._blendingFactor = 0;
  47703. this._originalValue = null;
  47704. };
  47705. RuntimeAnimation.prototype.isStopped = function () {
  47706. return this._stopped;
  47707. };
  47708. RuntimeAnimation.prototype.dispose = function () {
  47709. var index = this._animation.runtimeAnimations.indexOf(this);
  47710. if (index > -1) {
  47711. this._animation.runtimeAnimations.splice(index, 1);
  47712. }
  47713. };
  47714. RuntimeAnimation.prototype._getKeyValue = function (value) {
  47715. if (typeof value === "function") {
  47716. return value();
  47717. }
  47718. return value;
  47719. };
  47720. RuntimeAnimation.prototype._interpolate = function (currentFrame, repeatCount, loopMode, offsetValue, highLimitValue) {
  47721. if (loopMode === BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT && repeatCount > 0) {
  47722. return highLimitValue.clone ? highLimitValue.clone() : highLimitValue;
  47723. }
  47724. this._currentFrame = currentFrame;
  47725. var keys = this._animation.getKeys();
  47726. // Try to get a hash to find the right key
  47727. 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));
  47728. if (keys[startKeyIndex].frame >= currentFrame) {
  47729. while (startKeyIndex - 1 >= 0 && keys[startKeyIndex].frame >= currentFrame) {
  47730. startKeyIndex--;
  47731. }
  47732. }
  47733. for (var key = startKeyIndex; key < keys.length; key++) {
  47734. var endKey = keys[key + 1];
  47735. if (endKey.frame >= currentFrame) {
  47736. var startKey = keys[key];
  47737. var startValue = this._getKeyValue(startKey.value);
  47738. if (startKey.interpolation === BABYLON.AnimationKeyInterpolation.STEP) {
  47739. return startValue;
  47740. }
  47741. var endValue = this._getKeyValue(endKey.value);
  47742. var useTangent = startKey.outTangent !== undefined && endKey.inTangent !== undefined;
  47743. var frameDelta = endKey.frame - startKey.frame;
  47744. // gradient : percent of currentFrame between the frame inf and the frame sup
  47745. var gradient = (currentFrame - startKey.frame) / frameDelta;
  47746. // check for easingFunction and correction of gradient
  47747. var easingFunction = this._animation.getEasingFunction();
  47748. if (easingFunction != null) {
  47749. gradient = easingFunction.ease(gradient);
  47750. }
  47751. switch (this._animation.dataType) {
  47752. // Float
  47753. case BABYLON.Animation.ANIMATIONTYPE_FLOAT:
  47754. var floatValue = useTangent ? this._animation.floatInterpolateFunctionWithTangents(startValue, startKey.outTangent * frameDelta, endValue, endKey.inTangent * frameDelta, gradient) : this._animation.floatInterpolateFunction(startValue, endValue, gradient);
  47755. switch (loopMode) {
  47756. case BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE:
  47757. case BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT:
  47758. return floatValue;
  47759. case BABYLON.Animation.ANIMATIONLOOPMODE_RELATIVE:
  47760. return offsetValue * repeatCount + floatValue;
  47761. }
  47762. break;
  47763. // Quaternion
  47764. case BABYLON.Animation.ANIMATIONTYPE_QUATERNION:
  47765. var quatValue = useTangent ? this._animation.quaternionInterpolateFunctionWithTangents(startValue, startKey.outTangent.scale(frameDelta), endValue, endKey.inTangent.scale(frameDelta), gradient) : this._animation.quaternionInterpolateFunction(startValue, endValue, gradient);
  47766. switch (loopMode) {
  47767. case BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE:
  47768. case BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT:
  47769. return quatValue;
  47770. case BABYLON.Animation.ANIMATIONLOOPMODE_RELATIVE:
  47771. return quatValue.add(offsetValue.scale(repeatCount));
  47772. }
  47773. return quatValue;
  47774. // Vector3
  47775. case BABYLON.Animation.ANIMATIONTYPE_VECTOR3:
  47776. var vec3Value = useTangent ? this._animation.vector3InterpolateFunctionWithTangents(startValue, startKey.outTangent.scale(frameDelta), endValue, endKey.inTangent.scale(frameDelta), gradient) : this._animation.vector3InterpolateFunction(startValue, endValue, gradient);
  47777. switch (loopMode) {
  47778. case BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE:
  47779. case BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT:
  47780. return vec3Value;
  47781. case BABYLON.Animation.ANIMATIONLOOPMODE_RELATIVE:
  47782. return vec3Value.add(offsetValue.scale(repeatCount));
  47783. }
  47784. // Vector2
  47785. case BABYLON.Animation.ANIMATIONTYPE_VECTOR2:
  47786. var vec2Value = useTangent ? this._animation.vector2InterpolateFunctionWithTangents(startValue, startKey.outTangent.scale(frameDelta), endValue, endKey.inTangent.scale(frameDelta), gradient) : this._animation.vector2InterpolateFunction(startValue, endValue, gradient);
  47787. switch (loopMode) {
  47788. case BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE:
  47789. case BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT:
  47790. return vec2Value;
  47791. case BABYLON.Animation.ANIMATIONLOOPMODE_RELATIVE:
  47792. return vec2Value.add(offsetValue.scale(repeatCount));
  47793. }
  47794. // Size
  47795. case BABYLON.Animation.ANIMATIONTYPE_SIZE:
  47796. switch (loopMode) {
  47797. case BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE:
  47798. case BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT:
  47799. return this._animation.sizeInterpolateFunction(startValue, endValue, gradient);
  47800. case BABYLON.Animation.ANIMATIONLOOPMODE_RELATIVE:
  47801. return this._animation.sizeInterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  47802. }
  47803. // Color3
  47804. case BABYLON.Animation.ANIMATIONTYPE_COLOR3:
  47805. switch (loopMode) {
  47806. case BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE:
  47807. case BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT:
  47808. return this._animation.color3InterpolateFunction(startValue, endValue, gradient);
  47809. case BABYLON.Animation.ANIMATIONLOOPMODE_RELATIVE:
  47810. return this._animation.color3InterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  47811. }
  47812. // Matrix
  47813. case BABYLON.Animation.ANIMATIONTYPE_MATRIX:
  47814. switch (loopMode) {
  47815. case BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE:
  47816. case BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT:
  47817. if (BABYLON.Animation.AllowMatricesInterpolation) {
  47818. return this._animation.matrixInterpolateFunction(startValue, endValue, gradient);
  47819. }
  47820. case BABYLON.Animation.ANIMATIONLOOPMODE_RELATIVE:
  47821. return startValue;
  47822. }
  47823. default:
  47824. break;
  47825. }
  47826. break;
  47827. }
  47828. }
  47829. return this._getKeyValue(keys[keys.length - 1].value);
  47830. };
  47831. /**
  47832. * Affect the interpolated value to the target
  47833. * @param currentValue defines the value computed by the animation
  47834. * @param weight defines the weight to apply to this value
  47835. */
  47836. RuntimeAnimation.prototype.setValue = function (currentValue, weight) {
  47837. if (weight === void 0) { weight = 1.0; }
  47838. // Set value
  47839. var path;
  47840. var destination;
  47841. var targetPropertyPath = this._animation.targetPropertyPath;
  47842. if (targetPropertyPath.length > 1) {
  47843. var property = this._target[targetPropertyPath[0]];
  47844. for (var index = 1; index < targetPropertyPath.length - 1; index++) {
  47845. property = property[targetPropertyPath[index]];
  47846. }
  47847. path = targetPropertyPath[targetPropertyPath.length - 1];
  47848. destination = property;
  47849. }
  47850. else {
  47851. path = targetPropertyPath[0];
  47852. destination = this._target;
  47853. }
  47854. this._targetPath = path;
  47855. this._activeTarget = destination;
  47856. this._weight = weight;
  47857. // Blending
  47858. var enableBlending = this._target && this._target.animationPropertiesOverride ? this._target.animationPropertiesOverride.enableBlending : this._animation.enableBlending;
  47859. var blendingSpeed = this._target && this._target.animationPropertiesOverride ? this._target.animationPropertiesOverride.blendingSpeed : this._animation.blendingSpeed;
  47860. if (enableBlending && this._blendingFactor <= 1.0) {
  47861. if (!this._originalBlendValue) {
  47862. var originalValue = destination[path];
  47863. if (originalValue.clone) {
  47864. this._originalBlendValue = originalValue.clone();
  47865. }
  47866. else {
  47867. this._originalBlendValue = originalValue;
  47868. }
  47869. }
  47870. }
  47871. if (weight !== -1.0) {
  47872. if (!this._originalValue) {
  47873. var originalValue = void 0;
  47874. if (destination.getRestPose) {
  47875. originalValue = destination.getRestPose();
  47876. }
  47877. else {
  47878. originalValue = destination[path];
  47879. }
  47880. if (originalValue.clone) {
  47881. this._originalValue = originalValue.clone();
  47882. }
  47883. else {
  47884. this._originalValue = originalValue;
  47885. }
  47886. }
  47887. }
  47888. if (enableBlending && this._blendingFactor <= 1.0) {
  47889. if (this._originalBlendValue.prototype) {
  47890. if (this._originalBlendValue.prototype.Lerp) {
  47891. this._currentValue = this._originalBlendValue.construtor.prototype.Lerp(currentValue, this._originalBlendValue, this._blendingFactor);
  47892. }
  47893. else {
  47894. this._currentValue = currentValue;
  47895. }
  47896. }
  47897. else if (this._originalBlendValue.m) {
  47898. this._currentValue = BABYLON.Matrix.Lerp(this._originalBlendValue, currentValue, this._blendingFactor);
  47899. }
  47900. else {
  47901. this._currentValue = this._originalBlendValue * (1.0 - this._blendingFactor) + this._blendingFactor * currentValue;
  47902. }
  47903. this._blendingFactor += blendingSpeed;
  47904. }
  47905. else {
  47906. this._currentValue = currentValue;
  47907. }
  47908. if (weight !== -1.0) {
  47909. this._scene._registerTargetForLateAnimationBinding(this);
  47910. }
  47911. else {
  47912. destination[path] = this._currentValue;
  47913. }
  47914. if (this._target.markAsDirty) {
  47915. this._target.markAsDirty(this._animation.targetProperty);
  47916. }
  47917. };
  47918. RuntimeAnimation.prototype._getCorrectLoopMode = function () {
  47919. if (this._target && this._target.animationPropertiesOverride) {
  47920. return this._target.animationPropertiesOverride.loopMode;
  47921. }
  47922. return this._animation.loopMode;
  47923. };
  47924. /**
  47925. * Move the current animation to a given frame
  47926. * @param frame defines the frame to move to
  47927. */
  47928. RuntimeAnimation.prototype.goToFrame = function (frame) {
  47929. var keys = this._animation.getKeys();
  47930. if (frame < keys[0].frame) {
  47931. frame = keys[0].frame;
  47932. }
  47933. else if (frame > keys[keys.length - 1].frame) {
  47934. frame = keys[keys.length - 1].frame;
  47935. }
  47936. var currentValue = this._interpolate(frame, 0, this._getCorrectLoopMode());
  47937. this.setValue(currentValue, -1);
  47938. };
  47939. RuntimeAnimation.prototype._prepareForSpeedRatioChange = function (newSpeedRatio) {
  47940. var newRatio = this._previousDelay * (this._animation.framePerSecond * newSpeedRatio) / 1000.0;
  47941. this._ratioOffset = this._previousRatio - newRatio;
  47942. };
  47943. /**
  47944. * Execute the current animation
  47945. * @param delay defines the delay to add to the current frame
  47946. * @param from defines the lower bound of the animation range
  47947. * @param to defines the upper bound of the animation range
  47948. * @param loop defines if the current animation must loop
  47949. * @param speedRatio defines the current speed ratio
  47950. * @param weight defines the weight of the animation (default is -1 so no weight)
  47951. * @returns a boolean indicating if the animation has ended
  47952. */
  47953. RuntimeAnimation.prototype.animate = function (delay, from, to, loop, speedRatio, weight) {
  47954. if (weight === void 0) { weight = -1.0; }
  47955. var targetPropertyPath = this._animation.targetPropertyPath;
  47956. if (!targetPropertyPath || targetPropertyPath.length < 1) {
  47957. this._stopped = true;
  47958. return false;
  47959. }
  47960. var returnValue = true;
  47961. var keys = this._animation.getKeys();
  47962. // Adding a start key at frame 0 if missing
  47963. if (keys[0].frame !== 0) {
  47964. var newKey = { frame: 0, value: keys[0].value };
  47965. keys.splice(0, 0, newKey);
  47966. }
  47967. // Check limits
  47968. if (from < keys[0].frame || from > keys[keys.length - 1].frame) {
  47969. from = keys[0].frame;
  47970. }
  47971. if (to < keys[0].frame || to > keys[keys.length - 1].frame) {
  47972. to = keys[keys.length - 1].frame;
  47973. }
  47974. //to and from cannot be the same key
  47975. if (from === to) {
  47976. if (from > keys[0].frame) {
  47977. from--;
  47978. }
  47979. else if (to < keys[keys.length - 1].frame) {
  47980. to++;
  47981. }
  47982. }
  47983. // Compute ratio
  47984. var range = to - from;
  47985. var offsetValue;
  47986. // ratio represents the frame delta between from and to
  47987. var ratio = (delay * (this._animation.framePerSecond * speedRatio) / 1000.0) + this._ratioOffset;
  47988. var highLimitValue = 0;
  47989. this._previousDelay = delay;
  47990. this._previousRatio = ratio;
  47991. if (((to > from && ratio > range) || (from > to && ratio < range)) && !loop) {
  47992. returnValue = false;
  47993. highLimitValue = this._getKeyValue(keys[keys.length - 1].value);
  47994. }
  47995. else {
  47996. // Get max value if required
  47997. if (this._getCorrectLoopMode() !== BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE) {
  47998. var keyOffset = to.toString() + from.toString();
  47999. if (!this._offsetsCache[keyOffset]) {
  48000. var fromValue = this._interpolate(from, 0, BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE);
  48001. var toValue = this._interpolate(to, 0, BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE);
  48002. switch (this._animation.dataType) {
  48003. // Float
  48004. case BABYLON.Animation.ANIMATIONTYPE_FLOAT:
  48005. this._offsetsCache[keyOffset] = toValue - fromValue;
  48006. break;
  48007. // Quaternion
  48008. case BABYLON.Animation.ANIMATIONTYPE_QUATERNION:
  48009. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  48010. break;
  48011. // Vector3
  48012. case BABYLON.Animation.ANIMATIONTYPE_VECTOR3:
  48013. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  48014. // Vector2
  48015. case BABYLON.Animation.ANIMATIONTYPE_VECTOR2:
  48016. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  48017. // Size
  48018. case BABYLON.Animation.ANIMATIONTYPE_SIZE:
  48019. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  48020. // Color3
  48021. case BABYLON.Animation.ANIMATIONTYPE_COLOR3:
  48022. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  48023. default:
  48024. break;
  48025. }
  48026. this._highLimitsCache[keyOffset] = toValue;
  48027. }
  48028. highLimitValue = this._highLimitsCache[keyOffset];
  48029. offsetValue = this._offsetsCache[keyOffset];
  48030. }
  48031. }
  48032. if (offsetValue === undefined) {
  48033. switch (this._animation.dataType) {
  48034. // Float
  48035. case BABYLON.Animation.ANIMATIONTYPE_FLOAT:
  48036. offsetValue = 0;
  48037. break;
  48038. // Quaternion
  48039. case BABYLON.Animation.ANIMATIONTYPE_QUATERNION:
  48040. offsetValue = new BABYLON.Quaternion(0, 0, 0, 0);
  48041. break;
  48042. // Vector3
  48043. case BABYLON.Animation.ANIMATIONTYPE_VECTOR3:
  48044. offsetValue = BABYLON.Vector3.Zero();
  48045. break;
  48046. // Vector2
  48047. case BABYLON.Animation.ANIMATIONTYPE_VECTOR2:
  48048. offsetValue = BABYLON.Vector2.Zero();
  48049. break;
  48050. // Size
  48051. case BABYLON.Animation.ANIMATIONTYPE_SIZE:
  48052. offsetValue = BABYLON.Size.Zero();
  48053. break;
  48054. // Color3
  48055. case BABYLON.Animation.ANIMATIONTYPE_COLOR3:
  48056. offsetValue = BABYLON.Color3.Black();
  48057. }
  48058. }
  48059. // Compute value
  48060. var repeatCount = (ratio / range) >> 0;
  48061. var currentFrame = returnValue ? from + ratio % range : to;
  48062. // Need to normalize?
  48063. if (this._host && this._host.syncRoot) {
  48064. var syncRoot = this._host.syncRoot;
  48065. var hostNormalizedFrame = (syncRoot.masterFrame - syncRoot.fromFrame) / (syncRoot.toFrame - syncRoot.fromFrame);
  48066. currentFrame = from + (to - from) * hostNormalizedFrame;
  48067. }
  48068. var currentValue = this._interpolate(currentFrame, repeatCount, this._getCorrectLoopMode(), offsetValue, highLimitValue);
  48069. // Set value
  48070. this.setValue(currentValue, weight);
  48071. // Check events
  48072. var events = this._animation.getEvents();
  48073. for (var index = 0; index < events.length; index++) {
  48074. // Make sure current frame has passed event frame and that event frame is within the current range
  48075. // Also, handle both forward and reverse animations
  48076. if ((range > 0 && currentFrame >= events[index].frame && events[index].frame >= from) ||
  48077. (range < 0 && currentFrame <= events[index].frame && events[index].frame <= from)) {
  48078. var event = events[index];
  48079. if (!event.isDone) {
  48080. // If event should be done only once, remove it.
  48081. if (event.onlyOnce) {
  48082. events.splice(index, 1);
  48083. index--;
  48084. }
  48085. event.isDone = true;
  48086. event.action();
  48087. } // Don't do anything if the event has already be done.
  48088. }
  48089. else if (events[index].isDone && !events[index].onlyOnce) {
  48090. // reset event, the animation is looping
  48091. events[index].isDone = false;
  48092. }
  48093. }
  48094. if (!returnValue) {
  48095. this._stopped = true;
  48096. }
  48097. return returnValue;
  48098. };
  48099. return RuntimeAnimation;
  48100. }());
  48101. BABYLON.RuntimeAnimation = RuntimeAnimation;
  48102. })(BABYLON || (BABYLON = {}));
  48103. //# sourceMappingURL=babylon.runtimeAnimation.js.map
  48104. "use strict";
  48105. var BABYLON;
  48106. (function (BABYLON) {
  48107. var Animatable = /** @class */ (function () {
  48108. function Animatable(scene, target, fromFrame, toFrame, loopAnimation, speedRatio, onAnimationEnd, animations) {
  48109. if (fromFrame === void 0) { fromFrame = 0; }
  48110. if (toFrame === void 0) { toFrame = 100; }
  48111. if (loopAnimation === void 0) { loopAnimation = false; }
  48112. if (speedRatio === void 0) { speedRatio = 1.0; }
  48113. this.target = target;
  48114. this.fromFrame = fromFrame;
  48115. this.toFrame = toFrame;
  48116. this.loopAnimation = loopAnimation;
  48117. this.onAnimationEnd = onAnimationEnd;
  48118. this._localDelayOffset = null;
  48119. this._pausedDelay = null;
  48120. this._runtimeAnimations = new Array();
  48121. this._paused = false;
  48122. this._speedRatio = 1;
  48123. this._weight = -1.0;
  48124. this.animationStarted = false;
  48125. if (animations) {
  48126. this.appendAnimations(target, animations);
  48127. }
  48128. this._speedRatio = speedRatio;
  48129. this._scene = scene;
  48130. scene._activeAnimatables.push(this);
  48131. }
  48132. Object.defineProperty(Animatable.prototype, "syncRoot", {
  48133. /**
  48134. * Gets the root Animatable used to synchronize and normalize animations
  48135. */
  48136. get: function () {
  48137. return this._syncRoot;
  48138. },
  48139. enumerable: true,
  48140. configurable: true
  48141. });
  48142. Object.defineProperty(Animatable.prototype, "masterFrame", {
  48143. /**
  48144. * Gets the current frame of the first RuntimeAnimation
  48145. * Used to synchronize Animatables
  48146. */
  48147. get: function () {
  48148. if (this._runtimeAnimations.length === 0) {
  48149. return 0;
  48150. }
  48151. return this._runtimeAnimations[0].currentFrame;
  48152. },
  48153. enumerable: true,
  48154. configurable: true
  48155. });
  48156. Object.defineProperty(Animatable.prototype, "weight", {
  48157. /**
  48158. * Gets or sets the animatable weight (-1.0 by default meaning not weighted)
  48159. */
  48160. get: function () {
  48161. return this._weight;
  48162. },
  48163. set: function (value) {
  48164. if (value === -1) {
  48165. this._weight = -1;
  48166. return;
  48167. }
  48168. // Else weight must be in [0, 1] range
  48169. this._weight = Math.min(Math.max(value, 0), 1.0);
  48170. },
  48171. enumerable: true,
  48172. configurable: true
  48173. });
  48174. Object.defineProperty(Animatable.prototype, "speedRatio", {
  48175. /**
  48176. * Gets or sets the speed ratio to apply to the animatable (1.0 by default)
  48177. */
  48178. get: function () {
  48179. return this._speedRatio;
  48180. },
  48181. set: function (value) {
  48182. for (var index = 0; index < this._runtimeAnimations.length; index++) {
  48183. var animation = this._runtimeAnimations[index];
  48184. animation._prepareForSpeedRatioChange(value);
  48185. }
  48186. this._speedRatio = value;
  48187. },
  48188. enumerable: true,
  48189. configurable: true
  48190. });
  48191. // Methods
  48192. /**
  48193. * Synchronize and normalize current Animatable with a source Animatable.
  48194. * This is useful when using animation weights and when animations are not of the same length
  48195. * @param root defines the root Animatable to synchronize with
  48196. * @returns the current Animatable
  48197. */
  48198. Animatable.prototype.syncWith = function (root) {
  48199. this._syncRoot = root;
  48200. if (root) {
  48201. // Make sure this animatable will animate after the root
  48202. var index = this._scene._activeAnimatables.indexOf(this);
  48203. if (index > -1) {
  48204. this._scene._activeAnimatables.splice(index, 1);
  48205. this._scene._activeAnimatables.push(this);
  48206. }
  48207. }
  48208. return this;
  48209. };
  48210. Animatable.prototype.getAnimations = function () {
  48211. return this._runtimeAnimations;
  48212. };
  48213. Animatable.prototype.appendAnimations = function (target, animations) {
  48214. for (var index = 0; index < animations.length; index++) {
  48215. var animation = animations[index];
  48216. this._runtimeAnimations.push(new BABYLON.RuntimeAnimation(target, animation, this._scene, this));
  48217. }
  48218. };
  48219. Animatable.prototype.getAnimationByTargetProperty = function (property) {
  48220. var runtimeAnimations = this._runtimeAnimations;
  48221. for (var index = 0; index < runtimeAnimations.length; index++) {
  48222. if (runtimeAnimations[index].animation.targetProperty === property) {
  48223. return runtimeAnimations[index].animation;
  48224. }
  48225. }
  48226. return null;
  48227. };
  48228. Animatable.prototype.getRuntimeAnimationByTargetProperty = function (property) {
  48229. var runtimeAnimations = this._runtimeAnimations;
  48230. for (var index = 0; index < runtimeAnimations.length; index++) {
  48231. if (runtimeAnimations[index].animation.targetProperty === property) {
  48232. return runtimeAnimations[index];
  48233. }
  48234. }
  48235. return null;
  48236. };
  48237. Animatable.prototype.reset = function () {
  48238. var runtimeAnimations = this._runtimeAnimations;
  48239. for (var index = 0; index < runtimeAnimations.length; index++) {
  48240. runtimeAnimations[index].reset();
  48241. }
  48242. // Reset to original value
  48243. for (index = 0; index < runtimeAnimations.length; index++) {
  48244. var animation = runtimeAnimations[index];
  48245. animation.animate(0, this.fromFrame, this.toFrame, false, this._speedRatio);
  48246. }
  48247. this._localDelayOffset = null;
  48248. this._pausedDelay = null;
  48249. };
  48250. Animatable.prototype.enableBlending = function (blendingSpeed) {
  48251. var runtimeAnimations = this._runtimeAnimations;
  48252. for (var index = 0; index < runtimeAnimations.length; index++) {
  48253. runtimeAnimations[index].animation.enableBlending = true;
  48254. runtimeAnimations[index].animation.blendingSpeed = blendingSpeed;
  48255. }
  48256. };
  48257. Animatable.prototype.disableBlending = function () {
  48258. var runtimeAnimations = this._runtimeAnimations;
  48259. for (var index = 0; index < runtimeAnimations.length; index++) {
  48260. runtimeAnimations[index].animation.enableBlending = false;
  48261. }
  48262. };
  48263. Animatable.prototype.goToFrame = function (frame) {
  48264. var runtimeAnimations = this._runtimeAnimations;
  48265. if (runtimeAnimations[0]) {
  48266. var fps = runtimeAnimations[0].animation.framePerSecond;
  48267. var currentFrame = runtimeAnimations[0].currentFrame;
  48268. var adjustTime = frame - currentFrame;
  48269. var delay = adjustTime * 1000 / (fps * this.speedRatio);
  48270. if (this._localDelayOffset === null) {
  48271. this._localDelayOffset = 0;
  48272. }
  48273. this._localDelayOffset -= delay;
  48274. }
  48275. for (var index = 0; index < runtimeAnimations.length; index++) {
  48276. runtimeAnimations[index].goToFrame(frame);
  48277. }
  48278. };
  48279. Animatable.prototype.pause = function () {
  48280. if (this._paused) {
  48281. return;
  48282. }
  48283. this._paused = true;
  48284. };
  48285. Animatable.prototype.restart = function () {
  48286. this._paused = false;
  48287. };
  48288. Animatable.prototype.stop = function (animationName) {
  48289. if (animationName) {
  48290. var idx = this._scene._activeAnimatables.indexOf(this);
  48291. if (idx > -1) {
  48292. var runtimeAnimations = this._runtimeAnimations;
  48293. for (var index = runtimeAnimations.length - 1; index >= 0; index--) {
  48294. if (typeof animationName === "string" && runtimeAnimations[index].animation.name != animationName) {
  48295. continue;
  48296. }
  48297. runtimeAnimations[index].dispose();
  48298. runtimeAnimations.splice(index, 1);
  48299. }
  48300. if (runtimeAnimations.length == 0) {
  48301. this._scene._activeAnimatables.splice(idx, 1);
  48302. if (this.onAnimationEnd) {
  48303. this.onAnimationEnd();
  48304. }
  48305. }
  48306. }
  48307. }
  48308. else {
  48309. var index = this._scene._activeAnimatables.indexOf(this);
  48310. if (index > -1) {
  48311. this._scene._activeAnimatables.splice(index, 1);
  48312. var runtimeAnimations = this._runtimeAnimations;
  48313. for (var index = 0; index < runtimeAnimations.length; index++) {
  48314. runtimeAnimations[index].dispose();
  48315. }
  48316. if (this.onAnimationEnd) {
  48317. this.onAnimationEnd();
  48318. }
  48319. }
  48320. }
  48321. };
  48322. Animatable.prototype._animate = function (delay) {
  48323. if (this._paused) {
  48324. this.animationStarted = false;
  48325. if (this._pausedDelay === null) {
  48326. this._pausedDelay = delay;
  48327. }
  48328. return true;
  48329. }
  48330. if (this._localDelayOffset === null) {
  48331. this._localDelayOffset = delay;
  48332. this._pausedDelay = null;
  48333. }
  48334. else if (this._pausedDelay !== null) {
  48335. this._localDelayOffset += delay - this._pausedDelay;
  48336. this._pausedDelay = null;
  48337. }
  48338. if (this._weight === 0) {
  48339. return true;
  48340. }
  48341. // Animating
  48342. var running = false;
  48343. var runtimeAnimations = this._runtimeAnimations;
  48344. var index;
  48345. for (index = 0; index < runtimeAnimations.length; index++) {
  48346. var animation = runtimeAnimations[index];
  48347. var isRunning = animation.animate(delay - this._localDelayOffset, this.fromFrame, this.toFrame, this.loopAnimation, this._speedRatio, this._weight);
  48348. running = running || isRunning;
  48349. }
  48350. this.animationStarted = running;
  48351. if (!running) {
  48352. // Remove from active animatables
  48353. index = this._scene._activeAnimatables.indexOf(this);
  48354. this._scene._activeAnimatables.splice(index, 1);
  48355. // Dispose all runtime animations
  48356. for (index = 0; index < runtimeAnimations.length; index++) {
  48357. runtimeAnimations[index].dispose();
  48358. }
  48359. }
  48360. if (!running && this.onAnimationEnd) {
  48361. this.onAnimationEnd();
  48362. this.onAnimationEnd = null;
  48363. }
  48364. return running;
  48365. };
  48366. return Animatable;
  48367. }());
  48368. BABYLON.Animatable = Animatable;
  48369. })(BABYLON || (BABYLON = {}));
  48370. //# sourceMappingURL=babylon.animatable.js.map
  48371. "use strict";
  48372. var BABYLON;
  48373. (function (BABYLON) {
  48374. var EasingFunction = /** @class */ (function () {
  48375. function EasingFunction() {
  48376. // Properties
  48377. this._easingMode = EasingFunction.EASINGMODE_EASEIN;
  48378. }
  48379. Object.defineProperty(EasingFunction, "EASINGMODE_EASEIN", {
  48380. get: function () {
  48381. return EasingFunction._EASINGMODE_EASEIN;
  48382. },
  48383. enumerable: true,
  48384. configurable: true
  48385. });
  48386. Object.defineProperty(EasingFunction, "EASINGMODE_EASEOUT", {
  48387. get: function () {
  48388. return EasingFunction._EASINGMODE_EASEOUT;
  48389. },
  48390. enumerable: true,
  48391. configurable: true
  48392. });
  48393. Object.defineProperty(EasingFunction, "EASINGMODE_EASEINOUT", {
  48394. get: function () {
  48395. return EasingFunction._EASINGMODE_EASEINOUT;
  48396. },
  48397. enumerable: true,
  48398. configurable: true
  48399. });
  48400. EasingFunction.prototype.setEasingMode = function (easingMode) {
  48401. var n = Math.min(Math.max(easingMode, 0), 2);
  48402. this._easingMode = n;
  48403. };
  48404. EasingFunction.prototype.getEasingMode = function () {
  48405. return this._easingMode;
  48406. };
  48407. EasingFunction.prototype.easeInCore = function (gradient) {
  48408. throw new Error('You must implement this method');
  48409. };
  48410. EasingFunction.prototype.ease = function (gradient) {
  48411. switch (this._easingMode) {
  48412. case EasingFunction.EASINGMODE_EASEIN:
  48413. return this.easeInCore(gradient);
  48414. case EasingFunction.EASINGMODE_EASEOUT:
  48415. return (1 - this.easeInCore(1 - gradient));
  48416. }
  48417. if (gradient >= 0.5) {
  48418. return (((1 - this.easeInCore((1 - gradient) * 2)) * 0.5) + 0.5);
  48419. }
  48420. return (this.easeInCore(gradient * 2) * 0.5);
  48421. };
  48422. //Statics
  48423. EasingFunction._EASINGMODE_EASEIN = 0;
  48424. EasingFunction._EASINGMODE_EASEOUT = 1;
  48425. EasingFunction._EASINGMODE_EASEINOUT = 2;
  48426. return EasingFunction;
  48427. }());
  48428. BABYLON.EasingFunction = EasingFunction;
  48429. var CircleEase = /** @class */ (function (_super) {
  48430. __extends(CircleEase, _super);
  48431. function CircleEase() {
  48432. return _super !== null && _super.apply(this, arguments) || this;
  48433. }
  48434. CircleEase.prototype.easeInCore = function (gradient) {
  48435. gradient = Math.max(0, Math.min(1, gradient));
  48436. return (1.0 - Math.sqrt(1.0 - (gradient * gradient)));
  48437. };
  48438. return CircleEase;
  48439. }(EasingFunction));
  48440. BABYLON.CircleEase = CircleEase;
  48441. var BackEase = /** @class */ (function (_super) {
  48442. __extends(BackEase, _super);
  48443. function BackEase(amplitude) {
  48444. if (amplitude === void 0) { amplitude = 1; }
  48445. var _this = _super.call(this) || this;
  48446. _this.amplitude = amplitude;
  48447. return _this;
  48448. }
  48449. BackEase.prototype.easeInCore = function (gradient) {
  48450. var num = Math.max(0, this.amplitude);
  48451. return (Math.pow(gradient, 3.0) - ((gradient * num) * Math.sin(3.1415926535897931 * gradient)));
  48452. };
  48453. return BackEase;
  48454. }(EasingFunction));
  48455. BABYLON.BackEase = BackEase;
  48456. var BounceEase = /** @class */ (function (_super) {
  48457. __extends(BounceEase, _super);
  48458. function BounceEase(bounces, bounciness) {
  48459. if (bounces === void 0) { bounces = 3; }
  48460. if (bounciness === void 0) { bounciness = 2; }
  48461. var _this = _super.call(this) || this;
  48462. _this.bounces = bounces;
  48463. _this.bounciness = bounciness;
  48464. return _this;
  48465. }
  48466. BounceEase.prototype.easeInCore = function (gradient) {
  48467. var y = Math.max(0.0, this.bounces);
  48468. var bounciness = this.bounciness;
  48469. if (bounciness <= 1.0) {
  48470. bounciness = 1.001;
  48471. }
  48472. var num9 = Math.pow(bounciness, y);
  48473. var num5 = 1.0 - bounciness;
  48474. var num4 = ((1.0 - num9) / num5) + (num9 * 0.5);
  48475. var num15 = gradient * num4;
  48476. var num65 = Math.log((-num15 * (1.0 - bounciness)) + 1.0) / Math.log(bounciness);
  48477. var num3 = Math.floor(num65);
  48478. var num13 = num3 + 1.0;
  48479. var num8 = (1.0 - Math.pow(bounciness, num3)) / (num5 * num4);
  48480. var num12 = (1.0 - Math.pow(bounciness, num13)) / (num5 * num4);
  48481. var num7 = (num8 + num12) * 0.5;
  48482. var num6 = gradient - num7;
  48483. var num2 = num7 - num8;
  48484. return (((-Math.pow(1.0 / bounciness, y - num3) / (num2 * num2)) * (num6 - num2)) * (num6 + num2));
  48485. };
  48486. return BounceEase;
  48487. }(EasingFunction));
  48488. BABYLON.BounceEase = BounceEase;
  48489. var CubicEase = /** @class */ (function (_super) {
  48490. __extends(CubicEase, _super);
  48491. function CubicEase() {
  48492. return _super !== null && _super.apply(this, arguments) || this;
  48493. }
  48494. CubicEase.prototype.easeInCore = function (gradient) {
  48495. return (gradient * gradient * gradient);
  48496. };
  48497. return CubicEase;
  48498. }(EasingFunction));
  48499. BABYLON.CubicEase = CubicEase;
  48500. var ElasticEase = /** @class */ (function (_super) {
  48501. __extends(ElasticEase, _super);
  48502. function ElasticEase(oscillations, springiness) {
  48503. if (oscillations === void 0) { oscillations = 3; }
  48504. if (springiness === void 0) { springiness = 3; }
  48505. var _this = _super.call(this) || this;
  48506. _this.oscillations = oscillations;
  48507. _this.springiness = springiness;
  48508. return _this;
  48509. }
  48510. ElasticEase.prototype.easeInCore = function (gradient) {
  48511. var num2;
  48512. var num3 = Math.max(0.0, this.oscillations);
  48513. var num = Math.max(0.0, this.springiness);
  48514. if (num == 0) {
  48515. num2 = gradient;
  48516. }
  48517. else {
  48518. num2 = (Math.exp(num * gradient) - 1.0) / (Math.exp(num) - 1.0);
  48519. }
  48520. return (num2 * Math.sin(((6.2831853071795862 * num3) + 1.5707963267948966) * gradient));
  48521. };
  48522. return ElasticEase;
  48523. }(EasingFunction));
  48524. BABYLON.ElasticEase = ElasticEase;
  48525. var ExponentialEase = /** @class */ (function (_super) {
  48526. __extends(ExponentialEase, _super);
  48527. function ExponentialEase(exponent) {
  48528. if (exponent === void 0) { exponent = 2; }
  48529. var _this = _super.call(this) || this;
  48530. _this.exponent = exponent;
  48531. return _this;
  48532. }
  48533. ExponentialEase.prototype.easeInCore = function (gradient) {
  48534. if (this.exponent <= 0) {
  48535. return gradient;
  48536. }
  48537. return ((Math.exp(this.exponent * gradient) - 1.0) / (Math.exp(this.exponent) - 1.0));
  48538. };
  48539. return ExponentialEase;
  48540. }(EasingFunction));
  48541. BABYLON.ExponentialEase = ExponentialEase;
  48542. var PowerEase = /** @class */ (function (_super) {
  48543. __extends(PowerEase, _super);
  48544. function PowerEase(power) {
  48545. if (power === void 0) { power = 2; }
  48546. var _this = _super.call(this) || this;
  48547. _this.power = power;
  48548. return _this;
  48549. }
  48550. PowerEase.prototype.easeInCore = function (gradient) {
  48551. var y = Math.max(0.0, this.power);
  48552. return Math.pow(gradient, y);
  48553. };
  48554. return PowerEase;
  48555. }(EasingFunction));
  48556. BABYLON.PowerEase = PowerEase;
  48557. var QuadraticEase = /** @class */ (function (_super) {
  48558. __extends(QuadraticEase, _super);
  48559. function QuadraticEase() {
  48560. return _super !== null && _super.apply(this, arguments) || this;
  48561. }
  48562. QuadraticEase.prototype.easeInCore = function (gradient) {
  48563. return (gradient * gradient);
  48564. };
  48565. return QuadraticEase;
  48566. }(EasingFunction));
  48567. BABYLON.QuadraticEase = QuadraticEase;
  48568. var QuarticEase = /** @class */ (function (_super) {
  48569. __extends(QuarticEase, _super);
  48570. function QuarticEase() {
  48571. return _super !== null && _super.apply(this, arguments) || this;
  48572. }
  48573. QuarticEase.prototype.easeInCore = function (gradient) {
  48574. return (gradient * gradient * gradient * gradient);
  48575. };
  48576. return QuarticEase;
  48577. }(EasingFunction));
  48578. BABYLON.QuarticEase = QuarticEase;
  48579. var QuinticEase = /** @class */ (function (_super) {
  48580. __extends(QuinticEase, _super);
  48581. function QuinticEase() {
  48582. return _super !== null && _super.apply(this, arguments) || this;
  48583. }
  48584. QuinticEase.prototype.easeInCore = function (gradient) {
  48585. return (gradient * gradient * gradient * gradient * gradient);
  48586. };
  48587. return QuinticEase;
  48588. }(EasingFunction));
  48589. BABYLON.QuinticEase = QuinticEase;
  48590. var SineEase = /** @class */ (function (_super) {
  48591. __extends(SineEase, _super);
  48592. function SineEase() {
  48593. return _super !== null && _super.apply(this, arguments) || this;
  48594. }
  48595. SineEase.prototype.easeInCore = function (gradient) {
  48596. return (1.0 - Math.sin(1.5707963267948966 * (1.0 - gradient)));
  48597. };
  48598. return SineEase;
  48599. }(EasingFunction));
  48600. BABYLON.SineEase = SineEase;
  48601. var BezierCurveEase = /** @class */ (function (_super) {
  48602. __extends(BezierCurveEase, _super);
  48603. function BezierCurveEase(x1, y1, x2, y2) {
  48604. if (x1 === void 0) { x1 = 0; }
  48605. if (y1 === void 0) { y1 = 0; }
  48606. if (x2 === void 0) { x2 = 1; }
  48607. if (y2 === void 0) { y2 = 1; }
  48608. var _this = _super.call(this) || this;
  48609. _this.x1 = x1;
  48610. _this.y1 = y1;
  48611. _this.x2 = x2;
  48612. _this.y2 = y2;
  48613. return _this;
  48614. }
  48615. BezierCurveEase.prototype.easeInCore = function (gradient) {
  48616. return BABYLON.BezierCurve.interpolate(gradient, this.x1, this.y1, this.x2, this.y2);
  48617. };
  48618. return BezierCurveEase;
  48619. }(EasingFunction));
  48620. BABYLON.BezierCurveEase = BezierCurveEase;
  48621. })(BABYLON || (BABYLON = {}));
  48622. //# sourceMappingURL=babylon.easing.js.map
  48623. "use strict";
  48624. var BABYLON;
  48625. (function (BABYLON) {
  48626. /**
  48627. * A Condition applied to an Action
  48628. */
  48629. var Condition = /** @class */ (function () {
  48630. /**
  48631. * Creates a new Condition
  48632. * @param actionManager the manager of the action the condition is applied to
  48633. */
  48634. function Condition(actionManager) {
  48635. this._actionManager = actionManager;
  48636. }
  48637. /**
  48638. * Check if the current condition is valid
  48639. * @returns a boolean
  48640. */
  48641. Condition.prototype.isValid = function () {
  48642. return true;
  48643. };
  48644. /**
  48645. * Internal only
  48646. * @ignore
  48647. */
  48648. Condition.prototype._getProperty = function (propertyPath) {
  48649. return this._actionManager._getProperty(propertyPath);
  48650. };
  48651. /**
  48652. * Internal only
  48653. * @ignore
  48654. */
  48655. Condition.prototype._getEffectiveTarget = function (target, propertyPath) {
  48656. return this._actionManager._getEffectiveTarget(target, propertyPath);
  48657. };
  48658. /**
  48659. * Serialize placeholder for child classes
  48660. * @returns the serialized object
  48661. */
  48662. Condition.prototype.serialize = function () {
  48663. };
  48664. /**
  48665. * Internal only
  48666. * @ignore
  48667. */
  48668. Condition.prototype._serialize = function (serializedCondition) {
  48669. return {
  48670. type: 2,
  48671. children: [],
  48672. name: serializedCondition.name,
  48673. properties: serializedCondition.properties
  48674. };
  48675. };
  48676. return Condition;
  48677. }());
  48678. BABYLON.Condition = Condition;
  48679. /**
  48680. * Defines specific conditional operators as extensions of Condition
  48681. */
  48682. var ValueCondition = /** @class */ (function (_super) {
  48683. __extends(ValueCondition, _super);
  48684. /**
  48685. * Creates a new ValueCondition
  48686. * @param actionManager manager for the action the condition applies to
  48687. * @param target for the action
  48688. * @param propertyPath path to specify the property of the target the conditional operator uses
  48689. * @param value the vale compared by the conditional operator against the current value of the property
  48690. * @param operator the conditional operator, default {BABYLON.ValueCondition.IsEqual}
  48691. */
  48692. function ValueCondition(actionManager, target, propertyPath, value, operator) {
  48693. if (operator === void 0) { operator = ValueCondition.IsEqual; }
  48694. var _this = _super.call(this, actionManager) || this;
  48695. _this.propertyPath = propertyPath;
  48696. _this.value = value;
  48697. _this.operator = operator;
  48698. _this._target = target;
  48699. _this._effectiveTarget = _this._getEffectiveTarget(target, _this.propertyPath);
  48700. _this._property = _this._getProperty(_this.propertyPath);
  48701. return _this;
  48702. }
  48703. Object.defineProperty(ValueCondition, "IsEqual", {
  48704. /**
  48705. * returns the number for IsEqual
  48706. */
  48707. get: function () {
  48708. return ValueCondition._IsEqual;
  48709. },
  48710. enumerable: true,
  48711. configurable: true
  48712. });
  48713. Object.defineProperty(ValueCondition, "IsDifferent", {
  48714. /**
  48715. * Returns the number for IsDifferent
  48716. */
  48717. get: function () {
  48718. return ValueCondition._IsDifferent;
  48719. },
  48720. enumerable: true,
  48721. configurable: true
  48722. });
  48723. Object.defineProperty(ValueCondition, "IsGreater", {
  48724. /**
  48725. * Returns the number for IsGreater
  48726. */
  48727. get: function () {
  48728. return ValueCondition._IsGreater;
  48729. },
  48730. enumerable: true,
  48731. configurable: true
  48732. });
  48733. Object.defineProperty(ValueCondition, "IsLesser", {
  48734. /**
  48735. * Returns the number for IsLesser
  48736. */
  48737. get: function () {
  48738. return ValueCondition._IsLesser;
  48739. },
  48740. enumerable: true,
  48741. configurable: true
  48742. });
  48743. /**
  48744. * Compares the given value with the property value for the specified conditional operator
  48745. * @returns the result of the comparison
  48746. */
  48747. ValueCondition.prototype.isValid = function () {
  48748. switch (this.operator) {
  48749. case ValueCondition.IsGreater:
  48750. return this._effectiveTarget[this._property] > this.value;
  48751. case ValueCondition.IsLesser:
  48752. return this._effectiveTarget[this._property] < this.value;
  48753. case ValueCondition.IsEqual:
  48754. case ValueCondition.IsDifferent:
  48755. var check;
  48756. if (this.value.equals) {
  48757. check = this.value.equals(this._effectiveTarget[this._property]);
  48758. }
  48759. else {
  48760. check = this.value === this._effectiveTarget[this._property];
  48761. }
  48762. return this.operator === ValueCondition.IsEqual ? check : !check;
  48763. }
  48764. return false;
  48765. };
  48766. /**
  48767. * Serialize the ValueCondition into a JSON compatible object
  48768. * @returns serialization object
  48769. */
  48770. ValueCondition.prototype.serialize = function () {
  48771. return this._serialize({
  48772. name: "ValueCondition",
  48773. properties: [
  48774. BABYLON.Action._GetTargetProperty(this._target),
  48775. { name: "propertyPath", value: this.propertyPath },
  48776. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) },
  48777. { name: "operator", value: ValueCondition.GetOperatorName(this.operator) }
  48778. ]
  48779. });
  48780. };
  48781. /**
  48782. * Gets the name of the conditional operator for the ValueCondition
  48783. * @param operator the conditional operator
  48784. * @returns the name
  48785. */
  48786. ValueCondition.GetOperatorName = function (operator) {
  48787. switch (operator) {
  48788. case ValueCondition._IsEqual: return "IsEqual";
  48789. case ValueCondition._IsDifferent: return "IsDifferent";
  48790. case ValueCondition._IsGreater: return "IsGreater";
  48791. case ValueCondition._IsLesser: return "IsLesser";
  48792. default: return "";
  48793. }
  48794. };
  48795. /**
  48796. * Internal only
  48797. * @ignore
  48798. */
  48799. ValueCondition._IsEqual = 0;
  48800. /**
  48801. * Internal only
  48802. * @ignore
  48803. */
  48804. ValueCondition._IsDifferent = 1;
  48805. /**
  48806. * Internal only
  48807. * @ignore
  48808. */
  48809. ValueCondition._IsGreater = 2;
  48810. /**
  48811. * Internal only
  48812. * @ignore
  48813. */
  48814. ValueCondition._IsLesser = 3;
  48815. return ValueCondition;
  48816. }(Condition));
  48817. BABYLON.ValueCondition = ValueCondition;
  48818. /**
  48819. * Defines a predicate condition as an extension of Condition
  48820. */
  48821. var PredicateCondition = /** @class */ (function (_super) {
  48822. __extends(PredicateCondition, _super);
  48823. /**
  48824. * Creates a new {BABYLON.PredicateCondition}
  48825. * @param actionManager manager for the action the condition applies to
  48826. * @param predicate
  48827. */
  48828. function PredicateCondition(actionManager, predicate) {
  48829. var _this = _super.call(this, actionManager) || this;
  48830. _this.predicate = predicate;
  48831. return _this;
  48832. }
  48833. /**
  48834. * @returns the validity of the predicate condition
  48835. */
  48836. PredicateCondition.prototype.isValid = function () {
  48837. return this.predicate();
  48838. };
  48839. return PredicateCondition;
  48840. }(Condition));
  48841. BABYLON.PredicateCondition = PredicateCondition;
  48842. /**
  48843. * Defines a state condition as an extension of {BABYLON.Condition}
  48844. */
  48845. var StateCondition = /** @class */ (function (_super) {
  48846. __extends(StateCondition, _super);
  48847. /**
  48848. * Creates a new {BABYLON.StateCondition}
  48849. * @param actionManager manager for the action the condition applies to
  48850. * @param target of the condition
  48851. * @param value to compare with target state
  48852. */
  48853. function StateCondition(actionManager, target, value) {
  48854. var _this = _super.call(this, actionManager) || this;
  48855. _this.value = value;
  48856. _this._target = target;
  48857. return _this;
  48858. }
  48859. /**
  48860. * @returns the validity of the state
  48861. */
  48862. StateCondition.prototype.isValid = function () {
  48863. return this._target.state === this.value;
  48864. };
  48865. /**
  48866. * Serialize the {BABYLON.StateCondition} into a JSON compatible object
  48867. * @returns serialization object
  48868. */
  48869. StateCondition.prototype.serialize = function () {
  48870. return this._serialize({
  48871. name: "StateCondition",
  48872. properties: [
  48873. BABYLON.Action._GetTargetProperty(this._target),
  48874. { name: "value", value: this.value }
  48875. ]
  48876. });
  48877. };
  48878. return StateCondition;
  48879. }(Condition));
  48880. BABYLON.StateCondition = StateCondition;
  48881. })(BABYLON || (BABYLON = {}));
  48882. //# sourceMappingURL=babylon.condition.js.map
  48883. "use strict";
  48884. var BABYLON;
  48885. (function (BABYLON) {
  48886. /**
  48887. * The action to be carried out following a trigger
  48888. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#available-actions
  48889. */
  48890. var Action = /** @class */ (function () {
  48891. /**
  48892. * Creates a new Action
  48893. * @param triggerOptions the trigger, with or without parameters, for the action
  48894. * @param condition an optional determinant of action
  48895. */
  48896. function Action(triggerOptions, condition) {
  48897. this.triggerOptions = triggerOptions;
  48898. /**
  48899. * An event triggered prior to action being executed.
  48900. */
  48901. this.onBeforeExecuteObservable = new BABYLON.Observable();
  48902. if (triggerOptions.parameter) {
  48903. this.trigger = triggerOptions.trigger;
  48904. this._triggerParameter = triggerOptions.parameter;
  48905. }
  48906. else {
  48907. this.trigger = triggerOptions;
  48908. }
  48909. this._nextActiveAction = this;
  48910. this._condition = condition;
  48911. }
  48912. /**
  48913. * Internal only
  48914. * @ignore
  48915. */
  48916. Action.prototype._prepare = function () {
  48917. };
  48918. /**
  48919. * Gets the trigger parameters
  48920. * @returns the trigger parameters
  48921. */
  48922. Action.prototype.getTriggerParameter = function () {
  48923. return this._triggerParameter;
  48924. };
  48925. /**
  48926. * Internal only - executes current action event
  48927. * @ignore
  48928. */
  48929. Action.prototype._executeCurrent = function (evt) {
  48930. if (this._nextActiveAction._condition) {
  48931. var condition = this._nextActiveAction._condition;
  48932. var currentRenderId = this._actionManager.getScene().getRenderId();
  48933. // We cache the current evaluation for the current frame
  48934. if (condition._evaluationId === currentRenderId) {
  48935. if (!condition._currentResult) {
  48936. return;
  48937. }
  48938. }
  48939. else {
  48940. condition._evaluationId = currentRenderId;
  48941. if (!condition.isValid()) {
  48942. condition._currentResult = false;
  48943. return;
  48944. }
  48945. condition._currentResult = true;
  48946. }
  48947. }
  48948. this.onBeforeExecuteObservable.notifyObservers(this);
  48949. this._nextActiveAction.execute(evt);
  48950. this.skipToNextActiveAction();
  48951. };
  48952. /**
  48953. * Execute placeholder for child classes
  48954. * @param evt optional action event
  48955. */
  48956. Action.prototype.execute = function (evt) {
  48957. };
  48958. /**
  48959. * Skips to next active action
  48960. */
  48961. Action.prototype.skipToNextActiveAction = function () {
  48962. if (this._nextActiveAction._child) {
  48963. if (!this._nextActiveAction._child._actionManager) {
  48964. this._nextActiveAction._child._actionManager = this._actionManager;
  48965. }
  48966. this._nextActiveAction = this._nextActiveAction._child;
  48967. }
  48968. else {
  48969. this._nextActiveAction = this;
  48970. }
  48971. };
  48972. /**
  48973. * Adds action to chain of actions, may be a DoNothingAction
  48974. * @param index The index of the attribute.
  48975. * @returns The action passed in
  48976. * @see https://www.babylonjs-playground.com/#1T30HR#0
  48977. */
  48978. Action.prototype.then = function (action) {
  48979. this._child = action;
  48980. action._actionManager = this._actionManager;
  48981. action._prepare();
  48982. return action;
  48983. };
  48984. /**
  48985. * Internal only
  48986. * @ignore
  48987. */
  48988. Action.prototype._getProperty = function (propertyPath) {
  48989. return this._actionManager._getProperty(propertyPath);
  48990. };
  48991. /**
  48992. * Internal only
  48993. * @ignore
  48994. */
  48995. Action.prototype._getEffectiveTarget = function (target, propertyPath) {
  48996. return this._actionManager._getEffectiveTarget(target, propertyPath);
  48997. };
  48998. /**
  48999. * Serialize placeholder for child classes
  49000. * @param parent of child
  49001. * @returns the serialized object
  49002. */
  49003. Action.prototype.serialize = function (parent) {
  49004. };
  49005. /**
  49006. * Internal only called by serialize
  49007. * @ignore
  49008. */
  49009. Action.prototype._serialize = function (serializedAction, parent) {
  49010. var serializationObject = {
  49011. type: 1,
  49012. children: [],
  49013. name: serializedAction.name,
  49014. properties: serializedAction.properties || []
  49015. };
  49016. // Serialize child
  49017. if (this._child) {
  49018. this._child.serialize(serializationObject);
  49019. }
  49020. // Check if "this" has a condition
  49021. if (this._condition) {
  49022. var serializedCondition = this._condition.serialize();
  49023. serializedCondition.children.push(serializationObject);
  49024. if (parent) {
  49025. parent.children.push(serializedCondition);
  49026. }
  49027. return serializedCondition;
  49028. }
  49029. if (parent) {
  49030. parent.children.push(serializationObject);
  49031. }
  49032. return serializationObject;
  49033. };
  49034. /**
  49035. * Internal only
  49036. * @ignore
  49037. */
  49038. Action._SerializeValueAsString = function (value) {
  49039. if (typeof value === "number") {
  49040. return value.toString();
  49041. }
  49042. if (typeof value === "boolean") {
  49043. return value ? "true" : "false";
  49044. }
  49045. if (value instanceof BABYLON.Vector2) {
  49046. return value.x + ", " + value.y;
  49047. }
  49048. if (value instanceof BABYLON.Vector3) {
  49049. return value.x + ", " + value.y + ", " + value.z;
  49050. }
  49051. if (value instanceof BABYLON.Color3) {
  49052. return value.r + ", " + value.g + ", " + value.b;
  49053. }
  49054. if (value instanceof BABYLON.Color4) {
  49055. return value.r + ", " + value.g + ", " + value.b + ", " + value.a;
  49056. }
  49057. return value; // string
  49058. };
  49059. /**
  49060. * Internal only
  49061. * @ignore
  49062. */
  49063. Action._GetTargetProperty = function (target) {
  49064. return {
  49065. name: "target",
  49066. targetType: target instanceof BABYLON.Mesh ? "MeshProperties"
  49067. : target instanceof BABYLON.Light ? "LightProperties"
  49068. : target instanceof BABYLON.Camera ? "CameraProperties"
  49069. : "SceneProperties",
  49070. value: target instanceof BABYLON.Scene ? "Scene" : target.name
  49071. };
  49072. };
  49073. return Action;
  49074. }());
  49075. BABYLON.Action = Action;
  49076. })(BABYLON || (BABYLON = {}));
  49077. //# sourceMappingURL=babylon.action.js.map
  49078. "use strict";
  49079. var BABYLON;
  49080. (function (BABYLON) {
  49081. /**
  49082. * ActionEvent is the event being sent when an action is triggered.
  49083. */
  49084. var ActionEvent = /** @class */ (function () {
  49085. /**
  49086. * @param source The mesh or sprite that triggered the action.
  49087. * @param pointerX The X mouse cursor position at the time of the event
  49088. * @param pointerY The Y mouse cursor position at the time of the event
  49089. * @param meshUnderPointer The mesh that is currently pointed at (can be null)
  49090. * @param sourceEvent the original (browser) event that triggered the ActionEvent
  49091. */
  49092. function ActionEvent(source, pointerX, pointerY, meshUnderPointer, sourceEvent, additionalData) {
  49093. this.source = source;
  49094. this.pointerX = pointerX;
  49095. this.pointerY = pointerY;
  49096. this.meshUnderPointer = meshUnderPointer;
  49097. this.sourceEvent = sourceEvent;
  49098. this.additionalData = additionalData;
  49099. }
  49100. /**
  49101. * Helper function to auto-create an ActionEvent from a source mesh.
  49102. * @param source The source mesh that triggered the event
  49103. * @param evt {Event} The original (browser) event
  49104. */
  49105. ActionEvent.CreateNew = function (source, evt, additionalData) {
  49106. var scene = source.getScene();
  49107. return new ActionEvent(source, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt, additionalData);
  49108. };
  49109. /**
  49110. * Helper function to auto-create an ActionEvent from a source mesh.
  49111. * @param source The source sprite that triggered the event
  49112. * @param scene Scene associated with the sprite
  49113. * @param evt {Event} The original (browser) event
  49114. */
  49115. ActionEvent.CreateNewFromSprite = function (source, scene, evt, additionalData) {
  49116. return new ActionEvent(source, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt, additionalData);
  49117. };
  49118. /**
  49119. * Helper function to auto-create an ActionEvent from a scene. If triggered by a mesh use ActionEvent.CreateNew
  49120. * @param scene the scene where the event occurred
  49121. * @param evt {Event} The original (browser) event
  49122. */
  49123. ActionEvent.CreateNewFromScene = function (scene, evt) {
  49124. return new ActionEvent(null, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt);
  49125. };
  49126. ActionEvent.CreateNewFromPrimitive = function (prim, pointerPos, evt, additionalData) {
  49127. return new ActionEvent(prim, pointerPos.x, pointerPos.y, null, evt, additionalData);
  49128. };
  49129. return ActionEvent;
  49130. }());
  49131. BABYLON.ActionEvent = ActionEvent;
  49132. /**
  49133. * Action Manager manages all events to be triggered on a given mesh or the global scene.
  49134. * A single scene can have many Action Managers to handle predefined actions on specific meshes.
  49135. */
  49136. var ActionManager = /** @class */ (function () {
  49137. function ActionManager(scene) {
  49138. // Members
  49139. this.actions = new Array();
  49140. this.hoverCursor = '';
  49141. this._scene = scene;
  49142. scene._actionManagers.push(this);
  49143. }
  49144. Object.defineProperty(ActionManager, "NothingTrigger", {
  49145. get: function () {
  49146. return ActionManager._NothingTrigger;
  49147. },
  49148. enumerable: true,
  49149. configurable: true
  49150. });
  49151. Object.defineProperty(ActionManager, "OnPickTrigger", {
  49152. get: function () {
  49153. return ActionManager._OnPickTrigger;
  49154. },
  49155. enumerable: true,
  49156. configurable: true
  49157. });
  49158. Object.defineProperty(ActionManager, "OnLeftPickTrigger", {
  49159. get: function () {
  49160. return ActionManager._OnLeftPickTrigger;
  49161. },
  49162. enumerable: true,
  49163. configurable: true
  49164. });
  49165. Object.defineProperty(ActionManager, "OnRightPickTrigger", {
  49166. get: function () {
  49167. return ActionManager._OnRightPickTrigger;
  49168. },
  49169. enumerable: true,
  49170. configurable: true
  49171. });
  49172. Object.defineProperty(ActionManager, "OnCenterPickTrigger", {
  49173. get: function () {
  49174. return ActionManager._OnCenterPickTrigger;
  49175. },
  49176. enumerable: true,
  49177. configurable: true
  49178. });
  49179. Object.defineProperty(ActionManager, "OnPickDownTrigger", {
  49180. get: function () {
  49181. return ActionManager._OnPickDownTrigger;
  49182. },
  49183. enumerable: true,
  49184. configurable: true
  49185. });
  49186. Object.defineProperty(ActionManager, "OnDoublePickTrigger", {
  49187. get: function () {
  49188. return ActionManager._OnDoublePickTrigger;
  49189. },
  49190. enumerable: true,
  49191. configurable: true
  49192. });
  49193. Object.defineProperty(ActionManager, "OnPickUpTrigger", {
  49194. get: function () {
  49195. return ActionManager._OnPickUpTrigger;
  49196. },
  49197. enumerable: true,
  49198. configurable: true
  49199. });
  49200. Object.defineProperty(ActionManager, "OnPickOutTrigger", {
  49201. /// This trigger will only be raised if you also declared a OnPickDown
  49202. get: function () {
  49203. return ActionManager._OnPickOutTrigger;
  49204. },
  49205. enumerable: true,
  49206. configurable: true
  49207. });
  49208. Object.defineProperty(ActionManager, "OnLongPressTrigger", {
  49209. get: function () {
  49210. return ActionManager._OnLongPressTrigger;
  49211. },
  49212. enumerable: true,
  49213. configurable: true
  49214. });
  49215. Object.defineProperty(ActionManager, "OnPointerOverTrigger", {
  49216. get: function () {
  49217. return ActionManager._OnPointerOverTrigger;
  49218. },
  49219. enumerable: true,
  49220. configurable: true
  49221. });
  49222. Object.defineProperty(ActionManager, "OnPointerOutTrigger", {
  49223. get: function () {
  49224. return ActionManager._OnPointerOutTrigger;
  49225. },
  49226. enumerable: true,
  49227. configurable: true
  49228. });
  49229. Object.defineProperty(ActionManager, "OnEveryFrameTrigger", {
  49230. get: function () {
  49231. return ActionManager._OnEveryFrameTrigger;
  49232. },
  49233. enumerable: true,
  49234. configurable: true
  49235. });
  49236. Object.defineProperty(ActionManager, "OnIntersectionEnterTrigger", {
  49237. get: function () {
  49238. return ActionManager._OnIntersectionEnterTrigger;
  49239. },
  49240. enumerable: true,
  49241. configurable: true
  49242. });
  49243. Object.defineProperty(ActionManager, "OnIntersectionExitTrigger", {
  49244. get: function () {
  49245. return ActionManager._OnIntersectionExitTrigger;
  49246. },
  49247. enumerable: true,
  49248. configurable: true
  49249. });
  49250. Object.defineProperty(ActionManager, "OnKeyDownTrigger", {
  49251. get: function () {
  49252. return ActionManager._OnKeyDownTrigger;
  49253. },
  49254. enumerable: true,
  49255. configurable: true
  49256. });
  49257. Object.defineProperty(ActionManager, "OnKeyUpTrigger", {
  49258. get: function () {
  49259. return ActionManager._OnKeyUpTrigger;
  49260. },
  49261. enumerable: true,
  49262. configurable: true
  49263. });
  49264. // Methods
  49265. ActionManager.prototype.dispose = function () {
  49266. var index = this._scene._actionManagers.indexOf(this);
  49267. for (var i = 0; i < this.actions.length; i++) {
  49268. var action = this.actions[i];
  49269. ActionManager.Triggers[action.trigger]--;
  49270. if (ActionManager.Triggers[action.trigger] === 0) {
  49271. delete ActionManager.Triggers[action.trigger];
  49272. }
  49273. }
  49274. if (index > -1) {
  49275. this._scene._actionManagers.splice(index, 1);
  49276. }
  49277. };
  49278. ActionManager.prototype.getScene = function () {
  49279. return this._scene;
  49280. };
  49281. /**
  49282. * Does this action manager handles actions of any of the given triggers
  49283. * @param {number[]} triggers - the triggers to be tested
  49284. * @return {boolean} whether one (or more) of the triggers is handeled
  49285. */
  49286. ActionManager.prototype.hasSpecificTriggers = function (triggers) {
  49287. for (var index = 0; index < this.actions.length; index++) {
  49288. var action = this.actions[index];
  49289. if (triggers.indexOf(action.trigger) > -1) {
  49290. return true;
  49291. }
  49292. }
  49293. return false;
  49294. };
  49295. /**
  49296. * Does this action manager handles actions of a given trigger
  49297. * @param {number} trigger - the trigger to be tested
  49298. * @return {boolean} whether the trigger is handeled
  49299. */
  49300. ActionManager.prototype.hasSpecificTrigger = function (trigger) {
  49301. for (var index = 0; index < this.actions.length; index++) {
  49302. var action = this.actions[index];
  49303. if (action.trigger === trigger) {
  49304. return true;
  49305. }
  49306. }
  49307. return false;
  49308. };
  49309. Object.defineProperty(ActionManager.prototype, "hasPointerTriggers", {
  49310. /**
  49311. * Does this action manager has pointer triggers
  49312. * @return {boolean} whether or not it has pointer triggers
  49313. */
  49314. get: function () {
  49315. for (var index = 0; index < this.actions.length; index++) {
  49316. var action = this.actions[index];
  49317. if (action.trigger >= ActionManager._OnPickTrigger && action.trigger <= ActionManager._OnPointerOutTrigger) {
  49318. return true;
  49319. }
  49320. }
  49321. return false;
  49322. },
  49323. enumerable: true,
  49324. configurable: true
  49325. });
  49326. Object.defineProperty(ActionManager.prototype, "hasPickTriggers", {
  49327. /**
  49328. * Does this action manager has pick triggers
  49329. * @return {boolean} whether or not it has pick triggers
  49330. */
  49331. get: function () {
  49332. for (var index = 0; index < this.actions.length; index++) {
  49333. var action = this.actions[index];
  49334. if (action.trigger >= ActionManager._OnPickTrigger && action.trigger <= ActionManager._OnPickUpTrigger) {
  49335. return true;
  49336. }
  49337. }
  49338. return false;
  49339. },
  49340. enumerable: true,
  49341. configurable: true
  49342. });
  49343. Object.defineProperty(ActionManager, "HasTriggers", {
  49344. /**
  49345. * Does exist one action manager with at least one trigger
  49346. * @return {boolean} whether or not it exists one action manager with one trigger
  49347. **/
  49348. get: function () {
  49349. for (var t in ActionManager.Triggers) {
  49350. if (ActionManager.Triggers.hasOwnProperty(t)) {
  49351. return true;
  49352. }
  49353. }
  49354. return false;
  49355. },
  49356. enumerable: true,
  49357. configurable: true
  49358. });
  49359. Object.defineProperty(ActionManager, "HasPickTriggers", {
  49360. /**
  49361. * Does exist one action manager with at least one pick trigger
  49362. * @return {boolean} whether or not it exists one action manager with one pick trigger
  49363. **/
  49364. get: function () {
  49365. for (var t in ActionManager.Triggers) {
  49366. if (ActionManager.Triggers.hasOwnProperty(t)) {
  49367. var t_int = parseInt(t);
  49368. if (t_int >= ActionManager._OnPickTrigger && t_int <= ActionManager._OnPickUpTrigger) {
  49369. return true;
  49370. }
  49371. }
  49372. }
  49373. return false;
  49374. },
  49375. enumerable: true,
  49376. configurable: true
  49377. });
  49378. /**
  49379. * Does exist one action manager that handles actions of a given trigger
  49380. * @param {number} trigger - the trigger to be tested
  49381. * @return {boolean} whether the trigger is handeled by at least one action manager
  49382. **/
  49383. ActionManager.HasSpecificTrigger = function (trigger) {
  49384. for (var t in ActionManager.Triggers) {
  49385. if (ActionManager.Triggers.hasOwnProperty(t)) {
  49386. var t_int = parseInt(t);
  49387. if (t_int === trigger) {
  49388. return true;
  49389. }
  49390. }
  49391. }
  49392. return false;
  49393. };
  49394. /**
  49395. * Registers an action to this action manager
  49396. * @param {BABYLON.Action} action - the action to be registered
  49397. * @return {BABYLON.Action} the action amended (prepared) after registration
  49398. */
  49399. ActionManager.prototype.registerAction = function (action) {
  49400. if (action.trigger === ActionManager.OnEveryFrameTrigger) {
  49401. if (this.getScene().actionManager !== this) {
  49402. BABYLON.Tools.Warn("OnEveryFrameTrigger can only be used with scene.actionManager");
  49403. return null;
  49404. }
  49405. }
  49406. this.actions.push(action);
  49407. if (ActionManager.Triggers[action.trigger]) {
  49408. ActionManager.Triggers[action.trigger]++;
  49409. }
  49410. else {
  49411. ActionManager.Triggers[action.trigger] = 1;
  49412. }
  49413. action._actionManager = this;
  49414. action._prepare();
  49415. return action;
  49416. };
  49417. /**
  49418. * Unregisters an action to this action manager
  49419. * @param action The action to be unregistered
  49420. * @return whether the action has been unregistered
  49421. */
  49422. ActionManager.prototype.unregisterAction = function (action) {
  49423. var index = this.actions.indexOf(action);
  49424. if (index !== -1) {
  49425. this.actions.splice(index, 1);
  49426. ActionManager.Triggers[action.trigger] -= 1;
  49427. if (ActionManager.Triggers[action.trigger] === 0) {
  49428. delete ActionManager.Triggers[action.trigger];
  49429. }
  49430. delete action._actionManager;
  49431. return true;
  49432. }
  49433. return false;
  49434. };
  49435. /**
  49436. * Process a specific trigger
  49437. * @param {number} trigger - the trigger to process
  49438. * @param evt {BABYLON.ActionEvent} the event details to be processed
  49439. */
  49440. ActionManager.prototype.processTrigger = function (trigger, evt) {
  49441. for (var index = 0; index < this.actions.length; index++) {
  49442. var action = this.actions[index];
  49443. if (action.trigger === trigger) {
  49444. if (evt) {
  49445. if (trigger === ActionManager.OnKeyUpTrigger
  49446. || trigger === ActionManager.OnKeyDownTrigger) {
  49447. var parameter = action.getTriggerParameter();
  49448. if (parameter && parameter !== evt.sourceEvent.keyCode) {
  49449. if (!parameter.toLowerCase) {
  49450. continue;
  49451. }
  49452. var lowerCase = parameter.toLowerCase();
  49453. if (lowerCase !== evt.sourceEvent.key) {
  49454. var unicode = evt.sourceEvent.charCode ? evt.sourceEvent.charCode : evt.sourceEvent.keyCode;
  49455. var actualkey = String.fromCharCode(unicode).toLowerCase();
  49456. if (actualkey !== lowerCase) {
  49457. continue;
  49458. }
  49459. }
  49460. }
  49461. }
  49462. }
  49463. action._executeCurrent(evt);
  49464. }
  49465. }
  49466. };
  49467. ActionManager.prototype._getEffectiveTarget = function (target, propertyPath) {
  49468. var properties = propertyPath.split(".");
  49469. for (var index = 0; index < properties.length - 1; index++) {
  49470. target = target[properties[index]];
  49471. }
  49472. return target;
  49473. };
  49474. ActionManager.prototype._getProperty = function (propertyPath) {
  49475. var properties = propertyPath.split(".");
  49476. return properties[properties.length - 1];
  49477. };
  49478. ActionManager.prototype.serialize = function (name) {
  49479. var root = {
  49480. children: new Array(),
  49481. name: name,
  49482. type: 3,
  49483. properties: new Array() // Empty for root but required
  49484. };
  49485. for (var i = 0; i < this.actions.length; i++) {
  49486. var triggerObject = {
  49487. type: 0,
  49488. children: new Array(),
  49489. name: ActionManager.GetTriggerName(this.actions[i].trigger),
  49490. properties: new Array()
  49491. };
  49492. var triggerOptions = this.actions[i].triggerOptions;
  49493. if (triggerOptions && typeof triggerOptions !== "number") {
  49494. if (triggerOptions.parameter instanceof BABYLON.Node) {
  49495. triggerObject.properties.push(BABYLON.Action._GetTargetProperty(triggerOptions.parameter));
  49496. }
  49497. else {
  49498. var parameter = {};
  49499. BABYLON.Tools.DeepCopy(triggerOptions.parameter, parameter, ["mesh"]);
  49500. if (triggerOptions.parameter.mesh) {
  49501. parameter._meshId = triggerOptions.parameter.mesh.id;
  49502. }
  49503. triggerObject.properties.push({ name: "parameter", targetType: null, value: parameter });
  49504. }
  49505. }
  49506. // Serialize child action, recursively
  49507. this.actions[i].serialize(triggerObject);
  49508. // Add serialized trigger
  49509. root.children.push(triggerObject);
  49510. }
  49511. return root;
  49512. };
  49513. ActionManager.Parse = function (parsedActions, object, scene) {
  49514. var actionManager = new ActionManager(scene);
  49515. if (object === null)
  49516. scene.actionManager = actionManager;
  49517. else
  49518. object.actionManager = actionManager;
  49519. // instanciate a new object
  49520. var instanciate = function (name, params) {
  49521. // TODO: We will need to find a solution for the next line when using commonjs / es6 .
  49522. var newInstance = Object.create(BABYLON.Tools.Instantiate("BABYLON." + name).prototype);
  49523. newInstance.constructor.apply(newInstance, params);
  49524. return newInstance;
  49525. };
  49526. var parseParameter = function (name, value, target, propertyPath) {
  49527. if (propertyPath === null) {
  49528. // String, boolean or float
  49529. var floatValue = parseFloat(value);
  49530. if (value === "true" || value === "false")
  49531. return value === "true";
  49532. else
  49533. return isNaN(floatValue) ? value : floatValue;
  49534. }
  49535. var effectiveTarget = propertyPath.split(".");
  49536. var values = value.split(",");
  49537. // Get effective Target
  49538. for (var i = 0; i < effectiveTarget.length; i++) {
  49539. target = target[effectiveTarget[i]];
  49540. }
  49541. // Return appropriate value with its type
  49542. if (typeof (target) === "boolean")
  49543. return values[0] === "true";
  49544. if (typeof (target) === "string")
  49545. return values[0];
  49546. // Parameters with multiple values such as Vector3 etc.
  49547. var split = new Array();
  49548. for (var i = 0; i < values.length; i++)
  49549. split.push(parseFloat(values[i]));
  49550. if (target instanceof BABYLON.Vector3)
  49551. return BABYLON.Vector3.FromArray(split);
  49552. if (target instanceof BABYLON.Vector4)
  49553. return BABYLON.Vector4.FromArray(split);
  49554. if (target instanceof BABYLON.Color3)
  49555. return BABYLON.Color3.FromArray(split);
  49556. if (target instanceof BABYLON.Color4)
  49557. return BABYLON.Color4.FromArray(split);
  49558. return parseFloat(values[0]);
  49559. };
  49560. // traverse graph per trigger
  49561. var traverse = function (parsedAction, trigger, condition, action, combineArray) {
  49562. if (combineArray === void 0) { combineArray = null; }
  49563. if (parsedAction.detached)
  49564. return;
  49565. var parameters = new Array();
  49566. var target = null;
  49567. var propertyPath = null;
  49568. var combine = parsedAction.combine && parsedAction.combine.length > 0;
  49569. // Parameters
  49570. if (parsedAction.type === 2)
  49571. parameters.push(actionManager);
  49572. else
  49573. parameters.push(trigger);
  49574. if (combine) {
  49575. var actions = new Array();
  49576. for (var j = 0; j < parsedAction.combine.length; j++) {
  49577. traverse(parsedAction.combine[j], ActionManager.NothingTrigger, condition, action, actions);
  49578. }
  49579. parameters.push(actions);
  49580. }
  49581. else {
  49582. for (var i = 0; i < parsedAction.properties.length; i++) {
  49583. var value = parsedAction.properties[i].value;
  49584. var name = parsedAction.properties[i].name;
  49585. var targetType = parsedAction.properties[i].targetType;
  49586. if (name === "target")
  49587. if (targetType !== null && targetType === "SceneProperties")
  49588. value = target = scene;
  49589. else
  49590. value = target = scene.getNodeByName(value);
  49591. else if (name === "parent")
  49592. value = scene.getNodeByName(value);
  49593. else if (name === "sound")
  49594. value = scene.getSoundByName(value);
  49595. else if (name !== "propertyPath") {
  49596. if (parsedAction.type === 2 && name === "operator")
  49597. value = BABYLON.ValueCondition[value];
  49598. else
  49599. value = parseParameter(name, value, target, name === "value" ? propertyPath : null);
  49600. }
  49601. else {
  49602. propertyPath = value;
  49603. }
  49604. parameters.push(value);
  49605. }
  49606. }
  49607. if (combineArray === null) {
  49608. parameters.push(condition);
  49609. }
  49610. else {
  49611. parameters.push(null);
  49612. }
  49613. // If interpolate value action
  49614. if (parsedAction.name === "InterpolateValueAction") {
  49615. var param = parameters[parameters.length - 2];
  49616. parameters[parameters.length - 1] = param;
  49617. parameters[parameters.length - 2] = condition;
  49618. }
  49619. // Action or condition(s) and not CombineAction
  49620. var newAction = instanciate(parsedAction.name, parameters);
  49621. if (newAction instanceof BABYLON.Condition && condition !== null) {
  49622. var nothing = new BABYLON.DoNothingAction(trigger, condition);
  49623. if (action)
  49624. action.then(nothing);
  49625. else
  49626. actionManager.registerAction(nothing);
  49627. action = nothing;
  49628. }
  49629. if (combineArray === null) {
  49630. if (newAction instanceof BABYLON.Condition) {
  49631. condition = newAction;
  49632. newAction = action;
  49633. }
  49634. else {
  49635. condition = null;
  49636. if (action)
  49637. action.then(newAction);
  49638. else
  49639. actionManager.registerAction(newAction);
  49640. }
  49641. }
  49642. else {
  49643. combineArray.push(newAction);
  49644. }
  49645. for (var i = 0; i < parsedAction.children.length; i++)
  49646. traverse(parsedAction.children[i], trigger, condition, newAction, null);
  49647. };
  49648. // triggers
  49649. for (var i = 0; i < parsedActions.children.length; i++) {
  49650. var triggerParams;
  49651. var trigger = parsedActions.children[i];
  49652. if (trigger.properties.length > 0) {
  49653. var param = trigger.properties[0].value;
  49654. var value = trigger.properties[0].targetType === null ? param : scene.getMeshByName(param);
  49655. if (value._meshId) {
  49656. value.mesh = scene.getMeshByID(value._meshId);
  49657. }
  49658. triggerParams = { trigger: ActionManager[trigger.name], parameter: value };
  49659. }
  49660. else
  49661. triggerParams = ActionManager[trigger.name];
  49662. for (var j = 0; j < trigger.children.length; j++) {
  49663. if (!trigger.detached)
  49664. traverse(trigger.children[j], triggerParams, null, null);
  49665. }
  49666. }
  49667. };
  49668. ActionManager.GetTriggerName = function (trigger) {
  49669. switch (trigger) {
  49670. case 0: return "NothingTrigger";
  49671. case 1: return "OnPickTrigger";
  49672. case 2: return "OnLeftPickTrigger";
  49673. case 3: return "OnRightPickTrigger";
  49674. case 4: return "OnCenterPickTrigger";
  49675. case 5: return "OnPickDownTrigger";
  49676. case 6: return "OnPickUpTrigger";
  49677. case 7: return "OnLongPressTrigger";
  49678. case 8: return "OnPointerOverTrigger";
  49679. case 9: return "OnPointerOutTrigger";
  49680. case 10: return "OnEveryFrameTrigger";
  49681. case 11: return "OnIntersectionEnterTrigger";
  49682. case 12: return "OnIntersectionExitTrigger";
  49683. case 13: return "OnKeyDownTrigger";
  49684. case 14: return "OnKeyUpTrigger";
  49685. case 15: return "OnPickOutTrigger";
  49686. default: return "";
  49687. }
  49688. };
  49689. // Statics
  49690. ActionManager._NothingTrigger = 0;
  49691. ActionManager._OnPickTrigger = 1;
  49692. ActionManager._OnLeftPickTrigger = 2;
  49693. ActionManager._OnRightPickTrigger = 3;
  49694. ActionManager._OnCenterPickTrigger = 4;
  49695. ActionManager._OnPickDownTrigger = 5;
  49696. ActionManager._OnDoublePickTrigger = 6;
  49697. ActionManager._OnPickUpTrigger = 7;
  49698. ActionManager._OnLongPressTrigger = 8;
  49699. ActionManager._OnPointerOverTrigger = 9;
  49700. ActionManager._OnPointerOutTrigger = 10;
  49701. ActionManager._OnEveryFrameTrigger = 11;
  49702. ActionManager._OnIntersectionEnterTrigger = 12;
  49703. ActionManager._OnIntersectionExitTrigger = 13;
  49704. ActionManager._OnKeyDownTrigger = 14;
  49705. ActionManager._OnKeyUpTrigger = 15;
  49706. ActionManager._OnPickOutTrigger = 16;
  49707. ActionManager.Triggers = {};
  49708. return ActionManager;
  49709. }());
  49710. BABYLON.ActionManager = ActionManager;
  49711. })(BABYLON || (BABYLON = {}));
  49712. //# sourceMappingURL=babylon.actionManager.js.map
  49713. "use strict";
  49714. var BABYLON;
  49715. (function (BABYLON) {
  49716. var InterpolateValueAction = /** @class */ (function (_super) {
  49717. __extends(InterpolateValueAction, _super);
  49718. function InterpolateValueAction(triggerOptions, target, propertyPath, value, duration, condition, stopOtherAnimations, onInterpolationDone) {
  49719. if (duration === void 0) { duration = 1000; }
  49720. var _this = _super.call(this, triggerOptions, condition) || this;
  49721. _this.propertyPath = propertyPath;
  49722. _this.value = value;
  49723. _this.duration = duration;
  49724. _this.stopOtherAnimations = stopOtherAnimations;
  49725. _this.onInterpolationDone = onInterpolationDone;
  49726. _this.onInterpolationDoneObservable = new BABYLON.Observable();
  49727. _this._target = _this._effectiveTarget = target;
  49728. return _this;
  49729. }
  49730. InterpolateValueAction.prototype._prepare = function () {
  49731. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  49732. this._property = this._getProperty(this.propertyPath);
  49733. };
  49734. InterpolateValueAction.prototype.execute = function () {
  49735. var _this = this;
  49736. var scene = this._actionManager.getScene();
  49737. var keys = [
  49738. {
  49739. frame: 0,
  49740. value: this._effectiveTarget[this._property]
  49741. }, {
  49742. frame: 100,
  49743. value: this.value
  49744. }
  49745. ];
  49746. var dataType;
  49747. if (typeof this.value === "number") {
  49748. dataType = BABYLON.Animation.ANIMATIONTYPE_FLOAT;
  49749. }
  49750. else if (this.value instanceof BABYLON.Color3) {
  49751. dataType = BABYLON.Animation.ANIMATIONTYPE_COLOR3;
  49752. }
  49753. else if (this.value instanceof BABYLON.Vector3) {
  49754. dataType = BABYLON.Animation.ANIMATIONTYPE_VECTOR3;
  49755. }
  49756. else if (this.value instanceof BABYLON.Matrix) {
  49757. dataType = BABYLON.Animation.ANIMATIONTYPE_MATRIX;
  49758. }
  49759. else if (this.value instanceof BABYLON.Quaternion) {
  49760. dataType = BABYLON.Animation.ANIMATIONTYPE_QUATERNION;
  49761. }
  49762. else {
  49763. BABYLON.Tools.Warn("InterpolateValueAction: Unsupported type (" + typeof this.value + ")");
  49764. return;
  49765. }
  49766. var animation = new BABYLON.Animation("InterpolateValueAction", this._property, 100 * (1000.0 / this.duration), dataType, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  49767. animation.setKeys(keys);
  49768. if (this.stopOtherAnimations) {
  49769. scene.stopAnimation(this._effectiveTarget);
  49770. }
  49771. var wrapper = function () {
  49772. _this.onInterpolationDoneObservable.notifyObservers(_this);
  49773. if (_this.onInterpolationDone) {
  49774. _this.onInterpolationDone();
  49775. }
  49776. };
  49777. scene.beginDirectAnimation(this._effectiveTarget, [animation], 0, 100, false, 1, wrapper);
  49778. };
  49779. InterpolateValueAction.prototype.serialize = function (parent) {
  49780. return _super.prototype._serialize.call(this, {
  49781. name: "InterpolateValueAction",
  49782. properties: [
  49783. BABYLON.Action._GetTargetProperty(this._target),
  49784. { name: "propertyPath", value: this.propertyPath },
  49785. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) },
  49786. { name: "duration", value: BABYLON.Action._SerializeValueAsString(this.duration) },
  49787. { name: "stopOtherAnimations", value: BABYLON.Action._SerializeValueAsString(this.stopOtherAnimations) || false }
  49788. ]
  49789. }, parent);
  49790. };
  49791. return InterpolateValueAction;
  49792. }(BABYLON.Action));
  49793. BABYLON.InterpolateValueAction = InterpolateValueAction;
  49794. })(BABYLON || (BABYLON = {}));
  49795. //# sourceMappingURL=babylon.interpolateValueAction.js.map
  49796. "use strict";
  49797. var BABYLON;
  49798. (function (BABYLON) {
  49799. var SwitchBooleanAction = /** @class */ (function (_super) {
  49800. __extends(SwitchBooleanAction, _super);
  49801. function SwitchBooleanAction(triggerOptions, target, propertyPath, condition) {
  49802. var _this = _super.call(this, triggerOptions, condition) || this;
  49803. _this.propertyPath = propertyPath;
  49804. _this._target = _this._effectiveTarget = target;
  49805. return _this;
  49806. }
  49807. SwitchBooleanAction.prototype._prepare = function () {
  49808. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  49809. this._property = this._getProperty(this.propertyPath);
  49810. };
  49811. SwitchBooleanAction.prototype.execute = function () {
  49812. this._effectiveTarget[this._property] = !this._effectiveTarget[this._property];
  49813. };
  49814. SwitchBooleanAction.prototype.serialize = function (parent) {
  49815. return _super.prototype._serialize.call(this, {
  49816. name: "SwitchBooleanAction",
  49817. properties: [
  49818. BABYLON.Action._GetTargetProperty(this._target),
  49819. { name: "propertyPath", value: this.propertyPath }
  49820. ]
  49821. }, parent);
  49822. };
  49823. return SwitchBooleanAction;
  49824. }(BABYLON.Action));
  49825. BABYLON.SwitchBooleanAction = SwitchBooleanAction;
  49826. var SetStateAction = /** @class */ (function (_super) {
  49827. __extends(SetStateAction, _super);
  49828. function SetStateAction(triggerOptions, target, value, condition) {
  49829. var _this = _super.call(this, triggerOptions, condition) || this;
  49830. _this.value = value;
  49831. _this._target = target;
  49832. return _this;
  49833. }
  49834. SetStateAction.prototype.execute = function () {
  49835. this._target.state = this.value;
  49836. };
  49837. SetStateAction.prototype.serialize = function (parent) {
  49838. return _super.prototype._serialize.call(this, {
  49839. name: "SetStateAction",
  49840. properties: [
  49841. BABYLON.Action._GetTargetProperty(this._target),
  49842. { name: "value", value: this.value }
  49843. ]
  49844. }, parent);
  49845. };
  49846. return SetStateAction;
  49847. }(BABYLON.Action));
  49848. BABYLON.SetStateAction = SetStateAction;
  49849. var SetValueAction = /** @class */ (function (_super) {
  49850. __extends(SetValueAction, _super);
  49851. function SetValueAction(triggerOptions, target, propertyPath, value, condition) {
  49852. var _this = _super.call(this, triggerOptions, condition) || this;
  49853. _this.propertyPath = propertyPath;
  49854. _this.value = value;
  49855. _this._target = _this._effectiveTarget = target;
  49856. return _this;
  49857. }
  49858. SetValueAction.prototype._prepare = function () {
  49859. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  49860. this._property = this._getProperty(this.propertyPath);
  49861. };
  49862. SetValueAction.prototype.execute = function () {
  49863. this._effectiveTarget[this._property] = this.value;
  49864. if (this._target.markAsDirty) {
  49865. this._target.markAsDirty(this._property);
  49866. }
  49867. };
  49868. SetValueAction.prototype.serialize = function (parent) {
  49869. return _super.prototype._serialize.call(this, {
  49870. name: "SetValueAction",
  49871. properties: [
  49872. BABYLON.Action._GetTargetProperty(this._target),
  49873. { name: "propertyPath", value: this.propertyPath },
  49874. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) }
  49875. ]
  49876. }, parent);
  49877. };
  49878. return SetValueAction;
  49879. }(BABYLON.Action));
  49880. BABYLON.SetValueAction = SetValueAction;
  49881. var IncrementValueAction = /** @class */ (function (_super) {
  49882. __extends(IncrementValueAction, _super);
  49883. function IncrementValueAction(triggerOptions, target, propertyPath, value, condition) {
  49884. var _this = _super.call(this, triggerOptions, condition) || this;
  49885. _this.propertyPath = propertyPath;
  49886. _this.value = value;
  49887. _this._target = _this._effectiveTarget = target;
  49888. return _this;
  49889. }
  49890. IncrementValueAction.prototype._prepare = function () {
  49891. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  49892. this._property = this._getProperty(this.propertyPath);
  49893. if (typeof this._effectiveTarget[this._property] !== "number") {
  49894. BABYLON.Tools.Warn("Warning: IncrementValueAction can only be used with number values");
  49895. }
  49896. };
  49897. IncrementValueAction.prototype.execute = function () {
  49898. this._effectiveTarget[this._property] += this.value;
  49899. if (this._target.markAsDirty) {
  49900. this._target.markAsDirty(this._property);
  49901. }
  49902. };
  49903. IncrementValueAction.prototype.serialize = function (parent) {
  49904. return _super.prototype._serialize.call(this, {
  49905. name: "IncrementValueAction",
  49906. properties: [
  49907. BABYLON.Action._GetTargetProperty(this._target),
  49908. { name: "propertyPath", value: this.propertyPath },
  49909. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) }
  49910. ]
  49911. }, parent);
  49912. };
  49913. return IncrementValueAction;
  49914. }(BABYLON.Action));
  49915. BABYLON.IncrementValueAction = IncrementValueAction;
  49916. var PlayAnimationAction = /** @class */ (function (_super) {
  49917. __extends(PlayAnimationAction, _super);
  49918. function PlayAnimationAction(triggerOptions, target, from, to, loop, condition) {
  49919. var _this = _super.call(this, triggerOptions, condition) || this;
  49920. _this.from = from;
  49921. _this.to = to;
  49922. _this.loop = loop;
  49923. _this._target = target;
  49924. return _this;
  49925. }
  49926. PlayAnimationAction.prototype._prepare = function () {
  49927. };
  49928. PlayAnimationAction.prototype.execute = function () {
  49929. var scene = this._actionManager.getScene();
  49930. scene.beginAnimation(this._target, this.from, this.to, this.loop);
  49931. };
  49932. PlayAnimationAction.prototype.serialize = function (parent) {
  49933. return _super.prototype._serialize.call(this, {
  49934. name: "PlayAnimationAction",
  49935. properties: [
  49936. BABYLON.Action._GetTargetProperty(this._target),
  49937. { name: "from", value: String(this.from) },
  49938. { name: "to", value: String(this.to) },
  49939. { name: "loop", value: BABYLON.Action._SerializeValueAsString(this.loop) || false }
  49940. ]
  49941. }, parent);
  49942. };
  49943. return PlayAnimationAction;
  49944. }(BABYLON.Action));
  49945. BABYLON.PlayAnimationAction = PlayAnimationAction;
  49946. var StopAnimationAction = /** @class */ (function (_super) {
  49947. __extends(StopAnimationAction, _super);
  49948. function StopAnimationAction(triggerOptions, target, condition) {
  49949. var _this = _super.call(this, triggerOptions, condition) || this;
  49950. _this._target = target;
  49951. return _this;
  49952. }
  49953. StopAnimationAction.prototype._prepare = function () {
  49954. };
  49955. StopAnimationAction.prototype.execute = function () {
  49956. var scene = this._actionManager.getScene();
  49957. scene.stopAnimation(this._target);
  49958. };
  49959. StopAnimationAction.prototype.serialize = function (parent) {
  49960. return _super.prototype._serialize.call(this, {
  49961. name: "StopAnimationAction",
  49962. properties: [BABYLON.Action._GetTargetProperty(this._target)]
  49963. }, parent);
  49964. };
  49965. return StopAnimationAction;
  49966. }(BABYLON.Action));
  49967. BABYLON.StopAnimationAction = StopAnimationAction;
  49968. var DoNothingAction = /** @class */ (function (_super) {
  49969. __extends(DoNothingAction, _super);
  49970. function DoNothingAction(triggerOptions, condition) {
  49971. if (triggerOptions === void 0) { triggerOptions = BABYLON.ActionManager.NothingTrigger; }
  49972. return _super.call(this, triggerOptions, condition) || this;
  49973. }
  49974. DoNothingAction.prototype.execute = function () {
  49975. };
  49976. DoNothingAction.prototype.serialize = function (parent) {
  49977. return _super.prototype._serialize.call(this, {
  49978. name: "DoNothingAction",
  49979. properties: []
  49980. }, parent);
  49981. };
  49982. return DoNothingAction;
  49983. }(BABYLON.Action));
  49984. BABYLON.DoNothingAction = DoNothingAction;
  49985. var CombineAction = /** @class */ (function (_super) {
  49986. __extends(CombineAction, _super);
  49987. function CombineAction(triggerOptions, children, condition) {
  49988. var _this = _super.call(this, triggerOptions, condition) || this;
  49989. _this.children = children;
  49990. return _this;
  49991. }
  49992. CombineAction.prototype._prepare = function () {
  49993. for (var index = 0; index < this.children.length; index++) {
  49994. this.children[index]._actionManager = this._actionManager;
  49995. this.children[index]._prepare();
  49996. }
  49997. };
  49998. CombineAction.prototype.execute = function (evt) {
  49999. for (var index = 0; index < this.children.length; index++) {
  50000. this.children[index].execute(evt);
  50001. }
  50002. };
  50003. CombineAction.prototype.serialize = function (parent) {
  50004. var serializationObject = _super.prototype._serialize.call(this, {
  50005. name: "CombineAction",
  50006. properties: [],
  50007. combine: []
  50008. }, parent);
  50009. for (var i = 0; i < this.children.length; i++) {
  50010. serializationObject.combine.push(this.children[i].serialize(null));
  50011. }
  50012. return serializationObject;
  50013. };
  50014. return CombineAction;
  50015. }(BABYLON.Action));
  50016. BABYLON.CombineAction = CombineAction;
  50017. var ExecuteCodeAction = /** @class */ (function (_super) {
  50018. __extends(ExecuteCodeAction, _super);
  50019. function ExecuteCodeAction(triggerOptions, func, condition) {
  50020. var _this = _super.call(this, triggerOptions, condition) || this;
  50021. _this.func = func;
  50022. return _this;
  50023. }
  50024. ExecuteCodeAction.prototype.execute = function (evt) {
  50025. this.func(evt);
  50026. };
  50027. return ExecuteCodeAction;
  50028. }(BABYLON.Action));
  50029. BABYLON.ExecuteCodeAction = ExecuteCodeAction;
  50030. var SetParentAction = /** @class */ (function (_super) {
  50031. __extends(SetParentAction, _super);
  50032. function SetParentAction(triggerOptions, target, parent, condition) {
  50033. var _this = _super.call(this, triggerOptions, condition) || this;
  50034. _this._target = target;
  50035. _this._parent = parent;
  50036. return _this;
  50037. }
  50038. SetParentAction.prototype._prepare = function () {
  50039. };
  50040. SetParentAction.prototype.execute = function () {
  50041. if (this._target.parent === this._parent) {
  50042. return;
  50043. }
  50044. var invertParentWorldMatrix = this._parent.getWorldMatrix().clone();
  50045. invertParentWorldMatrix.invert();
  50046. this._target.position = BABYLON.Vector3.TransformCoordinates(this._target.position, invertParentWorldMatrix);
  50047. this._target.parent = this._parent;
  50048. };
  50049. SetParentAction.prototype.serialize = function (parent) {
  50050. return _super.prototype._serialize.call(this, {
  50051. name: "SetParentAction",
  50052. properties: [
  50053. BABYLON.Action._GetTargetProperty(this._target),
  50054. BABYLON.Action._GetTargetProperty(this._parent),
  50055. ]
  50056. }, parent);
  50057. };
  50058. return SetParentAction;
  50059. }(BABYLON.Action));
  50060. BABYLON.SetParentAction = SetParentAction;
  50061. var PlaySoundAction = /** @class */ (function (_super) {
  50062. __extends(PlaySoundAction, _super);
  50063. function PlaySoundAction(triggerOptions, sound, condition) {
  50064. var _this = _super.call(this, triggerOptions, condition) || this;
  50065. _this._sound = sound;
  50066. return _this;
  50067. }
  50068. PlaySoundAction.prototype._prepare = function () {
  50069. };
  50070. PlaySoundAction.prototype.execute = function () {
  50071. if (this._sound !== undefined)
  50072. this._sound.play();
  50073. };
  50074. PlaySoundAction.prototype.serialize = function (parent) {
  50075. return _super.prototype._serialize.call(this, {
  50076. name: "PlaySoundAction",
  50077. properties: [{ name: "sound", value: this._sound.name }]
  50078. }, parent);
  50079. };
  50080. return PlaySoundAction;
  50081. }(BABYLON.Action));
  50082. BABYLON.PlaySoundAction = PlaySoundAction;
  50083. var StopSoundAction = /** @class */ (function (_super) {
  50084. __extends(StopSoundAction, _super);
  50085. function StopSoundAction(triggerOptions, sound, condition) {
  50086. var _this = _super.call(this, triggerOptions, condition) || this;
  50087. _this._sound = sound;
  50088. return _this;
  50089. }
  50090. StopSoundAction.prototype._prepare = function () {
  50091. };
  50092. StopSoundAction.prototype.execute = function () {
  50093. if (this._sound !== undefined)
  50094. this._sound.stop();
  50095. };
  50096. StopSoundAction.prototype.serialize = function (parent) {
  50097. return _super.prototype._serialize.call(this, {
  50098. name: "StopSoundAction",
  50099. properties: [{ name: "sound", value: this._sound.name }]
  50100. }, parent);
  50101. };
  50102. return StopSoundAction;
  50103. }(BABYLON.Action));
  50104. BABYLON.StopSoundAction = StopSoundAction;
  50105. })(BABYLON || (BABYLON = {}));
  50106. //# sourceMappingURL=babylon.directActions.js.map
  50107. "use strict";
  50108. var BABYLON;
  50109. (function (BABYLON) {
  50110. var SpriteManager = /** @class */ (function () {
  50111. function SpriteManager(name, imgUrl, capacity, cellSize, scene, epsilon, samplingMode) {
  50112. if (epsilon === void 0) { epsilon = 0.01; }
  50113. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  50114. this.name = name;
  50115. this.sprites = new Array();
  50116. this.renderingGroupId = 0;
  50117. this.layerMask = 0x0FFFFFFF;
  50118. this.fogEnabled = true;
  50119. this.isPickable = false;
  50120. /**
  50121. * An event triggered when the manager is disposed.
  50122. */
  50123. this.onDisposeObservable = new BABYLON.Observable();
  50124. this._vertexBuffers = {};
  50125. this._capacity = capacity;
  50126. this._spriteTexture = new BABYLON.Texture(imgUrl, scene, true, false, samplingMode);
  50127. this._spriteTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  50128. this._spriteTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  50129. if (cellSize.width && cellSize.height) {
  50130. this.cellWidth = cellSize.width;
  50131. this.cellHeight = cellSize.height;
  50132. }
  50133. else if (cellSize !== undefined) {
  50134. this.cellWidth = cellSize;
  50135. this.cellHeight = cellSize;
  50136. }
  50137. else {
  50138. return;
  50139. }
  50140. this._epsilon = epsilon;
  50141. this._scene = scene;
  50142. this._scene.spriteManagers.push(this);
  50143. var indices = [];
  50144. var index = 0;
  50145. for (var count = 0; count < capacity; count++) {
  50146. indices.push(index);
  50147. indices.push(index + 1);
  50148. indices.push(index + 2);
  50149. indices.push(index);
  50150. indices.push(index + 2);
  50151. indices.push(index + 3);
  50152. index += 4;
  50153. }
  50154. this._indexBuffer = scene.getEngine().createIndexBuffer(indices);
  50155. // VBO
  50156. // 16 floats per sprite (x, y, z, angle, sizeX, sizeY, offsetX, offsetY, invertU, invertV, cellIndexX, cellIndexY, color r, color g, color b, color a)
  50157. this._vertexData = new Float32Array(capacity * 16 * 4);
  50158. this._buffer = new BABYLON.Buffer(scene.getEngine(), this._vertexData, true, 16);
  50159. var positions = this._buffer.createVertexBuffer(BABYLON.VertexBuffer.PositionKind, 0, 4);
  50160. var options = this._buffer.createVertexBuffer("options", 4, 4);
  50161. var cellInfo = this._buffer.createVertexBuffer("cellInfo", 8, 4);
  50162. var colors = this._buffer.createVertexBuffer(BABYLON.VertexBuffer.ColorKind, 12, 4);
  50163. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = positions;
  50164. this._vertexBuffers["options"] = options;
  50165. this._vertexBuffers["cellInfo"] = cellInfo;
  50166. this._vertexBuffers[BABYLON.VertexBuffer.ColorKind] = colors;
  50167. // Effects
  50168. this._effectBase = this._scene.getEngine().createEffect("sprites", [BABYLON.VertexBuffer.PositionKind, "options", "cellInfo", BABYLON.VertexBuffer.ColorKind], ["view", "projection", "textureInfos", "alphaTest"], ["diffuseSampler"], "");
  50169. this._effectFog = this._scene.getEngine().createEffect("sprites", [BABYLON.VertexBuffer.PositionKind, "options", "cellInfo", BABYLON.VertexBuffer.ColorKind], ["view", "projection", "textureInfos", "alphaTest", "vFogInfos", "vFogColor"], ["diffuseSampler"], "#define FOG");
  50170. }
  50171. Object.defineProperty(SpriteManager.prototype, "onDispose", {
  50172. set: function (callback) {
  50173. if (this._onDisposeObserver) {
  50174. this.onDisposeObservable.remove(this._onDisposeObserver);
  50175. }
  50176. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  50177. },
  50178. enumerable: true,
  50179. configurable: true
  50180. });
  50181. Object.defineProperty(SpriteManager.prototype, "texture", {
  50182. get: function () {
  50183. return this._spriteTexture;
  50184. },
  50185. set: function (value) {
  50186. this._spriteTexture = value;
  50187. },
  50188. enumerable: true,
  50189. configurable: true
  50190. });
  50191. SpriteManager.prototype._appendSpriteVertex = function (index, sprite, offsetX, offsetY, rowSize) {
  50192. var arrayOffset = index * 16;
  50193. if (offsetX === 0)
  50194. offsetX = this._epsilon;
  50195. else if (offsetX === 1)
  50196. offsetX = 1 - this._epsilon;
  50197. if (offsetY === 0)
  50198. offsetY = this._epsilon;
  50199. else if (offsetY === 1)
  50200. offsetY = 1 - this._epsilon;
  50201. this._vertexData[arrayOffset] = sprite.position.x;
  50202. this._vertexData[arrayOffset + 1] = sprite.position.y;
  50203. this._vertexData[arrayOffset + 2] = sprite.position.z;
  50204. this._vertexData[arrayOffset + 3] = sprite.angle;
  50205. this._vertexData[arrayOffset + 4] = sprite.width;
  50206. this._vertexData[arrayOffset + 5] = sprite.height;
  50207. this._vertexData[arrayOffset + 6] = offsetX;
  50208. this._vertexData[arrayOffset + 7] = offsetY;
  50209. this._vertexData[arrayOffset + 8] = sprite.invertU ? 1 : 0;
  50210. this._vertexData[arrayOffset + 9] = sprite.invertV ? 1 : 0;
  50211. var offset = (sprite.cellIndex / rowSize) >> 0;
  50212. this._vertexData[arrayOffset + 10] = sprite.cellIndex - offset * rowSize;
  50213. this._vertexData[arrayOffset + 11] = offset;
  50214. // Color
  50215. this._vertexData[arrayOffset + 12] = sprite.color.r;
  50216. this._vertexData[arrayOffset + 13] = sprite.color.g;
  50217. this._vertexData[arrayOffset + 14] = sprite.color.b;
  50218. this._vertexData[arrayOffset + 15] = sprite.color.a;
  50219. };
  50220. SpriteManager.prototype.intersects = function (ray, camera, predicate, fastCheck) {
  50221. var count = Math.min(this._capacity, this.sprites.length);
  50222. var min = BABYLON.Vector3.Zero();
  50223. var max = BABYLON.Vector3.Zero();
  50224. var distance = Number.MAX_VALUE;
  50225. var currentSprite = null;
  50226. var cameraSpacePosition = BABYLON.Vector3.Zero();
  50227. var cameraView = camera.getViewMatrix();
  50228. for (var index = 0; index < count; index++) {
  50229. var sprite = this.sprites[index];
  50230. if (!sprite) {
  50231. continue;
  50232. }
  50233. if (predicate) {
  50234. if (!predicate(sprite)) {
  50235. continue;
  50236. }
  50237. }
  50238. else if (!sprite.isPickable) {
  50239. continue;
  50240. }
  50241. BABYLON.Vector3.TransformCoordinatesToRef(sprite.position, cameraView, cameraSpacePosition);
  50242. min.copyFromFloats(cameraSpacePosition.x - sprite.width / 2, cameraSpacePosition.y - sprite.height / 2, cameraSpacePosition.z);
  50243. max.copyFromFloats(cameraSpacePosition.x + sprite.width / 2, cameraSpacePosition.y + sprite.height / 2, cameraSpacePosition.z);
  50244. if (ray.intersectsBoxMinMax(min, max)) {
  50245. var currentDistance = BABYLON.Vector3.Distance(cameraSpacePosition, ray.origin);
  50246. if (distance > currentDistance) {
  50247. distance = currentDistance;
  50248. currentSprite = sprite;
  50249. if (fastCheck) {
  50250. break;
  50251. }
  50252. }
  50253. }
  50254. }
  50255. if (currentSprite) {
  50256. var result = new BABYLON.PickingInfo();
  50257. result.hit = true;
  50258. result.pickedSprite = currentSprite;
  50259. result.distance = distance;
  50260. return result;
  50261. }
  50262. return null;
  50263. };
  50264. SpriteManager.prototype.render = function () {
  50265. // Check
  50266. if (!this._effectBase.isReady() || !this._effectFog.isReady() || !this._spriteTexture || !this._spriteTexture.isReady())
  50267. return;
  50268. var engine = this._scene.getEngine();
  50269. var baseSize = this._spriteTexture.getBaseSize();
  50270. // Sprites
  50271. var deltaTime = engine.getDeltaTime();
  50272. var max = Math.min(this._capacity, this.sprites.length);
  50273. var rowSize = baseSize.width / this.cellWidth;
  50274. var offset = 0;
  50275. for (var index = 0; index < max; index++) {
  50276. var sprite = this.sprites[index];
  50277. if (!sprite) {
  50278. continue;
  50279. }
  50280. sprite._animate(deltaTime);
  50281. this._appendSpriteVertex(offset++, sprite, 0, 0, rowSize);
  50282. this._appendSpriteVertex(offset++, sprite, 1, 0, rowSize);
  50283. this._appendSpriteVertex(offset++, sprite, 1, 1, rowSize);
  50284. this._appendSpriteVertex(offset++, sprite, 0, 1, rowSize);
  50285. }
  50286. this._buffer.update(this._vertexData);
  50287. // Render
  50288. var effect = this._effectBase;
  50289. if (this._scene.fogEnabled && this._scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && this.fogEnabled) {
  50290. effect = this._effectFog;
  50291. }
  50292. engine.enableEffect(effect);
  50293. var viewMatrix = this._scene.getViewMatrix();
  50294. effect.setTexture("diffuseSampler", this._spriteTexture);
  50295. effect.setMatrix("view", viewMatrix);
  50296. effect.setMatrix("projection", this._scene.getProjectionMatrix());
  50297. effect.setFloat2("textureInfos", this.cellWidth / baseSize.width, this.cellHeight / baseSize.height);
  50298. // Fog
  50299. if (this._scene.fogEnabled && this._scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && this.fogEnabled) {
  50300. effect.setFloat4("vFogInfos", this._scene.fogMode, this._scene.fogStart, this._scene.fogEnd, this._scene.fogDensity);
  50301. effect.setColor3("vFogColor", this._scene.fogColor);
  50302. }
  50303. // VBOs
  50304. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  50305. // Draw order
  50306. engine.setDepthFunctionToLessOrEqual();
  50307. effect.setBool("alphaTest", true);
  50308. engine.setColorWrite(false);
  50309. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, max * 6);
  50310. engine.setColorWrite(true);
  50311. effect.setBool("alphaTest", false);
  50312. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  50313. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, max * 6);
  50314. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  50315. };
  50316. SpriteManager.prototype.dispose = function () {
  50317. if (this._buffer) {
  50318. this._buffer.dispose();
  50319. this._buffer = null;
  50320. }
  50321. if (this._indexBuffer) {
  50322. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  50323. this._indexBuffer = null;
  50324. }
  50325. if (this._spriteTexture) {
  50326. this._spriteTexture.dispose();
  50327. this._spriteTexture = null;
  50328. }
  50329. // Remove from scene
  50330. var index = this._scene.spriteManagers.indexOf(this);
  50331. this._scene.spriteManagers.splice(index, 1);
  50332. // Callback
  50333. this.onDisposeObservable.notifyObservers(this);
  50334. this.onDisposeObservable.clear();
  50335. };
  50336. return SpriteManager;
  50337. }());
  50338. BABYLON.SpriteManager = SpriteManager;
  50339. })(BABYLON || (BABYLON = {}));
  50340. //# sourceMappingURL=babylon.spriteManager.js.map
  50341. "use strict";
  50342. var BABYLON;
  50343. (function (BABYLON) {
  50344. var Sprite = /** @class */ (function () {
  50345. function Sprite(name, manager) {
  50346. this.name = name;
  50347. this.color = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  50348. this.width = 1.0;
  50349. this.height = 1.0;
  50350. this.angle = 0;
  50351. this.cellIndex = 0;
  50352. this.invertU = 0;
  50353. this.invertV = 0;
  50354. this.animations = new Array();
  50355. this.isPickable = false;
  50356. this._animationStarted = false;
  50357. this._loopAnimation = false;
  50358. this._fromIndex = 0;
  50359. this._toIndex = 0;
  50360. this._delay = 0;
  50361. this._direction = 1;
  50362. this._time = 0;
  50363. this._manager = manager;
  50364. this._manager.sprites.push(this);
  50365. this.position = BABYLON.Vector3.Zero();
  50366. }
  50367. Object.defineProperty(Sprite.prototype, "size", {
  50368. get: function () {
  50369. return this.width;
  50370. },
  50371. set: function (value) {
  50372. this.width = value;
  50373. this.height = value;
  50374. },
  50375. enumerable: true,
  50376. configurable: true
  50377. });
  50378. Sprite.prototype.playAnimation = function (from, to, loop, delay, onAnimationEnd) {
  50379. this._fromIndex = from;
  50380. this._toIndex = to;
  50381. this._loopAnimation = loop;
  50382. this._delay = delay;
  50383. this._animationStarted = true;
  50384. this._direction = from < to ? 1 : -1;
  50385. this.cellIndex = from;
  50386. this._time = 0;
  50387. this._onAnimationEnd = onAnimationEnd;
  50388. };
  50389. Sprite.prototype.stopAnimation = function () {
  50390. this._animationStarted = false;
  50391. };
  50392. Sprite.prototype._animate = function (deltaTime) {
  50393. if (!this._animationStarted)
  50394. return;
  50395. this._time += deltaTime;
  50396. if (this._time > this._delay) {
  50397. this._time = this._time % this._delay;
  50398. this.cellIndex += this._direction;
  50399. if (this.cellIndex > this._toIndex) {
  50400. if (this._loopAnimation) {
  50401. this.cellIndex = this._fromIndex;
  50402. }
  50403. else {
  50404. this.cellIndex = this._toIndex;
  50405. this._animationStarted = false;
  50406. if (this._onAnimationEnd) {
  50407. this._onAnimationEnd();
  50408. }
  50409. if (this.disposeWhenFinishedAnimating) {
  50410. this.dispose();
  50411. }
  50412. }
  50413. }
  50414. }
  50415. };
  50416. Sprite.prototype.dispose = function () {
  50417. for (var i = 0; i < this._manager.sprites.length; i++) {
  50418. if (this._manager.sprites[i] == this) {
  50419. this._manager.sprites.splice(i, 1);
  50420. }
  50421. }
  50422. };
  50423. return Sprite;
  50424. }());
  50425. BABYLON.Sprite = Sprite;
  50426. })(BABYLON || (BABYLON = {}));
  50427. //# sourceMappingURL=babylon.sprite.js.map
  50428. "use strict";
  50429. var BABYLON;
  50430. (function (BABYLON) {
  50431. var IntersectionInfo = /** @class */ (function () {
  50432. function IntersectionInfo(bu, bv, distance) {
  50433. this.bu = bu;
  50434. this.bv = bv;
  50435. this.distance = distance;
  50436. this.faceId = 0;
  50437. this.subMeshId = 0;
  50438. }
  50439. return IntersectionInfo;
  50440. }());
  50441. BABYLON.IntersectionInfo = IntersectionInfo;
  50442. var PickingInfo = /** @class */ (function () {
  50443. function PickingInfo() {
  50444. this.hit = false;
  50445. this.distance = 0;
  50446. this.pickedPoint = null;
  50447. this.pickedMesh = null;
  50448. this.bu = 0;
  50449. this.bv = 0;
  50450. this.faceId = -1;
  50451. this.subMeshId = 0;
  50452. this.pickedSprite = null;
  50453. }
  50454. // Methods
  50455. PickingInfo.prototype.getNormal = function (useWorldCoordinates, useVerticesNormals) {
  50456. if (useWorldCoordinates === void 0) { useWorldCoordinates = false; }
  50457. if (useVerticesNormals === void 0) { useVerticesNormals = true; }
  50458. if (!this.pickedMesh || !this.pickedMesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  50459. return null;
  50460. }
  50461. var indices = this.pickedMesh.getIndices();
  50462. if (!indices) {
  50463. return null;
  50464. }
  50465. var result;
  50466. if (useVerticesNormals) {
  50467. var normals = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  50468. var normal0 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3] * 3);
  50469. var normal1 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3 + 1] * 3);
  50470. var normal2 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3 + 2] * 3);
  50471. normal0 = normal0.scale(this.bu);
  50472. normal1 = normal1.scale(this.bv);
  50473. normal2 = normal2.scale(1.0 - this.bu - this.bv);
  50474. result = new BABYLON.Vector3(normal0.x + normal1.x + normal2.x, normal0.y + normal1.y + normal2.y, normal0.z + normal1.z + normal2.z);
  50475. }
  50476. else {
  50477. var positions = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  50478. var vertex1 = BABYLON.Vector3.FromArray(positions, indices[this.faceId * 3] * 3);
  50479. var vertex2 = BABYLON.Vector3.FromArray(positions, indices[this.faceId * 3 + 1] * 3);
  50480. var vertex3 = BABYLON.Vector3.FromArray(positions, indices[this.faceId * 3 + 2] * 3);
  50481. var p1p2 = vertex1.subtract(vertex2);
  50482. var p3p2 = vertex3.subtract(vertex2);
  50483. result = BABYLON.Vector3.Cross(p1p2, p3p2);
  50484. }
  50485. if (useWorldCoordinates) {
  50486. result = BABYLON.Vector3.TransformNormal(result, this.pickedMesh.getWorldMatrix());
  50487. }
  50488. return BABYLON.Vector3.Normalize(result);
  50489. };
  50490. PickingInfo.prototype.getTextureCoordinates = function () {
  50491. if (!this.pickedMesh || !this.pickedMesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  50492. return null;
  50493. }
  50494. var indices = this.pickedMesh.getIndices();
  50495. if (!indices) {
  50496. return null;
  50497. }
  50498. var uvs = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  50499. if (!uvs) {
  50500. return null;
  50501. }
  50502. var uv0 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3] * 2);
  50503. var uv1 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3 + 1] * 2);
  50504. var uv2 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3 + 2] * 2);
  50505. uv0 = uv0.scale(1.0 - this.bu - this.bv);
  50506. uv1 = uv1.scale(this.bu);
  50507. uv2 = uv2.scale(this.bv);
  50508. return new BABYLON.Vector2(uv0.x + uv1.x + uv2.x, uv0.y + uv1.y + uv2.y);
  50509. };
  50510. return PickingInfo;
  50511. }());
  50512. BABYLON.PickingInfo = PickingInfo;
  50513. })(BABYLON || (BABYLON = {}));
  50514. //# sourceMappingURL=babylon.pickingInfo.js.map
  50515. "use strict";
  50516. var BABYLON;
  50517. (function (BABYLON) {
  50518. var Ray = /** @class */ (function () {
  50519. function Ray(origin, direction, length) {
  50520. if (length === void 0) { length = Number.MAX_VALUE; }
  50521. this.origin = origin;
  50522. this.direction = direction;
  50523. this.length = length;
  50524. }
  50525. // Methods
  50526. Ray.prototype.intersectsBoxMinMax = function (minimum, maximum) {
  50527. var d = 0.0;
  50528. var maxValue = Number.MAX_VALUE;
  50529. var inv;
  50530. var min;
  50531. var max;
  50532. var temp;
  50533. if (Math.abs(this.direction.x) < 0.0000001) {
  50534. if (this.origin.x < minimum.x || this.origin.x > maximum.x) {
  50535. return false;
  50536. }
  50537. }
  50538. else {
  50539. inv = 1.0 / this.direction.x;
  50540. min = (minimum.x - this.origin.x) * inv;
  50541. max = (maximum.x - this.origin.x) * inv;
  50542. if (max === -Infinity) {
  50543. max = Infinity;
  50544. }
  50545. if (min > max) {
  50546. temp = min;
  50547. min = max;
  50548. max = temp;
  50549. }
  50550. d = Math.max(min, d);
  50551. maxValue = Math.min(max, maxValue);
  50552. if (d > maxValue) {
  50553. return false;
  50554. }
  50555. }
  50556. if (Math.abs(this.direction.y) < 0.0000001) {
  50557. if (this.origin.y < minimum.y || this.origin.y > maximum.y) {
  50558. return false;
  50559. }
  50560. }
  50561. else {
  50562. inv = 1.0 / this.direction.y;
  50563. min = (minimum.y - this.origin.y) * inv;
  50564. max = (maximum.y - this.origin.y) * inv;
  50565. if (max === -Infinity) {
  50566. max = Infinity;
  50567. }
  50568. if (min > max) {
  50569. temp = min;
  50570. min = max;
  50571. max = temp;
  50572. }
  50573. d = Math.max(min, d);
  50574. maxValue = Math.min(max, maxValue);
  50575. if (d > maxValue) {
  50576. return false;
  50577. }
  50578. }
  50579. if (Math.abs(this.direction.z) < 0.0000001) {
  50580. if (this.origin.z < minimum.z || this.origin.z > maximum.z) {
  50581. return false;
  50582. }
  50583. }
  50584. else {
  50585. inv = 1.0 / this.direction.z;
  50586. min = (minimum.z - this.origin.z) * inv;
  50587. max = (maximum.z - this.origin.z) * inv;
  50588. if (max === -Infinity) {
  50589. max = Infinity;
  50590. }
  50591. if (min > max) {
  50592. temp = min;
  50593. min = max;
  50594. max = temp;
  50595. }
  50596. d = Math.max(min, d);
  50597. maxValue = Math.min(max, maxValue);
  50598. if (d > maxValue) {
  50599. return false;
  50600. }
  50601. }
  50602. return true;
  50603. };
  50604. Ray.prototype.intersectsBox = function (box) {
  50605. return this.intersectsBoxMinMax(box.minimum, box.maximum);
  50606. };
  50607. Ray.prototype.intersectsSphere = function (sphere) {
  50608. var x = sphere.center.x - this.origin.x;
  50609. var y = sphere.center.y - this.origin.y;
  50610. var z = sphere.center.z - this.origin.z;
  50611. var pyth = (x * x) + (y * y) + (z * z);
  50612. var rr = sphere.radius * sphere.radius;
  50613. if (pyth <= rr) {
  50614. return true;
  50615. }
  50616. var dot = (x * this.direction.x) + (y * this.direction.y) + (z * this.direction.z);
  50617. if (dot < 0.0) {
  50618. return false;
  50619. }
  50620. var temp = pyth - (dot * dot);
  50621. return temp <= rr;
  50622. };
  50623. Ray.prototype.intersectsTriangle = function (vertex0, vertex1, vertex2) {
  50624. if (!this._edge1) {
  50625. this._edge1 = BABYLON.Vector3.Zero();
  50626. this._edge2 = BABYLON.Vector3.Zero();
  50627. this._pvec = BABYLON.Vector3.Zero();
  50628. this._tvec = BABYLON.Vector3.Zero();
  50629. this._qvec = BABYLON.Vector3.Zero();
  50630. }
  50631. vertex1.subtractToRef(vertex0, this._edge1);
  50632. vertex2.subtractToRef(vertex0, this._edge2);
  50633. BABYLON.Vector3.CrossToRef(this.direction, this._edge2, this._pvec);
  50634. var det = BABYLON.Vector3.Dot(this._edge1, this._pvec);
  50635. if (det === 0) {
  50636. return null;
  50637. }
  50638. var invdet = 1 / det;
  50639. this.origin.subtractToRef(vertex0, this._tvec);
  50640. var bu = BABYLON.Vector3.Dot(this._tvec, this._pvec) * invdet;
  50641. if (bu < 0 || bu > 1.0) {
  50642. return null;
  50643. }
  50644. BABYLON.Vector3.CrossToRef(this._tvec, this._edge1, this._qvec);
  50645. var bv = BABYLON.Vector3.Dot(this.direction, this._qvec) * invdet;
  50646. if (bv < 0 || bu + bv > 1.0) {
  50647. return null;
  50648. }
  50649. //check if the distance is longer than the predefined length.
  50650. var distance = BABYLON.Vector3.Dot(this._edge2, this._qvec) * invdet;
  50651. if (distance > this.length) {
  50652. return null;
  50653. }
  50654. return new BABYLON.IntersectionInfo(bu, bv, distance);
  50655. };
  50656. Ray.prototype.intersectsPlane = function (plane) {
  50657. var distance;
  50658. var result1 = BABYLON.Vector3.Dot(plane.normal, this.direction);
  50659. if (Math.abs(result1) < 9.99999997475243E-07) {
  50660. return null;
  50661. }
  50662. else {
  50663. var result2 = BABYLON.Vector3.Dot(plane.normal, this.origin);
  50664. distance = (-plane.d - result2) / result1;
  50665. if (distance < 0.0) {
  50666. if (distance < -9.99999997475243E-07) {
  50667. return null;
  50668. }
  50669. else {
  50670. return 0;
  50671. }
  50672. }
  50673. return distance;
  50674. }
  50675. };
  50676. Ray.prototype.intersectsMesh = function (mesh, fastCheck) {
  50677. var tm = BABYLON.Tmp.Matrix[0];
  50678. mesh.getWorldMatrix().invertToRef(tm);
  50679. if (this._tmpRay) {
  50680. Ray.TransformToRef(this, tm, this._tmpRay);
  50681. }
  50682. else {
  50683. this._tmpRay = Ray.Transform(this, tm);
  50684. }
  50685. return mesh.intersects(this._tmpRay, fastCheck);
  50686. };
  50687. Ray.prototype.intersectsMeshes = function (meshes, fastCheck, results) {
  50688. if (results) {
  50689. results.length = 0;
  50690. }
  50691. else {
  50692. results = [];
  50693. }
  50694. for (var i = 0; i < meshes.length; i++) {
  50695. var pickInfo = this.intersectsMesh(meshes[i], fastCheck);
  50696. if (pickInfo.hit) {
  50697. results.push(pickInfo);
  50698. }
  50699. }
  50700. results.sort(this._comparePickingInfo);
  50701. return results;
  50702. };
  50703. Ray.prototype._comparePickingInfo = function (pickingInfoA, pickingInfoB) {
  50704. if (pickingInfoA.distance < pickingInfoB.distance) {
  50705. return -1;
  50706. }
  50707. else if (pickingInfoA.distance > pickingInfoB.distance) {
  50708. return 1;
  50709. }
  50710. else {
  50711. return 0;
  50712. }
  50713. };
  50714. /**
  50715. * Intersection test between the ray and a given segment whithin a given tolerance (threshold)
  50716. * @param sega the first point of the segment to test the intersection against
  50717. * @param segb the second point of the segment to test the intersection against
  50718. * @param threshold the tolerance margin, if the ray doesn't intersect the segment but is close to the given threshold, the intersection is successful
  50719. * @return the distance from the ray origin to the intersection point if there's intersection, or -1 if there's no intersection
  50720. */
  50721. Ray.prototype.intersectionSegment = function (sega, segb, threshold) {
  50722. var rsegb = this.origin.add(this.direction.multiplyByFloats(Ray.rayl, Ray.rayl, Ray.rayl));
  50723. var u = segb.subtract(sega);
  50724. var v = rsegb.subtract(this.origin);
  50725. var w = sega.subtract(this.origin);
  50726. var a = BABYLON.Vector3.Dot(u, u); // always >= 0
  50727. var b = BABYLON.Vector3.Dot(u, v);
  50728. var c = BABYLON.Vector3.Dot(v, v); // always >= 0
  50729. var d = BABYLON.Vector3.Dot(u, w);
  50730. var e = BABYLON.Vector3.Dot(v, w);
  50731. var D = a * c - b * b; // always >= 0
  50732. var sc, sN, sD = D; // sc = sN / sD, default sD = D >= 0
  50733. var tc, tN, tD = D; // tc = tN / tD, default tD = D >= 0
  50734. // compute the line parameters of the two closest points
  50735. if (D < Ray.smallnum) {
  50736. sN = 0.0; // force using point P0 on segment S1
  50737. sD = 1.0; // to prevent possible division by 0.0 later
  50738. tN = e;
  50739. tD = c;
  50740. }
  50741. else {
  50742. sN = (b * e - c * d);
  50743. tN = (a * e - b * d);
  50744. if (sN < 0.0) {
  50745. sN = 0.0;
  50746. tN = e;
  50747. tD = c;
  50748. }
  50749. else if (sN > sD) {
  50750. sN = sD;
  50751. tN = e + b;
  50752. tD = c;
  50753. }
  50754. }
  50755. if (tN < 0.0) {
  50756. tN = 0.0;
  50757. // recompute sc for this edge
  50758. if (-d < 0.0) {
  50759. sN = 0.0;
  50760. }
  50761. else if (-d > a)
  50762. sN = sD;
  50763. else {
  50764. sN = -d;
  50765. sD = a;
  50766. }
  50767. }
  50768. else if (tN > tD) {
  50769. tN = tD;
  50770. // recompute sc for this edge
  50771. if ((-d + b) < 0.0) {
  50772. sN = 0;
  50773. }
  50774. else if ((-d + b) > a) {
  50775. sN = sD;
  50776. }
  50777. else {
  50778. sN = (-d + b);
  50779. sD = a;
  50780. }
  50781. }
  50782. // finally do the division to get sc and tc
  50783. sc = (Math.abs(sN) < Ray.smallnum ? 0.0 : sN / sD);
  50784. tc = (Math.abs(tN) < Ray.smallnum ? 0.0 : tN / tD);
  50785. // get the difference of the two closest points
  50786. var qtc = v.multiplyByFloats(tc, tc, tc);
  50787. var dP = w.add(u.multiplyByFloats(sc, sc, sc)).subtract(qtc); // = S1(sc) - S2(tc)
  50788. var isIntersected = (tc > 0) && (tc <= this.length) && (dP.lengthSquared() < (threshold * threshold)); // return intersection result
  50789. if (isIntersected) {
  50790. return qtc.length();
  50791. }
  50792. return -1;
  50793. };
  50794. Ray.prototype.update = function (x, y, viewportWidth, viewportHeight, world, view, projection) {
  50795. BABYLON.Vector3.UnprojectFloatsToRef(x, y, 0, viewportWidth, viewportHeight, world, view, projection, this.origin);
  50796. BABYLON.Vector3.UnprojectFloatsToRef(x, y, 1, viewportWidth, viewportHeight, world, view, projection, BABYLON.Tmp.Vector3[0]);
  50797. BABYLON.Tmp.Vector3[0].subtractToRef(this.origin, this.direction);
  50798. this.direction.normalize();
  50799. return this;
  50800. };
  50801. // Statics
  50802. Ray.Zero = function () {
  50803. return new Ray(BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero());
  50804. };
  50805. Ray.CreateNew = function (x, y, viewportWidth, viewportHeight, world, view, projection) {
  50806. var result = Ray.Zero();
  50807. return result.update(x, y, viewportWidth, viewportHeight, world, view, projection);
  50808. };
  50809. /**
  50810. * 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
  50811. * transformed to the given world matrix.
  50812. * @param origin The origin point
  50813. * @param end The end point
  50814. * @param world a matrix to transform the ray to. Default is the identity matrix.
  50815. */
  50816. Ray.CreateNewFromTo = function (origin, end, world) {
  50817. if (world === void 0) { world = BABYLON.Matrix.Identity(); }
  50818. var direction = end.subtract(origin);
  50819. var length = Math.sqrt((direction.x * direction.x) + (direction.y * direction.y) + (direction.z * direction.z));
  50820. direction.normalize();
  50821. return Ray.Transform(new Ray(origin, direction, length), world);
  50822. };
  50823. Ray.Transform = function (ray, matrix) {
  50824. var result = new Ray(new BABYLON.Vector3(0, 0, 0), new BABYLON.Vector3(0, 0, 0));
  50825. Ray.TransformToRef(ray, matrix, result);
  50826. return result;
  50827. };
  50828. Ray.TransformToRef = function (ray, matrix, result) {
  50829. BABYLON.Vector3.TransformCoordinatesToRef(ray.origin, matrix, result.origin);
  50830. BABYLON.Vector3.TransformNormalToRef(ray.direction, matrix, result.direction);
  50831. result.length = ray.length;
  50832. var dir = result.direction;
  50833. var len = dir.length();
  50834. if (!(len === 0 || len === 1)) {
  50835. var num = 1.0 / len;
  50836. dir.x *= num;
  50837. dir.y *= num;
  50838. dir.z *= num;
  50839. result.length *= len;
  50840. }
  50841. };
  50842. Ray.smallnum = 0.00000001;
  50843. Ray.rayl = 10e8;
  50844. return Ray;
  50845. }());
  50846. BABYLON.Ray = Ray;
  50847. })(BABYLON || (BABYLON = {}));
  50848. //# sourceMappingURL=babylon.ray.js.map
  50849. "use strict";
  50850. var BABYLON;
  50851. (function (BABYLON) {
  50852. var intersectBoxAASphere = function (boxMin, boxMax, sphereCenter, sphereRadius) {
  50853. if (boxMin.x > sphereCenter.x + sphereRadius)
  50854. return false;
  50855. if (sphereCenter.x - sphereRadius > boxMax.x)
  50856. return false;
  50857. if (boxMin.y > sphereCenter.y + sphereRadius)
  50858. return false;
  50859. if (sphereCenter.y - sphereRadius > boxMax.y)
  50860. return false;
  50861. if (boxMin.z > sphereCenter.z + sphereRadius)
  50862. return false;
  50863. if (sphereCenter.z - sphereRadius > boxMax.z)
  50864. return false;
  50865. return true;
  50866. };
  50867. var getLowestRoot = (function () {
  50868. var result = { root: 0, found: false };
  50869. return function (a, b, c, maxR) {
  50870. result.root = 0;
  50871. result.found = false;
  50872. var determinant = b * b - 4.0 * a * c;
  50873. if (determinant < 0)
  50874. return result;
  50875. var sqrtD = Math.sqrt(determinant);
  50876. var r1 = (-b - sqrtD) / (2.0 * a);
  50877. var r2 = (-b + sqrtD) / (2.0 * a);
  50878. if (r1 > r2) {
  50879. var temp = r2;
  50880. r2 = r1;
  50881. r1 = temp;
  50882. }
  50883. if (r1 > 0 && r1 < maxR) {
  50884. result.root = r1;
  50885. result.found = true;
  50886. return result;
  50887. }
  50888. if (r2 > 0 && r2 < maxR) {
  50889. result.root = r2;
  50890. result.found = true;
  50891. return result;
  50892. }
  50893. return result;
  50894. };
  50895. })();
  50896. var Collider = /** @class */ (function () {
  50897. function Collider() {
  50898. this._collisionPoint = BABYLON.Vector3.Zero();
  50899. this._planeIntersectionPoint = BABYLON.Vector3.Zero();
  50900. this._tempVector = BABYLON.Vector3.Zero();
  50901. this._tempVector2 = BABYLON.Vector3.Zero();
  50902. this._tempVector3 = BABYLON.Vector3.Zero();
  50903. this._tempVector4 = BABYLON.Vector3.Zero();
  50904. this._edge = BABYLON.Vector3.Zero();
  50905. this._baseToVertex = BABYLON.Vector3.Zero();
  50906. this._destinationPoint = BABYLON.Vector3.Zero();
  50907. this._slidePlaneNormal = BABYLON.Vector3.Zero();
  50908. this._displacementVector = BABYLON.Vector3.Zero();
  50909. this._radius = BABYLON.Vector3.One();
  50910. this._retry = 0;
  50911. this._basePointWorld = BABYLON.Vector3.Zero();
  50912. this._velocityWorld = BABYLON.Vector3.Zero();
  50913. this._normalizedVelocity = BABYLON.Vector3.Zero();
  50914. this._collisionMask = -1;
  50915. }
  50916. Object.defineProperty(Collider.prototype, "collisionMask", {
  50917. get: function () {
  50918. return this._collisionMask;
  50919. },
  50920. set: function (mask) {
  50921. this._collisionMask = !isNaN(mask) ? mask : -1;
  50922. },
  50923. enumerable: true,
  50924. configurable: true
  50925. });
  50926. Object.defineProperty(Collider.prototype, "slidePlaneNormal", {
  50927. /**
  50928. * Gets the plane normal used to compute the sliding response (in local space)
  50929. */
  50930. get: function () {
  50931. return this._slidePlaneNormal;
  50932. },
  50933. enumerable: true,
  50934. configurable: true
  50935. });
  50936. // Methods
  50937. Collider.prototype._initialize = function (source, dir, e) {
  50938. this._velocity = dir;
  50939. BABYLON.Vector3.NormalizeToRef(dir, this._normalizedVelocity);
  50940. this._basePoint = source;
  50941. source.multiplyToRef(this._radius, this._basePointWorld);
  50942. dir.multiplyToRef(this._radius, this._velocityWorld);
  50943. this._velocityWorldLength = this._velocityWorld.length();
  50944. this._epsilon = e;
  50945. this.collisionFound = false;
  50946. };
  50947. Collider.prototype._checkPointInTriangle = function (point, pa, pb, pc, n) {
  50948. pa.subtractToRef(point, this._tempVector);
  50949. pb.subtractToRef(point, this._tempVector2);
  50950. BABYLON.Vector3.CrossToRef(this._tempVector, this._tempVector2, this._tempVector4);
  50951. var d = BABYLON.Vector3.Dot(this._tempVector4, n);
  50952. if (d < 0)
  50953. return false;
  50954. pc.subtractToRef(point, this._tempVector3);
  50955. BABYLON.Vector3.CrossToRef(this._tempVector2, this._tempVector3, this._tempVector4);
  50956. d = BABYLON.Vector3.Dot(this._tempVector4, n);
  50957. if (d < 0)
  50958. return false;
  50959. BABYLON.Vector3.CrossToRef(this._tempVector3, this._tempVector, this._tempVector4);
  50960. d = BABYLON.Vector3.Dot(this._tempVector4, n);
  50961. return d >= 0;
  50962. };
  50963. Collider.prototype._canDoCollision = function (sphereCenter, sphereRadius, vecMin, vecMax) {
  50964. var distance = BABYLON.Vector3.Distance(this._basePointWorld, sphereCenter);
  50965. var max = Math.max(this._radius.x, this._radius.y, this._radius.z);
  50966. if (distance > this._velocityWorldLength + max + sphereRadius) {
  50967. return false;
  50968. }
  50969. if (!intersectBoxAASphere(vecMin, vecMax, this._basePointWorld, this._velocityWorldLength + max))
  50970. return false;
  50971. return true;
  50972. };
  50973. Collider.prototype._testTriangle = function (faceIndex, trianglePlaneArray, p1, p2, p3, hasMaterial) {
  50974. var t0;
  50975. var embeddedInPlane = false;
  50976. //defensive programming, actually not needed.
  50977. if (!trianglePlaneArray) {
  50978. trianglePlaneArray = [];
  50979. }
  50980. if (!trianglePlaneArray[faceIndex]) {
  50981. trianglePlaneArray[faceIndex] = new BABYLON.Plane(0, 0, 0, 0);
  50982. trianglePlaneArray[faceIndex].copyFromPoints(p1, p2, p3);
  50983. }
  50984. var trianglePlane = trianglePlaneArray[faceIndex];
  50985. if ((!hasMaterial) && !trianglePlane.isFrontFacingTo(this._normalizedVelocity, 0))
  50986. return;
  50987. var signedDistToTrianglePlane = trianglePlane.signedDistanceTo(this._basePoint);
  50988. var normalDotVelocity = BABYLON.Vector3.Dot(trianglePlane.normal, this._velocity);
  50989. if (normalDotVelocity == 0) {
  50990. if (Math.abs(signedDistToTrianglePlane) >= 1.0)
  50991. return;
  50992. embeddedInPlane = true;
  50993. t0 = 0;
  50994. }
  50995. else {
  50996. t0 = (-1.0 - signedDistToTrianglePlane) / normalDotVelocity;
  50997. var t1 = (1.0 - signedDistToTrianglePlane) / normalDotVelocity;
  50998. if (t0 > t1) {
  50999. var temp = t1;
  51000. t1 = t0;
  51001. t0 = temp;
  51002. }
  51003. if (t0 > 1.0 || t1 < 0.0)
  51004. return;
  51005. if (t0 < 0)
  51006. t0 = 0;
  51007. if (t0 > 1.0)
  51008. t0 = 1.0;
  51009. }
  51010. this._collisionPoint.copyFromFloats(0, 0, 0);
  51011. var found = false;
  51012. var t = 1.0;
  51013. if (!embeddedInPlane) {
  51014. this._basePoint.subtractToRef(trianglePlane.normal, this._planeIntersectionPoint);
  51015. this._velocity.scaleToRef(t0, this._tempVector);
  51016. this._planeIntersectionPoint.addInPlace(this._tempVector);
  51017. if (this._checkPointInTriangle(this._planeIntersectionPoint, p1, p2, p3, trianglePlane.normal)) {
  51018. found = true;
  51019. t = t0;
  51020. this._collisionPoint.copyFrom(this._planeIntersectionPoint);
  51021. }
  51022. }
  51023. if (!found) {
  51024. var velocitySquaredLength = this._velocity.lengthSquared();
  51025. var a = velocitySquaredLength;
  51026. this._basePoint.subtractToRef(p1, this._tempVector);
  51027. var b = 2.0 * (BABYLON.Vector3.Dot(this._velocity, this._tempVector));
  51028. var c = this._tempVector.lengthSquared() - 1.0;
  51029. var lowestRoot = getLowestRoot(a, b, c, t);
  51030. if (lowestRoot.found) {
  51031. t = lowestRoot.root;
  51032. found = true;
  51033. this._collisionPoint.copyFrom(p1);
  51034. }
  51035. this._basePoint.subtractToRef(p2, this._tempVector);
  51036. b = 2.0 * (BABYLON.Vector3.Dot(this._velocity, this._tempVector));
  51037. c = this._tempVector.lengthSquared() - 1.0;
  51038. lowestRoot = getLowestRoot(a, b, c, t);
  51039. if (lowestRoot.found) {
  51040. t = lowestRoot.root;
  51041. found = true;
  51042. this._collisionPoint.copyFrom(p2);
  51043. }
  51044. this._basePoint.subtractToRef(p3, this._tempVector);
  51045. b = 2.0 * (BABYLON.Vector3.Dot(this._velocity, this._tempVector));
  51046. c = this._tempVector.lengthSquared() - 1.0;
  51047. lowestRoot = getLowestRoot(a, b, c, t);
  51048. if (lowestRoot.found) {
  51049. t = lowestRoot.root;
  51050. found = true;
  51051. this._collisionPoint.copyFrom(p3);
  51052. }
  51053. p2.subtractToRef(p1, this._edge);
  51054. p1.subtractToRef(this._basePoint, this._baseToVertex);
  51055. var edgeSquaredLength = this._edge.lengthSquared();
  51056. var edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this._velocity);
  51057. var edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  51058. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  51059. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this._velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  51060. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  51061. lowestRoot = getLowestRoot(a, b, c, t);
  51062. if (lowestRoot.found) {
  51063. var f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  51064. if (f >= 0.0 && f <= 1.0) {
  51065. t = lowestRoot.root;
  51066. found = true;
  51067. this._edge.scaleInPlace(f);
  51068. p1.addToRef(this._edge, this._collisionPoint);
  51069. }
  51070. }
  51071. p3.subtractToRef(p2, this._edge);
  51072. p2.subtractToRef(this._basePoint, this._baseToVertex);
  51073. edgeSquaredLength = this._edge.lengthSquared();
  51074. edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this._velocity);
  51075. edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  51076. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  51077. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this._velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  51078. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  51079. lowestRoot = getLowestRoot(a, b, c, t);
  51080. if (lowestRoot.found) {
  51081. f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  51082. if (f >= 0.0 && f <= 1.0) {
  51083. t = lowestRoot.root;
  51084. found = true;
  51085. this._edge.scaleInPlace(f);
  51086. p2.addToRef(this._edge, this._collisionPoint);
  51087. }
  51088. }
  51089. p1.subtractToRef(p3, this._edge);
  51090. p3.subtractToRef(this._basePoint, this._baseToVertex);
  51091. edgeSquaredLength = this._edge.lengthSquared();
  51092. edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this._velocity);
  51093. edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  51094. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  51095. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this._velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  51096. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  51097. lowestRoot = getLowestRoot(a, b, c, t);
  51098. if (lowestRoot.found) {
  51099. f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  51100. if (f >= 0.0 && f <= 1.0) {
  51101. t = lowestRoot.root;
  51102. found = true;
  51103. this._edge.scaleInPlace(f);
  51104. p3.addToRef(this._edge, this._collisionPoint);
  51105. }
  51106. }
  51107. }
  51108. if (found) {
  51109. var distToCollision = t * this._velocity.length();
  51110. if (!this.collisionFound || distToCollision < this._nearestDistance) {
  51111. if (!this.intersectionPoint) {
  51112. this.intersectionPoint = this._collisionPoint.clone();
  51113. }
  51114. else {
  51115. this.intersectionPoint.copyFrom(this._collisionPoint);
  51116. }
  51117. this._nearestDistance = distToCollision;
  51118. this.collisionFound = true;
  51119. }
  51120. }
  51121. };
  51122. Collider.prototype._collide = function (trianglePlaneArray, pts, indices, indexStart, indexEnd, decal, hasMaterial) {
  51123. for (var i = indexStart; i < indexEnd; i += 3) {
  51124. var p1 = pts[indices[i] - decal];
  51125. var p2 = pts[indices[i + 1] - decal];
  51126. var p3 = pts[indices[i + 2] - decal];
  51127. this._testTriangle(i, trianglePlaneArray, p3, p2, p1, hasMaterial);
  51128. }
  51129. };
  51130. Collider.prototype._getResponse = function (pos, vel) {
  51131. pos.addToRef(vel, this._destinationPoint);
  51132. vel.scaleInPlace((this._nearestDistance / vel.length()));
  51133. this._basePoint.addToRef(vel, pos);
  51134. pos.subtractToRef(this.intersectionPoint, this._slidePlaneNormal);
  51135. this._slidePlaneNormal.normalize();
  51136. this._slidePlaneNormal.scaleToRef(this._epsilon, this._displacementVector);
  51137. pos.addInPlace(this._displacementVector);
  51138. this.intersectionPoint.addInPlace(this._displacementVector);
  51139. this._slidePlaneNormal.scaleInPlace(BABYLON.Plane.SignedDistanceToPlaneFromPositionAndNormal(this.intersectionPoint, this._slidePlaneNormal, this._destinationPoint));
  51140. this._destinationPoint.subtractInPlace(this._slidePlaneNormal);
  51141. this._destinationPoint.subtractToRef(this.intersectionPoint, vel);
  51142. };
  51143. return Collider;
  51144. }());
  51145. BABYLON.Collider = Collider;
  51146. })(BABYLON || (BABYLON = {}));
  51147. //# sourceMappingURL=babylon.collider.js.map
  51148. "use strict";
  51149. var BABYLON;
  51150. (function (BABYLON) {
  51151. //WebWorker code will be inserted to this variable.
  51152. BABYLON.CollisionWorker = "";
  51153. var WorkerTaskType;
  51154. (function (WorkerTaskType) {
  51155. WorkerTaskType[WorkerTaskType["INIT"] = 0] = "INIT";
  51156. WorkerTaskType[WorkerTaskType["UPDATE"] = 1] = "UPDATE";
  51157. WorkerTaskType[WorkerTaskType["COLLIDE"] = 2] = "COLLIDE";
  51158. })(WorkerTaskType = BABYLON.WorkerTaskType || (BABYLON.WorkerTaskType = {}));
  51159. var WorkerReplyType;
  51160. (function (WorkerReplyType) {
  51161. WorkerReplyType[WorkerReplyType["SUCCESS"] = 0] = "SUCCESS";
  51162. WorkerReplyType[WorkerReplyType["UNKNOWN_ERROR"] = 1] = "UNKNOWN_ERROR";
  51163. })(WorkerReplyType = BABYLON.WorkerReplyType || (BABYLON.WorkerReplyType = {}));
  51164. var CollisionCoordinatorWorker = /** @class */ (function () {
  51165. function CollisionCoordinatorWorker() {
  51166. var _this = this;
  51167. this._scaledPosition = BABYLON.Vector3.Zero();
  51168. this._scaledVelocity = BABYLON.Vector3.Zero();
  51169. this.onMeshUpdated = function (transformNode) {
  51170. _this._addUpdateMeshesList[transformNode.uniqueId] = CollisionCoordinatorWorker.SerializeMesh(transformNode);
  51171. };
  51172. this.onGeometryUpdated = function (geometry) {
  51173. _this._addUpdateGeometriesList[geometry.id] = CollisionCoordinatorWorker.SerializeGeometry(geometry);
  51174. };
  51175. this._afterRender = function () {
  51176. if (!_this._init)
  51177. return;
  51178. if (_this._toRemoveGeometryArray.length == 0 && _this._toRemoveMeshesArray.length == 0 && Object.keys(_this._addUpdateGeometriesList).length == 0 && Object.keys(_this._addUpdateMeshesList).length == 0) {
  51179. return;
  51180. }
  51181. //5 concurrent updates were sent to the web worker and were not yet processed. Abort next update.
  51182. //TODO make sure update runs as fast as possible to be able to update 60 FPS.
  51183. if (_this._runningUpdated > 4) {
  51184. return;
  51185. }
  51186. ++_this._runningUpdated;
  51187. var payload = {
  51188. updatedMeshes: _this._addUpdateMeshesList,
  51189. updatedGeometries: _this._addUpdateGeometriesList,
  51190. removedGeometries: _this._toRemoveGeometryArray,
  51191. removedMeshes: _this._toRemoveMeshesArray
  51192. };
  51193. var message = {
  51194. payload: payload,
  51195. taskType: WorkerTaskType.UPDATE
  51196. };
  51197. var serializable = [];
  51198. for (var id in payload.updatedGeometries) {
  51199. if (payload.updatedGeometries.hasOwnProperty(id)) {
  51200. //prepare transferables
  51201. serializable.push(message.payload.updatedGeometries[id].indices.buffer);
  51202. serializable.push(message.payload.updatedGeometries[id].normals.buffer);
  51203. serializable.push(message.payload.updatedGeometries[id].positions.buffer);
  51204. }
  51205. }
  51206. _this._worker.postMessage(message, serializable);
  51207. _this._addUpdateMeshesList = {};
  51208. _this._addUpdateGeometriesList = {};
  51209. _this._toRemoveGeometryArray = [];
  51210. _this._toRemoveMeshesArray = [];
  51211. };
  51212. this._onMessageFromWorker = function (e) {
  51213. var returnData = e.data;
  51214. if (returnData.error != WorkerReplyType.SUCCESS) {
  51215. //TODO what errors can be returned from the worker?
  51216. BABYLON.Tools.Warn("error returned from worker!");
  51217. return;
  51218. }
  51219. switch (returnData.taskType) {
  51220. case WorkerTaskType.INIT:
  51221. _this._init = true;
  51222. //Update the worked with ALL of the scene's current state
  51223. _this._scene.meshes.forEach(function (mesh) {
  51224. _this.onMeshAdded(mesh);
  51225. });
  51226. _this._scene.getGeometries().forEach(function (geometry) {
  51227. _this.onGeometryAdded(geometry);
  51228. });
  51229. break;
  51230. case WorkerTaskType.UPDATE:
  51231. _this._runningUpdated--;
  51232. break;
  51233. case WorkerTaskType.COLLIDE:
  51234. var returnPayload = returnData.payload;
  51235. if (!_this._collisionsCallbackArray[returnPayload.collisionId])
  51236. return;
  51237. var callback = _this._collisionsCallbackArray[returnPayload.collisionId];
  51238. if (callback) {
  51239. var mesh = _this._scene.getMeshByUniqueID(returnPayload.collidedMeshUniqueId);
  51240. if (mesh) {
  51241. callback(returnPayload.collisionId, BABYLON.Vector3.FromArray(returnPayload.newPosition), mesh);
  51242. }
  51243. }
  51244. //cleanup
  51245. _this._collisionsCallbackArray[returnPayload.collisionId] = null;
  51246. break;
  51247. }
  51248. };
  51249. this._collisionsCallbackArray = [];
  51250. this._init = false;
  51251. this._runningUpdated = 0;
  51252. this._addUpdateMeshesList = {};
  51253. this._addUpdateGeometriesList = {};
  51254. this._toRemoveGeometryArray = [];
  51255. this._toRemoveMeshesArray = [];
  51256. }
  51257. CollisionCoordinatorWorker.prototype.getNewPosition = function (position, displacement, collider, maximumRetry, excludedMesh, onNewPosition, collisionIndex) {
  51258. if (!this._init)
  51259. return;
  51260. if (this._collisionsCallbackArray[collisionIndex] || this._collisionsCallbackArray[collisionIndex + 100000])
  51261. return;
  51262. position.divideToRef(collider._radius, this._scaledPosition);
  51263. displacement.divideToRef(collider._radius, this._scaledVelocity);
  51264. this._collisionsCallbackArray[collisionIndex] = onNewPosition;
  51265. var payload = {
  51266. collider: {
  51267. position: this._scaledPosition.asArray(),
  51268. velocity: this._scaledVelocity.asArray(),
  51269. radius: collider._radius.asArray()
  51270. },
  51271. collisionId: collisionIndex,
  51272. excludedMeshUniqueId: excludedMesh ? excludedMesh.uniqueId : null,
  51273. maximumRetry: maximumRetry
  51274. };
  51275. var message = {
  51276. payload: payload,
  51277. taskType: WorkerTaskType.COLLIDE
  51278. };
  51279. this._worker.postMessage(message);
  51280. };
  51281. CollisionCoordinatorWorker.prototype.init = function (scene) {
  51282. this._scene = scene;
  51283. this._scene.registerAfterRender(this._afterRender);
  51284. var workerUrl = BABYLON.WorkerIncluded ? BABYLON.Engine.CodeRepository + "Collisions/babylon.collisionWorker.js" : URL.createObjectURL(new Blob([BABYLON.CollisionWorker], { type: 'application/javascript' }));
  51285. this._worker = new Worker(workerUrl);
  51286. this._worker.onmessage = this._onMessageFromWorker;
  51287. var message = {
  51288. payload: {},
  51289. taskType: WorkerTaskType.INIT
  51290. };
  51291. this._worker.postMessage(message);
  51292. };
  51293. CollisionCoordinatorWorker.prototype.destroy = function () {
  51294. this._scene.unregisterAfterRender(this._afterRender);
  51295. this._worker.terminate();
  51296. };
  51297. CollisionCoordinatorWorker.prototype.onMeshAdded = function (mesh) {
  51298. mesh.registerAfterWorldMatrixUpdate(this.onMeshUpdated);
  51299. this.onMeshUpdated(mesh);
  51300. };
  51301. CollisionCoordinatorWorker.prototype.onMeshRemoved = function (mesh) {
  51302. this._toRemoveMeshesArray.push(mesh.uniqueId);
  51303. };
  51304. CollisionCoordinatorWorker.prototype.onGeometryAdded = function (geometry) {
  51305. //TODO this will break if the user uses his own function. This should be an array of callbacks!
  51306. geometry.onGeometryUpdated = this.onGeometryUpdated;
  51307. this.onGeometryUpdated(geometry);
  51308. };
  51309. CollisionCoordinatorWorker.prototype.onGeometryDeleted = function (geometry) {
  51310. this._toRemoveGeometryArray.push(geometry.id);
  51311. };
  51312. CollisionCoordinatorWorker.SerializeMesh = function (mesh) {
  51313. var submeshes = [];
  51314. if (mesh.subMeshes) {
  51315. submeshes = mesh.subMeshes.map(function (sm, idx) {
  51316. var boundingInfo = sm.getBoundingInfo();
  51317. return {
  51318. position: idx,
  51319. verticesStart: sm.verticesStart,
  51320. verticesCount: sm.verticesCount,
  51321. indexStart: sm.indexStart,
  51322. indexCount: sm.indexCount,
  51323. hasMaterial: !!sm.getMaterial(),
  51324. sphereCenter: boundingInfo.boundingSphere.centerWorld.asArray(),
  51325. sphereRadius: boundingInfo.boundingSphere.radiusWorld,
  51326. boxMinimum: boundingInfo.boundingBox.minimumWorld.asArray(),
  51327. boxMaximum: boundingInfo.boundingBox.maximumWorld.asArray()
  51328. };
  51329. });
  51330. }
  51331. var geometryId = null;
  51332. if (mesh instanceof BABYLON.Mesh) {
  51333. var geometry = mesh.geometry;
  51334. geometryId = geometry ? geometry.id : null;
  51335. }
  51336. else if (mesh instanceof BABYLON.InstancedMesh) {
  51337. var geometry = mesh.sourceMesh && mesh.sourceMesh.geometry;
  51338. geometryId = geometry ? geometry.id : null;
  51339. }
  51340. var boundingInfo = mesh.getBoundingInfo();
  51341. return {
  51342. uniqueId: mesh.uniqueId,
  51343. id: mesh.id,
  51344. name: mesh.name,
  51345. geometryId: geometryId,
  51346. sphereCenter: boundingInfo.boundingSphere.centerWorld.asArray(),
  51347. sphereRadius: boundingInfo.boundingSphere.radiusWorld,
  51348. boxMinimum: boundingInfo.boundingBox.minimumWorld.asArray(),
  51349. boxMaximum: boundingInfo.boundingBox.maximumWorld.asArray(),
  51350. worldMatrixFromCache: mesh.worldMatrixFromCache.asArray(),
  51351. subMeshes: submeshes,
  51352. checkCollisions: mesh.checkCollisions
  51353. };
  51354. };
  51355. CollisionCoordinatorWorker.SerializeGeometry = function (geometry) {
  51356. return {
  51357. id: geometry.id,
  51358. positions: new Float32Array(geometry.getVerticesData(BABYLON.VertexBuffer.PositionKind) || []),
  51359. normals: new Float32Array(geometry.getVerticesData(BABYLON.VertexBuffer.NormalKind) || []),
  51360. indices: new Uint32Array(geometry.getIndices() || []),
  51361. };
  51362. };
  51363. return CollisionCoordinatorWorker;
  51364. }());
  51365. BABYLON.CollisionCoordinatorWorker = CollisionCoordinatorWorker;
  51366. var CollisionCoordinatorLegacy = /** @class */ (function () {
  51367. function CollisionCoordinatorLegacy() {
  51368. this._scaledPosition = BABYLON.Vector3.Zero();
  51369. this._scaledVelocity = BABYLON.Vector3.Zero();
  51370. this._finalPosition = BABYLON.Vector3.Zero();
  51371. }
  51372. CollisionCoordinatorLegacy.prototype.getNewPosition = function (position, displacement, collider, maximumRetry, excludedMesh, onNewPosition, collisionIndex) {
  51373. position.divideToRef(collider._radius, this._scaledPosition);
  51374. displacement.divideToRef(collider._radius, this._scaledVelocity);
  51375. collider.collidedMesh = null;
  51376. collider._retry = 0;
  51377. collider._initialVelocity = this._scaledVelocity;
  51378. collider._initialPosition = this._scaledPosition;
  51379. this._collideWithWorld(this._scaledPosition, this._scaledVelocity, collider, maximumRetry, this._finalPosition, excludedMesh);
  51380. this._finalPosition.multiplyInPlace(collider._radius);
  51381. //run the callback
  51382. onNewPosition(collisionIndex, this._finalPosition, collider.collidedMesh);
  51383. };
  51384. CollisionCoordinatorLegacy.prototype.init = function (scene) {
  51385. this._scene = scene;
  51386. };
  51387. CollisionCoordinatorLegacy.prototype.destroy = function () {
  51388. //Legacy need no destruction method.
  51389. };
  51390. //No update in legacy mode
  51391. CollisionCoordinatorLegacy.prototype.onMeshAdded = function (mesh) { };
  51392. CollisionCoordinatorLegacy.prototype.onMeshUpdated = function (mesh) { };
  51393. CollisionCoordinatorLegacy.prototype.onMeshRemoved = function (mesh) { };
  51394. CollisionCoordinatorLegacy.prototype.onGeometryAdded = function (geometry) { };
  51395. CollisionCoordinatorLegacy.prototype.onGeometryUpdated = function (geometry) { };
  51396. CollisionCoordinatorLegacy.prototype.onGeometryDeleted = function (geometry) { };
  51397. CollisionCoordinatorLegacy.prototype._collideWithWorld = function (position, velocity, collider, maximumRetry, finalPosition, excludedMesh) {
  51398. if (excludedMesh === void 0) { excludedMesh = null; }
  51399. var closeDistance = BABYLON.Engine.CollisionsEpsilon * 10.0;
  51400. if (collider._retry >= maximumRetry) {
  51401. finalPosition.copyFrom(position);
  51402. return;
  51403. }
  51404. // Check if this is a mesh else camera or -1
  51405. var collisionMask = (excludedMesh ? excludedMesh.collisionMask : collider.collisionMask);
  51406. collider._initialize(position, velocity, closeDistance);
  51407. // Check all meshes
  51408. for (var index = 0; index < this._scene.meshes.length; index++) {
  51409. var mesh = this._scene.meshes[index];
  51410. if (mesh.isEnabled() && mesh.checkCollisions && mesh.subMeshes && mesh !== excludedMesh && ((collisionMask & mesh.collisionGroup) !== 0)) {
  51411. mesh._checkCollision(collider);
  51412. }
  51413. }
  51414. if (!collider.collisionFound) {
  51415. position.addToRef(velocity, finalPosition);
  51416. return;
  51417. }
  51418. if (velocity.x !== 0 || velocity.y !== 0 || velocity.z !== 0) {
  51419. collider._getResponse(position, velocity);
  51420. }
  51421. if (velocity.length() <= closeDistance) {
  51422. finalPosition.copyFrom(position);
  51423. return;
  51424. }
  51425. collider._retry++;
  51426. this._collideWithWorld(position, velocity, collider, maximumRetry, finalPosition, excludedMesh);
  51427. };
  51428. return CollisionCoordinatorLegacy;
  51429. }());
  51430. BABYLON.CollisionCoordinatorLegacy = CollisionCoordinatorLegacy;
  51431. })(BABYLON || (BABYLON = {}));
  51432. //# sourceMappingURL=babylon.collisionCoordinator.js.map
  51433. "use strict";
  51434. var BABYLON;
  51435. (function (BABYLON) {
  51436. /**
  51437. * A particle represents one of the element emitted by a particle system.
  51438. * This is mainly define by its coordinates, direction, velocity and age.
  51439. */
  51440. var Particle = /** @class */ (function () {
  51441. /**
  51442. * Creates a new instance Particle
  51443. * @param particleSystem the particle system the particle belongs to
  51444. */
  51445. function Particle(
  51446. /**
  51447. * particleSystem the particle system the particle belongs to.
  51448. */
  51449. particleSystem) {
  51450. this.particleSystem = particleSystem;
  51451. /**
  51452. * The world position of the particle in the scene.
  51453. */
  51454. this.position = BABYLON.Vector3.Zero();
  51455. /**
  51456. * The world direction of the particle in the scene.
  51457. */
  51458. this.direction = BABYLON.Vector3.Zero();
  51459. /**
  51460. * The color of the particle.
  51461. */
  51462. this.color = new BABYLON.Color4(0, 0, 0, 0);
  51463. /**
  51464. * The color change of the particle per step.
  51465. */
  51466. this.colorStep = new BABYLON.Color4(0, 0, 0, 0);
  51467. /**
  51468. * Defines how long will the life of the particle be.
  51469. */
  51470. this.lifeTime = 1.0;
  51471. /**
  51472. * The current age of the particle.
  51473. */
  51474. this.age = 0;
  51475. /**
  51476. * The current size of the particle.
  51477. */
  51478. this.size = 0;
  51479. /**
  51480. * The current angle of the particle.
  51481. */
  51482. this.angle = 0;
  51483. /**
  51484. * Defines how fast is the angle changing.
  51485. */
  51486. this.angularSpeed = 0;
  51487. /**
  51488. * Defines the cell index used by the particle to be rendered from a sprite.
  51489. */
  51490. this.cellIndex = 0;
  51491. this._currentFrameCounter = 0;
  51492. if (!this.particleSystem.isAnimationSheetEnabled) {
  51493. return;
  51494. }
  51495. this.updateCellInfoFromSystem();
  51496. }
  51497. Particle.prototype.updateCellInfoFromSystem = function () {
  51498. this.cellIndex = this.particleSystem.startSpriteCellID;
  51499. if (this.particleSystem.spriteCellChangeSpeed == 0) {
  51500. this.updateCellIndex = this._updateCellIndexWithSpeedCalculated;
  51501. }
  51502. else {
  51503. this.updateCellIndex = this._updateCellIndexWithCustomSpeed;
  51504. }
  51505. };
  51506. Particle.prototype._updateCellIndexWithSpeedCalculated = function (scaledUpdateSpeed) {
  51507. // (ageOffset / scaledUpdateSpeed) / available cells
  51508. var numberOfScaledUpdatesPerCell = ((this.lifeTime - this.age) / scaledUpdateSpeed) / (this.particleSystem.endSpriteCellID + 1 - this.cellIndex);
  51509. this._currentFrameCounter += scaledUpdateSpeed;
  51510. if (this._currentFrameCounter >= numberOfScaledUpdatesPerCell * scaledUpdateSpeed) {
  51511. this._currentFrameCounter = 0;
  51512. this.cellIndex++;
  51513. if (this.cellIndex > this.particleSystem.endSpriteCellID) {
  51514. this.cellIndex = this.particleSystem.endSpriteCellID;
  51515. }
  51516. }
  51517. };
  51518. Particle.prototype._updateCellIndexWithCustomSpeed = function () {
  51519. if (this._currentFrameCounter >= this.particleSystem.spriteCellChangeSpeed) {
  51520. this.cellIndex++;
  51521. this._currentFrameCounter = 0;
  51522. if (this.cellIndex > this.particleSystem.endSpriteCellID) {
  51523. if (this.particleSystem.spriteCellLoop) {
  51524. this.cellIndex = this.particleSystem.startSpriteCellID;
  51525. }
  51526. else {
  51527. this.cellIndex = this.particleSystem.endSpriteCellID;
  51528. }
  51529. }
  51530. }
  51531. else {
  51532. this._currentFrameCounter++;
  51533. }
  51534. };
  51535. /**
  51536. * Copy the properties of particle to another one.
  51537. * @param other the particle to copy the information to.
  51538. */
  51539. Particle.prototype.copyTo = function (other) {
  51540. other.position.copyFrom(this.position);
  51541. other.direction.copyFrom(this.direction);
  51542. other.color.copyFrom(this.color);
  51543. other.colorStep.copyFrom(this.colorStep);
  51544. other.lifeTime = this.lifeTime;
  51545. other.age = this.age;
  51546. other.size = this.size;
  51547. other.angle = this.angle;
  51548. other.angularSpeed = this.angularSpeed;
  51549. other.particleSystem = this.particleSystem;
  51550. other.cellIndex = this.cellIndex;
  51551. };
  51552. return Particle;
  51553. }());
  51554. BABYLON.Particle = Particle;
  51555. })(BABYLON || (BABYLON = {}));
  51556. //# sourceMappingURL=babylon.particle.js.map
  51557. "use strict";
  51558. var BABYLON;
  51559. (function (BABYLON) {
  51560. /**
  51561. * This represents a particle system in Babylon.
  51562. * 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.
  51563. * Particles can take different shapes while emitted like box, sphere, cone or you can write your custom function.
  51564. * @example https://doc.babylonjs.com/babylon101/particles
  51565. */
  51566. var ParticleSystem = /** @class */ (function () {
  51567. /**
  51568. * Instantiates a particle system.
  51569. * 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.
  51570. * @param name The name of the particle system
  51571. * @param capacity The max number of particles alive at the same time
  51572. * @param scene The scene the particle system belongs to
  51573. * @param customEffect a custom effect used to change the way particles are rendered by default
  51574. * @param isAnimationSheetEnabled Must be true if using a spritesheet to animate the particles texture
  51575. * @param epsilon Offset used to render the particles
  51576. */
  51577. function ParticleSystem(name, capacity, scene, customEffect, isAnimationSheetEnabled, epsilon) {
  51578. if (customEffect === void 0) { customEffect = null; }
  51579. if (isAnimationSheetEnabled === void 0) { isAnimationSheetEnabled = false; }
  51580. if (epsilon === void 0) { epsilon = 0.01; }
  51581. var _this = this;
  51582. /**
  51583. * List of animations used by the particle system.
  51584. */
  51585. this.animations = [];
  51586. /**
  51587. * The rendering group used by the Particle system to chose when to render.
  51588. */
  51589. this.renderingGroupId = 0;
  51590. /**
  51591. * The emitter represents the Mesh or position we are attaching the particle system to.
  51592. */
  51593. this.emitter = null;
  51594. /**
  51595. * The maximum number of particles to emit per frame
  51596. */
  51597. this.emitRate = 10;
  51598. /**
  51599. * If you want to launch only a few particles at once, that can be done, as well.
  51600. */
  51601. this.manualEmitCount = -1;
  51602. /**
  51603. * The overall motion speed (0.01 is default update speed, faster updates = faster animation)
  51604. */
  51605. this.updateSpeed = 0.01;
  51606. /**
  51607. * The amount of time the particle system is running (depends of the overall update speed).
  51608. */
  51609. this.targetStopDuration = 0;
  51610. /**
  51611. * Specifies whether the particle system will be disposed once it reaches the end of the animation.
  51612. */
  51613. this.disposeOnStop = false;
  51614. /**
  51615. * Minimum power of emitting particles.
  51616. */
  51617. this.minEmitPower = 1;
  51618. /**
  51619. * Maximum power of emitting particles.
  51620. */
  51621. this.maxEmitPower = 1;
  51622. /**
  51623. * Minimum life time of emitting particles.
  51624. */
  51625. this.minLifeTime = 1;
  51626. /**
  51627. * Maximum life time of emitting particles.
  51628. */
  51629. this.maxLifeTime = 1;
  51630. /**
  51631. * Minimum Size of emitting particles.
  51632. */
  51633. this.minSize = 1;
  51634. /**
  51635. * Maximum Size of emitting particles.
  51636. */
  51637. this.maxSize = 1;
  51638. /**
  51639. * Minimum angular speed of emitting particles (Z-axis rotation for each particle).
  51640. */
  51641. this.minAngularSpeed = 0;
  51642. /**
  51643. * Maximum angular speed of emitting particles (Z-axis rotation for each particle).
  51644. */
  51645. this.maxAngularSpeed = 0;
  51646. /**
  51647. * The layer mask we are rendering the particles through.
  51648. */
  51649. this.layerMask = 0x0FFFFFFF;
  51650. /**
  51651. * This can help using your own shader to render the particle system.
  51652. * The according effect will be created
  51653. */
  51654. this.customShader = null;
  51655. /**
  51656. * By default particle system starts as soon as they are created. This prevents the
  51657. * automatic start to happen and let you decide when to start emitting particles.
  51658. */
  51659. this.preventAutoStart = false;
  51660. /**
  51661. * Callback triggered when the particle animation is ending.
  51662. */
  51663. this.onAnimationEnd = null;
  51664. /**
  51665. * Blend mode use to render the particle, it can be either ParticleSystem.BLENDMODE_ONEONE or ParticleSystem.BLENDMODE_STANDARD.
  51666. */
  51667. this.blendMode = ParticleSystem.BLENDMODE_ONEONE;
  51668. /**
  51669. * Forces the particle to write their depth information to the depth buffer. This can help preventing other draw calls
  51670. * to override the particles.
  51671. */
  51672. this.forceDepthWrite = false;
  51673. /**
  51674. * You can use gravity if you want to give an orientation to your particles.
  51675. */
  51676. this.gravity = BABYLON.Vector3.Zero();
  51677. /**
  51678. * Random color of each particle after it has been emitted, between color1 and color2 vectors.
  51679. */
  51680. this.color1 = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  51681. /**
  51682. * Random color of each particle after it has been emitted, between color1 and color2 vectors.
  51683. */
  51684. this.color2 = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  51685. /**
  51686. * Color the particle will have at the end of its lifetime.
  51687. */
  51688. this.colorDead = new BABYLON.Color4(0, 0, 0, 1.0);
  51689. /**
  51690. * An optional mask to filter some colors out of the texture, or filter a part of the alpha channel.
  51691. */
  51692. this.textureMask = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  51693. /**
  51694. * If using a spritesheet (isAnimationSheetEnabled), defines if the sprite animation should loop between startSpriteCellID and endSpriteCellID or not.
  51695. */
  51696. this.spriteCellLoop = true;
  51697. /**
  51698. * If using a spritesheet (isAnimationSheetEnabled) and spriteCellLoop defines the speed of the sprite loop.
  51699. */
  51700. this.spriteCellChangeSpeed = 0;
  51701. /**
  51702. * If using a spritesheet (isAnimationSheetEnabled) and spriteCellLoop defines the first sprite cell to display.
  51703. */
  51704. this.startSpriteCellID = 0;
  51705. /**
  51706. * If using a spritesheet (isAnimationSheetEnabled) and spriteCellLoop defines the last sprite cell to display.
  51707. */
  51708. this.endSpriteCellID = 0;
  51709. /**
  51710. * If using a spritesheet (isAnimationSheetEnabled), defines the sprite cell width to use.
  51711. */
  51712. this.spriteCellWidth = 0;
  51713. /**
  51714. * If using a spritesheet (isAnimationSheetEnabled), defines the sprite cell height to use.
  51715. */
  51716. this.spriteCellHeight = 0;
  51717. /**
  51718. * An event triggered when the system is disposed.
  51719. */
  51720. this.onDisposeObservable = new BABYLON.Observable();
  51721. this._particles = new Array();
  51722. this._stockParticles = new Array();
  51723. this._newPartsExcess = 0;
  51724. this._vertexBuffers = {};
  51725. this._scaledColorStep = new BABYLON.Color4(0, 0, 0, 0);
  51726. this._colorDiff = new BABYLON.Color4(0, 0, 0, 0);
  51727. this._scaledDirection = BABYLON.Vector3.Zero();
  51728. this._scaledGravity = BABYLON.Vector3.Zero();
  51729. this._currentRenderId = -1;
  51730. this._started = false;
  51731. this._stopped = false;
  51732. this._actualFrame = 0;
  51733. this._vertexBufferSize = 11;
  51734. // start of sub system methods
  51735. /**
  51736. * "Recycles" one of the particle by copying it back to the "stock" of particles and removing it from the active list.
  51737. * Its lifetime will start back at 0.
  51738. */
  51739. this.recycleParticle = function (particle) {
  51740. var lastParticle = _this._particles.pop();
  51741. if (lastParticle !== particle) {
  51742. lastParticle.copyTo(particle);
  51743. }
  51744. _this._stockParticles.push(lastParticle);
  51745. };
  51746. this._createParticle = function () {
  51747. var particle;
  51748. if (_this._stockParticles.length !== 0) {
  51749. particle = _this._stockParticles.pop();
  51750. particle.age = 0;
  51751. particle.cellIndex = _this.startSpriteCellID;
  51752. }
  51753. else {
  51754. particle = new BABYLON.Particle(_this);
  51755. }
  51756. return particle;
  51757. };
  51758. this._emitFromParticle = function (particle) {
  51759. if (!_this.subEmitters || _this.subEmitters.length === 0) {
  51760. return;
  51761. }
  51762. var templateIndex = Math.floor(Math.random() * _this.subEmitters.length);
  51763. var subSystem = _this.subEmitters[templateIndex].clone(_this.name + "_sub", particle.position.clone());
  51764. subSystem._rootParticleSystem = _this;
  51765. _this.activeSubSystems.push(subSystem);
  51766. subSystem.start();
  51767. };
  51768. this._appendParticleVertexes = null;
  51769. this.id = name;
  51770. this.name = name;
  51771. this._capacity = capacity;
  51772. this._epsilon = epsilon;
  51773. this._isAnimationSheetEnabled = isAnimationSheetEnabled;
  51774. if (isAnimationSheetEnabled) {
  51775. this._vertexBufferSize = 12;
  51776. }
  51777. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  51778. this._customEffect = customEffect;
  51779. scene.particleSystems.push(this);
  51780. this._createIndexBuffer();
  51781. // 11 floats per particle (x, y, z, r, g, b, a, angle, size, offsetX, offsetY) + 1 filler
  51782. this._vertexData = new Float32Array(capacity * this._vertexBufferSize * 4);
  51783. this._vertexBuffer = new BABYLON.Buffer(scene.getEngine(), this._vertexData, true, this._vertexBufferSize);
  51784. var positions = this._vertexBuffer.createVertexBuffer(BABYLON.VertexBuffer.PositionKind, 0, 3);
  51785. var colors = this._vertexBuffer.createVertexBuffer(BABYLON.VertexBuffer.ColorKind, 3, 4);
  51786. var options = this._vertexBuffer.createVertexBuffer("options", 7, 4);
  51787. if (this._isAnimationSheetEnabled) {
  51788. var cellIndexBuffer = this._vertexBuffer.createVertexBuffer("cellIndex", 11, 1);
  51789. this._vertexBuffers["cellIndex"] = cellIndexBuffer;
  51790. }
  51791. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = positions;
  51792. this._vertexBuffers[BABYLON.VertexBuffer.ColorKind] = colors;
  51793. this._vertexBuffers["options"] = options;
  51794. // Default emitter type
  51795. this.particleEmitterType = new BABYLON.BoxParticleEmitter();
  51796. this.updateFunction = function (particles) {
  51797. for (var index = 0; index < particles.length; index++) {
  51798. var particle = particles[index];
  51799. particle.age += _this._scaledUpdateSpeed;
  51800. if (particle.age >= particle.lifeTime) {
  51801. _this._emitFromParticle(particle);
  51802. _this.recycleParticle(particle);
  51803. index--;
  51804. continue;
  51805. }
  51806. else {
  51807. particle.colorStep.scaleToRef(_this._scaledUpdateSpeed, _this._scaledColorStep);
  51808. particle.color.addInPlace(_this._scaledColorStep);
  51809. if (particle.color.a < 0)
  51810. particle.color.a = 0;
  51811. particle.angle += particle.angularSpeed * _this._scaledUpdateSpeed;
  51812. particle.direction.scaleToRef(_this._scaledUpdateSpeed, _this._scaledDirection);
  51813. particle.position.addInPlace(_this._scaledDirection);
  51814. _this.gravity.scaleToRef(_this._scaledUpdateSpeed, _this._scaledGravity);
  51815. particle.direction.addInPlace(_this._scaledGravity);
  51816. if (_this._isAnimationSheetEnabled) {
  51817. particle.updateCellIndex(_this._scaledUpdateSpeed);
  51818. }
  51819. }
  51820. }
  51821. };
  51822. }
  51823. Object.defineProperty(ParticleSystem.prototype, "direction1", {
  51824. /**
  51825. * Random direction of each particle after it has been emitted, between direction1 and direction2 vectors.
  51826. * This only works when particleEmitterTyps is a BoxParticleEmitter
  51827. */
  51828. get: function () {
  51829. if (this.particleEmitterType.direction1) {
  51830. return this.particleEmitterType.direction1;
  51831. }
  51832. return BABYLON.Vector3.Zero();
  51833. },
  51834. set: function (value) {
  51835. if (this.particleEmitterType.direction1) {
  51836. this.particleEmitterType.direction1 = value;
  51837. }
  51838. },
  51839. enumerable: true,
  51840. configurable: true
  51841. });
  51842. Object.defineProperty(ParticleSystem.prototype, "direction2", {
  51843. /**
  51844. * Random direction of each particle after it has been emitted, between direction1 and direction2 vectors.
  51845. * This only works when particleEmitterTyps is a BoxParticleEmitter
  51846. */
  51847. get: function () {
  51848. if (this.particleEmitterType.direction2) {
  51849. return this.particleEmitterType.direction2;
  51850. }
  51851. return BABYLON.Vector3.Zero();
  51852. },
  51853. set: function (value) {
  51854. if (this.particleEmitterType.direction2) {
  51855. this.particleEmitterType.direction2 = value;
  51856. }
  51857. },
  51858. enumerable: true,
  51859. configurable: true
  51860. });
  51861. Object.defineProperty(ParticleSystem.prototype, "minEmitBox", {
  51862. /**
  51863. * 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.
  51864. * This only works when particleEmitterTyps is a BoxParticleEmitter
  51865. */
  51866. get: function () {
  51867. if (this.particleEmitterType.minEmitBox) {
  51868. return this.particleEmitterType.minEmitBox;
  51869. }
  51870. return BABYLON.Vector3.Zero();
  51871. },
  51872. set: function (value) {
  51873. if (this.particleEmitterType.minEmitBox) {
  51874. this.particleEmitterType.minEmitBox = value;
  51875. }
  51876. },
  51877. enumerable: true,
  51878. configurable: true
  51879. });
  51880. Object.defineProperty(ParticleSystem.prototype, "maxEmitBox", {
  51881. /**
  51882. * 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.
  51883. * This only works when particleEmitterTyps is a BoxParticleEmitter
  51884. */
  51885. get: function () {
  51886. if (this.particleEmitterType.maxEmitBox) {
  51887. return this.particleEmitterType.maxEmitBox;
  51888. }
  51889. return BABYLON.Vector3.Zero();
  51890. },
  51891. set: function (value) {
  51892. if (this.particleEmitterType.maxEmitBox) {
  51893. this.particleEmitterType.maxEmitBox = value;
  51894. }
  51895. },
  51896. enumerable: true,
  51897. configurable: true
  51898. });
  51899. Object.defineProperty(ParticleSystem.prototype, "onDispose", {
  51900. /**
  51901. * Sets a callback that will be triggered when the system is disposed.
  51902. */
  51903. set: function (callback) {
  51904. if (this._onDisposeObserver) {
  51905. this.onDisposeObservable.remove(this._onDisposeObserver);
  51906. }
  51907. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  51908. },
  51909. enumerable: true,
  51910. configurable: true
  51911. });
  51912. Object.defineProperty(ParticleSystem.prototype, "isAnimationSheetEnabled", {
  51913. /**
  51914. * Gets wether an animation sprite sheet is enabled or not on the particle system.
  51915. */
  51916. get: function () {
  51917. return this._isAnimationSheetEnabled;
  51918. },
  51919. enumerable: true,
  51920. configurable: true
  51921. });
  51922. Object.defineProperty(ParticleSystem.prototype, "particles", {
  51923. //end of Sub-emitter
  51924. /**
  51925. * Gets the current list of active particles
  51926. */
  51927. get: function () {
  51928. return this._particles;
  51929. },
  51930. enumerable: true,
  51931. configurable: true
  51932. });
  51933. /**
  51934. * Returns the string "ParticleSystem"
  51935. * @returns a string containing the class name
  51936. */
  51937. ParticleSystem.prototype.getClassName = function () {
  51938. return "ParticleSystem";
  51939. };
  51940. ParticleSystem.prototype._createIndexBuffer = function () {
  51941. var indices = [];
  51942. var index = 0;
  51943. for (var count = 0; count < this._capacity; count++) {
  51944. indices.push(index);
  51945. indices.push(index + 1);
  51946. indices.push(index + 2);
  51947. indices.push(index);
  51948. indices.push(index + 2);
  51949. indices.push(index + 3);
  51950. index += 4;
  51951. }
  51952. this._indexBuffer = this._scene.getEngine().createIndexBuffer(indices);
  51953. };
  51954. /**
  51955. * Gets the maximum number of particles active at the same time.
  51956. * @returns The max number of active particles.
  51957. */
  51958. ParticleSystem.prototype.getCapacity = function () {
  51959. return this._capacity;
  51960. };
  51961. /**
  51962. * Gets Wether there are still active particles in the system.
  51963. * @returns True if it is alive, otherwise false.
  51964. */
  51965. ParticleSystem.prototype.isAlive = function () {
  51966. return this._alive;
  51967. };
  51968. /**
  51969. * Gets Wether the system has been started.
  51970. * @returns True if it has been started, otherwise false.
  51971. */
  51972. ParticleSystem.prototype.isStarted = function () {
  51973. return this._started;
  51974. };
  51975. /**
  51976. * Starts the particle system and begins to emit.
  51977. */
  51978. ParticleSystem.prototype.start = function () {
  51979. this._started = true;
  51980. this._stopped = false;
  51981. this._actualFrame = 0;
  51982. if (this.subEmitters && this.subEmitters.length != 0) {
  51983. this.activeSubSystems = new Array();
  51984. }
  51985. };
  51986. /**
  51987. * Stops the particle system.
  51988. * @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.
  51989. */
  51990. ParticleSystem.prototype.stop = function (stopSubEmitters) {
  51991. if (stopSubEmitters === void 0) { stopSubEmitters = true; }
  51992. this._stopped = true;
  51993. if (stopSubEmitters) {
  51994. this._stopSubEmitters();
  51995. }
  51996. };
  51997. // animation sheet
  51998. /**
  51999. * Remove all active particles
  52000. */
  52001. ParticleSystem.prototype.reset = function () {
  52002. this._stockParticles = [];
  52003. this._particles = [];
  52004. };
  52005. /**
  52006. * @ignore (for internal use only)
  52007. */
  52008. ParticleSystem.prototype._appendParticleVertex = function (index, particle, offsetX, offsetY) {
  52009. var offset = index * this._vertexBufferSize;
  52010. this._vertexData[offset] = particle.position.x;
  52011. this._vertexData[offset + 1] = particle.position.y;
  52012. this._vertexData[offset + 2] = particle.position.z;
  52013. this._vertexData[offset + 3] = particle.color.r;
  52014. this._vertexData[offset + 4] = particle.color.g;
  52015. this._vertexData[offset + 5] = particle.color.b;
  52016. this._vertexData[offset + 6] = particle.color.a;
  52017. this._vertexData[offset + 7] = particle.angle;
  52018. this._vertexData[offset + 8] = particle.size;
  52019. this._vertexData[offset + 9] = offsetX;
  52020. this._vertexData[offset + 10] = offsetY;
  52021. };
  52022. /**
  52023. * @ignore (for internal use only)
  52024. */
  52025. ParticleSystem.prototype._appendParticleVertexWithAnimation = function (index, particle, offsetX, offsetY) {
  52026. if (offsetX === 0)
  52027. offsetX = this._epsilon;
  52028. else if (offsetX === 1)
  52029. offsetX = 1 - this._epsilon;
  52030. if (offsetY === 0)
  52031. offsetY = this._epsilon;
  52032. else if (offsetY === 1)
  52033. offsetY = 1 - this._epsilon;
  52034. var offset = index * this._vertexBufferSize;
  52035. this._vertexData[offset] = particle.position.x;
  52036. this._vertexData[offset + 1] = particle.position.y;
  52037. this._vertexData[offset + 2] = particle.position.z;
  52038. this._vertexData[offset + 3] = particle.color.r;
  52039. this._vertexData[offset + 4] = particle.color.g;
  52040. this._vertexData[offset + 5] = particle.color.b;
  52041. this._vertexData[offset + 6] = particle.color.a;
  52042. this._vertexData[offset + 7] = particle.angle;
  52043. this._vertexData[offset + 8] = particle.size;
  52044. this._vertexData[offset + 9] = offsetX;
  52045. this._vertexData[offset + 10] = offsetY;
  52046. this._vertexData[offset + 11] = particle.cellIndex;
  52047. };
  52048. ParticleSystem.prototype._stopSubEmitters = function () {
  52049. if (!this.activeSubSystems) {
  52050. return;
  52051. }
  52052. this.activeSubSystems.forEach(function (subSystem) {
  52053. subSystem.stop(true);
  52054. });
  52055. this.activeSubSystems = new Array();
  52056. };
  52057. ParticleSystem.prototype._removeFromRoot = function () {
  52058. if (!this._rootParticleSystem) {
  52059. return;
  52060. }
  52061. var index = this._rootParticleSystem.activeSubSystems.indexOf(this);
  52062. if (index !== -1) {
  52063. this._rootParticleSystem.activeSubSystems.splice(index, 1);
  52064. }
  52065. };
  52066. // end of sub system methods
  52067. ParticleSystem.prototype._update = function (newParticles) {
  52068. // Update current
  52069. this._alive = this._particles.length > 0;
  52070. this.updateFunction(this._particles);
  52071. // Add new ones
  52072. var worldMatrix;
  52073. if (this.emitter.position) {
  52074. var emitterMesh = this.emitter;
  52075. worldMatrix = emitterMesh.getWorldMatrix();
  52076. }
  52077. else {
  52078. var emitterPosition = this.emitter;
  52079. worldMatrix = BABYLON.Matrix.Translation(emitterPosition.x, emitterPosition.y, emitterPosition.z);
  52080. }
  52081. var particle;
  52082. for (var index = 0; index < newParticles; index++) {
  52083. if (this._particles.length === this._capacity) {
  52084. break;
  52085. }
  52086. particle = this._createParticle();
  52087. this._particles.push(particle);
  52088. var emitPower = BABYLON.Scalar.RandomRange(this.minEmitPower, this.maxEmitPower);
  52089. if (this.startPositionFunction) {
  52090. this.startPositionFunction(worldMatrix, particle.position, particle);
  52091. }
  52092. else {
  52093. this.particleEmitterType.startPositionFunction(worldMatrix, particle.position, particle);
  52094. }
  52095. if (this.startDirectionFunction) {
  52096. this.startDirectionFunction(emitPower, worldMatrix, particle.direction, particle);
  52097. }
  52098. else {
  52099. this.particleEmitterType.startDirectionFunction(emitPower, worldMatrix, particle.direction, particle);
  52100. }
  52101. particle.lifeTime = BABYLON.Scalar.RandomRange(this.minLifeTime, this.maxLifeTime);
  52102. particle.size = BABYLON.Scalar.RandomRange(this.minSize, this.maxSize);
  52103. particle.angularSpeed = BABYLON.Scalar.RandomRange(this.minAngularSpeed, this.maxAngularSpeed);
  52104. var step = BABYLON.Scalar.RandomRange(0, 1.0);
  52105. BABYLON.Color4.LerpToRef(this.color1, this.color2, step, particle.color);
  52106. this.colorDead.subtractToRef(particle.color, this._colorDiff);
  52107. this._colorDiff.scaleToRef(1.0 / particle.lifeTime, particle.colorStep);
  52108. }
  52109. };
  52110. ParticleSystem.prototype._getEffect = function () {
  52111. if (this._customEffect) {
  52112. return this._customEffect;
  52113. }
  52114. ;
  52115. var defines = [];
  52116. if (this._scene.clipPlane) {
  52117. defines.push("#define CLIPPLANE");
  52118. }
  52119. if (this._isAnimationSheetEnabled) {
  52120. defines.push("#define ANIMATESHEET");
  52121. }
  52122. // Effect
  52123. var join = defines.join("\n");
  52124. if (this._cachedDefines !== join) {
  52125. this._cachedDefines = join;
  52126. var attributesNamesOrOptions;
  52127. var effectCreationOption;
  52128. if (this._isAnimationSheetEnabled) {
  52129. attributesNamesOrOptions = [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.ColorKind, "options", "cellIndex"];
  52130. effectCreationOption = ["invView", "view", "projection", "particlesInfos", "vClipPlane", "textureMask"];
  52131. }
  52132. else {
  52133. attributesNamesOrOptions = [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.ColorKind, "options"];
  52134. effectCreationOption = ["invView", "view", "projection", "vClipPlane", "textureMask"];
  52135. }
  52136. this._effect = this._scene.getEngine().createEffect("particles", attributesNamesOrOptions, effectCreationOption, ["diffuseSampler"], join);
  52137. }
  52138. return this._effect;
  52139. };
  52140. /**
  52141. * Animates the particle system for the current frame by emitting new particles and or animating the living ones.
  52142. */
  52143. ParticleSystem.prototype.animate = function () {
  52144. if (!this._started)
  52145. return;
  52146. var effect = this._getEffect();
  52147. // Check
  52148. if (!this.emitter || !effect.isReady() || !this.particleTexture || !this.particleTexture.isReady())
  52149. return;
  52150. if (this._currentRenderId === this._scene.getRenderId()) {
  52151. return;
  52152. }
  52153. this._currentRenderId = this._scene.getRenderId();
  52154. this._scaledUpdateSpeed = this.updateSpeed * this._scene.getAnimationRatio();
  52155. // determine the number of particles we need to create
  52156. var newParticles;
  52157. if (this.manualEmitCount > -1) {
  52158. newParticles = this.manualEmitCount;
  52159. this._newPartsExcess = 0;
  52160. this.manualEmitCount = 0;
  52161. }
  52162. else {
  52163. newParticles = ((this.emitRate * this._scaledUpdateSpeed) >> 0);
  52164. this._newPartsExcess += this.emitRate * this._scaledUpdateSpeed - newParticles;
  52165. }
  52166. if (this._newPartsExcess > 1.0) {
  52167. newParticles += this._newPartsExcess >> 0;
  52168. this._newPartsExcess -= this._newPartsExcess >> 0;
  52169. }
  52170. this._alive = false;
  52171. if (!this._stopped) {
  52172. this._actualFrame += this._scaledUpdateSpeed;
  52173. if (this.targetStopDuration && this._actualFrame >= this.targetStopDuration)
  52174. this.stop();
  52175. }
  52176. else {
  52177. newParticles = 0;
  52178. }
  52179. this._update(newParticles);
  52180. // Stopped?
  52181. if (this._stopped) {
  52182. if (!this._alive) {
  52183. this._started = false;
  52184. if (this.onAnimationEnd) {
  52185. this.onAnimationEnd();
  52186. }
  52187. if (this.disposeOnStop) {
  52188. this._scene._toBeDisposed.push(this);
  52189. }
  52190. }
  52191. }
  52192. // Animation sheet
  52193. if (this._isAnimationSheetEnabled) {
  52194. this._appendParticleVertexes = this._appenedParticleVertexesWithSheet;
  52195. }
  52196. else {
  52197. this._appendParticleVertexes = this._appenedParticleVertexesNoSheet;
  52198. }
  52199. // Update VBO
  52200. var offset = 0;
  52201. for (var index = 0; index < this._particles.length; index++) {
  52202. var particle = this._particles[index];
  52203. this._appendParticleVertexes(offset, particle);
  52204. offset += 4;
  52205. }
  52206. if (this._vertexBuffer) {
  52207. this._vertexBuffer.update(this._vertexData);
  52208. }
  52209. if (this.manualEmitCount === 0 && this.disposeOnStop) {
  52210. this.stop();
  52211. }
  52212. };
  52213. ParticleSystem.prototype._appenedParticleVertexesWithSheet = function (offset, particle) {
  52214. this._appendParticleVertexWithAnimation(offset++, particle, 0, 0);
  52215. this._appendParticleVertexWithAnimation(offset++, particle, 1, 0);
  52216. this._appendParticleVertexWithAnimation(offset++, particle, 1, 1);
  52217. this._appendParticleVertexWithAnimation(offset++, particle, 0, 1);
  52218. };
  52219. ParticleSystem.prototype._appenedParticleVertexesNoSheet = function (offset, particle) {
  52220. this._appendParticleVertex(offset++, particle, 0, 0);
  52221. this._appendParticleVertex(offset++, particle, 1, 0);
  52222. this._appendParticleVertex(offset++, particle, 1, 1);
  52223. this._appendParticleVertex(offset++, particle, 0, 1);
  52224. };
  52225. /**
  52226. * Rebuilds the particle system.
  52227. */
  52228. ParticleSystem.prototype.rebuild = function () {
  52229. this._createIndexBuffer();
  52230. if (this._vertexBuffer) {
  52231. this._vertexBuffer._rebuild();
  52232. }
  52233. };
  52234. /**
  52235. * Is this system ready to be used/rendered
  52236. * @return true if the system is ready
  52237. */
  52238. ParticleSystem.prototype.isReady = function () {
  52239. var effect = this._getEffect();
  52240. if (!this.emitter || !effect.isReady() || !this.particleTexture || !this.particleTexture.isReady()) {
  52241. return false;
  52242. }
  52243. return true;
  52244. };
  52245. /**
  52246. * Renders the particle system in its current state.
  52247. * @returns the current number of particles
  52248. */
  52249. ParticleSystem.prototype.render = function () {
  52250. var effect = this._getEffect();
  52251. // Check
  52252. if (!this.isReady() || !this._particles.length) {
  52253. return 0;
  52254. }
  52255. var engine = this._scene.getEngine();
  52256. // Render
  52257. engine.enableEffect(effect);
  52258. engine.setState(false);
  52259. var viewMatrix = this._scene.getViewMatrix();
  52260. effect.setTexture("diffuseSampler", this.particleTexture);
  52261. effect.setMatrix("view", viewMatrix);
  52262. effect.setMatrix("projection", this._scene.getProjectionMatrix());
  52263. if (this._isAnimationSheetEnabled && this.particleTexture) {
  52264. var baseSize = this.particleTexture.getBaseSize();
  52265. effect.setFloat3("particlesInfos", this.spriteCellWidth / baseSize.width, this.spriteCellHeight / baseSize.height, baseSize.width / this.spriteCellWidth);
  52266. }
  52267. effect.setFloat4("textureMask", this.textureMask.r, this.textureMask.g, this.textureMask.b, this.textureMask.a);
  52268. if (this._scene.clipPlane) {
  52269. var clipPlane = this._scene.clipPlane;
  52270. var invView = viewMatrix.clone();
  52271. invView.invert();
  52272. effect.setMatrix("invView", invView);
  52273. effect.setFloat4("vClipPlane", clipPlane.normal.x, clipPlane.normal.y, clipPlane.normal.z, clipPlane.d);
  52274. }
  52275. // VBOs
  52276. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  52277. // Draw order
  52278. if (this.blendMode === ParticleSystem.BLENDMODE_ONEONE) {
  52279. engine.setAlphaMode(BABYLON.Engine.ALPHA_ONEONE);
  52280. }
  52281. else {
  52282. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  52283. }
  52284. if (this.forceDepthWrite) {
  52285. engine.setDepthWrite(true);
  52286. }
  52287. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, this._particles.length * 6);
  52288. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  52289. return this._particles.length;
  52290. };
  52291. /**
  52292. * Disposes the particle system and free the associated resources
  52293. * @param disposeTexture defines if the particule texture must be disposed as well (true by default)
  52294. */
  52295. ParticleSystem.prototype.dispose = function (disposeTexture) {
  52296. if (disposeTexture === void 0) { disposeTexture = true; }
  52297. if (this._vertexBuffer) {
  52298. this._vertexBuffer.dispose();
  52299. this._vertexBuffer = null;
  52300. }
  52301. if (this._indexBuffer) {
  52302. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  52303. this._indexBuffer = null;
  52304. }
  52305. if (disposeTexture && this.particleTexture) {
  52306. this.particleTexture.dispose();
  52307. this.particleTexture = null;
  52308. }
  52309. this._removeFromRoot();
  52310. // Remove from scene
  52311. var index = this._scene.particleSystems.indexOf(this);
  52312. if (index > -1) {
  52313. this._scene.particleSystems.splice(index, 1);
  52314. }
  52315. // Callback
  52316. this.onDisposeObservable.notifyObservers(this);
  52317. this.onDisposeObservable.clear();
  52318. };
  52319. /**
  52320. * Creates a Sphere Emitter for the particle system. (emits along the sphere radius)
  52321. * @param radius The radius of the sphere to emit from
  52322. * @returns the emitter
  52323. */
  52324. ParticleSystem.prototype.createSphereEmitter = function (radius) {
  52325. if (radius === void 0) { radius = 1; }
  52326. var particleEmitter = new BABYLON.SphereParticleEmitter(radius);
  52327. this.particleEmitterType = particleEmitter;
  52328. return particleEmitter;
  52329. };
  52330. /**
  52331. * Creates a Directed Sphere Emitter for the particle system. (emits between direction1 and direction2)
  52332. * @param radius The radius of the sphere to emit from
  52333. * @param direction1 Particles are emitted between the direction1 and direction2 from within the sphere
  52334. * @param direction2 Particles are emitted between the direction1 and direction2 from within the sphere
  52335. * @returns the emitter
  52336. */
  52337. ParticleSystem.prototype.createDirectedSphereEmitter = function (radius, direction1, direction2) {
  52338. if (radius === void 0) { radius = 1; }
  52339. if (direction1 === void 0) { direction1 = new BABYLON.Vector3(0, 1.0, 0); }
  52340. if (direction2 === void 0) { direction2 = new BABYLON.Vector3(0, 1.0, 0); }
  52341. var particleEmitter = new BABYLON.SphereDirectedParticleEmitter(radius, direction1, direction2);
  52342. this.particleEmitterType = particleEmitter;
  52343. return particleEmitter;
  52344. };
  52345. /**
  52346. * Creates a Cone Emitter for the particle system. (emits from the cone to the particle position)
  52347. * @param radius The radius of the cone to emit from
  52348. * @param angle The base angle of the cone
  52349. * @returns the emitter
  52350. */
  52351. ParticleSystem.prototype.createConeEmitter = function (radius, angle) {
  52352. if (radius === void 0) { radius = 1; }
  52353. if (angle === void 0) { angle = Math.PI / 4; }
  52354. var particleEmitter = new BABYLON.ConeParticleEmitter(radius, angle);
  52355. this.particleEmitterType = particleEmitter;
  52356. return particleEmitter;
  52357. };
  52358. // 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.
  52359. /**
  52360. * Creates a Box Emitter for the particle system. (emits between direction1 and direction2 from withing the box defined by minEmitBox and maxEmitBox)
  52361. * @param direction1 Particles are emitted between the direction1 and direction2 from within the box
  52362. * @param direction2 Particles are emitted between the direction1 and direction2 from within the box
  52363. * @param minEmitBox Particles are emitted from the box between minEmitBox and maxEmitBox
  52364. * @param maxEmitBox Particles are emitted from the box between minEmitBox and maxEmitBox
  52365. * @returns the emitter
  52366. */
  52367. ParticleSystem.prototype.createBoxEmitter = function (direction1, direction2, minEmitBox, maxEmitBox) {
  52368. var particleEmitter = new BABYLON.BoxParticleEmitter();
  52369. this.particleEmitterType = particleEmitter;
  52370. this.direction1 = direction1;
  52371. this.direction2 = direction2;
  52372. this.minEmitBox = minEmitBox;
  52373. this.maxEmitBox = maxEmitBox;
  52374. return particleEmitter;
  52375. };
  52376. // Clone
  52377. /**
  52378. * Clones the particle system.
  52379. * @param name The name of the cloned object
  52380. * @param newEmitter The new emitter to use
  52381. * @returns the cloned particle system
  52382. */
  52383. ParticleSystem.prototype.clone = function (name, newEmitter) {
  52384. var custom = null;
  52385. var program = null;
  52386. if (this.customShader != null) {
  52387. program = this.customShader;
  52388. var defines = (program.shaderOptions.defines.length > 0) ? program.shaderOptions.defines.join("\n") : "";
  52389. custom = this._scene.getEngine().createEffectForParticles(program.shaderPath.fragmentElement, program.shaderOptions.uniforms, program.shaderOptions.samplers, defines);
  52390. }
  52391. var result = new ParticleSystem(name, this._capacity, this._scene, custom);
  52392. result.customShader = program;
  52393. BABYLON.Tools.DeepCopy(this, result, ["particles", "customShader"]);
  52394. if (newEmitter === undefined) {
  52395. newEmitter = this.emitter;
  52396. }
  52397. result.emitter = newEmitter;
  52398. if (this.particleTexture) {
  52399. result.particleTexture = new BABYLON.Texture(this.particleTexture.url, this._scene);
  52400. }
  52401. if (!this.preventAutoStart) {
  52402. result.start();
  52403. }
  52404. return result;
  52405. };
  52406. /**
  52407. * Serializes the particle system to a JSON object.
  52408. * @returns the JSON object
  52409. */
  52410. ParticleSystem.prototype.serialize = function () {
  52411. var serializationObject = {};
  52412. serializationObject.name = this.name;
  52413. serializationObject.id = this.id;
  52414. // Emitter
  52415. if (this.emitter.position) {
  52416. var emitterMesh = this.emitter;
  52417. serializationObject.emitterId = emitterMesh.id;
  52418. }
  52419. else {
  52420. var emitterPosition = this.emitter;
  52421. serializationObject.emitter = emitterPosition.asArray();
  52422. }
  52423. serializationObject.capacity = this.getCapacity();
  52424. if (this.particleTexture) {
  52425. serializationObject.textureName = this.particleTexture.name;
  52426. }
  52427. // Animations
  52428. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  52429. // Particle system
  52430. serializationObject.minAngularSpeed = this.minAngularSpeed;
  52431. serializationObject.maxAngularSpeed = this.maxAngularSpeed;
  52432. serializationObject.minSize = this.minSize;
  52433. serializationObject.maxSize = this.maxSize;
  52434. serializationObject.minEmitPower = this.minEmitPower;
  52435. serializationObject.maxEmitPower = this.maxEmitPower;
  52436. serializationObject.minLifeTime = this.minLifeTime;
  52437. serializationObject.maxLifeTime = this.maxLifeTime;
  52438. serializationObject.emitRate = this.emitRate;
  52439. serializationObject.minEmitBox = this.minEmitBox.asArray();
  52440. serializationObject.maxEmitBox = this.maxEmitBox.asArray();
  52441. serializationObject.gravity = this.gravity.asArray();
  52442. serializationObject.direction1 = this.direction1.asArray();
  52443. serializationObject.direction2 = this.direction2.asArray();
  52444. serializationObject.color1 = this.color1.asArray();
  52445. serializationObject.color2 = this.color2.asArray();
  52446. serializationObject.colorDead = this.colorDead.asArray();
  52447. serializationObject.updateSpeed = this.updateSpeed;
  52448. serializationObject.targetStopDuration = this.targetStopDuration;
  52449. serializationObject.textureMask = this.textureMask.asArray();
  52450. serializationObject.blendMode = this.blendMode;
  52451. serializationObject.customShader = this.customShader;
  52452. serializationObject.preventAutoStart = this.preventAutoStart;
  52453. serializationObject.startSpriteCellID = this.startSpriteCellID;
  52454. serializationObject.endSpriteCellID = this.endSpriteCellID;
  52455. serializationObject.spriteCellLoop = this.spriteCellLoop;
  52456. serializationObject.spriteCellChangeSpeed = this.spriteCellChangeSpeed;
  52457. serializationObject.spriteCellWidth = this.spriteCellWidth;
  52458. serializationObject.spriteCellHeight = this.spriteCellHeight;
  52459. serializationObject.isAnimationSheetEnabled = this._isAnimationSheetEnabled;
  52460. // Emitter
  52461. if (this.particleEmitterType) {
  52462. serializationObject.particleEmitterType = this.particleEmitterType.serialize();
  52463. }
  52464. return serializationObject;
  52465. };
  52466. /**
  52467. * Parses a JSON object to create a particle system.
  52468. * @param parsedParticleSystem The JSON object to parse
  52469. * @param scene The scene to create the particle system in
  52470. * @param rootUrl The root url to use to load external dependencies like texture
  52471. * @returns the Parsed particle system
  52472. */
  52473. ParticleSystem.Parse = function (parsedParticleSystem, scene, rootUrl) {
  52474. var name = parsedParticleSystem.name;
  52475. var custom = null;
  52476. var program = null;
  52477. if (parsedParticleSystem.customShader) {
  52478. program = parsedParticleSystem.customShader;
  52479. var defines = (program.shaderOptions.defines.length > 0) ? program.shaderOptions.defines.join("\n") : "";
  52480. custom = scene.getEngine().createEffectForParticles(program.shaderPath.fragmentElement, program.shaderOptions.uniforms, program.shaderOptions.samplers, defines);
  52481. }
  52482. var particleSystem = new ParticleSystem(name, parsedParticleSystem.capacity, scene, custom, parsedParticleSystem.isAnimationSheetEnabled);
  52483. particleSystem.customShader = program;
  52484. if (parsedParticleSystem.id) {
  52485. particleSystem.id = parsedParticleSystem.id;
  52486. }
  52487. // Auto start
  52488. if (parsedParticleSystem.preventAutoStart) {
  52489. particleSystem.preventAutoStart = parsedParticleSystem.preventAutoStart;
  52490. }
  52491. // Texture
  52492. if (parsedParticleSystem.textureName) {
  52493. particleSystem.particleTexture = new BABYLON.Texture(rootUrl + parsedParticleSystem.textureName, scene);
  52494. particleSystem.particleTexture.name = parsedParticleSystem.textureName;
  52495. }
  52496. // Emitter
  52497. if (parsedParticleSystem.emitterId) {
  52498. particleSystem.emitter = scene.getLastMeshByID(parsedParticleSystem.emitterId);
  52499. }
  52500. else {
  52501. particleSystem.emitter = BABYLON.Vector3.FromArray(parsedParticleSystem.emitter);
  52502. }
  52503. // Animations
  52504. if (parsedParticleSystem.animations) {
  52505. for (var animationIndex = 0; animationIndex < parsedParticleSystem.animations.length; animationIndex++) {
  52506. var parsedAnimation = parsedParticleSystem.animations[animationIndex];
  52507. particleSystem.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  52508. }
  52509. }
  52510. if (parsedParticleSystem.autoAnimate) {
  52511. scene.beginAnimation(particleSystem, parsedParticleSystem.autoAnimateFrom, parsedParticleSystem.autoAnimateTo, parsedParticleSystem.autoAnimateLoop, parsedParticleSystem.autoAnimateSpeed || 1.0);
  52512. }
  52513. // Particle system
  52514. particleSystem.minAngularSpeed = parsedParticleSystem.minAngularSpeed;
  52515. particleSystem.maxAngularSpeed = parsedParticleSystem.maxAngularSpeed;
  52516. particleSystem.minSize = parsedParticleSystem.minSize;
  52517. particleSystem.maxSize = parsedParticleSystem.maxSize;
  52518. particleSystem.minLifeTime = parsedParticleSystem.minLifeTime;
  52519. particleSystem.maxLifeTime = parsedParticleSystem.maxLifeTime;
  52520. particleSystem.minEmitPower = parsedParticleSystem.minEmitPower;
  52521. particleSystem.maxEmitPower = parsedParticleSystem.maxEmitPower;
  52522. particleSystem.emitRate = parsedParticleSystem.emitRate;
  52523. particleSystem.minEmitBox = BABYLON.Vector3.FromArray(parsedParticleSystem.minEmitBox);
  52524. particleSystem.maxEmitBox = BABYLON.Vector3.FromArray(parsedParticleSystem.maxEmitBox);
  52525. particleSystem.gravity = BABYLON.Vector3.FromArray(parsedParticleSystem.gravity);
  52526. particleSystem.direction1 = BABYLON.Vector3.FromArray(parsedParticleSystem.direction1);
  52527. particleSystem.direction2 = BABYLON.Vector3.FromArray(parsedParticleSystem.direction2);
  52528. particleSystem.color1 = BABYLON.Color4.FromArray(parsedParticleSystem.color1);
  52529. particleSystem.color2 = BABYLON.Color4.FromArray(parsedParticleSystem.color2);
  52530. particleSystem.colorDead = BABYLON.Color4.FromArray(parsedParticleSystem.colorDead);
  52531. particleSystem.updateSpeed = parsedParticleSystem.updateSpeed;
  52532. particleSystem.targetStopDuration = parsedParticleSystem.targetStopDuration;
  52533. particleSystem.textureMask = BABYLON.Color4.FromArray(parsedParticleSystem.textureMask);
  52534. particleSystem.blendMode = parsedParticleSystem.blendMode;
  52535. particleSystem.startSpriteCellID = parsedParticleSystem.startSpriteCellID;
  52536. particleSystem.endSpriteCellID = parsedParticleSystem.endSpriteCellID;
  52537. particleSystem.spriteCellLoop = parsedParticleSystem.spriteCellLoop;
  52538. particleSystem.spriteCellChangeSpeed = parsedParticleSystem.spriteCellChangeSpeed;
  52539. particleSystem.spriteCellWidth = parsedParticleSystem.spriteCellWidth;
  52540. particleSystem.spriteCellHeight = parsedParticleSystem.spriteCellHeight;
  52541. if (!particleSystem.preventAutoStart) {
  52542. particleSystem.start();
  52543. }
  52544. return particleSystem;
  52545. };
  52546. /**
  52547. * Source color is added to the destination color without alpha affecting the result.
  52548. */
  52549. ParticleSystem.BLENDMODE_ONEONE = 0;
  52550. /**
  52551. * Blend current color and particle color using particle’s alpha.
  52552. */
  52553. ParticleSystem.BLENDMODE_STANDARD = 1;
  52554. return ParticleSystem;
  52555. }());
  52556. BABYLON.ParticleSystem = ParticleSystem;
  52557. })(BABYLON || (BABYLON = {}));
  52558. //# sourceMappingURL=babylon.particleSystem.js.map
  52559. "use strict";
  52560. //# sourceMappingURL=babylon.IParticleEmitterType.js.map
  52561. "use strict";
  52562. var BABYLON;
  52563. (function (BABYLON) {
  52564. /**
  52565. * Particle emitter emitting particles from the inside of a box.
  52566. * It emits the particles randomly between 2 given directions.
  52567. */
  52568. var BoxParticleEmitter = /** @class */ (function () {
  52569. /**
  52570. * Creates a new instance BoxParticleEmitter
  52571. */
  52572. function BoxParticleEmitter() {
  52573. /**
  52574. * Random direction of each particle after it has been emitted, between direction1 and direction2 vectors.
  52575. */
  52576. this.direction1 = new BABYLON.Vector3(0, 1.0, 0);
  52577. /**
  52578. * Random direction of each particle after it has been emitted, between direction1 and direction2 vectors.
  52579. */
  52580. this.direction2 = new BABYLON.Vector3(0, 1.0, 0);
  52581. /**
  52582. * 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.
  52583. */
  52584. this.minEmitBox = new BABYLON.Vector3(-0.5, -0.5, -0.5);
  52585. /**
  52586. * 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.
  52587. */
  52588. this.maxEmitBox = new BABYLON.Vector3(0.5, 0.5, 0.5);
  52589. }
  52590. /**
  52591. * Called by the particle System when the direction is computed for the created particle.
  52592. * @param emitPower is the power of the particle (speed)
  52593. * @param worldMatrix is the world matrix of the particle system
  52594. * @param directionToUpdate is the direction vector to update with the result
  52595. * @param particle is the particle we are computed the direction for
  52596. */
  52597. BoxParticleEmitter.prototype.startDirectionFunction = function (emitPower, worldMatrix, directionToUpdate, particle) {
  52598. var randX = BABYLON.Scalar.RandomRange(this.direction1.x, this.direction2.x);
  52599. var randY = BABYLON.Scalar.RandomRange(this.direction1.y, this.direction2.y);
  52600. var randZ = BABYLON.Scalar.RandomRange(this.direction1.z, this.direction2.z);
  52601. BABYLON.Vector3.TransformNormalFromFloatsToRef(randX * emitPower, randY * emitPower, randZ * emitPower, worldMatrix, directionToUpdate);
  52602. };
  52603. /**
  52604. * Called by the particle System when the position is computed for the created particle.
  52605. * @param worldMatrix is the world matrix of the particle system
  52606. * @param positionToUpdate is the position vector to update with the result
  52607. * @param particle is the particle we are computed the position for
  52608. */
  52609. BoxParticleEmitter.prototype.startPositionFunction = function (worldMatrix, positionToUpdate, particle) {
  52610. var randX = BABYLON.Scalar.RandomRange(this.minEmitBox.x, this.maxEmitBox.x);
  52611. var randY = BABYLON.Scalar.RandomRange(this.minEmitBox.y, this.maxEmitBox.y);
  52612. var randZ = BABYLON.Scalar.RandomRange(this.minEmitBox.z, this.maxEmitBox.z);
  52613. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(randX, randY, randZ, worldMatrix, positionToUpdate);
  52614. };
  52615. /**
  52616. * Clones the current emitter and returns a copy of it
  52617. * @returns the new emitter
  52618. */
  52619. BoxParticleEmitter.prototype.clone = function () {
  52620. var newOne = new BoxParticleEmitter();
  52621. BABYLON.Tools.DeepCopy(this, newOne);
  52622. return newOne;
  52623. };
  52624. /**
  52625. * Called by the {BABYLON.GPUParticleSystem} to setup the update shader
  52626. * @param effect defines the update shader
  52627. */
  52628. BoxParticleEmitter.prototype.applyToShader = function (effect) {
  52629. effect.setVector3("direction1", this.direction1);
  52630. effect.setVector3("direction2", this.direction2);
  52631. effect.setVector3("minEmitBox", this.minEmitBox);
  52632. effect.setVector3("maxEmitBox", this.maxEmitBox);
  52633. };
  52634. /**
  52635. * Returns a string to use to update the GPU particles update shader
  52636. * @returns a string containng the defines string
  52637. */
  52638. BoxParticleEmitter.prototype.getEffectDefines = function () {
  52639. return "#define BOXEMITTER";
  52640. };
  52641. /**
  52642. * Returns the string "BoxEmitter"
  52643. * @returns a string containing the class name
  52644. */
  52645. BoxParticleEmitter.prototype.getClassName = function () {
  52646. return "BoxEmitter";
  52647. };
  52648. /**
  52649. * Serializes the particle system to a JSON object.
  52650. * @returns the JSON object
  52651. */
  52652. BoxParticleEmitter.prototype.serialize = function () {
  52653. var serializationObject = {};
  52654. serializationObject.type = this.getClassName();
  52655. serializationObject.direction1 = this.direction1.asArray();
  52656. ;
  52657. serializationObject.direction2 = this.direction2.asArray();
  52658. ;
  52659. serializationObject.minEmitBox = this.minEmitBox.asArray();
  52660. ;
  52661. serializationObject.maxEmitBox = this.maxEmitBox.asArray();
  52662. ;
  52663. return serializationObject;
  52664. };
  52665. /**
  52666. * Parse properties from a JSON object
  52667. * @param serializationObject defines the JSON object
  52668. */
  52669. BoxParticleEmitter.prototype.parse = function (serializationObject) {
  52670. this.direction1.copyFrom(serializationObject.direction1);
  52671. this.direction2.copyFrom(serializationObject.direction2);
  52672. this.minEmitBox.copyFrom(serializationObject.minEmitBox);
  52673. this.maxEmitBox.copyFrom(serializationObject.maxEmitBox);
  52674. };
  52675. return BoxParticleEmitter;
  52676. }());
  52677. BABYLON.BoxParticleEmitter = BoxParticleEmitter;
  52678. })(BABYLON || (BABYLON = {}));
  52679. //# sourceMappingURL=babylon.boxParticleEmitter.js.map
  52680. "use strict";
  52681. var BABYLON;
  52682. (function (BABYLON) {
  52683. /**
  52684. * Particle emitter emitting particles from the inside of a cone.
  52685. * It emits the particles alongside the cone volume from the base to the particle.
  52686. * The emission direction might be randomized.
  52687. */
  52688. var ConeParticleEmitter = /** @class */ (function () {
  52689. /**
  52690. * Creates a new instance ConeParticleEmitter
  52691. * @param radius the radius of the emission cone (1 by default)
  52692. * @param angles the cone base angle (PI by default)
  52693. * @param directionRandomizer defines how much to randomize the particle direction [0-1]
  52694. */
  52695. function ConeParticleEmitter(radius,
  52696. /**
  52697. * The radius of the emission cone.
  52698. */
  52699. angle,
  52700. /**
  52701. * The cone base angle.
  52702. */
  52703. directionRandomizer) {
  52704. if (radius === void 0) { radius = 1; }
  52705. if (angle === void 0) { angle = Math.PI; }
  52706. if (directionRandomizer === void 0) { directionRandomizer = 0; }
  52707. this.angle = angle;
  52708. this.directionRandomizer = directionRandomizer;
  52709. this.radius = radius;
  52710. }
  52711. Object.defineProperty(ConeParticleEmitter.prototype, "radius", {
  52712. /**
  52713. * Gets the radius of the emission cone.
  52714. */
  52715. get: function () {
  52716. return this._radius;
  52717. },
  52718. /**
  52719. * Sets the radius of the emission cone.
  52720. */
  52721. set: function (value) {
  52722. this._radius = value;
  52723. if (this.angle !== 0) {
  52724. this._height = value / Math.tan(this.angle / 2);
  52725. }
  52726. else {
  52727. this._height = 1;
  52728. }
  52729. },
  52730. enumerable: true,
  52731. configurable: true
  52732. });
  52733. /**
  52734. * Called by the particle System when the direction is computed for the created particle.
  52735. * @param emitPower is the power of the particle (speed)
  52736. * @param worldMatrix is the world matrix of the particle system
  52737. * @param directionToUpdate is the direction vector to update with the result
  52738. * @param particle is the particle we are computed the direction for
  52739. */
  52740. ConeParticleEmitter.prototype.startDirectionFunction = function (emitPower, worldMatrix, directionToUpdate, particle) {
  52741. if (this.angle === 0) {
  52742. BABYLON.Vector3.TransformNormalFromFloatsToRef(0, emitPower, 0, worldMatrix, directionToUpdate);
  52743. }
  52744. else {
  52745. // measure the direction Vector from the emitter to the particle.
  52746. var direction = particle.position.subtract(worldMatrix.getTranslation()).normalize();
  52747. var randX = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  52748. var randY = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  52749. var randZ = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  52750. direction.x += randX;
  52751. direction.y += randY;
  52752. direction.z += randZ;
  52753. direction.normalize();
  52754. BABYLON.Vector3.TransformNormalFromFloatsToRef(direction.x * emitPower, direction.y * emitPower, direction.z * emitPower, worldMatrix, directionToUpdate);
  52755. }
  52756. };
  52757. /**
  52758. * Called by the particle System when the position is computed for the created particle.
  52759. * @param worldMatrix is the world matrix of the particle system
  52760. * @param positionToUpdate is the position vector to update with the result
  52761. * @param particle is the particle we are computed the position for
  52762. */
  52763. ConeParticleEmitter.prototype.startPositionFunction = function (worldMatrix, positionToUpdate, particle) {
  52764. var s = BABYLON.Scalar.RandomRange(0, Math.PI * 2);
  52765. var h = BABYLON.Scalar.RandomRange(0, 1);
  52766. // Better distribution in a cone at normal angles.
  52767. h = 1 - h * h;
  52768. var radius = BABYLON.Scalar.RandomRange(0, this._radius);
  52769. radius = radius * h;
  52770. var randX = radius * Math.sin(s);
  52771. var randZ = radius * Math.cos(s);
  52772. var randY = h * this._height;
  52773. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(randX, randY, randZ, worldMatrix, positionToUpdate);
  52774. };
  52775. /**
  52776. * Clones the current emitter and returns a copy of it
  52777. * @returns the new emitter
  52778. */
  52779. ConeParticleEmitter.prototype.clone = function () {
  52780. var newOne = new ConeParticleEmitter(this.radius, this.angle, this.directionRandomizer);
  52781. BABYLON.Tools.DeepCopy(this, newOne);
  52782. return newOne;
  52783. };
  52784. /**
  52785. * Called by the {BABYLON.GPUParticleSystem} to setup the update shader
  52786. * @param effect defines the update shader
  52787. */
  52788. ConeParticleEmitter.prototype.applyToShader = function (effect) {
  52789. effect.setFloat("radius", this.radius);
  52790. effect.setFloat("angle", this.angle);
  52791. effect.setFloat("height", this._height);
  52792. effect.setFloat("directionRandomizer", this.directionRandomizer);
  52793. };
  52794. /**
  52795. * Returns a string to use to update the GPU particles update shader
  52796. * @returns a string containng the defines string
  52797. */
  52798. ConeParticleEmitter.prototype.getEffectDefines = function () {
  52799. return "#define CONEEMITTER";
  52800. };
  52801. /**
  52802. * Returns the string "BoxEmitter"
  52803. * @returns a string containing the class name
  52804. */
  52805. ConeParticleEmitter.prototype.getClassName = function () {
  52806. return "ConeEmitter";
  52807. };
  52808. /**
  52809. * Serializes the particle system to a JSON object.
  52810. * @returns the JSON object
  52811. */
  52812. ConeParticleEmitter.prototype.serialize = function () {
  52813. var serializationObject = {};
  52814. serializationObject.type = this.getClassName();
  52815. serializationObject.radius = this.radius;
  52816. serializationObject.angle = this.angle;
  52817. serializationObject.directionRandomizer = this.directionRandomizer;
  52818. return serializationObject;
  52819. };
  52820. /**
  52821. * Parse properties from a JSON object
  52822. * @param serializationObject defines the JSON object
  52823. */
  52824. ConeParticleEmitter.prototype.parse = function (serializationObject) {
  52825. this.radius = serializationObject.radius;
  52826. this.angle = serializationObject.angle;
  52827. this.directionRandomizer = serializationObject.directionRandomizer;
  52828. };
  52829. return ConeParticleEmitter;
  52830. }());
  52831. BABYLON.ConeParticleEmitter = ConeParticleEmitter;
  52832. })(BABYLON || (BABYLON = {}));
  52833. //# sourceMappingURL=babylon.coneParticleEmitter.js.map
  52834. "use strict";
  52835. var BABYLON;
  52836. (function (BABYLON) {
  52837. /**
  52838. * Particle emitter emitting particles from the inside of a sphere.
  52839. * It emits the particles alongside the sphere radius. The emission direction might be randomized.
  52840. */
  52841. var SphereParticleEmitter = /** @class */ (function () {
  52842. /**
  52843. * Creates a new instance SphereParticleEmitter
  52844. * @param radius the radius of the emission sphere (1 by default)
  52845. * @param directionRandomizer defines how much to randomize the particle direction [0-1]
  52846. */
  52847. function SphereParticleEmitter(
  52848. /**
  52849. * The radius of the emission sphere.
  52850. */
  52851. radius,
  52852. /**
  52853. * How much to randomize the particle direction [0-1].
  52854. */
  52855. directionRandomizer) {
  52856. if (radius === void 0) { radius = 1; }
  52857. if (directionRandomizer === void 0) { directionRandomizer = 0; }
  52858. this.radius = radius;
  52859. this.directionRandomizer = directionRandomizer;
  52860. }
  52861. /**
  52862. * Called by the particle System when the direction is computed for the created particle.
  52863. * @param emitPower is the power of the particle (speed)
  52864. * @param worldMatrix is the world matrix of the particle system
  52865. * @param directionToUpdate is the direction vector to update with the result
  52866. * @param particle is the particle we are computed the direction for
  52867. */
  52868. SphereParticleEmitter.prototype.startDirectionFunction = function (emitPower, worldMatrix, directionToUpdate, particle) {
  52869. var direction = particle.position.subtract(worldMatrix.getTranslation()).normalize();
  52870. var randX = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  52871. var randY = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  52872. var randZ = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  52873. direction.x += randX;
  52874. direction.y += randY;
  52875. direction.z += randZ;
  52876. direction.normalize();
  52877. BABYLON.Vector3.TransformNormalFromFloatsToRef(direction.x * emitPower, direction.y * emitPower, direction.z * emitPower, worldMatrix, directionToUpdate);
  52878. };
  52879. /**
  52880. * Called by the particle System when the position is computed for the created particle.
  52881. * @param worldMatrix is the world matrix of the particle system
  52882. * @param positionToUpdate is the position vector to update with the result
  52883. * @param particle is the particle we are computed the position for
  52884. */
  52885. SphereParticleEmitter.prototype.startPositionFunction = function (worldMatrix, positionToUpdate, particle) {
  52886. var phi = BABYLON.Scalar.RandomRange(0, 2 * Math.PI);
  52887. var theta = BABYLON.Scalar.RandomRange(0, Math.PI);
  52888. var randRadius = BABYLON.Scalar.RandomRange(0, this.radius);
  52889. var randX = randRadius * Math.cos(phi) * Math.sin(theta);
  52890. var randY = randRadius * Math.cos(theta);
  52891. var randZ = randRadius * Math.sin(phi) * Math.sin(theta);
  52892. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(randX, randY, randZ, worldMatrix, positionToUpdate);
  52893. };
  52894. /**
  52895. * Clones the current emitter and returns a copy of it
  52896. * @returns the new emitter
  52897. */
  52898. SphereParticleEmitter.prototype.clone = function () {
  52899. var newOne = new SphereParticleEmitter(this.radius, this.directionRandomizer);
  52900. BABYLON.Tools.DeepCopy(this, newOne);
  52901. return newOne;
  52902. };
  52903. /**
  52904. * Called by the {BABYLON.GPUParticleSystem} to setup the update shader
  52905. * @param effect defines the update shader
  52906. */
  52907. SphereParticleEmitter.prototype.applyToShader = function (effect) {
  52908. effect.setFloat("radius", this.radius);
  52909. effect.setFloat("directionRandomizer", this.directionRandomizer);
  52910. };
  52911. /**
  52912. * Returns a string to use to update the GPU particles update shader
  52913. * @returns a string containng the defines string
  52914. */
  52915. SphereParticleEmitter.prototype.getEffectDefines = function () {
  52916. return "#define SPHEREEMITTER";
  52917. };
  52918. /**
  52919. * Returns the string "SphereParticleEmitter"
  52920. * @returns a string containing the class name
  52921. */
  52922. SphereParticleEmitter.prototype.getClassName = function () {
  52923. return "SphereParticleEmitter";
  52924. };
  52925. /**
  52926. * Serializes the particle system to a JSON object.
  52927. * @returns the JSON object
  52928. */
  52929. SphereParticleEmitter.prototype.serialize = function () {
  52930. var serializationObject = {};
  52931. serializationObject.type = this.getClassName();
  52932. serializationObject.radius = this.radius;
  52933. serializationObject.directionRandomizer = this.directionRandomizer;
  52934. return serializationObject;
  52935. };
  52936. /**
  52937. * Parse properties from a JSON object
  52938. * @param serializationObject defines the JSON object
  52939. */
  52940. SphereParticleEmitter.prototype.parse = function (serializationObject) {
  52941. this.radius = serializationObject.radius;
  52942. this.directionRandomizer = serializationObject.directionRandomizer;
  52943. };
  52944. return SphereParticleEmitter;
  52945. }());
  52946. BABYLON.SphereParticleEmitter = SphereParticleEmitter;
  52947. /**
  52948. * Particle emitter emitting particles from the inside of a sphere.
  52949. * It emits the particles randomly between two vectors.
  52950. */
  52951. var SphereDirectedParticleEmitter = /** @class */ (function (_super) {
  52952. __extends(SphereDirectedParticleEmitter, _super);
  52953. /**
  52954. * Creates a new instance SphereDirectedParticleEmitter
  52955. * @param radius the radius of the emission sphere (1 by default)
  52956. * @param direction1 the min limit of the emission direction (up vector by default)
  52957. * @param direction2 the max limit of the emission direction (up vector by default)
  52958. */
  52959. function SphereDirectedParticleEmitter(radius,
  52960. /**
  52961. * The min limit of the emission direction.
  52962. */
  52963. direction1,
  52964. /**
  52965. * The max limit of the emission direction.
  52966. */
  52967. direction2) {
  52968. if (radius === void 0) { radius = 1; }
  52969. if (direction1 === void 0) { direction1 = new BABYLON.Vector3(0, 1, 0); }
  52970. if (direction2 === void 0) { direction2 = new BABYLON.Vector3(0, 1, 0); }
  52971. var _this = _super.call(this, radius) || this;
  52972. _this.direction1 = direction1;
  52973. _this.direction2 = direction2;
  52974. return _this;
  52975. }
  52976. /**
  52977. * Called by the particle System when the direction is computed for the created particle.
  52978. * @param emitPower is the power of the particle (speed)
  52979. * @param worldMatrix is the world matrix of the particle system
  52980. * @param directionToUpdate is the direction vector to update with the result
  52981. * @param particle is the particle we are computed the direction for
  52982. */
  52983. SphereDirectedParticleEmitter.prototype.startDirectionFunction = function (emitPower, worldMatrix, directionToUpdate, particle) {
  52984. var randX = BABYLON.Scalar.RandomRange(this.direction1.x, this.direction2.x);
  52985. var randY = BABYLON.Scalar.RandomRange(this.direction1.y, this.direction2.y);
  52986. var randZ = BABYLON.Scalar.RandomRange(this.direction1.z, this.direction2.z);
  52987. BABYLON.Vector3.TransformNormalFromFloatsToRef(randX * emitPower, randY * emitPower, randZ * emitPower, worldMatrix, directionToUpdate);
  52988. };
  52989. /**
  52990. * Clones the current emitter and returns a copy of it
  52991. * @returns the new emitter
  52992. */
  52993. SphereDirectedParticleEmitter.prototype.clone = function () {
  52994. var newOne = new SphereDirectedParticleEmitter(this.radius, this.direction1, this.direction2);
  52995. BABYLON.Tools.DeepCopy(this, newOne);
  52996. return newOne;
  52997. };
  52998. /**
  52999. * Called by the {BABYLON.GPUParticleSystem} to setup the update shader
  53000. * @param effect defines the update shader
  53001. */
  53002. SphereDirectedParticleEmitter.prototype.applyToShader = function (effect) {
  53003. effect.setFloat("radius", this.radius);
  53004. effect.setVector3("direction1", this.direction1);
  53005. effect.setVector3("direction2", this.direction2);
  53006. };
  53007. /**
  53008. * Returns a string to use to update the GPU particles update shader
  53009. * @returns a string containng the defines string
  53010. */
  53011. SphereDirectedParticleEmitter.prototype.getEffectDefines = function () {
  53012. return "#define SPHEREEMITTER\n#define DIRECTEDSPHEREEMITTER";
  53013. };
  53014. /**
  53015. * Returns the string "SphereDirectedParticleEmitter"
  53016. * @returns a string containing the class name
  53017. */
  53018. SphereDirectedParticleEmitter.prototype.getClassName = function () {
  53019. return "SphereDirectedParticleEmitter";
  53020. };
  53021. /**
  53022. * Serializes the particle system to a JSON object.
  53023. * @returns the JSON object
  53024. */
  53025. SphereDirectedParticleEmitter.prototype.serialize = function () {
  53026. var serializationObject = _super.prototype.serialize.call(this);
  53027. ;
  53028. serializationObject.direction1 = this.direction1.asArray();
  53029. ;
  53030. serializationObject.direction2 = this.direction2.asArray();
  53031. ;
  53032. return serializationObject;
  53033. };
  53034. /**
  53035. * Parse properties from a JSON object
  53036. * @param serializationObject defines the JSON object
  53037. */
  53038. SphereDirectedParticleEmitter.prototype.parse = function (serializationObject) {
  53039. _super.prototype.parse.call(this, serializationObject);
  53040. this.direction1.copyFrom(serializationObject.direction1);
  53041. this.direction2.copyFrom(serializationObject.direction2);
  53042. };
  53043. return SphereDirectedParticleEmitter;
  53044. }(SphereParticleEmitter));
  53045. BABYLON.SphereDirectedParticleEmitter = SphereDirectedParticleEmitter;
  53046. })(BABYLON || (BABYLON = {}));
  53047. //# sourceMappingURL=babylon.sphereParticleEmitter.js.map
  53048. "use strict";
  53049. var __assign = (this && this.__assign) || Object.assign || function(t) {
  53050. for (var s, i = 1, n = arguments.length; i < n; i++) {
  53051. s = arguments[i];
  53052. for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
  53053. t[p] = s[p];
  53054. }
  53055. return t;
  53056. };
  53057. var BABYLON;
  53058. (function (BABYLON) {
  53059. /**
  53060. * This represents a GPU particle system in Babylon
  53061. * This is the fastest particle system in Babylon as it uses the GPU to update the individual particle data
  53062. * @see https://www.babylonjs-playground.com/#PU4WYI#4
  53063. */
  53064. var GPUParticleSystem = /** @class */ (function () {
  53065. /**
  53066. * Instantiates a GPU particle system.
  53067. * 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.
  53068. * @param name The name of the particle system
  53069. * @param capacity The max number of particles alive at the same time
  53070. * @param scene The scene the particle system belongs to
  53071. */
  53072. function GPUParticleSystem(name, options, scene) {
  53073. /**
  53074. * The emitter represents the Mesh or position we are attaching the particle system to.
  53075. */
  53076. this.emitter = null;
  53077. /**
  53078. * The rendering group used by the Particle system to chose when to render.
  53079. */
  53080. this.renderingGroupId = 0;
  53081. /**
  53082. * The layer mask we are rendering the particles through.
  53083. */
  53084. this.layerMask = 0x0FFFFFFF;
  53085. this._targetIndex = 0;
  53086. this._currentRenderId = -1;
  53087. this._started = false;
  53088. this._stopped = false;
  53089. this._timeDelta = 0;
  53090. this._attributesStrideSize = 14;
  53091. this._actualFrame = 0;
  53092. /**
  53093. * List of animations used by the particle system.
  53094. */
  53095. this.animations = [];
  53096. /**
  53097. * An event triggered when the system is disposed.
  53098. */
  53099. this.onDisposeObservable = new BABYLON.Observable();
  53100. /**
  53101. * The overall motion speed (0.01 is default update speed, faster updates = faster animation)
  53102. */
  53103. this.updateSpeed = 0.01;
  53104. /**
  53105. * The amount of time the particle system is running (depends of the overall update speed).
  53106. */
  53107. this.targetStopDuration = 0;
  53108. /**
  53109. * Blend mode use to render the particle, it can be either ParticleSystem.BLENDMODE_ONEONE or ParticleSystem.BLENDMODE_STANDARD.
  53110. */
  53111. this.blendMode = BABYLON.ParticleSystem.BLENDMODE_ONEONE;
  53112. /**
  53113. * Minimum life time of emitting particles.
  53114. */
  53115. this.minLifeTime = 1;
  53116. /**
  53117. * Maximum life time of emitting particles.
  53118. */
  53119. this.maxLifeTime = 1;
  53120. /**
  53121. * Minimum Size of emitting particles.
  53122. */
  53123. this.minSize = 1;
  53124. /**
  53125. * Maximum Size of emitting particles.
  53126. */
  53127. this.maxSize = 1;
  53128. /**
  53129. * Random color of each particle after it has been emitted, between color1 and color2 vectors.
  53130. */
  53131. this.color1 = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  53132. /**
  53133. * Random color of each particle after it has been emitted, between color1 and color2 vectors.
  53134. */
  53135. this.color2 = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  53136. /**
  53137. * Color the particle will have at the end of its lifetime.
  53138. */
  53139. this.colorDead = new BABYLON.Color4(0, 0, 0, 0);
  53140. /**
  53141. * The maximum number of particles to emit per frame until we reach the activeParticleCount value
  53142. */
  53143. this.emitRate = 100;
  53144. /**
  53145. * You can use gravity if you want to give an orientation to your particles.
  53146. */
  53147. this.gravity = BABYLON.Vector3.Zero();
  53148. /**
  53149. * Minimum power of emitting particles.
  53150. */
  53151. this.minEmitPower = 1;
  53152. /**
  53153. * Maximum power of emitting particles.
  53154. */
  53155. this.maxEmitPower = 1;
  53156. /**
  53157. * Forces the particle to write their depth information to the depth buffer. This can help preventing other draw calls
  53158. * to override the particles.
  53159. */
  53160. this.forceDepthWrite = false;
  53161. this.id = name;
  53162. this.name = name;
  53163. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  53164. this._engine = this._scene.getEngine();
  53165. var fullOptions = __assign({ capacity: 50000, randomTextureSize: this._engine.getCaps().maxTextureSize }, options);
  53166. this._capacity = fullOptions.capacity;
  53167. this._activeCount = fullOptions.capacity;
  53168. this._currentActiveCount = 0;
  53169. this._scene.particleSystems.push(this);
  53170. this._updateEffectOptions = {
  53171. attributes: ["position", "age", "life", "seed", "size", "color", "direction"],
  53172. uniformsNames: ["currentCount", "timeDelta", "generalRandoms", "emitterWM", "lifeTime", "color1", "color2", "sizeRange", "gravity", "emitPower",
  53173. "direction1", "direction2", "minEmitBox", "maxEmitBox", "radius", "directionRandomizer", "height", "angle", "stopFactor"],
  53174. uniformBuffersNames: [],
  53175. samplers: ["randomSampler"],
  53176. defines: "",
  53177. fallbacks: null,
  53178. onCompiled: null,
  53179. onError: null,
  53180. indexParameters: null,
  53181. maxSimultaneousLights: 0,
  53182. transformFeedbackVaryings: ["outPosition", "outAge", "outLife", "outSeed", "outSize", "outColor", "outDirection"]
  53183. };
  53184. // Random data
  53185. var maxTextureSize = Math.min(this._engine.getCaps().maxTextureSize, fullOptions.randomTextureSize);
  53186. var d = [];
  53187. for (var i = 0; i < maxTextureSize; ++i) {
  53188. d.push(Math.random());
  53189. d.push(Math.random());
  53190. d.push(Math.random());
  53191. d.push(Math.random());
  53192. }
  53193. 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);
  53194. this._randomTexture.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  53195. this._randomTexture.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  53196. this._randomTextureSize = maxTextureSize;
  53197. this.particleEmitterType = new BABYLON.BoxParticleEmitter();
  53198. }
  53199. Object.defineProperty(GPUParticleSystem, "IsSupported", {
  53200. /**
  53201. * Gets a boolean indicating if the GPU particles can be rendered on current browser
  53202. */
  53203. get: function () {
  53204. if (!BABYLON.Engine.LastCreatedEngine) {
  53205. return false;
  53206. }
  53207. return BABYLON.Engine.LastCreatedEngine.webGLVersion > 1;
  53208. },
  53209. enumerable: true,
  53210. configurable: true
  53211. });
  53212. Object.defineProperty(GPUParticleSystem.prototype, "direction1", {
  53213. /**
  53214. * Random direction of each particle after it has been emitted, between direction1 and direction2 vectors.
  53215. * This only works when particleEmitterTyps is a BoxParticleEmitter
  53216. */
  53217. get: function () {
  53218. if (this.particleEmitterType.direction1) {
  53219. return this.particleEmitterType.direction1;
  53220. }
  53221. return BABYLON.Vector3.Zero();
  53222. },
  53223. set: function (value) {
  53224. if (this.particleEmitterType.direction1) {
  53225. this.particleEmitterType.direction1 = value;
  53226. }
  53227. },
  53228. enumerable: true,
  53229. configurable: true
  53230. });
  53231. Object.defineProperty(GPUParticleSystem.prototype, "direction2", {
  53232. /**
  53233. * Random direction of each particle after it has been emitted, between direction1 and direction2 vectors.
  53234. * This only works when particleEmitterTyps is a BoxParticleEmitter
  53235. */
  53236. get: function () {
  53237. if (this.particleEmitterType.direction2) {
  53238. return this.particleEmitterType.direction2;
  53239. }
  53240. return BABYLON.Vector3.Zero();
  53241. },
  53242. set: function (value) {
  53243. if (this.particleEmitterType.direction2) {
  53244. this.particleEmitterType.direction2 = value;
  53245. }
  53246. },
  53247. enumerable: true,
  53248. configurable: true
  53249. });
  53250. Object.defineProperty(GPUParticleSystem.prototype, "minEmitBox", {
  53251. /**
  53252. * 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.
  53253. * This only works when particleEmitterTyps is a BoxParticleEmitter
  53254. */
  53255. get: function () {
  53256. if (this.particleEmitterType.minEmitBox) {
  53257. return this.particleEmitterType.minEmitBox;
  53258. }
  53259. return BABYLON.Vector3.Zero();
  53260. },
  53261. set: function (value) {
  53262. if (this.particleEmitterType.minEmitBox) {
  53263. this.particleEmitterType.minEmitBox = value;
  53264. }
  53265. },
  53266. enumerable: true,
  53267. configurable: true
  53268. });
  53269. Object.defineProperty(GPUParticleSystem.prototype, "maxEmitBox", {
  53270. /**
  53271. * 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.
  53272. * This only works when particleEmitterTyps is a BoxParticleEmitter
  53273. */
  53274. get: function () {
  53275. if (this.particleEmitterType.maxEmitBox) {
  53276. return this.particleEmitterType.maxEmitBox;
  53277. }
  53278. return BABYLON.Vector3.Zero();
  53279. },
  53280. set: function (value) {
  53281. if (this.particleEmitterType.maxEmitBox) {
  53282. this.particleEmitterType.maxEmitBox = value;
  53283. }
  53284. },
  53285. enumerable: true,
  53286. configurable: true
  53287. });
  53288. /**
  53289. * Gets the maximum number of particles active at the same time.
  53290. * @returns The max number of active particles.
  53291. */
  53292. GPUParticleSystem.prototype.getCapacity = function () {
  53293. return this._capacity;
  53294. };
  53295. Object.defineProperty(GPUParticleSystem.prototype, "activeParticleCount", {
  53296. /**
  53297. * Gets or set the number of active particles
  53298. */
  53299. get: function () {
  53300. return this._activeCount;
  53301. },
  53302. set: function (value) {
  53303. this._activeCount = Math.min(value, this._capacity);
  53304. },
  53305. enumerable: true,
  53306. configurable: true
  53307. });
  53308. /**
  53309. * Is this system ready to be used/rendered
  53310. * @return true if the system is ready
  53311. */
  53312. GPUParticleSystem.prototype.isReady = function () {
  53313. if (!this._updateEffect) {
  53314. this._recreateUpdateEffect();
  53315. this._recreateRenderEffect();
  53316. return false;
  53317. }
  53318. if (!this.emitter || !this._updateEffect.isReady() || !this._renderEffect.isReady() || !this.particleTexture || !this.particleTexture.isReady()) {
  53319. return false;
  53320. }
  53321. return true;
  53322. };
  53323. /**
  53324. * Gets Wether the system has been started.
  53325. * @returns True if it has been started, otherwise false.
  53326. */
  53327. GPUParticleSystem.prototype.isStarted = function () {
  53328. return this._started;
  53329. };
  53330. /**
  53331. * Starts the particle system and begins to emit.
  53332. */
  53333. GPUParticleSystem.prototype.start = function () {
  53334. this._started = true;
  53335. this._stopped = false;
  53336. };
  53337. /**
  53338. * Stops the particle system.
  53339. */
  53340. GPUParticleSystem.prototype.stop = function () {
  53341. this._stopped = true;
  53342. };
  53343. /**
  53344. * Remove all active particles
  53345. */
  53346. GPUParticleSystem.prototype.reset = function () {
  53347. this._releaseBuffers();
  53348. this._releaseVAOs();
  53349. this._currentActiveCount = 0;
  53350. this._targetIndex = 0;
  53351. };
  53352. /**
  53353. * Returns the string "GPUParticleSystem"
  53354. * @returns a string containing the class name
  53355. */
  53356. GPUParticleSystem.prototype.getClassName = function () {
  53357. return "GPUParticleSystem";
  53358. };
  53359. GPUParticleSystem.prototype._createUpdateVAO = function (source) {
  53360. var updateVertexBuffers = {};
  53361. updateVertexBuffers["position"] = source.createVertexBuffer("position", 0, 3);
  53362. updateVertexBuffers["age"] = source.createVertexBuffer("age", 3, 1);
  53363. updateVertexBuffers["life"] = source.createVertexBuffer("life", 4, 1);
  53364. updateVertexBuffers["seed"] = source.createVertexBuffer("seed", 5, 1);
  53365. updateVertexBuffers["size"] = source.createVertexBuffer("size", 6, 1);
  53366. updateVertexBuffers["color"] = source.createVertexBuffer("color", 7, 4);
  53367. updateVertexBuffers["direction"] = source.createVertexBuffer("direction", 11, 3);
  53368. var vao = this._engine.recordVertexArrayObject(updateVertexBuffers, null, this._updateEffect);
  53369. this._engine.bindArrayBuffer(null);
  53370. return vao;
  53371. };
  53372. GPUParticleSystem.prototype._createRenderVAO = function (source, spriteSource) {
  53373. var renderVertexBuffers = {};
  53374. renderVertexBuffers["position"] = source.createVertexBuffer("position", 0, 3, this._attributesStrideSize, true);
  53375. renderVertexBuffers["age"] = source.createVertexBuffer("age", 3, 1, this._attributesStrideSize, true);
  53376. renderVertexBuffers["life"] = source.createVertexBuffer("life", 4, 1, this._attributesStrideSize, true);
  53377. renderVertexBuffers["size"] = source.createVertexBuffer("size", 6, 1, this._attributesStrideSize, true);
  53378. renderVertexBuffers["color"] = source.createVertexBuffer("color", 7, 4, this._attributesStrideSize, true);
  53379. renderVertexBuffers["offset"] = spriteSource.createVertexBuffer("offset", 0, 2);
  53380. renderVertexBuffers["uv"] = spriteSource.createVertexBuffer("uv", 2, 2);
  53381. var vao = this._engine.recordVertexArrayObject(renderVertexBuffers, null, this._renderEffect);
  53382. this._engine.bindArrayBuffer(null);
  53383. return vao;
  53384. };
  53385. GPUParticleSystem.prototype._initialize = function (force) {
  53386. if (force === void 0) { force = false; }
  53387. if (this._buffer0 && !force) {
  53388. return;
  53389. }
  53390. var engine = this._scene.getEngine();
  53391. var data = new Array();
  53392. for (var particleIndex = 0; particleIndex < this._capacity; particleIndex++) {
  53393. // position
  53394. data.push(0.0);
  53395. data.push(0.0);
  53396. data.push(0.0);
  53397. // Age and life
  53398. data.push(0.0); // create the particle as a dead one to create a new one at start
  53399. data.push(0.0);
  53400. // Seed
  53401. data.push(Math.random());
  53402. // Size
  53403. data.push(0.0);
  53404. // color
  53405. data.push(0.0);
  53406. data.push(0.0);
  53407. data.push(0.0);
  53408. data.push(0.0);
  53409. // direction
  53410. data.push(0.0);
  53411. data.push(0.0);
  53412. data.push(0.0);
  53413. }
  53414. // Sprite data
  53415. var spriteData = new Float32Array([0.5, 0.5, 1, 1,
  53416. -0.5, 0.5, 0, 1,
  53417. -0.5, -0.5, 0, 0,
  53418. 0.5, -0.5, 1, 0]);
  53419. // Buffers
  53420. this._buffer0 = new BABYLON.Buffer(engine, data, false, this._attributesStrideSize);
  53421. this._buffer1 = new BABYLON.Buffer(engine, data, false, this._attributesStrideSize);
  53422. this._spriteBuffer = new BABYLON.Buffer(engine, spriteData, false, 4);
  53423. // Update VAO
  53424. this._updateVAO = [];
  53425. this._updateVAO.push(this._createUpdateVAO(this._buffer0));
  53426. this._updateVAO.push(this._createUpdateVAO(this._buffer1));
  53427. // Render VAO
  53428. this._renderVAO = [];
  53429. this._renderVAO.push(this._createRenderVAO(this._buffer1, this._spriteBuffer));
  53430. this._renderVAO.push(this._createRenderVAO(this._buffer0, this._spriteBuffer));
  53431. // Links
  53432. this._sourceBuffer = this._buffer0;
  53433. this._targetBuffer = this._buffer1;
  53434. };
  53435. /** @ignore */
  53436. GPUParticleSystem.prototype._recreateUpdateEffect = function () {
  53437. var defines = this.particleEmitterType ? this.particleEmitterType.getEffectDefines() : "";
  53438. if (this._updateEffect && this._updateEffectOptions.defines === defines) {
  53439. return;
  53440. }
  53441. this._updateEffectOptions.defines = defines;
  53442. this._updateEffect = new BABYLON.Effect("gpuUpdateParticles", this._updateEffectOptions, this._scene.getEngine());
  53443. };
  53444. /** @ignore */
  53445. GPUParticleSystem.prototype._recreateRenderEffect = function () {
  53446. var defines = "";
  53447. if (this._scene.clipPlane) {
  53448. defines = "\n#define CLIPPLANE";
  53449. }
  53450. if (this._renderEffect && this._renderEffect.defines === defines) {
  53451. return;
  53452. }
  53453. this._renderEffect = new BABYLON.Effect("gpuRenderParticles", ["position", "age", "life", "size", "color", "offset", "uv"], ["view", "projection", "colorDead", "invView", "vClipPlane"], ["textureSampler"], this._scene.getEngine(), defines);
  53454. };
  53455. /**
  53456. * Animates the particle system for the current frame by emitting new particles and or animating the living ones.
  53457. */
  53458. GPUParticleSystem.prototype.animate = function () {
  53459. this._timeDelta = this.updateSpeed * this._scene.getAnimationRatio();
  53460. this._actualFrame += this._timeDelta;
  53461. if (!this._stopped) {
  53462. if (this.targetStopDuration && this._actualFrame >= this.targetStopDuration) {
  53463. this.stop();
  53464. }
  53465. }
  53466. };
  53467. /**
  53468. * Renders the particle system in its current state.
  53469. * @returns the current number of particles
  53470. */
  53471. GPUParticleSystem.prototype.render = function () {
  53472. if (!this._started) {
  53473. return 0;
  53474. }
  53475. this._recreateUpdateEffect();
  53476. this._recreateRenderEffect();
  53477. if (!this.isReady()) {
  53478. return 0;
  53479. }
  53480. if (this._currentRenderId === this._scene.getRenderId()) {
  53481. return 0;
  53482. }
  53483. this._currentRenderId = this._scene.getRenderId();
  53484. // Get everything ready to render
  53485. this._initialize();
  53486. this._currentActiveCount = Math.min(this._activeCount, this._currentActiveCount + (this.emitRate * this._timeDelta) | 0);
  53487. // Enable update effect
  53488. this._engine.enableEffect(this._updateEffect);
  53489. this._engine.setState(false);
  53490. this._updateEffect.setFloat("currentCount", this._currentActiveCount);
  53491. this._updateEffect.setFloat("timeDelta", this._timeDelta);
  53492. this._updateEffect.setFloat("stopFactor", this._stopped ? 0 : 1);
  53493. this._updateEffect.setFloat3("generalRandoms", Math.random(), Math.random(), Math.random());
  53494. this._updateEffect.setTexture("randomSampler", this._randomTexture);
  53495. this._updateEffect.setFloat2("lifeTime", this.minLifeTime, this.maxLifeTime);
  53496. this._updateEffect.setFloat2("emitPower", this.minEmitPower, this.maxEmitPower);
  53497. this._updateEffect.setDirectColor4("color1", this.color1);
  53498. this._updateEffect.setDirectColor4("color2", this.color2);
  53499. this._updateEffect.setFloat2("sizeRange", this.minSize, this.maxSize);
  53500. this._updateEffect.setVector3("gravity", this.gravity);
  53501. if (this.particleEmitterType) {
  53502. this.particleEmitterType.applyToShader(this._updateEffect);
  53503. }
  53504. var emitterWM;
  53505. if (this.emitter.position) {
  53506. var emitterMesh = this.emitter;
  53507. emitterWM = emitterMesh.getWorldMatrix();
  53508. }
  53509. else {
  53510. var emitterPosition = this.emitter;
  53511. emitterWM = BABYLON.Matrix.Translation(emitterPosition.x, emitterPosition.y, emitterPosition.z);
  53512. }
  53513. this._updateEffect.setMatrix("emitterWM", emitterWM);
  53514. // Bind source VAO
  53515. this._engine.bindVertexArrayObject(this._updateVAO[this._targetIndex], null);
  53516. // Update
  53517. this._engine.bindTransformFeedbackBuffer(this._targetBuffer.getBuffer());
  53518. this._engine.setRasterizerState(false);
  53519. this._engine.beginTransformFeedback();
  53520. this._engine.drawArraysType(BABYLON.Material.PointListDrawMode, 0, this._currentActiveCount);
  53521. this._engine.endTransformFeedback();
  53522. this._engine.setRasterizerState(true);
  53523. this._engine.bindTransformFeedbackBuffer(null);
  53524. // Enable render effect
  53525. this._engine.enableEffect(this._renderEffect);
  53526. var viewMatrix = this._scene.getViewMatrix();
  53527. this._renderEffect.setMatrix("view", viewMatrix);
  53528. this._renderEffect.setMatrix("projection", this._scene.getProjectionMatrix());
  53529. this._renderEffect.setTexture("textureSampler", this.particleTexture);
  53530. this._renderEffect.setDirectColor4("colorDead", this.colorDead);
  53531. if (this._scene.clipPlane) {
  53532. var clipPlane = this._scene.clipPlane;
  53533. var invView = viewMatrix.clone();
  53534. invView.invert();
  53535. this._renderEffect.setMatrix("invView", invView);
  53536. this._renderEffect.setFloat4("vClipPlane", clipPlane.normal.x, clipPlane.normal.y, clipPlane.normal.z, clipPlane.d);
  53537. }
  53538. // Draw order
  53539. if (this.blendMode === BABYLON.ParticleSystem.BLENDMODE_ONEONE) {
  53540. this._engine.setAlphaMode(BABYLON.Engine.ALPHA_ONEONE);
  53541. }
  53542. else {
  53543. this._engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  53544. }
  53545. if (this.forceDepthWrite) {
  53546. this._engine.setDepthWrite(true);
  53547. }
  53548. // Bind source VAO
  53549. this._engine.bindVertexArrayObject(this._renderVAO[this._targetIndex], null);
  53550. // Render
  53551. this._engine.drawArraysType(BABYLON.Material.TriangleFanDrawMode, 0, 4, this._currentActiveCount);
  53552. this._engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  53553. // Switch VAOs
  53554. this._targetIndex++;
  53555. if (this._targetIndex === 2) {
  53556. this._targetIndex = 0;
  53557. }
  53558. // Switch buffers
  53559. var tmpBuffer = this._sourceBuffer;
  53560. this._sourceBuffer = this._targetBuffer;
  53561. this._targetBuffer = tmpBuffer;
  53562. return this._currentActiveCount;
  53563. };
  53564. /**
  53565. * Rebuilds the particle system
  53566. */
  53567. GPUParticleSystem.prototype.rebuild = function () {
  53568. this._initialize(true);
  53569. };
  53570. GPUParticleSystem.prototype._releaseBuffers = function () {
  53571. if (this._buffer0) {
  53572. this._buffer0.dispose();
  53573. this._buffer0 = null;
  53574. }
  53575. if (this._buffer1) {
  53576. this._buffer1.dispose();
  53577. this._buffer1 = null;
  53578. }
  53579. if (this._spriteBuffer) {
  53580. this._spriteBuffer.dispose();
  53581. this._spriteBuffer = null;
  53582. }
  53583. };
  53584. GPUParticleSystem.prototype._releaseVAOs = function () {
  53585. if (!this._updateVAO) {
  53586. return;
  53587. }
  53588. for (var index = 0; index < this._updateVAO.length; index++) {
  53589. this._engine.releaseVertexArrayObject(this._updateVAO[index]);
  53590. }
  53591. this._updateVAO = [];
  53592. for (var index = 0; index < this._renderVAO.length; index++) {
  53593. this._engine.releaseVertexArrayObject(this._renderVAO[index]);
  53594. }
  53595. this._renderVAO = [];
  53596. };
  53597. /**
  53598. * Disposes the particle system and free the associated resources
  53599. * @param disposeTexture defines if the particule texture must be disposed as well (true by default)
  53600. */
  53601. GPUParticleSystem.prototype.dispose = function (disposeTexture) {
  53602. if (disposeTexture === void 0) { disposeTexture = true; }
  53603. var index = this._scene.particleSystems.indexOf(this);
  53604. if (index > -1) {
  53605. this._scene.particleSystems.splice(index, 1);
  53606. }
  53607. this._releaseBuffers();
  53608. this._releaseVAOs();
  53609. if (this._randomTexture) {
  53610. this._randomTexture.dispose();
  53611. this._randomTexture = null;
  53612. }
  53613. if (disposeTexture && this.particleTexture) {
  53614. this.particleTexture.dispose();
  53615. this.particleTexture = null;
  53616. }
  53617. // Callback
  53618. this.onDisposeObservable.notifyObservers(this);
  53619. this.onDisposeObservable.clear();
  53620. };
  53621. /**
  53622. * Clones the particle system.
  53623. * @param name The name of the cloned object
  53624. * @param newEmitter The new emitter to use
  53625. * @returns the cloned particle system
  53626. */
  53627. GPUParticleSystem.prototype.clone = function (name, newEmitter) {
  53628. var result = new GPUParticleSystem(name, { capacity: this._capacity, randomTextureSize: this._randomTextureSize }, this._scene);
  53629. BABYLON.Tools.DeepCopy(this, result);
  53630. if (newEmitter === undefined) {
  53631. newEmitter = this.emitter;
  53632. }
  53633. result.emitter = newEmitter;
  53634. if (this.particleTexture) {
  53635. result.particleTexture = new BABYLON.Texture(this.particleTexture.url, this._scene);
  53636. }
  53637. return result;
  53638. };
  53639. /**
  53640. * Serializes the particle system to a JSON object.
  53641. * @returns the JSON object
  53642. */
  53643. GPUParticleSystem.prototype.serialize = function () {
  53644. var serializationObject = {};
  53645. serializationObject.name = this.name;
  53646. serializationObject.id = this.id;
  53647. // Emitter
  53648. if (this.emitter.position) {
  53649. var emitterMesh = this.emitter;
  53650. serializationObject.emitterId = emitterMesh.id;
  53651. }
  53652. else {
  53653. var emitterPosition = this.emitter;
  53654. serializationObject.emitter = emitterPosition.asArray();
  53655. }
  53656. serializationObject.capacity = this.getCapacity();
  53657. if (this.particleTexture) {
  53658. serializationObject.textureName = this.particleTexture.name;
  53659. }
  53660. // Animations
  53661. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  53662. // Particle system
  53663. serializationObject.activeParticleCount = this.activeParticleCount;
  53664. serializationObject.randomTextureSize = this._randomTextureSize;
  53665. serializationObject.minSize = this.minSize;
  53666. serializationObject.maxSize = this.maxSize;
  53667. serializationObject.minEmitPower = this.minEmitPower;
  53668. serializationObject.maxEmitPower = this.maxEmitPower;
  53669. serializationObject.minLifeTime = this.minLifeTime;
  53670. serializationObject.maxLifeTime = this.maxLifeTime;
  53671. serializationObject.emitRate = this.emitRate;
  53672. serializationObject.gravity = this.gravity.asArray();
  53673. serializationObject.color1 = this.color1.asArray();
  53674. serializationObject.color2 = this.color2.asArray();
  53675. serializationObject.colorDead = this.colorDead.asArray();
  53676. serializationObject.updateSpeed = this.updateSpeed;
  53677. serializationObject.targetStopDuration = this.targetStopDuration;
  53678. serializationObject.blendMode = this.blendMode;
  53679. // Emitter
  53680. if (this.particleEmitterType) {
  53681. serializationObject.particleEmitterType = this.particleEmitterType.serialize();
  53682. }
  53683. return serializationObject;
  53684. };
  53685. /**
  53686. * Parses a JSON object to create a GPU particle system.
  53687. * @param parsedParticleSystem The JSON object to parse
  53688. * @param scene The scene to create the particle system in
  53689. * @param rootUrl The root url to use to load external dependencies like texture
  53690. * @returns the parsed GPU particle system
  53691. */
  53692. GPUParticleSystem.Parse = function (parsedParticleSystem, scene, rootUrl) {
  53693. var name = parsedParticleSystem.name;
  53694. var particleSystem = new GPUParticleSystem(name, { capacity: parsedParticleSystem.capacity, randomTextureSize: parsedParticleSystem.randomTextureSize }, scene);
  53695. if (parsedParticleSystem.id) {
  53696. particleSystem.id = parsedParticleSystem.id;
  53697. }
  53698. // Texture
  53699. if (parsedParticleSystem.textureName) {
  53700. particleSystem.particleTexture = new BABYLON.Texture(rootUrl + parsedParticleSystem.textureName, scene);
  53701. particleSystem.particleTexture.name = parsedParticleSystem.textureName;
  53702. }
  53703. // Emitter
  53704. if (parsedParticleSystem.emitterId) {
  53705. particleSystem.emitter = scene.getLastMeshByID(parsedParticleSystem.emitterId);
  53706. }
  53707. else {
  53708. particleSystem.emitter = BABYLON.Vector3.FromArray(parsedParticleSystem.emitter);
  53709. }
  53710. // Animations
  53711. if (parsedParticleSystem.animations) {
  53712. for (var animationIndex = 0; animationIndex < parsedParticleSystem.animations.length; animationIndex++) {
  53713. var parsedAnimation = parsedParticleSystem.animations[animationIndex];
  53714. particleSystem.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  53715. }
  53716. }
  53717. // Particle system
  53718. particleSystem.activeParticleCount = parsedParticleSystem.activeParticleCount;
  53719. particleSystem.minSize = parsedParticleSystem.minSize;
  53720. particleSystem.maxSize = parsedParticleSystem.maxSize;
  53721. particleSystem.minLifeTime = parsedParticleSystem.minLifeTime;
  53722. particleSystem.maxLifeTime = parsedParticleSystem.maxLifeTime;
  53723. particleSystem.minEmitPower = parsedParticleSystem.minEmitPower;
  53724. particleSystem.maxEmitPower = parsedParticleSystem.maxEmitPower;
  53725. particleSystem.emitRate = parsedParticleSystem.emitRate;
  53726. particleSystem.gravity = BABYLON.Vector3.FromArray(parsedParticleSystem.gravity);
  53727. particleSystem.color1 = BABYLON.Color4.FromArray(parsedParticleSystem.color1);
  53728. particleSystem.color2 = BABYLON.Color4.FromArray(parsedParticleSystem.color2);
  53729. particleSystem.colorDead = BABYLON.Color4.FromArray(parsedParticleSystem.colorDead);
  53730. particleSystem.updateSpeed = parsedParticleSystem.updateSpeed;
  53731. particleSystem.targetStopDuration = parsedParticleSystem.targetStopDuration;
  53732. particleSystem.blendMode = parsedParticleSystem.blendMode;
  53733. // Emitter
  53734. if (parsedParticleSystem.particleEmitterType) {
  53735. var emitterType = void 0;
  53736. switch (parsedParticleSystem.particleEmitterType.type) {
  53737. case "SphereEmitter":
  53738. emitterType = new BABYLON.SphereParticleEmitter();
  53739. break;
  53740. case "SphereDirectedParticleEmitter":
  53741. emitterType = new BABYLON.SphereDirectedParticleEmitter();
  53742. break;
  53743. case "ConeEmitter":
  53744. emitterType = new BABYLON.ConeParticleEmitter();
  53745. break;
  53746. case "BoxEmitter":
  53747. default:
  53748. emitterType = new BABYLON.BoxParticleEmitter();
  53749. break;
  53750. }
  53751. emitterType.parse(parsedParticleSystem.particleEmitterType);
  53752. particleSystem.particleEmitterType = emitterType;
  53753. }
  53754. return particleSystem;
  53755. };
  53756. return GPUParticleSystem;
  53757. }());
  53758. BABYLON.GPUParticleSystem = GPUParticleSystem;
  53759. })(BABYLON || (BABYLON = {}));
  53760. //# sourceMappingURL=babylon.gpuParticleSystem.js.map
  53761. "use strict";
  53762. var BABYLON;
  53763. (function (BABYLON) {
  53764. /**
  53765. * Represents one particle of a solid particle system.
  53766. */
  53767. var SolidParticle = /** @class */ (function () {
  53768. /**
  53769. * Creates a Solid Particle object.
  53770. * Don't create particles manually, use instead the Solid Particle System internal tools like _addParticle()
  53771. * @param particleIndex (integer) is the particle index in the Solid Particle System pool. It's also the particle identifier.
  53772. * @param positionIndex (integer) is the starting index of the particle vertices in the SPS "positions" array.
  53773. * @param indiceIndex (integer) is the starting index of the particle indices in the SPS "indices" array.
  53774. * @param model (ModelShape) is a reference to the model shape on what the particle is designed.
  53775. * @param shapeId (integer) is the model shape identifier in the SPS.
  53776. * @param idxInShape (integer) is the index of the particle in the current model (ex: the 10th box of addShape(box, 30))
  53777. * @param modelBoundingInfo is the reference to the model BoundingInfo used for intersection computations.
  53778. */
  53779. function SolidParticle(particleIndex, positionIndex, indiceIndex, model, shapeId, idxInShape, sps, modelBoundingInfo) {
  53780. if (modelBoundingInfo === void 0) { modelBoundingInfo = null; }
  53781. /**
  53782. * particle global index
  53783. */
  53784. this.idx = 0;
  53785. /**
  53786. * The color of the particle
  53787. */
  53788. this.color = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  53789. /**
  53790. * The world space position of the particle.
  53791. */
  53792. this.position = BABYLON.Vector3.Zero();
  53793. /**
  53794. * The world space rotation of the particle. (Not use if rotationQuaternion is set)
  53795. */
  53796. this.rotation = BABYLON.Vector3.Zero();
  53797. /**
  53798. * The scaling of the particle.
  53799. */
  53800. this.scaling = BABYLON.Vector3.One();
  53801. /**
  53802. * The uvs of the particle.
  53803. */
  53804. this.uvs = new BABYLON.Vector4(0.0, 0.0, 1.0, 1.0);
  53805. /**
  53806. * The current speed of the particle.
  53807. */
  53808. this.velocity = BABYLON.Vector3.Zero();
  53809. /**
  53810. * The pivot point in the particle local space.
  53811. */
  53812. this.pivot = BABYLON.Vector3.Zero();
  53813. /**
  53814. * Must the particle be translated from its pivot point in its local space ?
  53815. * In this case, the pivot point is set at the origin of the particle local space and the particle is translated.
  53816. * Default : false
  53817. */
  53818. this.translateFromPivot = false;
  53819. /**
  53820. * Is the particle active or not ?
  53821. */
  53822. this.alive = true;
  53823. /**
  53824. * Is the particle visible or not ?
  53825. */
  53826. this.isVisible = true;
  53827. /**
  53828. * Index of this particle in the global "positions" array (Internal use)
  53829. */
  53830. this._pos = 0;
  53831. /**
  53832. * Index of this particle in the global "indices" array (Internal use)
  53833. */
  53834. this._ind = 0;
  53835. /**
  53836. * ModelShape id of this particle
  53837. */
  53838. this.shapeId = 0;
  53839. /**
  53840. * Index of the particle in its shape id (Internal use)
  53841. */
  53842. this.idxInShape = 0;
  53843. /**
  53844. * Still set as invisible in order to skip useless computations (Internal use)
  53845. */
  53846. this._stillInvisible = false;
  53847. /**
  53848. * Last computed particle rotation matrix
  53849. */
  53850. this._rotationMatrix = [1.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 1.0];
  53851. /**
  53852. * Parent particle Id, if any.
  53853. * Default null.
  53854. */
  53855. this.parentId = null;
  53856. /**
  53857. * Internal global position in the SPS.
  53858. */
  53859. this._globalPosition = BABYLON.Vector3.Zero();
  53860. this.idx = particleIndex;
  53861. this._pos = positionIndex;
  53862. this._ind = indiceIndex;
  53863. this._model = model;
  53864. this.shapeId = shapeId;
  53865. this.idxInShape = idxInShape;
  53866. this._sps = sps;
  53867. if (modelBoundingInfo) {
  53868. this._modelBoundingInfo = modelBoundingInfo;
  53869. this._boundingInfo = new BABYLON.BoundingInfo(modelBoundingInfo.minimum, modelBoundingInfo.maximum);
  53870. }
  53871. }
  53872. Object.defineProperty(SolidParticle.prototype, "scale", {
  53873. /**
  53874. * Legacy support, changed scale to scaling
  53875. */
  53876. get: function () {
  53877. return this.scaling;
  53878. },
  53879. /**
  53880. * Legacy support, changed scale to scaling
  53881. */
  53882. set: function (scale) {
  53883. this.scaling = scale;
  53884. },
  53885. enumerable: true,
  53886. configurable: true
  53887. });
  53888. Object.defineProperty(SolidParticle.prototype, "quaternion", {
  53889. /**
  53890. * Legacy support, changed quaternion to rotationQuaternion
  53891. */
  53892. get: function () {
  53893. return this.rotationQuaternion;
  53894. },
  53895. /**
  53896. * Legacy support, changed quaternion to rotationQuaternion
  53897. */
  53898. set: function (q) {
  53899. this.rotationQuaternion = q;
  53900. },
  53901. enumerable: true,
  53902. configurable: true
  53903. });
  53904. /**
  53905. * Returns a boolean. True if the particle intersects another particle or another mesh, else false.
  53906. * The intersection is computed on the particle bounding sphere and Axis Aligned Bounding Box (AABB)
  53907. * @param target is the object (solid particle or mesh) what the intersection is computed against.
  53908. * @returns true if it intersects
  53909. */
  53910. SolidParticle.prototype.intersectsMesh = function (target) {
  53911. if (!this._boundingInfo || !target._boundingInfo) {
  53912. return false;
  53913. }
  53914. if (this._sps._bSphereOnly) {
  53915. return BABYLON.BoundingSphere.Intersects(this._boundingInfo.boundingSphere, target._boundingInfo.boundingSphere);
  53916. }
  53917. return this._boundingInfo.intersects(target._boundingInfo, false);
  53918. };
  53919. return SolidParticle;
  53920. }());
  53921. BABYLON.SolidParticle = SolidParticle;
  53922. /**
  53923. * Represents the shape of the model used by one particle of a solid particle system.
  53924. * SPS internal tool, don't use it manually.
  53925. */
  53926. var ModelShape = /** @class */ (function () {
  53927. /**
  53928. * 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.
  53929. * SPS internal tool, don't use it manually.
  53930. * @ignore
  53931. */
  53932. function ModelShape(id, shape, indicesLength, shapeUV, posFunction, vtxFunction) {
  53933. /**
  53934. * length of the shape in the model indices array (internal use)
  53935. */
  53936. this._indicesLength = 0;
  53937. this.shapeID = id;
  53938. this._shape = shape;
  53939. this._indicesLength = indicesLength;
  53940. this._shapeUV = shapeUV;
  53941. this._positionFunction = posFunction;
  53942. this._vertexFunction = vtxFunction;
  53943. }
  53944. return ModelShape;
  53945. }());
  53946. BABYLON.ModelShape = ModelShape;
  53947. /**
  53948. * Represents a Depth Sorted Particle in the solid particle system.
  53949. */
  53950. var DepthSortedParticle = /** @class */ (function () {
  53951. function DepthSortedParticle() {
  53952. /**
  53953. * Index of the particle in the "indices" array
  53954. */
  53955. this.ind = 0;
  53956. /**
  53957. * Length of the particle shape in the "indices" array
  53958. */
  53959. this.indicesLength = 0;
  53960. /**
  53961. * Squared distance from the particle to the camera
  53962. */
  53963. this.sqDistance = 0.0;
  53964. }
  53965. return DepthSortedParticle;
  53966. }());
  53967. BABYLON.DepthSortedParticle = DepthSortedParticle;
  53968. })(BABYLON || (BABYLON = {}));
  53969. //# sourceMappingURL=babylon.solidParticle.js.map
  53970. "use strict";
  53971. var BABYLON;
  53972. (function (BABYLON) {
  53973. /**
  53974. * The SPS is a single updatable mesh. The solid particles are simply separate parts or faces fo this big mesh.
  53975. *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.
  53976. * The SPS is also a particle system. It provides some methods to manage the particles.
  53977. * However it is behavior agnostic. This means it has no emitter, no particle physics, no particle recycler. You have to implement your own behavior.
  53978. *
  53979. * Full documentation here : http://doc.babylonjs.com/overviews/Solid_Particle_System
  53980. */
  53981. var SolidParticleSystem = /** @class */ (function () {
  53982. /**
  53983. * Creates a SPS (Solid Particle System) object.
  53984. * @param name (String) is the SPS name, this will be the underlying mesh name.
  53985. * @param scene (Scene) is the scene in which the SPS is added.
  53986. * @param updatable (optional boolean, default true) : if the SPS must be updatable or immutable.
  53987. * @param isPickable (optional boolean, default false) : if the solid particles must be pickable.
  53988. * @param enableDepthSort (optional boolean, default false) : if the solid particles must be sorted in the geometry according to their distance to the camera.
  53989. * @param particleIntersection (optional boolean, default false) : if the solid particle intersections must be computed.
  53990. * @param boundingSphereOnly (optional boolean, default false) : if the particle intersection must be computed only with the bounding sphere (no bounding box computation, so faster).
  53991. * @param bSphereRadiusFactor (optional float, default 1.0) : a number to multiply the boundind sphere radius by in order to reduce it for instance.
  53992. * @example bSphereRadiusFactor = 1.0 / Math.sqrt(3.0) => the bounding sphere exactly matches a spherical mesh.
  53993. */
  53994. function SolidParticleSystem(name, scene, options) {
  53995. /**
  53996. * The SPS array of Solid Particle objects. Just access each particle as with any classic array.
  53997. * Example : var p = SPS.particles[i];
  53998. */
  53999. this.particles = new Array();
  54000. /**
  54001. * The SPS total number of particles. Read only. Use SPS.counter instead if you need to set your own value.
  54002. */
  54003. this.nbParticles = 0;
  54004. /**
  54005. * If the particles must ever face the camera (default false). Useful for planar particles.
  54006. */
  54007. this.billboard = false;
  54008. /**
  54009. * Recompute normals when adding a shape
  54010. */
  54011. this.recomputeNormals = true;
  54012. /**
  54013. * This a counter ofr your own usage. It's not set by any SPS functions.
  54014. */
  54015. this.counter = 0;
  54016. /**
  54017. * This empty object is intended to store some SPS specific or temporary values in order to lower the Garbage Collector activity.
  54018. * Please read : http://doc.babylonjs.com/overviews/Solid_Particle_System#garbage-collector-concerns
  54019. */
  54020. this.vars = {};
  54021. /**
  54022. * If the particle intersection must be computed only with the bounding sphere (no bounding box computation, so faster). (Internal use only)
  54023. */
  54024. this._bSphereOnly = false;
  54025. /**
  54026. * A number to multiply the boundind sphere radius by in order to reduce it for instance. (Internal use only)
  54027. */
  54028. this._bSphereRadiusFactor = 1.0;
  54029. this._positions = new Array();
  54030. this._indices = new Array();
  54031. this._normals = new Array();
  54032. this._colors = new Array();
  54033. this._uvs = new Array();
  54034. this._index = 0; // indices index
  54035. this._updatable = true;
  54036. this._pickable = false;
  54037. this._isVisibilityBoxLocked = false;
  54038. this._alwaysVisible = false;
  54039. this._depthSort = false;
  54040. this._shapeCounter = 0;
  54041. this._copy = new BABYLON.SolidParticle(0, 0, 0, null, 0, 0, this);
  54042. this._color = new BABYLON.Color4(0, 0, 0, 0);
  54043. this._computeParticleColor = true;
  54044. this._computeParticleTexture = true;
  54045. this._computeParticleRotation = true;
  54046. this._computeParticleVertex = false;
  54047. this._computeBoundingBox = false;
  54048. this._depthSortParticles = true;
  54049. this._cam_axisZ = BABYLON.Vector3.Zero();
  54050. this._cam_axisY = BABYLON.Vector3.Zero();
  54051. this._cam_axisX = BABYLON.Vector3.Zero();
  54052. this._axisZ = BABYLON.Axis.Z;
  54053. this._camDir = BABYLON.Vector3.Zero();
  54054. this._camInvertedPosition = BABYLON.Vector3.Zero();
  54055. this._rotMatrix = new BABYLON.Matrix();
  54056. this._invertMatrix = new BABYLON.Matrix();
  54057. this._rotated = BABYLON.Vector3.Zero();
  54058. this._quaternion = new BABYLON.Quaternion();
  54059. this._vertex = BABYLON.Vector3.Zero();
  54060. this._normal = BABYLON.Vector3.Zero();
  54061. this._yaw = 0.0;
  54062. this._pitch = 0.0;
  54063. this._roll = 0.0;
  54064. this._halfroll = 0.0;
  54065. this._halfpitch = 0.0;
  54066. this._halfyaw = 0.0;
  54067. this._sinRoll = 0.0;
  54068. this._cosRoll = 0.0;
  54069. this._sinPitch = 0.0;
  54070. this._cosPitch = 0.0;
  54071. this._sinYaw = 0.0;
  54072. this._cosYaw = 0.0;
  54073. this._mustUnrotateFixedNormals = false;
  54074. this._minimum = BABYLON.Vector3.Zero();
  54075. this._maximum = BABYLON.Vector3.Zero();
  54076. this._minBbox = BABYLON.Vector3.Zero();
  54077. this._maxBbox = BABYLON.Vector3.Zero();
  54078. this._particlesIntersect = false;
  54079. this._depthSortFunction = function (p1, p2) {
  54080. return (p2.sqDistance - p1.sqDistance);
  54081. };
  54082. this._needs32Bits = false;
  54083. this._pivotBackTranslation = BABYLON.Vector3.Zero();
  54084. this._scaledPivot = BABYLON.Vector3.Zero();
  54085. this._particleHasParent = false;
  54086. this.name = name;
  54087. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  54088. this._camera = scene.activeCamera;
  54089. this._pickable = options ? options.isPickable : false;
  54090. this._depthSort = options ? options.enableDepthSort : false;
  54091. this._particlesIntersect = options ? options.particleIntersection : false;
  54092. this._bSphereOnly = options ? options.boundingSphereOnly : false;
  54093. this._bSphereRadiusFactor = (options && options.bSphereRadiusFactor) ? options.bSphereRadiusFactor : 1.0;
  54094. if (options && options.updatable) {
  54095. this._updatable = options.updatable;
  54096. }
  54097. else {
  54098. this._updatable = true;
  54099. }
  54100. if (this._pickable) {
  54101. this.pickedParticles = [];
  54102. }
  54103. if (this._depthSort) {
  54104. this.depthSortedParticles = [];
  54105. }
  54106. }
  54107. /**
  54108. * Builds the SPS underlying mesh. Returns a standard Mesh.
  54109. * If no model shape was added to the SPS, the returned mesh is just a single triangular plane.
  54110. * @returns the created mesh
  54111. */
  54112. SolidParticleSystem.prototype.buildMesh = function () {
  54113. if (this.nbParticles === 0) {
  54114. var triangle = BABYLON.MeshBuilder.CreateDisc("", { radius: 1, tessellation: 3 }, this._scene);
  54115. this.addShape(triangle, 1);
  54116. triangle.dispose();
  54117. }
  54118. this._indices32 = (this._needs32Bits) ? new Uint32Array(this._indices) : new Uint16Array(this._indices);
  54119. this._positions32 = new Float32Array(this._positions);
  54120. this._uvs32 = new Float32Array(this._uvs);
  54121. this._colors32 = new Float32Array(this._colors);
  54122. if (this.recomputeNormals) {
  54123. BABYLON.VertexData.ComputeNormals(this._positions32, this._indices32, this._normals);
  54124. }
  54125. this._normals32 = new Float32Array(this._normals);
  54126. this._fixedNormal32 = new Float32Array(this._normals);
  54127. if (this._mustUnrotateFixedNormals) {
  54128. this._unrotateFixedNormals();
  54129. }
  54130. var vertexData = new BABYLON.VertexData();
  54131. vertexData.indices = (this._depthSort) ? this._indices : this._indices32;
  54132. vertexData.set(this._positions32, BABYLON.VertexBuffer.PositionKind);
  54133. vertexData.set(this._normals32, BABYLON.VertexBuffer.NormalKind);
  54134. if (this._uvs32) {
  54135. vertexData.set(this._uvs32, BABYLON.VertexBuffer.UVKind);
  54136. ;
  54137. }
  54138. if (this._colors32) {
  54139. vertexData.set(this._colors32, BABYLON.VertexBuffer.ColorKind);
  54140. }
  54141. var mesh = new BABYLON.Mesh(this.name, this._scene);
  54142. vertexData.applyToMesh(mesh, this._updatable);
  54143. this.mesh = mesh;
  54144. this.mesh.isPickable = this._pickable;
  54145. // free memory
  54146. if (!this._depthSort) {
  54147. this._indices = null;
  54148. }
  54149. this._positions = null;
  54150. this._normals = null;
  54151. this._uvs = null;
  54152. this._colors = null;
  54153. if (!this._updatable) {
  54154. this.particles.length = 0;
  54155. }
  54156. return mesh;
  54157. };
  54158. /**
  54159. * Digests the mesh and generates as many solid particles in the system as wanted. Returns the SPS.
  54160. * These particles will have the same geometry than the mesh parts and will be positioned at the same localisation than the mesh original places.
  54161. * Thus the particles generated from `digest()` have their property `position` set yet.
  54162. * @param mesh ( Mesh ) is the mesh to be digested
  54163. * @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
  54164. * {delta} (optional integer, default 0) is the random extra number of facets per particle , each particle will have between `facetNb` and `facetNb + delta` facets
  54165. * {number} (optional positive integer) is the wanted number of particles : each particle is built with `mesh_total_facets / number` facets
  54166. * @returns the current SPS
  54167. */
  54168. SolidParticleSystem.prototype.digest = function (mesh, options) {
  54169. var size = (options && options.facetNb) || 1;
  54170. var number = (options && options.number) || 0;
  54171. var delta = (options && options.delta) || 0;
  54172. var meshPos = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  54173. var meshInd = mesh.getIndices();
  54174. var meshUV = mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  54175. var meshCol = mesh.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  54176. var meshNor = mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  54177. var f = 0; // facet counter
  54178. var totalFacets = meshInd.length / 3; // a facet is a triangle, so 3 indices
  54179. // compute size from number
  54180. if (number) {
  54181. number = (number > totalFacets) ? totalFacets : number;
  54182. size = Math.round(totalFacets / number);
  54183. delta = 0;
  54184. }
  54185. else {
  54186. size = (size > totalFacets) ? totalFacets : size;
  54187. }
  54188. var facetPos = []; // submesh positions
  54189. var facetInd = []; // submesh indices
  54190. var facetUV = []; // submesh UV
  54191. var facetCol = []; // submesh colors
  54192. var barycenter = BABYLON.Vector3.Zero();
  54193. var sizeO = size;
  54194. while (f < totalFacets) {
  54195. size = sizeO + Math.floor((1 + delta) * Math.random());
  54196. if (f > totalFacets - size) {
  54197. size = totalFacets - f;
  54198. }
  54199. // reset temp arrays
  54200. facetPos.length = 0;
  54201. facetInd.length = 0;
  54202. facetUV.length = 0;
  54203. facetCol.length = 0;
  54204. // iterate over "size" facets
  54205. var fi = 0;
  54206. for (var j = f * 3; j < (f + size) * 3; j++) {
  54207. facetInd.push(fi);
  54208. var i = meshInd[j];
  54209. facetPos.push(meshPos[i * 3], meshPos[i * 3 + 1], meshPos[i * 3 + 2]);
  54210. if (meshUV) {
  54211. facetUV.push(meshUV[i * 2], meshUV[i * 2 + 1]);
  54212. }
  54213. if (meshCol) {
  54214. facetCol.push(meshCol[i * 4], meshCol[i * 4 + 1], meshCol[i * 4 + 2], meshCol[i * 4 + 3]);
  54215. }
  54216. fi++;
  54217. }
  54218. // create a model shape for each single particle
  54219. var idx = this.nbParticles;
  54220. var shape = this._posToShape(facetPos);
  54221. var shapeUV = this._uvsToShapeUV(facetUV);
  54222. // compute the barycenter of the shape
  54223. var v;
  54224. for (v = 0; v < shape.length; v++) {
  54225. barycenter.addInPlace(shape[v]);
  54226. }
  54227. barycenter.scaleInPlace(1 / shape.length);
  54228. // shift the shape from its barycenter to the origin
  54229. for (v = 0; v < shape.length; v++) {
  54230. shape[v].subtractInPlace(barycenter);
  54231. }
  54232. var bInfo;
  54233. if (this._particlesIntersect) {
  54234. bInfo = new BABYLON.BoundingInfo(barycenter, barycenter);
  54235. }
  54236. var modelShape = new BABYLON.ModelShape(this._shapeCounter, shape, size * 3, shapeUV, null, null);
  54237. // add the particle in the SPS
  54238. var currentPos = this._positions.length;
  54239. var currentInd = this._indices.length;
  54240. this._meshBuilder(this._index, shape, this._positions, facetInd, this._indices, facetUV, this._uvs, facetCol, this._colors, meshNor, this._normals, idx, 0, null);
  54241. this._addParticle(idx, currentPos, currentInd, modelShape, this._shapeCounter, 0, bInfo);
  54242. // initialize the particle position
  54243. this.particles[this.nbParticles].position.addInPlace(barycenter);
  54244. this._index += shape.length;
  54245. idx++;
  54246. this.nbParticles++;
  54247. this._shapeCounter++;
  54248. f += size;
  54249. }
  54250. return this;
  54251. };
  54252. // unrotate the fixed normals in case the mesh was built with pre-rotated particles, ex : use of positionFunction in addShape()
  54253. SolidParticleSystem.prototype._unrotateFixedNormals = function () {
  54254. var index = 0;
  54255. var idx = 0;
  54256. for (var p = 0; p < this.particles.length; p++) {
  54257. this._particle = this.particles[p];
  54258. this._shape = this._particle._model._shape;
  54259. if (this._particle.rotationQuaternion) {
  54260. this._quaternion.copyFrom(this._particle.rotationQuaternion);
  54261. }
  54262. else {
  54263. this._yaw = this._particle.rotation.y;
  54264. this._pitch = this._particle.rotation.x;
  54265. this._roll = this._particle.rotation.z;
  54266. this._quaternionRotationYPR();
  54267. }
  54268. this._quaternionToRotationMatrix();
  54269. this._rotMatrix.invertToRef(this._invertMatrix);
  54270. for (var pt = 0; pt < this._shape.length; pt++) {
  54271. idx = index + pt * 3;
  54272. BABYLON.Vector3.TransformNormalFromFloatsToRef(this._normals32[idx], this._normals32[idx + 1], this._normals32[idx + 2], this._invertMatrix, this._normal);
  54273. this._fixedNormal32[idx] = this._normal.x;
  54274. this._fixedNormal32[idx + 1] = this._normal.y;
  54275. this._fixedNormal32[idx + 2] = this._normal.z;
  54276. }
  54277. index = idx + 3;
  54278. }
  54279. };
  54280. //reset copy
  54281. SolidParticleSystem.prototype._resetCopy = function () {
  54282. this._copy.position.x = 0;
  54283. this._copy.position.y = 0;
  54284. this._copy.position.z = 0;
  54285. this._copy.rotation.x = 0;
  54286. this._copy.rotation.y = 0;
  54287. this._copy.rotation.z = 0;
  54288. this._copy.rotationQuaternion = null;
  54289. this._copy.scaling.x = 1.0;
  54290. this._copy.scaling.y = 1.0;
  54291. this._copy.scaling.z = 1.0;
  54292. this._copy.uvs.x = 0;
  54293. this._copy.uvs.y = 0;
  54294. this._copy.uvs.z = 1.0;
  54295. this._copy.uvs.w = 1.0;
  54296. this._copy.color = null;
  54297. this._copy.translateFromPivot = false;
  54298. };
  54299. // _meshBuilder : inserts the shape model in the global SPS mesh
  54300. SolidParticleSystem.prototype._meshBuilder = function (p, shape, positions, meshInd, indices, meshUV, uvs, meshCol, colors, meshNor, normals, idx, idxInShape, options) {
  54301. var i;
  54302. var u = 0;
  54303. var c = 0;
  54304. var n = 0;
  54305. this._resetCopy();
  54306. if (options && options.positionFunction) {
  54307. options.positionFunction(this._copy, idx, idxInShape);
  54308. this._mustUnrotateFixedNormals = true;
  54309. }
  54310. if (this._copy.rotationQuaternion) {
  54311. this._quaternion.copyFrom(this._copy.rotationQuaternion);
  54312. }
  54313. else {
  54314. this._yaw = this._copy.rotation.y;
  54315. this._pitch = this._copy.rotation.x;
  54316. this._roll = this._copy.rotation.z;
  54317. this._quaternionRotationYPR();
  54318. }
  54319. this._quaternionToRotationMatrix();
  54320. this._scaledPivot.x = this._copy.pivot.x * this._copy.scaling.x;
  54321. this._scaledPivot.y = this._copy.pivot.y * this._copy.scaling.y;
  54322. this._scaledPivot.z = this._copy.pivot.z * this._copy.scaling.z;
  54323. if (this._copy.translateFromPivot) {
  54324. this._pivotBackTranslation.copyFromFloats(0.0, 0.0, 0.0);
  54325. }
  54326. else {
  54327. this._pivotBackTranslation.copyFrom(this._scaledPivot);
  54328. }
  54329. for (i = 0; i < shape.length; i++) {
  54330. this._vertex.x = shape[i].x;
  54331. this._vertex.y = shape[i].y;
  54332. this._vertex.z = shape[i].z;
  54333. if (options && options.vertexFunction) {
  54334. options.vertexFunction(this._copy, this._vertex, i);
  54335. }
  54336. this._vertex.x *= this._copy.scaling.x;
  54337. this._vertex.y *= this._copy.scaling.y;
  54338. this._vertex.z *= this._copy.scaling.z;
  54339. this._vertex.x -= this._scaledPivot.x;
  54340. this._vertex.y -= this._scaledPivot.y;
  54341. this._vertex.z -= this._scaledPivot.z;
  54342. BABYLON.Vector3.TransformCoordinatesToRef(this._vertex, this._rotMatrix, this._rotated);
  54343. this._rotated.addInPlace(this._pivotBackTranslation);
  54344. positions.push(this._copy.position.x + this._rotated.x, this._copy.position.y + this._rotated.y, this._copy.position.z + this._rotated.z);
  54345. if (meshUV) {
  54346. 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);
  54347. u += 2;
  54348. }
  54349. if (this._copy.color) {
  54350. this._color = this._copy.color;
  54351. }
  54352. else if (meshCol && meshCol[c] !== undefined) {
  54353. this._color.r = meshCol[c];
  54354. this._color.g = meshCol[c + 1];
  54355. this._color.b = meshCol[c + 2];
  54356. this._color.a = meshCol[c + 3];
  54357. }
  54358. else {
  54359. this._color.r = 1.0;
  54360. this._color.g = 1.0;
  54361. this._color.b = 1.0;
  54362. this._color.a = 1.0;
  54363. }
  54364. colors.push(this._color.r, this._color.g, this._color.b, this._color.a);
  54365. c += 4;
  54366. if (!this.recomputeNormals && meshNor) {
  54367. this._normal.x = meshNor[n];
  54368. this._normal.y = meshNor[n + 1];
  54369. this._normal.z = meshNor[n + 2];
  54370. BABYLON.Vector3.TransformNormalToRef(this._normal, this._rotMatrix, this._normal);
  54371. normals.push(this._normal.x, this._normal.y, this._normal.z);
  54372. n += 3;
  54373. }
  54374. }
  54375. for (i = 0; i < meshInd.length; i++) {
  54376. var current_ind = p + meshInd[i];
  54377. indices.push(current_ind);
  54378. if (current_ind > 65535) {
  54379. this._needs32Bits = true;
  54380. }
  54381. }
  54382. if (this._pickable) {
  54383. var nbfaces = meshInd.length / 3;
  54384. for (i = 0; i < nbfaces; i++) {
  54385. this.pickedParticles.push({ idx: idx, faceId: i });
  54386. }
  54387. }
  54388. if (this._depthSort) {
  54389. this.depthSortedParticles.push(new BABYLON.DepthSortedParticle());
  54390. }
  54391. return this._copy;
  54392. };
  54393. // returns a shape array from positions array
  54394. SolidParticleSystem.prototype._posToShape = function (positions) {
  54395. var shape = [];
  54396. for (var i = 0; i < positions.length; i += 3) {
  54397. shape.push(new BABYLON.Vector3(positions[i], positions[i + 1], positions[i + 2]));
  54398. }
  54399. return shape;
  54400. };
  54401. // returns a shapeUV array from a Vector4 uvs
  54402. SolidParticleSystem.prototype._uvsToShapeUV = function (uvs) {
  54403. var shapeUV = [];
  54404. if (uvs) {
  54405. for (var i = 0; i < uvs.length; i++)
  54406. shapeUV.push(uvs[i]);
  54407. }
  54408. return shapeUV;
  54409. };
  54410. // adds a new particle object in the particles array
  54411. SolidParticleSystem.prototype._addParticle = function (idx, idxpos, idxind, model, shapeId, idxInShape, bInfo) {
  54412. if (bInfo === void 0) { bInfo = null; }
  54413. var sp = new BABYLON.SolidParticle(idx, idxpos, idxind, model, shapeId, idxInShape, this, bInfo);
  54414. this.particles.push(sp);
  54415. return sp;
  54416. };
  54417. /**
  54418. * Adds some particles to the SPS from the model shape. Returns the shape id.
  54419. * Please read the doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#create-an-immutable-sps
  54420. * @param mesh is any Mesh object that will be used as a model for the solid particles.
  54421. * @param nb (positive integer) the number of particles to be created from this model
  54422. * @param options {positionFunction} is an optional javascript function to called for each particle on SPS creation.
  54423. * {vertexFunction} is an optional javascript function to called for each vertex of each particle on SPS creation
  54424. * @returns the number of shapes in the system
  54425. */
  54426. SolidParticleSystem.prototype.addShape = function (mesh, nb, options) {
  54427. var meshPos = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  54428. var meshInd = mesh.getIndices();
  54429. var meshUV = mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  54430. var meshCol = mesh.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  54431. var meshNor = mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  54432. var bbInfo;
  54433. if (this._particlesIntersect) {
  54434. bbInfo = mesh.getBoundingInfo();
  54435. }
  54436. var shape = this._posToShape(meshPos);
  54437. var shapeUV = this._uvsToShapeUV(meshUV);
  54438. var posfunc = options ? options.positionFunction : null;
  54439. var vtxfunc = options ? options.vertexFunction : null;
  54440. var modelShape = new BABYLON.ModelShape(this._shapeCounter, shape, meshInd.length, shapeUV, posfunc, vtxfunc);
  54441. // particles
  54442. var sp;
  54443. var currentCopy;
  54444. var idx = this.nbParticles;
  54445. for (var i = 0; i < nb; i++) {
  54446. var currentPos = this._positions.length;
  54447. var currentInd = this._indices.length;
  54448. currentCopy = this._meshBuilder(this._index, shape, this._positions, meshInd, this._indices, meshUV, this._uvs, meshCol, this._colors, meshNor, this._normals, idx, i, options);
  54449. if (this._updatable) {
  54450. sp = this._addParticle(idx, currentPos, currentInd, modelShape, this._shapeCounter, i, bbInfo);
  54451. sp.position.copyFrom(currentCopy.position);
  54452. sp.rotation.copyFrom(currentCopy.rotation);
  54453. if (currentCopy.rotationQuaternion && sp.rotationQuaternion) {
  54454. sp.rotationQuaternion.copyFrom(currentCopy.rotationQuaternion);
  54455. }
  54456. if (currentCopy.color && sp.color) {
  54457. sp.color.copyFrom(currentCopy.color);
  54458. }
  54459. sp.scaling.copyFrom(currentCopy.scaling);
  54460. sp.uvs.copyFrom(currentCopy.uvs);
  54461. }
  54462. this._index += shape.length;
  54463. idx++;
  54464. }
  54465. this.nbParticles += nb;
  54466. this._shapeCounter++;
  54467. return this._shapeCounter - 1;
  54468. };
  54469. // rebuilds a particle back to its just built status : if needed, recomputes the custom positions and vertices
  54470. SolidParticleSystem.prototype._rebuildParticle = function (particle) {
  54471. this._resetCopy();
  54472. if (particle._model._positionFunction) {
  54473. particle._model._positionFunction(this._copy, particle.idx, particle.idxInShape);
  54474. }
  54475. if (this._copy.rotationQuaternion) {
  54476. this._quaternion.copyFrom(this._copy.rotationQuaternion);
  54477. }
  54478. else {
  54479. this._yaw = this._copy.rotation.y;
  54480. this._pitch = this._copy.rotation.x;
  54481. this._roll = this._copy.rotation.z;
  54482. this._quaternionRotationYPR();
  54483. }
  54484. this._quaternionToRotationMatrix();
  54485. this._scaledPivot.x = this._particle.pivot.x * this._particle.scaling.x;
  54486. this._scaledPivot.y = this._particle.pivot.y * this._particle.scaling.y;
  54487. this._scaledPivot.z = this._particle.pivot.z * this._particle.scaling.z;
  54488. if (this._copy.translateFromPivot) {
  54489. this._pivotBackTranslation.copyFromFloats(0.0, 0.0, 0.0);
  54490. }
  54491. else {
  54492. this._pivotBackTranslation.copyFrom(this._scaledPivot);
  54493. }
  54494. this._shape = particle._model._shape;
  54495. for (var pt = 0; pt < this._shape.length; pt++) {
  54496. this._vertex.x = this._shape[pt].x;
  54497. this._vertex.y = this._shape[pt].y;
  54498. this._vertex.z = this._shape[pt].z;
  54499. if (particle._model._vertexFunction) {
  54500. particle._model._vertexFunction(this._copy, this._vertex, pt); // recall to stored vertexFunction
  54501. }
  54502. this._vertex.x *= this._copy.scaling.x;
  54503. this._vertex.y *= this._copy.scaling.y;
  54504. this._vertex.z *= this._copy.scaling.z;
  54505. this._vertex.x -= this._scaledPivot.x;
  54506. this._vertex.y -= this._scaledPivot.y;
  54507. this._vertex.z -= this._scaledPivot.z;
  54508. BABYLON.Vector3.TransformCoordinatesToRef(this._vertex, this._rotMatrix, this._rotated);
  54509. this._rotated.addInPlace(this._pivotBackTranslation);
  54510. this._positions32[particle._pos + pt * 3] = this._copy.position.x + this._rotated.x;
  54511. this._positions32[particle._pos + pt * 3 + 1] = this._copy.position.y + this._rotated.y;
  54512. this._positions32[particle._pos + pt * 3 + 2] = this._copy.position.z + this._rotated.z;
  54513. }
  54514. particle.position.x = 0.0;
  54515. particle.position.y = 0.0;
  54516. particle.position.z = 0.0;
  54517. particle.rotation.x = 0.0;
  54518. particle.rotation.y = 0.0;
  54519. particle.rotation.z = 0.0;
  54520. particle.rotationQuaternion = null;
  54521. particle.scaling.x = 1.0;
  54522. particle.scaling.y = 1.0;
  54523. particle.scaling.z = 1.0;
  54524. particle.uvs.x = 0.0;
  54525. particle.uvs.y = 0.0;
  54526. particle.uvs.z = 1.0;
  54527. particle.uvs.w = 1.0;
  54528. particle.pivot.x = 0.0;
  54529. particle.pivot.y = 0.0;
  54530. particle.pivot.z = 0.0;
  54531. particle.translateFromPivot = false;
  54532. particle.parentId = null;
  54533. };
  54534. /**
  54535. * Rebuilds the whole mesh and updates the VBO : custom positions and vertices are recomputed if needed.
  54536. * @returns the SPS.
  54537. */
  54538. SolidParticleSystem.prototype.rebuildMesh = function () {
  54539. for (var p = 0; p < this.particles.length; p++) {
  54540. this._rebuildParticle(this.particles[p]);
  54541. }
  54542. this.mesh.updateVerticesData(BABYLON.VertexBuffer.PositionKind, this._positions32, false, false);
  54543. return this;
  54544. };
  54545. /**
  54546. * Sets all the particles : this method actually really updates the mesh according to the particle positions, rotations, colors, textures, etc.
  54547. * This method calls `updateParticle()` for each particle of the SPS.
  54548. * For an animated SPS, it is usually called within the render loop.
  54549. * @param start The particle index in the particle array where to start to compute the particle property values _(default 0)_
  54550. * @param end The particle index in the particle array where to stop to compute the particle property values _(default nbParticle - 1)_
  54551. * @param update If the mesh must be finally updated on this call after all the particle computations _(default true)_
  54552. * @returns the SPS.
  54553. */
  54554. SolidParticleSystem.prototype.setParticles = function (start, end, update) {
  54555. if (start === void 0) { start = 0; }
  54556. if (end === void 0) { end = this.nbParticles - 1; }
  54557. if (update === void 0) { update = true; }
  54558. if (!this._updatable) {
  54559. return this;
  54560. }
  54561. // custom beforeUpdate
  54562. this.beforeUpdateParticles(start, end, update);
  54563. this._cam_axisX.x = 1.0;
  54564. this._cam_axisX.y = 0.0;
  54565. this._cam_axisX.z = 0.0;
  54566. this._cam_axisY.x = 0.0;
  54567. this._cam_axisY.y = 1.0;
  54568. this._cam_axisY.z = 0.0;
  54569. this._cam_axisZ.x = 0.0;
  54570. this._cam_axisZ.y = 0.0;
  54571. this._cam_axisZ.z = 1.0;
  54572. // cases when the World Matrix is to be computed first
  54573. if (this.billboard || this._depthSort) {
  54574. this.mesh.computeWorldMatrix(true);
  54575. this.mesh._worldMatrix.invertToRef(this._invertMatrix);
  54576. }
  54577. // if the particles will always face the camera
  54578. if (this.billboard) {
  54579. // compute the camera position and un-rotate it by the current mesh rotation
  54580. this._camera.getDirectionToRef(this._axisZ, this._camDir);
  54581. BABYLON.Vector3.TransformNormalToRef(this._camDir, this._invertMatrix, this._cam_axisZ);
  54582. this._cam_axisZ.normalize();
  54583. // same for camera up vector extracted from the cam view matrix
  54584. var view = this._camera.getViewMatrix(true);
  54585. BABYLON.Vector3.TransformNormalFromFloatsToRef(view.m[1], view.m[5], view.m[9], this._invertMatrix, this._cam_axisY);
  54586. BABYLON.Vector3.CrossToRef(this._cam_axisY, this._cam_axisZ, this._cam_axisX);
  54587. this._cam_axisY.normalize();
  54588. this._cam_axisX.normalize();
  54589. }
  54590. // if depthSort, compute the camera global position in the mesh local system
  54591. if (this._depthSort) {
  54592. BABYLON.Vector3.TransformCoordinatesToRef(this._camera.globalPosition, this._invertMatrix, this._camInvertedPosition); // then un-rotate the camera
  54593. }
  54594. BABYLON.Matrix.IdentityToRef(this._rotMatrix);
  54595. var idx = 0; // current position index in the global array positions32
  54596. var index = 0; // position start index in the global array positions32 of the current particle
  54597. var colidx = 0; // current color index in the global array colors32
  54598. var colorIndex = 0; // color start index in the global array colors32 of the current particle
  54599. var uvidx = 0; // current uv index in the global array uvs32
  54600. var uvIndex = 0; // uv start index in the global array uvs32 of the current particle
  54601. var pt = 0; // current index in the particle model shape
  54602. if (this.mesh.isFacetDataEnabled) {
  54603. this._computeBoundingBox = true;
  54604. }
  54605. end = (end >= this.nbParticles) ? this.nbParticles - 1 : end;
  54606. if (this._computeBoundingBox) {
  54607. if (start == 0 && end == this.nbParticles - 1) {
  54608. BABYLON.Vector3.FromFloatsToRef(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, this._minimum);
  54609. BABYLON.Vector3.FromFloatsToRef(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE, this._maximum);
  54610. }
  54611. else {
  54612. if (this.mesh._boundingInfo) {
  54613. this._minimum.copyFrom(this.mesh._boundingInfo.boundingBox.minimum);
  54614. this._maximum.copyFrom(this.mesh._boundingInfo.boundingBox.maximum);
  54615. }
  54616. }
  54617. }
  54618. // particle loop
  54619. index = this.particles[start]._pos;
  54620. var vpos = (index / 3) | 0;
  54621. colorIndex = vpos * 4;
  54622. uvIndex = vpos * 2;
  54623. for (var p = start; p <= end; p++) {
  54624. this._particle = this.particles[p];
  54625. this._shape = this._particle._model._shape;
  54626. this._shapeUV = this._particle._model._shapeUV;
  54627. // call to custom user function to update the particle properties
  54628. this.updateParticle(this._particle);
  54629. // camera-particle distance for depth sorting
  54630. if (this._depthSort && this._depthSortParticles) {
  54631. var dsp = this.depthSortedParticles[p];
  54632. dsp.ind = this._particle._ind;
  54633. dsp.indicesLength = this._particle._model._indicesLength;
  54634. dsp.sqDistance = BABYLON.Vector3.DistanceSquared(this._particle.position, this._camInvertedPosition);
  54635. }
  54636. // skip the computations for inactive or already invisible particles
  54637. if (!this._particle.alive || (this._particle._stillInvisible && !this._particle.isVisible)) {
  54638. // increment indexes for the next particle
  54639. pt = this._shape.length;
  54640. index += pt * 3;
  54641. colorIndex += pt * 4;
  54642. uvIndex += pt * 2;
  54643. continue;
  54644. }
  54645. if (this._particle.isVisible) {
  54646. this._particle._stillInvisible = false; // un-mark permanent invisibility
  54647. this._particleHasParent = (this._particle.parentId !== null);
  54648. this._scaledPivot.x = this._particle.pivot.x * this._particle.scaling.x;
  54649. this._scaledPivot.y = this._particle.pivot.y * this._particle.scaling.y;
  54650. this._scaledPivot.z = this._particle.pivot.z * this._particle.scaling.z;
  54651. // particle rotation matrix
  54652. if (this.billboard) {
  54653. this._particle.rotation.x = 0.0;
  54654. this._particle.rotation.y = 0.0;
  54655. }
  54656. if (this._computeParticleRotation || this.billboard) {
  54657. if (this._particle.rotationQuaternion) {
  54658. this._quaternion.copyFrom(this._particle.rotationQuaternion);
  54659. }
  54660. else {
  54661. this._yaw = this._particle.rotation.y;
  54662. this._pitch = this._particle.rotation.x;
  54663. this._roll = this._particle.rotation.z;
  54664. this._quaternionRotationYPR();
  54665. }
  54666. this._quaternionToRotationMatrix();
  54667. }
  54668. if (this._particleHasParent) {
  54669. this._parent = this.particles[this._particle.parentId];
  54670. 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];
  54671. 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];
  54672. 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];
  54673. this._particle._globalPosition.x = this._parent._globalPosition.x + this._rotated.x;
  54674. this._particle._globalPosition.y = this._parent._globalPosition.y + this._rotated.y;
  54675. this._particle._globalPosition.z = this._parent._globalPosition.z + this._rotated.z;
  54676. if (this._computeParticleRotation || this.billboard) {
  54677. 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];
  54678. 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];
  54679. 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];
  54680. 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];
  54681. 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];
  54682. 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];
  54683. 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];
  54684. 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];
  54685. 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];
  54686. }
  54687. }
  54688. else {
  54689. this._particle._globalPosition.x = this._particle.position.x;
  54690. this._particle._globalPosition.y = this._particle.position.y;
  54691. this._particle._globalPosition.z = this._particle.position.z;
  54692. if (this._computeParticleRotation || this.billboard) {
  54693. this._particle._rotationMatrix[0] = this._rotMatrix.m[0];
  54694. this._particle._rotationMatrix[1] = this._rotMatrix.m[1];
  54695. this._particle._rotationMatrix[2] = this._rotMatrix.m[2];
  54696. this._particle._rotationMatrix[3] = this._rotMatrix.m[4];
  54697. this._particle._rotationMatrix[4] = this._rotMatrix.m[5];
  54698. this._particle._rotationMatrix[5] = this._rotMatrix.m[6];
  54699. this._particle._rotationMatrix[6] = this._rotMatrix.m[8];
  54700. this._particle._rotationMatrix[7] = this._rotMatrix.m[9];
  54701. this._particle._rotationMatrix[8] = this._rotMatrix.m[10];
  54702. }
  54703. }
  54704. if (this._particle.translateFromPivot) {
  54705. this._pivotBackTranslation.x = 0.0;
  54706. this._pivotBackTranslation.y = 0.0;
  54707. this._pivotBackTranslation.z = 0.0;
  54708. }
  54709. else {
  54710. this._pivotBackTranslation.x = this._scaledPivot.x;
  54711. this._pivotBackTranslation.y = this._scaledPivot.y;
  54712. this._pivotBackTranslation.z = this._scaledPivot.z;
  54713. }
  54714. // particle vertex loop
  54715. for (pt = 0; pt < this._shape.length; pt++) {
  54716. idx = index + pt * 3;
  54717. colidx = colorIndex + pt * 4;
  54718. uvidx = uvIndex + pt * 2;
  54719. this._vertex.x = this._shape[pt].x;
  54720. this._vertex.y = this._shape[pt].y;
  54721. this._vertex.z = this._shape[pt].z;
  54722. if (this._computeParticleVertex) {
  54723. this.updateParticleVertex(this._particle, this._vertex, pt);
  54724. }
  54725. // positions
  54726. this._vertex.x *= this._particle.scaling.x;
  54727. this._vertex.y *= this._particle.scaling.y;
  54728. this._vertex.z *= this._particle.scaling.z;
  54729. this._vertex.x -= this._scaledPivot.x;
  54730. this._vertex.y -= this._scaledPivot.y;
  54731. this._vertex.z -= this._scaledPivot.z;
  54732. this._rotated.x = this._vertex.x * this._particle._rotationMatrix[0] + this._vertex.y * this._particle._rotationMatrix[3] + this._vertex.z * this._particle._rotationMatrix[6];
  54733. this._rotated.y = this._vertex.x * this._particle._rotationMatrix[1] + this._vertex.y * this._particle._rotationMatrix[4] + this._vertex.z * this._particle._rotationMatrix[7];
  54734. this._rotated.z = this._vertex.x * this._particle._rotationMatrix[2] + this._vertex.y * this._particle._rotationMatrix[5] + this._vertex.z * this._particle._rotationMatrix[8];
  54735. this._rotated.x += this._pivotBackTranslation.x;
  54736. this._rotated.y += this._pivotBackTranslation.y;
  54737. this._rotated.z += this._pivotBackTranslation.z;
  54738. 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;
  54739. 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;
  54740. 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;
  54741. if (this._computeBoundingBox) {
  54742. if (this._positions32[idx] < this._minimum.x) {
  54743. this._minimum.x = this._positions32[idx];
  54744. }
  54745. if (this._positions32[idx] > this._maximum.x) {
  54746. this._maximum.x = this._positions32[idx];
  54747. }
  54748. if (this._positions32[idx + 1] < this._minimum.y) {
  54749. this._minimum.y = this._positions32[idx + 1];
  54750. }
  54751. if (this._positions32[idx + 1] > this._maximum.y) {
  54752. this._maximum.y = this._positions32[idx + 1];
  54753. }
  54754. if (this._positions32[idx + 2] < this._minimum.z) {
  54755. this._minimum.z = this._positions32[idx + 2];
  54756. }
  54757. if (this._positions32[idx + 2] > this._maximum.z) {
  54758. this._maximum.z = this._positions32[idx + 2];
  54759. }
  54760. }
  54761. // normals : if the particles can't be morphed then just rotate the normals, what is much more faster than ComputeNormals()
  54762. if (!this._computeParticleVertex) {
  54763. this._normal.x = this._fixedNormal32[idx];
  54764. this._normal.y = this._fixedNormal32[idx + 1];
  54765. this._normal.z = this._fixedNormal32[idx + 2];
  54766. this._rotated.x = this._normal.x * this._particle._rotationMatrix[0] + this._normal.y * this._particle._rotationMatrix[3] + this._normal.z * this._particle._rotationMatrix[6];
  54767. this._rotated.y = this._normal.x * this._particle._rotationMatrix[1] + this._normal.y * this._particle._rotationMatrix[4] + this._normal.z * this._particle._rotationMatrix[7];
  54768. this._rotated.z = this._normal.x * this._particle._rotationMatrix[2] + this._normal.y * this._particle._rotationMatrix[5] + this._normal.z * this._particle._rotationMatrix[8];
  54769. this._normals32[idx] = this._cam_axisX.x * this._rotated.x + this._cam_axisY.x * this._rotated.y + this._cam_axisZ.x * this._rotated.z;
  54770. 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;
  54771. 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;
  54772. }
  54773. if (this._computeParticleColor && this._particle.color) {
  54774. this._colors32[colidx] = this._particle.color.r;
  54775. this._colors32[colidx + 1] = this._particle.color.g;
  54776. this._colors32[colidx + 2] = this._particle.color.b;
  54777. this._colors32[colidx + 3] = this._particle.color.a;
  54778. }
  54779. if (this._computeParticleTexture) {
  54780. this._uvs32[uvidx] = this._shapeUV[pt * 2] * (this._particle.uvs.z - this._particle.uvs.x) + this._particle.uvs.x;
  54781. this._uvs32[uvidx + 1] = this._shapeUV[pt * 2 + 1] * (this._particle.uvs.w - this._particle.uvs.y) + this._particle.uvs.y;
  54782. }
  54783. }
  54784. }
  54785. else {
  54786. this._particle._stillInvisible = true; // mark the particle as invisible
  54787. for (pt = 0; pt < this._shape.length; pt++) {
  54788. idx = index + pt * 3;
  54789. colidx = colorIndex + pt * 4;
  54790. uvidx = uvIndex + pt * 2;
  54791. this._positions32[idx] = 0.0;
  54792. this._positions32[idx + 1] = 0.0;
  54793. this._positions32[idx + 2] = 0.0;
  54794. this._normals32[idx] = 0.0;
  54795. this._normals32[idx + 1] = 0.0;
  54796. this._normals32[idx + 2] = 0.0;
  54797. if (this._computeParticleColor && this._particle.color) {
  54798. this._colors32[colidx] = this._particle.color.r;
  54799. this._colors32[colidx + 1] = this._particle.color.g;
  54800. this._colors32[colidx + 2] = this._particle.color.b;
  54801. this._colors32[colidx + 3] = this._particle.color.a;
  54802. }
  54803. if (this._computeParticleTexture) {
  54804. this._uvs32[uvidx] = this._shapeUV[pt * 2] * (this._particle.uvs.z - this._particle.uvs.x) + this._particle.uvs.x;
  54805. this._uvs32[uvidx + 1] = this._shapeUV[pt * 2 + 1] * (this._particle.uvs.w - this._particle.uvs.y) + this._particle.uvs.y;
  54806. }
  54807. }
  54808. }
  54809. // if the particle intersections must be computed : update the bbInfo
  54810. if (this._particlesIntersect) {
  54811. var bInfo = this._particle._boundingInfo;
  54812. var bBox = bInfo.boundingBox;
  54813. var bSphere = bInfo.boundingSphere;
  54814. if (!this._bSphereOnly) {
  54815. // place, scale and rotate the particle bbox within the SPS local system, then update it
  54816. for (var b = 0; b < bBox.vectors.length; b++) {
  54817. this._vertex.x = this._particle._modelBoundingInfo.boundingBox.vectors[b].x * this._particle.scaling.x;
  54818. this._vertex.y = this._particle._modelBoundingInfo.boundingBox.vectors[b].y * this._particle.scaling.y;
  54819. this._vertex.z = this._particle._modelBoundingInfo.boundingBox.vectors[b].z * this._particle.scaling.z;
  54820. this._rotated.x = this._vertex.x * this._particle._rotationMatrix[0] + this._vertex.y * this._particle._rotationMatrix[3] + this._vertex.z * this._particle._rotationMatrix[6];
  54821. this._rotated.y = this._vertex.x * this._particle._rotationMatrix[1] + this._vertex.y * this._particle._rotationMatrix[4] + this._vertex.z * this._particle._rotationMatrix[7];
  54822. this._rotated.z = this._vertex.x * this._particle._rotationMatrix[2] + this._vertex.y * this._particle._rotationMatrix[5] + this._vertex.z * this._particle._rotationMatrix[8];
  54823. 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;
  54824. 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;
  54825. 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;
  54826. }
  54827. bBox._update(this.mesh._worldMatrix);
  54828. }
  54829. // place and scale the particle bouding sphere in the SPS local system, then update it
  54830. this._minBbox.x = this._particle._modelBoundingInfo.minimum.x * this._particle.scaling.x;
  54831. this._minBbox.y = this._particle._modelBoundingInfo.minimum.y * this._particle.scaling.y;
  54832. this._minBbox.z = this._particle._modelBoundingInfo.minimum.z * this._particle.scaling.z;
  54833. this._maxBbox.x = this._particle._modelBoundingInfo.maximum.x * this._particle.scaling.x;
  54834. this._maxBbox.y = this._particle._modelBoundingInfo.maximum.y * this._particle.scaling.y;
  54835. this._maxBbox.z = this._particle._modelBoundingInfo.maximum.z * this._particle.scaling.z;
  54836. bSphere.center.x = this._particle._globalPosition.x + (this._minBbox.x + this._maxBbox.x) * 0.5;
  54837. bSphere.center.y = this._particle._globalPosition.y + (this._minBbox.y + this._maxBbox.y) * 0.5;
  54838. bSphere.center.z = this._particle._globalPosition.z + (this._minBbox.z + this._maxBbox.z) * 0.5;
  54839. 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));
  54840. bSphere._update(this.mesh._worldMatrix);
  54841. }
  54842. // increment indexes for the next particle
  54843. index = idx + 3;
  54844. colorIndex = colidx + 4;
  54845. uvIndex = uvidx + 2;
  54846. }
  54847. // if the VBO must be updated
  54848. if (update) {
  54849. if (this._computeParticleColor) {
  54850. this.mesh.updateVerticesData(BABYLON.VertexBuffer.ColorKind, this._colors32, false, false);
  54851. }
  54852. if (this._computeParticleTexture) {
  54853. this.mesh.updateVerticesData(BABYLON.VertexBuffer.UVKind, this._uvs32, false, false);
  54854. }
  54855. this.mesh.updateVerticesData(BABYLON.VertexBuffer.PositionKind, this._positions32, false, false);
  54856. if (!this.mesh.areNormalsFrozen || this.mesh.isFacetDataEnabled) {
  54857. if (this._computeParticleVertex || this.mesh.isFacetDataEnabled) {
  54858. // recompute the normals only if the particles can be morphed, update then also the normal reference array _fixedNormal32[]
  54859. var params = this.mesh.isFacetDataEnabled ? this.mesh.getFacetDataParameters() : null;
  54860. BABYLON.VertexData.ComputeNormals(this._positions32, this._indices32, this._normals32, params);
  54861. for (var i = 0; i < this._normals32.length; i++) {
  54862. this._fixedNormal32[i] = this._normals32[i];
  54863. }
  54864. }
  54865. if (!this.mesh.areNormalsFrozen) {
  54866. this.mesh.updateVerticesData(BABYLON.VertexBuffer.NormalKind, this._normals32, false, false);
  54867. }
  54868. }
  54869. if (this._depthSort && this._depthSortParticles) {
  54870. this.depthSortedParticles.sort(this._depthSortFunction);
  54871. var dspl = this.depthSortedParticles.length;
  54872. var sorted = 0;
  54873. var lind = 0;
  54874. var sind = 0;
  54875. var sid = 0;
  54876. for (sorted = 0; sorted < dspl; sorted++) {
  54877. lind = this.depthSortedParticles[sorted].indicesLength;
  54878. sind = this.depthSortedParticles[sorted].ind;
  54879. for (var i = 0; i < lind; i++) {
  54880. this._indices32[sid] = this._indices[sind + i];
  54881. sid++;
  54882. }
  54883. }
  54884. this.mesh.updateIndices(this._indices32);
  54885. }
  54886. }
  54887. if (this._computeBoundingBox) {
  54888. this.mesh._boundingInfo = new BABYLON.BoundingInfo(this._minimum, this._maximum);
  54889. this.mesh._boundingInfo.update(this.mesh._worldMatrix);
  54890. }
  54891. this.afterUpdateParticles(start, end, update);
  54892. return this;
  54893. };
  54894. SolidParticleSystem.prototype._quaternionRotationYPR = function () {
  54895. this._halfroll = this._roll * 0.5;
  54896. this._halfpitch = this._pitch * 0.5;
  54897. this._halfyaw = this._yaw * 0.5;
  54898. this._sinRoll = Math.sin(this._halfroll);
  54899. this._cosRoll = Math.cos(this._halfroll);
  54900. this._sinPitch = Math.sin(this._halfpitch);
  54901. this._cosPitch = Math.cos(this._halfpitch);
  54902. this._sinYaw = Math.sin(this._halfyaw);
  54903. this._cosYaw = Math.cos(this._halfyaw);
  54904. this._quaternion.x = this._cosYaw * this._sinPitch * this._cosRoll + this._sinYaw * this._cosPitch * this._sinRoll;
  54905. this._quaternion.y = this._sinYaw * this._cosPitch * this._cosRoll - this._cosYaw * this._sinPitch * this._sinRoll;
  54906. this._quaternion.z = this._cosYaw * this._cosPitch * this._sinRoll - this._sinYaw * this._sinPitch * this._cosRoll;
  54907. this._quaternion.w = this._cosYaw * this._cosPitch * this._cosRoll + this._sinYaw * this._sinPitch * this._sinRoll;
  54908. };
  54909. SolidParticleSystem.prototype._quaternionToRotationMatrix = function () {
  54910. this._rotMatrix.m[0] = 1.0 - (2.0 * (this._quaternion.y * this._quaternion.y + this._quaternion.z * this._quaternion.z));
  54911. this._rotMatrix.m[1] = 2.0 * (this._quaternion.x * this._quaternion.y + this._quaternion.z * this._quaternion.w);
  54912. this._rotMatrix.m[2] = 2.0 * (this._quaternion.z * this._quaternion.x - this._quaternion.y * this._quaternion.w);
  54913. this._rotMatrix.m[3] = 0;
  54914. this._rotMatrix.m[4] = 2.0 * (this._quaternion.x * this._quaternion.y - this._quaternion.z * this._quaternion.w);
  54915. this._rotMatrix.m[5] = 1.0 - (2.0 * (this._quaternion.z * this._quaternion.z + this._quaternion.x * this._quaternion.x));
  54916. this._rotMatrix.m[6] = 2.0 * (this._quaternion.y * this._quaternion.z + this._quaternion.x * this._quaternion.w);
  54917. this._rotMatrix.m[7] = 0;
  54918. this._rotMatrix.m[8] = 2.0 * (this._quaternion.z * this._quaternion.x + this._quaternion.y * this._quaternion.w);
  54919. this._rotMatrix.m[9] = 2.0 * (this._quaternion.y * this._quaternion.z - this._quaternion.x * this._quaternion.w);
  54920. this._rotMatrix.m[10] = 1.0 - (2.0 * (this._quaternion.y * this._quaternion.y + this._quaternion.x * this._quaternion.x));
  54921. this._rotMatrix.m[11] = 0;
  54922. this._rotMatrix.m[12] = 0;
  54923. this._rotMatrix.m[13] = 0;
  54924. this._rotMatrix.m[14] = 0;
  54925. this._rotMatrix.m[15] = 1.0;
  54926. };
  54927. /**
  54928. * Disposes the SPS.
  54929. */
  54930. SolidParticleSystem.prototype.dispose = function () {
  54931. this.mesh.dispose();
  54932. this.vars = null;
  54933. // drop references to internal big arrays for the GC
  54934. this._positions = null;
  54935. this._indices = null;
  54936. this._normals = null;
  54937. this._uvs = null;
  54938. this._colors = null;
  54939. this._indices32 = null;
  54940. this._positions32 = null;
  54941. this._normals32 = null;
  54942. this._fixedNormal32 = null;
  54943. this._uvs32 = null;
  54944. this._colors32 = null;
  54945. this.pickedParticles = null;
  54946. };
  54947. /**
  54948. * Visibilty helper : Recomputes the visible size according to the mesh bounding box
  54949. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  54950. * @returns the SPS.
  54951. */
  54952. SolidParticleSystem.prototype.refreshVisibleSize = function () {
  54953. if (!this._isVisibilityBoxLocked) {
  54954. this.mesh.refreshBoundingInfo();
  54955. }
  54956. return this;
  54957. };
  54958. /**
  54959. * Visibility helper : Sets the size of a visibility box, this sets the underlying mesh bounding box.
  54960. * @param size the size (float) of the visibility box
  54961. * note : this doesn't lock the SPS mesh bounding box.
  54962. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  54963. */
  54964. SolidParticleSystem.prototype.setVisibilityBox = function (size) {
  54965. var vis = size / 2;
  54966. this.mesh._boundingInfo = new BABYLON.BoundingInfo(new BABYLON.Vector3(-vis, -vis, -vis), new BABYLON.Vector3(vis, vis, vis));
  54967. };
  54968. Object.defineProperty(SolidParticleSystem.prototype, "isAlwaysVisible", {
  54969. /**
  54970. * Gets whether the SPS as always visible or not
  54971. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  54972. */
  54973. get: function () {
  54974. return this._alwaysVisible;
  54975. },
  54976. /**
  54977. * Sets the SPS as always visible or not
  54978. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  54979. */
  54980. set: function (val) {
  54981. this._alwaysVisible = val;
  54982. this.mesh.alwaysSelectAsActiveMesh = val;
  54983. },
  54984. enumerable: true,
  54985. configurable: true
  54986. });
  54987. Object.defineProperty(SolidParticleSystem.prototype, "isVisibilityBoxLocked", {
  54988. /**
  54989. * Gets if the SPS visibility box as locked or not. This enables/disables the underlying mesh bounding box updates.
  54990. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  54991. */
  54992. get: function () {
  54993. return this._isVisibilityBoxLocked;
  54994. },
  54995. /**
  54996. * Sets the SPS visibility box as locked or not. This enables/disables the underlying mesh bounding box updates.
  54997. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  54998. */
  54999. set: function (val) {
  55000. this._isVisibilityBoxLocked = val;
  55001. var boundingInfo = this.mesh.getBoundingInfo();
  55002. boundingInfo.isLocked = val;
  55003. },
  55004. enumerable: true,
  55005. configurable: true
  55006. });
  55007. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleRotation", {
  55008. /**
  55009. * Gets if `setParticles()` computes the particle rotations or not.
  55010. * Default value : true. The SPS is faster when it's set to false.
  55011. * Note : the particle rotations aren't stored values, so setting `computeParticleRotation` to false will prevents the particle to rotate.
  55012. */
  55013. get: function () {
  55014. return this._computeParticleRotation;
  55015. },
  55016. /**
  55017. * Tells to `setParticles()` to compute the particle rotations or not.
  55018. * Default value : true. The SPS is faster when it's set to false.
  55019. * Note : the particle rotations aren't stored values, so setting `computeParticleRotation` to false will prevents the particle to rotate.
  55020. */
  55021. set: function (val) {
  55022. this._computeParticleRotation = val;
  55023. },
  55024. enumerable: true,
  55025. configurable: true
  55026. });
  55027. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleColor", {
  55028. /**
  55029. * Gets if `setParticles()` computes the particle colors or not.
  55030. * Default value : true. The SPS is faster when it's set to false.
  55031. * Note : the particle colors are stored values, so setting `computeParticleColor` to false will keep yet the last colors set.
  55032. */
  55033. get: function () {
  55034. return this._computeParticleColor;
  55035. },
  55036. /**
  55037. * Tells to `setParticles()` to compute the particle colors or not.
  55038. * Default value : true. The SPS is faster when it's set to false.
  55039. * Note : the particle colors are stored values, so setting `computeParticleColor` to false will keep yet the last colors set.
  55040. */
  55041. set: function (val) {
  55042. this._computeParticleColor = val;
  55043. },
  55044. enumerable: true,
  55045. configurable: true
  55046. });
  55047. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleTexture", {
  55048. /**
  55049. * Gets if `setParticles()` computes the particle textures or not.
  55050. * Default value : true. The SPS is faster when it's set to false.
  55051. * Note : the particle textures are stored values, so setting `computeParticleTexture` to false will keep yet the last colors set.
  55052. */
  55053. get: function () {
  55054. return this._computeParticleTexture;
  55055. },
  55056. set: function (val) {
  55057. this._computeParticleTexture = val;
  55058. },
  55059. enumerable: true,
  55060. configurable: true
  55061. });
  55062. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleVertex", {
  55063. /**
  55064. * Gets if `setParticles()` calls the vertex function for each vertex of each particle, or not.
  55065. * Default value : false. The SPS is faster when it's set to false.
  55066. * Note : the particle custom vertex positions aren't stored values.
  55067. */
  55068. get: function () {
  55069. return this._computeParticleVertex;
  55070. },
  55071. /**
  55072. * Tells to `setParticles()` to call the vertex function for each vertex of each particle, or not.
  55073. * Default value : false. The SPS is faster when it's set to false.
  55074. * Note : the particle custom vertex positions aren't stored values.
  55075. */
  55076. set: function (val) {
  55077. this._computeParticleVertex = val;
  55078. },
  55079. enumerable: true,
  55080. configurable: true
  55081. });
  55082. Object.defineProperty(SolidParticleSystem.prototype, "computeBoundingBox", {
  55083. /**
  55084. * Gets if `setParticles()` computes or not the mesh bounding box when computing the particle positions.
  55085. */
  55086. get: function () {
  55087. return this._computeBoundingBox;
  55088. },
  55089. /**
  55090. * Tells to `setParticles()` to compute or not the mesh bounding box when computing the particle positions.
  55091. */
  55092. set: function (val) {
  55093. this._computeBoundingBox = val;
  55094. },
  55095. enumerable: true,
  55096. configurable: true
  55097. });
  55098. Object.defineProperty(SolidParticleSystem.prototype, "depthSortParticles", {
  55099. /**
  55100. * Gets if `setParticles()` sorts or not the distance between each particle and the camera.
  55101. * Skipped when `enableDepthSort` is set to `false` (default) at construction time.
  55102. * Default : `true`
  55103. */
  55104. get: function () {
  55105. return this._depthSortParticles;
  55106. },
  55107. /**
  55108. * Tells to `setParticles()` to sort or not the distance between each particle and the camera.
  55109. * Skipped when `enableDepthSort` is set to `false` (default) at construction time.
  55110. * Default : `true`
  55111. */
  55112. set: function (val) {
  55113. this._depthSortParticles = val;
  55114. },
  55115. enumerable: true,
  55116. configurable: true
  55117. });
  55118. // =======================================================================
  55119. // Particle behavior logic
  55120. // these following methods may be overwritten by the user to fit his needs
  55121. /**
  55122. * This function does nothing. It may be overwritten to set all the particle first values.
  55123. * The SPS doesn't call this function, you may have to call it by your own.
  55124. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#particle-management
  55125. */
  55126. SolidParticleSystem.prototype.initParticles = function () {
  55127. };
  55128. /**
  55129. * This function does nothing. It may be overwritten to recycle a particle.
  55130. * The SPS doesn't call this function, you may have to call it by your own.
  55131. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#particle-management
  55132. * @param particle The particle to recycle
  55133. * @returns the recycled particle
  55134. */
  55135. SolidParticleSystem.prototype.recycleParticle = function (particle) {
  55136. return particle;
  55137. };
  55138. /**
  55139. * Updates a particle : this function should be overwritten by the user.
  55140. * It is called on each particle by `setParticles()`. This is the place to code each particle behavior.
  55141. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#particle-management
  55142. * @example : just set a particle position or velocity and recycle conditions
  55143. * @param particle The particle to update
  55144. * @returns the updated particle
  55145. */
  55146. SolidParticleSystem.prototype.updateParticle = function (particle) {
  55147. return particle;
  55148. };
  55149. /**
  55150. * Updates a vertex of a particle : it can be overwritten by the user.
  55151. * This will be called on each vertex particle by `setParticles()` if `computeParticleVertex` is set to true only.
  55152. * @param particle the current particle
  55153. * @param vertex the current index of the current particle
  55154. * @param pt the index of the current vertex in the particle shape
  55155. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#update-each-particle-shape
  55156. * @example : just set a vertex particle position
  55157. * @returns the updated vertex
  55158. */
  55159. SolidParticleSystem.prototype.updateParticleVertex = function (particle, vertex, pt) {
  55160. return vertex;
  55161. };
  55162. /**
  55163. * This will be called before any other treatment by `setParticles()` and will be passed three parameters.
  55164. * This does nothing and may be overwritten by the user.
  55165. * @param start the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  55166. * @param stop the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  55167. * @param update the boolean update value actually passed to setParticles()
  55168. */
  55169. SolidParticleSystem.prototype.beforeUpdateParticles = function (start, stop, update) {
  55170. };
  55171. /**
  55172. * This will be called by `setParticles()` after all the other treatments and just before the actual mesh update.
  55173. * This will be passed three parameters.
  55174. * This does nothing and may be overwritten by the user.
  55175. * @param start the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  55176. * @param stop the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  55177. * @param update the boolean update value actually passed to setParticles()
  55178. */
  55179. SolidParticleSystem.prototype.afterUpdateParticles = function (start, stop, update) {
  55180. };
  55181. return SolidParticleSystem;
  55182. }());
  55183. BABYLON.SolidParticleSystem = SolidParticleSystem;
  55184. })(BABYLON || (BABYLON = {}));
  55185. //# sourceMappingURL=babylon.solidParticleSystem.js.map
  55186. "use strict";
  55187. var BABYLON;
  55188. (function (BABYLON) {
  55189. var ShaderMaterial = /** @class */ (function (_super) {
  55190. __extends(ShaderMaterial, _super);
  55191. function ShaderMaterial(name, scene, shaderPath, options) {
  55192. var _this = _super.call(this, name, scene) || this;
  55193. _this._textures = {};
  55194. _this._textureArrays = {};
  55195. _this._floats = {};
  55196. _this._ints = {};
  55197. _this._floatsArrays = {};
  55198. _this._colors3 = {};
  55199. _this._colors3Arrays = {};
  55200. _this._colors4 = {};
  55201. _this._vectors2 = {};
  55202. _this._vectors3 = {};
  55203. _this._vectors4 = {};
  55204. _this._matrices = {};
  55205. _this._matrices3x3 = {};
  55206. _this._matrices2x2 = {};
  55207. _this._vectors2Arrays = {};
  55208. _this._vectors3Arrays = {};
  55209. _this._cachedWorldViewMatrix = new BABYLON.Matrix();
  55210. _this._shaderPath = shaderPath;
  55211. options.needAlphaBlending = options.needAlphaBlending || false;
  55212. options.needAlphaTesting = options.needAlphaTesting || false;
  55213. options.attributes = options.attributes || ["position", "normal", "uv"];
  55214. options.uniforms = options.uniforms || ["worldViewProjection"];
  55215. options.uniformBuffers = options.uniformBuffers || [];
  55216. options.samplers = options.samplers || [];
  55217. options.defines = options.defines || [];
  55218. _this._options = options;
  55219. return _this;
  55220. }
  55221. ShaderMaterial.prototype.getClassName = function () {
  55222. return "ShaderMaterial";
  55223. };
  55224. ShaderMaterial.prototype.needAlphaBlending = function () {
  55225. return this._options.needAlphaBlending;
  55226. };
  55227. ShaderMaterial.prototype.needAlphaTesting = function () {
  55228. return this._options.needAlphaTesting;
  55229. };
  55230. ShaderMaterial.prototype._checkUniform = function (uniformName) {
  55231. if (this._options.uniforms.indexOf(uniformName) === -1) {
  55232. this._options.uniforms.push(uniformName);
  55233. }
  55234. };
  55235. ShaderMaterial.prototype.setTexture = function (name, texture) {
  55236. if (this._options.samplers.indexOf(name) === -1) {
  55237. this._options.samplers.push(name);
  55238. }
  55239. this._textures[name] = texture;
  55240. return this;
  55241. };
  55242. ShaderMaterial.prototype.setTextureArray = function (name, textures) {
  55243. if (this._options.samplers.indexOf(name) === -1) {
  55244. this._options.samplers.push(name);
  55245. }
  55246. this._checkUniform(name);
  55247. this._textureArrays[name] = textures;
  55248. return this;
  55249. };
  55250. ShaderMaterial.prototype.setFloat = function (name, value) {
  55251. this._checkUniform(name);
  55252. this._floats[name] = value;
  55253. return this;
  55254. };
  55255. ShaderMaterial.prototype.setInt = function (name, value) {
  55256. this._checkUniform(name);
  55257. this._ints[name] = value;
  55258. return this;
  55259. };
  55260. ShaderMaterial.prototype.setFloats = function (name, value) {
  55261. this._checkUniform(name);
  55262. this._floatsArrays[name] = value;
  55263. return this;
  55264. };
  55265. ShaderMaterial.prototype.setColor3 = function (name, value) {
  55266. this._checkUniform(name);
  55267. this._colors3[name] = value;
  55268. return this;
  55269. };
  55270. ShaderMaterial.prototype.setColor3Array = function (name, value) {
  55271. this._checkUniform(name);
  55272. this._colors3Arrays[name] = value.reduce(function (arr, color) {
  55273. color.toArray(arr, arr.length);
  55274. return arr;
  55275. }, []);
  55276. return this;
  55277. };
  55278. ShaderMaterial.prototype.setColor4 = function (name, value) {
  55279. this._checkUniform(name);
  55280. this._colors4[name] = value;
  55281. return this;
  55282. };
  55283. ShaderMaterial.prototype.setVector2 = function (name, value) {
  55284. this._checkUniform(name);
  55285. this._vectors2[name] = value;
  55286. return this;
  55287. };
  55288. ShaderMaterial.prototype.setVector3 = function (name, value) {
  55289. this._checkUniform(name);
  55290. this._vectors3[name] = value;
  55291. return this;
  55292. };
  55293. ShaderMaterial.prototype.setVector4 = function (name, value) {
  55294. this._checkUniform(name);
  55295. this._vectors4[name] = value;
  55296. return this;
  55297. };
  55298. ShaderMaterial.prototype.setMatrix = function (name, value) {
  55299. this._checkUniform(name);
  55300. this._matrices[name] = value;
  55301. return this;
  55302. };
  55303. ShaderMaterial.prototype.setMatrix3x3 = function (name, value) {
  55304. this._checkUniform(name);
  55305. this._matrices3x3[name] = value;
  55306. return this;
  55307. };
  55308. ShaderMaterial.prototype.setMatrix2x2 = function (name, value) {
  55309. this._checkUniform(name);
  55310. this._matrices2x2[name] = value;
  55311. return this;
  55312. };
  55313. ShaderMaterial.prototype.setArray2 = function (name, value) {
  55314. this._checkUniform(name);
  55315. this._vectors2Arrays[name] = value;
  55316. return this;
  55317. };
  55318. ShaderMaterial.prototype.setArray3 = function (name, value) {
  55319. this._checkUniform(name);
  55320. this._vectors3Arrays[name] = value;
  55321. return this;
  55322. };
  55323. ShaderMaterial.prototype._checkCache = function (scene, mesh, useInstances) {
  55324. if (!mesh) {
  55325. return true;
  55326. }
  55327. if (this._effect && (this._effect.defines.indexOf("#define INSTANCES") !== -1) !== useInstances) {
  55328. return false;
  55329. }
  55330. return false;
  55331. };
  55332. ShaderMaterial.prototype.isReady = function (mesh, useInstances) {
  55333. var scene = this.getScene();
  55334. var engine = scene.getEngine();
  55335. if (!this.checkReadyOnEveryCall) {
  55336. if (this._renderId === scene.getRenderId()) {
  55337. if (this._checkCache(scene, mesh, useInstances)) {
  55338. return true;
  55339. }
  55340. }
  55341. }
  55342. // Instances
  55343. var defines = [];
  55344. var attribs = [];
  55345. var fallbacks = new BABYLON.EffectFallbacks();
  55346. if (useInstances) {
  55347. defines.push("#define INSTANCES");
  55348. }
  55349. for (var index = 0; index < this._options.defines.length; index++) {
  55350. defines.push(this._options.defines[index]);
  55351. }
  55352. for (var index = 0; index < this._options.attributes.length; index++) {
  55353. attribs.push(this._options.attributes[index]);
  55354. }
  55355. if (mesh && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  55356. attribs.push(BABYLON.VertexBuffer.ColorKind);
  55357. defines.push("#define VERTEXCOLOR");
  55358. }
  55359. // Bones
  55360. if (mesh && mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  55361. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  55362. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  55363. if (mesh.numBoneInfluencers > 4) {
  55364. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  55365. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  55366. }
  55367. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  55368. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  55369. fallbacks.addCPUSkinningFallback(0, mesh);
  55370. if (this._options.uniforms.indexOf("mBones") === -1) {
  55371. this._options.uniforms.push("mBones");
  55372. }
  55373. }
  55374. else {
  55375. defines.push("#define NUM_BONE_INFLUENCERS 0");
  55376. }
  55377. // Textures
  55378. for (var name in this._textures) {
  55379. if (!this._textures[name].isReady()) {
  55380. return false;
  55381. }
  55382. }
  55383. // Alpha test
  55384. if (mesh && this._shouldTurnAlphaTestOn(mesh)) {
  55385. defines.push("#define ALPHATEST");
  55386. }
  55387. var previousEffect = this._effect;
  55388. var join = defines.join("\n");
  55389. this._effect = engine.createEffect(this._shaderPath, {
  55390. attributes: attribs,
  55391. uniformsNames: this._options.uniforms,
  55392. uniformBuffersNames: this._options.uniformBuffers,
  55393. samplers: this._options.samplers,
  55394. defines: join,
  55395. fallbacks: fallbacks,
  55396. onCompiled: this.onCompiled,
  55397. onError: this.onError
  55398. }, engine);
  55399. if (!this._effect.isReady()) {
  55400. return false;
  55401. }
  55402. if (previousEffect !== this._effect) {
  55403. scene.resetCachedMaterial();
  55404. }
  55405. this._renderId = scene.getRenderId();
  55406. return true;
  55407. };
  55408. ShaderMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  55409. var scene = this.getScene();
  55410. if (!this._effect) {
  55411. return;
  55412. }
  55413. if (this._options.uniforms.indexOf("world") !== -1) {
  55414. this._effect.setMatrix("world", world);
  55415. }
  55416. if (this._options.uniforms.indexOf("worldView") !== -1) {
  55417. world.multiplyToRef(scene.getViewMatrix(), this._cachedWorldViewMatrix);
  55418. this._effect.setMatrix("worldView", this._cachedWorldViewMatrix);
  55419. }
  55420. if (this._options.uniforms.indexOf("worldViewProjection") !== -1) {
  55421. this._effect.setMatrix("worldViewProjection", world.multiply(scene.getTransformMatrix()));
  55422. }
  55423. };
  55424. ShaderMaterial.prototype.bind = function (world, mesh) {
  55425. // Std values
  55426. this.bindOnlyWorldMatrix(world);
  55427. if (this._effect && this.getScene().getCachedMaterial() !== this) {
  55428. if (this._options.uniforms.indexOf("view") !== -1) {
  55429. this._effect.setMatrix("view", this.getScene().getViewMatrix());
  55430. }
  55431. if (this._options.uniforms.indexOf("projection") !== -1) {
  55432. this._effect.setMatrix("projection", this.getScene().getProjectionMatrix());
  55433. }
  55434. if (this._options.uniforms.indexOf("viewProjection") !== -1) {
  55435. this._effect.setMatrix("viewProjection", this.getScene().getTransformMatrix());
  55436. }
  55437. // Bones
  55438. BABYLON.MaterialHelper.BindBonesParameters(mesh, this._effect);
  55439. var name;
  55440. // Texture
  55441. for (name in this._textures) {
  55442. this._effect.setTexture(name, this._textures[name]);
  55443. }
  55444. // Texture arrays
  55445. for (name in this._textureArrays) {
  55446. this._effect.setTextureArray(name, this._textureArrays[name]);
  55447. }
  55448. // Int
  55449. for (name in this._ints) {
  55450. this._effect.setInt(name, this._ints[name]);
  55451. }
  55452. // Float
  55453. for (name in this._floats) {
  55454. this._effect.setFloat(name, this._floats[name]);
  55455. }
  55456. // Floats
  55457. for (name in this._floatsArrays) {
  55458. this._effect.setArray(name, this._floatsArrays[name]);
  55459. }
  55460. // Color3
  55461. for (name in this._colors3) {
  55462. this._effect.setColor3(name, this._colors3[name]);
  55463. }
  55464. for (name in this._colors3Arrays) {
  55465. this._effect.setArray3(name, this._colors3Arrays[name]);
  55466. }
  55467. // Color4
  55468. for (name in this._colors4) {
  55469. var color = this._colors4[name];
  55470. this._effect.setFloat4(name, color.r, color.g, color.b, color.a);
  55471. }
  55472. // Vector2
  55473. for (name in this._vectors2) {
  55474. this._effect.setVector2(name, this._vectors2[name]);
  55475. }
  55476. // Vector3
  55477. for (name in this._vectors3) {
  55478. this._effect.setVector3(name, this._vectors3[name]);
  55479. }
  55480. // Vector4
  55481. for (name in this._vectors4) {
  55482. this._effect.setVector4(name, this._vectors4[name]);
  55483. }
  55484. // Matrix
  55485. for (name in this._matrices) {
  55486. this._effect.setMatrix(name, this._matrices[name]);
  55487. }
  55488. // Matrix 3x3
  55489. for (name in this._matrices3x3) {
  55490. this._effect.setMatrix3x3(name, this._matrices3x3[name]);
  55491. }
  55492. // Matrix 2x2
  55493. for (name in this._matrices2x2) {
  55494. this._effect.setMatrix2x2(name, this._matrices2x2[name]);
  55495. }
  55496. // Vector2Array
  55497. for (name in this._vectors2Arrays) {
  55498. this._effect.setArray2(name, this._vectors2Arrays[name]);
  55499. }
  55500. // Vector3Array
  55501. for (name in this._vectors3Arrays) {
  55502. this._effect.setArray3(name, this._vectors3Arrays[name]);
  55503. }
  55504. }
  55505. this._afterBind(mesh);
  55506. };
  55507. ShaderMaterial.prototype.getActiveTextures = function () {
  55508. var activeTextures = _super.prototype.getActiveTextures.call(this);
  55509. for (var name in this._textures) {
  55510. activeTextures.push(this._textures[name]);
  55511. }
  55512. for (var name in this._textureArrays) {
  55513. var array = this._textureArrays[name];
  55514. for (var index = 0; index < array.length; index++) {
  55515. activeTextures.push(array[index]);
  55516. }
  55517. }
  55518. return activeTextures;
  55519. };
  55520. ShaderMaterial.prototype.hasTexture = function (texture) {
  55521. if (_super.prototype.hasTexture.call(this, texture)) {
  55522. return true;
  55523. }
  55524. for (var name in this._textures) {
  55525. if (this._textures[name] === texture) {
  55526. return true;
  55527. }
  55528. }
  55529. for (var name in this._textureArrays) {
  55530. var array = this._textureArrays[name];
  55531. for (var index = 0; index < array.length; index++) {
  55532. if (array[index] === texture) {
  55533. return true;
  55534. }
  55535. }
  55536. }
  55537. return false;
  55538. };
  55539. ShaderMaterial.prototype.clone = function (name) {
  55540. var newShaderMaterial = new ShaderMaterial(name, this.getScene(), this._shaderPath, this._options);
  55541. return newShaderMaterial;
  55542. };
  55543. ShaderMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  55544. if (forceDisposeTextures) {
  55545. var name;
  55546. for (name in this._textures) {
  55547. this._textures[name].dispose();
  55548. }
  55549. for (name in this._textureArrays) {
  55550. var array = this._textureArrays[name];
  55551. for (var index = 0; index < array.length; index++) {
  55552. array[index].dispose();
  55553. }
  55554. }
  55555. }
  55556. this._textures = {};
  55557. _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);
  55558. };
  55559. ShaderMaterial.prototype.serialize = function () {
  55560. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  55561. serializationObject.customType = "BABYLON.ShaderMaterial";
  55562. serializationObject.options = this._options;
  55563. serializationObject.shaderPath = this._shaderPath;
  55564. var name;
  55565. // Texture
  55566. serializationObject.textures = {};
  55567. for (name in this._textures) {
  55568. serializationObject.textures[name] = this._textures[name].serialize();
  55569. }
  55570. // Texture arrays
  55571. serializationObject.textureArrays = {};
  55572. for (name in this._textureArrays) {
  55573. serializationObject.textureArrays[name] = [];
  55574. var array = this._textureArrays[name];
  55575. for (var index = 0; index < array.length; index++) {
  55576. serializationObject.textureArrays[name].push(array[index].serialize());
  55577. }
  55578. }
  55579. // Float
  55580. serializationObject.floats = {};
  55581. for (name in this._floats) {
  55582. serializationObject.floats[name] = this._floats[name];
  55583. }
  55584. // Float s
  55585. serializationObject.FloatArrays = {};
  55586. for (name in this._floatsArrays) {
  55587. serializationObject.FloatArrays[name] = this._floatsArrays[name];
  55588. }
  55589. // Color3
  55590. serializationObject.colors3 = {};
  55591. for (name in this._colors3) {
  55592. serializationObject.colors3[name] = this._colors3[name].asArray();
  55593. }
  55594. // Color3 array
  55595. serializationObject.colors3Arrays = {};
  55596. for (name in this._colors3Arrays) {
  55597. serializationObject.colors3Arrays[name] = this._colors3Arrays[name];
  55598. }
  55599. // Color4
  55600. serializationObject.colors4 = {};
  55601. for (name in this._colors4) {
  55602. serializationObject.colors4[name] = this._colors4[name].asArray();
  55603. }
  55604. // Vector2
  55605. serializationObject.vectors2 = {};
  55606. for (name in this._vectors2) {
  55607. serializationObject.vectors2[name] = this._vectors2[name].asArray();
  55608. }
  55609. // Vector3
  55610. serializationObject.vectors3 = {};
  55611. for (name in this._vectors3) {
  55612. serializationObject.vectors3[name] = this._vectors3[name].asArray();
  55613. }
  55614. // Vector4
  55615. serializationObject.vectors4 = {};
  55616. for (name in this._vectors4) {
  55617. serializationObject.vectors4[name] = this._vectors4[name].asArray();
  55618. }
  55619. // Matrix
  55620. serializationObject.matrices = {};
  55621. for (name in this._matrices) {
  55622. serializationObject.matrices[name] = this._matrices[name].asArray();
  55623. }
  55624. // Matrix 3x3
  55625. serializationObject.matrices3x3 = {};
  55626. for (name in this._matrices3x3) {
  55627. serializationObject.matrices3x3[name] = this._matrices3x3[name];
  55628. }
  55629. // Matrix 2x2
  55630. serializationObject.matrices2x2 = {};
  55631. for (name in this._matrices2x2) {
  55632. serializationObject.matrices2x2[name] = this._matrices2x2[name];
  55633. }
  55634. // Vector2Array
  55635. serializationObject.vectors2Arrays = {};
  55636. for (name in this._vectors2Arrays) {
  55637. serializationObject.vectors2Arrays[name] = this._vectors2Arrays[name];
  55638. }
  55639. // Vector3Array
  55640. serializationObject.vectors3Arrays = {};
  55641. for (name in this._vectors3Arrays) {
  55642. serializationObject.vectors3Arrays[name] = this._vectors3Arrays[name];
  55643. }
  55644. return serializationObject;
  55645. };
  55646. ShaderMaterial.Parse = function (source, scene, rootUrl) {
  55647. var material = BABYLON.SerializationHelper.Parse(function () { return new ShaderMaterial(source.name, scene, source.shaderPath, source.options); }, source, scene, rootUrl);
  55648. var name;
  55649. // Texture
  55650. for (name in source.textures) {
  55651. material.setTexture(name, BABYLON.Texture.Parse(source.textures[name], scene, rootUrl));
  55652. }
  55653. // Texture arrays
  55654. for (name in source.textureArrays) {
  55655. var array = source.textureArrays[name];
  55656. var textureArray = new Array();
  55657. for (var index = 0; index < array.length; index++) {
  55658. textureArray.push(BABYLON.Texture.Parse(array[index], scene, rootUrl));
  55659. }
  55660. material.setTextureArray(name, textureArray);
  55661. }
  55662. // Float
  55663. for (name in source.floats) {
  55664. material.setFloat(name, source.floats[name]);
  55665. }
  55666. // Float s
  55667. for (name in source.floatsArrays) {
  55668. material.setFloats(name, source.floatsArrays[name]);
  55669. }
  55670. // Color3
  55671. for (name in source.colors3) {
  55672. material.setColor3(name, BABYLON.Color3.FromArray(source.colors3[name]));
  55673. }
  55674. // Color3 arrays
  55675. for (name in source.colors3Arrays) {
  55676. var colors = source.colors3Arrays[name].reduce(function (arr, num, i) {
  55677. if (i % 3 === 0) {
  55678. arr.push([num]);
  55679. }
  55680. else {
  55681. arr[arr.length - 1].push(num);
  55682. }
  55683. return arr;
  55684. }, []).map(function (color) { return BABYLON.Color3.FromArray(color); });
  55685. material.setColor3Array(name, colors);
  55686. }
  55687. // Color4
  55688. for (name in source.colors4) {
  55689. material.setColor4(name, BABYLON.Color4.FromArray(source.colors4[name]));
  55690. }
  55691. // Vector2
  55692. for (name in source.vectors2) {
  55693. material.setVector2(name, BABYLON.Vector2.FromArray(source.vectors2[name]));
  55694. }
  55695. // Vector3
  55696. for (name in source.vectors3) {
  55697. material.setVector3(name, BABYLON.Vector3.FromArray(source.vectors3[name]));
  55698. }
  55699. // Vector4
  55700. for (name in source.vectors4) {
  55701. material.setVector4(name, BABYLON.Vector4.FromArray(source.vectors4[name]));
  55702. }
  55703. // Matrix
  55704. for (name in source.matrices) {
  55705. material.setMatrix(name, BABYLON.Matrix.FromArray(source.matrices[name]));
  55706. }
  55707. // Matrix 3x3
  55708. for (name in source.matrices3x3) {
  55709. material.setMatrix3x3(name, source.matrices3x3[name]);
  55710. }
  55711. // Matrix 2x2
  55712. for (name in source.matrices2x2) {
  55713. material.setMatrix2x2(name, source.matrices2x2[name]);
  55714. }
  55715. // Vector2Array
  55716. for (name in source.vectors2Arrays) {
  55717. material.setArray2(name, source.vectors2Arrays[name]);
  55718. }
  55719. // Vector3Array
  55720. for (name in source.vectors3Arrays) {
  55721. material.setArray3(name, source.vectors3Arrays[name]);
  55722. }
  55723. return material;
  55724. };
  55725. return ShaderMaterial;
  55726. }(BABYLON.Material));
  55727. BABYLON.ShaderMaterial = ShaderMaterial;
  55728. })(BABYLON || (BABYLON = {}));
  55729. //# sourceMappingURL=babylon.shaderMaterial.js.map
  55730. "use strict";
  55731. var BABYLON;
  55732. (function (BABYLON) {
  55733. var GroundMesh = /** @class */ (function (_super) {
  55734. __extends(GroundMesh, _super);
  55735. function GroundMesh(name, scene) {
  55736. var _this = _super.call(this, name, scene) || this;
  55737. _this.generateOctree = false;
  55738. return _this;
  55739. }
  55740. GroundMesh.prototype.getClassName = function () {
  55741. return "GroundMesh";
  55742. };
  55743. Object.defineProperty(GroundMesh.prototype, "subdivisions", {
  55744. get: function () {
  55745. return Math.min(this._subdivisionsX, this._subdivisionsY);
  55746. },
  55747. enumerable: true,
  55748. configurable: true
  55749. });
  55750. Object.defineProperty(GroundMesh.prototype, "subdivisionsX", {
  55751. get: function () {
  55752. return this._subdivisionsX;
  55753. },
  55754. enumerable: true,
  55755. configurable: true
  55756. });
  55757. Object.defineProperty(GroundMesh.prototype, "subdivisionsY", {
  55758. get: function () {
  55759. return this._subdivisionsY;
  55760. },
  55761. enumerable: true,
  55762. configurable: true
  55763. });
  55764. GroundMesh.prototype.optimize = function (chunksCount, octreeBlocksSize) {
  55765. if (octreeBlocksSize === void 0) { octreeBlocksSize = 32; }
  55766. this._subdivisionsX = chunksCount;
  55767. this._subdivisionsY = chunksCount;
  55768. this.subdivide(chunksCount);
  55769. this.createOrUpdateSubmeshesOctree(octreeBlocksSize);
  55770. };
  55771. /**
  55772. * Returns a height (y) value in the Worl system :
  55773. * the ground altitude at the coordinates (x, z) expressed in the World system.
  55774. * Returns the ground y position if (x, z) are outside the ground surface.
  55775. */
  55776. GroundMesh.prototype.getHeightAtCoordinates = function (x, z) {
  55777. var world = this.getWorldMatrix();
  55778. var invMat = BABYLON.Tmp.Matrix[5];
  55779. world.invertToRef(invMat);
  55780. var tmpVect = BABYLON.Tmp.Vector3[8];
  55781. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, 0.0, z, invMat, tmpVect); // transform x,z in the mesh local space
  55782. x = tmpVect.x;
  55783. z = tmpVect.z;
  55784. if (x < this._minX || x > this._maxX || z < this._minZ || z > this._maxZ) {
  55785. return this.position.y;
  55786. }
  55787. if (!this._heightQuads || this._heightQuads.length == 0) {
  55788. this._initHeightQuads();
  55789. this._computeHeightQuads();
  55790. }
  55791. var facet = this._getFacetAt(x, z);
  55792. var y = -(facet.x * x + facet.z * z + facet.w) / facet.y;
  55793. // return y in the World system
  55794. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(0.0, y, 0.0, world, tmpVect);
  55795. return tmpVect.y;
  55796. };
  55797. /**
  55798. * Returns a normalized vector (Vector3) orthogonal to the ground
  55799. * at the ground coordinates (x, z) expressed in the World system.
  55800. * Returns Vector3(0.0, 1.0, 0.0) if (x, z) are outside the ground surface.
  55801. */
  55802. GroundMesh.prototype.getNormalAtCoordinates = function (x, z) {
  55803. var normal = new BABYLON.Vector3(0.0, 1.0, 0.0);
  55804. this.getNormalAtCoordinatesToRef(x, z, normal);
  55805. return normal;
  55806. };
  55807. /**
  55808. * Updates the Vector3 passed a reference with a normalized vector orthogonal to the ground
  55809. * at the ground coordinates (x, z) expressed in the World system.
  55810. * Doesn't uptade the reference Vector3 if (x, z) are outside the ground surface.
  55811. * Returns the GroundMesh.
  55812. */
  55813. GroundMesh.prototype.getNormalAtCoordinatesToRef = function (x, z, ref) {
  55814. var world = this.getWorldMatrix();
  55815. var tmpMat = BABYLON.Tmp.Matrix[5];
  55816. world.invertToRef(tmpMat);
  55817. var tmpVect = BABYLON.Tmp.Vector3[8];
  55818. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, 0.0, z, tmpMat, tmpVect); // transform x,z in the mesh local space
  55819. x = tmpVect.x;
  55820. z = tmpVect.z;
  55821. if (x < this._minX || x > this._maxX || z < this._minZ || z > this._maxZ) {
  55822. return this;
  55823. }
  55824. if (!this._heightQuads || this._heightQuads.length == 0) {
  55825. this._initHeightQuads();
  55826. this._computeHeightQuads();
  55827. }
  55828. var facet = this._getFacetAt(x, z);
  55829. BABYLON.Vector3.TransformNormalFromFloatsToRef(facet.x, facet.y, facet.z, world, ref);
  55830. return this;
  55831. };
  55832. /**
  55833. * Force the heights to be recomputed for getHeightAtCoordinates() or getNormalAtCoordinates()
  55834. * if the ground has been updated.
  55835. * This can be used in the render loop.
  55836. * Returns the GroundMesh.
  55837. */
  55838. GroundMesh.prototype.updateCoordinateHeights = function () {
  55839. if (!this._heightQuads || this._heightQuads.length == 0) {
  55840. this._initHeightQuads();
  55841. }
  55842. this._computeHeightQuads();
  55843. return this;
  55844. };
  55845. // Returns the element "facet" from the heightQuads array relative to (x, z) local coordinates
  55846. GroundMesh.prototype._getFacetAt = function (x, z) {
  55847. // retrieve col and row from x, z coordinates in the ground local system
  55848. var col = Math.floor((x + this._maxX) * this._subdivisionsX / this._width);
  55849. var row = Math.floor(-(z + this._maxZ) * this._subdivisionsY / this._height + this._subdivisionsY);
  55850. var quad = this._heightQuads[row * this._subdivisionsX + col];
  55851. var facet;
  55852. if (z < quad.slope.x * x + quad.slope.y) {
  55853. facet = quad.facet1;
  55854. }
  55855. else {
  55856. facet = quad.facet2;
  55857. }
  55858. return facet;
  55859. };
  55860. // Creates and populates the heightMap array with "facet" elements :
  55861. // a quad is two triangular facets separated by a slope, so a "facet" element is 1 slope + 2 facets
  55862. // slope : Vector2(c, h) = 2D diagonal line equation setting appart two triangular facets in a quad : z = cx + h
  55863. // facet1 : Vector4(a, b, c, d) = first facet 3D plane equation : ax + by + cz + d = 0
  55864. // facet2 : Vector4(a, b, c, d) = second facet 3D plane equation : ax + by + cz + d = 0
  55865. // Returns the GroundMesh.
  55866. GroundMesh.prototype._initHeightQuads = function () {
  55867. var subdivisionsX = this._subdivisionsX;
  55868. var subdivisionsY = this._subdivisionsY;
  55869. this._heightQuads = new Array();
  55870. for (var row = 0; row < subdivisionsY; row++) {
  55871. for (var col = 0; col < subdivisionsX; col++) {
  55872. 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) };
  55873. this._heightQuads[row * subdivisionsX + col] = quad;
  55874. }
  55875. }
  55876. return this;
  55877. };
  55878. // Compute each quad element values and update the the heightMap array :
  55879. // slope : Vector2(c, h) = 2D diagonal line equation setting appart two triangular facets in a quad : z = cx + h
  55880. // facet1 : Vector4(a, b, c, d) = first facet 3D plane equation : ax + by + cz + d = 0
  55881. // facet2 : Vector4(a, b, c, d) = second facet 3D plane equation : ax + by + cz + d = 0
  55882. // Returns the GroundMesh.
  55883. GroundMesh.prototype._computeHeightQuads = function () {
  55884. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  55885. if (!positions) {
  55886. return this;
  55887. }
  55888. var v1 = BABYLON.Tmp.Vector3[3];
  55889. var v2 = BABYLON.Tmp.Vector3[2];
  55890. var v3 = BABYLON.Tmp.Vector3[1];
  55891. var v4 = BABYLON.Tmp.Vector3[0];
  55892. var v1v2 = BABYLON.Tmp.Vector3[4];
  55893. var v1v3 = BABYLON.Tmp.Vector3[5];
  55894. var v1v4 = BABYLON.Tmp.Vector3[6];
  55895. var norm1 = BABYLON.Tmp.Vector3[7];
  55896. var norm2 = BABYLON.Tmp.Vector3[8];
  55897. var i = 0;
  55898. var j = 0;
  55899. var k = 0;
  55900. var cd = 0; // 2D slope coefficient : z = cd * x + h
  55901. var h = 0;
  55902. var d1 = 0; // facet plane equation : ax + by + cz + d = 0
  55903. var d2 = 0;
  55904. var subdivisionsX = this._subdivisionsX;
  55905. var subdivisionsY = this._subdivisionsY;
  55906. for (var row = 0; row < subdivisionsY; row++) {
  55907. for (var col = 0; col < subdivisionsX; col++) {
  55908. i = col * 3;
  55909. j = row * (subdivisionsX + 1) * 3;
  55910. k = (row + 1) * (subdivisionsX + 1) * 3;
  55911. v1.x = positions[j + i];
  55912. v1.y = positions[j + i + 1];
  55913. v1.z = positions[j + i + 2];
  55914. v2.x = positions[j + i + 3];
  55915. v2.y = positions[j + i + 4];
  55916. v2.z = positions[j + i + 5];
  55917. v3.x = positions[k + i];
  55918. v3.y = positions[k + i + 1];
  55919. v3.z = positions[k + i + 2];
  55920. v4.x = positions[k + i + 3];
  55921. v4.y = positions[k + i + 4];
  55922. v4.z = positions[k + i + 5];
  55923. // 2D slope V1V4
  55924. cd = (v4.z - v1.z) / (v4.x - v1.x);
  55925. h = v1.z - cd * v1.x; // v1 belongs to the slope
  55926. // facet equations :
  55927. // we compute each facet normal vector
  55928. // the equation of the facet plane is : norm.x * x + norm.y * y + norm.z * z + d = 0
  55929. // we compute the value d by applying the equation to v1 which belongs to the plane
  55930. // then we store the facet equation in a Vector4
  55931. v2.subtractToRef(v1, v1v2);
  55932. v3.subtractToRef(v1, v1v3);
  55933. v4.subtractToRef(v1, v1v4);
  55934. BABYLON.Vector3.CrossToRef(v1v4, v1v3, norm1); // caution : CrossToRef uses the Tmp class
  55935. BABYLON.Vector3.CrossToRef(v1v2, v1v4, norm2);
  55936. norm1.normalize();
  55937. norm2.normalize();
  55938. d1 = -(norm1.x * v1.x + norm1.y * v1.y + norm1.z * v1.z);
  55939. d2 = -(norm2.x * v2.x + norm2.y * v2.y + norm2.z * v2.z);
  55940. var quad = this._heightQuads[row * subdivisionsX + col];
  55941. quad.slope.copyFromFloats(cd, h);
  55942. quad.facet1.copyFromFloats(norm1.x, norm1.y, norm1.z, d1);
  55943. quad.facet2.copyFromFloats(norm2.x, norm2.y, norm2.z, d2);
  55944. }
  55945. }
  55946. return this;
  55947. };
  55948. GroundMesh.prototype.serialize = function (serializationObject) {
  55949. _super.prototype.serialize.call(this, serializationObject);
  55950. serializationObject.subdivisionsX = this._subdivisionsX;
  55951. serializationObject.subdivisionsY = this._subdivisionsY;
  55952. serializationObject.minX = this._minX;
  55953. serializationObject.maxX = this._maxX;
  55954. serializationObject.minZ = this._minZ;
  55955. serializationObject.maxZ = this._maxZ;
  55956. serializationObject.width = this._width;
  55957. serializationObject.height = this._height;
  55958. };
  55959. GroundMesh.Parse = function (parsedMesh, scene) {
  55960. var result = new GroundMesh(parsedMesh.name, scene);
  55961. result._subdivisionsX = parsedMesh.subdivisionsX || 1;
  55962. result._subdivisionsY = parsedMesh.subdivisionsY || 1;
  55963. result._minX = parsedMesh.minX;
  55964. result._maxX = parsedMesh.maxX;
  55965. result._minZ = parsedMesh.minZ;
  55966. result._maxZ = parsedMesh.maxZ;
  55967. result._width = parsedMesh.width;
  55968. result._height = parsedMesh.height;
  55969. return result;
  55970. };
  55971. return GroundMesh;
  55972. }(BABYLON.Mesh));
  55973. BABYLON.GroundMesh = GroundMesh;
  55974. })(BABYLON || (BABYLON = {}));
  55975. //# sourceMappingURL=babylon.groundMesh.js.map
  55976. "use strict";
  55977. var BABYLON;
  55978. (function (BABYLON) {
  55979. /**
  55980. * Creates an instance based on a source mesh.
  55981. */
  55982. var InstancedMesh = /** @class */ (function (_super) {
  55983. __extends(InstancedMesh, _super);
  55984. function InstancedMesh(name, source) {
  55985. var _this = _super.call(this, name, source.getScene()) || this;
  55986. source.instances.push(_this);
  55987. _this._sourceMesh = source;
  55988. _this.position.copyFrom(source.position);
  55989. _this.rotation.copyFrom(source.rotation);
  55990. _this.scaling.copyFrom(source.scaling);
  55991. if (source.rotationQuaternion) {
  55992. _this.rotationQuaternion = source.rotationQuaternion.clone();
  55993. }
  55994. _this.infiniteDistance = source.infiniteDistance;
  55995. _this.setPivotMatrix(source.getPivotMatrix());
  55996. _this.refreshBoundingInfo();
  55997. _this._syncSubMeshes();
  55998. return _this;
  55999. }
  56000. /**
  56001. * Returns the string "InstancedMesh".
  56002. */
  56003. InstancedMesh.prototype.getClassName = function () {
  56004. return "InstancedMesh";
  56005. };
  56006. Object.defineProperty(InstancedMesh.prototype, "receiveShadows", {
  56007. // Methods
  56008. get: function () {
  56009. return this._sourceMesh.receiveShadows;
  56010. },
  56011. enumerable: true,
  56012. configurable: true
  56013. });
  56014. Object.defineProperty(InstancedMesh.prototype, "material", {
  56015. get: function () {
  56016. return this._sourceMesh.material;
  56017. },
  56018. enumerable: true,
  56019. configurable: true
  56020. });
  56021. Object.defineProperty(InstancedMesh.prototype, "visibility", {
  56022. get: function () {
  56023. return this._sourceMesh.visibility;
  56024. },
  56025. enumerable: true,
  56026. configurable: true
  56027. });
  56028. Object.defineProperty(InstancedMesh.prototype, "skeleton", {
  56029. get: function () {
  56030. return this._sourceMesh.skeleton;
  56031. },
  56032. enumerable: true,
  56033. configurable: true
  56034. });
  56035. Object.defineProperty(InstancedMesh.prototype, "renderingGroupId", {
  56036. get: function () {
  56037. return this._sourceMesh.renderingGroupId;
  56038. },
  56039. set: function (value) {
  56040. if (!this._sourceMesh || value === this._sourceMesh.renderingGroupId) {
  56041. return;
  56042. }
  56043. //no-op with warning
  56044. BABYLON.Tools.Warn("Note - setting renderingGroupId of an instanced mesh has no effect on the scene");
  56045. },
  56046. enumerable: true,
  56047. configurable: true
  56048. });
  56049. /**
  56050. * Returns the total number of vertices (integer).
  56051. */
  56052. InstancedMesh.prototype.getTotalVertices = function () {
  56053. return this._sourceMesh.getTotalVertices();
  56054. };
  56055. Object.defineProperty(InstancedMesh.prototype, "sourceMesh", {
  56056. get: function () {
  56057. return this._sourceMesh;
  56058. },
  56059. enumerable: true,
  56060. configurable: true
  56061. });
  56062. /**
  56063. * Is this node ready to be used/rendered
  56064. * @param completeCheck defines if a complete check (including materials and lights) has to be done (false by default)
  56065. * @return {boolean} is it ready
  56066. */
  56067. InstancedMesh.prototype.isReady = function (completeCheck) {
  56068. if (completeCheck === void 0) { completeCheck = false; }
  56069. return this._sourceMesh.isReady(completeCheck, true);
  56070. };
  56071. /**
  56072. * Returns a float array or a Float32Array of the requested kind of data : positons, normals, uvs, etc.
  56073. */
  56074. InstancedMesh.prototype.getVerticesData = function (kind, copyWhenShared) {
  56075. return this._sourceMesh.getVerticesData(kind, copyWhenShared);
  56076. };
  56077. /**
  56078. * Sets the vertex data of the mesh geometry for the requested `kind`.
  56079. * If the mesh has no geometry, a new Geometry object is set to the mesh and then passed this vertex data.
  56080. * The `data` are either a numeric array either a Float32Array.
  56081. * The parameter `updatable` is passed as is to the underlying Geometry object constructor (if initianilly none) or updater.
  56082. * 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).
  56083. * Note that a new underlying VertexBuffer object is created each call.
  56084. * If the `kind` is the `PositionKind`, the mesh BoundingInfo is renewed, so the bounding box and sphere, and the mesh World Matrix is recomputed.
  56085. *
  56086. * Possible `kind` values :
  56087. * - BABYLON.VertexBuffer.PositionKind
  56088. * - BABYLON.VertexBuffer.UVKind
  56089. * - BABYLON.VertexBuffer.UV2Kind
  56090. * - BABYLON.VertexBuffer.UV3Kind
  56091. * - BABYLON.VertexBuffer.UV4Kind
  56092. * - BABYLON.VertexBuffer.UV5Kind
  56093. * - BABYLON.VertexBuffer.UV6Kind
  56094. * - BABYLON.VertexBuffer.ColorKind
  56095. * - BABYLON.VertexBuffer.MatricesIndicesKind
  56096. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  56097. * - BABYLON.VertexBuffer.MatricesWeightsKind
  56098. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  56099. *
  56100. * Returns the Mesh.
  56101. */
  56102. InstancedMesh.prototype.setVerticesData = function (kind, data, updatable, stride) {
  56103. if (this.sourceMesh) {
  56104. this.sourceMesh.setVerticesData(kind, data, updatable, stride);
  56105. }
  56106. return this.sourceMesh;
  56107. };
  56108. /**
  56109. * Updates the existing vertex data of the mesh geometry for the requested `kind`.
  56110. * If the mesh has no geometry, it is simply returned as it is.
  56111. * The `data` are either a numeric array either a Float32Array.
  56112. * No new underlying VertexBuffer object is created.
  56113. * 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.
  56114. * If the parameter `makeItUnique` is true, a new global geometry is created from this positions and is set to the mesh.
  56115. *
  56116. * Possible `kind` values :
  56117. * - BABYLON.VertexBuffer.PositionKind
  56118. * - BABYLON.VertexBuffer.UVKind
  56119. * - BABYLON.VertexBuffer.UV2Kind
  56120. * - BABYLON.VertexBuffer.UV3Kind
  56121. * - BABYLON.VertexBuffer.UV4Kind
  56122. * - BABYLON.VertexBuffer.UV5Kind
  56123. * - BABYLON.VertexBuffer.UV6Kind
  56124. * - BABYLON.VertexBuffer.ColorKind
  56125. * - BABYLON.VertexBuffer.MatricesIndicesKind
  56126. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  56127. * - BABYLON.VertexBuffer.MatricesWeightsKind
  56128. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  56129. *
  56130. * Returns the Mesh.
  56131. */
  56132. InstancedMesh.prototype.updateVerticesData = function (kind, data, updateExtends, makeItUnique) {
  56133. if (this.sourceMesh) {
  56134. this.sourceMesh.updateVerticesData(kind, data, updateExtends, makeItUnique);
  56135. }
  56136. return this.sourceMesh;
  56137. };
  56138. /**
  56139. * Sets the mesh indices.
  56140. * Expects an array populated with integers or a typed array (Int32Array, Uint32Array, Uint16Array).
  56141. * If the mesh has no geometry, a new Geometry object is created and set to the mesh.
  56142. * This method creates a new index buffer each call.
  56143. * Returns the Mesh.
  56144. */
  56145. InstancedMesh.prototype.setIndices = function (indices, totalVertices) {
  56146. if (totalVertices === void 0) { totalVertices = null; }
  56147. if (this.sourceMesh) {
  56148. this.sourceMesh.setIndices(indices, totalVertices);
  56149. }
  56150. return this.sourceMesh;
  56151. };
  56152. /**
  56153. * Boolean : True if the mesh owns the requested kind of data.
  56154. */
  56155. InstancedMesh.prototype.isVerticesDataPresent = function (kind) {
  56156. return this._sourceMesh.isVerticesDataPresent(kind);
  56157. };
  56158. /**
  56159. * Returns an array of indices (IndicesArray).
  56160. */
  56161. InstancedMesh.prototype.getIndices = function () {
  56162. return this._sourceMesh.getIndices();
  56163. };
  56164. Object.defineProperty(InstancedMesh.prototype, "_positions", {
  56165. get: function () {
  56166. return this._sourceMesh._positions;
  56167. },
  56168. enumerable: true,
  56169. configurable: true
  56170. });
  56171. /**
  56172. * Sets a new updated BoundingInfo to the mesh.
  56173. * Returns the mesh.
  56174. */
  56175. InstancedMesh.prototype.refreshBoundingInfo = function () {
  56176. var meshBB = this._sourceMesh.getBoundingInfo();
  56177. this._boundingInfo = new BABYLON.BoundingInfo(meshBB.minimum.clone(), meshBB.maximum.clone());
  56178. this._updateBoundingInfo();
  56179. return this;
  56180. };
  56181. InstancedMesh.prototype._preActivate = function () {
  56182. if (this._currentLOD) {
  56183. this._currentLOD._preActivate();
  56184. }
  56185. return this;
  56186. };
  56187. InstancedMesh.prototype._activate = function (renderId) {
  56188. if (this._currentLOD) {
  56189. this._currentLOD._registerInstanceForRenderId(this, renderId);
  56190. }
  56191. return this;
  56192. };
  56193. /**
  56194. * Returns the current associated LOD AbstractMesh.
  56195. */
  56196. InstancedMesh.prototype.getLOD = function (camera) {
  56197. if (!camera) {
  56198. return this;
  56199. }
  56200. var boundingInfo = this.getBoundingInfo();
  56201. this._currentLOD = this.sourceMesh.getLOD(camera, boundingInfo.boundingSphere);
  56202. if (this._currentLOD === this.sourceMesh) {
  56203. return this;
  56204. }
  56205. return this._currentLOD;
  56206. };
  56207. InstancedMesh.prototype._syncSubMeshes = function () {
  56208. this.releaseSubMeshes();
  56209. if (this._sourceMesh.subMeshes) {
  56210. for (var index = 0; index < this._sourceMesh.subMeshes.length; index++) {
  56211. this._sourceMesh.subMeshes[index].clone(this, this._sourceMesh);
  56212. }
  56213. }
  56214. return this;
  56215. };
  56216. InstancedMesh.prototype._generatePointsArray = function () {
  56217. return this._sourceMesh._generatePointsArray();
  56218. };
  56219. /**
  56220. * Creates a new InstancedMesh from the current mesh.
  56221. * - name (string) : the cloned mesh name
  56222. * - newParent (optional Node) : the optional Node to parent the clone to.
  56223. * - doNotCloneChildren (optional boolean, default `false`) : if `true` the model children aren't cloned.
  56224. *
  56225. * Returns the clone.
  56226. */
  56227. InstancedMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  56228. var result = this._sourceMesh.createInstance(name);
  56229. // Deep copy
  56230. BABYLON.Tools.DeepCopy(this, result, ["name", "subMeshes", "uniqueId"], []);
  56231. // Bounding info
  56232. this.refreshBoundingInfo();
  56233. // Parent
  56234. if (newParent) {
  56235. result.parent = newParent;
  56236. }
  56237. if (!doNotCloneChildren) {
  56238. // Children
  56239. for (var index = 0; index < this.getScene().meshes.length; index++) {
  56240. var mesh = this.getScene().meshes[index];
  56241. if (mesh.parent === this) {
  56242. mesh.clone(mesh.name, result);
  56243. }
  56244. }
  56245. }
  56246. result.computeWorldMatrix(true);
  56247. return result;
  56248. };
  56249. /**
  56250. * Disposes the InstancedMesh.
  56251. * Returns nothing.
  56252. */
  56253. InstancedMesh.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  56254. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  56255. // Remove from mesh
  56256. var index = this._sourceMesh.instances.indexOf(this);
  56257. this._sourceMesh.instances.splice(index, 1);
  56258. _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
  56259. };
  56260. return InstancedMesh;
  56261. }(BABYLON.AbstractMesh));
  56262. BABYLON.InstancedMesh = InstancedMesh;
  56263. })(BABYLON || (BABYLON = {}));
  56264. //# sourceMappingURL=babylon.instancedMesh.js.map
  56265. "use strict";
  56266. var BABYLON;
  56267. (function (BABYLON) {
  56268. var LinesMesh = /** @class */ (function (_super) {
  56269. __extends(LinesMesh, _super);
  56270. function LinesMesh(name, scene, parent, source, doNotCloneChildren, useVertexColor, useVertexAlpha) {
  56271. if (scene === void 0) { scene = null; }
  56272. if (parent === void 0) { parent = null; }
  56273. var _this = _super.call(this, name, scene, parent, source, doNotCloneChildren) || this;
  56274. _this.useVertexColor = useVertexColor;
  56275. _this.useVertexAlpha = useVertexAlpha;
  56276. _this.color = new BABYLON.Color3(1, 1, 1);
  56277. _this.alpha = 1;
  56278. if (source) {
  56279. _this.color = source.color.clone();
  56280. _this.alpha = source.alpha;
  56281. _this.useVertexColor = source.useVertexColor;
  56282. _this.useVertexAlpha = source.useVertexAlpha;
  56283. }
  56284. _this._intersectionThreshold = 0.1;
  56285. var defines = [];
  56286. var options = {
  56287. attributes: [BABYLON.VertexBuffer.PositionKind],
  56288. uniforms: ["world", "viewProjection"],
  56289. needAlphaBlending: true,
  56290. defines: defines
  56291. };
  56292. if (useVertexAlpha === false) {
  56293. options.needAlphaBlending = false;
  56294. }
  56295. if (!useVertexColor) {
  56296. options.uniforms.push("color");
  56297. }
  56298. else {
  56299. options.defines.push("#define VERTEXCOLOR");
  56300. options.attributes.push(BABYLON.VertexBuffer.ColorKind);
  56301. }
  56302. _this._colorShader = new BABYLON.ShaderMaterial("colorShader", _this.getScene(), "color", options);
  56303. return _this;
  56304. }
  56305. Object.defineProperty(LinesMesh.prototype, "intersectionThreshold", {
  56306. /**
  56307. * The intersection Threshold is the margin applied when intersection a segment of the LinesMesh with a Ray.
  56308. * This margin is expressed in world space coordinates, so its value may vary.
  56309. * Default value is 0.1
  56310. * @returns the intersection Threshold value.
  56311. */
  56312. get: function () {
  56313. return this._intersectionThreshold;
  56314. },
  56315. /**
  56316. * The intersection Threshold is the margin applied when intersection a segment of the LinesMesh with a Ray.
  56317. * This margin is expressed in world space coordinates, so its value may vary.
  56318. * @param value the new threshold to apply
  56319. */
  56320. set: function (value) {
  56321. if (this._intersectionThreshold === value) {
  56322. return;
  56323. }
  56324. this._intersectionThreshold = value;
  56325. if (this.geometry) {
  56326. this.geometry.boundingBias = new BABYLON.Vector2(0, value);
  56327. }
  56328. },
  56329. enumerable: true,
  56330. configurable: true
  56331. });
  56332. /**
  56333. * Returns the string "LineMesh"
  56334. */
  56335. LinesMesh.prototype.getClassName = function () {
  56336. return "LinesMesh";
  56337. };
  56338. Object.defineProperty(LinesMesh.prototype, "material", {
  56339. get: function () {
  56340. return this._colorShader;
  56341. },
  56342. set: function (value) {
  56343. // Do nothing
  56344. },
  56345. enumerable: true,
  56346. configurable: true
  56347. });
  56348. Object.defineProperty(LinesMesh.prototype, "checkCollisions", {
  56349. get: function () {
  56350. return false;
  56351. },
  56352. enumerable: true,
  56353. configurable: true
  56354. });
  56355. LinesMesh.prototype.createInstance = function (name) {
  56356. throw new Error("LinesMeshes do not support createInstance.");
  56357. };
  56358. LinesMesh.prototype._bind = function (subMesh, effect, fillMode) {
  56359. if (!this._geometry) {
  56360. return this;
  56361. }
  56362. // VBOs
  56363. this._geometry._bind(this._colorShader.getEffect());
  56364. // Color
  56365. if (!this.useVertexColor) {
  56366. this._colorShader.setColor4("color", this.color.toColor4(this.alpha));
  56367. }
  56368. return this;
  56369. };
  56370. LinesMesh.prototype._draw = function (subMesh, fillMode, instancesCount) {
  56371. if (!this._geometry || !this._geometry.getVertexBuffers() || !this._geometry.getIndexBuffer()) {
  56372. return this;
  56373. }
  56374. var engine = this.getScene().getEngine();
  56375. // Draw order
  56376. engine.drawElementsType(BABYLON.Material.LineListDrawMode, subMesh.indexStart, subMesh.indexCount);
  56377. return this;
  56378. };
  56379. LinesMesh.prototype.dispose = function (doNotRecurse) {
  56380. this._colorShader.dispose();
  56381. _super.prototype.dispose.call(this, doNotRecurse);
  56382. };
  56383. /**
  56384. * Returns a new LineMesh object cloned from the current one.
  56385. */
  56386. LinesMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  56387. return new LinesMesh(name, this.getScene(), newParent, this, doNotCloneChildren);
  56388. };
  56389. return LinesMesh;
  56390. }(BABYLON.Mesh));
  56391. BABYLON.LinesMesh = LinesMesh;
  56392. })(BABYLON || (BABYLON = {}));
  56393. //# sourceMappingURL=babylon.linesMesh.js.map
  56394. "use strict";
  56395. var BABYLON;
  56396. (function (BABYLON) {
  56397. var MeshBuilder = /** @class */ (function () {
  56398. function MeshBuilder() {
  56399. }
  56400. MeshBuilder.updateSideOrientation = function (orientation) {
  56401. if (orientation == BABYLON.Mesh.DOUBLESIDE) {
  56402. return BABYLON.Mesh.DOUBLESIDE;
  56403. }
  56404. if (orientation === undefined || orientation === null) {
  56405. return BABYLON.Mesh.FRONTSIDE;
  56406. }
  56407. return orientation;
  56408. };
  56409. /**
  56410. * Creates a box mesh.
  56411. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#box
  56412. * The parameter `size` sets the size (float) of each box side (default 1).
  56413. * You can set some different box dimensions by using the parameters `width`, `height` and `depth` (all by default have the same value than `size`).
  56414. * 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).
  56415. * Please read this tutorial : http://doc.babylonjs.com/tutorials/CreateBox_Per_Face_Textures_And_Colors
  56416. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  56417. * 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).
  56418. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  56419. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  56420. */
  56421. MeshBuilder.CreateBox = function (name, options, scene) {
  56422. if (scene === void 0) { scene = null; }
  56423. var box = new BABYLON.Mesh(name, scene);
  56424. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  56425. box._originalBuilderSideOrientation = options.sideOrientation;
  56426. var vertexData = BABYLON.VertexData.CreateBox(options);
  56427. vertexData.applyToMesh(box, options.updatable);
  56428. return box;
  56429. };
  56430. /**
  56431. * Creates a sphere mesh.
  56432. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#sphere
  56433. * The parameter `diameter` sets the diameter size (float) of the sphere (default 1).
  56434. * 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`).
  56435. * The parameter `segments` sets the sphere number of horizontal stripes (positive integer, default 32).
  56436. * 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
  56437. * 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).
  56438. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  56439. * 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).
  56440. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  56441. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  56442. */
  56443. MeshBuilder.CreateSphere = function (name, options, scene) {
  56444. var sphere = new BABYLON.Mesh(name, scene);
  56445. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  56446. sphere._originalBuilderSideOrientation = options.sideOrientation;
  56447. var vertexData = BABYLON.VertexData.CreateSphere(options);
  56448. vertexData.applyToMesh(sphere, options.updatable);
  56449. return sphere;
  56450. };
  56451. /**
  56452. * Creates a plane polygonal mesh. By default, this is a disc.
  56453. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#disc
  56454. * The parameter `radius` sets the radius size (float) of the polygon (default 0.5).
  56455. * 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.
  56456. * 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
  56457. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  56458. * 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).
  56459. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  56460. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  56461. */
  56462. MeshBuilder.CreateDisc = function (name, options, scene) {
  56463. if (scene === void 0) { scene = null; }
  56464. var disc = new BABYLON.Mesh(name, scene);
  56465. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  56466. disc._originalBuilderSideOrientation = options.sideOrientation;
  56467. var vertexData = BABYLON.VertexData.CreateDisc(options);
  56468. vertexData.applyToMesh(disc, options.updatable);
  56469. return disc;
  56470. };
  56471. /**
  56472. * Creates a sphere based upon an icosahedron with 20 triangular faces which can be subdivided.
  56473. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#icosphere
  56474. * The parameter `radius` sets the radius size (float) of the icosphere (default 1).
  56475. * 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`).
  56476. * The parameter `subdivisions` sets the number of subdivisions (postive integer, default 4). The more subdivisions, the more faces on the icosphere whatever its size.
  56477. * 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.
  56478. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  56479. * 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).
  56480. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  56481. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  56482. */
  56483. MeshBuilder.CreateIcoSphere = function (name, options, scene) {
  56484. var sphere = new BABYLON.Mesh(name, scene);
  56485. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  56486. sphere._originalBuilderSideOrientation = options.sideOrientation;
  56487. var vertexData = BABYLON.VertexData.CreateIcoSphere(options);
  56488. vertexData.applyToMesh(sphere, options.updatable);
  56489. return sphere;
  56490. };
  56491. ;
  56492. /**
  56493. * Creates a ribbon mesh.
  56494. * 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.
  56495. *
  56496. * Please read this full tutorial to understand how to design a ribbon : http://doc.babylonjs.com/tutorials/Ribbon_Tutorial
  56497. * The parameter `pathArray` is a required array of paths, what are each an array of successive Vector3. The pathArray parameter depicts the ribbon geometry.
  56498. * The parameter `closeArray` (boolean, default false) creates a seam between the first and the last paths of the path array.
  56499. * The parameter `closePath` (boolean, default false) creates a seam between the first and the last points of each path of the path array.
  56500. * 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.
  56501. * 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.
  56502. * 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
  56503. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  56504. * 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).
  56505. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  56506. * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture.
  56507. * 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.
  56508. * The parameters `colors` is an optional flat array of `Color4` to set/update each ribbon vertex with its own custom color values.
  56509. * 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
  56510. * if you set `closePath` to `true`, there's one extra vertex per path in the geometry.
  56511. * Moreover, you can use the parameter `color` with `instance` (to update the ribbon), only if you previously used it at creation time.
  56512. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  56513. */
  56514. MeshBuilder.CreateRibbon = function (name, options, scene) {
  56515. if (scene === void 0) { scene = null; }
  56516. var pathArray = options.pathArray;
  56517. var closeArray = options.closeArray;
  56518. var closePath = options.closePath;
  56519. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  56520. var instance = options.instance;
  56521. var updatable = options.updatable;
  56522. if (instance) {
  56523. // positionFunction : ribbon case
  56524. // only pathArray and sideOrientation parameters are taken into account for positions update
  56525. BABYLON.Vector3.FromFloatsToRef(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, BABYLON.Tmp.Vector3[0]); // minimum
  56526. BABYLON.Vector3.FromFloatsToRef(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE, BABYLON.Tmp.Vector3[1]);
  56527. var positionFunction = function (positions) {
  56528. var minlg = pathArray[0].length;
  56529. var i = 0;
  56530. var ns = (instance._originalBuilderSideOrientation === BABYLON.Mesh.DOUBLESIDE) ? 2 : 1;
  56531. for (var si = 1; si <= ns; si++) {
  56532. for (var p = 0; p < pathArray.length; p++) {
  56533. var path = pathArray[p];
  56534. var l = path.length;
  56535. minlg = (minlg < l) ? minlg : l;
  56536. var j = 0;
  56537. while (j < minlg) {
  56538. positions[i] = path[j].x;
  56539. positions[i + 1] = path[j].y;
  56540. positions[i + 2] = path[j].z;
  56541. if (path[j].x < BABYLON.Tmp.Vector3[0].x) {
  56542. BABYLON.Tmp.Vector3[0].x = path[j].x;
  56543. }
  56544. if (path[j].x > BABYLON.Tmp.Vector3[1].x) {
  56545. BABYLON.Tmp.Vector3[1].x = path[j].x;
  56546. }
  56547. if (path[j].y < BABYLON.Tmp.Vector3[0].y) {
  56548. BABYLON.Tmp.Vector3[0].y = path[j].y;
  56549. }
  56550. if (path[j].y > BABYLON.Tmp.Vector3[1].y) {
  56551. BABYLON.Tmp.Vector3[1].y = path[j].y;
  56552. }
  56553. if (path[j].z < BABYLON.Tmp.Vector3[0].z) {
  56554. BABYLON.Tmp.Vector3[0].z = path[j].z;
  56555. }
  56556. if (path[j].z > BABYLON.Tmp.Vector3[1].z) {
  56557. BABYLON.Tmp.Vector3[1].z = path[j].z;
  56558. }
  56559. j++;
  56560. i += 3;
  56561. }
  56562. if (instance._closePath) {
  56563. positions[i] = path[0].x;
  56564. positions[i + 1] = path[0].y;
  56565. positions[i + 2] = path[0].z;
  56566. i += 3;
  56567. }
  56568. }
  56569. }
  56570. };
  56571. var positions = instance.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  56572. positionFunction(positions);
  56573. instance._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Tmp.Vector3[0], BABYLON.Tmp.Vector3[1]);
  56574. instance._boundingInfo.update(instance._worldMatrix);
  56575. instance.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions, false, false);
  56576. if (options.colors) {
  56577. var colors = instance.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  56578. for (var c = 0; c < options.colors.length; c++) {
  56579. colors[c * 4] = options.colors[c].r;
  56580. colors[c * 4 + 1] = options.colors[c].g;
  56581. colors[c * 4 + 2] = options.colors[c].b;
  56582. colors[c * 4 + 3] = options.colors[c].a;
  56583. }
  56584. instance.updateVerticesData(BABYLON.VertexBuffer.ColorKind, colors, false, false);
  56585. }
  56586. if (options.uvs) {
  56587. var uvs = instance.getVerticesData(BABYLON.VertexBuffer.UVKind);
  56588. for (var i = 0; i < options.uvs.length; i++) {
  56589. uvs[i * 2] = options.uvs[i].x;
  56590. uvs[i * 2 + 1] = options.uvs[i].y;
  56591. }
  56592. instance.updateVerticesData(BABYLON.VertexBuffer.UVKind, uvs, false, false);
  56593. }
  56594. if (!instance.areNormalsFrozen || instance.isFacetDataEnabled) {
  56595. var indices = instance.getIndices();
  56596. var normals = instance.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  56597. var params = instance.isFacetDataEnabled ? instance.getFacetDataParameters() : null;
  56598. BABYLON.VertexData.ComputeNormals(positions, indices, normals, params);
  56599. if (instance._closePath) {
  56600. var indexFirst = 0;
  56601. var indexLast = 0;
  56602. for (var p = 0; p < pathArray.length; p++) {
  56603. indexFirst = instance._idx[p] * 3;
  56604. if (p + 1 < pathArray.length) {
  56605. indexLast = (instance._idx[p + 1] - 1) * 3;
  56606. }
  56607. else {
  56608. indexLast = normals.length - 3;
  56609. }
  56610. normals[indexFirst] = (normals[indexFirst] + normals[indexLast]) * 0.5;
  56611. normals[indexFirst + 1] = (normals[indexFirst + 1] + normals[indexLast + 1]) * 0.5;
  56612. normals[indexFirst + 2] = (normals[indexFirst + 2] + normals[indexLast + 2]) * 0.5;
  56613. normals[indexLast] = normals[indexFirst];
  56614. normals[indexLast + 1] = normals[indexFirst + 1];
  56615. normals[indexLast + 2] = normals[indexFirst + 2];
  56616. }
  56617. }
  56618. if (!(instance.areNormalsFrozen)) {
  56619. instance.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals, false, false);
  56620. }
  56621. }
  56622. return instance;
  56623. }
  56624. else {
  56625. var ribbon = new BABYLON.Mesh(name, scene);
  56626. ribbon._originalBuilderSideOrientation = sideOrientation;
  56627. var vertexData = BABYLON.VertexData.CreateRibbon(options);
  56628. if (closePath) {
  56629. ribbon._idx = vertexData._idx;
  56630. }
  56631. ribbon._closePath = closePath;
  56632. ribbon._closeArray = closeArray;
  56633. vertexData.applyToMesh(ribbon, updatable);
  56634. return ribbon;
  56635. }
  56636. };
  56637. /**
  56638. * Creates a cylinder or a cone mesh.
  56639. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#cylinder-or-cone
  56640. * The parameter `height` sets the height size (float) of the cylinder/cone (float, default 2).
  56641. * The parameter `diameter` sets the diameter of the top and bottom cap at once (float, default 1).
  56642. * 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.
  56643. * The parameter `tessellation` sets the number of cylinder sides (positive integer, default 24). Set it to 3 to get a prism for instance.
  56644. * The parameter `subdivisions` sets the number of rings along the cylinder height (positive integer, default 1).
  56645. * The parameter `hasRings` (boolean, default false) makes the subdivisions independent from each other, so they become different faces.
  56646. * The parameter `enclose` (boolean, default false) adds two extra faces per subdivision to a sliced cylinder to close it around its height axis.
  56647. * The parameter `arc` (float, default 1) is the ratio (max 1) to apply to the circumference to slice the cylinder.
  56648. * 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).
  56649. * 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
  56650. * Now, if the cylinder has 5 independent subdivisions (hasRings = true), n equals : top face + 5 stripe surfaces + bottom face = 2 + 5 = 7
  56651. * 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
  56652. * 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.
  56653. * If `enclose` is false, a ring surface is one element.
  56654. * If `enclose` is true, a ring surface is 3 successive elements in the array : the tubular surface, then the two closing faces.
  56655. * 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
  56656. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  56657. * 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).
  56658. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  56659. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  56660. */
  56661. MeshBuilder.CreateCylinder = function (name, options, scene) {
  56662. var cylinder = new BABYLON.Mesh(name, scene);
  56663. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  56664. cylinder._originalBuilderSideOrientation = options.sideOrientation;
  56665. var vertexData = BABYLON.VertexData.CreateCylinder(options);
  56666. vertexData.applyToMesh(cylinder, options.updatable);
  56667. return cylinder;
  56668. };
  56669. /**
  56670. * Creates a torus mesh.
  56671. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#torus
  56672. * The parameter `diameter` sets the diameter size (float) of the torus (default 1).
  56673. * The parameter `thickness` sets the diameter size of the tube of the torus (float, default 0.5).
  56674. * The parameter `tessellation` sets the number of torus sides (postive integer, default 16).
  56675. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  56676. * 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).
  56677. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  56678. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  56679. */
  56680. MeshBuilder.CreateTorus = function (name, options, scene) {
  56681. var torus = new BABYLON.Mesh(name, scene);
  56682. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  56683. torus._originalBuilderSideOrientation = options.sideOrientation;
  56684. var vertexData = BABYLON.VertexData.CreateTorus(options);
  56685. vertexData.applyToMesh(torus, options.updatable);
  56686. return torus;
  56687. };
  56688. /**
  56689. * Creates a torus knot mesh.
  56690. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#torus-knot
  56691. * The parameter `radius` sets the global radius size (float) of the torus knot (default 2).
  56692. * The parameter `radialSegments` sets the number of sides on each tube segments (positive integer, default 32).
  56693. * The parameter `tubularSegments` sets the number of tubes to decompose the knot into (positive integer, default 32).
  56694. * The parameters `p` and `q` are the number of windings on each axis (positive integers, default 2 and 3).
  56695. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  56696. * 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).
  56697. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  56698. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  56699. */
  56700. MeshBuilder.CreateTorusKnot = function (name, options, scene) {
  56701. var torusKnot = new BABYLON.Mesh(name, scene);
  56702. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  56703. torusKnot._originalBuilderSideOrientation = options.sideOrientation;
  56704. var vertexData = BABYLON.VertexData.CreateTorusKnot(options);
  56705. vertexData.applyToMesh(torusKnot, options.updatable);
  56706. return torusKnot;
  56707. };
  56708. /**
  56709. * Creates a line system mesh.
  56710. * A line system is a pool of many lines gathered in a single mesh.
  56711. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#linesystem
  56712. * 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.
  56713. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineSystem to this static function.
  56714. * The parameter `lines` is an array of lines, each line being an array of successive Vector3.
  56715. * The optional parameter `instance` is an instance of an existing LineSystem object to be updated with the passed `lines` parameter. The way to update it is the same than for
  56716. * The optional parameter `colors` is an array of line colors, each line colors being an array of successive Color4, one per line point.
  56717. * The optional parameter `useVertexAlpha' is to be set to `false` (default `true`) when you don't need the alpha blending (faster).
  56718. * 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
  56719. * When updating an instance, remember that only line point positions can change, not the number of points, neither the number of lines.
  56720. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  56721. */
  56722. MeshBuilder.CreateLineSystem = function (name, options, scene) {
  56723. var instance = options.instance;
  56724. var lines = options.lines;
  56725. var colors = options.colors;
  56726. if (instance) {
  56727. var positions = instance.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  56728. var vertexColor;
  56729. var lineColors;
  56730. if (colors) {
  56731. vertexColor = instance.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  56732. }
  56733. var i = 0;
  56734. var c = 0;
  56735. for (var l = 0; l < lines.length; l++) {
  56736. var points = lines[l];
  56737. for (var p = 0; p < points.length; p++) {
  56738. positions[i] = points[p].x;
  56739. positions[i + 1] = points[p].y;
  56740. positions[i + 2] = points[p].z;
  56741. if (colors && vertexColor) {
  56742. lineColors = colors[l];
  56743. vertexColor[c] = lineColors[p].r;
  56744. vertexColor[c + 1] = lineColors[p].g;
  56745. vertexColor[c + 2] = lineColors[p].b;
  56746. vertexColor[c + 3] = lineColors[p].a;
  56747. c += 4;
  56748. }
  56749. i += 3;
  56750. }
  56751. }
  56752. instance.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions, false, false);
  56753. if (colors && vertexColor) {
  56754. instance.updateVerticesData(BABYLON.VertexBuffer.ColorKind, vertexColor, false, false);
  56755. }
  56756. return instance;
  56757. }
  56758. // line system creation
  56759. var useVertexColor = (colors) ? true : false;
  56760. var lineSystem = new BABYLON.LinesMesh(name, scene, null, undefined, undefined, useVertexColor, options.useVertexAlpha);
  56761. var vertexData = BABYLON.VertexData.CreateLineSystem(options);
  56762. vertexData.applyToMesh(lineSystem, options.updatable);
  56763. return lineSystem;
  56764. };
  56765. /**
  56766. * Creates a line mesh.
  56767. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#lines
  56768. * 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.
  56769. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function.
  56770. * The parameter `points` is an array successive Vector3.
  56771. * 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
  56772. * The optional parameter `colors` is an array of successive Color4, one per line point.
  56773. * The optional parameter `useVertexAlpha' is to be set to `false` (default `true`) when you don't need alpha blending (faster).
  56774. * When updating an instance, remember that only point positions can change, not the number of points.
  56775. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  56776. */
  56777. MeshBuilder.CreateLines = function (name, options, scene) {
  56778. if (scene === void 0) { scene = null; }
  56779. var colors = (options.colors) ? [options.colors] : null;
  56780. var lines = MeshBuilder.CreateLineSystem(name, { lines: [options.points], updatable: options.updatable, instance: options.instance, colors: colors, useVertexAlpha: options.useVertexAlpha }, scene);
  56781. return lines;
  56782. };
  56783. /**
  56784. * Creates a dashed line mesh.
  56785. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#dashed-lines
  56786. * 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.
  56787. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function.
  56788. * The parameter `points` is an array successive Vector3.
  56789. * The parameter `dashNb` is the intended total number of dashes (positive integer, default 200).
  56790. * The parameter `dashSize` is the size of the dashes relatively the dash number (positive float, default 3).
  56791. * The parameter `gapSize` is the size of the gap between two successive dashes relatively the dash number (positive float, default 1).
  56792. * 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
  56793. * When updating an instance, remember that only point positions can change, not the number of points.
  56794. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  56795. */
  56796. MeshBuilder.CreateDashedLines = function (name, options, scene) {
  56797. if (scene === void 0) { scene = null; }
  56798. var points = options.points;
  56799. var instance = options.instance;
  56800. var gapSize = options.gapSize || 1;
  56801. var dashSize = options.dashSize || 3;
  56802. if (instance) {
  56803. var positionFunction = function (positions) {
  56804. var curvect = BABYLON.Vector3.Zero();
  56805. var nbSeg = positions.length / 6;
  56806. var lg = 0;
  56807. var nb = 0;
  56808. var shft = 0;
  56809. var dashshft = 0;
  56810. var curshft = 0;
  56811. var p = 0;
  56812. var i = 0;
  56813. var j = 0;
  56814. for (i = 0; i < points.length - 1; i++) {
  56815. points[i + 1].subtractToRef(points[i], curvect);
  56816. lg += curvect.length();
  56817. }
  56818. shft = lg / nbSeg;
  56819. dashshft = instance.dashSize * shft / (instance.dashSize + instance.gapSize);
  56820. for (i = 0; i < points.length - 1; i++) {
  56821. points[i + 1].subtractToRef(points[i], curvect);
  56822. nb = Math.floor(curvect.length() / shft);
  56823. curvect.normalize();
  56824. j = 0;
  56825. while (j < nb && p < positions.length) {
  56826. curshft = shft * j;
  56827. positions[p] = points[i].x + curshft * curvect.x;
  56828. positions[p + 1] = points[i].y + curshft * curvect.y;
  56829. positions[p + 2] = points[i].z + curshft * curvect.z;
  56830. positions[p + 3] = points[i].x + (curshft + dashshft) * curvect.x;
  56831. positions[p + 4] = points[i].y + (curshft + dashshft) * curvect.y;
  56832. positions[p + 5] = points[i].z + (curshft + dashshft) * curvect.z;
  56833. p += 6;
  56834. j++;
  56835. }
  56836. }
  56837. while (p < positions.length) {
  56838. positions[p] = points[i].x;
  56839. positions[p + 1] = points[i].y;
  56840. positions[p + 2] = points[i].z;
  56841. p += 3;
  56842. }
  56843. };
  56844. instance.updateMeshPositions(positionFunction, false);
  56845. return instance;
  56846. }
  56847. // dashed lines creation
  56848. var dashedLines = new BABYLON.LinesMesh(name, scene);
  56849. var vertexData = BABYLON.VertexData.CreateDashedLines(options);
  56850. vertexData.applyToMesh(dashedLines, options.updatable);
  56851. dashedLines.dashSize = dashSize;
  56852. dashedLines.gapSize = gapSize;
  56853. return dashedLines;
  56854. };
  56855. /**
  56856. * Creates an extruded shape mesh.
  56857. * 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.
  56858. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#extruded-shapes
  56859. *
  56860. * Please read this full tutorial to understand how to design an extruded shape : http://doc.babylonjs.com/tutorials/Parametric_Shapes#extrusion
  56861. * 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
  56862. * extruded along the Z axis.
  56863. * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  56864. * 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.
  56865. * The parameter `scale` (float, default 1) is the value to scale the shape.
  56866. * 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
  56867. * 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
  56868. * Remember you can only change the shape or path point positions, not their number when updating an extruded shape.
  56869. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  56870. * 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).
  56871. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  56872. * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture.
  56873. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  56874. */
  56875. MeshBuilder.ExtrudeShape = function (name, options, scene) {
  56876. if (scene === void 0) { scene = null; }
  56877. var path = options.path;
  56878. var shape = options.shape;
  56879. var scale = options.scale || 1;
  56880. var rotation = options.rotation || 0;
  56881. var cap = (options.cap === 0) ? 0 : options.cap || BABYLON.Mesh.NO_CAP;
  56882. var updatable = options.updatable;
  56883. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  56884. var instance = options.instance || null;
  56885. var invertUV = options.invertUV || false;
  56886. 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);
  56887. };
  56888. /**
  56889. * Creates an custom extruded shape mesh.
  56890. * 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.
  56891. * tuto :http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#custom-extruded-shapes
  56892. *
  56893. * Please read this full tutorial to understand how to design a custom extruded shape : http://doc.babylonjs.com/tutorials/Parametric_Shapes#extrusion
  56894. * 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
  56895. * extruded along the Z axis.
  56896. * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  56897. * 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
  56898. * and the distance of this point from the begining of the path :
  56899. * ```javascript
  56900. * var rotationFunction = function(i, distance) {
  56901. * // do things
  56902. * return rotationValue; }
  56903. * ```
  56904. * It must returns a float value that will be the rotation in radians applied to the shape on each path point.
  56905. * 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
  56906. * and the distance of this point from the begining of the path :
  56907. * ```javascript
  56908. * var scaleFunction = function(i, distance) {
  56909. * // do things
  56910. * return scaleValue;}
  56911. * ```
  56912. * It must returns a float value that will be the scale value applied to the shape on each path point.
  56913. * The parameter `ribbonClosePath` (boolean, default false) forces the extrusion underlying ribbon to close all the paths in its `pathArray`.
  56914. * The parameter `ribbonCloseArray` (boolean, default false) forces the extrusion underlying ribbon to close its `pathArray`.
  56915. * 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
  56916. * 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
  56917. * Remember you can only change the shape or path point positions, not their number when updating an extruded shape.
  56918. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  56919. * 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).
  56920. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  56921. * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture.
  56922. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  56923. */
  56924. MeshBuilder.ExtrudeShapeCustom = function (name, options, scene) {
  56925. var path = options.path;
  56926. var shape = options.shape;
  56927. var scaleFunction = options.scaleFunction || (function () { return 1; });
  56928. var rotationFunction = options.rotationFunction || (function () { return 0; });
  56929. var ribbonCloseArray = options.ribbonCloseArray || false;
  56930. var ribbonClosePath = options.ribbonClosePath || false;
  56931. var cap = (options.cap === 0) ? 0 : options.cap || BABYLON.Mesh.NO_CAP;
  56932. var updatable = options.updatable;
  56933. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  56934. var instance = options.instance;
  56935. var invertUV = options.invertUV || false;
  56936. 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);
  56937. };
  56938. /**
  56939. * Creates lathe mesh.
  56940. * The lathe is a shape with a symetry axis : a 2D model shape is rotated around this axis to design the lathe.
  56941. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#lathe
  56942. *
  56943. * 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
  56944. * rotated around the Y axis. It's usually a 2D shape, so the Vector3 z coordinates are often set to zero.
  56945. * The parameter `radius` (positive float, default 1) is the radius value of the lathe.
  56946. * The parameter `tessellation` (positive integer, default 64) is the side number of the lathe.
  56947. * 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.
  56948. * The parameter `closed` (boolean, default true) opens/closes the lathe circumference. This should be set to false when used with the parameter "arc".
  56949. * 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
  56950. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  56951. * 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).
  56952. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  56953. * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture.
  56954. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  56955. */
  56956. MeshBuilder.CreateLathe = function (name, options, scene) {
  56957. var arc = options.arc ? ((options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc) : 1.0;
  56958. var closed = (options.closed === undefined) ? true : options.closed;
  56959. var shape = options.shape;
  56960. var radius = options.radius || 1;
  56961. var tessellation = options.tessellation || 64;
  56962. var updatable = options.updatable;
  56963. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  56964. var cap = options.cap || BABYLON.Mesh.NO_CAP;
  56965. var pi2 = Math.PI * 2;
  56966. var paths = new Array();
  56967. var invertUV = options.invertUV || false;
  56968. var i = 0;
  56969. var p = 0;
  56970. var step = pi2 / tessellation * arc;
  56971. var rotated;
  56972. var path = new Array();
  56973. ;
  56974. for (i = 0; i <= tessellation; i++) {
  56975. var path = [];
  56976. if (cap == BABYLON.Mesh.CAP_START || cap == BABYLON.Mesh.CAP_ALL) {
  56977. path.push(new BABYLON.Vector3(0, shape[0].y, 0));
  56978. path.push(new BABYLON.Vector3(Math.cos(i * step) * shape[0].x * radius, shape[0].y, Math.sin(i * step) * shape[0].x * radius));
  56979. }
  56980. for (p = 0; p < shape.length; p++) {
  56981. rotated = new BABYLON.Vector3(Math.cos(i * step) * shape[p].x * radius, shape[p].y, Math.sin(i * step) * shape[p].x * radius);
  56982. path.push(rotated);
  56983. }
  56984. if (cap == BABYLON.Mesh.CAP_END || cap == BABYLON.Mesh.CAP_ALL) {
  56985. 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));
  56986. path.push(new BABYLON.Vector3(0, shape[shape.length - 1].y, 0));
  56987. }
  56988. paths.push(path);
  56989. }
  56990. // lathe ribbon
  56991. var lathe = MeshBuilder.CreateRibbon(name, { pathArray: paths, closeArray: closed, sideOrientation: sideOrientation, updatable: updatable, invertUV: invertUV, frontUVs: options.frontUVs, backUVs: options.backUVs }, scene);
  56992. return lathe;
  56993. };
  56994. /**
  56995. * Creates a plane mesh.
  56996. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#plane
  56997. * The parameter `size` sets the size (float) of both sides of the plane at once (default 1).
  56998. * You can set some different plane dimensions by using the parameters `width` and `height` (both by default have the same value than `size`).
  56999. * The parameter `sourcePlane` is a Plane instance. It builds a mesh plane from a Math plane.
  57000. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  57001. * 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).
  57002. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  57003. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  57004. */
  57005. MeshBuilder.CreatePlane = function (name, options, scene) {
  57006. var plane = new BABYLON.Mesh(name, scene);
  57007. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  57008. plane._originalBuilderSideOrientation = options.sideOrientation;
  57009. var vertexData = BABYLON.VertexData.CreatePlane(options);
  57010. vertexData.applyToMesh(plane, options.updatable);
  57011. if (options.sourcePlane) {
  57012. plane.translate(options.sourcePlane.normal, options.sourcePlane.d);
  57013. var product = Math.acos(BABYLON.Vector3.Dot(options.sourcePlane.normal, BABYLON.Axis.Z));
  57014. var vectorProduct = BABYLON.Vector3.Cross(BABYLON.Axis.Z, options.sourcePlane.normal);
  57015. plane.rotate(vectorProduct, product);
  57016. }
  57017. return plane;
  57018. };
  57019. /**
  57020. * Creates a ground mesh.
  57021. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#plane
  57022. * The parameters `width` and `height` (floats, default 1) set the width and height sizes of the ground.
  57023. * The parameter `subdivisions` (positive integer) sets the number of subdivisions per side.
  57024. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  57025. */
  57026. MeshBuilder.CreateGround = function (name, options, scene) {
  57027. var ground = new BABYLON.GroundMesh(name, scene);
  57028. ground._setReady(false);
  57029. ground._subdivisionsX = options.subdivisionsX || options.subdivisions || 1;
  57030. ground._subdivisionsY = options.subdivisionsY || options.subdivisions || 1;
  57031. ground._width = options.width || 1;
  57032. ground._height = options.height || 1;
  57033. ground._maxX = ground._width / 2;
  57034. ground._maxZ = ground._height / 2;
  57035. ground._minX = -ground._maxX;
  57036. ground._minZ = -ground._maxZ;
  57037. var vertexData = BABYLON.VertexData.CreateGround(options);
  57038. vertexData.applyToMesh(ground, options.updatable);
  57039. ground._setReady(true);
  57040. return ground;
  57041. };
  57042. /**
  57043. * Creates a tiled ground mesh.
  57044. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#tiled-ground
  57045. * The parameters `xmin` and `xmax` (floats, default -1 and 1) set the ground minimum and maximum X coordinates.
  57046. * The parameters `zmin` and `zmax` (floats, default -1 and 1) set the ground minimum and maximum Z coordinates.
  57047. * The parameter `subdivisions` is a javascript object `{w: positive integer, h: positive integer}` (default `{w: 6, h: 6}`). `w` and `h` are the
  57048. * numbers of subdivisions on the ground width and height. Each subdivision is called a tile.
  57049. * The parameter `precision` is a javascript object `{w: positive integer, h: positive integer}` (default `{w: 2, h: 2}`). `w` and `h` are the
  57050. * numbers of subdivisions on the ground width and height of each tile.
  57051. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  57052. */
  57053. MeshBuilder.CreateTiledGround = function (name, options, scene) {
  57054. var tiledGround = new BABYLON.Mesh(name, scene);
  57055. var vertexData = BABYLON.VertexData.CreateTiledGround(options);
  57056. vertexData.applyToMesh(tiledGround, options.updatable);
  57057. return tiledGround;
  57058. };
  57059. /**
  57060. * Creates a ground mesh from a height map.
  57061. * tuto : http://doc.babylonjs.com/tutorials/14._Height_Map
  57062. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#ground-from-a-height-map
  57063. * The parameter `url` sets the URL of the height map image resource.
  57064. * The parameters `width` and `height` (positive floats, default 10) set the ground width and height sizes.
  57065. * The parameter `subdivisions` (positive integer, default 1) sets the number of subdivision per side.
  57066. * The parameter `minHeight` (float, default 0) is the minimum altitude on the ground.
  57067. * The parameter `maxHeight` (float, default 1) is the maximum altitude on the ground.
  57068. * 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.
  57069. * 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).
  57070. * This function is passed the newly built mesh :
  57071. * ```javascript
  57072. * function(mesh) { // do things
  57073. * return; }
  57074. * ```
  57075. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  57076. */
  57077. MeshBuilder.CreateGroundFromHeightMap = function (name, url, options, scene) {
  57078. var width = options.width || 10.0;
  57079. var height = options.height || 10.0;
  57080. var subdivisions = options.subdivisions || 1 | 0;
  57081. var minHeight = options.minHeight || 0.0;
  57082. var maxHeight = options.maxHeight || 1.0;
  57083. var filter = options.colorFilter || new BABYLON.Color3(0.3, 0.59, 0.11);
  57084. var updatable = options.updatable;
  57085. var onReady = options.onReady;
  57086. var ground = new BABYLON.GroundMesh(name, scene);
  57087. ground._subdivisionsX = subdivisions;
  57088. ground._subdivisionsY = subdivisions;
  57089. ground._width = width;
  57090. ground._height = height;
  57091. ground._maxX = ground._width / 2.0;
  57092. ground._maxZ = ground._height / 2.0;
  57093. ground._minX = -ground._maxX;
  57094. ground._minZ = -ground._maxZ;
  57095. ground._setReady(false);
  57096. var onload = function (img) {
  57097. // Getting height map data
  57098. var canvas = document.createElement("canvas");
  57099. var context = canvas.getContext("2d");
  57100. if (!context) {
  57101. throw new Error("Unable to get 2d context for CreateGroundFromHeightMap");
  57102. }
  57103. if (scene.isDisposed) {
  57104. return;
  57105. }
  57106. var bufferWidth = img.width;
  57107. var bufferHeight = img.height;
  57108. canvas.width = bufferWidth;
  57109. canvas.height = bufferHeight;
  57110. context.drawImage(img, 0, 0);
  57111. // Create VertexData from map data
  57112. // Cast is due to wrong definition in lib.d.ts from ts 1.3 - https://github.com/Microsoft/TypeScript/issues/949
  57113. var buffer = context.getImageData(0, 0, bufferWidth, bufferHeight).data;
  57114. var vertexData = BABYLON.VertexData.CreateGroundFromHeightMap({
  57115. width: width, height: height,
  57116. subdivisions: subdivisions,
  57117. minHeight: minHeight, maxHeight: maxHeight, colorFilter: filter,
  57118. buffer: buffer, bufferWidth: bufferWidth, bufferHeight: bufferHeight
  57119. });
  57120. vertexData.applyToMesh(ground, updatable);
  57121. //execute ready callback, if set
  57122. if (onReady) {
  57123. onReady(ground);
  57124. }
  57125. ground._setReady(true);
  57126. };
  57127. BABYLON.Tools.LoadImage(url, onload, function () { }, scene.database);
  57128. return ground;
  57129. };
  57130. /**
  57131. * Creates a polygon mesh.
  57132. * The polygon's shape will depend on the input parameters and is constructed parallel to a ground mesh.
  57133. * 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.
  57134. * You can set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  57135. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  57136. * 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).
  57137. * Remember you can only change the shape positions, not their number when updating a polygon.
  57138. */
  57139. MeshBuilder.CreatePolygon = function (name, options, scene) {
  57140. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  57141. var shape = options.shape;
  57142. var holes = options.holes || [];
  57143. var depth = options.depth || 0;
  57144. var contours = [];
  57145. var hole = [];
  57146. for (var i = 0; i < shape.length; i++) {
  57147. contours[i] = new BABYLON.Vector2(shape[i].x, shape[i].z);
  57148. }
  57149. var epsilon = 0.00000001;
  57150. if (contours[0].equalsWithEpsilon(contours[contours.length - 1], epsilon)) {
  57151. contours.pop();
  57152. }
  57153. var polygonTriangulation = new BABYLON.PolygonMeshBuilder(name, contours, scene);
  57154. for (var hNb = 0; hNb < holes.length; hNb++) {
  57155. hole = [];
  57156. for (var hPoint = 0; hPoint < holes[hNb].length; hPoint++) {
  57157. hole.push(new BABYLON.Vector2(holes[hNb][hPoint].x, holes[hNb][hPoint].z));
  57158. }
  57159. polygonTriangulation.addHole(hole);
  57160. }
  57161. var polygon = polygonTriangulation.build(options.updatable, depth);
  57162. polygon._originalBuilderSideOrientation = options.sideOrientation;
  57163. var vertexData = BABYLON.VertexData.CreatePolygon(polygon, options.sideOrientation, options.faceUV, options.faceColors, options.frontUVs, options.backUVs);
  57164. vertexData.applyToMesh(polygon, options.updatable);
  57165. return polygon;
  57166. };
  57167. ;
  57168. /**
  57169. * Creates an extruded polygon mesh, with depth in the Y direction.
  57170. * 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).
  57171. * Please read this tutorial : http://doc.babylonjs.com/tutorials/CreateBox_Per_Face_Textures_And_Colors
  57172. */
  57173. MeshBuilder.ExtrudePolygon = function (name, options, scene) {
  57174. return MeshBuilder.CreatePolygon(name, options, scene);
  57175. };
  57176. ;
  57177. /**
  57178. * Creates a tube mesh.
  57179. * 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.
  57180. *
  57181. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#tube
  57182. * The parameter `path` is a required array of successive Vector3. It is the curve used as the axis of the tube.
  57183. * The parameter `radius` (positive float, default 1) sets the tube radius size.
  57184. * The parameter `tessellation` (positive float, default 64) is the number of sides on the tubular surface.
  57185. * The parameter `radiusFunction` (javascript function, default null) is a vanilla javascript function. If it is not null, it overwrittes the parameter `radius`.
  57186. * 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.
  57187. * It must return a radius value (positive float) :
  57188. * ```javascript
  57189. * var radiusFunction = function(i, distance) {
  57190. * // do things
  57191. * return radius; }
  57192. * ```
  57193. * The parameter `arc` (positive float, maximum 1, default 1) is the ratio to apply to the tube circumference : 2 x PI x arc.
  57194. * 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
  57195. * 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
  57196. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  57197. * 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).
  57198. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  57199. * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture.
  57200. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  57201. */
  57202. MeshBuilder.CreateTube = function (name, options, scene) {
  57203. var path = options.path;
  57204. var instance = options.instance;
  57205. var radius = 1.0;
  57206. if (instance) {
  57207. radius = instance.radius;
  57208. }
  57209. if (options.radius !== undefined) {
  57210. radius = options.radius;
  57211. }
  57212. ;
  57213. var tessellation = options.tessellation || 64 | 0;
  57214. var radiusFunction = options.radiusFunction || null;
  57215. var cap = options.cap || BABYLON.Mesh.NO_CAP;
  57216. var invertUV = options.invertUV || false;
  57217. var updatable = options.updatable;
  57218. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  57219. options.arc = options.arc && (options.arc <= 0.0 || options.arc > 1.0) ? 1.0 : options.arc || 1.0;
  57220. // tube geometry
  57221. var tubePathArray = function (path, path3D, circlePaths, radius, tessellation, radiusFunction, cap, arc) {
  57222. var tangents = path3D.getTangents();
  57223. var normals = path3D.getNormals();
  57224. var distances = path3D.getDistances();
  57225. var pi2 = Math.PI * 2;
  57226. var step = pi2 / tessellation * arc;
  57227. var returnRadius = function () { return radius; };
  57228. var radiusFunctionFinal = radiusFunction || returnRadius;
  57229. var circlePath;
  57230. var rad;
  57231. var normal;
  57232. var rotated;
  57233. var rotationMatrix = BABYLON.Tmp.Matrix[0];
  57234. var index = (cap === BABYLON.Mesh._NO_CAP || cap === BABYLON.Mesh.CAP_END) ? 0 : 2;
  57235. for (var i = 0; i < path.length; i++) {
  57236. rad = radiusFunctionFinal(i, distances[i]); // current radius
  57237. circlePath = Array(); // current circle array
  57238. normal = normals[i]; // current normal
  57239. for (var t = 0; t < tessellation; t++) {
  57240. BABYLON.Matrix.RotationAxisToRef(tangents[i], step * t, rotationMatrix);
  57241. rotated = circlePath[t] ? circlePath[t] : BABYLON.Vector3.Zero();
  57242. BABYLON.Vector3.TransformCoordinatesToRef(normal, rotationMatrix, rotated);
  57243. rotated.scaleInPlace(rad).addInPlace(path[i]);
  57244. circlePath[t] = rotated;
  57245. }
  57246. circlePaths[index] = circlePath;
  57247. index++;
  57248. }
  57249. // cap
  57250. var capPath = function (nbPoints, pathIndex) {
  57251. var pointCap = Array();
  57252. for (var i = 0; i < nbPoints; i++) {
  57253. pointCap.push(path[pathIndex]);
  57254. }
  57255. return pointCap;
  57256. };
  57257. switch (cap) {
  57258. case BABYLON.Mesh.NO_CAP:
  57259. break;
  57260. case BABYLON.Mesh.CAP_START:
  57261. circlePaths[0] = capPath(tessellation, 0);
  57262. circlePaths[1] = circlePaths[2].slice(0);
  57263. break;
  57264. case BABYLON.Mesh.CAP_END:
  57265. circlePaths[index] = circlePaths[index - 1].slice(0);
  57266. circlePaths[index + 1] = capPath(tessellation, path.length - 1);
  57267. break;
  57268. case BABYLON.Mesh.CAP_ALL:
  57269. circlePaths[0] = capPath(tessellation, 0);
  57270. circlePaths[1] = circlePaths[2].slice(0);
  57271. circlePaths[index] = circlePaths[index - 1].slice(0);
  57272. circlePaths[index + 1] = capPath(tessellation, path.length - 1);
  57273. break;
  57274. default:
  57275. break;
  57276. }
  57277. return circlePaths;
  57278. };
  57279. var path3D;
  57280. var pathArray;
  57281. if (instance) {
  57282. var arc = options.arc || instance.arc;
  57283. path3D = (instance.path3D).update(path);
  57284. pathArray = tubePathArray(path, path3D, instance.pathArray, radius, instance.tessellation, radiusFunction, instance.cap, arc);
  57285. instance = MeshBuilder.CreateRibbon("", { pathArray: pathArray, instance: instance });
  57286. instance.path3D = path3D;
  57287. instance.pathArray = pathArray;
  57288. instance.arc = arc;
  57289. instance.radius = radius;
  57290. return instance;
  57291. }
  57292. // tube creation
  57293. path3D = new BABYLON.Path3D(path);
  57294. var newPathArray = new Array();
  57295. cap = (cap < 0 || cap > 3) ? 0 : cap;
  57296. pathArray = tubePathArray(path, path3D, newPathArray, radius, tessellation, radiusFunction, cap, options.arc);
  57297. var tube = MeshBuilder.CreateRibbon(name, { pathArray: pathArray, closePath: true, closeArray: false, updatable: updatable, sideOrientation: sideOrientation, invertUV: invertUV, frontUVs: options.frontUVs, backUVs: options.backUVs }, scene);
  57298. tube.pathArray = pathArray;
  57299. tube.path3D = path3D;
  57300. tube.tessellation = tessellation;
  57301. tube.cap = cap;
  57302. tube.arc = options.arc;
  57303. tube.radius = radius;
  57304. return tube;
  57305. };
  57306. /**
  57307. * Creates a polyhedron mesh.
  57308. *
  57309. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#polyhedron
  57310. * 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
  57311. * to choose the wanted type.
  57312. * The parameter `size` (positive float, default 1) sets the polygon size.
  57313. * You can overwrite the `size` on each dimension bu using the parameters `sizeX`, `sizeY` or `sizeZ` (positive floats, default to `size` value).
  57314. * 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`.
  57315. * 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
  57316. * 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)`).
  57317. * 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
  57318. * 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.
  57319. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  57320. * 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).
  57321. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  57322. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  57323. */
  57324. MeshBuilder.CreatePolyhedron = function (name, options, scene) {
  57325. var polyhedron = new BABYLON.Mesh(name, scene);
  57326. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  57327. polyhedron._originalBuilderSideOrientation = options.sideOrientation;
  57328. var vertexData = BABYLON.VertexData.CreatePolyhedron(options);
  57329. vertexData.applyToMesh(polyhedron, options.updatable);
  57330. return polyhedron;
  57331. };
  57332. /**
  57333. * Creates a decal mesh.
  57334. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#decals
  57335. * 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.
  57336. * The parameter `position` (Vector3, default `(0, 0, 0)`) sets the position of the decal in World coordinates.
  57337. * The parameter `normal` (Vector3, default `Vector3.Up`) sets the normal of the mesh where the decal is applied onto in World coordinates.
  57338. * The parameter `size` (Vector3, default `(1, 1, 1)`) sets the decal scaling.
  57339. * The parameter `angle` (float in radian, default 0) sets the angle to rotate the decal.
  57340. */
  57341. MeshBuilder.CreateDecal = function (name, sourceMesh, options) {
  57342. var indices = sourceMesh.getIndices();
  57343. var positions = sourceMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  57344. var normals = sourceMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  57345. var position = options.position || BABYLON.Vector3.Zero();
  57346. var normal = options.normal || BABYLON.Vector3.Up();
  57347. var size = options.size || BABYLON.Vector3.One();
  57348. var angle = options.angle || 0;
  57349. // Getting correct rotation
  57350. if (!normal) {
  57351. var target = new BABYLON.Vector3(0, 0, 1);
  57352. var camera = sourceMesh.getScene().activeCamera;
  57353. var cameraWorldTarget = BABYLON.Vector3.TransformCoordinates(target, camera.getWorldMatrix());
  57354. normal = camera.globalPosition.subtract(cameraWorldTarget);
  57355. }
  57356. var yaw = -Math.atan2(normal.z, normal.x) - Math.PI / 2;
  57357. var len = Math.sqrt(normal.x * normal.x + normal.z * normal.z);
  57358. var pitch = Math.atan2(normal.y, len);
  57359. // Matrix
  57360. var decalWorldMatrix = BABYLON.Matrix.RotationYawPitchRoll(yaw, pitch, angle).multiply(BABYLON.Matrix.Translation(position.x, position.y, position.z));
  57361. var inverseDecalWorldMatrix = BABYLON.Matrix.Invert(decalWorldMatrix);
  57362. var meshWorldMatrix = sourceMesh.getWorldMatrix();
  57363. var transformMatrix = meshWorldMatrix.multiply(inverseDecalWorldMatrix);
  57364. var vertexData = new BABYLON.VertexData();
  57365. vertexData.indices = [];
  57366. vertexData.positions = [];
  57367. vertexData.normals = [];
  57368. vertexData.uvs = [];
  57369. var currentVertexDataIndex = 0;
  57370. var extractDecalVector3 = function (indexId) {
  57371. var result = new BABYLON.PositionNormalVertex();
  57372. if (!indices || !positions || !normals) {
  57373. return result;
  57374. }
  57375. var vertexId = indices[indexId];
  57376. result.position = new BABYLON.Vector3(positions[vertexId * 3], positions[vertexId * 3 + 1], positions[vertexId * 3 + 2]);
  57377. // Send vector to decal local world
  57378. result.position = BABYLON.Vector3.TransformCoordinates(result.position, transformMatrix);
  57379. // Get normal
  57380. result.normal = new BABYLON.Vector3(normals[vertexId * 3], normals[vertexId * 3 + 1], normals[vertexId * 3 + 2]);
  57381. result.normal = BABYLON.Vector3.TransformNormal(result.normal, transformMatrix);
  57382. return result;
  57383. }; // Inspired by https://github.com/mrdoob/three.js/blob/eee231960882f6f3b6113405f524956145148146/examples/js/geometries/DecalGeometry.js
  57384. var clip = function (vertices, axis) {
  57385. if (vertices.length === 0) {
  57386. return vertices;
  57387. }
  57388. var clipSize = 0.5 * Math.abs(BABYLON.Vector3.Dot(size, axis));
  57389. var clipVertices = function (v0, v1) {
  57390. var clipFactor = BABYLON.Vector3.GetClipFactor(v0.position, v1.position, axis, clipSize);
  57391. return new BABYLON.PositionNormalVertex(BABYLON.Vector3.Lerp(v0.position, v1.position, clipFactor), BABYLON.Vector3.Lerp(v0.normal, v1.normal, clipFactor));
  57392. };
  57393. var result = new Array();
  57394. for (var index = 0; index < vertices.length; index += 3) {
  57395. var v1Out;
  57396. var v2Out;
  57397. var v3Out;
  57398. var total = 0;
  57399. var nV1 = null;
  57400. var nV2 = null;
  57401. var nV3 = null;
  57402. var nV4 = null;
  57403. var d1 = BABYLON.Vector3.Dot(vertices[index].position, axis) - clipSize;
  57404. var d2 = BABYLON.Vector3.Dot(vertices[index + 1].position, axis) - clipSize;
  57405. var d3 = BABYLON.Vector3.Dot(vertices[index + 2].position, axis) - clipSize;
  57406. v1Out = d1 > 0;
  57407. v2Out = d2 > 0;
  57408. v3Out = d3 > 0;
  57409. total = (v1Out ? 1 : 0) + (v2Out ? 1 : 0) + (v3Out ? 1 : 0);
  57410. switch (total) {
  57411. case 0:
  57412. result.push(vertices[index]);
  57413. result.push(vertices[index + 1]);
  57414. result.push(vertices[index + 2]);
  57415. break;
  57416. case 1:
  57417. if (v1Out) {
  57418. nV1 = vertices[index + 1];
  57419. nV2 = vertices[index + 2];
  57420. nV3 = clipVertices(vertices[index], nV1);
  57421. nV4 = clipVertices(vertices[index], nV2);
  57422. }
  57423. if (v2Out) {
  57424. nV1 = vertices[index];
  57425. nV2 = vertices[index + 2];
  57426. nV3 = clipVertices(vertices[index + 1], nV1);
  57427. nV4 = clipVertices(vertices[index + 1], nV2);
  57428. result.push(nV3);
  57429. result.push(nV2.clone());
  57430. result.push(nV1.clone());
  57431. result.push(nV2.clone());
  57432. result.push(nV3.clone());
  57433. result.push(nV4);
  57434. break;
  57435. }
  57436. if (v3Out) {
  57437. nV1 = vertices[index];
  57438. nV2 = vertices[index + 1];
  57439. nV3 = clipVertices(vertices[index + 2], nV1);
  57440. nV4 = clipVertices(vertices[index + 2], nV2);
  57441. }
  57442. if (nV1 && nV2 && nV3 && nV4) {
  57443. result.push(nV1.clone());
  57444. result.push(nV2.clone());
  57445. result.push(nV3);
  57446. result.push(nV4);
  57447. result.push(nV3.clone());
  57448. result.push(nV2.clone());
  57449. }
  57450. break;
  57451. case 2:
  57452. if (!v1Out) {
  57453. nV1 = vertices[index].clone();
  57454. nV2 = clipVertices(nV1, vertices[index + 1]);
  57455. nV3 = clipVertices(nV1, vertices[index + 2]);
  57456. result.push(nV1);
  57457. result.push(nV2);
  57458. result.push(nV3);
  57459. }
  57460. if (!v2Out) {
  57461. nV1 = vertices[index + 1].clone();
  57462. nV2 = clipVertices(nV1, vertices[index + 2]);
  57463. nV3 = clipVertices(nV1, vertices[index]);
  57464. result.push(nV1);
  57465. result.push(nV2);
  57466. result.push(nV3);
  57467. }
  57468. if (!v3Out) {
  57469. nV1 = vertices[index + 2].clone();
  57470. nV2 = clipVertices(nV1, vertices[index]);
  57471. nV3 = clipVertices(nV1, vertices[index + 1]);
  57472. result.push(nV1);
  57473. result.push(nV2);
  57474. result.push(nV3);
  57475. }
  57476. break;
  57477. case 3:
  57478. break;
  57479. }
  57480. }
  57481. return result;
  57482. };
  57483. for (var index = 0; index < indices.length; index += 3) {
  57484. var faceVertices = new Array();
  57485. faceVertices.push(extractDecalVector3(index));
  57486. faceVertices.push(extractDecalVector3(index + 1));
  57487. faceVertices.push(extractDecalVector3(index + 2));
  57488. // Clip
  57489. faceVertices = clip(faceVertices, new BABYLON.Vector3(1, 0, 0));
  57490. faceVertices = clip(faceVertices, new BABYLON.Vector3(-1, 0, 0));
  57491. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, 1, 0));
  57492. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, -1, 0));
  57493. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, 0, 1));
  57494. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, 0, -1));
  57495. if (faceVertices.length === 0) {
  57496. continue;
  57497. }
  57498. // Add UVs and get back to world
  57499. for (var vIndex = 0; vIndex < faceVertices.length; vIndex++) {
  57500. var vertex = faceVertices[vIndex];
  57501. //TODO check for Int32Array | Uint32Array | Uint16Array
  57502. vertexData.indices.push(currentVertexDataIndex);
  57503. vertex.position.toArray(vertexData.positions, currentVertexDataIndex * 3);
  57504. vertex.normal.toArray(vertexData.normals, currentVertexDataIndex * 3);
  57505. vertexData.uvs.push(0.5 + vertex.position.x / size.x);
  57506. vertexData.uvs.push(0.5 + vertex.position.y / size.y);
  57507. currentVertexDataIndex++;
  57508. }
  57509. }
  57510. // Return mesh
  57511. var decal = new BABYLON.Mesh(name, sourceMesh.getScene());
  57512. vertexData.applyToMesh(decal);
  57513. decal.position = position.clone();
  57514. decal.rotation = new BABYLON.Vector3(pitch, yaw, angle);
  57515. return decal;
  57516. };
  57517. // Privates
  57518. MeshBuilder._ExtrudeShapeGeneric = function (name, shape, curve, scale, rotation, scaleFunction, rotateFunction, rbCA, rbCP, cap, custom, scene, updtbl, side, instance, invertUV, frontUVs, backUVs) {
  57519. // extrusion geometry
  57520. var extrusionPathArray = function (shape, curve, path3D, shapePaths, scale, rotation, scaleFunction, rotateFunction, cap, custom) {
  57521. var tangents = path3D.getTangents();
  57522. var normals = path3D.getNormals();
  57523. var binormals = path3D.getBinormals();
  57524. var distances = path3D.getDistances();
  57525. var angle = 0;
  57526. var returnScale = function () { return scale !== null ? scale : 1; };
  57527. var returnRotation = function () { return rotation !== null ? rotation : 0; };
  57528. var rotate = custom && rotateFunction ? rotateFunction : returnRotation;
  57529. var scl = custom && scaleFunction ? scaleFunction : returnScale;
  57530. var index = (cap === BABYLON.Mesh.NO_CAP || cap === BABYLON.Mesh.CAP_END) ? 0 : 2;
  57531. var rotationMatrix = BABYLON.Tmp.Matrix[0];
  57532. for (var i = 0; i < curve.length; i++) {
  57533. var shapePath = new Array();
  57534. var angleStep = rotate(i, distances[i]);
  57535. var scaleRatio = scl(i, distances[i]);
  57536. for (var p = 0; p < shape.length; p++) {
  57537. BABYLON.Matrix.RotationAxisToRef(tangents[i], angle, rotationMatrix);
  57538. var planed = ((tangents[i].scale(shape[p].z)).add(normals[i].scale(shape[p].x)).add(binormals[i].scale(shape[p].y)));
  57539. var rotated = shapePath[p] ? shapePath[p] : BABYLON.Vector3.Zero();
  57540. BABYLON.Vector3.TransformCoordinatesToRef(planed, rotationMatrix, rotated);
  57541. rotated.scaleInPlace(scaleRatio).addInPlace(curve[i]);
  57542. shapePath[p] = rotated;
  57543. }
  57544. shapePaths[index] = shapePath;
  57545. angle += angleStep;
  57546. index++;
  57547. }
  57548. // cap
  57549. var capPath = function (shapePath) {
  57550. var pointCap = Array();
  57551. var barycenter = BABYLON.Vector3.Zero();
  57552. var i;
  57553. for (i = 0; i < shapePath.length; i++) {
  57554. barycenter.addInPlace(shapePath[i]);
  57555. }
  57556. barycenter.scaleInPlace(1.0 / shapePath.length);
  57557. for (i = 0; i < shapePath.length; i++) {
  57558. pointCap.push(barycenter);
  57559. }
  57560. return pointCap;
  57561. };
  57562. switch (cap) {
  57563. case BABYLON.Mesh.NO_CAP:
  57564. break;
  57565. case BABYLON.Mesh.CAP_START:
  57566. shapePaths[0] = capPath(shapePaths[2]);
  57567. shapePaths[1] = shapePaths[2];
  57568. break;
  57569. case BABYLON.Mesh.CAP_END:
  57570. shapePaths[index] = shapePaths[index - 1];
  57571. shapePaths[index + 1] = capPath(shapePaths[index - 1]);
  57572. break;
  57573. case BABYLON.Mesh.CAP_ALL:
  57574. shapePaths[0] = capPath(shapePaths[2]);
  57575. shapePaths[1] = shapePaths[2];
  57576. shapePaths[index] = shapePaths[index - 1];
  57577. shapePaths[index + 1] = capPath(shapePaths[index - 1]);
  57578. break;
  57579. default:
  57580. break;
  57581. }
  57582. return shapePaths;
  57583. };
  57584. var path3D;
  57585. var pathArray;
  57586. if (instance) {
  57587. path3D = (instance.path3D).update(curve);
  57588. pathArray = extrusionPathArray(shape, curve, instance.path3D, instance.pathArray, scale, rotation, scaleFunction, rotateFunction, instance.cap, custom);
  57589. instance = BABYLON.Mesh.CreateRibbon("", pathArray, false, false, 0, scene || undefined, false, 0, instance);
  57590. return instance;
  57591. }
  57592. // extruded shape creation
  57593. path3D = new BABYLON.Path3D(curve);
  57594. var newShapePaths = new Array();
  57595. cap = (cap < 0 || cap > 3) ? 0 : cap;
  57596. pathArray = extrusionPathArray(shape, curve, path3D, newShapePaths, scale, rotation, scaleFunction, rotateFunction, cap, custom);
  57597. var extrudedGeneric = MeshBuilder.CreateRibbon(name, { pathArray: pathArray, closeArray: rbCA, closePath: rbCP, updatable: updtbl, sideOrientation: side, invertUV: invertUV, frontUVs: frontUVs || undefined, backUVs: backUVs || undefined }, scene);
  57598. extrudedGeneric.pathArray = pathArray;
  57599. extrudedGeneric.path3D = path3D;
  57600. extrudedGeneric.cap = cap;
  57601. return extrudedGeneric;
  57602. };
  57603. return MeshBuilder;
  57604. }());
  57605. BABYLON.MeshBuilder = MeshBuilder;
  57606. })(BABYLON || (BABYLON = {}));
  57607. //# sourceMappingURL=babylon.meshBuilder.js.map
  57608. "use strict";
  57609. var BABYLON;
  57610. (function (BABYLON) {
  57611. /**
  57612. * Draco compression (https://google.github.io/draco/)
  57613. */
  57614. var DracoCompression = /** @class */ (function () {
  57615. /**
  57616. * Constructor
  57617. * @param numWorkers The number of workers for async operations
  57618. */
  57619. function DracoCompression(numWorkers) {
  57620. if (numWorkers === void 0) { numWorkers = (navigator.hardwareConcurrency || 4); }
  57621. var workerBlobUrl = URL && URL.createObjectURL && URL.createObjectURL(new Blob(["(" + DracoCompression._Worker.toString() + ")()"], { type: "application/javascript" }));
  57622. if (!workerBlobUrl || !Worker) {
  57623. BABYLON.Tools.Error("Draco Compression disabled. The current context doesn't support worker creation or URL.createObjectURL");
  57624. return;
  57625. }
  57626. var workers = new Array(numWorkers);
  57627. for (var i = 0; i < workers.length; i++) {
  57628. var worker = new Worker(workerBlobUrl);
  57629. worker.postMessage({ id: "initDecoder", url: DracoCompression.DecoderUrl });
  57630. workers[i] = worker;
  57631. }
  57632. this._workerPool = new BABYLON.WorkerPool(workers);
  57633. }
  57634. /**
  57635. * Stop all async operations and release resources.
  57636. */
  57637. DracoCompression.prototype.dispose = function () {
  57638. this._workerPool.dispose();
  57639. delete this._workerPool;
  57640. };
  57641. /**
  57642. * Decode Draco compressed mesh data to vertex data.
  57643. * @param data The array buffer view for the Draco compression data
  57644. * @param attributes A map of attributes from vertex buffer kinds to Draco unique ids
  57645. * @returns A promise that resolves with the decoded vertex data
  57646. */
  57647. DracoCompression.prototype.decodeMeshAsync = function (data, attributes) {
  57648. var _this = this;
  57649. return new Promise(function (resolve, reject) {
  57650. _this._workerPool.push(function (worker, onComplete) {
  57651. var vertexData = new BABYLON.VertexData();
  57652. var onError = function (error) {
  57653. worker.removeEventListener("error", onError);
  57654. worker.removeEventListener("message", onMessage);
  57655. reject(error);
  57656. onComplete();
  57657. };
  57658. var onMessage = function (message) {
  57659. if (message.data === "done") {
  57660. worker.removeEventListener("error", onError);
  57661. worker.removeEventListener("message", onMessage);
  57662. resolve(vertexData);
  57663. onComplete();
  57664. }
  57665. else if (message.data.id === "indices") {
  57666. vertexData.indices = message.data.value;
  57667. }
  57668. else {
  57669. vertexData.set(message.data.value, message.data.id);
  57670. }
  57671. };
  57672. worker.addEventListener("error", onError);
  57673. worker.addEventListener("message", onMessage);
  57674. var dataCopy = new Uint8Array(data.byteLength);
  57675. dataCopy.set(new Uint8Array(data.buffer, data.byteOffset, data.byteLength));
  57676. worker.postMessage({ id: "decodeMesh", data: dataCopy, attributes: attributes }, [dataCopy.buffer]);
  57677. });
  57678. });
  57679. };
  57680. /**
  57681. * The worker function that gets converted to a blob url to pass into a worker.
  57682. */
  57683. DracoCompression._Worker = function () {
  57684. // self is actually a DedicatedWorkerGlobalScope
  57685. var _self = self;
  57686. var decodeMesh = function (data, attributes) {
  57687. var dracoModule = new DracoDecoderModule();
  57688. var buffer = new dracoModule.DecoderBuffer();
  57689. buffer.Init(data, data.byteLength);
  57690. var decoder = new dracoModule.Decoder();
  57691. var geometry;
  57692. var status;
  57693. try {
  57694. var type = decoder.GetEncodedGeometryType(buffer);
  57695. switch (type) {
  57696. case dracoModule.TRIANGULAR_MESH:
  57697. geometry = new dracoModule.Mesh();
  57698. status = decoder.DecodeBufferToMesh(buffer, geometry);
  57699. break;
  57700. case dracoModule.POINT_CLOUD:
  57701. geometry = new dracoModule.PointCloud();
  57702. status = decoder.DecodeBufferToPointCloud(buffer, geometry);
  57703. break;
  57704. default:
  57705. throw new Error("Invalid geometry type " + type);
  57706. }
  57707. if (!status.ok() || !geometry.ptr) {
  57708. throw new Error(status.error_msg());
  57709. }
  57710. var numPoints = geometry.num_points();
  57711. if (type === dracoModule.TRIANGULAR_MESH) {
  57712. var numFaces = geometry.num_faces();
  57713. var faceIndices = new dracoModule.DracoInt32Array();
  57714. try {
  57715. var indices = new Uint32Array(numFaces * 3);
  57716. for (var i = 0; i < numFaces; i++) {
  57717. decoder.GetFaceFromMesh(geometry, i, faceIndices);
  57718. var offset = i * 3;
  57719. indices[offset + 0] = faceIndices.GetValue(0);
  57720. indices[offset + 1] = faceIndices.GetValue(1);
  57721. indices[offset + 2] = faceIndices.GetValue(2);
  57722. }
  57723. _self.postMessage({ id: "indices", value: indices }, [indices.buffer]);
  57724. }
  57725. finally {
  57726. dracoModule.destroy(faceIndices);
  57727. }
  57728. }
  57729. for (var kind in attributes) {
  57730. var uniqueId = attributes[kind];
  57731. var attribute = decoder.GetAttributeByUniqueId(geometry, uniqueId);
  57732. var dracoData = new dracoModule.DracoFloat32Array();
  57733. try {
  57734. decoder.GetAttributeFloatForAllPoints(geometry, attribute, dracoData);
  57735. var babylonData = new Float32Array(numPoints * attribute.num_components());
  57736. for (var i = 0; i < babylonData.length; i++) {
  57737. babylonData[i] = dracoData.GetValue(i);
  57738. }
  57739. _self.postMessage({ id: kind, value: babylonData }, [babylonData.buffer]);
  57740. }
  57741. finally {
  57742. dracoModule.destroy(dracoData);
  57743. }
  57744. }
  57745. }
  57746. finally {
  57747. if (geometry) {
  57748. dracoModule.destroy(geometry);
  57749. }
  57750. dracoModule.destroy(decoder);
  57751. dracoModule.destroy(buffer);
  57752. }
  57753. _self.postMessage("done");
  57754. };
  57755. _self.onmessage = function (event) {
  57756. switch (event.data.id) {
  57757. case "initDecoder": {
  57758. importScripts(event.data.url);
  57759. break;
  57760. }
  57761. case "decodeMesh": {
  57762. decodeMesh(event.data.data, event.data.attributes);
  57763. break;
  57764. }
  57765. }
  57766. };
  57767. };
  57768. DracoCompression._GetDefaultDecoderUrl = function () {
  57769. if (!BABYLON.Tools.IsWindowObjectExist()) {
  57770. return null;
  57771. }
  57772. for (var i = 0; i < document.scripts.length; i++) {
  57773. if (document.scripts[i].type === "text/x-draco-decoder") {
  57774. return document.scripts[i].src;
  57775. }
  57776. }
  57777. return null;
  57778. };
  57779. /**
  57780. * Gets the url to the draco decoder if available.
  57781. */
  57782. DracoCompression.DecoderUrl = DracoCompression._GetDefaultDecoderUrl();
  57783. return DracoCompression;
  57784. }());
  57785. BABYLON.DracoCompression = DracoCompression;
  57786. })(BABYLON || (BABYLON = {}));
  57787. //# sourceMappingURL=babylon.dracoCompression.js.map
  57788. "use strict";
  57789. var BABYLON;
  57790. (function (BABYLON) {
  57791. var AudioEngine = /** @class */ (function () {
  57792. function AudioEngine() {
  57793. this._audioContext = null;
  57794. this._audioContextInitialized = false;
  57795. this.canUseWebAudio = false;
  57796. this.WarnedWebAudioUnsupported = false;
  57797. this.unlocked = false;
  57798. this.isMP3supported = false;
  57799. this.isOGGsupported = false;
  57800. if (typeof window.AudioContext !== 'undefined' || typeof window.webkitAudioContext !== 'undefined') {
  57801. window.AudioContext = window.AudioContext || window.webkitAudioContext;
  57802. this.canUseWebAudio = true;
  57803. }
  57804. var audioElem = document.createElement('audio');
  57805. try {
  57806. if (audioElem && !!audioElem.canPlayType && audioElem.canPlayType('audio/mpeg; codecs="mp3"').replace(/^no$/, '')) {
  57807. this.isMP3supported = true;
  57808. }
  57809. }
  57810. catch (e) {
  57811. // protect error during capability check.
  57812. }
  57813. try {
  57814. if (audioElem && !!audioElem.canPlayType && audioElem.canPlayType('audio/ogg; codecs="vorbis"').replace(/^no$/, '')) {
  57815. this.isOGGsupported = true;
  57816. }
  57817. }
  57818. catch (e) {
  57819. // protect error during capability check.
  57820. }
  57821. if (/iPad|iPhone|iPod/.test(navigator.platform)) {
  57822. this._unlockiOSaudio();
  57823. }
  57824. else {
  57825. this.unlocked = true;
  57826. }
  57827. }
  57828. Object.defineProperty(AudioEngine.prototype, "audioContext", {
  57829. get: function () {
  57830. if (!this._audioContextInitialized) {
  57831. this._initializeAudioContext();
  57832. }
  57833. return this._audioContext;
  57834. },
  57835. enumerable: true,
  57836. configurable: true
  57837. });
  57838. AudioEngine.prototype._unlockiOSaudio = function () {
  57839. var _this = this;
  57840. var unlockaudio = function () {
  57841. if (!_this.audioContext) {
  57842. return;
  57843. }
  57844. var buffer = _this.audioContext.createBuffer(1, 1, 22050);
  57845. var source = _this.audioContext.createBufferSource();
  57846. source.buffer = buffer;
  57847. source.connect(_this.audioContext.destination);
  57848. source.start(0);
  57849. setTimeout(function () {
  57850. if ((source.playbackState === source.PLAYING_STATE || source.playbackState === source.FINISHED_STATE)) {
  57851. _this.unlocked = true;
  57852. window.removeEventListener('touchend', unlockaudio, false);
  57853. if (_this.onAudioUnlocked) {
  57854. _this.onAudioUnlocked();
  57855. }
  57856. }
  57857. }, 0);
  57858. };
  57859. window.addEventListener('touchend', unlockaudio, false);
  57860. };
  57861. AudioEngine.prototype._initializeAudioContext = function () {
  57862. try {
  57863. if (this.canUseWebAudio) {
  57864. this._audioContext = new AudioContext();
  57865. // create a global volume gain node
  57866. this.masterGain = this._audioContext.createGain();
  57867. this.masterGain.gain.value = 1;
  57868. this.masterGain.connect(this._audioContext.destination);
  57869. this._audioContextInitialized = true;
  57870. }
  57871. }
  57872. catch (e) {
  57873. this.canUseWebAudio = false;
  57874. BABYLON.Tools.Error("Web Audio: " + e.message);
  57875. }
  57876. };
  57877. AudioEngine.prototype.dispose = function () {
  57878. if (this.canUseWebAudio && this._audioContextInitialized) {
  57879. if (this._connectedAnalyser && this._audioContext) {
  57880. this._connectedAnalyser.stopDebugCanvas();
  57881. this._connectedAnalyser.dispose();
  57882. this.masterGain.disconnect();
  57883. this.masterGain.connect(this._audioContext.destination);
  57884. this._connectedAnalyser = null;
  57885. }
  57886. this.masterGain.gain.value = 1;
  57887. }
  57888. this.WarnedWebAudioUnsupported = false;
  57889. };
  57890. AudioEngine.prototype.getGlobalVolume = function () {
  57891. if (this.canUseWebAudio && this._audioContextInitialized) {
  57892. return this.masterGain.gain.value;
  57893. }
  57894. else {
  57895. return -1;
  57896. }
  57897. };
  57898. AudioEngine.prototype.setGlobalVolume = function (newVolume) {
  57899. if (this.canUseWebAudio && this._audioContextInitialized) {
  57900. this.masterGain.gain.value = newVolume;
  57901. }
  57902. };
  57903. AudioEngine.prototype.connectToAnalyser = function (analyser) {
  57904. if (this._connectedAnalyser) {
  57905. this._connectedAnalyser.stopDebugCanvas();
  57906. }
  57907. if (this.canUseWebAudio && this._audioContextInitialized && this._audioContext) {
  57908. this._connectedAnalyser = analyser;
  57909. this.masterGain.disconnect();
  57910. this._connectedAnalyser.connectAudioNodes(this.masterGain, this._audioContext.destination);
  57911. }
  57912. };
  57913. return AudioEngine;
  57914. }());
  57915. BABYLON.AudioEngine = AudioEngine;
  57916. })(BABYLON || (BABYLON = {}));
  57917. //# sourceMappingURL=babylon.audioEngine.js.map
  57918. "use strict";
  57919. var BABYLON;
  57920. (function (BABYLON) {
  57921. var Sound = /** @class */ (function () {
  57922. /**
  57923. * Create a sound and attach it to a scene
  57924. * @param name Name of your sound
  57925. * @param urlOrArrayBuffer Url to the sound to load async or ArrayBuffer
  57926. * @param readyToPlayCallback Provide a callback function if you'd like to load your code once the sound is ready to be played
  57927. * @param options Objects to provide with the current available options: autoplay, loop, volume, spatialSound, maxDistance, rolloffFactor, refDistance, distanceModel, panningModel, streaming
  57928. */
  57929. function Sound(name, urlOrArrayBuffer, scene, readyToPlayCallback, options) {
  57930. if (readyToPlayCallback === void 0) { readyToPlayCallback = null; }
  57931. var _this = this;
  57932. this.autoplay = false;
  57933. this.loop = false;
  57934. this.useCustomAttenuation = false;
  57935. this.spatialSound = false;
  57936. this.refDistance = 1;
  57937. this.rolloffFactor = 1;
  57938. this.maxDistance = 100;
  57939. this.distanceModel = "linear";
  57940. this._panningModel = "equalpower";
  57941. this._playbackRate = 1;
  57942. this._streaming = false;
  57943. this._startTime = 0;
  57944. this._startOffset = 0;
  57945. this._position = BABYLON.Vector3.Zero();
  57946. this._localDirection = new BABYLON.Vector3(1, 0, 0);
  57947. this._volume = 1;
  57948. this._isReadyToPlay = false;
  57949. this.isPlaying = false;
  57950. this.isPaused = false;
  57951. this._isDirectional = false;
  57952. // Used if you'd like to create a directional sound.
  57953. // If not set, the sound will be omnidirectional
  57954. this._coneInnerAngle = 360;
  57955. this._coneOuterAngle = 360;
  57956. this._coneOuterGain = 0;
  57957. this._isOutputConnected = false;
  57958. this._urlType = "Unknown";
  57959. this.name = name;
  57960. this._scene = scene;
  57961. this._readyToPlayCallback = readyToPlayCallback;
  57962. // Default custom attenuation function is a linear attenuation
  57963. this._customAttenuationFunction = function (currentVolume, currentDistance, maxDistance, refDistance, rolloffFactor) {
  57964. if (currentDistance < maxDistance) {
  57965. return currentVolume * (1 - currentDistance / maxDistance);
  57966. }
  57967. else {
  57968. return 0;
  57969. }
  57970. };
  57971. if (options) {
  57972. this.autoplay = options.autoplay || false;
  57973. this.loop = options.loop || false;
  57974. // if volume === 0, we need another way to check this option
  57975. if (options.volume !== undefined) {
  57976. this._volume = options.volume;
  57977. }
  57978. this.spatialSound = options.spatialSound || false;
  57979. this.maxDistance = options.maxDistance || 100;
  57980. this.useCustomAttenuation = options.useCustomAttenuation || false;
  57981. this.rolloffFactor = options.rolloffFactor || 1;
  57982. this.refDistance = options.refDistance || 1;
  57983. this.distanceModel = options.distanceModel || "linear";
  57984. this._playbackRate = options.playbackRate || 1;
  57985. this._streaming = options.streaming || false;
  57986. }
  57987. if (BABYLON.Engine.audioEngine.canUseWebAudio && BABYLON.Engine.audioEngine.audioContext) {
  57988. this._soundGain = BABYLON.Engine.audioEngine.audioContext.createGain();
  57989. this._soundGain.gain.value = this._volume;
  57990. this._inputAudioNode = this._soundGain;
  57991. this._ouputAudioNode = this._soundGain;
  57992. if (this.spatialSound) {
  57993. this._createSpatialParameters();
  57994. }
  57995. this._scene.mainSoundTrack.AddSound(this);
  57996. var validParameter = true;
  57997. // if no parameter is passed, you need to call setAudioBuffer yourself to prepare the sound
  57998. if (urlOrArrayBuffer) {
  57999. try {
  58000. if (typeof (urlOrArrayBuffer) === "string")
  58001. this._urlType = "String";
  58002. if (Array.isArray(urlOrArrayBuffer))
  58003. this._urlType = "Array";
  58004. if (urlOrArrayBuffer instanceof ArrayBuffer)
  58005. this._urlType = "ArrayBuffer";
  58006. var urls = [];
  58007. var codecSupportedFound = false;
  58008. switch (this._urlType) {
  58009. case "ArrayBuffer":
  58010. if (urlOrArrayBuffer.byteLength > 0) {
  58011. codecSupportedFound = true;
  58012. this._soundLoaded(urlOrArrayBuffer);
  58013. }
  58014. break;
  58015. case "String":
  58016. urls.push(urlOrArrayBuffer);
  58017. case "Array":
  58018. if (urls.length === 0)
  58019. urls = urlOrArrayBuffer;
  58020. // If we found a supported format, we load it immediately and stop the loop
  58021. for (var i = 0; i < urls.length; i++) {
  58022. var url = urls[i];
  58023. if (url.indexOf(".mp3", url.length - 4) !== -1 && BABYLON.Engine.audioEngine.isMP3supported) {
  58024. codecSupportedFound = true;
  58025. }
  58026. if (url.indexOf(".ogg", url.length - 4) !== -1 && BABYLON.Engine.audioEngine.isOGGsupported) {
  58027. codecSupportedFound = true;
  58028. }
  58029. if (url.indexOf(".wav", url.length - 4) !== -1) {
  58030. codecSupportedFound = true;
  58031. }
  58032. if (url.indexOf("blob:") !== -1) {
  58033. codecSupportedFound = true;
  58034. }
  58035. if (codecSupportedFound) {
  58036. // Loading sound using XHR2
  58037. if (!this._streaming) {
  58038. this._scene._loadFile(url, function (data) {
  58039. _this._soundLoaded(data);
  58040. }, undefined, true, true, function (exception) {
  58041. if (exception) {
  58042. BABYLON.Tools.Error("XHR " + exception.status + " error on: " + url + ".");
  58043. }
  58044. BABYLON.Tools.Error("Sound creation aborted.");
  58045. _this._scene.mainSoundTrack.RemoveSound(_this);
  58046. });
  58047. }
  58048. else {
  58049. this._htmlAudioElement = new Audio(url);
  58050. this._htmlAudioElement.controls = false;
  58051. this._htmlAudioElement.loop = this.loop;
  58052. BABYLON.Tools.SetCorsBehavior(url, this._htmlAudioElement);
  58053. this._htmlAudioElement.preload = "auto";
  58054. this._htmlAudioElement.addEventListener("canplaythrough", function () {
  58055. _this._isReadyToPlay = true;
  58056. if (_this.autoplay) {
  58057. _this.play();
  58058. }
  58059. if (_this._readyToPlayCallback) {
  58060. _this._readyToPlayCallback();
  58061. }
  58062. });
  58063. document.body.appendChild(this._htmlAudioElement);
  58064. }
  58065. break;
  58066. }
  58067. }
  58068. break;
  58069. default:
  58070. validParameter = false;
  58071. break;
  58072. }
  58073. if (!validParameter) {
  58074. BABYLON.Tools.Error("Parameter must be a URL to the sound, an Array of URLs (.mp3 & .ogg) or an ArrayBuffer of the sound.");
  58075. }
  58076. else {
  58077. if (!codecSupportedFound) {
  58078. this._isReadyToPlay = true;
  58079. // Simulating a ready to play event to avoid breaking code path
  58080. if (this._readyToPlayCallback) {
  58081. window.setTimeout(function () {
  58082. if (_this._readyToPlayCallback) {
  58083. _this._readyToPlayCallback();
  58084. }
  58085. }, 1000);
  58086. }
  58087. }
  58088. }
  58089. }
  58090. catch (ex) {
  58091. BABYLON.Tools.Error("Unexpected error. Sound creation aborted.");
  58092. this._scene.mainSoundTrack.RemoveSound(this);
  58093. }
  58094. }
  58095. }
  58096. else {
  58097. // Adding an empty sound to avoid breaking audio calls for non Web Audio browsers
  58098. this._scene.mainSoundTrack.AddSound(this);
  58099. if (!BABYLON.Engine.audioEngine.WarnedWebAudioUnsupported) {
  58100. BABYLON.Tools.Error("Web Audio is not supported by your browser.");
  58101. BABYLON.Engine.audioEngine.WarnedWebAudioUnsupported = true;
  58102. }
  58103. // Simulating a ready to play event to avoid breaking code for non web audio browsers
  58104. if (this._readyToPlayCallback) {
  58105. window.setTimeout(function () {
  58106. if (_this._readyToPlayCallback) {
  58107. _this._readyToPlayCallback();
  58108. }
  58109. }, 1000);
  58110. }
  58111. }
  58112. }
  58113. Sound.prototype.dispose = function () {
  58114. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  58115. if (this.isPlaying) {
  58116. this.stop();
  58117. }
  58118. this._isReadyToPlay = false;
  58119. if (this.soundTrackId === -1) {
  58120. this._scene.mainSoundTrack.RemoveSound(this);
  58121. }
  58122. else {
  58123. this._scene.soundTracks[this.soundTrackId].RemoveSound(this);
  58124. }
  58125. if (this._soundGain) {
  58126. this._soundGain.disconnect();
  58127. this._soundGain = null;
  58128. }
  58129. if (this._soundPanner) {
  58130. this._soundPanner.disconnect();
  58131. this._soundPanner = null;
  58132. }
  58133. if (this._soundSource) {
  58134. this._soundSource.disconnect();
  58135. this._soundSource = null;
  58136. }
  58137. this._audioBuffer = null;
  58138. if (this._htmlAudioElement) {
  58139. this._htmlAudioElement.pause();
  58140. this._htmlAudioElement.src = "";
  58141. document.body.removeChild(this._htmlAudioElement);
  58142. }
  58143. if (this._connectedMesh && this._registerFunc) {
  58144. this._connectedMesh.unregisterAfterWorldMatrixUpdate(this._registerFunc);
  58145. this._connectedMesh = null;
  58146. }
  58147. }
  58148. };
  58149. Sound.prototype.isReady = function () {
  58150. return this._isReadyToPlay;
  58151. };
  58152. Sound.prototype._soundLoaded = function (audioData) {
  58153. var _this = this;
  58154. if (!BABYLON.Engine.audioEngine.audioContext) {
  58155. return;
  58156. }
  58157. BABYLON.Engine.audioEngine.audioContext.decodeAudioData(audioData, function (buffer) {
  58158. _this._audioBuffer = buffer;
  58159. _this._isReadyToPlay = true;
  58160. if (_this.autoplay) {
  58161. _this.play();
  58162. }
  58163. if (_this._readyToPlayCallback) {
  58164. _this._readyToPlayCallback();
  58165. }
  58166. }, function (err) { BABYLON.Tools.Error("Error while decoding audio data for: " + _this.name + " / Error: " + err); });
  58167. };
  58168. Sound.prototype.setAudioBuffer = function (audioBuffer) {
  58169. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  58170. this._audioBuffer = audioBuffer;
  58171. this._isReadyToPlay = true;
  58172. }
  58173. };
  58174. Sound.prototype.updateOptions = function (options) {
  58175. if (options) {
  58176. this.loop = options.loop || this.loop;
  58177. this.maxDistance = options.maxDistance || this.maxDistance;
  58178. this.useCustomAttenuation = options.useCustomAttenuation || this.useCustomAttenuation;
  58179. this.rolloffFactor = options.rolloffFactor || this.rolloffFactor;
  58180. this.refDistance = options.refDistance || this.refDistance;
  58181. this.distanceModel = options.distanceModel || this.distanceModel;
  58182. this._playbackRate = options.playbackRate || this._playbackRate;
  58183. this._updateSpatialParameters();
  58184. if (this.isPlaying) {
  58185. if (this._streaming) {
  58186. this._htmlAudioElement.playbackRate = this._playbackRate;
  58187. }
  58188. else {
  58189. if (this._soundSource) {
  58190. this._soundSource.playbackRate.value = this._playbackRate;
  58191. }
  58192. }
  58193. }
  58194. }
  58195. };
  58196. Sound.prototype._createSpatialParameters = function () {
  58197. if (BABYLON.Engine.audioEngine.canUseWebAudio && BABYLON.Engine.audioEngine.audioContext) {
  58198. if (this._scene.headphone) {
  58199. this._panningModel = "HRTF";
  58200. }
  58201. this._soundPanner = BABYLON.Engine.audioEngine.audioContext.createPanner();
  58202. this._updateSpatialParameters();
  58203. this._soundPanner.connect(this._ouputAudioNode);
  58204. this._inputAudioNode = this._soundPanner;
  58205. }
  58206. };
  58207. Sound.prototype._updateSpatialParameters = function () {
  58208. if (this.spatialSound && this._soundPanner) {
  58209. if (this.useCustomAttenuation) {
  58210. // Tricks to disable in a way embedded Web Audio attenuation
  58211. this._soundPanner.distanceModel = "linear";
  58212. this._soundPanner.maxDistance = Number.MAX_VALUE;
  58213. this._soundPanner.refDistance = 1;
  58214. this._soundPanner.rolloffFactor = 1;
  58215. this._soundPanner.panningModel = this._panningModel;
  58216. }
  58217. else {
  58218. this._soundPanner.distanceModel = this.distanceModel;
  58219. this._soundPanner.maxDistance = this.maxDistance;
  58220. this._soundPanner.refDistance = this.refDistance;
  58221. this._soundPanner.rolloffFactor = this.rolloffFactor;
  58222. this._soundPanner.panningModel = this._panningModel;
  58223. }
  58224. }
  58225. };
  58226. Sound.prototype.switchPanningModelToHRTF = function () {
  58227. this._panningModel = "HRTF";
  58228. this._switchPanningModel();
  58229. };
  58230. Sound.prototype.switchPanningModelToEqualPower = function () {
  58231. this._panningModel = "equalpower";
  58232. this._switchPanningModel();
  58233. };
  58234. Sound.prototype._switchPanningModel = function () {
  58235. if (BABYLON.Engine.audioEngine.canUseWebAudio && this.spatialSound && this._soundPanner) {
  58236. this._soundPanner.panningModel = this._panningModel;
  58237. }
  58238. };
  58239. Sound.prototype.connectToSoundTrackAudioNode = function (soundTrackAudioNode) {
  58240. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  58241. if (this._isOutputConnected) {
  58242. this._ouputAudioNode.disconnect();
  58243. }
  58244. this._ouputAudioNode.connect(soundTrackAudioNode);
  58245. this._isOutputConnected = true;
  58246. }
  58247. };
  58248. /**
  58249. * Transform this sound into a directional source
  58250. * @param coneInnerAngle Size of the inner cone in degree
  58251. * @param coneOuterAngle Size of the outer cone in degree
  58252. * @param coneOuterGain Volume of the sound outside the outer cone (between 0.0 and 1.0)
  58253. */
  58254. Sound.prototype.setDirectionalCone = function (coneInnerAngle, coneOuterAngle, coneOuterGain) {
  58255. if (coneOuterAngle < coneInnerAngle) {
  58256. BABYLON.Tools.Error("setDirectionalCone(): outer angle of the cone must be superior or equal to the inner angle.");
  58257. return;
  58258. }
  58259. this._coneInnerAngle = coneInnerAngle;
  58260. this._coneOuterAngle = coneOuterAngle;
  58261. this._coneOuterGain = coneOuterGain;
  58262. this._isDirectional = true;
  58263. if (this.isPlaying && this.loop) {
  58264. this.stop();
  58265. this.play();
  58266. }
  58267. };
  58268. Sound.prototype.setPosition = function (newPosition) {
  58269. this._position = newPosition;
  58270. if (BABYLON.Engine.audioEngine.canUseWebAudio && this.spatialSound && this._soundPanner) {
  58271. this._soundPanner.setPosition(this._position.x, this._position.y, this._position.z);
  58272. }
  58273. };
  58274. Sound.prototype.setLocalDirectionToMesh = function (newLocalDirection) {
  58275. this._localDirection = newLocalDirection;
  58276. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._connectedMesh && this.isPlaying) {
  58277. this._updateDirection();
  58278. }
  58279. };
  58280. Sound.prototype._updateDirection = function () {
  58281. if (!this._connectedMesh || !this._soundPanner) {
  58282. return;
  58283. }
  58284. var mat = this._connectedMesh.getWorldMatrix();
  58285. var direction = BABYLON.Vector3.TransformNormal(this._localDirection, mat);
  58286. direction.normalize();
  58287. this._soundPanner.setOrientation(direction.x, direction.y, direction.z);
  58288. };
  58289. Sound.prototype.updateDistanceFromListener = function () {
  58290. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._connectedMesh && this.useCustomAttenuation && this._soundGain && this._scene.activeCamera) {
  58291. var distance = this._connectedMesh.getDistanceToCamera(this._scene.activeCamera);
  58292. this._soundGain.gain.value = this._customAttenuationFunction(this._volume, distance, this.maxDistance, this.refDistance, this.rolloffFactor);
  58293. }
  58294. };
  58295. Sound.prototype.setAttenuationFunction = function (callback) {
  58296. this._customAttenuationFunction = callback;
  58297. };
  58298. /**
  58299. * Play the sound
  58300. * @param time (optional) Start the sound after X seconds. Start immediately (0) by default.
  58301. * @param offset (optional) Start the sound setting it at a specific time
  58302. */
  58303. Sound.prototype.play = function (time, offset) {
  58304. var _this = this;
  58305. if (this._isReadyToPlay && this._scene.audioEnabled && BABYLON.Engine.audioEngine.audioContext) {
  58306. try {
  58307. if (this._startOffset < 0) {
  58308. time = -this._startOffset;
  58309. this._startOffset = 0;
  58310. }
  58311. var startTime = time ? BABYLON.Engine.audioEngine.audioContext.currentTime + time : BABYLON.Engine.audioEngine.audioContext.currentTime;
  58312. if (!this._soundSource || !this._streamingSource) {
  58313. if (this.spatialSound && this._soundPanner) {
  58314. this._soundPanner.setPosition(this._position.x, this._position.y, this._position.z);
  58315. if (this._isDirectional) {
  58316. this._soundPanner.coneInnerAngle = this._coneInnerAngle;
  58317. this._soundPanner.coneOuterAngle = this._coneOuterAngle;
  58318. this._soundPanner.coneOuterGain = this._coneOuterGain;
  58319. if (this._connectedMesh) {
  58320. this._updateDirection();
  58321. }
  58322. else {
  58323. this._soundPanner.setOrientation(this._localDirection.x, this._localDirection.y, this._localDirection.z);
  58324. }
  58325. }
  58326. }
  58327. }
  58328. if (this._streaming) {
  58329. if (!this._streamingSource) {
  58330. this._streamingSource = BABYLON.Engine.audioEngine.audioContext.createMediaElementSource(this._htmlAudioElement);
  58331. this._htmlAudioElement.onended = function () { _this._onended(); };
  58332. this._htmlAudioElement.playbackRate = this._playbackRate;
  58333. }
  58334. this._streamingSource.disconnect();
  58335. this._streamingSource.connect(this._inputAudioNode);
  58336. this._htmlAudioElement.play();
  58337. }
  58338. else {
  58339. this._soundSource = BABYLON.Engine.audioEngine.audioContext.createBufferSource();
  58340. this._soundSource.buffer = this._audioBuffer;
  58341. this._soundSource.connect(this._inputAudioNode);
  58342. this._soundSource.loop = this.loop;
  58343. this._soundSource.playbackRate.value = this._playbackRate;
  58344. this._soundSource.onended = function () { _this._onended(); };
  58345. if (this._soundSource.buffer) {
  58346. this._soundSource.start(startTime, this.isPaused ? this._startOffset % this._soundSource.buffer.duration : offset ? offset : 0);
  58347. }
  58348. }
  58349. this._startTime = startTime;
  58350. this.isPlaying = true;
  58351. this.isPaused = false;
  58352. }
  58353. catch (ex) {
  58354. BABYLON.Tools.Error("Error while trying to play audio: " + this.name + ", " + ex.message);
  58355. }
  58356. }
  58357. };
  58358. Sound.prototype._onended = function () {
  58359. this.isPlaying = false;
  58360. if (this.onended) {
  58361. this.onended();
  58362. }
  58363. };
  58364. /**
  58365. * Stop the sound
  58366. * @param time (optional) Stop the sound after X seconds. Stop immediately (0) by default.
  58367. */
  58368. Sound.prototype.stop = function (time) {
  58369. if (this.isPlaying) {
  58370. if (this._streaming) {
  58371. this._htmlAudioElement.pause();
  58372. // Test needed for Firefox or it will generate an Invalid State Error
  58373. if (this._htmlAudioElement.currentTime > 0) {
  58374. this._htmlAudioElement.currentTime = 0;
  58375. }
  58376. }
  58377. else if (BABYLON.Engine.audioEngine.audioContext && this._soundSource) {
  58378. var stopTime = time ? BABYLON.Engine.audioEngine.audioContext.currentTime + time : BABYLON.Engine.audioEngine.audioContext.currentTime;
  58379. this._soundSource.stop(stopTime);
  58380. this._soundSource.onended = function () { };
  58381. if (!this.isPaused) {
  58382. this._startOffset = 0;
  58383. }
  58384. }
  58385. this.isPlaying = false;
  58386. }
  58387. };
  58388. Sound.prototype.pause = function () {
  58389. if (this.isPlaying) {
  58390. this.isPaused = true;
  58391. if (this._streaming) {
  58392. this._htmlAudioElement.pause();
  58393. }
  58394. else if (BABYLON.Engine.audioEngine.audioContext) {
  58395. this.stop(0);
  58396. this._startOffset += BABYLON.Engine.audioEngine.audioContext.currentTime - this._startTime;
  58397. }
  58398. }
  58399. };
  58400. Sound.prototype.setVolume = function (newVolume, time) {
  58401. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._soundGain) {
  58402. if (time && BABYLON.Engine.audioEngine.audioContext) {
  58403. this._soundGain.gain.cancelScheduledValues(BABYLON.Engine.audioEngine.audioContext.currentTime);
  58404. this._soundGain.gain.setValueAtTime(this._soundGain.gain.value, BABYLON.Engine.audioEngine.audioContext.currentTime);
  58405. this._soundGain.gain.linearRampToValueAtTime(newVolume, BABYLON.Engine.audioEngine.audioContext.currentTime + time);
  58406. }
  58407. else {
  58408. this._soundGain.gain.value = newVolume;
  58409. }
  58410. }
  58411. this._volume = newVolume;
  58412. };
  58413. Sound.prototype.setPlaybackRate = function (newPlaybackRate) {
  58414. this._playbackRate = newPlaybackRate;
  58415. if (this.isPlaying) {
  58416. if (this._streaming) {
  58417. this._htmlAudioElement.playbackRate = this._playbackRate;
  58418. }
  58419. else if (this._soundSource) {
  58420. this._soundSource.playbackRate.value = this._playbackRate;
  58421. }
  58422. }
  58423. };
  58424. Sound.prototype.getVolume = function () {
  58425. return this._volume;
  58426. };
  58427. Sound.prototype.attachToMesh = function (meshToConnectTo) {
  58428. var _this = this;
  58429. if (this._connectedMesh && this._registerFunc) {
  58430. this._connectedMesh.unregisterAfterWorldMatrixUpdate(this._registerFunc);
  58431. this._registerFunc = null;
  58432. }
  58433. this._connectedMesh = meshToConnectTo;
  58434. if (!this.spatialSound) {
  58435. this.spatialSound = true;
  58436. this._createSpatialParameters();
  58437. if (this.isPlaying && this.loop) {
  58438. this.stop();
  58439. this.play();
  58440. }
  58441. }
  58442. this._onRegisterAfterWorldMatrixUpdate(this._connectedMesh);
  58443. this._registerFunc = function (connectedMesh) { return _this._onRegisterAfterWorldMatrixUpdate(connectedMesh); };
  58444. meshToConnectTo.registerAfterWorldMatrixUpdate(this._registerFunc);
  58445. };
  58446. Sound.prototype.detachFromMesh = function () {
  58447. if (this._connectedMesh && this._registerFunc) {
  58448. this._connectedMesh.unregisterAfterWorldMatrixUpdate(this._registerFunc);
  58449. this._registerFunc = null;
  58450. this._connectedMesh = null;
  58451. }
  58452. };
  58453. Sound.prototype._onRegisterAfterWorldMatrixUpdate = function (node) {
  58454. if (!node.getBoundingInfo) {
  58455. return;
  58456. }
  58457. var mesh = node;
  58458. var boundingInfo = mesh.getBoundingInfo();
  58459. this.setPosition(boundingInfo.boundingSphere.centerWorld);
  58460. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._isDirectional && this.isPlaying) {
  58461. this._updateDirection();
  58462. }
  58463. };
  58464. Sound.prototype.clone = function () {
  58465. var _this = this;
  58466. if (!this._streaming) {
  58467. var setBufferAndRun = function () {
  58468. if (_this._isReadyToPlay) {
  58469. clonedSound._audioBuffer = _this.getAudioBuffer();
  58470. clonedSound._isReadyToPlay = true;
  58471. if (clonedSound.autoplay) {
  58472. clonedSound.play();
  58473. }
  58474. }
  58475. else {
  58476. window.setTimeout(setBufferAndRun, 300);
  58477. }
  58478. };
  58479. var currentOptions = {
  58480. autoplay: this.autoplay, loop: this.loop,
  58481. volume: this._volume, spatialSound: this.spatialSound, maxDistance: this.maxDistance,
  58482. useCustomAttenuation: this.useCustomAttenuation, rolloffFactor: this.rolloffFactor,
  58483. refDistance: this.refDistance, distanceModel: this.distanceModel
  58484. };
  58485. var clonedSound = new Sound(this.name + "_cloned", new ArrayBuffer(0), this._scene, null, currentOptions);
  58486. if (this.useCustomAttenuation) {
  58487. clonedSound.setAttenuationFunction(this._customAttenuationFunction);
  58488. }
  58489. clonedSound.setPosition(this._position);
  58490. clonedSound.setPlaybackRate(this._playbackRate);
  58491. setBufferAndRun();
  58492. return clonedSound;
  58493. }
  58494. else {
  58495. return null;
  58496. }
  58497. };
  58498. Sound.prototype.getAudioBuffer = function () {
  58499. return this._audioBuffer;
  58500. };
  58501. Sound.prototype.serialize = function () {
  58502. var serializationObject = {
  58503. name: this.name,
  58504. url: this.name,
  58505. autoplay: this.autoplay,
  58506. loop: this.loop,
  58507. volume: this._volume,
  58508. spatialSound: this.spatialSound,
  58509. maxDistance: this.maxDistance,
  58510. rolloffFactor: this.rolloffFactor,
  58511. refDistance: this.refDistance,
  58512. distanceModel: this.distanceModel,
  58513. playbackRate: this._playbackRate,
  58514. panningModel: this._panningModel,
  58515. soundTrackId: this.soundTrackId
  58516. };
  58517. if (this.spatialSound) {
  58518. if (this._connectedMesh)
  58519. serializationObject.connectedMeshId = this._connectedMesh.id;
  58520. serializationObject.position = this._position.asArray();
  58521. serializationObject.refDistance = this.refDistance;
  58522. serializationObject.distanceModel = this.distanceModel;
  58523. serializationObject.isDirectional = this._isDirectional;
  58524. serializationObject.localDirectionToMesh = this._localDirection.asArray();
  58525. serializationObject.coneInnerAngle = this._coneInnerAngle;
  58526. serializationObject.coneOuterAngle = this._coneOuterAngle;
  58527. serializationObject.coneOuterGain = this._coneOuterGain;
  58528. }
  58529. return serializationObject;
  58530. };
  58531. Sound.Parse = function (parsedSound, scene, rootUrl, sourceSound) {
  58532. var soundName = parsedSound.name;
  58533. var soundUrl;
  58534. if (parsedSound.url) {
  58535. soundUrl = rootUrl + parsedSound.url;
  58536. }
  58537. else {
  58538. soundUrl = rootUrl + soundName;
  58539. }
  58540. var options = {
  58541. autoplay: parsedSound.autoplay, loop: parsedSound.loop, volume: parsedSound.volume,
  58542. spatialSound: parsedSound.spatialSound, maxDistance: parsedSound.maxDistance,
  58543. rolloffFactor: parsedSound.rolloffFactor,
  58544. refDistance: parsedSound.refDistance,
  58545. distanceModel: parsedSound.distanceModel,
  58546. playbackRate: parsedSound.playbackRate
  58547. };
  58548. var newSound;
  58549. if (!sourceSound) {
  58550. newSound = new Sound(soundName, soundUrl, scene, function () { scene._removePendingData(newSound); }, options);
  58551. scene._addPendingData(newSound);
  58552. }
  58553. else {
  58554. var setBufferAndRun = function () {
  58555. if (sourceSound._isReadyToPlay) {
  58556. newSound._audioBuffer = sourceSound.getAudioBuffer();
  58557. newSound._isReadyToPlay = true;
  58558. if (newSound.autoplay) {
  58559. newSound.play();
  58560. }
  58561. }
  58562. else {
  58563. window.setTimeout(setBufferAndRun, 300);
  58564. }
  58565. };
  58566. newSound = new Sound(soundName, new ArrayBuffer(0), scene, null, options);
  58567. setBufferAndRun();
  58568. }
  58569. if (parsedSound.position) {
  58570. var soundPosition = BABYLON.Vector3.FromArray(parsedSound.position);
  58571. newSound.setPosition(soundPosition);
  58572. }
  58573. if (parsedSound.isDirectional) {
  58574. newSound.setDirectionalCone(parsedSound.coneInnerAngle || 360, parsedSound.coneOuterAngle || 360, parsedSound.coneOuterGain || 0);
  58575. if (parsedSound.localDirectionToMesh) {
  58576. var localDirectionToMesh = BABYLON.Vector3.FromArray(parsedSound.localDirectionToMesh);
  58577. newSound.setLocalDirectionToMesh(localDirectionToMesh);
  58578. }
  58579. }
  58580. if (parsedSound.connectedMeshId) {
  58581. var connectedMesh = scene.getMeshByID(parsedSound.connectedMeshId);
  58582. if (connectedMesh) {
  58583. newSound.attachToMesh(connectedMesh);
  58584. }
  58585. }
  58586. return newSound;
  58587. };
  58588. return Sound;
  58589. }());
  58590. BABYLON.Sound = Sound;
  58591. })(BABYLON || (BABYLON = {}));
  58592. //# sourceMappingURL=babylon.sound.js.map
  58593. "use strict";
  58594. var BABYLON;
  58595. (function (BABYLON) {
  58596. var SoundTrack = /** @class */ (function () {
  58597. function SoundTrack(scene, options) {
  58598. this.id = -1;
  58599. this._isMainTrack = false;
  58600. this._isInitialized = false;
  58601. this._scene = scene;
  58602. this.soundCollection = new Array();
  58603. this._options = options;
  58604. if (!this._isMainTrack) {
  58605. this._scene.soundTracks.push(this);
  58606. this.id = this._scene.soundTracks.length - 1;
  58607. }
  58608. }
  58609. SoundTrack.prototype._initializeSoundTrackAudioGraph = function () {
  58610. if (BABYLON.Engine.audioEngine.canUseWebAudio && BABYLON.Engine.audioEngine.audioContext) {
  58611. this._outputAudioNode = BABYLON.Engine.audioEngine.audioContext.createGain();
  58612. this._outputAudioNode.connect(BABYLON.Engine.audioEngine.masterGain);
  58613. if (this._options) {
  58614. if (this._options.volume) {
  58615. this._outputAudioNode.gain.value = this._options.volume;
  58616. }
  58617. if (this._options.mainTrack) {
  58618. this._isMainTrack = this._options.mainTrack;
  58619. }
  58620. }
  58621. this._isInitialized = true;
  58622. }
  58623. };
  58624. SoundTrack.prototype.dispose = function () {
  58625. if (BABYLON.Engine.audioEngine && BABYLON.Engine.audioEngine.canUseWebAudio) {
  58626. if (this._connectedAnalyser) {
  58627. this._connectedAnalyser.stopDebugCanvas();
  58628. }
  58629. while (this.soundCollection.length) {
  58630. this.soundCollection[0].dispose();
  58631. }
  58632. if (this._outputAudioNode) {
  58633. this._outputAudioNode.disconnect();
  58634. }
  58635. this._outputAudioNode = null;
  58636. }
  58637. };
  58638. SoundTrack.prototype.AddSound = function (sound) {
  58639. if (!this._isInitialized) {
  58640. this._initializeSoundTrackAudioGraph();
  58641. }
  58642. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._outputAudioNode) {
  58643. sound.connectToSoundTrackAudioNode(this._outputAudioNode);
  58644. }
  58645. if (sound.soundTrackId) {
  58646. if (sound.soundTrackId === -1) {
  58647. this._scene.mainSoundTrack.RemoveSound(sound);
  58648. }
  58649. else {
  58650. this._scene.soundTracks[sound.soundTrackId].RemoveSound(sound);
  58651. }
  58652. }
  58653. this.soundCollection.push(sound);
  58654. sound.soundTrackId = this.id;
  58655. };
  58656. SoundTrack.prototype.RemoveSound = function (sound) {
  58657. var index = this.soundCollection.indexOf(sound);
  58658. if (index !== -1) {
  58659. this.soundCollection.splice(index, 1);
  58660. }
  58661. };
  58662. SoundTrack.prototype.setVolume = function (newVolume) {
  58663. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._outputAudioNode) {
  58664. this._outputAudioNode.gain.value = newVolume;
  58665. }
  58666. };
  58667. SoundTrack.prototype.switchPanningModelToHRTF = function () {
  58668. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  58669. for (var i = 0; i < this.soundCollection.length; i++) {
  58670. this.soundCollection[i].switchPanningModelToHRTF();
  58671. }
  58672. }
  58673. };
  58674. SoundTrack.prototype.switchPanningModelToEqualPower = function () {
  58675. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  58676. for (var i = 0; i < this.soundCollection.length; i++) {
  58677. this.soundCollection[i].switchPanningModelToEqualPower();
  58678. }
  58679. }
  58680. };
  58681. SoundTrack.prototype.connectToAnalyser = function (analyser) {
  58682. if (this._connectedAnalyser) {
  58683. this._connectedAnalyser.stopDebugCanvas();
  58684. }
  58685. this._connectedAnalyser = analyser;
  58686. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._outputAudioNode) {
  58687. this._outputAudioNode.disconnect();
  58688. this._connectedAnalyser.connectAudioNodes(this._outputAudioNode, BABYLON.Engine.audioEngine.masterGain);
  58689. }
  58690. };
  58691. return SoundTrack;
  58692. }());
  58693. BABYLON.SoundTrack = SoundTrack;
  58694. })(BABYLON || (BABYLON = {}));
  58695. //# sourceMappingURL=babylon.soundtrack.js.map
  58696. "use strict";
  58697. var BABYLON;
  58698. (function (BABYLON) {
  58699. var Analyser = /** @class */ (function () {
  58700. function Analyser(scene) {
  58701. this.SMOOTHING = 0.75;
  58702. this.FFT_SIZE = 512;
  58703. this.BARGRAPHAMPLITUDE = 256;
  58704. this.DEBUGCANVASPOS = { x: 20, y: 20 };
  58705. this.DEBUGCANVASSIZE = { width: 320, height: 200 };
  58706. this._scene = scene;
  58707. this._audioEngine = BABYLON.Engine.audioEngine;
  58708. if (this._audioEngine.canUseWebAudio && this._audioEngine.audioContext) {
  58709. this._webAudioAnalyser = this._audioEngine.audioContext.createAnalyser();
  58710. this._webAudioAnalyser.minDecibels = -140;
  58711. this._webAudioAnalyser.maxDecibels = 0;
  58712. this._byteFreqs = new Uint8Array(this._webAudioAnalyser.frequencyBinCount);
  58713. this._byteTime = new Uint8Array(this._webAudioAnalyser.frequencyBinCount);
  58714. this._floatFreqs = new Float32Array(this._webAudioAnalyser.frequencyBinCount);
  58715. }
  58716. }
  58717. Analyser.prototype.getFrequencyBinCount = function () {
  58718. if (this._audioEngine.canUseWebAudio) {
  58719. return this._webAudioAnalyser.frequencyBinCount;
  58720. }
  58721. else {
  58722. return 0;
  58723. }
  58724. };
  58725. Analyser.prototype.getByteFrequencyData = function () {
  58726. if (this._audioEngine.canUseWebAudio) {
  58727. this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
  58728. this._webAudioAnalyser.fftSize = this.FFT_SIZE;
  58729. this._webAudioAnalyser.getByteFrequencyData(this._byteFreqs);
  58730. }
  58731. return this._byteFreqs;
  58732. };
  58733. Analyser.prototype.getByteTimeDomainData = function () {
  58734. if (this._audioEngine.canUseWebAudio) {
  58735. this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
  58736. this._webAudioAnalyser.fftSize = this.FFT_SIZE;
  58737. this._webAudioAnalyser.getByteTimeDomainData(this._byteTime);
  58738. }
  58739. return this._byteTime;
  58740. };
  58741. Analyser.prototype.getFloatFrequencyData = function () {
  58742. if (this._audioEngine.canUseWebAudio) {
  58743. this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
  58744. this._webAudioAnalyser.fftSize = this.FFT_SIZE;
  58745. this._webAudioAnalyser.getFloatFrequencyData(this._floatFreqs);
  58746. }
  58747. return this._floatFreqs;
  58748. };
  58749. Analyser.prototype.drawDebugCanvas = function () {
  58750. var _this = this;
  58751. if (this._audioEngine.canUseWebAudio) {
  58752. if (!this._debugCanvas) {
  58753. this._debugCanvas = document.createElement("canvas");
  58754. this._debugCanvas.width = this.DEBUGCANVASSIZE.width;
  58755. this._debugCanvas.height = this.DEBUGCANVASSIZE.height;
  58756. this._debugCanvas.style.position = "absolute";
  58757. this._debugCanvas.style.top = this.DEBUGCANVASPOS.y + "px";
  58758. this._debugCanvas.style.left = this.DEBUGCANVASPOS.x + "px";
  58759. this._debugCanvasContext = this._debugCanvas.getContext("2d");
  58760. document.body.appendChild(this._debugCanvas);
  58761. this._registerFunc = function () {
  58762. _this.drawDebugCanvas();
  58763. };
  58764. this._scene.registerBeforeRender(this._registerFunc);
  58765. }
  58766. if (this._registerFunc && this._debugCanvasContext) {
  58767. var workingArray = this.getByteFrequencyData();
  58768. this._debugCanvasContext.fillStyle = 'rgb(0, 0, 0)';
  58769. this._debugCanvasContext.fillRect(0, 0, this.DEBUGCANVASSIZE.width, this.DEBUGCANVASSIZE.height);
  58770. // Draw the frequency domain chart.
  58771. for (var i = 0; i < this.getFrequencyBinCount(); i++) {
  58772. var value = workingArray[i];
  58773. var percent = value / this.BARGRAPHAMPLITUDE;
  58774. var height = this.DEBUGCANVASSIZE.height * percent;
  58775. var offset = this.DEBUGCANVASSIZE.height - height - 1;
  58776. var barWidth = this.DEBUGCANVASSIZE.width / this.getFrequencyBinCount();
  58777. var hue = i / this.getFrequencyBinCount() * 360;
  58778. this._debugCanvasContext.fillStyle = 'hsl(' + hue + ', 100%, 50%)';
  58779. this._debugCanvasContext.fillRect(i * barWidth, offset, barWidth, height);
  58780. }
  58781. }
  58782. }
  58783. };
  58784. Analyser.prototype.stopDebugCanvas = function () {
  58785. if (this._debugCanvas) {
  58786. if (this._registerFunc) {
  58787. this._scene.unregisterBeforeRender(this._registerFunc);
  58788. this._registerFunc = null;
  58789. }
  58790. document.body.removeChild(this._debugCanvas);
  58791. this._debugCanvas = null;
  58792. this._debugCanvasContext = null;
  58793. }
  58794. };
  58795. Analyser.prototype.connectAudioNodes = function (inputAudioNode, outputAudioNode) {
  58796. if (this._audioEngine.canUseWebAudio) {
  58797. inputAudioNode.connect(this._webAudioAnalyser);
  58798. this._webAudioAnalyser.connect(outputAudioNode);
  58799. }
  58800. };
  58801. Analyser.prototype.dispose = function () {
  58802. if (this._audioEngine.canUseWebAudio) {
  58803. this._webAudioAnalyser.disconnect();
  58804. }
  58805. };
  58806. return Analyser;
  58807. }());
  58808. BABYLON.Analyser = Analyser;
  58809. })(BABYLON || (BABYLON = {}));
  58810. //# sourceMappingURL=babylon.analyser.js.map
  58811. "use strict";
  58812. var BABYLON;
  58813. (function (BABYLON) {
  58814. var CubeTexture = /** @class */ (function (_super) {
  58815. __extends(CubeTexture, _super);
  58816. function CubeTexture(rootUrl, scene, extensions, noMipmap, files, onLoad, onError, format, prefiltered, forcedExtension) {
  58817. if (extensions === void 0) { extensions = null; }
  58818. if (noMipmap === void 0) { noMipmap = false; }
  58819. if (files === void 0) { files = null; }
  58820. if (onLoad === void 0) { onLoad = null; }
  58821. if (onError === void 0) { onError = null; }
  58822. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  58823. if (prefiltered === void 0) { prefiltered = false; }
  58824. if (forcedExtension === void 0) { forcedExtension = null; }
  58825. var _this = _super.call(this, scene) || this;
  58826. _this.coordinatesMode = BABYLON.Texture.CUBIC_MODE;
  58827. /**
  58828. * Gets or sets the center of the bounding box associated with the cube texture
  58829. * It must define where the camera used to render the texture was set
  58830. */
  58831. _this.boundingBoxPosition = BABYLON.Vector3.Zero();
  58832. _this.name = rootUrl;
  58833. _this.url = rootUrl;
  58834. _this._noMipmap = noMipmap;
  58835. _this.hasAlpha = false;
  58836. _this._format = format;
  58837. _this._prefiltered = prefiltered;
  58838. _this.isCube = true;
  58839. _this._textureMatrix = BABYLON.Matrix.Identity();
  58840. if (prefiltered) {
  58841. _this.gammaSpace = false;
  58842. }
  58843. if (!rootUrl && !files) {
  58844. return _this;
  58845. }
  58846. _this._texture = _this._getFromCache(rootUrl, noMipmap);
  58847. var lastDot = rootUrl.lastIndexOf(".");
  58848. var extension = forcedExtension ? forcedExtension : (lastDot > -1 ? rootUrl.substring(lastDot).toLowerCase() : "");
  58849. var isDDS = (extension === ".dds");
  58850. if (!files) {
  58851. if (!isDDS && !extensions) {
  58852. extensions = ["_px.jpg", "_py.jpg", "_pz.jpg", "_nx.jpg", "_ny.jpg", "_nz.jpg"];
  58853. }
  58854. files = [];
  58855. if (extensions) {
  58856. for (var index = 0; index < extensions.length; index++) {
  58857. files.push(rootUrl + extensions[index]);
  58858. }
  58859. }
  58860. }
  58861. _this._files = files;
  58862. if (!_this._texture) {
  58863. if (!scene.useDelayedTextureLoading) {
  58864. if (prefiltered) {
  58865. _this._texture = scene.getEngine().createPrefilteredCubeTexture(rootUrl, scene, _this.lodGenerationScale, _this.lodGenerationOffset, onLoad, onError, format, forcedExtension);
  58866. }
  58867. else {
  58868. _this._texture = scene.getEngine().createCubeTexture(rootUrl, scene, files, noMipmap, onLoad, onError, _this._format, forcedExtension);
  58869. }
  58870. }
  58871. else {
  58872. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  58873. }
  58874. }
  58875. else if (onLoad) {
  58876. if (_this._texture.isReady) {
  58877. BABYLON.Tools.SetImmediate(function () { return onLoad(); });
  58878. }
  58879. else {
  58880. _this._texture.onLoadedObservable.add(onLoad);
  58881. }
  58882. }
  58883. return _this;
  58884. }
  58885. Object.defineProperty(CubeTexture.prototype, "boundingBoxSize", {
  58886. get: function () {
  58887. return this._boundingBoxSize;
  58888. },
  58889. /**
  58890. * Gets or sets the size of the bounding box associated with the cube texture
  58891. * When defined, the cubemap will switch to local mode
  58892. * @see https://community.arm.com/graphics/b/blog/posts/reflections-based-on-local-cubemaps-in-unity
  58893. * @example https://www.babylonjs-playground.com/#RNASML
  58894. */
  58895. set: function (value) {
  58896. if (this._boundingBoxSize && this._boundingBoxSize.equals(value)) {
  58897. return;
  58898. }
  58899. this._boundingBoxSize = value;
  58900. var scene = this.getScene();
  58901. if (scene) {
  58902. scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  58903. }
  58904. },
  58905. enumerable: true,
  58906. configurable: true
  58907. });
  58908. CubeTexture.CreateFromImages = function (files, scene, noMipmap) {
  58909. var rootUrlKey = "";
  58910. files.forEach(function (url) { return rootUrlKey += url; });
  58911. return new CubeTexture(rootUrlKey, scene, null, noMipmap, files);
  58912. };
  58913. CubeTexture.CreateFromPrefilteredData = function (url, scene, forcedExtension) {
  58914. if (forcedExtension === void 0) { forcedExtension = null; }
  58915. return new CubeTexture(url, scene, null, false, null, null, null, undefined, true, forcedExtension);
  58916. };
  58917. // Methods
  58918. CubeTexture.prototype.delayLoad = function () {
  58919. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  58920. return;
  58921. }
  58922. var scene = this.getScene();
  58923. if (!scene) {
  58924. return;
  58925. }
  58926. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  58927. this._texture = this._getFromCache(this.url, this._noMipmap);
  58928. if (!this._texture) {
  58929. if (this._prefiltered) {
  58930. this._texture = scene.getEngine().createPrefilteredCubeTexture(this.url, scene, this.lodGenerationScale, this.lodGenerationOffset, undefined, undefined, this._format);
  58931. }
  58932. else {
  58933. this._texture = scene.getEngine().createCubeTexture(this.url, scene, this._files, this._noMipmap, undefined, undefined, this._format);
  58934. }
  58935. }
  58936. };
  58937. CubeTexture.prototype.getReflectionTextureMatrix = function () {
  58938. return this._textureMatrix;
  58939. };
  58940. CubeTexture.prototype.setReflectionTextureMatrix = function (value) {
  58941. this._textureMatrix = value;
  58942. };
  58943. CubeTexture.Parse = function (parsedTexture, scene, rootUrl) {
  58944. var texture = BABYLON.SerializationHelper.Parse(function () {
  58945. return new CubeTexture(rootUrl + parsedTexture.name, scene, parsedTexture.extensions);
  58946. }, parsedTexture, scene);
  58947. // Local Cubemaps
  58948. if (parsedTexture.boundingBoxPosition) {
  58949. texture.boundingBoxPosition = BABYLON.Vector3.FromArray(parsedTexture.boundingBoxPosition);
  58950. }
  58951. if (parsedTexture.boundingBoxSize) {
  58952. texture.boundingBoxSize = BABYLON.Vector3.FromArray(parsedTexture.boundingBoxSize);
  58953. }
  58954. // Animations
  58955. if (parsedTexture.animations) {
  58956. for (var animationIndex = 0; animationIndex < parsedTexture.animations.length; animationIndex++) {
  58957. var parsedAnimation = parsedTexture.animations[animationIndex];
  58958. texture.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  58959. }
  58960. }
  58961. return texture;
  58962. };
  58963. CubeTexture.prototype.clone = function () {
  58964. var _this = this;
  58965. return BABYLON.SerializationHelper.Clone(function () {
  58966. var scene = _this.getScene();
  58967. if (!scene) {
  58968. return _this;
  58969. }
  58970. return new CubeTexture(_this.url, scene, _this._extensions, _this._noMipmap, _this._files);
  58971. }, this);
  58972. };
  58973. return CubeTexture;
  58974. }(BABYLON.BaseTexture));
  58975. BABYLON.CubeTexture = CubeTexture;
  58976. })(BABYLON || (BABYLON = {}));
  58977. //# sourceMappingURL=babylon.cubeTexture.js.map
  58978. "use strict";
  58979. var BABYLON;
  58980. (function (BABYLON) {
  58981. var RenderTargetTexture = /** @class */ (function (_super) {
  58982. __extends(RenderTargetTexture, _super);
  58983. /**
  58984. * Instantiate a render target texture. This is mainly to render of screen the scene to for instance apply post processse
  58985. * or used a shadow, depth texture...
  58986. * @param name The friendly name of the texture
  58987. * @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)
  58988. * @param scene The scene the RTT belongs to. The latest created scene will be used if not precised.
  58989. * @param generateMipMaps True if mip maps need to be generated after render.
  58990. * @param doNotChangeAspectRatio True to not change the aspect ratio of the scene in the RTT
  58991. * @param type The type of the buffer in the RTT (int, half float, float...)
  58992. * @param isCube True if a cube texture needs to be created
  58993. * @param samplingMode The sampling mode to be usedwith the render target (Linear, Nearest...)
  58994. * @param generateDepthBuffer True to generate a depth buffer
  58995. * @param generateStencilBuffer True to generate a stencil buffer
  58996. * @param isMulti True if multiple textures need to be created (Draw Buffers)
  58997. */
  58998. function RenderTargetTexture(name, size, scene, generateMipMaps, doNotChangeAspectRatio, type, isCube, samplingMode, generateDepthBuffer, generateStencilBuffer, isMulti) {
  58999. if (doNotChangeAspectRatio === void 0) { doNotChangeAspectRatio = true; }
  59000. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  59001. if (isCube === void 0) { isCube = false; }
  59002. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  59003. if (generateDepthBuffer === void 0) { generateDepthBuffer = true; }
  59004. if (generateStencilBuffer === void 0) { generateStencilBuffer = false; }
  59005. if (isMulti === void 0) { isMulti = false; }
  59006. var _this = _super.call(this, null, scene, !generateMipMaps) || this;
  59007. _this.isCube = isCube;
  59008. /**
  59009. * Use this list to define the list of mesh you want to render.
  59010. */
  59011. _this.renderList = new Array();
  59012. _this.renderParticles = true;
  59013. _this.renderSprites = false;
  59014. _this.coordinatesMode = BABYLON.Texture.PROJECTION_MODE;
  59015. _this.ignoreCameraViewport = false;
  59016. // Events
  59017. /**
  59018. * An event triggered when the texture is unbind.
  59019. */
  59020. _this.onBeforeBindObservable = new BABYLON.Observable();
  59021. /**
  59022. * An event triggered when the texture is unbind.
  59023. */
  59024. _this.onAfterUnbindObservable = new BABYLON.Observable();
  59025. /**
  59026. * An event triggered before rendering the texture
  59027. */
  59028. _this.onBeforeRenderObservable = new BABYLON.Observable();
  59029. /**
  59030. * An event triggered after rendering the texture
  59031. */
  59032. _this.onAfterRenderObservable = new BABYLON.Observable();
  59033. /**
  59034. * An event triggered after the texture clear
  59035. */
  59036. _this.onClearObservable = new BABYLON.Observable();
  59037. _this._currentRefreshId = -1;
  59038. _this._refreshRate = 1;
  59039. _this._samples = 1;
  59040. /**
  59041. * Gets or sets the center of the bounding box associated with the texture (when in cube mode)
  59042. * It must define where the camera used to render the texture is set
  59043. */
  59044. _this.boundingBoxPosition = BABYLON.Vector3.Zero();
  59045. scene = _this.getScene();
  59046. if (!scene) {
  59047. return _this;
  59048. }
  59049. _this._engine = scene.getEngine();
  59050. _this.name = name;
  59051. _this.isRenderTarget = true;
  59052. _this._initialSizeParameter = size;
  59053. _this._processSizeParameter(size);
  59054. _this._resizeObserver = _this.getScene().getEngine().onResizeObservable.add(function () {
  59055. });
  59056. _this._generateMipMaps = generateMipMaps ? true : false;
  59057. _this._doNotChangeAspectRatio = doNotChangeAspectRatio;
  59058. // Rendering groups
  59059. _this._renderingManager = new BABYLON.RenderingManager(scene);
  59060. if (isMulti) {
  59061. return _this;
  59062. }
  59063. _this._renderTargetOptions = {
  59064. generateMipMaps: generateMipMaps,
  59065. type: type,
  59066. samplingMode: samplingMode,
  59067. generateDepthBuffer: generateDepthBuffer,
  59068. generateStencilBuffer: generateStencilBuffer
  59069. };
  59070. if (samplingMode === BABYLON.Texture.NEAREST_SAMPLINGMODE) {
  59071. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  59072. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  59073. }
  59074. if (isCube) {
  59075. _this._texture = scene.getEngine().createRenderTargetCubeTexture(_this.getRenderSize(), _this._renderTargetOptions);
  59076. _this.coordinatesMode = BABYLON.Texture.INVCUBIC_MODE;
  59077. _this._textureMatrix = BABYLON.Matrix.Identity();
  59078. }
  59079. else {
  59080. _this._texture = scene.getEngine().createRenderTargetTexture(_this._size, _this._renderTargetOptions);
  59081. }
  59082. return _this;
  59083. }
  59084. Object.defineProperty(RenderTargetTexture, "REFRESHRATE_RENDER_ONCE", {
  59085. get: function () {
  59086. return RenderTargetTexture._REFRESHRATE_RENDER_ONCE;
  59087. },
  59088. enumerable: true,
  59089. configurable: true
  59090. });
  59091. Object.defineProperty(RenderTargetTexture, "REFRESHRATE_RENDER_ONEVERYFRAME", {
  59092. get: function () {
  59093. return RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYFRAME;
  59094. },
  59095. enumerable: true,
  59096. configurable: true
  59097. });
  59098. Object.defineProperty(RenderTargetTexture, "REFRESHRATE_RENDER_ONEVERYTWOFRAMES", {
  59099. get: function () {
  59100. return RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYTWOFRAMES;
  59101. },
  59102. enumerable: true,
  59103. configurable: true
  59104. });
  59105. Object.defineProperty(RenderTargetTexture.prototype, "onAfterUnbind", {
  59106. set: function (callback) {
  59107. if (this._onAfterUnbindObserver) {
  59108. this.onAfterUnbindObservable.remove(this._onAfterUnbindObserver);
  59109. }
  59110. this._onAfterUnbindObserver = this.onAfterUnbindObservable.add(callback);
  59111. },
  59112. enumerable: true,
  59113. configurable: true
  59114. });
  59115. Object.defineProperty(RenderTargetTexture.prototype, "onBeforeRender", {
  59116. set: function (callback) {
  59117. if (this._onBeforeRenderObserver) {
  59118. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  59119. }
  59120. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  59121. },
  59122. enumerable: true,
  59123. configurable: true
  59124. });
  59125. Object.defineProperty(RenderTargetTexture.prototype, "onAfterRender", {
  59126. set: function (callback) {
  59127. if (this._onAfterRenderObserver) {
  59128. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  59129. }
  59130. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  59131. },
  59132. enumerable: true,
  59133. configurable: true
  59134. });
  59135. Object.defineProperty(RenderTargetTexture.prototype, "onClear", {
  59136. set: function (callback) {
  59137. if (this._onClearObserver) {
  59138. this.onClearObservable.remove(this._onClearObserver);
  59139. }
  59140. this._onClearObserver = this.onClearObservable.add(callback);
  59141. },
  59142. enumerable: true,
  59143. configurable: true
  59144. });
  59145. Object.defineProperty(RenderTargetTexture.prototype, "renderTargetOptions", {
  59146. get: function () {
  59147. return this._renderTargetOptions;
  59148. },
  59149. enumerable: true,
  59150. configurable: true
  59151. });
  59152. RenderTargetTexture.prototype._onRatioRescale = function () {
  59153. if (this._sizeRatio) {
  59154. this.resize(this._initialSizeParameter);
  59155. }
  59156. };
  59157. Object.defineProperty(RenderTargetTexture.prototype, "boundingBoxSize", {
  59158. get: function () {
  59159. return this._boundingBoxSize;
  59160. },
  59161. /**
  59162. * Gets or sets the size of the bounding box associated with the texture (when in cube mode)
  59163. * When defined, the cubemap will switch to local mode
  59164. * @see https://community.arm.com/graphics/b/blog/posts/reflections-based-on-local-cubemaps-in-unity
  59165. * @example https://www.babylonjs-playground.com/#RNASML
  59166. */
  59167. set: function (value) {
  59168. if (this._boundingBoxSize && this._boundingBoxSize.equals(value)) {
  59169. return;
  59170. }
  59171. this._boundingBoxSize = value;
  59172. var scene = this.getScene();
  59173. if (scene) {
  59174. scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  59175. }
  59176. },
  59177. enumerable: true,
  59178. configurable: true
  59179. });
  59180. /**
  59181. * Creates a depth stencil texture.
  59182. * This is only available in WebGL 2 or with the depth texture extension available.
  59183. * @param comparisonFunction Specifies the comparison function to set on the texture. If 0 or undefined, the texture is not in comparison mode
  59184. * @param bilinearFiltering Specifies whether or not bilinear filtering is enable on the texture
  59185. * @param generateStencil Specifies whether or not a stencil should be allocated in the texture
  59186. */
  59187. RenderTargetTexture.prototype.createDepthStencilTexture = function (comparisonFunction, bilinearFiltering, generateStencil) {
  59188. if (comparisonFunction === void 0) { comparisonFunction = 0; }
  59189. if (bilinearFiltering === void 0) { bilinearFiltering = true; }
  59190. if (generateStencil === void 0) { generateStencil = false; }
  59191. if (!this.getScene()) {
  59192. return;
  59193. }
  59194. var engine = this.getScene().getEngine();
  59195. this.depthStencilTexture = engine.createDepthStencilTexture(this._size, {
  59196. bilinearFiltering: bilinearFiltering,
  59197. comparisonFunction: comparisonFunction,
  59198. generateStencil: generateStencil,
  59199. isCube: this.isCube
  59200. });
  59201. engine.setFrameBufferDepthStencilTexture(this);
  59202. };
  59203. RenderTargetTexture.prototype._processSizeParameter = function (size) {
  59204. if (size.ratio) {
  59205. this._sizeRatio = size.ratio;
  59206. this._size = {
  59207. width: this._bestReflectionRenderTargetDimension(this._engine.getRenderWidth(), this._sizeRatio),
  59208. height: this._bestReflectionRenderTargetDimension(this._engine.getRenderHeight(), this._sizeRatio)
  59209. };
  59210. }
  59211. else {
  59212. this._size = size;
  59213. }
  59214. };
  59215. Object.defineProperty(RenderTargetTexture.prototype, "samples", {
  59216. get: function () {
  59217. return this._samples;
  59218. },
  59219. set: function (value) {
  59220. if (this._samples === value) {
  59221. return;
  59222. }
  59223. var scene = this.getScene();
  59224. if (!scene) {
  59225. return;
  59226. }
  59227. this._samples = scene.getEngine().updateRenderTargetTextureSampleCount(this._texture, value);
  59228. },
  59229. enumerable: true,
  59230. configurable: true
  59231. });
  59232. RenderTargetTexture.prototype.resetRefreshCounter = function () {
  59233. this._currentRefreshId = -1;
  59234. };
  59235. Object.defineProperty(RenderTargetTexture.prototype, "refreshRate", {
  59236. get: function () {
  59237. return this._refreshRate;
  59238. },
  59239. // Use 0 to render just once, 1 to render on every frame, 2 to render every two frames and so on...
  59240. set: function (value) {
  59241. this._refreshRate = value;
  59242. this.resetRefreshCounter();
  59243. },
  59244. enumerable: true,
  59245. configurable: true
  59246. });
  59247. RenderTargetTexture.prototype.addPostProcess = function (postProcess) {
  59248. if (!this._postProcessManager) {
  59249. var scene = this.getScene();
  59250. if (!scene) {
  59251. return;
  59252. }
  59253. this._postProcessManager = new BABYLON.PostProcessManager(scene);
  59254. this._postProcesses = new Array();
  59255. }
  59256. this._postProcesses.push(postProcess);
  59257. this._postProcesses[0].autoClear = false;
  59258. };
  59259. RenderTargetTexture.prototype.clearPostProcesses = function (dispose) {
  59260. if (!this._postProcesses) {
  59261. return;
  59262. }
  59263. if (dispose) {
  59264. for (var _i = 0, _a = this._postProcesses; _i < _a.length; _i++) {
  59265. var postProcess = _a[_i];
  59266. postProcess.dispose();
  59267. }
  59268. }
  59269. this._postProcesses = [];
  59270. };
  59271. RenderTargetTexture.prototype.removePostProcess = function (postProcess) {
  59272. if (!this._postProcesses) {
  59273. return;
  59274. }
  59275. var index = this._postProcesses.indexOf(postProcess);
  59276. if (index === -1) {
  59277. return;
  59278. }
  59279. this._postProcesses.splice(index, 1);
  59280. if (this._postProcesses.length > 0) {
  59281. this._postProcesses[0].autoClear = false;
  59282. }
  59283. };
  59284. RenderTargetTexture.prototype._shouldRender = function () {
  59285. if (this._currentRefreshId === -1) {
  59286. this._currentRefreshId = 1;
  59287. return true;
  59288. }
  59289. if (this.refreshRate === this._currentRefreshId) {
  59290. this._currentRefreshId = 1;
  59291. return true;
  59292. }
  59293. this._currentRefreshId++;
  59294. return false;
  59295. };
  59296. RenderTargetTexture.prototype.getRenderSize = function () {
  59297. if (this._size.width) {
  59298. return this._size.width;
  59299. }
  59300. return this._size;
  59301. };
  59302. RenderTargetTexture.prototype.getRenderWidth = function () {
  59303. if (this._size.width) {
  59304. return this._size.width;
  59305. }
  59306. return this._size;
  59307. };
  59308. RenderTargetTexture.prototype.getRenderHeight = function () {
  59309. if (this._size.width) {
  59310. return this._size.height;
  59311. }
  59312. return this._size;
  59313. };
  59314. Object.defineProperty(RenderTargetTexture.prototype, "canRescale", {
  59315. get: function () {
  59316. return true;
  59317. },
  59318. enumerable: true,
  59319. configurable: true
  59320. });
  59321. RenderTargetTexture.prototype.scale = function (ratio) {
  59322. var newSize = this.getRenderSize() * ratio;
  59323. this.resize(newSize);
  59324. };
  59325. RenderTargetTexture.prototype.getReflectionTextureMatrix = function () {
  59326. if (this.isCube) {
  59327. return this._textureMatrix;
  59328. }
  59329. return _super.prototype.getReflectionTextureMatrix.call(this);
  59330. };
  59331. RenderTargetTexture.prototype.resize = function (size) {
  59332. this.releaseInternalTexture();
  59333. var scene = this.getScene();
  59334. if (!scene) {
  59335. return;
  59336. }
  59337. this._processSizeParameter(size);
  59338. if (this.isCube) {
  59339. this._texture = scene.getEngine().createRenderTargetCubeTexture(this.getRenderSize(), this._renderTargetOptions);
  59340. }
  59341. else {
  59342. this._texture = scene.getEngine().createRenderTargetTexture(this._size, this._renderTargetOptions);
  59343. }
  59344. };
  59345. RenderTargetTexture.prototype.render = function (useCameraPostProcess, dumpForDebug) {
  59346. if (useCameraPostProcess === void 0) { useCameraPostProcess = false; }
  59347. if (dumpForDebug === void 0) { dumpForDebug = false; }
  59348. var scene = this.getScene();
  59349. if (!scene) {
  59350. return;
  59351. }
  59352. var engine = scene.getEngine();
  59353. if (this.useCameraPostProcesses !== undefined) {
  59354. useCameraPostProcess = this.useCameraPostProcesses;
  59355. }
  59356. if (this._waitingRenderList) {
  59357. this.renderList = [];
  59358. for (var index = 0; index < this._waitingRenderList.length; index++) {
  59359. var id = this._waitingRenderList[index];
  59360. var mesh_1 = scene.getMeshByID(id);
  59361. if (mesh_1) {
  59362. this.renderList.push(mesh_1);
  59363. }
  59364. }
  59365. delete this._waitingRenderList;
  59366. }
  59367. // Is predicate defined?
  59368. if (this.renderListPredicate) {
  59369. if (this.renderList) {
  59370. this.renderList.splice(0); // Clear previous renderList
  59371. }
  59372. else {
  59373. this.renderList = [];
  59374. }
  59375. var scene = this.getScene();
  59376. if (!scene) {
  59377. return;
  59378. }
  59379. var sceneMeshes = scene.meshes;
  59380. for (var index = 0; index < sceneMeshes.length; index++) {
  59381. var mesh = sceneMeshes[index];
  59382. if (this.renderListPredicate(mesh)) {
  59383. this.renderList.push(mesh);
  59384. }
  59385. }
  59386. }
  59387. this.onBeforeBindObservable.notifyObservers(this);
  59388. // Set custom projection.
  59389. // Needs to be before binding to prevent changing the aspect ratio.
  59390. var camera;
  59391. if (this.activeCamera) {
  59392. camera = this.activeCamera;
  59393. engine.setViewport(this.activeCamera.viewport, this.getRenderWidth(), this.getRenderHeight());
  59394. if (this.activeCamera !== scene.activeCamera) {
  59395. scene.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix(true));
  59396. }
  59397. }
  59398. else {
  59399. camera = scene.activeCamera;
  59400. if (camera) {
  59401. engine.setViewport(camera.viewport, this.getRenderWidth(), this.getRenderHeight());
  59402. }
  59403. }
  59404. // Prepare renderingManager
  59405. this._renderingManager.reset();
  59406. var currentRenderList = this.renderList ? this.renderList : scene.getActiveMeshes().data;
  59407. var currentRenderListLength = this.renderList ? this.renderList.length : scene.getActiveMeshes().length;
  59408. var sceneRenderId = scene.getRenderId();
  59409. for (var meshIndex = 0; meshIndex < currentRenderListLength; meshIndex++) {
  59410. var mesh = currentRenderList[meshIndex];
  59411. if (mesh) {
  59412. if (!mesh.isReady(this.refreshRate === 0)) {
  59413. this.resetRefreshCounter();
  59414. continue;
  59415. }
  59416. mesh._preActivateForIntermediateRendering(sceneRenderId);
  59417. var isMasked = void 0;
  59418. if (!this.renderList && camera) {
  59419. isMasked = ((mesh.layerMask & camera.layerMask) === 0);
  59420. }
  59421. else {
  59422. isMasked = false;
  59423. }
  59424. if (mesh.isEnabled() && mesh.isVisible && mesh.subMeshes && !isMasked) {
  59425. mesh._activate(sceneRenderId);
  59426. for (var subIndex = 0; subIndex < mesh.subMeshes.length; subIndex++) {
  59427. var subMesh = mesh.subMeshes[subIndex];
  59428. scene._activeIndices.addCount(subMesh.indexCount, false);
  59429. this._renderingManager.dispatch(subMesh, mesh);
  59430. }
  59431. }
  59432. }
  59433. }
  59434. for (var particleIndex = 0; particleIndex < scene.particleSystems.length; particleIndex++) {
  59435. var particleSystem = scene.particleSystems[particleIndex];
  59436. var emitter = particleSystem.emitter;
  59437. if (!particleSystem.isStarted() || !emitter || !emitter.position || !emitter.isEnabled()) {
  59438. continue;
  59439. }
  59440. if (currentRenderList.indexOf(emitter) >= 0) {
  59441. this._renderingManager.dispatchParticles(particleSystem);
  59442. }
  59443. }
  59444. if (this.isCube) {
  59445. for (var face = 0; face < 6; face++) {
  59446. this.renderToTarget(face, currentRenderList, currentRenderListLength, useCameraPostProcess, dumpForDebug);
  59447. scene.incrementRenderId();
  59448. scene.resetCachedMaterial();
  59449. }
  59450. }
  59451. else {
  59452. this.renderToTarget(0, currentRenderList, currentRenderListLength, useCameraPostProcess, dumpForDebug);
  59453. }
  59454. this.onAfterUnbindObservable.notifyObservers(this);
  59455. if (scene.activeCamera) {
  59456. if (this.activeCamera && this.activeCamera !== scene.activeCamera) {
  59457. scene.setTransformMatrix(scene.activeCamera.getViewMatrix(), scene.activeCamera.getProjectionMatrix(true));
  59458. }
  59459. engine.setViewport(scene.activeCamera.viewport);
  59460. }
  59461. scene.resetCachedMaterial();
  59462. };
  59463. RenderTargetTexture.prototype._bestReflectionRenderTargetDimension = function (renderDimension, scale) {
  59464. var minimum = 128;
  59465. var x = renderDimension * scale;
  59466. var curved = BABYLON.Tools.NearestPOT(x + (minimum * minimum / (minimum + x)));
  59467. // Ensure we don't exceed the render dimension (while staying POT)
  59468. return Math.min(BABYLON.Tools.FloorPOT(renderDimension), curved);
  59469. };
  59470. RenderTargetTexture.prototype.unbindFrameBuffer = function (engine, faceIndex) {
  59471. var _this = this;
  59472. if (!this._texture) {
  59473. return;
  59474. }
  59475. engine.unBindFramebuffer(this._texture, this.isCube, function () {
  59476. _this.onAfterRenderObservable.notifyObservers(faceIndex);
  59477. });
  59478. };
  59479. RenderTargetTexture.prototype.renderToTarget = function (faceIndex, currentRenderList, currentRenderListLength, useCameraPostProcess, dumpForDebug) {
  59480. var scene = this.getScene();
  59481. if (!scene) {
  59482. return;
  59483. }
  59484. var engine = scene.getEngine();
  59485. if (!this._texture) {
  59486. return;
  59487. }
  59488. // Bind
  59489. if (this._postProcessManager) {
  59490. this._postProcessManager._prepareFrame(this._texture, this._postProcesses);
  59491. }
  59492. else if (!useCameraPostProcess || !scene.postProcessManager._prepareFrame(this._texture)) {
  59493. if (this._texture) {
  59494. engine.bindFramebuffer(this._texture, this.isCube ? faceIndex : undefined, undefined, undefined, this.ignoreCameraViewport, this.depthStencilTexture ? this.depthStencilTexture : undefined);
  59495. }
  59496. }
  59497. this.onBeforeRenderObservable.notifyObservers(faceIndex);
  59498. // Clear
  59499. if (this.onClearObservable.hasObservers()) {
  59500. this.onClearObservable.notifyObservers(engine);
  59501. }
  59502. else {
  59503. engine.clear(this.clearColor || scene.clearColor, true, true, true);
  59504. }
  59505. if (!this._doNotChangeAspectRatio) {
  59506. scene.updateTransformMatrix(true);
  59507. }
  59508. // Render
  59509. this._renderingManager.render(this.customRenderFunction, currentRenderList, this.renderParticles, this.renderSprites);
  59510. if (this._postProcessManager) {
  59511. this._postProcessManager._finalizeFrame(false, this._texture, faceIndex, this._postProcesses, this.ignoreCameraViewport);
  59512. }
  59513. else if (useCameraPostProcess) {
  59514. scene.postProcessManager._finalizeFrame(false, this._texture, faceIndex);
  59515. }
  59516. if (!this._doNotChangeAspectRatio) {
  59517. scene.updateTransformMatrix(true);
  59518. }
  59519. // Dump ?
  59520. if (dumpForDebug) {
  59521. BABYLON.Tools.DumpFramebuffer(this.getRenderWidth(), this.getRenderHeight(), engine);
  59522. }
  59523. // Unbind
  59524. if (!this.isCube || faceIndex === 5) {
  59525. if (this.isCube) {
  59526. if (faceIndex === 5) {
  59527. engine.generateMipMapsForCubemap(this._texture);
  59528. }
  59529. }
  59530. this.unbindFrameBuffer(engine, faceIndex);
  59531. }
  59532. else {
  59533. this.onAfterRenderObservable.notifyObservers(faceIndex);
  59534. }
  59535. };
  59536. /**
  59537. * Overrides the default sort function applied in the renderging group to prepare the meshes.
  59538. * This allowed control for front to back rendering or reversly depending of the special needs.
  59539. *
  59540. * @param renderingGroupId The rendering group id corresponding to its index
  59541. * @param opaqueSortCompareFn The opaque queue comparison function use to sort.
  59542. * @param alphaTestSortCompareFn The alpha test queue comparison function use to sort.
  59543. * @param transparentSortCompareFn The transparent queue comparison function use to sort.
  59544. */
  59545. RenderTargetTexture.prototype.setRenderingOrder = function (renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  59546. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  59547. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  59548. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  59549. this._renderingManager.setRenderingOrder(renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn);
  59550. };
  59551. /**
  59552. * Specifies whether or not the stencil and depth buffer are cleared between two rendering groups.
  59553. *
  59554. * @param renderingGroupId The rendering group id corresponding to its index
  59555. * @param autoClearDepthStencil Automatically clears depth and stencil between groups if true.
  59556. */
  59557. RenderTargetTexture.prototype.setRenderingAutoClearDepthStencil = function (renderingGroupId, autoClearDepthStencil) {
  59558. this._renderingManager.setRenderingAutoClearDepthStencil(renderingGroupId, autoClearDepthStencil);
  59559. };
  59560. RenderTargetTexture.prototype.clone = function () {
  59561. var textureSize = this.getSize();
  59562. var newTexture = new RenderTargetTexture(this.name, textureSize.width, this.getScene(), this._renderTargetOptions.generateMipMaps, this._doNotChangeAspectRatio, this._renderTargetOptions.type, this.isCube, this._renderTargetOptions.samplingMode, this._renderTargetOptions.generateDepthBuffer, this._renderTargetOptions.generateStencilBuffer);
  59563. // Base texture
  59564. newTexture.hasAlpha = this.hasAlpha;
  59565. newTexture.level = this.level;
  59566. // RenderTarget Texture
  59567. newTexture.coordinatesMode = this.coordinatesMode;
  59568. if (this.renderList) {
  59569. newTexture.renderList = this.renderList.slice(0);
  59570. }
  59571. return newTexture;
  59572. };
  59573. RenderTargetTexture.prototype.serialize = function () {
  59574. if (!this.name) {
  59575. return null;
  59576. }
  59577. var serializationObject = _super.prototype.serialize.call(this);
  59578. serializationObject.renderTargetSize = this.getRenderSize();
  59579. serializationObject.renderList = [];
  59580. if (this.renderList) {
  59581. for (var index = 0; index < this.renderList.length; index++) {
  59582. serializationObject.renderList.push(this.renderList[index].id);
  59583. }
  59584. }
  59585. return serializationObject;
  59586. };
  59587. // This will remove the attached framebuffer objects. The texture will not be able to be used as render target anymore
  59588. RenderTargetTexture.prototype.disposeFramebufferObjects = function () {
  59589. var objBuffer = this.getInternalTexture();
  59590. var scene = this.getScene();
  59591. if (objBuffer && scene) {
  59592. scene.getEngine()._releaseFramebufferObjects(objBuffer);
  59593. }
  59594. };
  59595. RenderTargetTexture.prototype.dispose = function () {
  59596. if (this._postProcessManager) {
  59597. this._postProcessManager.dispose();
  59598. this._postProcessManager = null;
  59599. }
  59600. this.clearPostProcesses(true);
  59601. if (this._resizeObserver) {
  59602. this.getScene().getEngine().onResizeObservable.remove(this._resizeObserver);
  59603. this._resizeObserver = null;
  59604. }
  59605. this.renderList = null;
  59606. // Remove from custom render targets
  59607. var scene = this.getScene();
  59608. if (!scene) {
  59609. return;
  59610. }
  59611. var index = scene.customRenderTargets.indexOf(this);
  59612. if (index >= 0) {
  59613. scene.customRenderTargets.splice(index, 1);
  59614. }
  59615. for (var _i = 0, _a = scene.cameras; _i < _a.length; _i++) {
  59616. var camera = _a[_i];
  59617. index = camera.customRenderTargets.indexOf(this);
  59618. if (index >= 0) {
  59619. camera.customRenderTargets.splice(index, 1);
  59620. }
  59621. }
  59622. _super.prototype.dispose.call(this);
  59623. };
  59624. RenderTargetTexture.prototype._rebuild = function () {
  59625. if (this.refreshRate === RenderTargetTexture.REFRESHRATE_RENDER_ONCE) {
  59626. this.refreshRate = RenderTargetTexture.REFRESHRATE_RENDER_ONCE;
  59627. }
  59628. if (this._postProcessManager) {
  59629. this._postProcessManager._rebuild();
  59630. }
  59631. };
  59632. /**
  59633. * Clear the info related to rendering groups preventing retention point in material dispose.
  59634. */
  59635. RenderTargetTexture.prototype.freeRenderingGroups = function () {
  59636. if (this._renderingManager) {
  59637. this._renderingManager.freeRenderingGroups();
  59638. }
  59639. };
  59640. RenderTargetTexture._REFRESHRATE_RENDER_ONCE = 0;
  59641. RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYFRAME = 1;
  59642. RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYTWOFRAMES = 2;
  59643. return RenderTargetTexture;
  59644. }(BABYLON.Texture));
  59645. BABYLON.RenderTargetTexture = RenderTargetTexture;
  59646. })(BABYLON || (BABYLON = {}));
  59647. //# sourceMappingURL=babylon.renderTargetTexture.js.map
  59648. "use strict";
  59649. var BABYLON;
  59650. (function (BABYLON) {
  59651. ;
  59652. var MultiRenderTarget = /** @class */ (function (_super) {
  59653. __extends(MultiRenderTarget, _super);
  59654. function MultiRenderTarget(name, size, count, scene, options) {
  59655. var _this = this;
  59656. var generateMipMaps = options && options.generateMipMaps ? options.generateMipMaps : false;
  59657. var generateDepthTexture = options && options.generateDepthTexture ? options.generateDepthTexture : false;
  59658. var doNotChangeAspectRatio = !options || options.doNotChangeAspectRatio === undefined ? true : options.doNotChangeAspectRatio;
  59659. _this = _super.call(this, name, size, scene, generateMipMaps, doNotChangeAspectRatio) || this;
  59660. _this._engine = scene.getEngine();
  59661. if (!_this.isSupported) {
  59662. _this.dispose();
  59663. return;
  59664. }
  59665. var types = [];
  59666. var samplingModes = [];
  59667. for (var i = 0; i < count; i++) {
  59668. if (options && options.types && options.types[i] !== undefined) {
  59669. types.push(options.types[i]);
  59670. }
  59671. else {
  59672. types.push(options && options.defaultType ? options.defaultType : BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  59673. }
  59674. if (options && options.samplingModes && options.samplingModes[i] !== undefined) {
  59675. samplingModes.push(options.samplingModes[i]);
  59676. }
  59677. else {
  59678. samplingModes.push(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  59679. }
  59680. }
  59681. var generateDepthBuffer = !options || options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  59682. var generateStencilBuffer = !options || options.generateStencilBuffer === undefined ? false : options.generateStencilBuffer;
  59683. _this._size = size;
  59684. _this._multiRenderTargetOptions = {
  59685. samplingModes: samplingModes,
  59686. generateMipMaps: generateMipMaps,
  59687. generateDepthBuffer: generateDepthBuffer,
  59688. generateStencilBuffer: generateStencilBuffer,
  59689. generateDepthTexture: generateDepthTexture,
  59690. types: types,
  59691. textureCount: count
  59692. };
  59693. _this._createInternalTextures();
  59694. _this._createTextures();
  59695. return _this;
  59696. }
  59697. Object.defineProperty(MultiRenderTarget.prototype, "isSupported", {
  59698. get: function () {
  59699. return this._engine.webGLVersion > 1 || this._engine.getCaps().drawBuffersExtension;
  59700. },
  59701. enumerable: true,
  59702. configurable: true
  59703. });
  59704. Object.defineProperty(MultiRenderTarget.prototype, "textures", {
  59705. get: function () {
  59706. return this._textures;
  59707. },
  59708. enumerable: true,
  59709. configurable: true
  59710. });
  59711. Object.defineProperty(MultiRenderTarget.prototype, "depthTexture", {
  59712. get: function () {
  59713. return this._textures[this._textures.length - 1];
  59714. },
  59715. enumerable: true,
  59716. configurable: true
  59717. });
  59718. Object.defineProperty(MultiRenderTarget.prototype, "wrapU", {
  59719. set: function (wrap) {
  59720. if (this._textures) {
  59721. for (var i = 0; i < this._textures.length; i++) {
  59722. this._textures[i].wrapU = wrap;
  59723. }
  59724. }
  59725. },
  59726. enumerable: true,
  59727. configurable: true
  59728. });
  59729. Object.defineProperty(MultiRenderTarget.prototype, "wrapV", {
  59730. set: function (wrap) {
  59731. if (this._textures) {
  59732. for (var i = 0; i < this._textures.length; i++) {
  59733. this._textures[i].wrapV = wrap;
  59734. }
  59735. }
  59736. },
  59737. enumerable: true,
  59738. configurable: true
  59739. });
  59740. MultiRenderTarget.prototype._rebuild = function () {
  59741. this.releaseInternalTextures();
  59742. this._createInternalTextures();
  59743. for (var i = 0; i < this._internalTextures.length; i++) {
  59744. var texture = this._textures[i];
  59745. texture._texture = this._internalTextures[i];
  59746. }
  59747. // Keeps references to frame buffer and stencil/depth buffer
  59748. this._texture = this._internalTextures[0];
  59749. };
  59750. MultiRenderTarget.prototype._createInternalTextures = function () {
  59751. this._internalTextures = this._engine.createMultipleRenderTarget(this._size, this._multiRenderTargetOptions);
  59752. };
  59753. MultiRenderTarget.prototype._createTextures = function () {
  59754. this._textures = [];
  59755. for (var i = 0; i < this._internalTextures.length; i++) {
  59756. var texture = new BABYLON.Texture(null, this.getScene());
  59757. texture._texture = this._internalTextures[i];
  59758. this._textures.push(texture);
  59759. }
  59760. // Keeps references to frame buffer and stencil/depth buffer
  59761. this._texture = this._internalTextures[0];
  59762. };
  59763. Object.defineProperty(MultiRenderTarget.prototype, "samples", {
  59764. get: function () {
  59765. return this._samples;
  59766. },
  59767. set: function (value) {
  59768. if (this._samples === value) {
  59769. return;
  59770. }
  59771. this._samples = this._engine.updateMultipleRenderTargetTextureSampleCount(this._internalTextures, value);
  59772. },
  59773. enumerable: true,
  59774. configurable: true
  59775. });
  59776. MultiRenderTarget.prototype.resize = function (size) {
  59777. this.releaseInternalTextures();
  59778. this._internalTextures = this._engine.createMultipleRenderTarget(size, this._multiRenderTargetOptions);
  59779. this._createInternalTextures();
  59780. };
  59781. MultiRenderTarget.prototype.unbindFrameBuffer = function (engine, faceIndex) {
  59782. var _this = this;
  59783. engine.unBindMultiColorAttachmentFramebuffer(this._internalTextures, this.isCube, function () {
  59784. _this.onAfterRenderObservable.notifyObservers(faceIndex);
  59785. });
  59786. };
  59787. MultiRenderTarget.prototype.dispose = function () {
  59788. this.releaseInternalTextures();
  59789. _super.prototype.dispose.call(this);
  59790. };
  59791. MultiRenderTarget.prototype.releaseInternalTextures = function () {
  59792. if (!this._internalTextures) {
  59793. return;
  59794. }
  59795. for (var i = this._internalTextures.length - 1; i >= 0; i--) {
  59796. if (this._internalTextures[i] !== undefined) {
  59797. this._internalTextures[i].dispose();
  59798. this._internalTextures.splice(i, 1);
  59799. }
  59800. }
  59801. };
  59802. return MultiRenderTarget;
  59803. }(BABYLON.RenderTargetTexture));
  59804. BABYLON.MultiRenderTarget = MultiRenderTarget;
  59805. })(BABYLON || (BABYLON = {}));
  59806. //# sourceMappingURL=babylon.multiRenderTarget.js.map
  59807. "use strict";
  59808. var BABYLON;
  59809. (function (BABYLON) {
  59810. var MirrorTexture = /** @class */ (function (_super) {
  59811. __extends(MirrorTexture, _super);
  59812. function MirrorTexture(name, size, scene, generateMipMaps, type, samplingMode, generateDepthBuffer) {
  59813. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  59814. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  59815. if (generateDepthBuffer === void 0) { generateDepthBuffer = true; }
  59816. var _this = _super.call(this, name, size, scene, generateMipMaps, true, type, false, samplingMode, generateDepthBuffer) || this;
  59817. _this.mirrorPlane = new BABYLON.Plane(0, 1, 0, 1);
  59818. _this._transformMatrix = BABYLON.Matrix.Zero();
  59819. _this._mirrorMatrix = BABYLON.Matrix.Zero();
  59820. _this._adaptiveBlurKernel = 0;
  59821. _this._blurKernelX = 0;
  59822. _this._blurKernelY = 0;
  59823. _this._blurRatio = 1.0;
  59824. _this.ignoreCameraViewport = true;
  59825. _this.onBeforeRenderObservable.add(function () {
  59826. BABYLON.Matrix.ReflectionToRef(_this.mirrorPlane, _this._mirrorMatrix);
  59827. _this._savedViewMatrix = scene.getViewMatrix();
  59828. _this._mirrorMatrix.multiplyToRef(_this._savedViewMatrix, _this._transformMatrix);
  59829. scene.setTransformMatrix(_this._transformMatrix, scene.getProjectionMatrix());
  59830. scene.clipPlane = _this.mirrorPlane;
  59831. scene.getEngine().cullBackFaces = false;
  59832. scene._mirroredCameraPosition = BABYLON.Vector3.TransformCoordinates(scene.activeCamera.globalPosition, _this._mirrorMatrix);
  59833. });
  59834. _this.onAfterRenderObservable.add(function () {
  59835. scene.setTransformMatrix(_this._savedViewMatrix, scene.getProjectionMatrix());
  59836. scene.getEngine().cullBackFaces = true;
  59837. scene._mirroredCameraPosition = null;
  59838. delete scene.clipPlane;
  59839. });
  59840. return _this;
  59841. }
  59842. Object.defineProperty(MirrorTexture.prototype, "blurRatio", {
  59843. get: function () {
  59844. return this._blurRatio;
  59845. },
  59846. set: function (value) {
  59847. if (this._blurRatio === value) {
  59848. return;
  59849. }
  59850. this._blurRatio = value;
  59851. this._preparePostProcesses();
  59852. },
  59853. enumerable: true,
  59854. configurable: true
  59855. });
  59856. Object.defineProperty(MirrorTexture.prototype, "adaptiveBlurKernel", {
  59857. set: function (value) {
  59858. this._adaptiveBlurKernel = value;
  59859. this._autoComputeBlurKernel();
  59860. },
  59861. enumerable: true,
  59862. configurable: true
  59863. });
  59864. Object.defineProperty(MirrorTexture.prototype, "blurKernel", {
  59865. set: function (value) {
  59866. this.blurKernelX = value;
  59867. this.blurKernelY = value;
  59868. },
  59869. enumerable: true,
  59870. configurable: true
  59871. });
  59872. Object.defineProperty(MirrorTexture.prototype, "blurKernelX", {
  59873. get: function () {
  59874. return this._blurKernelX;
  59875. },
  59876. set: function (value) {
  59877. if (this._blurKernelX === value) {
  59878. return;
  59879. }
  59880. this._blurKernelX = value;
  59881. this._preparePostProcesses();
  59882. },
  59883. enumerable: true,
  59884. configurable: true
  59885. });
  59886. Object.defineProperty(MirrorTexture.prototype, "blurKernelY", {
  59887. get: function () {
  59888. return this._blurKernelY;
  59889. },
  59890. set: function (value) {
  59891. if (this._blurKernelY === value) {
  59892. return;
  59893. }
  59894. this._blurKernelY = value;
  59895. this._preparePostProcesses();
  59896. },
  59897. enumerable: true,
  59898. configurable: true
  59899. });
  59900. MirrorTexture.prototype._autoComputeBlurKernel = function () {
  59901. var engine = this.getScene().getEngine();
  59902. var dw = this.getRenderWidth() / engine.getRenderWidth();
  59903. var dh = this.getRenderHeight() / engine.getRenderHeight();
  59904. this.blurKernelX = this._adaptiveBlurKernel * dw;
  59905. this.blurKernelY = this._adaptiveBlurKernel * dh;
  59906. };
  59907. MirrorTexture.prototype._onRatioRescale = function () {
  59908. if (this._sizeRatio) {
  59909. this.resize(this._initialSizeParameter);
  59910. if (!this._adaptiveBlurKernel) {
  59911. this._preparePostProcesses();
  59912. }
  59913. }
  59914. if (this._adaptiveBlurKernel) {
  59915. this._autoComputeBlurKernel();
  59916. }
  59917. };
  59918. MirrorTexture.prototype._preparePostProcesses = function () {
  59919. this.clearPostProcesses(true);
  59920. if (this._blurKernelX && this._blurKernelY) {
  59921. var engine = this.getScene().getEngine();
  59922. var textureType = engine.getCaps().textureFloatRender ? BABYLON.Engine.TEXTURETYPE_FLOAT : BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  59923. 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);
  59924. this._blurX.autoClear = false;
  59925. if (this._blurRatio === 1 && this.samples < 2 && this._texture) {
  59926. this._blurX.inputTexture = this._texture;
  59927. }
  59928. else {
  59929. this._blurX.alwaysForcePOT = true;
  59930. }
  59931. 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);
  59932. this._blurY.autoClear = false;
  59933. this._blurY.alwaysForcePOT = this._blurRatio !== 1;
  59934. this.addPostProcess(this._blurX);
  59935. this.addPostProcess(this._blurY);
  59936. }
  59937. else {
  59938. if (this._blurY) {
  59939. this.removePostProcess(this._blurY);
  59940. this._blurY.dispose();
  59941. this._blurY = null;
  59942. }
  59943. if (this._blurX) {
  59944. this.removePostProcess(this._blurX);
  59945. this._blurX.dispose();
  59946. this._blurX = null;
  59947. }
  59948. }
  59949. };
  59950. MirrorTexture.prototype.clone = function () {
  59951. var scene = this.getScene();
  59952. if (!scene) {
  59953. return this;
  59954. }
  59955. var textureSize = this.getSize();
  59956. var newTexture = new MirrorTexture(this.name, textureSize.width, scene, this._renderTargetOptions.generateMipMaps, this._renderTargetOptions.type, this._renderTargetOptions.samplingMode, this._renderTargetOptions.generateDepthBuffer);
  59957. // Base texture
  59958. newTexture.hasAlpha = this.hasAlpha;
  59959. newTexture.level = this.level;
  59960. // Mirror Texture
  59961. newTexture.mirrorPlane = this.mirrorPlane.clone();
  59962. if (this.renderList) {
  59963. newTexture.renderList = this.renderList.slice(0);
  59964. }
  59965. return newTexture;
  59966. };
  59967. MirrorTexture.prototype.serialize = function () {
  59968. if (!this.name) {
  59969. return null;
  59970. }
  59971. var serializationObject = _super.prototype.serialize.call(this);
  59972. serializationObject.mirrorPlane = this.mirrorPlane.asArray();
  59973. return serializationObject;
  59974. };
  59975. return MirrorTexture;
  59976. }(BABYLON.RenderTargetTexture));
  59977. BABYLON.MirrorTexture = MirrorTexture;
  59978. })(BABYLON || (BABYLON = {}));
  59979. //# sourceMappingURL=babylon.mirrorTexture.js.map
  59980. "use strict";
  59981. var BABYLON;
  59982. (function (BABYLON) {
  59983. /**
  59984. * Creates a refraction texture used by refraction channel of the standard material.
  59985. * @param name the texture name
  59986. * @param size size of the underlying texture
  59987. * @param scene root scene
  59988. */
  59989. var RefractionTexture = /** @class */ (function (_super) {
  59990. __extends(RefractionTexture, _super);
  59991. function RefractionTexture(name, size, scene, generateMipMaps) {
  59992. var _this = _super.call(this, name, size, scene, generateMipMaps, true) || this;
  59993. _this.refractionPlane = new BABYLON.Plane(0, 1, 0, 1);
  59994. _this.depth = 2.0;
  59995. _this.onBeforeRenderObservable.add(function () {
  59996. scene.clipPlane = _this.refractionPlane;
  59997. });
  59998. _this.onAfterRenderObservable.add(function () {
  59999. delete scene.clipPlane;
  60000. });
  60001. return _this;
  60002. }
  60003. RefractionTexture.prototype.clone = function () {
  60004. var scene = this.getScene();
  60005. if (!scene) {
  60006. return this;
  60007. }
  60008. var textureSize = this.getSize();
  60009. var newTexture = new RefractionTexture(this.name, textureSize.width, scene, this._generateMipMaps);
  60010. // Base texture
  60011. newTexture.hasAlpha = this.hasAlpha;
  60012. newTexture.level = this.level;
  60013. // Refraction Texture
  60014. newTexture.refractionPlane = this.refractionPlane.clone();
  60015. if (this.renderList) {
  60016. newTexture.renderList = this.renderList.slice(0);
  60017. }
  60018. newTexture.depth = this.depth;
  60019. return newTexture;
  60020. };
  60021. RefractionTexture.prototype.serialize = function () {
  60022. if (!this.name) {
  60023. return null;
  60024. }
  60025. var serializationObject = _super.prototype.serialize.call(this);
  60026. serializationObject.mirrorPlane = this.refractionPlane.asArray();
  60027. serializationObject.depth = this.depth;
  60028. return serializationObject;
  60029. };
  60030. return RefractionTexture;
  60031. }(BABYLON.RenderTargetTexture));
  60032. BABYLON.RefractionTexture = RefractionTexture;
  60033. })(BABYLON || (BABYLON = {}));
  60034. //# sourceMappingURL=babylon.refractionTexture.js.map
  60035. "use strict";
  60036. var BABYLON;
  60037. (function (BABYLON) {
  60038. /**
  60039. * A class extending {BABYLON.Texture} allowing drawing on a texture
  60040. * @see http://doc.babylonjs.com/how_to/dynamictexture
  60041. */
  60042. var DynamicTexture = /** @class */ (function (_super) {
  60043. __extends(DynamicTexture, _super);
  60044. /**
  60045. * Creates a {BABYLON.DynamicTexture}
  60046. * @param name defines the name of the texture
  60047. * @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
  60048. * @param scene defines the scene where you want the texture
  60049. * @param generateMipMaps defines the use of MinMaps or not (default is false)
  60050. * @param samplingMode defines the sampling mode to use (default is BABYLON.Texture.TRILINEAR_SAMPLINGMODE)
  60051. * @param format defines the texture format to use (default is BABYLON.Engine.TEXTUREFORMAT_RGBA)
  60052. */
  60053. function DynamicTexture(name, options, scene, generateMipMaps, samplingMode, format) {
  60054. if (scene === void 0) { scene = null; }
  60055. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  60056. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  60057. var _this = _super.call(this, null, scene, !generateMipMaps, undefined, samplingMode, undefined, undefined, undefined, undefined, format) || this;
  60058. _this.name = name;
  60059. _this._engine = _this.getScene().getEngine();
  60060. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  60061. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  60062. _this._generateMipMaps = generateMipMaps;
  60063. if (options.getContext) {
  60064. _this._canvas = options;
  60065. _this._texture = _this._engine.createDynamicTexture(options.width, options.height, generateMipMaps, samplingMode);
  60066. }
  60067. else {
  60068. _this._canvas = document.createElement("canvas");
  60069. if (options.width) {
  60070. _this._texture = _this._engine.createDynamicTexture(options.width, options.height, generateMipMaps, samplingMode);
  60071. }
  60072. else {
  60073. _this._texture = _this._engine.createDynamicTexture(options, options, generateMipMaps, samplingMode);
  60074. }
  60075. }
  60076. var textureSize = _this.getSize();
  60077. _this._canvas.width = textureSize.width;
  60078. _this._canvas.height = textureSize.height;
  60079. _this._context = _this._canvas.getContext("2d");
  60080. return _this;
  60081. }
  60082. Object.defineProperty(DynamicTexture.prototype, "canRescale", {
  60083. /**
  60084. * Gets the current state of canRescale
  60085. */
  60086. get: function () {
  60087. return true;
  60088. },
  60089. enumerable: true,
  60090. configurable: true
  60091. });
  60092. DynamicTexture.prototype._recreate = function (textureSize) {
  60093. this._canvas.width = textureSize.width;
  60094. this._canvas.height = textureSize.height;
  60095. this.releaseInternalTexture();
  60096. this._texture = this._engine.createDynamicTexture(textureSize.width, textureSize.height, this._generateMipMaps, this._samplingMode);
  60097. };
  60098. /**
  60099. * Scales the texture
  60100. * @param ratio the scale factor to apply to both width and height
  60101. */
  60102. DynamicTexture.prototype.scale = function (ratio) {
  60103. var textureSize = this.getSize();
  60104. textureSize.width *= ratio;
  60105. textureSize.height *= ratio;
  60106. this._recreate(textureSize);
  60107. };
  60108. /**
  60109. * Resizes the texture
  60110. * @param width the new width
  60111. * @param height the new height
  60112. */
  60113. DynamicTexture.prototype.scaleTo = function (width, height) {
  60114. var textureSize = this.getSize();
  60115. textureSize.width = width;
  60116. textureSize.height = height;
  60117. this._recreate(textureSize);
  60118. };
  60119. /**
  60120. * Gets the context of the canvas used by the texture
  60121. * @returns the canvas context of the dynamic texture
  60122. */
  60123. DynamicTexture.prototype.getContext = function () {
  60124. return this._context;
  60125. };
  60126. /**
  60127. * Clears the texture
  60128. */
  60129. DynamicTexture.prototype.clear = function () {
  60130. var size = this.getSize();
  60131. this._context.fillRect(0, 0, size.width, size.height);
  60132. };
  60133. /**
  60134. * Updates the texture
  60135. * @param invertY defines the direction for the Y axis (default is true - y increases downwards)
  60136. */
  60137. DynamicTexture.prototype.update = function (invertY) {
  60138. this._engine.updateDynamicTexture(this._texture, this._canvas, invertY === undefined ? true : invertY, undefined, this._format || undefined);
  60139. };
  60140. /**
  60141. * Draws text onto the texture
  60142. * @param text defines the text to be drawn
  60143. * @param x defines the placement of the text from the left
  60144. * @param y defines the placement of the text from the top when invertY is true and from the bottom when false
  60145. * @param font defines the font to be used with font-style, font-size, font-name
  60146. * @param color defines the color used for the text
  60147. * @param clearColor defines the color for the canvas, use null to not overwrite canvas
  60148. * @param invertY defines the direction for the Y axis (default is true - y increases downwards)
  60149. * @param update defines whether texture is immediately update (default is true)
  60150. */
  60151. DynamicTexture.prototype.drawText = function (text, x, y, font, color, clearColor, invertY, update) {
  60152. if (update === void 0) { update = true; }
  60153. var size = this.getSize();
  60154. if (clearColor) {
  60155. this._context.fillStyle = clearColor;
  60156. this._context.fillRect(0, 0, size.width, size.height);
  60157. }
  60158. this._context.font = font;
  60159. if (x === null || x === undefined) {
  60160. var textSize = this._context.measureText(text);
  60161. x = (size.width - textSize.width) / 2;
  60162. }
  60163. if (y === null || y === undefined) {
  60164. var fontSize = parseInt((font.replace(/\D/g, '')));
  60165. ;
  60166. y = (size.height / 2) + (fontSize / 3.65);
  60167. }
  60168. this._context.fillStyle = color;
  60169. this._context.fillText(text, x, y);
  60170. if (update) {
  60171. this.update(invertY);
  60172. }
  60173. };
  60174. /**
  60175. * Clones the texture
  60176. * @returns the clone of the texture.
  60177. */
  60178. DynamicTexture.prototype.clone = function () {
  60179. var scene = this.getScene();
  60180. if (!scene) {
  60181. return this;
  60182. }
  60183. var textureSize = this.getSize();
  60184. var newTexture = new DynamicTexture(this.name, textureSize, scene, this._generateMipMaps);
  60185. // Base texture
  60186. newTexture.hasAlpha = this.hasAlpha;
  60187. newTexture.level = this.level;
  60188. // Dynamic Texture
  60189. newTexture.wrapU = this.wrapU;
  60190. newTexture.wrapV = this.wrapV;
  60191. return newTexture;
  60192. };
  60193. /** @ignore */
  60194. DynamicTexture.prototype._rebuild = function () {
  60195. this.update();
  60196. };
  60197. return DynamicTexture;
  60198. }(BABYLON.Texture));
  60199. BABYLON.DynamicTexture = DynamicTexture;
  60200. })(BABYLON || (BABYLON = {}));
  60201. //# sourceMappingURL=babylon.dynamicTexture.js.map
  60202. "use strict";
  60203. var BABYLON;
  60204. (function (BABYLON) {
  60205. var VideoTexture = /** @class */ (function (_super) {
  60206. __extends(VideoTexture, _super);
  60207. /**
  60208. * Creates a video texture.
  60209. * Sample : https://doc.babylonjs.com/how_to/video_texture
  60210. * @param {string | null} name optional name, will detect from video source, if not defined
  60211. * @param {(string | string[] | HTMLVideoElement)} src can be used to provide an url, array of urls or an already setup HTML video element.
  60212. * @param {BABYLON.Scene} scene is obviously the current scene.
  60213. * @param {boolean} generateMipMaps can be used to turn on mipmaps (Can be expensive for videoTextures because they are often updated).
  60214. * @param {boolean} invertY is false by default but can be used to invert video on Y axis
  60215. * @param {number} samplingMode controls the sampling method and is set to TRILINEAR_SAMPLINGMODE by default
  60216. * @param {VideoTextureSettings} [settings] allows finer control over video usage
  60217. */
  60218. function VideoTexture(name, src, scene, generateMipMaps, invertY, samplingMode, settings) {
  60219. if (generateMipMaps === void 0) { generateMipMaps = false; }
  60220. if (invertY === void 0) { invertY = false; }
  60221. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  60222. if (settings === void 0) { settings = {
  60223. autoPlay: true,
  60224. loop: true,
  60225. autoUpdateTexture: true,
  60226. }; }
  60227. var _this = _super.call(this, null, scene, !generateMipMaps, invertY) || this;
  60228. _this._createInternalTexture = function () {
  60229. if (_this._texture != null) {
  60230. return;
  60231. }
  60232. if (!_this._engine.needPOTTextures ||
  60233. (BABYLON.Tools.IsExponentOfTwo(_this.video.videoWidth) && BABYLON.Tools.IsExponentOfTwo(_this.video.videoHeight))) {
  60234. _this.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  60235. _this.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  60236. }
  60237. else {
  60238. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  60239. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  60240. _this._generateMipMaps = false;
  60241. }
  60242. _this._texture = _this._engine.createDynamicTexture(_this.video.videoWidth, _this.video.videoHeight, _this._generateMipMaps, _this._samplingMode);
  60243. _this._texture.isReady = true;
  60244. _this._updateInternalTexture();
  60245. if (_this._onLoadObservable && _this._onLoadObservable.hasObservers()) {
  60246. _this.onLoadObservable.notifyObservers(_this);
  60247. }
  60248. };
  60249. _this.reset = function () {
  60250. if (_this._texture == null) {
  60251. return;
  60252. }
  60253. _this._texture.dispose();
  60254. _this._texture = null;
  60255. };
  60256. _this._updateInternalTexture = function (e) {
  60257. if (_this._texture == null || !_this._texture.isReady) {
  60258. return;
  60259. }
  60260. if (_this.video.readyState < _this.video.HAVE_CURRENT_DATA) {
  60261. return;
  60262. }
  60263. _this._engine.updateVideoTexture(_this._texture, _this.video, _this._invertY);
  60264. };
  60265. _this._engine = _this.getScene().getEngine();
  60266. _this._generateMipMaps = generateMipMaps;
  60267. _this._samplingMode = samplingMode;
  60268. _this.autoUpdateTexture = settings.autoUpdateTexture;
  60269. _this.name = name || _this._getName(src);
  60270. _this.video = _this._getVideo(src);
  60271. if (settings.autoPlay !== undefined) {
  60272. _this.video.autoplay = settings.autoPlay;
  60273. }
  60274. if (settings.loop !== undefined) {
  60275. _this.video.loop = settings.loop;
  60276. }
  60277. _this.video.addEventListener("canplay", _this._createInternalTexture);
  60278. _this.video.addEventListener("paused", _this._updateInternalTexture);
  60279. _this.video.addEventListener("seeked", _this._updateInternalTexture);
  60280. _this.video.addEventListener("emptied", _this.reset);
  60281. if (_this.video.readyState >= _this.video.HAVE_CURRENT_DATA) {
  60282. _this._createInternalTexture();
  60283. }
  60284. return _this;
  60285. }
  60286. VideoTexture.prototype._getName = function (src) {
  60287. if (src instanceof HTMLVideoElement) {
  60288. return src.currentSrc;
  60289. }
  60290. if (typeof src === "object") {
  60291. return src.toString();
  60292. }
  60293. return src;
  60294. };
  60295. ;
  60296. VideoTexture.prototype._getVideo = function (src) {
  60297. if (src instanceof HTMLVideoElement) {
  60298. BABYLON.Tools.SetCorsBehavior(src.currentSrc, src);
  60299. return src;
  60300. }
  60301. var video = document.createElement("video");
  60302. if (typeof src === "string") {
  60303. BABYLON.Tools.SetCorsBehavior(src, video);
  60304. video.src = src;
  60305. }
  60306. else {
  60307. BABYLON.Tools.SetCorsBehavior(src[0], video);
  60308. src.forEach(function (url) {
  60309. var source = document.createElement("source");
  60310. source.src = url;
  60311. video.appendChild(source);
  60312. });
  60313. }
  60314. return video;
  60315. };
  60316. ;
  60317. /**
  60318. * Internal method to initiate `update`.
  60319. */
  60320. VideoTexture.prototype._rebuild = function () {
  60321. this.update();
  60322. };
  60323. /**
  60324. * Update Texture in the `auto` mode. Does not do anything if `settings.autoUpdateTexture` is false.
  60325. */
  60326. VideoTexture.prototype.update = function () {
  60327. if (!this.autoUpdateTexture) {
  60328. // Expecting user to call `updateTexture` manually
  60329. return;
  60330. }
  60331. this.updateTexture(true);
  60332. };
  60333. /**
  60334. * Update Texture in `manual` mode. Does not do anything if not visible or paused.
  60335. * @param isVisible Visibility state, detected by user using `scene.getActiveMeshes()` or othervise.
  60336. */
  60337. VideoTexture.prototype.updateTexture = function (isVisible) {
  60338. if (!isVisible) {
  60339. return;
  60340. }
  60341. if (this.video.paused) {
  60342. return;
  60343. }
  60344. this._updateInternalTexture();
  60345. };
  60346. /**
  60347. * Change video content. Changing video instance or setting multiple urls (as in constructor) is not supported.
  60348. * @param url New url.
  60349. */
  60350. VideoTexture.prototype.updateURL = function (url) {
  60351. this.video.src = url;
  60352. };
  60353. VideoTexture.prototype.dispose = function () {
  60354. _super.prototype.dispose.call(this);
  60355. this.video.removeEventListener("canplay", this._createInternalTexture);
  60356. this.video.removeEventListener("paused", this._updateInternalTexture);
  60357. this.video.removeEventListener("seeked", this._updateInternalTexture);
  60358. this.video.removeEventListener("emptied", this.reset);
  60359. this.video.pause();
  60360. };
  60361. VideoTexture.CreateFromWebCam = function (scene, onReady, constraints) {
  60362. var video = document.createElement("video");
  60363. var constraintsDeviceId;
  60364. if (constraints && constraints.deviceId) {
  60365. constraintsDeviceId = {
  60366. exact: constraints.deviceId,
  60367. };
  60368. }
  60369. window.URL = window.URL || window.webkitURL || window.mozURL || window.msURL;
  60370. if (navigator.mediaDevices) {
  60371. navigator.mediaDevices.getUserMedia({ video: constraints })
  60372. .then(function (stream) {
  60373. if (video.mozSrcObject !== undefined) {
  60374. // hack for Firefox < 19
  60375. video.mozSrcObject = stream;
  60376. }
  60377. else {
  60378. video.srcObject = stream;
  60379. }
  60380. var onPlaying = function () {
  60381. if (onReady) {
  60382. onReady(new VideoTexture("video", video, scene, true, true));
  60383. }
  60384. video.removeEventListener("playing", onPlaying);
  60385. };
  60386. video.addEventListener("playing", onPlaying);
  60387. video.play();
  60388. })
  60389. .catch(function (err) {
  60390. BABYLON.Tools.Error(err.name);
  60391. });
  60392. }
  60393. else {
  60394. navigator.getUserMedia =
  60395. navigator.getUserMedia ||
  60396. navigator.webkitGetUserMedia ||
  60397. navigator.mozGetUserMedia ||
  60398. navigator.msGetUserMedia;
  60399. if (navigator.getUserMedia) {
  60400. navigator.getUserMedia({
  60401. video: {
  60402. deviceId: constraintsDeviceId,
  60403. width: {
  60404. min: (constraints && constraints.minWidth) || 256,
  60405. max: (constraints && constraints.maxWidth) || 640,
  60406. },
  60407. height: {
  60408. min: (constraints && constraints.minHeight) || 256,
  60409. max: (constraints && constraints.maxHeight) || 480,
  60410. },
  60411. },
  60412. }, function (stream) {
  60413. if (video.mozSrcObject !== undefined) {
  60414. // hack for Firefox < 19
  60415. video.mozSrcObject = stream;
  60416. }
  60417. else {
  60418. video.src = (window.URL && window.URL.createObjectURL(stream)) || stream;
  60419. }
  60420. video.play();
  60421. if (onReady) {
  60422. onReady(new VideoTexture("video", video, scene, true, true));
  60423. }
  60424. }, function (e) {
  60425. BABYLON.Tools.Error(e.name);
  60426. });
  60427. }
  60428. }
  60429. };
  60430. return VideoTexture;
  60431. }(BABYLON.Texture));
  60432. BABYLON.VideoTexture = VideoTexture;
  60433. })(BABYLON || (BABYLON = {}));
  60434. //# sourceMappingURL=babylon.videoTexture.js.map
  60435. "use strict";
  60436. var BABYLON;
  60437. (function (BABYLON) {
  60438. var RawTexture = /** @class */ (function (_super) {
  60439. __extends(RawTexture, _super);
  60440. function RawTexture(data, width, height, format, scene, generateMipMaps, invertY, samplingMode, type) {
  60441. if (generateMipMaps === void 0) { generateMipMaps = true; }
  60442. if (invertY === void 0) { invertY = false; }
  60443. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  60444. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  60445. var _this = _super.call(this, null, scene, !generateMipMaps, invertY) || this;
  60446. _this.format = format;
  60447. _this._engine = scene.getEngine();
  60448. _this._texture = scene.getEngine().createRawTexture(data, width, height, format, generateMipMaps, invertY, samplingMode, null, type);
  60449. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  60450. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  60451. return _this;
  60452. }
  60453. RawTexture.prototype.update = function (data) {
  60454. this._engine.updateRawTexture(this._texture, data, this._texture.format, this._texture.invertY, undefined, this._texture.type);
  60455. };
  60456. // Statics
  60457. RawTexture.CreateLuminanceTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  60458. if (generateMipMaps === void 0) { generateMipMaps = true; }
  60459. if (invertY === void 0) { invertY = false; }
  60460. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  60461. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_LUMINANCE, scene, generateMipMaps, invertY, samplingMode);
  60462. };
  60463. RawTexture.CreateLuminanceAlphaTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  60464. if (generateMipMaps === void 0) { generateMipMaps = true; }
  60465. if (invertY === void 0) { invertY = false; }
  60466. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  60467. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_LUMINANCE_ALPHA, scene, generateMipMaps, invertY, samplingMode);
  60468. };
  60469. RawTexture.CreateAlphaTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  60470. if (generateMipMaps === void 0) { generateMipMaps = true; }
  60471. if (invertY === void 0) { invertY = false; }
  60472. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  60473. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_ALPHA, scene, generateMipMaps, invertY, samplingMode);
  60474. };
  60475. RawTexture.CreateRGBTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode, type) {
  60476. if (generateMipMaps === void 0) { generateMipMaps = true; }
  60477. if (invertY === void 0) { invertY = false; }
  60478. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  60479. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  60480. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_RGB, scene, generateMipMaps, invertY, samplingMode, type);
  60481. };
  60482. RawTexture.CreateRGBATexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode, type) {
  60483. if (generateMipMaps === void 0) { generateMipMaps = true; }
  60484. if (invertY === void 0) { invertY = false; }
  60485. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  60486. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  60487. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_RGBA, scene, generateMipMaps, invertY, samplingMode, type);
  60488. };
  60489. return RawTexture;
  60490. }(BABYLON.Texture));
  60491. BABYLON.RawTexture = RawTexture;
  60492. })(BABYLON || (BABYLON = {}));
  60493. //# sourceMappingURL=babylon.rawTexture.js.map
  60494. "use strict";
  60495. var BABYLON;
  60496. (function (BABYLON) {
  60497. /**
  60498. * PostProcess can be used to apply a shader to a texture after it has been rendered
  60499. * See https://doc.babylonjs.com/how_to/how_to_use_postprocesses
  60500. */
  60501. var PostProcess = /** @class */ (function () {
  60502. /**
  60503. * Creates a new instance PostProcess
  60504. * @param name The name of the PostProcess.
  60505. * @param fragmentUrl The url of the fragment shader to be used.
  60506. * @param parameters Array of the names of uniform non-sampler2D variables that will be passed to the shader.
  60507. * @param samplers Array of the names of uniform sampler2D variables that will be passed to the shader.
  60508. * @param options The required width/height ratio to downsize to before computing the render pass. (Use 1.0 for full size)
  60509. * @param camera The camera to apply the render pass to.
  60510. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  60511. * @param engine The engine which the post process will be applied. (default: current engine)
  60512. * @param reusable If the post process can be reused on the same frame. (default: false)
  60513. * @param defines String of defines that will be set when running the fragment shader. (default: null)
  60514. * @param textureType Type of textures used when performing the post process. (default: 0)
  60515. * @param vertexUrl The url of the vertex shader to be used. (default: "postprocess")
  60516. * @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
  60517. * @param blockCompilation If the shader should not be compiled imediatly. (default: false)
  60518. */
  60519. function PostProcess(/** Name of the PostProcess. */ name, fragmentUrl, parameters, samplers, options, camera, samplingMode, engine, reusable, defines, textureType, vertexUrl, indexParameters, blockCompilation) {
  60520. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE; }
  60521. if (defines === void 0) { defines = null; }
  60522. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  60523. if (vertexUrl === void 0) { vertexUrl = "postprocess"; }
  60524. if (blockCompilation === void 0) { blockCompilation = false; }
  60525. this.name = name;
  60526. /**
  60527. * Width of the texture to apply the post process on
  60528. */
  60529. this.width = -1;
  60530. /**
  60531. * Height of the texture to apply the post process on
  60532. */
  60533. this.height = -1;
  60534. /**
  60535. * Internal, reference to the location where this postprocess was output to. (Typically the texture on the next postprocess in the chain)
  60536. */
  60537. this._outputTexture = null;
  60538. /**
  60539. * If the buffer needs to be cleared before applying the post process. (default: true)
  60540. * Should be set to false if shader will overwrite all previous pixels.
  60541. */
  60542. this.autoClear = true;
  60543. /**
  60544. * Type of alpha mode to use when performing the post process (default: Engine.ALPHA_DISABLE)
  60545. */
  60546. this.alphaMode = BABYLON.Engine.ALPHA_DISABLE;
  60547. /**
  60548. * Animations to be used for the post processing
  60549. */
  60550. this.animations = new Array();
  60551. /**
  60552. * Enable Pixel Perfect mode where texture is not scaled to be power of 2.
  60553. * Can only be used on a single postprocess or on the last one of a chain. (default: false)
  60554. */
  60555. this.enablePixelPerfectMode = false;
  60556. /**
  60557. * Scale mode for the post process (default: Engine.SCALEMODE_FLOOR)
  60558. */
  60559. this.scaleMode = BABYLON.Engine.SCALEMODE_FLOOR;
  60560. /**
  60561. * Force textures to be a power of two (default: false)
  60562. */
  60563. this.alwaysForcePOT = false;
  60564. /**
  60565. * Number of sample textures (default: 1)
  60566. */
  60567. this.samples = 1;
  60568. /**
  60569. * Modify the scale of the post process to be the same as the viewport (default: false)
  60570. */
  60571. this.adaptScaleToCurrentViewport = false;
  60572. this._reusable = false;
  60573. /**
  60574. * Smart array of input and output textures for the post process.
  60575. */
  60576. this._textures = new BABYLON.SmartArray(2);
  60577. /**
  60578. * The index in _textures that corresponds to the output texture.
  60579. */
  60580. this._currentRenderTextureInd = 0;
  60581. this._scaleRatio = new BABYLON.Vector2(1, 1);
  60582. this._texelSize = BABYLON.Vector2.Zero();
  60583. // Events
  60584. /**
  60585. * An event triggered when the postprocess is activated.
  60586. */
  60587. this.onActivateObservable = new BABYLON.Observable();
  60588. /**
  60589. * An event triggered when the postprocess changes its size.
  60590. */
  60591. this.onSizeChangedObservable = new BABYLON.Observable();
  60592. /**
  60593. * An event triggered when the postprocess applies its effect.
  60594. */
  60595. this.onApplyObservable = new BABYLON.Observable();
  60596. /**
  60597. * An event triggered before rendering the postprocess
  60598. */
  60599. this.onBeforeRenderObservable = new BABYLON.Observable();
  60600. /**
  60601. * An event triggered after rendering the postprocess
  60602. */
  60603. this.onAfterRenderObservable = new BABYLON.Observable();
  60604. if (camera != null) {
  60605. this._camera = camera;
  60606. this._scene = camera.getScene();
  60607. camera.attachPostProcess(this);
  60608. this._engine = this._scene.getEngine();
  60609. this._scene.postProcesses.push(this);
  60610. }
  60611. else if (engine) {
  60612. this._engine = engine;
  60613. this._engine.postProcesses.push(this);
  60614. }
  60615. this._options = options;
  60616. this.renderTargetSamplingMode = samplingMode ? samplingMode : BABYLON.Texture.NEAREST_SAMPLINGMODE;
  60617. this._reusable = reusable || false;
  60618. this._textureType = textureType;
  60619. this._samplers = samplers || [];
  60620. this._samplers.push("textureSampler");
  60621. this._fragmentUrl = fragmentUrl;
  60622. this._vertexUrl = vertexUrl;
  60623. this._parameters = parameters || [];
  60624. this._parameters.push("scale");
  60625. this._indexParameters = indexParameters;
  60626. if (!blockCompilation) {
  60627. this.updateEffect(defines);
  60628. }
  60629. }
  60630. Object.defineProperty(PostProcess.prototype, "onActivate", {
  60631. /**
  60632. * A function that is added to the onActivateObservable
  60633. */
  60634. set: function (callback) {
  60635. if (this._onActivateObserver) {
  60636. this.onActivateObservable.remove(this._onActivateObserver);
  60637. }
  60638. if (callback) {
  60639. this._onActivateObserver = this.onActivateObservable.add(callback);
  60640. }
  60641. },
  60642. enumerable: true,
  60643. configurable: true
  60644. });
  60645. Object.defineProperty(PostProcess.prototype, "onSizeChanged", {
  60646. /**
  60647. * A function that is added to the onSizeChangedObservable
  60648. */
  60649. set: function (callback) {
  60650. if (this._onSizeChangedObserver) {
  60651. this.onSizeChangedObservable.remove(this._onSizeChangedObserver);
  60652. }
  60653. this._onSizeChangedObserver = this.onSizeChangedObservable.add(callback);
  60654. },
  60655. enumerable: true,
  60656. configurable: true
  60657. });
  60658. Object.defineProperty(PostProcess.prototype, "onApply", {
  60659. /**
  60660. * A function that is added to the onApplyObservable
  60661. */
  60662. set: function (callback) {
  60663. if (this._onApplyObserver) {
  60664. this.onApplyObservable.remove(this._onApplyObserver);
  60665. }
  60666. this._onApplyObserver = this.onApplyObservable.add(callback);
  60667. },
  60668. enumerable: true,
  60669. configurable: true
  60670. });
  60671. Object.defineProperty(PostProcess.prototype, "onBeforeRender", {
  60672. /**
  60673. * A function that is added to the onBeforeRenderObservable
  60674. */
  60675. set: function (callback) {
  60676. if (this._onBeforeRenderObserver) {
  60677. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  60678. }
  60679. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  60680. },
  60681. enumerable: true,
  60682. configurable: true
  60683. });
  60684. Object.defineProperty(PostProcess.prototype, "onAfterRender", {
  60685. /**
  60686. * A function that is added to the onAfterRenderObservable
  60687. */
  60688. set: function (callback) {
  60689. if (this._onAfterRenderObserver) {
  60690. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  60691. }
  60692. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  60693. },
  60694. enumerable: true,
  60695. configurable: true
  60696. });
  60697. Object.defineProperty(PostProcess.prototype, "inputTexture", {
  60698. /**
  60699. * 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
  60700. * render it's output into this texture and this texture will be used as textureSampler in the fragment shader of this post process.
  60701. */
  60702. get: function () {
  60703. return this._textures.data[this._currentRenderTextureInd];
  60704. },
  60705. set: function (value) {
  60706. this._forcedOutputTexture = value;
  60707. },
  60708. enumerable: true,
  60709. configurable: true
  60710. });
  60711. /**
  60712. * Gets the camera which post process is applied to.
  60713. * @returns The camera the post process is applied to.
  60714. */
  60715. PostProcess.prototype.getCamera = function () {
  60716. return this._camera;
  60717. };
  60718. Object.defineProperty(PostProcess.prototype, "texelSize", {
  60719. /**
  60720. * Gets the texel size of the postprocess.
  60721. * See https://en.wikipedia.org/wiki/Texel_(graphics)
  60722. */
  60723. get: function () {
  60724. if (this._shareOutputWithPostProcess) {
  60725. return this._shareOutputWithPostProcess.texelSize;
  60726. }
  60727. if (this._forcedOutputTexture) {
  60728. this._texelSize.copyFromFloats(1.0 / this._forcedOutputTexture.width, 1.0 / this._forcedOutputTexture.height);
  60729. }
  60730. return this._texelSize;
  60731. },
  60732. enumerable: true,
  60733. configurable: true
  60734. });
  60735. /**
  60736. * Gets the engine which this post process belongs to.
  60737. * @returns The engine the post process was enabled with.
  60738. */
  60739. PostProcess.prototype.getEngine = function () {
  60740. return this._engine;
  60741. };
  60742. /**
  60743. * The effect that is created when initializing the post process.
  60744. * @returns The created effect corrisponding the the postprocess.
  60745. */
  60746. PostProcess.prototype.getEffect = function () {
  60747. return this._effect;
  60748. };
  60749. /**
  60750. * To avoid multiple redundant textures for multiple post process, the output the output texture for this post process can be shared with another.
  60751. * @param postProcess The post process to share the output with.
  60752. * @returns This post process.
  60753. */
  60754. PostProcess.prototype.shareOutputWith = function (postProcess) {
  60755. this._disposeTextures();
  60756. this._shareOutputWithPostProcess = postProcess;
  60757. return this;
  60758. };
  60759. /**
  60760. * Reverses the effect of calling shareOutputWith and returns the post process back to its original state.
  60761. * This should be called if the post process that shares output with this post process is disabled/disposed.
  60762. */
  60763. PostProcess.prototype.useOwnOutput = function () {
  60764. if (this._textures.length == 0) {
  60765. this._textures = new BABYLON.SmartArray(2);
  60766. }
  60767. this._shareOutputWithPostProcess = null;
  60768. };
  60769. /**
  60770. * Updates the effect with the current post process compile time values and recompiles the shader.
  60771. * @param defines Define statements that should be added at the beginning of the shader. (default: null)
  60772. * @param uniforms Set of uniform variables that will be passed to the shader. (default: null)
  60773. * @param samplers Set of Texture2D variables that will be passed to the shader. (default: null)
  60774. * @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
  60775. * @param onCompiled Called when the shader has been compiled.
  60776. * @param onError Called if there is an error when compiling a shader.
  60777. */
  60778. PostProcess.prototype.updateEffect = function (defines, uniforms, samplers, indexParameters, onCompiled, onError) {
  60779. if (defines === void 0) { defines = null; }
  60780. if (uniforms === void 0) { uniforms = null; }
  60781. if (samplers === void 0) { samplers = null; }
  60782. 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);
  60783. };
  60784. /**
  60785. * The post process is reusable if it can be used multiple times within one frame.
  60786. * @returns If the post process is reusable
  60787. */
  60788. PostProcess.prototype.isReusable = function () {
  60789. return this._reusable;
  60790. };
  60791. /** invalidate frameBuffer to hint the postprocess to create a depth buffer */
  60792. PostProcess.prototype.markTextureDirty = function () {
  60793. this.width = -1;
  60794. };
  60795. /**
  60796. * Activates the post process by intializing the textures to be used when executed. Notifies onActivateObservable.
  60797. * 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.
  60798. * @param camera The camera that will be used in the post process. This camera will be used when calling onActivateObservable.
  60799. * @param sourceTexture The source texture to be inspected to get the width and height if not specified in the post process constructor. (default: null)
  60800. * @param forceDepthStencil If true, a depth and stencil buffer will be generated. (default: false)
  60801. * @returns The target texture that was bound to be written to.
  60802. */
  60803. PostProcess.prototype.activate = function (camera, sourceTexture, forceDepthStencil) {
  60804. var _this = this;
  60805. if (sourceTexture === void 0) { sourceTexture = null; }
  60806. camera = camera || this._camera;
  60807. var scene = camera.getScene();
  60808. var engine = scene.getEngine();
  60809. var maxSize = engine.getCaps().maxTextureSize;
  60810. var requiredWidth = ((sourceTexture ? sourceTexture.width : this._engine.getRenderWidth(true)) * this._options) | 0;
  60811. var requiredHeight = ((sourceTexture ? sourceTexture.height : this._engine.getRenderHeight(true)) * this._options) | 0;
  60812. // 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
  60813. var webVRCamera = camera.parent;
  60814. if (webVRCamera && (webVRCamera.leftCamera == camera || webVRCamera.rightCamera == camera)) {
  60815. requiredWidth /= 2;
  60816. }
  60817. var desiredWidth = (this._options.width || requiredWidth);
  60818. var desiredHeight = this._options.height || requiredHeight;
  60819. if (!this._shareOutputWithPostProcess && !this._forcedOutputTexture) {
  60820. if (this.adaptScaleToCurrentViewport) {
  60821. var currentViewport = engine.currentViewport;
  60822. if (currentViewport) {
  60823. desiredWidth *= currentViewport.width;
  60824. desiredHeight *= currentViewport.height;
  60825. }
  60826. }
  60827. if (this.renderTargetSamplingMode === BABYLON.Texture.TRILINEAR_SAMPLINGMODE || this.alwaysForcePOT) {
  60828. if (!this._options.width) {
  60829. desiredWidth = engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(desiredWidth, maxSize, this.scaleMode) : desiredWidth;
  60830. }
  60831. if (!this._options.height) {
  60832. desiredHeight = engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(desiredHeight, maxSize, this.scaleMode) : desiredHeight;
  60833. }
  60834. }
  60835. if (this.width !== desiredWidth || this.height !== desiredHeight) {
  60836. if (this._textures.length > 0) {
  60837. for (var i = 0; i < this._textures.length; i++) {
  60838. this._engine._releaseTexture(this._textures.data[i]);
  60839. }
  60840. this._textures.reset();
  60841. }
  60842. this.width = desiredWidth;
  60843. this.height = desiredHeight;
  60844. var textureSize = { width: this.width, height: this.height };
  60845. var textureOptions = {
  60846. generateMipMaps: false,
  60847. generateDepthBuffer: forceDepthStencil || camera._postProcesses.indexOf(this) === 0,
  60848. generateStencilBuffer: (forceDepthStencil || camera._postProcesses.indexOf(this) === 0) && this._engine.isStencilEnable,
  60849. samplingMode: this.renderTargetSamplingMode,
  60850. type: this._textureType
  60851. };
  60852. this._textures.push(this._engine.createRenderTargetTexture(textureSize, textureOptions));
  60853. if (this._reusable) {
  60854. this._textures.push(this._engine.createRenderTargetTexture(textureSize, textureOptions));
  60855. }
  60856. this._texelSize.copyFromFloats(1.0 / this.width, 1.0 / this.height);
  60857. this.onSizeChangedObservable.notifyObservers(this);
  60858. }
  60859. this._textures.forEach(function (texture) {
  60860. if (texture.samples !== _this.samples) {
  60861. _this._engine.updateRenderTargetTextureSampleCount(texture, _this.samples);
  60862. }
  60863. });
  60864. }
  60865. var target;
  60866. if (this._shareOutputWithPostProcess) {
  60867. target = this._shareOutputWithPostProcess.inputTexture;
  60868. }
  60869. else if (this._forcedOutputTexture) {
  60870. target = this._forcedOutputTexture;
  60871. this.width = this._forcedOutputTexture.width;
  60872. this.height = this._forcedOutputTexture.height;
  60873. }
  60874. else {
  60875. target = this.inputTexture;
  60876. }
  60877. // Bind the input of this post process to be used as the output of the previous post process.
  60878. if (this.enablePixelPerfectMode) {
  60879. this._scaleRatio.copyFromFloats(requiredWidth / desiredWidth, requiredHeight / desiredHeight);
  60880. this._engine.bindFramebuffer(target, 0, requiredWidth, requiredHeight, true);
  60881. }
  60882. else {
  60883. this._scaleRatio.copyFromFloats(1, 1);
  60884. this._engine.bindFramebuffer(target, 0, undefined, undefined, true);
  60885. }
  60886. this.onActivateObservable.notifyObservers(camera);
  60887. // Clear
  60888. if (this.autoClear && this.alphaMode === BABYLON.Engine.ALPHA_DISABLE) {
  60889. this._engine.clear(this.clearColor ? this.clearColor : scene.clearColor, true, true, true);
  60890. }
  60891. if (this._reusable) {
  60892. this._currentRenderTextureInd = (this._currentRenderTextureInd + 1) % 2;
  60893. }
  60894. return target;
  60895. };
  60896. Object.defineProperty(PostProcess.prototype, "isSupported", {
  60897. /**
  60898. * If the post process is supported.
  60899. */
  60900. get: function () {
  60901. return this._effect.isSupported;
  60902. },
  60903. enumerable: true,
  60904. configurable: true
  60905. });
  60906. Object.defineProperty(PostProcess.prototype, "aspectRatio", {
  60907. /**
  60908. * The aspect ratio of the output texture.
  60909. */
  60910. get: function () {
  60911. if (this._shareOutputWithPostProcess) {
  60912. return this._shareOutputWithPostProcess.aspectRatio;
  60913. }
  60914. if (this._forcedOutputTexture) {
  60915. return this._forcedOutputTexture.width / this._forcedOutputTexture.height;
  60916. }
  60917. return this.width / this.height;
  60918. },
  60919. enumerable: true,
  60920. configurable: true
  60921. });
  60922. /**
  60923. * Get a value indicating if the post-process is ready to be used
  60924. * @returns true if the post-process is ready (shader is compiled)
  60925. */
  60926. PostProcess.prototype.isReady = function () {
  60927. return this._effect && this._effect.isReady();
  60928. };
  60929. /**
  60930. * Binds all textures and uniforms to the shader, this will be run on every pass.
  60931. * @returns the effect corrisponding to this post process. Null if not compiled or not ready.
  60932. */
  60933. PostProcess.prototype.apply = function () {
  60934. // Check
  60935. if (!this._effect || !this._effect.isReady())
  60936. return null;
  60937. // States
  60938. this._engine.enableEffect(this._effect);
  60939. this._engine.setState(false);
  60940. this._engine.setDepthBuffer(false);
  60941. this._engine.setDepthWrite(false);
  60942. // Alpha
  60943. this._engine.setAlphaMode(this.alphaMode);
  60944. if (this.alphaConstants) {
  60945. this.getEngine().setAlphaConstants(this.alphaConstants.r, this.alphaConstants.g, this.alphaConstants.b, this.alphaConstants.a);
  60946. }
  60947. // Bind the output texture of the preivous post process as the input to this post process.
  60948. var source;
  60949. if (this._shareOutputWithPostProcess) {
  60950. source = this._shareOutputWithPostProcess.inputTexture;
  60951. }
  60952. else if (this._forcedOutputTexture) {
  60953. source = this._forcedOutputTexture;
  60954. }
  60955. else {
  60956. source = this.inputTexture;
  60957. }
  60958. this._effect._bindTexture("textureSampler", source);
  60959. // Parameters
  60960. this._effect.setVector2("scale", this._scaleRatio);
  60961. this.onApplyObservable.notifyObservers(this._effect);
  60962. return this._effect;
  60963. };
  60964. PostProcess.prototype._disposeTextures = function () {
  60965. if (this._shareOutputWithPostProcess || this._forcedOutputTexture) {
  60966. return;
  60967. }
  60968. if (this._textures.length > 0) {
  60969. for (var i = 0; i < this._textures.length; i++) {
  60970. this._engine._releaseTexture(this._textures.data[i]);
  60971. }
  60972. }
  60973. this._textures.dispose();
  60974. };
  60975. /**
  60976. * Disposes the post process.
  60977. * @param camera The camera to dispose the post process on.
  60978. */
  60979. PostProcess.prototype.dispose = function (camera) {
  60980. camera = camera || this._camera;
  60981. this._disposeTextures();
  60982. if (this._scene) {
  60983. var index_1 = this._scene.postProcesses.indexOf(this);
  60984. if (index_1 !== -1) {
  60985. this._scene.postProcesses.splice(index_1, 1);
  60986. }
  60987. }
  60988. else {
  60989. var index_2 = this._engine.postProcesses.indexOf(this);
  60990. if (index_2 !== -1) {
  60991. this._engine.postProcesses.splice(index_2, 1);
  60992. }
  60993. }
  60994. if (!camera) {
  60995. return;
  60996. }
  60997. camera.detachPostProcess(this);
  60998. var index = camera._postProcesses.indexOf(this);
  60999. if (index === 0 && camera._postProcesses.length > 0) {
  61000. var firstPostProcess = this._camera._getFirstPostProcess();
  61001. if (firstPostProcess) {
  61002. firstPostProcess.markTextureDirty();
  61003. }
  61004. }
  61005. this.onActivateObservable.clear();
  61006. this.onAfterRenderObservable.clear();
  61007. this.onApplyObservable.clear();
  61008. this.onBeforeRenderObservable.clear();
  61009. this.onSizeChangedObservable.clear();
  61010. };
  61011. return PostProcess;
  61012. }());
  61013. BABYLON.PostProcess = PostProcess;
  61014. })(BABYLON || (BABYLON = {}));
  61015. //# sourceMappingURL=babylon.postProcess.js.map
  61016. "use strict";
  61017. var BABYLON;
  61018. (function (BABYLON) {
  61019. var PassPostProcess = /** @class */ (function (_super) {
  61020. __extends(PassPostProcess, _super);
  61021. function PassPostProcess(name, options, camera, samplingMode, engine, reusable, textureType, blockCompilation) {
  61022. if (camera === void 0) { camera = null; }
  61023. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  61024. if (blockCompilation === void 0) { blockCompilation = false; }
  61025. return _super.call(this, name, "pass", null, null, options, camera, samplingMode, engine, reusable, undefined, textureType, undefined, null, blockCompilation) || this;
  61026. }
  61027. return PassPostProcess;
  61028. }(BABYLON.PostProcess));
  61029. BABYLON.PassPostProcess = PassPostProcess;
  61030. })(BABYLON || (BABYLON = {}));
  61031. //# sourceMappingURL=babylon.passPostProcess.js.map
  61032. "use strict";
  61033. var __assign = (this && this.__assign) || Object.assign || function(t) {
  61034. for (var s, i = 1, n = arguments.length; i < n; i++) {
  61035. s = arguments[i];
  61036. for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
  61037. t[p] = s[p];
  61038. }
  61039. return t;
  61040. };
  61041. var BABYLON;
  61042. (function (BABYLON) {
  61043. /**
  61044. * Default implementation IShadowGenerator.
  61045. * This is the main object responsible of generating shadows in the framework.
  61046. * Documentation: https://doc.babylonjs.com/babylon101/shadows
  61047. */
  61048. var ShadowGenerator = /** @class */ (function () {
  61049. /**
  61050. * Creates a ShadowGenerator object.
  61051. * A ShadowGenerator is the required tool to use the shadows.
  61052. * Each light casting shadows needs to use its own ShadowGenerator.
  61053. * Documentation : http://doc.babylonjs.com/tutorials/shadows
  61054. * @param mapSize The size of the texture what stores the shadows. Example : 1024.
  61055. * @param light The light object generating the shadows.
  61056. * @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.
  61057. */
  61058. function ShadowGenerator(mapSize, light, useFullFloatFirst) {
  61059. this._bias = 0.00005;
  61060. this._normalBias = 0;
  61061. this._blurBoxOffset = 1;
  61062. this._blurScale = 2;
  61063. this._blurKernel = 1;
  61064. this._useKernelBlur = false;
  61065. this._filter = ShadowGenerator.FILTER_NONE;
  61066. this._filteringQuality = ShadowGenerator.QUALITY_HIGH;
  61067. this._contactHardeningLightSizeUVRatio = 0.1;
  61068. this._darkness = 0;
  61069. this._transparencyShadow = false;
  61070. /**
  61071. * Controls the extent to which the shadows fade out at the edge of the frustum
  61072. * Used only by directionals and spots
  61073. */
  61074. this.frustumEdgeFalloff = 0;
  61075. /**
  61076. * If true the shadow map is generated by rendering the back face of the mesh instead of the front face.
  61077. * This can help with self-shadowing as the geometry making up the back of objects is slightly offset.
  61078. * It might on the other hand introduce peter panning.
  61079. */
  61080. this.forceBackFacesOnly = false;
  61081. this._lightDirection = BABYLON.Vector3.Zero();
  61082. this._viewMatrix = BABYLON.Matrix.Zero();
  61083. this._projectionMatrix = BABYLON.Matrix.Zero();
  61084. this._transformMatrix = BABYLON.Matrix.Zero();
  61085. this._cachedPosition = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  61086. this._cachedDirection = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  61087. this._currentFaceIndex = 0;
  61088. this._currentFaceIndexCache = 0;
  61089. this._defaultTextureMatrix = BABYLON.Matrix.Identity();
  61090. this._mapSize = mapSize;
  61091. this._light = light;
  61092. this._scene = light.getScene();
  61093. light._shadowGenerator = this;
  61094. // Texture type fallback from float to int if not supported.
  61095. var caps = this._scene.getEngine().getCaps();
  61096. if (!useFullFloatFirst) {
  61097. if (caps.textureHalfFloatRender && caps.textureHalfFloatLinearFiltering) {
  61098. this._textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  61099. }
  61100. else if (caps.textureFloatRender && caps.textureFloatLinearFiltering) {
  61101. this._textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  61102. }
  61103. else {
  61104. this._textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  61105. }
  61106. }
  61107. else {
  61108. if (caps.textureFloatRender && caps.textureFloatLinearFiltering) {
  61109. this._textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  61110. }
  61111. else if (caps.textureHalfFloatRender && caps.textureHalfFloatLinearFiltering) {
  61112. this._textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  61113. }
  61114. else {
  61115. this._textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  61116. }
  61117. }
  61118. this._initializeGenerator();
  61119. this._applyFilterValues();
  61120. }
  61121. Object.defineProperty(ShadowGenerator.prototype, "bias", {
  61122. /**
  61123. * Gets the bias: offset applied on the depth preventing acnea (in light direction).
  61124. */
  61125. get: function () {
  61126. return this._bias;
  61127. },
  61128. /**
  61129. * Sets the bias: offset applied on the depth preventing acnea (in light direction).
  61130. */
  61131. set: function (bias) {
  61132. this._bias = bias;
  61133. },
  61134. enumerable: true,
  61135. configurable: true
  61136. });
  61137. Object.defineProperty(ShadowGenerator.prototype, "normalBias", {
  61138. /**
  61139. * Gets the normalBias: offset applied on the depth preventing acnea (along side the normal direction and proportinal to the light/normal angle).
  61140. */
  61141. get: function () {
  61142. return this._normalBias;
  61143. },
  61144. /**
  61145. * Sets the normalBias: offset applied on the depth preventing acnea (along side the normal direction and proportinal to the light/normal angle).
  61146. */
  61147. set: function (normalBias) {
  61148. this._normalBias = normalBias;
  61149. },
  61150. enumerable: true,
  61151. configurable: true
  61152. });
  61153. Object.defineProperty(ShadowGenerator.prototype, "blurBoxOffset", {
  61154. /**
  61155. * Gets the blur box offset: offset applied during the blur pass.
  61156. * Only usefull if useKernelBlur = false
  61157. */
  61158. get: function () {
  61159. return this._blurBoxOffset;
  61160. },
  61161. /**
  61162. * Sets the blur box offset: offset applied during the blur pass.
  61163. * Only usefull if useKernelBlur = false
  61164. */
  61165. set: function (value) {
  61166. if (this._blurBoxOffset === value) {
  61167. return;
  61168. }
  61169. this._blurBoxOffset = value;
  61170. this._disposeBlurPostProcesses();
  61171. },
  61172. enumerable: true,
  61173. configurable: true
  61174. });
  61175. Object.defineProperty(ShadowGenerator.prototype, "blurScale", {
  61176. /**
  61177. * Gets the blur scale: scale of the blurred texture compared to the main shadow map.
  61178. * 2 means half of the size.
  61179. */
  61180. get: function () {
  61181. return this._blurScale;
  61182. },
  61183. /**
  61184. * Sets the blur scale: scale of the blurred texture compared to the main shadow map.
  61185. * 2 means half of the size.
  61186. */
  61187. set: function (value) {
  61188. if (this._blurScale === value) {
  61189. return;
  61190. }
  61191. this._blurScale = value;
  61192. this._disposeBlurPostProcesses();
  61193. },
  61194. enumerable: true,
  61195. configurable: true
  61196. });
  61197. Object.defineProperty(ShadowGenerator.prototype, "blurKernel", {
  61198. /**
  61199. * Gets the blur kernel: kernel size of the blur pass.
  61200. * Only usefull if useKernelBlur = true
  61201. */
  61202. get: function () {
  61203. return this._blurKernel;
  61204. },
  61205. /**
  61206. * Sets the blur kernel: kernel size of the blur pass.
  61207. * Only usefull if useKernelBlur = true
  61208. */
  61209. set: function (value) {
  61210. if (this._blurKernel === value) {
  61211. return;
  61212. }
  61213. this._blurKernel = value;
  61214. this._disposeBlurPostProcesses();
  61215. },
  61216. enumerable: true,
  61217. configurable: true
  61218. });
  61219. Object.defineProperty(ShadowGenerator.prototype, "useKernelBlur", {
  61220. /**
  61221. * Gets whether the blur pass is a kernel blur (if true) or box blur.
  61222. * Only usefull in filtered mode (useBlurExponentialShadowMap...)
  61223. */
  61224. get: function () {
  61225. return this._useKernelBlur;
  61226. },
  61227. /**
  61228. * Sets whether the blur pass is a kernel blur (if true) or box blur.
  61229. * Only usefull in filtered mode (useBlurExponentialShadowMap...)
  61230. */
  61231. set: function (value) {
  61232. if (this._useKernelBlur === value) {
  61233. return;
  61234. }
  61235. this._useKernelBlur = value;
  61236. this._disposeBlurPostProcesses();
  61237. },
  61238. enumerable: true,
  61239. configurable: true
  61240. });
  61241. Object.defineProperty(ShadowGenerator.prototype, "depthScale", {
  61242. /**
  61243. * Gets the depth scale used in ESM mode.
  61244. */
  61245. get: function () {
  61246. return this._depthScale !== undefined ? this._depthScale : this._light.getDepthScale();
  61247. },
  61248. /**
  61249. * Sets the depth scale used in ESM mode.
  61250. * This can override the scale stored on the light.
  61251. */
  61252. set: function (value) {
  61253. this._depthScale = value;
  61254. },
  61255. enumerable: true,
  61256. configurable: true
  61257. });
  61258. Object.defineProperty(ShadowGenerator.prototype, "filter", {
  61259. /**
  61260. * Gets the current mode of the shadow generator (normal, PCF, ESM...).
  61261. * The returned value is a number equal to one of the available mode defined in ShadowMap.FILTER_x like _FILTER_NONE
  61262. */
  61263. get: function () {
  61264. return this._filter;
  61265. },
  61266. /**
  61267. * Sets the current mode of the shadow generator (normal, PCF, ESM...).
  61268. * The returned value is a number equal to one of the available mode defined in ShadowMap.FILTER_x like _FILTER_NONE
  61269. */
  61270. set: function (value) {
  61271. // Blurring the cubemap is going to be too expensive. Reverting to unblurred version
  61272. if (this._light.needCube()) {
  61273. if (value === ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP) {
  61274. this.useExponentialShadowMap = true;
  61275. return;
  61276. }
  61277. else if (value === ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP) {
  61278. this.useCloseExponentialShadowMap = true;
  61279. return;
  61280. }
  61281. else if (value === ShadowGenerator.FILTER_PCF || value === ShadowGenerator.FILTER_PCSS) {
  61282. this.usePoissonSampling = true;
  61283. return;
  61284. }
  61285. }
  61286. // Weblg1 fallback for PCF.
  61287. if (value === ShadowGenerator.FILTER_PCF || value === ShadowGenerator.FILTER_PCSS) {
  61288. if (this._scene.getEngine().webGLVersion === 1) {
  61289. this.usePoissonSampling = true;
  61290. return;
  61291. }
  61292. }
  61293. if (this._filter === value) {
  61294. return;
  61295. }
  61296. this._filter = value;
  61297. this._disposeBlurPostProcesses();
  61298. this._applyFilterValues();
  61299. this._light._markMeshesAsLightDirty();
  61300. },
  61301. enumerable: true,
  61302. configurable: true
  61303. });
  61304. Object.defineProperty(ShadowGenerator.prototype, "usePoissonSampling", {
  61305. /**
  61306. * Gets if the current filter is set to Poisson Sampling.
  61307. */
  61308. get: function () {
  61309. return this.filter === ShadowGenerator.FILTER_POISSONSAMPLING;
  61310. },
  61311. /**
  61312. * Sets the current filter to Poisson Sampling.
  61313. */
  61314. set: function (value) {
  61315. if (!value && this.filter !== ShadowGenerator.FILTER_POISSONSAMPLING) {
  61316. return;
  61317. }
  61318. this.filter = (value ? ShadowGenerator.FILTER_POISSONSAMPLING : ShadowGenerator.FILTER_NONE);
  61319. },
  61320. enumerable: true,
  61321. configurable: true
  61322. });
  61323. Object.defineProperty(ShadowGenerator.prototype, "useVarianceShadowMap", {
  61324. /**
  61325. * Gets if the current filter is set to VSM.
  61326. * DEPRECATED. Should use useExponentialShadowMap instead.
  61327. */
  61328. get: function () {
  61329. BABYLON.Tools.Warn("VSM are now replaced by ESM. Please use useExponentialShadowMap instead.");
  61330. return this.useExponentialShadowMap;
  61331. },
  61332. /**
  61333. * Sets the current filter is to VSM.
  61334. * DEPRECATED. Should use useExponentialShadowMap instead.
  61335. */
  61336. set: function (value) {
  61337. BABYLON.Tools.Warn("VSM are now replaced by ESM. Please use useExponentialShadowMap instead.");
  61338. this.useExponentialShadowMap = value;
  61339. },
  61340. enumerable: true,
  61341. configurable: true
  61342. });
  61343. Object.defineProperty(ShadowGenerator.prototype, "useBlurVarianceShadowMap", {
  61344. /**
  61345. * Gets if the current filter is set to blurred VSM.
  61346. * DEPRECATED. Should use useBlurExponentialShadowMap instead.
  61347. */
  61348. get: function () {
  61349. BABYLON.Tools.Warn("VSM are now replaced by ESM. Please use useBlurExponentialShadowMap instead.");
  61350. return this.useBlurExponentialShadowMap;
  61351. },
  61352. /**
  61353. * Sets the current filter is to blurred VSM.
  61354. * DEPRECATED. Should use useBlurExponentialShadowMap instead.
  61355. */
  61356. set: function (value) {
  61357. BABYLON.Tools.Warn("VSM are now replaced by ESM. Please use useBlurExponentialShadowMap instead.");
  61358. this.useBlurExponentialShadowMap = value;
  61359. },
  61360. enumerable: true,
  61361. configurable: true
  61362. });
  61363. Object.defineProperty(ShadowGenerator.prototype, "useExponentialShadowMap", {
  61364. /**
  61365. * Gets if the current filter is set to ESM.
  61366. */
  61367. get: function () {
  61368. return this.filter === ShadowGenerator.FILTER_EXPONENTIALSHADOWMAP;
  61369. },
  61370. /**
  61371. * Sets the current filter is to ESM.
  61372. */
  61373. set: function (value) {
  61374. if (!value && this.filter !== ShadowGenerator.FILTER_EXPONENTIALSHADOWMAP) {
  61375. return;
  61376. }
  61377. this.filter = (value ? ShadowGenerator.FILTER_EXPONENTIALSHADOWMAP : ShadowGenerator.FILTER_NONE);
  61378. },
  61379. enumerable: true,
  61380. configurable: true
  61381. });
  61382. Object.defineProperty(ShadowGenerator.prototype, "useBlurExponentialShadowMap", {
  61383. /**
  61384. * Gets if the current filter is set to filtered ESM.
  61385. */
  61386. get: function () {
  61387. return this.filter === ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP;
  61388. },
  61389. /**
  61390. * Gets if the current filter is set to filtered ESM.
  61391. */
  61392. set: function (value) {
  61393. if (!value && this.filter !== ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP) {
  61394. return;
  61395. }
  61396. this.filter = (value ? ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP : ShadowGenerator.FILTER_NONE);
  61397. },
  61398. enumerable: true,
  61399. configurable: true
  61400. });
  61401. Object.defineProperty(ShadowGenerator.prototype, "useCloseExponentialShadowMap", {
  61402. /**
  61403. * Gets if the current filter is set to "close ESM" (using the inverse of the
  61404. * exponential to prevent steep falloff artifacts).
  61405. */
  61406. get: function () {
  61407. return this.filter === ShadowGenerator.FILTER_CLOSEEXPONENTIALSHADOWMAP;
  61408. },
  61409. /**
  61410. * Sets the current filter to "close ESM" (using the inverse of the
  61411. * exponential to prevent steep falloff artifacts).
  61412. */
  61413. set: function (value) {
  61414. if (!value && this.filter !== ShadowGenerator.FILTER_CLOSEEXPONENTIALSHADOWMAP) {
  61415. return;
  61416. }
  61417. this.filter = (value ? ShadowGenerator.FILTER_CLOSEEXPONENTIALSHADOWMAP : ShadowGenerator.FILTER_NONE);
  61418. },
  61419. enumerable: true,
  61420. configurable: true
  61421. });
  61422. Object.defineProperty(ShadowGenerator.prototype, "useBlurCloseExponentialShadowMap", {
  61423. /**
  61424. * Gets if the current filter is set to filtered "close ESM" (using the inverse of the
  61425. * exponential to prevent steep falloff artifacts).
  61426. */
  61427. get: function () {
  61428. return this.filter === ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP;
  61429. },
  61430. /**
  61431. * Sets the current filter to filtered "close ESM" (using the inverse of the
  61432. * exponential to prevent steep falloff artifacts).
  61433. */
  61434. set: function (value) {
  61435. if (!value && this.filter !== ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP) {
  61436. return;
  61437. }
  61438. this.filter = (value ? ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP : ShadowGenerator.FILTER_NONE);
  61439. },
  61440. enumerable: true,
  61441. configurable: true
  61442. });
  61443. Object.defineProperty(ShadowGenerator.prototype, "usePercentageCloserFiltering", {
  61444. /**
  61445. * Gets if the current filter is set to "PCF" (percentage closer filtering).
  61446. */
  61447. get: function () {
  61448. return this.filter === ShadowGenerator.FILTER_PCF;
  61449. },
  61450. /**
  61451. * Sets the current filter to "PCF" (percentage closer filtering).
  61452. */
  61453. set: function (value) {
  61454. if (!value && this.filter !== ShadowGenerator.FILTER_PCF) {
  61455. return;
  61456. }
  61457. this.filter = (value ? ShadowGenerator.FILTER_PCF : ShadowGenerator.FILTER_NONE);
  61458. },
  61459. enumerable: true,
  61460. configurable: true
  61461. });
  61462. Object.defineProperty(ShadowGenerator.prototype, "filteringQuality", {
  61463. /**
  61464. * Gets the PCF or PCSS Quality.
  61465. * Only valid if usePercentageCloserFiltering or usePercentageCloserFiltering is true.
  61466. */
  61467. get: function () {
  61468. return this._filteringQuality;
  61469. },
  61470. /**
  61471. * Sets the PCF or PCSS Quality.
  61472. * Only valid if usePercentageCloserFiltering or usePercentageCloserFiltering is true.
  61473. */
  61474. set: function (filteringQuality) {
  61475. this._filteringQuality = filteringQuality;
  61476. },
  61477. enumerable: true,
  61478. configurable: true
  61479. });
  61480. Object.defineProperty(ShadowGenerator.prototype, "useContactHardeningShadow", {
  61481. /**
  61482. * Gets if the current filter is set to "PCSS" (contact hardening).
  61483. */
  61484. get: function () {
  61485. return this.filter === ShadowGenerator.FILTER_PCSS;
  61486. },
  61487. /**
  61488. * Sets the current filter to "PCSS" (contact hardening).
  61489. */
  61490. set: function (value) {
  61491. if (!value && this.filter !== ShadowGenerator.FILTER_PCSS) {
  61492. return;
  61493. }
  61494. this.filter = (value ? ShadowGenerator.FILTER_PCSS : ShadowGenerator.FILTER_NONE);
  61495. },
  61496. enumerable: true,
  61497. configurable: true
  61498. });
  61499. Object.defineProperty(ShadowGenerator.prototype, "contactHardeningLightSizeUVRatio", {
  61500. /**
  61501. * Gets the Light Size (in shadow map uv unit) used in PCSS to determine the blocker search area and the penumbra size.
  61502. * Using a ratio helps keeping shape stability independently of the map size.
  61503. *
  61504. * It does not account for the light projection as it was having too much
  61505. * instability during the light setup or during light position changes.
  61506. *
  61507. * Only valid if useContactHardeningShadow is true.
  61508. */
  61509. get: function () {
  61510. return this._contactHardeningLightSizeUVRatio;
  61511. },
  61512. /**
  61513. * Sets the Light Size (in shadow map uv unit) used in PCSS to determine the blocker search area and the penumbra size.
  61514. * Using a ratio helps keeping shape stability independently of the map size.
  61515. *
  61516. * It does not account for the light projection as it was having too much
  61517. * instability during the light setup or during light position changes.
  61518. *
  61519. * Only valid if useContactHardeningShadow is true.
  61520. */
  61521. set: function (contactHardeningLightSizeUVRatio) {
  61522. this._contactHardeningLightSizeUVRatio = contactHardeningLightSizeUVRatio;
  61523. },
  61524. enumerable: true,
  61525. configurable: true
  61526. });
  61527. /**
  61528. * Returns the darkness value (float). This can only decrease the actual darkness of a shadow.
  61529. * 0 means strongest and 1 would means no shadow.
  61530. * @returns the darkness.
  61531. */
  61532. ShadowGenerator.prototype.getDarkness = function () {
  61533. return this._darkness;
  61534. };
  61535. /**
  61536. * Sets the darkness value (float). This can only decrease the actual darkness of a shadow.
  61537. * @param darkness The darkness value 0 means strongest and 1 would means no shadow.
  61538. * @returns the shadow generator allowing fluent coding.
  61539. */
  61540. ShadowGenerator.prototype.setDarkness = function (darkness) {
  61541. if (darkness >= 1.0)
  61542. this._darkness = 1.0;
  61543. else if (darkness <= 0.0)
  61544. this._darkness = 0.0;
  61545. else
  61546. this._darkness = darkness;
  61547. return this;
  61548. };
  61549. /**
  61550. * Sets the ability to have transparent shadow (boolean).
  61551. * @param transparent True if transparent else False
  61552. * @returns the shadow generator allowing fluent coding
  61553. */
  61554. ShadowGenerator.prototype.setTransparencyShadow = function (transparent) {
  61555. this._transparencyShadow = transparent;
  61556. return this;
  61557. };
  61558. /**
  61559. * Gets the main RTT containing the shadow map (usually storing depth from the light point of view).
  61560. * @returns The render target texture if present otherwise, null
  61561. */
  61562. ShadowGenerator.prototype.getShadowMap = function () {
  61563. return this._shadowMap;
  61564. };
  61565. /**
  61566. * Gets the RTT used during rendering (can be a blurred version of the shadow map or the shadow map itself).
  61567. * @returns The render target texture if the shadow map is present otherwise, null
  61568. */
  61569. ShadowGenerator.prototype.getShadowMapForRendering = function () {
  61570. if (this._shadowMap2) {
  61571. return this._shadowMap2;
  61572. }
  61573. return this._shadowMap;
  61574. };
  61575. /**
  61576. * Helper function to add a mesh and its descendants to the list of shadow casters.
  61577. * @param mesh Mesh to add
  61578. * @param includeDescendants boolean indicating if the descendants should be added. Default to true
  61579. * @returns the Shadow Generator itself
  61580. */
  61581. ShadowGenerator.prototype.addShadowCaster = function (mesh, includeDescendants) {
  61582. if (includeDescendants === void 0) { includeDescendants = true; }
  61583. if (!this._shadowMap) {
  61584. return this;
  61585. }
  61586. if (!this._shadowMap.renderList) {
  61587. this._shadowMap.renderList = [];
  61588. }
  61589. this._shadowMap.renderList.push(mesh);
  61590. if (includeDescendants) {
  61591. (_a = this._shadowMap.renderList).push.apply(_a, mesh.getChildMeshes());
  61592. }
  61593. return this;
  61594. var _a;
  61595. };
  61596. /**
  61597. * Helper function to remove a mesh and its descendants from the list of shadow casters
  61598. * @param mesh Mesh to remove
  61599. * @param includeDescendants boolean indicating if the descendants should be removed. Default to true
  61600. * @returns the Shadow Generator itself
  61601. */
  61602. ShadowGenerator.prototype.removeShadowCaster = function (mesh, includeDescendants) {
  61603. if (includeDescendants === void 0) { includeDescendants = true; }
  61604. if (!this._shadowMap || !this._shadowMap.renderList) {
  61605. return this;
  61606. }
  61607. var index = this._shadowMap.renderList.indexOf(mesh);
  61608. if (index !== -1) {
  61609. this._shadowMap.renderList.splice(index, 1);
  61610. }
  61611. if (includeDescendants) {
  61612. for (var _i = 0, _a = mesh.getChildren(); _i < _a.length; _i++) {
  61613. var child = _a[_i];
  61614. this.removeShadowCaster(child);
  61615. }
  61616. }
  61617. return this;
  61618. };
  61619. /**
  61620. * Returns the associated light object.
  61621. * @returns the light generating the shadow
  61622. */
  61623. ShadowGenerator.prototype.getLight = function () {
  61624. return this._light;
  61625. };
  61626. ShadowGenerator.prototype._initializeGenerator = function () {
  61627. this._light._markMeshesAsLightDirty();
  61628. this._initializeShadowMap();
  61629. };
  61630. ShadowGenerator.prototype._initializeShadowMap = function () {
  61631. var _this = this;
  61632. // Render target
  61633. var engine = this._scene.getEngine();
  61634. if (engine.webGLVersion > 1) {
  61635. this._shadowMap = new BABYLON.RenderTargetTexture(this._light.name + "_shadowMap", this._mapSize, this._scene, false, true, this._textureType, this._light.needCube(), undefined, false, false);
  61636. this._shadowMap.createDepthStencilTexture(BABYLON.Engine.LESS, true);
  61637. }
  61638. else {
  61639. this._shadowMap = new BABYLON.RenderTargetTexture(this._light.name + "_shadowMap", this._mapSize, this._scene, false, true, this._textureType, this._light.needCube());
  61640. }
  61641. this._shadowMap.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  61642. this._shadowMap.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  61643. this._shadowMap.anisotropicFilteringLevel = 1;
  61644. this._shadowMap.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  61645. this._shadowMap.renderParticles = false;
  61646. this._shadowMap.ignoreCameraViewport = true;
  61647. // Record Face Index before render.
  61648. this._shadowMap.onBeforeRenderObservable.add(function (faceIndex) {
  61649. _this._currentFaceIndex = faceIndex;
  61650. if (_this._filter === ShadowGenerator.FILTER_PCF) {
  61651. engine.setColorWrite(false);
  61652. }
  61653. });
  61654. // Custom render function.
  61655. this._shadowMap.customRenderFunction = this._renderForShadowMap.bind(this);
  61656. // Blur if required afer render.
  61657. this._shadowMap.onAfterUnbindObservable.add(function () {
  61658. if (_this._filter === ShadowGenerator.FILTER_PCF) {
  61659. engine.setColorWrite(true);
  61660. }
  61661. if (!_this.useBlurExponentialShadowMap && !_this.useBlurCloseExponentialShadowMap) {
  61662. return;
  61663. }
  61664. var shadowMap = _this.getShadowMapForRendering();
  61665. if (shadowMap) {
  61666. _this._scene.postProcessManager.directRender(_this._blurPostProcesses, shadowMap.getInternalTexture(), true);
  61667. }
  61668. });
  61669. // Clear according to the chosen filter.
  61670. var clearZero = new BABYLON.Color4(0, 0, 0, 0);
  61671. var clearOne = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  61672. this._shadowMap.onClearObservable.add(function (engine) {
  61673. if (_this._filter === ShadowGenerator.FILTER_PCF) {
  61674. engine.clear(clearOne, false, true, false);
  61675. }
  61676. else if (_this.useExponentialShadowMap || _this.useBlurExponentialShadowMap) {
  61677. engine.clear(clearZero, true, true, false);
  61678. }
  61679. else {
  61680. engine.clear(clearOne, true, true, false);
  61681. }
  61682. });
  61683. };
  61684. ShadowGenerator.prototype._initializeBlurRTTAndPostProcesses = function () {
  61685. var _this = this;
  61686. var engine = this._scene.getEngine();
  61687. var targetSize = this._mapSize / this.blurScale;
  61688. if (!this.useKernelBlur || this.blurScale !== 1.0) {
  61689. this._shadowMap2 = new BABYLON.RenderTargetTexture(this._light.name + "_shadowMap2", targetSize, this._scene, false, true, this._textureType);
  61690. this._shadowMap2.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  61691. this._shadowMap2.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  61692. this._shadowMap2.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  61693. }
  61694. if (this.useKernelBlur) {
  61695. 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);
  61696. this._kernelBlurXPostprocess.width = targetSize;
  61697. this._kernelBlurXPostprocess.height = targetSize;
  61698. this._kernelBlurXPostprocess.onApplyObservable.add(function (effect) {
  61699. effect.setTexture("textureSampler", _this._shadowMap);
  61700. });
  61701. 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);
  61702. this._kernelBlurXPostprocess.autoClear = false;
  61703. this._kernelBlurYPostprocess.autoClear = false;
  61704. if (this._textureType === BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT) {
  61705. this._kernelBlurXPostprocess.packedFloat = true;
  61706. this._kernelBlurYPostprocess.packedFloat = true;
  61707. }
  61708. this._blurPostProcesses = [this._kernelBlurXPostprocess, this._kernelBlurYPostprocess];
  61709. }
  61710. else {
  61711. 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);
  61712. this._boxBlurPostprocess.onApplyObservable.add(function (effect) {
  61713. effect.setFloat2("screenSize", targetSize, targetSize);
  61714. effect.setTexture("textureSampler", _this._shadowMap);
  61715. });
  61716. this._boxBlurPostprocess.autoClear = false;
  61717. this._blurPostProcesses = [this._boxBlurPostprocess];
  61718. }
  61719. };
  61720. ShadowGenerator.prototype._renderForShadowMap = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes) {
  61721. var index;
  61722. var engine = this._scene.getEngine();
  61723. if (depthOnlySubMeshes.length) {
  61724. engine.setColorWrite(false);
  61725. for (index = 0; index < depthOnlySubMeshes.length; index++) {
  61726. this._renderSubMeshForShadowMap(depthOnlySubMeshes.data[index]);
  61727. }
  61728. engine.setColorWrite(true);
  61729. }
  61730. for (index = 0; index < opaqueSubMeshes.length; index++) {
  61731. this._renderSubMeshForShadowMap(opaqueSubMeshes.data[index]);
  61732. }
  61733. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  61734. this._renderSubMeshForShadowMap(alphaTestSubMeshes.data[index]);
  61735. }
  61736. if (this._transparencyShadow) {
  61737. for (index = 0; index < transparentSubMeshes.length; index++) {
  61738. this._renderSubMeshForShadowMap(transparentSubMeshes.data[index]);
  61739. }
  61740. }
  61741. };
  61742. ShadowGenerator.prototype._renderSubMeshForShadowMap = function (subMesh) {
  61743. var _this = this;
  61744. var mesh = subMesh.getRenderingMesh();
  61745. var scene = this._scene;
  61746. var engine = scene.getEngine();
  61747. var material = subMesh.getMaterial();
  61748. if (!material) {
  61749. return;
  61750. }
  61751. // Culling
  61752. engine.setState(material.backFaceCulling);
  61753. // Managing instances
  61754. var batch = mesh._getInstancesRenderList(subMesh._id);
  61755. if (batch.mustReturn) {
  61756. return;
  61757. }
  61758. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  61759. if (this.isReady(subMesh, hardwareInstancedRendering)) {
  61760. engine.enableEffect(this._effect);
  61761. mesh._bind(subMesh, this._effect, BABYLON.Material.TriangleFillMode);
  61762. this._effect.setFloat3("biasAndScale", this.bias, this.normalBias, this.depthScale);
  61763. this._effect.setMatrix("viewProjection", this.getTransformMatrix());
  61764. if (this.getLight().getTypeID() === BABYLON.Light.LIGHTTYPEID_DIRECTIONALLIGHT) {
  61765. this._effect.setVector3("lightData", this._cachedDirection);
  61766. }
  61767. else {
  61768. this._effect.setVector3("lightData", this._cachedPosition);
  61769. }
  61770. if (scene.activeCamera) {
  61771. this._effect.setFloat2("depthValues", this.getLight().getDepthMinZ(scene.activeCamera), this.getLight().getDepthMinZ(scene.activeCamera) + this.getLight().getDepthMaxZ(scene.activeCamera));
  61772. }
  61773. // Alpha test
  61774. if (material && material.needAlphaTesting()) {
  61775. var alphaTexture = material.getAlphaTestTexture();
  61776. if (alphaTexture) {
  61777. this._effect.setTexture("diffuseSampler", alphaTexture);
  61778. this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix() || this._defaultTextureMatrix);
  61779. }
  61780. }
  61781. // Bones
  61782. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  61783. this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices((mesh)));
  61784. }
  61785. // Morph targets
  61786. BABYLON.MaterialHelper.BindMorphTargetParameters(mesh, this._effect);
  61787. if (this.forceBackFacesOnly) {
  61788. engine.setState(true, 0, false, true);
  61789. }
  61790. // Draw
  61791. mesh._processRendering(subMesh, this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effect.setMatrix("world", world); });
  61792. if (this.forceBackFacesOnly) {
  61793. engine.setState(true, 0, false, false);
  61794. }
  61795. }
  61796. else {
  61797. // Need to reset refresh rate of the shadowMap
  61798. if (this._shadowMap) {
  61799. this._shadowMap.resetRefreshCounter();
  61800. }
  61801. }
  61802. };
  61803. ShadowGenerator.prototype._applyFilterValues = function () {
  61804. if (!this._shadowMap) {
  61805. return;
  61806. }
  61807. if (this.filter === ShadowGenerator.FILTER_NONE || this.filter === ShadowGenerator.FILTER_PCSS) {
  61808. this._shadowMap.updateSamplingMode(BABYLON.Texture.NEAREST_SAMPLINGMODE);
  61809. }
  61810. else {
  61811. this._shadowMap.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  61812. }
  61813. };
  61814. /**
  61815. * Forces all the attached effect to compile to enable rendering only once ready vs. lazyly compiling effects.
  61816. * @param onCompiled Callback triggered at the and of the effects compilation
  61817. * @param options Sets of optional options forcing the compilation with different modes
  61818. */
  61819. ShadowGenerator.prototype.forceCompilation = function (onCompiled, options) {
  61820. var _this = this;
  61821. var localOptions = __assign({ useInstances: false }, options);
  61822. var shadowMap = this.getShadowMap();
  61823. if (!shadowMap) {
  61824. if (onCompiled) {
  61825. onCompiled(this);
  61826. }
  61827. return;
  61828. }
  61829. var renderList = shadowMap.renderList;
  61830. if (!renderList) {
  61831. if (onCompiled) {
  61832. onCompiled(this);
  61833. }
  61834. return;
  61835. }
  61836. var subMeshes = new Array();
  61837. for (var _i = 0, renderList_1 = renderList; _i < renderList_1.length; _i++) {
  61838. var mesh = renderList_1[_i];
  61839. subMeshes.push.apply(subMeshes, mesh.subMeshes);
  61840. }
  61841. if (subMeshes.length === 0) {
  61842. if (onCompiled) {
  61843. onCompiled(this);
  61844. }
  61845. return;
  61846. }
  61847. var currentIndex = 0;
  61848. var checkReady = function () {
  61849. if (!_this._scene || !_this._scene.getEngine()) {
  61850. return;
  61851. }
  61852. while (_this.isReady(subMeshes[currentIndex], localOptions.useInstances)) {
  61853. currentIndex++;
  61854. if (currentIndex >= subMeshes.length) {
  61855. if (onCompiled) {
  61856. onCompiled(_this);
  61857. }
  61858. return;
  61859. }
  61860. }
  61861. setTimeout(checkReady, 16);
  61862. };
  61863. checkReady();
  61864. };
  61865. /**
  61866. * Forces all the attached effect to compile to enable rendering only once ready vs. lazyly compiling effects.
  61867. * @param options Sets of optional options forcing the compilation with different modes
  61868. * @returns A promise that resolves when the compilation completes
  61869. */
  61870. ShadowGenerator.prototype.forceCompilationAsync = function (options) {
  61871. var _this = this;
  61872. return new Promise(function (resolve) {
  61873. _this.forceCompilation(function () {
  61874. resolve();
  61875. }, options);
  61876. });
  61877. };
  61878. /**
  61879. * Determine wheter the shadow generator is ready or not (mainly all effects and related post processes needs to be ready).
  61880. * @param subMesh The submesh we want to render in the shadow map
  61881. * @param useInstances Defines wether will draw in the map using instances
  61882. * @returns true if ready otherwise, false
  61883. */
  61884. ShadowGenerator.prototype.isReady = function (subMesh, useInstances) {
  61885. var defines = [];
  61886. if (this._textureType !== BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT) {
  61887. defines.push("#define FLOAT");
  61888. }
  61889. if (this.useExponentialShadowMap || this.useBlurExponentialShadowMap) {
  61890. defines.push("#define ESM");
  61891. }
  61892. else if (this.usePercentageCloserFiltering || this.useContactHardeningShadow) {
  61893. defines.push("#define DEPTHTEXTURE");
  61894. }
  61895. var attribs = [BABYLON.VertexBuffer.PositionKind];
  61896. var mesh = subMesh.getMesh();
  61897. var material = subMesh.getMaterial();
  61898. // Normal bias.
  61899. if (this.normalBias && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  61900. attribs.push(BABYLON.VertexBuffer.NormalKind);
  61901. defines.push("#define NORMAL");
  61902. if (mesh.nonUniformScaling) {
  61903. defines.push("#define NONUNIFORMSCALING");
  61904. }
  61905. if (this.getLight().getTypeID() === BABYLON.Light.LIGHTTYPEID_DIRECTIONALLIGHT) {
  61906. defines.push("#define DIRECTIONINLIGHTDATA");
  61907. }
  61908. }
  61909. // Alpha test
  61910. if (material && material.needAlphaTesting()) {
  61911. var alphaTexture = material.getAlphaTestTexture();
  61912. if (alphaTexture) {
  61913. defines.push("#define ALPHATEST");
  61914. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  61915. attribs.push(BABYLON.VertexBuffer.UVKind);
  61916. defines.push("#define UV1");
  61917. }
  61918. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  61919. if (alphaTexture.coordinatesIndex === 1) {
  61920. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  61921. defines.push("#define UV2");
  61922. }
  61923. }
  61924. }
  61925. }
  61926. // Bones
  61927. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  61928. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  61929. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  61930. if (mesh.numBoneInfluencers > 4) {
  61931. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  61932. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  61933. }
  61934. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  61935. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  61936. }
  61937. else {
  61938. defines.push("#define NUM_BONE_INFLUENCERS 0");
  61939. }
  61940. // Morph targets
  61941. var manager = mesh.morphTargetManager;
  61942. var morphInfluencers = 0;
  61943. if (manager) {
  61944. if (manager.numInfluencers > 0) {
  61945. defines.push("#define MORPHTARGETS");
  61946. morphInfluencers = manager.numInfluencers;
  61947. defines.push("#define NUM_MORPH_INFLUENCERS " + morphInfluencers);
  61948. BABYLON.MaterialHelper.PrepareAttributesForMorphTargets(attribs, mesh, { "NUM_MORPH_INFLUENCERS": morphInfluencers });
  61949. }
  61950. }
  61951. // Instances
  61952. if (useInstances) {
  61953. defines.push("#define INSTANCES");
  61954. attribs.push("world0");
  61955. attribs.push("world1");
  61956. attribs.push("world2");
  61957. attribs.push("world3");
  61958. }
  61959. // Get correct effect
  61960. var join = defines.join("\n");
  61961. if (this._cachedDefines !== join) {
  61962. this._cachedDefines = join;
  61963. this._effect = this._scene.getEngine().createEffect("shadowMap", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "lightData", "depthValues", "biasAndScale", "morphTargetInfluences"], ["diffuseSampler"], join, undefined, undefined, undefined, { maxSimultaneousMorphTargets: morphInfluencers });
  61964. }
  61965. if (!this._effect.isReady()) {
  61966. return false;
  61967. }
  61968. if (this.useBlurExponentialShadowMap || this.useBlurCloseExponentialShadowMap) {
  61969. if (!this._blurPostProcesses || !this._blurPostProcesses.length) {
  61970. this._initializeBlurRTTAndPostProcesses();
  61971. }
  61972. }
  61973. if (this._kernelBlurXPostprocess && !this._kernelBlurXPostprocess.isReady()) {
  61974. return false;
  61975. }
  61976. if (this._kernelBlurYPostprocess && !this._kernelBlurYPostprocess.isReady()) {
  61977. return false;
  61978. }
  61979. if (this._boxBlurPostprocess && !this._boxBlurPostprocess.isReady()) {
  61980. return false;
  61981. }
  61982. return true;
  61983. };
  61984. /**
  61985. * Prepare all the defines in a material relying on a shadow map at the specified light index.
  61986. * @param defines Defines of the material we want to update
  61987. * @param lightIndex Index of the light in the enabled light list of the material
  61988. */
  61989. ShadowGenerator.prototype.prepareDefines = function (defines, lightIndex) {
  61990. var scene = this._scene;
  61991. var light = this._light;
  61992. if (!scene.shadowsEnabled || !light.shadowEnabled) {
  61993. return;
  61994. }
  61995. defines["SHADOW" + lightIndex] = true;
  61996. if (this.useContactHardeningShadow) {
  61997. defines["SHADOWPCSS" + lightIndex] = true;
  61998. if (this._filteringQuality === ShadowGenerator.QUALITY_LOW) {
  61999. defines["SHADOWLOWQUALITY" + lightIndex] = true;
  62000. }
  62001. else if (this._filteringQuality === ShadowGenerator.QUALITY_MEDIUM) {
  62002. defines["SHADOWMEDIUMQUALITY" + lightIndex] = true;
  62003. }
  62004. // else default to high.
  62005. }
  62006. if (this.usePercentageCloserFiltering) {
  62007. defines["SHADOWPCF" + lightIndex] = true;
  62008. if (this._filteringQuality === ShadowGenerator.QUALITY_LOW) {
  62009. defines["SHADOWLOWQUALITY" + lightIndex] = true;
  62010. }
  62011. else if (this._filteringQuality === ShadowGenerator.QUALITY_MEDIUM) {
  62012. defines["SHADOWMEDIUMQUALITY" + lightIndex] = true;
  62013. }
  62014. // else default to high.
  62015. }
  62016. else if (this.usePoissonSampling) {
  62017. defines["SHADOWPOISSON" + lightIndex] = true;
  62018. }
  62019. else if (this.useExponentialShadowMap || this.useBlurExponentialShadowMap) {
  62020. defines["SHADOWESM" + lightIndex] = true;
  62021. }
  62022. else if (this.useCloseExponentialShadowMap || this.useBlurCloseExponentialShadowMap) {
  62023. defines["SHADOWCLOSEESM" + lightIndex] = true;
  62024. }
  62025. if (light.needCube()) {
  62026. defines["SHADOWCUBE" + lightIndex] = true;
  62027. }
  62028. };
  62029. /**
  62030. * Binds the shadow related information inside of an effect (information like near, far, darkness...
  62031. * defined in the generator but impacting the effect).
  62032. * @param lightIndex Index of the light in the enabled light list of the material owning the effect
  62033. * @param effect The effect we are binfing the information for
  62034. */
  62035. ShadowGenerator.prototype.bindShadowLight = function (lightIndex, effect) {
  62036. var light = this._light;
  62037. var scene = this._scene;
  62038. if (!scene.shadowsEnabled || !light.shadowEnabled) {
  62039. return;
  62040. }
  62041. var camera = scene.activeCamera;
  62042. if (!camera) {
  62043. return;
  62044. }
  62045. var shadowMap = this.getShadowMap();
  62046. if (!shadowMap) {
  62047. return;
  62048. }
  62049. if (!light.needCube()) {
  62050. effect.setMatrix("lightMatrix" + lightIndex, this.getTransformMatrix());
  62051. }
  62052. // Only PCF uses depth stencil texture.
  62053. if (this._filter === ShadowGenerator.FILTER_PCF) {
  62054. effect.setDepthStencilTexture("shadowSampler" + lightIndex, this.getShadowMapForRendering());
  62055. light._uniformBuffer.updateFloat4("shadowsInfo", this.getDarkness(), shadowMap.getSize().width, 1 / shadowMap.getSize().width, this.frustumEdgeFalloff, lightIndex);
  62056. }
  62057. else if (this._filter === ShadowGenerator.FILTER_PCSS) {
  62058. effect.setDepthStencilTexture("shadowSampler" + lightIndex, this.getShadowMapForRendering());
  62059. effect.setTexture("depthSampler" + lightIndex, this.getShadowMapForRendering());
  62060. light._uniformBuffer.updateFloat4("shadowsInfo", this.getDarkness(), 1 / shadowMap.getSize().width, this._contactHardeningLightSizeUVRatio * shadowMap.getSize().width, this.frustumEdgeFalloff, lightIndex);
  62061. }
  62062. else {
  62063. effect.setTexture("shadowSampler" + lightIndex, this.getShadowMapForRendering());
  62064. light._uniformBuffer.updateFloat4("shadowsInfo", this.getDarkness(), this.blurScale / shadowMap.getSize().width, this.depthScale, this.frustumEdgeFalloff, lightIndex);
  62065. }
  62066. light._uniformBuffer.updateFloat2("depthValues", this.getLight().getDepthMinZ(camera), this.getLight().getDepthMinZ(camera) + this.getLight().getDepthMaxZ(camera), lightIndex);
  62067. };
  62068. /**
  62069. * Gets the transformation matrix used to project the meshes into the map from the light point of view.
  62070. * (eq to shadow prjection matrix * light transform matrix)
  62071. * @returns The transform matrix used to create the shadow map
  62072. */
  62073. ShadowGenerator.prototype.getTransformMatrix = function () {
  62074. var scene = this._scene;
  62075. if (this._currentRenderID === scene.getRenderId() && this._currentFaceIndexCache === this._currentFaceIndex) {
  62076. return this._transformMatrix;
  62077. }
  62078. this._currentRenderID = scene.getRenderId();
  62079. this._currentFaceIndexCache = this._currentFaceIndex;
  62080. var lightPosition = this._light.position;
  62081. if (this._light.computeTransformedInformation()) {
  62082. lightPosition = this._light.transformedPosition;
  62083. }
  62084. BABYLON.Vector3.NormalizeToRef(this._light.getShadowDirection(this._currentFaceIndex), this._lightDirection);
  62085. if (Math.abs(BABYLON.Vector3.Dot(this._lightDirection, BABYLON.Vector3.Up())) === 1.0) {
  62086. this._lightDirection.z = 0.0000000000001; // Required to avoid perfectly perpendicular light
  62087. }
  62088. if (this._light.needProjectionMatrixCompute() || !this._cachedPosition || !this._cachedDirection || !lightPosition.equals(this._cachedPosition) || !this._lightDirection.equals(this._cachedDirection)) {
  62089. this._cachedPosition.copyFrom(lightPosition);
  62090. this._cachedDirection.copyFrom(this._lightDirection);
  62091. BABYLON.Matrix.LookAtLHToRef(lightPosition, lightPosition.add(this._lightDirection), BABYLON.Vector3.Up(), this._viewMatrix);
  62092. var shadowMap = this.getShadowMap();
  62093. if (shadowMap) {
  62094. var renderList = shadowMap.renderList;
  62095. if (renderList) {
  62096. this._light.setShadowProjectionMatrix(this._projectionMatrix, this._viewMatrix, renderList);
  62097. }
  62098. }
  62099. this._viewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  62100. }
  62101. return this._transformMatrix;
  62102. };
  62103. /**
  62104. * Recreates the shadow map dependencies like RTT and post processes. This can be used during the switch between
  62105. * Cube and 2D textures for instance.
  62106. */
  62107. ShadowGenerator.prototype.recreateShadowMap = function () {
  62108. var shadowMap = this._shadowMap;
  62109. if (!shadowMap) {
  62110. return;
  62111. }
  62112. // Track render list.
  62113. var renderList = shadowMap.renderList;
  62114. // Clean up existing data.
  62115. this._disposeRTTandPostProcesses();
  62116. // Reinitializes.
  62117. this._initializeGenerator();
  62118. // Reaffect the filter to ensure a correct fallback if necessary.
  62119. this.filter = this.filter;
  62120. // Reaffect the filter.
  62121. this._applyFilterValues();
  62122. // Reaffect Render List.
  62123. this._shadowMap.renderList = renderList;
  62124. };
  62125. ShadowGenerator.prototype._disposeBlurPostProcesses = function () {
  62126. if (this._shadowMap2) {
  62127. this._shadowMap2.dispose();
  62128. this._shadowMap2 = null;
  62129. }
  62130. if (this._boxBlurPostprocess) {
  62131. this._boxBlurPostprocess.dispose();
  62132. this._boxBlurPostprocess = null;
  62133. }
  62134. if (this._kernelBlurXPostprocess) {
  62135. this._kernelBlurXPostprocess.dispose();
  62136. this._kernelBlurXPostprocess = null;
  62137. }
  62138. if (this._kernelBlurYPostprocess) {
  62139. this._kernelBlurYPostprocess.dispose();
  62140. this._kernelBlurYPostprocess = null;
  62141. }
  62142. this._blurPostProcesses = [];
  62143. };
  62144. ShadowGenerator.prototype._disposeRTTandPostProcesses = function () {
  62145. if (this._shadowMap) {
  62146. this._shadowMap.dispose();
  62147. this._shadowMap = null;
  62148. }
  62149. this._disposeBlurPostProcesses();
  62150. };
  62151. /**
  62152. * Disposes the ShadowGenerator.
  62153. * Returns nothing.
  62154. */
  62155. ShadowGenerator.prototype.dispose = function () {
  62156. this._disposeRTTandPostProcesses();
  62157. if (this._light) {
  62158. this._light._shadowGenerator = null;
  62159. this._light._markMeshesAsLightDirty();
  62160. }
  62161. };
  62162. /**
  62163. * Serializes the shadow generator setup to a json object.
  62164. * @returns The serialized JSON object
  62165. */
  62166. ShadowGenerator.prototype.serialize = function () {
  62167. var serializationObject = {};
  62168. var shadowMap = this.getShadowMap();
  62169. if (!shadowMap) {
  62170. return serializationObject;
  62171. }
  62172. serializationObject.lightId = this._light.id;
  62173. serializationObject.mapSize = shadowMap.getRenderSize();
  62174. serializationObject.useExponentialShadowMap = this.useExponentialShadowMap;
  62175. serializationObject.useBlurExponentialShadowMap = this.useBlurExponentialShadowMap;
  62176. serializationObject.useCloseExponentialShadowMap = this.useBlurExponentialShadowMap;
  62177. serializationObject.useBlurCloseExponentialShadowMap = this.useBlurExponentialShadowMap;
  62178. serializationObject.usePoissonSampling = this.usePoissonSampling;
  62179. serializationObject.forceBackFacesOnly = this.forceBackFacesOnly;
  62180. serializationObject.depthScale = this.depthScale;
  62181. serializationObject.darkness = this.getDarkness();
  62182. serializationObject.blurBoxOffset = this.blurBoxOffset;
  62183. serializationObject.blurKernel = this.blurKernel;
  62184. serializationObject.blurScale = this.blurScale;
  62185. serializationObject.useKernelBlur = this.useKernelBlur;
  62186. serializationObject.transparencyShadow = this._transparencyShadow;
  62187. serializationObject.bias = this.bias;
  62188. serializationObject.normalBias = this.normalBias;
  62189. serializationObject.usePercentageCloserFiltering = this.usePercentageCloserFiltering;
  62190. serializationObject.useContactHardeningShadow = this.useContactHardeningShadow;
  62191. serializationObject.filteringQuality = this.filteringQuality;
  62192. serializationObject.contactHardeningLightSizeUVRatio = this.contactHardeningLightSizeUVRatio;
  62193. serializationObject.renderList = [];
  62194. if (shadowMap.renderList) {
  62195. for (var meshIndex = 0; meshIndex < shadowMap.renderList.length; meshIndex++) {
  62196. var mesh = shadowMap.renderList[meshIndex];
  62197. serializationObject.renderList.push(mesh.id);
  62198. }
  62199. }
  62200. return serializationObject;
  62201. };
  62202. /**
  62203. * Parses a serialized ShadowGenerator and returns a new ShadowGenerator.
  62204. * @param parsedShadowGenerator The JSON object to parse
  62205. * @param scene The scene to create the shadow map for
  62206. * @returns The parsed shadow generator
  62207. */
  62208. ShadowGenerator.Parse = function (parsedShadowGenerator, scene) {
  62209. //casting to point light, as light is missing the position attr and typescript complains.
  62210. var light = scene.getLightByID(parsedShadowGenerator.lightId);
  62211. var shadowGenerator = new ShadowGenerator(parsedShadowGenerator.mapSize, light);
  62212. var shadowMap = shadowGenerator.getShadowMap();
  62213. for (var meshIndex = 0; meshIndex < parsedShadowGenerator.renderList.length; meshIndex++) {
  62214. var meshes = scene.getMeshesByID(parsedShadowGenerator.renderList[meshIndex]);
  62215. meshes.forEach(function (mesh) {
  62216. if (!shadowMap) {
  62217. return;
  62218. }
  62219. if (!shadowMap.renderList) {
  62220. shadowMap.renderList = [];
  62221. }
  62222. shadowMap.renderList.push(mesh);
  62223. });
  62224. }
  62225. if (parsedShadowGenerator.usePoissonSampling) {
  62226. shadowGenerator.usePoissonSampling = true;
  62227. }
  62228. else if (parsedShadowGenerator.useExponentialShadowMap) {
  62229. shadowGenerator.useExponentialShadowMap = true;
  62230. }
  62231. else if (parsedShadowGenerator.useBlurExponentialShadowMap) {
  62232. shadowGenerator.useBlurExponentialShadowMap = true;
  62233. }
  62234. else if (parsedShadowGenerator.useCloseExponentialShadowMap) {
  62235. shadowGenerator.useCloseExponentialShadowMap = true;
  62236. }
  62237. else if (parsedShadowGenerator.useBlurCloseExponentialShadowMap) {
  62238. shadowGenerator.useBlurCloseExponentialShadowMap = true;
  62239. }
  62240. else if (parsedShadowGenerator.usePercentageCloserFiltering) {
  62241. shadowGenerator.usePercentageCloserFiltering = true;
  62242. }
  62243. else if (parsedShadowGenerator.useContactHardeningShadow) {
  62244. shadowGenerator.useContactHardeningShadow = true;
  62245. }
  62246. if (parsedShadowGenerator.filteringQuality) {
  62247. shadowGenerator.filteringQuality = parsedShadowGenerator.filteringQuality;
  62248. }
  62249. if (parsedShadowGenerator.contactHardeningLightSizeUVRatio) {
  62250. shadowGenerator.contactHardeningLightSizeUVRatio = parsedShadowGenerator.contactHardeningLightSizeUVRatio;
  62251. }
  62252. else if (parsedShadowGenerator.useVarianceShadowMap) {
  62253. shadowGenerator.useExponentialShadowMap = true;
  62254. }
  62255. else if (parsedShadowGenerator.useBlurVarianceShadowMap) {
  62256. shadowGenerator.useBlurExponentialShadowMap = true;
  62257. }
  62258. if (parsedShadowGenerator.depthScale) {
  62259. shadowGenerator.depthScale = parsedShadowGenerator.depthScale;
  62260. }
  62261. if (parsedShadowGenerator.blurScale) {
  62262. shadowGenerator.blurScale = parsedShadowGenerator.blurScale;
  62263. }
  62264. if (parsedShadowGenerator.blurBoxOffset) {
  62265. shadowGenerator.blurBoxOffset = parsedShadowGenerator.blurBoxOffset;
  62266. }
  62267. if (parsedShadowGenerator.useKernelBlur) {
  62268. shadowGenerator.useKernelBlur = parsedShadowGenerator.useKernelBlur;
  62269. }
  62270. if (parsedShadowGenerator.blurKernel) {
  62271. shadowGenerator.blurKernel = parsedShadowGenerator.blurKernel;
  62272. }
  62273. if (parsedShadowGenerator.bias !== undefined) {
  62274. shadowGenerator.bias = parsedShadowGenerator.bias;
  62275. }
  62276. if (parsedShadowGenerator.normalBias !== undefined) {
  62277. shadowGenerator.normalBias = parsedShadowGenerator.normalBias;
  62278. }
  62279. if (parsedShadowGenerator.darkness) {
  62280. shadowGenerator.setDarkness(parsedShadowGenerator.darkness);
  62281. }
  62282. if (parsedShadowGenerator.transparencyShadow) {
  62283. shadowGenerator.setTransparencyShadow(true);
  62284. }
  62285. shadowGenerator.forceBackFacesOnly = parsedShadowGenerator.forceBackFacesOnly;
  62286. return shadowGenerator;
  62287. };
  62288. /**
  62289. * Shadow generator mode None: no filtering applied.
  62290. */
  62291. ShadowGenerator.FILTER_NONE = 0;
  62292. /**
  62293. * Shadow generator mode ESM: Exponential Shadow Mapping.
  62294. * (http://developer.download.nvidia.com/presentations/2008/GDC/GDC08_SoftShadowMapping.pdf)
  62295. */
  62296. ShadowGenerator.FILTER_EXPONENTIALSHADOWMAP = 1;
  62297. /**
  62298. * Shadow generator mode Poisson Sampling: Percentage Closer Filtering.
  62299. * (Multiple Tap around evenly distributed around the pixel are used to evaluate the shadow strength)
  62300. */
  62301. ShadowGenerator.FILTER_POISSONSAMPLING = 2;
  62302. /**
  62303. * Shadow generator mode ESM: Blurred Exponential Shadow Mapping.
  62304. * (http://developer.download.nvidia.com/presentations/2008/GDC/GDC08_SoftShadowMapping.pdf)
  62305. */
  62306. ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP = 3;
  62307. /**
  62308. * Shadow generator mode ESM: Exponential Shadow Mapping using the inverse of the exponential preventing
  62309. * edge artifacts on steep falloff.
  62310. * (http://developer.download.nvidia.com/presentations/2008/GDC/GDC08_SoftShadowMapping.pdf)
  62311. */
  62312. ShadowGenerator.FILTER_CLOSEEXPONENTIALSHADOWMAP = 4;
  62313. /**
  62314. * Shadow generator mode ESM: Blurred Exponential Shadow Mapping using the inverse of the exponential preventing
  62315. * edge artifacts on steep falloff.
  62316. * (http://developer.download.nvidia.com/presentations/2008/GDC/GDC08_SoftShadowMapping.pdf)
  62317. */
  62318. ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP = 5;
  62319. /**
  62320. * Shadow generator mode PCF: Percentage Closer Filtering
  62321. * benefits from Webgl 2 shadow samplers. Fallback to Poisson Sampling in Webgl 1
  62322. * (https://developer.nvidia.com/gpugems/GPUGems/gpugems_ch11.html)
  62323. */
  62324. ShadowGenerator.FILTER_PCF = 6;
  62325. /**
  62326. * Shadow generator mode PCSS: Percentage Closering Soft Shadow.
  62327. * benefits from Webgl 2 shadow samplers. Fallback to Poisson Sampling in Webgl 1
  62328. * Contact Hardening
  62329. */
  62330. ShadowGenerator.FILTER_PCSS = 7;
  62331. /**
  62332. * Reserved for PCF and PCSS
  62333. * Highest Quality.
  62334. *
  62335. * Execute PCF on a 5*5 kernel improving a lot the shadow aliasing artifacts.
  62336. *
  62337. * Execute PCSS with 32 taps blocker search and 64 taps PCF.
  62338. */
  62339. ShadowGenerator.QUALITY_HIGH = 0;
  62340. /**
  62341. * Reserved for PCF and PCSS
  62342. * Good tradeoff for quality/perf cross devices
  62343. *
  62344. * Execute PCF on a 3*3 kernel.
  62345. *
  62346. * Execute PCSS with 16 taps blocker search and 32 taps PCF.
  62347. */
  62348. ShadowGenerator.QUALITY_MEDIUM = 1;
  62349. /**
  62350. * Reserved for PCF and PCSS
  62351. * The lowest quality but the fastest.
  62352. *
  62353. * Execute PCF on a 1*1 kernel.
  62354. *
  62355. * Execute PCSS with 16 taps blocker search and 16 taps PCF.
  62356. */
  62357. ShadowGenerator.QUALITY_LOW = 2;
  62358. return ShadowGenerator;
  62359. }());
  62360. BABYLON.ShadowGenerator = ShadowGenerator;
  62361. })(BABYLON || (BABYLON = {}));
  62362. //# sourceMappingURL=babylon.shadowGenerator.js.map
  62363. "use strict";
  62364. var BABYLON;
  62365. (function (BABYLON) {
  62366. var DefaultLoadingScreen = /** @class */ (function () {
  62367. function DefaultLoadingScreen(_renderingCanvas, _loadingText, _loadingDivBackgroundColor) {
  62368. if (_loadingText === void 0) { _loadingText = ""; }
  62369. if (_loadingDivBackgroundColor === void 0) { _loadingDivBackgroundColor = "black"; }
  62370. var _this = this;
  62371. this._renderingCanvas = _renderingCanvas;
  62372. this._loadingText = _loadingText;
  62373. this._loadingDivBackgroundColor = _loadingDivBackgroundColor;
  62374. // Resize
  62375. this._resizeLoadingUI = function () {
  62376. var canvasRect = _this._renderingCanvas.getBoundingClientRect();
  62377. var canvasPositioning = window.getComputedStyle(_this._renderingCanvas).position;
  62378. if (!_this._loadingDiv) {
  62379. return;
  62380. }
  62381. _this._loadingDiv.style.position = (canvasPositioning === "fixed") ? "fixed" : "absolute";
  62382. _this._loadingDiv.style.left = canvasRect.left + "px";
  62383. _this._loadingDiv.style.top = canvasRect.top + "px";
  62384. _this._loadingDiv.style.width = canvasRect.width + "px";
  62385. _this._loadingDiv.style.height = canvasRect.height + "px";
  62386. };
  62387. }
  62388. DefaultLoadingScreen.prototype.displayLoadingUI = function () {
  62389. if (this._loadingDiv) {
  62390. // Do not add a loading screen if there is already one
  62391. return;
  62392. }
  62393. this._loadingDiv = document.createElement("div");
  62394. this._loadingDiv.id = "babylonjsLoadingDiv";
  62395. this._loadingDiv.style.opacity = "0";
  62396. this._loadingDiv.style.transition = "opacity 1.5s ease";
  62397. this._loadingDiv.style.pointerEvents = "none";
  62398. // Loading text
  62399. this._loadingTextDiv = document.createElement("div");
  62400. this._loadingTextDiv.style.position = "absolute";
  62401. this._loadingTextDiv.style.left = "0";
  62402. this._loadingTextDiv.style.top = "50%";
  62403. this._loadingTextDiv.style.marginTop = "80px";
  62404. this._loadingTextDiv.style.width = "100%";
  62405. this._loadingTextDiv.style.height = "20px";
  62406. this._loadingTextDiv.style.fontFamily = "Arial";
  62407. this._loadingTextDiv.style.fontSize = "14px";
  62408. this._loadingTextDiv.style.color = "white";
  62409. this._loadingTextDiv.style.textAlign = "center";
  62410. this._loadingTextDiv.innerHTML = "Loading";
  62411. this._loadingDiv.appendChild(this._loadingTextDiv);
  62412. //set the predefined text
  62413. this._loadingTextDiv.innerHTML = this._loadingText;
  62414. // Generating keyframes
  62415. var style = document.createElement('style');
  62416. style.type = 'text/css';
  62417. 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 }";
  62418. style.innerHTML = keyFrames;
  62419. document.getElementsByTagName('head')[0].appendChild(style);
  62420. // Loading img
  62421. var imgBack = new Image();
  62422. 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";
  62423. imgBack.style.position = "absolute";
  62424. imgBack.style.left = "50%";
  62425. imgBack.style.top = "50%";
  62426. imgBack.style.marginLeft = "-60px";
  62427. imgBack.style.marginTop = "-60px";
  62428. imgBack.style.animation = "spin1 2s infinite ease-in-out";
  62429. imgBack.style.webkitAnimation = "spin1 2s infinite ease-in-out";
  62430. imgBack.style.transformOrigin = "50% 50%";
  62431. imgBack.style.webkitTransformOrigin = "50% 50%";
  62432. this._loadingDiv.appendChild(imgBack);
  62433. this._resizeLoadingUI();
  62434. window.addEventListener("resize", this._resizeLoadingUI);
  62435. this._loadingDiv.style.backgroundColor = this._loadingDivBackgroundColor;
  62436. document.body.appendChild(this._loadingDiv);
  62437. this._loadingDiv.style.opacity = "1";
  62438. };
  62439. DefaultLoadingScreen.prototype.hideLoadingUI = function () {
  62440. var _this = this;
  62441. if (!this._loadingDiv) {
  62442. return;
  62443. }
  62444. var onTransitionEnd = function () {
  62445. if (!_this._loadingDiv) {
  62446. return;
  62447. }
  62448. document.body.removeChild(_this._loadingDiv);
  62449. window.removeEventListener("resize", _this._resizeLoadingUI);
  62450. _this._loadingDiv = null;
  62451. };
  62452. this._loadingDiv.style.opacity = "0";
  62453. this._loadingDiv.addEventListener("transitionend", onTransitionEnd);
  62454. };
  62455. Object.defineProperty(DefaultLoadingScreen.prototype, "loadingUIText", {
  62456. set: function (text) {
  62457. this._loadingText = text;
  62458. if (this._loadingTextDiv) {
  62459. this._loadingTextDiv.innerHTML = this._loadingText;
  62460. }
  62461. },
  62462. enumerable: true,
  62463. configurable: true
  62464. });
  62465. Object.defineProperty(DefaultLoadingScreen.prototype, "loadingUIBackgroundColor", {
  62466. get: function () {
  62467. return this._loadingDivBackgroundColor;
  62468. },
  62469. set: function (color) {
  62470. this._loadingDivBackgroundColor = color;
  62471. if (!this._loadingDiv) {
  62472. return;
  62473. }
  62474. this._loadingDiv.style.backgroundColor = this._loadingDivBackgroundColor;
  62475. },
  62476. enumerable: true,
  62477. configurable: true
  62478. });
  62479. return DefaultLoadingScreen;
  62480. }());
  62481. BABYLON.DefaultLoadingScreen = DefaultLoadingScreen;
  62482. })(BABYLON || (BABYLON = {}));
  62483. //# sourceMappingURL=babylon.loadingScreen.js.map
  62484. "use strict";
  62485. var BABYLON;
  62486. (function (BABYLON) {
  62487. var SceneLoaderProgressEvent = /** @class */ (function () {
  62488. function SceneLoaderProgressEvent(lengthComputable, loaded, total) {
  62489. this.lengthComputable = lengthComputable;
  62490. this.loaded = loaded;
  62491. this.total = total;
  62492. }
  62493. SceneLoaderProgressEvent.FromProgressEvent = function (event) {
  62494. return new SceneLoaderProgressEvent(event.lengthComputable, event.loaded, event.total);
  62495. };
  62496. return SceneLoaderProgressEvent;
  62497. }());
  62498. BABYLON.SceneLoaderProgressEvent = SceneLoaderProgressEvent;
  62499. var SceneLoader = /** @class */ (function () {
  62500. function SceneLoader() {
  62501. }
  62502. Object.defineProperty(SceneLoader, "NO_LOGGING", {
  62503. get: function () {
  62504. return 0;
  62505. },
  62506. enumerable: true,
  62507. configurable: true
  62508. });
  62509. Object.defineProperty(SceneLoader, "MINIMAL_LOGGING", {
  62510. get: function () {
  62511. return 1;
  62512. },
  62513. enumerable: true,
  62514. configurable: true
  62515. });
  62516. Object.defineProperty(SceneLoader, "SUMMARY_LOGGING", {
  62517. get: function () {
  62518. return 2;
  62519. },
  62520. enumerable: true,
  62521. configurable: true
  62522. });
  62523. Object.defineProperty(SceneLoader, "DETAILED_LOGGING", {
  62524. get: function () {
  62525. return 3;
  62526. },
  62527. enumerable: true,
  62528. configurable: true
  62529. });
  62530. Object.defineProperty(SceneLoader, "ForceFullSceneLoadingForIncremental", {
  62531. get: function () {
  62532. return SceneLoader._ForceFullSceneLoadingForIncremental;
  62533. },
  62534. set: function (value) {
  62535. SceneLoader._ForceFullSceneLoadingForIncremental = value;
  62536. },
  62537. enumerable: true,
  62538. configurable: true
  62539. });
  62540. Object.defineProperty(SceneLoader, "ShowLoadingScreen", {
  62541. get: function () {
  62542. return SceneLoader._ShowLoadingScreen;
  62543. },
  62544. set: function (value) {
  62545. SceneLoader._ShowLoadingScreen = value;
  62546. },
  62547. enumerable: true,
  62548. configurable: true
  62549. });
  62550. Object.defineProperty(SceneLoader, "loggingLevel", {
  62551. get: function () {
  62552. return SceneLoader._loggingLevel;
  62553. },
  62554. set: function (value) {
  62555. SceneLoader._loggingLevel = value;
  62556. },
  62557. enumerable: true,
  62558. configurable: true
  62559. });
  62560. Object.defineProperty(SceneLoader, "CleanBoneMatrixWeights", {
  62561. get: function () {
  62562. return SceneLoader._CleanBoneMatrixWeights;
  62563. },
  62564. set: function (value) {
  62565. SceneLoader._CleanBoneMatrixWeights = value;
  62566. },
  62567. enumerable: true,
  62568. configurable: true
  62569. });
  62570. SceneLoader._getDefaultPlugin = function () {
  62571. return SceneLoader._registeredPlugins[".babylon"];
  62572. };
  62573. SceneLoader._getPluginForExtension = function (extension) {
  62574. var registeredPlugin = SceneLoader._registeredPlugins[extension];
  62575. if (registeredPlugin) {
  62576. return registeredPlugin;
  62577. }
  62578. BABYLON.Tools.Warn("Unable to find a plugin to load " + extension + " files. Trying to use .babylon default plugin.");
  62579. return SceneLoader._getDefaultPlugin();
  62580. };
  62581. SceneLoader._getPluginForDirectLoad = function (data) {
  62582. for (var extension in SceneLoader._registeredPlugins) {
  62583. var plugin = SceneLoader._registeredPlugins[extension].plugin;
  62584. if (plugin.canDirectLoad && plugin.canDirectLoad(data)) {
  62585. return SceneLoader._registeredPlugins[extension];
  62586. }
  62587. }
  62588. return SceneLoader._getDefaultPlugin();
  62589. };
  62590. SceneLoader._getPluginForFilename = function (sceneFilename) {
  62591. if (sceneFilename.name) {
  62592. sceneFilename = sceneFilename.name;
  62593. }
  62594. var queryStringPosition = sceneFilename.indexOf("?");
  62595. if (queryStringPosition !== -1) {
  62596. sceneFilename = sceneFilename.substring(0, queryStringPosition);
  62597. }
  62598. var dotPosition = sceneFilename.lastIndexOf(".");
  62599. var extension = sceneFilename.substring(dotPosition, sceneFilename.length).toLowerCase();
  62600. return SceneLoader._getPluginForExtension(extension);
  62601. };
  62602. // use babylon file loader directly if sceneFilename is prefixed with "data:"
  62603. SceneLoader._getDirectLoad = function (sceneFilename) {
  62604. if (sceneFilename.substr && sceneFilename.substr(0, 5) === "data:") {
  62605. return sceneFilename.substr(5);
  62606. }
  62607. return null;
  62608. };
  62609. SceneLoader._loadData = function (rootUrl, sceneFilename, scene, onSuccess, onProgress, onError, onDispose, pluginExtension) {
  62610. var directLoad = SceneLoader._getDirectLoad(sceneFilename);
  62611. var registeredPlugin = pluginExtension ? SceneLoader._getPluginForExtension(pluginExtension) : (directLoad ? SceneLoader._getPluginForDirectLoad(sceneFilename) : SceneLoader._getPluginForFilename(sceneFilename));
  62612. var plugin;
  62613. if (registeredPlugin.plugin.createPlugin) {
  62614. plugin = registeredPlugin.plugin.createPlugin();
  62615. }
  62616. else {
  62617. plugin = registeredPlugin.plugin;
  62618. }
  62619. var useArrayBuffer = registeredPlugin.isBinary;
  62620. var database;
  62621. SceneLoader.OnPluginActivatedObservable.notifyObservers(plugin);
  62622. var dataCallback = function (data, responseURL) {
  62623. if (scene.isDisposed) {
  62624. onError("Scene has been disposed");
  62625. return;
  62626. }
  62627. scene.database = database;
  62628. onSuccess(plugin, data, responseURL);
  62629. };
  62630. var request = null;
  62631. var pluginDisposed = false;
  62632. var onDisposeObservable = plugin.onDisposeObservable;
  62633. if (onDisposeObservable) {
  62634. onDisposeObservable.add(function () {
  62635. pluginDisposed = true;
  62636. if (request) {
  62637. request.abort();
  62638. request = null;
  62639. }
  62640. onDispose();
  62641. });
  62642. }
  62643. var manifestChecked = function () {
  62644. if (pluginDisposed) {
  62645. return;
  62646. }
  62647. var url = rootUrl + sceneFilename;
  62648. request = BABYLON.Tools.LoadFile(url, dataCallback, onProgress ? function (event) {
  62649. onProgress(SceneLoaderProgressEvent.FromProgressEvent(event));
  62650. } : undefined, database, useArrayBuffer, function (request, exception) {
  62651. onError("Failed to load scene." + (exception ? "" : " " + exception.message), exception);
  62652. });
  62653. };
  62654. if (directLoad) {
  62655. dataCallback(directLoad);
  62656. return plugin;
  62657. }
  62658. if (rootUrl.indexOf("file:") === -1) {
  62659. var canUseOfflineSupport = scene.getEngine().enableOfflineSupport;
  62660. if (canUseOfflineSupport) {
  62661. // Also check for exceptions
  62662. var exceptionFound = false;
  62663. for (var _i = 0, _a = scene.disableOfflineSupportExceptionRules; _i < _a.length; _i++) {
  62664. var regex = _a[_i];
  62665. if (regex.test(rootUrl + sceneFilename)) {
  62666. exceptionFound = true;
  62667. break;
  62668. }
  62669. }
  62670. canUseOfflineSupport = !exceptionFound;
  62671. }
  62672. if (canUseOfflineSupport) {
  62673. // Checking if a manifest file has been set for this scene and if offline mode has been requested
  62674. database = new BABYLON.Database(rootUrl + sceneFilename, manifestChecked);
  62675. }
  62676. else {
  62677. manifestChecked();
  62678. }
  62679. }
  62680. else {
  62681. var fileOrString = sceneFilename;
  62682. if (fileOrString.name) {
  62683. request = BABYLON.Tools.ReadFile(fileOrString, dataCallback, onProgress, useArrayBuffer);
  62684. }
  62685. else if (BABYLON.FilesInput.FilesToLoad[sceneFilename]) {
  62686. request = BABYLON.Tools.ReadFile(BABYLON.FilesInput.FilesToLoad[sceneFilename], dataCallback, onProgress, useArrayBuffer);
  62687. }
  62688. else {
  62689. onError("Unable to find file named " + sceneFilename);
  62690. }
  62691. }
  62692. return plugin;
  62693. };
  62694. // Public functions
  62695. SceneLoader.GetPluginForExtension = function (extension) {
  62696. return SceneLoader._getPluginForExtension(extension).plugin;
  62697. };
  62698. SceneLoader.IsPluginForExtensionAvailable = function (extension) {
  62699. return !!SceneLoader._registeredPlugins[extension];
  62700. };
  62701. SceneLoader.RegisterPlugin = function (plugin) {
  62702. if (typeof plugin.extensions === "string") {
  62703. var extension = plugin.extensions;
  62704. SceneLoader._registeredPlugins[extension.toLowerCase()] = {
  62705. plugin: plugin,
  62706. isBinary: false
  62707. };
  62708. }
  62709. else {
  62710. var extensions = plugin.extensions;
  62711. Object.keys(extensions).forEach(function (extension) {
  62712. SceneLoader._registeredPlugins[extension.toLowerCase()] = {
  62713. plugin: plugin,
  62714. isBinary: extensions[extension].isBinary
  62715. };
  62716. });
  62717. }
  62718. };
  62719. /**
  62720. * Import meshes into a scene
  62721. * @param meshNames an array of mesh names, a single mesh name, or empty string for all meshes that filter what meshes are imported
  62722. * @param rootUrl a string that defines the root url for scene and resources
  62723. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  62724. * @param scene the instance of BABYLON.Scene to append to
  62725. * @param onSuccess a callback with a list of imported meshes, particleSystems, and skeletons when import succeeds
  62726. * @param onProgress a callback with a progress event for each file being loaded
  62727. * @param onError a callback with the scene, a message, and possibly an exception when import fails
  62728. * @param pluginExtension the extension used to determine the plugin
  62729. * @returns The loaded plugin
  62730. */
  62731. SceneLoader.ImportMesh = function (meshNames, rootUrl, sceneFilename, scene, onSuccess, onProgress, onError, pluginExtension) {
  62732. if (onSuccess === void 0) { onSuccess = null; }
  62733. if (onProgress === void 0) { onProgress = null; }
  62734. if (onError === void 0) { onError = null; }
  62735. if (pluginExtension === void 0) { pluginExtension = null; }
  62736. if (sceneFilename.substr && sceneFilename.substr(0, 1) === "/") {
  62737. BABYLON.Tools.Error("Wrong sceneFilename parameter");
  62738. return null;
  62739. }
  62740. var loadingToken = {};
  62741. scene._addPendingData(loadingToken);
  62742. var disposeHandler = function () {
  62743. scene._removePendingData(loadingToken);
  62744. };
  62745. var errorHandler = function (message, exception) {
  62746. var errorMessage = "Unable to import meshes from " + rootUrl + sceneFilename + ": " + message;
  62747. if (onError) {
  62748. onError(scene, errorMessage, exception);
  62749. }
  62750. else {
  62751. BABYLON.Tools.Error(errorMessage);
  62752. // should the exception be thrown?
  62753. }
  62754. disposeHandler();
  62755. };
  62756. var progressHandler = onProgress ? function (event) {
  62757. try {
  62758. onProgress(event);
  62759. }
  62760. catch (e) {
  62761. errorHandler("Error in onProgress callback", e);
  62762. }
  62763. } : undefined;
  62764. var successHandler = function (meshes, particleSystems, skeletons) {
  62765. scene.importedMeshesFiles.push(rootUrl + sceneFilename);
  62766. if (onSuccess) {
  62767. try {
  62768. onSuccess(meshes, particleSystems, skeletons);
  62769. }
  62770. catch (e) {
  62771. errorHandler("Error in onSuccess callback", e);
  62772. }
  62773. }
  62774. scene._removePendingData(loadingToken);
  62775. };
  62776. return SceneLoader._loadData(rootUrl, sceneFilename, scene, function (plugin, data, responseURL) {
  62777. if (plugin.rewriteRootURL) {
  62778. rootUrl = plugin.rewriteRootURL(rootUrl, responseURL);
  62779. }
  62780. if (sceneFilename === "") {
  62781. if (sceneFilename === "") {
  62782. rootUrl = BABYLON.Tools.GetFolderPath(rootUrl, true);
  62783. }
  62784. }
  62785. if (plugin.importMesh) {
  62786. var syncedPlugin = plugin;
  62787. var meshes = new Array();
  62788. var particleSystems = new Array();
  62789. var skeletons = new Array();
  62790. if (!syncedPlugin.importMesh(meshNames, scene, data, rootUrl, meshes, particleSystems, skeletons, errorHandler)) {
  62791. return;
  62792. }
  62793. scene.loadingPluginName = plugin.name;
  62794. successHandler(meshes, particleSystems, skeletons);
  62795. }
  62796. else {
  62797. var asyncedPlugin = plugin;
  62798. asyncedPlugin.importMeshAsync(meshNames, scene, data, rootUrl, progressHandler).then(function (result) {
  62799. scene.loadingPluginName = plugin.name;
  62800. successHandler(result.meshes, result.particleSystems, result.skeletons);
  62801. }).catch(function (error) {
  62802. errorHandler(error.message, error);
  62803. });
  62804. }
  62805. }, progressHandler, errorHandler, disposeHandler, pluginExtension);
  62806. };
  62807. /**
  62808. * Import meshes into a scene
  62809. * @param meshNames an array of mesh names, a single mesh name, or empty string for all meshes that filter what meshes are imported
  62810. * @param rootUrl a string that defines the root url for scene and resources
  62811. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  62812. * @param scene the instance of BABYLON.Scene to append to
  62813. * @param onProgress a callback with a progress event for each file being loaded
  62814. * @param pluginExtension the extension used to determine the plugin
  62815. * @returns The loaded list of imported meshes, particleSystems, and skeletons
  62816. */
  62817. SceneLoader.ImportMeshAsync = function (meshNames, rootUrl, sceneFilename, scene, onProgress, pluginExtension) {
  62818. if (onProgress === void 0) { onProgress = null; }
  62819. if (pluginExtension === void 0) { pluginExtension = null; }
  62820. return new Promise(function (resolve, reject) {
  62821. SceneLoader.ImportMesh(meshNames, rootUrl, sceneFilename, scene, function (meshes, particleSystems, skeletons) {
  62822. resolve({
  62823. meshes: meshes,
  62824. particleSystems: particleSystems,
  62825. skeletons: skeletons
  62826. });
  62827. }, onProgress, function (scene, message, exception) {
  62828. reject(exception || new Error(message));
  62829. });
  62830. });
  62831. };
  62832. /**
  62833. * Load a scene
  62834. * @param rootUrl a string that defines the root url for scene and resources
  62835. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  62836. * @param engine is the instance of BABYLON.Engine to use to create the scene
  62837. * @param onSuccess a callback with the scene when import succeeds
  62838. * @param onProgress a callback with a progress event for each file being loaded
  62839. * @param onError a callback with the scene, a message, and possibly an exception when import fails
  62840. * @param pluginExtension the extension used to determine the plugin
  62841. * @returns The loaded plugin
  62842. */
  62843. SceneLoader.Load = function (rootUrl, sceneFilename, engine, onSuccess, onProgress, onError, pluginExtension) {
  62844. if (onSuccess === void 0) { onSuccess = null; }
  62845. if (onProgress === void 0) { onProgress = null; }
  62846. if (onError === void 0) { onError = null; }
  62847. if (pluginExtension === void 0) { pluginExtension = null; }
  62848. return SceneLoader.Append(rootUrl, sceneFilename, new BABYLON.Scene(engine), onSuccess, onProgress, onError, pluginExtension);
  62849. };
  62850. /**
  62851. * Load a scene
  62852. * @param rootUrl a string that defines the root url for scene and resources
  62853. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  62854. * @param engine is the instance of BABYLON.Engine to use to create the scene
  62855. * @param onProgress a callback with a progress event for each file being loaded
  62856. * @param pluginExtension the extension used to determine the plugin
  62857. * @returns The loaded scene
  62858. */
  62859. SceneLoader.LoadAsync = function (rootUrl, sceneFilename, engine, onProgress, pluginExtension) {
  62860. if (onProgress === void 0) { onProgress = null; }
  62861. if (pluginExtension === void 0) { pluginExtension = null; }
  62862. return new Promise(function (resolve, reject) {
  62863. SceneLoader.Load(rootUrl, sceneFilename, engine, function (scene) {
  62864. resolve(scene);
  62865. }, onProgress, function (scene, message, exception) {
  62866. reject(exception || new Error(message));
  62867. }, pluginExtension);
  62868. });
  62869. };
  62870. /**
  62871. * Append a scene
  62872. * @param rootUrl a string that defines the root url for scene and resources
  62873. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  62874. * @param scene is the instance of BABYLON.Scene to append to
  62875. * @param onSuccess a callback with the scene when import succeeds
  62876. * @param onProgress a callback with a progress event for each file being loaded
  62877. * @param onError a callback with the scene, a message, and possibly an exception when import fails
  62878. * @param pluginExtension the extension used to determine the plugin
  62879. * @returns The loaded plugin
  62880. */
  62881. SceneLoader.Append = function (rootUrl, sceneFilename, scene, onSuccess, onProgress, onError, pluginExtension) {
  62882. if (onSuccess === void 0) { onSuccess = null; }
  62883. if (onProgress === void 0) { onProgress = null; }
  62884. if (onError === void 0) { onError = null; }
  62885. if (pluginExtension === void 0) { pluginExtension = null; }
  62886. if (sceneFilename.substr && sceneFilename.substr(0, 1) === "/") {
  62887. BABYLON.Tools.Error("Wrong sceneFilename parameter");
  62888. return null;
  62889. }
  62890. if (SceneLoader.ShowLoadingScreen) {
  62891. scene.getEngine().displayLoadingUI();
  62892. }
  62893. var loadingToken = {};
  62894. scene._addPendingData(loadingToken);
  62895. var disposeHandler = function () {
  62896. scene._removePendingData(loadingToken);
  62897. scene.getEngine().hideLoadingUI();
  62898. };
  62899. var errorHandler = function (message, exception) {
  62900. var errorMessage = "Unable to load from " + rootUrl + sceneFilename + (message ? ": " + message : "");
  62901. if (onError) {
  62902. onError(scene, errorMessage, exception);
  62903. }
  62904. else {
  62905. BABYLON.Tools.Error(errorMessage);
  62906. // should the exception be thrown?
  62907. }
  62908. disposeHandler();
  62909. };
  62910. var progressHandler = onProgress ? function (event) {
  62911. try {
  62912. onProgress(event);
  62913. }
  62914. catch (e) {
  62915. errorHandler("Error in onProgress callback", e);
  62916. }
  62917. } : undefined;
  62918. var successHandler = function () {
  62919. if (onSuccess) {
  62920. try {
  62921. onSuccess(scene);
  62922. }
  62923. catch (e) {
  62924. errorHandler("Error in onSuccess callback", e);
  62925. }
  62926. }
  62927. scene._removePendingData(loadingToken);
  62928. };
  62929. return SceneLoader._loadData(rootUrl, sceneFilename, scene, function (plugin, data, responseURL) {
  62930. if (sceneFilename === "") {
  62931. rootUrl = BABYLON.Tools.GetFolderPath(rootUrl, true);
  62932. }
  62933. if (plugin.load) {
  62934. var syncedPlugin = plugin;
  62935. if (!syncedPlugin.load(scene, data, rootUrl, errorHandler)) {
  62936. return;
  62937. }
  62938. scene.loadingPluginName = plugin.name;
  62939. successHandler();
  62940. }
  62941. else {
  62942. var asyncedPlugin = plugin;
  62943. asyncedPlugin.loadAsync(scene, data, rootUrl, progressHandler).then(function () {
  62944. scene.loadingPluginName = plugin.name;
  62945. successHandler();
  62946. }).catch(function (error) {
  62947. errorHandler(error.message, error);
  62948. });
  62949. }
  62950. if (SceneLoader.ShowLoadingScreen) {
  62951. scene.executeWhenReady(function () {
  62952. scene.getEngine().hideLoadingUI();
  62953. });
  62954. }
  62955. }, progressHandler, errorHandler, disposeHandler, pluginExtension);
  62956. };
  62957. /**
  62958. * Append a scene
  62959. * @param rootUrl a string that defines the root url for scene and resources
  62960. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  62961. * @param scene is the instance of BABYLON.Scene to append to
  62962. * @param onProgress a callback with a progress event for each file being loaded
  62963. * @param pluginExtension the extension used to determine the plugin
  62964. * @returns The given scene
  62965. */
  62966. SceneLoader.AppendAsync = function (rootUrl, sceneFilename, scene, onProgress, pluginExtension) {
  62967. if (onProgress === void 0) { onProgress = null; }
  62968. if (pluginExtension === void 0) { pluginExtension = null; }
  62969. return new Promise(function (resolve, reject) {
  62970. SceneLoader.Append(rootUrl, sceneFilename, scene, function (scene) {
  62971. resolve(scene);
  62972. }, onProgress, function (scene, message, exception) {
  62973. reject(exception || new Error(message));
  62974. }, pluginExtension);
  62975. });
  62976. };
  62977. /**
  62978. * Load a scene into an asset container
  62979. * @param rootUrl a string that defines the root url for scene and resources
  62980. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  62981. * @param scene is the instance of BABYLON.Scene to append to
  62982. * @param onSuccess a callback with the scene when import succeeds
  62983. * @param onProgress a callback with a progress event for each file being loaded
  62984. * @param onError a callback with the scene, a message, and possibly an exception when import fails
  62985. * @param pluginExtension the extension used to determine the plugin
  62986. * @returns The loaded plugin
  62987. */
  62988. SceneLoader.LoadAssetContainer = function (rootUrl, sceneFilename, scene, onSuccess, onProgress, onError, pluginExtension) {
  62989. if (onSuccess === void 0) { onSuccess = null; }
  62990. if (onProgress === void 0) { onProgress = null; }
  62991. if (onError === void 0) { onError = null; }
  62992. if (pluginExtension === void 0) { pluginExtension = null; }
  62993. if (sceneFilename.substr && sceneFilename.substr(0, 1) === "/") {
  62994. BABYLON.Tools.Error("Wrong sceneFilename parameter");
  62995. return null;
  62996. }
  62997. var loadingToken = {};
  62998. scene._addPendingData(loadingToken);
  62999. var disposeHandler = function () {
  63000. scene._removePendingData(loadingToken);
  63001. };
  63002. var errorHandler = function (message, exception) {
  63003. var errorMessage = "Unable to load assets from " + rootUrl + sceneFilename + (message ? ": " + message : "");
  63004. if (onError) {
  63005. onError(scene, errorMessage, exception);
  63006. }
  63007. else {
  63008. BABYLON.Tools.Error(errorMessage);
  63009. // should the exception be thrown?
  63010. }
  63011. disposeHandler();
  63012. };
  63013. var progressHandler = onProgress ? function (event) {
  63014. try {
  63015. onProgress(event);
  63016. }
  63017. catch (e) {
  63018. errorHandler("Error in onProgress callback", e);
  63019. }
  63020. } : undefined;
  63021. var successHandler = function (assets) {
  63022. if (onSuccess) {
  63023. try {
  63024. onSuccess(assets);
  63025. }
  63026. catch (e) {
  63027. errorHandler("Error in onSuccess callback", e);
  63028. }
  63029. }
  63030. scene._removePendingData(loadingToken);
  63031. };
  63032. return SceneLoader._loadData(rootUrl, sceneFilename, scene, function (plugin, data, responseURL) {
  63033. if (plugin.loadAssetContainer) {
  63034. var syncedPlugin = plugin;
  63035. var assetContainer = syncedPlugin.loadAssetContainer(scene, data, rootUrl, errorHandler);
  63036. if (!assetContainer) {
  63037. return;
  63038. }
  63039. scene.loadingPluginName = plugin.name;
  63040. successHandler(assetContainer);
  63041. }
  63042. else if (plugin.loadAssetContainerAsync) {
  63043. var asyncedPlugin = plugin;
  63044. asyncedPlugin.loadAssetContainerAsync(scene, data, rootUrl, progressHandler).then(function (assetContainer) {
  63045. scene.loadingPluginName = plugin.name;
  63046. successHandler(assetContainer);
  63047. }).catch(function (error) {
  63048. errorHandler(error.message, error);
  63049. });
  63050. }
  63051. else {
  63052. errorHandler("LoadAssetContainer is not supported by this plugin. Plugin did not provide a loadAssetContainer or loadAssetContainerAsync method.");
  63053. }
  63054. if (SceneLoader.ShowLoadingScreen) {
  63055. scene.executeWhenReady(function () {
  63056. scene.getEngine().hideLoadingUI();
  63057. });
  63058. }
  63059. }, progressHandler, errorHandler, disposeHandler, pluginExtension);
  63060. };
  63061. /**
  63062. * Load a scene into an asset container
  63063. * @param rootUrl a string that defines the root url for scene and resources
  63064. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  63065. * @param scene is the instance of BABYLON.Scene to append to
  63066. * @param onProgress a callback with a progress event for each file being loaded
  63067. * @param pluginExtension the extension used to determine the plugin
  63068. * @returns The loaded asset container
  63069. */
  63070. SceneLoader.LoadAssetContainerAsync = function (rootUrl, sceneFilename, scene, onProgress, pluginExtension) {
  63071. if (onProgress === void 0) { onProgress = null; }
  63072. if (pluginExtension === void 0) { pluginExtension = null; }
  63073. return new Promise(function (resolve, reject) {
  63074. SceneLoader.LoadAssetContainer(rootUrl, sceneFilename, scene, function (assetContainer) {
  63075. resolve(assetContainer);
  63076. }, onProgress, function (scene, message, exception) {
  63077. reject(exception || new Error(message));
  63078. }, pluginExtension);
  63079. });
  63080. };
  63081. // Flags
  63082. SceneLoader._ForceFullSceneLoadingForIncremental = false;
  63083. SceneLoader._ShowLoadingScreen = true;
  63084. SceneLoader._CleanBoneMatrixWeights = false;
  63085. SceneLoader._loggingLevel = SceneLoader.NO_LOGGING;
  63086. // Members
  63087. SceneLoader.OnPluginActivatedObservable = new BABYLON.Observable();
  63088. SceneLoader._registeredPlugins = {};
  63089. return SceneLoader;
  63090. }());
  63091. BABYLON.SceneLoader = SceneLoader;
  63092. ;
  63093. })(BABYLON || (BABYLON = {}));
  63094. //# sourceMappingURL=babylon.sceneLoader.js.map
  63095. "use strict";
  63096. var BABYLON;
  63097. (function (BABYLON) {
  63098. var parseMaterialById = function (id, parsedData, scene, rootUrl) {
  63099. for (var index = 0, cache = parsedData.materials.length; index < cache; index++) {
  63100. var parsedMaterial = parsedData.materials[index];
  63101. if (parsedMaterial.id === id) {
  63102. return BABYLON.Material.Parse(parsedMaterial, scene, rootUrl);
  63103. }
  63104. }
  63105. return null;
  63106. };
  63107. var isDescendantOf = function (mesh, names, hierarchyIds) {
  63108. for (var i in names) {
  63109. if (mesh.name === names[i]) {
  63110. hierarchyIds.push(mesh.id);
  63111. return true;
  63112. }
  63113. }
  63114. if (mesh.parentId && hierarchyIds.indexOf(mesh.parentId) !== -1) {
  63115. hierarchyIds.push(mesh.id);
  63116. return true;
  63117. }
  63118. return false;
  63119. };
  63120. var logOperation = function (operation, producer) {
  63121. return operation + " of " + (producer ? producer.file + " from " + producer.name + " version: " + producer.version + ", exporter version: " + producer.exporter_version : "unknown");
  63122. };
  63123. var loadAssetContainer = function (scene, data, rootUrl, onError, addToScene) {
  63124. if (addToScene === void 0) { addToScene = false; }
  63125. var container = new BABYLON.AssetContainer(scene);
  63126. // Entire method running in try block, so ALWAYS logs as far as it got, only actually writes details
  63127. // when SceneLoader.debugLogging = true (default), or exception encountered.
  63128. // Everything stored in var log instead of writing separate lines to support only writing in exception,
  63129. // and avoid problems with multiple concurrent .babylon loads.
  63130. var log = "importScene has failed JSON parse";
  63131. try {
  63132. var parsedData = JSON.parse(data);
  63133. log = "";
  63134. var fullDetails = BABYLON.SceneLoader.loggingLevel === BABYLON.SceneLoader.DETAILED_LOGGING;
  63135. var index;
  63136. var cache;
  63137. // Lights
  63138. if (parsedData.lights !== undefined && parsedData.lights !== null) {
  63139. for (index = 0, cache = parsedData.lights.length; index < cache; index++) {
  63140. var parsedLight = parsedData.lights[index];
  63141. var light = BABYLON.Light.Parse(parsedLight, scene);
  63142. if (light) {
  63143. container.lights.push(light);
  63144. log += (index === 0 ? "\n\tLights:" : "");
  63145. log += "\n\t\t" + light.toString(fullDetails);
  63146. }
  63147. }
  63148. }
  63149. // Animations
  63150. if (parsedData.animations !== undefined && parsedData.animations !== null) {
  63151. for (index = 0, cache = parsedData.animations.length; index < cache; index++) {
  63152. var parsedAnimation = parsedData.animations[index];
  63153. var animation = BABYLON.Animation.Parse(parsedAnimation);
  63154. scene.animations.push(animation);
  63155. container.animations.push(animation);
  63156. log += (index === 0 ? "\n\tAnimations:" : "");
  63157. log += "\n\t\t" + animation.toString(fullDetails);
  63158. }
  63159. }
  63160. // Materials
  63161. if (parsedData.materials !== undefined && parsedData.materials !== null) {
  63162. for (index = 0, cache = parsedData.materials.length; index < cache; index++) {
  63163. var parsedMaterial = parsedData.materials[index];
  63164. var mat = BABYLON.Material.Parse(parsedMaterial, scene, rootUrl);
  63165. container.materials.push(mat);
  63166. log += (index === 0 ? "\n\tMaterials:" : "");
  63167. log += "\n\t\t" + mat.toString(fullDetails);
  63168. }
  63169. }
  63170. if (parsedData.multiMaterials !== undefined && parsedData.multiMaterials !== null) {
  63171. for (index = 0, cache = parsedData.multiMaterials.length; index < cache; index++) {
  63172. var parsedMultiMaterial = parsedData.multiMaterials[index];
  63173. var mmat = BABYLON.Material.ParseMultiMaterial(parsedMultiMaterial, scene);
  63174. container.multiMaterials.push(mmat);
  63175. log += (index === 0 ? "\n\tMultiMaterials:" : "");
  63176. log += "\n\t\t" + mmat.toString(fullDetails);
  63177. }
  63178. }
  63179. // Morph targets
  63180. if (parsedData.morphTargetManagers !== undefined && parsedData.morphTargetManagers !== null) {
  63181. for (var _i = 0, _a = parsedData.morphTargetManagers; _i < _a.length; _i++) {
  63182. var managerData = _a[_i];
  63183. container.morphTargetManagers.push(BABYLON.MorphTargetManager.Parse(managerData, scene));
  63184. }
  63185. }
  63186. // Skeletons
  63187. if (parsedData.skeletons !== undefined && parsedData.skeletons !== null) {
  63188. for (index = 0, cache = parsedData.skeletons.length; index < cache; index++) {
  63189. var parsedSkeleton = parsedData.skeletons[index];
  63190. var skeleton = BABYLON.Skeleton.Parse(parsedSkeleton, scene);
  63191. container.skeletons.push(skeleton);
  63192. log += (index === 0 ? "\n\tSkeletons:" : "");
  63193. log += "\n\t\t" + skeleton.toString(fullDetails);
  63194. }
  63195. }
  63196. // Geometries
  63197. var geometries = parsedData.geometries;
  63198. if (geometries !== undefined && geometries !== null) {
  63199. var addedGeometry = new Array();
  63200. // Boxes
  63201. var boxes = geometries.boxes;
  63202. if (boxes !== undefined && boxes !== null) {
  63203. for (index = 0, cache = boxes.length; index < cache; index++) {
  63204. var parsedBox = boxes[index];
  63205. addedGeometry.push(BABYLON.BoxGeometry.Parse(parsedBox, scene));
  63206. }
  63207. }
  63208. // Spheres
  63209. var spheres = geometries.spheres;
  63210. if (spheres !== undefined && spheres !== null) {
  63211. for (index = 0, cache = spheres.length; index < cache; index++) {
  63212. var parsedSphere = spheres[index];
  63213. addedGeometry.push(BABYLON.SphereGeometry.Parse(parsedSphere, scene));
  63214. }
  63215. }
  63216. // Cylinders
  63217. var cylinders = geometries.cylinders;
  63218. if (cylinders !== undefined && cylinders !== null) {
  63219. for (index = 0, cache = cylinders.length; index < cache; index++) {
  63220. var parsedCylinder = cylinders[index];
  63221. addedGeometry.push(BABYLON.CylinderGeometry.Parse(parsedCylinder, scene));
  63222. }
  63223. }
  63224. // Toruses
  63225. var toruses = geometries.toruses;
  63226. if (toruses !== undefined && toruses !== null) {
  63227. for (index = 0, cache = toruses.length; index < cache; index++) {
  63228. var parsedTorus = toruses[index];
  63229. addedGeometry.push(BABYLON.TorusGeometry.Parse(parsedTorus, scene));
  63230. }
  63231. }
  63232. // Grounds
  63233. var grounds = geometries.grounds;
  63234. if (grounds !== undefined && grounds !== null) {
  63235. for (index = 0, cache = grounds.length; index < cache; index++) {
  63236. var parsedGround = grounds[index];
  63237. addedGeometry.push(BABYLON.GroundGeometry.Parse(parsedGround, scene));
  63238. }
  63239. }
  63240. // Planes
  63241. var planes = geometries.planes;
  63242. if (planes !== undefined && planes !== null) {
  63243. for (index = 0, cache = planes.length; index < cache; index++) {
  63244. var parsedPlane = planes[index];
  63245. addedGeometry.push(BABYLON.PlaneGeometry.Parse(parsedPlane, scene));
  63246. }
  63247. }
  63248. // TorusKnots
  63249. var torusKnots = geometries.torusKnots;
  63250. if (torusKnots !== undefined && torusKnots !== null) {
  63251. for (index = 0, cache = torusKnots.length; index < cache; index++) {
  63252. var parsedTorusKnot = torusKnots[index];
  63253. addedGeometry.push(BABYLON.TorusKnotGeometry.Parse(parsedTorusKnot, scene));
  63254. }
  63255. }
  63256. // VertexData
  63257. var vertexData = geometries.vertexData;
  63258. if (vertexData !== undefined && vertexData !== null) {
  63259. for (index = 0, cache = vertexData.length; index < cache; index++) {
  63260. var parsedVertexData = vertexData[index];
  63261. addedGeometry.push(BABYLON.Geometry.Parse(parsedVertexData, scene, rootUrl));
  63262. }
  63263. }
  63264. addedGeometry.forEach(function (g) {
  63265. if (g) {
  63266. container.geometries.push(g);
  63267. }
  63268. });
  63269. }
  63270. // Transform nodes
  63271. if (parsedData.transformNodes !== undefined && parsedData.transformNodes !== null) {
  63272. for (index = 0, cache = parsedData.transformNodes.length; index < cache; index++) {
  63273. var parsedTransformNode = parsedData.transformNodes[index];
  63274. var node = BABYLON.TransformNode.Parse(parsedTransformNode, scene, rootUrl);
  63275. container.transformNodes.push(node);
  63276. }
  63277. }
  63278. // Meshes
  63279. if (parsedData.meshes !== undefined && parsedData.meshes !== null) {
  63280. for (index = 0, cache = parsedData.meshes.length; index < cache; index++) {
  63281. var parsedMesh = parsedData.meshes[index];
  63282. var mesh = BABYLON.Mesh.Parse(parsedMesh, scene, rootUrl);
  63283. container.meshes.push(mesh);
  63284. log += (index === 0 ? "\n\tMeshes:" : "");
  63285. log += "\n\t\t" + mesh.toString(fullDetails);
  63286. }
  63287. }
  63288. // Cameras
  63289. if (parsedData.cameras !== undefined && parsedData.cameras !== null) {
  63290. for (index = 0, cache = parsedData.cameras.length; index < cache; index++) {
  63291. var parsedCamera = parsedData.cameras[index];
  63292. var camera = BABYLON.Camera.Parse(parsedCamera, scene);
  63293. container.cameras.push(camera);
  63294. log += (index === 0 ? "\n\tCameras:" : "");
  63295. log += "\n\t\t" + camera.toString(fullDetails);
  63296. }
  63297. }
  63298. // Browsing all the graph to connect the dots
  63299. for (index = 0, cache = scene.cameras.length; index < cache; index++) {
  63300. var camera = scene.cameras[index];
  63301. if (camera._waitingParentId) {
  63302. camera.parent = scene.getLastEntryByID(camera._waitingParentId);
  63303. camera._waitingParentId = null;
  63304. }
  63305. }
  63306. for (index = 0, cache = scene.lights.length; index < cache; index++) {
  63307. var light_1 = scene.lights[index];
  63308. if (light_1 && light_1._waitingParentId) {
  63309. light_1.parent = scene.getLastEntryByID(light_1._waitingParentId);
  63310. light_1._waitingParentId = null;
  63311. }
  63312. }
  63313. // Sounds
  63314. // TODO: add sound
  63315. var loadedSounds = [];
  63316. var loadedSound;
  63317. if (BABYLON.AudioEngine && parsedData.sounds !== undefined && parsedData.sounds !== null) {
  63318. for (index = 0, cache = parsedData.sounds.length; index < cache; index++) {
  63319. var parsedSound = parsedData.sounds[index];
  63320. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  63321. if (!parsedSound.url)
  63322. parsedSound.url = parsedSound.name;
  63323. if (!loadedSounds[parsedSound.url]) {
  63324. loadedSound = BABYLON.Sound.Parse(parsedSound, scene, rootUrl);
  63325. loadedSounds[parsedSound.url] = loadedSound;
  63326. container.sounds.push(loadedSound);
  63327. }
  63328. else {
  63329. container.sounds.push(BABYLON.Sound.Parse(parsedSound, scene, rootUrl, loadedSounds[parsedSound.url]));
  63330. }
  63331. }
  63332. else {
  63333. container.sounds.push(new BABYLON.Sound(parsedSound.name, null, scene));
  63334. }
  63335. }
  63336. }
  63337. loadedSounds = [];
  63338. // Connect parents & children and parse actions
  63339. for (index = 0, cache = scene.transformNodes.length; index < cache; index++) {
  63340. var transformNode = scene.transformNodes[index];
  63341. if (transformNode._waitingParentId) {
  63342. transformNode.parent = scene.getLastEntryByID(transformNode._waitingParentId);
  63343. transformNode._waitingParentId = null;
  63344. }
  63345. }
  63346. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  63347. var mesh = scene.meshes[index];
  63348. if (mesh._waitingParentId) {
  63349. mesh.parent = scene.getLastEntryByID(mesh._waitingParentId);
  63350. mesh._waitingParentId = null;
  63351. }
  63352. if (mesh._waitingActions) {
  63353. BABYLON.ActionManager.Parse(mesh._waitingActions, mesh, scene);
  63354. mesh._waitingActions = null;
  63355. }
  63356. }
  63357. // freeze world matrix application
  63358. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  63359. var currentMesh = scene.meshes[index];
  63360. if (currentMesh._waitingFreezeWorldMatrix) {
  63361. currentMesh.freezeWorldMatrix();
  63362. currentMesh._waitingFreezeWorldMatrix = null;
  63363. }
  63364. else {
  63365. currentMesh.computeWorldMatrix(true);
  63366. }
  63367. }
  63368. // Particles Systems
  63369. if (parsedData.particleSystems !== undefined && parsedData.particleSystems !== null) {
  63370. for (index = 0, cache = parsedData.particleSystems.length; index < cache; index++) {
  63371. var parsedParticleSystem = parsedData.particleSystems[index];
  63372. if (parsedParticleSystem.activeParticleCount) {
  63373. var ps = BABYLON.GPUParticleSystem.Parse(parsedParticleSystem, scene, rootUrl);
  63374. container.particleSystems.push(ps);
  63375. }
  63376. else {
  63377. var ps = BABYLON.ParticleSystem.Parse(parsedParticleSystem, scene, rootUrl);
  63378. container.particleSystems.push(ps);
  63379. }
  63380. }
  63381. }
  63382. // Lens flares
  63383. if (parsedData.lensFlareSystems !== undefined && parsedData.lensFlareSystems !== null) {
  63384. for (index = 0, cache = parsedData.lensFlareSystems.length; index < cache; index++) {
  63385. var parsedLensFlareSystem = parsedData.lensFlareSystems[index];
  63386. var lf = BABYLON.LensFlareSystem.Parse(parsedLensFlareSystem, scene, rootUrl);
  63387. container.lensFlareSystems.push(lf);
  63388. }
  63389. }
  63390. // Shadows
  63391. if (parsedData.shadowGenerators !== undefined && parsedData.shadowGenerators !== null) {
  63392. for (index = 0, cache = parsedData.shadowGenerators.length; index < cache; index++) {
  63393. var parsedShadowGenerator = parsedData.shadowGenerators[index];
  63394. var sg = BABYLON.ShadowGenerator.Parse(parsedShadowGenerator, scene);
  63395. container.shadowGenerators.push(sg);
  63396. }
  63397. }
  63398. // Lights exclusions / inclusions
  63399. for (index = 0, cache = scene.lights.length; index < cache; index++) {
  63400. var light_2 = scene.lights[index];
  63401. // Excluded check
  63402. if (light_2._excludedMeshesIds.length > 0) {
  63403. for (var excludedIndex = 0; excludedIndex < light_2._excludedMeshesIds.length; excludedIndex++) {
  63404. var excludedMesh = scene.getMeshByID(light_2._excludedMeshesIds[excludedIndex]);
  63405. if (excludedMesh) {
  63406. light_2.excludedMeshes.push(excludedMesh);
  63407. }
  63408. }
  63409. light_2._excludedMeshesIds = [];
  63410. }
  63411. // Included check
  63412. if (light_2._includedOnlyMeshesIds.length > 0) {
  63413. for (var includedOnlyIndex = 0; includedOnlyIndex < light_2._includedOnlyMeshesIds.length; includedOnlyIndex++) {
  63414. var includedOnlyMesh = scene.getMeshByID(light_2._includedOnlyMeshesIds[includedOnlyIndex]);
  63415. if (includedOnlyMesh) {
  63416. light_2.includedOnlyMeshes.push(includedOnlyMesh);
  63417. }
  63418. }
  63419. light_2._includedOnlyMeshesIds = [];
  63420. }
  63421. }
  63422. // Actions (scene)
  63423. if (parsedData.actions !== undefined && parsedData.actions !== null) {
  63424. BABYLON.ActionManager.Parse(parsedData.actions, null, scene);
  63425. }
  63426. if (!addToScene) {
  63427. container.removeAllFromScene();
  63428. }
  63429. }
  63430. catch (err) {
  63431. var msg = logOperation("loadAssts", parsedData ? parsedData.producer : "Unknown") + log;
  63432. if (onError) {
  63433. onError(msg, err);
  63434. }
  63435. else {
  63436. BABYLON.Tools.Log(msg);
  63437. throw err;
  63438. }
  63439. }
  63440. finally {
  63441. if (log !== null && BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.NO_LOGGING) {
  63442. BABYLON.Tools.Log(logOperation("loadAssts", parsedData ? parsedData.producer : "Unknown") + (BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.MINIMAL_LOGGING ? log : ""));
  63443. }
  63444. }
  63445. return container;
  63446. };
  63447. BABYLON.SceneLoader.RegisterPlugin({
  63448. name: "babylon.js",
  63449. extensions: ".babylon",
  63450. canDirectLoad: function (data) {
  63451. if (data.indexOf("babylon") !== -1) {
  63452. return true;
  63453. }
  63454. return false;
  63455. },
  63456. importMesh: function (meshesNames, scene, data, rootUrl, meshes, particleSystems, skeletons, onError) {
  63457. // Entire method running in try block, so ALWAYS logs as far as it got, only actually writes details
  63458. // when SceneLoader.debugLogging = true (default), or exception encountered.
  63459. // Everything stored in var log instead of writing separate lines to support only writing in exception,
  63460. // and avoid problems with multiple concurrent .babylon loads.
  63461. var log = "importMesh has failed JSON parse";
  63462. try {
  63463. var parsedData = JSON.parse(data);
  63464. log = "";
  63465. var fullDetails = BABYLON.SceneLoader.loggingLevel === BABYLON.SceneLoader.DETAILED_LOGGING;
  63466. if (!meshesNames) {
  63467. meshesNames = null;
  63468. }
  63469. else if (!Array.isArray(meshesNames)) {
  63470. meshesNames = [meshesNames];
  63471. }
  63472. var hierarchyIds = new Array();
  63473. if (parsedData.meshes !== undefined && parsedData.meshes !== null) {
  63474. var loadedSkeletonsIds = [];
  63475. var loadedMaterialsIds = [];
  63476. var index;
  63477. var cache;
  63478. for (index = 0, cache = parsedData.meshes.length; index < cache; index++) {
  63479. var parsedMesh = parsedData.meshes[index];
  63480. if (meshesNames === null || isDescendantOf(parsedMesh, meshesNames, hierarchyIds)) {
  63481. if (meshesNames !== null) {
  63482. // Remove found mesh name from list.
  63483. delete meshesNames[meshesNames.indexOf(parsedMesh.name)];
  63484. }
  63485. //Geometry?
  63486. if (parsedMesh.geometryId !== undefined && parsedMesh.geometryId !== null) {
  63487. //does the file contain geometries?
  63488. if (parsedData.geometries !== undefined && parsedData.geometries !== null) {
  63489. //find the correct geometry and add it to the scene
  63490. var found = false;
  63491. ["boxes", "spheres", "cylinders", "toruses", "grounds", "planes", "torusKnots", "vertexData"].forEach(function (geometryType) {
  63492. if (found === true || !parsedData.geometries[geometryType] || !(Array.isArray(parsedData.geometries[geometryType]))) {
  63493. return;
  63494. }
  63495. else {
  63496. parsedData.geometries[geometryType].forEach(function (parsedGeometryData) {
  63497. if (parsedGeometryData.id === parsedMesh.geometryId) {
  63498. switch (geometryType) {
  63499. case "boxes":
  63500. BABYLON.BoxGeometry.Parse(parsedGeometryData, scene);
  63501. break;
  63502. case "spheres":
  63503. BABYLON.SphereGeometry.Parse(parsedGeometryData, scene);
  63504. break;
  63505. case "cylinders":
  63506. BABYLON.CylinderGeometry.Parse(parsedGeometryData, scene);
  63507. break;
  63508. case "toruses":
  63509. BABYLON.TorusGeometry.Parse(parsedGeometryData, scene);
  63510. break;
  63511. case "grounds":
  63512. BABYLON.GroundGeometry.Parse(parsedGeometryData, scene);
  63513. break;
  63514. case "planes":
  63515. BABYLON.PlaneGeometry.Parse(parsedGeometryData, scene);
  63516. break;
  63517. case "torusKnots":
  63518. BABYLON.TorusKnotGeometry.Parse(parsedGeometryData, scene);
  63519. break;
  63520. case "vertexData":
  63521. BABYLON.Geometry.Parse(parsedGeometryData, scene, rootUrl);
  63522. break;
  63523. }
  63524. found = true;
  63525. }
  63526. });
  63527. }
  63528. });
  63529. if (found === false) {
  63530. BABYLON.Tools.Warn("Geometry not found for mesh " + parsedMesh.id);
  63531. }
  63532. }
  63533. }
  63534. // Material ?
  63535. if (parsedMesh.materialId) {
  63536. var materialFound = (loadedMaterialsIds.indexOf(parsedMesh.materialId) !== -1);
  63537. if (materialFound === false && parsedData.multiMaterials !== undefined && parsedData.multiMaterials !== null) {
  63538. for (var multimatIndex = 0, multimatCache = parsedData.multiMaterials.length; multimatIndex < multimatCache; multimatIndex++) {
  63539. var parsedMultiMaterial = parsedData.multiMaterials[multimatIndex];
  63540. if (parsedMultiMaterial.id === parsedMesh.materialId) {
  63541. for (var matIndex = 0, matCache = parsedMultiMaterial.materials.length; matIndex < matCache; matIndex++) {
  63542. var subMatId = parsedMultiMaterial.materials[matIndex];
  63543. loadedMaterialsIds.push(subMatId);
  63544. var mat = parseMaterialById(subMatId, parsedData, scene, rootUrl);
  63545. if (mat) {
  63546. log += "\n\tMaterial " + mat.toString(fullDetails);
  63547. }
  63548. }
  63549. loadedMaterialsIds.push(parsedMultiMaterial.id);
  63550. var mmat = BABYLON.Material.ParseMultiMaterial(parsedMultiMaterial, scene);
  63551. if (mmat) {
  63552. materialFound = true;
  63553. log += "\n\tMulti-Material " + mmat.toString(fullDetails);
  63554. }
  63555. break;
  63556. }
  63557. }
  63558. }
  63559. if (materialFound === false) {
  63560. loadedMaterialsIds.push(parsedMesh.materialId);
  63561. var mat = parseMaterialById(parsedMesh.materialId, parsedData, scene, rootUrl);
  63562. if (!mat) {
  63563. BABYLON.Tools.Warn("Material not found for mesh " + parsedMesh.id);
  63564. }
  63565. else {
  63566. log += "\n\tMaterial " + mat.toString(fullDetails);
  63567. }
  63568. }
  63569. }
  63570. // Skeleton ?
  63571. if (parsedMesh.skeletonId > -1 && parsedData.skeletons !== undefined && parsedData.skeletons !== null) {
  63572. var skeletonAlreadyLoaded = (loadedSkeletonsIds.indexOf(parsedMesh.skeletonId) > -1);
  63573. if (skeletonAlreadyLoaded === false) {
  63574. for (var skeletonIndex = 0, skeletonCache = parsedData.skeletons.length; skeletonIndex < skeletonCache; skeletonIndex++) {
  63575. var parsedSkeleton = parsedData.skeletons[skeletonIndex];
  63576. if (parsedSkeleton.id === parsedMesh.skeletonId) {
  63577. var skeleton = BABYLON.Skeleton.Parse(parsedSkeleton, scene);
  63578. skeletons.push(skeleton);
  63579. loadedSkeletonsIds.push(parsedSkeleton.id);
  63580. log += "\n\tSkeleton " + skeleton.toString(fullDetails);
  63581. }
  63582. }
  63583. }
  63584. }
  63585. var mesh = BABYLON.Mesh.Parse(parsedMesh, scene, rootUrl);
  63586. meshes.push(mesh);
  63587. log += "\n\tMesh " + mesh.toString(fullDetails);
  63588. }
  63589. }
  63590. // Connecting parents
  63591. var currentMesh;
  63592. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  63593. currentMesh = scene.meshes[index];
  63594. if (currentMesh._waitingParentId) {
  63595. currentMesh.parent = scene.getLastEntryByID(currentMesh._waitingParentId);
  63596. currentMesh._waitingParentId = null;
  63597. }
  63598. }
  63599. // freeze and compute world matrix application
  63600. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  63601. currentMesh = scene.meshes[index];
  63602. if (currentMesh._waitingFreezeWorldMatrix) {
  63603. currentMesh.freezeWorldMatrix();
  63604. currentMesh._waitingFreezeWorldMatrix = null;
  63605. }
  63606. else {
  63607. currentMesh.computeWorldMatrix(true);
  63608. }
  63609. }
  63610. }
  63611. // Particles
  63612. if (parsedData.particleSystems !== undefined && parsedData.particleSystems !== null) {
  63613. for (index = 0, cache = parsedData.particleSystems.length; index < cache; index++) {
  63614. var parsedParticleSystem = parsedData.particleSystems[index];
  63615. if (hierarchyIds.indexOf(parsedParticleSystem.emitterId) !== -1) {
  63616. particleSystems.push(BABYLON.ParticleSystem.Parse(parsedParticleSystem, scene, rootUrl));
  63617. }
  63618. }
  63619. }
  63620. return true;
  63621. }
  63622. catch (err) {
  63623. var msg = logOperation("importMesh", parsedData ? parsedData.producer : "Unknown") + log;
  63624. if (onError) {
  63625. onError(msg, err);
  63626. }
  63627. else {
  63628. BABYLON.Tools.Log(msg);
  63629. throw err;
  63630. }
  63631. }
  63632. finally {
  63633. if (log !== null && BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.NO_LOGGING) {
  63634. BABYLON.Tools.Log(logOperation("importMesh", parsedData ? parsedData.producer : "Unknown") + (BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.MINIMAL_LOGGING ? log : ""));
  63635. }
  63636. }
  63637. return false;
  63638. },
  63639. load: function (scene, data, rootUrl, onError) {
  63640. // Entire method running in try block, so ALWAYS logs as far as it got, only actually writes details
  63641. // when SceneLoader.debugLogging = true (default), or exception encountered.
  63642. // Everything stored in var log instead of writing separate lines to support only writing in exception,
  63643. // and avoid problems with multiple concurrent .babylon loads.
  63644. var log = "importScene has failed JSON parse";
  63645. try {
  63646. var parsedData = JSON.parse(data);
  63647. log = "";
  63648. // Scene
  63649. if (parsedData.useDelayedTextureLoading !== undefined && parsedData.useDelayedTextureLoading !== null) {
  63650. scene.useDelayedTextureLoading = parsedData.useDelayedTextureLoading && !BABYLON.SceneLoader.ForceFullSceneLoadingForIncremental;
  63651. }
  63652. if (parsedData.autoClear !== undefined && parsedData.autoClear !== null) {
  63653. scene.autoClear = parsedData.autoClear;
  63654. }
  63655. if (parsedData.clearColor !== undefined && parsedData.clearColor !== null) {
  63656. scene.clearColor = BABYLON.Color4.FromArray(parsedData.clearColor);
  63657. }
  63658. if (parsedData.ambientColor !== undefined && parsedData.ambientColor !== null) {
  63659. scene.ambientColor = BABYLON.Color3.FromArray(parsedData.ambientColor);
  63660. }
  63661. if (parsedData.gravity !== undefined && parsedData.gravity !== null) {
  63662. scene.gravity = BABYLON.Vector3.FromArray(parsedData.gravity);
  63663. }
  63664. // Fog
  63665. if (parsedData.fogMode && parsedData.fogMode !== 0) {
  63666. scene.fogMode = parsedData.fogMode;
  63667. scene.fogColor = BABYLON.Color3.FromArray(parsedData.fogColor);
  63668. scene.fogStart = parsedData.fogStart;
  63669. scene.fogEnd = parsedData.fogEnd;
  63670. scene.fogDensity = parsedData.fogDensity;
  63671. log += "\tFog mode for scene: ";
  63672. switch (scene.fogMode) {
  63673. // getters not compiling, so using hardcoded
  63674. case 1:
  63675. log += "exp\n";
  63676. break;
  63677. case 2:
  63678. log += "exp2\n";
  63679. break;
  63680. case 3:
  63681. log += "linear\n";
  63682. break;
  63683. }
  63684. }
  63685. //Physics
  63686. if (parsedData.physicsEnabled) {
  63687. var physicsPlugin;
  63688. if (parsedData.physicsEngine === "cannon") {
  63689. physicsPlugin = new BABYLON.CannonJSPlugin();
  63690. }
  63691. else if (parsedData.physicsEngine === "oimo") {
  63692. physicsPlugin = new BABYLON.OimoJSPlugin();
  63693. }
  63694. log = "\tPhysics engine " + (parsedData.physicsEngine ? parsedData.physicsEngine : "oimo") + " enabled\n";
  63695. //else - default engine, which is currently oimo
  63696. var physicsGravity = parsedData.physicsGravity ? BABYLON.Vector3.FromArray(parsedData.physicsGravity) : null;
  63697. scene.enablePhysics(physicsGravity, physicsPlugin);
  63698. }
  63699. // Metadata
  63700. if (parsedData.metadata !== undefined && parsedData.metadata !== null) {
  63701. scene.metadata = parsedData.metadata;
  63702. }
  63703. //collisions, if defined. otherwise, default is true
  63704. if (parsedData.collisionsEnabled !== undefined && parsedData.collisionsEnabled !== null) {
  63705. scene.collisionsEnabled = parsedData.collisionsEnabled;
  63706. }
  63707. scene.workerCollisions = !!parsedData.workerCollisions;
  63708. var container = loadAssetContainer(scene, data, rootUrl, onError, true);
  63709. if (!container) {
  63710. return false;
  63711. }
  63712. if (parsedData.autoAnimate) {
  63713. scene.beginAnimation(scene, parsedData.autoAnimateFrom, parsedData.autoAnimateTo, parsedData.autoAnimateLoop, parsedData.autoAnimateSpeed || 1.0);
  63714. }
  63715. if (parsedData.activeCameraID !== undefined && parsedData.activeCameraID !== null) {
  63716. scene.setActiveCameraByID(parsedData.activeCameraID);
  63717. }
  63718. // Environment texture
  63719. if (parsedData.environmentTexture !== undefined && parsedData.environmentTexture !== null) {
  63720. scene.environmentTexture = BABYLON.CubeTexture.CreateFromPrefilteredData(rootUrl + parsedData.environmentTexture, scene);
  63721. if (parsedData.createDefaultSkybox === true) {
  63722. var skyboxScale = (scene.activeCamera !== undefined && scene.activeCamera !== null) ? (scene.activeCamera.maxZ - scene.activeCamera.minZ) / 2 : 1000;
  63723. var skyboxBlurLevel = parsedData.skyboxBlurLevel || 0;
  63724. scene.createDefaultSkybox(undefined, true, skyboxScale, skyboxBlurLevel);
  63725. }
  63726. }
  63727. // Finish
  63728. return true;
  63729. }
  63730. catch (err) {
  63731. var msg = logOperation("importScene", parsedData ? parsedData.producer : "Unknown") + log;
  63732. if (onError) {
  63733. onError(msg, err);
  63734. }
  63735. else {
  63736. BABYLON.Tools.Log(msg);
  63737. throw err;
  63738. }
  63739. }
  63740. finally {
  63741. if (log !== null && BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.NO_LOGGING) {
  63742. BABYLON.Tools.Log(logOperation("importScene", parsedData ? parsedData.producer : "Unknown") + (BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.MINIMAL_LOGGING ? log : ""));
  63743. }
  63744. }
  63745. return false;
  63746. },
  63747. loadAssetContainer: function (scene, data, rootUrl, onError) {
  63748. var container = loadAssetContainer(scene, data, rootUrl, onError);
  63749. return container;
  63750. }
  63751. });
  63752. })(BABYLON || (BABYLON = {}));
  63753. //# sourceMappingURL=babylon.babylonFileLoader.js.map
  63754. "use strict";
  63755. var BABYLON;
  63756. (function (BABYLON) {
  63757. var FilesInput = /** @class */ (function () {
  63758. function FilesInput(engine, scene, sceneLoadedCallback, progressCallback, additionalRenderLoopLogicCallback, textureLoadingCallback, startingProcessingFilesCallback, onReloadCallback, errorCallback) {
  63759. this.onProcessFileCallback = function () { return true; };
  63760. this._engine = engine;
  63761. this._currentScene = scene;
  63762. this._sceneLoadedCallback = sceneLoadedCallback;
  63763. this._progressCallback = progressCallback;
  63764. this._additionalRenderLoopLogicCallback = additionalRenderLoopLogicCallback;
  63765. this._textureLoadingCallback = textureLoadingCallback;
  63766. this._startingProcessingFilesCallback = startingProcessingFilesCallback;
  63767. this._onReloadCallback = onReloadCallback;
  63768. this._errorCallback = errorCallback;
  63769. }
  63770. FilesInput.prototype.monitorElementForDragNDrop = function (elementToMonitor) {
  63771. var _this = this;
  63772. if (elementToMonitor) {
  63773. this._elementToMonitor = elementToMonitor;
  63774. this._dragEnterHandler = function (e) { _this.drag(e); };
  63775. this._dragOverHandler = function (e) { _this.drag(e); };
  63776. this._dropHandler = function (e) { _this.drop(e); };
  63777. this._elementToMonitor.addEventListener("dragenter", this._dragEnterHandler, false);
  63778. this._elementToMonitor.addEventListener("dragover", this._dragOverHandler, false);
  63779. this._elementToMonitor.addEventListener("drop", this._dropHandler, false);
  63780. }
  63781. };
  63782. FilesInput.prototype.dispose = function () {
  63783. if (!this._elementToMonitor) {
  63784. return;
  63785. }
  63786. this._elementToMonitor.removeEventListener("dragenter", this._dragEnterHandler);
  63787. this._elementToMonitor.removeEventListener("dragover", this._dragOverHandler);
  63788. this._elementToMonitor.removeEventListener("drop", this._dropHandler);
  63789. };
  63790. FilesInput.prototype.renderFunction = function () {
  63791. if (this._additionalRenderLoopLogicCallback) {
  63792. this._additionalRenderLoopLogicCallback();
  63793. }
  63794. if (this._currentScene) {
  63795. if (this._textureLoadingCallback) {
  63796. var remaining = this._currentScene.getWaitingItemsCount();
  63797. if (remaining > 0) {
  63798. this._textureLoadingCallback(remaining);
  63799. }
  63800. }
  63801. this._currentScene.render();
  63802. }
  63803. };
  63804. FilesInput.prototype.drag = function (e) {
  63805. e.stopPropagation();
  63806. e.preventDefault();
  63807. };
  63808. FilesInput.prototype.drop = function (eventDrop) {
  63809. eventDrop.stopPropagation();
  63810. eventDrop.preventDefault();
  63811. this.loadFiles(eventDrop);
  63812. };
  63813. FilesInput.prototype._traverseFolder = function (folder, files, remaining, callback) {
  63814. var _this = this;
  63815. var reader = folder.createReader();
  63816. var relativePath = folder.fullPath.replace(/^\//, "").replace(/(.+?)\/?$/, "$1/");
  63817. reader.readEntries(function (entries) {
  63818. remaining.count += entries.length;
  63819. for (var _i = 0, entries_1 = entries; _i < entries_1.length; _i++) {
  63820. var entry = entries_1[_i];
  63821. if (entry.isFile) {
  63822. entry.file(function (file) {
  63823. file.correctName = relativePath + file.name;
  63824. files.push(file);
  63825. if (--remaining.count === 0) {
  63826. callback();
  63827. }
  63828. });
  63829. }
  63830. else if (entry.isDirectory) {
  63831. _this._traverseFolder(entry, files, remaining, callback);
  63832. }
  63833. }
  63834. if (--remaining.count) {
  63835. callback();
  63836. }
  63837. });
  63838. };
  63839. FilesInput.prototype._processFiles = function (files) {
  63840. for (var i = 0; i < files.length; i++) {
  63841. var name = files[i].correctName.toLowerCase();
  63842. var extension = name.split('.').pop();
  63843. if (!this.onProcessFileCallback(files[i], name, extension)) {
  63844. continue;
  63845. }
  63846. if ((extension === "babylon" || extension === "stl" || extension === "obj" || extension === "gltf" || extension === "glb")
  63847. && name.indexOf(".binary.babylon") === -1 && name.indexOf(".incremental.babylon") === -1) {
  63848. this._sceneFileToLoad = files[i];
  63849. }
  63850. else {
  63851. FilesInput.FilesToLoad[name] = files[i];
  63852. }
  63853. }
  63854. };
  63855. FilesInput.prototype.loadFiles = function (event) {
  63856. var _this = this;
  63857. if (this._startingProcessingFilesCallback)
  63858. this._startingProcessingFilesCallback();
  63859. // Handling data transfer via drag'n'drop
  63860. if (event && event.dataTransfer && event.dataTransfer.files) {
  63861. this._filesToLoad = event.dataTransfer.files;
  63862. }
  63863. // Handling files from input files
  63864. if (event && event.target && event.target.files) {
  63865. this._filesToLoad = event.target.files;
  63866. }
  63867. if (this._filesToLoad && this._filesToLoad.length > 0) {
  63868. var files_1 = new Array();
  63869. var folders = [];
  63870. var items = event.dataTransfer ? event.dataTransfer.items : null;
  63871. for (var i = 0; i < this._filesToLoad.length; i++) {
  63872. var fileToLoad = this._filesToLoad[i];
  63873. var name_1 = fileToLoad.name.toLowerCase();
  63874. var entry = void 0;
  63875. fileToLoad.correctName = name_1;
  63876. if (items) {
  63877. var item = items[i];
  63878. if (item.getAsEntry) {
  63879. entry = item.getAsEntry();
  63880. }
  63881. else if (item.webkitGetAsEntry) {
  63882. entry = item.webkitGetAsEntry();
  63883. }
  63884. }
  63885. if (!entry) {
  63886. files_1.push(fileToLoad);
  63887. }
  63888. else {
  63889. if (entry.isDirectory) {
  63890. folders.push(entry);
  63891. }
  63892. else {
  63893. files_1.push(fileToLoad);
  63894. }
  63895. }
  63896. }
  63897. if (folders.length === 0) {
  63898. this._processFiles(files_1);
  63899. this._processReload();
  63900. }
  63901. else {
  63902. var remaining = { count: folders.length };
  63903. for (var _i = 0, folders_1 = folders; _i < folders_1.length; _i++) {
  63904. var folder = folders_1[_i];
  63905. this._traverseFolder(folder, files_1, remaining, function () {
  63906. _this._processFiles(files_1);
  63907. if (remaining.count === 0) {
  63908. _this._processReload();
  63909. }
  63910. });
  63911. }
  63912. }
  63913. }
  63914. };
  63915. FilesInput.prototype._processReload = function () {
  63916. if (this._onReloadCallback) {
  63917. this._onReloadCallback(this._sceneFileToLoad);
  63918. }
  63919. else {
  63920. this.reload();
  63921. }
  63922. };
  63923. FilesInput.prototype.reload = function () {
  63924. var _this = this;
  63925. // If a scene file has been provided
  63926. if (this._sceneFileToLoad) {
  63927. if (this._currentScene) {
  63928. if (BABYLON.Tools.errorsCount > 0) {
  63929. BABYLON.Tools.ClearLogCache();
  63930. }
  63931. this._engine.stopRenderLoop();
  63932. this._currentScene.dispose();
  63933. }
  63934. BABYLON.SceneLoader.LoadAsync("file:", this._sceneFileToLoad, this._engine, function (progress) {
  63935. if (_this._progressCallback) {
  63936. _this._progressCallback(progress);
  63937. }
  63938. }).then(function (scene) {
  63939. _this._currentScene = scene;
  63940. if (_this._sceneLoadedCallback) {
  63941. _this._sceneLoadedCallback(_this._sceneFileToLoad, _this._currentScene);
  63942. }
  63943. // Wait for textures and shaders to be ready
  63944. _this._currentScene.executeWhenReady(function () {
  63945. _this._engine.runRenderLoop(function () {
  63946. _this.renderFunction();
  63947. });
  63948. });
  63949. }).catch(function (error) {
  63950. if (_this._errorCallback) {
  63951. _this._errorCallback(_this._sceneFileToLoad, _this._currentScene, error.message);
  63952. }
  63953. });
  63954. }
  63955. else {
  63956. BABYLON.Tools.Error("Please provide a valid .babylon file.");
  63957. }
  63958. };
  63959. FilesInput.FilesToLoad = {};
  63960. return FilesInput;
  63961. }());
  63962. BABYLON.FilesInput = FilesInput;
  63963. })(BABYLON || (BABYLON = {}));
  63964. //# sourceMappingURL=babylon.filesInput.js.map
  63965. "use strict";
  63966. var BABYLON;
  63967. (function (BABYLON) {
  63968. /**
  63969. * This class implement a typical dictionary using a string as key and the generic type T as value.
  63970. * The underlying implementation relies on an associative array to ensure the best performances.
  63971. * The value can be anything including 'null' but except 'undefined'
  63972. */
  63973. var StringDictionary = /** @class */ (function () {
  63974. function StringDictionary() {
  63975. this._count = 0;
  63976. this._data = {};
  63977. }
  63978. /**
  63979. * This will clear this dictionary and copy the content from the 'source' one.
  63980. * If the T value is a custom object, it won't be copied/cloned, the same object will be used
  63981. * @param source the dictionary to take the content from and copy to this dictionary
  63982. */
  63983. StringDictionary.prototype.copyFrom = function (source) {
  63984. var _this = this;
  63985. this.clear();
  63986. source.forEach(function (t, v) { return _this.add(t, v); });
  63987. };
  63988. /**
  63989. * Get a value based from its key
  63990. * @param key the given key to get the matching value from
  63991. * @return the value if found, otherwise undefined is returned
  63992. */
  63993. StringDictionary.prototype.get = function (key) {
  63994. var val = this._data[key];
  63995. if (val !== undefined) {
  63996. return val;
  63997. }
  63998. return undefined;
  63999. };
  64000. /**
  64001. * Get a value from its key or add it if it doesn't exist.
  64002. * This method will ensure you that a given key/data will be present in the dictionary.
  64003. * @param key the given key to get the matching value from
  64004. * @param factory the factory that will create the value if the key is not present in the dictionary.
  64005. * The factory will only be invoked if there's no data for the given key.
  64006. * @return the value corresponding to the key.
  64007. */
  64008. StringDictionary.prototype.getOrAddWithFactory = function (key, factory) {
  64009. var val = this.get(key);
  64010. if (val !== undefined) {
  64011. return val;
  64012. }
  64013. val = factory(key);
  64014. if (val) {
  64015. this.add(key, val);
  64016. }
  64017. return val;
  64018. };
  64019. /**
  64020. * Get a value from its key if present in the dictionary otherwise add it
  64021. * @param key the key to get the value from
  64022. * @param val if there's no such key/value pair in the dictionary add it with this value
  64023. * @return the value corresponding to the key
  64024. */
  64025. StringDictionary.prototype.getOrAdd = function (key, val) {
  64026. var curVal = this.get(key);
  64027. if (curVal !== undefined) {
  64028. return curVal;
  64029. }
  64030. this.add(key, val);
  64031. return val;
  64032. };
  64033. /**
  64034. * Check if there's a given key in the dictionary
  64035. * @param key the key to check for
  64036. * @return true if the key is present, false otherwise
  64037. */
  64038. StringDictionary.prototype.contains = function (key) {
  64039. return this._data[key] !== undefined;
  64040. };
  64041. /**
  64042. * Add a new key and its corresponding value
  64043. * @param key the key to add
  64044. * @param value the value corresponding to the key
  64045. * @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
  64046. */
  64047. StringDictionary.prototype.add = function (key, value) {
  64048. if (this._data[key] !== undefined) {
  64049. return false;
  64050. }
  64051. this._data[key] = value;
  64052. ++this._count;
  64053. return true;
  64054. };
  64055. StringDictionary.prototype.set = function (key, value) {
  64056. if (this._data[key] === undefined) {
  64057. return false;
  64058. }
  64059. this._data[key] = value;
  64060. return true;
  64061. };
  64062. /**
  64063. * Get the element of the given key and remove it from the dictionary
  64064. * @param key
  64065. */
  64066. StringDictionary.prototype.getAndRemove = function (key) {
  64067. var val = this.get(key);
  64068. if (val !== undefined) {
  64069. delete this._data[key];
  64070. --this._count;
  64071. return val;
  64072. }
  64073. return null;
  64074. };
  64075. /**
  64076. * Remove a key/value from the dictionary.
  64077. * @param key the key to remove
  64078. * @return true if the item was successfully deleted, false if no item with such key exist in the dictionary
  64079. */
  64080. StringDictionary.prototype.remove = function (key) {
  64081. if (this.contains(key)) {
  64082. delete this._data[key];
  64083. --this._count;
  64084. return true;
  64085. }
  64086. return false;
  64087. };
  64088. /**
  64089. * Clear the whole content of the dictionary
  64090. */
  64091. StringDictionary.prototype.clear = function () {
  64092. this._data = {};
  64093. this._count = 0;
  64094. };
  64095. Object.defineProperty(StringDictionary.prototype, "count", {
  64096. get: function () {
  64097. return this._count;
  64098. },
  64099. enumerable: true,
  64100. configurable: true
  64101. });
  64102. /**
  64103. * Execute a callback on each key/val of the dictionary.
  64104. * Note that you can remove any element in this dictionary in the callback implementation
  64105. * @param callback the callback to execute on a given key/value pair
  64106. */
  64107. StringDictionary.prototype.forEach = function (callback) {
  64108. for (var cur in this._data) {
  64109. var val = this._data[cur];
  64110. callback(cur, val);
  64111. }
  64112. };
  64113. /**
  64114. * Execute a callback on every occurrence of the dictionary until it returns a valid TRes object.
  64115. * If the callback returns null or undefined the method will iterate to the next key/value pair
  64116. * Note that you can remove any element in this dictionary in the callback implementation
  64117. * @param callback the callback to execute, if it return a valid T instanced object the enumeration will stop and the object will be returned
  64118. */
  64119. StringDictionary.prototype.first = function (callback) {
  64120. for (var cur in this._data) {
  64121. var val = this._data[cur];
  64122. var res = callback(cur, val);
  64123. if (res) {
  64124. return res;
  64125. }
  64126. }
  64127. return null;
  64128. };
  64129. return StringDictionary;
  64130. }());
  64131. BABYLON.StringDictionary = StringDictionary;
  64132. })(BABYLON || (BABYLON = {}));
  64133. //# sourceMappingURL=babylon.stringDictionary.js.map
  64134. "use strict";
  64135. var BABYLON;
  64136. (function (BABYLON) {
  64137. var Tags = /** @class */ (function () {
  64138. function Tags() {
  64139. }
  64140. Tags.EnableFor = function (obj) {
  64141. obj._tags = obj._tags || {};
  64142. obj.hasTags = function () {
  64143. return Tags.HasTags(obj);
  64144. };
  64145. obj.addTags = function (tagsString) {
  64146. return Tags.AddTagsTo(obj, tagsString);
  64147. };
  64148. obj.removeTags = function (tagsString) {
  64149. return Tags.RemoveTagsFrom(obj, tagsString);
  64150. };
  64151. obj.matchesTagsQuery = function (tagsQuery) {
  64152. return Tags.MatchesQuery(obj, tagsQuery);
  64153. };
  64154. };
  64155. Tags.DisableFor = function (obj) {
  64156. delete obj._tags;
  64157. delete obj.hasTags;
  64158. delete obj.addTags;
  64159. delete obj.removeTags;
  64160. delete obj.matchesTagsQuery;
  64161. };
  64162. Tags.HasTags = function (obj) {
  64163. if (!obj._tags) {
  64164. return false;
  64165. }
  64166. return !BABYLON.Tools.IsEmpty(obj._tags);
  64167. };
  64168. Tags.GetTags = function (obj, asString) {
  64169. if (asString === void 0) { asString = true; }
  64170. if (!obj._tags) {
  64171. return null;
  64172. }
  64173. if (asString) {
  64174. var tagsArray = [];
  64175. for (var tag in obj._tags) {
  64176. if (obj._tags.hasOwnProperty(tag) && obj._tags[tag] === true) {
  64177. tagsArray.push(tag);
  64178. }
  64179. }
  64180. return tagsArray.join(" ");
  64181. }
  64182. else {
  64183. return obj._tags;
  64184. }
  64185. };
  64186. // the tags 'true' and 'false' are reserved and cannot be used as tags
  64187. // a tag cannot start with '||', '&&', and '!'
  64188. // it cannot contain whitespaces
  64189. Tags.AddTagsTo = function (obj, tagsString) {
  64190. if (!tagsString) {
  64191. return;
  64192. }
  64193. if (typeof tagsString !== "string") {
  64194. return;
  64195. }
  64196. var tags = tagsString.split(" ");
  64197. tags.forEach(function (tag, index, array) {
  64198. Tags._AddTagTo(obj, tag);
  64199. });
  64200. };
  64201. Tags._AddTagTo = function (obj, tag) {
  64202. tag = tag.trim();
  64203. if (tag === "" || tag === "true" || tag === "false") {
  64204. return;
  64205. }
  64206. if (tag.match(/[\s]/) || tag.match(/^([!]|([|]|[&]){2})/)) {
  64207. return;
  64208. }
  64209. Tags.EnableFor(obj);
  64210. obj._tags[tag] = true;
  64211. };
  64212. Tags.RemoveTagsFrom = function (obj, tagsString) {
  64213. if (!Tags.HasTags(obj)) {
  64214. return;
  64215. }
  64216. var tags = tagsString.split(" ");
  64217. for (var t in tags) {
  64218. Tags._RemoveTagFrom(obj, tags[t]);
  64219. }
  64220. };
  64221. Tags._RemoveTagFrom = function (obj, tag) {
  64222. delete obj._tags[tag];
  64223. };
  64224. Tags.MatchesQuery = function (obj, tagsQuery) {
  64225. if (tagsQuery === undefined) {
  64226. return true;
  64227. }
  64228. if (tagsQuery === "") {
  64229. return Tags.HasTags(obj);
  64230. }
  64231. return BABYLON.AndOrNotEvaluator.Eval(tagsQuery, function (r) { return Tags.HasTags(obj) && obj._tags[r]; });
  64232. };
  64233. return Tags;
  64234. }());
  64235. BABYLON.Tags = Tags;
  64236. })(BABYLON || (BABYLON = {}));
  64237. //# sourceMappingURL=babylon.tags.js.map
  64238. "use strict";
  64239. var BABYLON;
  64240. (function (BABYLON) {
  64241. var AndOrNotEvaluator = /** @class */ (function () {
  64242. function AndOrNotEvaluator() {
  64243. }
  64244. AndOrNotEvaluator.Eval = function (query, evaluateCallback) {
  64245. if (!query.match(/\([^\(\)]*\)/g)) {
  64246. query = AndOrNotEvaluator._HandleParenthesisContent(query, evaluateCallback);
  64247. }
  64248. else {
  64249. query = query.replace(/\([^\(\)]*\)/g, function (r) {
  64250. // remove parenthesis
  64251. r = r.slice(1, r.length - 1);
  64252. return AndOrNotEvaluator._HandleParenthesisContent(r, evaluateCallback);
  64253. });
  64254. }
  64255. if (query === "true") {
  64256. return true;
  64257. }
  64258. if (query === "false") {
  64259. return false;
  64260. }
  64261. return AndOrNotEvaluator.Eval(query, evaluateCallback);
  64262. };
  64263. AndOrNotEvaluator._HandleParenthesisContent = function (parenthesisContent, evaluateCallback) {
  64264. evaluateCallback = evaluateCallback || (function (r) {
  64265. return r === "true" ? true : false;
  64266. });
  64267. var result;
  64268. var or = parenthesisContent.split("||");
  64269. for (var i in or) {
  64270. if (or.hasOwnProperty(i)) {
  64271. var ori = AndOrNotEvaluator._SimplifyNegation(or[i].trim());
  64272. var and = ori.split("&&");
  64273. if (and.length > 1) {
  64274. for (var j = 0; j < and.length; ++j) {
  64275. var andj = AndOrNotEvaluator._SimplifyNegation(and[j].trim());
  64276. if (andj !== "true" && andj !== "false") {
  64277. if (andj[0] === "!") {
  64278. result = !evaluateCallback(andj.substring(1));
  64279. }
  64280. else {
  64281. result = evaluateCallback(andj);
  64282. }
  64283. }
  64284. else {
  64285. result = andj === "true" ? true : false;
  64286. }
  64287. if (!result) {
  64288. ori = "false";
  64289. break;
  64290. }
  64291. }
  64292. }
  64293. if (result || ori === "true") {
  64294. result = true;
  64295. break;
  64296. }
  64297. // result equals false (or undefined)
  64298. if (ori !== "true" && ori !== "false") {
  64299. if (ori[0] === "!") {
  64300. result = !evaluateCallback(ori.substring(1));
  64301. }
  64302. else {
  64303. result = evaluateCallback(ori);
  64304. }
  64305. }
  64306. else {
  64307. result = ori === "true" ? true : false;
  64308. }
  64309. }
  64310. }
  64311. // the whole parenthesis scope is replaced by 'true' or 'false'
  64312. return result ? "true" : "false";
  64313. };
  64314. AndOrNotEvaluator._SimplifyNegation = function (booleanString) {
  64315. booleanString = booleanString.replace(/^[\s!]+/, function (r) {
  64316. // remove whitespaces
  64317. r = r.replace(/[\s]/g, function () { return ""; });
  64318. return r.length % 2 ? "!" : "";
  64319. });
  64320. booleanString = booleanString.trim();
  64321. if (booleanString === "!true") {
  64322. booleanString = "false";
  64323. }
  64324. else if (booleanString === "!false") {
  64325. booleanString = "true";
  64326. }
  64327. return booleanString;
  64328. };
  64329. return AndOrNotEvaluator;
  64330. }());
  64331. BABYLON.AndOrNotEvaluator = AndOrNotEvaluator;
  64332. })(BABYLON || (BABYLON = {}));
  64333. //# sourceMappingURL=babylon.andOrNotEvaluator.js.map
  64334. "use strict";
  64335. var BABYLON;
  64336. (function (BABYLON) {
  64337. var Database = /** @class */ (function () {
  64338. function Database(urlToScene, callbackManifestChecked) {
  64339. // Handling various flavors of prefixed version of IndexedDB
  64340. this.idbFactory = (window.indexedDB || window.mozIndexedDB || window.webkitIndexedDB || window.msIndexedDB);
  64341. this.callbackManifestChecked = callbackManifestChecked;
  64342. this.currentSceneUrl = Database.ReturnFullUrlLocation(urlToScene);
  64343. this.db = null;
  64344. this._enableSceneOffline = false;
  64345. this._enableTexturesOffline = false;
  64346. this.manifestVersionFound = 0;
  64347. this.mustUpdateRessources = false;
  64348. this.hasReachedQuota = false;
  64349. if (!Database.IDBStorageEnabled) {
  64350. this.callbackManifestChecked(true);
  64351. }
  64352. else {
  64353. this.checkManifestFile();
  64354. }
  64355. }
  64356. Object.defineProperty(Database.prototype, "enableSceneOffline", {
  64357. get: function () {
  64358. return this._enableSceneOffline;
  64359. },
  64360. enumerable: true,
  64361. configurable: true
  64362. });
  64363. Object.defineProperty(Database.prototype, "enableTexturesOffline", {
  64364. get: function () {
  64365. return this._enableTexturesOffline;
  64366. },
  64367. enumerable: true,
  64368. configurable: true
  64369. });
  64370. Database.prototype.checkManifestFile = function () {
  64371. var _this = this;
  64372. var noManifestFile = function () {
  64373. _this._enableSceneOffline = false;
  64374. _this._enableTexturesOffline = false;
  64375. _this.callbackManifestChecked(false);
  64376. };
  64377. var timeStampUsed = false;
  64378. var manifestURL = this.currentSceneUrl + ".manifest";
  64379. var xhr = new XMLHttpRequest();
  64380. if (navigator.onLine) {
  64381. // Adding a timestamp to by-pass browsers' cache
  64382. timeStampUsed = true;
  64383. manifestURL = manifestURL + (manifestURL.match(/\?/) == null ? "?" : "&") + (new Date()).getTime();
  64384. }
  64385. xhr.open("GET", manifestURL, true);
  64386. xhr.addEventListener("load", function () {
  64387. if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, 1)) {
  64388. try {
  64389. var manifestFile = JSON.parse(xhr.response);
  64390. _this._enableSceneOffline = manifestFile.enableSceneOffline;
  64391. _this._enableTexturesOffline = manifestFile.enableTexturesOffline;
  64392. if (manifestFile.version && !isNaN(parseInt(manifestFile.version))) {
  64393. _this.manifestVersionFound = manifestFile.version;
  64394. }
  64395. if (_this.callbackManifestChecked) {
  64396. _this.callbackManifestChecked(true);
  64397. }
  64398. }
  64399. catch (ex) {
  64400. noManifestFile();
  64401. }
  64402. }
  64403. else {
  64404. noManifestFile();
  64405. }
  64406. }, false);
  64407. xhr.addEventListener("error", function (event) {
  64408. if (timeStampUsed) {
  64409. timeStampUsed = false;
  64410. // Let's retry without the timeStamp
  64411. // It could fail when coupled with HTML5 Offline API
  64412. var retryManifestURL = _this.currentSceneUrl + ".manifest";
  64413. xhr.open("GET", retryManifestURL, true);
  64414. xhr.send();
  64415. }
  64416. else {
  64417. noManifestFile();
  64418. }
  64419. }, false);
  64420. try {
  64421. xhr.send();
  64422. }
  64423. catch (ex) {
  64424. BABYLON.Tools.Error("Error on XHR send request.");
  64425. this.callbackManifestChecked(false);
  64426. }
  64427. };
  64428. Database.prototype.openAsync = function (successCallback, errorCallback) {
  64429. var _this = this;
  64430. var handleError = function () {
  64431. _this.isSupported = false;
  64432. if (errorCallback)
  64433. errorCallback();
  64434. };
  64435. if (!this.idbFactory || !(this._enableSceneOffline || this._enableTexturesOffline)) {
  64436. // Your browser doesn't support IndexedDB
  64437. this.isSupported = false;
  64438. if (errorCallback)
  64439. errorCallback();
  64440. }
  64441. else {
  64442. // If the DB hasn't been opened or created yet
  64443. if (!this.db) {
  64444. this.hasReachedQuota = false;
  64445. this.isSupported = true;
  64446. var request = this.idbFactory.open("babylonjs", 1);
  64447. // Could occur if user is blocking the quota for the DB and/or doesn't grant access to IndexedDB
  64448. request.onerror = function (event) {
  64449. handleError();
  64450. };
  64451. // executes when a version change transaction cannot complete due to other active transactions
  64452. request.onblocked = function (event) {
  64453. BABYLON.Tools.Error("IDB request blocked. Please reload the page.");
  64454. handleError();
  64455. };
  64456. // DB has been opened successfully
  64457. request.onsuccess = function (event) {
  64458. _this.db = request.result;
  64459. successCallback();
  64460. };
  64461. // Initialization of the DB. Creating Scenes & Textures stores
  64462. request.onupgradeneeded = function (event) {
  64463. _this.db = (event.target).result;
  64464. if (_this.db) {
  64465. try {
  64466. _this.db.createObjectStore("scenes", { keyPath: "sceneUrl" });
  64467. _this.db.createObjectStore("versions", { keyPath: "sceneUrl" });
  64468. _this.db.createObjectStore("textures", { keyPath: "textureUrl" });
  64469. }
  64470. catch (ex) {
  64471. BABYLON.Tools.Error("Error while creating object stores. Exception: " + ex.message);
  64472. handleError();
  64473. }
  64474. }
  64475. };
  64476. }
  64477. else {
  64478. if (successCallback)
  64479. successCallback();
  64480. }
  64481. }
  64482. };
  64483. Database.prototype.loadImageFromDB = function (url, image) {
  64484. var _this = this;
  64485. var completeURL = Database.ReturnFullUrlLocation(url);
  64486. var saveAndLoadImage = function () {
  64487. if (!_this.hasReachedQuota && _this.db !== null) {
  64488. // the texture is not yet in the DB, let's try to save it
  64489. _this._saveImageIntoDBAsync(completeURL, image);
  64490. }
  64491. else {
  64492. image.src = url;
  64493. }
  64494. };
  64495. if (!this.mustUpdateRessources) {
  64496. this._loadImageFromDBAsync(completeURL, image, saveAndLoadImage);
  64497. }
  64498. else {
  64499. saveAndLoadImage();
  64500. }
  64501. };
  64502. Database.prototype._loadImageFromDBAsync = function (url, image, notInDBCallback) {
  64503. if (this.isSupported && this.db !== null) {
  64504. var texture;
  64505. var transaction = this.db.transaction(["textures"]);
  64506. transaction.onabort = function (event) {
  64507. image.src = url;
  64508. };
  64509. transaction.oncomplete = function (event) {
  64510. var blobTextureURL;
  64511. if (texture) {
  64512. var URL = window.URL || window.webkitURL;
  64513. blobTextureURL = URL.createObjectURL(texture.data, { oneTimeOnly: true });
  64514. image.onerror = function () {
  64515. BABYLON.Tools.Error("Error loading image from blob URL: " + blobTextureURL + " switching back to web url: " + url);
  64516. image.src = url;
  64517. };
  64518. image.src = blobTextureURL;
  64519. }
  64520. else {
  64521. notInDBCallback();
  64522. }
  64523. };
  64524. var getRequest = transaction.objectStore("textures").get(url);
  64525. getRequest.onsuccess = function (event) {
  64526. texture = (event.target).result;
  64527. };
  64528. getRequest.onerror = function (event) {
  64529. BABYLON.Tools.Error("Error loading texture " + url + " from DB.");
  64530. image.src = url;
  64531. };
  64532. }
  64533. else {
  64534. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  64535. image.src = url;
  64536. }
  64537. };
  64538. Database.prototype._saveImageIntoDBAsync = function (url, image) {
  64539. var _this = this;
  64540. if (this.isSupported) {
  64541. // In case of error (type not supported or quota exceeded), we're at least sending back XHR data to allow texture loading later on
  64542. var generateBlobUrl = function () {
  64543. var blobTextureURL;
  64544. if (blob) {
  64545. var URL = window.URL || window.webkitURL;
  64546. try {
  64547. blobTextureURL = URL.createObjectURL(blob, { oneTimeOnly: true });
  64548. }
  64549. // Chrome is raising a type error if we're setting the oneTimeOnly parameter
  64550. catch (ex) {
  64551. blobTextureURL = URL.createObjectURL(blob);
  64552. }
  64553. }
  64554. if (blobTextureURL) {
  64555. image.src = blobTextureURL;
  64556. }
  64557. };
  64558. if (Database.IsUASupportingBlobStorage) {
  64559. var xhr = new XMLHttpRequest(), blob;
  64560. xhr.open("GET", url, true);
  64561. xhr.responseType = "blob";
  64562. xhr.addEventListener("load", function () {
  64563. if (xhr.status === 200 && _this.db) {
  64564. // Blob as response (XHR2)
  64565. blob = xhr.response;
  64566. var transaction = _this.db.transaction(["textures"], "readwrite");
  64567. // the transaction could abort because of a QuotaExceededError error
  64568. transaction.onabort = function (event) {
  64569. try {
  64570. //backwards compatibility with ts 1.0, srcElement doesn't have an "error" according to ts 1.3
  64571. var srcElement = (event.srcElement || event.target);
  64572. var error = srcElement.error;
  64573. if (error && error.name === "QuotaExceededError") {
  64574. _this.hasReachedQuota = true;
  64575. }
  64576. }
  64577. catch (ex) { }
  64578. generateBlobUrl();
  64579. };
  64580. transaction.oncomplete = function (event) {
  64581. generateBlobUrl();
  64582. };
  64583. var newTexture = { textureUrl: url, data: blob };
  64584. try {
  64585. // Put the blob into the dabase
  64586. var addRequest = transaction.objectStore("textures").put(newTexture);
  64587. addRequest.onsuccess = function (event) {
  64588. };
  64589. addRequest.onerror = function (event) {
  64590. generateBlobUrl();
  64591. };
  64592. }
  64593. catch (ex) {
  64594. // "DataCloneError" generated by Chrome when you try to inject blob into IndexedDB
  64595. if (ex.code === 25) {
  64596. Database.IsUASupportingBlobStorage = false;
  64597. }
  64598. image.src = url;
  64599. }
  64600. }
  64601. else {
  64602. image.src = url;
  64603. }
  64604. }, false);
  64605. xhr.addEventListener("error", function (event) {
  64606. BABYLON.Tools.Error("Error in XHR request in BABYLON.Database.");
  64607. image.src = url;
  64608. }, false);
  64609. xhr.send();
  64610. }
  64611. else {
  64612. image.src = url;
  64613. }
  64614. }
  64615. else {
  64616. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  64617. image.src = url;
  64618. }
  64619. };
  64620. Database.prototype._checkVersionFromDB = function (url, versionLoaded) {
  64621. var _this = this;
  64622. var updateVersion = function () {
  64623. // the version is not yet in the DB or we need to update it
  64624. _this._saveVersionIntoDBAsync(url, versionLoaded);
  64625. };
  64626. this._loadVersionFromDBAsync(url, versionLoaded, updateVersion);
  64627. };
  64628. Database.prototype._loadVersionFromDBAsync = function (url, callback, updateInDBCallback) {
  64629. var _this = this;
  64630. if (this.isSupported && this.db) {
  64631. var version;
  64632. try {
  64633. var transaction = this.db.transaction(["versions"]);
  64634. transaction.oncomplete = function (event) {
  64635. if (version) {
  64636. // If the version in the JSON file is > than the version in DB
  64637. if (_this.manifestVersionFound > version.data) {
  64638. _this.mustUpdateRessources = true;
  64639. updateInDBCallback();
  64640. }
  64641. else {
  64642. callback(version.data);
  64643. }
  64644. }
  64645. else {
  64646. _this.mustUpdateRessources = true;
  64647. updateInDBCallback();
  64648. }
  64649. };
  64650. transaction.onabort = function (event) {
  64651. callback(-1);
  64652. };
  64653. var getRequest = transaction.objectStore("versions").get(url);
  64654. getRequest.onsuccess = function (event) {
  64655. version = (event.target).result;
  64656. };
  64657. getRequest.onerror = function (event) {
  64658. BABYLON.Tools.Error("Error loading version for scene " + url + " from DB.");
  64659. callback(-1);
  64660. };
  64661. }
  64662. catch (ex) {
  64663. BABYLON.Tools.Error("Error while accessing 'versions' object store (READ OP). Exception: " + ex.message);
  64664. callback(-1);
  64665. }
  64666. }
  64667. else {
  64668. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  64669. callback(-1);
  64670. }
  64671. };
  64672. Database.prototype._saveVersionIntoDBAsync = function (url, callback) {
  64673. var _this = this;
  64674. if (this.isSupported && !this.hasReachedQuota && this.db) {
  64675. try {
  64676. // Open a transaction to the database
  64677. var transaction = this.db.transaction(["versions"], "readwrite");
  64678. // the transaction could abort because of a QuotaExceededError error
  64679. transaction.onabort = function (event) {
  64680. try {
  64681. var error = event.srcElement['error'];
  64682. if (error && error.name === "QuotaExceededError") {
  64683. _this.hasReachedQuota = true;
  64684. }
  64685. }
  64686. catch (ex) { }
  64687. callback(-1);
  64688. };
  64689. transaction.oncomplete = function (event) {
  64690. callback(_this.manifestVersionFound);
  64691. };
  64692. var newVersion = { sceneUrl: url, data: this.manifestVersionFound };
  64693. // Put the scene into the database
  64694. var addRequest = transaction.objectStore("versions").put(newVersion);
  64695. addRequest.onsuccess = function (event) {
  64696. };
  64697. addRequest.onerror = function (event) {
  64698. BABYLON.Tools.Error("Error in DB add version request in BABYLON.Database.");
  64699. };
  64700. }
  64701. catch (ex) {
  64702. BABYLON.Tools.Error("Error while accessing 'versions' object store (WRITE OP). Exception: " + ex.message);
  64703. callback(-1);
  64704. }
  64705. }
  64706. else {
  64707. callback(-1);
  64708. }
  64709. };
  64710. Database.prototype.loadFileFromDB = function (url, sceneLoaded, progressCallBack, errorCallback, useArrayBuffer) {
  64711. var _this = this;
  64712. var completeUrl = Database.ReturnFullUrlLocation(url);
  64713. var saveAndLoadFile = function () {
  64714. // the scene is not yet in the DB, let's try to save it
  64715. _this._saveFileIntoDBAsync(completeUrl, sceneLoaded, progressCallBack);
  64716. };
  64717. this._checkVersionFromDB(completeUrl, function (version) {
  64718. if (version !== -1) {
  64719. if (!_this.mustUpdateRessources) {
  64720. _this._loadFileFromDBAsync(completeUrl, sceneLoaded, saveAndLoadFile, useArrayBuffer);
  64721. }
  64722. else {
  64723. _this._saveFileIntoDBAsync(completeUrl, sceneLoaded, progressCallBack, useArrayBuffer);
  64724. }
  64725. }
  64726. else {
  64727. if (errorCallback) {
  64728. errorCallback();
  64729. }
  64730. }
  64731. });
  64732. };
  64733. Database.prototype._loadFileFromDBAsync = function (url, callback, notInDBCallback, useArrayBuffer) {
  64734. if (this.isSupported && this.db) {
  64735. var targetStore;
  64736. if (url.indexOf(".babylon") !== -1) {
  64737. targetStore = "scenes";
  64738. }
  64739. else {
  64740. targetStore = "textures";
  64741. }
  64742. var file;
  64743. var transaction = this.db.transaction([targetStore]);
  64744. transaction.oncomplete = function (event) {
  64745. if (file) {
  64746. callback(file.data);
  64747. }
  64748. else {
  64749. notInDBCallback();
  64750. }
  64751. };
  64752. transaction.onabort = function (event) {
  64753. notInDBCallback();
  64754. };
  64755. var getRequest = transaction.objectStore(targetStore).get(url);
  64756. getRequest.onsuccess = function (event) {
  64757. file = (event.target).result;
  64758. };
  64759. getRequest.onerror = function (event) {
  64760. BABYLON.Tools.Error("Error loading file " + url + " from DB.");
  64761. notInDBCallback();
  64762. };
  64763. }
  64764. else {
  64765. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  64766. callback();
  64767. }
  64768. };
  64769. Database.prototype._saveFileIntoDBAsync = function (url, callback, progressCallback, useArrayBuffer) {
  64770. var _this = this;
  64771. if (this.isSupported) {
  64772. var targetStore;
  64773. if (url.indexOf(".babylon") !== -1) {
  64774. targetStore = "scenes";
  64775. }
  64776. else {
  64777. targetStore = "textures";
  64778. }
  64779. // Create XHR
  64780. var xhr = new XMLHttpRequest();
  64781. var fileData;
  64782. xhr.open("GET", url, true);
  64783. if (useArrayBuffer) {
  64784. xhr.responseType = "arraybuffer";
  64785. }
  64786. if (progressCallback) {
  64787. xhr.onprogress = progressCallback;
  64788. }
  64789. xhr.addEventListener("load", function () {
  64790. if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, !useArrayBuffer ? 1 : 6)) {
  64791. // Blob as response (XHR2)
  64792. //fileData = xhr.responseText;
  64793. fileData = !useArrayBuffer ? xhr.responseText : xhr.response;
  64794. if (!_this.hasReachedQuota && _this.db) {
  64795. // Open a transaction to the database
  64796. var transaction = _this.db.transaction([targetStore], "readwrite");
  64797. // the transaction could abort because of a QuotaExceededError error
  64798. transaction.onabort = function (event) {
  64799. try {
  64800. //backwards compatibility with ts 1.0, srcElement doesn't have an "error" according to ts 1.3
  64801. var error = event.srcElement['error'];
  64802. if (error && error.name === "QuotaExceededError") {
  64803. _this.hasReachedQuota = true;
  64804. }
  64805. }
  64806. catch (ex) { }
  64807. callback(fileData);
  64808. };
  64809. transaction.oncomplete = function (event) {
  64810. callback(fileData);
  64811. };
  64812. var newFile;
  64813. if (targetStore === "scenes") {
  64814. newFile = { sceneUrl: url, data: fileData, version: _this.manifestVersionFound };
  64815. }
  64816. else {
  64817. newFile = { textureUrl: url, data: fileData };
  64818. }
  64819. try {
  64820. // Put the scene into the database
  64821. var addRequest = transaction.objectStore(targetStore).put(newFile);
  64822. addRequest.onsuccess = function (event) {
  64823. };
  64824. addRequest.onerror = function (event) {
  64825. BABYLON.Tools.Error("Error in DB add file request in BABYLON.Database.");
  64826. };
  64827. }
  64828. catch (ex) {
  64829. callback(fileData);
  64830. }
  64831. }
  64832. else {
  64833. callback(fileData);
  64834. }
  64835. }
  64836. else {
  64837. callback();
  64838. }
  64839. }, false);
  64840. xhr.addEventListener("error", function (event) {
  64841. BABYLON.Tools.Error("error on XHR request.");
  64842. callback();
  64843. }, false);
  64844. xhr.send();
  64845. }
  64846. else {
  64847. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  64848. callback();
  64849. }
  64850. };
  64851. Database.IsUASupportingBlobStorage = true;
  64852. Database.IDBStorageEnabled = true;
  64853. Database.parseURL = function (url) {
  64854. var a = document.createElement('a');
  64855. a.href = url;
  64856. var urlWithoutHash = url.substring(0, url.lastIndexOf("#"));
  64857. var fileName = url.substring(urlWithoutHash.lastIndexOf("/") + 1, url.length);
  64858. var absLocation = url.substring(0, url.indexOf(fileName, 0));
  64859. return absLocation;
  64860. };
  64861. Database.ReturnFullUrlLocation = function (url) {
  64862. if (url.indexOf("http:/") === -1 && url.indexOf("https:/") === -1) {
  64863. return (Database.parseURL(window.location.href) + url);
  64864. }
  64865. else {
  64866. return url;
  64867. }
  64868. };
  64869. return Database;
  64870. }());
  64871. BABYLON.Database = Database;
  64872. })(BABYLON || (BABYLON = {}));
  64873. //# sourceMappingURL=babylon.database.js.map
  64874. "use strict";
  64875. var BABYLON;
  64876. (function (BABYLON) {
  64877. var FresnelParameters = /** @class */ (function () {
  64878. function FresnelParameters() {
  64879. this._isEnabled = true;
  64880. this.leftColor = BABYLON.Color3.White();
  64881. this.rightColor = BABYLON.Color3.Black();
  64882. this.bias = 0;
  64883. this.power = 1;
  64884. }
  64885. Object.defineProperty(FresnelParameters.prototype, "isEnabled", {
  64886. get: function () {
  64887. return this._isEnabled;
  64888. },
  64889. set: function (value) {
  64890. if (this._isEnabled === value) {
  64891. return;
  64892. }
  64893. this._isEnabled = value;
  64894. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.FresnelDirtyFlag | BABYLON.Material.MiscDirtyFlag);
  64895. },
  64896. enumerable: true,
  64897. configurable: true
  64898. });
  64899. FresnelParameters.prototype.clone = function () {
  64900. var newFresnelParameters = new FresnelParameters();
  64901. BABYLON.Tools.DeepCopy(this, newFresnelParameters);
  64902. return newFresnelParameters;
  64903. };
  64904. FresnelParameters.prototype.serialize = function () {
  64905. var serializationObject = {};
  64906. serializationObject.isEnabled = this.isEnabled;
  64907. serializationObject.leftColor = this.leftColor.asArray();
  64908. serializationObject.rightColor = this.rightColor.asArray();
  64909. serializationObject.bias = this.bias;
  64910. serializationObject.power = this.power;
  64911. return serializationObject;
  64912. };
  64913. FresnelParameters.Parse = function (parsedFresnelParameters) {
  64914. var fresnelParameters = new FresnelParameters();
  64915. fresnelParameters.isEnabled = parsedFresnelParameters.isEnabled;
  64916. fresnelParameters.leftColor = BABYLON.Color3.FromArray(parsedFresnelParameters.leftColor);
  64917. fresnelParameters.rightColor = BABYLON.Color3.FromArray(parsedFresnelParameters.rightColor);
  64918. fresnelParameters.bias = parsedFresnelParameters.bias;
  64919. fresnelParameters.power = parsedFresnelParameters.power || 1.0;
  64920. return fresnelParameters;
  64921. };
  64922. return FresnelParameters;
  64923. }());
  64924. BABYLON.FresnelParameters = FresnelParameters;
  64925. })(BABYLON || (BABYLON = {}));
  64926. //# sourceMappingURL=babylon.fresnelParameters.js.map
  64927. "use strict";
  64928. var BABYLON;
  64929. (function (BABYLON) {
  64930. var MultiMaterial = /** @class */ (function (_super) {
  64931. __extends(MultiMaterial, _super);
  64932. function MultiMaterial(name, scene) {
  64933. var _this = _super.call(this, name, scene, true) || this;
  64934. scene.multiMaterials.push(_this);
  64935. _this.subMaterials = new Array();
  64936. _this.storeEffectOnSubMeshes = true; // multimaterial is considered like a push material
  64937. return _this;
  64938. }
  64939. Object.defineProperty(MultiMaterial.prototype, "subMaterials", {
  64940. get: function () {
  64941. return this._subMaterials;
  64942. },
  64943. set: function (value) {
  64944. this._subMaterials = value;
  64945. this._hookArray(value);
  64946. },
  64947. enumerable: true,
  64948. configurable: true
  64949. });
  64950. MultiMaterial.prototype._hookArray = function (array) {
  64951. var _this = this;
  64952. var oldPush = array.push;
  64953. array.push = function () {
  64954. var items = [];
  64955. for (var _i = 0; _i < arguments.length; _i++) {
  64956. items[_i] = arguments[_i];
  64957. }
  64958. var result = oldPush.apply(array, items);
  64959. _this._markAllSubMeshesAsTexturesDirty();
  64960. return result;
  64961. };
  64962. var oldSplice = array.splice;
  64963. array.splice = function (index, deleteCount) {
  64964. var deleted = oldSplice.apply(array, [index, deleteCount]);
  64965. _this._markAllSubMeshesAsTexturesDirty();
  64966. return deleted;
  64967. };
  64968. };
  64969. // Properties
  64970. MultiMaterial.prototype.getSubMaterial = function (index) {
  64971. if (index < 0 || index >= this.subMaterials.length) {
  64972. return this.getScene().defaultMaterial;
  64973. }
  64974. return this.subMaterials[index];
  64975. };
  64976. MultiMaterial.prototype.getActiveTextures = function () {
  64977. return (_a = _super.prototype.getActiveTextures.call(this)).concat.apply(_a, this.subMaterials.map(function (subMaterial) {
  64978. if (subMaterial) {
  64979. return subMaterial.getActiveTextures();
  64980. }
  64981. else {
  64982. return [];
  64983. }
  64984. }));
  64985. var _a;
  64986. };
  64987. // Methods
  64988. MultiMaterial.prototype.getClassName = function () {
  64989. return "MultiMaterial";
  64990. };
  64991. MultiMaterial.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  64992. for (var index = 0; index < this.subMaterials.length; index++) {
  64993. var subMaterial = this.subMaterials[index];
  64994. if (subMaterial) {
  64995. if (subMaterial.storeEffectOnSubMeshes) {
  64996. if (!subMaterial.isReadyForSubMesh(mesh, subMesh, useInstances)) {
  64997. return false;
  64998. }
  64999. continue;
  65000. }
  65001. if (!subMaterial.isReady(mesh)) {
  65002. return false;
  65003. }
  65004. }
  65005. }
  65006. return true;
  65007. };
  65008. MultiMaterial.prototype.clone = function (name, cloneChildren) {
  65009. var newMultiMaterial = new MultiMaterial(name, this.getScene());
  65010. for (var index = 0; index < this.subMaterials.length; index++) {
  65011. var subMaterial = null;
  65012. var current = this.subMaterials[index];
  65013. if (cloneChildren && current) {
  65014. subMaterial = current.clone(name + "-" + current.name);
  65015. }
  65016. else {
  65017. subMaterial = this.subMaterials[index];
  65018. }
  65019. newMultiMaterial.subMaterials.push(subMaterial);
  65020. }
  65021. return newMultiMaterial;
  65022. };
  65023. MultiMaterial.prototype.serialize = function () {
  65024. var serializationObject = {};
  65025. serializationObject.name = this.name;
  65026. serializationObject.id = this.id;
  65027. if (BABYLON.Tags) {
  65028. serializationObject.tags = BABYLON.Tags.GetTags(this);
  65029. }
  65030. serializationObject.materials = [];
  65031. for (var matIndex = 0; matIndex < this.subMaterials.length; matIndex++) {
  65032. var subMat = this.subMaterials[matIndex];
  65033. if (subMat) {
  65034. serializationObject.materials.push(subMat.id);
  65035. }
  65036. else {
  65037. serializationObject.materials.push(null);
  65038. }
  65039. }
  65040. return serializationObject;
  65041. };
  65042. MultiMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  65043. var scene = this.getScene();
  65044. if (!scene) {
  65045. return;
  65046. }
  65047. var index = scene.multiMaterials.indexOf(this);
  65048. if (index >= 0) {
  65049. scene.multiMaterials.splice(index, 1);
  65050. }
  65051. _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);
  65052. };
  65053. return MultiMaterial;
  65054. }(BABYLON.Material));
  65055. BABYLON.MultiMaterial = MultiMaterial;
  65056. })(BABYLON || (BABYLON = {}));
  65057. //# sourceMappingURL=babylon.multiMaterial.js.map
  65058. "use strict";
  65059. var BABYLON;
  65060. (function (BABYLON) {
  65061. var FreeCameraTouchInput = /** @class */ (function () {
  65062. function FreeCameraTouchInput() {
  65063. this._offsetX = null;
  65064. this._offsetY = null;
  65065. this._pointerPressed = new Array();
  65066. this.touchAngularSensibility = 200000.0;
  65067. this.touchMoveSensibility = 250.0;
  65068. }
  65069. FreeCameraTouchInput.prototype.attachControl = function (element, noPreventDefault) {
  65070. var _this = this;
  65071. var previousPosition = null;
  65072. if (this._pointerInput === undefined) {
  65073. this._onLostFocus = function (evt) {
  65074. _this._offsetX = null;
  65075. _this._offsetY = null;
  65076. };
  65077. this._pointerInput = function (p, s) {
  65078. var evt = p.event;
  65079. if (evt.pointerType === "mouse") {
  65080. return;
  65081. }
  65082. if (p.type === BABYLON.PointerEventTypes.POINTERDOWN) {
  65083. if (!noPreventDefault) {
  65084. evt.preventDefault();
  65085. }
  65086. _this._pointerPressed.push(evt.pointerId);
  65087. if (_this._pointerPressed.length !== 1) {
  65088. return;
  65089. }
  65090. previousPosition = {
  65091. x: evt.clientX,
  65092. y: evt.clientY
  65093. };
  65094. }
  65095. else if (p.type === BABYLON.PointerEventTypes.POINTERUP) {
  65096. if (!noPreventDefault) {
  65097. evt.preventDefault();
  65098. }
  65099. var index = _this._pointerPressed.indexOf(evt.pointerId);
  65100. if (index === -1) {
  65101. return;
  65102. }
  65103. _this._pointerPressed.splice(index, 1);
  65104. if (index != 0) {
  65105. return;
  65106. }
  65107. previousPosition = null;
  65108. _this._offsetX = null;
  65109. _this._offsetY = null;
  65110. }
  65111. else if (p.type === BABYLON.PointerEventTypes.POINTERMOVE) {
  65112. if (!noPreventDefault) {
  65113. evt.preventDefault();
  65114. }
  65115. if (!previousPosition) {
  65116. return;
  65117. }
  65118. var index = _this._pointerPressed.indexOf(evt.pointerId);
  65119. if (index != 0) {
  65120. return;
  65121. }
  65122. _this._offsetX = evt.clientX - previousPosition.x;
  65123. _this._offsetY = -(evt.clientY - previousPosition.y);
  65124. }
  65125. };
  65126. }
  65127. this._observer = this.camera.getScene().onPointerObservable.add(this._pointerInput, BABYLON.PointerEventTypes.POINTERDOWN | BABYLON.PointerEventTypes.POINTERUP | BABYLON.PointerEventTypes.POINTERMOVE);
  65128. if (this._onLostFocus) {
  65129. element.addEventListener("blur", this._onLostFocus);
  65130. }
  65131. };
  65132. FreeCameraTouchInput.prototype.detachControl = function (element) {
  65133. if (this._pointerInput && element) {
  65134. if (this._observer) {
  65135. this.camera.getScene().onPointerObservable.remove(this._observer);
  65136. this._observer = null;
  65137. }
  65138. if (this._onLostFocus) {
  65139. element.removeEventListener("blur", this._onLostFocus);
  65140. this._onLostFocus = null;
  65141. }
  65142. this._pointerPressed = [];
  65143. this._offsetX = null;
  65144. this._offsetY = null;
  65145. }
  65146. };
  65147. FreeCameraTouchInput.prototype.checkInputs = function () {
  65148. if (this._offsetX && this._offsetY) {
  65149. var camera = this.camera;
  65150. camera.cameraRotation.y += this._offsetX / this.touchAngularSensibility;
  65151. if (this._pointerPressed.length > 1) {
  65152. camera.cameraRotation.x += -this._offsetY / this.touchAngularSensibility;
  65153. }
  65154. else {
  65155. var speed = camera._computeLocalCameraSpeed();
  65156. var direction = new BABYLON.Vector3(0, 0, speed * this._offsetY / this.touchMoveSensibility);
  65157. BABYLON.Matrix.RotationYawPitchRollToRef(camera.rotation.y, camera.rotation.x, 0, camera._cameraRotationMatrix);
  65158. camera.cameraDirection.addInPlace(BABYLON.Vector3.TransformCoordinates(direction, camera._cameraRotationMatrix));
  65159. }
  65160. }
  65161. };
  65162. FreeCameraTouchInput.prototype.getClassName = function () {
  65163. return "FreeCameraTouchInput";
  65164. };
  65165. FreeCameraTouchInput.prototype.getSimpleName = function () {
  65166. return "touch";
  65167. };
  65168. __decorate([
  65169. BABYLON.serialize()
  65170. ], FreeCameraTouchInput.prototype, "touchAngularSensibility", void 0);
  65171. __decorate([
  65172. BABYLON.serialize()
  65173. ], FreeCameraTouchInput.prototype, "touchMoveSensibility", void 0);
  65174. return FreeCameraTouchInput;
  65175. }());
  65176. BABYLON.FreeCameraTouchInput = FreeCameraTouchInput;
  65177. BABYLON.CameraInputTypes["FreeCameraTouchInput"] = FreeCameraTouchInput;
  65178. })(BABYLON || (BABYLON = {}));
  65179. //# sourceMappingURL=babylon.freeCameraTouchInput.js.map
  65180. "use strict";
  65181. var BABYLON;
  65182. (function (BABYLON) {
  65183. // We're mainly based on the logic defined into the FreeCamera code
  65184. var TouchCamera = /** @class */ (function (_super) {
  65185. __extends(TouchCamera, _super);
  65186. //-- end properties for backward compatibility for inputs
  65187. function TouchCamera(name, position, scene) {
  65188. var _this = _super.call(this, name, position, scene) || this;
  65189. _this.inputs.addTouch();
  65190. _this._setupInputs();
  65191. return _this;
  65192. }
  65193. Object.defineProperty(TouchCamera.prototype, "touchAngularSensibility", {
  65194. //-- Begin properties for backward compatibility for inputs
  65195. get: function () {
  65196. var touch = this.inputs.attached["touch"];
  65197. if (touch)
  65198. return touch.touchAngularSensibility;
  65199. return 0;
  65200. },
  65201. set: function (value) {
  65202. var touch = this.inputs.attached["touch"];
  65203. if (touch)
  65204. touch.touchAngularSensibility = value;
  65205. },
  65206. enumerable: true,
  65207. configurable: true
  65208. });
  65209. Object.defineProperty(TouchCamera.prototype, "touchMoveSensibility", {
  65210. get: function () {
  65211. var touch = this.inputs.attached["touch"];
  65212. if (touch)
  65213. return touch.touchMoveSensibility;
  65214. return 0;
  65215. },
  65216. set: function (value) {
  65217. var touch = this.inputs.attached["touch"];
  65218. if (touch)
  65219. touch.touchMoveSensibility = value;
  65220. },
  65221. enumerable: true,
  65222. configurable: true
  65223. });
  65224. TouchCamera.prototype.getClassName = function () {
  65225. return "TouchCamera";
  65226. };
  65227. TouchCamera.prototype._setupInputs = function () {
  65228. var mouse = this.inputs.attached["mouse"];
  65229. if (mouse) {
  65230. mouse.touchEnabled = false;
  65231. }
  65232. };
  65233. return TouchCamera;
  65234. }(BABYLON.FreeCamera));
  65235. BABYLON.TouchCamera = TouchCamera;
  65236. })(BABYLON || (BABYLON = {}));
  65237. //# sourceMappingURL=babylon.touchCamera.js.map
  65238. "use strict";
  65239. var BABYLON;
  65240. (function (BABYLON) {
  65241. var ProceduralTexture = /** @class */ (function (_super) {
  65242. __extends(ProceduralTexture, _super);
  65243. function ProceduralTexture(name, size, fragment, scene, fallbackTexture, generateMipMaps, isCube) {
  65244. if (fallbackTexture === void 0) { fallbackTexture = null; }
  65245. if (generateMipMaps === void 0) { generateMipMaps = true; }
  65246. if (isCube === void 0) { isCube = false; }
  65247. var _this = _super.call(this, null, scene, !generateMipMaps) || this;
  65248. _this.isCube = isCube;
  65249. _this.isEnabled = true;
  65250. _this._currentRefreshId = -1;
  65251. _this._refreshRate = 1;
  65252. _this._vertexBuffers = {};
  65253. _this._uniforms = new Array();
  65254. _this._samplers = new Array();
  65255. _this._textures = {};
  65256. _this._floats = {};
  65257. _this._floatsArrays = {};
  65258. _this._colors3 = {};
  65259. _this._colors4 = {};
  65260. _this._vectors2 = {};
  65261. _this._vectors3 = {};
  65262. _this._matrices = {};
  65263. _this._fallbackTextureUsed = false;
  65264. scene._proceduralTextures.push(_this);
  65265. _this._engine = scene.getEngine();
  65266. _this.name = name;
  65267. _this.isRenderTarget = true;
  65268. _this._size = size;
  65269. _this._generateMipMaps = generateMipMaps;
  65270. _this.setFragment(fragment);
  65271. _this._fallbackTexture = fallbackTexture;
  65272. if (isCube) {
  65273. _this._texture = _this._engine.createRenderTargetCubeTexture(size, { generateMipMaps: generateMipMaps });
  65274. _this.setFloat("face", 0);
  65275. }
  65276. else {
  65277. _this._texture = _this._engine.createRenderTargetTexture(size, generateMipMaps);
  65278. }
  65279. // VBO
  65280. var vertices = [];
  65281. vertices.push(1, 1);
  65282. vertices.push(-1, 1);
  65283. vertices.push(-1, -1);
  65284. vertices.push(1, -1);
  65285. _this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(_this._engine, vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  65286. _this._createIndexBuffer();
  65287. return _this;
  65288. }
  65289. ProceduralTexture.prototype._createIndexBuffer = function () {
  65290. var engine = this._engine;
  65291. // Indices
  65292. var indices = [];
  65293. indices.push(0);
  65294. indices.push(1);
  65295. indices.push(2);
  65296. indices.push(0);
  65297. indices.push(2);
  65298. indices.push(3);
  65299. this._indexBuffer = engine.createIndexBuffer(indices);
  65300. };
  65301. ProceduralTexture.prototype._rebuild = function () {
  65302. var vb = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  65303. if (vb) {
  65304. vb._rebuild();
  65305. }
  65306. this._createIndexBuffer();
  65307. if (this.refreshRate === BABYLON.RenderTargetTexture.REFRESHRATE_RENDER_ONCE) {
  65308. this.refreshRate = BABYLON.RenderTargetTexture.REFRESHRATE_RENDER_ONCE;
  65309. }
  65310. };
  65311. ProceduralTexture.prototype.reset = function () {
  65312. if (this._effect === undefined) {
  65313. return;
  65314. }
  65315. var engine = this._engine;
  65316. engine._releaseEffect(this._effect);
  65317. };
  65318. ProceduralTexture.prototype.isReady = function () {
  65319. var _this = this;
  65320. var engine = this._engine;
  65321. var shaders;
  65322. if (!this._fragment) {
  65323. return false;
  65324. }
  65325. if (this._fallbackTextureUsed) {
  65326. return true;
  65327. }
  65328. if (this._fragment.fragmentElement !== undefined) {
  65329. shaders = { vertex: "procedural", fragmentElement: this._fragment.fragmentElement };
  65330. }
  65331. else {
  65332. shaders = { vertex: "procedural", fragment: this._fragment };
  65333. }
  65334. this._effect = engine.createEffect(shaders, [BABYLON.VertexBuffer.PositionKind], this._uniforms, this._samplers, "", undefined, undefined, function () {
  65335. _this.releaseInternalTexture();
  65336. if (_this._fallbackTexture) {
  65337. _this._texture = _this._fallbackTexture._texture;
  65338. if (_this._texture) {
  65339. _this._texture.incrementReferences();
  65340. }
  65341. }
  65342. _this._fallbackTextureUsed = true;
  65343. });
  65344. return this._effect.isReady();
  65345. };
  65346. ProceduralTexture.prototype.resetRefreshCounter = function () {
  65347. this._currentRefreshId = -1;
  65348. };
  65349. ProceduralTexture.prototype.setFragment = function (fragment) {
  65350. this._fragment = fragment;
  65351. };
  65352. Object.defineProperty(ProceduralTexture.prototype, "refreshRate", {
  65353. get: function () {
  65354. return this._refreshRate;
  65355. },
  65356. // Use 0 to render just once, 1 to render on every frame, 2 to render every two frames and so on...
  65357. set: function (value) {
  65358. this._refreshRate = value;
  65359. this.resetRefreshCounter();
  65360. },
  65361. enumerable: true,
  65362. configurable: true
  65363. });
  65364. ProceduralTexture.prototype._shouldRender = function () {
  65365. if (!this.isEnabled || !this.isReady() || !this._texture) {
  65366. return false;
  65367. }
  65368. if (this._fallbackTextureUsed) {
  65369. return false;
  65370. }
  65371. if (this._currentRefreshId === -1) {
  65372. this._currentRefreshId = 1;
  65373. return true;
  65374. }
  65375. if (this.refreshRate === this._currentRefreshId) {
  65376. this._currentRefreshId = 1;
  65377. return true;
  65378. }
  65379. this._currentRefreshId++;
  65380. return false;
  65381. };
  65382. ProceduralTexture.prototype.getRenderSize = function () {
  65383. return this._size;
  65384. };
  65385. ProceduralTexture.prototype.resize = function (size, generateMipMaps) {
  65386. if (this._fallbackTextureUsed) {
  65387. return;
  65388. }
  65389. this.releaseInternalTexture();
  65390. this._texture = this._engine.createRenderTargetTexture(size, generateMipMaps);
  65391. };
  65392. ProceduralTexture.prototype._checkUniform = function (uniformName) {
  65393. if (this._uniforms.indexOf(uniformName) === -1) {
  65394. this._uniforms.push(uniformName);
  65395. }
  65396. };
  65397. ProceduralTexture.prototype.setTexture = function (name, texture) {
  65398. if (this._samplers.indexOf(name) === -1) {
  65399. this._samplers.push(name);
  65400. }
  65401. this._textures[name] = texture;
  65402. return this;
  65403. };
  65404. ProceduralTexture.prototype.setFloat = function (name, value) {
  65405. this._checkUniform(name);
  65406. this._floats[name] = value;
  65407. return this;
  65408. };
  65409. ProceduralTexture.prototype.setFloats = function (name, value) {
  65410. this._checkUniform(name);
  65411. this._floatsArrays[name] = value;
  65412. return this;
  65413. };
  65414. ProceduralTexture.prototype.setColor3 = function (name, value) {
  65415. this._checkUniform(name);
  65416. this._colors3[name] = value;
  65417. return this;
  65418. };
  65419. ProceduralTexture.prototype.setColor4 = function (name, value) {
  65420. this._checkUniform(name);
  65421. this._colors4[name] = value;
  65422. return this;
  65423. };
  65424. ProceduralTexture.prototype.setVector2 = function (name, value) {
  65425. this._checkUniform(name);
  65426. this._vectors2[name] = value;
  65427. return this;
  65428. };
  65429. ProceduralTexture.prototype.setVector3 = function (name, value) {
  65430. this._checkUniform(name);
  65431. this._vectors3[name] = value;
  65432. return this;
  65433. };
  65434. ProceduralTexture.prototype.setMatrix = function (name, value) {
  65435. this._checkUniform(name);
  65436. this._matrices[name] = value;
  65437. return this;
  65438. };
  65439. ProceduralTexture.prototype.render = function (useCameraPostProcess) {
  65440. var scene = this.getScene();
  65441. if (!scene) {
  65442. return;
  65443. }
  65444. var engine = this._engine;
  65445. // Render
  65446. engine.enableEffect(this._effect);
  65447. engine.setState(false);
  65448. // Texture
  65449. for (var name in this._textures) {
  65450. this._effect.setTexture(name, this._textures[name]);
  65451. }
  65452. // Float
  65453. for (name in this._floats) {
  65454. this._effect.setFloat(name, this._floats[name]);
  65455. }
  65456. // Floats
  65457. for (name in this._floatsArrays) {
  65458. this._effect.setArray(name, this._floatsArrays[name]);
  65459. }
  65460. // Color3
  65461. for (name in this._colors3) {
  65462. this._effect.setColor3(name, this._colors3[name]);
  65463. }
  65464. // Color4
  65465. for (name in this._colors4) {
  65466. var color = this._colors4[name];
  65467. this._effect.setFloat4(name, color.r, color.g, color.b, color.a);
  65468. }
  65469. // Vector2
  65470. for (name in this._vectors2) {
  65471. this._effect.setVector2(name, this._vectors2[name]);
  65472. }
  65473. // Vector3
  65474. for (name in this._vectors3) {
  65475. this._effect.setVector3(name, this._vectors3[name]);
  65476. }
  65477. // Matrix
  65478. for (name in this._matrices) {
  65479. this._effect.setMatrix(name, this._matrices[name]);
  65480. }
  65481. if (!this._texture) {
  65482. return;
  65483. }
  65484. if (this.isCube) {
  65485. for (var face = 0; face < 6; face++) {
  65486. engine.bindFramebuffer(this._texture, face, undefined, undefined, true);
  65487. // VBOs
  65488. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._effect);
  65489. this._effect.setFloat("face", face);
  65490. // Clear
  65491. engine.clear(scene.clearColor, true, true, true);
  65492. // Draw order
  65493. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  65494. // Mipmaps
  65495. if (face === 5) {
  65496. engine.generateMipMapsForCubemap(this._texture);
  65497. }
  65498. }
  65499. }
  65500. else {
  65501. engine.bindFramebuffer(this._texture, 0, undefined, undefined, true);
  65502. // VBOs
  65503. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._effect);
  65504. // Clear
  65505. engine.clear(scene.clearColor, true, true, true);
  65506. // Draw order
  65507. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  65508. }
  65509. // Unbind
  65510. engine.unBindFramebuffer(this._texture, this.isCube);
  65511. if (this.onGenerated) {
  65512. this.onGenerated();
  65513. }
  65514. };
  65515. ProceduralTexture.prototype.clone = function () {
  65516. var textureSize = this.getSize();
  65517. var newTexture = new ProceduralTexture(this.name, textureSize.width, this._fragment, this.getScene(), this._fallbackTexture, this._generateMipMaps);
  65518. // Base texture
  65519. newTexture.hasAlpha = this.hasAlpha;
  65520. newTexture.level = this.level;
  65521. // RenderTarget Texture
  65522. newTexture.coordinatesMode = this.coordinatesMode;
  65523. return newTexture;
  65524. };
  65525. ProceduralTexture.prototype.dispose = function () {
  65526. var scene = this.getScene();
  65527. if (!scene) {
  65528. return;
  65529. }
  65530. var index = scene._proceduralTextures.indexOf(this);
  65531. if (index >= 0) {
  65532. scene._proceduralTextures.splice(index, 1);
  65533. }
  65534. var vertexBuffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  65535. if (vertexBuffer) {
  65536. vertexBuffer.dispose();
  65537. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  65538. }
  65539. if (this._indexBuffer && this._engine._releaseBuffer(this._indexBuffer)) {
  65540. this._indexBuffer = null;
  65541. }
  65542. _super.prototype.dispose.call(this);
  65543. };
  65544. return ProceduralTexture;
  65545. }(BABYLON.Texture));
  65546. BABYLON.ProceduralTexture = ProceduralTexture;
  65547. })(BABYLON || (BABYLON = {}));
  65548. //# sourceMappingURL=babylon.proceduralTexture.js.map
  65549. "use strict";
  65550. var BABYLON;
  65551. (function (BABYLON) {
  65552. var CustomProceduralTexture = /** @class */ (function (_super) {
  65553. __extends(CustomProceduralTexture, _super);
  65554. function CustomProceduralTexture(name, texturePath, size, scene, fallbackTexture, generateMipMaps) {
  65555. var _this = _super.call(this, name, size, null, scene, fallbackTexture, generateMipMaps) || this;
  65556. _this._animate = true;
  65557. _this._time = 0;
  65558. _this._texturePath = texturePath;
  65559. //Try to load json
  65560. _this.loadJson(texturePath);
  65561. _this.refreshRate = 1;
  65562. return _this;
  65563. }
  65564. CustomProceduralTexture.prototype.loadJson = function (jsonUrl) {
  65565. var _this = this;
  65566. var noConfigFile = function () {
  65567. BABYLON.Tools.Log("No config file found in " + jsonUrl + " trying to use ShadersStore or DOM element");
  65568. try {
  65569. _this.setFragment(_this._texturePath);
  65570. }
  65571. catch (ex) {
  65572. BABYLON.Tools.Error("No json or ShaderStore or DOM element found for CustomProceduralTexture");
  65573. }
  65574. };
  65575. var configFileUrl = jsonUrl + "/config.json";
  65576. var xhr = new XMLHttpRequest();
  65577. xhr.open("GET", configFileUrl, true);
  65578. xhr.addEventListener("load", function () {
  65579. if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, 1)) {
  65580. try {
  65581. _this._config = JSON.parse(xhr.response);
  65582. _this.updateShaderUniforms();
  65583. _this.updateTextures();
  65584. _this.setFragment(_this._texturePath + "/custom");
  65585. _this._animate = _this._config.animate;
  65586. _this.refreshRate = _this._config.refreshrate;
  65587. }
  65588. catch (ex) {
  65589. noConfigFile();
  65590. }
  65591. }
  65592. else {
  65593. noConfigFile();
  65594. }
  65595. }, false);
  65596. xhr.addEventListener("error", function () {
  65597. noConfigFile();
  65598. }, false);
  65599. try {
  65600. xhr.send();
  65601. }
  65602. catch (ex) {
  65603. BABYLON.Tools.Error("CustomProceduralTexture: Error on XHR send request.");
  65604. }
  65605. };
  65606. CustomProceduralTexture.prototype.isReady = function () {
  65607. if (!_super.prototype.isReady.call(this)) {
  65608. return false;
  65609. }
  65610. for (var name in this._textures) {
  65611. var texture = this._textures[name];
  65612. if (!texture.isReady()) {
  65613. return false;
  65614. }
  65615. }
  65616. return true;
  65617. };
  65618. CustomProceduralTexture.prototype.render = function (useCameraPostProcess) {
  65619. var scene = this.getScene();
  65620. if (this._animate && scene) {
  65621. this._time += scene.getAnimationRatio() * 0.03;
  65622. this.updateShaderUniforms();
  65623. }
  65624. _super.prototype.render.call(this, useCameraPostProcess);
  65625. };
  65626. CustomProceduralTexture.prototype.updateTextures = function () {
  65627. for (var i = 0; i < this._config.sampler2Ds.length; i++) {
  65628. this.setTexture(this._config.sampler2Ds[i].sample2Dname, new BABYLON.Texture(this._texturePath + "/" + this._config.sampler2Ds[i].textureRelativeUrl, this.getScene()));
  65629. }
  65630. };
  65631. CustomProceduralTexture.prototype.updateShaderUniforms = function () {
  65632. if (this._config) {
  65633. for (var j = 0; j < this._config.uniforms.length; j++) {
  65634. var uniform = this._config.uniforms[j];
  65635. switch (uniform.type) {
  65636. case "float":
  65637. this.setFloat(uniform.name, uniform.value);
  65638. break;
  65639. case "color3":
  65640. this.setColor3(uniform.name, new BABYLON.Color3(uniform.r, uniform.g, uniform.b));
  65641. break;
  65642. case "color4":
  65643. this.setColor4(uniform.name, new BABYLON.Color4(uniform.r, uniform.g, uniform.b, uniform.a));
  65644. break;
  65645. case "vector2":
  65646. this.setVector2(uniform.name, new BABYLON.Vector2(uniform.x, uniform.y));
  65647. break;
  65648. case "vector3":
  65649. this.setVector3(uniform.name, new BABYLON.Vector3(uniform.x, uniform.y, uniform.z));
  65650. break;
  65651. }
  65652. }
  65653. }
  65654. this.setFloat("time", this._time);
  65655. };
  65656. Object.defineProperty(CustomProceduralTexture.prototype, "animate", {
  65657. get: function () {
  65658. return this._animate;
  65659. },
  65660. set: function (value) {
  65661. this._animate = value;
  65662. },
  65663. enumerable: true,
  65664. configurable: true
  65665. });
  65666. return CustomProceduralTexture;
  65667. }(BABYLON.ProceduralTexture));
  65668. BABYLON.CustomProceduralTexture = CustomProceduralTexture;
  65669. })(BABYLON || (BABYLON = {}));
  65670. //# sourceMappingURL=babylon.customProceduralTexture.js.map
  65671. "use strict";
  65672. var BABYLON;
  65673. (function (BABYLON) {
  65674. var FreeCameraGamepadInput = /** @class */ (function () {
  65675. function FreeCameraGamepadInput() {
  65676. this.gamepadAngularSensibility = 200;
  65677. this.gamepadMoveSensibility = 40;
  65678. // private members
  65679. this._cameraTransform = BABYLON.Matrix.Identity();
  65680. this._deltaTransform = BABYLON.Vector3.Zero();
  65681. this._vector3 = BABYLON.Vector3.Zero();
  65682. this._vector2 = BABYLON.Vector2.Zero();
  65683. }
  65684. FreeCameraGamepadInput.prototype.attachControl = function (element, noPreventDefault) {
  65685. var _this = this;
  65686. var manager = this.camera.getScene().gamepadManager;
  65687. this._onGamepadConnectedObserver = manager.onGamepadConnectedObservable.add(function (gamepad) {
  65688. if (gamepad.type !== BABYLON.Gamepad.POSE_ENABLED) {
  65689. // prioritize XBOX gamepads.
  65690. if (!_this.gamepad || gamepad.type === BABYLON.Gamepad.XBOX) {
  65691. _this.gamepad = gamepad;
  65692. }
  65693. }
  65694. });
  65695. this._onGamepadDisconnectedObserver = manager.onGamepadDisconnectedObservable.add(function (gamepad) {
  65696. if (_this.gamepad === gamepad) {
  65697. _this.gamepad = null;
  65698. }
  65699. });
  65700. this.gamepad = manager.getGamepadByType(BABYLON.Gamepad.XBOX);
  65701. };
  65702. FreeCameraGamepadInput.prototype.detachControl = function (element) {
  65703. this.camera.getScene().gamepadManager.onGamepadConnectedObservable.remove(this._onGamepadConnectedObserver);
  65704. this.camera.getScene().gamepadManager.onGamepadDisconnectedObservable.remove(this._onGamepadDisconnectedObserver);
  65705. this.gamepad = null;
  65706. };
  65707. FreeCameraGamepadInput.prototype.checkInputs = function () {
  65708. if (this.gamepad && this.gamepad.leftStick) {
  65709. var camera = this.camera;
  65710. var LSValues = this.gamepad.leftStick;
  65711. var normalizedLX = LSValues.x / this.gamepadMoveSensibility;
  65712. var normalizedLY = LSValues.y / this.gamepadMoveSensibility;
  65713. LSValues.x = Math.abs(normalizedLX) > 0.005 ? 0 + normalizedLX : 0;
  65714. LSValues.y = Math.abs(normalizedLY) > 0.005 ? 0 + normalizedLY : 0;
  65715. var RSValues = this.gamepad.rightStick;
  65716. if (RSValues) {
  65717. var normalizedRX = RSValues.x / this.gamepadAngularSensibility;
  65718. var normalizedRY = RSValues.y / this.gamepadAngularSensibility;
  65719. RSValues.x = Math.abs(normalizedRX) > 0.001 ? 0 + normalizedRX : 0;
  65720. RSValues.y = Math.abs(normalizedRY) > 0.001 ? 0 + normalizedRY : 0;
  65721. }
  65722. else {
  65723. RSValues = { x: 0, y: 0 };
  65724. }
  65725. if (!camera.rotationQuaternion) {
  65726. BABYLON.Matrix.RotationYawPitchRollToRef(camera.rotation.y, camera.rotation.x, 0, this._cameraTransform);
  65727. }
  65728. else {
  65729. camera.rotationQuaternion.toRotationMatrix(this._cameraTransform);
  65730. }
  65731. var speed = camera._computeLocalCameraSpeed() * 50.0;
  65732. this._vector3.copyFromFloats(LSValues.x * speed, 0, -LSValues.y * speed);
  65733. BABYLON.Vector3.TransformCoordinatesToRef(this._vector3, this._cameraTransform, this._deltaTransform);
  65734. camera.cameraDirection.addInPlace(this._deltaTransform);
  65735. this._vector2.copyFromFloats(RSValues.y, RSValues.x);
  65736. camera.cameraRotation.addInPlace(this._vector2);
  65737. }
  65738. };
  65739. FreeCameraGamepadInput.prototype.getClassName = function () {
  65740. return "FreeCameraGamepadInput";
  65741. };
  65742. FreeCameraGamepadInput.prototype.getSimpleName = function () {
  65743. return "gamepad";
  65744. };
  65745. __decorate([
  65746. BABYLON.serialize()
  65747. ], FreeCameraGamepadInput.prototype, "gamepadAngularSensibility", void 0);
  65748. __decorate([
  65749. BABYLON.serialize()
  65750. ], FreeCameraGamepadInput.prototype, "gamepadMoveSensibility", void 0);
  65751. return FreeCameraGamepadInput;
  65752. }());
  65753. BABYLON.FreeCameraGamepadInput = FreeCameraGamepadInput;
  65754. BABYLON.CameraInputTypes["FreeCameraGamepadInput"] = FreeCameraGamepadInput;
  65755. })(BABYLON || (BABYLON = {}));
  65756. //# sourceMappingURL=babylon.freeCameraGamepadInput.js.map
  65757. "use strict";
  65758. var BABYLON;
  65759. (function (BABYLON) {
  65760. var ArcRotateCameraGamepadInput = /** @class */ (function () {
  65761. function ArcRotateCameraGamepadInput() {
  65762. this.gamepadRotationSensibility = 80;
  65763. this.gamepadMoveSensibility = 40;
  65764. }
  65765. ArcRotateCameraGamepadInput.prototype.attachControl = function (element, noPreventDefault) {
  65766. var _this = this;
  65767. var manager = this.camera.getScene().gamepadManager;
  65768. this._onGamepadConnectedObserver = manager.onGamepadConnectedObservable.add(function (gamepad) {
  65769. if (gamepad.type !== BABYLON.Gamepad.POSE_ENABLED) {
  65770. // prioritize XBOX gamepads.
  65771. if (!_this.gamepad || gamepad.type === BABYLON.Gamepad.XBOX) {
  65772. _this.gamepad = gamepad;
  65773. }
  65774. }
  65775. });
  65776. this._onGamepadDisconnectedObserver = manager.onGamepadDisconnectedObservable.add(function (gamepad) {
  65777. if (_this.gamepad === gamepad) {
  65778. _this.gamepad = null;
  65779. }
  65780. });
  65781. this.gamepad = manager.getGamepadByType(BABYLON.Gamepad.XBOX);
  65782. };
  65783. ArcRotateCameraGamepadInput.prototype.detachControl = function (element) {
  65784. this.camera.getScene().gamepadManager.onGamepadConnectedObservable.remove(this._onGamepadConnectedObserver);
  65785. this.camera.getScene().gamepadManager.onGamepadDisconnectedObservable.remove(this._onGamepadDisconnectedObserver);
  65786. this.gamepad = null;
  65787. };
  65788. ArcRotateCameraGamepadInput.prototype.checkInputs = function () {
  65789. if (this.gamepad) {
  65790. var camera = this.camera;
  65791. var RSValues = this.gamepad.rightStick;
  65792. if (RSValues) {
  65793. if (RSValues.x != 0) {
  65794. var normalizedRX = RSValues.x / this.gamepadRotationSensibility;
  65795. if (normalizedRX != 0 && Math.abs(normalizedRX) > 0.005) {
  65796. camera.inertialAlphaOffset += normalizedRX;
  65797. }
  65798. }
  65799. if (RSValues.y != 0) {
  65800. var normalizedRY = RSValues.y / this.gamepadRotationSensibility;
  65801. if (normalizedRY != 0 && Math.abs(normalizedRY) > 0.005) {
  65802. camera.inertialBetaOffset += normalizedRY;
  65803. }
  65804. }
  65805. }
  65806. var LSValues = this.gamepad.leftStick;
  65807. if (LSValues && LSValues.y != 0) {
  65808. var normalizedLY = LSValues.y / this.gamepadMoveSensibility;
  65809. if (normalizedLY != 0 && Math.abs(normalizedLY) > 0.005) {
  65810. this.camera.inertialRadiusOffset -= normalizedLY;
  65811. }
  65812. }
  65813. }
  65814. };
  65815. ArcRotateCameraGamepadInput.prototype.getClassName = function () {
  65816. return "ArcRotateCameraGamepadInput";
  65817. };
  65818. ArcRotateCameraGamepadInput.prototype.getSimpleName = function () {
  65819. return "gamepad";
  65820. };
  65821. __decorate([
  65822. BABYLON.serialize()
  65823. ], ArcRotateCameraGamepadInput.prototype, "gamepadRotationSensibility", void 0);
  65824. __decorate([
  65825. BABYLON.serialize()
  65826. ], ArcRotateCameraGamepadInput.prototype, "gamepadMoveSensibility", void 0);
  65827. return ArcRotateCameraGamepadInput;
  65828. }());
  65829. BABYLON.ArcRotateCameraGamepadInput = ArcRotateCameraGamepadInput;
  65830. BABYLON.CameraInputTypes["ArcRotateCameraGamepadInput"] = ArcRotateCameraGamepadInput;
  65831. })(BABYLON || (BABYLON = {}));
  65832. //# sourceMappingURL=babylon.arcRotateCameraGamepadInput.js.map
  65833. "use strict";
  65834. var BABYLON;
  65835. (function (BABYLON) {
  65836. var GamepadManager = /** @class */ (function () {
  65837. function GamepadManager(_scene) {
  65838. var _this = this;
  65839. this._scene = _scene;
  65840. this._babylonGamepads = [];
  65841. this._oneGamepadConnected = false;
  65842. this._isMonitoring = false;
  65843. this.onGamepadDisconnectedObservable = new BABYLON.Observable();
  65844. if (!BABYLON.Tools.IsWindowObjectExist()) {
  65845. this._gamepadEventSupported = false;
  65846. }
  65847. else {
  65848. this._gamepadEventSupported = 'GamepadEvent' in window;
  65849. this._gamepadSupport = (navigator.getGamepads ||
  65850. navigator.webkitGetGamepads || navigator.msGetGamepads || navigator.webkitGamepads);
  65851. }
  65852. this.onGamepadConnectedObservable = new BABYLON.Observable(function (observer) {
  65853. // This will be used to raise the onGamepadConnected for all gamepads ALREADY connected
  65854. for (var i in _this._babylonGamepads) {
  65855. var gamepad = _this._babylonGamepads[i];
  65856. if (gamepad && gamepad._isConnected) {
  65857. _this.onGamepadConnectedObservable.notifyObserver(observer, gamepad);
  65858. }
  65859. }
  65860. });
  65861. this._onGamepadConnectedEvent = function (evt) {
  65862. var gamepad = evt.gamepad;
  65863. if (gamepad.index in _this._babylonGamepads) {
  65864. if (_this._babylonGamepads[gamepad.index].isConnected) {
  65865. return;
  65866. }
  65867. }
  65868. var newGamepad;
  65869. if (_this._babylonGamepads[gamepad.index]) {
  65870. newGamepad = _this._babylonGamepads[gamepad.index];
  65871. newGamepad.browserGamepad = gamepad;
  65872. newGamepad._isConnected = true;
  65873. }
  65874. else {
  65875. newGamepad = _this._addNewGamepad(gamepad);
  65876. }
  65877. _this.onGamepadConnectedObservable.notifyObservers(newGamepad);
  65878. _this._startMonitoringGamepads();
  65879. };
  65880. this._onGamepadDisconnectedEvent = function (evt) {
  65881. var gamepad = evt.gamepad;
  65882. // Remove the gamepad from the list of gamepads to monitor.
  65883. for (var i in _this._babylonGamepads) {
  65884. if (_this._babylonGamepads[i].index === gamepad.index) {
  65885. var disconnectedGamepad = _this._babylonGamepads[i];
  65886. disconnectedGamepad._isConnected = false;
  65887. _this.onGamepadDisconnectedObservable.notifyObservers(disconnectedGamepad);
  65888. break;
  65889. }
  65890. }
  65891. };
  65892. if (this._gamepadSupport) {
  65893. //first add already-connected gamepads
  65894. this._updateGamepadObjects();
  65895. if (this._babylonGamepads.length) {
  65896. this._startMonitoringGamepads();
  65897. }
  65898. // Checking if the gamepad connected event is supported (like in Firefox)
  65899. if (this._gamepadEventSupported) {
  65900. window.addEventListener('gamepadconnected', this._onGamepadConnectedEvent, false);
  65901. window.addEventListener('gamepaddisconnected', this._onGamepadDisconnectedEvent, false);
  65902. }
  65903. else {
  65904. this._startMonitoringGamepads();
  65905. }
  65906. }
  65907. }
  65908. Object.defineProperty(GamepadManager.prototype, "gamepads", {
  65909. get: function () {
  65910. return this._babylonGamepads;
  65911. },
  65912. enumerable: true,
  65913. configurable: true
  65914. });
  65915. GamepadManager.prototype.getGamepadByType = function (type) {
  65916. if (type === void 0) { type = BABYLON.Gamepad.XBOX; }
  65917. for (var _i = 0, _a = this._babylonGamepads; _i < _a.length; _i++) {
  65918. var gamepad = _a[_i];
  65919. if (gamepad && gamepad.type === type) {
  65920. return gamepad;
  65921. }
  65922. }
  65923. return null;
  65924. };
  65925. GamepadManager.prototype.dispose = function () {
  65926. if (this._gamepadEventSupported) {
  65927. if (this._onGamepadConnectedEvent) {
  65928. window.removeEventListener('gamepadconnected', this._onGamepadConnectedEvent);
  65929. }
  65930. if (this._onGamepadDisconnectedEvent) {
  65931. window.removeEventListener('gamepaddisconnected', this._onGamepadDisconnectedEvent);
  65932. }
  65933. this._onGamepadConnectedEvent = null;
  65934. this._onGamepadDisconnectedEvent = null;
  65935. }
  65936. this._babylonGamepads.forEach(function (gamepad) {
  65937. gamepad.dispose();
  65938. });
  65939. this.onGamepadConnectedObservable.clear();
  65940. this.onGamepadDisconnectedObservable.clear();
  65941. this._oneGamepadConnected = false;
  65942. this._stopMonitoringGamepads();
  65943. this._babylonGamepads = [];
  65944. };
  65945. GamepadManager.prototype._addNewGamepad = function (gamepad) {
  65946. if (!this._oneGamepadConnected) {
  65947. this._oneGamepadConnected = true;
  65948. }
  65949. var newGamepad;
  65950. var xboxOne = (gamepad.id.search("Xbox One") !== -1);
  65951. if (xboxOne || gamepad.id.search("Xbox 360") !== -1 || gamepad.id.search("xinput") !== -1) {
  65952. newGamepad = new BABYLON.Xbox360Pad(gamepad.id, gamepad.index, gamepad, xboxOne);
  65953. }
  65954. else if (gamepad.pose) {
  65955. newGamepad = BABYLON.PoseEnabledControllerHelper.InitiateController(gamepad);
  65956. }
  65957. else {
  65958. newGamepad = new BABYLON.GenericPad(gamepad.id, gamepad.index, gamepad);
  65959. }
  65960. this._babylonGamepads[newGamepad.index] = newGamepad;
  65961. return newGamepad;
  65962. };
  65963. GamepadManager.prototype._startMonitoringGamepads = function () {
  65964. if (!this._isMonitoring) {
  65965. this._isMonitoring = true;
  65966. //back-comp
  65967. if (!this._scene) {
  65968. this._checkGamepadsStatus();
  65969. }
  65970. }
  65971. };
  65972. GamepadManager.prototype._stopMonitoringGamepads = function () {
  65973. this._isMonitoring = false;
  65974. };
  65975. GamepadManager.prototype._checkGamepadsStatus = function () {
  65976. var _this = this;
  65977. // Hack to be compatible Chrome
  65978. this._updateGamepadObjects();
  65979. for (var i in this._babylonGamepads) {
  65980. var gamepad = this._babylonGamepads[i];
  65981. if (!gamepad || !gamepad.isConnected) {
  65982. continue;
  65983. }
  65984. gamepad.update();
  65985. }
  65986. if (this._isMonitoring && !this._scene) {
  65987. BABYLON.Tools.QueueNewFrame(function () { _this._checkGamepadsStatus(); });
  65988. }
  65989. };
  65990. // This function is called only on Chrome, which does not properly support
  65991. // connection/disconnection events and forces you to recopy again the gamepad object
  65992. GamepadManager.prototype._updateGamepadObjects = function () {
  65993. var gamepads = navigator.getGamepads ? navigator.getGamepads() : (navigator.webkitGetGamepads ? navigator.webkitGetGamepads() : []);
  65994. for (var i = 0; i < gamepads.length; i++) {
  65995. if (gamepads[i]) {
  65996. if (!this._babylonGamepads[gamepads[i].index]) {
  65997. var newGamepad = this._addNewGamepad(gamepads[i]);
  65998. this.onGamepadConnectedObservable.notifyObservers(newGamepad);
  65999. }
  66000. else {
  66001. // Forced to copy again this object for Chrome for unknown reason
  66002. this._babylonGamepads[i].browserGamepad = gamepads[i];
  66003. if (!this._babylonGamepads[i].isConnected) {
  66004. this._babylonGamepads[i]._isConnected = true;
  66005. this.onGamepadConnectedObservable.notifyObservers(this._babylonGamepads[i]);
  66006. }
  66007. }
  66008. }
  66009. }
  66010. };
  66011. return GamepadManager;
  66012. }());
  66013. BABYLON.GamepadManager = GamepadManager;
  66014. })(BABYLON || (BABYLON = {}));
  66015. //# sourceMappingURL=babylon.gamepadManager.js.map
  66016. "use strict";
  66017. var BABYLON;
  66018. (function (BABYLON) {
  66019. var StickValues = /** @class */ (function () {
  66020. function StickValues(x, y) {
  66021. this.x = x;
  66022. this.y = y;
  66023. }
  66024. return StickValues;
  66025. }());
  66026. BABYLON.StickValues = StickValues;
  66027. var Gamepad = /** @class */ (function () {
  66028. function Gamepad(id, index, browserGamepad, leftStickX, leftStickY, rightStickX, rightStickY) {
  66029. if (leftStickX === void 0) { leftStickX = 0; }
  66030. if (leftStickY === void 0) { leftStickY = 1; }
  66031. if (rightStickX === void 0) { rightStickX = 2; }
  66032. if (rightStickY === void 0) { rightStickY = 3; }
  66033. this.id = id;
  66034. this.index = index;
  66035. this.browserGamepad = browserGamepad;
  66036. this._isConnected = true;
  66037. this._invertLeftStickY = false;
  66038. this.type = Gamepad.GAMEPAD;
  66039. this._leftStickAxisX = leftStickX;
  66040. this._leftStickAxisY = leftStickY;
  66041. this._rightStickAxisX = rightStickX;
  66042. this._rightStickAxisY = rightStickY;
  66043. if (this.browserGamepad.axes.length >= 2) {
  66044. this._leftStick = { x: this.browserGamepad.axes[this._leftStickAxisX], y: this.browserGamepad.axes[this._leftStickAxisY] };
  66045. }
  66046. if (this.browserGamepad.axes.length >= 4) {
  66047. this._rightStick = { x: this.browserGamepad.axes[this._rightStickAxisX], y: this.browserGamepad.axes[this._rightStickAxisY] };
  66048. }
  66049. }
  66050. Object.defineProperty(Gamepad.prototype, "isConnected", {
  66051. get: function () {
  66052. return this._isConnected;
  66053. },
  66054. enumerable: true,
  66055. configurable: true
  66056. });
  66057. Gamepad.prototype.onleftstickchanged = function (callback) {
  66058. this._onleftstickchanged = callback;
  66059. };
  66060. Gamepad.prototype.onrightstickchanged = function (callback) {
  66061. this._onrightstickchanged = callback;
  66062. };
  66063. Object.defineProperty(Gamepad.prototype, "leftStick", {
  66064. get: function () {
  66065. return this._leftStick;
  66066. },
  66067. set: function (newValues) {
  66068. if (this._onleftstickchanged && (this._leftStick.x !== newValues.x || this._leftStick.y !== newValues.y)) {
  66069. this._onleftstickchanged(newValues);
  66070. }
  66071. this._leftStick = newValues;
  66072. },
  66073. enumerable: true,
  66074. configurable: true
  66075. });
  66076. Object.defineProperty(Gamepad.prototype, "rightStick", {
  66077. get: function () {
  66078. return this._rightStick;
  66079. },
  66080. set: function (newValues) {
  66081. if (this._onrightstickchanged && (this._rightStick.x !== newValues.x || this._rightStick.y !== newValues.y)) {
  66082. this._onrightstickchanged(newValues);
  66083. }
  66084. this._rightStick = newValues;
  66085. },
  66086. enumerable: true,
  66087. configurable: true
  66088. });
  66089. Gamepad.prototype.update = function () {
  66090. if (this._leftStick) {
  66091. this.leftStick = { x: this.browserGamepad.axes[this._leftStickAxisX], y: this.browserGamepad.axes[this._leftStickAxisY] };
  66092. if (this._invertLeftStickY) {
  66093. this.leftStick.y *= -1;
  66094. }
  66095. }
  66096. if (this._rightStick) {
  66097. this.rightStick = { x: this.browserGamepad.axes[this._rightStickAxisX], y: this.browserGamepad.axes[this._rightStickAxisY] };
  66098. }
  66099. };
  66100. Gamepad.prototype.dispose = function () {
  66101. };
  66102. Gamepad.GAMEPAD = 0;
  66103. Gamepad.GENERIC = 1;
  66104. Gamepad.XBOX = 2;
  66105. Gamepad.POSE_ENABLED = 3;
  66106. return Gamepad;
  66107. }());
  66108. BABYLON.Gamepad = Gamepad;
  66109. var GenericPad = /** @class */ (function (_super) {
  66110. __extends(GenericPad, _super);
  66111. function GenericPad(id, index, browserGamepad) {
  66112. var _this = _super.call(this, id, index, browserGamepad) || this;
  66113. _this.onButtonDownObservable = new BABYLON.Observable();
  66114. _this.onButtonUpObservable = new BABYLON.Observable();
  66115. _this.type = Gamepad.GENERIC;
  66116. _this._buttons = new Array(browserGamepad.buttons.length);
  66117. return _this;
  66118. }
  66119. GenericPad.prototype.onbuttondown = function (callback) {
  66120. this._onbuttondown = callback;
  66121. };
  66122. GenericPad.prototype.onbuttonup = function (callback) {
  66123. this._onbuttonup = callback;
  66124. };
  66125. GenericPad.prototype._setButtonValue = function (newValue, currentValue, buttonIndex) {
  66126. if (newValue !== currentValue) {
  66127. if (newValue === 1) {
  66128. if (this._onbuttondown) {
  66129. this._onbuttondown(buttonIndex);
  66130. }
  66131. this.onButtonDownObservable.notifyObservers(buttonIndex);
  66132. }
  66133. if (newValue === 0) {
  66134. if (this._onbuttonup) {
  66135. this._onbuttonup(buttonIndex);
  66136. }
  66137. this.onButtonUpObservable.notifyObservers(buttonIndex);
  66138. }
  66139. }
  66140. return newValue;
  66141. };
  66142. GenericPad.prototype.update = function () {
  66143. _super.prototype.update.call(this);
  66144. for (var index = 0; index < this._buttons.length; index++) {
  66145. this._buttons[index] = this._setButtonValue(this.browserGamepad.buttons[index].value, this._buttons[index], index);
  66146. }
  66147. };
  66148. GenericPad.prototype.dispose = function () {
  66149. _super.prototype.dispose.call(this);
  66150. this.onButtonDownObservable.clear();
  66151. this.onButtonUpObservable.clear();
  66152. };
  66153. return GenericPad;
  66154. }(Gamepad));
  66155. BABYLON.GenericPad = GenericPad;
  66156. })(BABYLON || (BABYLON = {}));
  66157. //# sourceMappingURL=babylon.gamepad.js.map
  66158. "use strict";
  66159. var BABYLON;
  66160. (function (BABYLON) {
  66161. var Xbox360Button;
  66162. (function (Xbox360Button) {
  66163. Xbox360Button[Xbox360Button["A"] = 0] = "A";
  66164. Xbox360Button[Xbox360Button["B"] = 1] = "B";
  66165. Xbox360Button[Xbox360Button["X"] = 2] = "X";
  66166. Xbox360Button[Xbox360Button["Y"] = 3] = "Y";
  66167. Xbox360Button[Xbox360Button["Start"] = 4] = "Start";
  66168. Xbox360Button[Xbox360Button["Back"] = 5] = "Back";
  66169. Xbox360Button[Xbox360Button["LB"] = 6] = "LB";
  66170. Xbox360Button[Xbox360Button["RB"] = 7] = "RB";
  66171. Xbox360Button[Xbox360Button["LeftStick"] = 8] = "LeftStick";
  66172. Xbox360Button[Xbox360Button["RightStick"] = 9] = "RightStick";
  66173. })(Xbox360Button = BABYLON.Xbox360Button || (BABYLON.Xbox360Button = {}));
  66174. var Xbox360Dpad;
  66175. (function (Xbox360Dpad) {
  66176. Xbox360Dpad[Xbox360Dpad["Up"] = 0] = "Up";
  66177. Xbox360Dpad[Xbox360Dpad["Down"] = 1] = "Down";
  66178. Xbox360Dpad[Xbox360Dpad["Left"] = 2] = "Left";
  66179. Xbox360Dpad[Xbox360Dpad["Right"] = 3] = "Right";
  66180. })(Xbox360Dpad = BABYLON.Xbox360Dpad || (BABYLON.Xbox360Dpad = {}));
  66181. var Xbox360Pad = /** @class */ (function (_super) {
  66182. __extends(Xbox360Pad, _super);
  66183. function Xbox360Pad(id, index, gamepad, xboxOne) {
  66184. if (xboxOne === void 0) { xboxOne = false; }
  66185. var _this = _super.call(this, id, index, gamepad, 0, 1, 2, 3) || this;
  66186. _this._leftTrigger = 0;
  66187. _this._rightTrigger = 0;
  66188. _this.onButtonDownObservable = new BABYLON.Observable();
  66189. _this.onButtonUpObservable = new BABYLON.Observable();
  66190. _this.onPadDownObservable = new BABYLON.Observable();
  66191. _this.onPadUpObservable = new BABYLON.Observable();
  66192. _this._buttonA = 0;
  66193. _this._buttonB = 0;
  66194. _this._buttonX = 0;
  66195. _this._buttonY = 0;
  66196. _this._buttonBack = 0;
  66197. _this._buttonStart = 0;
  66198. _this._buttonLB = 0;
  66199. _this._buttonRB = 0;
  66200. _this._buttonLeftStick = 0;
  66201. _this._buttonRightStick = 0;
  66202. _this._dPadUp = 0;
  66203. _this._dPadDown = 0;
  66204. _this._dPadLeft = 0;
  66205. _this._dPadRight = 0;
  66206. _this._isXboxOnePad = false;
  66207. _this.type = BABYLON.Gamepad.XBOX;
  66208. _this._isXboxOnePad = xboxOne;
  66209. return _this;
  66210. }
  66211. Xbox360Pad.prototype.onlefttriggerchanged = function (callback) {
  66212. this._onlefttriggerchanged = callback;
  66213. };
  66214. Xbox360Pad.prototype.onrighttriggerchanged = function (callback) {
  66215. this._onrighttriggerchanged = callback;
  66216. };
  66217. Object.defineProperty(Xbox360Pad.prototype, "leftTrigger", {
  66218. get: function () {
  66219. return this._leftTrigger;
  66220. },
  66221. set: function (newValue) {
  66222. if (this._onlefttriggerchanged && this._leftTrigger !== newValue) {
  66223. this._onlefttriggerchanged(newValue);
  66224. }
  66225. this._leftTrigger = newValue;
  66226. },
  66227. enumerable: true,
  66228. configurable: true
  66229. });
  66230. Object.defineProperty(Xbox360Pad.prototype, "rightTrigger", {
  66231. get: function () {
  66232. return this._rightTrigger;
  66233. },
  66234. set: function (newValue) {
  66235. if (this._onrighttriggerchanged && this._rightTrigger !== newValue) {
  66236. this._onrighttriggerchanged(newValue);
  66237. }
  66238. this._rightTrigger = newValue;
  66239. },
  66240. enumerable: true,
  66241. configurable: true
  66242. });
  66243. Xbox360Pad.prototype.onbuttondown = function (callback) {
  66244. this._onbuttondown = callback;
  66245. };
  66246. Xbox360Pad.prototype.onbuttonup = function (callback) {
  66247. this._onbuttonup = callback;
  66248. };
  66249. Xbox360Pad.prototype.ondpaddown = function (callback) {
  66250. this._ondpaddown = callback;
  66251. };
  66252. Xbox360Pad.prototype.ondpadup = function (callback) {
  66253. this._ondpadup = callback;
  66254. };
  66255. Xbox360Pad.prototype._setButtonValue = function (newValue, currentValue, buttonType) {
  66256. if (newValue !== currentValue) {
  66257. if (newValue === 1) {
  66258. if (this._onbuttondown) {
  66259. this._onbuttondown(buttonType);
  66260. }
  66261. this.onButtonDownObservable.notifyObservers(buttonType);
  66262. }
  66263. if (newValue === 0) {
  66264. if (this._onbuttonup) {
  66265. this._onbuttonup(buttonType);
  66266. }
  66267. this.onButtonUpObservable.notifyObservers(buttonType);
  66268. }
  66269. }
  66270. return newValue;
  66271. };
  66272. Xbox360Pad.prototype._setDPadValue = function (newValue, currentValue, buttonType) {
  66273. if (newValue !== currentValue) {
  66274. if (newValue === 1) {
  66275. if (this._ondpaddown) {
  66276. this._ondpaddown(buttonType);
  66277. }
  66278. this.onPadDownObservable.notifyObservers(buttonType);
  66279. }
  66280. if (newValue === 0) {
  66281. if (this._ondpadup) {
  66282. this._ondpadup(buttonType);
  66283. }
  66284. this.onPadUpObservable.notifyObservers(buttonType);
  66285. }
  66286. }
  66287. return newValue;
  66288. };
  66289. Object.defineProperty(Xbox360Pad.prototype, "buttonA", {
  66290. get: function () {
  66291. return this._buttonA;
  66292. },
  66293. set: function (value) {
  66294. this._buttonA = this._setButtonValue(value, this._buttonA, Xbox360Button.A);
  66295. },
  66296. enumerable: true,
  66297. configurable: true
  66298. });
  66299. Object.defineProperty(Xbox360Pad.prototype, "buttonB", {
  66300. get: function () {
  66301. return this._buttonB;
  66302. },
  66303. set: function (value) {
  66304. this._buttonB = this._setButtonValue(value, this._buttonB, Xbox360Button.B);
  66305. },
  66306. enumerable: true,
  66307. configurable: true
  66308. });
  66309. Object.defineProperty(Xbox360Pad.prototype, "buttonX", {
  66310. get: function () {
  66311. return this._buttonX;
  66312. },
  66313. set: function (value) {
  66314. this._buttonX = this._setButtonValue(value, this._buttonX, Xbox360Button.X);
  66315. },
  66316. enumerable: true,
  66317. configurable: true
  66318. });
  66319. Object.defineProperty(Xbox360Pad.prototype, "buttonY", {
  66320. get: function () {
  66321. return this._buttonY;
  66322. },
  66323. set: function (value) {
  66324. this._buttonY = this._setButtonValue(value, this._buttonY, Xbox360Button.Y);
  66325. },
  66326. enumerable: true,
  66327. configurable: true
  66328. });
  66329. Object.defineProperty(Xbox360Pad.prototype, "buttonStart", {
  66330. get: function () {
  66331. return this._buttonStart;
  66332. },
  66333. set: function (value) {
  66334. this._buttonStart = this._setButtonValue(value, this._buttonStart, Xbox360Button.Start);
  66335. },
  66336. enumerable: true,
  66337. configurable: true
  66338. });
  66339. Object.defineProperty(Xbox360Pad.prototype, "buttonBack", {
  66340. get: function () {
  66341. return this._buttonBack;
  66342. },
  66343. set: function (value) {
  66344. this._buttonBack = this._setButtonValue(value, this._buttonBack, Xbox360Button.Back);
  66345. },
  66346. enumerable: true,
  66347. configurable: true
  66348. });
  66349. Object.defineProperty(Xbox360Pad.prototype, "buttonLB", {
  66350. get: function () {
  66351. return this._buttonLB;
  66352. },
  66353. set: function (value) {
  66354. this._buttonLB = this._setButtonValue(value, this._buttonLB, Xbox360Button.LB);
  66355. },
  66356. enumerable: true,
  66357. configurable: true
  66358. });
  66359. Object.defineProperty(Xbox360Pad.prototype, "buttonRB", {
  66360. get: function () {
  66361. return this._buttonRB;
  66362. },
  66363. set: function (value) {
  66364. this._buttonRB = this._setButtonValue(value, this._buttonRB, Xbox360Button.RB);
  66365. },
  66366. enumerable: true,
  66367. configurable: true
  66368. });
  66369. Object.defineProperty(Xbox360Pad.prototype, "buttonLeftStick", {
  66370. get: function () {
  66371. return this._buttonLeftStick;
  66372. },
  66373. set: function (value) {
  66374. this._buttonLeftStick = this._setButtonValue(value, this._buttonLeftStick, Xbox360Button.LeftStick);
  66375. },
  66376. enumerable: true,
  66377. configurable: true
  66378. });
  66379. Object.defineProperty(Xbox360Pad.prototype, "buttonRightStick", {
  66380. get: function () {
  66381. return this._buttonRightStick;
  66382. },
  66383. set: function (value) {
  66384. this._buttonRightStick = this._setButtonValue(value, this._buttonRightStick, Xbox360Button.RightStick);
  66385. },
  66386. enumerable: true,
  66387. configurable: true
  66388. });
  66389. Object.defineProperty(Xbox360Pad.prototype, "dPadUp", {
  66390. get: function () {
  66391. return this._dPadUp;
  66392. },
  66393. set: function (value) {
  66394. this._dPadUp = this._setDPadValue(value, this._dPadUp, Xbox360Dpad.Up);
  66395. },
  66396. enumerable: true,
  66397. configurable: true
  66398. });
  66399. Object.defineProperty(Xbox360Pad.prototype, "dPadDown", {
  66400. get: function () {
  66401. return this._dPadDown;
  66402. },
  66403. set: function (value) {
  66404. this._dPadDown = this._setDPadValue(value, this._dPadDown, Xbox360Dpad.Down);
  66405. },
  66406. enumerable: true,
  66407. configurable: true
  66408. });
  66409. Object.defineProperty(Xbox360Pad.prototype, "dPadLeft", {
  66410. get: function () {
  66411. return this._dPadLeft;
  66412. },
  66413. set: function (value) {
  66414. this._dPadLeft = this._setDPadValue(value, this._dPadLeft, Xbox360Dpad.Left);
  66415. },
  66416. enumerable: true,
  66417. configurable: true
  66418. });
  66419. Object.defineProperty(Xbox360Pad.prototype, "dPadRight", {
  66420. get: function () {
  66421. return this._dPadRight;
  66422. },
  66423. set: function (value) {
  66424. this._dPadRight = this._setDPadValue(value, this._dPadRight, Xbox360Dpad.Right);
  66425. },
  66426. enumerable: true,
  66427. configurable: true
  66428. });
  66429. Xbox360Pad.prototype.update = function () {
  66430. _super.prototype.update.call(this);
  66431. if (this._isXboxOnePad) {
  66432. this.buttonA = this.browserGamepad.buttons[0].value;
  66433. this.buttonB = this.browserGamepad.buttons[1].value;
  66434. this.buttonX = this.browserGamepad.buttons[2].value;
  66435. this.buttonY = this.browserGamepad.buttons[3].value;
  66436. this.buttonLB = this.browserGamepad.buttons[4].value;
  66437. this.buttonRB = this.browserGamepad.buttons[5].value;
  66438. this.leftTrigger = this.browserGamepad.axes[2];
  66439. this.rightTrigger = this.browserGamepad.axes[5];
  66440. this.buttonBack = this.browserGamepad.buttons[9].value;
  66441. this.buttonStart = this.browserGamepad.buttons[8].value;
  66442. this.buttonLeftStick = this.browserGamepad.buttons[6].value;
  66443. this.buttonRightStick = this.browserGamepad.buttons[7].value;
  66444. this.dPadUp = this.browserGamepad.buttons[11].value;
  66445. this.dPadDown = this.browserGamepad.buttons[12].value;
  66446. this.dPadLeft = this.browserGamepad.buttons[13].value;
  66447. this.dPadRight = this.browserGamepad.buttons[14].value;
  66448. }
  66449. else {
  66450. this.buttonA = this.browserGamepad.buttons[0].value;
  66451. this.buttonB = this.browserGamepad.buttons[1].value;
  66452. this.buttonX = this.browserGamepad.buttons[2].value;
  66453. this.buttonY = this.browserGamepad.buttons[3].value;
  66454. this.buttonLB = this.browserGamepad.buttons[4].value;
  66455. this.buttonRB = this.browserGamepad.buttons[5].value;
  66456. this.leftTrigger = this.browserGamepad.buttons[6].value;
  66457. this.rightTrigger = this.browserGamepad.buttons[7].value;
  66458. this.buttonBack = this.browserGamepad.buttons[8].value;
  66459. this.buttonStart = this.browserGamepad.buttons[9].value;
  66460. this.buttonLeftStick = this.browserGamepad.buttons[10].value;
  66461. this.buttonRightStick = this.browserGamepad.buttons[11].value;
  66462. this.dPadUp = this.browserGamepad.buttons[12].value;
  66463. this.dPadDown = this.browserGamepad.buttons[13].value;
  66464. this.dPadLeft = this.browserGamepad.buttons[14].value;
  66465. this.dPadRight = this.browserGamepad.buttons[15].value;
  66466. }
  66467. };
  66468. Xbox360Pad.prototype.dispose = function () {
  66469. _super.prototype.dispose.call(this);
  66470. this.onButtonDownObservable.clear();
  66471. this.onButtonUpObservable.clear();
  66472. this.onPadDownObservable.clear();
  66473. this.onPadUpObservable.clear();
  66474. };
  66475. return Xbox360Pad;
  66476. }(BABYLON.Gamepad));
  66477. BABYLON.Xbox360Pad = Xbox360Pad;
  66478. })(BABYLON || (BABYLON = {}));
  66479. //# sourceMappingURL=babylon.xboxGamepad.js.map
  66480. "use strict";
  66481. var BABYLON;
  66482. (function (BABYLON) {
  66483. var PoseEnabledControllerType;
  66484. (function (PoseEnabledControllerType) {
  66485. PoseEnabledControllerType[PoseEnabledControllerType["VIVE"] = 0] = "VIVE";
  66486. PoseEnabledControllerType[PoseEnabledControllerType["OCULUS"] = 1] = "OCULUS";
  66487. PoseEnabledControllerType[PoseEnabledControllerType["WINDOWS"] = 2] = "WINDOWS";
  66488. PoseEnabledControllerType[PoseEnabledControllerType["GEAR_VR"] = 3] = "GEAR_VR";
  66489. /**
  66490. * Google Daydream
  66491. */
  66492. PoseEnabledControllerType[PoseEnabledControllerType["DAYDREAM"] = 4] = "DAYDREAM";
  66493. PoseEnabledControllerType[PoseEnabledControllerType["GENERIC"] = 5] = "GENERIC";
  66494. })(PoseEnabledControllerType = BABYLON.PoseEnabledControllerType || (BABYLON.PoseEnabledControllerType = {}));
  66495. var PoseEnabledControllerHelper = /** @class */ (function () {
  66496. function PoseEnabledControllerHelper() {
  66497. }
  66498. PoseEnabledControllerHelper.InitiateController = function (vrGamepad) {
  66499. // Oculus Touch
  66500. if (vrGamepad.id.indexOf('Oculus Touch') !== -1) {
  66501. return new BABYLON.OculusTouchController(vrGamepad);
  66502. }
  66503. else if (vrGamepad.id.indexOf(BABYLON.WindowsMotionController.GAMEPAD_ID_PREFIX) === 0) {
  66504. return new BABYLON.WindowsMotionController(vrGamepad);
  66505. }
  66506. else if (vrGamepad.id.toLowerCase().indexOf('openvr') !== -1) {
  66507. return new BABYLON.ViveController(vrGamepad);
  66508. }
  66509. else if (vrGamepad.id.indexOf(BABYLON.GearVRController.GAMEPAD_ID_PREFIX) === 0) {
  66510. return new BABYLON.GearVRController(vrGamepad);
  66511. }
  66512. else if (vrGamepad.id.indexOf(BABYLON.DaydreamController.GAMEPAD_ID_PREFIX) === 0) {
  66513. return new BABYLON.DaydreamController(vrGamepad);
  66514. }
  66515. else {
  66516. return new BABYLON.GenericController(vrGamepad);
  66517. }
  66518. };
  66519. return PoseEnabledControllerHelper;
  66520. }());
  66521. BABYLON.PoseEnabledControllerHelper = PoseEnabledControllerHelper;
  66522. var PoseEnabledController = /** @class */ (function (_super) {
  66523. __extends(PoseEnabledController, _super);
  66524. function PoseEnabledController(browserGamepad) {
  66525. var _this = _super.call(this, browserGamepad.id, browserGamepad.index, browserGamepad) || this;
  66526. // Represents device position and rotation in room space. Should only be used to help calculate babylon space values
  66527. _this._deviceRoomPosition = BABYLON.Vector3.Zero();
  66528. _this._deviceRoomRotationQuaternion = new BABYLON.Quaternion();
  66529. // Represents device position and rotation in babylon space
  66530. _this.devicePosition = BABYLON.Vector3.Zero();
  66531. _this.deviceRotationQuaternion = new BABYLON.Quaternion();
  66532. _this.deviceScaleFactor = 1;
  66533. _this._leftHandSystemQuaternion = new BABYLON.Quaternion();
  66534. _this._deviceToWorld = BABYLON.Matrix.Identity();
  66535. /**
  66536. * Node to be used when casting a ray from the controller
  66537. */
  66538. _this._pointingPoseNode = null;
  66539. _this._workingMatrix = BABYLON.Matrix.Identity();
  66540. _this.type = BABYLON.Gamepad.POSE_ENABLED;
  66541. _this.controllerType = PoseEnabledControllerType.GENERIC;
  66542. _this.position = BABYLON.Vector3.Zero();
  66543. _this.rotationQuaternion = new BABYLON.Quaternion();
  66544. _this._calculatedPosition = BABYLON.Vector3.Zero();
  66545. _this._calculatedRotation = new BABYLON.Quaternion();
  66546. BABYLON.Quaternion.RotationYawPitchRollToRef(Math.PI, 0, 0, _this._leftHandSystemQuaternion);
  66547. return _this;
  66548. }
  66549. PoseEnabledController.prototype.update = function () {
  66550. _super.prototype.update.call(this);
  66551. var pose = this.browserGamepad.pose;
  66552. this.updateFromDevice(pose);
  66553. BABYLON.Vector3.TransformCoordinatesToRef(this._calculatedPosition, this._deviceToWorld, this.devicePosition);
  66554. this._deviceToWorld.getRotationMatrixToRef(this._workingMatrix);
  66555. BABYLON.Quaternion.FromRotationMatrixToRef(this._workingMatrix, this.deviceRotationQuaternion);
  66556. this.deviceRotationQuaternion.multiplyInPlace(this._calculatedRotation);
  66557. if (this._mesh) {
  66558. this._mesh.position.copyFrom(this.devicePosition);
  66559. if (this._mesh.rotationQuaternion) {
  66560. this._mesh.rotationQuaternion.copyFrom(this.deviceRotationQuaternion);
  66561. }
  66562. }
  66563. };
  66564. PoseEnabledController.prototype.updateFromDevice = function (poseData) {
  66565. if (poseData) {
  66566. this.rawPose = poseData;
  66567. if (poseData.position) {
  66568. this._deviceRoomPosition.copyFromFloats(poseData.position[0], poseData.position[1], -poseData.position[2]);
  66569. if (this._mesh && this._mesh.getScene().useRightHandedSystem) {
  66570. this._deviceRoomPosition.z *= -1;
  66571. }
  66572. this._deviceRoomPosition.scaleToRef(this.deviceScaleFactor, this._calculatedPosition);
  66573. this._calculatedPosition.addInPlace(this.position);
  66574. }
  66575. var pose = this.rawPose;
  66576. if (poseData.orientation && pose.orientation) {
  66577. this._deviceRoomRotationQuaternion.copyFromFloats(pose.orientation[0], pose.orientation[1], -pose.orientation[2], -pose.orientation[3]);
  66578. if (this._mesh) {
  66579. if (this._mesh.getScene().useRightHandedSystem) {
  66580. this._deviceRoomRotationQuaternion.z *= -1;
  66581. this._deviceRoomRotationQuaternion.w *= -1;
  66582. }
  66583. else {
  66584. this._deviceRoomRotationQuaternion.multiplyToRef(this._leftHandSystemQuaternion, this._deviceRoomRotationQuaternion);
  66585. }
  66586. }
  66587. // if the camera is set, rotate to the camera's rotation
  66588. this._deviceRoomRotationQuaternion.multiplyToRef(this.rotationQuaternion, this._calculatedRotation);
  66589. }
  66590. }
  66591. };
  66592. PoseEnabledController.prototype.attachToMesh = function (mesh) {
  66593. if (this._mesh) {
  66594. this._mesh.parent = null;
  66595. }
  66596. this._mesh = mesh;
  66597. if (this._poseControlledCamera) {
  66598. this._mesh.parent = this._poseControlledCamera;
  66599. }
  66600. if (!this._mesh.rotationQuaternion) {
  66601. this._mesh.rotationQuaternion = new BABYLON.Quaternion();
  66602. }
  66603. };
  66604. PoseEnabledController.prototype.attachToPoseControlledCamera = function (camera) {
  66605. this._poseControlledCamera = camera;
  66606. if (this._mesh) {
  66607. this._mesh.parent = this._poseControlledCamera;
  66608. }
  66609. };
  66610. PoseEnabledController.prototype.dispose = function () {
  66611. if (this._mesh) {
  66612. this._mesh.dispose();
  66613. }
  66614. this._mesh = null;
  66615. _super.prototype.dispose.call(this);
  66616. };
  66617. Object.defineProperty(PoseEnabledController.prototype, "mesh", {
  66618. get: function () {
  66619. return this._mesh;
  66620. },
  66621. enumerable: true,
  66622. configurable: true
  66623. });
  66624. PoseEnabledController.prototype.getForwardRay = function (length) {
  66625. if (length === void 0) { length = 100; }
  66626. if (!this.mesh) {
  66627. return new BABYLON.Ray(BABYLON.Vector3.Zero(), new BABYLON.Vector3(0, 0, 1), length);
  66628. }
  66629. var m = this._pointingPoseNode ? this._pointingPoseNode.getWorldMatrix() : this.mesh.getWorldMatrix();
  66630. var origin = m.getTranslation();
  66631. var forward = new BABYLON.Vector3(0, 0, -1);
  66632. var forwardWorld = BABYLON.Vector3.TransformNormal(forward, m);
  66633. var direction = BABYLON.Vector3.Normalize(forwardWorld);
  66634. return new BABYLON.Ray(origin, direction, length);
  66635. };
  66636. /**
  66637. * Name of the child mesh that can be used to cast a ray from the controller
  66638. */
  66639. PoseEnabledController.POINTING_POSE = "POINTING_POSE";
  66640. return PoseEnabledController;
  66641. }(BABYLON.Gamepad));
  66642. BABYLON.PoseEnabledController = PoseEnabledController;
  66643. })(BABYLON || (BABYLON = {}));
  66644. //# sourceMappingURL=babylon.poseEnabledController.js.map
  66645. "use strict";
  66646. var BABYLON;
  66647. (function (BABYLON) {
  66648. var WebVRController = /** @class */ (function (_super) {
  66649. __extends(WebVRController, _super);
  66650. function WebVRController(vrGamepad) {
  66651. var _this = _super.call(this, vrGamepad) || this;
  66652. // Observables
  66653. _this.onTriggerStateChangedObservable = new BABYLON.Observable();
  66654. _this.onMainButtonStateChangedObservable = new BABYLON.Observable();
  66655. _this.onSecondaryButtonStateChangedObservable = new BABYLON.Observable();
  66656. _this.onPadStateChangedObservable = new BABYLON.Observable();
  66657. _this.onPadValuesChangedObservable = new BABYLON.Observable();
  66658. _this.pad = { x: 0, y: 0 };
  66659. // avoid GC, store state in a tmp object
  66660. _this._changes = {
  66661. pressChanged: false,
  66662. touchChanged: false,
  66663. valueChanged: false,
  66664. changed: false
  66665. };
  66666. _this._buttons = new Array(vrGamepad.buttons.length);
  66667. _this.hand = vrGamepad.hand;
  66668. return _this;
  66669. }
  66670. WebVRController.prototype.onButtonStateChange = function (callback) {
  66671. this._onButtonStateChange = callback;
  66672. };
  66673. Object.defineProperty(WebVRController.prototype, "defaultModel", {
  66674. get: function () {
  66675. return this._defaultModel;
  66676. },
  66677. enumerable: true,
  66678. configurable: true
  66679. });
  66680. WebVRController.prototype.update = function () {
  66681. _super.prototype.update.call(this);
  66682. for (var index = 0; index < this._buttons.length; index++) {
  66683. this._setButtonValue(this.browserGamepad.buttons[index], this._buttons[index], index);
  66684. }
  66685. ;
  66686. if (this.leftStick.x !== this.pad.x || this.leftStick.y !== this.pad.y) {
  66687. this.pad.x = this.leftStick.x;
  66688. this.pad.y = this.leftStick.y;
  66689. this.onPadValuesChangedObservable.notifyObservers(this.pad);
  66690. }
  66691. };
  66692. WebVRController.prototype._setButtonValue = function (newState, currentState, buttonIndex) {
  66693. if (!newState) {
  66694. newState = {
  66695. pressed: false,
  66696. touched: false,
  66697. value: 0
  66698. };
  66699. }
  66700. if (!currentState) {
  66701. this._buttons[buttonIndex] = {
  66702. pressed: newState.pressed,
  66703. touched: newState.touched,
  66704. value: newState.value
  66705. };
  66706. return;
  66707. }
  66708. this._checkChanges(newState, currentState);
  66709. if (this._changes.changed) {
  66710. this._onButtonStateChange && this._onButtonStateChange(this.index, buttonIndex, newState);
  66711. this._handleButtonChange(buttonIndex, newState, this._changes);
  66712. }
  66713. this._buttons[buttonIndex].pressed = newState.pressed;
  66714. this._buttons[buttonIndex].touched = newState.touched;
  66715. // oculus triggers are never 0, thou not touched.
  66716. this._buttons[buttonIndex].value = newState.value < 0.00000001 ? 0 : newState.value;
  66717. };
  66718. WebVRController.prototype._checkChanges = function (newState, currentState) {
  66719. this._changes.pressChanged = newState.pressed !== currentState.pressed;
  66720. this._changes.touchChanged = newState.touched !== currentState.touched;
  66721. this._changes.valueChanged = newState.value !== currentState.value;
  66722. this._changes.changed = this._changes.pressChanged || this._changes.touchChanged || this._changes.valueChanged;
  66723. return this._changes;
  66724. };
  66725. WebVRController.prototype.dispose = function () {
  66726. _super.prototype.dispose.call(this);
  66727. this.onTriggerStateChangedObservable.clear();
  66728. this.onMainButtonStateChangedObservable.clear();
  66729. this.onSecondaryButtonStateChangedObservable.clear();
  66730. this.onPadStateChangedObservable.clear();
  66731. this.onPadValuesChangedObservable.clear();
  66732. };
  66733. return WebVRController;
  66734. }(BABYLON.PoseEnabledController));
  66735. BABYLON.WebVRController = WebVRController;
  66736. })(BABYLON || (BABYLON = {}));
  66737. //# sourceMappingURL=babylon.webVRController.js.map
  66738. "use strict";
  66739. var BABYLON;
  66740. (function (BABYLON) {
  66741. var OculusTouchController = /** @class */ (function (_super) {
  66742. __extends(OculusTouchController, _super);
  66743. function OculusTouchController(vrGamepad) {
  66744. var _this = _super.call(this, vrGamepad) || this;
  66745. _this.onSecondaryTriggerStateChangedObservable = new BABYLON.Observable();
  66746. _this.onThumbRestChangedObservable = new BABYLON.Observable();
  66747. _this.controllerType = BABYLON.PoseEnabledControllerType.OCULUS;
  66748. return _this;
  66749. }
  66750. OculusTouchController.prototype.initControllerMesh = function (scene, meshLoaded) {
  66751. var _this = this;
  66752. var meshName;
  66753. // Hand
  66754. if (this.hand === 'left') {
  66755. meshName = OculusTouchController.MODEL_LEFT_FILENAME;
  66756. }
  66757. else {
  66758. meshName = OculusTouchController.MODEL_RIGHT_FILENAME;
  66759. }
  66760. BABYLON.SceneLoader.ImportMesh("", OculusTouchController.MODEL_BASE_URL, meshName, scene, function (newMeshes) {
  66761. /*
  66762. Parent Mesh name: oculus_touch_left
  66763. - body
  66764. - trigger
  66765. - thumbstick
  66766. - grip
  66767. - button_y
  66768. - button_x
  66769. - button_enter
  66770. */
  66771. _this._defaultModel = newMeshes[1];
  66772. _this.attachToMesh(_this._defaultModel);
  66773. if (meshLoaded) {
  66774. meshLoaded(_this._defaultModel);
  66775. }
  66776. });
  66777. };
  66778. Object.defineProperty(OculusTouchController.prototype, "onAButtonStateChangedObservable", {
  66779. // helper getters for left and right hand.
  66780. get: function () {
  66781. if (this.hand === 'right') {
  66782. return this.onMainButtonStateChangedObservable;
  66783. }
  66784. else {
  66785. throw new Error('No A button on left hand');
  66786. }
  66787. },
  66788. enumerable: true,
  66789. configurable: true
  66790. });
  66791. Object.defineProperty(OculusTouchController.prototype, "onBButtonStateChangedObservable", {
  66792. get: function () {
  66793. if (this.hand === 'right') {
  66794. return this.onSecondaryButtonStateChangedObservable;
  66795. }
  66796. else {
  66797. throw new Error('No B button on left hand');
  66798. }
  66799. },
  66800. enumerable: true,
  66801. configurable: true
  66802. });
  66803. Object.defineProperty(OculusTouchController.prototype, "onXButtonStateChangedObservable", {
  66804. get: function () {
  66805. if (this.hand === 'left') {
  66806. return this.onMainButtonStateChangedObservable;
  66807. }
  66808. else {
  66809. throw new Error('No X button on right hand');
  66810. }
  66811. },
  66812. enumerable: true,
  66813. configurable: true
  66814. });
  66815. Object.defineProperty(OculusTouchController.prototype, "onYButtonStateChangedObservable", {
  66816. get: function () {
  66817. if (this.hand === 'left') {
  66818. return this.onSecondaryButtonStateChangedObservable;
  66819. }
  66820. else {
  66821. throw new Error('No Y button on right hand');
  66822. }
  66823. },
  66824. enumerable: true,
  66825. configurable: true
  66826. });
  66827. /*
  66828. 0) thumb stick (touch, press, value = pressed (0,1)). value is in this.leftStick
  66829. 1) index trigger (touch (?), press (only when value > 0.1), value 0 to 1)
  66830. 2) secondary trigger (same)
  66831. 3) A (right) X (left), touch, pressed = value
  66832. 4) B / Y
  66833. 5) thumb rest
  66834. */
  66835. OculusTouchController.prototype._handleButtonChange = function (buttonIdx, state, changes) {
  66836. var notifyObject = state; //{ state: state, changes: changes };
  66837. var triggerDirection = this.hand === 'right' ? -1 : 1;
  66838. switch (buttonIdx) {
  66839. case 0:
  66840. this.onPadStateChangedObservable.notifyObservers(notifyObject);
  66841. return;
  66842. case 1:// index trigger
  66843. if (this._defaultModel) {
  66844. (this._defaultModel.getChildren()[3]).rotation.x = -notifyObject.value * 0.20;
  66845. (this._defaultModel.getChildren()[3]).position.y = -notifyObject.value * 0.005;
  66846. (this._defaultModel.getChildren()[3]).position.z = -notifyObject.value * 0.005;
  66847. }
  66848. this.onTriggerStateChangedObservable.notifyObservers(notifyObject);
  66849. return;
  66850. case 2:// secondary trigger
  66851. if (this._defaultModel) {
  66852. (this._defaultModel.getChildren()[4]).position.x = triggerDirection * notifyObject.value * 0.0035;
  66853. }
  66854. this.onSecondaryTriggerStateChangedObservable.notifyObservers(notifyObject);
  66855. return;
  66856. case 3:
  66857. if (this._defaultModel) {
  66858. if (notifyObject.pressed) {
  66859. (this._defaultModel.getChildren()[1]).position.y = -0.001;
  66860. }
  66861. else {
  66862. (this._defaultModel.getChildren()[1]).position.y = 0;
  66863. }
  66864. }
  66865. this.onMainButtonStateChangedObservable.notifyObservers(notifyObject);
  66866. return;
  66867. case 4:
  66868. if (this._defaultModel) {
  66869. if (notifyObject.pressed) {
  66870. (this._defaultModel.getChildren()[2]).position.y = -0.001;
  66871. }
  66872. else {
  66873. (this._defaultModel.getChildren()[2]).position.y = 0;
  66874. }
  66875. }
  66876. this.onSecondaryButtonStateChangedObservable.notifyObservers(notifyObject);
  66877. return;
  66878. case 5:
  66879. this.onThumbRestChangedObservable.notifyObservers(notifyObject);
  66880. return;
  66881. }
  66882. };
  66883. OculusTouchController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/oculus/';
  66884. OculusTouchController.MODEL_LEFT_FILENAME = 'left.babylon';
  66885. OculusTouchController.MODEL_RIGHT_FILENAME = 'right.babylon';
  66886. return OculusTouchController;
  66887. }(BABYLON.WebVRController));
  66888. BABYLON.OculusTouchController = OculusTouchController;
  66889. })(BABYLON || (BABYLON = {}));
  66890. //# sourceMappingURL=babylon.oculusTouchController.js.map
  66891. "use strict";
  66892. var BABYLON;
  66893. (function (BABYLON) {
  66894. var ViveController = /** @class */ (function (_super) {
  66895. __extends(ViveController, _super);
  66896. function ViveController(vrGamepad) {
  66897. var _this = _super.call(this, vrGamepad) || this;
  66898. _this.controllerType = BABYLON.PoseEnabledControllerType.VIVE;
  66899. _this._invertLeftStickY = true;
  66900. return _this;
  66901. }
  66902. ViveController.prototype.initControllerMesh = function (scene, meshLoaded) {
  66903. var _this = this;
  66904. BABYLON.SceneLoader.ImportMesh("", ViveController.MODEL_BASE_URL, ViveController.MODEL_FILENAME, scene, function (newMeshes) {
  66905. /*
  66906. Parent Mesh name: ViveWand
  66907. - body
  66908. - r_gripper
  66909. - l_gripper
  66910. - menu_button
  66911. - system_button
  66912. - trackpad
  66913. - trigger
  66914. - LED
  66915. */
  66916. _this._defaultModel = newMeshes[1];
  66917. _this.attachToMesh(_this._defaultModel);
  66918. if (meshLoaded) {
  66919. meshLoaded(_this._defaultModel);
  66920. }
  66921. });
  66922. };
  66923. Object.defineProperty(ViveController.prototype, "onLeftButtonStateChangedObservable", {
  66924. get: function () {
  66925. return this.onMainButtonStateChangedObservable;
  66926. },
  66927. enumerable: true,
  66928. configurable: true
  66929. });
  66930. Object.defineProperty(ViveController.prototype, "onRightButtonStateChangedObservable", {
  66931. get: function () {
  66932. return this.onMainButtonStateChangedObservable;
  66933. },
  66934. enumerable: true,
  66935. configurable: true
  66936. });
  66937. Object.defineProperty(ViveController.prototype, "onMenuButtonStateChangedObservable", {
  66938. get: function () {
  66939. return this.onSecondaryButtonStateChangedObservable;
  66940. },
  66941. enumerable: true,
  66942. configurable: true
  66943. });
  66944. /**
  66945. * Vive mapping:
  66946. * 0: touchpad
  66947. * 1: trigger
  66948. * 2: left AND right buttons
  66949. * 3: menu button
  66950. */
  66951. ViveController.prototype._handleButtonChange = function (buttonIdx, state, changes) {
  66952. var notifyObject = state; //{ state: state, changes: changes };
  66953. switch (buttonIdx) {
  66954. case 0:
  66955. this.onPadStateChangedObservable.notifyObservers(notifyObject);
  66956. return;
  66957. case 1:// index trigger
  66958. if (this._defaultModel) {
  66959. (this._defaultModel.getChildren()[6]).rotation.x = -notifyObject.value * 0.15;
  66960. }
  66961. this.onTriggerStateChangedObservable.notifyObservers(notifyObject);
  66962. return;
  66963. case 2:// left AND right button
  66964. this.onMainButtonStateChangedObservable.notifyObservers(notifyObject);
  66965. return;
  66966. case 3:
  66967. if (this._defaultModel) {
  66968. if (notifyObject.pressed) {
  66969. (this._defaultModel.getChildren()[2]).position.y = -0.001;
  66970. }
  66971. else {
  66972. (this._defaultModel.getChildren()[2]).position.y = 0;
  66973. }
  66974. }
  66975. this.onSecondaryButtonStateChangedObservable.notifyObservers(notifyObject);
  66976. return;
  66977. }
  66978. };
  66979. ViveController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/vive/';
  66980. ViveController.MODEL_FILENAME = 'wand.babylon';
  66981. return ViveController;
  66982. }(BABYLON.WebVRController));
  66983. BABYLON.ViveController = ViveController;
  66984. })(BABYLON || (BABYLON = {}));
  66985. //# sourceMappingURL=babylon.viveController.js.map
  66986. "use strict";
  66987. var BABYLON;
  66988. (function (BABYLON) {
  66989. var GenericController = /** @class */ (function (_super) {
  66990. __extends(GenericController, _super);
  66991. function GenericController(vrGamepad) {
  66992. return _super.call(this, vrGamepad) || this;
  66993. }
  66994. GenericController.prototype.initControllerMesh = function (scene, meshLoaded) {
  66995. var _this = this;
  66996. BABYLON.SceneLoader.ImportMesh("", GenericController.MODEL_BASE_URL, GenericController.MODEL_FILENAME, scene, function (newMeshes) {
  66997. _this._defaultModel = newMeshes[1];
  66998. _this.attachToMesh(_this._defaultModel);
  66999. if (meshLoaded) {
  67000. meshLoaded(_this._defaultModel);
  67001. }
  67002. });
  67003. };
  67004. GenericController.prototype._handleButtonChange = function (buttonIdx, state, changes) {
  67005. console.log("Button id: " + buttonIdx + "state: ");
  67006. console.dir(state);
  67007. };
  67008. GenericController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/generic/';
  67009. GenericController.MODEL_FILENAME = 'generic.babylon';
  67010. return GenericController;
  67011. }(BABYLON.WebVRController));
  67012. BABYLON.GenericController = GenericController;
  67013. })(BABYLON || (BABYLON = {}));
  67014. //# sourceMappingURL=babylon.genericController.js.map
  67015. "use strict";
  67016. var BABYLON;
  67017. (function (BABYLON) {
  67018. var LoadedMeshInfo = /** @class */ (function () {
  67019. function LoadedMeshInfo() {
  67020. this.buttonMeshes = {};
  67021. this.axisMeshes = {};
  67022. }
  67023. return LoadedMeshInfo;
  67024. }());
  67025. var WindowsMotionController = /** @class */ (function (_super) {
  67026. __extends(WindowsMotionController, _super);
  67027. function WindowsMotionController(vrGamepad) {
  67028. var _this = _super.call(this, vrGamepad) || this;
  67029. _this._mapping = {
  67030. // Semantic button names
  67031. buttons: ['thumbstick', 'trigger', 'grip', 'menu', 'trackpad'],
  67032. // A mapping of the button name to glTF model node name
  67033. // that should be transformed by button value.
  67034. buttonMeshNames: {
  67035. 'trigger': 'SELECT',
  67036. 'menu': 'MENU',
  67037. 'grip': 'GRASP',
  67038. 'thumbstick': 'THUMBSTICK_PRESS',
  67039. 'trackpad': 'TOUCHPAD_PRESS'
  67040. },
  67041. // This mapping is used to translate from the Motion Controller to Babylon semantics
  67042. buttonObservableNames: {
  67043. 'trigger': 'onTriggerStateChangedObservable',
  67044. 'menu': 'onSecondaryButtonStateChangedObservable',
  67045. 'grip': 'onMainButtonStateChangedObservable',
  67046. 'thumbstick': 'onPadStateChangedObservable',
  67047. 'trackpad': 'onTrackpadChangedObservable'
  67048. },
  67049. // A mapping of the axis name to glTF model node name
  67050. // that should be transformed by axis value.
  67051. // This array mirrors the browserGamepad.axes array, such that
  67052. // the mesh corresponding to axis 0 is in this array index 0.
  67053. axisMeshNames: [
  67054. 'THUMBSTICK_X',
  67055. 'THUMBSTICK_Y',
  67056. 'TOUCHPAD_TOUCH_X',
  67057. 'TOUCHPAD_TOUCH_Y'
  67058. ],
  67059. pointingPoseMeshName: BABYLON.PoseEnabledController.POINTING_POSE
  67060. };
  67061. _this.onTrackpadChangedObservable = new BABYLON.Observable();
  67062. _this.onTrackpadValuesChangedObservable = new BABYLON.Observable();
  67063. _this.trackpad = { x: 0, y: 0 };
  67064. _this.controllerType = BABYLON.PoseEnabledControllerType.WINDOWS;
  67065. _this._loadedMeshInfo = null;
  67066. return _this;
  67067. }
  67068. Object.defineProperty(WindowsMotionController.prototype, "onTriggerButtonStateChangedObservable", {
  67069. get: function () {
  67070. return this.onTriggerStateChangedObservable;
  67071. },
  67072. enumerable: true,
  67073. configurable: true
  67074. });
  67075. Object.defineProperty(WindowsMotionController.prototype, "onMenuButtonStateChangedObservable", {
  67076. get: function () {
  67077. return this.onSecondaryButtonStateChangedObservable;
  67078. },
  67079. enumerable: true,
  67080. configurable: true
  67081. });
  67082. Object.defineProperty(WindowsMotionController.prototype, "onGripButtonStateChangedObservable", {
  67083. get: function () {
  67084. return this.onMainButtonStateChangedObservable;
  67085. },
  67086. enumerable: true,
  67087. configurable: true
  67088. });
  67089. Object.defineProperty(WindowsMotionController.prototype, "onThumbstickButtonStateChangedObservable", {
  67090. get: function () {
  67091. return this.onPadStateChangedObservable;
  67092. },
  67093. enumerable: true,
  67094. configurable: true
  67095. });
  67096. Object.defineProperty(WindowsMotionController.prototype, "onTouchpadButtonStateChangedObservable", {
  67097. get: function () {
  67098. return this.onTrackpadChangedObservable;
  67099. },
  67100. enumerable: true,
  67101. configurable: true
  67102. });
  67103. Object.defineProperty(WindowsMotionController.prototype, "onTouchpadValuesChangedObservable", {
  67104. get: function () {
  67105. return this.onTrackpadValuesChangedObservable;
  67106. },
  67107. enumerable: true,
  67108. configurable: true
  67109. });
  67110. /**
  67111. * Called once per frame by the engine.
  67112. */
  67113. WindowsMotionController.prototype.update = function () {
  67114. _super.prototype.update.call(this);
  67115. if (this.browserGamepad.axes) {
  67116. if (this.browserGamepad.axes[2] != this.trackpad.x || this.browserGamepad.axes[3] != this.trackpad.y) {
  67117. this.trackpad.x = this.browserGamepad["axes"][2];
  67118. this.trackpad.y = this.browserGamepad["axes"][3];
  67119. this.onTrackpadValuesChangedObservable.notifyObservers(this.trackpad);
  67120. }
  67121. // Only need to animate axes if there is a loaded mesh
  67122. if (this._loadedMeshInfo) {
  67123. for (var axis = 0; axis < this._mapping.axisMeshNames.length; axis++) {
  67124. this.lerpAxisTransform(axis, this.browserGamepad.axes[axis]);
  67125. }
  67126. }
  67127. }
  67128. };
  67129. /**
  67130. * Called once for each button that changed state since the last frame
  67131. * @param buttonIdx Which button index changed
  67132. * @param state New state of the button
  67133. * @param changes Which properties on the state changed since last frame
  67134. */
  67135. WindowsMotionController.prototype._handleButtonChange = function (buttonIdx, state, changes) {
  67136. var buttonName = this._mapping.buttons[buttonIdx];
  67137. if (!buttonName) {
  67138. return;
  67139. }
  67140. // Only emit events for buttons that we know how to map from index to name
  67141. var observable = this[(this._mapping.buttonObservableNames)[buttonName]];
  67142. if (observable) {
  67143. observable.notifyObservers(state);
  67144. }
  67145. this.lerpButtonTransform(buttonName, state.value);
  67146. };
  67147. WindowsMotionController.prototype.lerpButtonTransform = function (buttonName, buttonValue) {
  67148. // If there is no loaded mesh, there is nothing to transform.
  67149. if (!this._loadedMeshInfo) {
  67150. return;
  67151. }
  67152. var meshInfo = this._loadedMeshInfo.buttonMeshes[buttonName];
  67153. if (!meshInfo.unpressed.rotationQuaternion || !meshInfo.pressed.rotationQuaternion || !meshInfo.value.rotationQuaternion) {
  67154. return;
  67155. }
  67156. BABYLON.Quaternion.SlerpToRef(meshInfo.unpressed.rotationQuaternion, meshInfo.pressed.rotationQuaternion, buttonValue, meshInfo.value.rotationQuaternion);
  67157. BABYLON.Vector3.LerpToRef(meshInfo.unpressed.position, meshInfo.pressed.position, buttonValue, meshInfo.value.position);
  67158. };
  67159. WindowsMotionController.prototype.lerpAxisTransform = function (axis, axisValue) {
  67160. if (!this._loadedMeshInfo) {
  67161. return;
  67162. }
  67163. var meshInfo = this._loadedMeshInfo.axisMeshes[axis];
  67164. if (!meshInfo) {
  67165. return;
  67166. }
  67167. if (!meshInfo.min.rotationQuaternion || !meshInfo.max.rotationQuaternion || !meshInfo.value.rotationQuaternion) {
  67168. return;
  67169. }
  67170. // Convert from gamepad value range (-1 to +1) to lerp range (0 to 1)
  67171. var lerpValue = axisValue * 0.5 + 0.5;
  67172. BABYLON.Quaternion.SlerpToRef(meshInfo.min.rotationQuaternion, meshInfo.max.rotationQuaternion, lerpValue, meshInfo.value.rotationQuaternion);
  67173. BABYLON.Vector3.LerpToRef(meshInfo.min.position, meshInfo.max.position, lerpValue, meshInfo.value.position);
  67174. };
  67175. /**
  67176. * Implements abstract method on WebVRController class, loading controller meshes and calling this.attachToMesh if successful.
  67177. * @param scene scene in which to add meshes
  67178. * @param meshLoaded optional callback function that will be called if the mesh loads successfully.
  67179. */
  67180. WindowsMotionController.prototype.initControllerMesh = function (scene, meshLoaded, forceDefault) {
  67181. var _this = this;
  67182. if (forceDefault === void 0) { forceDefault = false; }
  67183. var path;
  67184. var filename;
  67185. // Checking if GLB loader is present
  67186. if (BABYLON.SceneLoader.IsPluginForExtensionAvailable(".glb")) {
  67187. // Determine the device specific folder based on the ID suffix
  67188. var device = 'default';
  67189. if (this.id && !forceDefault) {
  67190. var match = this.id.match(WindowsMotionController.GAMEPAD_ID_PATTERN);
  67191. device = ((match && match[0]) || device);
  67192. }
  67193. // Hand
  67194. if (this.hand === 'left') {
  67195. filename = WindowsMotionController.MODEL_LEFT_FILENAME;
  67196. }
  67197. else {
  67198. filename = WindowsMotionController.MODEL_RIGHT_FILENAME;
  67199. }
  67200. path = WindowsMotionController.MODEL_BASE_URL + device + '/';
  67201. }
  67202. else {
  67203. BABYLON.Tools.Warn("You need to reference GLTF loader to load Windows Motion Controllers model. Falling back to generic models");
  67204. path = BABYLON.GenericController.MODEL_BASE_URL;
  67205. filename = BABYLON.GenericController.MODEL_FILENAME;
  67206. }
  67207. BABYLON.SceneLoader.ImportMesh("", path, filename, scene, function (meshes) {
  67208. // glTF files successfully loaded from the remote server, now process them to ensure they are in the right format.
  67209. _this._loadedMeshInfo = _this.processModel(scene, meshes);
  67210. if (!_this._loadedMeshInfo) {
  67211. return;
  67212. }
  67213. _this._defaultModel = _this._loadedMeshInfo.rootNode;
  67214. _this.attachToMesh(_this._defaultModel);
  67215. if (meshLoaded) {
  67216. meshLoaded(_this._defaultModel);
  67217. }
  67218. }, null, function (scene, message) {
  67219. BABYLON.Tools.Log(message);
  67220. BABYLON.Tools.Warn('Failed to retrieve controller model from the remote server: ' + path + filename);
  67221. if (!forceDefault) {
  67222. _this.initControllerMesh(scene, meshLoaded, true);
  67223. }
  67224. });
  67225. };
  67226. /**
  67227. * Takes a list of meshes (as loaded from the glTF file) and finds the root node, as well as nodes that
  67228. * can be transformed by button presses and axes values, based on this._mapping.
  67229. *
  67230. * @param scene scene in which the meshes exist
  67231. * @param meshes list of meshes that make up the controller model to process
  67232. * @return structured view of the given meshes, with mapping of buttons and axes to meshes that can be transformed.
  67233. */
  67234. WindowsMotionController.prototype.processModel = function (scene, meshes) {
  67235. var loadedMeshInfo = null;
  67236. // Create a new mesh to contain the glTF hierarchy
  67237. var parentMesh = new BABYLON.Mesh(this.id + " " + this.hand, scene);
  67238. // Find the root node in the loaded glTF scene, and attach it as a child of 'parentMesh'
  67239. var childMesh = null;
  67240. for (var i = 0; i < meshes.length; i++) {
  67241. var mesh = meshes[i];
  67242. if (!mesh.parent) {
  67243. // Exclude controller meshes from picking results
  67244. mesh.isPickable = false;
  67245. // Handle root node, attach to the new parentMesh
  67246. childMesh = mesh;
  67247. break;
  67248. }
  67249. }
  67250. if (childMesh) {
  67251. childMesh.setParent(parentMesh);
  67252. // Create our mesh info. Note that this method will always return non-null.
  67253. loadedMeshInfo = this.createMeshInfo(parentMesh);
  67254. }
  67255. else {
  67256. BABYLON.Tools.Warn('Could not find root node in model file.');
  67257. }
  67258. return loadedMeshInfo;
  67259. };
  67260. WindowsMotionController.prototype.createMeshInfo = function (rootNode) {
  67261. var loadedMeshInfo = new LoadedMeshInfo();
  67262. var i;
  67263. loadedMeshInfo.rootNode = rootNode;
  67264. // Reset the caches
  67265. loadedMeshInfo.buttonMeshes = {};
  67266. loadedMeshInfo.axisMeshes = {};
  67267. // Button Meshes
  67268. for (i = 0; i < this._mapping.buttons.length; i++) {
  67269. var buttonMeshName = this._mapping.buttonMeshNames[this._mapping.buttons[i]];
  67270. if (!buttonMeshName) {
  67271. BABYLON.Tools.Log('Skipping unknown button at index: ' + i + ' with mapped name: ' + this._mapping.buttons[i]);
  67272. continue;
  67273. }
  67274. var buttonMesh = getChildByName(rootNode, buttonMeshName);
  67275. if (!buttonMesh) {
  67276. BABYLON.Tools.Warn('Missing button mesh with name: ' + buttonMeshName);
  67277. continue;
  67278. }
  67279. var buttonMeshInfo = {
  67280. index: i,
  67281. value: getImmediateChildByName(buttonMesh, 'VALUE'),
  67282. pressed: getImmediateChildByName(buttonMesh, 'PRESSED'),
  67283. unpressed: getImmediateChildByName(buttonMesh, 'UNPRESSED')
  67284. };
  67285. if (buttonMeshInfo.value && buttonMeshInfo.pressed && buttonMeshInfo.unpressed) {
  67286. loadedMeshInfo.buttonMeshes[this._mapping.buttons[i]] = buttonMeshInfo;
  67287. }
  67288. else {
  67289. // If we didn't find the mesh, it simply means this button won't have transforms applied as mapped button value changes.
  67290. BABYLON.Tools.Warn('Missing button submesh under mesh with name: ' + buttonMeshName +
  67291. '(VALUE: ' + !!buttonMeshInfo.value +
  67292. ', PRESSED: ' + !!buttonMeshInfo.pressed +
  67293. ', UNPRESSED:' + !!buttonMeshInfo.unpressed +
  67294. ')');
  67295. }
  67296. }
  67297. // Axis Meshes
  67298. for (i = 0; i < this._mapping.axisMeshNames.length; i++) {
  67299. var axisMeshName = this._mapping.axisMeshNames[i];
  67300. if (!axisMeshName) {
  67301. BABYLON.Tools.Log('Skipping unknown axis at index: ' + i);
  67302. continue;
  67303. }
  67304. var axisMesh = getChildByName(rootNode, axisMeshName);
  67305. if (!axisMesh) {
  67306. BABYLON.Tools.Warn('Missing axis mesh with name: ' + axisMeshName);
  67307. continue;
  67308. }
  67309. var axisMeshInfo = {
  67310. index: i,
  67311. value: getImmediateChildByName(axisMesh, 'VALUE'),
  67312. min: getImmediateChildByName(axisMesh, 'MIN'),
  67313. max: getImmediateChildByName(axisMesh, 'MAX')
  67314. };
  67315. if (axisMeshInfo.value && axisMeshInfo.min && axisMeshInfo.max) {
  67316. loadedMeshInfo.axisMeshes[i] = axisMeshInfo;
  67317. }
  67318. else {
  67319. // If we didn't find the mesh, it simply means thit axis won't have transforms applied as mapped axis values change.
  67320. BABYLON.Tools.Warn('Missing axis submesh under mesh with name: ' + axisMeshName +
  67321. '(VALUE: ' + !!axisMeshInfo.value +
  67322. ', MIN: ' + !!axisMeshInfo.min +
  67323. ', MAX:' + !!axisMeshInfo.max +
  67324. ')');
  67325. }
  67326. }
  67327. // Pointing Ray
  67328. loadedMeshInfo.pointingPoseNode = getChildByName(rootNode, this._mapping.pointingPoseMeshName);
  67329. if (!loadedMeshInfo.pointingPoseNode) {
  67330. BABYLON.Tools.Warn('Missing pointing pose mesh with name: ' + this._mapping.pointingPoseMeshName);
  67331. }
  67332. return loadedMeshInfo;
  67333. // Look through all children recursively. This will return null if no mesh exists with the given name.
  67334. function getChildByName(node, name) {
  67335. return node.getChildMeshes(false, function (n) { return n.name === name; })[0];
  67336. }
  67337. // Look through only immediate children. This will return null if no mesh exists with the given name.
  67338. function getImmediateChildByName(node, name) {
  67339. return node.getChildMeshes(true, function (n) { return n.name == name; })[0];
  67340. }
  67341. };
  67342. WindowsMotionController.prototype.getForwardRay = function (length) {
  67343. if (length === void 0) { length = 100; }
  67344. if (!(this._loadedMeshInfo && this._loadedMeshInfo.pointingPoseNode)) {
  67345. return _super.prototype.getForwardRay.call(this, length);
  67346. }
  67347. var m = this._loadedMeshInfo.pointingPoseNode.getWorldMatrix();
  67348. var origin = m.getTranslation();
  67349. var forward = new BABYLON.Vector3(0, 0, -1);
  67350. var forwardWorld = BABYLON.Vector3.TransformNormal(forward, m);
  67351. var direction = BABYLON.Vector3.Normalize(forwardWorld);
  67352. return new BABYLON.Ray(origin, direction, length);
  67353. };
  67354. WindowsMotionController.prototype.dispose = function () {
  67355. _super.prototype.dispose.call(this);
  67356. this.onTrackpadChangedObservable.clear();
  67357. };
  67358. WindowsMotionController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/microsoft/';
  67359. WindowsMotionController.MODEL_LEFT_FILENAME = 'left.glb';
  67360. WindowsMotionController.MODEL_RIGHT_FILENAME = 'right.glb';
  67361. WindowsMotionController.GAMEPAD_ID_PREFIX = 'Spatial Controller (Spatial Interaction Source) ';
  67362. WindowsMotionController.GAMEPAD_ID_PATTERN = /([0-9a-zA-Z]+-[0-9a-zA-Z]+)$/;
  67363. return WindowsMotionController;
  67364. }(BABYLON.WebVRController));
  67365. BABYLON.WindowsMotionController = WindowsMotionController;
  67366. })(BABYLON || (BABYLON = {}));
  67367. //# sourceMappingURL=babylon.windowsMotionController.js.map
  67368. "use strict";
  67369. var BABYLON;
  67370. (function (BABYLON) {
  67371. var GearVRController = /** @class */ (function (_super) {
  67372. __extends(GearVRController, _super);
  67373. function GearVRController(vrGamepad) {
  67374. var _this = _super.call(this, vrGamepad) || this;
  67375. _this._buttonIndexToObservableNameMap = [
  67376. 'onTrackpadChangedObservable',
  67377. 'onTriggerStateChangedObservable' // Trigger
  67378. ];
  67379. _this.controllerType = BABYLON.PoseEnabledControllerType.GEAR_VR;
  67380. return _this;
  67381. }
  67382. GearVRController.prototype.initControllerMesh = function (scene, meshLoaded) {
  67383. var _this = this;
  67384. BABYLON.SceneLoader.ImportMesh("", GearVRController.MODEL_BASE_URL, GearVRController.MODEL_FILENAME, scene, function (newMeshes) {
  67385. _this._defaultModel = newMeshes[1];
  67386. _this.attachToMesh(_this._defaultModel);
  67387. if (meshLoaded) {
  67388. meshLoaded(_this._defaultModel);
  67389. }
  67390. });
  67391. };
  67392. GearVRController.prototype._handleButtonChange = function (buttonIdx, state, changes) {
  67393. if (buttonIdx < this._buttonIndexToObservableNameMap.length) {
  67394. var observableName = this._buttonIndexToObservableNameMap[buttonIdx];
  67395. // Only emit events for buttons that we know how to map from index to observable
  67396. var observable = this[observableName];
  67397. if (observable) {
  67398. observable.notifyObservers(state);
  67399. }
  67400. }
  67401. };
  67402. GearVRController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/generic/';
  67403. GearVRController.MODEL_FILENAME = 'generic.babylon';
  67404. GearVRController.GAMEPAD_ID_PREFIX = 'Gear VR'; // id is 'Gear VR Controller'
  67405. return GearVRController;
  67406. }(BABYLON.WebVRController));
  67407. BABYLON.GearVRController = GearVRController;
  67408. })(BABYLON || (BABYLON = {}));
  67409. //# sourceMappingURL=babylon.gearVRController.js.map
  67410. "use strict";
  67411. var BABYLON;
  67412. (function (BABYLON) {
  67413. /**
  67414. * Google Daydream controller
  67415. */
  67416. var DaydreamController = /** @class */ (function (_super) {
  67417. __extends(DaydreamController, _super);
  67418. function DaydreamController(vrGamepad) {
  67419. var _this = _super.call(this, vrGamepad) || this;
  67420. _this.controllerType = BABYLON.PoseEnabledControllerType.DAYDREAM;
  67421. return _this;
  67422. }
  67423. DaydreamController.prototype.initControllerMesh = function (scene, meshLoaded) {
  67424. var _this = this;
  67425. BABYLON.SceneLoader.ImportMesh("", DaydreamController.MODEL_BASE_URL, DaydreamController.MODEL_FILENAME, scene, function (newMeshes) {
  67426. _this._defaultModel = newMeshes[1];
  67427. _this.attachToMesh(_this._defaultModel);
  67428. if (meshLoaded) {
  67429. meshLoaded(_this._defaultModel);
  67430. }
  67431. });
  67432. };
  67433. DaydreamController.prototype._handleButtonChange = function (buttonIdx, state, changes) {
  67434. // Daydream controller only has 1 GamepadButton (on the trackpad).
  67435. if (buttonIdx === 0) {
  67436. var observable = this.onTriggerStateChangedObservable;
  67437. if (observable) {
  67438. observable.notifyObservers(state);
  67439. }
  67440. }
  67441. else {
  67442. // If the app or home buttons are ever made available
  67443. BABYLON.Tools.Warn("Unrecognized Daydream button index: " + buttonIdx);
  67444. }
  67445. };
  67446. /**
  67447. * Base Url for the controller model.
  67448. */
  67449. DaydreamController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/generic/';
  67450. /**
  67451. * File name for the controller model.
  67452. */
  67453. DaydreamController.MODEL_FILENAME = 'generic.babylon';
  67454. /**
  67455. * Gamepad Id prefix used to identify Daydream Controller.
  67456. */
  67457. DaydreamController.GAMEPAD_ID_PREFIX = 'Daydream'; // id is 'Daydream Controller'
  67458. return DaydreamController;
  67459. }(BABYLON.WebVRController));
  67460. BABYLON.DaydreamController = DaydreamController;
  67461. })(BABYLON || (BABYLON = {}));
  67462. //# sourceMappingURL=babylon.daydreamController.js.map
  67463. "use strict";
  67464. var BABYLON;
  67465. (function (BABYLON) {
  67466. var FollowCamera = /** @class */ (function (_super) {
  67467. __extends(FollowCamera, _super);
  67468. function FollowCamera(name, position, scene, lockedTarget) {
  67469. if (lockedTarget === void 0) { lockedTarget = null; }
  67470. var _this = _super.call(this, name, position, scene) || this;
  67471. _this.radius = 12;
  67472. _this.rotationOffset = 0;
  67473. _this.heightOffset = 4;
  67474. _this.cameraAcceleration = 0.05;
  67475. _this.maxCameraSpeed = 20;
  67476. _this.lockedTarget = lockedTarget;
  67477. return _this;
  67478. }
  67479. FollowCamera.prototype.getRadians = function (degrees) {
  67480. return degrees * Math.PI / 180;
  67481. };
  67482. FollowCamera.prototype.follow = function (cameraTarget) {
  67483. if (!cameraTarget)
  67484. return;
  67485. var yRotation;
  67486. if (cameraTarget.rotationQuaternion) {
  67487. var rotMatrix = new BABYLON.Matrix();
  67488. cameraTarget.rotationQuaternion.toRotationMatrix(rotMatrix);
  67489. yRotation = Math.atan2(rotMatrix.m[8], rotMatrix.m[10]);
  67490. }
  67491. else {
  67492. yRotation = cameraTarget.rotation.y;
  67493. }
  67494. var radians = this.getRadians(this.rotationOffset) + yRotation;
  67495. var targetPosition = cameraTarget.getAbsolutePosition();
  67496. var targetX = targetPosition.x + Math.sin(radians) * this.radius;
  67497. var targetZ = targetPosition.z + Math.cos(radians) * this.radius;
  67498. var dx = targetX - this.position.x;
  67499. var dy = (targetPosition.y + this.heightOffset) - this.position.y;
  67500. var dz = (targetZ) - this.position.z;
  67501. var vx = dx * this.cameraAcceleration * 2; //this is set to .05
  67502. var vy = dy * this.cameraAcceleration;
  67503. var vz = dz * this.cameraAcceleration * 2;
  67504. if (vx > this.maxCameraSpeed || vx < -this.maxCameraSpeed) {
  67505. vx = vx < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  67506. }
  67507. if (vy > this.maxCameraSpeed || vy < -this.maxCameraSpeed) {
  67508. vy = vy < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  67509. }
  67510. if (vz > this.maxCameraSpeed || vz < -this.maxCameraSpeed) {
  67511. vz = vz < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  67512. }
  67513. this.position = new BABYLON.Vector3(this.position.x + vx, this.position.y + vy, this.position.z + vz);
  67514. this.setTarget(targetPosition);
  67515. };
  67516. FollowCamera.prototype._checkInputs = function () {
  67517. _super.prototype._checkInputs.call(this);
  67518. if (this.lockedTarget) {
  67519. this.follow(this.lockedTarget);
  67520. }
  67521. };
  67522. FollowCamera.prototype.getClassName = function () {
  67523. return "FollowCamera";
  67524. };
  67525. __decorate([
  67526. BABYLON.serialize()
  67527. ], FollowCamera.prototype, "radius", void 0);
  67528. __decorate([
  67529. BABYLON.serialize()
  67530. ], FollowCamera.prototype, "rotationOffset", void 0);
  67531. __decorate([
  67532. BABYLON.serialize()
  67533. ], FollowCamera.prototype, "heightOffset", void 0);
  67534. __decorate([
  67535. BABYLON.serialize()
  67536. ], FollowCamera.prototype, "cameraAcceleration", void 0);
  67537. __decorate([
  67538. BABYLON.serialize()
  67539. ], FollowCamera.prototype, "maxCameraSpeed", void 0);
  67540. __decorate([
  67541. BABYLON.serializeAsMeshReference("lockedTargetId")
  67542. ], FollowCamera.prototype, "lockedTarget", void 0);
  67543. return FollowCamera;
  67544. }(BABYLON.TargetCamera));
  67545. BABYLON.FollowCamera = FollowCamera;
  67546. var ArcFollowCamera = /** @class */ (function (_super) {
  67547. __extends(ArcFollowCamera, _super);
  67548. function ArcFollowCamera(name, alpha, beta, radius, target, scene) {
  67549. var _this = _super.call(this, name, BABYLON.Vector3.Zero(), scene) || this;
  67550. _this.alpha = alpha;
  67551. _this.beta = beta;
  67552. _this.radius = radius;
  67553. _this.target = target;
  67554. _this._cartesianCoordinates = BABYLON.Vector3.Zero();
  67555. _this.follow();
  67556. return _this;
  67557. }
  67558. ArcFollowCamera.prototype.follow = function () {
  67559. if (!this.target) {
  67560. return;
  67561. }
  67562. this._cartesianCoordinates.x = this.radius * Math.cos(this.alpha) * Math.cos(this.beta);
  67563. this._cartesianCoordinates.y = this.radius * Math.sin(this.beta);
  67564. this._cartesianCoordinates.z = this.radius * Math.sin(this.alpha) * Math.cos(this.beta);
  67565. var targetPosition = this.target.getAbsolutePosition();
  67566. this.position = targetPosition.add(this._cartesianCoordinates);
  67567. this.setTarget(targetPosition);
  67568. };
  67569. ArcFollowCamera.prototype._checkInputs = function () {
  67570. _super.prototype._checkInputs.call(this);
  67571. this.follow();
  67572. };
  67573. ArcFollowCamera.prototype.getClassName = function () {
  67574. return "ArcFollowCamera";
  67575. };
  67576. return ArcFollowCamera;
  67577. }(BABYLON.TargetCamera));
  67578. BABYLON.ArcFollowCamera = ArcFollowCamera;
  67579. })(BABYLON || (BABYLON = {}));
  67580. //# sourceMappingURL=babylon.followCamera.js.map
  67581. "use strict";
  67582. var BABYLON;
  67583. (function (BABYLON) {
  67584. // We're mainly based on the logic defined into the FreeCamera code
  67585. var UniversalCamera = /** @class */ (function (_super) {
  67586. __extends(UniversalCamera, _super);
  67587. //-- end properties for backward compatibility for inputs
  67588. function UniversalCamera(name, position, scene) {
  67589. var _this = _super.call(this, name, position, scene) || this;
  67590. _this.inputs.addGamepad();
  67591. return _this;
  67592. }
  67593. Object.defineProperty(UniversalCamera.prototype, "gamepadAngularSensibility", {
  67594. //-- Begin properties for backward compatibility for inputs
  67595. get: function () {
  67596. var gamepad = this.inputs.attached["gamepad"];
  67597. if (gamepad)
  67598. return gamepad.gamepadAngularSensibility;
  67599. return 0;
  67600. },
  67601. set: function (value) {
  67602. var gamepad = this.inputs.attached["gamepad"];
  67603. if (gamepad)
  67604. gamepad.gamepadAngularSensibility = value;
  67605. },
  67606. enumerable: true,
  67607. configurable: true
  67608. });
  67609. Object.defineProperty(UniversalCamera.prototype, "gamepadMoveSensibility", {
  67610. get: function () {
  67611. var gamepad = this.inputs.attached["gamepad"];
  67612. if (gamepad)
  67613. return gamepad.gamepadMoveSensibility;
  67614. return 0;
  67615. },
  67616. set: function (value) {
  67617. var gamepad = this.inputs.attached["gamepad"];
  67618. if (gamepad)
  67619. gamepad.gamepadMoveSensibility = value;
  67620. },
  67621. enumerable: true,
  67622. configurable: true
  67623. });
  67624. UniversalCamera.prototype.getClassName = function () {
  67625. return "UniversalCamera";
  67626. };
  67627. return UniversalCamera;
  67628. }(BABYLON.TouchCamera));
  67629. BABYLON.UniversalCamera = UniversalCamera;
  67630. })(BABYLON || (BABYLON = {}));
  67631. //# sourceMappingURL=babylon.universalCamera.js.map
  67632. "use strict";
  67633. var BABYLON;
  67634. (function (BABYLON) {
  67635. // We're mainly based on the logic defined into the FreeCamera code
  67636. var GamepadCamera = /** @class */ (function (_super) {
  67637. __extends(GamepadCamera, _super);
  67638. //-- end properties for backward compatibility for inputs
  67639. function GamepadCamera(name, position, scene) {
  67640. return _super.call(this, name, position, scene) || this;
  67641. }
  67642. Object.defineProperty(GamepadCamera.prototype, "gamepadAngularSensibility", {
  67643. //-- Begin properties for backward compatibility for inputs
  67644. get: function () {
  67645. var gamepad = this.inputs.attached["gamepad"];
  67646. if (gamepad)
  67647. return gamepad.gamepadAngularSensibility;
  67648. return 0;
  67649. },
  67650. set: function (value) {
  67651. var gamepad = this.inputs.attached["gamepad"];
  67652. if (gamepad)
  67653. gamepad.gamepadAngularSensibility = value;
  67654. },
  67655. enumerable: true,
  67656. configurable: true
  67657. });
  67658. Object.defineProperty(GamepadCamera.prototype, "gamepadMoveSensibility", {
  67659. get: function () {
  67660. var gamepad = this.inputs.attached["gamepad"];
  67661. if (gamepad)
  67662. return gamepad.gamepadMoveSensibility;
  67663. return 0;
  67664. },
  67665. set: function (value) {
  67666. var gamepad = this.inputs.attached["gamepad"];
  67667. if (gamepad)
  67668. gamepad.gamepadMoveSensibility = value;
  67669. },
  67670. enumerable: true,
  67671. configurable: true
  67672. });
  67673. GamepadCamera.prototype.getClassName = function () {
  67674. return "GamepadCamera";
  67675. };
  67676. return GamepadCamera;
  67677. }(BABYLON.UniversalCamera));
  67678. BABYLON.GamepadCamera = GamepadCamera;
  67679. })(BABYLON || (BABYLON = {}));
  67680. //# sourceMappingURL=babylon.gamepadCamera.js.map
  67681. "use strict";
  67682. var BABYLON;
  67683. (function (BABYLON) {
  67684. var PostProcessRenderPipelineManager = /** @class */ (function () {
  67685. function PostProcessRenderPipelineManager() {
  67686. this._renderPipelines = {};
  67687. }
  67688. PostProcessRenderPipelineManager.prototype.addPipeline = function (renderPipeline) {
  67689. this._renderPipelines[renderPipeline._name] = renderPipeline;
  67690. };
  67691. PostProcessRenderPipelineManager.prototype.attachCamerasToRenderPipeline = function (renderPipelineName, cameras, unique) {
  67692. if (unique === void 0) { unique = false; }
  67693. var renderPipeline = this._renderPipelines[renderPipelineName];
  67694. if (!renderPipeline) {
  67695. return;
  67696. }
  67697. renderPipeline._attachCameras(cameras, unique);
  67698. };
  67699. PostProcessRenderPipelineManager.prototype.detachCamerasFromRenderPipeline = function (renderPipelineName, cameras) {
  67700. var renderPipeline = this._renderPipelines[renderPipelineName];
  67701. if (!renderPipeline) {
  67702. return;
  67703. }
  67704. renderPipeline._detachCameras(cameras);
  67705. };
  67706. PostProcessRenderPipelineManager.prototype.enableEffectInPipeline = function (renderPipelineName, renderEffectName, cameras) {
  67707. var renderPipeline = this._renderPipelines[renderPipelineName];
  67708. if (!renderPipeline) {
  67709. return;
  67710. }
  67711. renderPipeline._enableEffect(renderEffectName, cameras);
  67712. };
  67713. PostProcessRenderPipelineManager.prototype.disableEffectInPipeline = function (renderPipelineName, renderEffectName, cameras) {
  67714. var renderPipeline = this._renderPipelines[renderPipelineName];
  67715. if (!renderPipeline) {
  67716. return;
  67717. }
  67718. renderPipeline._disableEffect(renderEffectName, cameras);
  67719. };
  67720. PostProcessRenderPipelineManager.prototype.update = function () {
  67721. for (var renderPipelineName in this._renderPipelines) {
  67722. if (this._renderPipelines.hasOwnProperty(renderPipelineName)) {
  67723. var pipeline = this._renderPipelines[renderPipelineName];
  67724. if (!pipeline.isSupported) {
  67725. pipeline.dispose();
  67726. delete this._renderPipelines[renderPipelineName];
  67727. }
  67728. else {
  67729. pipeline._update();
  67730. }
  67731. }
  67732. }
  67733. };
  67734. PostProcessRenderPipelineManager.prototype._rebuild = function () {
  67735. for (var renderPipelineName in this._renderPipelines) {
  67736. if (this._renderPipelines.hasOwnProperty(renderPipelineName)) {
  67737. var pipeline = this._renderPipelines[renderPipelineName];
  67738. pipeline._rebuild();
  67739. }
  67740. }
  67741. };
  67742. PostProcessRenderPipelineManager.prototype.dispose = function () {
  67743. for (var renderPipelineName in this._renderPipelines) {
  67744. if (this._renderPipelines.hasOwnProperty(renderPipelineName)) {
  67745. var pipeline = this._renderPipelines[renderPipelineName];
  67746. pipeline.dispose();
  67747. }
  67748. }
  67749. };
  67750. return PostProcessRenderPipelineManager;
  67751. }());
  67752. BABYLON.PostProcessRenderPipelineManager = PostProcessRenderPipelineManager;
  67753. })(BABYLON || (BABYLON = {}));
  67754. //# sourceMappingURL=babylon.postProcessRenderPipelineManager.js.map
  67755. "use strict";
  67756. var BABYLON;
  67757. (function (BABYLON) {
  67758. /**
  67759. * This represents a set of one or more post processes in Babylon.
  67760. * A post process can be used to apply a shader to a texture after it is rendered.
  67761. * @example https://doc.babylonjs.com/how_to/how_to_use_postprocessrenderpipeline
  67762. */
  67763. var PostProcessRenderEffect = /** @class */ (function () {
  67764. /**
  67765. * Instantiates a post process render effect.
  67766. * A post process can be used to apply a shader to a texture after it is rendered.
  67767. * @param engine The engine the effect is tied to
  67768. * @param name The name of the effect
  67769. * @param getPostProcesses A function that returns a set of post processes which the effect will run in order to be run.
  67770. * @param singleInstance False if this post process can be run on multiple cameras. (default: true)
  67771. */
  67772. function PostProcessRenderEffect(engine, name, getPostProcesses, singleInstance) {
  67773. this._name = name;
  67774. this._singleInstance = singleInstance || true;
  67775. this._getPostProcesses = getPostProcesses;
  67776. this._cameras = {};
  67777. this._indicesForCamera = {};
  67778. this._postProcesses = {};
  67779. }
  67780. Object.defineProperty(PostProcessRenderEffect.prototype, "isSupported", {
  67781. /**
  67782. * Checks if all the post processes in the effect are supported.
  67783. */
  67784. get: function () {
  67785. for (var index in this._postProcesses) {
  67786. for (var ppIndex in this._postProcesses[index]) {
  67787. if (!this._postProcesses[index][ppIndex].isSupported) {
  67788. return false;
  67789. }
  67790. }
  67791. }
  67792. return true;
  67793. },
  67794. enumerable: true,
  67795. configurable: true
  67796. });
  67797. /**
  67798. * Updates the current state of the effect
  67799. */
  67800. PostProcessRenderEffect.prototype._update = function () {
  67801. };
  67802. /**
  67803. * Attaches the effect on cameras
  67804. * @param cameras The camera to attach to.
  67805. */
  67806. PostProcessRenderEffect.prototype._attachCameras = function (cameras) {
  67807. var _this = this;
  67808. var cameraKey;
  67809. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  67810. if (!cams) {
  67811. return;
  67812. }
  67813. for (var i = 0; i < cams.length; i++) {
  67814. var camera = cams[i];
  67815. var cameraName = camera.name;
  67816. if (this._singleInstance) {
  67817. cameraKey = 0;
  67818. }
  67819. else {
  67820. cameraKey = cameraName;
  67821. }
  67822. if (!this._postProcesses[cameraKey]) {
  67823. var postProcess = this._getPostProcesses();
  67824. if (postProcess) {
  67825. this._postProcesses[cameraKey] = Array.isArray(postProcess) ? postProcess : [postProcess];
  67826. }
  67827. }
  67828. if (!this._indicesForCamera[cameraName]) {
  67829. this._indicesForCamera[cameraName] = [];
  67830. }
  67831. this._postProcesses[cameraKey].forEach(function (postProcess) {
  67832. var index = camera.attachPostProcess(postProcess);
  67833. _this._indicesForCamera[cameraName].push(index);
  67834. });
  67835. if (!this._cameras[cameraName]) {
  67836. this._cameras[cameraName] = camera;
  67837. }
  67838. }
  67839. };
  67840. /**
  67841. * Detatches the effect on cameras
  67842. * @param cameras The camera to detatch from.
  67843. */
  67844. PostProcessRenderEffect.prototype._detachCameras = function (cameras) {
  67845. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  67846. if (!cams) {
  67847. return;
  67848. }
  67849. for (var i = 0; i < cams.length; i++) {
  67850. var camera = cams[i];
  67851. var cameraName = camera.name;
  67852. this._postProcesses[this._singleInstance ? 0 : cameraName].forEach(function (postProcess) {
  67853. camera.detachPostProcess(postProcess);
  67854. });
  67855. if (this._cameras[cameraName]) {
  67856. //this._indicesForCamera.splice(index, 1);
  67857. this._cameras[cameraName] = null;
  67858. }
  67859. }
  67860. };
  67861. /**
  67862. * Enables the effect on given cameras
  67863. * @param cameras The camera to enable.
  67864. */
  67865. PostProcessRenderEffect.prototype._enable = function (cameras) {
  67866. var _this = this;
  67867. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  67868. if (!cams) {
  67869. return;
  67870. }
  67871. for (var i = 0; i < cams.length; i++) {
  67872. var camera = cams[i];
  67873. var cameraName = camera.name;
  67874. for (var j = 0; j < this._indicesForCamera[cameraName].length; j++) {
  67875. if (camera._postProcesses[this._indicesForCamera[cameraName][j]] === undefined || camera._postProcesses[this._indicesForCamera[cameraName][j]] === null) {
  67876. this._postProcesses[this._singleInstance ? 0 : cameraName].forEach(function (postProcess) {
  67877. cams[i].attachPostProcess(postProcess, _this._indicesForCamera[cameraName][j]);
  67878. });
  67879. }
  67880. }
  67881. }
  67882. };
  67883. /**
  67884. * Disables the effect on the given cameras
  67885. * @param cameras The camera to disable.
  67886. */
  67887. PostProcessRenderEffect.prototype._disable = function (cameras) {
  67888. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  67889. if (!cams) {
  67890. return;
  67891. }
  67892. for (var i = 0; i < cams.length; i++) {
  67893. var camera = cams[i];
  67894. var cameraName = camera.name;
  67895. this._postProcesses[this._singleInstance ? 0 : cameraName].forEach(function (postProcess) {
  67896. camera.detachPostProcess(postProcess);
  67897. });
  67898. }
  67899. };
  67900. /**
  67901. * Gets a list of the post processes contained in the effect.
  67902. * @param camera The camera to get the post processes on.
  67903. * @returns The list of the post processes in the effect.
  67904. */
  67905. PostProcessRenderEffect.prototype.getPostProcesses = function (camera) {
  67906. if (this._singleInstance) {
  67907. return this._postProcesses[0];
  67908. }
  67909. else {
  67910. if (!camera) {
  67911. return null;
  67912. }
  67913. return this._postProcesses[camera.name];
  67914. }
  67915. };
  67916. return PostProcessRenderEffect;
  67917. }());
  67918. BABYLON.PostProcessRenderEffect = PostProcessRenderEffect;
  67919. })(BABYLON || (BABYLON = {}));
  67920. //# sourceMappingURL=babylon.postProcessRenderEffect.js.map
  67921. "use strict";
  67922. var BABYLON;
  67923. (function (BABYLON) {
  67924. var PostProcessRenderPipeline = /** @class */ (function () {
  67925. function PostProcessRenderPipeline(engine, name) {
  67926. this.engine = engine;
  67927. this._name = name;
  67928. this._renderEffects = {};
  67929. this._renderEffectsForIsolatedPass = new Array();
  67930. this._cameras = [];
  67931. }
  67932. PostProcessRenderPipeline.prototype.getClassName = function () {
  67933. return "PostProcessRenderPipeline";
  67934. };
  67935. Object.defineProperty(PostProcessRenderPipeline.prototype, "isSupported", {
  67936. get: function () {
  67937. for (var renderEffectName in this._renderEffects) {
  67938. if (this._renderEffects.hasOwnProperty(renderEffectName)) {
  67939. if (!this._renderEffects[renderEffectName].isSupported) {
  67940. return false;
  67941. }
  67942. }
  67943. }
  67944. return true;
  67945. },
  67946. enumerable: true,
  67947. configurable: true
  67948. });
  67949. PostProcessRenderPipeline.prototype.addEffect = function (renderEffect) {
  67950. this._renderEffects[renderEffect._name] = renderEffect;
  67951. };
  67952. // private
  67953. PostProcessRenderPipeline.prototype._rebuild = function () {
  67954. };
  67955. PostProcessRenderPipeline.prototype._enableEffect = function (renderEffectName, cameras) {
  67956. var renderEffects = this._renderEffects[renderEffectName];
  67957. if (!renderEffects) {
  67958. return;
  67959. }
  67960. renderEffects._enable(BABYLON.Tools.MakeArray(cameras || this._cameras));
  67961. };
  67962. PostProcessRenderPipeline.prototype._disableEffect = function (renderEffectName, cameras) {
  67963. var renderEffects = this._renderEffects[renderEffectName];
  67964. if (!renderEffects) {
  67965. return;
  67966. }
  67967. renderEffects._disable(BABYLON.Tools.MakeArray(cameras || this._cameras));
  67968. };
  67969. PostProcessRenderPipeline.prototype._attachCameras = function (cameras, unique) {
  67970. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  67971. if (!cams) {
  67972. return;
  67973. }
  67974. var indicesToDelete = [];
  67975. var i;
  67976. for (i = 0; i < cams.length; i++) {
  67977. var camera = cams[i];
  67978. var cameraName = camera.name;
  67979. if (this._cameras.indexOf(camera) === -1) {
  67980. this._cameras[cameraName] = camera;
  67981. }
  67982. else if (unique) {
  67983. indicesToDelete.push(i);
  67984. }
  67985. }
  67986. for (i = 0; i < indicesToDelete.length; i++) {
  67987. cameras.splice(indicesToDelete[i], 1);
  67988. }
  67989. for (var renderEffectName in this._renderEffects) {
  67990. if (this._renderEffects.hasOwnProperty(renderEffectName)) {
  67991. this._renderEffects[renderEffectName]._attachCameras(cams);
  67992. }
  67993. }
  67994. };
  67995. PostProcessRenderPipeline.prototype._detachCameras = function (cameras) {
  67996. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  67997. if (!cams) {
  67998. return;
  67999. }
  68000. for (var renderEffectName in this._renderEffects) {
  68001. if (this._renderEffects.hasOwnProperty(renderEffectName)) {
  68002. this._renderEffects[renderEffectName]._detachCameras(cams);
  68003. }
  68004. }
  68005. for (var i = 0; i < cams.length; i++) {
  68006. this._cameras.splice(this._cameras.indexOf(cams[i]), 1);
  68007. }
  68008. };
  68009. PostProcessRenderPipeline.prototype._update = function () {
  68010. for (var renderEffectName in this._renderEffects) {
  68011. if (this._renderEffects.hasOwnProperty(renderEffectName)) {
  68012. this._renderEffects[renderEffectName]._update();
  68013. }
  68014. }
  68015. for (var i = 0; i < this._cameras.length; i++) {
  68016. var cameraName = this._cameras[i].name;
  68017. if (this._renderEffectsForIsolatedPass[cameraName]) {
  68018. this._renderEffectsForIsolatedPass[cameraName]._update();
  68019. }
  68020. }
  68021. };
  68022. PostProcessRenderPipeline.prototype._reset = function () {
  68023. this._renderEffects = {};
  68024. this._renderEffectsForIsolatedPass = new Array();
  68025. };
  68026. PostProcessRenderPipeline.prototype._enableMSAAOnFirstPostProcess = function (sampleCount) {
  68027. // 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)
  68028. var effectKeys = Object.keys(this._renderEffects);
  68029. if (this.engine.webGLVersion >= 2 && effectKeys.length > 0) {
  68030. var postProcesses = this._renderEffects[effectKeys[0]].getPostProcesses();
  68031. if (postProcesses) {
  68032. postProcesses[0].samples = sampleCount;
  68033. return true;
  68034. }
  68035. }
  68036. return false;
  68037. };
  68038. PostProcessRenderPipeline.prototype.dispose = function () {
  68039. // Must be implemented by children
  68040. };
  68041. __decorate([
  68042. BABYLON.serialize()
  68043. ], PostProcessRenderPipeline.prototype, "_name", void 0);
  68044. return PostProcessRenderPipeline;
  68045. }());
  68046. BABYLON.PostProcessRenderPipeline = PostProcessRenderPipeline;
  68047. })(BABYLON || (BABYLON = {}));
  68048. //# sourceMappingURL=babylon.postProcessRenderPipeline.js.map
  68049. "use strict";
  68050. var BABYLON;
  68051. (function (BABYLON) {
  68052. /**
  68053. * This represents a depth renderer in Babylon.
  68054. * A depth renderer will render to it's depth map every frame which can be displayed or used in post processing
  68055. */
  68056. var DepthRenderer = /** @class */ (function () {
  68057. /**
  68058. * Instantiates a depth renderer
  68059. * @param scene The scene the renderer belongs to
  68060. * @param type The texture type of the depth map (default: Engine.TEXTURETYPE_FLOAT)
  68061. * @param camera The camera to be used to render the depth map (default: scene's active camera)
  68062. */
  68063. function DepthRenderer(scene, type, camera) {
  68064. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_FLOAT; }
  68065. if (camera === void 0) { camera = null; }
  68066. var _this = this;
  68067. this._scene = scene;
  68068. this._camera = camera;
  68069. var engine = scene.getEngine();
  68070. // Render target
  68071. this._depthMap = new BABYLON.RenderTargetTexture("depthMap", { width: engine.getRenderWidth(), height: engine.getRenderHeight() }, this._scene, false, true, type);
  68072. this._depthMap.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  68073. this._depthMap.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  68074. this._depthMap.refreshRate = 1;
  68075. this._depthMap.renderParticles = false;
  68076. this._depthMap.renderList = null;
  68077. // Camera to get depth map from to support multiple concurrent cameras
  68078. this._depthMap.activeCamera = this._camera;
  68079. this._depthMap.ignoreCameraViewport = true;
  68080. this._depthMap.useCameraPostProcesses = false;
  68081. // set default depth value to 1.0 (far away)
  68082. this._depthMap.onClearObservable.add(function (engine) {
  68083. engine.clear(new BABYLON.Color4(1.0, 1.0, 1.0, 1.0), true, true, true);
  68084. });
  68085. // Custom render function
  68086. var renderSubMesh = function (subMesh) {
  68087. var mesh = subMesh.getRenderingMesh();
  68088. var scene = _this._scene;
  68089. var engine = scene.getEngine();
  68090. var material = subMesh.getMaterial();
  68091. if (!material) {
  68092. return;
  68093. }
  68094. // Culling and reverse (right handed system)
  68095. engine.setState(material.backFaceCulling, 0, false, scene.useRightHandedSystem);
  68096. // Managing instances
  68097. var batch = mesh._getInstancesRenderList(subMesh._id);
  68098. if (batch.mustReturn) {
  68099. return;
  68100. }
  68101. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null);
  68102. var camera = _this._camera || scene.activeCamera;
  68103. if (_this.isReady(subMesh, hardwareInstancedRendering) && camera) {
  68104. engine.enableEffect(_this._effect);
  68105. mesh._bind(subMesh, _this._effect, BABYLON.Material.TriangleFillMode);
  68106. _this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  68107. _this._effect.setFloat2("depthValues", camera.minZ, camera.minZ + camera.maxZ);
  68108. // Alpha test
  68109. if (material && material.needAlphaTesting()) {
  68110. var alphaTexture = material.getAlphaTestTexture();
  68111. if (alphaTexture) {
  68112. _this._effect.setTexture("diffuseSampler", alphaTexture);
  68113. _this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  68114. }
  68115. }
  68116. // Bones
  68117. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  68118. _this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  68119. }
  68120. // Draw
  68121. mesh._processRendering(subMesh, _this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effect.setMatrix("world", world); });
  68122. }
  68123. };
  68124. this._depthMap.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes) {
  68125. var index;
  68126. if (depthOnlySubMeshes.length) {
  68127. engine.setColorWrite(false);
  68128. for (index = 0; index < depthOnlySubMeshes.length; index++) {
  68129. renderSubMesh(depthOnlySubMeshes.data[index]);
  68130. }
  68131. engine.setColorWrite(true);
  68132. }
  68133. for (index = 0; index < opaqueSubMeshes.length; index++) {
  68134. renderSubMesh(opaqueSubMeshes.data[index]);
  68135. }
  68136. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  68137. renderSubMesh(alphaTestSubMeshes.data[index]);
  68138. }
  68139. };
  68140. }
  68141. /**
  68142. * Creates the depth rendering effect and checks if the effect is ready.
  68143. * @param subMesh The submesh to be used to render the depth map of
  68144. * @param useInstances If multiple world instances should be used
  68145. * @returns if the depth renderer is ready to render the depth map
  68146. */
  68147. DepthRenderer.prototype.isReady = function (subMesh, useInstances) {
  68148. var material = subMesh.getMaterial();
  68149. if (material.disableDepthWrite) {
  68150. return false;
  68151. }
  68152. var defines = [];
  68153. var attribs = [BABYLON.VertexBuffer.PositionKind];
  68154. var mesh = subMesh.getMesh();
  68155. // Alpha test
  68156. if (material && material.needAlphaTesting() && material.getAlphaTestTexture()) {
  68157. defines.push("#define ALPHATEST");
  68158. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  68159. attribs.push(BABYLON.VertexBuffer.UVKind);
  68160. defines.push("#define UV1");
  68161. }
  68162. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  68163. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  68164. defines.push("#define UV2");
  68165. }
  68166. }
  68167. // Bones
  68168. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  68169. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  68170. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  68171. if (mesh.numBoneInfluencers > 4) {
  68172. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  68173. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  68174. }
  68175. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  68176. defines.push("#define BonesPerMesh " + (mesh.skeleton ? mesh.skeleton.bones.length + 1 : 0));
  68177. }
  68178. else {
  68179. defines.push("#define NUM_BONE_INFLUENCERS 0");
  68180. }
  68181. // Instances
  68182. if (useInstances) {
  68183. defines.push("#define INSTANCES");
  68184. attribs.push("world0");
  68185. attribs.push("world1");
  68186. attribs.push("world2");
  68187. attribs.push("world3");
  68188. }
  68189. // Get correct effect
  68190. var join = defines.join("\n");
  68191. if (this._cachedDefines !== join) {
  68192. this._cachedDefines = join;
  68193. this._effect = this._scene.getEngine().createEffect("depth", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "depthValues"], ["diffuseSampler"], join);
  68194. }
  68195. return this._effect.isReady();
  68196. };
  68197. /**
  68198. * Gets the texture which the depth map will be written to.
  68199. * @returns The depth map texture
  68200. */
  68201. DepthRenderer.prototype.getDepthMap = function () {
  68202. return this._depthMap;
  68203. };
  68204. /**
  68205. * Disposes of the depth renderer.
  68206. */
  68207. DepthRenderer.prototype.dispose = function () {
  68208. this._depthMap.dispose();
  68209. };
  68210. return DepthRenderer;
  68211. }());
  68212. BABYLON.DepthRenderer = DepthRenderer;
  68213. })(BABYLON || (BABYLON = {}));
  68214. //# sourceMappingURL=babylon.depthRenderer.js.map
  68215. "use strict";
  68216. var BABYLON;
  68217. (function (BABYLON) {
  68218. var SSAORenderingPipeline = /** @class */ (function (_super) {
  68219. __extends(SSAORenderingPipeline, _super);
  68220. /**
  68221. * @constructor
  68222. * @param {string} name - The rendering pipeline name
  68223. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  68224. * @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 }
  68225. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  68226. */
  68227. function SSAORenderingPipeline(name, scene, ratio, cameras) {
  68228. var _this = _super.call(this, scene.getEngine(), name) || this;
  68229. // Members
  68230. /**
  68231. * The PassPostProcess id in the pipeline that contains the original scene color
  68232. */
  68233. _this.SSAOOriginalSceneColorEffect = "SSAOOriginalSceneColorEffect";
  68234. /**
  68235. * The SSAO PostProcess id in the pipeline
  68236. */
  68237. _this.SSAORenderEffect = "SSAORenderEffect";
  68238. /**
  68239. * The horizontal blur PostProcess id in the pipeline
  68240. */
  68241. _this.SSAOBlurHRenderEffect = "SSAOBlurHRenderEffect";
  68242. /**
  68243. * The vertical blur PostProcess id in the pipeline
  68244. */
  68245. _this.SSAOBlurVRenderEffect = "SSAOBlurVRenderEffect";
  68246. /**
  68247. * The PostProcess id in the pipeline that combines the SSAO-Blur output with the original scene color (SSAOOriginalSceneColorEffect)
  68248. */
  68249. _this.SSAOCombineRenderEffect = "SSAOCombineRenderEffect";
  68250. /**
  68251. * The output strength of the SSAO post-process. Default value is 1.0.
  68252. */
  68253. _this.totalStrength = 1.0;
  68254. /**
  68255. * The radius around the analyzed pixel used by the SSAO post-process. Default value is 0.0006
  68256. */
  68257. _this.radius = 0.0001;
  68258. /**
  68259. * Related to fallOff, used to interpolate SSAO samples (first interpolate function input) based on the occlusion difference of each pixel
  68260. * Must not be equal to fallOff and superior to fallOff.
  68261. * Default value is 0.975
  68262. */
  68263. _this.area = 0.0075;
  68264. /**
  68265. * Related to area, used to interpolate SSAO samples (second interpolate function input) based on the occlusion difference of each pixel
  68266. * Must not be equal to area and inferior to area.
  68267. * Default value is 0.0
  68268. */
  68269. _this.fallOff = 0.000001;
  68270. /**
  68271. * The base color of the SSAO post-process
  68272. * The final result is "base + ssao" between [0, 1]
  68273. */
  68274. _this.base = 0.5;
  68275. _this._firstUpdate = true;
  68276. _this._scene = scene;
  68277. // Set up assets
  68278. _this._createRandomTexture();
  68279. _this._depthTexture = scene.enableDepthRenderer().getDepthMap(); // Force depth renderer "on"
  68280. var ssaoRatio = ratio.ssaoRatio || ratio;
  68281. var combineRatio = ratio.combineRatio || ratio;
  68282. _this._originalColorPostProcess = new BABYLON.PassPostProcess("SSAOOriginalSceneColor", combineRatio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false);
  68283. _this._createSSAOPostProcess(ssaoRatio);
  68284. _this._createBlurPostProcess(ssaoRatio);
  68285. _this._createSSAOCombinePostProcess(combineRatio);
  68286. // Set up pipeline
  68287. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOOriginalSceneColorEffect, function () { return _this._originalColorPostProcess; }, true));
  68288. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAORenderEffect, function () { return _this._ssaoPostProcess; }, true));
  68289. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOBlurHRenderEffect, function () { return _this._blurHPostProcess; }, true));
  68290. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOBlurVRenderEffect, function () { return _this._blurVPostProcess; }, true));
  68291. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOCombineRenderEffect, function () { return _this._ssaoCombinePostProcess; }, true));
  68292. // Finish
  68293. scene.postProcessRenderPipelineManager.addPipeline(_this);
  68294. if (cameras)
  68295. scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);
  68296. return _this;
  68297. }
  68298. // Public Methods
  68299. /**
  68300. * Removes the internal pipeline assets and detatches the pipeline from the scene cameras
  68301. */
  68302. SSAORenderingPipeline.prototype.dispose = function (disableDepthRender) {
  68303. if (disableDepthRender === void 0) { disableDepthRender = false; }
  68304. for (var i = 0; i < this._scene.cameras.length; i++) {
  68305. var camera = this._scene.cameras[i];
  68306. this._originalColorPostProcess.dispose(camera);
  68307. this._ssaoPostProcess.dispose(camera);
  68308. this._blurHPostProcess.dispose(camera);
  68309. this._blurVPostProcess.dispose(camera);
  68310. this._ssaoCombinePostProcess.dispose(camera);
  68311. }
  68312. this._randomTexture.dispose();
  68313. if (disableDepthRender)
  68314. this._scene.disableDepthRenderer();
  68315. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._scene.cameras);
  68316. _super.prototype.dispose.call(this);
  68317. };
  68318. // Private Methods
  68319. SSAORenderingPipeline.prototype._createBlurPostProcess = function (ratio) {
  68320. var _this = this;
  68321. var size = 16;
  68322. 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);
  68323. 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);
  68324. this._blurHPostProcess.onActivateObservable.add(function () {
  68325. var dw = _this._blurHPostProcess.width / _this._scene.getEngine().getRenderWidth();
  68326. _this._blurHPostProcess.kernel = size * dw;
  68327. });
  68328. this._blurVPostProcess.onActivateObservable.add(function () {
  68329. var dw = _this._blurVPostProcess.height / _this._scene.getEngine().getRenderHeight();
  68330. _this._blurVPostProcess.kernel = size * dw;
  68331. });
  68332. };
  68333. SSAORenderingPipeline.prototype._rebuild = function () {
  68334. this._firstUpdate = true;
  68335. _super.prototype._rebuild.call(this);
  68336. };
  68337. SSAORenderingPipeline.prototype._createSSAOPostProcess = function (ratio) {
  68338. var _this = this;
  68339. var numSamples = 16;
  68340. var sampleSphere = [
  68341. 0.5381, 0.1856, -0.4319,
  68342. 0.1379, 0.2486, 0.4430,
  68343. 0.3371, 0.5679, -0.0057,
  68344. -0.6999, -0.0451, -0.0019,
  68345. 0.0689, -0.1598, -0.8547,
  68346. 0.0560, 0.0069, -0.1843,
  68347. -0.0146, 0.1402, 0.0762,
  68348. 0.0100, -0.1924, -0.0344,
  68349. -0.3577, -0.5301, -0.4358,
  68350. -0.3169, 0.1063, 0.0158,
  68351. 0.0103, -0.5869, 0.0046,
  68352. -0.0897, -0.4940, 0.3287,
  68353. 0.7119, -0.0154, -0.0918,
  68354. -0.0533, 0.0596, -0.5411,
  68355. 0.0352, -0.0631, 0.5460,
  68356. -0.4776, 0.2847, -0.0271
  68357. ];
  68358. var samplesFactor = 1.0 / numSamples;
  68359. this._ssaoPostProcess = new BABYLON.PostProcess("ssao", "ssao", [
  68360. "sampleSphere", "samplesFactor", "randTextureTiles", "totalStrength", "radius",
  68361. "area", "fallOff", "base", "range", "viewport"
  68362. ], ["randomSampler"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, "#define SAMPLES " + numSamples + "\n#define SSAO");
  68363. this._ssaoPostProcess.onApply = function (effect) {
  68364. if (_this._firstUpdate) {
  68365. effect.setArray3("sampleSphere", sampleSphere);
  68366. effect.setFloat("samplesFactor", samplesFactor);
  68367. effect.setFloat("randTextureTiles", 4.0);
  68368. }
  68369. effect.setFloat("totalStrength", _this.totalStrength);
  68370. effect.setFloat("radius", _this.radius);
  68371. effect.setFloat("area", _this.area);
  68372. effect.setFloat("fallOff", _this.fallOff);
  68373. effect.setFloat("base", _this.base);
  68374. effect.setTexture("textureSampler", _this._depthTexture);
  68375. effect.setTexture("randomSampler", _this._randomTexture);
  68376. };
  68377. };
  68378. SSAORenderingPipeline.prototype._createSSAOCombinePostProcess = function (ratio) {
  68379. var _this = this;
  68380. this._ssaoCombinePostProcess = new BABYLON.PostProcess("ssaoCombine", "ssaoCombine", [], ["originalColor"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  68381. this._ssaoCombinePostProcess.onApply = function (effect) {
  68382. effect.setTextureFromPostProcess("originalColor", _this._originalColorPostProcess);
  68383. };
  68384. };
  68385. SSAORenderingPipeline.prototype._createRandomTexture = function () {
  68386. var size = 512;
  68387. this._randomTexture = new BABYLON.DynamicTexture("SSAORandomTexture", size, this._scene, false, BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  68388. this._randomTexture.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  68389. this._randomTexture.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  68390. var context = this._randomTexture.getContext();
  68391. var rand = function (min, max) {
  68392. return Math.random() * (max - min) + min;
  68393. };
  68394. var randVector = BABYLON.Vector3.Zero();
  68395. for (var x = 0; x < size; x++) {
  68396. for (var y = 0; y < size; y++) {
  68397. randVector.x = Math.floor(rand(-1.0, 1.0) * 255);
  68398. randVector.y = Math.floor(rand(-1.0, 1.0) * 255);
  68399. randVector.z = Math.floor(rand(-1.0, 1.0) * 255);
  68400. context.fillStyle = 'rgb(' + randVector.x + ', ' + randVector.y + ', ' + randVector.z + ')';
  68401. context.fillRect(x, y, 1, 1);
  68402. }
  68403. }
  68404. this._randomTexture.update(false);
  68405. };
  68406. __decorate([
  68407. BABYLON.serialize()
  68408. ], SSAORenderingPipeline.prototype, "totalStrength", void 0);
  68409. __decorate([
  68410. BABYLON.serialize()
  68411. ], SSAORenderingPipeline.prototype, "radius", void 0);
  68412. __decorate([
  68413. BABYLON.serialize()
  68414. ], SSAORenderingPipeline.prototype, "area", void 0);
  68415. __decorate([
  68416. BABYLON.serialize()
  68417. ], SSAORenderingPipeline.prototype, "fallOff", void 0);
  68418. __decorate([
  68419. BABYLON.serialize()
  68420. ], SSAORenderingPipeline.prototype, "base", void 0);
  68421. return SSAORenderingPipeline;
  68422. }(BABYLON.PostProcessRenderPipeline));
  68423. BABYLON.SSAORenderingPipeline = SSAORenderingPipeline;
  68424. })(BABYLON || (BABYLON = {}));
  68425. //# sourceMappingURL=babylon.ssaoRenderingPipeline.js.map
  68426. "use strict";
  68427. var BABYLON;
  68428. (function (BABYLON) {
  68429. var SSAO2RenderingPipeline = /** @class */ (function (_super) {
  68430. __extends(SSAO2RenderingPipeline, _super);
  68431. /**
  68432. * @constructor
  68433. * @param {string} name - The rendering pipeline name
  68434. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  68435. * @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 }
  68436. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  68437. */
  68438. function SSAO2RenderingPipeline(name, scene, ratio, cameras) {
  68439. var _this = _super.call(this, scene.getEngine(), name) || this;
  68440. // Members
  68441. /**
  68442. * The PassPostProcess id in the pipeline that contains the original scene color
  68443. */
  68444. _this.SSAOOriginalSceneColorEffect = "SSAOOriginalSceneColorEffect";
  68445. /**
  68446. * The SSAO PostProcess id in the pipeline
  68447. */
  68448. _this.SSAORenderEffect = "SSAORenderEffect";
  68449. /**
  68450. * The horizontal blur PostProcess id in the pipeline
  68451. */
  68452. _this.SSAOBlurHRenderEffect = "SSAOBlurHRenderEffect";
  68453. /**
  68454. * The vertical blur PostProcess id in the pipeline
  68455. */
  68456. _this.SSAOBlurVRenderEffect = "SSAOBlurVRenderEffect";
  68457. /**
  68458. * The PostProcess id in the pipeline that combines the SSAO-Blur output with the original scene color (SSAOOriginalSceneColorEffect)
  68459. */
  68460. _this.SSAOCombineRenderEffect = "SSAOCombineRenderEffect";
  68461. /**
  68462. * The output strength of the SSAO post-process. Default value is 1.0.
  68463. */
  68464. _this.totalStrength = 1.0;
  68465. /**
  68466. * Maximum depth value to still render AO. A smooth falloff makes the dimming more natural, so there will be no abrupt shading change.
  68467. */
  68468. _this.maxZ = 100.0;
  68469. /**
  68470. * In order to save performances, SSAO radius is clamped on close geometry. This ratio changes by how much
  68471. */
  68472. _this.minZAspect = 0.2;
  68473. /**
  68474. * Number of samples used for the SSAO calculations. Default value is 8
  68475. */
  68476. _this._samples = 8;
  68477. /**
  68478. * Are we using bilateral blur ?
  68479. */
  68480. _this._expensiveBlur = true;
  68481. /**
  68482. * The radius around the analyzed pixel used by the SSAO post-process. Default value is 2.0
  68483. */
  68484. _this.radius = 2.0;
  68485. /**
  68486. * The base color of the SSAO post-process
  68487. * The final result is "base + ssao" between [0, 1]
  68488. */
  68489. _this.base = 0.1;
  68490. _this._firstUpdate = true;
  68491. _this._scene = scene;
  68492. if (!_this.isSupported) {
  68493. BABYLON.Tools.Error("SSAO 2 needs WebGL 2 support.");
  68494. return _this;
  68495. }
  68496. var ssaoRatio = ratio.ssaoRatio || ratio;
  68497. var blurRatio = ratio.blurRatio || ratio;
  68498. // Set up assets
  68499. var geometryBufferRenderer = scene.enableGeometryBufferRenderer();
  68500. _this._createRandomTexture();
  68501. _this._depthTexture = geometryBufferRenderer.getGBuffer().textures[0];
  68502. _this._normalTexture = geometryBufferRenderer.getGBuffer().textures[1];
  68503. _this._originalColorPostProcess = new BABYLON.PassPostProcess("SSAOOriginalSceneColor", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false);
  68504. _this._createSSAOPostProcess(1.0);
  68505. _this._createBlurPostProcess(ssaoRatio, blurRatio);
  68506. _this._createSSAOCombinePostProcess(blurRatio);
  68507. // Set up pipeline
  68508. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOOriginalSceneColorEffect, function () { return _this._originalColorPostProcess; }, true));
  68509. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAORenderEffect, function () { return _this._ssaoPostProcess; }, true));
  68510. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOBlurHRenderEffect, function () { return _this._blurHPostProcess; }, true));
  68511. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOBlurVRenderEffect, function () { return _this._blurVPostProcess; }, true));
  68512. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOCombineRenderEffect, function () { return _this._ssaoCombinePostProcess; }, true));
  68513. // Finish
  68514. scene.postProcessRenderPipelineManager.addPipeline(_this);
  68515. if (cameras)
  68516. scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);
  68517. return _this;
  68518. }
  68519. Object.defineProperty(SSAO2RenderingPipeline.prototype, "samples", {
  68520. get: function () {
  68521. return this._samples;
  68522. },
  68523. set: function (n) {
  68524. this._ssaoPostProcess.updateEffect("#define SAMPLES " + n + "\n#define SSAO");
  68525. this._samples = n;
  68526. this._sampleSphere = this._generateHemisphere();
  68527. this._firstUpdate = true;
  68528. },
  68529. enumerable: true,
  68530. configurable: true
  68531. });
  68532. Object.defineProperty(SSAO2RenderingPipeline.prototype, "expensiveBlur", {
  68533. get: function () {
  68534. return this._expensiveBlur;
  68535. },
  68536. set: function (b) {
  68537. 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"]);
  68538. this._blurVPostProcess.updateEffect("#define BILATERAL_BLUR\n#define SAMPLES 16\n#define EXPENSIVE " + (b ? "1" : "0") + "\n", null, ["textureSampler", "depthSampler"]);
  68539. this._expensiveBlur = b;
  68540. this._firstUpdate = true;
  68541. },
  68542. enumerable: true,
  68543. configurable: true
  68544. });
  68545. Object.defineProperty(SSAO2RenderingPipeline, "IsSupported", {
  68546. /**
  68547. * Support test.
  68548. */
  68549. get: function () {
  68550. var engine = BABYLON.Engine.LastCreatedEngine;
  68551. if (!engine) {
  68552. return false;
  68553. }
  68554. return engine.getCaps().drawBuffersExtension;
  68555. },
  68556. enumerable: true,
  68557. configurable: true
  68558. });
  68559. // Public Methods
  68560. /**
  68561. * Removes the internal pipeline assets and detatches the pipeline from the scene cameras
  68562. */
  68563. SSAO2RenderingPipeline.prototype.dispose = function (disableGeometryBufferRenderer) {
  68564. if (disableGeometryBufferRenderer === void 0) { disableGeometryBufferRenderer = false; }
  68565. for (var i = 0; i < this._scene.cameras.length; i++) {
  68566. var camera = this._scene.cameras[i];
  68567. this._originalColorPostProcess.dispose(camera);
  68568. this._ssaoPostProcess.dispose(camera);
  68569. this._blurHPostProcess.dispose(camera);
  68570. this._blurVPostProcess.dispose(camera);
  68571. this._ssaoCombinePostProcess.dispose(camera);
  68572. }
  68573. this._randomTexture.dispose();
  68574. if (disableGeometryBufferRenderer)
  68575. this._scene.disableGeometryBufferRenderer();
  68576. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._scene.cameras);
  68577. _super.prototype.dispose.call(this);
  68578. };
  68579. // Private Methods
  68580. SSAO2RenderingPipeline.prototype._createBlurPostProcess = function (ssaoRatio, blurRatio) {
  68581. var _this = this;
  68582. this._samplerOffsets = [];
  68583. var expensive = this.expensiveBlur;
  68584. for (var i = -8; i < 8; i++) {
  68585. this._samplerOffsets.push(i * 2 + 0.5);
  68586. }
  68587. 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");
  68588. this._blurHPostProcess.onApply = function (effect) {
  68589. if (!_this._scene.activeCamera) {
  68590. return;
  68591. }
  68592. effect.setFloat("outSize", _this._ssaoCombinePostProcess.width > 0 ? _this._ssaoCombinePostProcess.width : _this._originalColorPostProcess.width);
  68593. effect.setFloat("near", _this._scene.activeCamera.minZ);
  68594. effect.setFloat("far", _this._scene.activeCamera.maxZ);
  68595. effect.setFloat("radius", _this.radius);
  68596. effect.setTexture("depthSampler", _this._depthTexture);
  68597. if (_this._firstUpdate) {
  68598. effect.setArray("samplerOffsets", _this._samplerOffsets);
  68599. }
  68600. };
  68601. 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");
  68602. this._blurVPostProcess.onApply = function (effect) {
  68603. if (!_this._scene.activeCamera) {
  68604. return;
  68605. }
  68606. effect.setFloat("outSize", _this._ssaoCombinePostProcess.height > 0 ? _this._ssaoCombinePostProcess.height : _this._originalColorPostProcess.height);
  68607. effect.setFloat("near", _this._scene.activeCamera.minZ);
  68608. effect.setFloat("far", _this._scene.activeCamera.maxZ);
  68609. effect.setFloat("radius", _this.radius);
  68610. effect.setTexture("depthSampler", _this._depthTexture);
  68611. if (_this._firstUpdate) {
  68612. effect.setArray("samplerOffsets", _this._samplerOffsets);
  68613. _this._firstUpdate = false;
  68614. }
  68615. };
  68616. };
  68617. SSAO2RenderingPipeline.prototype._rebuild = function () {
  68618. this._firstUpdate = true;
  68619. _super.prototype._rebuild.call(this);
  68620. };
  68621. SSAO2RenderingPipeline.prototype._generateHemisphere = function () {
  68622. var numSamples = this.samples;
  68623. var result = [];
  68624. var vector, scale;
  68625. var rand = function (min, max) {
  68626. return Math.random() * (max - min) + min;
  68627. };
  68628. var i = 0;
  68629. while (i < numSamples) {
  68630. vector = new BABYLON.Vector3(rand(-1.0, 1.0), rand(-1.0, 1.0), rand(0.30, 1.0));
  68631. vector.normalize();
  68632. scale = i / numSamples;
  68633. scale = BABYLON.Scalar.Lerp(0.1, 1.0, scale * scale);
  68634. vector.scaleInPlace(scale);
  68635. result.push(vector.x, vector.y, vector.z);
  68636. i++;
  68637. }
  68638. return result;
  68639. };
  68640. SSAO2RenderingPipeline.prototype._createSSAOPostProcess = function (ratio) {
  68641. var _this = this;
  68642. var numSamples = this.samples;
  68643. this._sampleSphere = this._generateHemisphere();
  68644. this._ssaoPostProcess = new BABYLON.PostProcess("ssao2", "ssao2", [
  68645. "sampleSphere", "samplesFactor", "randTextureTiles", "totalStrength", "radius",
  68646. "base", "range", "projection", "near", "far", "texelSize",
  68647. "xViewport", "yViewport", "maxZ", "minZAspect"
  68648. ], ["randomSampler", "normalSampler"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, "#define SAMPLES " + numSamples + "\n#define SSAO");
  68649. this._ssaoPostProcess.onApply = function (effect) {
  68650. if (_this._firstUpdate) {
  68651. effect.setArray3("sampleSphere", _this._sampleSphere);
  68652. effect.setFloat("randTextureTiles", 4.0);
  68653. }
  68654. if (!_this._scene.activeCamera) {
  68655. return;
  68656. }
  68657. effect.setFloat("samplesFactor", 1 / _this.samples);
  68658. effect.setFloat("totalStrength", _this.totalStrength);
  68659. effect.setFloat2("texelSize", 1 / _this._ssaoPostProcess.width, 1 / _this._ssaoPostProcess.height);
  68660. effect.setFloat("radius", _this.radius);
  68661. effect.setFloat("maxZ", _this.maxZ);
  68662. effect.setFloat("minZAspect", _this.minZAspect);
  68663. effect.setFloat("base", _this.base);
  68664. effect.setFloat("near", _this._scene.activeCamera.minZ);
  68665. effect.setFloat("far", _this._scene.activeCamera.maxZ);
  68666. effect.setFloat("xViewport", Math.tan(_this._scene.activeCamera.fov / 2) * _this._scene.getEngine().getAspectRatio(_this._scene.activeCamera, true));
  68667. effect.setFloat("yViewport", Math.tan(_this._scene.activeCamera.fov / 2));
  68668. effect.setMatrix("projection", _this._scene.getProjectionMatrix());
  68669. effect.setTexture("textureSampler", _this._depthTexture);
  68670. effect.setTexture("normalSampler", _this._normalTexture);
  68671. effect.setTexture("randomSampler", _this._randomTexture);
  68672. };
  68673. };
  68674. SSAO2RenderingPipeline.prototype._createSSAOCombinePostProcess = function (ratio) {
  68675. var _this = this;
  68676. this._ssaoCombinePostProcess = new BABYLON.PostProcess("ssaoCombine", "ssaoCombine", [], ["originalColor"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  68677. this._ssaoCombinePostProcess.onApply = function (effect) {
  68678. effect.setTextureFromPostProcess("originalColor", _this._originalColorPostProcess);
  68679. };
  68680. };
  68681. SSAO2RenderingPipeline.prototype._createRandomTexture = function () {
  68682. var size = 512;
  68683. this._randomTexture = new BABYLON.DynamicTexture("SSAORandomTexture", size, this._scene, false, BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  68684. this._randomTexture.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  68685. this._randomTexture.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  68686. var context = this._randomTexture.getContext();
  68687. var rand = function (min, max) {
  68688. return Math.random() * (max - min) + min;
  68689. };
  68690. var randVector = BABYLON.Vector3.Zero();
  68691. for (var x = 0; x < size; x++) {
  68692. for (var y = 0; y < size; y++) {
  68693. randVector.x = rand(0.0, 1.0);
  68694. randVector.y = rand(0.0, 1.0);
  68695. randVector.z = 0.0;
  68696. randVector.normalize();
  68697. randVector.scaleInPlace(255);
  68698. randVector.x = Math.floor(randVector.x);
  68699. randVector.y = Math.floor(randVector.y);
  68700. context.fillStyle = 'rgb(' + randVector.x + ', ' + randVector.y + ', ' + randVector.z + ')';
  68701. context.fillRect(x, y, 1, 1);
  68702. }
  68703. }
  68704. this._randomTexture.update(false);
  68705. };
  68706. __decorate([
  68707. BABYLON.serialize()
  68708. ], SSAO2RenderingPipeline.prototype, "totalStrength", void 0);
  68709. __decorate([
  68710. BABYLON.serialize()
  68711. ], SSAO2RenderingPipeline.prototype, "maxZ", void 0);
  68712. __decorate([
  68713. BABYLON.serialize()
  68714. ], SSAO2RenderingPipeline.prototype, "minZAspect", void 0);
  68715. __decorate([
  68716. BABYLON.serialize("samples")
  68717. ], SSAO2RenderingPipeline.prototype, "_samples", void 0);
  68718. __decorate([
  68719. BABYLON.serialize("expensiveBlur")
  68720. ], SSAO2RenderingPipeline.prototype, "_expensiveBlur", void 0);
  68721. __decorate([
  68722. BABYLON.serialize()
  68723. ], SSAO2RenderingPipeline.prototype, "radius", void 0);
  68724. __decorate([
  68725. BABYLON.serialize()
  68726. ], SSAO2RenderingPipeline.prototype, "base", void 0);
  68727. return SSAO2RenderingPipeline;
  68728. }(BABYLON.PostProcessRenderPipeline));
  68729. BABYLON.SSAO2RenderingPipeline = SSAO2RenderingPipeline;
  68730. })(BABYLON || (BABYLON = {}));
  68731. //# sourceMappingURL=babylon.ssao2RenderingPipeline.js.map
  68732. "use strict";
  68733. // BABYLON.JS Chromatic Aberration GLSL Shader
  68734. // Author: Olivier Guyot
  68735. // Separates very slightly R, G and B colors on the edges of the screen
  68736. // Inspired by Francois Tarlier & Martins Upitis
  68737. var BABYLON;
  68738. (function (BABYLON) {
  68739. var LensRenderingPipeline = /** @class */ (function (_super) {
  68740. __extends(LensRenderingPipeline, _super);
  68741. /**
  68742. * @constructor
  68743. *
  68744. * Effect parameters are as follow:
  68745. * {
  68746. * chromatic_aberration: number; // from 0 to x (1 for realism)
  68747. * edge_blur: number; // from 0 to x (1 for realism)
  68748. * distortion: number; // from 0 to x (1 for realism)
  68749. * grain_amount: number; // from 0 to 1
  68750. * grain_texture: BABYLON.Texture; // texture to use for grain effect; if unset, use random B&W noise
  68751. * dof_focus_distance: number; // depth-of-field: focus distance; unset to disable (disabled by default)
  68752. * dof_aperture: number; // depth-of-field: focus blur bias (default: 1)
  68753. * dof_darken: number; // depth-of-field: darken that which is out of focus (from 0 to 1, disabled by default)
  68754. * dof_pentagon: boolean; // depth-of-field: makes a pentagon-like "bokeh" effect
  68755. * dof_gain: number; // depth-of-field: highlights gain; unset to disable (disabled by default)
  68756. * dof_threshold: number; // depth-of-field: highlights threshold (default: 1)
  68757. * blur_noise: boolean; // add a little bit of noise to the blur (default: true)
  68758. * }
  68759. * Note: if an effect parameter is unset, effect is disabled
  68760. *
  68761. * @param {string} name - The rendering pipeline name
  68762. * @param {object} parameters - An object containing all parameters (see above)
  68763. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  68764. * @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)
  68765. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  68766. */
  68767. function LensRenderingPipeline(name, parameters, scene, ratio, cameras) {
  68768. if (ratio === void 0) { ratio = 1.0; }
  68769. var _this = _super.call(this, scene.getEngine(), name) || this;
  68770. // Lens effects can be of the following:
  68771. // - chromatic aberration (slight shift of RGB colors)
  68772. // - blur on the edge of the lens
  68773. // - lens distortion
  68774. // - depth-of-field blur & highlights enhancing
  68775. // - depth-of-field 'bokeh' effect (shapes appearing in blurred areas)
  68776. // - grain effect (noise or custom texture)
  68777. // Two additional texture samplers are needed:
  68778. // - depth map (for depth-of-field)
  68779. // - grain texture
  68780. /**
  68781. * The chromatic aberration PostProcess id in the pipeline
  68782. */
  68783. _this.LensChromaticAberrationEffect = "LensChromaticAberrationEffect";
  68784. /**
  68785. * The highlights enhancing PostProcess id in the pipeline
  68786. */
  68787. _this.HighlightsEnhancingEffect = "HighlightsEnhancingEffect";
  68788. /**
  68789. * The depth-of-field PostProcess id in the pipeline
  68790. */
  68791. _this.LensDepthOfFieldEffect = "LensDepthOfFieldEffect";
  68792. _this._scene = scene;
  68793. // Fetch texture samplers
  68794. _this._depthTexture = scene.enableDepthRenderer().getDepthMap(); // Force depth renderer "on"
  68795. if (parameters.grain_texture) {
  68796. _this._grainTexture = parameters.grain_texture;
  68797. }
  68798. else {
  68799. _this._createGrainTexture();
  68800. }
  68801. // save parameters
  68802. _this._edgeBlur = parameters.edge_blur ? parameters.edge_blur : 0;
  68803. _this._grainAmount = parameters.grain_amount ? parameters.grain_amount : 0;
  68804. _this._chromaticAberration = parameters.chromatic_aberration ? parameters.chromatic_aberration : 0;
  68805. _this._distortion = parameters.distortion ? parameters.distortion : 0;
  68806. _this._highlightsGain = parameters.dof_gain !== undefined ? parameters.dof_gain : -1;
  68807. _this._highlightsThreshold = parameters.dof_threshold ? parameters.dof_threshold : 1;
  68808. _this._dofDistance = parameters.dof_focus_distance !== undefined ? parameters.dof_focus_distance : -1;
  68809. _this._dofAperture = parameters.dof_aperture ? parameters.dof_aperture : 1;
  68810. _this._dofDarken = parameters.dof_darken ? parameters.dof_darken : 0;
  68811. _this._dofPentagon = parameters.dof_pentagon !== undefined ? parameters.dof_pentagon : true;
  68812. _this._blurNoise = parameters.blur_noise !== undefined ? parameters.blur_noise : true;
  68813. // Create effects
  68814. _this._createChromaticAberrationPostProcess(ratio);
  68815. _this._createHighlightsPostProcess(ratio);
  68816. _this._createDepthOfFieldPostProcess(ratio / 4);
  68817. // Set up pipeline
  68818. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.LensChromaticAberrationEffect, function () { return _this._chromaticAberrationPostProcess; }, true));
  68819. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.HighlightsEnhancingEffect, function () { return _this._highlightsPostProcess; }, true));
  68820. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.LensDepthOfFieldEffect, function () { return _this._depthOfFieldPostProcess; }, true));
  68821. if (_this._highlightsGain === -1) {
  68822. _this._disableEffect(_this.HighlightsEnhancingEffect, null);
  68823. }
  68824. // Finish
  68825. scene.postProcessRenderPipelineManager.addPipeline(_this);
  68826. if (cameras) {
  68827. scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);
  68828. }
  68829. return _this;
  68830. }
  68831. // public methods (self explanatory)
  68832. LensRenderingPipeline.prototype.setEdgeBlur = function (amount) { this._edgeBlur = amount; };
  68833. LensRenderingPipeline.prototype.disableEdgeBlur = function () { this._edgeBlur = 0; };
  68834. LensRenderingPipeline.prototype.setGrainAmount = function (amount) { this._grainAmount = amount; };
  68835. LensRenderingPipeline.prototype.disableGrain = function () { this._grainAmount = 0; };
  68836. LensRenderingPipeline.prototype.setChromaticAberration = function (amount) { this._chromaticAberration = amount; };
  68837. LensRenderingPipeline.prototype.disableChromaticAberration = function () { this._chromaticAberration = 0; };
  68838. LensRenderingPipeline.prototype.setEdgeDistortion = function (amount) { this._distortion = amount; };
  68839. LensRenderingPipeline.prototype.disableEdgeDistortion = function () { this._distortion = 0; };
  68840. LensRenderingPipeline.prototype.setFocusDistance = function (amount) { this._dofDistance = amount; };
  68841. LensRenderingPipeline.prototype.disableDepthOfField = function () { this._dofDistance = -1; };
  68842. LensRenderingPipeline.prototype.setAperture = function (amount) { this._dofAperture = amount; };
  68843. LensRenderingPipeline.prototype.setDarkenOutOfFocus = function (amount) { this._dofDarken = amount; };
  68844. LensRenderingPipeline.prototype.enablePentagonBokeh = function () {
  68845. this._highlightsPostProcess.updateEffect("#define PENTAGON\n");
  68846. };
  68847. LensRenderingPipeline.prototype.disablePentagonBokeh = function () {
  68848. this._highlightsPostProcess.updateEffect();
  68849. };
  68850. LensRenderingPipeline.prototype.enableNoiseBlur = function () { this._blurNoise = true; };
  68851. LensRenderingPipeline.prototype.disableNoiseBlur = function () { this._blurNoise = false; };
  68852. LensRenderingPipeline.prototype.setHighlightsGain = function (amount) {
  68853. this._highlightsGain = amount;
  68854. };
  68855. LensRenderingPipeline.prototype.setHighlightsThreshold = function (amount) {
  68856. if (this._highlightsGain === -1) {
  68857. this._highlightsGain = 1.0;
  68858. }
  68859. this._highlightsThreshold = amount;
  68860. };
  68861. LensRenderingPipeline.prototype.disableHighlights = function () {
  68862. this._highlightsGain = -1;
  68863. };
  68864. /**
  68865. * Removes the internal pipeline assets and detaches the pipeline from the scene cameras
  68866. */
  68867. LensRenderingPipeline.prototype.dispose = function (disableDepthRender) {
  68868. if (disableDepthRender === void 0) { disableDepthRender = false; }
  68869. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._scene.cameras);
  68870. this._chromaticAberrationPostProcess = null;
  68871. this._highlightsPostProcess = null;
  68872. this._depthOfFieldPostProcess = null;
  68873. this._grainTexture.dispose();
  68874. if (disableDepthRender)
  68875. this._scene.disableDepthRenderer();
  68876. };
  68877. // colors shifting and distortion
  68878. LensRenderingPipeline.prototype._createChromaticAberrationPostProcess = function (ratio) {
  68879. var _this = this;
  68880. this._chromaticAberrationPostProcess = new BABYLON.PostProcess("LensChromaticAberration", "chromaticAberration", ["chromatic_aberration", "screen_width", "screen_height", "direction", "radialIntensity", "centerPosition"], // uniforms
  68881. [], // samplers
  68882. ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  68883. this._chromaticAberrationPostProcess.onApply = function (effect) {
  68884. effect.setFloat('chromatic_aberration', _this._chromaticAberration);
  68885. effect.setFloat('screen_width', _this._scene.getEngine().getRenderWidth());
  68886. effect.setFloat('screen_height', _this._scene.getEngine().getRenderHeight());
  68887. effect.setFloat('radialIntensity', 1);
  68888. effect.setFloat2('direction', 17, 17);
  68889. effect.setFloat2('centerPosition', 0.5, 0.5);
  68890. };
  68891. };
  68892. // highlights enhancing
  68893. LensRenderingPipeline.prototype._createHighlightsPostProcess = function (ratio) {
  68894. var _this = this;
  68895. this._highlightsPostProcess = new BABYLON.PostProcess("LensHighlights", "lensHighlights", ["gain", "threshold", "screen_width", "screen_height"], // uniforms
  68896. [], // samplers
  68897. ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, this._dofPentagon ? "#define PENTAGON\n" : "");
  68898. this._highlightsPostProcess.onApply = function (effect) {
  68899. effect.setFloat('gain', _this._highlightsGain);
  68900. effect.setFloat('threshold', _this._highlightsThreshold);
  68901. effect.setTextureFromPostProcess("textureSampler", _this._chromaticAberrationPostProcess);
  68902. effect.setFloat('screen_width', _this._scene.getEngine().getRenderWidth());
  68903. effect.setFloat('screen_height', _this._scene.getEngine().getRenderHeight());
  68904. };
  68905. };
  68906. // colors shifting and distortion
  68907. LensRenderingPipeline.prototype._createDepthOfFieldPostProcess = function (ratio) {
  68908. var _this = this;
  68909. this._depthOfFieldPostProcess = new BABYLON.PostProcess("LensDepthOfField", "depthOfField", [
  68910. "grain_amount", "blur_noise", "screen_width", "screen_height", "distortion", "dof_enabled",
  68911. "screen_distance", "aperture", "darken", "edge_blur", "highlights", "near", "far"
  68912. ], ["depthSampler", "grainSampler", "highlightsSampler"], ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  68913. this._depthOfFieldPostProcess.onApply = function (effect) {
  68914. effect.setTexture("depthSampler", _this._depthTexture);
  68915. effect.setTexture("grainSampler", _this._grainTexture);
  68916. effect.setTextureFromPostProcess("textureSampler", _this._highlightsPostProcess);
  68917. effect.setTextureFromPostProcess("highlightsSampler", _this._depthOfFieldPostProcess);
  68918. effect.setFloat('grain_amount', _this._grainAmount);
  68919. effect.setBool('blur_noise', _this._blurNoise);
  68920. effect.setFloat('screen_width', _this._scene.getEngine().getRenderWidth());
  68921. effect.setFloat('screen_height', _this._scene.getEngine().getRenderHeight());
  68922. effect.setFloat('distortion', _this._distortion);
  68923. effect.setBool('dof_enabled', (_this._dofDistance !== -1));
  68924. effect.setFloat('screen_distance', 1.0 / (0.1 - 1.0 / _this._dofDistance));
  68925. effect.setFloat('aperture', _this._dofAperture);
  68926. effect.setFloat('darken', _this._dofDarken);
  68927. effect.setFloat('edge_blur', _this._edgeBlur);
  68928. effect.setBool('highlights', (_this._highlightsGain !== -1));
  68929. if (_this._scene.activeCamera) {
  68930. effect.setFloat('near', _this._scene.activeCamera.minZ);
  68931. effect.setFloat('far', _this._scene.activeCamera.maxZ);
  68932. }
  68933. };
  68934. };
  68935. // creates a black and white random noise texture, 512x512
  68936. LensRenderingPipeline.prototype._createGrainTexture = function () {
  68937. var size = 512;
  68938. this._grainTexture = new BABYLON.DynamicTexture("LensNoiseTexture", size, this._scene, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  68939. this._grainTexture.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  68940. this._grainTexture.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  68941. var context = this._grainTexture.getContext();
  68942. var rand = function (min, max) {
  68943. return Math.random() * (max - min) + min;
  68944. };
  68945. var value;
  68946. for (var x = 0; x < size; x++) {
  68947. for (var y = 0; y < size; y++) {
  68948. value = Math.floor(rand(0.42, 0.58) * 255);
  68949. context.fillStyle = 'rgb(' + value + ', ' + value + ', ' + value + ')';
  68950. context.fillRect(x, y, 1, 1);
  68951. }
  68952. }
  68953. this._grainTexture.update(false);
  68954. };
  68955. return LensRenderingPipeline;
  68956. }(BABYLON.PostProcessRenderPipeline));
  68957. BABYLON.LensRenderingPipeline = LensRenderingPipeline;
  68958. })(BABYLON || (BABYLON = {}));
  68959. //# sourceMappingURL=babylon.lensRenderingPipeline.js.map
  68960. "use strict";
  68961. var BABYLON;
  68962. (function (BABYLON) {
  68963. var StandardRenderingPipeline = /** @class */ (function (_super) {
  68964. __extends(StandardRenderingPipeline, _super);
  68965. /**
  68966. * @constructor
  68967. * @param {string} name - The rendering pipeline name
  68968. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  68969. * @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)
  68970. * @param {BABYLON.PostProcess} originalPostProcess - the custom original color post-process. Must be "reusable". Can be null.
  68971. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  68972. */
  68973. function StandardRenderingPipeline(name, scene, ratio, originalPostProcess, cameras) {
  68974. if (originalPostProcess === void 0) { originalPostProcess = null; }
  68975. var _this = _super.call(this, scene.getEngine(), name) || this;
  68976. _this.downSampleX4PostProcess = null;
  68977. _this.brightPassPostProcess = null;
  68978. _this.blurHPostProcesses = [];
  68979. _this.blurVPostProcesses = [];
  68980. _this.textureAdderPostProcess = null;
  68981. _this.volumetricLightPostProcess = null;
  68982. _this.volumetricLightSmoothXPostProcess = null;
  68983. _this.volumetricLightSmoothYPostProcess = null;
  68984. _this.volumetricLightMergePostProces = null;
  68985. _this.volumetricLightFinalPostProcess = null;
  68986. _this.luminancePostProcess = null;
  68987. _this.luminanceDownSamplePostProcesses = [];
  68988. _this.hdrPostProcess = null;
  68989. _this.textureAdderFinalPostProcess = null;
  68990. _this.lensFlareFinalPostProcess = null;
  68991. _this.hdrFinalPostProcess = null;
  68992. _this.lensFlarePostProcess = null;
  68993. _this.lensFlareComposePostProcess = null;
  68994. _this.motionBlurPostProcess = null;
  68995. _this.depthOfFieldPostProcess = null;
  68996. // Values
  68997. _this.brightThreshold = 1.0;
  68998. _this.blurWidth = 512.0;
  68999. _this.horizontalBlur = false;
  69000. _this.exposure = 1.0;
  69001. _this.lensTexture = null;
  69002. _this.volumetricLightCoefficient = 0.2;
  69003. _this.volumetricLightPower = 4.0;
  69004. _this.volumetricLightBlurScale = 64.0;
  69005. _this.sourceLight = null;
  69006. _this.hdrMinimumLuminance = 1.0;
  69007. _this.hdrDecreaseRate = 0.5;
  69008. _this.hdrIncreaseRate = 0.5;
  69009. _this.lensColorTexture = null;
  69010. _this.lensFlareStrength = 20.0;
  69011. _this.lensFlareGhostDispersal = 1.4;
  69012. _this.lensFlareHaloWidth = 0.7;
  69013. _this.lensFlareDistortionStrength = 16.0;
  69014. _this.lensStarTexture = null;
  69015. _this.lensFlareDirtTexture = null;
  69016. _this.depthOfFieldDistance = 10.0;
  69017. _this.depthOfFieldBlurWidth = 64.0;
  69018. _this.motionStrength = 1.0;
  69019. // IAnimatable
  69020. _this.animations = [];
  69021. _this._currentDepthOfFieldSource = null;
  69022. _this._hdrCurrentLuminance = 1.0;
  69023. // Getters and setters
  69024. _this._bloomEnabled = true;
  69025. _this._depthOfFieldEnabled = false;
  69026. _this._vlsEnabled = false;
  69027. _this._lensFlareEnabled = false;
  69028. _this._hdrEnabled = false;
  69029. _this._motionBlurEnabled = false;
  69030. _this._motionBlurSamples = 64.0;
  69031. _this._volumetricLightStepsCount = 50.0;
  69032. _this._cameras = cameras || [];
  69033. // Initialize
  69034. _this._scene = scene;
  69035. _this._basePostProcess = originalPostProcess;
  69036. _this._ratio = ratio;
  69037. // Misc
  69038. _this._floatTextureType = scene.getEngine().getCaps().textureFloatRender ? BABYLON.Engine.TEXTURETYPE_FLOAT : BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  69039. // Finish
  69040. scene.postProcessRenderPipelineManager.addPipeline(_this);
  69041. _this._buildPipeline();
  69042. return _this;
  69043. }
  69044. Object.defineProperty(StandardRenderingPipeline.prototype, "BloomEnabled", {
  69045. get: function () {
  69046. return this._bloomEnabled;
  69047. },
  69048. set: function (enabled) {
  69049. if (this._bloomEnabled === enabled) {
  69050. return;
  69051. }
  69052. this._bloomEnabled = enabled;
  69053. this._buildPipeline();
  69054. },
  69055. enumerable: true,
  69056. configurable: true
  69057. });
  69058. Object.defineProperty(StandardRenderingPipeline.prototype, "DepthOfFieldEnabled", {
  69059. get: function () {
  69060. return this._depthOfFieldEnabled;
  69061. },
  69062. set: function (enabled) {
  69063. if (this._depthOfFieldEnabled === enabled) {
  69064. return;
  69065. }
  69066. this._depthOfFieldEnabled = enabled;
  69067. this._buildPipeline();
  69068. },
  69069. enumerable: true,
  69070. configurable: true
  69071. });
  69072. Object.defineProperty(StandardRenderingPipeline.prototype, "LensFlareEnabled", {
  69073. get: function () {
  69074. return this._lensFlareEnabled;
  69075. },
  69076. set: function (enabled) {
  69077. if (this._lensFlareEnabled === enabled) {
  69078. return;
  69079. }
  69080. this._lensFlareEnabled = enabled;
  69081. this._buildPipeline();
  69082. },
  69083. enumerable: true,
  69084. configurable: true
  69085. });
  69086. Object.defineProperty(StandardRenderingPipeline.prototype, "HDREnabled", {
  69087. get: function () {
  69088. return this._hdrEnabled;
  69089. },
  69090. set: function (enabled) {
  69091. if (this._hdrEnabled === enabled) {
  69092. return;
  69093. }
  69094. this._hdrEnabled = enabled;
  69095. this._buildPipeline();
  69096. },
  69097. enumerable: true,
  69098. configurable: true
  69099. });
  69100. Object.defineProperty(StandardRenderingPipeline.prototype, "VLSEnabled", {
  69101. get: function () {
  69102. return this._vlsEnabled;
  69103. },
  69104. set: function (enabled) {
  69105. if (this._vlsEnabled === enabled) {
  69106. return;
  69107. }
  69108. if (enabled) {
  69109. var geometry = this._scene.enableGeometryBufferRenderer();
  69110. if (!geometry) {
  69111. BABYLON.Tools.Warn("Geometry renderer is not supported, cannot create volumetric lights in Standard Rendering Pipeline");
  69112. return;
  69113. }
  69114. }
  69115. this._vlsEnabled = enabled;
  69116. this._buildPipeline();
  69117. },
  69118. enumerable: true,
  69119. configurable: true
  69120. });
  69121. Object.defineProperty(StandardRenderingPipeline.prototype, "MotionBlurEnabled", {
  69122. get: function () {
  69123. return this._motionBlurEnabled;
  69124. },
  69125. set: function (enabled) {
  69126. if (this._motionBlurEnabled === enabled) {
  69127. return;
  69128. }
  69129. this._motionBlurEnabled = enabled;
  69130. this._buildPipeline();
  69131. },
  69132. enumerable: true,
  69133. configurable: true
  69134. });
  69135. Object.defineProperty(StandardRenderingPipeline.prototype, "volumetricLightStepsCount", {
  69136. get: function () {
  69137. return this._volumetricLightStepsCount;
  69138. },
  69139. set: function (count) {
  69140. if (this.volumetricLightPostProcess) {
  69141. this.volumetricLightPostProcess.updateEffect("#define VLS\n#define NB_STEPS " + count.toFixed(1));
  69142. }
  69143. this._volumetricLightStepsCount = count;
  69144. },
  69145. enumerable: true,
  69146. configurable: true
  69147. });
  69148. Object.defineProperty(StandardRenderingPipeline.prototype, "motionBlurSamples", {
  69149. get: function () {
  69150. return this._motionBlurSamples;
  69151. },
  69152. set: function (samples) {
  69153. if (this.motionBlurPostProcess) {
  69154. this.motionBlurPostProcess.updateEffect("#define MOTION_BLUR\n#define MAX_MOTION_SAMPLES " + samples.toFixed(1));
  69155. }
  69156. this._motionBlurSamples = samples;
  69157. },
  69158. enumerable: true,
  69159. configurable: true
  69160. });
  69161. StandardRenderingPipeline.prototype._buildPipeline = function () {
  69162. var _this = this;
  69163. var ratio = this._ratio;
  69164. var scene = this._scene;
  69165. this._disposePostProcesses();
  69166. this._reset();
  69167. // Create pass post-process
  69168. if (!this._basePostProcess) {
  69169. this.originalPostProcess = new BABYLON.PostProcess("HDRPass", "standard", [], [], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define PASS_POST_PROCESS", this._floatTextureType);
  69170. this.originalPostProcess.onApply = function (effect) {
  69171. _this._currentDepthOfFieldSource = _this.originalPostProcess;
  69172. };
  69173. }
  69174. else {
  69175. this.originalPostProcess = this._basePostProcess;
  69176. }
  69177. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRPassPostProcess", function () { return _this.originalPostProcess; }, true));
  69178. this._currentDepthOfFieldSource = this.originalPostProcess;
  69179. if (this._vlsEnabled) {
  69180. // Create volumetric light
  69181. this._createVolumetricLightPostProcess(scene, ratio);
  69182. // Create volumetric light final post-process
  69183. 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);
  69184. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRVLSFinal", function () { return _this.volumetricLightFinalPostProcess; }, true));
  69185. }
  69186. if (this._bloomEnabled) {
  69187. // Create down sample X4 post-process
  69188. this._createDownSampleX4PostProcess(scene, ratio / 2);
  69189. // Create bright pass post-process
  69190. this._createBrightPassPostProcess(scene, ratio / 2);
  69191. // Create gaussian blur post-processes (down sampling blurs)
  69192. this._createBlurPostProcesses(scene, ratio / 4, 1);
  69193. // Create texture adder post-process
  69194. this._createTextureAdderPostProcess(scene, ratio);
  69195. // Create depth-of-field source post-process
  69196. 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);
  69197. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRBaseDepthOfFieldSource", function () { return _this.textureAdderFinalPostProcess; }, true));
  69198. }
  69199. if (this._lensFlareEnabled) {
  69200. // Create lens flare post-process
  69201. this._createLensFlarePostProcess(scene, ratio);
  69202. // Create depth-of-field source post-process post lens-flare and disable it now
  69203. 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);
  69204. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRPostLensFlareDepthOfFieldSource", function () { return _this.lensFlareFinalPostProcess; }, true));
  69205. }
  69206. if (this._hdrEnabled) {
  69207. // Create luminance
  69208. this._createLuminancePostProcesses(scene, this._floatTextureType);
  69209. // Create HDR
  69210. this._createHdrPostProcess(scene, ratio);
  69211. // Create depth-of-field source post-process post hdr and disable it now
  69212. 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);
  69213. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRPostHDReDepthOfFieldSource", function () { return _this.hdrFinalPostProcess; }, true));
  69214. }
  69215. if (this._depthOfFieldEnabled) {
  69216. // Create gaussian blur used by depth-of-field
  69217. this._createBlurPostProcesses(scene, ratio / 2, 3, "depthOfFieldBlurWidth");
  69218. // Create depth-of-field post-process
  69219. this._createDepthOfFieldPostProcess(scene, ratio);
  69220. }
  69221. if (this._motionBlurEnabled) {
  69222. // Create motion blur post-process
  69223. this._createMotionBlurPostProcess(scene, ratio);
  69224. }
  69225. if (this._cameras !== null) {
  69226. this._scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(this._name, this._cameras);
  69227. }
  69228. };
  69229. // Down Sample X4 Post-Processs
  69230. StandardRenderingPipeline.prototype._createDownSampleX4PostProcess = function (scene, ratio) {
  69231. var _this = this;
  69232. var downSampleX4Offsets = new Array(32);
  69233. 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);
  69234. this.downSampleX4PostProcess.onApply = function (effect) {
  69235. var id = 0;
  69236. var width = _this.downSampleX4PostProcess.width;
  69237. var height = _this.downSampleX4PostProcess.height;
  69238. for (var i = -2; i < 2; i++) {
  69239. for (var j = -2; j < 2; j++) {
  69240. downSampleX4Offsets[id] = (i + 0.5) * (1.0 / width);
  69241. downSampleX4Offsets[id + 1] = (j + 0.5) * (1.0 / height);
  69242. id += 2;
  69243. }
  69244. }
  69245. effect.setArray2("dsOffsets", downSampleX4Offsets);
  69246. };
  69247. // Add to pipeline
  69248. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRDownSampleX4", function () { return _this.downSampleX4PostProcess; }, true));
  69249. };
  69250. // Brightpass Post-Process
  69251. StandardRenderingPipeline.prototype._createBrightPassPostProcess = function (scene, ratio) {
  69252. var _this = this;
  69253. var brightOffsets = new Array(8);
  69254. 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);
  69255. this.brightPassPostProcess.onApply = function (effect) {
  69256. var sU = (1.0 / _this.brightPassPostProcess.width);
  69257. var sV = (1.0 / _this.brightPassPostProcess.height);
  69258. brightOffsets[0] = -0.5 * sU;
  69259. brightOffsets[1] = 0.5 * sV;
  69260. brightOffsets[2] = 0.5 * sU;
  69261. brightOffsets[3] = 0.5 * sV;
  69262. brightOffsets[4] = -0.5 * sU;
  69263. brightOffsets[5] = -0.5 * sV;
  69264. brightOffsets[6] = 0.5 * sU;
  69265. brightOffsets[7] = -0.5 * sV;
  69266. effect.setArray2("dsOffsets", brightOffsets);
  69267. effect.setFloat("brightThreshold", _this.brightThreshold);
  69268. };
  69269. // Add to pipeline
  69270. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRBrightPass", function () { return _this.brightPassPostProcess; }, true));
  69271. };
  69272. // Create blur H&V post-processes
  69273. StandardRenderingPipeline.prototype._createBlurPostProcesses = function (scene, ratio, indice, blurWidthKey) {
  69274. var _this = this;
  69275. if (blurWidthKey === void 0) { blurWidthKey = "blurWidth"; }
  69276. var engine = scene.getEngine();
  69277. 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);
  69278. 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);
  69279. blurX.onActivateObservable.add(function () {
  69280. var dw = blurX.width / engine.getRenderWidth();
  69281. blurX.kernel = _this[blurWidthKey] * dw;
  69282. });
  69283. blurY.onActivateObservable.add(function () {
  69284. var dw = blurY.height / engine.getRenderHeight();
  69285. blurY.kernel = _this.horizontalBlur ? 64 * dw : _this[blurWidthKey] * dw;
  69286. });
  69287. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRBlurH" + indice, function () { return blurX; }, true));
  69288. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRBlurV" + indice, function () { return blurY; }, true));
  69289. this.blurHPostProcesses.push(blurX);
  69290. this.blurVPostProcesses.push(blurY);
  69291. };
  69292. // Create texture adder post-process
  69293. StandardRenderingPipeline.prototype._createTextureAdderPostProcess = function (scene, ratio) {
  69294. var _this = this;
  69295. 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);
  69296. this.textureAdderPostProcess.onApply = function (effect) {
  69297. effect.setTextureFromPostProcess("otherSampler", _this._vlsEnabled ? _this._currentDepthOfFieldSource : _this.originalPostProcess);
  69298. effect.setTexture("lensSampler", _this.lensTexture);
  69299. effect.setFloat("exposure", _this.exposure);
  69300. _this._currentDepthOfFieldSource = _this.textureAdderFinalPostProcess;
  69301. };
  69302. // Add to pipeline
  69303. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRTextureAdder", function () { return _this.textureAdderPostProcess; }, true));
  69304. };
  69305. StandardRenderingPipeline.prototype._createVolumetricLightPostProcess = function (scene, ratio) {
  69306. var _this = this;
  69307. var geometryRenderer = scene.enableGeometryBufferRenderer();
  69308. geometryRenderer.enablePosition = true;
  69309. var geometry = geometryRenderer.getGBuffer();
  69310. // Base post-process
  69311. 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));
  69312. var depthValues = BABYLON.Vector2.Zero();
  69313. this.volumetricLightPostProcess.onApply = function (effect) {
  69314. if (_this.sourceLight && _this.sourceLight.getShadowGenerator() && _this._scene.activeCamera) {
  69315. var generator = _this.sourceLight.getShadowGenerator();
  69316. effect.setTexture("shadowMapSampler", generator.getShadowMap());
  69317. effect.setTexture("positionSampler", geometry.textures[2]);
  69318. effect.setColor3("sunColor", _this.sourceLight.diffuse);
  69319. effect.setVector3("sunDirection", _this.sourceLight.getShadowDirection());
  69320. effect.setVector3("cameraPosition", _this._scene.activeCamera.globalPosition);
  69321. effect.setMatrix("shadowViewProjection", generator.getTransformMatrix());
  69322. effect.setFloat("scatteringCoefficient", _this.volumetricLightCoefficient);
  69323. effect.setFloat("scatteringPower", _this.volumetricLightPower);
  69324. depthValues.x = generator.getLight().getDepthMinZ(_this._scene.activeCamera);
  69325. depthValues.y = generator.getLight().getDepthMaxZ(_this._scene.activeCamera);
  69326. effect.setVector2("depthValues", depthValues);
  69327. }
  69328. };
  69329. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRVLS", function () { return _this.volumetricLightPostProcess; }, true));
  69330. // Smooth
  69331. this._createBlurPostProcesses(scene, ratio / 4, 0, "volumetricLightBlurScale");
  69332. // Merge
  69333. this.volumetricLightMergePostProces = new BABYLON.PostProcess("HDRVLSMerge", "standard", [], ["originalSampler"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define VLSMERGE");
  69334. this.volumetricLightMergePostProces.onApply = function (effect) {
  69335. effect.setTextureFromPostProcess("originalSampler", _this.originalPostProcess);
  69336. _this._currentDepthOfFieldSource = _this.volumetricLightFinalPostProcess;
  69337. };
  69338. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRVLSMerge", function () { return _this.volumetricLightMergePostProces; }, true));
  69339. };
  69340. // Create luminance
  69341. StandardRenderingPipeline.prototype._createLuminancePostProcesses = function (scene, textureType) {
  69342. var _this = this;
  69343. // Create luminance
  69344. var size = Math.pow(3, StandardRenderingPipeline.LuminanceSteps);
  69345. this.luminancePostProcess = new BABYLON.PostProcess("HDRLuminance", "standard", ["lumOffsets"], [], { width: size, height: size }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define LUMINANCE", textureType);
  69346. var offsets = [];
  69347. this.luminancePostProcess.onApply = function (effect) {
  69348. var sU = (1.0 / _this.luminancePostProcess.width);
  69349. var sV = (1.0 / _this.luminancePostProcess.height);
  69350. offsets[0] = -0.5 * sU;
  69351. offsets[1] = 0.5 * sV;
  69352. offsets[2] = 0.5 * sU;
  69353. offsets[3] = 0.5 * sV;
  69354. offsets[4] = -0.5 * sU;
  69355. offsets[5] = -0.5 * sV;
  69356. offsets[6] = 0.5 * sU;
  69357. offsets[7] = -0.5 * sV;
  69358. effect.setArray2("lumOffsets", offsets);
  69359. };
  69360. // Add to pipeline
  69361. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRLuminance", function () { return _this.luminancePostProcess; }, true));
  69362. // Create down sample luminance
  69363. for (var i = StandardRenderingPipeline.LuminanceSteps - 1; i >= 0; i--) {
  69364. var size = Math.pow(3, i);
  69365. var defines = "#define LUMINANCE_DOWN_SAMPLE\n";
  69366. if (i === 0) {
  69367. defines += "#define FINAL_DOWN_SAMPLER";
  69368. }
  69369. var postProcess = new BABYLON.PostProcess("HDRLuminanceDownSample" + i, "standard", ["dsOffsets", "halfDestPixelSize"], [], { width: size, height: size }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, defines, textureType);
  69370. this.luminanceDownSamplePostProcesses.push(postProcess);
  69371. }
  69372. // Create callbacks and add effects
  69373. var lastLuminance = this.luminancePostProcess;
  69374. this.luminanceDownSamplePostProcesses.forEach(function (pp, index) {
  69375. var downSampleOffsets = new Array(18);
  69376. pp.onApply = function (effect) {
  69377. if (!lastLuminance) {
  69378. return;
  69379. }
  69380. var id = 0;
  69381. for (var x = -1; x < 2; x++) {
  69382. for (var y = -1; y < 2; y++) {
  69383. downSampleOffsets[id] = x / lastLuminance.width;
  69384. downSampleOffsets[id + 1] = y / lastLuminance.height;
  69385. id += 2;
  69386. }
  69387. }
  69388. effect.setArray2("dsOffsets", downSampleOffsets);
  69389. effect.setFloat("halfDestPixelSize", 0.5 / lastLuminance.width);
  69390. if (index === _this.luminanceDownSamplePostProcesses.length - 1) {
  69391. lastLuminance = _this.luminancePostProcess;
  69392. }
  69393. else {
  69394. lastLuminance = pp;
  69395. }
  69396. };
  69397. if (index === _this.luminanceDownSamplePostProcesses.length - 1) {
  69398. pp.onAfterRender = function (effect) {
  69399. var pixel = scene.getEngine().readPixels(0, 0, 1, 1);
  69400. 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);
  69401. _this._hdrCurrentLuminance = (pixel[0] * bit_shift.x + pixel[1] * bit_shift.y + pixel[2] * bit_shift.z + pixel[3] * bit_shift.w) / 100.0;
  69402. };
  69403. }
  69404. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRLuminanceDownSample" + index, function () { return pp; }, true));
  69405. });
  69406. };
  69407. // Create HDR post-process
  69408. StandardRenderingPipeline.prototype._createHdrPostProcess = function (scene, ratio) {
  69409. var _this = this;
  69410. 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);
  69411. var outputLiminance = 1;
  69412. var time = 0;
  69413. var lastTime = 0;
  69414. this.hdrPostProcess.onApply = function (effect) {
  69415. effect.setTextureFromPostProcess("textureAdderSampler", _this._currentDepthOfFieldSource);
  69416. time += scene.getEngine().getDeltaTime();
  69417. if (outputLiminance < 0) {
  69418. outputLiminance = _this._hdrCurrentLuminance;
  69419. }
  69420. else {
  69421. var dt = (lastTime - time) / 1000.0;
  69422. if (_this._hdrCurrentLuminance < outputLiminance + _this.hdrDecreaseRate * dt) {
  69423. outputLiminance += _this.hdrDecreaseRate * dt;
  69424. }
  69425. else if (_this._hdrCurrentLuminance > outputLiminance - _this.hdrIncreaseRate * dt) {
  69426. outputLiminance -= _this.hdrIncreaseRate * dt;
  69427. }
  69428. else {
  69429. outputLiminance = _this._hdrCurrentLuminance;
  69430. }
  69431. }
  69432. outputLiminance = BABYLON.Scalar.Clamp(outputLiminance, _this.hdrMinimumLuminance, 1e20);
  69433. effect.setFloat("averageLuminance", outputLiminance);
  69434. lastTime = time;
  69435. _this._currentDepthOfFieldSource = _this.hdrFinalPostProcess;
  69436. };
  69437. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDR", function () { return _this.hdrPostProcess; }, true));
  69438. };
  69439. // Create lens flare post-process
  69440. StandardRenderingPipeline.prototype._createLensFlarePostProcess = function (scene, ratio) {
  69441. var _this = this;
  69442. 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);
  69443. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRLensFlare", function () { return _this.lensFlarePostProcess; }, true));
  69444. this._createBlurPostProcesses(scene, ratio / 4, 2);
  69445. 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);
  69446. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRLensFlareCompose", function () { return _this.lensFlareComposePostProcess; }, true));
  69447. var resolution = new BABYLON.Vector2(0, 0);
  69448. // Lens flare
  69449. this.lensFlarePostProcess.onApply = function (effect) {
  69450. effect.setTextureFromPostProcess("textureSampler", _this._bloomEnabled ? _this.blurHPostProcesses[0] : _this.originalPostProcess);
  69451. effect.setTexture("lensColorSampler", _this.lensColorTexture);
  69452. effect.setFloat("strength", _this.lensFlareStrength);
  69453. effect.setFloat("ghostDispersal", _this.lensFlareGhostDispersal);
  69454. effect.setFloat("haloWidth", _this.lensFlareHaloWidth);
  69455. // Shift
  69456. resolution.x = _this.lensFlarePostProcess.width;
  69457. resolution.y = _this.lensFlarePostProcess.height;
  69458. effect.setVector2("resolution", resolution);
  69459. effect.setFloat("distortionStrength", _this.lensFlareDistortionStrength);
  69460. };
  69461. // Compose
  69462. 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);
  69463. 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);
  69464. this.lensFlareComposePostProcess.onApply = function (effect) {
  69465. if (!_this._scene.activeCamera) {
  69466. return;
  69467. }
  69468. effect.setTextureFromPostProcess("otherSampler", _this._currentDepthOfFieldSource);
  69469. effect.setTexture("lensDirtSampler", _this.lensFlareDirtTexture);
  69470. effect.setTexture("lensStarSampler", _this.lensStarTexture);
  69471. // Lens start rotation matrix
  69472. var camerax = _this._scene.activeCamera.getViewMatrix().getRow(0);
  69473. var cameraz = _this._scene.activeCamera.getViewMatrix().getRow(2);
  69474. 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));
  69475. camRot *= 4.0;
  69476. 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);
  69477. var lensStarMatrix = scaleBias2.multiply(starRotation).multiply(scaleBias1);
  69478. effect.setMatrix("lensStarMatrix", lensStarMatrix);
  69479. _this._currentDepthOfFieldSource = _this.lensFlareFinalPostProcess;
  69480. };
  69481. };
  69482. // Create depth-of-field post-process
  69483. StandardRenderingPipeline.prototype._createDepthOfFieldPostProcess = function (scene, ratio) {
  69484. var _this = this;
  69485. 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);
  69486. this.depthOfFieldPostProcess.onApply = function (effect) {
  69487. effect.setTextureFromPostProcess("otherSampler", _this._currentDepthOfFieldSource);
  69488. effect.setTexture("depthSampler", _this._getDepthTexture());
  69489. effect.setFloat("distance", _this.depthOfFieldDistance);
  69490. };
  69491. // Add to pipeline
  69492. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRDepthOfField", function () { return _this.depthOfFieldPostProcess; }, true));
  69493. };
  69494. // Create motion blur post-process
  69495. StandardRenderingPipeline.prototype._createMotionBlurPostProcess = function (scene, ratio) {
  69496. var _this = this;
  69497. 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);
  69498. var motionScale = 0;
  69499. var prevViewProjection = BABYLON.Matrix.Identity();
  69500. var invViewProjection = BABYLON.Matrix.Identity();
  69501. var viewProjection = BABYLON.Matrix.Identity();
  69502. var screenSize = BABYLON.Vector2.Zero();
  69503. this.motionBlurPostProcess.onApply = function (effect) {
  69504. viewProjection = scene.getProjectionMatrix().multiply(scene.getViewMatrix());
  69505. viewProjection.invertToRef(invViewProjection);
  69506. effect.setMatrix("inverseViewProjection", invViewProjection);
  69507. effect.setMatrix("prevViewProjection", prevViewProjection);
  69508. prevViewProjection = viewProjection;
  69509. screenSize.x = _this.motionBlurPostProcess.width;
  69510. screenSize.y = _this.motionBlurPostProcess.height;
  69511. effect.setVector2("screenSize", screenSize);
  69512. motionScale = scene.getEngine().getFps() / 60.0;
  69513. effect.setFloat("motionScale", motionScale);
  69514. effect.setFloat("motionStrength", _this.motionStrength);
  69515. effect.setTexture("depthSampler", _this._getDepthTexture());
  69516. };
  69517. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRMotionBlur", function () { return _this.motionBlurPostProcess; }, true));
  69518. };
  69519. StandardRenderingPipeline.prototype._getDepthTexture = function () {
  69520. if (this._scene.getEngine().getCaps().drawBuffersExtension) {
  69521. var renderer = this._scene.enableGeometryBufferRenderer();
  69522. return renderer.getGBuffer().textures[0];
  69523. }
  69524. return this._scene.enableDepthRenderer().getDepthMap();
  69525. };
  69526. StandardRenderingPipeline.prototype._disposePostProcesses = function () {
  69527. for (var i = 0; i < this._cameras.length; i++) {
  69528. var camera = this._cameras[i];
  69529. if (this.originalPostProcess) {
  69530. this.originalPostProcess.dispose(camera);
  69531. }
  69532. if (this.downSampleX4PostProcess) {
  69533. this.downSampleX4PostProcess.dispose(camera);
  69534. }
  69535. if (this.brightPassPostProcess) {
  69536. this.brightPassPostProcess.dispose(camera);
  69537. }
  69538. if (this.textureAdderPostProcess) {
  69539. this.textureAdderPostProcess.dispose(camera);
  69540. }
  69541. if (this.textureAdderFinalPostProcess) {
  69542. this.textureAdderFinalPostProcess.dispose(camera);
  69543. }
  69544. if (this.volumetricLightPostProcess) {
  69545. this.volumetricLightPostProcess.dispose(camera);
  69546. }
  69547. if (this.volumetricLightSmoothXPostProcess) {
  69548. this.volumetricLightSmoothXPostProcess.dispose(camera);
  69549. }
  69550. if (this.volumetricLightSmoothYPostProcess) {
  69551. this.volumetricLightSmoothYPostProcess.dispose(camera);
  69552. }
  69553. if (this.volumetricLightMergePostProces) {
  69554. this.volumetricLightMergePostProces.dispose(camera);
  69555. }
  69556. if (this.volumetricLightFinalPostProcess) {
  69557. this.volumetricLightFinalPostProcess.dispose(camera);
  69558. }
  69559. if (this.lensFlarePostProcess) {
  69560. this.lensFlarePostProcess.dispose(camera);
  69561. }
  69562. if (this.lensFlareComposePostProcess) {
  69563. this.lensFlareComposePostProcess.dispose(camera);
  69564. }
  69565. for (var j = 0; j < this.luminanceDownSamplePostProcesses.length; j++) {
  69566. this.luminanceDownSamplePostProcesses[j].dispose(camera);
  69567. }
  69568. if (this.luminancePostProcess) {
  69569. this.luminancePostProcess.dispose(camera);
  69570. }
  69571. if (this.hdrPostProcess) {
  69572. this.hdrPostProcess.dispose(camera);
  69573. }
  69574. if (this.hdrFinalPostProcess) {
  69575. this.hdrFinalPostProcess.dispose(camera);
  69576. }
  69577. if (this.depthOfFieldPostProcess) {
  69578. this.depthOfFieldPostProcess.dispose(camera);
  69579. }
  69580. if (this.motionBlurPostProcess) {
  69581. this.motionBlurPostProcess.dispose(camera);
  69582. }
  69583. for (var j = 0; j < this.blurHPostProcesses.length; j++) {
  69584. this.blurHPostProcesses[j].dispose(camera);
  69585. }
  69586. for (var j = 0; j < this.blurVPostProcesses.length; j++) {
  69587. this.blurVPostProcesses[j].dispose(camera);
  69588. }
  69589. }
  69590. this.originalPostProcess = null;
  69591. this.downSampleX4PostProcess = null;
  69592. this.brightPassPostProcess = null;
  69593. this.textureAdderPostProcess = null;
  69594. this.textureAdderFinalPostProcess = null;
  69595. this.volumetricLightPostProcess = null;
  69596. this.volumetricLightSmoothXPostProcess = null;
  69597. this.volumetricLightSmoothYPostProcess = null;
  69598. this.volumetricLightMergePostProces = null;
  69599. this.volumetricLightFinalPostProcess = null;
  69600. this.lensFlarePostProcess = null;
  69601. this.lensFlareComposePostProcess = null;
  69602. this.luminancePostProcess = null;
  69603. this.hdrPostProcess = null;
  69604. this.hdrFinalPostProcess = null;
  69605. this.depthOfFieldPostProcess = null;
  69606. this.motionBlurPostProcess = null;
  69607. this.luminanceDownSamplePostProcesses = [];
  69608. this.blurHPostProcesses = [];
  69609. this.blurVPostProcesses = [];
  69610. };
  69611. // Dispose
  69612. StandardRenderingPipeline.prototype.dispose = function () {
  69613. this._disposePostProcesses();
  69614. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._cameras);
  69615. _super.prototype.dispose.call(this);
  69616. };
  69617. // Serialize rendering pipeline
  69618. StandardRenderingPipeline.prototype.serialize = function () {
  69619. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  69620. serializationObject.customType = "StandardRenderingPipeline";
  69621. return serializationObject;
  69622. };
  69623. /**
  69624. * Static members
  69625. */
  69626. // Parse serialized pipeline
  69627. StandardRenderingPipeline.Parse = function (source, scene, rootUrl) {
  69628. return BABYLON.SerializationHelper.Parse(function () { return new StandardRenderingPipeline(source._name, scene, source._ratio); }, source, scene, rootUrl);
  69629. };
  69630. // Luminance steps
  69631. StandardRenderingPipeline.LuminanceSteps = 6;
  69632. __decorate([
  69633. BABYLON.serialize()
  69634. ], StandardRenderingPipeline.prototype, "brightThreshold", void 0);
  69635. __decorate([
  69636. BABYLON.serialize()
  69637. ], StandardRenderingPipeline.prototype, "blurWidth", void 0);
  69638. __decorate([
  69639. BABYLON.serialize()
  69640. ], StandardRenderingPipeline.prototype, "horizontalBlur", void 0);
  69641. __decorate([
  69642. BABYLON.serialize()
  69643. ], StandardRenderingPipeline.prototype, "exposure", void 0);
  69644. __decorate([
  69645. BABYLON.serializeAsTexture("lensTexture")
  69646. ], StandardRenderingPipeline.prototype, "lensTexture", void 0);
  69647. __decorate([
  69648. BABYLON.serialize()
  69649. ], StandardRenderingPipeline.prototype, "volumetricLightCoefficient", void 0);
  69650. __decorate([
  69651. BABYLON.serialize()
  69652. ], StandardRenderingPipeline.prototype, "volumetricLightPower", void 0);
  69653. __decorate([
  69654. BABYLON.serialize()
  69655. ], StandardRenderingPipeline.prototype, "volumetricLightBlurScale", void 0);
  69656. __decorate([
  69657. BABYLON.serialize()
  69658. ], StandardRenderingPipeline.prototype, "hdrMinimumLuminance", void 0);
  69659. __decorate([
  69660. BABYLON.serialize()
  69661. ], StandardRenderingPipeline.prototype, "hdrDecreaseRate", void 0);
  69662. __decorate([
  69663. BABYLON.serialize()
  69664. ], StandardRenderingPipeline.prototype, "hdrIncreaseRate", void 0);
  69665. __decorate([
  69666. BABYLON.serializeAsTexture("lensColorTexture")
  69667. ], StandardRenderingPipeline.prototype, "lensColorTexture", void 0);
  69668. __decorate([
  69669. BABYLON.serialize()
  69670. ], StandardRenderingPipeline.prototype, "lensFlareStrength", void 0);
  69671. __decorate([
  69672. BABYLON.serialize()
  69673. ], StandardRenderingPipeline.prototype, "lensFlareGhostDispersal", void 0);
  69674. __decorate([
  69675. BABYLON.serialize()
  69676. ], StandardRenderingPipeline.prototype, "lensFlareHaloWidth", void 0);
  69677. __decorate([
  69678. BABYLON.serialize()
  69679. ], StandardRenderingPipeline.prototype, "lensFlareDistortionStrength", void 0);
  69680. __decorate([
  69681. BABYLON.serializeAsTexture("lensStarTexture")
  69682. ], StandardRenderingPipeline.prototype, "lensStarTexture", void 0);
  69683. __decorate([
  69684. BABYLON.serializeAsTexture("lensFlareDirtTexture")
  69685. ], StandardRenderingPipeline.prototype, "lensFlareDirtTexture", void 0);
  69686. __decorate([
  69687. BABYLON.serialize()
  69688. ], StandardRenderingPipeline.prototype, "depthOfFieldDistance", void 0);
  69689. __decorate([
  69690. BABYLON.serialize()
  69691. ], StandardRenderingPipeline.prototype, "depthOfFieldBlurWidth", void 0);
  69692. __decorate([
  69693. BABYLON.serialize()
  69694. ], StandardRenderingPipeline.prototype, "motionStrength", void 0);
  69695. __decorate([
  69696. BABYLON.serialize()
  69697. ], StandardRenderingPipeline.prototype, "_ratio", void 0);
  69698. __decorate([
  69699. BABYLON.serialize()
  69700. ], StandardRenderingPipeline.prototype, "BloomEnabled", null);
  69701. __decorate([
  69702. BABYLON.serialize()
  69703. ], StandardRenderingPipeline.prototype, "DepthOfFieldEnabled", null);
  69704. __decorate([
  69705. BABYLON.serialize()
  69706. ], StandardRenderingPipeline.prototype, "LensFlareEnabled", null);
  69707. __decorate([
  69708. BABYLON.serialize()
  69709. ], StandardRenderingPipeline.prototype, "HDREnabled", null);
  69710. __decorate([
  69711. BABYLON.serialize()
  69712. ], StandardRenderingPipeline.prototype, "VLSEnabled", null);
  69713. __decorate([
  69714. BABYLON.serialize()
  69715. ], StandardRenderingPipeline.prototype, "MotionBlurEnabled", null);
  69716. __decorate([
  69717. BABYLON.serialize()
  69718. ], StandardRenderingPipeline.prototype, "volumetricLightStepsCount", null);
  69719. __decorate([
  69720. BABYLON.serialize()
  69721. ], StandardRenderingPipeline.prototype, "motionBlurSamples", null);
  69722. return StandardRenderingPipeline;
  69723. }(BABYLON.PostProcessRenderPipeline));
  69724. BABYLON.StandardRenderingPipeline = StandardRenderingPipeline;
  69725. })(BABYLON || (BABYLON = {}));
  69726. //# sourceMappingURL=babylon.standardRenderingPipeline.js.map
  69727. "use strict";
  69728. var BABYLON;
  69729. (function (BABYLON) {
  69730. var FxaaPostProcess = /** @class */ (function (_super) {
  69731. __extends(FxaaPostProcess, _super);
  69732. function FxaaPostProcess(name, options, camera, samplingMode, engine, reusable, textureType) {
  69733. if (camera === void 0) { camera = null; }
  69734. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  69735. var _this = _super.call(this, name, "fxaa", ["texelSize"], null, options, camera, samplingMode || BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, reusable, null, textureType, "fxaa") || this;
  69736. _this.onApplyObservable.add(function (effect) {
  69737. var texelSize = _this.texelSize;
  69738. effect.setFloat2("texelSize", texelSize.x, texelSize.y);
  69739. });
  69740. return _this;
  69741. }
  69742. return FxaaPostProcess;
  69743. }(BABYLON.PostProcess));
  69744. BABYLON.FxaaPostProcess = FxaaPostProcess;
  69745. })(BABYLON || (BABYLON = {}));
  69746. //# sourceMappingURL=babylon.fxaaPostProcess.js.map
  69747. "use strict";
  69748. var BABYLON;
  69749. (function (BABYLON) {
  69750. /**
  69751. * The ChromaticAberrationPostProcess separates the rgb channels in an image to produce chromatic distortion around the edges of the screen
  69752. */
  69753. var ChromaticAberrationPostProcess = /** @class */ (function (_super) {
  69754. __extends(ChromaticAberrationPostProcess, _super);
  69755. /**
  69756. * Creates a new instance ChromaticAberrationPostProcess
  69757. * @param name The name of the effect.
  69758. * @param screenWidth The width of the screen to apply the effect on.
  69759. * @param screenHeight The height of the screen to apply the effect on.
  69760. * @param options The required width/height ratio to downsize to before computing the render pass.
  69761. * @param camera The camera to apply the render pass to.
  69762. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  69763. * @param engine The engine which the post process will be applied. (default: current engine)
  69764. * @param reusable If the post process can be reused on the same frame. (default: false)
  69765. * @param textureType Type of textures used when performing the post process. (default: 0)
  69766. * @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)
  69767. */
  69768. function ChromaticAberrationPostProcess(name, screenWidth, screenHeight, options, camera, samplingMode, engine, reusable, textureType, blockCompilation) {
  69769. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  69770. if (blockCompilation === void 0) { blockCompilation = false; }
  69771. 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;
  69772. /**
  69773. * The amount of seperation of rgb channels (default: 30)
  69774. */
  69775. _this.aberrationAmount = 30;
  69776. /**
  69777. * The amount the effect will increase for pixels closer to the edge of the screen. (default: 0)
  69778. */
  69779. _this.radialIntensity = 0;
  69780. /**
  69781. * 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))
  69782. */
  69783. _this.direction = new BABYLON.Vector2(0.707, 0.707);
  69784. /**
  69785. * 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))
  69786. */
  69787. _this.centerPosition = new BABYLON.Vector2(0.5, 0.5);
  69788. _this.onApplyObservable.add(function (effect) {
  69789. effect.setFloat('chromatic_aberration', _this.aberrationAmount);
  69790. effect.setFloat('screen_width', screenWidth);
  69791. effect.setFloat('screen_height', screenHeight);
  69792. effect.setFloat('radialIntensity', _this.radialIntensity);
  69793. effect.setFloat2('direction', _this.direction.x, _this.direction.y);
  69794. effect.setFloat2('centerPosition', _this.centerPosition.x, _this.centerPosition.y);
  69795. });
  69796. return _this;
  69797. }
  69798. return ChromaticAberrationPostProcess;
  69799. }(BABYLON.PostProcess));
  69800. BABYLON.ChromaticAberrationPostProcess = ChromaticAberrationPostProcess;
  69801. })(BABYLON || (BABYLON = {}));
  69802. //# sourceMappingURL=babylon.chromaticAberrationPostProcess.js.map
  69803. "use strict";
  69804. var BABYLON;
  69805. (function (BABYLON) {
  69806. /**
  69807. * The GrainPostProcess adds noise to the image at mid luminance levels
  69808. */
  69809. var GrainPostProcess = /** @class */ (function (_super) {
  69810. __extends(GrainPostProcess, _super);
  69811. /**
  69812. * Creates a new instance of @see GrainPostProcess
  69813. * @param name The name of the effect.
  69814. * @param options The required width/height ratio to downsize to before computing the render pass.
  69815. * @param camera The camera to apply the render pass to.
  69816. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  69817. * @param engine The engine which the post process will be applied. (default: current engine)
  69818. * @param reusable If the post process can be reused on the same frame. (default: false)
  69819. * @param textureType Type of textures used when performing the post process. (default: 0)
  69820. * @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)
  69821. */
  69822. function GrainPostProcess(name, options, camera, samplingMode, engine, reusable, textureType, blockCompilation) {
  69823. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  69824. if (blockCompilation === void 0) { blockCompilation = false; }
  69825. var _this = _super.call(this, name, "grain", ["intensity", "animatedSeed"], [], options, camera, samplingMode, engine, reusable, null, textureType, undefined, null, blockCompilation) || this;
  69826. /**
  69827. * The intensity of the grain added (default: 30)
  69828. */
  69829. _this.intensity = 30;
  69830. /**
  69831. * If the grain should be randomized on every frame
  69832. */
  69833. _this.animated = false;
  69834. _this.onApplyObservable.add(function (effect) {
  69835. effect.setFloat('intensity', _this.intensity);
  69836. effect.setFloat('animatedSeed', _this.animated ? Math.random() + 1 : 1);
  69837. });
  69838. return _this;
  69839. }
  69840. return GrainPostProcess;
  69841. }(BABYLON.PostProcess));
  69842. BABYLON.GrainPostProcess = GrainPostProcess;
  69843. })(BABYLON || (BABYLON = {}));
  69844. //# sourceMappingURL=babylon.grainPostProcess.js.map
  69845. "use strict";
  69846. var BABYLON;
  69847. (function (BABYLON) {
  69848. /**
  69849. * The SharpenPostProcess applies a sharpen kernel to every pixel
  69850. * See http://en.wikipedia.org/wiki/Kernel_(image_processing)
  69851. */
  69852. var SharpenPostProcess = /** @class */ (function (_super) {
  69853. __extends(SharpenPostProcess, _super);
  69854. /**
  69855. * Creates a new instance ConvolutionPostProcess
  69856. * @param name The name of the effect.
  69857. * @param options The required width/height ratio to downsize to before computing the render pass.
  69858. * @param camera The camera to apply the render pass to.
  69859. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  69860. * @param engine The engine which the post process will be applied. (default: current engine)
  69861. * @param reusable If the post process can be reused on the same frame. (default: false)
  69862. * @param textureType Type of textures used when performing the post process. (default: 0)
  69863. * @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)
  69864. */
  69865. function SharpenPostProcess(name, options, camera, samplingMode, engine, reusable, textureType, blockCompilation) {
  69866. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  69867. if (blockCompilation === void 0) { blockCompilation = false; }
  69868. var _this = _super.call(this, name, "sharpen", ["sharpnessAmounts", "screenSize"], null, options, camera, samplingMode, engine, reusable, null, textureType, undefined, null, blockCompilation) || this;
  69869. /**
  69870. * How much of the original color should be applied. Setting this to 0 will display edge detection. (default: 1)
  69871. */
  69872. _this.colorAmount = 1.0;
  69873. /**
  69874. * How much sharpness should be applied (default: 0.3)
  69875. */
  69876. _this.edgeAmount = 0.3;
  69877. _this.onApply = function (effect) {
  69878. effect.setFloat2("screenSize", _this.width, _this.height);
  69879. effect.setFloat2("sharpnessAmounts", _this.edgeAmount, _this.colorAmount);
  69880. };
  69881. return _this;
  69882. }
  69883. return SharpenPostProcess;
  69884. }(BABYLON.PostProcess));
  69885. BABYLON.SharpenPostProcess = SharpenPostProcess;
  69886. })(BABYLON || (BABYLON = {}));
  69887. //# sourceMappingURL=babylon.sharpenPostProcess.js.map
  69888. "use strict";
  69889. var BABYLON;
  69890. (function (BABYLON) {
  69891. /**
  69892. * The Blur Post Process which blurs an image based on a kernel and direction.
  69893. * Can be used twice in x and y directions to perform a guassian blur in two passes.
  69894. */
  69895. var BlurPostProcess = /** @class */ (function (_super) {
  69896. __extends(BlurPostProcess, _super);
  69897. /**
  69898. * Creates a new instance BlurPostProcess
  69899. * @param name The name of the effect.
  69900. * @param direction The direction in which to blur the image.
  69901. * @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.
  69902. * @param options The required width/height ratio to downsize to before computing the render pass. (Use 1.0 for full size)
  69903. * @param camera The camera to apply the render pass to.
  69904. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  69905. * @param engine The engine which the post process will be applied. (default: current engine)
  69906. * @param reusable If the post process can be reused on the same frame. (default: false)
  69907. * @param textureType Type of textures used when performing the post process. (default: 0)
  69908. * @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)
  69909. */
  69910. function BlurPostProcess(name, /** The direction in which to blur the image. */ direction, kernel, options, camera, samplingMode, engine, reusable, textureType, defines, blockCompilation) {
  69911. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  69912. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  69913. if (defines === void 0) { defines = ""; }
  69914. if (blockCompilation === void 0) { blockCompilation = false; }
  69915. 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;
  69916. _this.direction = direction;
  69917. _this.blockCompilation = blockCompilation;
  69918. _this._packedFloat = false;
  69919. _this._staticDefines = "";
  69920. _this._staticDefines = defines;
  69921. _this.onApplyObservable.add(function (effect) {
  69922. effect.setFloat2('delta', (1 / _this.width) * _this.direction.x, (1 / _this.height) * _this.direction.y);
  69923. });
  69924. _this.kernel = kernel;
  69925. return _this;
  69926. }
  69927. Object.defineProperty(BlurPostProcess.prototype, "kernel", {
  69928. /**
  69929. * Gets the length in pixels of the blur sample region
  69930. */
  69931. get: function () {
  69932. return this._idealKernel;
  69933. },
  69934. /**
  69935. * Sets the length in pixels of the blur sample region
  69936. */
  69937. set: function (v) {
  69938. if (this._idealKernel === v) {
  69939. return;
  69940. }
  69941. v = Math.max(v, 1);
  69942. this._idealKernel = v;
  69943. this._kernel = this._nearestBestKernel(v);
  69944. if (!this.blockCompilation) {
  69945. this._updateParameters();
  69946. }
  69947. },
  69948. enumerable: true,
  69949. configurable: true
  69950. });
  69951. Object.defineProperty(BlurPostProcess.prototype, "packedFloat", {
  69952. /**
  69953. * Gets wether or not the blur is unpacking/repacking floats
  69954. */
  69955. get: function () {
  69956. return this._packedFloat;
  69957. },
  69958. /**
  69959. * Sets wether or not the blur needs to unpack/repack floats
  69960. */
  69961. set: function (v) {
  69962. if (this._packedFloat === v) {
  69963. return;
  69964. }
  69965. this._packedFloat = v;
  69966. if (!this.blockCompilation) {
  69967. this._updateParameters();
  69968. }
  69969. },
  69970. enumerable: true,
  69971. configurable: true
  69972. });
  69973. /**
  69974. * Updates the effect with the current post process compile time values and recompiles the shader.
  69975. * @param defines Define statements that should be added at the beginning of the shader. (default: null)
  69976. * @param uniforms Set of uniform variables that will be passed to the shader. (default: null)
  69977. * @param samplers Set of Texture2D variables that will be passed to the shader. (default: null)
  69978. * @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
  69979. * @param onCompiled Called when the shader has been compiled.
  69980. * @param onError Called if there is an error when compiling a shader.
  69981. */
  69982. BlurPostProcess.prototype.updateEffect = function (defines, uniforms, samplers, indexParameters, onCompiled, onError) {
  69983. if (defines === void 0) { defines = null; }
  69984. if (uniforms === void 0) { uniforms = null; }
  69985. if (samplers === void 0) { samplers = null; }
  69986. this._updateParameters(onCompiled, onError);
  69987. };
  69988. BlurPostProcess.prototype._updateParameters = function (onCompiled, onError) {
  69989. // Generate sampling offsets and weights
  69990. var N = this._kernel;
  69991. var centerIndex = (N - 1) / 2;
  69992. // Generate Gaussian sampling weights over kernel
  69993. var offsets = [];
  69994. var weights = [];
  69995. var totalWeight = 0;
  69996. for (var i = 0; i < N; i++) {
  69997. var u = i / (N - 1);
  69998. var w = this._gaussianWeight(u * 2.0 - 1);
  69999. offsets[i] = (i - centerIndex);
  70000. weights[i] = w;
  70001. totalWeight += w;
  70002. }
  70003. // Normalize weights
  70004. for (var i = 0; i < weights.length; i++) {
  70005. weights[i] /= totalWeight;
  70006. }
  70007. // Optimize: combine samples to take advantage of hardware linear sampling
  70008. // Walk from left to center, combining pairs (symmetrically)
  70009. var linearSamplingWeights = [];
  70010. var linearSamplingOffsets = [];
  70011. var linearSamplingMap = [];
  70012. for (var i = 0; i <= centerIndex; i += 2) {
  70013. var j = Math.min(i + 1, Math.floor(centerIndex));
  70014. var singleCenterSample = i === j;
  70015. if (singleCenterSample) {
  70016. linearSamplingMap.push({ o: offsets[i], w: weights[i] });
  70017. }
  70018. else {
  70019. var sharedCell = j === centerIndex;
  70020. var weightLinear = (weights[i] + weights[j] * (sharedCell ? .5 : 1.));
  70021. var offsetLinear = offsets[i] + 1 / (1 + weights[i] / weights[j]);
  70022. if (offsetLinear === 0) {
  70023. linearSamplingMap.push({ o: offsets[i], w: weights[i] });
  70024. linearSamplingMap.push({ o: offsets[i + 1], w: weights[i + 1] });
  70025. }
  70026. else {
  70027. linearSamplingMap.push({ o: offsetLinear, w: weightLinear });
  70028. linearSamplingMap.push({ o: -offsetLinear, w: weightLinear });
  70029. }
  70030. }
  70031. }
  70032. for (var i = 0; i < linearSamplingMap.length; i++) {
  70033. linearSamplingOffsets[i] = linearSamplingMap[i].o;
  70034. linearSamplingWeights[i] = linearSamplingMap[i].w;
  70035. }
  70036. // Replace with optimized
  70037. offsets = linearSamplingOffsets;
  70038. weights = linearSamplingWeights;
  70039. // Generate shaders
  70040. var maxVaryingRows = this.getEngine().getCaps().maxVaryingVectors;
  70041. var freeVaryingVec2 = Math.max(maxVaryingRows, 0.) - 1; // Because of sampleCenter
  70042. var varyingCount = Math.min(offsets.length, freeVaryingVec2);
  70043. var defines = "";
  70044. defines += this._staticDefines;
  70045. for (var i = 0; i < varyingCount; i++) {
  70046. defines += "#define KERNEL_OFFSET" + i + " " + this._glslFloat(offsets[i]) + "\r\n";
  70047. defines += "#define KERNEL_WEIGHT" + i + " " + this._glslFloat(weights[i]) + "\r\n";
  70048. }
  70049. var depCount = 0;
  70050. for (var i = freeVaryingVec2; i < offsets.length; i++) {
  70051. defines += "#define KERNEL_DEP_OFFSET" + depCount + " " + this._glslFloat(offsets[i]) + "\r\n";
  70052. defines += "#define KERNEL_DEP_WEIGHT" + depCount + " " + this._glslFloat(weights[i]) + "\r\n";
  70053. depCount++;
  70054. }
  70055. if (this.packedFloat) {
  70056. defines += "#define PACKEDFLOAT 1";
  70057. }
  70058. this.blockCompilation = false;
  70059. _super.prototype.updateEffect.call(this, defines, null, null, {
  70060. varyingCount: varyingCount,
  70061. depCount: depCount
  70062. }, onCompiled, onError);
  70063. };
  70064. /**
  70065. * Best kernels are odd numbers that when divided by 2, their integer part is even, so 5, 9 or 13.
  70066. * Other odd kernels optimize correctly but require proportionally more samples, even kernels are
  70067. * possible but will produce minor visual artifacts. Since each new kernel requires a new shader we
  70068. * want to minimize kernel changes, having gaps between physical kernels is helpful in that regard.
  70069. * The gaps between physical kernels are compensated for in the weighting of the samples
  70070. * @param idealKernel Ideal blur kernel.
  70071. * @return Nearest best kernel.
  70072. */
  70073. BlurPostProcess.prototype._nearestBestKernel = function (idealKernel) {
  70074. var v = Math.round(idealKernel);
  70075. for (var _i = 0, _a = [v, v - 1, v + 1, v - 2, v + 2]; _i < _a.length; _i++) {
  70076. var k = _a[_i];
  70077. if (((k % 2) !== 0) && ((Math.floor(k / 2) % 2) === 0) && k > 0) {
  70078. return Math.max(k, 3);
  70079. }
  70080. }
  70081. return Math.max(v, 3);
  70082. };
  70083. /**
  70084. * Calculates the value of a Gaussian distribution with sigma 3 at a given point.
  70085. * @param x The point on the Gaussian distribution to sample.
  70086. * @return the value of the Gaussian function at x.
  70087. */
  70088. BlurPostProcess.prototype._gaussianWeight = function (x) {
  70089. //reference: Engine/ImageProcessingBlur.cpp #dcc760
  70090. // We are evaluating the Gaussian (normal) distribution over a kernel parameter space of [-1,1],
  70091. // so we truncate at three standard deviations by setting stddev (sigma) to 1/3.
  70092. // The choice of 3-sigma truncation is common but arbitrary, and means that the signal is
  70093. // truncated at around 1.3% of peak strength.
  70094. //the distribution is scaled to account for the difference between the actual kernel size and the requested kernel size
  70095. var sigma = (1 / 3);
  70096. var denominator = Math.sqrt(2.0 * Math.PI) * sigma;
  70097. var exponent = -((x * x) / (2.0 * sigma * sigma));
  70098. var weight = (1.0 / denominator) * Math.exp(exponent);
  70099. return weight;
  70100. };
  70101. /**
  70102. * Generates a string that can be used as a floating point number in GLSL.
  70103. * @param x Value to print.
  70104. * @param decimalFigures Number of decimal places to print the number to (excluding trailing 0s).
  70105. * @return GLSL float string.
  70106. */
  70107. BlurPostProcess.prototype._glslFloat = function (x, decimalFigures) {
  70108. if (decimalFigures === void 0) { decimalFigures = 8; }
  70109. return x.toFixed(decimalFigures).replace(/0+$/, '');
  70110. };
  70111. return BlurPostProcess;
  70112. }(BABYLON.PostProcess));
  70113. BABYLON.BlurPostProcess = BlurPostProcess;
  70114. })(BABYLON || (BABYLON = {}));
  70115. //# sourceMappingURL=babylon.blurPostProcess.js.map
  70116. "use strict";
  70117. var BABYLON;
  70118. (function (BABYLON) {
  70119. /**
  70120. * The DepthOfFieldBlurPostProcess applied a blur in a give direction.
  70121. * This blur differs from the standard BlurPostProcess as it attempts to avoid blurring pixels
  70122. * based on samples that have a large difference in distance than the center pixel.
  70123. * See section 2.6.2 http://fileadmin.cs.lth.se/cs/education/edan35/lectures/12dof.pdf
  70124. */
  70125. var DepthOfFieldBlurPostProcess = /** @class */ (function (_super) {
  70126. __extends(DepthOfFieldBlurPostProcess, _super);
  70127. /**
  70128. * Creates a new instance CircleOfConfusionPostProcess
  70129. * @param name The name of the effect.
  70130. * @param scene The scene the effect belongs to.
  70131. * @param direction The direction the blur should be applied.
  70132. * @param kernel The size of the kernel used to blur.
  70133. * @param options The required width/height ratio to downsize to before computing the render pass.
  70134. * @param camera The camera to apply the render pass to.
  70135. * @param circleOfConfusion The circle of confusion + depth map to be used to avoid blurring accross edges
  70136. * @param imageToBlur The image to apply the blur to (default: Current rendered frame)
  70137. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  70138. * @param engine The engine which the post process will be applied. (default: current engine)
  70139. * @param reusable If the post process can be reused on the same frame. (default: false)
  70140. * @param textureType Type of textures used when performing the post process. (default: 0)
  70141. * @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)
  70142. */
  70143. function DepthOfFieldBlurPostProcess(name, scene, direction, kernel, options, camera, circleOfConfusion, imageToBlur, samplingMode, engine, reusable, textureType, blockCompilation) {
  70144. if (imageToBlur === void 0) { imageToBlur = null; }
  70145. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  70146. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  70147. if (blockCompilation === void 0) { blockCompilation = false; }
  70148. 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;
  70149. _this.direction = direction;
  70150. _this.onApplyObservable.add(function (effect) {
  70151. if (imageToBlur != null) {
  70152. effect.setTextureFromPostProcess("textureSampler", imageToBlur);
  70153. }
  70154. effect.setTextureFromPostProcessOutput("circleOfConfusionSampler", circleOfConfusion);
  70155. if (scene.activeCamera) {
  70156. effect.setFloat2('cameraMinMaxZ', scene.activeCamera.minZ, scene.activeCamera.maxZ);
  70157. }
  70158. });
  70159. return _this;
  70160. }
  70161. return DepthOfFieldBlurPostProcess;
  70162. }(BABYLON.BlurPostProcess));
  70163. BABYLON.DepthOfFieldBlurPostProcess = DepthOfFieldBlurPostProcess;
  70164. })(BABYLON || (BABYLON = {}));
  70165. //# sourceMappingURL=babylon.depthOfFieldBlurPostProcess.js.map
  70166. "use strict";
  70167. var BABYLON;
  70168. (function (BABYLON) {
  70169. /**
  70170. * Options to be set when merging outputs from the default pipeline.
  70171. */
  70172. var DepthOfFieldMergePostProcessOptions = /** @class */ (function () {
  70173. function DepthOfFieldMergePostProcessOptions() {
  70174. }
  70175. return DepthOfFieldMergePostProcessOptions;
  70176. }());
  70177. BABYLON.DepthOfFieldMergePostProcessOptions = DepthOfFieldMergePostProcessOptions;
  70178. /**
  70179. * The DepthOfFieldMergePostProcess merges blurred images with the original based on the values of the circle of confusion.
  70180. */
  70181. var DepthOfFieldMergePostProcess = /** @class */ (function (_super) {
  70182. __extends(DepthOfFieldMergePostProcess, _super);
  70183. /**
  70184. * Creates a new instance of DepthOfFieldMergePostProcess
  70185. * @param name The name of the effect.
  70186. * @param originalFromInput Post process which's input will be used for the merge.
  70187. * @param circleOfConfusion Circle of confusion post process which's output will be used to blur each pixel.
  70188. * @param blurSteps Blur post processes from low to high which will be mixed with the original image.
  70189. * @param options The required width/height ratio to downsize to before computing the render pass.
  70190. * @param camera The camera to apply the render pass to.
  70191. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  70192. * @param engine The engine which the post process will be applied. (default: current engine)
  70193. * @param reusable If the post process can be reused on the same frame. (default: false)
  70194. * @param textureType Type of textures used when performing the post process. (default: 0)
  70195. * @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)
  70196. */
  70197. function DepthOfFieldMergePostProcess(name, originalFromInput, circleOfConfusion, blurSteps, options, camera, samplingMode, engine, reusable, textureType, blockCompilation) {
  70198. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  70199. if (blockCompilation === void 0) { blockCompilation = false; }
  70200. var _this = _super.call(this, name, "depthOfFieldMerge", ["bloomWeight"], ["circleOfConfusionSampler", "blurStep0", "blurStep1", "blurStep2", "bloomBlur"], options, camera, samplingMode, engine, reusable, null, textureType, undefined, null, true) || this;
  70201. _this.blurSteps = blurSteps;
  70202. _this.onApplyObservable.add(function (effect) {
  70203. effect.setTextureFromPostProcess("textureSampler", originalFromInput);
  70204. effect.setTextureFromPostProcessOutput("circleOfConfusionSampler", circleOfConfusion);
  70205. blurSteps.forEach(function (step, index) {
  70206. effect.setTextureFromPostProcessOutput("blurStep" + (blurSteps.length - index - 1), step);
  70207. });
  70208. });
  70209. if (!blockCompilation) {
  70210. _this.updateEffect();
  70211. }
  70212. return _this;
  70213. }
  70214. /**
  70215. * Updates the effect with the current post process compile time values and recompiles the shader.
  70216. * @param defines Define statements that should be added at the beginning of the shader. (default: null)
  70217. * @param uniforms Set of uniform variables that will be passed to the shader. (default: null)
  70218. * @param samplers Set of Texture2D variables that will be passed to the shader. (default: null)
  70219. * @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
  70220. * @param onCompiled Called when the shader has been compiled.
  70221. * @param onError Called if there is an error when compiling a shader.
  70222. */
  70223. DepthOfFieldMergePostProcess.prototype.updateEffect = function (defines, uniforms, samplers, indexParameters, onCompiled, onError) {
  70224. if (defines === void 0) { defines = null; }
  70225. if (uniforms === void 0) { uniforms = null; }
  70226. if (samplers === void 0) { samplers = null; }
  70227. if (!defines) {
  70228. defines = "";
  70229. defines += "#define BLUR_LEVEL " + (this.blurSteps.length - 1) + "\n";
  70230. }
  70231. _super.prototype.updateEffect.call(this, defines, uniforms, samplers, indexParameters, onCompiled, onError);
  70232. };
  70233. return DepthOfFieldMergePostProcess;
  70234. }(BABYLON.PostProcess));
  70235. BABYLON.DepthOfFieldMergePostProcess = DepthOfFieldMergePostProcess;
  70236. })(BABYLON || (BABYLON = {}));
  70237. //# sourceMappingURL=babylon.depthOfFieldMergePostProcess.js.map
  70238. "use strict";
  70239. var BABYLON;
  70240. (function (BABYLON) {
  70241. /**
  70242. * The CircleOfConfusionPostProcess computes the circle of confusion value for each pixel given required lens parameters. See https://en.wikipedia.org/wiki/Circle_of_confusion
  70243. */
  70244. var CircleOfConfusionPostProcess = /** @class */ (function (_super) {
  70245. __extends(CircleOfConfusionPostProcess, _super);
  70246. /**
  70247. * Creates a new instance CircleOfConfusionPostProcess
  70248. * @param name The name of the effect.
  70249. * @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.
  70250. * @param options The required width/height ratio to downsize to before computing the render pass.
  70251. * @param camera The camera to apply the render pass to.
  70252. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  70253. * @param engine The engine which the post process will be applied. (default: current engine)
  70254. * @param reusable If the post process can be reused on the same frame. (default: false)
  70255. * @param textureType Type of textures used when performing the post process. (default: 0)
  70256. * @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)
  70257. */
  70258. function CircleOfConfusionPostProcess(name, depthTexture, options, camera, samplingMode, engine, reusable, textureType, blockCompilation) {
  70259. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  70260. if (blockCompilation === void 0) { blockCompilation = false; }
  70261. var _this = _super.call(this, name, "circleOfConfusion", ["cameraMinMaxZ", "focusDistance", "cocPrecalculation"], ["depthSampler"], options, camera, samplingMode, engine, reusable, null, textureType, undefined, null, blockCompilation) || this;
  70262. /**
  70263. * 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.
  70264. */
  70265. _this.lensSize = 50;
  70266. /**
  70267. * F-Stop of the effect's camera. The diamater of the resulting aperture can be computed by lensSize/fStop. (default: 1.4)
  70268. */
  70269. _this.fStop = 1.4;
  70270. /**
  70271. * Distance away from the camera to focus on in scene units/1000 (eg. millimeter). (default: 2000)
  70272. */
  70273. _this.focusDistance = 2000;
  70274. /**
  70275. * Focal length of the effect's camera in scene units/1000 (eg. millimeter). (default: 50)
  70276. */
  70277. _this.focalLength = 50;
  70278. _this._depthTexture = null;
  70279. _this._depthTexture = depthTexture;
  70280. _this.onApplyObservable.add(function (effect) {
  70281. if (!_this._depthTexture) {
  70282. BABYLON.Tools.Warn("No depth texture set on CircleOfConfusionPostProcess");
  70283. return;
  70284. }
  70285. effect.setTexture("depthSampler", _this._depthTexture);
  70286. // Circle of confusion calculation, See https://developer.nvidia.com/gpugems/GPUGems/gpugems_ch23.html
  70287. var aperture = _this.lensSize / _this.fStop;
  70288. var cocPrecalculation = ((aperture * _this.focalLength) / ((_this.focusDistance - _this.focalLength))); // * ((this.focusDistance - pixelDistance)/pixelDistance) [This part is done in shader]
  70289. effect.setFloat('focusDistance', _this.focusDistance);
  70290. effect.setFloat('cocPrecalculation', cocPrecalculation);
  70291. effect.setFloat2('cameraMinMaxZ', _this._depthTexture.activeCamera.minZ, _this._depthTexture.activeCamera.maxZ);
  70292. });
  70293. return _this;
  70294. }
  70295. Object.defineProperty(CircleOfConfusionPostProcess.prototype, "depthTexture", {
  70296. /**
  70297. * 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.
  70298. */
  70299. set: function (value) {
  70300. this._depthTexture = value;
  70301. },
  70302. enumerable: true,
  70303. configurable: true
  70304. });
  70305. return CircleOfConfusionPostProcess;
  70306. }(BABYLON.PostProcess));
  70307. BABYLON.CircleOfConfusionPostProcess = CircleOfConfusionPostProcess;
  70308. })(BABYLON || (BABYLON = {}));
  70309. //# sourceMappingURL=babylon.circleOfConfusionPostProcess.js.map
  70310. "use strict";
  70311. var BABYLON;
  70312. (function (BABYLON) {
  70313. /**
  70314. * Specifies the level of max blur that should be applied when using the depth of field effect
  70315. */
  70316. var DepthOfFieldEffectBlurLevel;
  70317. (function (DepthOfFieldEffectBlurLevel) {
  70318. /**
  70319. * Subtle blur
  70320. */
  70321. DepthOfFieldEffectBlurLevel[DepthOfFieldEffectBlurLevel["Low"] = 0] = "Low";
  70322. /**
  70323. * Medium blur
  70324. */
  70325. DepthOfFieldEffectBlurLevel[DepthOfFieldEffectBlurLevel["Medium"] = 1] = "Medium";
  70326. /**
  70327. * Large blur
  70328. */
  70329. DepthOfFieldEffectBlurLevel[DepthOfFieldEffectBlurLevel["High"] = 2] = "High";
  70330. })(DepthOfFieldEffectBlurLevel = BABYLON.DepthOfFieldEffectBlurLevel || (BABYLON.DepthOfFieldEffectBlurLevel = {}));
  70331. ;
  70332. /**
  70333. * The depth of field effect applies a blur to objects that are closer or further from where the camera is focusing.
  70334. */
  70335. var DepthOfFieldEffect = /** @class */ (function (_super) {
  70336. __extends(DepthOfFieldEffect, _super);
  70337. /**
  70338. * Creates a new instance DepthOfFieldEffect
  70339. * @param scene The scene the effect belongs to.
  70340. * @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.
  70341. * @param pipelineTextureType The type of texture to be used when performing the post processing.
  70342. * @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)
  70343. */
  70344. function DepthOfFieldEffect(scene, depthTexture, blurLevel, pipelineTextureType, blockCompilation) {
  70345. if (blurLevel === void 0) { blurLevel = DepthOfFieldEffectBlurLevel.Low; }
  70346. if (pipelineTextureType === void 0) { pipelineTextureType = 0; }
  70347. if (blockCompilation === void 0) { blockCompilation = false; }
  70348. var _this = _super.call(this, scene.getEngine(), "depth of field", function () {
  70349. return _this._effects;
  70350. }, true) || this;
  70351. /**
  70352. * Internal post processes in depth of field effect
  70353. */
  70354. _this._effects = [];
  70355. // Circle of confusion value for each pixel is used to determine how much to blur that pixel
  70356. _this._circleOfConfusion = new BABYLON.CircleOfConfusionPostProcess("circleOfConfusion", depthTexture, 1, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, pipelineTextureType, blockCompilation);
  70357. // 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)
  70358. // Blur the image but do not blur on sharp far to near distance changes to avoid bleeding artifacts
  70359. // See section 2.6.2 http://fileadmin.cs.lth.se/cs/education/edan35/lectures/12dof.pdf
  70360. _this._depthOfFieldBlurY = [];
  70361. _this._depthOfFieldBlurX = [];
  70362. var blurCount = 1;
  70363. var kernelSize = 15;
  70364. switch (blurLevel) {
  70365. case DepthOfFieldEffectBlurLevel.High: {
  70366. blurCount = 3;
  70367. kernelSize = 51;
  70368. break;
  70369. }
  70370. case DepthOfFieldEffectBlurLevel.Medium: {
  70371. blurCount = 2;
  70372. kernelSize = 31;
  70373. break;
  70374. }
  70375. default: {
  70376. kernelSize = 15;
  70377. blurCount = 1;
  70378. break;
  70379. }
  70380. }
  70381. var adjustedKernelSize = kernelSize / Math.pow(2, blurCount - 1);
  70382. for (var i = 0; i < blurCount; i++) {
  70383. var blurY = new BABYLON.DepthOfFieldBlurPostProcess("verticle blur", scene, new BABYLON.Vector2(0, 1.0), adjustedKernelSize, 1.0 / Math.pow(2, i), null, _this._circleOfConfusion, i == 0 ? _this._circleOfConfusion : null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, pipelineTextureType, blockCompilation);
  70384. blurY.autoClear = false;
  70385. var blurX = new BABYLON.DepthOfFieldBlurPostProcess("horizontal blur", scene, new BABYLON.Vector2(1.0, 0), adjustedKernelSize, 1.0 / Math.pow(2, i), null, _this._circleOfConfusion, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, pipelineTextureType, blockCompilation);
  70386. blurX.autoClear = false;
  70387. _this._depthOfFieldBlurY.push(blurY);
  70388. _this._depthOfFieldBlurX.push(blurX);
  70389. }
  70390. // Set all post processes on the effect.
  70391. _this._effects = [_this._circleOfConfusion];
  70392. for (var i = 0; i < _this._depthOfFieldBlurX.length; i++) {
  70393. _this._effects.push(_this._depthOfFieldBlurY[i]);
  70394. _this._effects.push(_this._depthOfFieldBlurX[i]);
  70395. }
  70396. // Merge blurred images with original image based on circleOfConfusion
  70397. _this._dofMerge = new BABYLON.DepthOfFieldMergePostProcess("dofMerge", _this._circleOfConfusion, _this._circleOfConfusion, _this._depthOfFieldBlurX, 1, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, pipelineTextureType, blockCompilation);
  70398. _this._dofMerge.autoClear = false;
  70399. _this._effects.push(_this._dofMerge);
  70400. return _this;
  70401. }
  70402. Object.defineProperty(DepthOfFieldEffect.prototype, "focalLength", {
  70403. get: function () {
  70404. return this._circleOfConfusion.focalLength;
  70405. },
  70406. /**
  70407. * The focal the length of the camera used in the effect
  70408. */
  70409. set: function (value) {
  70410. this._circleOfConfusion.focalLength = value;
  70411. },
  70412. enumerable: true,
  70413. configurable: true
  70414. });
  70415. Object.defineProperty(DepthOfFieldEffect.prototype, "fStop", {
  70416. get: function () {
  70417. return this._circleOfConfusion.fStop;
  70418. },
  70419. /**
  70420. * F-Stop of the effect's camera. The diamater of the resulting aperture can be computed by lensSize/fStop. (default: 1.4)
  70421. */
  70422. set: function (value) {
  70423. this._circleOfConfusion.fStop = value;
  70424. },
  70425. enumerable: true,
  70426. configurable: true
  70427. });
  70428. Object.defineProperty(DepthOfFieldEffect.prototype, "focusDistance", {
  70429. get: function () {
  70430. return this._circleOfConfusion.focusDistance;
  70431. },
  70432. /**
  70433. * Distance away from the camera to focus on in scene units/1000 (eg. millimeter). (default: 2000)
  70434. */
  70435. set: function (value) {
  70436. this._circleOfConfusion.focusDistance = value;
  70437. },
  70438. enumerable: true,
  70439. configurable: true
  70440. });
  70441. Object.defineProperty(DepthOfFieldEffect.prototype, "lensSize", {
  70442. get: function () {
  70443. return this._circleOfConfusion.lensSize;
  70444. },
  70445. /**
  70446. * 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.
  70447. */
  70448. set: function (value) {
  70449. this._circleOfConfusion.lensSize = value;
  70450. },
  70451. enumerable: true,
  70452. configurable: true
  70453. });
  70454. Object.defineProperty(DepthOfFieldEffect.prototype, "depthTexture", {
  70455. /**
  70456. * 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.
  70457. */
  70458. set: function (value) {
  70459. this._circleOfConfusion.depthTexture = value;
  70460. },
  70461. enumerable: true,
  70462. configurable: true
  70463. });
  70464. /**
  70465. * Disposes each of the internal effects for a given camera.
  70466. * @param camera The camera to dispose the effect on.
  70467. */
  70468. DepthOfFieldEffect.prototype.disposeEffects = function (camera) {
  70469. for (var effect in this._effects) {
  70470. this._effects[effect].dispose(camera);
  70471. }
  70472. };
  70473. /**
  70474. * Internal
  70475. */
  70476. DepthOfFieldEffect.prototype._updateEffects = function () {
  70477. for (var effect in this._effects) {
  70478. this._effects[effect].updateEffect();
  70479. }
  70480. };
  70481. /**
  70482. * Internal
  70483. * @returns if all the contained post processes are ready.
  70484. */
  70485. DepthOfFieldEffect.prototype._isReady = function () {
  70486. for (var effect in this._effects) {
  70487. if (!this._effects[effect].isReady()) {
  70488. return false;
  70489. }
  70490. }
  70491. return true;
  70492. };
  70493. return DepthOfFieldEffect;
  70494. }(BABYLON.PostProcessRenderEffect));
  70495. BABYLON.DepthOfFieldEffect = DepthOfFieldEffect;
  70496. })(BABYLON || (BABYLON = {}));
  70497. //# sourceMappingURL=babylon.depthOfFieldEffect.js.map
  70498. "use strict";
  70499. var BABYLON;
  70500. (function (BABYLON) {
  70501. /**
  70502. * The BloomMergePostProcess merges blurred images with the original based on the values of the circle of confusion.
  70503. */
  70504. var BloomMergePostProcess = /** @class */ (function (_super) {
  70505. __extends(BloomMergePostProcess, _super);
  70506. /**
  70507. * Creates a new instance of @see BloomMergePostProcess
  70508. * @param name The name of the effect.
  70509. * @param originalFromInput Post process which's input will be used for the merge.
  70510. * @param blurred Blurred highlights post process which's output will be used.
  70511. * @param weight Weight of the bloom to be added to the original input.
  70512. * @param options The required width/height ratio to downsize to before computing the render pass.
  70513. * @param camera The camera to apply the render pass to.
  70514. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  70515. * @param engine The engine which the post process will be applied. (default: current engine)
  70516. * @param reusable If the post process can be reused on the same frame. (default: false)
  70517. * @param textureType Type of textures used when performing the post process. (default: 0)
  70518. * @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)
  70519. */
  70520. function BloomMergePostProcess(name, originalFromInput, blurred, /** Weight of the bloom to be added to the original input. */ weight, options, camera, samplingMode, engine, reusable, textureType, blockCompilation) {
  70521. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  70522. if (blockCompilation === void 0) { blockCompilation = false; }
  70523. var _this = _super.call(this, name, "bloomMerge", ["bloomWeight"], ["circleOfConfusionSampler", "blurStep0", "blurStep1", "blurStep2", "bloomBlur"], options, camera, samplingMode, engine, reusable, null, textureType, undefined, null, true) || this;
  70524. _this.weight = weight;
  70525. _this.onApplyObservable.add(function (effect) {
  70526. effect.setTextureFromPostProcess("textureSampler", originalFromInput);
  70527. effect.setTextureFromPostProcessOutput("bloomBlur", blurred);
  70528. effect.setFloat("bloomWeight", _this.weight);
  70529. });
  70530. if (!blockCompilation) {
  70531. _this.updateEffect();
  70532. }
  70533. return _this;
  70534. }
  70535. return BloomMergePostProcess;
  70536. }(BABYLON.PostProcess));
  70537. BABYLON.BloomMergePostProcess = BloomMergePostProcess;
  70538. })(BABYLON || (BABYLON = {}));
  70539. //# sourceMappingURL=babylon.bloomMergePostProcess.js.map
  70540. "use strict";
  70541. var BABYLON;
  70542. (function (BABYLON) {
  70543. /**
  70544. * 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.
  70545. */
  70546. var ExtractHighlightsPostProcess = /** @class */ (function (_super) {
  70547. __extends(ExtractHighlightsPostProcess, _super);
  70548. function ExtractHighlightsPostProcess(name, options, camera, samplingMode, engine, reusable, textureType, blockCompilation) {
  70549. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  70550. if (blockCompilation === void 0) { blockCompilation = false; }
  70551. var _this = _super.call(this, name, "extractHighlights", ["threshold", "exposure"], null, options, camera, samplingMode, engine, reusable, null, textureType, undefined, null, blockCompilation) || this;
  70552. /**
  70553. * The luminance threshold, pixels below this value will be set to black.
  70554. */
  70555. _this.threshold = 0.9;
  70556. /**
  70557. * Internal
  70558. */
  70559. _this._exposure = 1;
  70560. /**
  70561. * Post process which has the input texture to be used when performing highlight extraction
  70562. */
  70563. _this._inputPostProcess = null;
  70564. _this.onApplyObservable.add(function (effect) {
  70565. if (_this._inputPostProcess) {
  70566. effect.setTextureFromPostProcess("textureSampler", _this._inputPostProcess);
  70567. }
  70568. effect.setFloat('threshold', Math.pow(_this.threshold, BABYLON.ToGammaSpace));
  70569. effect.setFloat('exposure', _this._exposure);
  70570. });
  70571. return _this;
  70572. }
  70573. return ExtractHighlightsPostProcess;
  70574. }(BABYLON.PostProcess));
  70575. BABYLON.ExtractHighlightsPostProcess = ExtractHighlightsPostProcess;
  70576. })(BABYLON || (BABYLON = {}));
  70577. //# sourceMappingURL=babylon.extractHighlightsPostProcess.js.map
  70578. "use strict";
  70579. var BABYLON;
  70580. (function (BABYLON) {
  70581. /**
  70582. * The bloom effect spreads bright areas of an image to simulate artifacts seen in cameras
  70583. */
  70584. var BloomEffect = /** @class */ (function (_super) {
  70585. __extends(BloomEffect, _super);
  70586. /**
  70587. * Creates a new instance of @see BloomEffect
  70588. * @param scene The scene the effect belongs to.
  70589. * @param bloomScale The ratio of the blur texture to the input texture that should be used to compute the bloom.
  70590. * @param bloomKernel The size of the kernel to be used when applying the blur.
  70591. * @param bloomWeight The the strength of bloom.
  70592. * @param pipelineTextureType The type of texture to be used when performing the post processing.
  70593. * @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)
  70594. */
  70595. function BloomEffect(scene, bloomScale, bloomWeight, bloomKernel, pipelineTextureType, blockCompilation) {
  70596. if (pipelineTextureType === void 0) { pipelineTextureType = 0; }
  70597. if (blockCompilation === void 0) { blockCompilation = false; }
  70598. var _this = _super.call(this, scene.getEngine(), "bloom", function () {
  70599. return _this._effects;
  70600. }, true) || this;
  70601. _this.bloomScale = bloomScale;
  70602. /**
  70603. * Internal
  70604. */
  70605. _this._effects = [];
  70606. _this._downscale = new BABYLON.ExtractHighlightsPostProcess("highlights", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, pipelineTextureType, blockCompilation);
  70607. _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);
  70608. _this._blurX.alwaysForcePOT = true;
  70609. _this._blurX.autoClear = false;
  70610. _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);
  70611. _this._blurY.alwaysForcePOT = true;
  70612. _this._blurY.autoClear = false;
  70613. _this.kernel = bloomKernel;
  70614. _this._upscale = new BABYLON.PassPostProcess("upscale", bloomScale, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, pipelineTextureType, blockCompilation);
  70615. _this._upscale.autoClear = false;
  70616. _this._effects = [_this._downscale, _this._blurX, _this._blurY, _this._upscale];
  70617. _this._merge = new BABYLON.BloomMergePostProcess("bloomMerge", _this._downscale, _this._blurY, bloomWeight, 1, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, pipelineTextureType, blockCompilation);
  70618. _this._merge.autoClear = false;
  70619. _this._effects.push(_this._merge);
  70620. return _this;
  70621. }
  70622. Object.defineProperty(BloomEffect.prototype, "threshold", {
  70623. /**
  70624. * The luminance threshold to find bright areas of the image to bloom.
  70625. */
  70626. get: function () {
  70627. return this._downscale.threshold;
  70628. },
  70629. set: function (value) {
  70630. this._downscale.threshold = value;
  70631. },
  70632. enumerable: true,
  70633. configurable: true
  70634. });
  70635. Object.defineProperty(BloomEffect.prototype, "weight", {
  70636. /**
  70637. * The strength of the bloom.
  70638. */
  70639. get: function () {
  70640. return this._merge.weight;
  70641. },
  70642. set: function (value) {
  70643. this._merge.weight = value;
  70644. },
  70645. enumerable: true,
  70646. configurable: true
  70647. });
  70648. Object.defineProperty(BloomEffect.prototype, "kernel", {
  70649. /**
  70650. * Specifies the size of the bloom blur kernel, relative to the final output size
  70651. */
  70652. get: function () {
  70653. return this._blurX.kernel / this.bloomScale;
  70654. },
  70655. set: function (value) {
  70656. this._blurX.kernel = value * this.bloomScale;
  70657. this._blurY.kernel = value * this.bloomScale;
  70658. },
  70659. enumerable: true,
  70660. configurable: true
  70661. });
  70662. /**
  70663. * Disposes each of the internal effects for a given camera.
  70664. * @param camera The camera to dispose the effect on.
  70665. */
  70666. BloomEffect.prototype.disposeEffects = function (camera) {
  70667. for (var effect in this._effects) {
  70668. this._effects[effect].dispose(camera);
  70669. }
  70670. };
  70671. /**
  70672. * Internal
  70673. */
  70674. BloomEffect.prototype._updateEffects = function () {
  70675. for (var effect in this._effects) {
  70676. this._effects[effect].updateEffect();
  70677. }
  70678. };
  70679. /**
  70680. * Internal
  70681. * @returns if all the contained post processes are ready.
  70682. */
  70683. BloomEffect.prototype._isReady = function () {
  70684. for (var effect in this._effects) {
  70685. if (!this._effects[effect].isReady()) {
  70686. return false;
  70687. }
  70688. }
  70689. return true;
  70690. };
  70691. return BloomEffect;
  70692. }(BABYLON.PostProcessRenderEffect));
  70693. BABYLON.BloomEffect = BloomEffect;
  70694. })(BABYLON || (BABYLON = {}));
  70695. //# sourceMappingURL=babylon.bloomEffect.js.map
  70696. "use strict";
  70697. var BABYLON;
  70698. (function (BABYLON) {
  70699. /**
  70700. * The default rendering pipeline can be added to a scene to apply common post processing effects such as anti-aliasing or depth of field.
  70701. * See https://doc.babylonjs.com/how_to/using_default_rendering_pipeline
  70702. */
  70703. var DefaultRenderingPipeline = /** @class */ (function (_super) {
  70704. __extends(DefaultRenderingPipeline, _super);
  70705. /**
  70706. * @constructor
  70707. * @param {string} name - The rendering pipeline name
  70708. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  70709. * @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)
  70710. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  70711. * @param {boolean} automaticBuild - if false, you will have to manually call prepare() to update the pipeline
  70712. */
  70713. function DefaultRenderingPipeline(name, hdr, scene, cameras, automaticBuild) {
  70714. if (automaticBuild === void 0) { automaticBuild = true; }
  70715. var _this = _super.call(this, scene.getEngine(), name) || this;
  70716. _this._originalCameras = [];
  70717. /**
  70718. * ID of the sharpen post process,
  70719. */
  70720. _this.SharpenPostProcessId = "SharpenPostProcessEffect";
  70721. /**
  70722. * ID of the image processing post process;
  70723. */
  70724. _this.ImageProcessingPostProcessId = "ImageProcessingPostProcessEffect";
  70725. /**
  70726. * ID of the Fast Approximate Anti-Aliasing post process;
  70727. */
  70728. _this.FxaaPostProcessId = "FxaaPostProcessEffect";
  70729. /**
  70730. * ID of the chromatic aberration post process,
  70731. */
  70732. _this.ChromaticAberrationPostProcessId = "ChromaticAberrationPostProcessEffect";
  70733. /**
  70734. * ID of the grain post process
  70735. */
  70736. _this.GrainPostProcessId = "GrainPostProcessEffect";
  70737. /**
  70738. * Animations which can be used to tweak settings over a period of time
  70739. */
  70740. _this.animations = [];
  70741. _this._imageProcessingConfigurationObserver = null;
  70742. // Values
  70743. _this._sharpenEnabled = false;
  70744. _this._bloomEnabled = false;
  70745. _this._depthOfFieldEnabled = false;
  70746. _this._depthOfFieldBlurLevel = BABYLON.DepthOfFieldEffectBlurLevel.Low;
  70747. _this._fxaaEnabled = false;
  70748. _this._imageProcessingEnabled = true;
  70749. _this._bloomScale = 0.5;
  70750. _this._chromaticAberrationEnabled = false;
  70751. _this._grainEnabled = false;
  70752. _this._buildAllowed = true;
  70753. _this._resizeObserver = null;
  70754. _this._hardwareScaleLevel = 1.0;
  70755. _this._bloomKernel = 64;
  70756. /**
  70757. * Specifies the weight of the bloom in the final rendering
  70758. */
  70759. _this._bloomWeight = 0.15;
  70760. /**
  70761. * Specifies the luma threshold for the area that will be blurred by the bloom
  70762. */
  70763. _this._bloomThreshold = 0.9;
  70764. _this._samples = 1;
  70765. _this._hasCleared = false;
  70766. _this._prevPostProcess = null;
  70767. _this._prevPrevPostProcess = null;
  70768. _this._cameras = cameras || [];
  70769. _this._originalCameras = _this._cameras.slice();
  70770. _this._buildAllowed = automaticBuild;
  70771. // Initialize
  70772. _this._scene = scene;
  70773. var caps = _this._scene.getEngine().getCaps();
  70774. _this._hdr = hdr && (caps.textureHalfFloatRender || caps.textureFloatRender);
  70775. // Misc
  70776. if (_this._hdr) {
  70777. if (caps.textureHalfFloatRender) {
  70778. _this._defaultPipelineTextureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  70779. }
  70780. else if (caps.textureFloatRender) {
  70781. _this._defaultPipelineTextureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  70782. }
  70783. }
  70784. else {
  70785. _this._defaultPipelineTextureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  70786. }
  70787. // Attach
  70788. scene.postProcessRenderPipelineManager.addPipeline(_this);
  70789. var engine = _this._scene.getEngine();
  70790. // Create post processes before hand so they can be modified before enabled.
  70791. // Block compilation flag is set to true to avoid compilation prior to use, these will be updated on first use in build pipeline.
  70792. _this.sharpen = new BABYLON.SharpenPostProcess("sharpen", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, _this._defaultPipelineTextureType, true);
  70793. _this._sharpenEffect = new BABYLON.PostProcessRenderEffect(engine, _this.SharpenPostProcessId, function () { return _this.sharpen; }, true);
  70794. _this.depthOfField = new BABYLON.DepthOfFieldEffect(_this._scene, null, _this._depthOfFieldBlurLevel, _this._defaultPipelineTextureType, true);
  70795. _this.bloom = new BABYLON.BloomEffect(_this._scene, _this._bloomScale, _this._bloomWeight, _this.bloomKernel, _this._defaultPipelineTextureType, true);
  70796. _this.chromaticAberration = new BABYLON.ChromaticAberrationPostProcess("ChromaticAberration", engine.getRenderWidth(), engine.getRenderHeight(), 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, _this._defaultPipelineTextureType, true);
  70797. _this._chromaticAberrationEffect = new BABYLON.PostProcessRenderEffect(engine, _this.ChromaticAberrationPostProcessId, function () { return _this.chromaticAberration; }, true);
  70798. _this.grain = new BABYLON.GrainPostProcess("Grain", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, _this._defaultPipelineTextureType, true);
  70799. _this._grainEffect = new BABYLON.PostProcessRenderEffect(engine, _this.GrainPostProcessId, function () { return _this.grain; }, true);
  70800. _this._resizeObserver = engine.onResizeObservable.add(function () {
  70801. _this._hardwareScaleLevel = engine.getHardwareScalingLevel();
  70802. _this.bloomKernel = _this.bloomKernel;
  70803. });
  70804. _this._imageProcessingConfigurationObserver = _this._scene.imageProcessingConfiguration.onUpdateParameters.add(function () {
  70805. _this.bloom._downscale._exposure = _this._scene.imageProcessingConfiguration.exposure;
  70806. });
  70807. _this._buildPipeline();
  70808. return _this;
  70809. }
  70810. Object.defineProperty(DefaultRenderingPipeline.prototype, "sharpenEnabled", {
  70811. get: function () {
  70812. return this._sharpenEnabled;
  70813. },
  70814. /**
  70815. * Enable or disable the sharpen process from the pipeline
  70816. */
  70817. set: function (enabled) {
  70818. if (this._sharpenEnabled === enabled) {
  70819. return;
  70820. }
  70821. this._sharpenEnabled = enabled;
  70822. this._buildPipeline();
  70823. },
  70824. enumerable: true,
  70825. configurable: true
  70826. });
  70827. Object.defineProperty(DefaultRenderingPipeline.prototype, "bloomKernel", {
  70828. /**
  70829. * Specifies the size of the bloom blur kernel, relative to the final output size
  70830. */
  70831. get: function () {
  70832. return this._bloomKernel;
  70833. },
  70834. set: function (value) {
  70835. this._bloomKernel = value;
  70836. this.bloom.kernel = value / this._hardwareScaleLevel;
  70837. },
  70838. enumerable: true,
  70839. configurable: true
  70840. });
  70841. Object.defineProperty(DefaultRenderingPipeline.prototype, "bloomWeight", {
  70842. get: function () {
  70843. return this._bloomWeight;
  70844. },
  70845. /**
  70846. * The strength of the bloom.
  70847. */
  70848. set: function (value) {
  70849. if (this._bloomWeight === value) {
  70850. return;
  70851. }
  70852. this.bloom.weight = value;
  70853. this._bloomWeight = value;
  70854. },
  70855. enumerable: true,
  70856. configurable: true
  70857. });
  70858. Object.defineProperty(DefaultRenderingPipeline.prototype, "bloomThreshold", {
  70859. get: function () {
  70860. return this._bloomThreshold;
  70861. },
  70862. /**
  70863. * The strength of the bloom.
  70864. */
  70865. set: function (value) {
  70866. if (this._bloomThreshold === value) {
  70867. return;
  70868. }
  70869. this.bloom.threshold = value;
  70870. this._bloomThreshold = value;
  70871. },
  70872. enumerable: true,
  70873. configurable: true
  70874. });
  70875. Object.defineProperty(DefaultRenderingPipeline.prototype, "bloomScale", {
  70876. get: function () {
  70877. return this._bloomScale;
  70878. },
  70879. /**
  70880. * The scale of the bloom, lower value will provide better performance.
  70881. */
  70882. set: function (value) {
  70883. if (this._bloomScale === value) {
  70884. return;
  70885. }
  70886. this._bloomScale = value;
  70887. // recreate bloom and dispose old as this setting is not dynamic
  70888. this._rebuildBloom();
  70889. this._buildPipeline();
  70890. },
  70891. enumerable: true,
  70892. configurable: true
  70893. });
  70894. Object.defineProperty(DefaultRenderingPipeline.prototype, "bloomEnabled", {
  70895. get: function () {
  70896. return this._bloomEnabled;
  70897. },
  70898. /**
  70899. * Enable or disable the bloom from the pipeline
  70900. */
  70901. set: function (enabled) {
  70902. if (this._bloomEnabled === enabled) {
  70903. return;
  70904. }
  70905. this._bloomEnabled = enabled;
  70906. this._buildPipeline();
  70907. },
  70908. enumerable: true,
  70909. configurable: true
  70910. });
  70911. DefaultRenderingPipeline.prototype._rebuildBloom = function () {
  70912. // recreate bloom and dispose old as this setting is not dynamic
  70913. var oldBloom = this.bloom;
  70914. this.bloom = new BABYLON.BloomEffect(this._scene, this.bloomScale, this._bloomWeight, this.bloomKernel, this._defaultPipelineTextureType, false);
  70915. this.bloom.threshold = oldBloom.threshold;
  70916. for (var i = 0; i < this._cameras.length; i++) {
  70917. oldBloom.disposeEffects(this._cameras[i]);
  70918. }
  70919. };
  70920. Object.defineProperty(DefaultRenderingPipeline.prototype, "depthOfFieldEnabled", {
  70921. /**
  70922. * If the depth of field is enabled.
  70923. */
  70924. get: function () {
  70925. return this._depthOfFieldEnabled;
  70926. },
  70927. set: function (enabled) {
  70928. if (this._depthOfFieldEnabled === enabled) {
  70929. return;
  70930. }
  70931. this._depthOfFieldEnabled = enabled;
  70932. this._buildPipeline();
  70933. },
  70934. enumerable: true,
  70935. configurable: true
  70936. });
  70937. Object.defineProperty(DefaultRenderingPipeline.prototype, "depthOfFieldBlurLevel", {
  70938. /**
  70939. * Blur level of the depth of field effect. (Higher blur will effect performance)
  70940. */
  70941. get: function () {
  70942. return this._depthOfFieldBlurLevel;
  70943. },
  70944. set: function (value) {
  70945. if (this._depthOfFieldBlurLevel === value) {
  70946. return;
  70947. }
  70948. this._depthOfFieldBlurLevel = value;
  70949. // recreate dof and dispose old as this setting is not dynamic
  70950. var oldDof = this.depthOfField;
  70951. this.depthOfField = new BABYLON.DepthOfFieldEffect(this._scene, null, this._depthOfFieldBlurLevel, this._defaultPipelineTextureType, false);
  70952. this.depthOfField.focalLength = oldDof.focalLength;
  70953. this.depthOfField.focusDistance = oldDof.focusDistance;
  70954. this.depthOfField.fStop = oldDof.fStop;
  70955. this.depthOfField.lensSize = oldDof.lensSize;
  70956. for (var i = 0; i < this._cameras.length; i++) {
  70957. oldDof.disposeEffects(this._cameras[i]);
  70958. }
  70959. this._buildPipeline();
  70960. },
  70961. enumerable: true,
  70962. configurable: true
  70963. });
  70964. Object.defineProperty(DefaultRenderingPipeline.prototype, "fxaaEnabled", {
  70965. get: function () {
  70966. return this._fxaaEnabled;
  70967. },
  70968. /**
  70969. * If the anti aliasing is enabled.
  70970. */
  70971. set: function (enabled) {
  70972. if (this._fxaaEnabled === enabled) {
  70973. return;
  70974. }
  70975. this._fxaaEnabled = enabled;
  70976. this._buildPipeline();
  70977. },
  70978. enumerable: true,
  70979. configurable: true
  70980. });
  70981. Object.defineProperty(DefaultRenderingPipeline.prototype, "samples", {
  70982. get: function () {
  70983. return this._samples;
  70984. },
  70985. /**
  70986. * MSAA sample count, setting this to 4 will provide 4x anti aliasing. (default: 1)
  70987. */
  70988. set: function (sampleCount) {
  70989. if (this._samples === sampleCount) {
  70990. return;
  70991. }
  70992. this._samples = sampleCount;
  70993. this._buildPipeline();
  70994. },
  70995. enumerable: true,
  70996. configurable: true
  70997. });
  70998. Object.defineProperty(DefaultRenderingPipeline.prototype, "imageProcessingEnabled", {
  70999. get: function () {
  71000. return this._imageProcessingEnabled;
  71001. },
  71002. /**
  71003. * If image processing is enabled.
  71004. */
  71005. set: function (enabled) {
  71006. if (this._imageProcessingEnabled === enabled) {
  71007. return;
  71008. }
  71009. this._imageProcessingEnabled = enabled;
  71010. this._buildPipeline();
  71011. },
  71012. enumerable: true,
  71013. configurable: true
  71014. });
  71015. Object.defineProperty(DefaultRenderingPipeline.prototype, "chromaticAberrationEnabled", {
  71016. get: function () {
  71017. return this._chromaticAberrationEnabled;
  71018. },
  71019. /**
  71020. * Enable or disable the chromaticAberration process from the pipeline
  71021. */
  71022. set: function (enabled) {
  71023. if (this._chromaticAberrationEnabled === enabled) {
  71024. return;
  71025. }
  71026. this._chromaticAberrationEnabled = enabled;
  71027. this._buildPipeline();
  71028. },
  71029. enumerable: true,
  71030. configurable: true
  71031. });
  71032. Object.defineProperty(DefaultRenderingPipeline.prototype, "grainEnabled", {
  71033. get: function () {
  71034. return this._grainEnabled;
  71035. },
  71036. /**
  71037. * Enable or disable the grain process from the pipeline
  71038. */
  71039. set: function (enabled) {
  71040. if (this._grainEnabled === enabled) {
  71041. return;
  71042. }
  71043. this._grainEnabled = enabled;
  71044. this._buildPipeline();
  71045. },
  71046. enumerable: true,
  71047. configurable: true
  71048. });
  71049. /**
  71050. * Force the compilation of the entire pipeline.
  71051. */
  71052. DefaultRenderingPipeline.prototype.prepare = function () {
  71053. var previousState = this._buildAllowed;
  71054. this._buildAllowed = true;
  71055. this._buildPipeline();
  71056. this._buildAllowed = previousState;
  71057. };
  71058. DefaultRenderingPipeline.prototype._setAutoClearAndTextureSharing = function (postProcess, skipTextureSharing) {
  71059. if (skipTextureSharing === void 0) { skipTextureSharing = false; }
  71060. if (this._hasCleared) {
  71061. postProcess.autoClear = false;
  71062. }
  71063. else {
  71064. postProcess.autoClear = true;
  71065. this._scene.autoClear = false;
  71066. this._hasCleared = true;
  71067. }
  71068. if (!skipTextureSharing) {
  71069. if (this._prevPrevPostProcess) {
  71070. postProcess.shareOutputWith(this._prevPrevPostProcess);
  71071. }
  71072. else {
  71073. postProcess.useOwnOutput();
  71074. }
  71075. if (this._prevPostProcess) {
  71076. this._prevPrevPostProcess = this._prevPostProcess;
  71077. }
  71078. this._prevPostProcess = postProcess;
  71079. }
  71080. };
  71081. DefaultRenderingPipeline.prototype._buildPipeline = function () {
  71082. var _this = this;
  71083. if (!this._buildAllowed) {
  71084. return;
  71085. }
  71086. this._scene.autoClear = true;
  71087. var engine = this._scene.getEngine();
  71088. this._disposePostProcesses();
  71089. if (this._cameras !== null) {
  71090. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._cameras);
  71091. // get back cameras to be used to reattach pipeline
  71092. this._cameras = this._originalCameras.slice();
  71093. }
  71094. this._reset();
  71095. this._prevPostProcess = null;
  71096. this._prevPrevPostProcess = null;
  71097. this._hasCleared = false;
  71098. if (this.depthOfFieldEnabled) {
  71099. var depthTexture = this._scene.enableDepthRenderer(this._cameras[0]).getDepthMap();
  71100. this.depthOfField.depthTexture = depthTexture;
  71101. if (!this.depthOfField._isReady()) {
  71102. this.depthOfField._updateEffects();
  71103. }
  71104. this.addEffect(this.depthOfField);
  71105. this._setAutoClearAndTextureSharing(this.depthOfField._effects[0], true);
  71106. }
  71107. if (this.bloomEnabled) {
  71108. if (!this.bloom._isReady()) {
  71109. this.bloom._updateEffects();
  71110. }
  71111. this.addEffect(this.bloom);
  71112. this._setAutoClearAndTextureSharing(this.bloom._effects[0], true);
  71113. }
  71114. if (this._imageProcessingEnabled) {
  71115. this.imageProcessing = new BABYLON.ImageProcessingPostProcess("imageProcessing", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, this._defaultPipelineTextureType);
  71116. if (this._hdr) {
  71117. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.ImageProcessingPostProcessId, function () { return _this.imageProcessing; }, true));
  71118. this._setAutoClearAndTextureSharing(this.imageProcessing);
  71119. }
  71120. else {
  71121. this._scene.imageProcessingConfiguration.applyByPostProcess = false;
  71122. }
  71123. }
  71124. if (this.sharpenEnabled) {
  71125. if (!this.sharpen.isReady()) {
  71126. this.sharpen.updateEffect();
  71127. }
  71128. this.addEffect(this._sharpenEffect);
  71129. this._setAutoClearAndTextureSharing(this.sharpen);
  71130. }
  71131. if (this.grainEnabled) {
  71132. if (!this.grain.isReady()) {
  71133. this.grain.updateEffect();
  71134. }
  71135. this.addEffect(this._grainEffect);
  71136. this._setAutoClearAndTextureSharing(this.grain);
  71137. }
  71138. if (this.chromaticAberrationEnabled) {
  71139. if (!this.chromaticAberration.isReady()) {
  71140. this.chromaticAberration.updateEffect();
  71141. }
  71142. this.addEffect(this._chromaticAberrationEffect);
  71143. this._setAutoClearAndTextureSharing(this.chromaticAberration);
  71144. }
  71145. if (this.fxaaEnabled) {
  71146. this.fxaa = new BABYLON.FxaaPostProcess("fxaa", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, this._defaultPipelineTextureType);
  71147. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.FxaaPostProcessId, function () { return _this.fxaa; }, true));
  71148. this._setAutoClearAndTextureSharing(this.fxaa, true);
  71149. }
  71150. if (this._cameras !== null) {
  71151. this._scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(this._name, this._cameras);
  71152. }
  71153. if (!this._enableMSAAOnFirstPostProcess(this.samples) && this.samples > 1) {
  71154. BABYLON.Tools.Warn("MSAA failed to enable, MSAA is only supported in browsers that support webGL >= 2.0");
  71155. }
  71156. };
  71157. DefaultRenderingPipeline.prototype._disposePostProcesses = function (disposeNonRecreated) {
  71158. if (disposeNonRecreated === void 0) { disposeNonRecreated = false; }
  71159. for (var i = 0; i < this._cameras.length; i++) {
  71160. var camera = this._cameras[i];
  71161. if (this.imageProcessing) {
  71162. this.imageProcessing.dispose(camera);
  71163. }
  71164. if (this.fxaa) {
  71165. this.fxaa.dispose(camera);
  71166. }
  71167. // These are created in the constructor and should not be disposed on every pipeline change
  71168. if (disposeNonRecreated) {
  71169. if (this.sharpen) {
  71170. this.sharpen.dispose(camera);
  71171. }
  71172. if (this.depthOfField) {
  71173. this.depthOfField.disposeEffects(camera);
  71174. }
  71175. if (this.bloom) {
  71176. this.bloom.disposeEffects(camera);
  71177. }
  71178. if (this.chromaticAberration) {
  71179. this.chromaticAberration.dispose(camera);
  71180. }
  71181. if (this.grain) {
  71182. this.grain.dispose(camera);
  71183. }
  71184. }
  71185. }
  71186. this.imageProcessing = null;
  71187. this.fxaa = null;
  71188. if (disposeNonRecreated) {
  71189. this.sharpen = null;
  71190. this._sharpenEffect = null;
  71191. this.depthOfField = null;
  71192. this.bloom = null;
  71193. this.chromaticAberration = null;
  71194. this._chromaticAberrationEffect = null;
  71195. this.grain = null;
  71196. this._grainEffect = null;
  71197. }
  71198. };
  71199. /**
  71200. * Dispose of the pipeline and stop all post processes
  71201. */
  71202. DefaultRenderingPipeline.prototype.dispose = function () {
  71203. this._disposePostProcesses(true);
  71204. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._cameras);
  71205. this._scene.autoClear = true;
  71206. if (this._resizeObserver) {
  71207. this._scene.getEngine().onResizeObservable.remove(this._resizeObserver);
  71208. this._resizeObserver = null;
  71209. }
  71210. this._scene.imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingConfigurationObserver);
  71211. _super.prototype.dispose.call(this);
  71212. };
  71213. /**
  71214. * Serialize the rendering pipeline (Used when exporting)
  71215. * @returns the serialized object
  71216. */
  71217. DefaultRenderingPipeline.prototype.serialize = function () {
  71218. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  71219. serializationObject.customType = "DefaultRenderingPipeline";
  71220. return serializationObject;
  71221. };
  71222. /**
  71223. * Parse the serialized pipeline
  71224. * @param source Source pipeline.
  71225. * @param scene The scene to load the pipeline to.
  71226. * @param rootUrl The URL of the serialized pipeline.
  71227. * @returns An instantiated pipeline from the serialized object.
  71228. */
  71229. DefaultRenderingPipeline.Parse = function (source, scene, rootUrl) {
  71230. return BABYLON.SerializationHelper.Parse(function () { return new DefaultRenderingPipeline(source._name, source._name._hdr, scene); }, source, scene, rootUrl);
  71231. };
  71232. __decorate([
  71233. BABYLON.serialize()
  71234. ], DefaultRenderingPipeline.prototype, "sharpenEnabled", null);
  71235. __decorate([
  71236. BABYLON.serialize()
  71237. ], DefaultRenderingPipeline.prototype, "bloomKernel", null);
  71238. __decorate([
  71239. BABYLON.serialize()
  71240. ], DefaultRenderingPipeline.prototype, "_bloomWeight", void 0);
  71241. __decorate([
  71242. BABYLON.serialize()
  71243. ], DefaultRenderingPipeline.prototype, "_bloomThreshold", void 0);
  71244. __decorate([
  71245. BABYLON.serialize()
  71246. ], DefaultRenderingPipeline.prototype, "_hdr", void 0);
  71247. __decorate([
  71248. BABYLON.serialize()
  71249. ], DefaultRenderingPipeline.prototype, "bloomWeight", null);
  71250. __decorate([
  71251. BABYLON.serialize()
  71252. ], DefaultRenderingPipeline.prototype, "bloomThreshold", null);
  71253. __decorate([
  71254. BABYLON.serialize()
  71255. ], DefaultRenderingPipeline.prototype, "bloomScale", null);
  71256. __decorate([
  71257. BABYLON.serialize()
  71258. ], DefaultRenderingPipeline.prototype, "bloomEnabled", null);
  71259. __decorate([
  71260. BABYLON.serialize()
  71261. ], DefaultRenderingPipeline.prototype, "depthOfFieldEnabled", null);
  71262. __decorate([
  71263. BABYLON.serialize()
  71264. ], DefaultRenderingPipeline.prototype, "depthOfFieldBlurLevel", null);
  71265. __decorate([
  71266. BABYLON.serialize()
  71267. ], DefaultRenderingPipeline.prototype, "fxaaEnabled", null);
  71268. __decorate([
  71269. BABYLON.serialize()
  71270. ], DefaultRenderingPipeline.prototype, "samples", null);
  71271. __decorate([
  71272. BABYLON.serialize()
  71273. ], DefaultRenderingPipeline.prototype, "imageProcessingEnabled", null);
  71274. __decorate([
  71275. BABYLON.serialize()
  71276. ], DefaultRenderingPipeline.prototype, "chromaticAberrationEnabled", null);
  71277. __decorate([
  71278. BABYLON.serialize()
  71279. ], DefaultRenderingPipeline.prototype, "grainEnabled", null);
  71280. return DefaultRenderingPipeline;
  71281. }(BABYLON.PostProcessRenderPipeline));
  71282. BABYLON.DefaultRenderingPipeline = DefaultRenderingPipeline;
  71283. })(BABYLON || (BABYLON = {}));
  71284. //# sourceMappingURL=babylon.defaultRenderingPipeline.js.map
  71285. "use strict";
  71286. var BABYLON;
  71287. (function (BABYLON) {
  71288. /**
  71289. * This renderer is helpfull to fill one of the render target with a geometry buffer.
  71290. */
  71291. var GeometryBufferRenderer = /** @class */ (function () {
  71292. /**
  71293. * Creates a new G Buffer for the scene
  71294. * @param scene The scene the buffer belongs to
  71295. * @param ratio How big is the buffer related to the main canvas.
  71296. */
  71297. function GeometryBufferRenderer(scene, ratio) {
  71298. if (ratio === void 0) { ratio = 1; }
  71299. this._enablePosition = false;
  71300. this._scene = scene;
  71301. this._ratio = ratio;
  71302. // Render target
  71303. this._createRenderTargets();
  71304. }
  71305. Object.defineProperty(GeometryBufferRenderer.prototype, "renderList", {
  71306. /**
  71307. * Set the render list (meshes to be rendered) used in the G buffer.
  71308. */
  71309. set: function (meshes) {
  71310. this._multiRenderTarget.renderList = meshes;
  71311. },
  71312. enumerable: true,
  71313. configurable: true
  71314. });
  71315. Object.defineProperty(GeometryBufferRenderer.prototype, "isSupported", {
  71316. /**
  71317. * Gets wether or not G buffer are supported by the running hardware.
  71318. * This requires draw buffer supports
  71319. */
  71320. get: function () {
  71321. return this._multiRenderTarget.isSupported;
  71322. },
  71323. enumerable: true,
  71324. configurable: true
  71325. });
  71326. Object.defineProperty(GeometryBufferRenderer.prototype, "enablePosition", {
  71327. /**
  71328. * Gets wether or not position are enabled for the G buffer.
  71329. */
  71330. get: function () {
  71331. return this._enablePosition;
  71332. },
  71333. /**
  71334. * Sets wether or not position are enabled for the G buffer.
  71335. */
  71336. set: function (enable) {
  71337. this._enablePosition = enable;
  71338. this.dispose();
  71339. this._createRenderTargets();
  71340. },
  71341. enumerable: true,
  71342. configurable: true
  71343. });
  71344. Object.defineProperty(GeometryBufferRenderer.prototype, "scene", {
  71345. /**
  71346. * Gets the scene associated with the buffer.
  71347. */
  71348. get: function () {
  71349. return this._scene;
  71350. },
  71351. enumerable: true,
  71352. configurable: true
  71353. });
  71354. Object.defineProperty(GeometryBufferRenderer.prototype, "ratio", {
  71355. /**
  71356. * Gets the ratio used by the buffer during its creation.
  71357. * How big is the buffer related to the main canvas.
  71358. */
  71359. get: function () {
  71360. return this._ratio;
  71361. },
  71362. enumerable: true,
  71363. configurable: true
  71364. });
  71365. /**
  71366. * Checks wether everything is ready to render a submesh to the G buffer.
  71367. * @param subMesh the submesh to check readiness for
  71368. * @param useInstances is the mesh drawn using instance or not
  71369. * @returns true if ready otherwise false
  71370. */
  71371. GeometryBufferRenderer.prototype.isReady = function (subMesh, useInstances) {
  71372. var material = subMesh.getMaterial();
  71373. if (material && material.disableDepthWrite) {
  71374. return false;
  71375. }
  71376. var defines = [];
  71377. var attribs = [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.NormalKind];
  71378. var mesh = subMesh.getMesh();
  71379. // Alpha test
  71380. if (material && material.needAlphaTesting()) {
  71381. defines.push("#define ALPHATEST");
  71382. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  71383. attribs.push(BABYLON.VertexBuffer.UVKind);
  71384. defines.push("#define UV1");
  71385. }
  71386. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  71387. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  71388. defines.push("#define UV2");
  71389. }
  71390. }
  71391. // Buffers
  71392. if (this._enablePosition) {
  71393. defines.push("#define POSITION");
  71394. }
  71395. // Bones
  71396. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  71397. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  71398. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  71399. if (mesh.numBoneInfluencers > 4) {
  71400. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  71401. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  71402. }
  71403. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  71404. defines.push("#define BonesPerMesh " + (mesh.skeleton ? mesh.skeleton.bones.length + 1 : 0));
  71405. }
  71406. else {
  71407. defines.push("#define NUM_BONE_INFLUENCERS 0");
  71408. }
  71409. // Instances
  71410. if (useInstances) {
  71411. defines.push("#define INSTANCES");
  71412. attribs.push("world0");
  71413. attribs.push("world1");
  71414. attribs.push("world2");
  71415. attribs.push("world3");
  71416. }
  71417. // Get correct effect
  71418. var join = defines.join("\n");
  71419. if (this._cachedDefines !== join) {
  71420. this._cachedDefines = join;
  71421. this._effect = this._scene.getEngine().createEffect("geometry", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "view"], ["diffuseSampler"], join, undefined, undefined, undefined, { buffersCount: this._enablePosition ? 3 : 2 });
  71422. }
  71423. return this._effect.isReady();
  71424. };
  71425. /**
  71426. * Gets the current underlying G Buffer.
  71427. * @returns the buffer
  71428. */
  71429. GeometryBufferRenderer.prototype.getGBuffer = function () {
  71430. return this._multiRenderTarget;
  71431. };
  71432. Object.defineProperty(GeometryBufferRenderer.prototype, "samples", {
  71433. /**
  71434. * Gets the number of samples used to render the buffer (anti aliasing).
  71435. */
  71436. get: function () {
  71437. return this._multiRenderTarget.samples;
  71438. },
  71439. /**
  71440. * Sets the number of samples used to render the buffer (anti aliasing).
  71441. */
  71442. set: function (value) {
  71443. this._multiRenderTarget.samples = value;
  71444. },
  71445. enumerable: true,
  71446. configurable: true
  71447. });
  71448. /**
  71449. * Disposes the renderer and frees up associated resources.
  71450. */
  71451. GeometryBufferRenderer.prototype.dispose = function () {
  71452. this.getGBuffer().dispose();
  71453. };
  71454. GeometryBufferRenderer.prototype._createRenderTargets = function () {
  71455. var _this = this;
  71456. var engine = this._scene.getEngine();
  71457. var count = this._enablePosition ? 3 : 2;
  71458. 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 });
  71459. if (!this.isSupported) {
  71460. return;
  71461. }
  71462. this._multiRenderTarget.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  71463. this._multiRenderTarget.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  71464. this._multiRenderTarget.refreshRate = 1;
  71465. this._multiRenderTarget.renderParticles = false;
  71466. this._multiRenderTarget.renderList = null;
  71467. // set default depth value to 1.0 (far away)
  71468. this._multiRenderTarget.onClearObservable.add(function (engine) {
  71469. engine.clear(new BABYLON.Color4(0.0, 0.0, 0.0, 1.0), true, true, true);
  71470. });
  71471. // Custom render function
  71472. var renderSubMesh = function (subMesh) {
  71473. var mesh = subMesh.getRenderingMesh();
  71474. var scene = _this._scene;
  71475. var engine = scene.getEngine();
  71476. var material = subMesh.getMaterial();
  71477. if (!material) {
  71478. return;
  71479. }
  71480. // Culling
  71481. engine.setState(material.backFaceCulling, 0, false, scene.useRightHandedSystem);
  71482. // Managing instances
  71483. var batch = mesh._getInstancesRenderList(subMesh._id);
  71484. if (batch.mustReturn) {
  71485. return;
  71486. }
  71487. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null);
  71488. if (_this.isReady(subMesh, hardwareInstancedRendering)) {
  71489. engine.enableEffect(_this._effect);
  71490. mesh._bind(subMesh, _this._effect, BABYLON.Material.TriangleFillMode);
  71491. _this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  71492. _this._effect.setMatrix("view", scene.getViewMatrix());
  71493. // Alpha test
  71494. if (material && material.needAlphaTesting()) {
  71495. var alphaTexture = material.getAlphaTestTexture();
  71496. if (alphaTexture) {
  71497. _this._effect.setTexture("diffuseSampler", alphaTexture);
  71498. _this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  71499. }
  71500. }
  71501. // Bones
  71502. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  71503. _this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  71504. }
  71505. // Draw
  71506. mesh._processRendering(subMesh, _this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effect.setMatrix("world", world); });
  71507. }
  71508. };
  71509. this._multiRenderTarget.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes) {
  71510. var index;
  71511. if (depthOnlySubMeshes.length) {
  71512. engine.setColorWrite(false);
  71513. for (index = 0; index < depthOnlySubMeshes.length; index++) {
  71514. renderSubMesh(depthOnlySubMeshes.data[index]);
  71515. }
  71516. engine.setColorWrite(true);
  71517. }
  71518. for (index = 0; index < opaqueSubMeshes.length; index++) {
  71519. renderSubMesh(opaqueSubMeshes.data[index]);
  71520. }
  71521. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  71522. renderSubMesh(alphaTestSubMeshes.data[index]);
  71523. }
  71524. };
  71525. };
  71526. return GeometryBufferRenderer;
  71527. }());
  71528. BABYLON.GeometryBufferRenderer = GeometryBufferRenderer;
  71529. })(BABYLON || (BABYLON = {}));
  71530. //# sourceMappingURL=babylon.geometryBufferRenderer.js.map
  71531. "use strict";
  71532. var BABYLON;
  71533. (function (BABYLON) {
  71534. var RefractionPostProcess = /** @class */ (function (_super) {
  71535. __extends(RefractionPostProcess, _super);
  71536. function RefractionPostProcess(name, refractionTextureUrl, color, depth, colorLevel, options, camera, samplingMode, engine, reusable) {
  71537. var _this = _super.call(this, name, "refraction", ["baseColor", "depth", "colorLevel"], ["refractionSampler"], options, camera, samplingMode, engine, reusable) || this;
  71538. _this.color = color;
  71539. _this.depth = depth;
  71540. _this.colorLevel = colorLevel;
  71541. _this._ownRefractionTexture = true;
  71542. _this.onActivateObservable.add(function (cam) {
  71543. _this._refTexture = _this._refTexture || new BABYLON.Texture(refractionTextureUrl, cam.getScene());
  71544. });
  71545. _this.onApplyObservable.add(function (effect) {
  71546. effect.setColor3("baseColor", _this.color);
  71547. effect.setFloat("depth", _this.depth);
  71548. effect.setFloat("colorLevel", _this.colorLevel);
  71549. effect.setTexture("refractionSampler", _this._refTexture);
  71550. });
  71551. return _this;
  71552. }
  71553. Object.defineProperty(RefractionPostProcess.prototype, "refractionTexture", {
  71554. /**
  71555. * Gets or sets the refraction texture
  71556. * Please note that you are responsible for disposing the texture if you set it manually
  71557. */
  71558. get: function () {
  71559. return this._refTexture;
  71560. },
  71561. set: function (value) {
  71562. if (this._refTexture && this._ownRefractionTexture) {
  71563. this._refTexture.dispose();
  71564. }
  71565. this._refTexture = value;
  71566. this._ownRefractionTexture = false;
  71567. },
  71568. enumerable: true,
  71569. configurable: true
  71570. });
  71571. // Methods
  71572. RefractionPostProcess.prototype.dispose = function (camera) {
  71573. if (this._refTexture && this._ownRefractionTexture) {
  71574. this._refTexture.dispose();
  71575. this._refTexture = null;
  71576. }
  71577. _super.prototype.dispose.call(this, camera);
  71578. };
  71579. return RefractionPostProcess;
  71580. }(BABYLON.PostProcess));
  71581. BABYLON.RefractionPostProcess = RefractionPostProcess;
  71582. })(BABYLON || (BABYLON = {}));
  71583. //# sourceMappingURL=babylon.refractionPostProcess.js.map
  71584. "use strict";
  71585. var BABYLON;
  71586. (function (BABYLON) {
  71587. var BlackAndWhitePostProcess = /** @class */ (function (_super) {
  71588. __extends(BlackAndWhitePostProcess, _super);
  71589. function BlackAndWhitePostProcess(name, options, camera, samplingMode, engine, reusable) {
  71590. var _this = _super.call(this, name, "blackAndWhite", ["degree"], null, options, camera, samplingMode, engine, reusable) || this;
  71591. _this.degree = 1;
  71592. _this.onApplyObservable.add(function (effect) {
  71593. effect.setFloat("degree", _this.degree);
  71594. });
  71595. return _this;
  71596. }
  71597. return BlackAndWhitePostProcess;
  71598. }(BABYLON.PostProcess));
  71599. BABYLON.BlackAndWhitePostProcess = BlackAndWhitePostProcess;
  71600. })(BABYLON || (BABYLON = {}));
  71601. //# sourceMappingURL=babylon.blackAndWhitePostProcess.js.map
  71602. "use strict";
  71603. var BABYLON;
  71604. (function (BABYLON) {
  71605. /**
  71606. * The ConvolutionPostProcess applies a 3x3 kernel to every pixel of the
  71607. * input texture to perform effects such as edge detection or sharpening
  71608. * See http://en.wikipedia.org/wiki/Kernel_(image_processing)
  71609. */
  71610. var ConvolutionPostProcess = /** @class */ (function (_super) {
  71611. __extends(ConvolutionPostProcess, _super);
  71612. /**
  71613. * Creates a new instance ConvolutionPostProcess
  71614. * @param name The name of the effect.
  71615. * @param kernel Array of 9 values corrisponding to the 3x3 kernel to be applied
  71616. * @param options The required width/height ratio to downsize to before computing the render pass.
  71617. * @param camera The camera to apply the render pass to.
  71618. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  71619. * @param engine The engine which the post process will be applied. (default: current engine)
  71620. * @param reusable If the post process can be reused on the same frame. (default: false)
  71621. * @param textureType Type of textures used when performing the post process. (default: 0)
  71622. */
  71623. function ConvolutionPostProcess(name, /** Array of 9 values corrisponding to the 3x3 kernel to be applied */ kernel, options, camera, samplingMode, engine, reusable, textureType) {
  71624. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  71625. var _this = _super.call(this, name, "convolution", ["kernel", "screenSize"], null, options, camera, samplingMode, engine, reusable, null, textureType) || this;
  71626. _this.kernel = kernel;
  71627. _this.onApply = function (effect) {
  71628. effect.setFloat2("screenSize", _this.width, _this.height);
  71629. effect.setArray("kernel", _this.kernel);
  71630. };
  71631. return _this;
  71632. }
  71633. // Statics
  71634. /**
  71635. * Edge detection 0 see https://en.wikipedia.org/wiki/Kernel_(image_processing)
  71636. */
  71637. ConvolutionPostProcess.EdgeDetect0Kernel = [1, 0, -1, 0, 0, 0, -1, 0, 1];
  71638. /**
  71639. * Edge detection 1 see https://en.wikipedia.org/wiki/Kernel_(image_processing)
  71640. */
  71641. ConvolutionPostProcess.EdgeDetect1Kernel = [0, 1, 0, 1, -4, 1, 0, 1, 0];
  71642. /**
  71643. * Edge detection 2 see https://en.wikipedia.org/wiki/Kernel_(image_processing)
  71644. */
  71645. ConvolutionPostProcess.EdgeDetect2Kernel = [-1, -1, -1, -1, 8, -1, -1, -1, -1];
  71646. /**
  71647. * Kernel to sharpen an image see https://en.wikipedia.org/wiki/Kernel_(image_processing)
  71648. */
  71649. ConvolutionPostProcess.SharpenKernel = [0, -1, 0, -1, 5, -1, 0, -1, 0];
  71650. /**
  71651. * Kernel to emboss an image see https://en.wikipedia.org/wiki/Kernel_(image_processing)
  71652. */
  71653. ConvolutionPostProcess.EmbossKernel = [-2, -1, 0, -1, 1, 1, 0, 1, 2];
  71654. /**
  71655. * Kernel to blur an image see https://en.wikipedia.org/wiki/Kernel_(image_processing)
  71656. */
  71657. ConvolutionPostProcess.GaussianKernel = [0, 1, 0, 1, 1, 1, 0, 1, 0];
  71658. return ConvolutionPostProcess;
  71659. }(BABYLON.PostProcess));
  71660. BABYLON.ConvolutionPostProcess = ConvolutionPostProcess;
  71661. })(BABYLON || (BABYLON = {}));
  71662. //# sourceMappingURL=babylon.convolutionPostProcess.js.map
  71663. "use strict";
  71664. var BABYLON;
  71665. (function (BABYLON) {
  71666. var FilterPostProcess = /** @class */ (function (_super) {
  71667. __extends(FilterPostProcess, _super);
  71668. function FilterPostProcess(name, kernelMatrix, options, camera, samplingMode, engine, reusable) {
  71669. var _this = _super.call(this, name, "filter", ["kernelMatrix"], null, options, camera, samplingMode, engine, reusable) || this;
  71670. _this.kernelMatrix = kernelMatrix;
  71671. _this.onApply = function (effect) {
  71672. effect.setMatrix("kernelMatrix", _this.kernelMatrix);
  71673. };
  71674. return _this;
  71675. }
  71676. return FilterPostProcess;
  71677. }(BABYLON.PostProcess));
  71678. BABYLON.FilterPostProcess = FilterPostProcess;
  71679. })(BABYLON || (BABYLON = {}));
  71680. //# sourceMappingURL=babylon.filterPostProcess.js.map
  71681. "use strict";
  71682. var BABYLON;
  71683. (function (BABYLON) {
  71684. // Inspired by http://http.developer.nvidia.com/GPUGems3/gpugems3_ch13.html
  71685. var VolumetricLightScatteringPostProcess = /** @class */ (function (_super) {
  71686. __extends(VolumetricLightScatteringPostProcess, _super);
  71687. /**
  71688. * @constructor
  71689. * @param {string} name - The post-process name
  71690. * @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)
  71691. * @param {BABYLON.Camera} camera - The camera that the post-process will be attached to
  71692. * @param {BABYLON.Mesh} mesh - The mesh used to create the light scattering
  71693. * @param {number} samples - The post-process quality, default 100
  71694. * @param {number} samplingMode - The post-process filtering mode
  71695. * @param {BABYLON.Engine} engine - The babylon engine
  71696. * @param {boolean} reusable - If the post-process is reusable
  71697. * @param {BABYLON.Scene} scene - The constructor needs a scene reference to initialize internal components. If "camera" is null (RenderPipelineà, "scene" must be provided
  71698. */
  71699. function VolumetricLightScatteringPostProcess(name, ratio, camera, mesh, samples, samplingMode, engine, reusable, scene) {
  71700. if (samples === void 0) { samples = 100; }
  71701. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  71702. 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;
  71703. _this._screenCoordinates = BABYLON.Vector2.Zero();
  71704. /**
  71705. * Custom position of the mesh. Used if "useCustomMeshPosition" is set to "true"
  71706. */
  71707. _this.customMeshPosition = BABYLON.Vector3.Zero();
  71708. /**
  71709. * Set if the post-process should use a custom position for the light source (true) or the internal mesh position (false)
  71710. */
  71711. _this.useCustomMeshPosition = false;
  71712. /**
  71713. * If the post-process should inverse the light scattering direction
  71714. */
  71715. _this.invert = true;
  71716. /**
  71717. * Array containing the excluded meshes not rendered in the internal pass
  71718. */
  71719. _this.excludedMeshes = new Array();
  71720. /**
  71721. * Controls the overall intensity of the post-process
  71722. */
  71723. _this.exposure = 0.3;
  71724. /**
  71725. * Dissipates each sample's contribution in range [0, 1]
  71726. */
  71727. _this.decay = 0.96815;
  71728. /**
  71729. * Controls the overall intensity of each sample
  71730. */
  71731. _this.weight = 0.58767;
  71732. /**
  71733. * Controls the density of each sample
  71734. */
  71735. _this.density = 0.926;
  71736. scene = ((camera === null) ? scene : camera.getScene()); // parameter "scene" can be null.
  71737. engine = scene.getEngine();
  71738. _this._viewPort = new BABYLON.Viewport(0, 0, 1, 1).toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  71739. // Configure mesh
  71740. _this.mesh = ((mesh !== null) ? mesh : VolumetricLightScatteringPostProcess.CreateDefaultMesh("VolumetricLightScatteringMesh", scene));
  71741. // Configure
  71742. _this._createPass(scene, ratio.passRatio || ratio);
  71743. _this.onActivate = function (camera) {
  71744. if (!_this.isSupported) {
  71745. _this.dispose(camera);
  71746. }
  71747. _this.onActivate = null;
  71748. };
  71749. _this.onApplyObservable.add(function (effect) {
  71750. _this._updateMeshScreenCoordinates(scene);
  71751. effect.setTexture("lightScatteringSampler", _this._volumetricLightScatteringRTT);
  71752. effect.setFloat("exposure", _this.exposure);
  71753. effect.setFloat("decay", _this.decay);
  71754. effect.setFloat("weight", _this.weight);
  71755. effect.setFloat("density", _this.density);
  71756. effect.setVector2("meshPositionOnScreen", _this._screenCoordinates);
  71757. });
  71758. return _this;
  71759. }
  71760. Object.defineProperty(VolumetricLightScatteringPostProcess.prototype, "useDiffuseColor", {
  71761. get: function () {
  71762. BABYLON.Tools.Warn("VolumetricLightScatteringPostProcess.useDiffuseColor is no longer used, use the mesh material directly instead");
  71763. return false;
  71764. },
  71765. set: function (useDiffuseColor) {
  71766. BABYLON.Tools.Warn("VolumetricLightScatteringPostProcess.useDiffuseColor is no longer used, use the mesh material directly instead");
  71767. },
  71768. enumerable: true,
  71769. configurable: true
  71770. });
  71771. VolumetricLightScatteringPostProcess.prototype.getClassName = function () {
  71772. return "VolumetricLightScatteringPostProcess";
  71773. };
  71774. VolumetricLightScatteringPostProcess.prototype._isReady = function (subMesh, useInstances) {
  71775. var mesh = subMesh.getMesh();
  71776. // Render this.mesh as default
  71777. if (mesh === this.mesh && mesh.material) {
  71778. return mesh.material.isReady(mesh);
  71779. }
  71780. var defines = [];
  71781. var attribs = [BABYLON.VertexBuffer.PositionKind];
  71782. var material = subMesh.getMaterial();
  71783. // Alpha test
  71784. if (material) {
  71785. if (material.needAlphaTesting()) {
  71786. defines.push("#define ALPHATEST");
  71787. }
  71788. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  71789. attribs.push(BABYLON.VertexBuffer.UVKind);
  71790. defines.push("#define UV1");
  71791. }
  71792. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  71793. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  71794. defines.push("#define UV2");
  71795. }
  71796. }
  71797. // Bones
  71798. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  71799. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  71800. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  71801. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  71802. defines.push("#define BonesPerMesh " + (mesh.skeleton ? (mesh.skeleton.bones.length + 1) : 0));
  71803. }
  71804. else {
  71805. defines.push("#define NUM_BONE_INFLUENCERS 0");
  71806. }
  71807. // Instances
  71808. if (useInstances) {
  71809. defines.push("#define INSTANCES");
  71810. attribs.push("world0");
  71811. attribs.push("world1");
  71812. attribs.push("world2");
  71813. attribs.push("world3");
  71814. }
  71815. // Get correct effect
  71816. var join = defines.join("\n");
  71817. if (this._cachedDefines !== join) {
  71818. this._cachedDefines = join;
  71819. this._volumetricLightScatteringPass = mesh.getScene().getEngine().createEffect({ vertexElement: "depth", fragmentElement: "volumetricLightScatteringPass" }, attribs, ["world", "mBones", "viewProjection", "diffuseMatrix"], ["diffuseSampler"], join);
  71820. }
  71821. return this._volumetricLightScatteringPass.isReady();
  71822. };
  71823. /**
  71824. * Sets the new light position for light scattering effect
  71825. * @param {BABYLON.Vector3} The new custom light position
  71826. */
  71827. VolumetricLightScatteringPostProcess.prototype.setCustomMeshPosition = function (position) {
  71828. this.customMeshPosition = position;
  71829. };
  71830. /**
  71831. * Returns the light position for light scattering effect
  71832. * @return {BABYLON.Vector3} The custom light position
  71833. */
  71834. VolumetricLightScatteringPostProcess.prototype.getCustomMeshPosition = function () {
  71835. return this.customMeshPosition;
  71836. };
  71837. /**
  71838. * Disposes the internal assets and detaches the post-process from the camera
  71839. */
  71840. VolumetricLightScatteringPostProcess.prototype.dispose = function (camera) {
  71841. var rttIndex = camera.getScene().customRenderTargets.indexOf(this._volumetricLightScatteringRTT);
  71842. if (rttIndex !== -1) {
  71843. camera.getScene().customRenderTargets.splice(rttIndex, 1);
  71844. }
  71845. this._volumetricLightScatteringRTT.dispose();
  71846. _super.prototype.dispose.call(this, camera);
  71847. };
  71848. /**
  71849. * Returns the render target texture used by the post-process
  71850. * @return {BABYLON.RenderTargetTexture} The render target texture used by the post-process
  71851. */
  71852. VolumetricLightScatteringPostProcess.prototype.getPass = function () {
  71853. return this._volumetricLightScatteringRTT;
  71854. };
  71855. // Private methods
  71856. VolumetricLightScatteringPostProcess.prototype._meshExcluded = function (mesh) {
  71857. if (this.excludedMeshes.length > 0 && this.excludedMeshes.indexOf(mesh) !== -1) {
  71858. return true;
  71859. }
  71860. return false;
  71861. };
  71862. VolumetricLightScatteringPostProcess.prototype._createPass = function (scene, ratio) {
  71863. var _this = this;
  71864. var engine = scene.getEngine();
  71865. this._volumetricLightScatteringRTT = new BABYLON.RenderTargetTexture("volumetricLightScatteringMap", { width: engine.getRenderWidth() * ratio, height: engine.getRenderHeight() * ratio }, scene, false, true, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  71866. this._volumetricLightScatteringRTT.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  71867. this._volumetricLightScatteringRTT.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  71868. this._volumetricLightScatteringRTT.renderList = null;
  71869. this._volumetricLightScatteringRTT.renderParticles = false;
  71870. this._volumetricLightScatteringRTT.ignoreCameraViewport = true;
  71871. var camera = this.getCamera();
  71872. if (camera) {
  71873. camera.customRenderTargets.push(this._volumetricLightScatteringRTT);
  71874. }
  71875. else {
  71876. scene.customRenderTargets.push(this._volumetricLightScatteringRTT);
  71877. }
  71878. // Custom render function for submeshes
  71879. var renderSubMesh = function (subMesh) {
  71880. var mesh = subMesh.getRenderingMesh();
  71881. if (_this._meshExcluded(mesh)) {
  71882. return;
  71883. }
  71884. var material = subMesh.getMaterial();
  71885. if (!material) {
  71886. return;
  71887. }
  71888. var scene = mesh.getScene();
  71889. var engine = scene.getEngine();
  71890. // Culling
  71891. engine.setState(material.backFaceCulling);
  71892. // Managing instances
  71893. var batch = mesh._getInstancesRenderList(subMesh._id);
  71894. if (batch.mustReturn) {
  71895. return;
  71896. }
  71897. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null);
  71898. if (_this._isReady(subMesh, hardwareInstancedRendering)) {
  71899. var effect = _this._volumetricLightScatteringPass;
  71900. if (mesh === _this.mesh) {
  71901. if (subMesh.effect) {
  71902. effect = subMesh.effect;
  71903. }
  71904. else {
  71905. effect = material.getEffect();
  71906. }
  71907. }
  71908. engine.enableEffect(effect);
  71909. mesh._bind(subMesh, effect, BABYLON.Material.TriangleFillMode);
  71910. if (mesh === _this.mesh) {
  71911. material.bind(mesh.getWorldMatrix(), mesh);
  71912. }
  71913. else {
  71914. _this._volumetricLightScatteringPass.setMatrix("viewProjection", scene.getTransformMatrix());
  71915. // Alpha test
  71916. if (material && material.needAlphaTesting()) {
  71917. var alphaTexture = material.getAlphaTestTexture();
  71918. _this._volumetricLightScatteringPass.setTexture("diffuseSampler", alphaTexture);
  71919. if (alphaTexture) {
  71920. _this._volumetricLightScatteringPass.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  71921. }
  71922. }
  71923. // Bones
  71924. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  71925. _this._volumetricLightScatteringPass.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  71926. }
  71927. }
  71928. // Draw
  71929. mesh._processRendering(subMesh, _this._volumetricLightScatteringPass, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return effect.setMatrix("world", world); });
  71930. }
  71931. };
  71932. // Render target texture callbacks
  71933. var savedSceneClearColor;
  71934. var sceneClearColor = new BABYLON.Color4(0.0, 0.0, 0.0, 1.0);
  71935. this._volumetricLightScatteringRTT.onBeforeRenderObservable.add(function () {
  71936. savedSceneClearColor = scene.clearColor;
  71937. scene.clearColor = sceneClearColor;
  71938. });
  71939. this._volumetricLightScatteringRTT.onAfterRenderObservable.add(function () {
  71940. scene.clearColor = savedSceneClearColor;
  71941. });
  71942. this._volumetricLightScatteringRTT.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes) {
  71943. var engine = scene.getEngine();
  71944. var index;
  71945. if (depthOnlySubMeshes.length) {
  71946. engine.setColorWrite(false);
  71947. for (index = 0; index < depthOnlySubMeshes.length; index++) {
  71948. renderSubMesh(depthOnlySubMeshes.data[index]);
  71949. }
  71950. engine.setColorWrite(true);
  71951. }
  71952. for (index = 0; index < opaqueSubMeshes.length; index++) {
  71953. renderSubMesh(opaqueSubMeshes.data[index]);
  71954. }
  71955. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  71956. renderSubMesh(alphaTestSubMeshes.data[index]);
  71957. }
  71958. if (transparentSubMeshes.length) {
  71959. // Sort sub meshes
  71960. for (index = 0; index < transparentSubMeshes.length; index++) {
  71961. var submesh = transparentSubMeshes.data[index];
  71962. var boundingInfo = submesh.getBoundingInfo();
  71963. if (boundingInfo && scene.activeCamera) {
  71964. submesh._alphaIndex = submesh.getMesh().alphaIndex;
  71965. submesh._distanceToCamera = boundingInfo.boundingSphere.centerWorld.subtract(scene.activeCamera.position).length();
  71966. }
  71967. }
  71968. var sortedArray = transparentSubMeshes.data.slice(0, transparentSubMeshes.length);
  71969. sortedArray.sort(function (a, b) {
  71970. // Alpha index first
  71971. if (a._alphaIndex > b._alphaIndex) {
  71972. return 1;
  71973. }
  71974. if (a._alphaIndex < b._alphaIndex) {
  71975. return -1;
  71976. }
  71977. // Then distance to camera
  71978. if (a._distanceToCamera < b._distanceToCamera) {
  71979. return 1;
  71980. }
  71981. if (a._distanceToCamera > b._distanceToCamera) {
  71982. return -1;
  71983. }
  71984. return 0;
  71985. });
  71986. // Render sub meshes
  71987. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  71988. for (index = 0; index < sortedArray.length; index++) {
  71989. renderSubMesh(sortedArray[index]);
  71990. }
  71991. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  71992. }
  71993. };
  71994. };
  71995. VolumetricLightScatteringPostProcess.prototype._updateMeshScreenCoordinates = function (scene) {
  71996. var transform = scene.getTransformMatrix();
  71997. var meshPosition;
  71998. if (this.useCustomMeshPosition) {
  71999. meshPosition = this.customMeshPosition;
  72000. }
  72001. else if (this.attachedNode) {
  72002. meshPosition = this.attachedNode.position;
  72003. }
  72004. else {
  72005. meshPosition = this.mesh.parent ? this.mesh.getAbsolutePosition() : this.mesh.position;
  72006. }
  72007. var pos = BABYLON.Vector3.Project(meshPosition, BABYLON.Matrix.Identity(), transform, this._viewPort);
  72008. this._screenCoordinates.x = pos.x / this._viewPort.width;
  72009. this._screenCoordinates.y = pos.y / this._viewPort.height;
  72010. if (this.invert)
  72011. this._screenCoordinates.y = 1.0 - this._screenCoordinates.y;
  72012. };
  72013. // Static methods
  72014. /**
  72015. * Creates a default mesh for the Volumeric Light Scattering post-process
  72016. * @param {string} The mesh name
  72017. * @param {BABYLON.Scene} The scene where to create the mesh
  72018. * @return {BABYLON.Mesh} the default mesh
  72019. */
  72020. VolumetricLightScatteringPostProcess.CreateDefaultMesh = function (name, scene) {
  72021. var mesh = BABYLON.Mesh.CreatePlane(name, 1, scene);
  72022. mesh.billboardMode = BABYLON.AbstractMesh.BILLBOARDMODE_ALL;
  72023. var material = new BABYLON.StandardMaterial(name + "Material", scene);
  72024. material.emissiveColor = new BABYLON.Color3(1, 1, 1);
  72025. mesh.material = material;
  72026. return mesh;
  72027. };
  72028. __decorate([
  72029. BABYLON.serializeAsVector3()
  72030. ], VolumetricLightScatteringPostProcess.prototype, "customMeshPosition", void 0);
  72031. __decorate([
  72032. BABYLON.serialize()
  72033. ], VolumetricLightScatteringPostProcess.prototype, "useCustomMeshPosition", void 0);
  72034. __decorate([
  72035. BABYLON.serialize()
  72036. ], VolumetricLightScatteringPostProcess.prototype, "invert", void 0);
  72037. __decorate([
  72038. BABYLON.serializeAsMeshReference()
  72039. ], VolumetricLightScatteringPostProcess.prototype, "mesh", void 0);
  72040. __decorate([
  72041. BABYLON.serialize()
  72042. ], VolumetricLightScatteringPostProcess.prototype, "excludedMeshes", void 0);
  72043. __decorate([
  72044. BABYLON.serialize()
  72045. ], VolumetricLightScatteringPostProcess.prototype, "exposure", void 0);
  72046. __decorate([
  72047. BABYLON.serialize()
  72048. ], VolumetricLightScatteringPostProcess.prototype, "decay", void 0);
  72049. __decorate([
  72050. BABYLON.serialize()
  72051. ], VolumetricLightScatteringPostProcess.prototype, "weight", void 0);
  72052. __decorate([
  72053. BABYLON.serialize()
  72054. ], VolumetricLightScatteringPostProcess.prototype, "density", void 0);
  72055. return VolumetricLightScatteringPostProcess;
  72056. }(BABYLON.PostProcess));
  72057. BABYLON.VolumetricLightScatteringPostProcess = VolumetricLightScatteringPostProcess;
  72058. })(BABYLON || (BABYLON = {}));
  72059. //# sourceMappingURL=babylon.volumetricLightScatteringPostProcess.js.map
  72060. "use strict";
  72061. //
  72062. // This post-process allows the modification of rendered colors by using
  72063. // a 'look-up table' (LUT). This effect is also called Color Grading.
  72064. //
  72065. // The object needs to be provided an url to a texture containing the color
  72066. // look-up table: the texture must be 256 pixels wide and 16 pixels high.
  72067. // Use an image editing software to tweak the LUT to match your needs.
  72068. //
  72069. // For an example of a color LUT, see here:
  72070. // http://udn.epicgames.com/Three/rsrc/Three/ColorGrading/RGBTable16x1.png
  72071. // For explanations on color grading, see here:
  72072. // http://udn.epicgames.com/Three/ColorGrading.html
  72073. //
  72074. var BABYLON;
  72075. (function (BABYLON) {
  72076. var ColorCorrectionPostProcess = /** @class */ (function (_super) {
  72077. __extends(ColorCorrectionPostProcess, _super);
  72078. function ColorCorrectionPostProcess(name, colorTableUrl, options, camera, samplingMode, engine, reusable) {
  72079. var _this = _super.call(this, name, 'colorCorrection', null, ['colorTable'], options, camera, samplingMode, engine, reusable) || this;
  72080. _this._colorTableTexture = new BABYLON.Texture(colorTableUrl, camera.getScene(), true, false, BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  72081. _this._colorTableTexture.anisotropicFilteringLevel = 1;
  72082. _this._colorTableTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  72083. _this._colorTableTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  72084. _this.onApply = function (effect) {
  72085. effect.setTexture("colorTable", _this._colorTableTexture);
  72086. };
  72087. return _this;
  72088. }
  72089. return ColorCorrectionPostProcess;
  72090. }(BABYLON.PostProcess));
  72091. BABYLON.ColorCorrectionPostProcess = ColorCorrectionPostProcess;
  72092. })(BABYLON || (BABYLON = {}));
  72093. //# sourceMappingURL=babylon.colorCorrectionPostProcess.js.map
  72094. "use strict";
  72095. var BABYLON;
  72096. (function (BABYLON) {
  72097. var TonemappingOperator;
  72098. (function (TonemappingOperator) {
  72099. TonemappingOperator[TonemappingOperator["Hable"] = 0] = "Hable";
  72100. TonemappingOperator[TonemappingOperator["Reinhard"] = 1] = "Reinhard";
  72101. TonemappingOperator[TonemappingOperator["HejiDawson"] = 2] = "HejiDawson";
  72102. TonemappingOperator[TonemappingOperator["Photographic"] = 3] = "Photographic";
  72103. })(TonemappingOperator = BABYLON.TonemappingOperator || (BABYLON.TonemappingOperator = {}));
  72104. ;
  72105. var TonemapPostProcess = /** @class */ (function (_super) {
  72106. __extends(TonemapPostProcess, _super);
  72107. function TonemapPostProcess(name, _operator, exposureAdjustment, camera, samplingMode, engine, textureFormat) {
  72108. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  72109. if (textureFormat === void 0) { textureFormat = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  72110. var _this = _super.call(this, name, "tonemap", ["_ExposureAdjustment"], null, 1.0, camera, samplingMode, engine, true, null, textureFormat) || this;
  72111. _this._operator = _operator;
  72112. _this.exposureAdjustment = exposureAdjustment;
  72113. var defines = "#define ";
  72114. if (_this._operator === TonemappingOperator.Hable)
  72115. defines += "HABLE_TONEMAPPING";
  72116. else if (_this._operator === TonemappingOperator.Reinhard)
  72117. defines += "REINHARD_TONEMAPPING";
  72118. else if (_this._operator === TonemappingOperator.HejiDawson)
  72119. defines += "OPTIMIZED_HEJIDAWSON_TONEMAPPING";
  72120. else if (_this._operator === TonemappingOperator.Photographic)
  72121. defines += "PHOTOGRAPHIC_TONEMAPPING";
  72122. //sadly a second call to create the effect.
  72123. _this.updateEffect(defines);
  72124. _this.onApply = function (effect) {
  72125. effect.setFloat("_ExposureAdjustment", _this.exposureAdjustment);
  72126. };
  72127. return _this;
  72128. }
  72129. return TonemapPostProcess;
  72130. }(BABYLON.PostProcess));
  72131. BABYLON.TonemapPostProcess = TonemapPostProcess;
  72132. })(BABYLON || (BABYLON = {}));
  72133. //# sourceMappingURL=babylon.tonemapPostProcess.js.map
  72134. "use strict";
  72135. var BABYLON;
  72136. (function (BABYLON) {
  72137. var DisplayPassPostProcess = /** @class */ (function (_super) {
  72138. __extends(DisplayPassPostProcess, _super);
  72139. function DisplayPassPostProcess(name, options, camera, samplingMode, engine, reusable) {
  72140. return _super.call(this, name, "displayPass", ["passSampler"], ["passSampler"], options, camera, samplingMode, engine, reusable) || this;
  72141. }
  72142. return DisplayPassPostProcess;
  72143. }(BABYLON.PostProcess));
  72144. BABYLON.DisplayPassPostProcess = DisplayPassPostProcess;
  72145. })(BABYLON || (BABYLON = {}));
  72146. //# sourceMappingURL=babylon.displayPassPostProcess.js.map
  72147. "use strict";
  72148. var BABYLON;
  72149. (function (BABYLON) {
  72150. var HighlightsPostProcess = /** @class */ (function (_super) {
  72151. __extends(HighlightsPostProcess, _super);
  72152. function HighlightsPostProcess(name, options, camera, samplingMode, engine, reusable, textureType) {
  72153. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  72154. return _super.call(this, name, "highlights", null, null, options, camera, samplingMode, engine, reusable, null, textureType) || this;
  72155. }
  72156. return HighlightsPostProcess;
  72157. }(BABYLON.PostProcess));
  72158. BABYLON.HighlightsPostProcess = HighlightsPostProcess;
  72159. })(BABYLON || (BABYLON = {}));
  72160. //# sourceMappingURL=babylon.highlightsPostProcess.js.map
  72161. "use strict";
  72162. var BABYLON;
  72163. (function (BABYLON) {
  72164. var ImageProcessingPostProcess = /** @class */ (function (_super) {
  72165. __extends(ImageProcessingPostProcess, _super);
  72166. function ImageProcessingPostProcess(name, options, camera, samplingMode, engine, reusable, textureType, imageProcessingConfiguration) {
  72167. if (camera === void 0) { camera = null; }
  72168. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  72169. var _this = _super.call(this, name, "imageProcessing", [], [], options, camera, samplingMode, engine, reusable, null, textureType, "postprocess", null, true) || this;
  72170. _this._fromLinearSpace = true;
  72171. /**
  72172. * Defines cache preventing GC.
  72173. */
  72174. _this._defines = {
  72175. IMAGEPROCESSING: false,
  72176. VIGNETTE: false,
  72177. VIGNETTEBLENDMODEMULTIPLY: false,
  72178. VIGNETTEBLENDMODEOPAQUE: false,
  72179. TONEMAPPING: false,
  72180. CONTRAST: false,
  72181. COLORCURVES: false,
  72182. COLORGRADING: false,
  72183. COLORGRADING3D: false,
  72184. FROMLINEARSPACE: false,
  72185. SAMPLER3DGREENDEPTH: false,
  72186. SAMPLER3DBGRMAP: false,
  72187. IMAGEPROCESSINGPOSTPROCESS: false,
  72188. EXPOSURE: false,
  72189. };
  72190. // Setup the configuration as forced by the constructor. This would then not force the
  72191. // scene materials output in linear space and let untouched the default forward pass.
  72192. if (imageProcessingConfiguration) {
  72193. imageProcessingConfiguration.applyByPostProcess = true;
  72194. _this._attachImageProcessingConfiguration(imageProcessingConfiguration, true);
  72195. // This will cause the shader to be compiled
  72196. _this.fromLinearSpace = false;
  72197. }
  72198. else {
  72199. _this._attachImageProcessingConfiguration(null, true);
  72200. _this.imageProcessingConfiguration.applyByPostProcess = true;
  72201. }
  72202. _this.onApply = function (effect) {
  72203. _this.imageProcessingConfiguration.bind(effect, _this.aspectRatio);
  72204. };
  72205. return _this;
  72206. }
  72207. Object.defineProperty(ImageProcessingPostProcess.prototype, "imageProcessingConfiguration", {
  72208. /**
  72209. * Gets the image processing configuration used either in this material.
  72210. */
  72211. get: function () {
  72212. return this._imageProcessingConfiguration;
  72213. },
  72214. /**
  72215. * Sets the Default image processing configuration used either in the this material.
  72216. *
  72217. * If sets to null, the scene one is in use.
  72218. */
  72219. set: function (value) {
  72220. this._attachImageProcessingConfiguration(value);
  72221. },
  72222. enumerable: true,
  72223. configurable: true
  72224. });
  72225. /**
  72226. * Attaches a new image processing configuration to the PBR Material.
  72227. * @param configuration
  72228. */
  72229. ImageProcessingPostProcess.prototype._attachImageProcessingConfiguration = function (configuration, doNotBuild) {
  72230. var _this = this;
  72231. if (doNotBuild === void 0) { doNotBuild = false; }
  72232. if (configuration === this._imageProcessingConfiguration) {
  72233. return;
  72234. }
  72235. // Detaches observer.
  72236. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  72237. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  72238. }
  72239. // Pick the scene configuration if needed.
  72240. if (!configuration) {
  72241. var scene = null;
  72242. var engine = this.getEngine();
  72243. var camera = this.getCamera();
  72244. if (camera) {
  72245. scene = camera.getScene();
  72246. }
  72247. else if (engine && engine.scenes) {
  72248. var scenes = engine.scenes;
  72249. scene = scenes[scenes.length - 1];
  72250. }
  72251. else {
  72252. scene = BABYLON.Engine.LastCreatedScene;
  72253. }
  72254. this._imageProcessingConfiguration = scene.imageProcessingConfiguration;
  72255. }
  72256. else {
  72257. this._imageProcessingConfiguration = configuration;
  72258. }
  72259. // Attaches observer.
  72260. this._imageProcessingObserver = this._imageProcessingConfiguration.onUpdateParameters.add(function (conf) {
  72261. _this._updateParameters();
  72262. });
  72263. // Ensure the effect will be rebuilt.
  72264. if (!doNotBuild) {
  72265. this._updateParameters();
  72266. }
  72267. };
  72268. Object.defineProperty(ImageProcessingPostProcess.prototype, "colorCurves", {
  72269. /**
  72270. * Gets Color curves setup used in the effect if colorCurvesEnabled is set to true .
  72271. */
  72272. get: function () {
  72273. return this.imageProcessingConfiguration.colorCurves;
  72274. },
  72275. /**
  72276. * Sets Color curves setup used in the effect if colorCurvesEnabled is set to true .
  72277. */
  72278. set: function (value) {
  72279. this.imageProcessingConfiguration.colorCurves = value;
  72280. },
  72281. enumerable: true,
  72282. configurable: true
  72283. });
  72284. Object.defineProperty(ImageProcessingPostProcess.prototype, "colorCurvesEnabled", {
  72285. /**
  72286. * Gets wether the color curves effect is enabled.
  72287. */
  72288. get: function () {
  72289. return this.imageProcessingConfiguration.colorCurvesEnabled;
  72290. },
  72291. /**
  72292. * Sets wether the color curves effect is enabled.
  72293. */
  72294. set: function (value) {
  72295. this.imageProcessingConfiguration.colorCurvesEnabled = value;
  72296. },
  72297. enumerable: true,
  72298. configurable: true
  72299. });
  72300. Object.defineProperty(ImageProcessingPostProcess.prototype, "colorGradingTexture", {
  72301. /**
  72302. * Gets Color grading LUT texture used in the effect if colorGradingEnabled is set to true.
  72303. */
  72304. get: function () {
  72305. return this.imageProcessingConfiguration.colorGradingTexture;
  72306. },
  72307. /**
  72308. * Sets Color grading LUT texture used in the effect if colorGradingEnabled is set to true.
  72309. */
  72310. set: function (value) {
  72311. this.imageProcessingConfiguration.colorGradingTexture = value;
  72312. },
  72313. enumerable: true,
  72314. configurable: true
  72315. });
  72316. Object.defineProperty(ImageProcessingPostProcess.prototype, "colorGradingEnabled", {
  72317. /**
  72318. * Gets wether the color grading effect is enabled.
  72319. */
  72320. get: function () {
  72321. return this.imageProcessingConfiguration.colorGradingEnabled;
  72322. },
  72323. /**
  72324. * Gets wether the color grading effect is enabled.
  72325. */
  72326. set: function (value) {
  72327. this.imageProcessingConfiguration.colorGradingEnabled = value;
  72328. },
  72329. enumerable: true,
  72330. configurable: true
  72331. });
  72332. Object.defineProperty(ImageProcessingPostProcess.prototype, "exposure", {
  72333. /**
  72334. * Gets exposure used in the effect.
  72335. */
  72336. get: function () {
  72337. return this.imageProcessingConfiguration.exposure;
  72338. },
  72339. /**
  72340. * Sets exposure used in the effect.
  72341. */
  72342. set: function (value) {
  72343. this.imageProcessingConfiguration.exposure = value;
  72344. },
  72345. enumerable: true,
  72346. configurable: true
  72347. });
  72348. Object.defineProperty(ImageProcessingPostProcess.prototype, "toneMappingEnabled", {
  72349. /**
  72350. * Gets wether tonemapping is enabled or not.
  72351. */
  72352. get: function () {
  72353. return this._imageProcessingConfiguration.toneMappingEnabled;
  72354. },
  72355. /**
  72356. * Sets wether tonemapping is enabled or not
  72357. */
  72358. set: function (value) {
  72359. this._imageProcessingConfiguration.toneMappingEnabled = value;
  72360. },
  72361. enumerable: true,
  72362. configurable: true
  72363. });
  72364. ;
  72365. ;
  72366. Object.defineProperty(ImageProcessingPostProcess.prototype, "contrast", {
  72367. /**
  72368. * Gets contrast used in the effect.
  72369. */
  72370. get: function () {
  72371. return this.imageProcessingConfiguration.contrast;
  72372. },
  72373. /**
  72374. * Sets contrast used in the effect.
  72375. */
  72376. set: function (value) {
  72377. this.imageProcessingConfiguration.contrast = value;
  72378. },
  72379. enumerable: true,
  72380. configurable: true
  72381. });
  72382. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteStretch", {
  72383. /**
  72384. * Gets Vignette stretch size.
  72385. */
  72386. get: function () {
  72387. return this.imageProcessingConfiguration.vignetteStretch;
  72388. },
  72389. /**
  72390. * Sets Vignette stretch size.
  72391. */
  72392. set: function (value) {
  72393. this.imageProcessingConfiguration.vignetteStretch = value;
  72394. },
  72395. enumerable: true,
  72396. configurable: true
  72397. });
  72398. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteCentreX", {
  72399. /**
  72400. * Gets Vignette centre X Offset.
  72401. */
  72402. get: function () {
  72403. return this.imageProcessingConfiguration.vignetteCentreX;
  72404. },
  72405. /**
  72406. * Sets Vignette centre X Offset.
  72407. */
  72408. set: function (value) {
  72409. this.imageProcessingConfiguration.vignetteCentreX = value;
  72410. },
  72411. enumerable: true,
  72412. configurable: true
  72413. });
  72414. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteCentreY", {
  72415. /**
  72416. * Gets Vignette centre Y Offset.
  72417. */
  72418. get: function () {
  72419. return this.imageProcessingConfiguration.vignetteCentreY;
  72420. },
  72421. /**
  72422. * Sets Vignette centre Y Offset.
  72423. */
  72424. set: function (value) {
  72425. this.imageProcessingConfiguration.vignetteCentreY = value;
  72426. },
  72427. enumerable: true,
  72428. configurable: true
  72429. });
  72430. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteWeight", {
  72431. /**
  72432. * Gets Vignette weight or intensity of the vignette effect.
  72433. */
  72434. get: function () {
  72435. return this.imageProcessingConfiguration.vignetteWeight;
  72436. },
  72437. /**
  72438. * Sets Vignette weight or intensity of the vignette effect.
  72439. */
  72440. set: function (value) {
  72441. this.imageProcessingConfiguration.vignetteWeight = value;
  72442. },
  72443. enumerable: true,
  72444. configurable: true
  72445. });
  72446. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteColor", {
  72447. /**
  72448. * Gets Color of the vignette applied on the screen through the chosen blend mode (vignetteBlendMode)
  72449. * if vignetteEnabled is set to true.
  72450. */
  72451. get: function () {
  72452. return this.imageProcessingConfiguration.vignetteColor;
  72453. },
  72454. /**
  72455. * Sets Color of the vignette applied on the screen through the chosen blend mode (vignetteBlendMode)
  72456. * if vignetteEnabled is set to true.
  72457. */
  72458. set: function (value) {
  72459. this.imageProcessingConfiguration.vignetteColor = value;
  72460. },
  72461. enumerable: true,
  72462. configurable: true
  72463. });
  72464. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteCameraFov", {
  72465. /**
  72466. * Gets Camera field of view used by the Vignette effect.
  72467. */
  72468. get: function () {
  72469. return this.imageProcessingConfiguration.vignetteCameraFov;
  72470. },
  72471. /**
  72472. * Sets Camera field of view used by the Vignette effect.
  72473. */
  72474. set: function (value) {
  72475. this.imageProcessingConfiguration.vignetteCameraFov = value;
  72476. },
  72477. enumerable: true,
  72478. configurable: true
  72479. });
  72480. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteBlendMode", {
  72481. /**
  72482. * Gets the vignette blend mode allowing different kind of effect.
  72483. */
  72484. get: function () {
  72485. return this.imageProcessingConfiguration.vignetteBlendMode;
  72486. },
  72487. /**
  72488. * Sets the vignette blend mode allowing different kind of effect.
  72489. */
  72490. set: function (value) {
  72491. this.imageProcessingConfiguration.vignetteBlendMode = value;
  72492. },
  72493. enumerable: true,
  72494. configurable: true
  72495. });
  72496. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteEnabled", {
  72497. /**
  72498. * Gets wether the vignette effect is enabled.
  72499. */
  72500. get: function () {
  72501. return this.imageProcessingConfiguration.vignetteEnabled;
  72502. },
  72503. /**
  72504. * Sets wether the vignette effect is enabled.
  72505. */
  72506. set: function (value) {
  72507. this.imageProcessingConfiguration.vignetteEnabled = value;
  72508. },
  72509. enumerable: true,
  72510. configurable: true
  72511. });
  72512. Object.defineProperty(ImageProcessingPostProcess.prototype, "fromLinearSpace", {
  72513. /**
  72514. * Gets wether the input of the processing is in Gamma or Linear Space.
  72515. */
  72516. get: function () {
  72517. return this._fromLinearSpace;
  72518. },
  72519. /**
  72520. * Sets wether the input of the processing is in Gamma or Linear Space.
  72521. */
  72522. set: function (value) {
  72523. if (this._fromLinearSpace === value) {
  72524. return;
  72525. }
  72526. this._fromLinearSpace = value;
  72527. this._updateParameters();
  72528. },
  72529. enumerable: true,
  72530. configurable: true
  72531. });
  72532. ImageProcessingPostProcess.prototype.getClassName = function () {
  72533. return "ImageProcessingPostProcess";
  72534. };
  72535. ImageProcessingPostProcess.prototype._updateParameters = function () {
  72536. this._defines.FROMLINEARSPACE = this._fromLinearSpace;
  72537. this.imageProcessingConfiguration.prepareDefines(this._defines, true);
  72538. var defines = "";
  72539. for (var define in this._defines) {
  72540. if (this._defines[define]) {
  72541. defines += "#define " + define + ";\r\n";
  72542. }
  72543. }
  72544. var samplers = ["textureSampler"];
  72545. BABYLON.ImageProcessingConfiguration.PrepareSamplers(samplers, this._defines);
  72546. var uniforms = ["scale"];
  72547. BABYLON.ImageProcessingConfiguration.PrepareUniforms(uniforms, this._defines);
  72548. this.updateEffect(defines, uniforms, samplers);
  72549. };
  72550. ImageProcessingPostProcess.prototype.dispose = function (camera) {
  72551. _super.prototype.dispose.call(this, camera);
  72552. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  72553. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  72554. }
  72555. this.imageProcessingConfiguration.applyByPostProcess = false;
  72556. };
  72557. __decorate([
  72558. BABYLON.serialize()
  72559. ], ImageProcessingPostProcess.prototype, "_fromLinearSpace", void 0);
  72560. return ImageProcessingPostProcess;
  72561. }(BABYLON.PostProcess));
  72562. BABYLON.ImageProcessingPostProcess = ImageProcessingPostProcess;
  72563. })(BABYLON || (BABYLON = {}));
  72564. //# sourceMappingURL=babylon.imageProcessingPostProcess.js.map
  72565. "use strict";
  72566. var BABYLON;
  72567. (function (BABYLON) {
  72568. var Bone = /** @class */ (function (_super) {
  72569. __extends(Bone, _super);
  72570. function Bone(name, skeleton, parentBone, localMatrix, restPose, baseMatrix, index) {
  72571. if (parentBone === void 0) { parentBone = null; }
  72572. if (localMatrix === void 0) { localMatrix = null; }
  72573. if (restPose === void 0) { restPose = null; }
  72574. if (baseMatrix === void 0) { baseMatrix = null; }
  72575. if (index === void 0) { index = null; }
  72576. var _this = _super.call(this, name, skeleton.getScene()) || this;
  72577. _this.name = name;
  72578. _this.children = new Array();
  72579. _this.animations = new Array();
  72580. // Set this value to map this bone to a different index in the transform matrices.
  72581. // Set this value to -1 to exclude the bone from the transform matrices.
  72582. _this._index = null;
  72583. _this._worldTransform = new BABYLON.Matrix();
  72584. _this._absoluteTransform = new BABYLON.Matrix();
  72585. _this._invertedAbsoluteTransform = new BABYLON.Matrix();
  72586. _this._scaleMatrix = BABYLON.Matrix.Identity();
  72587. _this._scaleVector = BABYLON.Vector3.One();
  72588. _this._negateScaleChildren = BABYLON.Vector3.One();
  72589. _this._scalingDeterminant = 1;
  72590. _this._skeleton = skeleton;
  72591. _this._localMatrix = localMatrix ? localMatrix : BABYLON.Matrix.Identity();
  72592. _this._restPose = restPose ? restPose : _this._localMatrix.clone();
  72593. _this._baseMatrix = baseMatrix ? baseMatrix : _this._localMatrix.clone();
  72594. _this._index = index;
  72595. skeleton.bones.push(_this);
  72596. _this.setParent(parentBone, false);
  72597. _this._updateDifferenceMatrix();
  72598. return _this;
  72599. }
  72600. Object.defineProperty(Bone.prototype, "_matrix", {
  72601. get: function () {
  72602. return this._localMatrix;
  72603. },
  72604. set: function (val) {
  72605. if (this._localMatrix) {
  72606. this._localMatrix.copyFrom(val);
  72607. }
  72608. else {
  72609. this._localMatrix = val;
  72610. }
  72611. },
  72612. enumerable: true,
  72613. configurable: true
  72614. });
  72615. // Members
  72616. Bone.prototype.getSkeleton = function () {
  72617. return this._skeleton;
  72618. };
  72619. Bone.prototype.getParent = function () {
  72620. return this._parent;
  72621. };
  72622. Bone.prototype.setParent = function (parent, updateDifferenceMatrix) {
  72623. if (updateDifferenceMatrix === void 0) { updateDifferenceMatrix = true; }
  72624. if (this._parent === parent) {
  72625. return;
  72626. }
  72627. if (this._parent) {
  72628. var index = this._parent.children.indexOf(this);
  72629. if (index !== -1) {
  72630. this._parent.children.splice(index, 1);
  72631. }
  72632. }
  72633. this._parent = parent;
  72634. if (this._parent) {
  72635. this._parent.children.push(this);
  72636. }
  72637. if (updateDifferenceMatrix) {
  72638. this._updateDifferenceMatrix();
  72639. }
  72640. };
  72641. Bone.prototype.getLocalMatrix = function () {
  72642. return this._localMatrix;
  72643. };
  72644. Bone.prototype.getBaseMatrix = function () {
  72645. return this._baseMatrix;
  72646. };
  72647. Bone.prototype.getRestPose = function () {
  72648. return this._restPose;
  72649. };
  72650. Bone.prototype.returnToRest = function () {
  72651. this.updateMatrix(this._restPose.clone());
  72652. };
  72653. Bone.prototype.getWorldMatrix = function () {
  72654. return this._worldTransform;
  72655. };
  72656. Bone.prototype.getInvertedAbsoluteTransform = function () {
  72657. return this._invertedAbsoluteTransform;
  72658. };
  72659. Bone.prototype.getAbsoluteTransform = function () {
  72660. return this._absoluteTransform;
  72661. };
  72662. Object.defineProperty(Bone.prototype, "position", {
  72663. // Properties (matches AbstractMesh properties)
  72664. get: function () {
  72665. return this.getPosition();
  72666. },
  72667. set: function (newPosition) {
  72668. this.setPosition(newPosition);
  72669. },
  72670. enumerable: true,
  72671. configurable: true
  72672. });
  72673. Object.defineProperty(Bone.prototype, "rotation", {
  72674. get: function () {
  72675. return this.getRotation();
  72676. },
  72677. set: function (newRotation) {
  72678. this.setRotation(newRotation);
  72679. },
  72680. enumerable: true,
  72681. configurable: true
  72682. });
  72683. Object.defineProperty(Bone.prototype, "rotationQuaternion", {
  72684. get: function () {
  72685. return this.getRotationQuaternion();
  72686. },
  72687. set: function (newRotation) {
  72688. this.setRotationQuaternion(newRotation);
  72689. },
  72690. enumerable: true,
  72691. configurable: true
  72692. });
  72693. Object.defineProperty(Bone.prototype, "scaling", {
  72694. get: function () {
  72695. return this.getScale();
  72696. },
  72697. set: function (newScaling) {
  72698. this.setScale(newScaling.x, newScaling.y, newScaling.z);
  72699. },
  72700. enumerable: true,
  72701. configurable: true
  72702. });
  72703. Object.defineProperty(Bone.prototype, "animationPropertiesOverride", {
  72704. /**
  72705. * Gets the animation properties override
  72706. */
  72707. get: function () {
  72708. return this._skeleton.animationPropertiesOverride;
  72709. },
  72710. enumerable: true,
  72711. configurable: true
  72712. });
  72713. // Methods
  72714. Bone.prototype.updateMatrix = function (matrix, updateDifferenceMatrix) {
  72715. if (updateDifferenceMatrix === void 0) { updateDifferenceMatrix = true; }
  72716. this._baseMatrix = matrix.clone();
  72717. this._localMatrix = matrix.clone();
  72718. this._skeleton._markAsDirty();
  72719. if (updateDifferenceMatrix) {
  72720. this._updateDifferenceMatrix();
  72721. }
  72722. };
  72723. Bone.prototype._updateDifferenceMatrix = function (rootMatrix) {
  72724. if (!rootMatrix) {
  72725. rootMatrix = this._baseMatrix;
  72726. }
  72727. if (this._parent) {
  72728. rootMatrix.multiplyToRef(this._parent._absoluteTransform, this._absoluteTransform);
  72729. }
  72730. else {
  72731. this._absoluteTransform.copyFrom(rootMatrix);
  72732. }
  72733. this._absoluteTransform.invertToRef(this._invertedAbsoluteTransform);
  72734. for (var index = 0; index < this.children.length; index++) {
  72735. this.children[index]._updateDifferenceMatrix();
  72736. }
  72737. this._scalingDeterminant = (this._absoluteTransform.determinant() < 0 ? -1 : 1);
  72738. };
  72739. Bone.prototype.markAsDirty = function () {
  72740. this._currentRenderId++;
  72741. this._childRenderId++;
  72742. this._skeleton._markAsDirty();
  72743. };
  72744. Bone.prototype.copyAnimationRange = function (source, rangeName, frameOffset, rescaleAsRequired, skelDimensionsRatio) {
  72745. if (rescaleAsRequired === void 0) { rescaleAsRequired = false; }
  72746. if (skelDimensionsRatio === void 0) { skelDimensionsRatio = null; }
  72747. // all animation may be coming from a library skeleton, so may need to create animation
  72748. if (this.animations.length === 0) {
  72749. this.animations.push(new BABYLON.Animation(this.name, "_matrix", source.animations[0].framePerSecond, BABYLON.Animation.ANIMATIONTYPE_MATRIX, 0));
  72750. this.animations[0].setKeys([]);
  72751. }
  72752. // get animation info / verify there is such a range from the source bone
  72753. var sourceRange = source.animations[0].getRange(rangeName);
  72754. if (!sourceRange) {
  72755. return false;
  72756. }
  72757. var from = sourceRange.from;
  72758. var to = sourceRange.to;
  72759. var sourceKeys = source.animations[0].getKeys();
  72760. // rescaling prep
  72761. var sourceBoneLength = source.length;
  72762. var sourceParent = source.getParent();
  72763. var parent = this.getParent();
  72764. var parentScalingReqd = rescaleAsRequired && sourceParent && sourceBoneLength && this.length && sourceBoneLength !== this.length;
  72765. var parentRatio = parentScalingReqd && parent && sourceParent ? parent.length / sourceParent.length : 1;
  72766. var dimensionsScalingReqd = rescaleAsRequired && !parent && skelDimensionsRatio && (skelDimensionsRatio.x !== 1 || skelDimensionsRatio.y !== 1 || skelDimensionsRatio.z !== 1);
  72767. var destKeys = this.animations[0].getKeys();
  72768. // loop vars declaration
  72769. var orig;
  72770. var origTranslation;
  72771. var mat;
  72772. for (var key = 0, nKeys = sourceKeys.length; key < nKeys; key++) {
  72773. orig = sourceKeys[key];
  72774. if (orig.frame >= from && orig.frame <= to) {
  72775. if (rescaleAsRequired) {
  72776. mat = orig.value.clone();
  72777. // scale based on parent ratio, when bone has parent
  72778. if (parentScalingReqd) {
  72779. origTranslation = mat.getTranslation();
  72780. mat.setTranslation(origTranslation.scaleInPlace(parentRatio));
  72781. // scale based on skeleton dimension ratio when root bone, and value is passed
  72782. }
  72783. else if (dimensionsScalingReqd && skelDimensionsRatio) {
  72784. origTranslation = mat.getTranslation();
  72785. mat.setTranslation(origTranslation.multiplyInPlace(skelDimensionsRatio));
  72786. // use original when root bone, and no data for skelDimensionsRatio
  72787. }
  72788. else {
  72789. mat = orig.value;
  72790. }
  72791. }
  72792. else {
  72793. mat = orig.value;
  72794. }
  72795. destKeys.push({ frame: orig.frame + frameOffset, value: mat });
  72796. }
  72797. }
  72798. this.animations[0].createRange(rangeName, from + frameOffset, to + frameOffset);
  72799. return true;
  72800. };
  72801. /**
  72802. * Translate the bone in local or world space.
  72803. * @param vec The amount to translate the bone.
  72804. * @param space The space that the translation is in.
  72805. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  72806. */
  72807. Bone.prototype.translate = function (vec, space, mesh) {
  72808. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  72809. var lm = this.getLocalMatrix();
  72810. if (space == BABYLON.Space.LOCAL) {
  72811. lm.m[12] += vec.x;
  72812. lm.m[13] += vec.y;
  72813. lm.m[14] += vec.z;
  72814. }
  72815. else {
  72816. var wm = null;
  72817. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  72818. if (mesh) {
  72819. wm = mesh.getWorldMatrix();
  72820. }
  72821. this._skeleton.computeAbsoluteTransforms();
  72822. var tmat = Bone._tmpMats[0];
  72823. var tvec = Bone._tmpVecs[0];
  72824. if (this._parent) {
  72825. if (mesh && wm) {
  72826. tmat.copyFrom(this._parent.getAbsoluteTransform());
  72827. tmat.multiplyToRef(wm, tmat);
  72828. }
  72829. else {
  72830. tmat.copyFrom(this._parent.getAbsoluteTransform());
  72831. }
  72832. }
  72833. tmat.m[12] = 0;
  72834. tmat.m[13] = 0;
  72835. tmat.m[14] = 0;
  72836. tmat.invert();
  72837. BABYLON.Vector3.TransformCoordinatesToRef(vec, tmat, tvec);
  72838. lm.m[12] += tvec.x;
  72839. lm.m[13] += tvec.y;
  72840. lm.m[14] += tvec.z;
  72841. }
  72842. this.markAsDirty();
  72843. };
  72844. /**
  72845. * Set the postion of the bone in local or world space.
  72846. * @param position The position to set the bone.
  72847. * @param space The space that the position is in.
  72848. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  72849. */
  72850. Bone.prototype.setPosition = function (position, space, mesh) {
  72851. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  72852. var lm = this.getLocalMatrix();
  72853. if (space == BABYLON.Space.LOCAL) {
  72854. lm.m[12] = position.x;
  72855. lm.m[13] = position.y;
  72856. lm.m[14] = position.z;
  72857. }
  72858. else {
  72859. var wm = null;
  72860. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  72861. if (mesh) {
  72862. wm = mesh.getWorldMatrix();
  72863. }
  72864. this._skeleton.computeAbsoluteTransforms();
  72865. var tmat = Bone._tmpMats[0];
  72866. var vec = Bone._tmpVecs[0];
  72867. if (this._parent) {
  72868. if (mesh && wm) {
  72869. tmat.copyFrom(this._parent.getAbsoluteTransform());
  72870. tmat.multiplyToRef(wm, tmat);
  72871. }
  72872. else {
  72873. tmat.copyFrom(this._parent.getAbsoluteTransform());
  72874. }
  72875. }
  72876. tmat.invert();
  72877. BABYLON.Vector3.TransformCoordinatesToRef(position, tmat, vec);
  72878. lm.m[12] = vec.x;
  72879. lm.m[13] = vec.y;
  72880. lm.m[14] = vec.z;
  72881. }
  72882. this.markAsDirty();
  72883. };
  72884. /**
  72885. * Set the absolute postion of the bone (world space).
  72886. * @param position The position to set the bone.
  72887. * @param mesh The mesh that this bone is attached to.
  72888. */
  72889. Bone.prototype.setAbsolutePosition = function (position, mesh) {
  72890. this.setPosition(position, BABYLON.Space.WORLD, mesh);
  72891. };
  72892. /**
  72893. * Set the scale of the bone on the x, y and z axes.
  72894. * @param x The scale of the bone on the x axis.
  72895. * @param x The scale of the bone on the y axis.
  72896. * @param z The scale of the bone on the z axis.
  72897. * @param scaleChildren Set this to true if children of the bone should be scaled.
  72898. */
  72899. Bone.prototype.setScale = function (x, y, z, scaleChildren) {
  72900. if (scaleChildren === void 0) { scaleChildren = false; }
  72901. if (this.animations[0] && !this.animations[0].hasRunningRuntimeAnimations) {
  72902. if (!scaleChildren) {
  72903. this._negateScaleChildren.x = 1 / x;
  72904. this._negateScaleChildren.y = 1 / y;
  72905. this._negateScaleChildren.z = 1 / z;
  72906. }
  72907. this._syncScaleVector();
  72908. }
  72909. this.scale(x / this._scaleVector.x, y / this._scaleVector.y, z / this._scaleVector.z, scaleChildren);
  72910. };
  72911. /**
  72912. * Scale the bone on the x, y and z axes.
  72913. * @param x The amount to scale the bone on the x axis.
  72914. * @param x The amount to scale the bone on the y axis.
  72915. * @param z The amount to scale the bone on the z axis.
  72916. * @param scaleChildren Set this to true if children of the bone should be scaled.
  72917. */
  72918. Bone.prototype.scale = function (x, y, z, scaleChildren) {
  72919. if (scaleChildren === void 0) { scaleChildren = false; }
  72920. var locMat = this.getLocalMatrix();
  72921. var origLocMat = Bone._tmpMats[0];
  72922. origLocMat.copyFrom(locMat);
  72923. var origLocMatInv = Bone._tmpMats[1];
  72924. origLocMatInv.copyFrom(origLocMat);
  72925. origLocMatInv.invert();
  72926. var scaleMat = Bone._tmpMats[2];
  72927. BABYLON.Matrix.FromValuesToRef(x, 0, 0, 0, 0, y, 0, 0, 0, 0, z, 0, 0, 0, 0, 1, scaleMat);
  72928. this._scaleMatrix.multiplyToRef(scaleMat, this._scaleMatrix);
  72929. this._scaleVector.x *= x;
  72930. this._scaleVector.y *= y;
  72931. this._scaleVector.z *= z;
  72932. locMat.multiplyToRef(origLocMatInv, locMat);
  72933. locMat.multiplyToRef(scaleMat, locMat);
  72934. locMat.multiplyToRef(origLocMat, locMat);
  72935. var parent = this.getParent();
  72936. if (parent) {
  72937. locMat.multiplyToRef(parent.getAbsoluteTransform(), this.getAbsoluteTransform());
  72938. }
  72939. else {
  72940. this.getAbsoluteTransform().copyFrom(locMat);
  72941. }
  72942. var len = this.children.length;
  72943. scaleMat.invert();
  72944. for (var i = 0; i < len; i++) {
  72945. var child = this.children[i];
  72946. var cm = child.getLocalMatrix();
  72947. cm.multiplyToRef(scaleMat, cm);
  72948. var lm = child.getLocalMatrix();
  72949. lm.m[12] *= x;
  72950. lm.m[13] *= y;
  72951. lm.m[14] *= z;
  72952. }
  72953. this.computeAbsoluteTransforms();
  72954. if (scaleChildren) {
  72955. for (var i = 0; i < len; i++) {
  72956. this.children[i].scale(x, y, z, scaleChildren);
  72957. }
  72958. }
  72959. this.markAsDirty();
  72960. };
  72961. /**
  72962. * Set the yaw, pitch, and roll of the bone in local or world space.
  72963. * @param yaw The rotation of the bone on the y axis.
  72964. * @param pitch The rotation of the bone on the x axis.
  72965. * @param roll The rotation of the bone on the z axis.
  72966. * @param space The space that the axes of rotation are in.
  72967. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  72968. */
  72969. Bone.prototype.setYawPitchRoll = function (yaw, pitch, roll, space, mesh) {
  72970. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  72971. var rotMat = Bone._tmpMats[0];
  72972. BABYLON.Matrix.RotationYawPitchRollToRef(yaw, pitch, roll, rotMat);
  72973. var rotMatInv = Bone._tmpMats[1];
  72974. this._getNegativeRotationToRef(rotMatInv, space, mesh);
  72975. rotMatInv.multiplyToRef(rotMat, rotMat);
  72976. this._rotateWithMatrix(rotMat, space, mesh);
  72977. };
  72978. /**
  72979. * Rotate the bone on an axis in local or world space.
  72980. * @param axis The axis to rotate the bone on.
  72981. * @param amount The amount to rotate the bone.
  72982. * @param space The space that the axis is in.
  72983. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  72984. */
  72985. Bone.prototype.rotate = function (axis, amount, space, mesh) {
  72986. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  72987. var rmat = Bone._tmpMats[0];
  72988. rmat.m[12] = 0;
  72989. rmat.m[13] = 0;
  72990. rmat.m[14] = 0;
  72991. BABYLON.Matrix.RotationAxisToRef(axis, amount, rmat);
  72992. this._rotateWithMatrix(rmat, space, mesh);
  72993. };
  72994. /**
  72995. * Set the rotation of the bone to a particular axis angle in local or world space.
  72996. * @param axis The axis to rotate the bone on.
  72997. * @param angle The angle that the bone should be rotated to.
  72998. * @param space The space that the axis is in.
  72999. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  73000. */
  73001. Bone.prototype.setAxisAngle = function (axis, angle, space, mesh) {
  73002. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  73003. var rotMat = Bone._tmpMats[0];
  73004. BABYLON.Matrix.RotationAxisToRef(axis, angle, rotMat);
  73005. var rotMatInv = Bone._tmpMats[1];
  73006. this._getNegativeRotationToRef(rotMatInv, space, mesh);
  73007. rotMatInv.multiplyToRef(rotMat, rotMat);
  73008. this._rotateWithMatrix(rotMat, space, mesh);
  73009. };
  73010. /**
  73011. * Set the euler rotation of the bone in local of world space.
  73012. * @param rotation The euler rotation that the bone should be set to.
  73013. * @param space The space that the rotation is in.
  73014. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  73015. */
  73016. Bone.prototype.setRotation = function (rotation, space, mesh) {
  73017. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  73018. this.setYawPitchRoll(rotation.y, rotation.x, rotation.z, space, mesh);
  73019. };
  73020. /**
  73021. * Set the quaternion rotation of the bone in local of world space.
  73022. * @param quat The quaternion rotation that the bone should be set to.
  73023. * @param space The space that the rotation is in.
  73024. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  73025. */
  73026. Bone.prototype.setRotationQuaternion = function (quat, space, mesh) {
  73027. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  73028. var rotMatInv = Bone._tmpMats[0];
  73029. this._getNegativeRotationToRef(rotMatInv, space, mesh);
  73030. var rotMat = Bone._tmpMats[1];
  73031. BABYLON.Matrix.FromQuaternionToRef(quat, rotMat);
  73032. rotMatInv.multiplyToRef(rotMat, rotMat);
  73033. this._rotateWithMatrix(rotMat, space, mesh);
  73034. };
  73035. /**
  73036. * Set the rotation matrix of the bone in local of world space.
  73037. * @param rotMat The rotation matrix that the bone should be set to.
  73038. * @param space The space that the rotation is in.
  73039. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  73040. */
  73041. Bone.prototype.setRotationMatrix = function (rotMat, space, mesh) {
  73042. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  73043. var rotMatInv = Bone._tmpMats[0];
  73044. this._getNegativeRotationToRef(rotMatInv, space, mesh);
  73045. var rotMat2 = Bone._tmpMats[1];
  73046. rotMat2.copyFrom(rotMat);
  73047. rotMatInv.multiplyToRef(rotMat, rotMat2);
  73048. this._rotateWithMatrix(rotMat2, space, mesh);
  73049. };
  73050. Bone.prototype._rotateWithMatrix = function (rmat, space, mesh) {
  73051. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  73052. var lmat = this.getLocalMatrix();
  73053. var lx = lmat.m[12];
  73054. var ly = lmat.m[13];
  73055. var lz = lmat.m[14];
  73056. var parent = this.getParent();
  73057. var parentScale = Bone._tmpMats[3];
  73058. var parentScaleInv = Bone._tmpMats[4];
  73059. if (parent) {
  73060. if (space == BABYLON.Space.WORLD) {
  73061. if (mesh) {
  73062. parentScale.copyFrom(mesh.getWorldMatrix());
  73063. parent.getAbsoluteTransform().multiplyToRef(parentScale, parentScale);
  73064. }
  73065. else {
  73066. parentScale.copyFrom(parent.getAbsoluteTransform());
  73067. }
  73068. }
  73069. else {
  73070. parentScale = parent._scaleMatrix;
  73071. }
  73072. parentScaleInv.copyFrom(parentScale);
  73073. parentScaleInv.invert();
  73074. lmat.multiplyToRef(parentScale, lmat);
  73075. lmat.multiplyToRef(rmat, lmat);
  73076. lmat.multiplyToRef(parentScaleInv, lmat);
  73077. }
  73078. else {
  73079. if (space == BABYLON.Space.WORLD && mesh) {
  73080. parentScale.copyFrom(mesh.getWorldMatrix());
  73081. parentScaleInv.copyFrom(parentScale);
  73082. parentScaleInv.invert();
  73083. lmat.multiplyToRef(parentScale, lmat);
  73084. lmat.multiplyToRef(rmat, lmat);
  73085. lmat.multiplyToRef(parentScaleInv, lmat);
  73086. }
  73087. else {
  73088. lmat.multiplyToRef(rmat, lmat);
  73089. }
  73090. }
  73091. lmat.m[12] = lx;
  73092. lmat.m[13] = ly;
  73093. lmat.m[14] = lz;
  73094. this.computeAbsoluteTransforms();
  73095. this.markAsDirty();
  73096. };
  73097. Bone.prototype._getNegativeRotationToRef = function (rotMatInv, space, mesh) {
  73098. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  73099. if (space == BABYLON.Space.WORLD) {
  73100. var scaleMatrix = Bone._tmpMats[2];
  73101. scaleMatrix.copyFrom(this._scaleMatrix);
  73102. rotMatInv.copyFrom(this.getAbsoluteTransform());
  73103. if (mesh) {
  73104. rotMatInv.multiplyToRef(mesh.getWorldMatrix(), rotMatInv);
  73105. var meshScale = Bone._tmpMats[3];
  73106. BABYLON.Matrix.ScalingToRef(mesh.scaling.x, mesh.scaling.y, mesh.scaling.z, meshScale);
  73107. scaleMatrix.multiplyToRef(meshScale, scaleMatrix);
  73108. }
  73109. rotMatInv.invert();
  73110. scaleMatrix.m[0] *= this._scalingDeterminant;
  73111. rotMatInv.multiplyToRef(scaleMatrix, rotMatInv);
  73112. }
  73113. else {
  73114. rotMatInv.copyFrom(this.getLocalMatrix());
  73115. rotMatInv.invert();
  73116. var scaleMatrix = Bone._tmpMats[2];
  73117. scaleMatrix.copyFrom(this._scaleMatrix);
  73118. if (this._parent) {
  73119. var pscaleMatrix = Bone._tmpMats[3];
  73120. pscaleMatrix.copyFrom(this._parent._scaleMatrix);
  73121. pscaleMatrix.invert();
  73122. pscaleMatrix.multiplyToRef(rotMatInv, rotMatInv);
  73123. }
  73124. else {
  73125. scaleMatrix.m[0] *= this._scalingDeterminant;
  73126. }
  73127. rotMatInv.multiplyToRef(scaleMatrix, rotMatInv);
  73128. }
  73129. };
  73130. /**
  73131. * Get the scale of the bone
  73132. * @returns the scale of the bone
  73133. */
  73134. Bone.prototype.getScale = function () {
  73135. return this._scaleVector.clone();
  73136. };
  73137. /**
  73138. * Copy the scale of the bone to a vector3.
  73139. * @param result The vector3 to copy the scale to
  73140. */
  73141. Bone.prototype.getScaleToRef = function (result) {
  73142. result.copyFrom(this._scaleVector);
  73143. };
  73144. /**
  73145. * Get the position of the bone in local or world space.
  73146. * @param space The space that the returned position is in.
  73147. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  73148. * @returns The position of the bone
  73149. */
  73150. Bone.prototype.getPosition = function (space, mesh) {
  73151. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  73152. if (mesh === void 0) { mesh = null; }
  73153. var pos = BABYLON.Vector3.Zero();
  73154. this.getPositionToRef(space, mesh, pos);
  73155. return pos;
  73156. };
  73157. /**
  73158. * Copy the position of the bone to a vector3 in local or world space.
  73159. * @param space The space that the returned position is in.
  73160. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  73161. * @param result The vector3 to copy the position to.
  73162. */
  73163. Bone.prototype.getPositionToRef = function (space, mesh, result) {
  73164. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  73165. if (space == BABYLON.Space.LOCAL) {
  73166. var lm = this.getLocalMatrix();
  73167. result.x = lm.m[12];
  73168. result.y = lm.m[13];
  73169. result.z = lm.m[14];
  73170. }
  73171. else {
  73172. var wm = null;
  73173. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  73174. if (mesh) {
  73175. wm = mesh.getWorldMatrix();
  73176. }
  73177. this._skeleton.computeAbsoluteTransforms();
  73178. var tmat = Bone._tmpMats[0];
  73179. if (mesh && wm) {
  73180. tmat.copyFrom(this.getAbsoluteTransform());
  73181. tmat.multiplyToRef(wm, tmat);
  73182. }
  73183. else {
  73184. tmat = this.getAbsoluteTransform();
  73185. }
  73186. result.x = tmat.m[12];
  73187. result.y = tmat.m[13];
  73188. result.z = tmat.m[14];
  73189. }
  73190. };
  73191. /**
  73192. * Get the absolute position of the bone (world space).
  73193. * @param mesh The mesh that this bone is attached to.
  73194. * @returns The absolute position of the bone
  73195. */
  73196. Bone.prototype.getAbsolutePosition = function (mesh) {
  73197. if (mesh === void 0) { mesh = null; }
  73198. var pos = BABYLON.Vector3.Zero();
  73199. this.getPositionToRef(BABYLON.Space.WORLD, mesh, pos);
  73200. return pos;
  73201. };
  73202. /**
  73203. * Copy the absolute position of the bone (world space) to the result param.
  73204. * @param mesh The mesh that this bone is attached to.
  73205. * @param result The vector3 to copy the absolute position to.
  73206. */
  73207. Bone.prototype.getAbsolutePositionToRef = function (mesh, result) {
  73208. this.getPositionToRef(BABYLON.Space.WORLD, mesh, result);
  73209. };
  73210. /**
  73211. * Compute the absolute transforms of this bone and its children.
  73212. */
  73213. Bone.prototype.computeAbsoluteTransforms = function () {
  73214. if (this._parent) {
  73215. this._localMatrix.multiplyToRef(this._parent._absoluteTransform, this._absoluteTransform);
  73216. }
  73217. else {
  73218. this._absoluteTransform.copyFrom(this._localMatrix);
  73219. var poseMatrix = this._skeleton.getPoseMatrix();
  73220. if (poseMatrix) {
  73221. this._absoluteTransform.multiplyToRef(poseMatrix, this._absoluteTransform);
  73222. }
  73223. }
  73224. var children = this.children;
  73225. var len = children.length;
  73226. for (var i = 0; i < len; i++) {
  73227. children[i].computeAbsoluteTransforms();
  73228. }
  73229. };
  73230. Bone.prototype._syncScaleVector = function () {
  73231. var lm = this.getLocalMatrix();
  73232. var xsq = (lm.m[0] * lm.m[0] + lm.m[1] * lm.m[1] + lm.m[2] * lm.m[2]);
  73233. var ysq = (lm.m[4] * lm.m[4] + lm.m[5] * lm.m[5] + lm.m[6] * lm.m[6]);
  73234. var zsq = (lm.m[8] * lm.m[8] + lm.m[9] * lm.m[9] + lm.m[10] * lm.m[10]);
  73235. var xs = lm.m[0] * lm.m[1] * lm.m[2] * lm.m[3] < 0 ? -1 : 1;
  73236. var ys = lm.m[4] * lm.m[5] * lm.m[6] * lm.m[7] < 0 ? -1 : 1;
  73237. var zs = lm.m[8] * lm.m[9] * lm.m[10] * lm.m[11] < 0 ? -1 : 1;
  73238. this._scaleVector.x = xs * Math.sqrt(xsq);
  73239. this._scaleVector.y = ys * Math.sqrt(ysq);
  73240. this._scaleVector.z = zs * Math.sqrt(zsq);
  73241. if (this._parent) {
  73242. this._scaleVector.x /= this._parent._negateScaleChildren.x;
  73243. this._scaleVector.y /= this._parent._negateScaleChildren.y;
  73244. this._scaleVector.z /= this._parent._negateScaleChildren.z;
  73245. }
  73246. BABYLON.Matrix.FromValuesToRef(this._scaleVector.x, 0, 0, 0, 0, this._scaleVector.y, 0, 0, 0, 0, this._scaleVector.z, 0, 0, 0, 0, 1, this._scaleMatrix);
  73247. };
  73248. /**
  73249. * Get the world direction from an axis that is in the local space of the bone.
  73250. * @param localAxis The local direction that is used to compute the world direction.
  73251. * @param mesh The mesh that this bone is attached to.
  73252. * @returns The world direction
  73253. */
  73254. Bone.prototype.getDirection = function (localAxis, mesh) {
  73255. if (mesh === void 0) { mesh = null; }
  73256. var result = BABYLON.Vector3.Zero();
  73257. this.getDirectionToRef(localAxis, mesh, result);
  73258. return result;
  73259. };
  73260. /**
  73261. * Copy the world direction to a vector3 from an axis that is in the local space of the bone.
  73262. * @param localAxis The local direction that is used to compute the world direction.
  73263. * @param mesh The mesh that this bone is attached to.
  73264. * @param result The vector3 that the world direction will be copied to.
  73265. */
  73266. Bone.prototype.getDirectionToRef = function (localAxis, mesh, result) {
  73267. if (mesh === void 0) { mesh = null; }
  73268. var wm = null;
  73269. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  73270. if (mesh) {
  73271. wm = mesh.getWorldMatrix();
  73272. }
  73273. this._skeleton.computeAbsoluteTransforms();
  73274. var mat = Bone._tmpMats[0];
  73275. mat.copyFrom(this.getAbsoluteTransform());
  73276. if (mesh && wm) {
  73277. mat.multiplyToRef(wm, mat);
  73278. }
  73279. BABYLON.Vector3.TransformNormalToRef(localAxis, mat, result);
  73280. result.normalize();
  73281. };
  73282. /**
  73283. * Get the euler rotation of the bone in local or world space.
  73284. * @param space The space that the rotation should be in.
  73285. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  73286. * @returns The euler rotation
  73287. */
  73288. Bone.prototype.getRotation = function (space, mesh) {
  73289. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  73290. if (mesh === void 0) { mesh = null; }
  73291. var result = BABYLON.Vector3.Zero();
  73292. this.getRotationToRef(space, mesh, result);
  73293. return result;
  73294. };
  73295. /**
  73296. * Copy the euler rotation of the bone to a vector3. The rotation can be in either local or world space.
  73297. * @param space The space that the rotation should be in.
  73298. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  73299. * @param result The vector3 that the rotation should be copied to.
  73300. */
  73301. Bone.prototype.getRotationToRef = function (space, mesh, result) {
  73302. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  73303. if (mesh === void 0) { mesh = null; }
  73304. var quat = Bone._tmpQuat;
  73305. this.getRotationQuaternionToRef(space, mesh, quat);
  73306. quat.toEulerAnglesToRef(result);
  73307. };
  73308. /**
  73309. * Get the quaternion rotation of the bone in either local or world space.
  73310. * @param space The space that the rotation should be in.
  73311. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  73312. * @returns The quaternion rotation
  73313. */
  73314. Bone.prototype.getRotationQuaternion = function (space, mesh) {
  73315. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  73316. if (mesh === void 0) { mesh = null; }
  73317. var result = BABYLON.Quaternion.Identity();
  73318. this.getRotationQuaternionToRef(space, mesh, result);
  73319. return result;
  73320. };
  73321. /**
  73322. * Copy the quaternion rotation of the bone to a quaternion. The rotation can be in either local or world space.
  73323. * @param space The space that the rotation should be in.
  73324. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  73325. * @param result The quaternion that the rotation should be copied to.
  73326. */
  73327. Bone.prototype.getRotationQuaternionToRef = function (space, mesh, result) {
  73328. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  73329. if (mesh === void 0) { mesh = null; }
  73330. if (space == BABYLON.Space.LOCAL) {
  73331. this.getLocalMatrix().decompose(Bone._tmpVecs[0], result, Bone._tmpVecs[1]);
  73332. }
  73333. else {
  73334. var mat = Bone._tmpMats[0];
  73335. var amat = this.getAbsoluteTransform();
  73336. if (mesh) {
  73337. amat.multiplyToRef(mesh.getWorldMatrix(), mat);
  73338. }
  73339. else {
  73340. mat.copyFrom(amat);
  73341. }
  73342. mat.m[0] *= this._scalingDeterminant;
  73343. mat.m[1] *= this._scalingDeterminant;
  73344. mat.m[2] *= this._scalingDeterminant;
  73345. mat.decompose(Bone._tmpVecs[0], result, Bone._tmpVecs[1]);
  73346. }
  73347. };
  73348. /**
  73349. * Get the rotation matrix of the bone in local or world space.
  73350. * @param space The space that the rotation should be in.
  73351. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  73352. * @returns The rotation matrix
  73353. */
  73354. Bone.prototype.getRotationMatrix = function (space, mesh) {
  73355. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  73356. var result = BABYLON.Matrix.Identity();
  73357. this.getRotationMatrixToRef(space, mesh, result);
  73358. return result;
  73359. };
  73360. /**
  73361. * Copy the rotation matrix of the bone to a matrix. The rotation can be in either local or world space.
  73362. * @param space The space that the rotation should be in.
  73363. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  73364. * @param result The quaternion that the rotation should be copied to.
  73365. */
  73366. Bone.prototype.getRotationMatrixToRef = function (space, mesh, result) {
  73367. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  73368. if (space == BABYLON.Space.LOCAL) {
  73369. this.getLocalMatrix().getRotationMatrixToRef(result);
  73370. }
  73371. else {
  73372. var mat = Bone._tmpMats[0];
  73373. var amat = this.getAbsoluteTransform();
  73374. if (mesh) {
  73375. amat.multiplyToRef(mesh.getWorldMatrix(), mat);
  73376. }
  73377. else {
  73378. mat.copyFrom(amat);
  73379. }
  73380. mat.m[0] *= this._scalingDeterminant;
  73381. mat.m[1] *= this._scalingDeterminant;
  73382. mat.m[2] *= this._scalingDeterminant;
  73383. mat.getRotationMatrixToRef(result);
  73384. }
  73385. };
  73386. /**
  73387. * Get the world position of a point that is in the local space of the bone.
  73388. * @param position The local position
  73389. * @param mesh The mesh that this bone is attached to.
  73390. * @returns The world position
  73391. */
  73392. Bone.prototype.getAbsolutePositionFromLocal = function (position, mesh) {
  73393. if (mesh === void 0) { mesh = null; }
  73394. var result = BABYLON.Vector3.Zero();
  73395. this.getAbsolutePositionFromLocalToRef(position, mesh, result);
  73396. return result;
  73397. };
  73398. /**
  73399. * Get the world position of a point that is in the local space of the bone and copy it to the result param.
  73400. * @param position The local position
  73401. * @param mesh The mesh that this bone is attached to.
  73402. * @param result The vector3 that the world position should be copied to.
  73403. */
  73404. Bone.prototype.getAbsolutePositionFromLocalToRef = function (position, mesh, result) {
  73405. if (mesh === void 0) { mesh = null; }
  73406. var wm = null;
  73407. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  73408. if (mesh) {
  73409. wm = mesh.getWorldMatrix();
  73410. }
  73411. this._skeleton.computeAbsoluteTransforms();
  73412. var tmat = Bone._tmpMats[0];
  73413. if (mesh && wm) {
  73414. tmat.copyFrom(this.getAbsoluteTransform());
  73415. tmat.multiplyToRef(wm, tmat);
  73416. }
  73417. else {
  73418. tmat = this.getAbsoluteTransform();
  73419. }
  73420. BABYLON.Vector3.TransformCoordinatesToRef(position, tmat, result);
  73421. };
  73422. /**
  73423. * Get the local position of a point that is in world space.
  73424. * @param position The world position
  73425. * @param mesh The mesh that this bone is attached to.
  73426. * @returns The local position
  73427. */
  73428. Bone.prototype.getLocalPositionFromAbsolute = function (position, mesh) {
  73429. if (mesh === void 0) { mesh = null; }
  73430. var result = BABYLON.Vector3.Zero();
  73431. this.getLocalPositionFromAbsoluteToRef(position, mesh, result);
  73432. return result;
  73433. };
  73434. /**
  73435. * Get the local position of a point that is in world space and copy it to the result param.
  73436. * @param position The world position
  73437. * @param mesh The mesh that this bone is attached to.
  73438. * @param result The vector3 that the local position should be copied to.
  73439. */
  73440. Bone.prototype.getLocalPositionFromAbsoluteToRef = function (position, mesh, result) {
  73441. if (mesh === void 0) { mesh = null; }
  73442. var wm = null;
  73443. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  73444. if (mesh) {
  73445. wm = mesh.getWorldMatrix();
  73446. }
  73447. this._skeleton.computeAbsoluteTransforms();
  73448. var tmat = Bone._tmpMats[0];
  73449. tmat.copyFrom(this.getAbsoluteTransform());
  73450. if (mesh && wm) {
  73451. tmat.multiplyToRef(wm, tmat);
  73452. }
  73453. tmat.invert();
  73454. BABYLON.Vector3.TransformCoordinatesToRef(position, tmat, result);
  73455. };
  73456. Bone._tmpVecs = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  73457. Bone._tmpQuat = BABYLON.Quaternion.Identity();
  73458. Bone._tmpMats = [BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity()];
  73459. return Bone;
  73460. }(BABYLON.Node));
  73461. BABYLON.Bone = Bone;
  73462. })(BABYLON || (BABYLON = {}));
  73463. //# sourceMappingURL=babylon.bone.js.map
  73464. "use strict";
  73465. var BABYLON;
  73466. (function (BABYLON) {
  73467. var BoneIKController = /** @class */ (function () {
  73468. function BoneIKController(mesh, bone, options) {
  73469. this.targetPosition = BABYLON.Vector3.Zero();
  73470. this.poleTargetPosition = BABYLON.Vector3.Zero();
  73471. this.poleTargetLocalOffset = BABYLON.Vector3.Zero();
  73472. this.poleAngle = 0;
  73473. this.slerpAmount = 1;
  73474. this._bone1Quat = BABYLON.Quaternion.Identity();
  73475. this._bone1Mat = BABYLON.Matrix.Identity();
  73476. this._bone2Ang = Math.PI;
  73477. this._maxAngle = Math.PI;
  73478. this._rightHandedSystem = false;
  73479. this._bendAxis = BABYLON.Vector3.Right();
  73480. this._slerping = false;
  73481. this._adjustRoll = 0;
  73482. this._bone2 = bone;
  73483. this._bone1 = bone.getParent();
  73484. if (!this._bone1) {
  73485. return;
  73486. }
  73487. this.mesh = mesh;
  73488. var bonePos = bone.getPosition();
  73489. if (bone.getAbsoluteTransform().determinant() > 0) {
  73490. this._rightHandedSystem = true;
  73491. this._bendAxis.x = 0;
  73492. this._bendAxis.y = 0;
  73493. this._bendAxis.z = -1;
  73494. if (bonePos.x > bonePos.y && bonePos.x > bonePos.z) {
  73495. this._adjustRoll = Math.PI * .5;
  73496. this._bendAxis.z = 1;
  73497. }
  73498. }
  73499. if (this._bone1.length) {
  73500. var boneScale1 = this._bone1.getScale();
  73501. var boneScale2 = this._bone2.getScale();
  73502. this._bone1Length = this._bone1.length * boneScale1.y * this.mesh.scaling.y;
  73503. this._bone2Length = this._bone2.length * boneScale2.y * this.mesh.scaling.y;
  73504. }
  73505. else if (this._bone1.children[0]) {
  73506. mesh.computeWorldMatrix(true);
  73507. var pos1 = this._bone2.children[0].getAbsolutePosition(mesh);
  73508. var pos2 = this._bone2.getAbsolutePosition(mesh);
  73509. var pos3 = this._bone1.getAbsolutePosition(mesh);
  73510. this._bone1Length = BABYLON.Vector3.Distance(pos1, pos2);
  73511. this._bone2Length = BABYLON.Vector3.Distance(pos2, pos3);
  73512. }
  73513. this._bone1.getRotationMatrixToRef(BABYLON.Space.WORLD, mesh, this._bone1Mat);
  73514. this.maxAngle = Math.PI;
  73515. if (options) {
  73516. if (options.targetMesh) {
  73517. this.targetMesh = options.targetMesh;
  73518. this.targetMesh.computeWorldMatrix(true);
  73519. }
  73520. if (options.poleTargetMesh) {
  73521. this.poleTargetMesh = options.poleTargetMesh;
  73522. this.poleTargetMesh.computeWorldMatrix(true);
  73523. }
  73524. else if (options.poleTargetBone) {
  73525. this.poleTargetBone = options.poleTargetBone;
  73526. }
  73527. else if (this._bone1.getParent()) {
  73528. this.poleTargetBone = this._bone1.getParent();
  73529. }
  73530. if (options.poleTargetLocalOffset) {
  73531. this.poleTargetLocalOffset.copyFrom(options.poleTargetLocalOffset);
  73532. }
  73533. if (options.poleAngle) {
  73534. this.poleAngle = options.poleAngle;
  73535. }
  73536. if (options.bendAxis) {
  73537. this._bendAxis.copyFrom(options.bendAxis);
  73538. }
  73539. if (options.maxAngle) {
  73540. this.maxAngle = options.maxAngle;
  73541. }
  73542. if (options.slerpAmount) {
  73543. this.slerpAmount = options.slerpAmount;
  73544. }
  73545. }
  73546. }
  73547. Object.defineProperty(BoneIKController.prototype, "maxAngle", {
  73548. get: function () {
  73549. return this._maxAngle;
  73550. },
  73551. set: function (value) {
  73552. this._setMaxAngle(value);
  73553. },
  73554. enumerable: true,
  73555. configurable: true
  73556. });
  73557. BoneIKController.prototype._setMaxAngle = function (ang) {
  73558. if (ang < 0) {
  73559. ang = 0;
  73560. }
  73561. if (ang > Math.PI || ang == undefined) {
  73562. ang = Math.PI;
  73563. }
  73564. this._maxAngle = ang;
  73565. var a = this._bone1Length;
  73566. var b = this._bone2Length;
  73567. this._maxReach = Math.sqrt(a * a + b * b - 2 * a * b * Math.cos(ang));
  73568. };
  73569. BoneIKController.prototype.update = function () {
  73570. var bone1 = this._bone1;
  73571. if (!bone1) {
  73572. return;
  73573. }
  73574. var target = this.targetPosition;
  73575. var poleTarget = this.poleTargetPosition;
  73576. var mat1 = BoneIKController._tmpMats[0];
  73577. var mat2 = BoneIKController._tmpMats[1];
  73578. if (this.targetMesh) {
  73579. target.copyFrom(this.targetMesh.getAbsolutePosition());
  73580. }
  73581. if (this.poleTargetBone) {
  73582. this.poleTargetBone.getAbsolutePositionFromLocalToRef(this.poleTargetLocalOffset, this.mesh, poleTarget);
  73583. }
  73584. else if (this.poleTargetMesh) {
  73585. BABYLON.Vector3.TransformCoordinatesToRef(this.poleTargetLocalOffset, this.poleTargetMesh.getWorldMatrix(), poleTarget);
  73586. }
  73587. var bonePos = BoneIKController._tmpVecs[0];
  73588. var zaxis = BoneIKController._tmpVecs[1];
  73589. var xaxis = BoneIKController._tmpVecs[2];
  73590. var yaxis = BoneIKController._tmpVecs[3];
  73591. var upAxis = BoneIKController._tmpVecs[4];
  73592. var _tmpQuat = BoneIKController._tmpQuat;
  73593. bone1.getAbsolutePositionToRef(this.mesh, bonePos);
  73594. poleTarget.subtractToRef(bonePos, upAxis);
  73595. if (upAxis.x == 0 && upAxis.y == 0 && upAxis.z == 0) {
  73596. upAxis.y = 1;
  73597. }
  73598. else {
  73599. upAxis.normalize();
  73600. }
  73601. target.subtractToRef(bonePos, yaxis);
  73602. yaxis.normalize();
  73603. BABYLON.Vector3.CrossToRef(yaxis, upAxis, zaxis);
  73604. zaxis.normalize();
  73605. BABYLON.Vector3.CrossToRef(yaxis, zaxis, xaxis);
  73606. xaxis.normalize();
  73607. BABYLON.Matrix.FromXYZAxesToRef(xaxis, yaxis, zaxis, mat1);
  73608. var a = this._bone1Length;
  73609. var b = this._bone2Length;
  73610. var c = BABYLON.Vector3.Distance(bonePos, target);
  73611. if (this._maxReach > 0) {
  73612. c = Math.min(this._maxReach, c);
  73613. }
  73614. var acosa = (b * b + c * c - a * a) / (2 * b * c);
  73615. var acosb = (c * c + a * a - b * b) / (2 * c * a);
  73616. if (acosa > 1) {
  73617. acosa = 1;
  73618. }
  73619. if (acosb > 1) {
  73620. acosb = 1;
  73621. }
  73622. if (acosa < -1) {
  73623. acosa = -1;
  73624. }
  73625. if (acosb < -1) {
  73626. acosb = -1;
  73627. }
  73628. var angA = Math.acos(acosa);
  73629. var angB = Math.acos(acosb);
  73630. var angC = -angA - angB;
  73631. if (this._rightHandedSystem) {
  73632. BABYLON.Matrix.RotationYawPitchRollToRef(0, 0, this._adjustRoll, mat2);
  73633. mat2.multiplyToRef(mat1, mat1);
  73634. BABYLON.Matrix.RotationAxisToRef(this._bendAxis, angB, mat2);
  73635. mat2.multiplyToRef(mat1, mat1);
  73636. }
  73637. else {
  73638. var _tmpVec = BoneIKController._tmpVecs[5];
  73639. _tmpVec.copyFrom(this._bendAxis);
  73640. _tmpVec.x *= -1;
  73641. BABYLON.Matrix.RotationAxisToRef(_tmpVec, -angB, mat2);
  73642. mat2.multiplyToRef(mat1, mat1);
  73643. }
  73644. if (this.poleAngle) {
  73645. BABYLON.Matrix.RotationAxisToRef(yaxis, this.poleAngle, mat2);
  73646. mat1.multiplyToRef(mat2, mat1);
  73647. }
  73648. if (this._bone1) {
  73649. if (this.slerpAmount < 1) {
  73650. if (!this._slerping) {
  73651. BABYLON.Quaternion.FromRotationMatrixToRef(this._bone1Mat, this._bone1Quat);
  73652. }
  73653. BABYLON.Quaternion.FromRotationMatrixToRef(mat1, _tmpQuat);
  73654. BABYLON.Quaternion.SlerpToRef(this._bone1Quat, _tmpQuat, this.slerpAmount, this._bone1Quat);
  73655. angC = this._bone2Ang * (1.0 - this.slerpAmount) + angC * this.slerpAmount;
  73656. this._bone1.setRotationQuaternion(this._bone1Quat, BABYLON.Space.WORLD, this.mesh);
  73657. this._slerping = true;
  73658. }
  73659. else {
  73660. this._bone1.setRotationMatrix(mat1, BABYLON.Space.WORLD, this.mesh);
  73661. this._bone1Mat.copyFrom(mat1);
  73662. this._slerping = false;
  73663. }
  73664. }
  73665. this._bone2.setAxisAngle(this._bendAxis, angC, BABYLON.Space.LOCAL);
  73666. this._bone2Ang = angC;
  73667. };
  73668. BoneIKController._tmpVecs = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  73669. BoneIKController._tmpQuat = BABYLON.Quaternion.Identity();
  73670. BoneIKController._tmpMats = [BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity()];
  73671. return BoneIKController;
  73672. }());
  73673. BABYLON.BoneIKController = BoneIKController;
  73674. })(BABYLON || (BABYLON = {}));
  73675. //# sourceMappingURL=babylon.boneIKController.js.map
  73676. "use strict";
  73677. var BABYLON;
  73678. (function (BABYLON) {
  73679. var BoneLookController = /** @class */ (function () {
  73680. /**
  73681. * Create a BoneLookController
  73682. * @param mesh the mesh that the bone belongs to
  73683. * @param bone the bone that will be looking to the target
  73684. * @param target the target Vector3 to look at
  73685. * @param settings optional settings:
  73686. * - maxYaw: the maximum angle the bone will yaw to
  73687. * - minYaw: the minimum angle the bone will yaw to
  73688. * - maxPitch: the maximum angle the bone will pitch to
  73689. * - minPitch: the minimum angle the bone will yaw to
  73690. * - slerpAmount: set the between 0 and 1 to make the bone slerp to the target.
  73691. * - upAxis: the up axis of the coordinate system
  73692. * - upAxisSpace: the space that the up axis is in - BABYLON.Space.BONE, BABYLON.Space.LOCAL (default), or BABYLON.Space.WORLD.
  73693. * - yawAxis: set yawAxis if the bone does not yaw on the y axis
  73694. * - pitchAxis: set pitchAxis if the bone does not pitch on the x axis
  73695. * - adjustYaw: used to make an adjustment to the yaw of the bone
  73696. * - adjustPitch: used to make an adjustment to the pitch of the bone
  73697. * - adjustRoll: used to make an adjustment to the roll of the bone
  73698. **/
  73699. function BoneLookController(mesh, bone, target, options) {
  73700. /**
  73701. * The up axis of the coordinate system that is used when the bone is rotated.
  73702. */
  73703. this.upAxis = BABYLON.Vector3.Up();
  73704. /**
  73705. * The space that the up axis is in - BABYLON.Space.BONE, BABYLON.Space.LOCAL (default), or BABYLON.Space.WORLD.
  73706. */
  73707. this.upAxisSpace = BABYLON.Space.LOCAL;
  73708. /**
  73709. * Used to make an adjustment to the yaw of the bone.
  73710. */
  73711. this.adjustYaw = 0;
  73712. /**
  73713. * Used to make an adjustment to the pitch of the bone.
  73714. */
  73715. this.adjustPitch = 0;
  73716. /**
  73717. * Used to make an adjustment to the roll of the bone.
  73718. */
  73719. this.adjustRoll = 0;
  73720. /**
  73721. * 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).
  73722. */
  73723. this.slerpAmount = 1;
  73724. this._boneQuat = BABYLON.Quaternion.Identity();
  73725. this._slerping = false;
  73726. this._firstFrameSkipped = false;
  73727. this._fowardAxis = BABYLON.Vector3.Forward();
  73728. this.mesh = mesh;
  73729. this.bone = bone;
  73730. this.target = target;
  73731. if (options) {
  73732. if (options.adjustYaw) {
  73733. this.adjustYaw = options.adjustYaw;
  73734. }
  73735. if (options.adjustPitch) {
  73736. this.adjustPitch = options.adjustPitch;
  73737. }
  73738. if (options.adjustRoll) {
  73739. this.adjustRoll = options.adjustRoll;
  73740. }
  73741. if (options.maxYaw != null) {
  73742. this.maxYaw = options.maxYaw;
  73743. }
  73744. else {
  73745. this.maxYaw = Math.PI;
  73746. }
  73747. if (options.minYaw != null) {
  73748. this.minYaw = options.minYaw;
  73749. }
  73750. else {
  73751. this.minYaw = -Math.PI;
  73752. }
  73753. if (options.maxPitch != null) {
  73754. this.maxPitch = options.maxPitch;
  73755. }
  73756. else {
  73757. this.maxPitch = Math.PI;
  73758. }
  73759. if (options.minPitch != null) {
  73760. this.minPitch = options.minPitch;
  73761. }
  73762. else {
  73763. this.minPitch = -Math.PI;
  73764. }
  73765. if (options.slerpAmount != null) {
  73766. this.slerpAmount = options.slerpAmount;
  73767. }
  73768. if (options.upAxis != null) {
  73769. this.upAxis = options.upAxis;
  73770. }
  73771. if (options.upAxisSpace != null) {
  73772. this.upAxisSpace = options.upAxisSpace;
  73773. }
  73774. if (options.yawAxis != null || options.pitchAxis != null) {
  73775. var newYawAxis = BABYLON.Axis.Y;
  73776. var newPitchAxis = BABYLON.Axis.X;
  73777. if (options.yawAxis != null) {
  73778. newYawAxis = options.yawAxis.clone();
  73779. newYawAxis.normalize();
  73780. }
  73781. if (options.pitchAxis != null) {
  73782. newPitchAxis = options.pitchAxis.clone();
  73783. newPitchAxis.normalize();
  73784. }
  73785. var newRollAxis = BABYLON.Vector3.Cross(newPitchAxis, newYawAxis);
  73786. this._transformYawPitch = BABYLON.Matrix.Identity();
  73787. BABYLON.Matrix.FromXYZAxesToRef(newPitchAxis, newYawAxis, newRollAxis, this._transformYawPitch);
  73788. this._transformYawPitchInv = this._transformYawPitch.clone();
  73789. this._transformYawPitch.invert();
  73790. }
  73791. }
  73792. if (!bone.getParent() && this.upAxisSpace == BABYLON.Space.BONE) {
  73793. this.upAxisSpace = BABYLON.Space.LOCAL;
  73794. }
  73795. }
  73796. Object.defineProperty(BoneLookController.prototype, "minYaw", {
  73797. /**
  73798. * Get/set the minimum yaw angle that the bone can look to.
  73799. */
  73800. get: function () {
  73801. return this._minYaw;
  73802. },
  73803. set: function (value) {
  73804. this._minYaw = value;
  73805. this._minYawSin = Math.sin(value);
  73806. this._minYawCos = Math.cos(value);
  73807. if (this._maxYaw != null) {
  73808. this._midYawConstraint = this._getAngleDiff(this._minYaw, this._maxYaw) * .5 + this._minYaw;
  73809. this._yawRange = this._maxYaw - this._minYaw;
  73810. }
  73811. },
  73812. enumerable: true,
  73813. configurable: true
  73814. });
  73815. Object.defineProperty(BoneLookController.prototype, "maxYaw", {
  73816. /**
  73817. * Get/set the maximum yaw angle that the bone can look to.
  73818. */
  73819. get: function () {
  73820. return this._maxYaw;
  73821. },
  73822. set: function (value) {
  73823. this._maxYaw = value;
  73824. this._maxYawSin = Math.sin(value);
  73825. this._maxYawCos = Math.cos(value);
  73826. if (this._minYaw != null) {
  73827. this._midYawConstraint = this._getAngleDiff(this._minYaw, this._maxYaw) * .5 + this._minYaw;
  73828. this._yawRange = this._maxYaw - this._minYaw;
  73829. }
  73830. },
  73831. enumerable: true,
  73832. configurable: true
  73833. });
  73834. Object.defineProperty(BoneLookController.prototype, "minPitch", {
  73835. /**
  73836. * Get/set the minimum pitch angle that the bone can look to.
  73837. */
  73838. get: function () {
  73839. return this._minPitch;
  73840. },
  73841. set: function (value) {
  73842. this._minPitch = value;
  73843. this._minPitchTan = Math.tan(value);
  73844. },
  73845. enumerable: true,
  73846. configurable: true
  73847. });
  73848. Object.defineProperty(BoneLookController.prototype, "maxPitch", {
  73849. /**
  73850. * Get/set the maximum pitch angle that the bone can look to.
  73851. */
  73852. get: function () {
  73853. return this._maxPitch;
  73854. },
  73855. set: function (value) {
  73856. this._maxPitch = value;
  73857. this._maxPitchTan = Math.tan(value);
  73858. },
  73859. enumerable: true,
  73860. configurable: true
  73861. });
  73862. /**
  73863. * Update the bone to look at the target. This should be called before the scene is rendered (use scene.registerBeforeRender()).
  73864. */
  73865. BoneLookController.prototype.update = function () {
  73866. //skip the first frame when slerping so that the mesh rotation is correct
  73867. if (this.slerpAmount < 1 && !this._firstFrameSkipped) {
  73868. this._firstFrameSkipped = true;
  73869. return;
  73870. }
  73871. var bone = this.bone;
  73872. var bonePos = BoneLookController._tmpVecs[0];
  73873. bone.getAbsolutePositionToRef(this.mesh, bonePos);
  73874. var target = this.target;
  73875. var _tmpMat1 = BoneLookController._tmpMats[0];
  73876. var _tmpMat2 = BoneLookController._tmpMats[1];
  73877. var mesh = this.mesh;
  73878. var parentBone = bone.getParent();
  73879. var upAxis = BoneLookController._tmpVecs[1];
  73880. upAxis.copyFrom(this.upAxis);
  73881. if (this.upAxisSpace == BABYLON.Space.BONE && parentBone) {
  73882. if (this._transformYawPitch) {
  73883. BABYLON.Vector3.TransformCoordinatesToRef(upAxis, this._transformYawPitchInv, upAxis);
  73884. }
  73885. parentBone.getDirectionToRef(upAxis, this.mesh, upAxis);
  73886. }
  73887. else if (this.upAxisSpace == BABYLON.Space.LOCAL) {
  73888. mesh.getDirectionToRef(upAxis, upAxis);
  73889. if (mesh.scaling.x != 1 || mesh.scaling.y != 1 || mesh.scaling.z != 1) {
  73890. upAxis.normalize();
  73891. }
  73892. }
  73893. var checkYaw = false;
  73894. var checkPitch = false;
  73895. if (this._maxYaw != Math.PI || this._minYaw != -Math.PI) {
  73896. checkYaw = true;
  73897. }
  73898. if (this._maxPitch != Math.PI || this._minPitch != -Math.PI) {
  73899. checkPitch = true;
  73900. }
  73901. if (checkYaw || checkPitch) {
  73902. var spaceMat = BoneLookController._tmpMats[2];
  73903. var spaceMatInv = BoneLookController._tmpMats[3];
  73904. if (this.upAxisSpace == BABYLON.Space.BONE && upAxis.y == 1 && parentBone) {
  73905. parentBone.getRotationMatrixToRef(BABYLON.Space.WORLD, this.mesh, spaceMat);
  73906. }
  73907. else if (this.upAxisSpace == BABYLON.Space.LOCAL && upAxis.y == 1 && !parentBone) {
  73908. spaceMat.copyFrom(mesh.getWorldMatrix());
  73909. }
  73910. else {
  73911. var forwardAxis = BoneLookController._tmpVecs[2];
  73912. forwardAxis.copyFrom(this._fowardAxis);
  73913. if (this._transformYawPitch) {
  73914. BABYLON.Vector3.TransformCoordinatesToRef(forwardAxis, this._transformYawPitchInv, forwardAxis);
  73915. }
  73916. if (parentBone) {
  73917. parentBone.getDirectionToRef(forwardAxis, this.mesh, forwardAxis);
  73918. }
  73919. else {
  73920. mesh.getDirectionToRef(forwardAxis, forwardAxis);
  73921. }
  73922. var rightAxis = BABYLON.Vector3.Cross(upAxis, forwardAxis);
  73923. rightAxis.normalize();
  73924. var forwardAxis = BABYLON.Vector3.Cross(rightAxis, upAxis);
  73925. BABYLON.Matrix.FromXYZAxesToRef(rightAxis, upAxis, forwardAxis, spaceMat);
  73926. }
  73927. spaceMat.invertToRef(spaceMatInv);
  73928. var xzlen = null;
  73929. if (checkPitch) {
  73930. var localTarget = BoneLookController._tmpVecs[3];
  73931. target.subtractToRef(bonePos, localTarget);
  73932. BABYLON.Vector3.TransformCoordinatesToRef(localTarget, spaceMatInv, localTarget);
  73933. xzlen = Math.sqrt(localTarget.x * localTarget.x + localTarget.z * localTarget.z);
  73934. var pitch = Math.atan2(localTarget.y, xzlen);
  73935. var newPitch = pitch;
  73936. if (pitch > this._maxPitch) {
  73937. localTarget.y = this._maxPitchTan * xzlen;
  73938. newPitch = this._maxPitch;
  73939. }
  73940. else if (pitch < this._minPitch) {
  73941. localTarget.y = this._minPitchTan * xzlen;
  73942. newPitch = this._minPitch;
  73943. }
  73944. if (pitch != newPitch) {
  73945. BABYLON.Vector3.TransformCoordinatesToRef(localTarget, spaceMat, localTarget);
  73946. localTarget.addInPlace(bonePos);
  73947. target = localTarget;
  73948. }
  73949. }
  73950. if (checkYaw) {
  73951. var localTarget = BoneLookController._tmpVecs[4];
  73952. target.subtractToRef(bonePos, localTarget);
  73953. BABYLON.Vector3.TransformCoordinatesToRef(localTarget, spaceMatInv, localTarget);
  73954. var yaw = Math.atan2(localTarget.x, localTarget.z);
  73955. var newYaw = yaw;
  73956. if (yaw > this._maxYaw || yaw < this._minYaw) {
  73957. if (xzlen == null) {
  73958. xzlen = Math.sqrt(localTarget.x * localTarget.x + localTarget.z * localTarget.z);
  73959. }
  73960. if (this._yawRange > Math.PI) {
  73961. if (this._isAngleBetween(yaw, this._maxYaw, this._midYawConstraint)) {
  73962. localTarget.z = this._maxYawCos * xzlen;
  73963. localTarget.x = this._maxYawSin * xzlen;
  73964. newYaw = this._maxYaw;
  73965. }
  73966. else if (this._isAngleBetween(yaw, this._midYawConstraint, this._minYaw)) {
  73967. localTarget.z = this._minYawCos * xzlen;
  73968. localTarget.x = this._minYawSin * xzlen;
  73969. newYaw = this._minYaw;
  73970. }
  73971. }
  73972. else {
  73973. if (yaw > this._maxYaw) {
  73974. localTarget.z = this._maxYawCos * xzlen;
  73975. localTarget.x = this._maxYawSin * xzlen;
  73976. newYaw = this._maxYaw;
  73977. }
  73978. else if (yaw < this._minYaw) {
  73979. localTarget.z = this._minYawCos * xzlen;
  73980. localTarget.x = this._minYawSin * xzlen;
  73981. newYaw = this._minYaw;
  73982. }
  73983. }
  73984. }
  73985. if (this._slerping && this._yawRange > Math.PI) {
  73986. //are we going to be crossing into the min/max region?
  73987. var boneFwd = BoneLookController._tmpVecs[8];
  73988. boneFwd.copyFrom(BABYLON.Axis.Z);
  73989. if (this._transformYawPitch) {
  73990. BABYLON.Vector3.TransformCoordinatesToRef(boneFwd, this._transformYawPitchInv, boneFwd);
  73991. }
  73992. var boneRotMat = BoneLookController._tmpMats[4];
  73993. this._boneQuat.toRotationMatrix(boneRotMat);
  73994. this.mesh.getWorldMatrix().multiplyToRef(boneRotMat, boneRotMat);
  73995. BABYLON.Vector3.TransformCoordinatesToRef(boneFwd, boneRotMat, boneFwd);
  73996. BABYLON.Vector3.TransformCoordinatesToRef(boneFwd, spaceMatInv, boneFwd);
  73997. var boneYaw = Math.atan2(boneFwd.x, boneFwd.z);
  73998. var angBtwTar = this._getAngleBetween(boneYaw, yaw);
  73999. var angBtwMidYaw = this._getAngleBetween(boneYaw, this._midYawConstraint);
  74000. if (angBtwTar > angBtwMidYaw) {
  74001. if (xzlen == null) {
  74002. xzlen = Math.sqrt(localTarget.x * localTarget.x + localTarget.z * localTarget.z);
  74003. }
  74004. var angBtwMax = this._getAngleBetween(boneYaw, this._maxYaw);
  74005. var angBtwMin = this._getAngleBetween(boneYaw, this._minYaw);
  74006. if (angBtwMin < angBtwMax) {
  74007. newYaw = boneYaw + Math.PI * .75;
  74008. localTarget.z = Math.cos(newYaw) * xzlen;
  74009. localTarget.x = Math.sin(newYaw) * xzlen;
  74010. }
  74011. else {
  74012. newYaw = boneYaw - Math.PI * .75;
  74013. localTarget.z = Math.cos(newYaw) * xzlen;
  74014. localTarget.x = Math.sin(newYaw) * xzlen;
  74015. }
  74016. }
  74017. }
  74018. if (yaw != newYaw) {
  74019. BABYLON.Vector3.TransformCoordinatesToRef(localTarget, spaceMat, localTarget);
  74020. localTarget.addInPlace(bonePos);
  74021. target = localTarget;
  74022. }
  74023. }
  74024. }
  74025. var zaxis = BoneLookController._tmpVecs[5];
  74026. var xaxis = BoneLookController._tmpVecs[6];
  74027. var yaxis = BoneLookController._tmpVecs[7];
  74028. var _tmpQuat = BoneLookController._tmpQuat;
  74029. target.subtractToRef(bonePos, zaxis);
  74030. zaxis.normalize();
  74031. BABYLON.Vector3.CrossToRef(upAxis, zaxis, xaxis);
  74032. xaxis.normalize();
  74033. BABYLON.Vector3.CrossToRef(zaxis, xaxis, yaxis);
  74034. yaxis.normalize();
  74035. BABYLON.Matrix.FromXYZAxesToRef(xaxis, yaxis, zaxis, _tmpMat1);
  74036. if (xaxis.x === 0 && xaxis.y === 0 && xaxis.z === 0) {
  74037. return;
  74038. }
  74039. if (yaxis.x === 0 && yaxis.y === 0 && yaxis.z === 0) {
  74040. return;
  74041. }
  74042. if (zaxis.x === 0 && zaxis.y === 0 && zaxis.z === 0) {
  74043. return;
  74044. }
  74045. if (this.adjustYaw || this.adjustPitch || this.adjustRoll) {
  74046. BABYLON.Matrix.RotationYawPitchRollToRef(this.adjustYaw, this.adjustPitch, this.adjustRoll, _tmpMat2);
  74047. _tmpMat2.multiplyToRef(_tmpMat1, _tmpMat1);
  74048. }
  74049. if (this.slerpAmount < 1) {
  74050. if (!this._slerping) {
  74051. this.bone.getRotationQuaternionToRef(BABYLON.Space.WORLD, this.mesh, this._boneQuat);
  74052. }
  74053. if (this._transformYawPitch) {
  74054. this._transformYawPitch.multiplyToRef(_tmpMat1, _tmpMat1);
  74055. }
  74056. BABYLON.Quaternion.FromRotationMatrixToRef(_tmpMat1, _tmpQuat);
  74057. BABYLON.Quaternion.SlerpToRef(this._boneQuat, _tmpQuat, this.slerpAmount, this._boneQuat);
  74058. this.bone.setRotationQuaternion(this._boneQuat, BABYLON.Space.WORLD, this.mesh);
  74059. this._slerping = true;
  74060. }
  74061. else {
  74062. if (this._transformYawPitch) {
  74063. this._transformYawPitch.multiplyToRef(_tmpMat1, _tmpMat1);
  74064. }
  74065. this.bone.setRotationMatrix(_tmpMat1, BABYLON.Space.WORLD, this.mesh);
  74066. this._slerping = false;
  74067. }
  74068. };
  74069. BoneLookController.prototype._getAngleDiff = function (ang1, ang2) {
  74070. var angDiff = ang2 - ang1;
  74071. angDiff %= Math.PI * 2;
  74072. if (angDiff > Math.PI) {
  74073. angDiff -= Math.PI * 2;
  74074. }
  74075. else if (angDiff < -Math.PI) {
  74076. angDiff += Math.PI * 2;
  74077. }
  74078. return angDiff;
  74079. };
  74080. BoneLookController.prototype._getAngleBetween = function (ang1, ang2) {
  74081. ang1 %= (2 * Math.PI);
  74082. ang1 = (ang1 < 0) ? ang1 + (2 * Math.PI) : ang1;
  74083. ang2 %= (2 * Math.PI);
  74084. ang2 = (ang2 < 0) ? ang2 + (2 * Math.PI) : ang2;
  74085. var ab = 0;
  74086. if (ang1 < ang2) {
  74087. ab = ang2 - ang1;
  74088. }
  74089. else {
  74090. ab = ang1 - ang2;
  74091. }
  74092. if (ab > Math.PI) {
  74093. ab = Math.PI * 2 - ab;
  74094. }
  74095. return ab;
  74096. };
  74097. BoneLookController.prototype._isAngleBetween = function (ang, ang1, ang2) {
  74098. ang %= (2 * Math.PI);
  74099. ang = (ang < 0) ? ang + (2 * Math.PI) : ang;
  74100. ang1 %= (2 * Math.PI);
  74101. ang1 = (ang1 < 0) ? ang1 + (2 * Math.PI) : ang1;
  74102. ang2 %= (2 * Math.PI);
  74103. ang2 = (ang2 < 0) ? ang2 + (2 * Math.PI) : ang2;
  74104. if (ang1 < ang2) {
  74105. if (ang > ang1 && ang < ang2) {
  74106. return true;
  74107. }
  74108. }
  74109. else {
  74110. if (ang > ang2 && ang < ang1) {
  74111. return true;
  74112. }
  74113. }
  74114. return false;
  74115. };
  74116. 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()];
  74117. BoneLookController._tmpQuat = BABYLON.Quaternion.Identity();
  74118. BoneLookController._tmpMats = [BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity()];
  74119. return BoneLookController;
  74120. }());
  74121. BABYLON.BoneLookController = BoneLookController;
  74122. })(BABYLON || (BABYLON = {}));
  74123. //# sourceMappingURL=babylon.boneLookController.js.map
  74124. "use strict";
  74125. var BABYLON;
  74126. (function (BABYLON) {
  74127. var Skeleton = /** @class */ (function () {
  74128. function Skeleton(name, id, scene) {
  74129. this.name = name;
  74130. this.id = id;
  74131. this.bones = new Array();
  74132. this.needInitialSkinMatrix = false;
  74133. this._isDirty = true;
  74134. this._meshesWithPoseMatrix = new Array();
  74135. this._identity = BABYLON.Matrix.Identity();
  74136. this._ranges = {};
  74137. this._lastAbsoluteTransformsUpdateId = -1;
  74138. /**
  74139. * Specifies if the skeleton should be serialized.
  74140. */
  74141. this.doNotSerialize = false;
  74142. // Events
  74143. /**
  74144. * An event triggered before computing the skeleton's matrices
  74145. */
  74146. this.onBeforeComputeObservable = new BABYLON.Observable();
  74147. this.bones = [];
  74148. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  74149. scene.skeletons.push(this);
  74150. //make sure it will recalculate the matrix next time prepare is called.
  74151. this._isDirty = true;
  74152. }
  74153. // Members
  74154. Skeleton.prototype.getTransformMatrices = function (mesh) {
  74155. if (this.needInitialSkinMatrix && mesh._bonesTransformMatrices) {
  74156. return mesh._bonesTransformMatrices;
  74157. }
  74158. if (!this._transformMatrices) {
  74159. this.prepare();
  74160. }
  74161. return this._transformMatrices;
  74162. };
  74163. Skeleton.prototype.getScene = function () {
  74164. return this._scene;
  74165. };
  74166. // Methods
  74167. /**
  74168. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  74169. */
  74170. Skeleton.prototype.toString = function (fullDetails) {
  74171. var ret = "Name: " + this.name + ", nBones: " + this.bones.length;
  74172. ret += ", nAnimationRanges: " + (this._ranges ? Object.keys(this._ranges).length : "none");
  74173. if (fullDetails) {
  74174. ret += ", Ranges: {";
  74175. var first = true;
  74176. for (var name_1 in this._ranges) {
  74177. if (first) {
  74178. ret += ", ";
  74179. first = false;
  74180. }
  74181. ret += name_1;
  74182. }
  74183. ret += "}";
  74184. }
  74185. return ret;
  74186. };
  74187. /**
  74188. * Get bone's index searching by name
  74189. * @param {string} name is bone's name to search for
  74190. * @return {number} Indice of the bone. Returns -1 if not found
  74191. */
  74192. Skeleton.prototype.getBoneIndexByName = function (name) {
  74193. for (var boneIndex = 0, cache = this.bones.length; boneIndex < cache; boneIndex++) {
  74194. if (this.bones[boneIndex].name === name) {
  74195. return boneIndex;
  74196. }
  74197. }
  74198. return -1;
  74199. };
  74200. Skeleton.prototype.createAnimationRange = function (name, from, to) {
  74201. // check name not already in use
  74202. if (!this._ranges[name]) {
  74203. this._ranges[name] = new BABYLON.AnimationRange(name, from, to);
  74204. for (var i = 0, nBones = this.bones.length; i < nBones; i++) {
  74205. if (this.bones[i].animations[0]) {
  74206. this.bones[i].animations[0].createRange(name, from, to);
  74207. }
  74208. }
  74209. }
  74210. };
  74211. Skeleton.prototype.deleteAnimationRange = function (name, deleteFrames) {
  74212. if (deleteFrames === void 0) { deleteFrames = true; }
  74213. for (var i = 0, nBones = this.bones.length; i < nBones; i++) {
  74214. if (this.bones[i].animations[0]) {
  74215. this.bones[i].animations[0].deleteRange(name, deleteFrames);
  74216. }
  74217. }
  74218. this._ranges[name] = null; // said much faster than 'delete this._range[name]'
  74219. };
  74220. Skeleton.prototype.getAnimationRange = function (name) {
  74221. return this._ranges[name];
  74222. };
  74223. /**
  74224. * Returns as an Array, all AnimationRanges defined on this skeleton
  74225. */
  74226. Skeleton.prototype.getAnimationRanges = function () {
  74227. var animationRanges = [];
  74228. var name;
  74229. var i = 0;
  74230. for (name in this._ranges) {
  74231. animationRanges[i] = this._ranges[name];
  74232. i++;
  74233. }
  74234. return animationRanges;
  74235. };
  74236. /**
  74237. * note: This is not for a complete retargeting, only between very similar skeleton's with only possible bone length differences
  74238. */
  74239. Skeleton.prototype.copyAnimationRange = function (source, name, rescaleAsRequired) {
  74240. if (rescaleAsRequired === void 0) { rescaleAsRequired = false; }
  74241. if (this._ranges[name] || !source.getAnimationRange(name)) {
  74242. return false;
  74243. }
  74244. var ret = true;
  74245. var frameOffset = this._getHighestAnimationFrame() + 1;
  74246. // make a dictionary of source skeleton's bones, so exact same order or doublely nested loop is not required
  74247. var boneDict = {};
  74248. var sourceBones = source.bones;
  74249. var nBones;
  74250. var i;
  74251. for (i = 0, nBones = sourceBones.length; i < nBones; i++) {
  74252. boneDict[sourceBones[i].name] = sourceBones[i];
  74253. }
  74254. if (this.bones.length !== sourceBones.length) {
  74255. BABYLON.Tools.Warn("copyAnimationRange: this rig has " + this.bones.length + " bones, while source as " + sourceBones.length);
  74256. ret = false;
  74257. }
  74258. var skelDimensionsRatio = (rescaleAsRequired && this.dimensionsAtRest && source.dimensionsAtRest) ? this.dimensionsAtRest.divide(source.dimensionsAtRest) : null;
  74259. for (i = 0, nBones = this.bones.length; i < nBones; i++) {
  74260. var boneName = this.bones[i].name;
  74261. var sourceBone = boneDict[boneName];
  74262. if (sourceBone) {
  74263. ret = ret && this.bones[i].copyAnimationRange(sourceBone, name, frameOffset, rescaleAsRequired, skelDimensionsRatio);
  74264. }
  74265. else {
  74266. BABYLON.Tools.Warn("copyAnimationRange: not same rig, missing source bone " + boneName);
  74267. ret = false;
  74268. }
  74269. }
  74270. // do not call createAnimationRange(), since it also is done to bones, which was already done
  74271. var range = source.getAnimationRange(name);
  74272. if (range) {
  74273. this._ranges[name] = new BABYLON.AnimationRange(name, range.from + frameOffset, range.to + frameOffset);
  74274. }
  74275. return ret;
  74276. };
  74277. Skeleton.prototype.returnToRest = function () {
  74278. for (var index = 0; index < this.bones.length; index++) {
  74279. this.bones[index].returnToRest();
  74280. }
  74281. };
  74282. Skeleton.prototype._getHighestAnimationFrame = function () {
  74283. var ret = 0;
  74284. for (var i = 0, nBones = this.bones.length; i < nBones; i++) {
  74285. if (this.bones[i].animations[0]) {
  74286. var highest = this.bones[i].animations[0].getHighestFrame();
  74287. if (ret < highest) {
  74288. ret = highest;
  74289. }
  74290. }
  74291. }
  74292. return ret;
  74293. };
  74294. Skeleton.prototype.beginAnimation = function (name, loop, speedRatio, onAnimationEnd) {
  74295. var range = this.getAnimationRange(name);
  74296. if (!range) {
  74297. return null;
  74298. }
  74299. return this._scene.beginAnimation(this, range.from, range.to, loop, speedRatio, onAnimationEnd);
  74300. };
  74301. Skeleton.prototype._markAsDirty = function () {
  74302. this._isDirty = true;
  74303. };
  74304. Skeleton.prototype._registerMeshWithPoseMatrix = function (mesh) {
  74305. this._meshesWithPoseMatrix.push(mesh);
  74306. };
  74307. Skeleton.prototype._unregisterMeshWithPoseMatrix = function (mesh) {
  74308. var index = this._meshesWithPoseMatrix.indexOf(mesh);
  74309. if (index > -1) {
  74310. this._meshesWithPoseMatrix.splice(index, 1);
  74311. }
  74312. };
  74313. Skeleton.prototype._computeTransformMatrices = function (targetMatrix, initialSkinMatrix) {
  74314. this.onBeforeComputeObservable.notifyObservers(this);
  74315. for (var index = 0; index < this.bones.length; index++) {
  74316. var bone = this.bones[index];
  74317. var parentBone = bone.getParent();
  74318. if (parentBone) {
  74319. bone.getLocalMatrix().multiplyToRef(parentBone.getWorldMatrix(), bone.getWorldMatrix());
  74320. }
  74321. else {
  74322. if (initialSkinMatrix) {
  74323. bone.getLocalMatrix().multiplyToRef(initialSkinMatrix, bone.getWorldMatrix());
  74324. }
  74325. else {
  74326. bone.getWorldMatrix().copyFrom(bone.getLocalMatrix());
  74327. }
  74328. }
  74329. if (bone._index !== -1) {
  74330. var mappedIndex = bone._index === null ? index : bone._index;
  74331. bone.getInvertedAbsoluteTransform().multiplyToArray(bone.getWorldMatrix(), targetMatrix, mappedIndex * 16);
  74332. }
  74333. }
  74334. this._identity.copyToArray(targetMatrix, this.bones.length * 16);
  74335. };
  74336. Skeleton.prototype.prepare = function () {
  74337. if (!this._isDirty) {
  74338. return;
  74339. }
  74340. if (this.needInitialSkinMatrix) {
  74341. for (var index = 0; index < this._meshesWithPoseMatrix.length; index++) {
  74342. var mesh = this._meshesWithPoseMatrix[index];
  74343. var poseMatrix = mesh.getPoseMatrix();
  74344. if (!mesh._bonesTransformMatrices || mesh._bonesTransformMatrices.length !== 16 * (this.bones.length + 1)) {
  74345. mesh._bonesTransformMatrices = new Float32Array(16 * (this.bones.length + 1));
  74346. }
  74347. if (this._synchronizedWithMesh !== mesh) {
  74348. this._synchronizedWithMesh = mesh;
  74349. // Prepare bones
  74350. for (var boneIndex = 0; boneIndex < this.bones.length; boneIndex++) {
  74351. var bone = this.bones[boneIndex];
  74352. if (!bone.getParent()) {
  74353. var matrix = bone.getBaseMatrix();
  74354. matrix.multiplyToRef(poseMatrix, BABYLON.Tmp.Matrix[1]);
  74355. bone._updateDifferenceMatrix(BABYLON.Tmp.Matrix[1]);
  74356. }
  74357. }
  74358. }
  74359. this._computeTransformMatrices(mesh._bonesTransformMatrices, poseMatrix);
  74360. }
  74361. }
  74362. else {
  74363. if (!this._transformMatrices || this._transformMatrices.length !== 16 * (this.bones.length + 1)) {
  74364. this._transformMatrices = new Float32Array(16 * (this.bones.length + 1));
  74365. }
  74366. this._computeTransformMatrices(this._transformMatrices, null);
  74367. }
  74368. this._isDirty = false;
  74369. this._scene._activeBones.addCount(this.bones.length, false);
  74370. };
  74371. Skeleton.prototype.getAnimatables = function () {
  74372. if (!this._animatables || this._animatables.length !== this.bones.length) {
  74373. this._animatables = [];
  74374. for (var index = 0; index < this.bones.length; index++) {
  74375. this._animatables.push(this.bones[index]);
  74376. }
  74377. }
  74378. return this._animatables;
  74379. };
  74380. Skeleton.prototype.clone = function (name, id) {
  74381. var result = new Skeleton(name, id || name, this._scene);
  74382. result.needInitialSkinMatrix = this.needInitialSkinMatrix;
  74383. for (var index = 0; index < this.bones.length; index++) {
  74384. var source = this.bones[index];
  74385. var parentBone = null;
  74386. var parent_1 = source.getParent();
  74387. if (parent_1) {
  74388. var parentIndex = this.bones.indexOf(parent_1);
  74389. parentBone = result.bones[parentIndex];
  74390. }
  74391. var bone = new BABYLON.Bone(source.name, result, parentBone, source.getBaseMatrix().clone(), source.getRestPose().clone());
  74392. BABYLON.Tools.DeepCopy(source.animations, bone.animations);
  74393. }
  74394. if (this._ranges) {
  74395. result._ranges = {};
  74396. for (var rangeName in this._ranges) {
  74397. var range = this._ranges[rangeName];
  74398. if (range) {
  74399. result._ranges[rangeName] = range.clone();
  74400. }
  74401. }
  74402. }
  74403. this._isDirty = true;
  74404. return result;
  74405. };
  74406. Skeleton.prototype.enableBlending = function (blendingSpeed) {
  74407. if (blendingSpeed === void 0) { blendingSpeed = 0.01; }
  74408. this.bones.forEach(function (bone) {
  74409. bone.animations.forEach(function (animation) {
  74410. animation.enableBlending = true;
  74411. animation.blendingSpeed = blendingSpeed;
  74412. });
  74413. });
  74414. };
  74415. Skeleton.prototype.dispose = function () {
  74416. this._meshesWithPoseMatrix = [];
  74417. // Animations
  74418. this.getScene().stopAnimation(this);
  74419. // Remove from scene
  74420. this.getScene().removeSkeleton(this);
  74421. };
  74422. Skeleton.prototype.serialize = function () {
  74423. var serializationObject = {};
  74424. serializationObject.name = this.name;
  74425. serializationObject.id = this.id;
  74426. serializationObject.dimensionsAtRest = this.dimensionsAtRest.asArray();
  74427. serializationObject.bones = [];
  74428. serializationObject.needInitialSkinMatrix = this.needInitialSkinMatrix;
  74429. for (var index = 0; index < this.bones.length; index++) {
  74430. var bone = this.bones[index];
  74431. var parent_2 = bone.getParent();
  74432. var serializedBone = {
  74433. parentBoneIndex: parent_2 ? this.bones.indexOf(parent_2) : -1,
  74434. name: bone.name,
  74435. matrix: bone.getBaseMatrix().toArray(),
  74436. rest: bone.getRestPose().toArray()
  74437. };
  74438. serializationObject.bones.push(serializedBone);
  74439. if (bone.length) {
  74440. serializedBone.length = bone.length;
  74441. }
  74442. if (bone.animations && bone.animations.length > 0) {
  74443. serializedBone.animation = bone.animations[0].serialize();
  74444. }
  74445. serializationObject.ranges = [];
  74446. for (var name in this._ranges) {
  74447. var source = this._ranges[name];
  74448. if (!source) {
  74449. continue;
  74450. }
  74451. var range = {};
  74452. range.name = name;
  74453. range.from = source.from;
  74454. range.to = source.to;
  74455. serializationObject.ranges.push(range);
  74456. }
  74457. }
  74458. return serializationObject;
  74459. };
  74460. Skeleton.Parse = function (parsedSkeleton, scene) {
  74461. var skeleton = new Skeleton(parsedSkeleton.name, parsedSkeleton.id, scene);
  74462. if (parsedSkeleton.dimensionsAtRest) {
  74463. skeleton.dimensionsAtRest = BABYLON.Vector3.FromArray(parsedSkeleton.dimensionsAtRest);
  74464. }
  74465. skeleton.needInitialSkinMatrix = parsedSkeleton.needInitialSkinMatrix;
  74466. var index;
  74467. for (index = 0; index < parsedSkeleton.bones.length; index++) {
  74468. var parsedBone = parsedSkeleton.bones[index];
  74469. var parentBone = null;
  74470. if (parsedBone.parentBoneIndex > -1) {
  74471. parentBone = skeleton.bones[parsedBone.parentBoneIndex];
  74472. }
  74473. var rest = parsedBone.rest ? BABYLON.Matrix.FromArray(parsedBone.rest) : null;
  74474. var bone = new BABYLON.Bone(parsedBone.name, skeleton, parentBone, BABYLON.Matrix.FromArray(parsedBone.matrix), rest);
  74475. if (parsedBone.length) {
  74476. bone.length = parsedBone.length;
  74477. }
  74478. if (parsedBone.animation) {
  74479. bone.animations.push(BABYLON.Animation.Parse(parsedBone.animation));
  74480. }
  74481. }
  74482. // placed after bones, so createAnimationRange can cascade down
  74483. if (parsedSkeleton.ranges) {
  74484. for (index = 0; index < parsedSkeleton.ranges.length; index++) {
  74485. var data = parsedSkeleton.ranges[index];
  74486. skeleton.createAnimationRange(data.name, data.from, data.to);
  74487. }
  74488. }
  74489. return skeleton;
  74490. };
  74491. Skeleton.prototype.computeAbsoluteTransforms = function (forceUpdate) {
  74492. if (forceUpdate === void 0) { forceUpdate = false; }
  74493. var renderId = this._scene.getRenderId();
  74494. if (this._lastAbsoluteTransformsUpdateId != renderId || forceUpdate) {
  74495. this.bones[0].computeAbsoluteTransforms();
  74496. this._lastAbsoluteTransformsUpdateId = renderId;
  74497. }
  74498. };
  74499. Skeleton.prototype.getPoseMatrix = function () {
  74500. var poseMatrix = null;
  74501. if (this._meshesWithPoseMatrix.length > 0) {
  74502. poseMatrix = this._meshesWithPoseMatrix[0].getPoseMatrix();
  74503. }
  74504. return poseMatrix;
  74505. };
  74506. Skeleton.prototype.sortBones = function () {
  74507. var bones = new Array();
  74508. var visited = new Array(this.bones.length);
  74509. for (var index = 0; index < this.bones.length; index++) {
  74510. this._sortBones(index, bones, visited);
  74511. }
  74512. this.bones = bones;
  74513. };
  74514. Skeleton.prototype._sortBones = function (index, bones, visited) {
  74515. if (visited[index]) {
  74516. return;
  74517. }
  74518. visited[index] = true;
  74519. var bone = this.bones[index];
  74520. if (bone._index === undefined) {
  74521. bone._index = index;
  74522. }
  74523. var parentBone = bone.getParent();
  74524. if (parentBone) {
  74525. this._sortBones(this.bones.indexOf(parentBone), bones, visited);
  74526. }
  74527. bones.push(bone);
  74528. };
  74529. return Skeleton;
  74530. }());
  74531. BABYLON.Skeleton = Skeleton;
  74532. })(BABYLON || (BABYLON = {}));
  74533. //# sourceMappingURL=babylon.skeleton.js.map
  74534. "use strict";
  74535. var BABYLON;
  74536. (function (BABYLON) {
  74537. var SphericalPolynomial = /** @class */ (function () {
  74538. function SphericalPolynomial() {
  74539. this.x = BABYLON.Vector3.Zero();
  74540. this.y = BABYLON.Vector3.Zero();
  74541. this.z = BABYLON.Vector3.Zero();
  74542. this.xx = BABYLON.Vector3.Zero();
  74543. this.yy = BABYLON.Vector3.Zero();
  74544. this.zz = BABYLON.Vector3.Zero();
  74545. this.xy = BABYLON.Vector3.Zero();
  74546. this.yz = BABYLON.Vector3.Zero();
  74547. this.zx = BABYLON.Vector3.Zero();
  74548. }
  74549. SphericalPolynomial.prototype.addAmbient = function (color) {
  74550. var colorVector = new BABYLON.Vector3(color.r, color.g, color.b);
  74551. this.xx = this.xx.add(colorVector);
  74552. this.yy = this.yy.add(colorVector);
  74553. this.zz = this.zz.add(colorVector);
  74554. };
  74555. SphericalPolynomial.getSphericalPolynomialFromHarmonics = function (harmonics) {
  74556. var result = new SphericalPolynomial();
  74557. result.x = harmonics.L11.scale(1.02333);
  74558. result.y = harmonics.L1_1.scale(1.02333);
  74559. result.z = harmonics.L10.scale(1.02333);
  74560. result.xx = harmonics.L00.scale(0.886277).subtract(harmonics.L20.scale(0.247708)).add(harmonics.L22.scale(0.429043));
  74561. result.yy = harmonics.L00.scale(0.886277).subtract(harmonics.L20.scale(0.247708)).subtract(harmonics.L22.scale(0.429043));
  74562. result.zz = harmonics.L00.scale(0.886277).add(harmonics.L20.scale(0.495417));
  74563. result.yz = harmonics.L2_1.scale(0.858086);
  74564. result.zx = harmonics.L21.scale(0.858086);
  74565. result.xy = harmonics.L2_2.scale(0.858086);
  74566. result.scale(1.0 / Math.PI);
  74567. return result;
  74568. };
  74569. SphericalPolynomial.prototype.scale = function (scale) {
  74570. this.x = this.x.scale(scale);
  74571. this.y = this.y.scale(scale);
  74572. this.z = this.z.scale(scale);
  74573. this.xx = this.xx.scale(scale);
  74574. this.yy = this.yy.scale(scale);
  74575. this.zz = this.zz.scale(scale);
  74576. this.yz = this.yz.scale(scale);
  74577. this.zx = this.zx.scale(scale);
  74578. this.xy = this.xy.scale(scale);
  74579. };
  74580. return SphericalPolynomial;
  74581. }());
  74582. BABYLON.SphericalPolynomial = SphericalPolynomial;
  74583. var SphericalHarmonics = /** @class */ (function () {
  74584. function SphericalHarmonics() {
  74585. this.L00 = BABYLON.Vector3.Zero();
  74586. this.L1_1 = BABYLON.Vector3.Zero();
  74587. this.L10 = BABYLON.Vector3.Zero();
  74588. this.L11 = BABYLON.Vector3.Zero();
  74589. this.L2_2 = BABYLON.Vector3.Zero();
  74590. this.L2_1 = BABYLON.Vector3.Zero();
  74591. this.L20 = BABYLON.Vector3.Zero();
  74592. this.L21 = BABYLON.Vector3.Zero();
  74593. this.L22 = BABYLON.Vector3.Zero();
  74594. }
  74595. SphericalHarmonics.prototype.addLight = function (direction, color, deltaSolidAngle) {
  74596. var colorVector = new BABYLON.Vector3(color.r, color.g, color.b);
  74597. var c = colorVector.scale(deltaSolidAngle);
  74598. this.L00 = this.L00.add(c.scale(0.282095));
  74599. this.L1_1 = this.L1_1.add(c.scale(0.488603 * direction.y));
  74600. this.L10 = this.L10.add(c.scale(0.488603 * direction.z));
  74601. this.L11 = this.L11.add(c.scale(0.488603 * direction.x));
  74602. this.L2_2 = this.L2_2.add(c.scale(1.092548 * direction.x * direction.y));
  74603. this.L2_1 = this.L2_1.add(c.scale(1.092548 * direction.y * direction.z));
  74604. this.L21 = this.L21.add(c.scale(1.092548 * direction.x * direction.z));
  74605. this.L20 = this.L20.add(c.scale(0.315392 * (3.0 * direction.z * direction.z - 1.0)));
  74606. this.L22 = this.L22.add(c.scale(0.546274 * (direction.x * direction.x - direction.y * direction.y)));
  74607. };
  74608. SphericalHarmonics.prototype.scale = function (scale) {
  74609. this.L00 = this.L00.scale(scale);
  74610. this.L1_1 = this.L1_1.scale(scale);
  74611. this.L10 = this.L10.scale(scale);
  74612. this.L11 = this.L11.scale(scale);
  74613. this.L2_2 = this.L2_2.scale(scale);
  74614. this.L2_1 = this.L2_1.scale(scale);
  74615. this.L20 = this.L20.scale(scale);
  74616. this.L21 = this.L21.scale(scale);
  74617. this.L22 = this.L22.scale(scale);
  74618. };
  74619. SphericalHarmonics.prototype.convertIncidentRadianceToIrradiance = function () {
  74620. // Convert from incident radiance (Li) to irradiance (E) by applying convolution with the cosine-weighted hemisphere.
  74621. //
  74622. // E_lm = A_l * L_lm
  74623. //
  74624. // In spherical harmonics this convolution amounts to scaling factors for each frequency band.
  74625. // This corresponds to equation 5 in "An Efficient Representation for Irradiance Environment Maps", where
  74626. // the scaling factors are given in equation 9.
  74627. // Constant (Band 0)
  74628. this.L00 = this.L00.scale(3.141593);
  74629. // Linear (Band 1)
  74630. this.L1_1 = this.L1_1.scale(2.094395);
  74631. this.L10 = this.L10.scale(2.094395);
  74632. this.L11 = this.L11.scale(2.094395);
  74633. // Quadratic (Band 2)
  74634. this.L2_2 = this.L2_2.scale(0.785398);
  74635. this.L2_1 = this.L2_1.scale(0.785398);
  74636. this.L20 = this.L20.scale(0.785398);
  74637. this.L21 = this.L21.scale(0.785398);
  74638. this.L22 = this.L22.scale(0.785398);
  74639. };
  74640. SphericalHarmonics.prototype.convertIrradianceToLambertianRadiance = function () {
  74641. // Convert from irradiance to outgoing radiance for Lambertian BDRF, suitable for efficient shader evaluation.
  74642. // L = (1/pi) * E * rho
  74643. //
  74644. // This is done by an additional scale by 1/pi, so is a fairly trivial operation but important conceptually.
  74645. this.scale(1.0 / Math.PI);
  74646. // The resultant SH now represents outgoing radiance, so includes the Lambert 1/pi normalisation factor but without albedo (rho) applied
  74647. // (The pixel shader must apply albedo after texture fetches, etc).
  74648. };
  74649. SphericalHarmonics.getsphericalHarmonicsFromPolynomial = function (polynomial) {
  74650. var result = new SphericalHarmonics();
  74651. result.L00 = polynomial.xx.scale(0.376127).add(polynomial.yy.scale(0.376127)).add(polynomial.zz.scale(0.376126));
  74652. result.L1_1 = polynomial.y.scale(0.977204);
  74653. result.L10 = polynomial.z.scale(0.977204);
  74654. result.L11 = polynomial.x.scale(0.977204);
  74655. result.L2_2 = polynomial.xy.scale(1.16538);
  74656. result.L2_1 = polynomial.yz.scale(1.16538);
  74657. result.L20 = polynomial.zz.scale(1.34567).subtract(polynomial.xx.scale(0.672834)).subtract(polynomial.yy.scale(0.672834));
  74658. result.L21 = polynomial.zx.scale(1.16538);
  74659. result.L22 = polynomial.xx.scale(1.16538).subtract(polynomial.yy.scale(1.16538));
  74660. result.scale(Math.PI);
  74661. return result;
  74662. };
  74663. return SphericalHarmonics;
  74664. }());
  74665. BABYLON.SphericalHarmonics = SphericalHarmonics;
  74666. })(BABYLON || (BABYLON = {}));
  74667. //# sourceMappingURL=babylon.sphericalPolynomial.js.map
  74668. "use strict";
  74669. var BABYLON;
  74670. (function (BABYLON) {
  74671. var FileFaceOrientation = /** @class */ (function () {
  74672. function FileFaceOrientation(name, worldAxisForNormal, worldAxisForFileX, worldAxisForFileY) {
  74673. this.name = name;
  74674. this.worldAxisForNormal = worldAxisForNormal;
  74675. this.worldAxisForFileX = worldAxisForFileX;
  74676. this.worldAxisForFileY = worldAxisForFileY;
  74677. }
  74678. return FileFaceOrientation;
  74679. }());
  74680. ;
  74681. /**
  74682. * Helper class dealing with the extraction of spherical polynomial dataArray
  74683. * from a cube map.
  74684. */
  74685. var CubeMapToSphericalPolynomialTools = /** @class */ (function () {
  74686. function CubeMapToSphericalPolynomialTools() {
  74687. }
  74688. /**
  74689. * Converts a texture to the according Spherical Polynomial data.
  74690. * This extracts the first 3 orders only as they are the only one used in the lighting.
  74691. *
  74692. * @param texture The texture to extract the information from.
  74693. * @return The Spherical Polynomial data.
  74694. */
  74695. CubeMapToSphericalPolynomialTools.ConvertCubeMapTextureToSphericalPolynomial = function (texture) {
  74696. if (!texture.isCube) {
  74697. // Only supports cube Textures currently.
  74698. return null;
  74699. }
  74700. var size = texture.getSize().width;
  74701. var right = texture.readPixels(0);
  74702. var left = texture.readPixels(1);
  74703. var up;
  74704. var down;
  74705. if (texture.isRenderTarget) {
  74706. up = texture.readPixels(3);
  74707. down = texture.readPixels(2);
  74708. }
  74709. else {
  74710. up = texture.readPixels(2);
  74711. down = texture.readPixels(3);
  74712. }
  74713. var front = texture.readPixels(4);
  74714. var back = texture.readPixels(5);
  74715. var gammaSpace = texture.gammaSpace;
  74716. // Always read as RGBA.
  74717. var format = BABYLON.Engine.TEXTUREFORMAT_RGBA;
  74718. var type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  74719. if (texture.textureType && texture.textureType !== BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT) {
  74720. type = BABYLON.Engine.TEXTURETYPE_FLOAT;
  74721. }
  74722. var cubeInfo = {
  74723. size: size,
  74724. right: right,
  74725. left: left,
  74726. up: up,
  74727. down: down,
  74728. front: front,
  74729. back: back,
  74730. format: format,
  74731. type: type,
  74732. gammaSpace: gammaSpace,
  74733. };
  74734. return this.ConvertCubeMapToSphericalPolynomial(cubeInfo);
  74735. };
  74736. /**
  74737. * Converts a cubemap to the according Spherical Polynomial data.
  74738. * This extracts the first 3 orders only as they are the only one used in the lighting.
  74739. *
  74740. * @param cubeInfo The Cube map to extract the information from.
  74741. * @return The Spherical Polynomial data.
  74742. */
  74743. CubeMapToSphericalPolynomialTools.ConvertCubeMapToSphericalPolynomial = function (cubeInfo) {
  74744. var sphericalHarmonics = new BABYLON.SphericalHarmonics();
  74745. var totalSolidAngle = 0.0;
  74746. // The (u,v) range is [-1,+1], so the distance between each texel is 2/Size.
  74747. var du = 2.0 / cubeInfo.size;
  74748. var dv = du;
  74749. // The (u,v) of the first texel is half a texel from the corner (-1,-1).
  74750. var minUV = du * 0.5 - 1.0;
  74751. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  74752. var fileFace = this.FileFaces[faceIndex];
  74753. var dataArray = cubeInfo[fileFace.name];
  74754. var v = minUV;
  74755. // TODO: we could perform the summation directly into a SphericalPolynomial (SP), which is more efficient than SphericalHarmonic (SH).
  74756. // This is possible because during the summation we do not need the SH-specific properties, e.g. orthogonality.
  74757. // Because SP is still linear, so summation is fine in that basis.
  74758. var stride = cubeInfo.format === BABYLON.Engine.TEXTUREFORMAT_RGBA ? 4 : 3;
  74759. for (var y = 0; y < cubeInfo.size; y++) {
  74760. var u = minUV;
  74761. for (var x = 0; x < cubeInfo.size; x++) {
  74762. // World direction (not normalised)
  74763. var worldDirection = fileFace.worldAxisForFileX.scale(u).add(fileFace.worldAxisForFileY.scale(v)).add(fileFace.worldAxisForNormal);
  74764. worldDirection.normalize();
  74765. var deltaSolidAngle = Math.pow(1.0 + u * u + v * v, -3.0 / 2.0);
  74766. var r = dataArray[(y * cubeInfo.size * stride) + (x * stride) + 0];
  74767. var g = dataArray[(y * cubeInfo.size * stride) + (x * stride) + 1];
  74768. var b = dataArray[(y * cubeInfo.size * stride) + (x * stride) + 2];
  74769. // Handle Integer types.
  74770. if (cubeInfo.type === BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT) {
  74771. r /= 255;
  74772. g /= 255;
  74773. b /= 255;
  74774. }
  74775. // Handle Gamma space textures.
  74776. if (cubeInfo.gammaSpace) {
  74777. r = Math.pow(BABYLON.Scalar.Clamp(r), BABYLON.ToLinearSpace);
  74778. g = Math.pow(BABYLON.Scalar.Clamp(g), BABYLON.ToLinearSpace);
  74779. b = Math.pow(BABYLON.Scalar.Clamp(b), BABYLON.ToLinearSpace);
  74780. }
  74781. var color = new BABYLON.Color3(r, g, b);
  74782. sphericalHarmonics.addLight(worldDirection, color, deltaSolidAngle);
  74783. totalSolidAngle += deltaSolidAngle;
  74784. u += du;
  74785. }
  74786. v += dv;
  74787. }
  74788. }
  74789. // Solid angle for entire sphere is 4*pi
  74790. var sphereSolidAngle = 4.0 * Math.PI;
  74791. // Adjust the solid angle to allow for how many faces we processed.
  74792. var facesProcessed = 6.0;
  74793. var expectedSolidAngle = sphereSolidAngle * facesProcessed / 6.0;
  74794. // Adjust the harmonics so that the accumulated solid angle matches the expected solid angle.
  74795. // This is needed because the numerical integration over the cube uses a
  74796. // small angle approximation of solid angle for each texel (see deltaSolidAngle),
  74797. // and also to compensate for accumulative error due to float precision in the summation.
  74798. var correctionFactor = expectedSolidAngle / totalSolidAngle;
  74799. sphericalHarmonics.scale(correctionFactor);
  74800. sphericalHarmonics.convertIncidentRadianceToIrradiance();
  74801. sphericalHarmonics.convertIrradianceToLambertianRadiance();
  74802. return BABYLON.SphericalPolynomial.getSphericalPolynomialFromHarmonics(sphericalHarmonics);
  74803. };
  74804. CubeMapToSphericalPolynomialTools.FileFaces = [
  74805. new FileFaceOrientation("right", new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, 0, -1), new BABYLON.Vector3(0, -1, 0)),
  74806. new FileFaceOrientation("left", new BABYLON.Vector3(-1, 0, 0), new BABYLON.Vector3(0, 0, 1), new BABYLON.Vector3(0, -1, 0)),
  74807. new FileFaceOrientation("up", new BABYLON.Vector3(0, 1, 0), new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, 0, 1)),
  74808. new FileFaceOrientation("down", new BABYLON.Vector3(0, -1, 0), new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, 0, -1)),
  74809. new FileFaceOrientation("front", new BABYLON.Vector3(0, 0, 1), new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, -1, 0)),
  74810. new FileFaceOrientation("back", new BABYLON.Vector3(0, 0, -1), new BABYLON.Vector3(-1, 0, 0), new BABYLON.Vector3(0, -1, 0)) // -Z bottom
  74811. ];
  74812. return CubeMapToSphericalPolynomialTools;
  74813. }());
  74814. BABYLON.CubeMapToSphericalPolynomialTools = CubeMapToSphericalPolynomialTools;
  74815. })(BABYLON || (BABYLON = {}));
  74816. //# sourceMappingURL=babylon.cubemapToSphericalPolynomial.js.map
  74817. "use strict";
  74818. var BABYLON;
  74819. (function (BABYLON) {
  74820. /**
  74821. * Helper class usefull to convert panorama picture to their cubemap representation in 6 faces.
  74822. */
  74823. var PanoramaToCubeMapTools = /** @class */ (function () {
  74824. function PanoramaToCubeMapTools() {
  74825. }
  74826. /**
  74827. * Converts a panorma stored in RGB right to left up to down format into a cubemap (6 faces).
  74828. *
  74829. * @param float32Array The source data.
  74830. * @param inputWidth The width of the input panorama.
  74831. * @param inputhHeight The height of the input panorama.
  74832. * @param size The willing size of the generated cubemap (each faces will be size * size pixels)
  74833. * @return The cubemap data
  74834. */
  74835. PanoramaToCubeMapTools.ConvertPanoramaToCubemap = function (float32Array, inputWidth, inputHeight, size) {
  74836. if (!float32Array) {
  74837. throw "ConvertPanoramaToCubemap: input cannot be null";
  74838. }
  74839. if (float32Array.length != inputWidth * inputHeight * 3) {
  74840. throw "ConvertPanoramaToCubemap: input size is wrong";
  74841. }
  74842. var textureFront = this.CreateCubemapTexture(size, this.FACE_FRONT, float32Array, inputWidth, inputHeight);
  74843. var textureBack = this.CreateCubemapTexture(size, this.FACE_BACK, float32Array, inputWidth, inputHeight);
  74844. var textureLeft = this.CreateCubemapTexture(size, this.FACE_LEFT, float32Array, inputWidth, inputHeight);
  74845. var textureRight = this.CreateCubemapTexture(size, this.FACE_RIGHT, float32Array, inputWidth, inputHeight);
  74846. var textureUp = this.CreateCubemapTexture(size, this.FACE_UP, float32Array, inputWidth, inputHeight);
  74847. var textureDown = this.CreateCubemapTexture(size, this.FACE_DOWN, float32Array, inputWidth, inputHeight);
  74848. return {
  74849. front: textureFront,
  74850. back: textureBack,
  74851. left: textureLeft,
  74852. right: textureRight,
  74853. up: textureUp,
  74854. down: textureDown,
  74855. size: size,
  74856. type: BABYLON.Engine.TEXTURETYPE_FLOAT,
  74857. format: BABYLON.Engine.TEXTUREFORMAT_RGB,
  74858. gammaSpace: false,
  74859. };
  74860. };
  74861. PanoramaToCubeMapTools.CreateCubemapTexture = function (texSize, faceData, float32Array, inputWidth, inputHeight) {
  74862. var buffer = new ArrayBuffer(texSize * texSize * 4 * 3);
  74863. var textureArray = new Float32Array(buffer);
  74864. var rotDX1 = faceData[1].subtract(faceData[0]).scale(1 / texSize);
  74865. var rotDX2 = faceData[3].subtract(faceData[2]).scale(1 / texSize);
  74866. var dy = 1 / texSize;
  74867. var fy = 0;
  74868. for (var y = 0; y < texSize; y++) {
  74869. var xv1 = faceData[0];
  74870. var xv2 = faceData[2];
  74871. for (var x = 0; x < texSize; x++) {
  74872. var v = xv2.subtract(xv1).scale(fy).add(xv1);
  74873. v.normalize();
  74874. var color = this.CalcProjectionSpherical(v, float32Array, inputWidth, inputHeight);
  74875. // 3 channels per pixels
  74876. textureArray[y * texSize * 3 + (x * 3) + 0] = color.r;
  74877. textureArray[y * texSize * 3 + (x * 3) + 1] = color.g;
  74878. textureArray[y * texSize * 3 + (x * 3) + 2] = color.b;
  74879. xv1 = xv1.add(rotDX1);
  74880. xv2 = xv2.add(rotDX2);
  74881. }
  74882. fy += dy;
  74883. }
  74884. return textureArray;
  74885. };
  74886. PanoramaToCubeMapTools.CalcProjectionSpherical = function (vDir, float32Array, inputWidth, inputHeight) {
  74887. var theta = Math.atan2(vDir.z, vDir.x);
  74888. var phi = Math.acos(vDir.y);
  74889. while (theta < -Math.PI)
  74890. theta += 2 * Math.PI;
  74891. while (theta > Math.PI)
  74892. theta -= 2 * Math.PI;
  74893. var dx = theta / Math.PI;
  74894. var dy = phi / Math.PI;
  74895. // recenter.
  74896. dx = dx * 0.5 + 0.5;
  74897. var px = Math.round(dx * inputWidth);
  74898. if (px < 0)
  74899. px = 0;
  74900. else if (px >= inputWidth)
  74901. px = inputWidth - 1;
  74902. var py = Math.round(dy * inputHeight);
  74903. if (py < 0)
  74904. py = 0;
  74905. else if (py >= inputHeight)
  74906. py = inputHeight - 1;
  74907. var inputY = (inputHeight - py - 1);
  74908. var r = float32Array[inputY * inputWidth * 3 + (px * 3) + 0];
  74909. var g = float32Array[inputY * inputWidth * 3 + (px * 3) + 1];
  74910. var b = float32Array[inputY * inputWidth * 3 + (px * 3) + 2];
  74911. return {
  74912. r: r,
  74913. g: g,
  74914. b: b
  74915. };
  74916. };
  74917. PanoramaToCubeMapTools.FACE_FRONT = [
  74918. new BABYLON.Vector3(-1.0, -1.0, -1.0),
  74919. new BABYLON.Vector3(1.0, -1.0, -1.0),
  74920. new BABYLON.Vector3(-1.0, 1.0, -1.0),
  74921. new BABYLON.Vector3(1.0, 1.0, -1.0)
  74922. ];
  74923. PanoramaToCubeMapTools.FACE_BACK = [
  74924. new BABYLON.Vector3(1.0, -1.0, 1.0),
  74925. new BABYLON.Vector3(-1.0, -1.0, 1.0),
  74926. new BABYLON.Vector3(1.0, 1.0, 1.0),
  74927. new BABYLON.Vector3(-1.0, 1.0, 1.0)
  74928. ];
  74929. PanoramaToCubeMapTools.FACE_RIGHT = [
  74930. new BABYLON.Vector3(1.0, -1.0, -1.0),
  74931. new BABYLON.Vector3(1.0, -1.0, 1.0),
  74932. new BABYLON.Vector3(1.0, 1.0, -1.0),
  74933. new BABYLON.Vector3(1.0, 1.0, 1.0)
  74934. ];
  74935. PanoramaToCubeMapTools.FACE_LEFT = [
  74936. new BABYLON.Vector3(-1.0, -1.0, 1.0),
  74937. new BABYLON.Vector3(-1.0, -1.0, -1.0),
  74938. new BABYLON.Vector3(-1.0, 1.0, 1.0),
  74939. new BABYLON.Vector3(-1.0, 1.0, -1.0)
  74940. ];
  74941. PanoramaToCubeMapTools.FACE_DOWN = [
  74942. new BABYLON.Vector3(-1.0, 1.0, -1.0),
  74943. new BABYLON.Vector3(1.0, 1.0, -1.0),
  74944. new BABYLON.Vector3(-1.0, 1.0, 1.0),
  74945. new BABYLON.Vector3(1.0, 1.0, 1.0)
  74946. ];
  74947. PanoramaToCubeMapTools.FACE_UP = [
  74948. new BABYLON.Vector3(-1.0, -1.0, 1.0),
  74949. new BABYLON.Vector3(1.0, -1.0, 1.0),
  74950. new BABYLON.Vector3(-1.0, -1.0, -1.0),
  74951. new BABYLON.Vector3(1.0, -1.0, -1.0)
  74952. ];
  74953. return PanoramaToCubeMapTools;
  74954. }());
  74955. BABYLON.PanoramaToCubeMapTools = PanoramaToCubeMapTools;
  74956. })(BABYLON || (BABYLON = {}));
  74957. //# sourceMappingURL=babylon.panoramaToCubemap.js.map
  74958. "use strict";
  74959. var BABYLON;
  74960. (function (BABYLON) {
  74961. ;
  74962. /**
  74963. * This groups tools to convert HDR texture to native colors array.
  74964. */
  74965. var HDRTools = /** @class */ (function () {
  74966. function HDRTools() {
  74967. }
  74968. HDRTools.Ldexp = function (mantissa, exponent) {
  74969. if (exponent > 1023) {
  74970. return mantissa * Math.pow(2, 1023) * Math.pow(2, exponent - 1023);
  74971. }
  74972. if (exponent < -1074) {
  74973. return mantissa * Math.pow(2, -1074) * Math.pow(2, exponent + 1074);
  74974. }
  74975. return mantissa * Math.pow(2, exponent);
  74976. };
  74977. HDRTools.Rgbe2float = function (float32array, red, green, blue, exponent, index) {
  74978. if (exponent > 0) {
  74979. exponent = this.Ldexp(1.0, exponent - (128 + 8));
  74980. float32array[index + 0] = red * exponent;
  74981. float32array[index + 1] = green * exponent;
  74982. float32array[index + 2] = blue * exponent;
  74983. }
  74984. else {
  74985. float32array[index + 0] = 0;
  74986. float32array[index + 1] = 0;
  74987. float32array[index + 2] = 0;
  74988. }
  74989. };
  74990. HDRTools.readStringLine = function (uint8array, startIndex) {
  74991. var line = "";
  74992. var character = "";
  74993. for (var i = startIndex; i < uint8array.length - startIndex; i++) {
  74994. character = String.fromCharCode(uint8array[i]);
  74995. if (character == "\n") {
  74996. break;
  74997. }
  74998. line += character;
  74999. }
  75000. return line;
  75001. };
  75002. /**
  75003. * Reads header information from an RGBE texture stored in a native array.
  75004. * More information on this format are available here:
  75005. * https://en.wikipedia.org/wiki/RGBE_image_format
  75006. *
  75007. * @param uint8array The binary file stored in native array.
  75008. * @return The header information.
  75009. */
  75010. HDRTools.RGBE_ReadHeader = function (uint8array) {
  75011. var height = 0;
  75012. var width = 0;
  75013. var line = this.readStringLine(uint8array, 0);
  75014. if (line[0] != '#' || line[1] != '?') {
  75015. throw "Bad HDR Format.";
  75016. }
  75017. var endOfHeader = false;
  75018. var findFormat = false;
  75019. var lineIndex = 0;
  75020. do {
  75021. lineIndex += (line.length + 1);
  75022. line = this.readStringLine(uint8array, lineIndex);
  75023. if (line == "FORMAT=32-bit_rle_rgbe") {
  75024. findFormat = true;
  75025. }
  75026. else if (line.length == 0) {
  75027. endOfHeader = true;
  75028. }
  75029. } while (!endOfHeader);
  75030. if (!findFormat) {
  75031. throw "HDR Bad header format, unsupported FORMAT";
  75032. }
  75033. lineIndex += (line.length + 1);
  75034. line = this.readStringLine(uint8array, lineIndex);
  75035. var sizeRegexp = /^\-Y (.*) \+X (.*)$/g;
  75036. var match = sizeRegexp.exec(line);
  75037. // TODO. Support +Y and -X if needed.
  75038. if (!match || match.length < 3) {
  75039. throw "HDR Bad header format, no size";
  75040. }
  75041. width = parseInt(match[2]);
  75042. height = parseInt(match[1]);
  75043. if (width < 8 || width > 0x7fff) {
  75044. throw "HDR Bad header format, unsupported size";
  75045. }
  75046. lineIndex += (line.length + 1);
  75047. return {
  75048. height: height,
  75049. width: width,
  75050. dataPosition: lineIndex
  75051. };
  75052. };
  75053. /**
  75054. * Returns the cubemap information (each faces texture data) extracted from an RGBE texture.
  75055. * This RGBE texture needs to store the information as a panorama.
  75056. *
  75057. * More information on this format are available here:
  75058. * https://en.wikipedia.org/wiki/RGBE_image_format
  75059. *
  75060. * @param buffer The binary file stored in an array buffer.
  75061. * @param size The expected size of the extracted cubemap.
  75062. * @return The Cube Map information.
  75063. */
  75064. HDRTools.GetCubeMapTextureData = function (buffer, size) {
  75065. var uint8array = new Uint8Array(buffer);
  75066. var hdrInfo = this.RGBE_ReadHeader(uint8array);
  75067. var data = this.RGBE_ReadPixels_RLE(uint8array, hdrInfo);
  75068. var cubeMapData = BABYLON.PanoramaToCubeMapTools.ConvertPanoramaToCubemap(data, hdrInfo.width, hdrInfo.height, size);
  75069. return cubeMapData;
  75070. };
  75071. /**
  75072. * Returns the pixels data extracted from an RGBE texture.
  75073. * This pixels will be stored left to right up to down in the R G B order in one array.
  75074. *
  75075. * More information on this format are available here:
  75076. * https://en.wikipedia.org/wiki/RGBE_image_format
  75077. *
  75078. * @param uint8array The binary file stored in an array buffer.
  75079. * @param hdrInfo The header information of the file.
  75080. * @return The pixels data in RGB right to left up to down order.
  75081. */
  75082. HDRTools.RGBE_ReadPixels = function (uint8array, hdrInfo) {
  75083. // Keep for multi format supports.
  75084. return this.RGBE_ReadPixels_RLE(uint8array, hdrInfo);
  75085. };
  75086. HDRTools.RGBE_ReadPixels_RLE = function (uint8array, hdrInfo) {
  75087. var num_scanlines = hdrInfo.height;
  75088. var scanline_width = hdrInfo.width;
  75089. var a, b, c, d, count;
  75090. var dataIndex = hdrInfo.dataPosition;
  75091. var index = 0, endIndex = 0, i = 0;
  75092. var scanLineArrayBuffer = new ArrayBuffer(scanline_width * 4); // four channel R G B E
  75093. var scanLineArray = new Uint8Array(scanLineArrayBuffer);
  75094. // 3 channels of 4 bytes per pixel in float.
  75095. var resultBuffer = new ArrayBuffer(hdrInfo.width * hdrInfo.height * 4 * 3);
  75096. var resultArray = new Float32Array(resultBuffer);
  75097. // read in each successive scanline
  75098. while (num_scanlines > 0) {
  75099. a = uint8array[dataIndex++];
  75100. b = uint8array[dataIndex++];
  75101. c = uint8array[dataIndex++];
  75102. d = uint8array[dataIndex++];
  75103. if (a != 2 || b != 2 || (c & 0x80)) {
  75104. // this file is not run length encoded
  75105. throw "HDR Bad header format, not RLE";
  75106. }
  75107. if (((c << 8) | d) != scanline_width) {
  75108. throw "HDR Bad header format, wrong scan line width";
  75109. }
  75110. index = 0;
  75111. // read each of the four channels for the scanline into the buffer
  75112. for (i = 0; i < 4; i++) {
  75113. endIndex = (i + 1) * scanline_width;
  75114. while (index < endIndex) {
  75115. a = uint8array[dataIndex++];
  75116. b = uint8array[dataIndex++];
  75117. if (a > 128) {
  75118. // a run of the same value
  75119. count = a - 128;
  75120. if ((count == 0) || (count > endIndex - index)) {
  75121. throw "HDR Bad Format, bad scanline data (run)";
  75122. }
  75123. while (count-- > 0) {
  75124. scanLineArray[index++] = b;
  75125. }
  75126. }
  75127. else {
  75128. // a non-run
  75129. count = a;
  75130. if ((count == 0) || (count > endIndex - index)) {
  75131. throw "HDR Bad Format, bad scanline data (non-run)";
  75132. }
  75133. scanLineArray[index++] = b;
  75134. if (--count > 0) {
  75135. for (var j = 0; j < count; j++) {
  75136. scanLineArray[index++] = uint8array[dataIndex++];
  75137. }
  75138. }
  75139. }
  75140. }
  75141. }
  75142. // now convert data from buffer into floats
  75143. for (i = 0; i < scanline_width; i++) {
  75144. a = scanLineArray[i];
  75145. b = scanLineArray[i + scanline_width];
  75146. c = scanLineArray[i + 2 * scanline_width];
  75147. d = scanLineArray[i + 3 * scanline_width];
  75148. this.Rgbe2float(resultArray, a, b, c, d, (hdrInfo.height - num_scanlines) * scanline_width * 3 + i * 3);
  75149. }
  75150. num_scanlines--;
  75151. }
  75152. return resultArray;
  75153. };
  75154. return HDRTools;
  75155. }());
  75156. BABYLON.HDRTools = HDRTools;
  75157. })(BABYLON || (BABYLON = {}));
  75158. //# sourceMappingURL=babylon.hdr.js.map
  75159. "use strict";
  75160. var BABYLON;
  75161. (function (BABYLON) {
  75162. /**
  75163. * This represents a texture coming from an HDR input.
  75164. *
  75165. * The only supported format is currently panorama picture stored in RGBE format.
  75166. * Example of such files can be found on HDRLib: http://hdrlib.com/
  75167. */
  75168. var HDRCubeTexture = /** @class */ (function (_super) {
  75169. __extends(HDRCubeTexture, _super);
  75170. /**
  75171. * Instantiates an HDRTexture from the following parameters.
  75172. *
  75173. * @param url The location of the HDR raw data (Panorama stored in RGBE format)
  75174. * @param scene The scene the texture will be used in
  75175. * @param size The cubemap 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.
  75176. * @param noMipmap Forces to not generate the mipmap if true
  75177. * @param generateHarmonics Specifies whether you want to extract the polynomial harmonics during the generation process
  75178. * @param useInGammaSpace 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)
  75179. * @param usePMREMGenerator Specifies whether or not to generate the CubeMap through CubeMapGen to avoid seams issue at run time.
  75180. */
  75181. function HDRCubeTexture(url, scene, size, noMipmap, generateHarmonics, useInGammaSpace, usePMREMGenerator, onLoad, onError) {
  75182. if (noMipmap === void 0) { noMipmap = false; }
  75183. if (generateHarmonics === void 0) { generateHarmonics = true; }
  75184. if (useInGammaSpace === void 0) { useInGammaSpace = false; }
  75185. if (usePMREMGenerator === void 0) { usePMREMGenerator = false; }
  75186. if (onLoad === void 0) { onLoad = null; }
  75187. if (onError === void 0) { onError = null; }
  75188. var _this = _super.call(this, scene) || this;
  75189. _this._useInGammaSpace = false;
  75190. _this._generateHarmonics = true;
  75191. _this._isBABYLONPreprocessed = false;
  75192. _this._onLoad = null;
  75193. _this._onError = null;
  75194. /**
  75195. * The texture coordinates mode. As this texture is stored in a cube format, please modify carefully.
  75196. */
  75197. _this.coordinatesMode = BABYLON.Texture.CUBIC_MODE;
  75198. /**
  75199. * Specifies wether the texture has been generated through the PMREMGenerator tool.
  75200. * This is usefull at run time to apply the good shader.
  75201. */
  75202. _this.isPMREM = false;
  75203. _this._isBlocking = true;
  75204. /**
  75205. * Gets or sets the center of the bounding box associated with the cube texture
  75206. * It must define where the camera used to render the texture was set
  75207. */
  75208. _this.boundingBoxPosition = BABYLON.Vector3.Zero();
  75209. if (!url) {
  75210. return _this;
  75211. }
  75212. _this.name = url;
  75213. _this.url = url;
  75214. _this.hasAlpha = false;
  75215. _this.isCube = true;
  75216. _this._textureMatrix = BABYLON.Matrix.Identity();
  75217. _this._onLoad = onLoad;
  75218. _this._onError = onError;
  75219. _this.gammaSpace = false;
  75220. var caps = scene.getEngine().getCaps();
  75221. if (size) {
  75222. _this._isBABYLONPreprocessed = false;
  75223. _this._noMipmap = noMipmap;
  75224. _this._size = size;
  75225. _this._useInGammaSpace = useInGammaSpace;
  75226. _this._usePMREMGenerator = usePMREMGenerator &&
  75227. caps.textureLOD &&
  75228. caps.textureFloat &&
  75229. !_this._useInGammaSpace;
  75230. }
  75231. else {
  75232. _this._isBABYLONPreprocessed = true;
  75233. _this._noMipmap = false;
  75234. _this._useInGammaSpace = false;
  75235. _this._usePMREMGenerator = caps.textureLOD && caps.textureFloat &&
  75236. !_this._useInGammaSpace;
  75237. }
  75238. _this.isPMREM = _this._usePMREMGenerator;
  75239. _this._texture = _this._getFromCache(url, _this._noMipmap);
  75240. if (!_this._texture) {
  75241. if (!scene.useDelayedTextureLoading) {
  75242. _this.loadTexture();
  75243. }
  75244. else {
  75245. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  75246. }
  75247. }
  75248. return _this;
  75249. }
  75250. Object.defineProperty(HDRCubeTexture.prototype, "isBlocking", {
  75251. /**
  75252. * Gets wether or not the texture is blocking during loading.
  75253. */
  75254. get: function () {
  75255. return this._isBlocking;
  75256. },
  75257. /**
  75258. * Sets wether or not the texture is blocking during loading.
  75259. */
  75260. set: function (value) {
  75261. this._isBlocking = value;
  75262. },
  75263. enumerable: true,
  75264. configurable: true
  75265. });
  75266. Object.defineProperty(HDRCubeTexture.prototype, "boundingBoxSize", {
  75267. get: function () {
  75268. return this._boundingBoxSize;
  75269. },
  75270. /**
  75271. * Gets or sets the size of the bounding box associated with the cube texture
  75272. * When defined, the cubemap will switch to local mode
  75273. * @see https://community.arm.com/graphics/b/blog/posts/reflections-based-on-local-cubemaps-in-unity
  75274. * @example https://www.babylonjs-playground.com/#RNASML
  75275. */
  75276. set: function (value) {
  75277. if (this._boundingBoxSize && this._boundingBoxSize.equals(value)) {
  75278. return;
  75279. }
  75280. this._boundingBoxSize = value;
  75281. var scene = this.getScene();
  75282. if (scene) {
  75283. scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  75284. }
  75285. },
  75286. enumerable: true,
  75287. configurable: true
  75288. });
  75289. /**
  75290. * Occurs when the file is a preprocessed .babylon.hdr file.
  75291. */
  75292. HDRCubeTexture.prototype.loadBabylonTexture = function () {
  75293. var _this = this;
  75294. var mipLevels = 0;
  75295. var floatArrayView = null;
  75296. var scene = this.getScene();
  75297. var mipmapGenerator = (!this._useInGammaSpace && scene && scene.getEngine().getCaps().textureFloat) ? function (data) {
  75298. var mips = new Array();
  75299. if (!floatArrayView) {
  75300. return mips;
  75301. }
  75302. var startIndex = 30;
  75303. for (var level = 0; level < mipLevels; level++) {
  75304. mips.push([]);
  75305. // Fill each pixel of the mip level.
  75306. var faceSize = Math.pow(_this._size >> level, 2) * 3;
  75307. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  75308. var faceData = floatArrayView.subarray(startIndex, startIndex + faceSize);
  75309. mips[level].push(faceData);
  75310. startIndex += faceSize;
  75311. }
  75312. }
  75313. return mips;
  75314. } : null;
  75315. var callback = function (buffer) {
  75316. var scene = _this.getScene();
  75317. if (!scene) {
  75318. return null;
  75319. }
  75320. // Create Native Array Views
  75321. var intArrayView = new Int32Array(buffer);
  75322. floatArrayView = new Float32Array(buffer);
  75323. // Fill header.
  75324. var version = intArrayView[0]; // Version 1. (MAy be use in case of format changes for backward compaibility)
  75325. _this._size = intArrayView[1]; // CubeMap max mip face size.
  75326. // Update Texture Information.
  75327. if (!_this._texture) {
  75328. return null;
  75329. }
  75330. _this._texture.updateSize(_this._size, _this._size);
  75331. // Fill polynomial information.
  75332. var sphericalPolynomial = new BABYLON.SphericalPolynomial();
  75333. sphericalPolynomial.x.copyFromFloats(floatArrayView[2], floatArrayView[3], floatArrayView[4]);
  75334. sphericalPolynomial.y.copyFromFloats(floatArrayView[5], floatArrayView[6], floatArrayView[7]);
  75335. sphericalPolynomial.z.copyFromFloats(floatArrayView[8], floatArrayView[9], floatArrayView[10]);
  75336. sphericalPolynomial.xx.copyFromFloats(floatArrayView[11], floatArrayView[12], floatArrayView[13]);
  75337. sphericalPolynomial.yy.copyFromFloats(floatArrayView[14], floatArrayView[15], floatArrayView[16]);
  75338. sphericalPolynomial.zz.copyFromFloats(floatArrayView[17], floatArrayView[18], floatArrayView[19]);
  75339. sphericalPolynomial.xy.copyFromFloats(floatArrayView[20], floatArrayView[21], floatArrayView[22]);
  75340. sphericalPolynomial.yz.copyFromFloats(floatArrayView[23], floatArrayView[24], floatArrayView[25]);
  75341. sphericalPolynomial.zx.copyFromFloats(floatArrayView[26], floatArrayView[27], floatArrayView[28]);
  75342. _this.sphericalPolynomial = sphericalPolynomial;
  75343. // Fill pixel data.
  75344. mipLevels = intArrayView[29]; // Number of mip levels.
  75345. var startIndex = 30;
  75346. var data = [];
  75347. var faceSize = Math.pow(_this._size, 2) * 3;
  75348. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  75349. data.push(floatArrayView.subarray(startIndex, startIndex + faceSize));
  75350. startIndex += faceSize;
  75351. }
  75352. var results = [];
  75353. var byteArray = null;
  75354. // Push each faces.
  75355. for (var k = 0; k < 6; k++) {
  75356. var dataFace = null;
  75357. // To be deprecated.
  75358. if (version === 1) {
  75359. var j = ([0, 2, 4, 1, 3, 5])[k]; // Transforms +X+Y+Z... to +X-X+Y-Y...
  75360. dataFace = data[j];
  75361. }
  75362. // If special cases.
  75363. if (!mipmapGenerator && dataFace) {
  75364. if (!scene.getEngine().getCaps().textureFloat) {
  75365. // 3 channels of 1 bytes per pixel in bytes.
  75366. var byteBuffer = new ArrayBuffer(faceSize);
  75367. byteArray = new Uint8Array(byteBuffer);
  75368. }
  75369. for (var i = 0; i < _this._size * _this._size; i++) {
  75370. // Put in gamma space if requested.
  75371. if (_this._useInGammaSpace) {
  75372. dataFace[(i * 3) + 0] = Math.pow(dataFace[(i * 3) + 0], BABYLON.ToGammaSpace);
  75373. dataFace[(i * 3) + 1] = Math.pow(dataFace[(i * 3) + 1], BABYLON.ToGammaSpace);
  75374. dataFace[(i * 3) + 2] = Math.pow(dataFace[(i * 3) + 2], BABYLON.ToGammaSpace);
  75375. }
  75376. // Convert to int texture for fallback.
  75377. if (byteArray) {
  75378. var r = Math.max(dataFace[(i * 3) + 0] * 255, 0);
  75379. var g = Math.max(dataFace[(i * 3) + 1] * 255, 0);
  75380. var b = Math.max(dataFace[(i * 3) + 2] * 255, 0);
  75381. // May use luminance instead if the result is not accurate.
  75382. var max = Math.max(Math.max(r, g), b);
  75383. if (max > 255) {
  75384. var scale = 255 / max;
  75385. r *= scale;
  75386. g *= scale;
  75387. b *= scale;
  75388. }
  75389. byteArray[(i * 3) + 0] = r;
  75390. byteArray[(i * 3) + 1] = g;
  75391. byteArray[(i * 3) + 2] = b;
  75392. }
  75393. }
  75394. }
  75395. // Fill the array accordingly.
  75396. if (byteArray) {
  75397. results.push(byteArray);
  75398. }
  75399. else {
  75400. results.push(dataFace);
  75401. }
  75402. }
  75403. return results;
  75404. };
  75405. if (scene) {
  75406. 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, mipmapGenerator, this._onLoad, this._onError);
  75407. }
  75408. };
  75409. /**
  75410. * Occurs when the file is raw .hdr file.
  75411. */
  75412. HDRCubeTexture.prototype.loadHDRTexture = function () {
  75413. var _this = this;
  75414. var callback = function (buffer) {
  75415. var scene = _this.getScene();
  75416. if (!scene) {
  75417. return null;
  75418. }
  75419. // Extract the raw linear data.
  75420. var data = BABYLON.HDRTools.GetCubeMapTextureData(buffer, _this._size);
  75421. // Generate harmonics if needed.
  75422. if (_this._generateHarmonics) {
  75423. var sphericalPolynomial = BABYLON.CubeMapToSphericalPolynomialTools.ConvertCubeMapToSphericalPolynomial(data);
  75424. _this.sphericalPolynomial = sphericalPolynomial;
  75425. }
  75426. var results = [];
  75427. var byteArray = null;
  75428. // Push each faces.
  75429. for (var j = 0; j < 6; j++) {
  75430. // Create uintarray fallback.
  75431. if (!scene.getEngine().getCaps().textureFloat) {
  75432. // 3 channels of 1 bytes per pixel in bytes.
  75433. var byteBuffer = new ArrayBuffer(_this._size * _this._size * 3);
  75434. byteArray = new Uint8Array(byteBuffer);
  75435. }
  75436. var dataFace = (data[HDRCubeTexture._facesMapping[j]]);
  75437. // If special cases.
  75438. if (_this._useInGammaSpace || byteArray) {
  75439. for (var i = 0; i < _this._size * _this._size; i++) {
  75440. // Put in gamma space if requested.
  75441. if (_this._useInGammaSpace) {
  75442. dataFace[(i * 3) + 0] = Math.pow(dataFace[(i * 3) + 0], BABYLON.ToGammaSpace);
  75443. dataFace[(i * 3) + 1] = Math.pow(dataFace[(i * 3) + 1], BABYLON.ToGammaSpace);
  75444. dataFace[(i * 3) + 2] = Math.pow(dataFace[(i * 3) + 2], BABYLON.ToGammaSpace);
  75445. }
  75446. // Convert to int texture for fallback.
  75447. if (byteArray) {
  75448. var r = Math.max(dataFace[(i * 3) + 0] * 255, 0);
  75449. var g = Math.max(dataFace[(i * 3) + 1] * 255, 0);
  75450. var b = Math.max(dataFace[(i * 3) + 2] * 255, 0);
  75451. // May use luminance instead if the result is not accurate.
  75452. var max = Math.max(Math.max(r, g), b);
  75453. if (max > 255) {
  75454. var scale = 255 / max;
  75455. r *= scale;
  75456. g *= scale;
  75457. b *= scale;
  75458. }
  75459. byteArray[(i * 3) + 0] = r;
  75460. byteArray[(i * 3) + 1] = g;
  75461. byteArray[(i * 3) + 2] = b;
  75462. }
  75463. }
  75464. }
  75465. if (byteArray) {
  75466. results.push(byteArray);
  75467. }
  75468. else {
  75469. results.push(dataFace);
  75470. }
  75471. }
  75472. return results;
  75473. };
  75474. var mipmapGenerator = null;
  75475. // TODO. Implement In code PMREM Generator following the LYS toolset generation.
  75476. // if (!this._noMipmap &&
  75477. // this._usePMREMGenerator) {
  75478. // mipmapGenerator = (data: ArrayBufferView[]) => {
  75479. // // Custom setup of the generator matching with the PBR shader values.
  75480. // var generator = new BABYLON.PMREMGenerator(data,
  75481. // this._size,
  75482. // this._size,
  75483. // 0,
  75484. // 3,
  75485. // this.getScene().getEngine().getCaps().textureFloat,
  75486. // 2048,
  75487. // 0.25,
  75488. // false,
  75489. // true);
  75490. // return generator.filterCubeMap();
  75491. // };
  75492. // }
  75493. var scene = this.getScene();
  75494. if (scene) {
  75495. 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, mipmapGenerator, this._onLoad, this._onError);
  75496. }
  75497. };
  75498. /**
  75499. * Starts the loading process of the texture.
  75500. */
  75501. HDRCubeTexture.prototype.loadTexture = function () {
  75502. if (this._isBABYLONPreprocessed) {
  75503. this.loadBabylonTexture();
  75504. }
  75505. else {
  75506. this.loadHDRTexture();
  75507. }
  75508. };
  75509. HDRCubeTexture.prototype.clone = function () {
  75510. var scene = this.getScene();
  75511. if (!scene) {
  75512. return this;
  75513. }
  75514. var size = (this._isBABYLONPreprocessed ? null : this._size);
  75515. var newTexture = new HDRCubeTexture(this.url, scene, size, this._noMipmap, this._generateHarmonics, this._useInGammaSpace, this._usePMREMGenerator);
  75516. // Base texture
  75517. newTexture.level = this.level;
  75518. newTexture.wrapU = this.wrapU;
  75519. newTexture.wrapV = this.wrapV;
  75520. newTexture.coordinatesIndex = this.coordinatesIndex;
  75521. newTexture.coordinatesMode = this.coordinatesMode;
  75522. return newTexture;
  75523. };
  75524. // Methods
  75525. HDRCubeTexture.prototype.delayLoad = function () {
  75526. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  75527. return;
  75528. }
  75529. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  75530. this._texture = this._getFromCache(this.url, this._noMipmap);
  75531. if (!this._texture) {
  75532. this.loadTexture();
  75533. }
  75534. };
  75535. HDRCubeTexture.prototype.getReflectionTextureMatrix = function () {
  75536. return this._textureMatrix;
  75537. };
  75538. HDRCubeTexture.prototype.setReflectionTextureMatrix = function (value) {
  75539. this._textureMatrix = value;
  75540. };
  75541. HDRCubeTexture.Parse = function (parsedTexture, scene, rootUrl) {
  75542. var texture = null;
  75543. if (parsedTexture.name && !parsedTexture.isRenderTarget) {
  75544. var size = parsedTexture.isBABYLONPreprocessed ? null : parsedTexture.size;
  75545. texture = new HDRCubeTexture(rootUrl + parsedTexture.name, scene, size, parsedTexture.noMipmap, parsedTexture.generateHarmonics, parsedTexture.useInGammaSpace, parsedTexture.usePMREMGenerator);
  75546. texture.name = parsedTexture.name;
  75547. texture.hasAlpha = parsedTexture.hasAlpha;
  75548. texture.level = parsedTexture.level;
  75549. texture.coordinatesMode = parsedTexture.coordinatesMode;
  75550. texture.isBlocking = parsedTexture.isBlocking;
  75551. }
  75552. if (texture) {
  75553. if (parsedTexture.boundingBoxPosition) {
  75554. texture.boundingBoxPosition = BABYLON.Vector3.FromArray(parsedTexture.boundingBoxPosition);
  75555. }
  75556. if (parsedTexture.boundingBoxSize) {
  75557. texture.boundingBoxSize = BABYLON.Vector3.FromArray(parsedTexture.boundingBoxSize);
  75558. }
  75559. }
  75560. return texture;
  75561. };
  75562. HDRCubeTexture.prototype.serialize = function () {
  75563. if (!this.name) {
  75564. return null;
  75565. }
  75566. var serializationObject = {};
  75567. serializationObject.name = this.name;
  75568. serializationObject.hasAlpha = this.hasAlpha;
  75569. serializationObject.isCube = true;
  75570. serializationObject.level = this.level;
  75571. serializationObject.size = this._size;
  75572. serializationObject.coordinatesMode = this.coordinatesMode;
  75573. serializationObject.useInGammaSpace = this._useInGammaSpace;
  75574. serializationObject.generateHarmonics = this._generateHarmonics;
  75575. serializationObject.usePMREMGenerator = this._usePMREMGenerator;
  75576. serializationObject.isBABYLONPreprocessed = this._isBABYLONPreprocessed;
  75577. serializationObject.customType = "BABYLON.HDRCubeTexture";
  75578. serializationObject.noMipmap = this._noMipmap;
  75579. serializationObject.isBlocking = this._isBlocking;
  75580. return serializationObject;
  75581. };
  75582. /**
  75583. * Saves as a file the data contained in the texture in a binary format.
  75584. * This can be used to prevent the long loading tie associated with creating the seamless texture as well
  75585. * as the spherical used in the lighting.
  75586. * @param url The HDR file url.
  75587. * @param size The size of the texture data to generate (one of the cubemap face desired width).
  75588. * @param onError Method called if any error happens during download.
  75589. * @return The packed binary data.
  75590. */
  75591. HDRCubeTexture.generateBabylonHDROnDisk = function (url, size, onError) {
  75592. if (onError === void 0) { onError = null; }
  75593. var callback = function (buffer) {
  75594. var data = new Blob([buffer], { type: 'application/octet-stream' });
  75595. // Returns a URL you can use as a href.
  75596. var objUrl = window.URL.createObjectURL(data);
  75597. // Simulates a link to it and click to dowload.
  75598. var a = document.createElement("a");
  75599. document.body.appendChild(a);
  75600. a.style.display = "none";
  75601. a.href = objUrl;
  75602. a.download = "envmap.babylon.hdr";
  75603. a.click();
  75604. };
  75605. HDRCubeTexture.generateBabylonHDR(url, size, callback, onError);
  75606. };
  75607. /**
  75608. * Serializes the data contained in the texture in a binary format.
  75609. * This can be used to prevent the long loading tie associated with creating the seamless texture as well
  75610. * as the spherical used in the lighting.
  75611. * @param url The HDR file url.
  75612. * @param size The size of the texture data to generate (one of the cubemap face desired width).
  75613. * @param onError Method called if any error happens during download.
  75614. * @return The packed binary data.
  75615. */
  75616. HDRCubeTexture.generateBabylonHDR = function (url, size, callback, onError) {
  75617. if (onError === void 0) { onError = null; }
  75618. // Needs the url tho create the texture.
  75619. if (!url) {
  75620. return;
  75621. }
  75622. // Check Power of two size.
  75623. if (!BABYLON.Tools.IsExponentOfTwo(size)) {
  75624. return;
  75625. }
  75626. // Coming Back in 3.x.
  75627. BABYLON.Tools.Error("Generation of Babylon HDR is coming back in 3.2.");
  75628. };
  75629. HDRCubeTexture._facesMapping = [
  75630. "right",
  75631. "left",
  75632. "up",
  75633. "down",
  75634. "front",
  75635. "back"
  75636. ];
  75637. return HDRCubeTexture;
  75638. }(BABYLON.BaseTexture));
  75639. BABYLON.HDRCubeTexture = HDRCubeTexture;
  75640. })(BABYLON || (BABYLON = {}));
  75641. //# sourceMappingURL=babylon.hdrCubeTexture.js.map
  75642. "use strict";
  75643. // All the credit goes to this project and the guy who's behind it https://github.com/mapbox/earcut
  75644. // Huge respect for a such great lib.
  75645. // Earcut license:
  75646. // Copyright (c) 2016, Mapbox
  75647. //
  75648. // Permission to use, copy, modify, and/or distribute this software for any purpose
  75649. // with or without fee is hereby granted, provided that the above copyright notice
  75650. // and this permission notice appear in all copies.
  75651. //
  75652. // THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH
  75653. // REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND
  75654. // FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,
  75655. // INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS
  75656. // OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER
  75657. // TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF
  75658. // THIS SOFTWARE.
  75659. var Earcut;
  75660. (function (Earcut) {
  75661. /**
  75662. * The fastest and smallest JavaScript polygon triangulation library for your WebGL apps
  75663. * @param data is a flat array of vertice coordinates like [x0, y0, x1, y1, x2, y2, ...].
  75664. * @param holeIndices is an array of hole indices if any (e.g. [5, 8] for a 12- vertice input would mean one hole with vertices 5–7 and another with 8–11).
  75665. * @param dim is the number of coordinates per vertice in the input array (2 by default).
  75666. */
  75667. function earcut(data, holeIndices, dim) {
  75668. dim = dim || 2;
  75669. var hasHoles = holeIndices && holeIndices.length, outerLen = hasHoles ? holeIndices[0] * dim : data.length, outerNode = linkedList(data, 0, outerLen, dim, true), triangles = new Array();
  75670. if (!outerNode)
  75671. return triangles;
  75672. var minX = 0, minY = 0, maxX, maxY, x, y, size = 0;
  75673. if (hasHoles)
  75674. outerNode = eliminateHoles(data, holeIndices, outerNode, dim);
  75675. // if the shape is not too simple, we'll use z-order curve hash later; calculate polygon bbox
  75676. if (data.length > 80 * dim) {
  75677. minX = maxX = data[0];
  75678. minY = maxY = data[1];
  75679. for (var i = dim; i < outerLen; i += dim) {
  75680. x = data[i];
  75681. y = data[i + 1];
  75682. if (x < minX)
  75683. minX = x;
  75684. if (y < minY)
  75685. minY = y;
  75686. if (x > maxX)
  75687. maxX = x;
  75688. if (y > maxY)
  75689. maxY = y;
  75690. }
  75691. // minX, minY and size are later used to transform coords into integers for z-order calculation
  75692. size = Math.max(maxX - minX, maxY - minY);
  75693. }
  75694. earcutLinked(outerNode, triangles, dim, minX, minY, size, 0);
  75695. return triangles;
  75696. }
  75697. Earcut.earcut = earcut;
  75698. var Node = /** @class */ (function () {
  75699. function Node(i, x, y) {
  75700. this.i = i;
  75701. this.x = x;
  75702. this.y = y;
  75703. this.prev = null;
  75704. this.next = null;
  75705. this.z = null;
  75706. this.prevZ = null;
  75707. this.nextZ = null;
  75708. this.steiner = false;
  75709. }
  75710. return Node;
  75711. }());
  75712. // create a circular doubly linked list from polygon points in the specified winding order
  75713. function linkedList(data, start, end, dim, clockwise) {
  75714. var i, last = null;
  75715. if (clockwise === (signedArea(data, start, end, dim) > 0)) {
  75716. for (i = start; i < end; i += dim)
  75717. last = insertNode(i, data[i], data[i + 1], last);
  75718. }
  75719. else {
  75720. for (i = end - dim; i >= start; i -= dim)
  75721. last = insertNode(i, data[i], data[i + 1], last);
  75722. }
  75723. if (last && equals(last, last.next)) {
  75724. removeNode(last);
  75725. last = last.next;
  75726. }
  75727. return last;
  75728. }
  75729. // eliminate colinear or duplicate points
  75730. function filterPoints(start, end) {
  75731. if (!start)
  75732. return start;
  75733. if (!end)
  75734. end = start;
  75735. var p = start, again;
  75736. do {
  75737. again = false;
  75738. if (!p.steiner && (equals(p, p.next) || area(p.prev, p, p.next) === 0)) {
  75739. removeNode(p);
  75740. p = end = p.prev;
  75741. if (p === p.next)
  75742. return undefined;
  75743. again = true;
  75744. }
  75745. else {
  75746. p = p.next;
  75747. }
  75748. } while (again || p !== end);
  75749. return end;
  75750. }
  75751. // main ear slicing loop which triangulates a polygon (given as a linked list)
  75752. function earcutLinked(ear, triangles, dim, minX, minY, size, pass) {
  75753. if (!ear)
  75754. return;
  75755. // interlink polygon nodes in z-order
  75756. if (!pass && size)
  75757. indexCurve(ear, minX, minY, size);
  75758. var stop = ear, prev, next;
  75759. // iterate through ears, slicing them one by one
  75760. while (ear.prev !== ear.next) {
  75761. prev = ear.prev;
  75762. next = ear.next;
  75763. if (size ? isEarHashed(ear, minX, minY, size) : isEar(ear)) {
  75764. // cut off the triangle
  75765. triangles.push(prev.i / dim);
  75766. triangles.push(ear.i / dim);
  75767. triangles.push(next.i / dim);
  75768. removeNode(ear);
  75769. // skipping the next vertice leads to less sliver triangles
  75770. ear = next.next;
  75771. stop = next.next;
  75772. continue;
  75773. }
  75774. ear = next;
  75775. // if we looped through the whole remaining polygon and can't find any more ears
  75776. if (ear === stop) {
  75777. // try filtering points and slicing again
  75778. if (!pass) {
  75779. earcutLinked(filterPoints(ear, undefined), triangles, dim, minX, minY, size, 1);
  75780. // if this didn't work, try curing all small self-intersections locally
  75781. }
  75782. else if (pass === 1) {
  75783. ear = cureLocalIntersections(ear, triangles, dim);
  75784. earcutLinked(ear, triangles, dim, minX, minY, size, 2);
  75785. // as a last resort, try splitting the remaining polygon into two
  75786. }
  75787. else if (pass === 2) {
  75788. splitEarcut(ear, triangles, dim, minX, minY, size);
  75789. }
  75790. break;
  75791. }
  75792. }
  75793. }
  75794. // check whether a polygon node forms a valid ear with adjacent nodes
  75795. function isEar(ear) {
  75796. var a = ear.prev, b = ear, c = ear.next;
  75797. if (area(a, b, c) >= 0)
  75798. return false; // reflex, can't be an ear
  75799. // now make sure we don't have other points inside the potential ear
  75800. var p = ear.next.next;
  75801. while (p !== ear.prev) {
  75802. if (pointInTriangle(a.x, a.y, b.x, b.y, c.x, c.y, p.x, p.y) &&
  75803. area(p.prev, p, p.next) >= 0)
  75804. return false;
  75805. p = p.next;
  75806. }
  75807. return true;
  75808. }
  75809. function isEarHashed(ear, minX, minY, size) {
  75810. var a = ear.prev, b = ear, c = ear.next;
  75811. if (area(a, b, c) >= 0)
  75812. return false; // reflex, can't be an ear
  75813. // triangle bbox; min & max are calculated like this for speed
  75814. var minTX = a.x < b.x ? (a.x < c.x ? a.x : c.x) : (b.x < c.x ? b.x : c.x), minTY = a.y < b.y ? (a.y < c.y ? a.y : c.y) : (b.y < c.y ? b.y : c.y), maxTX = a.x > b.x ? (a.x > c.x ? a.x : c.x) : (b.x > c.x ? b.x : c.x), maxTY = a.y > b.y ? (a.y > c.y ? a.y : c.y) : (b.y > c.y ? b.y : c.y);
  75815. // z-order range for the current triangle bbox;
  75816. var minZ = zOrder(minTX, minTY, minX, minY, size), maxZ = zOrder(maxTX, maxTY, minX, minY, size);
  75817. // first look for points inside the triangle in increasing z-order
  75818. var p = ear.nextZ;
  75819. while (p && p.z <= maxZ) {
  75820. if (p !== ear.prev &&
  75821. p !== ear.next &&
  75822. pointInTriangle(a.x, a.y, b.x, b.y, c.x, c.y, p.x, p.y) &&
  75823. area(p.prev, p, p.next) >= 0)
  75824. return false;
  75825. p = p.nextZ;
  75826. }
  75827. // then look for points in decreasing z-order
  75828. p = ear.prevZ;
  75829. while (p && p.z >= minZ) {
  75830. if (p !== ear.prev &&
  75831. p !== ear.next &&
  75832. pointInTriangle(a.x, a.y, b.x, b.y, c.x, c.y, p.x, p.y) &&
  75833. area(p.prev, p, p.next) >= 0)
  75834. return false;
  75835. p = p.prevZ;
  75836. }
  75837. return true;
  75838. }
  75839. // go through all polygon nodes and cure small local self-intersections
  75840. function cureLocalIntersections(start, triangles, dim) {
  75841. var p = start;
  75842. do {
  75843. var a = p.prev, b = p.next.next;
  75844. if (!equals(a, b) && intersects(a, p, p.next, b) && locallyInside(a, b) && locallyInside(b, a)) {
  75845. triangles.push(a.i / dim);
  75846. triangles.push(p.i / dim);
  75847. triangles.push(b.i / dim);
  75848. // remove two nodes involved
  75849. removeNode(p);
  75850. removeNode(p.next);
  75851. p = start = b;
  75852. }
  75853. p = p.next;
  75854. } while (p !== start);
  75855. return p;
  75856. }
  75857. // try splitting polygon into two and triangulate them independently
  75858. function splitEarcut(start, triangles, dim, minX, minY, size) {
  75859. // look for a valid diagonal that divides the polygon into two
  75860. var a = start;
  75861. do {
  75862. var b = a.next.next;
  75863. while (b !== a.prev) {
  75864. if (a.i !== b.i && isValidDiagonal(a, b)) {
  75865. // split the polygon in two by the diagonal
  75866. var c = splitPolygon(a, b);
  75867. // filter colinear points around the cuts
  75868. a = filterPoints(a, a.next);
  75869. c = filterPoints(c, c.next);
  75870. // run earcut on each half
  75871. earcutLinked(a, triangles, dim, minX, minY, size, undefined);
  75872. earcutLinked(c, triangles, dim, minX, minY, size, undefined);
  75873. return;
  75874. }
  75875. b = b.next;
  75876. }
  75877. a = a.next;
  75878. } while (a !== start);
  75879. }
  75880. // link every hole into the outer loop, producing a single-ring polygon without holes
  75881. function eliminateHoles(data, holeIndices, outerNode, dim) {
  75882. var queue = [], i, len, start, end, list;
  75883. for (i = 0, len = holeIndices.length; i < len; i++) {
  75884. start = holeIndices[i] * dim;
  75885. end = i < len - 1 ? holeIndices[i + 1] * dim : data.length;
  75886. list = linkedList(data, start, end, dim, false);
  75887. if (list === list.next)
  75888. list.steiner = true;
  75889. queue.push(getLeftmost(list));
  75890. }
  75891. queue.sort(compareX);
  75892. // process holes from left to right
  75893. for (i = 0; i < queue.length; i++) {
  75894. eliminateHole(queue[i], outerNode);
  75895. outerNode = filterPoints(outerNode, outerNode.next);
  75896. }
  75897. return outerNode;
  75898. }
  75899. function compareX(a, b) {
  75900. return a.x - b.x;
  75901. }
  75902. // find a bridge between vertices that connects hole with an outer ring and and link it
  75903. function eliminateHole(hole, outerNode) {
  75904. outerNode = findHoleBridge(hole, outerNode);
  75905. if (outerNode) {
  75906. var b = splitPolygon(outerNode, hole);
  75907. filterPoints(b, b.next);
  75908. }
  75909. }
  75910. // David Eberly's algorithm for finding a bridge between hole and outer polygon
  75911. function findHoleBridge(hole, outerNode) {
  75912. var p = outerNode, hx = hole.x, hy = hole.y, qx = -Infinity, m;
  75913. // find a segment intersected by a ray from the hole's leftmost point to the left;
  75914. // segment's endpoint with lesser x will be potential connection point
  75915. do {
  75916. if (hy <= p.y && hy >= p.next.y) {
  75917. var x = p.x + (hy - p.y) * (p.next.x - p.x) / (p.next.y - p.y);
  75918. if (x <= hx && x > qx) {
  75919. qx = x;
  75920. if (x === hx) {
  75921. if (hy === p.y)
  75922. return p;
  75923. if (hy === p.next.y)
  75924. return p.next;
  75925. }
  75926. m = p.x < p.next.x ? p : p.next;
  75927. }
  75928. }
  75929. p = p.next;
  75930. } while (p !== outerNode);
  75931. if (!m)
  75932. return null;
  75933. if (hx === qx)
  75934. return m.prev; // hole touches outer segment; pick lower endpoint
  75935. // look for points inside the triangle of hole point, segment intersection and endpoint;
  75936. // if there are no points found, we have a valid connection;
  75937. // otherwise choose the point of the minimum angle with the ray as connection point
  75938. var stop = m, mx = m.x, my = m.y, tanMin = Infinity, tan;
  75939. p = m.next;
  75940. while (p !== stop) {
  75941. if (hx >= p.x &&
  75942. p.x >= mx &&
  75943. pointInTriangle(hy < my ? hx : qx, hy, mx, my, hy < my ? qx : hx, hy, p.x, p.y)) {
  75944. tan = Math.abs(hy - p.y) / (hx - p.x); // tangential
  75945. if ((tan < tanMin || (tan === tanMin && p.x > m.x)) && locallyInside(p, hole)) {
  75946. m = p;
  75947. tanMin = tan;
  75948. }
  75949. }
  75950. p = p.next;
  75951. }
  75952. return m;
  75953. }
  75954. // interlink polygon nodes in z-order
  75955. function indexCurve(start, minX, minY, size) {
  75956. var p = start;
  75957. do {
  75958. if (p.z === null)
  75959. p.z = zOrder(p.x, p.y, minX, minY, size);
  75960. p.prevZ = p.prev;
  75961. p.nextZ = p.next;
  75962. p = p.next;
  75963. } while (p !== start);
  75964. p.prevZ.nextZ = null;
  75965. p.prevZ = null;
  75966. sortLinked(p);
  75967. }
  75968. // Simon Tatham's linked list merge sort algorithm
  75969. // http://www.chiark.greenend.org.uk/~sgtatham/algorithms/listsort.html
  75970. function sortLinked(list) {
  75971. var i, p, q, e, tail, numMerges, pSize, qSize, inSize = 1;
  75972. do {
  75973. p = list;
  75974. list = null;
  75975. tail = null;
  75976. numMerges = 0;
  75977. while (p) {
  75978. numMerges++;
  75979. q = p;
  75980. pSize = 0;
  75981. for (i = 0; i < inSize; i++) {
  75982. pSize++;
  75983. q = q.nextZ;
  75984. if (!q)
  75985. break;
  75986. }
  75987. qSize = inSize;
  75988. while (pSize > 0 || (qSize > 0 && q)) {
  75989. if (pSize === 0) {
  75990. e = q;
  75991. q = q.nextZ;
  75992. qSize--;
  75993. }
  75994. else if (qSize === 0 || !q) {
  75995. e = p;
  75996. p = p.nextZ;
  75997. pSize--;
  75998. }
  75999. else if (p.z <= q.z) {
  76000. e = p;
  76001. p = p.nextZ;
  76002. pSize--;
  76003. }
  76004. else {
  76005. e = q;
  76006. q = q.nextZ;
  76007. qSize--;
  76008. }
  76009. if (tail)
  76010. tail.nextZ = e;
  76011. else
  76012. list = e;
  76013. e.prevZ = tail;
  76014. tail = e;
  76015. }
  76016. p = q;
  76017. }
  76018. tail.nextZ = null;
  76019. inSize *= 2;
  76020. } while (numMerges > 1);
  76021. return list;
  76022. }
  76023. // z-order of a point given coords and size of the data bounding box
  76024. function zOrder(x, y, minX, minY, size) {
  76025. // coords are transformed into non-negative 15-bit integer range
  76026. x = 32767 * (x - minX) / size;
  76027. y = 32767 * (y - minY) / size;
  76028. x = (x | (x << 8)) & 0x00FF00FF;
  76029. x = (x | (x << 4)) & 0x0F0F0F0F;
  76030. x = (x | (x << 2)) & 0x33333333;
  76031. x = (x | (x << 1)) & 0x55555555;
  76032. y = (y | (y << 8)) & 0x00FF00FF;
  76033. y = (y | (y << 4)) & 0x0F0F0F0F;
  76034. y = (y | (y << 2)) & 0x33333333;
  76035. y = (y | (y << 1)) & 0x55555555;
  76036. return x | (y << 1);
  76037. }
  76038. // find the leftmost node of a polygon ring
  76039. function getLeftmost(start) {
  76040. var p = start, leftmost = start;
  76041. do {
  76042. if (p.x < leftmost.x)
  76043. leftmost = p;
  76044. p = p.next;
  76045. } while (p !== start);
  76046. return leftmost;
  76047. }
  76048. // check if a point lies within a convex triangle
  76049. function pointInTriangle(ax, ay, bx, by, cx, cy, px, py) {
  76050. return (cx - px) * (ay - py) - (ax - px) * (cy - py) >= 0 &&
  76051. (ax - px) * (by - py) - (bx - px) * (ay - py) >= 0 &&
  76052. (bx - px) * (cy - py) - (cx - px) * (by - py) >= 0;
  76053. }
  76054. // check if a diagonal between two polygon nodes is valid (lies in polygon interior)
  76055. function isValidDiagonal(a, b) {
  76056. return a.next.i !== b.i &&
  76057. a.prev.i !== b.i &&
  76058. !intersectsPolygon(a, b) &&
  76059. locallyInside(a, b) &&
  76060. locallyInside(b, a) &&
  76061. middleInside(a, b);
  76062. }
  76063. // signed area of a triangle
  76064. function area(p, q, r) {
  76065. return (q.y - p.y) * (r.x - q.x) - (q.x - p.x) * (r.y - q.y);
  76066. }
  76067. // check if two points are equal
  76068. function equals(p1, p2) {
  76069. return p1.x === p2.x && p1.y === p2.y;
  76070. }
  76071. // check if two segments intersect
  76072. function intersects(p1, q1, p2, q2) {
  76073. if ((equals(p1, q1) && equals(p2, q2)) ||
  76074. (equals(p1, q2) && equals(p2, q1)))
  76075. return true;
  76076. return area(p1, q1, p2) > 0 !== area(p1, q1, q2) > 0 &&
  76077. area(p2, q2, p1) > 0 !== area(p2, q2, q1) > 0;
  76078. }
  76079. // check if a polygon diagonal intersects any polygon segments
  76080. function intersectsPolygon(a, b) {
  76081. var p = a;
  76082. do {
  76083. if (p.i !== a.i &&
  76084. p.next.i !== a.i &&
  76085. p.i !== b.i &&
  76086. p.next.i !== b.i &&
  76087. intersects(p, p.next, a, b))
  76088. return true;
  76089. p = p.next;
  76090. } while (p !== a);
  76091. return false;
  76092. }
  76093. // check if a polygon diagonal is locally inside the polygon
  76094. function locallyInside(a, b) {
  76095. return area(a.prev, a, a.next) < 0
  76096. ? area(a, b, a.next) >= 0 && area(a, a.prev, b) >= 0
  76097. : area(a, b, a.prev) < 0 || area(a, a.next, b) < 0;
  76098. }
  76099. // check if the middle point of a polygon diagonal is inside the polygon
  76100. function middleInside(a, b) {
  76101. var p = a, inside = false, px = (a.x + b.x) / 2, py = (a.y + b.y) / 2;
  76102. do {
  76103. if (((p.y > py) !== (p.next.y > py)) && (px < (p.next.x - p.x) * (py - p.y) / (p.next.y - p.y) + p.x))
  76104. inside = !inside;
  76105. p = p.next;
  76106. } while (p !== a);
  76107. return inside;
  76108. }
  76109. // link two polygon vertices with a bridge; if the vertices belong to the same ring, it splits polygon into two;
  76110. // if one belongs to the outer ring and another to a hole, it merges it into a single ring
  76111. function splitPolygon(a, b) {
  76112. var a2 = new Node(a.i, a.x, a.y), b2 = new Node(b.i, b.x, b.y), an = a.next, bp = b.prev;
  76113. a.next = b;
  76114. b.prev = a;
  76115. a2.next = an;
  76116. an.prev = a2;
  76117. b2.next = a2;
  76118. a2.prev = b2;
  76119. bp.next = b2;
  76120. b2.prev = bp;
  76121. return b2;
  76122. }
  76123. // create a node and optionally link it with previous one (in a circular doubly linked list)
  76124. function insertNode(i, x, y, last) {
  76125. var p = new Node(i, x, y);
  76126. if (!last) {
  76127. p.prev = p;
  76128. p.next = p;
  76129. }
  76130. else {
  76131. p.next = last.next;
  76132. p.prev = last;
  76133. last.next.prev = p;
  76134. last.next = p;
  76135. }
  76136. return p;
  76137. }
  76138. function removeNode(p) {
  76139. p.next.prev = p.prev;
  76140. p.prev.next = p.next;
  76141. if (p.prevZ)
  76142. p.prevZ.nextZ = p.nextZ;
  76143. if (p.nextZ)
  76144. p.nextZ.prevZ = p.prevZ;
  76145. }
  76146. /**
  76147. * return a percentage difference between the polygon area and its triangulation area;
  76148. * used to verify correctness of triangulation
  76149. */
  76150. function deviation(data, holeIndices, dim, triangles) {
  76151. var hasHoles = holeIndices && holeIndices.length;
  76152. var outerLen = hasHoles ? holeIndices[0] * dim : data.length;
  76153. var polygonArea = Math.abs(signedArea(data, 0, outerLen, dim));
  76154. if (hasHoles) {
  76155. for (var i = 0, len = holeIndices.length; i < len; i++) {
  76156. var start = holeIndices[i] * dim;
  76157. var end = i < len - 1 ? holeIndices[i + 1] * dim : data.length;
  76158. polygonArea -= Math.abs(signedArea(data, start, end, dim));
  76159. }
  76160. }
  76161. var trianglesArea = 0;
  76162. for (i = 0; i < triangles.length; i += 3) {
  76163. var a = triangles[i] * dim;
  76164. var b = triangles[i + 1] * dim;
  76165. var c = triangles[i + 2] * dim;
  76166. trianglesArea += Math.abs((data[a] - data[c]) * (data[b + 1] - data[a + 1]) -
  76167. (data[a] - data[b]) * (data[c + 1] - data[a + 1]));
  76168. }
  76169. return polygonArea === 0 && trianglesArea === 0 ? 0 : Math.abs((trianglesArea - polygonArea) / polygonArea);
  76170. }
  76171. Earcut.deviation = deviation;
  76172. ;
  76173. function signedArea(data, start, end, dim) {
  76174. var sum = 0;
  76175. for (var i = start, j = end - dim; i < end; i += dim) {
  76176. sum += (data[j] - data[i]) * (data[i + 1] + data[j + 1]);
  76177. j = i;
  76178. }
  76179. return sum;
  76180. }
  76181. /**
  76182. * turn a polygon in a multi-dimensional array form (e.g. as in GeoJSON) into a form Earcut accepts
  76183. */
  76184. function flatten(data) {
  76185. var dim = data[0][0].length, result = { vertices: new Array(), holes: new Array(), dimensions: dim }, holeIndex = 0;
  76186. for (var i = 0; i < data.length; i++) {
  76187. for (var j = 0; j < data[i].length; j++) {
  76188. for (var d = 0; d < dim; d++)
  76189. result.vertices.push(data[i][j][d]);
  76190. }
  76191. if (i > 0) {
  76192. holeIndex += data[i - 1].length;
  76193. result.holes.push(holeIndex);
  76194. }
  76195. }
  76196. return result;
  76197. }
  76198. Earcut.flatten = flatten;
  76199. ;
  76200. })(Earcut || (Earcut = {}));
  76201. //# sourceMappingURL=babylon.earcut.js.map
  76202. "use strict";
  76203. var BABYLON;
  76204. (function (BABYLON) {
  76205. var IndexedVector2 = /** @class */ (function (_super) {
  76206. __extends(IndexedVector2, _super);
  76207. function IndexedVector2(original, index) {
  76208. var _this = _super.call(this, original.x, original.y) || this;
  76209. _this.index = index;
  76210. return _this;
  76211. }
  76212. return IndexedVector2;
  76213. }(BABYLON.Vector2));
  76214. var PolygonPoints = /** @class */ (function () {
  76215. function PolygonPoints() {
  76216. this.elements = new Array();
  76217. }
  76218. PolygonPoints.prototype.add = function (originalPoints) {
  76219. var _this = this;
  76220. var result = new Array();
  76221. originalPoints.forEach(function (point) {
  76222. if (result.length === 0 || !point.equalsWithEpsilon(result[0])) {
  76223. var newPoint = new IndexedVector2(point, _this.elements.length);
  76224. result.push(newPoint);
  76225. _this.elements.push(newPoint);
  76226. }
  76227. });
  76228. return result;
  76229. };
  76230. PolygonPoints.prototype.computeBounds = function () {
  76231. var lmin = new BABYLON.Vector2(this.elements[0].x, this.elements[0].y);
  76232. var lmax = new BABYLON.Vector2(this.elements[0].x, this.elements[0].y);
  76233. this.elements.forEach(function (point) {
  76234. // x
  76235. if (point.x < lmin.x) {
  76236. lmin.x = point.x;
  76237. }
  76238. else if (point.x > lmax.x) {
  76239. lmax.x = point.x;
  76240. }
  76241. // y
  76242. if (point.y < lmin.y) {
  76243. lmin.y = point.y;
  76244. }
  76245. else if (point.y > lmax.y) {
  76246. lmax.y = point.y;
  76247. }
  76248. });
  76249. return {
  76250. min: lmin,
  76251. max: lmax,
  76252. width: lmax.x - lmin.x,
  76253. height: lmax.y - lmin.y
  76254. };
  76255. };
  76256. return PolygonPoints;
  76257. }());
  76258. var Polygon = /** @class */ (function () {
  76259. function Polygon() {
  76260. }
  76261. Polygon.Rectangle = function (xmin, ymin, xmax, ymax) {
  76262. return [
  76263. new BABYLON.Vector2(xmin, ymin),
  76264. new BABYLON.Vector2(xmax, ymin),
  76265. new BABYLON.Vector2(xmax, ymax),
  76266. new BABYLON.Vector2(xmin, ymax)
  76267. ];
  76268. };
  76269. Polygon.Circle = function (radius, cx, cy, numberOfSides) {
  76270. if (cx === void 0) { cx = 0; }
  76271. if (cy === void 0) { cy = 0; }
  76272. if (numberOfSides === void 0) { numberOfSides = 32; }
  76273. var result = new Array();
  76274. var angle = 0;
  76275. var increment = (Math.PI * 2) / numberOfSides;
  76276. for (var i = 0; i < numberOfSides; i++) {
  76277. result.push(new BABYLON.Vector2(cx + Math.cos(angle) * radius, cy + Math.sin(angle) * radius));
  76278. angle -= increment;
  76279. }
  76280. return result;
  76281. };
  76282. Polygon.Parse = function (input) {
  76283. var floats = input.split(/[^-+eE\.\d]+/).map(parseFloat).filter(function (val) { return (!isNaN(val)); });
  76284. var i, result = [];
  76285. for (i = 0; i < (floats.length & 0x7FFFFFFE); i += 2) {
  76286. result.push(new BABYLON.Vector2(floats[i], floats[i + 1]));
  76287. }
  76288. return result;
  76289. };
  76290. Polygon.StartingAt = function (x, y) {
  76291. return BABYLON.Path2.StartingAt(x, y);
  76292. };
  76293. return Polygon;
  76294. }());
  76295. BABYLON.Polygon = Polygon;
  76296. var PolygonMeshBuilder = /** @class */ (function () {
  76297. function PolygonMeshBuilder(name, contours, scene) {
  76298. this._points = new PolygonPoints();
  76299. this._outlinepoints = new PolygonPoints();
  76300. this._holes = new Array();
  76301. this._epoints = new Array();
  76302. this._eholes = new Array();
  76303. this._name = name;
  76304. this._scene = scene;
  76305. var points;
  76306. if (contours instanceof BABYLON.Path2) {
  76307. points = contours.getPoints();
  76308. }
  76309. else {
  76310. points = contours;
  76311. }
  76312. this._addToepoint(points);
  76313. this._points.add(points);
  76314. this._outlinepoints.add(points);
  76315. }
  76316. PolygonMeshBuilder.prototype._addToepoint = function (points) {
  76317. for (var _i = 0, points_1 = points; _i < points_1.length; _i++) {
  76318. var p = points_1[_i];
  76319. this._epoints.push(p.x, p.y);
  76320. }
  76321. };
  76322. PolygonMeshBuilder.prototype.addHole = function (hole) {
  76323. this._points.add(hole);
  76324. var holepoints = new PolygonPoints();
  76325. holepoints.add(hole);
  76326. this._holes.push(holepoints);
  76327. this._eholes.push(this._epoints.length / 2);
  76328. this._addToepoint(hole);
  76329. return this;
  76330. };
  76331. PolygonMeshBuilder.prototype.build = function (updatable, depth) {
  76332. var _this = this;
  76333. if (updatable === void 0) { updatable = false; }
  76334. if (depth === void 0) { depth = 0; }
  76335. var result = new BABYLON.Mesh(this._name, this._scene);
  76336. var normals = new Array();
  76337. var positions = new Array();
  76338. var uvs = new Array();
  76339. var bounds = this._points.computeBounds();
  76340. this._points.elements.forEach(function (p) {
  76341. normals.push(0, 1.0, 0);
  76342. positions.push(p.x, 0, p.y);
  76343. uvs.push((p.x - bounds.min.x) / bounds.width, (p.y - bounds.min.y) / bounds.height);
  76344. });
  76345. var indices = new Array();
  76346. var res = Earcut.earcut(this._epoints, this._eholes, 2);
  76347. for (var i = 0; i < res.length; i++) {
  76348. indices.push(res[i]);
  76349. }
  76350. if (depth > 0) {
  76351. var positionscount = (positions.length / 3); //get the current pointcount
  76352. this._points.elements.forEach(function (p) {
  76353. normals.push(0, -1.0, 0);
  76354. positions.push(p.x, -depth, p.y);
  76355. uvs.push(1 - (p.x - bounds.min.x) / bounds.width, 1 - (p.y - bounds.min.y) / bounds.height);
  76356. });
  76357. var totalCount = indices.length;
  76358. for (var i = 0; i < totalCount; i += 3) {
  76359. var i0 = indices[i + 0];
  76360. var i1 = indices[i + 1];
  76361. var i2 = indices[i + 2];
  76362. indices.push(i2 + positionscount);
  76363. indices.push(i1 + positionscount);
  76364. indices.push(i0 + positionscount);
  76365. }
  76366. //Add the sides
  76367. this.addSide(positions, normals, uvs, indices, bounds, this._outlinepoints, depth, false);
  76368. this._holes.forEach(function (hole) {
  76369. _this.addSide(positions, normals, uvs, indices, bounds, hole, depth, true);
  76370. });
  76371. }
  76372. result.setVerticesData(BABYLON.VertexBuffer.PositionKind, positions, updatable);
  76373. result.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals, updatable);
  76374. result.setVerticesData(BABYLON.VertexBuffer.UVKind, uvs, updatable);
  76375. result.setIndices(indices);
  76376. return result;
  76377. };
  76378. PolygonMeshBuilder.prototype.addSide = function (positions, normals, uvs, indices, bounds, points, depth, flip) {
  76379. var StartIndex = positions.length / 3;
  76380. var ulength = 0;
  76381. for (var i = 0; i < points.elements.length; i++) {
  76382. var p = points.elements[i];
  76383. var p1;
  76384. if ((i + 1) > points.elements.length - 1) {
  76385. p1 = points.elements[0];
  76386. }
  76387. else {
  76388. p1 = points.elements[i + 1];
  76389. }
  76390. positions.push(p.x, 0, p.y);
  76391. positions.push(p.x, -depth, p.y);
  76392. positions.push(p1.x, 0, p1.y);
  76393. positions.push(p1.x, -depth, p1.y);
  76394. var v1 = new BABYLON.Vector3(p.x, 0, p.y);
  76395. var v2 = new BABYLON.Vector3(p1.x, 0, p1.y);
  76396. var v3 = v2.subtract(v1);
  76397. var v4 = new BABYLON.Vector3(0, 1, 0);
  76398. var vn = BABYLON.Vector3.Cross(v3, v4);
  76399. vn = vn.normalize();
  76400. uvs.push(ulength / bounds.width, 0);
  76401. uvs.push(ulength / bounds.width, 1);
  76402. ulength += v3.length();
  76403. uvs.push((ulength / bounds.width), 0);
  76404. uvs.push((ulength / bounds.width), 1);
  76405. if (!flip) {
  76406. normals.push(-vn.x, -vn.y, -vn.z);
  76407. normals.push(-vn.x, -vn.y, -vn.z);
  76408. normals.push(-vn.x, -vn.y, -vn.z);
  76409. normals.push(-vn.x, -vn.y, -vn.z);
  76410. indices.push(StartIndex);
  76411. indices.push(StartIndex + 1);
  76412. indices.push(StartIndex + 2);
  76413. indices.push(StartIndex + 1);
  76414. indices.push(StartIndex + 3);
  76415. indices.push(StartIndex + 2);
  76416. }
  76417. else {
  76418. normals.push(vn.x, vn.y, vn.z);
  76419. normals.push(vn.x, vn.y, vn.z);
  76420. normals.push(vn.x, vn.y, vn.z);
  76421. normals.push(vn.x, vn.y, vn.z);
  76422. indices.push(StartIndex);
  76423. indices.push(StartIndex + 2);
  76424. indices.push(StartIndex + 1);
  76425. indices.push(StartIndex + 1);
  76426. indices.push(StartIndex + 2);
  76427. indices.push(StartIndex + 3);
  76428. }
  76429. StartIndex += 4;
  76430. }
  76431. ;
  76432. };
  76433. return PolygonMeshBuilder;
  76434. }());
  76435. BABYLON.PolygonMeshBuilder = PolygonMeshBuilder;
  76436. })(BABYLON || (BABYLON = {}));
  76437. //# sourceMappingURL=babylon.polygonMesh.js.map
  76438. "use strict";
  76439. var BABYLON;
  76440. (function (BABYLON) {
  76441. // Unique ID when we import meshes from Babylon to CSG
  76442. var currentCSGMeshId = 0;
  76443. // # class Vertex
  76444. // Represents a vertex of a polygon. Use your own vertex class instead of this
  76445. // one to provide additional features like texture coordinates and vertex
  76446. // colors. Custom vertex classes need to provide a `pos` property and `clone()`,
  76447. // `flip()`, and `interpolate()` methods that behave analogous to the ones
  76448. // defined by `BABYLON.CSG.Vertex`. This class provides `normal` so convenience
  76449. // functions like `BABYLON.CSG.sphere()` can return a smooth vertex normal, but `normal`
  76450. // is not used anywhere else.
  76451. // Same goes for uv, it allows to keep the original vertex uv coordinates of the 2 meshes
  76452. var Vertex = /** @class */ (function () {
  76453. function Vertex(pos, normal, uv) {
  76454. this.pos = pos;
  76455. this.normal = normal;
  76456. this.uv = uv;
  76457. }
  76458. Vertex.prototype.clone = function () {
  76459. return new Vertex(this.pos.clone(), this.normal.clone(), this.uv.clone());
  76460. };
  76461. // Invert all orientation-specific data (e.g. vertex normal). Called when the
  76462. // orientation of a polygon is flipped.
  76463. Vertex.prototype.flip = function () {
  76464. this.normal = this.normal.scale(-1);
  76465. };
  76466. // Create a new vertex between this vertex and `other` by linearly
  76467. // interpolating all properties using a parameter of `t`. Subclasses should
  76468. // override this to interpolate additional properties.
  76469. Vertex.prototype.interpolate = function (other, t) {
  76470. 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));
  76471. };
  76472. return Vertex;
  76473. }());
  76474. // # class Plane
  76475. // Represents a plane in 3D space.
  76476. var Plane = /** @class */ (function () {
  76477. function Plane(normal, w) {
  76478. this.normal = normal;
  76479. this.w = w;
  76480. }
  76481. Plane.FromPoints = function (a, b, c) {
  76482. var v0 = c.subtract(a);
  76483. var v1 = b.subtract(a);
  76484. if (v0.lengthSquared() === 0 || v1.lengthSquared() === 0) {
  76485. return null;
  76486. }
  76487. var n = BABYLON.Vector3.Normalize(BABYLON.Vector3.Cross(v0, v1));
  76488. return new Plane(n, BABYLON.Vector3.Dot(n, a));
  76489. };
  76490. Plane.prototype.clone = function () {
  76491. return new Plane(this.normal.clone(), this.w);
  76492. };
  76493. Plane.prototype.flip = function () {
  76494. this.normal.scaleInPlace(-1);
  76495. this.w = -this.w;
  76496. };
  76497. // Split `polygon` by this plane if needed, then put the polygon or polygon
  76498. // fragments in the appropriate lists. Coplanar polygons go into either
  76499. // `coplanarFront` or `coplanarBack` depending on their orientation with
  76500. // respect to this plane. Polygons in front or in back of this plane go into
  76501. // either `front` or `back`.
  76502. Plane.prototype.splitPolygon = function (polygon, coplanarFront, coplanarBack, front, back) {
  76503. var COPLANAR = 0;
  76504. var FRONT = 1;
  76505. var BACK = 2;
  76506. var SPANNING = 3;
  76507. // Classify each point as well as the entire polygon into one of the above
  76508. // four classes.
  76509. var polygonType = 0;
  76510. var types = [];
  76511. var i;
  76512. var t;
  76513. for (i = 0; i < polygon.vertices.length; i++) {
  76514. t = BABYLON.Vector3.Dot(this.normal, polygon.vertices[i].pos) - this.w;
  76515. var type = (t < -Plane.EPSILON) ? BACK : (t > Plane.EPSILON) ? FRONT : COPLANAR;
  76516. polygonType |= type;
  76517. types.push(type);
  76518. }
  76519. // Put the polygon in the correct list, splitting it when necessary.
  76520. switch (polygonType) {
  76521. case COPLANAR:
  76522. (BABYLON.Vector3.Dot(this.normal, polygon.plane.normal) > 0 ? coplanarFront : coplanarBack).push(polygon);
  76523. break;
  76524. case FRONT:
  76525. front.push(polygon);
  76526. break;
  76527. case BACK:
  76528. back.push(polygon);
  76529. break;
  76530. case SPANNING:
  76531. var f = [], b = [];
  76532. for (i = 0; i < polygon.vertices.length; i++) {
  76533. var j = (i + 1) % polygon.vertices.length;
  76534. var ti = types[i], tj = types[j];
  76535. var vi = polygon.vertices[i], vj = polygon.vertices[j];
  76536. if (ti !== BACK)
  76537. f.push(vi);
  76538. if (ti !== FRONT)
  76539. b.push(ti !== BACK ? vi.clone() : vi);
  76540. if ((ti | tj) === SPANNING) {
  76541. t = (this.w - BABYLON.Vector3.Dot(this.normal, vi.pos)) / BABYLON.Vector3.Dot(this.normal, vj.pos.subtract(vi.pos));
  76542. var v = vi.interpolate(vj, t);
  76543. f.push(v);
  76544. b.push(v.clone());
  76545. }
  76546. }
  76547. var poly;
  76548. if (f.length >= 3) {
  76549. poly = new Polygon(f, polygon.shared);
  76550. if (poly.plane)
  76551. front.push(poly);
  76552. }
  76553. if (b.length >= 3) {
  76554. poly = new Polygon(b, polygon.shared);
  76555. if (poly.plane)
  76556. back.push(poly);
  76557. }
  76558. break;
  76559. }
  76560. };
  76561. // `BABYLON.CSG.Plane.EPSILON` is the tolerance used by `splitPolygon()` to decide if a
  76562. // point is on the plane.
  76563. Plane.EPSILON = 1e-5;
  76564. return Plane;
  76565. }());
  76566. // # class Polygon
  76567. // Represents a convex polygon. The vertices used to initialize a polygon must
  76568. // be coplanar and form a convex loop.
  76569. //
  76570. // Each convex polygon has a `shared` property, which is shared between all
  76571. // polygons that are clones of each other or were split from the same polygon.
  76572. // This can be used to define per-polygon properties (such as surface color).
  76573. var Polygon = /** @class */ (function () {
  76574. function Polygon(vertices, shared) {
  76575. this.vertices = vertices;
  76576. this.shared = shared;
  76577. this.plane = Plane.FromPoints(vertices[0].pos, vertices[1].pos, vertices[2].pos);
  76578. }
  76579. Polygon.prototype.clone = function () {
  76580. var vertices = this.vertices.map(function (v) { return v.clone(); });
  76581. return new Polygon(vertices, this.shared);
  76582. };
  76583. Polygon.prototype.flip = function () {
  76584. this.vertices.reverse().map(function (v) { v.flip(); });
  76585. this.plane.flip();
  76586. };
  76587. return Polygon;
  76588. }());
  76589. // # class Node
  76590. // Holds a node in a BSP tree. A BSP tree is built from a collection of polygons
  76591. // by picking a polygon to split along. That polygon (and all other coplanar
  76592. // polygons) are added directly to that node and the other polygons are added to
  76593. // the front and/or back subtrees. This is not a leafy BSP tree since there is
  76594. // no distinction between internal and leaf nodes.
  76595. var Node = /** @class */ (function () {
  76596. function Node(polygons) {
  76597. this.plane = null;
  76598. this.front = null;
  76599. this.back = null;
  76600. this.polygons = new Array();
  76601. if (polygons) {
  76602. this.build(polygons);
  76603. }
  76604. }
  76605. Node.prototype.clone = function () {
  76606. var node = new Node();
  76607. node.plane = this.plane && this.plane.clone();
  76608. node.front = this.front && this.front.clone();
  76609. node.back = this.back && this.back.clone();
  76610. node.polygons = this.polygons.map(function (p) { return p.clone(); });
  76611. return node;
  76612. };
  76613. // Convert solid space to empty space and empty space to solid space.
  76614. Node.prototype.invert = function () {
  76615. for (var i = 0; i < this.polygons.length; i++) {
  76616. this.polygons[i].flip();
  76617. }
  76618. if (this.plane) {
  76619. this.plane.flip();
  76620. }
  76621. if (this.front) {
  76622. this.front.invert();
  76623. }
  76624. if (this.back) {
  76625. this.back.invert();
  76626. }
  76627. var temp = this.front;
  76628. this.front = this.back;
  76629. this.back = temp;
  76630. };
  76631. // Recursively remove all polygons in `polygons` that are inside this BSP
  76632. // tree.
  76633. Node.prototype.clipPolygons = function (polygons) {
  76634. if (!this.plane)
  76635. return polygons.slice();
  76636. var front = new Array(), back = new Array();
  76637. for (var i = 0; i < polygons.length; i++) {
  76638. this.plane.splitPolygon(polygons[i], front, back, front, back);
  76639. }
  76640. if (this.front) {
  76641. front = this.front.clipPolygons(front);
  76642. }
  76643. if (this.back) {
  76644. back = this.back.clipPolygons(back);
  76645. }
  76646. else {
  76647. back = [];
  76648. }
  76649. return front.concat(back);
  76650. };
  76651. // Remove all polygons in this BSP tree that are inside the other BSP tree
  76652. // `bsp`.
  76653. Node.prototype.clipTo = function (bsp) {
  76654. this.polygons = bsp.clipPolygons(this.polygons);
  76655. if (this.front)
  76656. this.front.clipTo(bsp);
  76657. if (this.back)
  76658. this.back.clipTo(bsp);
  76659. };
  76660. // Return a list of all polygons in this BSP tree.
  76661. Node.prototype.allPolygons = function () {
  76662. var polygons = this.polygons.slice();
  76663. if (this.front)
  76664. polygons = polygons.concat(this.front.allPolygons());
  76665. if (this.back)
  76666. polygons = polygons.concat(this.back.allPolygons());
  76667. return polygons;
  76668. };
  76669. // Build a BSP tree out of `polygons`. When called on an existing tree, the
  76670. // new polygons are filtered down to the bottom of the tree and become new
  76671. // nodes there. Each set of polygons is partitioned using the first polygon
  76672. // (no heuristic is used to pick a good split).
  76673. Node.prototype.build = function (polygons) {
  76674. if (!polygons.length)
  76675. return;
  76676. if (!this.plane)
  76677. this.plane = polygons[0].plane.clone();
  76678. var front = new Array(), back = new Array();
  76679. for (var i = 0; i < polygons.length; i++) {
  76680. this.plane.splitPolygon(polygons[i], this.polygons, this.polygons, front, back);
  76681. }
  76682. if (front.length) {
  76683. if (!this.front)
  76684. this.front = new Node();
  76685. this.front.build(front);
  76686. }
  76687. if (back.length) {
  76688. if (!this.back)
  76689. this.back = new Node();
  76690. this.back.build(back);
  76691. }
  76692. };
  76693. return Node;
  76694. }());
  76695. var CSG = /** @class */ (function () {
  76696. function CSG() {
  76697. this.polygons = new Array();
  76698. }
  76699. // Convert BABYLON.Mesh to BABYLON.CSG
  76700. CSG.FromMesh = function (mesh) {
  76701. var vertex, normal, uv, position, polygon, polygons = new Array(), vertices;
  76702. var matrix, meshPosition, meshRotation, meshRotationQuaternion = null, meshScaling;
  76703. if (mesh instanceof BABYLON.Mesh) {
  76704. mesh.computeWorldMatrix(true);
  76705. matrix = mesh.getWorldMatrix();
  76706. meshPosition = mesh.position.clone();
  76707. meshRotation = mesh.rotation.clone();
  76708. if (mesh.rotationQuaternion) {
  76709. meshRotationQuaternion = mesh.rotationQuaternion.clone();
  76710. }
  76711. meshScaling = mesh.scaling.clone();
  76712. }
  76713. else {
  76714. throw 'BABYLON.CSG: Wrong Mesh type, must be BABYLON.Mesh';
  76715. }
  76716. var indices = mesh.getIndices(), positions = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind), normals = mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind), uvs = mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  76717. var subMeshes = mesh.subMeshes;
  76718. for (var sm = 0, sml = subMeshes.length; sm < sml; sm++) {
  76719. for (var i = subMeshes[sm].indexStart, il = subMeshes[sm].indexCount + subMeshes[sm].indexStart; i < il; i += 3) {
  76720. vertices = [];
  76721. for (var j = 0; j < 3; j++) {
  76722. var sourceNormal = new BABYLON.Vector3(normals[indices[i + j] * 3], normals[indices[i + j] * 3 + 1], normals[indices[i + j] * 3 + 2]);
  76723. uv = new BABYLON.Vector2(uvs[indices[i + j] * 2], uvs[indices[i + j] * 2 + 1]);
  76724. var sourcePosition = new BABYLON.Vector3(positions[indices[i + j] * 3], positions[indices[i + j] * 3 + 1], positions[indices[i + j] * 3 + 2]);
  76725. position = BABYLON.Vector3.TransformCoordinates(sourcePosition, matrix);
  76726. normal = BABYLON.Vector3.TransformNormal(sourceNormal, matrix);
  76727. vertex = new Vertex(position, normal, uv);
  76728. vertices.push(vertex);
  76729. }
  76730. polygon = new Polygon(vertices, { subMeshId: sm, meshId: currentCSGMeshId, materialIndex: subMeshes[sm].materialIndex });
  76731. // To handle the case of degenerated triangle
  76732. // polygon.plane == null <=> the polygon does not represent 1 single plane <=> the triangle is degenerated
  76733. if (polygon.plane)
  76734. polygons.push(polygon);
  76735. }
  76736. }
  76737. var csg = CSG.FromPolygons(polygons);
  76738. csg.matrix = matrix;
  76739. csg.position = meshPosition;
  76740. csg.rotation = meshRotation;
  76741. csg.scaling = meshScaling;
  76742. csg.rotationQuaternion = meshRotationQuaternion;
  76743. currentCSGMeshId++;
  76744. return csg;
  76745. };
  76746. // Construct a BABYLON.CSG solid from a list of `BABYLON.CSG.Polygon` instances.
  76747. CSG.FromPolygons = function (polygons) {
  76748. var csg = new CSG();
  76749. csg.polygons = polygons;
  76750. return csg;
  76751. };
  76752. CSG.prototype.clone = function () {
  76753. var csg = new CSG();
  76754. csg.polygons = this.polygons.map(function (p) { return p.clone(); });
  76755. csg.copyTransformAttributes(this);
  76756. return csg;
  76757. };
  76758. CSG.prototype.union = function (csg) {
  76759. var a = new Node(this.clone().polygons);
  76760. var b = new Node(csg.clone().polygons);
  76761. a.clipTo(b);
  76762. b.clipTo(a);
  76763. b.invert();
  76764. b.clipTo(a);
  76765. b.invert();
  76766. a.build(b.allPolygons());
  76767. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  76768. };
  76769. CSG.prototype.unionInPlace = function (csg) {
  76770. var a = new Node(this.polygons);
  76771. var b = new Node(csg.polygons);
  76772. a.clipTo(b);
  76773. b.clipTo(a);
  76774. b.invert();
  76775. b.clipTo(a);
  76776. b.invert();
  76777. a.build(b.allPolygons());
  76778. this.polygons = a.allPolygons();
  76779. };
  76780. CSG.prototype.subtract = function (csg) {
  76781. var a = new Node(this.clone().polygons);
  76782. var b = new Node(csg.clone().polygons);
  76783. a.invert();
  76784. a.clipTo(b);
  76785. b.clipTo(a);
  76786. b.invert();
  76787. b.clipTo(a);
  76788. b.invert();
  76789. a.build(b.allPolygons());
  76790. a.invert();
  76791. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  76792. };
  76793. CSG.prototype.subtractInPlace = function (csg) {
  76794. var a = new Node(this.polygons);
  76795. var b = new Node(csg.polygons);
  76796. a.invert();
  76797. a.clipTo(b);
  76798. b.clipTo(a);
  76799. b.invert();
  76800. b.clipTo(a);
  76801. b.invert();
  76802. a.build(b.allPolygons());
  76803. a.invert();
  76804. this.polygons = a.allPolygons();
  76805. };
  76806. CSG.prototype.intersect = function (csg) {
  76807. var a = new Node(this.clone().polygons);
  76808. var b = new Node(csg.clone().polygons);
  76809. a.invert();
  76810. b.clipTo(a);
  76811. b.invert();
  76812. a.clipTo(b);
  76813. b.clipTo(a);
  76814. a.build(b.allPolygons());
  76815. a.invert();
  76816. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  76817. };
  76818. CSG.prototype.intersectInPlace = function (csg) {
  76819. var a = new Node(this.polygons);
  76820. var b = new Node(csg.polygons);
  76821. a.invert();
  76822. b.clipTo(a);
  76823. b.invert();
  76824. a.clipTo(b);
  76825. b.clipTo(a);
  76826. a.build(b.allPolygons());
  76827. a.invert();
  76828. this.polygons = a.allPolygons();
  76829. };
  76830. // Return a new BABYLON.CSG solid with solid and empty space switched. This solid is
  76831. // not modified.
  76832. CSG.prototype.inverse = function () {
  76833. var csg = this.clone();
  76834. csg.inverseInPlace();
  76835. return csg;
  76836. };
  76837. CSG.prototype.inverseInPlace = function () {
  76838. this.polygons.map(function (p) { p.flip(); });
  76839. };
  76840. // This is used to keep meshes transformations so they can be restored
  76841. // when we build back a Babylon Mesh
  76842. // NB : All CSG operations are performed in world coordinates
  76843. CSG.prototype.copyTransformAttributes = function (csg) {
  76844. this.matrix = csg.matrix;
  76845. this.position = csg.position;
  76846. this.rotation = csg.rotation;
  76847. this.scaling = csg.scaling;
  76848. this.rotationQuaternion = csg.rotationQuaternion;
  76849. return this;
  76850. };
  76851. // Build Raw mesh from CSG
  76852. // Coordinates here are in world space
  76853. CSG.prototype.buildMeshGeometry = function (name, scene, keepSubMeshes) {
  76854. var matrix = this.matrix.clone();
  76855. matrix.invert();
  76856. 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;
  76857. if (keepSubMeshes) {
  76858. // Sort Polygons, since subMeshes are indices range
  76859. polygons.sort(function (a, b) {
  76860. if (a.shared.meshId === b.shared.meshId) {
  76861. return a.shared.subMeshId - b.shared.subMeshId;
  76862. }
  76863. else {
  76864. return a.shared.meshId - b.shared.meshId;
  76865. }
  76866. });
  76867. }
  76868. for (var i = 0, il = polygons.length; i < il; i++) {
  76869. polygon = polygons[i];
  76870. // Building SubMeshes
  76871. if (!subMesh_dict[polygon.shared.meshId]) {
  76872. subMesh_dict[polygon.shared.meshId] = {};
  76873. }
  76874. if (!subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId]) {
  76875. subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId] = {
  76876. indexStart: +Infinity,
  76877. indexEnd: -Infinity,
  76878. materialIndex: polygon.shared.materialIndex
  76879. };
  76880. }
  76881. subMesh_obj = subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId];
  76882. for (var j = 2, jl = polygon.vertices.length; j < jl; j++) {
  76883. polygonIndices[0] = 0;
  76884. polygonIndices[1] = j - 1;
  76885. polygonIndices[2] = j;
  76886. for (var k = 0; k < 3; k++) {
  76887. vertex.copyFrom(polygon.vertices[polygonIndices[k]].pos);
  76888. normal.copyFrom(polygon.vertices[polygonIndices[k]].normal);
  76889. uv.copyFrom(polygon.vertices[polygonIndices[k]].uv);
  76890. var localVertex = BABYLON.Vector3.TransformCoordinates(vertex, matrix);
  76891. var localNormal = BABYLON.Vector3.TransformNormal(normal, matrix);
  76892. vertex_idx = vertice_dict[localVertex.x + ',' + localVertex.y + ',' + localVertex.z];
  76893. // Check if 2 points can be merged
  76894. if (!(typeof vertex_idx !== 'undefined' &&
  76895. normals[vertex_idx * 3] === localNormal.x &&
  76896. normals[vertex_idx * 3 + 1] === localNormal.y &&
  76897. normals[vertex_idx * 3 + 2] === localNormal.z &&
  76898. uvs[vertex_idx * 2] === uv.x &&
  76899. uvs[vertex_idx * 2 + 1] === uv.y)) {
  76900. vertices.push(localVertex.x, localVertex.y, localVertex.z);
  76901. uvs.push(uv.x, uv.y);
  76902. normals.push(normal.x, normal.y, normal.z);
  76903. vertex_idx = vertice_dict[localVertex.x + ',' + localVertex.y + ',' + localVertex.z] = (vertices.length / 3) - 1;
  76904. }
  76905. indices.push(vertex_idx);
  76906. subMesh_obj.indexStart = Math.min(currentIndex, subMesh_obj.indexStart);
  76907. subMesh_obj.indexEnd = Math.max(currentIndex, subMesh_obj.indexEnd);
  76908. currentIndex++;
  76909. }
  76910. }
  76911. }
  76912. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, vertices);
  76913. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals);
  76914. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, uvs);
  76915. mesh.setIndices(indices, null);
  76916. if (keepSubMeshes) {
  76917. // We offset the materialIndex by the previous number of materials in the CSG mixed meshes
  76918. var materialIndexOffset = 0, materialMaxIndex;
  76919. mesh.subMeshes = new Array();
  76920. for (var m in subMesh_dict) {
  76921. materialMaxIndex = -1;
  76922. for (var sm in subMesh_dict[m]) {
  76923. subMesh_obj = subMesh_dict[m][sm];
  76924. BABYLON.SubMesh.CreateFromIndices(subMesh_obj.materialIndex + materialIndexOffset, subMesh_obj.indexStart, subMesh_obj.indexEnd - subMesh_obj.indexStart + 1, mesh);
  76925. materialMaxIndex = Math.max(subMesh_obj.materialIndex, materialMaxIndex);
  76926. }
  76927. materialIndexOffset += ++materialMaxIndex;
  76928. }
  76929. }
  76930. return mesh;
  76931. };
  76932. // Build Mesh from CSG taking material and transforms into account
  76933. CSG.prototype.toMesh = function (name, material, scene, keepSubMeshes) {
  76934. var mesh = this.buildMeshGeometry(name, scene, keepSubMeshes);
  76935. mesh.material = material;
  76936. mesh.position.copyFrom(this.position);
  76937. mesh.rotation.copyFrom(this.rotation);
  76938. if (this.rotationQuaternion) {
  76939. mesh.rotationQuaternion = this.rotationQuaternion.clone();
  76940. }
  76941. mesh.scaling.copyFrom(this.scaling);
  76942. mesh.computeWorldMatrix(true);
  76943. return mesh;
  76944. };
  76945. return CSG;
  76946. }());
  76947. BABYLON.CSG = CSG;
  76948. })(BABYLON || (BABYLON = {}));
  76949. //# sourceMappingURL=babylon.csg.js.map
  76950. "use strict";
  76951. var BABYLON;
  76952. (function (BABYLON) {
  76953. var LensFlare = /** @class */ (function () {
  76954. function LensFlare(size, position, color, imgUrl, system) {
  76955. this.size = size;
  76956. this.position = position;
  76957. this.alphaMode = BABYLON.Engine.ALPHA_ONEONE;
  76958. this.color = color || new BABYLON.Color3(1, 1, 1);
  76959. this.texture = imgUrl ? new BABYLON.Texture(imgUrl, system.getScene(), true) : null;
  76960. this._system = system;
  76961. system.lensFlares.push(this);
  76962. }
  76963. LensFlare.AddFlare = function (size, position, color, imgUrl, system) {
  76964. return new LensFlare(size, position, color, imgUrl, system);
  76965. };
  76966. LensFlare.prototype.dispose = function () {
  76967. if (this.texture) {
  76968. this.texture.dispose();
  76969. }
  76970. // Remove from scene
  76971. var index = this._system.lensFlares.indexOf(this);
  76972. this._system.lensFlares.splice(index, 1);
  76973. };
  76974. ;
  76975. return LensFlare;
  76976. }());
  76977. BABYLON.LensFlare = LensFlare;
  76978. })(BABYLON || (BABYLON = {}));
  76979. //# sourceMappingURL=babylon.lensFlare.js.map
  76980. "use strict";
  76981. var BABYLON;
  76982. (function (BABYLON) {
  76983. var LensFlareSystem = /** @class */ (function () {
  76984. function LensFlareSystem(name, emitter, scene) {
  76985. this.name = name;
  76986. this.lensFlares = new Array();
  76987. this.borderLimit = 300;
  76988. this.viewportBorder = 0;
  76989. this.layerMask = 0x0FFFFFFF;
  76990. this._vertexBuffers = {};
  76991. this._isEnabled = true;
  76992. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  76993. this._emitter = emitter;
  76994. this.id = name;
  76995. scene.lensFlareSystems.push(this);
  76996. this.meshesSelectionPredicate = function (m) { return (scene.activeCamera && m.material && m.isVisible && m.isEnabled() && m.isBlocker && ((m.layerMask & scene.activeCamera.layerMask) != 0)); };
  76997. var engine = scene.getEngine();
  76998. // VBO
  76999. var vertices = [];
  77000. vertices.push(1, 1);
  77001. vertices.push(-1, 1);
  77002. vertices.push(-1, -1);
  77003. vertices.push(1, -1);
  77004. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(engine, vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  77005. // Indices
  77006. var indices = [];
  77007. indices.push(0);
  77008. indices.push(1);
  77009. indices.push(2);
  77010. indices.push(0);
  77011. indices.push(2);
  77012. indices.push(3);
  77013. this._indexBuffer = engine.createIndexBuffer(indices);
  77014. // Effects
  77015. this._effect = engine.createEffect("lensFlare", [BABYLON.VertexBuffer.PositionKind], ["color", "viewportMatrix"], ["textureSampler"], "");
  77016. }
  77017. Object.defineProperty(LensFlareSystem.prototype, "isEnabled", {
  77018. get: function () {
  77019. return this._isEnabled;
  77020. },
  77021. set: function (value) {
  77022. this._isEnabled = value;
  77023. },
  77024. enumerable: true,
  77025. configurable: true
  77026. });
  77027. LensFlareSystem.prototype.getScene = function () {
  77028. return this._scene;
  77029. };
  77030. LensFlareSystem.prototype.getEmitter = function () {
  77031. return this._emitter;
  77032. };
  77033. LensFlareSystem.prototype.setEmitter = function (newEmitter) {
  77034. this._emitter = newEmitter;
  77035. };
  77036. LensFlareSystem.prototype.getEmitterPosition = function () {
  77037. return this._emitter.getAbsolutePosition ? this._emitter.getAbsolutePosition() : this._emitter.position;
  77038. };
  77039. LensFlareSystem.prototype.computeEffectivePosition = function (globalViewport) {
  77040. var position = this.getEmitterPosition();
  77041. position = BABYLON.Vector3.Project(position, BABYLON.Matrix.Identity(), this._scene.getTransformMatrix(), globalViewport);
  77042. this._positionX = position.x;
  77043. this._positionY = position.y;
  77044. position = BABYLON.Vector3.TransformCoordinates(this.getEmitterPosition(), this._scene.getViewMatrix());
  77045. if (this.viewportBorder > 0) {
  77046. globalViewport.x -= this.viewportBorder;
  77047. globalViewport.y -= this.viewportBorder;
  77048. globalViewport.width += this.viewportBorder * 2;
  77049. globalViewport.height += this.viewportBorder * 2;
  77050. position.x += this.viewportBorder;
  77051. position.y += this.viewportBorder;
  77052. this._positionX += this.viewportBorder;
  77053. this._positionY += this.viewportBorder;
  77054. }
  77055. if (position.z > 0) {
  77056. if ((this._positionX > globalViewport.x) && (this._positionX < globalViewport.x + globalViewport.width)) {
  77057. if ((this._positionY > globalViewport.y) && (this._positionY < globalViewport.y + globalViewport.height))
  77058. return true;
  77059. }
  77060. return true;
  77061. }
  77062. return false;
  77063. };
  77064. LensFlareSystem.prototype._isVisible = function () {
  77065. if (!this._isEnabled || !this._scene.activeCamera) {
  77066. return false;
  77067. }
  77068. var emitterPosition = this.getEmitterPosition();
  77069. var direction = emitterPosition.subtract(this._scene.activeCamera.globalPosition);
  77070. var distance = direction.length();
  77071. direction.normalize();
  77072. var ray = new BABYLON.Ray(this._scene.activeCamera.globalPosition, direction);
  77073. var pickInfo = this._scene.pickWithRay(ray, this.meshesSelectionPredicate, true);
  77074. return !pickInfo || !pickInfo.hit || pickInfo.distance > distance;
  77075. };
  77076. LensFlareSystem.prototype.render = function () {
  77077. if (!this._effect.isReady() || !this._scene.activeCamera)
  77078. return false;
  77079. var engine = this._scene.getEngine();
  77080. var viewport = this._scene.activeCamera.viewport;
  77081. var globalViewport = viewport.toGlobal(engine.getRenderWidth(true), engine.getRenderHeight(true));
  77082. // Position
  77083. if (!this.computeEffectivePosition(globalViewport)) {
  77084. return false;
  77085. }
  77086. // Visibility
  77087. if (!this._isVisible()) {
  77088. return false;
  77089. }
  77090. // Intensity
  77091. var awayX;
  77092. var awayY;
  77093. if (this._positionX < this.borderLimit + globalViewport.x) {
  77094. awayX = this.borderLimit + globalViewport.x - this._positionX;
  77095. }
  77096. else if (this._positionX > globalViewport.x + globalViewport.width - this.borderLimit) {
  77097. awayX = this._positionX - globalViewport.x - globalViewport.width + this.borderLimit;
  77098. }
  77099. else {
  77100. awayX = 0;
  77101. }
  77102. if (this._positionY < this.borderLimit + globalViewport.y) {
  77103. awayY = this.borderLimit + globalViewport.y - this._positionY;
  77104. }
  77105. else if (this._positionY > globalViewport.y + globalViewport.height - this.borderLimit) {
  77106. awayY = this._positionY - globalViewport.y - globalViewport.height + this.borderLimit;
  77107. }
  77108. else {
  77109. awayY = 0;
  77110. }
  77111. var away = (awayX > awayY) ? awayX : awayY;
  77112. away -= this.viewportBorder;
  77113. if (away > this.borderLimit) {
  77114. away = this.borderLimit;
  77115. }
  77116. var intensity = 1.0 - (away / this.borderLimit);
  77117. if (intensity < 0) {
  77118. return false;
  77119. }
  77120. if (intensity > 1.0) {
  77121. intensity = 1.0;
  77122. }
  77123. if (this.viewportBorder > 0) {
  77124. globalViewport.x += this.viewportBorder;
  77125. globalViewport.y += this.viewportBorder;
  77126. globalViewport.width -= this.viewportBorder * 2;
  77127. globalViewport.height -= this.viewportBorder * 2;
  77128. this._positionX -= this.viewportBorder;
  77129. this._positionY -= this.viewportBorder;
  77130. }
  77131. // Position
  77132. var centerX = globalViewport.x + globalViewport.width / 2;
  77133. var centerY = globalViewport.y + globalViewport.height / 2;
  77134. var distX = centerX - this._positionX;
  77135. var distY = centerY - this._positionY;
  77136. // Effects
  77137. engine.enableEffect(this._effect);
  77138. engine.setState(false);
  77139. engine.setDepthBuffer(false);
  77140. // VBOs
  77141. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._effect);
  77142. // Flares
  77143. for (var index = 0; index < this.lensFlares.length; index++) {
  77144. var flare = this.lensFlares[index];
  77145. engine.setAlphaMode(flare.alphaMode);
  77146. var x = centerX - (distX * flare.position);
  77147. var y = centerY - (distY * flare.position);
  77148. var cw = flare.size;
  77149. var ch = flare.size * engine.getAspectRatio(this._scene.activeCamera, true);
  77150. var cx = 2 * (x / (globalViewport.width + globalViewport.x * 2)) - 1.0;
  77151. var cy = 1.0 - 2 * (y / (globalViewport.height + globalViewport.y * 2));
  77152. var viewportMatrix = BABYLON.Matrix.FromValues(cw / 2, 0, 0, 0, 0, ch / 2, 0, 0, 0, 0, 1, 0, cx, cy, 0, 1);
  77153. this._effect.setMatrix("viewportMatrix", viewportMatrix);
  77154. // Texture
  77155. this._effect.setTexture("textureSampler", flare.texture);
  77156. // Color
  77157. this._effect.setFloat4("color", flare.color.r * intensity, flare.color.g * intensity, flare.color.b * intensity, 1.0);
  77158. // Draw order
  77159. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  77160. }
  77161. engine.setDepthBuffer(true);
  77162. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  77163. return true;
  77164. };
  77165. LensFlareSystem.prototype.dispose = function () {
  77166. var vertexBuffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  77167. if (vertexBuffer) {
  77168. vertexBuffer.dispose();
  77169. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  77170. }
  77171. if (this._indexBuffer) {
  77172. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  77173. this._indexBuffer = null;
  77174. }
  77175. while (this.lensFlares.length) {
  77176. this.lensFlares[0].dispose();
  77177. }
  77178. // Remove from scene
  77179. var index = this._scene.lensFlareSystems.indexOf(this);
  77180. this._scene.lensFlareSystems.splice(index, 1);
  77181. };
  77182. LensFlareSystem.Parse = function (parsedLensFlareSystem, scene, rootUrl) {
  77183. var emitter = scene.getLastEntryByID(parsedLensFlareSystem.emitterId);
  77184. var name = parsedLensFlareSystem.name || "lensFlareSystem#" + parsedLensFlareSystem.emitterId;
  77185. var lensFlareSystem = new LensFlareSystem(name, emitter, scene);
  77186. lensFlareSystem.id = parsedLensFlareSystem.id || name;
  77187. lensFlareSystem.borderLimit = parsedLensFlareSystem.borderLimit;
  77188. for (var index = 0; index < parsedLensFlareSystem.flares.length; index++) {
  77189. var parsedFlare = parsedLensFlareSystem.flares[index];
  77190. BABYLON.LensFlare.AddFlare(parsedFlare.size, parsedFlare.position, BABYLON.Color3.FromArray(parsedFlare.color), parsedFlare.textureName ? rootUrl + parsedFlare.textureName : "", lensFlareSystem);
  77191. }
  77192. return lensFlareSystem;
  77193. };
  77194. LensFlareSystem.prototype.serialize = function () {
  77195. var serializationObject = {};
  77196. serializationObject.id = this.id;
  77197. serializationObject.name = this.name;
  77198. serializationObject.emitterId = this.getEmitter().id;
  77199. serializationObject.borderLimit = this.borderLimit;
  77200. serializationObject.flares = [];
  77201. for (var index = 0; index < this.lensFlares.length; index++) {
  77202. var flare = this.lensFlares[index];
  77203. serializationObject.flares.push({
  77204. size: flare.size,
  77205. position: flare.position,
  77206. color: flare.color.asArray(),
  77207. textureName: BABYLON.Tools.GetFilename(flare.texture ? flare.texture.name : "")
  77208. });
  77209. }
  77210. return serializationObject;
  77211. };
  77212. return LensFlareSystem;
  77213. }());
  77214. BABYLON.LensFlareSystem = LensFlareSystem;
  77215. })(BABYLON || (BABYLON = {}));
  77216. //# sourceMappingURL=babylon.lensFlareSystem.js.map
  77217. "use strict";
  77218. var BABYLON;
  77219. (function (BABYLON) {
  77220. /**
  77221. * This is a holder class for the physics joint created by the physics plugin.
  77222. * It holds a set of functions to control the underlying joint.
  77223. */
  77224. var PhysicsJoint = /** @class */ (function () {
  77225. function PhysicsJoint(type, jointData) {
  77226. this.type = type;
  77227. this.jointData = jointData;
  77228. jointData.nativeParams = jointData.nativeParams || {};
  77229. }
  77230. Object.defineProperty(PhysicsJoint.prototype, "physicsJoint", {
  77231. get: function () {
  77232. return this._physicsJoint;
  77233. },
  77234. set: function (newJoint) {
  77235. if (this._physicsJoint) {
  77236. //remove from the wolrd
  77237. }
  77238. this._physicsJoint = newJoint;
  77239. },
  77240. enumerable: true,
  77241. configurable: true
  77242. });
  77243. Object.defineProperty(PhysicsJoint.prototype, "physicsPlugin", {
  77244. set: function (physicsPlugin) {
  77245. this._physicsPlugin = physicsPlugin;
  77246. },
  77247. enumerable: true,
  77248. configurable: true
  77249. });
  77250. /**
  77251. * Execute a function that is physics-plugin specific.
  77252. * @param {Function} func the function that will be executed.
  77253. * It accepts two parameters: the physics world and the physics joint.
  77254. */
  77255. PhysicsJoint.prototype.executeNativeFunction = function (func) {
  77256. func(this._physicsPlugin.world, this._physicsJoint);
  77257. };
  77258. //TODO check if the native joints are the same
  77259. //Joint Types
  77260. PhysicsJoint.DistanceJoint = 0;
  77261. PhysicsJoint.HingeJoint = 1;
  77262. PhysicsJoint.BallAndSocketJoint = 2;
  77263. PhysicsJoint.WheelJoint = 3;
  77264. PhysicsJoint.SliderJoint = 4;
  77265. //OIMO
  77266. PhysicsJoint.PrismaticJoint = 5;
  77267. //ENERGY FTW! (compare with this - http://ode-wiki.org/wiki/index.php?title=Manual:_Joint_Types_and_Functions)
  77268. PhysicsJoint.UniversalJoint = 6;
  77269. PhysicsJoint.Hinge2Joint = PhysicsJoint.WheelJoint;
  77270. //Cannon
  77271. //Similar to a Ball-Joint. Different in params
  77272. PhysicsJoint.PointToPointJoint = 8;
  77273. //Cannon only at the moment
  77274. PhysicsJoint.SpringJoint = 9;
  77275. PhysicsJoint.LockJoint = 10;
  77276. return PhysicsJoint;
  77277. }());
  77278. BABYLON.PhysicsJoint = PhysicsJoint;
  77279. /**
  77280. * A class representing a physics distance joint.
  77281. */
  77282. var DistanceJoint = /** @class */ (function (_super) {
  77283. __extends(DistanceJoint, _super);
  77284. function DistanceJoint(jointData) {
  77285. return _super.call(this, PhysicsJoint.DistanceJoint, jointData) || this;
  77286. }
  77287. /**
  77288. * Update the predefined distance.
  77289. */
  77290. DistanceJoint.prototype.updateDistance = function (maxDistance, minDistance) {
  77291. this._physicsPlugin.updateDistanceJoint(this, maxDistance, minDistance);
  77292. };
  77293. return DistanceJoint;
  77294. }(PhysicsJoint));
  77295. BABYLON.DistanceJoint = DistanceJoint;
  77296. var MotorEnabledJoint = /** @class */ (function (_super) {
  77297. __extends(MotorEnabledJoint, _super);
  77298. function MotorEnabledJoint(type, jointData) {
  77299. return _super.call(this, type, jointData) || this;
  77300. }
  77301. /**
  77302. * Set the motor values.
  77303. * Attention, this function is plugin specific. Engines won't react 100% the same.
  77304. * @param {number} force the force to apply
  77305. * @param {number} maxForce max force for this motor.
  77306. */
  77307. MotorEnabledJoint.prototype.setMotor = function (force, maxForce) {
  77308. this._physicsPlugin.setMotor(this, force || 0, maxForce);
  77309. };
  77310. /**
  77311. * Set the motor's limits.
  77312. * Attention, this function is plugin specific. Engines won't react 100% the same.
  77313. */
  77314. MotorEnabledJoint.prototype.setLimit = function (upperLimit, lowerLimit) {
  77315. this._physicsPlugin.setLimit(this, upperLimit, lowerLimit);
  77316. };
  77317. return MotorEnabledJoint;
  77318. }(PhysicsJoint));
  77319. BABYLON.MotorEnabledJoint = MotorEnabledJoint;
  77320. /**
  77321. * This class represents a single hinge physics joint
  77322. */
  77323. var HingeJoint = /** @class */ (function (_super) {
  77324. __extends(HingeJoint, _super);
  77325. function HingeJoint(jointData) {
  77326. return _super.call(this, PhysicsJoint.HingeJoint, jointData) || this;
  77327. }
  77328. /**
  77329. * Set the motor values.
  77330. * Attention, this function is plugin specific. Engines won't react 100% the same.
  77331. * @param {number} force the force to apply
  77332. * @param {number} maxForce max force for this motor.
  77333. */
  77334. HingeJoint.prototype.setMotor = function (force, maxForce) {
  77335. this._physicsPlugin.setMotor(this, force || 0, maxForce);
  77336. };
  77337. /**
  77338. * Set the motor's limits.
  77339. * Attention, this function is plugin specific. Engines won't react 100% the same.
  77340. */
  77341. HingeJoint.prototype.setLimit = function (upperLimit, lowerLimit) {
  77342. this._physicsPlugin.setLimit(this, upperLimit, lowerLimit);
  77343. };
  77344. return HingeJoint;
  77345. }(MotorEnabledJoint));
  77346. BABYLON.HingeJoint = HingeJoint;
  77347. /**
  77348. * This class represents a dual hinge physics joint (same as wheel joint)
  77349. */
  77350. var Hinge2Joint = /** @class */ (function (_super) {
  77351. __extends(Hinge2Joint, _super);
  77352. function Hinge2Joint(jointData) {
  77353. return _super.call(this, PhysicsJoint.Hinge2Joint, jointData) || this;
  77354. }
  77355. /**
  77356. * Set the motor values.
  77357. * Attention, this function is plugin specific. Engines won't react 100% the same.
  77358. * @param {number} force the force to apply
  77359. * @param {number} maxForce max force for this motor.
  77360. * @param {motorIndex} the motor's index, 0 or 1.
  77361. */
  77362. Hinge2Joint.prototype.setMotor = function (force, maxForce, motorIndex) {
  77363. if (motorIndex === void 0) { motorIndex = 0; }
  77364. this._physicsPlugin.setMotor(this, force || 0, maxForce, motorIndex);
  77365. };
  77366. /**
  77367. * Set the motor limits.
  77368. * Attention, this function is plugin specific. Engines won't react 100% the same.
  77369. * @param {number} upperLimit the upper limit
  77370. * @param {number} lowerLimit lower limit
  77371. * @param {motorIndex} the motor's index, 0 or 1.
  77372. */
  77373. Hinge2Joint.prototype.setLimit = function (upperLimit, lowerLimit, motorIndex) {
  77374. if (motorIndex === void 0) { motorIndex = 0; }
  77375. this._physicsPlugin.setLimit(this, upperLimit, lowerLimit, motorIndex);
  77376. };
  77377. return Hinge2Joint;
  77378. }(MotorEnabledJoint));
  77379. BABYLON.Hinge2Joint = Hinge2Joint;
  77380. })(BABYLON || (BABYLON = {}));
  77381. //# sourceMappingURL=babylon.physicsJoint.js.map
  77382. "use strict";
  77383. var BABYLON;
  77384. (function (BABYLON) {
  77385. var PhysicsImpostor = /** @class */ (function () {
  77386. function PhysicsImpostor(object, type, _options, _scene) {
  77387. if (_options === void 0) { _options = { mass: 0 }; }
  77388. var _this = this;
  77389. this.object = object;
  77390. this.type = type;
  77391. this._options = _options;
  77392. this._scene = _scene;
  77393. this._bodyUpdateRequired = false;
  77394. this._onBeforePhysicsStepCallbacks = new Array();
  77395. this._onAfterPhysicsStepCallbacks = new Array();
  77396. this._onPhysicsCollideCallbacks = [];
  77397. this._deltaPosition = BABYLON.Vector3.Zero();
  77398. this._isDisposed = false;
  77399. //temp variables for parent rotation calculations
  77400. //private _mats: Array<Matrix> = [new Matrix(), new Matrix()];
  77401. this._tmpQuat = new BABYLON.Quaternion();
  77402. this._tmpQuat2 = new BABYLON.Quaternion();
  77403. /**
  77404. * this function is executed by the physics engine.
  77405. */
  77406. this.beforeStep = function () {
  77407. if (!_this._physicsEngine) {
  77408. return;
  77409. }
  77410. _this.object.translate(_this._deltaPosition, -1);
  77411. _this._deltaRotationConjugated && _this.object.rotationQuaternion && _this.object.rotationQuaternion.multiplyToRef(_this._deltaRotationConjugated, _this.object.rotationQuaternion);
  77412. _this.object.computeWorldMatrix(false);
  77413. if (_this.object.parent && _this.object.rotationQuaternion) {
  77414. _this.getParentsRotation();
  77415. _this._tmpQuat.multiplyToRef(_this.object.rotationQuaternion, _this._tmpQuat);
  77416. }
  77417. else {
  77418. _this._tmpQuat.copyFrom(_this.object.rotationQuaternion || new BABYLON.Quaternion());
  77419. }
  77420. if (!_this._options.disableBidirectionalTransformation) {
  77421. _this.object.rotationQuaternion && _this._physicsEngine.getPhysicsPlugin().setPhysicsBodyTransformation(_this, /*bInfo.boundingBox.centerWorld*/ _this.object.getAbsolutePivotPoint(), _this._tmpQuat);
  77422. }
  77423. _this._onBeforePhysicsStepCallbacks.forEach(function (func) {
  77424. func(_this);
  77425. });
  77426. };
  77427. /**
  77428. * this function is executed by the physics engine.
  77429. */
  77430. this.afterStep = function () {
  77431. if (!_this._physicsEngine) {
  77432. return;
  77433. }
  77434. _this._onAfterPhysicsStepCallbacks.forEach(function (func) {
  77435. func(_this);
  77436. });
  77437. _this._physicsEngine.getPhysicsPlugin().setTransformationFromPhysicsBody(_this);
  77438. // object has now its world rotation. needs to be converted to local.
  77439. if (_this.object.parent && _this.object.rotationQuaternion) {
  77440. _this.getParentsRotation();
  77441. _this._tmpQuat.conjugateInPlace();
  77442. _this._tmpQuat.multiplyToRef(_this.object.rotationQuaternion, _this.object.rotationQuaternion);
  77443. }
  77444. // take the position set and make it the absolute position of this object.
  77445. _this.object.setAbsolutePosition(_this.object.position);
  77446. _this._deltaRotation && _this.object.rotationQuaternion && _this.object.rotationQuaternion.multiplyToRef(_this._deltaRotation, _this.object.rotationQuaternion);
  77447. _this.object.translate(_this._deltaPosition, 1);
  77448. };
  77449. /**
  77450. * Legacy collision detection event support
  77451. */
  77452. this.onCollideEvent = null;
  77453. //event and body object due to cannon's event-based architecture.
  77454. this.onCollide = function (e) {
  77455. if (!_this._onPhysicsCollideCallbacks.length && !_this.onCollideEvent) {
  77456. return;
  77457. }
  77458. if (!_this._physicsEngine) {
  77459. return;
  77460. }
  77461. var otherImpostor = _this._physicsEngine.getImpostorWithPhysicsBody(e.body);
  77462. if (otherImpostor) {
  77463. // Legacy collision detection event support
  77464. if (_this.onCollideEvent) {
  77465. _this.onCollideEvent(_this, otherImpostor);
  77466. }
  77467. _this._onPhysicsCollideCallbacks.filter(function (obj) {
  77468. return obj.otherImpostors.indexOf(otherImpostor) !== -1;
  77469. }).forEach(function (obj) {
  77470. obj.callback(_this, otherImpostor);
  77471. });
  77472. }
  77473. };
  77474. //sanity check!
  77475. if (!this.object) {
  77476. BABYLON.Tools.Error("No object was provided. A physics object is obligatory");
  77477. return;
  77478. }
  77479. //legacy support for old syntax.
  77480. if (!this._scene && object.getScene) {
  77481. this._scene = object.getScene();
  77482. }
  77483. if (!this._scene) {
  77484. return;
  77485. }
  77486. this._physicsEngine = this._scene.getPhysicsEngine();
  77487. if (!this._physicsEngine) {
  77488. BABYLON.Tools.Error("Physics not enabled. Please use scene.enablePhysics(...) before creating impostors.");
  77489. }
  77490. else {
  77491. //set the object's quaternion, if not set
  77492. if (!this.object.rotationQuaternion) {
  77493. if (this.object.rotation) {
  77494. this.object.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(this.object.rotation.y, this.object.rotation.x, this.object.rotation.z);
  77495. }
  77496. else {
  77497. this.object.rotationQuaternion = new BABYLON.Quaternion();
  77498. }
  77499. }
  77500. //default options params
  77501. this._options.mass = (_options.mass === void 0) ? 0 : _options.mass;
  77502. this._options.friction = (_options.friction === void 0) ? 0.2 : _options.friction;
  77503. this._options.restitution = (_options.restitution === void 0) ? 0.2 : _options.restitution;
  77504. this._joints = [];
  77505. //If the mesh has a parent, don't initialize the physicsBody. Instead wait for the parent to do that.
  77506. if (!this.object.parent || this._options.ignoreParent) {
  77507. this._init();
  77508. }
  77509. else if (this.object.parent.physicsImpostor) {
  77510. BABYLON.Tools.Warn("You must affect impostors to children before affecting impostor to parent.");
  77511. }
  77512. }
  77513. }
  77514. Object.defineProperty(PhysicsImpostor.prototype, "isDisposed", {
  77515. get: function () {
  77516. return this._isDisposed;
  77517. },
  77518. enumerable: true,
  77519. configurable: true
  77520. });
  77521. Object.defineProperty(PhysicsImpostor.prototype, "mass", {
  77522. get: function () {
  77523. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getBodyMass(this) : 0;
  77524. },
  77525. set: function (value) {
  77526. this.setMass(value);
  77527. },
  77528. enumerable: true,
  77529. configurable: true
  77530. });
  77531. Object.defineProperty(PhysicsImpostor.prototype, "friction", {
  77532. get: function () {
  77533. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getBodyFriction(this) : 0;
  77534. },
  77535. set: function (value) {
  77536. if (!this._physicsEngine) {
  77537. return;
  77538. }
  77539. this._physicsEngine.getPhysicsPlugin().setBodyFriction(this, value);
  77540. },
  77541. enumerable: true,
  77542. configurable: true
  77543. });
  77544. Object.defineProperty(PhysicsImpostor.prototype, "restitution", {
  77545. get: function () {
  77546. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getBodyRestitution(this) : 0;
  77547. },
  77548. set: function (value) {
  77549. if (!this._physicsEngine) {
  77550. return;
  77551. }
  77552. this._physicsEngine.getPhysicsPlugin().setBodyRestitution(this, value);
  77553. },
  77554. enumerable: true,
  77555. configurable: true
  77556. });
  77557. /**
  77558. * This function will completly initialize this impostor.
  77559. * It will create a new body - but only if this mesh has no parent.
  77560. * If it has, this impostor will not be used other than to define the impostor
  77561. * of the child mesh.
  77562. */
  77563. PhysicsImpostor.prototype._init = function () {
  77564. if (!this._physicsEngine) {
  77565. return;
  77566. }
  77567. this._physicsEngine.removeImpostor(this);
  77568. this.physicsBody = null;
  77569. this._parent = this._parent || this._getPhysicsParent();
  77570. if (!this._isDisposed && (!this.parent || this._options.ignoreParent)) {
  77571. this._physicsEngine.addImpostor(this);
  77572. }
  77573. };
  77574. PhysicsImpostor.prototype._getPhysicsParent = function () {
  77575. if (this.object.parent instanceof BABYLON.AbstractMesh) {
  77576. var parentMesh = this.object.parent;
  77577. return parentMesh.physicsImpostor;
  77578. }
  77579. return null;
  77580. };
  77581. /**
  77582. * Should a new body be generated.
  77583. */
  77584. PhysicsImpostor.prototype.isBodyInitRequired = function () {
  77585. return this._bodyUpdateRequired || (!this._physicsBody && !this._parent);
  77586. };
  77587. PhysicsImpostor.prototype.setScalingUpdated = function (updated) {
  77588. this.forceUpdate();
  77589. };
  77590. /**
  77591. * Force a regeneration of this or the parent's impostor's body.
  77592. * Use under cautious - This will remove all joints already implemented.
  77593. */
  77594. PhysicsImpostor.prototype.forceUpdate = function () {
  77595. this._init();
  77596. if (this.parent && !this._options.ignoreParent) {
  77597. this.parent.forceUpdate();
  77598. }
  77599. };
  77600. Object.defineProperty(PhysicsImpostor.prototype, "physicsBody", {
  77601. /*public get mesh(): AbstractMesh {
  77602. return this._mesh;
  77603. }*/
  77604. /**
  77605. * Gets the body that holds this impostor. Either its own, or its parent.
  77606. */
  77607. get: function () {
  77608. return (this._parent && !this._options.ignoreParent) ? this._parent.physicsBody : this._physicsBody;
  77609. },
  77610. /**
  77611. * Set the physics body. Used mainly by the physics engine/plugin
  77612. */
  77613. set: function (physicsBody) {
  77614. if (this._physicsBody && this._physicsEngine) {
  77615. this._physicsEngine.getPhysicsPlugin().removePhysicsBody(this);
  77616. }
  77617. this._physicsBody = physicsBody;
  77618. this.resetUpdateFlags();
  77619. },
  77620. enumerable: true,
  77621. configurable: true
  77622. });
  77623. Object.defineProperty(PhysicsImpostor.prototype, "parent", {
  77624. get: function () {
  77625. return !this._options.ignoreParent && this._parent ? this._parent : null;
  77626. },
  77627. set: function (value) {
  77628. this._parent = value;
  77629. },
  77630. enumerable: true,
  77631. configurable: true
  77632. });
  77633. PhysicsImpostor.prototype.resetUpdateFlags = function () {
  77634. this._bodyUpdateRequired = false;
  77635. };
  77636. PhysicsImpostor.prototype.getObjectExtendSize = function () {
  77637. if (this.object.getBoundingInfo) {
  77638. var q = this.object.rotationQuaternion;
  77639. //reset rotation
  77640. this.object.rotationQuaternion = PhysicsImpostor.IDENTITY_QUATERNION;
  77641. //calculate the world matrix with no rotation
  77642. this.object.computeWorldMatrix && this.object.computeWorldMatrix(true);
  77643. var boundingInfo = this.object.getBoundingInfo();
  77644. var size = boundingInfo.boundingBox.extendSizeWorld.scale(2);
  77645. //bring back the rotation
  77646. this.object.rotationQuaternion = q;
  77647. //calculate the world matrix with the new rotation
  77648. this.object.computeWorldMatrix && this.object.computeWorldMatrix(true);
  77649. return size;
  77650. }
  77651. else {
  77652. return PhysicsImpostor.DEFAULT_OBJECT_SIZE;
  77653. }
  77654. };
  77655. PhysicsImpostor.prototype.getObjectCenter = function () {
  77656. if (this.object.getBoundingInfo) {
  77657. var boundingInfo = this.object.getBoundingInfo();
  77658. return boundingInfo.boundingBox.centerWorld;
  77659. }
  77660. else {
  77661. return this.object.position;
  77662. }
  77663. };
  77664. /**
  77665. * Get a specific parametes from the options parameter.
  77666. */
  77667. PhysicsImpostor.prototype.getParam = function (paramName) {
  77668. return this._options[paramName];
  77669. };
  77670. /**
  77671. * Sets a specific parameter in the options given to the physics plugin
  77672. */
  77673. PhysicsImpostor.prototype.setParam = function (paramName, value) {
  77674. this._options[paramName] = value;
  77675. this._bodyUpdateRequired = true;
  77676. };
  77677. /**
  77678. * Specifically change the body's mass option. Won't recreate the physics body object
  77679. */
  77680. PhysicsImpostor.prototype.setMass = function (mass) {
  77681. if (this.getParam("mass") !== mass) {
  77682. this.setParam("mass", mass);
  77683. }
  77684. if (this._physicsEngine) {
  77685. this._physicsEngine.getPhysicsPlugin().setBodyMass(this, mass);
  77686. }
  77687. };
  77688. PhysicsImpostor.prototype.getLinearVelocity = function () {
  77689. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getLinearVelocity(this) : BABYLON.Vector3.Zero();
  77690. };
  77691. PhysicsImpostor.prototype.setLinearVelocity = function (velocity) {
  77692. if (this._physicsEngine) {
  77693. this._physicsEngine.getPhysicsPlugin().setLinearVelocity(this, velocity);
  77694. }
  77695. };
  77696. PhysicsImpostor.prototype.getAngularVelocity = function () {
  77697. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getAngularVelocity(this) : BABYLON.Vector3.Zero();
  77698. };
  77699. PhysicsImpostor.prototype.setAngularVelocity = function (velocity) {
  77700. if (this._physicsEngine) {
  77701. this._physicsEngine.getPhysicsPlugin().setAngularVelocity(this, velocity);
  77702. }
  77703. };
  77704. /**
  77705. * Execute a function with the physics plugin native code.
  77706. * Provide a function the will have two variables - the world object and the physics body object.
  77707. */
  77708. PhysicsImpostor.prototype.executeNativeFunction = function (func) {
  77709. if (this._physicsEngine) {
  77710. func(this._physicsEngine.getPhysicsPlugin().world, this.physicsBody);
  77711. }
  77712. };
  77713. /**
  77714. * Register a function that will be executed before the physics world is stepping forward.
  77715. */
  77716. PhysicsImpostor.prototype.registerBeforePhysicsStep = function (func) {
  77717. this._onBeforePhysicsStepCallbacks.push(func);
  77718. };
  77719. PhysicsImpostor.prototype.unregisterBeforePhysicsStep = function (func) {
  77720. var index = this._onBeforePhysicsStepCallbacks.indexOf(func);
  77721. if (index > -1) {
  77722. this._onBeforePhysicsStepCallbacks.splice(index, 1);
  77723. }
  77724. else {
  77725. BABYLON.Tools.Warn("Function to remove was not found");
  77726. }
  77727. };
  77728. /**
  77729. * Register a function that will be executed after the physics step
  77730. */
  77731. PhysicsImpostor.prototype.registerAfterPhysicsStep = function (func) {
  77732. this._onAfterPhysicsStepCallbacks.push(func);
  77733. };
  77734. PhysicsImpostor.prototype.unregisterAfterPhysicsStep = function (func) {
  77735. var index = this._onAfterPhysicsStepCallbacks.indexOf(func);
  77736. if (index > -1) {
  77737. this._onAfterPhysicsStepCallbacks.splice(index, 1);
  77738. }
  77739. else {
  77740. BABYLON.Tools.Warn("Function to remove was not found");
  77741. }
  77742. };
  77743. /**
  77744. * register a function that will be executed when this impostor collides against a different body.
  77745. */
  77746. PhysicsImpostor.prototype.registerOnPhysicsCollide = function (collideAgainst, func) {
  77747. var collidedAgainstList = collideAgainst instanceof Array ? collideAgainst : [collideAgainst];
  77748. this._onPhysicsCollideCallbacks.push({ callback: func, otherImpostors: collidedAgainstList });
  77749. };
  77750. PhysicsImpostor.prototype.unregisterOnPhysicsCollide = function (collideAgainst, func) {
  77751. var collidedAgainstList = collideAgainst instanceof Array ? collideAgainst : [collideAgainst];
  77752. var index = this._onPhysicsCollideCallbacks.indexOf({ callback: func, otherImpostors: collidedAgainstList });
  77753. if (index > -1) {
  77754. this._onPhysicsCollideCallbacks.splice(index, 1);
  77755. }
  77756. else {
  77757. BABYLON.Tools.Warn("Function to remove was not found");
  77758. }
  77759. };
  77760. PhysicsImpostor.prototype.getParentsRotation = function () {
  77761. var parent = this.object.parent;
  77762. this._tmpQuat.copyFromFloats(0, 0, 0, 1);
  77763. while (parent) {
  77764. if (parent.rotationQuaternion) {
  77765. this._tmpQuat2.copyFrom(parent.rotationQuaternion);
  77766. }
  77767. else {
  77768. BABYLON.Quaternion.RotationYawPitchRollToRef(parent.rotation.y, parent.rotation.x, parent.rotation.z, this._tmpQuat2);
  77769. }
  77770. this._tmpQuat.multiplyToRef(this._tmpQuat2, this._tmpQuat);
  77771. parent = parent.parent;
  77772. }
  77773. return this._tmpQuat;
  77774. };
  77775. /**
  77776. * Apply a force
  77777. */
  77778. PhysicsImpostor.prototype.applyForce = function (force, contactPoint) {
  77779. if (this._physicsEngine) {
  77780. this._physicsEngine.getPhysicsPlugin().applyForce(this, force, contactPoint);
  77781. }
  77782. return this;
  77783. };
  77784. /**
  77785. * Apply an impulse
  77786. */
  77787. PhysicsImpostor.prototype.applyImpulse = function (force, contactPoint) {
  77788. if (this._physicsEngine) {
  77789. this._physicsEngine.getPhysicsPlugin().applyImpulse(this, force, contactPoint);
  77790. }
  77791. return this;
  77792. };
  77793. /**
  77794. * A help function to create a joint.
  77795. */
  77796. PhysicsImpostor.prototype.createJoint = function (otherImpostor, jointType, jointData) {
  77797. var joint = new BABYLON.PhysicsJoint(jointType, jointData);
  77798. this.addJoint(otherImpostor, joint);
  77799. return this;
  77800. };
  77801. /**
  77802. * Add a joint to this impostor with a different impostor.
  77803. */
  77804. PhysicsImpostor.prototype.addJoint = function (otherImpostor, joint) {
  77805. this._joints.push({
  77806. otherImpostor: otherImpostor,
  77807. joint: joint
  77808. });
  77809. if (this._physicsEngine) {
  77810. this._physicsEngine.addJoint(this, otherImpostor, joint);
  77811. }
  77812. return this;
  77813. };
  77814. /**
  77815. * Will keep this body still, in a sleep mode.
  77816. */
  77817. PhysicsImpostor.prototype.sleep = function () {
  77818. if (this._physicsEngine) {
  77819. this._physicsEngine.getPhysicsPlugin().sleepBody(this);
  77820. }
  77821. return this;
  77822. };
  77823. /**
  77824. * Wake the body up.
  77825. */
  77826. PhysicsImpostor.prototype.wakeUp = function () {
  77827. if (this._physicsEngine) {
  77828. this._physicsEngine.getPhysicsPlugin().wakeUpBody(this);
  77829. }
  77830. return this;
  77831. };
  77832. PhysicsImpostor.prototype.clone = function (newObject) {
  77833. if (!newObject)
  77834. return null;
  77835. return new PhysicsImpostor(newObject, this.type, this._options, this._scene);
  77836. };
  77837. PhysicsImpostor.prototype.dispose = function () {
  77838. var _this = this;
  77839. //no dispose if no physics engine is available.
  77840. if (!this._physicsEngine) {
  77841. return;
  77842. }
  77843. this._joints.forEach(function (j) {
  77844. if (_this._physicsEngine) {
  77845. _this._physicsEngine.removeJoint(_this, j.otherImpostor, j.joint);
  77846. }
  77847. });
  77848. //dispose the physics body
  77849. this._physicsEngine.removeImpostor(this);
  77850. if (this.parent) {
  77851. this.parent.forceUpdate();
  77852. }
  77853. else {
  77854. /*this._object.getChildMeshes().forEach(function(mesh) {
  77855. if (mesh.physicsImpostor) {
  77856. if (disposeChildren) {
  77857. mesh.physicsImpostor.dispose();
  77858. mesh.physicsImpostor = null;
  77859. }
  77860. }
  77861. })*/
  77862. }
  77863. this._isDisposed = true;
  77864. };
  77865. PhysicsImpostor.prototype.setDeltaPosition = function (position) {
  77866. this._deltaPosition.copyFrom(position);
  77867. };
  77868. PhysicsImpostor.prototype.setDeltaRotation = function (rotation) {
  77869. if (!this._deltaRotation) {
  77870. this._deltaRotation = new BABYLON.Quaternion();
  77871. }
  77872. this._deltaRotation.copyFrom(rotation);
  77873. this._deltaRotationConjugated = this._deltaRotation.conjugate();
  77874. };
  77875. PhysicsImpostor.prototype.getBoxSizeToRef = function (result) {
  77876. if (this._physicsEngine) {
  77877. this._physicsEngine.getPhysicsPlugin().getBoxSizeToRef(this, result);
  77878. }
  77879. return this;
  77880. };
  77881. PhysicsImpostor.prototype.getRadius = function () {
  77882. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getRadius(this) : 0;
  77883. };
  77884. /**
  77885. * Sync a bone with this impostor
  77886. * @param bone The bone to sync to the impostor.
  77887. * @param boneMesh The mesh that the bone is influencing.
  77888. * @param jointPivot The pivot of the joint / bone in local space.
  77889. * @param distToJoint Optional distance from the impostor to the joint.
  77890. * @param adjustRotation Optional quaternion for adjusting the local rotation of the bone.
  77891. */
  77892. PhysicsImpostor.prototype.syncBoneWithImpostor = function (bone, boneMesh, jointPivot, distToJoint, adjustRotation) {
  77893. var tempVec = PhysicsImpostor._tmpVecs[0];
  77894. var mesh = this.object;
  77895. if (mesh.rotationQuaternion) {
  77896. if (adjustRotation) {
  77897. var tempQuat = PhysicsImpostor._tmpQuat;
  77898. mesh.rotationQuaternion.multiplyToRef(adjustRotation, tempQuat);
  77899. bone.setRotationQuaternion(tempQuat, BABYLON.Space.WORLD, boneMesh);
  77900. }
  77901. else {
  77902. bone.setRotationQuaternion(mesh.rotationQuaternion, BABYLON.Space.WORLD, boneMesh);
  77903. }
  77904. }
  77905. tempVec.x = 0;
  77906. tempVec.y = 0;
  77907. tempVec.z = 0;
  77908. if (jointPivot) {
  77909. tempVec.x = jointPivot.x;
  77910. tempVec.y = jointPivot.y;
  77911. tempVec.z = jointPivot.z;
  77912. bone.getDirectionToRef(tempVec, boneMesh, tempVec);
  77913. if (distToJoint === undefined || distToJoint === null) {
  77914. distToJoint = jointPivot.length();
  77915. }
  77916. tempVec.x *= distToJoint;
  77917. tempVec.y *= distToJoint;
  77918. tempVec.z *= distToJoint;
  77919. }
  77920. if (bone.getParent()) {
  77921. tempVec.addInPlace(mesh.getAbsolutePosition());
  77922. bone.setAbsolutePosition(tempVec, boneMesh);
  77923. }
  77924. else {
  77925. boneMesh.setAbsolutePosition(mesh.getAbsolutePosition());
  77926. boneMesh.position.x -= tempVec.x;
  77927. boneMesh.position.y -= tempVec.y;
  77928. boneMesh.position.z -= tempVec.z;
  77929. }
  77930. };
  77931. /**
  77932. * Sync impostor to a bone
  77933. * @param bone The bone that the impostor will be synced to.
  77934. * @param boneMesh The mesh that the bone is influencing.
  77935. * @param jointPivot The pivot of the joint / bone in local space.
  77936. * @param distToJoint Optional distance from the impostor to the joint.
  77937. * @param adjustRotation Optional quaternion for adjusting the local rotation of the bone.
  77938. * @param boneAxis Optional vector3 axis the bone is aligned with
  77939. */
  77940. PhysicsImpostor.prototype.syncImpostorWithBone = function (bone, boneMesh, jointPivot, distToJoint, adjustRotation, boneAxis) {
  77941. var mesh = this.object;
  77942. if (mesh.rotationQuaternion) {
  77943. if (adjustRotation) {
  77944. var tempQuat = PhysicsImpostor._tmpQuat;
  77945. bone.getRotationQuaternionToRef(BABYLON.Space.WORLD, boneMesh, tempQuat);
  77946. tempQuat.multiplyToRef(adjustRotation, mesh.rotationQuaternion);
  77947. }
  77948. else {
  77949. bone.getRotationQuaternionToRef(BABYLON.Space.WORLD, boneMesh, mesh.rotationQuaternion);
  77950. }
  77951. }
  77952. var pos = PhysicsImpostor._tmpVecs[0];
  77953. var boneDir = PhysicsImpostor._tmpVecs[1];
  77954. if (!boneAxis) {
  77955. boneAxis = PhysicsImpostor._tmpVecs[2];
  77956. boneAxis.x = 0;
  77957. boneAxis.y = 1;
  77958. boneAxis.z = 0;
  77959. }
  77960. bone.getDirectionToRef(boneAxis, boneMesh, boneDir);
  77961. bone.getAbsolutePositionToRef(boneMesh, pos);
  77962. if ((distToJoint === undefined || distToJoint === null) && jointPivot) {
  77963. distToJoint = jointPivot.length();
  77964. }
  77965. if (distToJoint !== undefined && distToJoint !== null) {
  77966. pos.x += boneDir.x * distToJoint;
  77967. pos.y += boneDir.y * distToJoint;
  77968. pos.z += boneDir.z * distToJoint;
  77969. }
  77970. mesh.setAbsolutePosition(pos);
  77971. };
  77972. PhysicsImpostor.DEFAULT_OBJECT_SIZE = new BABYLON.Vector3(1, 1, 1);
  77973. PhysicsImpostor.IDENTITY_QUATERNION = BABYLON.Quaternion.Identity();
  77974. PhysicsImpostor._tmpVecs = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  77975. PhysicsImpostor._tmpQuat = BABYLON.Quaternion.Identity();
  77976. //Impostor types
  77977. PhysicsImpostor.NoImpostor = 0;
  77978. PhysicsImpostor.SphereImpostor = 1;
  77979. PhysicsImpostor.BoxImpostor = 2;
  77980. PhysicsImpostor.PlaneImpostor = 3;
  77981. PhysicsImpostor.MeshImpostor = 4;
  77982. PhysicsImpostor.CylinderImpostor = 7;
  77983. PhysicsImpostor.ParticleImpostor = 8;
  77984. PhysicsImpostor.HeightmapImpostor = 9;
  77985. return PhysicsImpostor;
  77986. }());
  77987. BABYLON.PhysicsImpostor = PhysicsImpostor;
  77988. })(BABYLON || (BABYLON = {}));
  77989. //# sourceMappingURL=babylon.physicsImpostor.js.map
  77990. "use strict";
  77991. var BABYLON;
  77992. (function (BABYLON) {
  77993. var PhysicsEngine = /** @class */ (function () {
  77994. function PhysicsEngine(gravity, _physicsPlugin) {
  77995. if (_physicsPlugin === void 0) { _physicsPlugin = new BABYLON.CannonJSPlugin(); }
  77996. this._physicsPlugin = _physicsPlugin;
  77997. //new methods and parameters
  77998. this._impostors = [];
  77999. this._joints = [];
  78000. if (!this._physicsPlugin.isSupported()) {
  78001. throw new Error("Physics Engine " + this._physicsPlugin.name + " cannot be found. "
  78002. + "Please make sure it is included.");
  78003. }
  78004. gravity = gravity || new BABYLON.Vector3(0, -9.807, 0);
  78005. this.setGravity(gravity);
  78006. this.setTimeStep();
  78007. }
  78008. PhysicsEngine.prototype.setGravity = function (gravity) {
  78009. this.gravity = gravity;
  78010. this._physicsPlugin.setGravity(this.gravity);
  78011. };
  78012. /**
  78013. * Set the time step of the physics engine.
  78014. * default is 1/60.
  78015. * To slow it down, enter 1/600 for example.
  78016. * To speed it up, 1/30
  78017. * @param {number} newTimeStep the new timestep to apply to this world.
  78018. */
  78019. PhysicsEngine.prototype.setTimeStep = function (newTimeStep) {
  78020. if (newTimeStep === void 0) { newTimeStep = 1 / 60; }
  78021. this._physicsPlugin.setTimeStep(newTimeStep);
  78022. };
  78023. /**
  78024. * Get the time step of the physics engine.
  78025. */
  78026. PhysicsEngine.prototype.getTimeStep = function () {
  78027. return this._physicsPlugin.getTimeStep();
  78028. };
  78029. PhysicsEngine.prototype.dispose = function () {
  78030. this._impostors.forEach(function (impostor) {
  78031. impostor.dispose();
  78032. });
  78033. this._physicsPlugin.dispose();
  78034. };
  78035. PhysicsEngine.prototype.getPhysicsPluginName = function () {
  78036. return this._physicsPlugin.name;
  78037. };
  78038. /**
  78039. * Adding a new impostor for the impostor tracking.
  78040. * This will be done by the impostor itself.
  78041. * @param {PhysicsImpostor} impostor the impostor to add
  78042. */
  78043. PhysicsEngine.prototype.addImpostor = function (impostor) {
  78044. impostor.uniqueId = this._impostors.push(impostor);
  78045. //if no parent, generate the body
  78046. if (!impostor.parent) {
  78047. this._physicsPlugin.generatePhysicsBody(impostor);
  78048. }
  78049. };
  78050. /**
  78051. * Remove an impostor from the engine.
  78052. * This impostor and its mesh will not longer be updated by the physics engine.
  78053. * @param {PhysicsImpostor} impostor the impostor to remove
  78054. */
  78055. PhysicsEngine.prototype.removeImpostor = function (impostor) {
  78056. var index = this._impostors.indexOf(impostor);
  78057. if (index > -1) {
  78058. var removed = this._impostors.splice(index, 1);
  78059. //Is it needed?
  78060. if (removed.length) {
  78061. //this will also remove it from the world.
  78062. removed[0].physicsBody = null;
  78063. }
  78064. }
  78065. };
  78066. /**
  78067. * Add a joint to the physics engine
  78068. * @param {PhysicsImpostor} mainImpostor the main impostor to which the joint is added.
  78069. * @param {PhysicsImpostor} connectedImpostor the impostor that is connected to the main impostor using this joint
  78070. * @param {PhysicsJoint} the joint that will connect both impostors.
  78071. */
  78072. PhysicsEngine.prototype.addJoint = function (mainImpostor, connectedImpostor, joint) {
  78073. var impostorJoint = {
  78074. mainImpostor: mainImpostor,
  78075. connectedImpostor: connectedImpostor,
  78076. joint: joint
  78077. };
  78078. joint.physicsPlugin = this._physicsPlugin;
  78079. this._joints.push(impostorJoint);
  78080. this._physicsPlugin.generateJoint(impostorJoint);
  78081. };
  78082. PhysicsEngine.prototype.removeJoint = function (mainImpostor, connectedImpostor, joint) {
  78083. var matchingJoints = this._joints.filter(function (impostorJoint) {
  78084. return (impostorJoint.connectedImpostor === connectedImpostor
  78085. && impostorJoint.joint === joint
  78086. && impostorJoint.mainImpostor === mainImpostor);
  78087. });
  78088. if (matchingJoints.length) {
  78089. this._physicsPlugin.removeJoint(matchingJoints[0]);
  78090. //TODO remove it from the list as well
  78091. }
  78092. };
  78093. /**
  78094. * Called by the scene. no need to call it.
  78095. */
  78096. PhysicsEngine.prototype._step = function (delta) {
  78097. var _this = this;
  78098. //check if any mesh has no body / requires an update
  78099. this._impostors.forEach(function (impostor) {
  78100. if (impostor.isBodyInitRequired()) {
  78101. _this._physicsPlugin.generatePhysicsBody(impostor);
  78102. }
  78103. });
  78104. if (delta > 0.1) {
  78105. delta = 0.1;
  78106. }
  78107. else if (delta <= 0) {
  78108. delta = 1.0 / 60.0;
  78109. }
  78110. this._physicsPlugin.executeStep(delta, this._impostors);
  78111. };
  78112. PhysicsEngine.prototype.getPhysicsPlugin = function () {
  78113. return this._physicsPlugin;
  78114. };
  78115. PhysicsEngine.prototype.getImpostors = function () {
  78116. return this._impostors;
  78117. };
  78118. PhysicsEngine.prototype.getImpostorForPhysicsObject = function (object) {
  78119. for (var i = 0; i < this._impostors.length; ++i) {
  78120. if (this._impostors[i].object === object) {
  78121. return this._impostors[i];
  78122. }
  78123. }
  78124. return null;
  78125. };
  78126. PhysicsEngine.prototype.getImpostorWithPhysicsBody = function (body) {
  78127. for (var i = 0; i < this._impostors.length; ++i) {
  78128. if (this._impostors[i].physicsBody === body) {
  78129. return this._impostors[i];
  78130. }
  78131. }
  78132. return null;
  78133. };
  78134. // Statics
  78135. PhysicsEngine.Epsilon = 0.001;
  78136. return PhysicsEngine;
  78137. }());
  78138. BABYLON.PhysicsEngine = PhysicsEngine;
  78139. })(BABYLON || (BABYLON = {}));
  78140. //# sourceMappingURL=babylon.physicsEngine.js.map
  78141. "use strict";
  78142. var BABYLON;
  78143. (function (BABYLON) {
  78144. var PhysicsHelper = /** @class */ (function () {
  78145. function PhysicsHelper(scene) {
  78146. this._scene = scene;
  78147. this._physicsEngine = this._scene.getPhysicsEngine();
  78148. if (!this._physicsEngine) {
  78149. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you can use the methods.');
  78150. }
  78151. }
  78152. /**
  78153. * @param {Vector3} origin the origin of the explosion
  78154. * @param {number} radius the explosion radius
  78155. * @param {number} strength the explosion strength
  78156. * @param {PhysicsRadialImpulseFalloff} falloff possible options: Constant & Linear. Defaults to Constant
  78157. */
  78158. PhysicsHelper.prototype.applyRadialExplosionImpulse = function (origin, radius, strength, falloff) {
  78159. if (falloff === void 0) { falloff = PhysicsRadialImpulseFalloff.Constant; }
  78160. if (!this._physicsEngine) {
  78161. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you call this method.');
  78162. return null;
  78163. }
  78164. var impostors = this._physicsEngine.getImpostors();
  78165. if (impostors.length === 0) {
  78166. return null;
  78167. }
  78168. var event = new PhysicsRadialExplosionEvent(this._scene);
  78169. impostors.forEach(function (impostor) {
  78170. var impostorForceAndContactPoint = event.getImpostorForceAndContactPoint(impostor, origin, radius, strength, falloff);
  78171. if (!impostorForceAndContactPoint) {
  78172. return;
  78173. }
  78174. impostor.applyImpulse(impostorForceAndContactPoint.force, impostorForceAndContactPoint.contactPoint);
  78175. });
  78176. event.dispose(false);
  78177. return event;
  78178. };
  78179. /**
  78180. * @param {Vector3} origin the origin of the explosion
  78181. * @param {number} radius the explosion radius
  78182. * @param {number} strength the explosion strength
  78183. * @param {PhysicsRadialImpulseFalloff} falloff possible options: Constant & Linear. Defaults to Constant
  78184. */
  78185. PhysicsHelper.prototype.applyRadialExplosionForce = function (origin, radius, strength, falloff) {
  78186. if (falloff === void 0) { falloff = PhysicsRadialImpulseFalloff.Constant; }
  78187. if (!this._physicsEngine) {
  78188. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you call the PhysicsHelper.');
  78189. return null;
  78190. }
  78191. var impostors = this._physicsEngine.getImpostors();
  78192. if (impostors.length === 0) {
  78193. return null;
  78194. }
  78195. var event = new PhysicsRadialExplosionEvent(this._scene);
  78196. impostors.forEach(function (impostor) {
  78197. var impostorForceAndContactPoint = event.getImpostorForceAndContactPoint(impostor, origin, radius, strength, falloff);
  78198. if (!impostorForceAndContactPoint) {
  78199. return;
  78200. }
  78201. impostor.applyForce(impostorForceAndContactPoint.force, impostorForceAndContactPoint.contactPoint);
  78202. });
  78203. event.dispose(false);
  78204. return event;
  78205. };
  78206. /**
  78207. * @param {Vector3} origin the origin of the explosion
  78208. * @param {number} radius the explosion radius
  78209. * @param {number} strength the explosion strength
  78210. * @param {PhysicsRadialImpulseFalloff} falloff possible options: Constant & Linear. Defaults to Constant
  78211. */
  78212. PhysicsHelper.prototype.gravitationalField = function (origin, radius, strength, falloff) {
  78213. if (falloff === void 0) { falloff = PhysicsRadialImpulseFalloff.Constant; }
  78214. if (!this._physicsEngine) {
  78215. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you call the PhysicsHelper.');
  78216. return null;
  78217. }
  78218. var impostors = this._physicsEngine.getImpostors();
  78219. if (impostors.length === 0) {
  78220. return null;
  78221. }
  78222. var event = new PhysicsGravitationalFieldEvent(this, this._scene, origin, radius, strength, falloff);
  78223. event.dispose(false);
  78224. return event;
  78225. };
  78226. /**
  78227. * @param {Vector3} origin the origin of the updraft
  78228. * @param {number} radius the radius of the updraft
  78229. * @param {number} strength the strength of the updraft
  78230. * @param {number} height the height of the updraft
  78231. * @param {PhysicsUpdraftMode} updraftMode possible options: Center & Perpendicular. Defaults to Center
  78232. */
  78233. PhysicsHelper.prototype.updraft = function (origin, radius, strength, height, updraftMode) {
  78234. if (updraftMode === void 0) { updraftMode = PhysicsUpdraftMode.Center; }
  78235. if (!this._physicsEngine) {
  78236. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you call the PhysicsHelper.');
  78237. return null;
  78238. }
  78239. if (this._physicsEngine.getImpostors().length === 0) {
  78240. return null;
  78241. }
  78242. var event = new PhysicsUpdraftEvent(this._scene, origin, radius, strength, height, updraftMode);
  78243. event.dispose(false);
  78244. return event;
  78245. };
  78246. /**
  78247. * @param {Vector3} origin the of the vortex
  78248. * @param {number} radius the radius of the vortex
  78249. * @param {number} strength the strength of the vortex
  78250. * @param {number} height the height of the vortex
  78251. */
  78252. PhysicsHelper.prototype.vortex = function (origin, radius, strength, height) {
  78253. if (!this._physicsEngine) {
  78254. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you call the PhysicsHelper.');
  78255. return null;
  78256. }
  78257. if (this._physicsEngine.getImpostors().length === 0) {
  78258. return null;
  78259. }
  78260. var event = new PhysicsVortexEvent(this._scene, origin, radius, strength, height);
  78261. event.dispose(false);
  78262. return event;
  78263. };
  78264. return PhysicsHelper;
  78265. }());
  78266. BABYLON.PhysicsHelper = PhysicsHelper;
  78267. /***** Radial explosion *****/
  78268. var PhysicsRadialExplosionEvent = /** @class */ (function () {
  78269. function PhysicsRadialExplosionEvent(scene) {
  78270. this._sphereOptions = { segments: 32, diameter: 1 }; // TODO: make configurable
  78271. this._rays = [];
  78272. this._dataFetched = false; // check if the data has been fetched. If not, do cleanup
  78273. this._scene = scene;
  78274. }
  78275. /**
  78276. * Returns the data related to the radial explosion event (sphere & rays).
  78277. * @returns {PhysicsRadialExplosionEventData}
  78278. */
  78279. PhysicsRadialExplosionEvent.prototype.getData = function () {
  78280. this._dataFetched = true;
  78281. return {
  78282. sphere: this._sphere,
  78283. rays: this._rays,
  78284. };
  78285. };
  78286. /**
  78287. * Returns the force and contact point of the impostor or false, if the impostor is not affected by the force/impulse.
  78288. * @param impostor
  78289. * @param {Vector3} origin the origin of the explosion
  78290. * @param {number} radius the explosion radius
  78291. * @param {number} strength the explosion strength
  78292. * @param {PhysicsRadialImpulseFalloff} falloff possible options: Constant & Linear
  78293. * @returns {Nullable<PhysicsForceAndContactPoint>}
  78294. */
  78295. PhysicsRadialExplosionEvent.prototype.getImpostorForceAndContactPoint = function (impostor, origin, radius, strength, falloff) {
  78296. if (impostor.mass === 0) {
  78297. return null;
  78298. }
  78299. if (!this._intersectsWithSphere(impostor, origin, radius)) {
  78300. return null;
  78301. }
  78302. if (impostor.object.getClassName() !== 'Mesh' && impostor.object.getClassName() !== 'InstancedMesh') {
  78303. return null;
  78304. }
  78305. var impostorObjectCenter = impostor.getObjectCenter();
  78306. var direction = impostorObjectCenter.subtract(origin);
  78307. var ray = new BABYLON.Ray(origin, direction, radius);
  78308. this._rays.push(ray);
  78309. var hit = ray.intersectsMesh(impostor.object);
  78310. var contactPoint = hit.pickedPoint;
  78311. if (!contactPoint) {
  78312. return null;
  78313. }
  78314. var distanceFromOrigin = BABYLON.Vector3.Distance(origin, contactPoint);
  78315. if (distanceFromOrigin > radius) {
  78316. return null;
  78317. }
  78318. var multiplier = falloff === PhysicsRadialImpulseFalloff.Constant
  78319. ? strength
  78320. : strength * (1 - (distanceFromOrigin / radius));
  78321. var force = direction.multiplyByFloats(multiplier, multiplier, multiplier);
  78322. return { force: force, contactPoint: contactPoint };
  78323. };
  78324. /**
  78325. * Disposes the sphere.
  78326. * @param {bolean} force
  78327. */
  78328. PhysicsRadialExplosionEvent.prototype.dispose = function (force) {
  78329. var _this = this;
  78330. if (force === void 0) { force = true; }
  78331. if (force) {
  78332. this._sphere.dispose();
  78333. }
  78334. else {
  78335. setTimeout(function () {
  78336. if (!_this._dataFetched) {
  78337. _this._sphere.dispose();
  78338. }
  78339. }, 0);
  78340. }
  78341. };
  78342. /*** Helpers ***/
  78343. PhysicsRadialExplosionEvent.prototype._prepareSphere = function () {
  78344. if (!this._sphere) {
  78345. this._sphere = BABYLON.MeshBuilder.CreateSphere("radialExplosionEventSphere", this._sphereOptions, this._scene);
  78346. this._sphere.isVisible = false;
  78347. }
  78348. };
  78349. PhysicsRadialExplosionEvent.prototype._intersectsWithSphere = function (impostor, origin, radius) {
  78350. var impostorObject = impostor.object;
  78351. this._prepareSphere();
  78352. this._sphere.position = origin;
  78353. this._sphere.scaling = new BABYLON.Vector3(radius * 2, radius * 2, radius * 2);
  78354. this._sphere._updateBoundingInfo();
  78355. this._sphere.computeWorldMatrix(true);
  78356. return this._sphere.intersectsMesh(impostorObject, true);
  78357. };
  78358. return PhysicsRadialExplosionEvent;
  78359. }());
  78360. BABYLON.PhysicsRadialExplosionEvent = PhysicsRadialExplosionEvent;
  78361. /***** Gravitational Field *****/
  78362. var PhysicsGravitationalFieldEvent = /** @class */ (function () {
  78363. function PhysicsGravitationalFieldEvent(physicsHelper, scene, origin, radius, strength, falloff) {
  78364. if (falloff === void 0) { falloff = PhysicsRadialImpulseFalloff.Constant; }
  78365. this._dataFetched = false; // check if the has been fetched the data. If not, do cleanup
  78366. this._physicsHelper = physicsHelper;
  78367. this._scene = scene;
  78368. this._origin = origin;
  78369. this._radius = radius;
  78370. this._strength = strength;
  78371. this._falloff = falloff;
  78372. this._tickCallback = this._tick.bind(this);
  78373. }
  78374. /**
  78375. * Returns the data related to the gravitational field event (sphere).
  78376. * @returns {PhysicsGravitationalFieldEventData}
  78377. */
  78378. PhysicsGravitationalFieldEvent.prototype.getData = function () {
  78379. this._dataFetched = true;
  78380. return {
  78381. sphere: this._sphere,
  78382. };
  78383. };
  78384. /**
  78385. * Enables the gravitational field.
  78386. */
  78387. PhysicsGravitationalFieldEvent.prototype.enable = function () {
  78388. this._tickCallback.call(this);
  78389. this._scene.registerBeforeRender(this._tickCallback);
  78390. };
  78391. /**
  78392. * Disables the gravitational field.
  78393. */
  78394. PhysicsGravitationalFieldEvent.prototype.disable = function () {
  78395. this._scene.unregisterBeforeRender(this._tickCallback);
  78396. };
  78397. /**
  78398. * Disposes the sphere.
  78399. * @param {bolean} force
  78400. */
  78401. PhysicsGravitationalFieldEvent.prototype.dispose = function (force) {
  78402. var _this = this;
  78403. if (force === void 0) { force = true; }
  78404. if (force) {
  78405. this._sphere.dispose();
  78406. }
  78407. else {
  78408. setTimeout(function () {
  78409. if (!_this._dataFetched) {
  78410. _this._sphere.dispose();
  78411. }
  78412. }, 0);
  78413. }
  78414. };
  78415. PhysicsGravitationalFieldEvent.prototype._tick = function () {
  78416. // Since the params won't change, we fetch the event only once
  78417. if (this._sphere) {
  78418. this._physicsHelper.applyRadialExplosionForce(this._origin, this._radius, this._strength * -1, this._falloff);
  78419. }
  78420. else {
  78421. var radialExplosionEvent = this._physicsHelper.applyRadialExplosionForce(this._origin, this._radius, this._strength * -1, this._falloff);
  78422. if (radialExplosionEvent) {
  78423. this._sphere = radialExplosionEvent.getData().sphere.clone('radialExplosionEventSphereClone');
  78424. }
  78425. }
  78426. };
  78427. return PhysicsGravitationalFieldEvent;
  78428. }());
  78429. BABYLON.PhysicsGravitationalFieldEvent = PhysicsGravitationalFieldEvent;
  78430. /***** Updraft *****/
  78431. var PhysicsUpdraftEvent = /** @class */ (function () {
  78432. function PhysicsUpdraftEvent(_scene, _origin, _radius, _strength, _height, _updraftMode) {
  78433. this._scene = _scene;
  78434. this._origin = _origin;
  78435. this._radius = _radius;
  78436. this._strength = _strength;
  78437. this._height = _height;
  78438. this._updraftMode = _updraftMode;
  78439. this._originTop = BABYLON.Vector3.Zero(); // the most upper part of the cylinder
  78440. this._originDirection = BABYLON.Vector3.Zero(); // used if the updraftMode is perpendicular
  78441. this._cylinderPosition = BABYLON.Vector3.Zero(); // to keep the cylinders position, because normally the origin is in the center and not on the bottom
  78442. this._dataFetched = false; // check if the has been fetched the data. If not, do cleanup
  78443. this._physicsEngine = this._scene.getPhysicsEngine();
  78444. this._origin.addToRef(new BABYLON.Vector3(0, this._height / 2, 0), this._cylinderPosition);
  78445. this._origin.addToRef(new BABYLON.Vector3(0, this._height, 0), this._originTop);
  78446. if (this._updraftMode === PhysicsUpdraftMode.Perpendicular) {
  78447. this._originDirection = this._origin.subtract(this._originTop).normalize();
  78448. }
  78449. this._tickCallback = this._tick.bind(this);
  78450. }
  78451. /**
  78452. * Returns the data related to the updraft event (cylinder).
  78453. * @returns {PhysicsUpdraftEventData}
  78454. */
  78455. PhysicsUpdraftEvent.prototype.getData = function () {
  78456. this._dataFetched = true;
  78457. return {
  78458. cylinder: this._cylinder,
  78459. };
  78460. };
  78461. /**
  78462. * Enables the updraft.
  78463. */
  78464. PhysicsUpdraftEvent.prototype.enable = function () {
  78465. this._tickCallback.call(this);
  78466. this._scene.registerBeforeRender(this._tickCallback);
  78467. };
  78468. /**
  78469. * Disables the cortex.
  78470. */
  78471. PhysicsUpdraftEvent.prototype.disable = function () {
  78472. this._scene.unregisterBeforeRender(this._tickCallback);
  78473. };
  78474. /**
  78475. * Disposes the sphere.
  78476. * @param {bolean} force
  78477. */
  78478. PhysicsUpdraftEvent.prototype.dispose = function (force) {
  78479. var _this = this;
  78480. if (force === void 0) { force = true; }
  78481. if (force) {
  78482. this._cylinder.dispose();
  78483. }
  78484. else {
  78485. setTimeout(function () {
  78486. if (!_this._dataFetched) {
  78487. _this._cylinder.dispose();
  78488. }
  78489. }, 0);
  78490. }
  78491. };
  78492. PhysicsUpdraftEvent.prototype.getImpostorForceAndContactPoint = function (impostor) {
  78493. if (impostor.mass === 0) {
  78494. return null;
  78495. }
  78496. if (!this._intersectsWithCylinder(impostor)) {
  78497. return null;
  78498. }
  78499. var impostorObjectCenter = impostor.getObjectCenter();
  78500. if (this._updraftMode === PhysicsUpdraftMode.Perpendicular) {
  78501. var direction = this._originDirection;
  78502. }
  78503. else {
  78504. var direction = impostorObjectCenter.subtract(this._originTop);
  78505. }
  78506. var multiplier = this._strength * -1;
  78507. var force = direction.multiplyByFloats(multiplier, multiplier, multiplier);
  78508. return { force: force, contactPoint: impostorObjectCenter };
  78509. };
  78510. PhysicsUpdraftEvent.prototype._tick = function () {
  78511. var _this = this;
  78512. this._physicsEngine.getImpostors().forEach(function (impostor) {
  78513. var impostorForceAndContactPoint = _this.getImpostorForceAndContactPoint(impostor);
  78514. if (!impostorForceAndContactPoint) {
  78515. return;
  78516. }
  78517. impostor.applyForce(impostorForceAndContactPoint.force, impostorForceAndContactPoint.contactPoint);
  78518. });
  78519. };
  78520. /*** Helpers ***/
  78521. PhysicsUpdraftEvent.prototype._prepareCylinder = function () {
  78522. if (!this._cylinder) {
  78523. this._cylinder = BABYLON.MeshBuilder.CreateCylinder("updraftEventCylinder", {
  78524. height: this._height,
  78525. diameter: this._radius * 2,
  78526. }, this._scene);
  78527. this._cylinder.isVisible = false;
  78528. }
  78529. };
  78530. PhysicsUpdraftEvent.prototype._intersectsWithCylinder = function (impostor) {
  78531. var impostorObject = impostor.object;
  78532. this._prepareCylinder();
  78533. this._cylinder.position = this._cylinderPosition;
  78534. return this._cylinder.intersectsMesh(impostorObject, true);
  78535. };
  78536. return PhysicsUpdraftEvent;
  78537. }());
  78538. BABYLON.PhysicsUpdraftEvent = PhysicsUpdraftEvent;
  78539. /***** Vortex *****/
  78540. var PhysicsVortexEvent = /** @class */ (function () {
  78541. function PhysicsVortexEvent(_scene, _origin, _radius, _strength, _height) {
  78542. this._scene = _scene;
  78543. this._origin = _origin;
  78544. this._radius = _radius;
  78545. this._strength = _strength;
  78546. this._height = _height;
  78547. this._originTop = BABYLON.Vector3.Zero(); // the most upper part of the cylinder
  78548. this._centripetalForceThreshold = 0.7; // at which distance, relative to the radius the centripetal forces should kick in
  78549. this._updraftMultiplier = 0.02;
  78550. this._cylinderPosition = BABYLON.Vector3.Zero(); // to keep the cylinders position, because normally the origin is in the center and not on the bottom
  78551. this._dataFetched = false; // check if the has been fetched the data. If not, do cleanup
  78552. this._physicsEngine = this._scene.getPhysicsEngine();
  78553. this._origin.addToRef(new BABYLON.Vector3(0, this._height / 2, 0), this._cylinderPosition);
  78554. this._origin.addToRef(new BABYLON.Vector3(0, this._height, 0), this._originTop);
  78555. this._tickCallback = this._tick.bind(this);
  78556. }
  78557. /**
  78558. * Returns the data related to the vortex event (cylinder).
  78559. * @returns {PhysicsVortexEventData}
  78560. */
  78561. PhysicsVortexEvent.prototype.getData = function () {
  78562. this._dataFetched = true;
  78563. return {
  78564. cylinder: this._cylinder,
  78565. };
  78566. };
  78567. /**
  78568. * Enables the vortex.
  78569. */
  78570. PhysicsVortexEvent.prototype.enable = function () {
  78571. this._tickCallback.call(this);
  78572. this._scene.registerBeforeRender(this._tickCallback);
  78573. };
  78574. /**
  78575. * Disables the cortex.
  78576. */
  78577. PhysicsVortexEvent.prototype.disable = function () {
  78578. this._scene.unregisterBeforeRender(this._tickCallback);
  78579. };
  78580. /**
  78581. * Disposes the sphere.
  78582. * @param {bolean} force
  78583. */
  78584. PhysicsVortexEvent.prototype.dispose = function (force) {
  78585. var _this = this;
  78586. if (force === void 0) { force = true; }
  78587. if (force) {
  78588. this._cylinder.dispose();
  78589. }
  78590. else {
  78591. setTimeout(function () {
  78592. if (!_this._dataFetched) {
  78593. _this._cylinder.dispose();
  78594. }
  78595. }, 0);
  78596. }
  78597. };
  78598. PhysicsVortexEvent.prototype.getImpostorForceAndContactPoint = function (impostor) {
  78599. if (impostor.mass === 0) {
  78600. return null;
  78601. }
  78602. if (!this._intersectsWithCylinder(impostor)) {
  78603. return null;
  78604. }
  78605. if (impostor.object.getClassName() !== 'Mesh' && impostor.object.getClassName() !== 'InstancedMesh') {
  78606. return null;
  78607. }
  78608. var impostorObjectCenter = impostor.getObjectCenter();
  78609. 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)
  78610. var originToImpostorDirection = impostorObjectCenter.subtract(originOnPlane);
  78611. var ray = new BABYLON.Ray(originOnPlane, originToImpostorDirection, this._radius);
  78612. var hit = ray.intersectsMesh(impostor.object);
  78613. var contactPoint = hit.pickedPoint;
  78614. if (!contactPoint) {
  78615. return null;
  78616. }
  78617. var absoluteDistanceFromOrigin = hit.distance / this._radius;
  78618. var perpendicularDirection = BABYLON.Vector3.Cross(originOnPlane, impostorObjectCenter).normalize();
  78619. var directionToOrigin = contactPoint.normalize();
  78620. if (absoluteDistanceFromOrigin > this._centripetalForceThreshold) {
  78621. directionToOrigin = directionToOrigin.negate();
  78622. }
  78623. // TODO: find a more physically based solution
  78624. if (absoluteDistanceFromOrigin > this._centripetalForceThreshold) {
  78625. var forceX = directionToOrigin.x * this._strength / 8;
  78626. var forceY = directionToOrigin.y * this._updraftMultiplier;
  78627. var forceZ = directionToOrigin.z * this._strength / 8;
  78628. }
  78629. else {
  78630. var forceX = (perpendicularDirection.x + directionToOrigin.x) / 2;
  78631. var forceY = this._originTop.y * this._updraftMultiplier;
  78632. var forceZ = (perpendicularDirection.z + directionToOrigin.z) / 2;
  78633. }
  78634. var force = new BABYLON.Vector3(forceX, forceY, forceZ);
  78635. force = force.multiplyByFloats(this._strength, this._strength, this._strength);
  78636. return { force: force, contactPoint: impostorObjectCenter };
  78637. };
  78638. PhysicsVortexEvent.prototype._tick = function () {
  78639. var _this = this;
  78640. this._physicsEngine.getImpostors().forEach(function (impostor) {
  78641. var impostorForceAndContactPoint = _this.getImpostorForceAndContactPoint(impostor);
  78642. if (!impostorForceAndContactPoint) {
  78643. return;
  78644. }
  78645. impostor.applyForce(impostorForceAndContactPoint.force, impostorForceAndContactPoint.contactPoint);
  78646. });
  78647. };
  78648. /*** Helpers ***/
  78649. PhysicsVortexEvent.prototype._prepareCylinder = function () {
  78650. if (!this._cylinder) {
  78651. this._cylinder = BABYLON.MeshBuilder.CreateCylinder("vortexEventCylinder", {
  78652. height: this._height,
  78653. diameter: this._radius * 2,
  78654. }, this._scene);
  78655. this._cylinder.isVisible = false;
  78656. }
  78657. };
  78658. PhysicsVortexEvent.prototype._intersectsWithCylinder = function (impostor) {
  78659. var impostorObject = impostor.object;
  78660. this._prepareCylinder();
  78661. this._cylinder.position = this._cylinderPosition;
  78662. return this._cylinder.intersectsMesh(impostorObject, true);
  78663. };
  78664. return PhysicsVortexEvent;
  78665. }());
  78666. BABYLON.PhysicsVortexEvent = PhysicsVortexEvent;
  78667. /***** Enums *****/
  78668. /**
  78669. * The strenght of the force in correspondence to the distance of the affected object
  78670. */
  78671. var PhysicsRadialImpulseFalloff;
  78672. (function (PhysicsRadialImpulseFalloff) {
  78673. PhysicsRadialImpulseFalloff[PhysicsRadialImpulseFalloff["Constant"] = 0] = "Constant";
  78674. PhysicsRadialImpulseFalloff[PhysicsRadialImpulseFalloff["Linear"] = 1] = "Linear"; // impulse gets weaker if it's further from the origin
  78675. })(PhysicsRadialImpulseFalloff = BABYLON.PhysicsRadialImpulseFalloff || (BABYLON.PhysicsRadialImpulseFalloff = {}));
  78676. /**
  78677. * The strenght of the force in correspondence to the distance of the affected object
  78678. */
  78679. var PhysicsUpdraftMode;
  78680. (function (PhysicsUpdraftMode) {
  78681. PhysicsUpdraftMode[PhysicsUpdraftMode["Center"] = 0] = "Center";
  78682. PhysicsUpdraftMode[PhysicsUpdraftMode["Perpendicular"] = 1] = "Perpendicular"; // once a impostor is inside the cylinder, it will shoot out perpendicular from the ground of the cylinder
  78683. })(PhysicsUpdraftMode = BABYLON.PhysicsUpdraftMode || (BABYLON.PhysicsUpdraftMode = {}));
  78684. })(BABYLON || (BABYLON = {}));
  78685. //# sourceMappingURL=babylon.physicsHelper.js.map
  78686. "use strict";
  78687. var BABYLON;
  78688. (function (BABYLON) {
  78689. var CannonJSPlugin = /** @class */ (function () {
  78690. function CannonJSPlugin(_useDeltaForWorldStep, iterations) {
  78691. if (_useDeltaForWorldStep === void 0) { _useDeltaForWorldStep = true; }
  78692. if (iterations === void 0) { iterations = 10; }
  78693. this._useDeltaForWorldStep = _useDeltaForWorldStep;
  78694. this.name = "CannonJSPlugin";
  78695. this._physicsMaterials = new Array();
  78696. this._fixedTimeStep = 1 / 60;
  78697. //See https://github.com/schteppe/CANNON.js/blob/gh-pages/demos/collisionFilter.html
  78698. this.BJSCANNON = CANNON;
  78699. this._minus90X = new BABYLON.Quaternion(-0.7071067811865475, 0, 0, 0.7071067811865475);
  78700. this._plus90X = new BABYLON.Quaternion(0.7071067811865475, 0, 0, 0.7071067811865475);
  78701. this._tmpPosition = BABYLON.Vector3.Zero();
  78702. this._tmpDeltaPosition = BABYLON.Vector3.Zero();
  78703. this._tmpUnityRotation = new BABYLON.Quaternion();
  78704. if (!this.isSupported()) {
  78705. BABYLON.Tools.Error("CannonJS is not available. Please make sure you included the js file.");
  78706. return;
  78707. }
  78708. this._extendNamespace();
  78709. this.world = new this.BJSCANNON.World();
  78710. this.world.broadphase = new this.BJSCANNON.NaiveBroadphase();
  78711. this.world.solver.iterations = iterations;
  78712. }
  78713. CannonJSPlugin.prototype.setGravity = function (gravity) {
  78714. this.world.gravity.copy(gravity);
  78715. };
  78716. CannonJSPlugin.prototype.setTimeStep = function (timeStep) {
  78717. this._fixedTimeStep = timeStep;
  78718. };
  78719. CannonJSPlugin.prototype.getTimeStep = function () {
  78720. return this._fixedTimeStep;
  78721. };
  78722. CannonJSPlugin.prototype.executeStep = function (delta, impostors) {
  78723. this.world.step(this._fixedTimeStep, this._useDeltaForWorldStep ? delta : 0, 3);
  78724. };
  78725. CannonJSPlugin.prototype.applyImpulse = function (impostor, force, contactPoint) {
  78726. var worldPoint = new this.BJSCANNON.Vec3(contactPoint.x, contactPoint.y, contactPoint.z);
  78727. var impulse = new this.BJSCANNON.Vec3(force.x, force.y, force.z);
  78728. impostor.physicsBody.applyImpulse(impulse, worldPoint);
  78729. };
  78730. CannonJSPlugin.prototype.applyForce = function (impostor, force, contactPoint) {
  78731. var worldPoint = new this.BJSCANNON.Vec3(contactPoint.x, contactPoint.y, contactPoint.z);
  78732. var impulse = new this.BJSCANNON.Vec3(force.x, force.y, force.z);
  78733. impostor.physicsBody.applyForce(impulse, worldPoint);
  78734. };
  78735. CannonJSPlugin.prototype.generatePhysicsBody = function (impostor) {
  78736. //parent-child relationship. Does this impostor has a parent impostor?
  78737. if (impostor.parent) {
  78738. if (impostor.physicsBody) {
  78739. this.removePhysicsBody(impostor);
  78740. //TODO is that needed?
  78741. impostor.forceUpdate();
  78742. }
  78743. return;
  78744. }
  78745. //should a new body be created for this impostor?
  78746. if (impostor.isBodyInitRequired()) {
  78747. var shape = this._createShape(impostor);
  78748. //unregister events, if body is being changed
  78749. var oldBody = impostor.physicsBody;
  78750. if (oldBody) {
  78751. this.removePhysicsBody(impostor);
  78752. }
  78753. //create the body and material
  78754. var material = this._addMaterial("mat-" + impostor.uniqueId, impostor.getParam("friction"), impostor.getParam("restitution"));
  78755. var bodyCreationObject = {
  78756. mass: impostor.getParam("mass"),
  78757. material: material
  78758. };
  78759. // A simple extend, in case native options were used.
  78760. var nativeOptions = impostor.getParam("nativeOptions");
  78761. for (var key in nativeOptions) {
  78762. if (nativeOptions.hasOwnProperty(key)) {
  78763. bodyCreationObject[key] = nativeOptions[key];
  78764. }
  78765. }
  78766. impostor.physicsBody = new this.BJSCANNON.Body(bodyCreationObject);
  78767. impostor.physicsBody.addEventListener("collide", impostor.onCollide);
  78768. this.world.addEventListener("preStep", impostor.beforeStep);
  78769. this.world.addEventListener("postStep", impostor.afterStep);
  78770. impostor.physicsBody.addShape(shape);
  78771. this.world.add(impostor.physicsBody);
  78772. //try to keep the body moving in the right direction by taking old properties.
  78773. //Should be tested!
  78774. if (oldBody) {
  78775. ['force', 'torque', 'velocity', 'angularVelocity'].forEach(function (param) {
  78776. impostor.physicsBody[param].copy(oldBody[param]);
  78777. });
  78778. }
  78779. this._processChildMeshes(impostor);
  78780. }
  78781. //now update the body's transformation
  78782. this._updatePhysicsBodyTransformation(impostor);
  78783. };
  78784. CannonJSPlugin.prototype._processChildMeshes = function (mainImpostor) {
  78785. var _this = this;
  78786. var meshChildren = mainImpostor.object.getChildMeshes ? mainImpostor.object.getChildMeshes(true) : [];
  78787. var currentRotation = mainImpostor.object.rotationQuaternion;
  78788. if (meshChildren.length) {
  78789. var processMesh = function (localPosition, mesh) {
  78790. if (!currentRotation || !mesh.rotationQuaternion) {
  78791. return;
  78792. }
  78793. var childImpostor = mesh.getPhysicsImpostor();
  78794. if (childImpostor) {
  78795. var parent = childImpostor.parent;
  78796. if (parent !== mainImpostor) {
  78797. var pPosition = mesh.getAbsolutePosition().subtract(mainImpostor.object.getAbsolutePosition());
  78798. var localRotation = mesh.rotationQuaternion.multiply(BABYLON.Quaternion.Inverse(currentRotation));
  78799. if (childImpostor.physicsBody) {
  78800. _this.removePhysicsBody(childImpostor);
  78801. childImpostor.physicsBody = null;
  78802. }
  78803. childImpostor.parent = mainImpostor;
  78804. childImpostor.resetUpdateFlags();
  78805. 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));
  78806. //Add the mass of the children.
  78807. mainImpostor.physicsBody.mass += childImpostor.getParam("mass");
  78808. }
  78809. }
  78810. currentRotation.multiplyInPlace(mesh.rotationQuaternion);
  78811. mesh.getChildMeshes(true).filter(function (m) { return !!m.physicsImpostor; }).forEach(processMesh.bind(_this, mesh.getAbsolutePosition()));
  78812. };
  78813. meshChildren.filter(function (m) { return !!m.physicsImpostor; }).forEach(processMesh.bind(this, mainImpostor.object.getAbsolutePosition()));
  78814. }
  78815. };
  78816. CannonJSPlugin.prototype.removePhysicsBody = function (impostor) {
  78817. impostor.physicsBody.removeEventListener("collide", impostor.onCollide);
  78818. this.world.removeEventListener("preStep", impostor.beforeStep);
  78819. this.world.removeEventListener("postStep", impostor.afterStep);
  78820. this.world.remove(impostor.physicsBody);
  78821. };
  78822. CannonJSPlugin.prototype.generateJoint = function (impostorJoint) {
  78823. var mainBody = impostorJoint.mainImpostor.physicsBody;
  78824. var connectedBody = impostorJoint.connectedImpostor.physicsBody;
  78825. if (!mainBody || !connectedBody) {
  78826. return;
  78827. }
  78828. var constraint;
  78829. var jointData = impostorJoint.joint.jointData;
  78830. //TODO - https://github.com/schteppe/this.BJSCANNON.js/blob/gh-pages/demos/collisionFilter.html
  78831. var constraintData = {
  78832. pivotA: jointData.mainPivot ? new this.BJSCANNON.Vec3().copy(jointData.mainPivot) : null,
  78833. pivotB: jointData.connectedPivot ? new this.BJSCANNON.Vec3().copy(jointData.connectedPivot) : null,
  78834. axisA: jointData.mainAxis ? new this.BJSCANNON.Vec3().copy(jointData.mainAxis) : null,
  78835. axisB: jointData.connectedAxis ? new this.BJSCANNON.Vec3().copy(jointData.connectedAxis) : null,
  78836. maxForce: jointData.nativeParams.maxForce,
  78837. collideConnected: !!jointData.collision
  78838. };
  78839. switch (impostorJoint.joint.type) {
  78840. case BABYLON.PhysicsJoint.HingeJoint:
  78841. case BABYLON.PhysicsJoint.Hinge2Joint:
  78842. constraint = new this.BJSCANNON.HingeConstraint(mainBody, connectedBody, constraintData);
  78843. break;
  78844. case BABYLON.PhysicsJoint.DistanceJoint:
  78845. constraint = new this.BJSCANNON.DistanceConstraint(mainBody, connectedBody, jointData.maxDistance || 2);
  78846. break;
  78847. case BABYLON.PhysicsJoint.SpringJoint:
  78848. var springData = jointData;
  78849. constraint = new this.BJSCANNON.Spring(mainBody, connectedBody, {
  78850. restLength: springData.length,
  78851. stiffness: springData.stiffness,
  78852. damping: springData.damping,
  78853. localAnchorA: constraintData.pivotA,
  78854. localAnchorB: constraintData.pivotB
  78855. });
  78856. break;
  78857. case BABYLON.PhysicsJoint.LockJoint:
  78858. constraint = new this.BJSCANNON.LockConstraint(mainBody, connectedBody, constraintData);
  78859. break;
  78860. case BABYLON.PhysicsJoint.PointToPointJoint:
  78861. case BABYLON.PhysicsJoint.BallAndSocketJoint:
  78862. default:
  78863. constraint = new this.BJSCANNON.PointToPointConstraint(mainBody, constraintData.pivotA, connectedBody, constraintData.pivotA, constraintData.maxForce);
  78864. break;
  78865. }
  78866. //set the collideConnected flag after the creation, since DistanceJoint ignores it.
  78867. constraint.collideConnected = !!jointData.collision;
  78868. impostorJoint.joint.physicsJoint = constraint;
  78869. //don't add spring as constraint, as it is not one.
  78870. if (impostorJoint.joint.type !== BABYLON.PhysicsJoint.SpringJoint) {
  78871. this.world.addConstraint(constraint);
  78872. }
  78873. else {
  78874. impostorJoint.mainImpostor.registerAfterPhysicsStep(function () {
  78875. constraint.applyForce();
  78876. });
  78877. }
  78878. };
  78879. CannonJSPlugin.prototype.removeJoint = function (impostorJoint) {
  78880. this.world.removeConstraint(impostorJoint.joint.physicsJoint);
  78881. };
  78882. CannonJSPlugin.prototype._addMaterial = function (name, friction, restitution) {
  78883. var index;
  78884. var mat;
  78885. for (index = 0; index < this._physicsMaterials.length; index++) {
  78886. mat = this._physicsMaterials[index];
  78887. if (mat.friction === friction && mat.restitution === restitution) {
  78888. return mat;
  78889. }
  78890. }
  78891. var currentMat = new this.BJSCANNON.Material(name);
  78892. currentMat.friction = friction;
  78893. currentMat.restitution = restitution;
  78894. this._physicsMaterials.push(currentMat);
  78895. return currentMat;
  78896. };
  78897. CannonJSPlugin.prototype._checkWithEpsilon = function (value) {
  78898. return value < BABYLON.PhysicsEngine.Epsilon ? BABYLON.PhysicsEngine.Epsilon : value;
  78899. };
  78900. CannonJSPlugin.prototype._createShape = function (impostor) {
  78901. var object = impostor.object;
  78902. var returnValue;
  78903. var extendSize = impostor.getObjectExtendSize();
  78904. switch (impostor.type) {
  78905. case BABYLON.PhysicsImpostor.SphereImpostor:
  78906. var radiusX = extendSize.x;
  78907. var radiusY = extendSize.y;
  78908. var radiusZ = extendSize.z;
  78909. returnValue = new this.BJSCANNON.Sphere(Math.max(this._checkWithEpsilon(radiusX), this._checkWithEpsilon(radiusY), this._checkWithEpsilon(radiusZ)) / 2);
  78910. break;
  78911. //TMP also for cylinder - TODO Cannon supports cylinder natively.
  78912. case BABYLON.PhysicsImpostor.CylinderImpostor:
  78913. returnValue = new this.BJSCANNON.Cylinder(this._checkWithEpsilon(extendSize.x) / 2, this._checkWithEpsilon(extendSize.x) / 2, this._checkWithEpsilon(extendSize.y), 16);
  78914. break;
  78915. case BABYLON.PhysicsImpostor.BoxImpostor:
  78916. var box = extendSize.scale(0.5);
  78917. returnValue = new this.BJSCANNON.Box(new this.BJSCANNON.Vec3(this._checkWithEpsilon(box.x), this._checkWithEpsilon(box.y), this._checkWithEpsilon(box.z)));
  78918. break;
  78919. case BABYLON.PhysicsImpostor.PlaneImpostor:
  78920. BABYLON.Tools.Warn("Attention, PlaneImposter might not behave as you expect. Consider using BoxImposter instead");
  78921. returnValue = new this.BJSCANNON.Plane();
  78922. break;
  78923. case BABYLON.PhysicsImpostor.MeshImpostor:
  78924. // should transform the vertex data to world coordinates!!
  78925. var rawVerts = object.getVerticesData ? object.getVerticesData(BABYLON.VertexBuffer.PositionKind) : [];
  78926. var rawFaces = object.getIndices ? object.getIndices() : [];
  78927. if (!rawVerts)
  78928. return;
  78929. // get only scale! so the object could transform correctly.
  78930. var oldPosition = object.position.clone();
  78931. var oldRotation = object.rotation && object.rotation.clone();
  78932. var oldQuaternion = object.rotationQuaternion && object.rotationQuaternion.clone();
  78933. object.position.copyFromFloats(0, 0, 0);
  78934. object.rotation && object.rotation.copyFromFloats(0, 0, 0);
  78935. object.rotationQuaternion && object.rotationQuaternion.copyFrom(impostor.getParentsRotation());
  78936. object.rotationQuaternion && object.parent && object.rotationQuaternion.conjugateInPlace();
  78937. var transform = object.computeWorldMatrix(true);
  78938. // convert rawVerts to object space
  78939. var temp = new Array();
  78940. var index;
  78941. for (index = 0; index < rawVerts.length; index += 3) {
  78942. BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.FromArray(rawVerts, index), transform).toArray(temp, index);
  78943. }
  78944. BABYLON.Tools.Warn("MeshImpostor only collides against spheres.");
  78945. returnValue = new this.BJSCANNON.Trimesh(temp, rawFaces);
  78946. //now set back the transformation!
  78947. object.position.copyFrom(oldPosition);
  78948. oldRotation && object.rotation && object.rotation.copyFrom(oldRotation);
  78949. oldQuaternion && object.rotationQuaternion && object.rotationQuaternion.copyFrom(oldQuaternion);
  78950. break;
  78951. case BABYLON.PhysicsImpostor.HeightmapImpostor:
  78952. var oldPosition2 = object.position.clone();
  78953. var oldRotation2 = object.rotation && object.rotation.clone();
  78954. var oldQuaternion2 = object.rotationQuaternion && object.rotationQuaternion.clone();
  78955. object.position.copyFromFloats(0, 0, 0);
  78956. object.rotation && object.rotation.copyFromFloats(0, 0, 0);
  78957. object.rotationQuaternion && object.rotationQuaternion.copyFrom(impostor.getParentsRotation());
  78958. object.rotationQuaternion && object.parent && object.rotationQuaternion.conjugateInPlace();
  78959. object.rotationQuaternion && object.rotationQuaternion.multiplyInPlace(this._minus90X);
  78960. returnValue = this._createHeightmap(object);
  78961. object.position.copyFrom(oldPosition2);
  78962. oldRotation2 && object.rotation && object.rotation.copyFrom(oldRotation2);
  78963. oldQuaternion2 && object.rotationQuaternion && object.rotationQuaternion.copyFrom(oldQuaternion2);
  78964. object.computeWorldMatrix(true);
  78965. break;
  78966. case BABYLON.PhysicsImpostor.ParticleImpostor:
  78967. returnValue = new this.BJSCANNON.Particle();
  78968. break;
  78969. }
  78970. return returnValue;
  78971. };
  78972. CannonJSPlugin.prototype._createHeightmap = function (object, pointDepth) {
  78973. var pos = (object.getVerticesData(BABYLON.VertexBuffer.PositionKind));
  78974. var transform = object.computeWorldMatrix(true);
  78975. // convert rawVerts to object space
  78976. var temp = new Array();
  78977. var index;
  78978. for (index = 0; index < pos.length; index += 3) {
  78979. BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.FromArray(pos, index), transform).toArray(temp, index);
  78980. }
  78981. pos = temp;
  78982. var matrix = new Array();
  78983. //For now pointDepth will not be used and will be automatically calculated.
  78984. //Future reference - try and find the best place to add a reference to the pointDepth variable.
  78985. var arraySize = pointDepth || ~~(Math.sqrt(pos.length / 3) - 1);
  78986. var boundingInfo = object.getBoundingInfo();
  78987. var dim = Math.min(boundingInfo.boundingBox.extendSizeWorld.x, boundingInfo.boundingBox.extendSizeWorld.y);
  78988. var minY = boundingInfo.boundingBox.extendSizeWorld.z;
  78989. var elementSize = dim * 2 / arraySize;
  78990. for (var i = 0; i < pos.length; i = i + 3) {
  78991. var x = Math.round((pos[i + 0]) / elementSize + arraySize / 2);
  78992. var z = Math.round(((pos[i + 1]) / elementSize - arraySize / 2) * -1);
  78993. var y = -pos[i + 2] + minY;
  78994. if (!matrix[x]) {
  78995. matrix[x] = [];
  78996. }
  78997. if (!matrix[x][z]) {
  78998. matrix[x][z] = y;
  78999. }
  79000. matrix[x][z] = Math.max(y, matrix[x][z]);
  79001. }
  79002. for (var x = 0; x <= arraySize; ++x) {
  79003. if (!matrix[x]) {
  79004. var loc = 1;
  79005. while (!matrix[(x + loc) % arraySize]) {
  79006. loc++;
  79007. }
  79008. matrix[x] = matrix[(x + loc) % arraySize].slice();
  79009. //console.log("missing x", x);
  79010. }
  79011. for (var z = 0; z <= arraySize; ++z) {
  79012. if (!matrix[x][z]) {
  79013. var loc = 1;
  79014. var newValue;
  79015. while (newValue === undefined) {
  79016. newValue = matrix[x][(z + loc++) % arraySize];
  79017. }
  79018. matrix[x][z] = newValue;
  79019. }
  79020. }
  79021. }
  79022. var shape = new this.BJSCANNON.Heightfield(matrix, {
  79023. elementSize: elementSize
  79024. });
  79025. //For future reference, needed for body transformation
  79026. shape.minY = minY;
  79027. return shape;
  79028. };
  79029. CannonJSPlugin.prototype._updatePhysicsBodyTransformation = function (impostor) {
  79030. var object = impostor.object;
  79031. //make sure it is updated...
  79032. object.computeWorldMatrix && object.computeWorldMatrix(true);
  79033. // The delta between the mesh position and the mesh bounding box center
  79034. var bInfo = object.getBoundingInfo();
  79035. if (!bInfo)
  79036. return;
  79037. var center = impostor.getObjectCenter();
  79038. //m.getAbsolutePosition().subtract(m.getBoundingInfo().boundingBox.centerWorld)
  79039. this._tmpDeltaPosition.copyFrom(object.getAbsolutePivotPoint().subtract(center));
  79040. this._tmpDeltaPosition.divideInPlace(impostor.object.scaling);
  79041. this._tmpPosition.copyFrom(center);
  79042. var quaternion = object.rotationQuaternion;
  79043. if (!quaternion) {
  79044. return;
  79045. }
  79046. //is shape is a plane or a heightmap, it must be rotated 90 degs in the X axis.
  79047. if (impostor.type === BABYLON.PhysicsImpostor.PlaneImpostor || impostor.type === BABYLON.PhysicsImpostor.HeightmapImpostor || impostor.type === BABYLON.PhysicsImpostor.CylinderImpostor) {
  79048. //-90 DEG in X, precalculated
  79049. quaternion = quaternion.multiply(this._minus90X);
  79050. //Invert! (Precalculated, 90 deg in X)
  79051. //No need to clone. this will never change.
  79052. impostor.setDeltaRotation(this._plus90X);
  79053. }
  79054. //If it is a heightfield, if should be centered.
  79055. if (impostor.type === BABYLON.PhysicsImpostor.HeightmapImpostor) {
  79056. var mesh = object;
  79057. var boundingInfo = mesh.getBoundingInfo();
  79058. //calculate the correct body position:
  79059. var rotationQuaternion = mesh.rotationQuaternion;
  79060. mesh.rotationQuaternion = this._tmpUnityRotation;
  79061. mesh.computeWorldMatrix(true);
  79062. //get original center with no rotation
  79063. var c = center.clone();
  79064. var oldPivot = mesh.getPivotMatrix() || BABYLON.Matrix.Translation(0, 0, 0);
  79065. //calculate the new center using a pivot (since this.BJSCANNON.js doesn't center height maps)
  79066. var p = BABYLON.Matrix.Translation(boundingInfo.boundingBox.extendSizeWorld.x, 0, -boundingInfo.boundingBox.extendSizeWorld.z);
  79067. mesh.setPreTransformMatrix(p);
  79068. mesh.computeWorldMatrix(true);
  79069. //calculate the translation
  79070. var translation = boundingInfo.boundingBox.centerWorld.subtract(center).subtract(mesh.position).negate();
  79071. this._tmpPosition.copyFromFloats(translation.x, translation.y - boundingInfo.boundingBox.extendSizeWorld.y, translation.z);
  79072. //add it inverted to the delta
  79073. this._tmpDeltaPosition.copyFrom(boundingInfo.boundingBox.centerWorld.subtract(c));
  79074. this._tmpDeltaPosition.y += boundingInfo.boundingBox.extendSizeWorld.y;
  79075. //rotation is back
  79076. mesh.rotationQuaternion = rotationQuaternion;
  79077. mesh.setPreTransformMatrix(oldPivot);
  79078. mesh.computeWorldMatrix(true);
  79079. }
  79080. else if (impostor.type === BABYLON.PhysicsImpostor.MeshImpostor) {
  79081. this._tmpDeltaPosition.copyFromFloats(0, 0, 0);
  79082. //this._tmpPosition.copyFrom(object.position);
  79083. }
  79084. impostor.setDeltaPosition(this._tmpDeltaPosition);
  79085. //Now update the impostor object
  79086. impostor.physicsBody.position.copy(this._tmpPosition);
  79087. impostor.physicsBody.quaternion.copy(quaternion);
  79088. };
  79089. CannonJSPlugin.prototype.setTransformationFromPhysicsBody = function (impostor) {
  79090. impostor.object.position.copyFrom(impostor.physicsBody.position);
  79091. if (impostor.object.rotationQuaternion) {
  79092. impostor.object.rotationQuaternion.copyFrom(impostor.physicsBody.quaternion);
  79093. }
  79094. };
  79095. CannonJSPlugin.prototype.setPhysicsBodyTransformation = function (impostor, newPosition, newRotation) {
  79096. impostor.physicsBody.position.copy(newPosition);
  79097. impostor.physicsBody.quaternion.copy(newRotation);
  79098. };
  79099. CannonJSPlugin.prototype.isSupported = function () {
  79100. return this.BJSCANNON !== undefined;
  79101. };
  79102. CannonJSPlugin.prototype.setLinearVelocity = function (impostor, velocity) {
  79103. impostor.physicsBody.velocity.copy(velocity);
  79104. };
  79105. CannonJSPlugin.prototype.setAngularVelocity = function (impostor, velocity) {
  79106. impostor.physicsBody.angularVelocity.copy(velocity);
  79107. };
  79108. CannonJSPlugin.prototype.getLinearVelocity = function (impostor) {
  79109. var v = impostor.physicsBody.velocity;
  79110. if (!v) {
  79111. return null;
  79112. }
  79113. return new BABYLON.Vector3(v.x, v.y, v.z);
  79114. };
  79115. CannonJSPlugin.prototype.getAngularVelocity = function (impostor) {
  79116. var v = impostor.physicsBody.angularVelocity;
  79117. if (!v) {
  79118. return null;
  79119. }
  79120. return new BABYLON.Vector3(v.x, v.y, v.z);
  79121. };
  79122. CannonJSPlugin.prototype.setBodyMass = function (impostor, mass) {
  79123. impostor.physicsBody.mass = mass;
  79124. impostor.physicsBody.updateMassProperties();
  79125. };
  79126. CannonJSPlugin.prototype.getBodyMass = function (impostor) {
  79127. return impostor.physicsBody.mass;
  79128. };
  79129. CannonJSPlugin.prototype.getBodyFriction = function (impostor) {
  79130. return impostor.physicsBody.material.friction;
  79131. };
  79132. CannonJSPlugin.prototype.setBodyFriction = function (impostor, friction) {
  79133. impostor.physicsBody.material.friction = friction;
  79134. };
  79135. CannonJSPlugin.prototype.getBodyRestitution = function (impostor) {
  79136. return impostor.physicsBody.material.restitution;
  79137. };
  79138. CannonJSPlugin.prototype.setBodyRestitution = function (impostor, restitution) {
  79139. impostor.physicsBody.material.restitution = restitution;
  79140. };
  79141. CannonJSPlugin.prototype.sleepBody = function (impostor) {
  79142. impostor.physicsBody.sleep();
  79143. };
  79144. CannonJSPlugin.prototype.wakeUpBody = function (impostor) {
  79145. impostor.physicsBody.wakeUp();
  79146. };
  79147. CannonJSPlugin.prototype.updateDistanceJoint = function (joint, maxDistance, minDistance) {
  79148. joint.physicsJoint.distance = maxDistance;
  79149. };
  79150. // private enableMotor(joint: IMotorEnabledJoint, motorIndex?: number) {
  79151. // if (!motorIndex) {
  79152. // joint.physicsJoint.enableMotor();
  79153. // }
  79154. // }
  79155. // private disableMotor(joint: IMotorEnabledJoint, motorIndex?: number) {
  79156. // if (!motorIndex) {
  79157. // joint.physicsJoint.disableMotor();
  79158. // }
  79159. // }
  79160. CannonJSPlugin.prototype.setMotor = function (joint, speed, maxForce, motorIndex) {
  79161. if (!motorIndex) {
  79162. joint.physicsJoint.enableMotor();
  79163. joint.physicsJoint.setMotorSpeed(speed);
  79164. if (maxForce) {
  79165. this.setLimit(joint, maxForce);
  79166. }
  79167. }
  79168. };
  79169. CannonJSPlugin.prototype.setLimit = function (joint, upperLimit, lowerLimit) {
  79170. joint.physicsJoint.motorEquation.maxForce = upperLimit;
  79171. joint.physicsJoint.motorEquation.minForce = lowerLimit === void 0 ? -upperLimit : lowerLimit;
  79172. };
  79173. CannonJSPlugin.prototype.syncMeshWithImpostor = function (mesh, impostor) {
  79174. var body = impostor.physicsBody;
  79175. mesh.position.x = body.position.x;
  79176. mesh.position.y = body.position.y;
  79177. mesh.position.z = body.position.z;
  79178. if (mesh.rotationQuaternion) {
  79179. mesh.rotationQuaternion.x = body.quaternion.x;
  79180. mesh.rotationQuaternion.y = body.quaternion.y;
  79181. mesh.rotationQuaternion.z = body.quaternion.z;
  79182. mesh.rotationQuaternion.w = body.quaternion.w;
  79183. }
  79184. };
  79185. CannonJSPlugin.prototype.getRadius = function (impostor) {
  79186. var shape = impostor.physicsBody.shapes[0];
  79187. return shape.boundingSphereRadius;
  79188. };
  79189. CannonJSPlugin.prototype.getBoxSizeToRef = function (impostor, result) {
  79190. var shape = impostor.physicsBody.shapes[0];
  79191. result.x = shape.halfExtents.x * 2;
  79192. result.y = shape.halfExtents.y * 2;
  79193. result.z = shape.halfExtents.z * 2;
  79194. };
  79195. CannonJSPlugin.prototype.dispose = function () {
  79196. };
  79197. CannonJSPlugin.prototype._extendNamespace = function () {
  79198. //this will force cannon to execute at least one step when using interpolation
  79199. var step_tmp1 = new this.BJSCANNON.Vec3();
  79200. var Engine = this.BJSCANNON;
  79201. this.BJSCANNON.World.prototype.step = function (dt, timeSinceLastCalled, maxSubSteps) {
  79202. maxSubSteps = maxSubSteps || 10;
  79203. timeSinceLastCalled = timeSinceLastCalled || 0;
  79204. if (timeSinceLastCalled === 0) {
  79205. this.internalStep(dt);
  79206. this.time += dt;
  79207. }
  79208. else {
  79209. var internalSteps = Math.floor((this.time + timeSinceLastCalled) / dt) - Math.floor(this.time / dt);
  79210. internalSteps = Math.min(internalSteps, maxSubSteps) || 1;
  79211. var t0 = performance.now();
  79212. for (var i = 0; i !== internalSteps; i++) {
  79213. this.internalStep(dt);
  79214. if (performance.now() - t0 > dt * 1000) {
  79215. break;
  79216. }
  79217. }
  79218. this.time += timeSinceLastCalled;
  79219. var h = this.time % dt;
  79220. var h_div_dt = h / dt;
  79221. var interpvelo = step_tmp1;
  79222. var bodies = this.bodies;
  79223. for (var j = 0; j !== bodies.length; j++) {
  79224. var b = bodies[j];
  79225. if (b.type !== Engine.Body.STATIC && b.sleepState !== Engine.Body.SLEEPING) {
  79226. b.position.vsub(b.previousPosition, interpvelo);
  79227. interpvelo.scale(h_div_dt, interpvelo);
  79228. b.position.vadd(interpvelo, b.interpolatedPosition);
  79229. }
  79230. else {
  79231. b.interpolatedPosition.copy(b.position);
  79232. b.interpolatedQuaternion.copy(b.quaternion);
  79233. }
  79234. }
  79235. }
  79236. };
  79237. };
  79238. return CannonJSPlugin;
  79239. }());
  79240. BABYLON.CannonJSPlugin = CannonJSPlugin;
  79241. })(BABYLON || (BABYLON = {}));
  79242. //# sourceMappingURL=babylon.cannonJSPlugin.js.map
  79243. "use strict";
  79244. var BABYLON;
  79245. (function (BABYLON) {
  79246. var OimoJSPlugin = /** @class */ (function () {
  79247. function OimoJSPlugin(iterations) {
  79248. this.name = "OimoJSPlugin";
  79249. this._tmpImpostorsArray = [];
  79250. this._tmpPositionVector = BABYLON.Vector3.Zero();
  79251. this.BJSOIMO = OIMO;
  79252. this.world = new this.BJSOIMO.World({
  79253. iterations: iterations
  79254. });
  79255. this.world.clear();
  79256. }
  79257. OimoJSPlugin.prototype.setGravity = function (gravity) {
  79258. this.world.gravity.copy(gravity);
  79259. };
  79260. OimoJSPlugin.prototype.setTimeStep = function (timeStep) {
  79261. this.world.timeStep = timeStep;
  79262. };
  79263. OimoJSPlugin.prototype.getTimeStep = function () {
  79264. return this.world.timeStep;
  79265. };
  79266. OimoJSPlugin.prototype.executeStep = function (delta, impostors) {
  79267. var _this = this;
  79268. impostors.forEach(function (impostor) {
  79269. impostor.beforeStep();
  79270. });
  79271. this.world.step();
  79272. impostors.forEach(function (impostor) {
  79273. impostor.afterStep();
  79274. //update the ordered impostors array
  79275. _this._tmpImpostorsArray[impostor.uniqueId] = impostor;
  79276. });
  79277. //check for collisions
  79278. var contact = this.world.contacts;
  79279. while (contact !== null) {
  79280. if (contact.touching && !contact.body1.sleeping && !contact.body2.sleeping) {
  79281. contact = contact.next;
  79282. continue;
  79283. }
  79284. //is this body colliding with any other? get the impostor
  79285. var mainImpostor = this._tmpImpostorsArray[+contact.body1.name];
  79286. var collidingImpostor = this._tmpImpostorsArray[+contact.body2.name];
  79287. if (!mainImpostor || !collidingImpostor) {
  79288. contact = contact.next;
  79289. continue;
  79290. }
  79291. mainImpostor.onCollide({ body: collidingImpostor.physicsBody });
  79292. collidingImpostor.onCollide({ body: mainImpostor.physicsBody });
  79293. contact = contact.next;
  79294. }
  79295. };
  79296. OimoJSPlugin.prototype.applyImpulse = function (impostor, force, contactPoint) {
  79297. var mass = impostor.physicsBody.mass;
  79298. impostor.physicsBody.applyImpulse(contactPoint.scale(this.world.invScale), force.scale(this.world.invScale * mass));
  79299. };
  79300. OimoJSPlugin.prototype.applyForce = function (impostor, force, contactPoint) {
  79301. BABYLON.Tools.Warn("Oimo doesn't support applying force. Using impule instead.");
  79302. this.applyImpulse(impostor, force, contactPoint);
  79303. };
  79304. OimoJSPlugin.prototype.generatePhysicsBody = function (impostor) {
  79305. var _this = this;
  79306. //parent-child relationship. Does this impostor has a parent impostor?
  79307. if (impostor.parent) {
  79308. if (impostor.physicsBody) {
  79309. this.removePhysicsBody(impostor);
  79310. //TODO is that needed?
  79311. impostor.forceUpdate();
  79312. }
  79313. return;
  79314. }
  79315. if (impostor.isBodyInitRequired()) {
  79316. var bodyConfig = {
  79317. name: impostor.uniqueId,
  79318. //Oimo must have mass, also for static objects.
  79319. config: [impostor.getParam("mass") || 1, impostor.getParam("friction"), impostor.getParam("restitution")],
  79320. size: [],
  79321. type: [],
  79322. pos: [],
  79323. posShape: [],
  79324. rot: [],
  79325. rotShape: [],
  79326. move: impostor.getParam("mass") !== 0,
  79327. density: impostor.getParam("mass"),
  79328. friction: impostor.getParam("friction"),
  79329. restitution: impostor.getParam("restitution"),
  79330. //Supporting older versions of Oimo
  79331. world: this.world
  79332. };
  79333. var impostors = [impostor];
  79334. var addToArray = function (parent) {
  79335. if (!parent.getChildMeshes)
  79336. return;
  79337. parent.getChildMeshes().forEach(function (m) {
  79338. if (m.physicsImpostor) {
  79339. impostors.push(m.physicsImpostor);
  79340. //m.physicsImpostor._init();
  79341. }
  79342. });
  79343. };
  79344. addToArray(impostor.object);
  79345. var checkWithEpsilon_1 = function (value) {
  79346. return Math.max(value, BABYLON.PhysicsEngine.Epsilon);
  79347. };
  79348. impostors.forEach(function (i) {
  79349. if (!i.object.rotationQuaternion) {
  79350. return;
  79351. }
  79352. //get the correct bounding box
  79353. var oldQuaternion = i.object.rotationQuaternion;
  79354. var rot = oldQuaternion.toEulerAngles();
  79355. var extendSize = i.getObjectExtendSize();
  79356. var radToDeg = 57.295779513082320876;
  79357. if (i === impostor) {
  79358. var center = impostor.getObjectCenter();
  79359. impostor.object.getAbsolutePivotPoint().subtractToRef(center, _this._tmpPositionVector);
  79360. _this._tmpPositionVector.divideInPlace(impostor.object.scaling);
  79361. //Can also use Array.prototype.push.apply
  79362. bodyConfig.pos.push(center.x);
  79363. bodyConfig.pos.push(center.y);
  79364. bodyConfig.pos.push(center.z);
  79365. bodyConfig.posShape.push(0, 0, 0);
  79366. //tmp solution
  79367. bodyConfig.rot.push(rot.x * radToDeg);
  79368. bodyConfig.rot.push(rot.y * radToDeg);
  79369. bodyConfig.rot.push(rot.z * radToDeg);
  79370. bodyConfig.rotShape.push(0, 0, 0);
  79371. }
  79372. else {
  79373. var localPosition = i.object.getAbsolutePosition().subtract(impostor.object.getAbsolutePosition());
  79374. bodyConfig.posShape.push(localPosition.x);
  79375. bodyConfig.posShape.push(localPosition.y);
  79376. bodyConfig.posShape.push(localPosition.z);
  79377. bodyConfig.pos.push(0, 0, 0);
  79378. //tmp solution until https://github.com/lo-th/OIMO.js/pull/37 is merged
  79379. bodyConfig.rot.push(0);
  79380. bodyConfig.rot.push(0);
  79381. bodyConfig.rot.push(0);
  79382. bodyConfig.rotShape.push(rot.x * radToDeg);
  79383. bodyConfig.rotShape.push(rot.y * radToDeg);
  79384. bodyConfig.rotShape.push(rot.z * radToDeg);
  79385. }
  79386. // register mesh
  79387. switch (i.type) {
  79388. case BABYLON.PhysicsImpostor.ParticleImpostor:
  79389. BABYLON.Tools.Warn("No Particle support in OIMO.js. using SphereImpostor instead");
  79390. case BABYLON.PhysicsImpostor.SphereImpostor:
  79391. var radiusX = extendSize.x;
  79392. var radiusY = extendSize.y;
  79393. var radiusZ = extendSize.z;
  79394. var size = Math.max(checkWithEpsilon_1(radiusX), checkWithEpsilon_1(radiusY), checkWithEpsilon_1(radiusZ)) / 2;
  79395. bodyConfig.type.push('sphere');
  79396. //due to the way oimo works with compounds, add 3 times
  79397. bodyConfig.size.push(size);
  79398. bodyConfig.size.push(size);
  79399. bodyConfig.size.push(size);
  79400. break;
  79401. case BABYLON.PhysicsImpostor.CylinderImpostor:
  79402. var sizeX = checkWithEpsilon_1(extendSize.x) / 2;
  79403. var sizeY = checkWithEpsilon_1(extendSize.y);
  79404. bodyConfig.type.push('cylinder');
  79405. bodyConfig.size.push(sizeX);
  79406. bodyConfig.size.push(sizeY);
  79407. //due to the way oimo works with compounds, add one more value.
  79408. bodyConfig.size.push(sizeY);
  79409. break;
  79410. case BABYLON.PhysicsImpostor.PlaneImpostor:
  79411. case BABYLON.PhysicsImpostor.BoxImpostor:
  79412. default:
  79413. var sizeX = checkWithEpsilon_1(extendSize.x);
  79414. var sizeY = checkWithEpsilon_1(extendSize.y);
  79415. var sizeZ = checkWithEpsilon_1(extendSize.z);
  79416. bodyConfig.type.push('box');
  79417. //if (i === impostor) {
  79418. bodyConfig.size.push(sizeX);
  79419. bodyConfig.size.push(sizeY);
  79420. bodyConfig.size.push(sizeZ);
  79421. //} else {
  79422. // bodyConfig.size.push(0,0,0);
  79423. //}
  79424. break;
  79425. }
  79426. //actually not needed, but hey...
  79427. i.object.rotationQuaternion = oldQuaternion;
  79428. });
  79429. impostor.physicsBody = this.world.add(bodyConfig);
  79430. }
  79431. else {
  79432. this._tmpPositionVector.copyFromFloats(0, 0, 0);
  79433. }
  79434. impostor.setDeltaPosition(this._tmpPositionVector);
  79435. //this._tmpPositionVector.addInPlace(impostor.mesh.getBoundingInfo().boundingBox.center);
  79436. //this.setPhysicsBodyTransformation(impostor, this._tmpPositionVector, impostor.mesh.rotationQuaternion);
  79437. };
  79438. OimoJSPlugin.prototype.removePhysicsBody = function (impostor) {
  79439. //impostor.physicsBody.dispose();
  79440. //Same as : (older oimo versions)
  79441. this.world.removeRigidBody(impostor.physicsBody);
  79442. };
  79443. OimoJSPlugin.prototype.generateJoint = function (impostorJoint) {
  79444. var mainBody = impostorJoint.mainImpostor.physicsBody;
  79445. var connectedBody = impostorJoint.connectedImpostor.physicsBody;
  79446. if (!mainBody || !connectedBody) {
  79447. return;
  79448. }
  79449. var jointData = impostorJoint.joint.jointData;
  79450. var options = jointData.nativeParams || {};
  79451. var type;
  79452. var nativeJointData = {
  79453. body1: mainBody,
  79454. body2: connectedBody,
  79455. axe1: options.axe1 || (jointData.mainAxis ? jointData.mainAxis.asArray() : null),
  79456. axe2: options.axe2 || (jointData.connectedAxis ? jointData.connectedAxis.asArray() : null),
  79457. pos1: options.pos1 || (jointData.mainPivot ? jointData.mainPivot.asArray() : null),
  79458. pos2: options.pos2 || (jointData.connectedPivot ? jointData.connectedPivot.asArray() : null),
  79459. min: options.min,
  79460. max: options.max,
  79461. collision: options.collision || jointData.collision,
  79462. spring: options.spring,
  79463. //supporting older version of Oimo
  79464. world: this.world
  79465. };
  79466. switch (impostorJoint.joint.type) {
  79467. case BABYLON.PhysicsJoint.BallAndSocketJoint:
  79468. type = "jointBall";
  79469. break;
  79470. case BABYLON.PhysicsJoint.SpringJoint:
  79471. BABYLON.Tools.Warn("OIMO.js doesn't support Spring Constraint. Simulating using DistanceJoint instead");
  79472. var springData = jointData;
  79473. nativeJointData.min = springData.length || nativeJointData.min;
  79474. //Max should also be set, just make sure it is at least min
  79475. nativeJointData.max = Math.max(nativeJointData.min, nativeJointData.max);
  79476. case BABYLON.PhysicsJoint.DistanceJoint:
  79477. type = "jointDistance";
  79478. nativeJointData.max = jointData.maxDistance;
  79479. break;
  79480. case BABYLON.PhysicsJoint.PrismaticJoint:
  79481. type = "jointPrisme";
  79482. break;
  79483. case BABYLON.PhysicsJoint.SliderJoint:
  79484. type = "jointSlide";
  79485. break;
  79486. case BABYLON.PhysicsJoint.WheelJoint:
  79487. type = "jointWheel";
  79488. break;
  79489. case BABYLON.PhysicsJoint.HingeJoint:
  79490. default:
  79491. type = "jointHinge";
  79492. break;
  79493. }
  79494. nativeJointData.type = type;
  79495. impostorJoint.joint.physicsJoint = this.world.add(nativeJointData);
  79496. };
  79497. OimoJSPlugin.prototype.removeJoint = function (impostorJoint) {
  79498. //Bug in Oimo prevents us from disposing a joint in the playground
  79499. //joint.joint.physicsJoint.dispose();
  79500. //So we will bruteforce it!
  79501. try {
  79502. this.world.removeJoint(impostorJoint.joint.physicsJoint);
  79503. }
  79504. catch (e) {
  79505. BABYLON.Tools.Warn(e);
  79506. }
  79507. };
  79508. OimoJSPlugin.prototype.isSupported = function () {
  79509. return this.BJSOIMO !== undefined;
  79510. };
  79511. OimoJSPlugin.prototype.setTransformationFromPhysicsBody = function (impostor) {
  79512. if (!impostor.physicsBody.sleeping) {
  79513. //TODO check that
  79514. /*if (impostor.physicsBody.shapes.next) {
  79515. var parentShape = this._getLastShape(impostor.physicsBody);
  79516. impostor.object.position.copyFrom(parentShape.position);
  79517. console.log(parentShape.position);
  79518. } else {*/
  79519. impostor.object.position.copyFrom(impostor.physicsBody.getPosition());
  79520. //}
  79521. if (impostor.object.rotationQuaternion) {
  79522. impostor.object.rotationQuaternion.copyFrom(impostor.physicsBody.getQuaternion());
  79523. }
  79524. }
  79525. };
  79526. OimoJSPlugin.prototype.setPhysicsBodyTransformation = function (impostor, newPosition, newRotation) {
  79527. var body = impostor.physicsBody;
  79528. body.position.copy(newPosition);
  79529. body.orientation.copy(newRotation);
  79530. body.syncShapes();
  79531. body.awake();
  79532. };
  79533. /*private _getLastShape(body: any): any {
  79534. var lastShape = body.shapes;
  79535. while (lastShape.next) {
  79536. lastShape = lastShape.next;
  79537. }
  79538. return lastShape;
  79539. }*/
  79540. OimoJSPlugin.prototype.setLinearVelocity = function (impostor, velocity) {
  79541. impostor.physicsBody.linearVelocity.init(velocity.x, velocity.y, velocity.z);
  79542. };
  79543. OimoJSPlugin.prototype.setAngularVelocity = function (impostor, velocity) {
  79544. impostor.physicsBody.angularVelocity.init(velocity.x, velocity.y, velocity.z);
  79545. };
  79546. OimoJSPlugin.prototype.getLinearVelocity = function (impostor) {
  79547. var v = impostor.physicsBody.linearVelocity;
  79548. if (!v) {
  79549. return null;
  79550. }
  79551. return new BABYLON.Vector3(v.x, v.y, v.z);
  79552. };
  79553. OimoJSPlugin.prototype.getAngularVelocity = function (impostor) {
  79554. var v = impostor.physicsBody.angularVelocity;
  79555. if (!v) {
  79556. return null;
  79557. }
  79558. return new BABYLON.Vector3(v.x, v.y, v.z);
  79559. };
  79560. OimoJSPlugin.prototype.setBodyMass = function (impostor, mass) {
  79561. var staticBody = mass === 0;
  79562. //this will actually set the body's density and not its mass.
  79563. //But this is how oimo treats the mass variable.
  79564. impostor.physicsBody.shapes.density = staticBody ? 1 : mass;
  79565. impostor.physicsBody.setupMass(staticBody ? 0x2 : 0x1);
  79566. };
  79567. OimoJSPlugin.prototype.getBodyMass = function (impostor) {
  79568. return impostor.physicsBody.shapes.density;
  79569. };
  79570. OimoJSPlugin.prototype.getBodyFriction = function (impostor) {
  79571. return impostor.physicsBody.shapes.friction;
  79572. };
  79573. OimoJSPlugin.prototype.setBodyFriction = function (impostor, friction) {
  79574. impostor.physicsBody.shapes.friction = friction;
  79575. };
  79576. OimoJSPlugin.prototype.getBodyRestitution = function (impostor) {
  79577. return impostor.physicsBody.shapes.restitution;
  79578. };
  79579. OimoJSPlugin.prototype.setBodyRestitution = function (impostor, restitution) {
  79580. impostor.physicsBody.shapes.restitution = restitution;
  79581. };
  79582. OimoJSPlugin.prototype.sleepBody = function (impostor) {
  79583. impostor.physicsBody.sleep();
  79584. };
  79585. OimoJSPlugin.prototype.wakeUpBody = function (impostor) {
  79586. impostor.physicsBody.awake();
  79587. };
  79588. OimoJSPlugin.prototype.updateDistanceJoint = function (joint, maxDistance, minDistance) {
  79589. joint.physicsJoint.limitMotor.upperLimit = maxDistance;
  79590. if (minDistance !== void 0) {
  79591. joint.physicsJoint.limitMotor.lowerLimit = minDistance;
  79592. }
  79593. };
  79594. OimoJSPlugin.prototype.setMotor = function (joint, speed, maxForce, motorIndex) {
  79595. //TODO separate rotational and transational motors.
  79596. var motor = motorIndex ? joint.physicsJoint.rotationalLimitMotor2 : joint.physicsJoint.rotationalLimitMotor1 || joint.physicsJoint.rotationalLimitMotor || joint.physicsJoint.limitMotor;
  79597. if (motor) {
  79598. motor.setMotor(speed, maxForce);
  79599. }
  79600. };
  79601. OimoJSPlugin.prototype.setLimit = function (joint, upperLimit, lowerLimit, motorIndex) {
  79602. //TODO separate rotational and transational motors.
  79603. var motor = motorIndex ? joint.physicsJoint.rotationalLimitMotor2 : joint.physicsJoint.rotationalLimitMotor1 || joint.physicsJoint.rotationalLimitMotor || joint.physicsJoint.limitMotor;
  79604. if (motor) {
  79605. motor.setLimit(upperLimit, lowerLimit === void 0 ? -upperLimit : lowerLimit);
  79606. }
  79607. };
  79608. OimoJSPlugin.prototype.syncMeshWithImpostor = function (mesh, impostor) {
  79609. var body = impostor.physicsBody;
  79610. mesh.position.x = body.position.x;
  79611. mesh.position.y = body.position.y;
  79612. mesh.position.z = body.position.z;
  79613. if (mesh.rotationQuaternion) {
  79614. mesh.rotationQuaternion.x = body.orientation.x;
  79615. mesh.rotationQuaternion.y = body.orientation.y;
  79616. mesh.rotationQuaternion.z = body.orientation.z;
  79617. mesh.rotationQuaternion.w = body.orientation.s;
  79618. }
  79619. };
  79620. OimoJSPlugin.prototype.getRadius = function (impostor) {
  79621. return impostor.physicsBody.shapes.radius;
  79622. };
  79623. OimoJSPlugin.prototype.getBoxSizeToRef = function (impostor, result) {
  79624. var shape = impostor.physicsBody.shapes;
  79625. result.x = shape.halfWidth * 2;
  79626. result.y = shape.halfHeight * 2;
  79627. result.z = shape.halfDepth * 2;
  79628. };
  79629. OimoJSPlugin.prototype.dispose = function () {
  79630. this.world.clear();
  79631. };
  79632. return OimoJSPlugin;
  79633. }());
  79634. BABYLON.OimoJSPlugin = OimoJSPlugin;
  79635. })(BABYLON || (BABYLON = {}));
  79636. //# sourceMappingURL=babylon.oimoJSPlugin.js.map
  79637. "use strict";
  79638. var BABYLON;
  79639. (function (BABYLON) {
  79640. /*
  79641. * Based on jsTGALoader - Javascript loader for TGA file
  79642. * By Vincent Thibault
  79643. * @blog http://blog.robrowser.com/javascript-tga-loader.html
  79644. */
  79645. var TGATools = /** @class */ (function () {
  79646. function TGATools() {
  79647. }
  79648. TGATools.GetTGAHeader = function (data) {
  79649. var offset = 0;
  79650. var header = {
  79651. id_length: data[offset++],
  79652. colormap_type: data[offset++],
  79653. image_type: data[offset++],
  79654. colormap_index: data[offset++] | data[offset++] << 8,
  79655. colormap_length: data[offset++] | data[offset++] << 8,
  79656. colormap_size: data[offset++],
  79657. origin: [
  79658. data[offset++] | data[offset++] << 8,
  79659. data[offset++] | data[offset++] << 8
  79660. ],
  79661. width: data[offset++] | data[offset++] << 8,
  79662. height: data[offset++] | data[offset++] << 8,
  79663. pixel_size: data[offset++],
  79664. flags: data[offset++]
  79665. };
  79666. return header;
  79667. };
  79668. TGATools.UploadContent = function (gl, data) {
  79669. // Not enough data to contain header ?
  79670. if (data.length < 19) {
  79671. BABYLON.Tools.Error("Unable to load TGA file - Not enough data to contain header");
  79672. return;
  79673. }
  79674. // Read Header
  79675. var offset = 18;
  79676. var header = TGATools.GetTGAHeader(data);
  79677. // Assume it's a valid Targa file.
  79678. if (header.id_length + offset > data.length) {
  79679. BABYLON.Tools.Error("Unable to load TGA file - Not enough data");
  79680. return;
  79681. }
  79682. // Skip not needed data
  79683. offset += header.id_length;
  79684. var use_rle = false;
  79685. var use_pal = false;
  79686. var use_grey = false;
  79687. // Get some informations.
  79688. switch (header.image_type) {
  79689. case TGATools._TYPE_RLE_INDEXED:
  79690. use_rle = true;
  79691. case TGATools._TYPE_INDEXED:
  79692. use_pal = true;
  79693. break;
  79694. case TGATools._TYPE_RLE_RGB:
  79695. use_rle = true;
  79696. case TGATools._TYPE_RGB:
  79697. // use_rgb = true;
  79698. break;
  79699. case TGATools._TYPE_RLE_GREY:
  79700. use_rle = true;
  79701. case TGATools._TYPE_GREY:
  79702. use_grey = true;
  79703. break;
  79704. }
  79705. var pixel_data;
  79706. // var numAlphaBits = header.flags & 0xf;
  79707. var pixel_size = header.pixel_size >> 3;
  79708. var pixel_total = header.width * header.height * pixel_size;
  79709. // Read palettes
  79710. var palettes;
  79711. if (use_pal) {
  79712. palettes = data.subarray(offset, offset += header.colormap_length * (header.colormap_size >> 3));
  79713. }
  79714. // Read LRE
  79715. if (use_rle) {
  79716. pixel_data = new Uint8Array(pixel_total);
  79717. var c, count, i;
  79718. var localOffset = 0;
  79719. var pixels = new Uint8Array(pixel_size);
  79720. while (offset < pixel_total && localOffset < pixel_total) {
  79721. c = data[offset++];
  79722. count = (c & 0x7f) + 1;
  79723. // RLE pixels
  79724. if (c & 0x80) {
  79725. // Bind pixel tmp array
  79726. for (i = 0; i < pixel_size; ++i) {
  79727. pixels[i] = data[offset++];
  79728. }
  79729. // Copy pixel array
  79730. for (i = 0; i < count; ++i) {
  79731. pixel_data.set(pixels, localOffset + i * pixel_size);
  79732. }
  79733. localOffset += pixel_size * count;
  79734. }
  79735. else {
  79736. count *= pixel_size;
  79737. for (i = 0; i < count; ++i) {
  79738. pixel_data[localOffset + i] = data[offset++];
  79739. }
  79740. localOffset += count;
  79741. }
  79742. }
  79743. }
  79744. else {
  79745. pixel_data = data.subarray(offset, offset += (use_pal ? header.width * header.height : pixel_total));
  79746. }
  79747. // Load to texture
  79748. var x_start, y_start, x_step, y_step, y_end, x_end;
  79749. switch ((header.flags & TGATools._ORIGIN_MASK) >> TGATools._ORIGIN_SHIFT) {
  79750. default:
  79751. case TGATools._ORIGIN_UL:
  79752. x_start = 0;
  79753. x_step = 1;
  79754. x_end = header.width;
  79755. y_start = 0;
  79756. y_step = 1;
  79757. y_end = header.height;
  79758. break;
  79759. case TGATools._ORIGIN_BL:
  79760. x_start = 0;
  79761. x_step = 1;
  79762. x_end = header.width;
  79763. y_start = header.height - 1;
  79764. y_step = -1;
  79765. y_end = -1;
  79766. break;
  79767. case TGATools._ORIGIN_UR:
  79768. x_start = header.width - 1;
  79769. x_step = -1;
  79770. x_end = -1;
  79771. y_start = 0;
  79772. y_step = 1;
  79773. y_end = header.height;
  79774. break;
  79775. case TGATools._ORIGIN_BR:
  79776. x_start = header.width - 1;
  79777. x_step = -1;
  79778. x_end = -1;
  79779. y_start = header.height - 1;
  79780. y_step = -1;
  79781. y_end = -1;
  79782. break;
  79783. }
  79784. // Load the specify method
  79785. var func = '_getImageData' + (use_grey ? 'Grey' : '') + (header.pixel_size) + 'bits';
  79786. var imageData = TGATools[func](header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end);
  79787. gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, header.width, header.height, 0, gl.RGBA, gl.UNSIGNED_BYTE, imageData);
  79788. };
  79789. TGATools._getImageData8bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  79790. var image = pixel_data, colormap = palettes;
  79791. var width = header.width, height = header.height;
  79792. var color, i = 0, x, y;
  79793. var imageData = new Uint8Array(width * height * 4);
  79794. for (y = y_start; y !== y_end; y += y_step) {
  79795. for (x = x_start; x !== x_end; x += x_step, i++) {
  79796. color = image[i];
  79797. imageData[(x + width * y) * 4 + 3] = 255;
  79798. imageData[(x + width * y) * 4 + 2] = colormap[(color * 3) + 0];
  79799. imageData[(x + width * y) * 4 + 1] = colormap[(color * 3) + 1];
  79800. imageData[(x + width * y) * 4 + 0] = colormap[(color * 3) + 2];
  79801. }
  79802. }
  79803. return imageData;
  79804. };
  79805. TGATools._getImageData16bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  79806. var image = pixel_data;
  79807. var width = header.width, height = header.height;
  79808. var color, i = 0, x, y;
  79809. var imageData = new Uint8Array(width * height * 4);
  79810. for (y = y_start; y !== y_end; y += y_step) {
  79811. for (x = x_start; x !== x_end; x += x_step, i += 2) {
  79812. color = image[i + 0] + (image[i + 1] << 8); // Inversed ?
  79813. var r = (((color & 0x7C00) >> 10) * 255) / 0x1F | 0;
  79814. var g = (((color & 0x03E0) >> 5) * 255) / 0x1F | 0;
  79815. var b = ((color & 0x001F) * 255) / 0x1F | 0;
  79816. imageData[(x + width * y) * 4 + 0] = r;
  79817. imageData[(x + width * y) * 4 + 1] = g;
  79818. imageData[(x + width * y) * 4 + 2] = b;
  79819. imageData[(x + width * y) * 4 + 3] = (color & 0x8000) ? 0 : 255;
  79820. }
  79821. }
  79822. return imageData;
  79823. };
  79824. TGATools._getImageData24bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  79825. var image = pixel_data;
  79826. var width = header.width, height = header.height;
  79827. var i = 0, x, y;
  79828. var imageData = new Uint8Array(width * height * 4);
  79829. for (y = y_start; y !== y_end; y += y_step) {
  79830. for (x = x_start; x !== x_end; x += x_step, i += 3) {
  79831. imageData[(x + width * y) * 4 + 3] = 255;
  79832. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  79833. imageData[(x + width * y) * 4 + 1] = image[i + 1];
  79834. imageData[(x + width * y) * 4 + 0] = image[i + 2];
  79835. }
  79836. }
  79837. return imageData;
  79838. };
  79839. TGATools._getImageData32bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  79840. var image = pixel_data;
  79841. var width = header.width, height = header.height;
  79842. var i = 0, x, y;
  79843. var imageData = new Uint8Array(width * height * 4);
  79844. for (y = y_start; y !== y_end; y += y_step) {
  79845. for (x = x_start; x !== x_end; x += x_step, i += 4) {
  79846. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  79847. imageData[(x + width * y) * 4 + 1] = image[i + 1];
  79848. imageData[(x + width * y) * 4 + 0] = image[i + 2];
  79849. imageData[(x + width * y) * 4 + 3] = image[i + 3];
  79850. }
  79851. }
  79852. return imageData;
  79853. };
  79854. TGATools._getImageDataGrey8bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  79855. var image = pixel_data;
  79856. var width = header.width, height = header.height;
  79857. var color, i = 0, x, y;
  79858. var imageData = new Uint8Array(width * height * 4);
  79859. for (y = y_start; y !== y_end; y += y_step) {
  79860. for (x = x_start; x !== x_end; x += x_step, i++) {
  79861. color = image[i];
  79862. imageData[(x + width * y) * 4 + 0] = color;
  79863. imageData[(x + width * y) * 4 + 1] = color;
  79864. imageData[(x + width * y) * 4 + 2] = color;
  79865. imageData[(x + width * y) * 4 + 3] = 255;
  79866. }
  79867. }
  79868. return imageData;
  79869. };
  79870. TGATools._getImageDataGrey16bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  79871. var image = pixel_data;
  79872. var width = header.width, height = header.height;
  79873. var i = 0, x, y;
  79874. var imageData = new Uint8Array(width * height * 4);
  79875. for (y = y_start; y !== y_end; y += y_step) {
  79876. for (x = x_start; x !== x_end; x += x_step, i += 2) {
  79877. imageData[(x + width * y) * 4 + 0] = image[i + 0];
  79878. imageData[(x + width * y) * 4 + 1] = image[i + 0];
  79879. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  79880. imageData[(x + width * y) * 4 + 3] = image[i + 1];
  79881. }
  79882. }
  79883. return imageData;
  79884. };
  79885. //private static _TYPE_NO_DATA = 0;
  79886. TGATools._TYPE_INDEXED = 1;
  79887. TGATools._TYPE_RGB = 2;
  79888. TGATools._TYPE_GREY = 3;
  79889. TGATools._TYPE_RLE_INDEXED = 9;
  79890. TGATools._TYPE_RLE_RGB = 10;
  79891. TGATools._TYPE_RLE_GREY = 11;
  79892. TGATools._ORIGIN_MASK = 0x30;
  79893. TGATools._ORIGIN_SHIFT = 0x04;
  79894. TGATools._ORIGIN_BL = 0x00;
  79895. TGATools._ORIGIN_BR = 0x01;
  79896. TGATools._ORIGIN_UL = 0x02;
  79897. TGATools._ORIGIN_UR = 0x03;
  79898. return TGATools;
  79899. }());
  79900. BABYLON.TGATools = TGATools;
  79901. })(BABYLON || (BABYLON = {}));
  79902. //# sourceMappingURL=babylon.tga.js.map
  79903. "use strict";
  79904. var BABYLON;
  79905. (function (BABYLON) {
  79906. // Based on demo done by Brandon Jones - http://media.tojicode.com/webgl-samples/dds.html
  79907. // All values and structures referenced from:
  79908. // http://msdn.microsoft.com/en-us/library/bb943991.aspx/
  79909. var DDS_MAGIC = 0x20534444;
  79910. var
  79911. //DDSD_CAPS = 0x1,
  79912. //DDSD_HEIGHT = 0x2,
  79913. //DDSD_WIDTH = 0x4,
  79914. //DDSD_PITCH = 0x8,
  79915. //DDSD_PIXELFORMAT = 0x1000,
  79916. DDSD_MIPMAPCOUNT = 0x20000;
  79917. //DDSD_LINEARSIZE = 0x80000,
  79918. //DDSD_DEPTH = 0x800000;
  79919. // var DDSCAPS_COMPLEX = 0x8,
  79920. // DDSCAPS_MIPMAP = 0x400000,
  79921. // DDSCAPS_TEXTURE = 0x1000;
  79922. var DDSCAPS2_CUBEMAP = 0x200;
  79923. // DDSCAPS2_CUBEMAP_POSITIVEX = 0x400,
  79924. // DDSCAPS2_CUBEMAP_NEGATIVEX = 0x800,
  79925. // DDSCAPS2_CUBEMAP_POSITIVEY = 0x1000,
  79926. // DDSCAPS2_CUBEMAP_NEGATIVEY = 0x2000,
  79927. // DDSCAPS2_CUBEMAP_POSITIVEZ = 0x4000,
  79928. // DDSCAPS2_CUBEMAP_NEGATIVEZ = 0x8000,
  79929. // DDSCAPS2_VOLUME = 0x200000;
  79930. var
  79931. //DDPF_ALPHAPIXELS = 0x1,
  79932. //DDPF_ALPHA = 0x2,
  79933. DDPF_FOURCC = 0x4, DDPF_RGB = 0x40,
  79934. //DDPF_YUV = 0x200,
  79935. DDPF_LUMINANCE = 0x20000;
  79936. function FourCCToInt32(value) {
  79937. return value.charCodeAt(0) +
  79938. (value.charCodeAt(1) << 8) +
  79939. (value.charCodeAt(2) << 16) +
  79940. (value.charCodeAt(3) << 24);
  79941. }
  79942. function Int32ToFourCC(value) {
  79943. return String.fromCharCode(value & 0xff, (value >> 8) & 0xff, (value >> 16) & 0xff, (value >> 24) & 0xff);
  79944. }
  79945. var FOURCC_DXT1 = FourCCToInt32("DXT1");
  79946. var FOURCC_DXT3 = FourCCToInt32("DXT3");
  79947. var FOURCC_DXT5 = FourCCToInt32("DXT5");
  79948. var FOURCC_DX10 = FourCCToInt32("DX10");
  79949. var FOURCC_D3DFMT_R16G16B16A16F = 113;
  79950. var FOURCC_D3DFMT_R32G32B32A32F = 116;
  79951. var DXGI_FORMAT_R16G16B16A16_FLOAT = 10;
  79952. var DXGI_FORMAT_B8G8R8X8_UNORM = 88;
  79953. var headerLengthInt = 31; // The header length in 32 bit ints
  79954. // Offsets into the header array
  79955. var off_magic = 0;
  79956. var off_size = 1;
  79957. var off_flags = 2;
  79958. var off_height = 3;
  79959. var off_width = 4;
  79960. var off_mipmapCount = 7;
  79961. var off_pfFlags = 20;
  79962. var off_pfFourCC = 21;
  79963. var off_RGBbpp = 22;
  79964. var off_RMask = 23;
  79965. var off_GMask = 24;
  79966. var off_BMask = 25;
  79967. var off_AMask = 26;
  79968. // var off_caps1 = 27;
  79969. var off_caps2 = 28;
  79970. // var off_caps3 = 29;
  79971. // var off_caps4 = 30;
  79972. var off_dxgiFormat = 32;
  79973. ;
  79974. var DDSTools = /** @class */ (function () {
  79975. function DDSTools() {
  79976. }
  79977. DDSTools.GetDDSInfo = function (arrayBuffer) {
  79978. var header = new Int32Array(arrayBuffer, 0, headerLengthInt);
  79979. var extendedHeader = new Int32Array(arrayBuffer, 0, headerLengthInt + 4);
  79980. var mipmapCount = 1;
  79981. if (header[off_flags] & DDSD_MIPMAPCOUNT) {
  79982. mipmapCount = Math.max(1, header[off_mipmapCount]);
  79983. }
  79984. var fourCC = header[off_pfFourCC];
  79985. var dxgiFormat = (fourCC === FOURCC_DX10) ? extendedHeader[off_dxgiFormat] : 0;
  79986. var textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  79987. switch (fourCC) {
  79988. case FOURCC_D3DFMT_R16G16B16A16F:
  79989. textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  79990. break;
  79991. case FOURCC_D3DFMT_R32G32B32A32F:
  79992. textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  79993. break;
  79994. case FOURCC_DX10:
  79995. if (dxgiFormat === DXGI_FORMAT_R16G16B16A16_FLOAT) {
  79996. textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  79997. break;
  79998. }
  79999. }
  80000. return {
  80001. width: header[off_width],
  80002. height: header[off_height],
  80003. mipmapCount: mipmapCount,
  80004. isFourCC: (header[off_pfFlags] & DDPF_FOURCC) === DDPF_FOURCC,
  80005. isRGB: (header[off_pfFlags] & DDPF_RGB) === DDPF_RGB,
  80006. isLuminance: (header[off_pfFlags] & DDPF_LUMINANCE) === DDPF_LUMINANCE,
  80007. isCube: (header[off_caps2] & DDSCAPS2_CUBEMAP) === DDSCAPS2_CUBEMAP,
  80008. isCompressed: (fourCC === FOURCC_DXT1 || fourCC === FOURCC_DXT3 || fourCC === FOURCC_DXT5),
  80009. dxgiFormat: dxgiFormat,
  80010. textureType: textureType
  80011. };
  80012. };
  80013. DDSTools._ToHalfFloat = function (value) {
  80014. if (!DDSTools._FloatView) {
  80015. DDSTools._FloatView = new Float32Array(1);
  80016. DDSTools._Int32View = new Int32Array(DDSTools._FloatView.buffer);
  80017. }
  80018. DDSTools._FloatView[0] = value;
  80019. var x = DDSTools._Int32View[0];
  80020. var bits = (x >> 16) & 0x8000; /* Get the sign */
  80021. var m = (x >> 12) & 0x07ff; /* Keep one extra bit for rounding */
  80022. var e = (x >> 23) & 0xff; /* Using int is faster here */
  80023. /* If zero, or denormal, or exponent underflows too much for a denormal
  80024. * half, return signed zero. */
  80025. if (e < 103) {
  80026. return bits;
  80027. }
  80028. /* If NaN, return NaN. If Inf or exponent overflow, return Inf. */
  80029. if (e > 142) {
  80030. bits |= 0x7c00;
  80031. /* If exponent was 0xff and one mantissa bit was set, it means NaN,
  80032. * not Inf, so make sure we set one mantissa bit too. */
  80033. bits |= ((e == 255) ? 0 : 1) && (x & 0x007fffff);
  80034. return bits;
  80035. }
  80036. /* If exponent underflows but not too much, return a denormal */
  80037. if (e < 113) {
  80038. m |= 0x0800;
  80039. /* Extra rounding may overflow and set mantissa to 0 and exponent
  80040. * to 1, which is OK. */
  80041. bits |= (m >> (114 - e)) + ((m >> (113 - e)) & 1);
  80042. return bits;
  80043. }
  80044. bits |= ((e - 112) << 10) | (m >> 1);
  80045. bits += m & 1;
  80046. return bits;
  80047. };
  80048. DDSTools._FromHalfFloat = function (value) {
  80049. var s = (value & 0x8000) >> 15;
  80050. var e = (value & 0x7C00) >> 10;
  80051. var f = value & 0x03FF;
  80052. if (e === 0) {
  80053. return (s ? -1 : 1) * Math.pow(2, -14) * (f / Math.pow(2, 10));
  80054. }
  80055. else if (e == 0x1F) {
  80056. return f ? NaN : ((s ? -1 : 1) * Infinity);
  80057. }
  80058. return (s ? -1 : 1) * Math.pow(2, e - 15) * (1 + (f / Math.pow(2, 10)));
  80059. };
  80060. DDSTools._GetHalfFloatAsFloatRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  80061. var destArray = new Float32Array(dataLength);
  80062. var srcData = new Uint16Array(arrayBuffer, dataOffset);
  80063. var index = 0;
  80064. for (var y = 0; y < height; y++) {
  80065. for (var x = 0; x < width; x++) {
  80066. var srcPos = (x + y * width) * 4;
  80067. destArray[index] = DDSTools._FromHalfFloat(srcData[srcPos]);
  80068. destArray[index + 1] = DDSTools._FromHalfFloat(srcData[srcPos + 1]);
  80069. destArray[index + 2] = DDSTools._FromHalfFloat(srcData[srcPos + 2]);
  80070. if (DDSTools.StoreLODInAlphaChannel) {
  80071. destArray[index + 3] = lod;
  80072. }
  80073. else {
  80074. destArray[index + 3] = DDSTools._FromHalfFloat(srcData[srcPos + 3]);
  80075. }
  80076. index += 4;
  80077. }
  80078. }
  80079. return destArray;
  80080. };
  80081. DDSTools._GetHalfFloatRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  80082. if (DDSTools.StoreLODInAlphaChannel) {
  80083. var destArray = new Uint16Array(dataLength);
  80084. var srcData = new Uint16Array(arrayBuffer, dataOffset);
  80085. var index = 0;
  80086. for (var y = 0; y < height; y++) {
  80087. for (var x = 0; x < width; x++) {
  80088. var srcPos = (x + y * width) * 4;
  80089. destArray[index] = srcData[srcPos];
  80090. destArray[index + 1] = srcData[srcPos + 1];
  80091. destArray[index + 2] = srcData[srcPos + 2];
  80092. destArray[index + 3] = DDSTools._ToHalfFloat(lod);
  80093. index += 4;
  80094. }
  80095. }
  80096. return destArray;
  80097. }
  80098. return new Uint16Array(arrayBuffer, dataOffset, dataLength);
  80099. };
  80100. DDSTools._GetFloatRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  80101. if (DDSTools.StoreLODInAlphaChannel) {
  80102. var destArray = new Float32Array(dataLength);
  80103. var srcData = new Float32Array(arrayBuffer, dataOffset);
  80104. var index = 0;
  80105. for (var y = 0; y < height; y++) {
  80106. for (var x = 0; x < width; x++) {
  80107. var srcPos = (x + y * width) * 4;
  80108. destArray[index] = srcData[srcPos];
  80109. destArray[index + 1] = srcData[srcPos + 1];
  80110. destArray[index + 2] = srcData[srcPos + 2];
  80111. destArray[index + 3] = lod;
  80112. index += 4;
  80113. }
  80114. }
  80115. return destArray;
  80116. }
  80117. return new Float32Array(arrayBuffer, dataOffset, dataLength);
  80118. };
  80119. DDSTools._GetFloatAsUIntRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  80120. var destArray = new Uint8Array(dataLength);
  80121. var srcData = new Float32Array(arrayBuffer, dataOffset);
  80122. var index = 0;
  80123. for (var y = 0; y < height; y++) {
  80124. for (var x = 0; x < width; x++) {
  80125. var srcPos = (x + y * width) * 4;
  80126. destArray[index] = BABYLON.Scalar.Clamp(srcData[srcPos]) * 255;
  80127. destArray[index + 1] = BABYLON.Scalar.Clamp(srcData[srcPos + 1]) * 255;
  80128. destArray[index + 2] = BABYLON.Scalar.Clamp(srcData[srcPos + 2]) * 255;
  80129. if (DDSTools.StoreLODInAlphaChannel) {
  80130. destArray[index + 3] = lod;
  80131. }
  80132. else {
  80133. destArray[index + 3] = BABYLON.Scalar.Clamp(srcData[srcPos + 3]) * 255;
  80134. }
  80135. index += 4;
  80136. }
  80137. }
  80138. return destArray;
  80139. };
  80140. DDSTools._GetHalfFloatAsUIntRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  80141. var destArray = new Uint8Array(dataLength);
  80142. var srcData = new Uint16Array(arrayBuffer, dataOffset);
  80143. var index = 0;
  80144. for (var y = 0; y < height; y++) {
  80145. for (var x = 0; x < width; x++) {
  80146. var srcPos = (x + y * width) * 4;
  80147. destArray[index] = BABYLON.Scalar.Clamp(DDSTools._FromHalfFloat(srcData[srcPos])) * 255;
  80148. destArray[index + 1] = BABYLON.Scalar.Clamp(DDSTools._FromHalfFloat(srcData[srcPos + 1])) * 255;
  80149. destArray[index + 2] = BABYLON.Scalar.Clamp(DDSTools._FromHalfFloat(srcData[srcPos + 2])) * 255;
  80150. if (DDSTools.StoreLODInAlphaChannel) {
  80151. destArray[index + 3] = lod;
  80152. }
  80153. else {
  80154. destArray[index + 3] = BABYLON.Scalar.Clamp(DDSTools._FromHalfFloat(srcData[srcPos + 3])) * 255;
  80155. }
  80156. index += 4;
  80157. }
  80158. }
  80159. return destArray;
  80160. };
  80161. DDSTools._GetRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, rOffset, gOffset, bOffset, aOffset) {
  80162. var byteArray = new Uint8Array(dataLength);
  80163. var srcData = new Uint8Array(arrayBuffer, dataOffset);
  80164. var index = 0;
  80165. for (var y = 0; y < height; y++) {
  80166. for (var x = 0; x < width; x++) {
  80167. var srcPos = (x + y * width) * 4;
  80168. byteArray[index] = srcData[srcPos + rOffset];
  80169. byteArray[index + 1] = srcData[srcPos + gOffset];
  80170. byteArray[index + 2] = srcData[srcPos + bOffset];
  80171. byteArray[index + 3] = srcData[srcPos + aOffset];
  80172. index += 4;
  80173. }
  80174. }
  80175. return byteArray;
  80176. };
  80177. DDSTools._ExtractLongWordOrder = function (value) {
  80178. if (value === 0 || value === 255 || value === -16777216) {
  80179. return 0;
  80180. }
  80181. return 1 + DDSTools._ExtractLongWordOrder(value >> 8);
  80182. };
  80183. DDSTools._GetRGBArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, rOffset, gOffset, bOffset) {
  80184. var byteArray = new Uint8Array(dataLength);
  80185. var srcData = new Uint8Array(arrayBuffer, dataOffset);
  80186. var index = 0;
  80187. for (var y = 0; y < height; y++) {
  80188. for (var x = 0; x < width; x++) {
  80189. var srcPos = (x + y * width) * 3;
  80190. byteArray[index] = srcData[srcPos + rOffset];
  80191. byteArray[index + 1] = srcData[srcPos + gOffset];
  80192. byteArray[index + 2] = srcData[srcPos + bOffset];
  80193. index += 3;
  80194. }
  80195. }
  80196. return byteArray;
  80197. };
  80198. DDSTools._GetLuminanceArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer) {
  80199. var byteArray = new Uint8Array(dataLength);
  80200. var srcData = new Uint8Array(arrayBuffer, dataOffset);
  80201. var index = 0;
  80202. for (var y = 0; y < height; y++) {
  80203. for (var x = 0; x < width; x++) {
  80204. var srcPos = (x + y * width);
  80205. byteArray[index] = srcData[srcPos];
  80206. index++;
  80207. }
  80208. }
  80209. return byteArray;
  80210. };
  80211. DDSTools.UploadDDSLevels = function (engine, gl, arrayBuffer, info, loadMipmaps, faces, lodIndex, currentFace) {
  80212. if (lodIndex === void 0) { lodIndex = -1; }
  80213. var ext = engine.getCaps().s3tc;
  80214. var header = new Int32Array(arrayBuffer, 0, headerLengthInt);
  80215. var fourCC, width, height, dataLength = 0, dataOffset;
  80216. var byteArray, mipmapCount, mip;
  80217. var internalFormat = 0;
  80218. var format = 0;
  80219. var blockBytes = 1;
  80220. if (header[off_magic] !== DDS_MAGIC) {
  80221. BABYLON.Tools.Error("Invalid magic number in DDS header");
  80222. return;
  80223. }
  80224. if (!info.isFourCC && !info.isRGB && !info.isLuminance) {
  80225. BABYLON.Tools.Error("Unsupported format, must contain a FourCC, RGB or LUMINANCE code");
  80226. return;
  80227. }
  80228. if (info.isCompressed && !ext) {
  80229. BABYLON.Tools.Error("Compressed textures are not supported on this platform.");
  80230. return;
  80231. }
  80232. var bpp = header[off_RGBbpp];
  80233. dataOffset = header[off_size] + 4;
  80234. var computeFormats = false;
  80235. if (info.isFourCC) {
  80236. fourCC = header[off_pfFourCC];
  80237. switch (fourCC) {
  80238. case FOURCC_DXT1:
  80239. blockBytes = 8;
  80240. internalFormat = ext.COMPRESSED_RGBA_S3TC_DXT1_EXT;
  80241. break;
  80242. case FOURCC_DXT3:
  80243. blockBytes = 16;
  80244. internalFormat = ext.COMPRESSED_RGBA_S3TC_DXT3_EXT;
  80245. break;
  80246. case FOURCC_DXT5:
  80247. blockBytes = 16;
  80248. internalFormat = ext.COMPRESSED_RGBA_S3TC_DXT5_EXT;
  80249. break;
  80250. case FOURCC_D3DFMT_R16G16B16A16F:
  80251. computeFormats = true;
  80252. break;
  80253. case FOURCC_D3DFMT_R32G32B32A32F:
  80254. computeFormats = true;
  80255. break;
  80256. case FOURCC_DX10:
  80257. // There is an additionnal header so dataOffset need to be changed
  80258. dataOffset += 5 * 4; // 5 uints
  80259. var supported = false;
  80260. switch (info.dxgiFormat) {
  80261. case DXGI_FORMAT_R16G16B16A16_FLOAT:
  80262. computeFormats = true;
  80263. supported = true;
  80264. break;
  80265. case DXGI_FORMAT_B8G8R8X8_UNORM:
  80266. info.isRGB = true;
  80267. info.isFourCC = false;
  80268. bpp = 32;
  80269. supported = true;
  80270. break;
  80271. }
  80272. if (supported) {
  80273. break;
  80274. }
  80275. default:
  80276. console.error("Unsupported FourCC code:", Int32ToFourCC(fourCC));
  80277. return;
  80278. }
  80279. }
  80280. var rOffset = DDSTools._ExtractLongWordOrder(header[off_RMask]);
  80281. var gOffset = DDSTools._ExtractLongWordOrder(header[off_GMask]);
  80282. var bOffset = DDSTools._ExtractLongWordOrder(header[off_BMask]);
  80283. var aOffset = DDSTools._ExtractLongWordOrder(header[off_AMask]);
  80284. if (computeFormats) {
  80285. format = engine._getWebGLTextureType(info.textureType);
  80286. internalFormat = engine._getRGBABufferInternalSizedFormat(info.textureType);
  80287. }
  80288. mipmapCount = 1;
  80289. if (header[off_flags] & DDSD_MIPMAPCOUNT && loadMipmaps !== false) {
  80290. mipmapCount = Math.max(1, header[off_mipmapCount]);
  80291. }
  80292. for (var face = 0; face < faces; face++) {
  80293. var sampler = faces === 1 ? gl.TEXTURE_2D : (gl.TEXTURE_CUBE_MAP_POSITIVE_X + face + (currentFace ? currentFace : 0));
  80294. width = header[off_width];
  80295. height = header[off_height];
  80296. for (mip = 0; mip < mipmapCount; ++mip) {
  80297. if (lodIndex === -1 || lodIndex === mip) {
  80298. // In case of fixed LOD, if the lod has just been uploaded, early exit.
  80299. var i = (lodIndex === -1) ? mip : 0;
  80300. if (!info.isCompressed && info.isFourCC) {
  80301. dataLength = width * height * 4;
  80302. var floatArray = null;
  80303. if (engine.badOS || engine.badDesktopOS || (!engine.getCaps().textureHalfFloat && !engine.getCaps().textureFloat)) {
  80304. if (bpp === 128) {
  80305. floatArray = DDSTools._GetFloatAsUIntRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  80306. }
  80307. else if (bpp === 64) {
  80308. floatArray = DDSTools._GetHalfFloatAsUIntRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  80309. }
  80310. info.textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  80311. format = engine._getWebGLTextureType(info.textureType);
  80312. internalFormat = engine._getRGBABufferInternalSizedFormat(info.textureType);
  80313. }
  80314. else {
  80315. if (bpp === 128) {
  80316. floatArray = DDSTools._GetFloatRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  80317. }
  80318. else if (bpp === 64 && !engine.getCaps().textureHalfFloat) {
  80319. floatArray = DDSTools._GetHalfFloatAsFloatRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  80320. info.textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  80321. format = engine._getWebGLTextureType(info.textureType);
  80322. internalFormat = engine._getRGBABufferInternalSizedFormat(info.textureType);
  80323. }
  80324. else {
  80325. floatArray = DDSTools._GetHalfFloatRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  80326. }
  80327. }
  80328. if (floatArray) {
  80329. engine._uploadDataToTexture(sampler, i, internalFormat, width, height, gl.RGBA, format, floatArray);
  80330. }
  80331. }
  80332. else if (info.isRGB) {
  80333. if (bpp === 24) {
  80334. dataLength = width * height * 3;
  80335. byteArray = DDSTools._GetRGBArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, rOffset, gOffset, bOffset);
  80336. engine._uploadDataToTexture(sampler, i, gl.RGB, width, height, gl.RGB, gl.UNSIGNED_BYTE, byteArray);
  80337. }
  80338. else {
  80339. dataLength = width * height * 4;
  80340. byteArray = DDSTools._GetRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, rOffset, gOffset, bOffset, aOffset);
  80341. engine._uploadDataToTexture(sampler, i, gl.RGBA, width, height, gl.RGBA, gl.UNSIGNED_BYTE, byteArray);
  80342. }
  80343. }
  80344. else if (info.isLuminance) {
  80345. var unpackAlignment = gl.getParameter(gl.UNPACK_ALIGNMENT);
  80346. var unpaddedRowSize = width;
  80347. var paddedRowSize = Math.floor((width + unpackAlignment - 1) / unpackAlignment) * unpackAlignment;
  80348. dataLength = paddedRowSize * (height - 1) + unpaddedRowSize;
  80349. byteArray = DDSTools._GetLuminanceArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer);
  80350. engine._uploadDataToTexture(sampler, i, gl.LUMINANCE, width, height, gl.LUMINANCE, gl.UNSIGNED_BYTE, byteArray);
  80351. }
  80352. else {
  80353. dataLength = Math.max(4, width) / 4 * Math.max(4, height) / 4 * blockBytes;
  80354. byteArray = new Uint8Array(arrayBuffer, dataOffset, dataLength);
  80355. engine._uploadCompressedDataToTexture(sampler, i, internalFormat, width, height, byteArray);
  80356. }
  80357. }
  80358. dataOffset += bpp ? (width * height * (bpp / 8)) : dataLength;
  80359. width *= 0.5;
  80360. height *= 0.5;
  80361. width = Math.max(1.0, width);
  80362. height = Math.max(1.0, height);
  80363. }
  80364. if (currentFace !== undefined) {
  80365. // Loading a single face
  80366. break;
  80367. }
  80368. }
  80369. };
  80370. DDSTools.StoreLODInAlphaChannel = false;
  80371. return DDSTools;
  80372. }());
  80373. BABYLON.DDSTools = DDSTools;
  80374. })(BABYLON || (BABYLON = {}));
  80375. //# sourceMappingURL=babylon.dds.js.map
  80376. "use strict";
  80377. var BABYLON;
  80378. (function (BABYLON) {
  80379. /**
  80380. * for description see https://www.khronos.org/opengles/sdk/tools/KTX/
  80381. * for file layout see https://www.khronos.org/opengles/sdk/tools/KTX/file_format_spec/
  80382. */
  80383. var KhronosTextureContainer = /** @class */ (function () {
  80384. /**
  80385. * @param {ArrayBuffer} arrayBuffer- contents of the KTX container file
  80386. * @param {number} facesExpected- should be either 1 or 6, based whether a cube texture or or
  80387. * @param {boolean} threeDExpected- provision for indicating that data should be a 3D texture, not implemented
  80388. * @param {boolean} textureArrayExpected- provision for indicating that data should be a texture array, not implemented
  80389. */
  80390. function KhronosTextureContainer(arrayBuffer, facesExpected, threeDExpected, textureArrayExpected) {
  80391. this.arrayBuffer = arrayBuffer;
  80392. // Test that it is a ktx formatted file, based on the first 12 bytes, character representation is:
  80393. // '�', 'K', 'T', 'X', ' ', '1', '1', '�', '\r', '\n', '\x1A', '\n'
  80394. // 0xAB, 0x4B, 0x54, 0x58, 0x20, 0x31, 0x31, 0xBB, 0x0D, 0x0A, 0x1A, 0x0A
  80395. var identifier = new Uint8Array(this.arrayBuffer, 0, 12);
  80396. if (identifier[0] !== 0xAB || identifier[1] !== 0x4B || identifier[2] !== 0x54 || identifier[3] !== 0x58 || identifier[4] !== 0x20 || identifier[5] !== 0x31 ||
  80397. identifier[6] !== 0x31 || identifier[7] !== 0xBB || identifier[8] !== 0x0D || identifier[9] !== 0x0A || identifier[10] !== 0x1A || identifier[11] !== 0x0A) {
  80398. BABYLON.Tools.Error("texture missing KTX identifier");
  80399. return;
  80400. }
  80401. // load the reset of the header in native 32 bit int
  80402. var header = new Int32Array(this.arrayBuffer, 12, 13);
  80403. // determine of the remaining header values are recorded in the opposite endianness & require conversion
  80404. var oppositeEndianess = header[0] === 0x01020304;
  80405. // read all the header elements in order they exist in the file, without modification (sans endainness)
  80406. this.glType = oppositeEndianess ? this.switchEndainness(header[1]) : header[1]; // must be 0 for compressed textures
  80407. this.glTypeSize = oppositeEndianess ? this.switchEndainness(header[2]) : header[2]; // must be 1 for compressed textures
  80408. this.glFormat = oppositeEndianess ? this.switchEndainness(header[3]) : header[3]; // must be 0 for compressed textures
  80409. this.glInternalFormat = oppositeEndianess ? this.switchEndainness(header[4]) : header[4]; // the value of arg passed to gl.compressedTexImage2D(,,x,,,,)
  80410. this.glBaseInternalFormat = oppositeEndianess ? this.switchEndainness(header[5]) : header[5]; // specify GL_RGB, GL_RGBA, GL_ALPHA, etc (un-compressed only)
  80411. this.pixelWidth = oppositeEndianess ? this.switchEndainness(header[6]) : header[6]; // level 0 value of arg passed to gl.compressedTexImage2D(,,,x,,,)
  80412. this.pixelHeight = oppositeEndianess ? this.switchEndainness(header[7]) : header[7]; // level 0 value of arg passed to gl.compressedTexImage2D(,,,,x,,)
  80413. this.pixelDepth = oppositeEndianess ? this.switchEndainness(header[8]) : header[8]; // level 0 value of arg passed to gl.compressedTexImage3D(,,,,,x,,)
  80414. this.numberOfArrayElements = oppositeEndianess ? this.switchEndainness(header[9]) : header[9]; // used for texture arrays
  80415. this.numberOfFaces = oppositeEndianess ? this.switchEndainness(header[10]) : header[10]; // used for cubemap textures, should either be 1 or 6
  80416. this.numberOfMipmapLevels = oppositeEndianess ? this.switchEndainness(header[11]) : header[11]; // number of levels; disregard possibility of 0 for compressed textures
  80417. this.bytesOfKeyValueData = oppositeEndianess ? this.switchEndainness(header[12]) : header[12]; // the amount of space after the header for meta-data
  80418. // Make sure we have a compressed type. Not only reduces work, but probably better to let dev know they are not compressing.
  80419. if (this.glType !== 0) {
  80420. BABYLON.Tools.Error("only compressed formats currently supported");
  80421. return;
  80422. }
  80423. else {
  80424. // value of zero is an indication to generate mipmaps @ runtime. Not usually allowed for compressed, so disregard.
  80425. this.numberOfMipmapLevels = Math.max(1, this.numberOfMipmapLevels);
  80426. }
  80427. if (this.pixelHeight === 0 || this.pixelDepth !== 0) {
  80428. BABYLON.Tools.Error("only 2D textures currently supported");
  80429. return;
  80430. }
  80431. if (this.numberOfArrayElements !== 0) {
  80432. BABYLON.Tools.Error("texture arrays not currently supported");
  80433. return;
  80434. }
  80435. if (this.numberOfFaces !== facesExpected) {
  80436. BABYLON.Tools.Error("number of faces expected" + facesExpected + ", but found " + this.numberOfFaces);
  80437. return;
  80438. }
  80439. // we now have a completely validated file, so could use existence of loadType as success
  80440. // would need to make this more elaborate & adjust checks above to support more than one load type
  80441. this.loadType = KhronosTextureContainer.COMPRESSED_2D;
  80442. }
  80443. // not as fast hardware based, but will probably never need to use
  80444. KhronosTextureContainer.prototype.switchEndainness = function (val) {
  80445. return ((val & 0xFF) << 24)
  80446. | ((val & 0xFF00) << 8)
  80447. | ((val >> 8) & 0xFF00)
  80448. | ((val >> 24) & 0xFF);
  80449. };
  80450. /**
  80451. * It is assumed that the texture has already been created & is currently bound
  80452. */
  80453. KhronosTextureContainer.prototype.uploadLevels = function (gl, loadMipmaps) {
  80454. switch (this.loadType) {
  80455. case KhronosTextureContainer.COMPRESSED_2D:
  80456. this._upload2DCompressedLevels(gl, loadMipmaps);
  80457. break;
  80458. case KhronosTextureContainer.TEX_2D:
  80459. case KhronosTextureContainer.COMPRESSED_3D:
  80460. case KhronosTextureContainer.TEX_3D:
  80461. }
  80462. };
  80463. KhronosTextureContainer.prototype._upload2DCompressedLevels = function (gl, loadMipmaps) {
  80464. // initialize width & height for level 1
  80465. var dataOffset = KhronosTextureContainer.HEADER_LEN + this.bytesOfKeyValueData;
  80466. var width = this.pixelWidth;
  80467. var height = this.pixelHeight;
  80468. var mipmapCount = loadMipmaps ? this.numberOfMipmapLevels : 1;
  80469. for (var level = 0; level < mipmapCount; level++) {
  80470. var imageSize = new Int32Array(this.arrayBuffer, dataOffset, 1)[0]; // size per face, since not supporting array cubemaps
  80471. for (var face = 0; face < this.numberOfFaces; face++) {
  80472. var sampler = this.numberOfFaces === 1 ? gl.TEXTURE_2D : (gl.TEXTURE_CUBE_MAP_POSITIVE_X + face);
  80473. var byteArray = new Uint8Array(this.arrayBuffer, dataOffset + 4, imageSize);
  80474. gl.compressedTexImage2D(sampler, level, this.glInternalFormat, width, height, 0, byteArray);
  80475. dataOffset += imageSize + 4; // size of the image + 4 for the imageSize field
  80476. dataOffset += 3 - ((imageSize + 3) % 4); // add padding for odd sized image
  80477. }
  80478. width = Math.max(1.0, width * 0.5);
  80479. height = Math.max(1.0, height * 0.5);
  80480. }
  80481. };
  80482. KhronosTextureContainer.HEADER_LEN = 12 + (13 * 4); // identifier + header elements (not including key value meta-data pairs)
  80483. // load types
  80484. KhronosTextureContainer.COMPRESSED_2D = 0; // uses a gl.compressedTexImage2D()
  80485. KhronosTextureContainer.COMPRESSED_3D = 1; // uses a gl.compressedTexImage3D()
  80486. KhronosTextureContainer.TEX_2D = 2; // uses a gl.texImage2D()
  80487. KhronosTextureContainer.TEX_3D = 3; // uses a gl.texImage3D()
  80488. return KhronosTextureContainer;
  80489. }());
  80490. BABYLON.KhronosTextureContainer = KhronosTextureContainer;
  80491. })(BABYLON || (BABYLON = {}));
  80492. //# sourceMappingURL=babylon.khronosTextureContainer.js.map
  80493. "use strict";
  80494. var BABYLON;
  80495. (function (BABYLON) {
  80496. var Debug = /** @class */ (function () {
  80497. function Debug() {
  80498. }
  80499. Debug.AxesViewer = /** @class */ (function () {
  80500. function AxesViewer(scene, scaleLines) {
  80501. if (scaleLines === void 0) { scaleLines = 1; }
  80502. this._xline = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  80503. this._yline = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  80504. this._zline = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  80505. this.scaleLines = 1;
  80506. this.scaleLines = scaleLines;
  80507. this._xmesh = BABYLON.Mesh.CreateLines("xline", this._xline, scene, true);
  80508. this._ymesh = BABYLON.Mesh.CreateLines("yline", this._yline, scene, true);
  80509. this._zmesh = BABYLON.Mesh.CreateLines("zline", this._zline, scene, true);
  80510. this._xmesh.renderingGroupId = 2;
  80511. this._ymesh.renderingGroupId = 2;
  80512. this._zmesh.renderingGroupId = 2;
  80513. this._xmesh.material.checkReadyOnlyOnce = true;
  80514. this._xmesh.color = new BABYLON.Color3(1, 0, 0);
  80515. this._ymesh.material.checkReadyOnlyOnce = true;
  80516. this._ymesh.color = new BABYLON.Color3(0, 1, 0);
  80517. this._zmesh.material.checkReadyOnlyOnce = true;
  80518. this._zmesh.color = new BABYLON.Color3(0, 0, 1);
  80519. this.scene = scene;
  80520. }
  80521. AxesViewer.prototype.update = function (position, xaxis, yaxis, zaxis) {
  80522. var scaleLines = this.scaleLines;
  80523. if (this._xmesh) {
  80524. this._xmesh.position.copyFrom(position);
  80525. }
  80526. if (this._ymesh) {
  80527. this._ymesh.position.copyFrom(position);
  80528. }
  80529. if (this._zmesh) {
  80530. this._zmesh.position.copyFrom(position);
  80531. }
  80532. var point2 = this._xline[1];
  80533. point2.x = xaxis.x * scaleLines;
  80534. point2.y = xaxis.y * scaleLines;
  80535. point2.z = xaxis.z * scaleLines;
  80536. BABYLON.Mesh.CreateLines("", this._xline, null, false, this._xmesh);
  80537. point2 = this._yline[1];
  80538. point2.x = yaxis.x * scaleLines;
  80539. point2.y = yaxis.y * scaleLines;
  80540. point2.z = yaxis.z * scaleLines;
  80541. BABYLON.Mesh.CreateLines("", this._yline, null, false, this._ymesh);
  80542. point2 = this._zline[1];
  80543. point2.x = zaxis.x * scaleLines;
  80544. point2.y = zaxis.y * scaleLines;
  80545. point2.z = zaxis.z * scaleLines;
  80546. BABYLON.Mesh.CreateLines("", this._zline, null, false, this._zmesh);
  80547. };
  80548. AxesViewer.prototype.dispose = function () {
  80549. if (this._xmesh) {
  80550. this._xmesh.dispose();
  80551. }
  80552. if (this._ymesh) {
  80553. this._ymesh.dispose();
  80554. }
  80555. if (this._zmesh) {
  80556. this._zmesh.dispose();
  80557. }
  80558. this._xmesh = null;
  80559. this._ymesh = null;
  80560. this._zmesh = null;
  80561. this.scene = null;
  80562. };
  80563. return AxesViewer;
  80564. }());
  80565. Debug.BoneAxesViewer = /** @class */ (function (_super) {
  80566. __extends(BoneAxesViewer, _super);
  80567. function BoneAxesViewer(scene, bone, mesh, scaleLines) {
  80568. if (scaleLines === void 0) { scaleLines = 1; }
  80569. var _this = _super.call(this, scene, scaleLines) || this;
  80570. _this.pos = BABYLON.Vector3.Zero();
  80571. _this.xaxis = BABYLON.Vector3.Zero();
  80572. _this.yaxis = BABYLON.Vector3.Zero();
  80573. _this.zaxis = BABYLON.Vector3.Zero();
  80574. _this.mesh = mesh;
  80575. _this.bone = bone;
  80576. return _this;
  80577. }
  80578. BoneAxesViewer.prototype.update = function () {
  80579. if (!this.mesh || !this.bone) {
  80580. return;
  80581. }
  80582. var bone = this.bone;
  80583. bone.getAbsolutePositionToRef(this.mesh, this.pos);
  80584. bone.getDirectionToRef(BABYLON.Axis.X, this.mesh, this.xaxis);
  80585. bone.getDirectionToRef(BABYLON.Axis.Y, this.mesh, this.yaxis);
  80586. bone.getDirectionToRef(BABYLON.Axis.Z, this.mesh, this.zaxis);
  80587. _super.prototype.update.call(this, this.pos, this.xaxis, this.yaxis, this.zaxis);
  80588. };
  80589. BoneAxesViewer.prototype.dispose = function () {
  80590. if (this.mesh) {
  80591. this.mesh = null;
  80592. this.bone = null;
  80593. _super.prototype.dispose.call(this);
  80594. }
  80595. };
  80596. return BoneAxesViewer;
  80597. }(Debug.AxesViewer));
  80598. Debug.PhysicsViewer = /** @class */ (function () {
  80599. function PhysicsViewer(scene) {
  80600. this._impostors = [];
  80601. this._meshes = [];
  80602. this._numMeshes = 0;
  80603. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  80604. var physicEngine = this._scene.getPhysicsEngine();
  80605. if (physicEngine) {
  80606. this._physicsEnginePlugin = physicEngine.getPhysicsPlugin();
  80607. }
  80608. }
  80609. PhysicsViewer.prototype._updateDebugMeshes = function () {
  80610. var plugin = this._physicsEnginePlugin;
  80611. for (var i = 0; i < this._numMeshes; i++) {
  80612. var impostor = this._impostors[i];
  80613. if (!impostor) {
  80614. continue;
  80615. }
  80616. if (impostor.isDisposed) {
  80617. this.hideImpostor(this._impostors[i--]);
  80618. }
  80619. else {
  80620. var mesh = this._meshes[i];
  80621. if (mesh && plugin) {
  80622. plugin.syncMeshWithImpostor(mesh, impostor);
  80623. }
  80624. }
  80625. }
  80626. };
  80627. PhysicsViewer.prototype.showImpostor = function (impostor) {
  80628. if (!this._scene) {
  80629. return;
  80630. }
  80631. for (var i = 0; i < this._numMeshes; i++) {
  80632. if (this._impostors[i] == impostor) {
  80633. return;
  80634. }
  80635. }
  80636. var debugMesh = this._getDebugMesh(impostor, this._scene);
  80637. if (debugMesh) {
  80638. this._impostors[this._numMeshes] = impostor;
  80639. this._meshes[this._numMeshes] = debugMesh;
  80640. if (this._numMeshes === 0) {
  80641. this._renderFunction = this._updateDebugMeshes.bind(this);
  80642. this._scene.registerBeforeRender(this._renderFunction);
  80643. }
  80644. this._numMeshes++;
  80645. }
  80646. };
  80647. PhysicsViewer.prototype.hideImpostor = function (impostor) {
  80648. if (!impostor || !this._scene) {
  80649. return;
  80650. }
  80651. var removed = false;
  80652. for (var i = 0; i < this._numMeshes; i++) {
  80653. if (this._impostors[i] == impostor) {
  80654. var mesh = this._meshes[i];
  80655. if (!mesh) {
  80656. continue;
  80657. }
  80658. this._scene.removeMesh(mesh);
  80659. mesh.dispose();
  80660. this._numMeshes--;
  80661. if (this._numMeshes > 0) {
  80662. this._meshes[i] = this._meshes[this._numMeshes];
  80663. this._impostors[i] = this._impostors[this._numMeshes];
  80664. this._meshes[this._numMeshes] = null;
  80665. this._impostors[this._numMeshes] = null;
  80666. }
  80667. else {
  80668. this._meshes[0] = null;
  80669. this._impostors[0] = null;
  80670. }
  80671. removed = true;
  80672. break;
  80673. }
  80674. }
  80675. if (removed && this._numMeshes === 0) {
  80676. this._scene.unregisterBeforeRender(this._renderFunction);
  80677. }
  80678. };
  80679. PhysicsViewer.prototype._getDebugMaterial = function (scene) {
  80680. if (!this._debugMaterial) {
  80681. this._debugMaterial = new BABYLON.StandardMaterial('', scene);
  80682. this._debugMaterial.wireframe = true;
  80683. }
  80684. return this._debugMaterial;
  80685. };
  80686. PhysicsViewer.prototype._getDebugBoxMesh = function (scene) {
  80687. if (!this._debugBoxMesh) {
  80688. this._debugBoxMesh = BABYLON.MeshBuilder.CreateBox('physicsBodyBoxViewMesh', { size: 1 }, scene);
  80689. this._debugBoxMesh.renderingGroupId = 1;
  80690. this._debugBoxMesh.rotationQuaternion = BABYLON.Quaternion.Identity();
  80691. this._debugBoxMesh.material = this._getDebugMaterial(scene);
  80692. scene.removeMesh(this._debugBoxMesh);
  80693. }
  80694. return this._debugBoxMesh.createInstance('physicsBodyBoxViewInstance');
  80695. };
  80696. PhysicsViewer.prototype._getDebugSphereMesh = function (scene) {
  80697. if (!this._debugSphereMesh) {
  80698. this._debugSphereMesh = BABYLON.MeshBuilder.CreateSphere('physicsBodySphereViewMesh', { diameter: 1 }, scene);
  80699. this._debugSphereMesh.renderingGroupId = 1;
  80700. this._debugSphereMesh.rotationQuaternion = BABYLON.Quaternion.Identity();
  80701. this._debugSphereMesh.material = this._getDebugMaterial(scene);
  80702. scene.removeMesh(this._debugSphereMesh);
  80703. }
  80704. return this._debugSphereMesh.createInstance('physicsBodyBoxViewInstance');
  80705. };
  80706. PhysicsViewer.prototype._getDebugMesh = function (impostor, scene) {
  80707. var mesh = null;
  80708. if (impostor.type == BABYLON.PhysicsImpostor.BoxImpostor) {
  80709. mesh = this._getDebugBoxMesh(scene);
  80710. impostor.getBoxSizeToRef(mesh.scaling);
  80711. }
  80712. else if (impostor.type == BABYLON.PhysicsImpostor.SphereImpostor) {
  80713. mesh = this._getDebugSphereMesh(scene);
  80714. var radius = impostor.getRadius();
  80715. mesh.scaling.x = radius * 2;
  80716. mesh.scaling.y = radius * 2;
  80717. mesh.scaling.z = radius * 2;
  80718. }
  80719. return mesh;
  80720. };
  80721. PhysicsViewer.prototype.dispose = function () {
  80722. for (var i = 0; i < this._numMeshes; i++) {
  80723. this.hideImpostor(this._impostors[i]);
  80724. }
  80725. if (this._debugBoxMesh) {
  80726. this._debugBoxMesh.dispose();
  80727. }
  80728. if (this._debugSphereMesh) {
  80729. this._debugSphereMesh.dispose();
  80730. }
  80731. if (this._debugMaterial) {
  80732. this._debugMaterial.dispose();
  80733. }
  80734. this._impostors.length = 0;
  80735. this._scene = null;
  80736. this._physicsEnginePlugin = null;
  80737. };
  80738. return PhysicsViewer;
  80739. }());
  80740. Debug.SkeletonViewer = /** @class */ (function () {
  80741. function SkeletonViewer(skeleton, mesh, scene, autoUpdateBonesMatrices, renderingGroupId) {
  80742. if (autoUpdateBonesMatrices === void 0) { autoUpdateBonesMatrices = true; }
  80743. if (renderingGroupId === void 0) { renderingGroupId = 1; }
  80744. this.skeleton = skeleton;
  80745. this.mesh = mesh;
  80746. this.autoUpdateBonesMatrices = autoUpdateBonesMatrices;
  80747. this.renderingGroupId = renderingGroupId;
  80748. this.color = BABYLON.Color3.White();
  80749. this._debugLines = new Array();
  80750. this._isEnabled = false;
  80751. this._scene = scene;
  80752. this.update();
  80753. this._renderFunction = this.update.bind(this);
  80754. }
  80755. Object.defineProperty(SkeletonViewer.prototype, "isEnabled", {
  80756. get: function () {
  80757. return this._isEnabled;
  80758. },
  80759. set: function (value) {
  80760. if (this._isEnabled === value) {
  80761. return;
  80762. }
  80763. this._isEnabled = value;
  80764. if (value) {
  80765. this._scene.registerBeforeRender(this._renderFunction);
  80766. }
  80767. else {
  80768. this._scene.unregisterBeforeRender(this._renderFunction);
  80769. }
  80770. },
  80771. enumerable: true,
  80772. configurable: true
  80773. });
  80774. SkeletonViewer.prototype._getBonePosition = function (position, bone, meshMat, x, y, z) {
  80775. if (x === void 0) { x = 0; }
  80776. if (y === void 0) { y = 0; }
  80777. if (z === void 0) { z = 0; }
  80778. var tmat = BABYLON.Tmp.Matrix[0];
  80779. var parentBone = bone.getParent();
  80780. tmat.copyFrom(bone.getLocalMatrix());
  80781. if (x !== 0 || y !== 0 || z !== 0) {
  80782. var tmat2 = BABYLON.Tmp.Matrix[1];
  80783. BABYLON.Matrix.IdentityToRef(tmat2);
  80784. tmat2.m[12] = x;
  80785. tmat2.m[13] = y;
  80786. tmat2.m[14] = z;
  80787. tmat2.multiplyToRef(tmat, tmat);
  80788. }
  80789. if (parentBone) {
  80790. tmat.multiplyToRef(parentBone.getAbsoluteTransform(), tmat);
  80791. }
  80792. tmat.multiplyToRef(meshMat, tmat);
  80793. position.x = tmat.m[12];
  80794. position.y = tmat.m[13];
  80795. position.z = tmat.m[14];
  80796. };
  80797. SkeletonViewer.prototype._getLinesForBonesWithLength = function (bones, meshMat) {
  80798. var len = bones.length;
  80799. var meshPos = this.mesh.position;
  80800. for (var i = 0; i < len; i++) {
  80801. var bone = bones[i];
  80802. var points = this._debugLines[i];
  80803. if (!points) {
  80804. points = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  80805. this._debugLines[i] = points;
  80806. }
  80807. this._getBonePosition(points[0], bone, meshMat);
  80808. this._getBonePosition(points[1], bone, meshMat, 0, bone.length, 0);
  80809. points[0].subtractInPlace(meshPos);
  80810. points[1].subtractInPlace(meshPos);
  80811. }
  80812. };
  80813. SkeletonViewer.prototype._getLinesForBonesNoLength = function (bones, meshMat) {
  80814. var len = bones.length;
  80815. var boneNum = 0;
  80816. var meshPos = this.mesh.position;
  80817. for (var i = len - 1; i >= 0; i--) {
  80818. var childBone = bones[i];
  80819. var parentBone = childBone.getParent();
  80820. if (!parentBone) {
  80821. continue;
  80822. }
  80823. var points = this._debugLines[boneNum];
  80824. if (!points) {
  80825. points = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  80826. this._debugLines[boneNum] = points;
  80827. }
  80828. childBone.getAbsolutePositionToRef(this.mesh, points[0]);
  80829. parentBone.getAbsolutePositionToRef(this.mesh, points[1]);
  80830. points[0].subtractInPlace(meshPos);
  80831. points[1].subtractInPlace(meshPos);
  80832. boneNum++;
  80833. }
  80834. };
  80835. SkeletonViewer.prototype.update = function () {
  80836. if (this.autoUpdateBonesMatrices) {
  80837. this.skeleton.computeAbsoluteTransforms();
  80838. }
  80839. if (this.skeleton.bones[0].length === undefined) {
  80840. this._getLinesForBonesNoLength(this.skeleton.bones, this.mesh.getWorldMatrix());
  80841. }
  80842. else {
  80843. this._getLinesForBonesWithLength(this.skeleton.bones, this.mesh.getWorldMatrix());
  80844. }
  80845. if (!this._debugMesh) {
  80846. this._debugMesh = BABYLON.MeshBuilder.CreateLineSystem("", { lines: this._debugLines, updatable: true, instance: null }, this._scene);
  80847. this._debugMesh.renderingGroupId = this.renderingGroupId;
  80848. }
  80849. else {
  80850. BABYLON.MeshBuilder.CreateLineSystem("", { lines: this._debugLines, updatable: true, instance: this._debugMesh }, this._scene);
  80851. }
  80852. this._debugMesh.position.copyFrom(this.mesh.position);
  80853. this._debugMesh.color = this.color;
  80854. };
  80855. SkeletonViewer.prototype.dispose = function () {
  80856. if (this._debugMesh) {
  80857. this.isEnabled = false;
  80858. this._debugMesh.dispose();
  80859. this._debugMesh = null;
  80860. }
  80861. };
  80862. return SkeletonViewer;
  80863. }());
  80864. return Debug;
  80865. }());
  80866. BABYLON.Debug = Debug;
  80867. })(BABYLON || (BABYLON = {}));
  80868. //# sourceMappingURL=babylon.debugModules.js.map
  80869. "use strict";
  80870. var BABYLON;
  80871. (function (BABYLON) {
  80872. var RayHelper = /** @class */ (function () {
  80873. function RayHelper(ray) {
  80874. this.ray = ray;
  80875. }
  80876. RayHelper.CreateAndShow = function (ray, scene, color) {
  80877. var helper = new RayHelper(ray);
  80878. helper.show(scene, color);
  80879. return helper;
  80880. };
  80881. RayHelper.prototype.show = function (scene, color) {
  80882. if (!this._renderFunction && this.ray) {
  80883. var ray = this.ray;
  80884. this._renderFunction = this._render.bind(this);
  80885. this._scene = scene;
  80886. this._renderPoints = [ray.origin, ray.origin.add(ray.direction.scale(ray.length))];
  80887. this._renderLine = BABYLON.Mesh.CreateLines("ray", this._renderPoints, scene, true);
  80888. if (this._renderFunction) {
  80889. this._scene.registerBeforeRender(this._renderFunction);
  80890. }
  80891. }
  80892. if (color && this._renderLine) {
  80893. this._renderLine.color.copyFrom(color);
  80894. }
  80895. };
  80896. RayHelper.prototype.hide = function () {
  80897. if (this._renderFunction && this._scene) {
  80898. this._scene.unregisterBeforeRender(this._renderFunction);
  80899. this._scene = null;
  80900. this._renderFunction = null;
  80901. if (this._renderLine) {
  80902. this._renderLine.dispose();
  80903. this._renderLine = null;
  80904. }
  80905. this._renderPoints = [];
  80906. }
  80907. };
  80908. RayHelper.prototype._render = function () {
  80909. var ray = this.ray;
  80910. if (!ray) {
  80911. return;
  80912. }
  80913. var point = this._renderPoints[1];
  80914. var len = Math.min(ray.length, 1000000);
  80915. point.copyFrom(ray.direction);
  80916. point.scaleInPlace(len);
  80917. point.addInPlace(ray.origin);
  80918. BABYLON.Mesh.CreateLines("ray", this._renderPoints, this._scene, true, this._renderLine);
  80919. };
  80920. RayHelper.prototype.attachToMesh = function (mesh, meshSpaceDirection, meshSpaceOrigin, length) {
  80921. this._attachedToMesh = mesh;
  80922. var ray = this.ray;
  80923. if (!ray) {
  80924. return;
  80925. }
  80926. if (!ray.direction) {
  80927. ray.direction = BABYLON.Vector3.Zero();
  80928. }
  80929. if (!ray.origin) {
  80930. ray.origin = BABYLON.Vector3.Zero();
  80931. }
  80932. if (length) {
  80933. ray.length = length;
  80934. }
  80935. if (!meshSpaceOrigin) {
  80936. meshSpaceOrigin = BABYLON.Vector3.Zero();
  80937. }
  80938. if (!meshSpaceDirection) {
  80939. // -1 so that this will work with Mesh.lookAt
  80940. meshSpaceDirection = new BABYLON.Vector3(0, 0, -1);
  80941. }
  80942. if (!this._meshSpaceDirection) {
  80943. this._meshSpaceDirection = meshSpaceDirection.clone();
  80944. this._meshSpaceOrigin = meshSpaceOrigin.clone();
  80945. }
  80946. else {
  80947. this._meshSpaceDirection.copyFrom(meshSpaceDirection);
  80948. this._meshSpaceOrigin.copyFrom(meshSpaceOrigin);
  80949. }
  80950. if (!this._updateToMeshFunction) {
  80951. this._updateToMeshFunction = this._updateToMesh.bind(this);
  80952. this._attachedToMesh.getScene().registerBeforeRender(this._updateToMeshFunction);
  80953. }
  80954. this._updateToMesh();
  80955. };
  80956. RayHelper.prototype.detachFromMesh = function () {
  80957. if (this._attachedToMesh) {
  80958. if (this._updateToMeshFunction) {
  80959. this._attachedToMesh.getScene().unregisterBeforeRender(this._updateToMeshFunction);
  80960. }
  80961. this._attachedToMesh = null;
  80962. this._updateToMeshFunction = null;
  80963. }
  80964. };
  80965. RayHelper.prototype._updateToMesh = function () {
  80966. var ray = this.ray;
  80967. if (!this._attachedToMesh || !ray) {
  80968. return;
  80969. }
  80970. if (this._attachedToMesh._isDisposed) {
  80971. this.detachFromMesh();
  80972. return;
  80973. }
  80974. this._attachedToMesh.getDirectionToRef(this._meshSpaceDirection, ray.direction);
  80975. BABYLON.Vector3.TransformCoordinatesToRef(this._meshSpaceOrigin, this._attachedToMesh.getWorldMatrix(), ray.origin);
  80976. };
  80977. RayHelper.prototype.dispose = function () {
  80978. this.hide();
  80979. this.detachFromMesh();
  80980. this.ray = null;
  80981. };
  80982. return RayHelper;
  80983. }());
  80984. BABYLON.RayHelper = RayHelper;
  80985. })(BABYLON || (BABYLON = {}));
  80986. //# sourceMappingURL=babylon.rayHelper.js.map
  80987. "use strict";
  80988. var BABYLON;
  80989. (function (BABYLON) {
  80990. // load the inspector using require, if not present in the global namespace.
  80991. var DebugLayer = /** @class */ (function () {
  80992. function DebugLayer(scene) {
  80993. this.BJSINSPECTOR = typeof INSPECTOR !== 'undefined' ? INSPECTOR : undefined;
  80994. this._scene = scene;
  80995. // load inspector using require, if it doesn't exist on the global namespace.
  80996. }
  80997. /** Creates the inspector window. */
  80998. DebugLayer.prototype._createInspector = function (config) {
  80999. if (config === void 0) { config = {}; }
  81000. var popup = config.popup || false;
  81001. var initialTab = config.initialTab || 0;
  81002. var parentElement = config.parentElement || null;
  81003. if (!this._inspector) {
  81004. this.BJSINSPECTOR = this.BJSINSPECTOR || typeof INSPECTOR !== 'undefined' ? INSPECTOR : undefined;
  81005. this._inspector = new this.BJSINSPECTOR.Inspector(this._scene, popup, initialTab, parentElement, config.newColors);
  81006. } // else nothing to do,; instance is already existing
  81007. };
  81008. DebugLayer.prototype.isVisible = function () {
  81009. if (!this._inspector) {
  81010. return false;
  81011. }
  81012. return true;
  81013. };
  81014. DebugLayer.prototype.hide = function () {
  81015. if (this._inspector) {
  81016. try {
  81017. this._inspector.dispose();
  81018. }
  81019. catch (e) {
  81020. // If the inspector has been removed directly from the inspector tool
  81021. }
  81022. this._inspector = null;
  81023. }
  81024. };
  81025. DebugLayer.prototype.show = function (config) {
  81026. if (config === void 0) { config = {}; }
  81027. if (typeof this.BJSINSPECTOR == 'undefined') {
  81028. // Load inspector and add it to the DOM
  81029. BABYLON.Tools.LoadScript(DebugLayer.InspectorURL, this._createInspector.bind(this, config));
  81030. }
  81031. else {
  81032. // Otherwise creates the inspector
  81033. this._createInspector(config);
  81034. }
  81035. };
  81036. DebugLayer.InspectorURL = 'https://preview.babylonjs.com/inspector/babylon.inspector.bundle.js';
  81037. return DebugLayer;
  81038. }());
  81039. BABYLON.DebugLayer = DebugLayer;
  81040. })(BABYLON || (BABYLON = {}));
  81041. //# sourceMappingURL=babylon.debugLayer.js.map
  81042. "use strict";
  81043. var BABYLON;
  81044. (function (BABYLON) {
  81045. var BoundingBoxRenderer = /** @class */ (function () {
  81046. function BoundingBoxRenderer(scene) {
  81047. this.frontColor = new BABYLON.Color3(1, 1, 1);
  81048. this.backColor = new BABYLON.Color3(0.1, 0.1, 0.1);
  81049. this.showBackLines = true;
  81050. this.renderList = new BABYLON.SmartArray(32);
  81051. this._vertexBuffers = {};
  81052. this._scene = scene;
  81053. }
  81054. BoundingBoxRenderer.prototype._prepareRessources = function () {
  81055. if (this._colorShader) {
  81056. return;
  81057. }
  81058. this._colorShader = new BABYLON.ShaderMaterial("colorShader", this._scene, "color", {
  81059. attributes: [BABYLON.VertexBuffer.PositionKind],
  81060. uniforms: ["world", "viewProjection", "color"]
  81061. });
  81062. var engine = this._scene.getEngine();
  81063. var boxdata = BABYLON.VertexData.CreateBox({ size: 1.0 });
  81064. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(engine, boxdata.positions, BABYLON.VertexBuffer.PositionKind, false);
  81065. this._createIndexBuffer();
  81066. };
  81067. BoundingBoxRenderer.prototype._createIndexBuffer = function () {
  81068. var engine = this._scene.getEngine();
  81069. 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]);
  81070. };
  81071. BoundingBoxRenderer.prototype._rebuild = function () {
  81072. var vb = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  81073. if (vb) {
  81074. vb._rebuild();
  81075. }
  81076. this._createIndexBuffer();
  81077. };
  81078. BoundingBoxRenderer.prototype.reset = function () {
  81079. this.renderList.reset();
  81080. };
  81081. BoundingBoxRenderer.prototype.render = function () {
  81082. if (this.renderList.length === 0) {
  81083. return;
  81084. }
  81085. this._prepareRessources();
  81086. if (!this._colorShader.isReady()) {
  81087. return;
  81088. }
  81089. var engine = this._scene.getEngine();
  81090. engine.setDepthWrite(false);
  81091. this._colorShader._preBind();
  81092. for (var boundingBoxIndex = 0; boundingBoxIndex < this.renderList.length; boundingBoxIndex++) {
  81093. var boundingBox = this.renderList.data[boundingBoxIndex];
  81094. var min = boundingBox.minimum;
  81095. var max = boundingBox.maximum;
  81096. var diff = max.subtract(min);
  81097. var median = min.add(diff.scale(0.5));
  81098. var worldMatrix = BABYLON.Matrix.Scaling(diff.x, diff.y, diff.z)
  81099. .multiply(BABYLON.Matrix.Translation(median.x, median.y, median.z))
  81100. .multiply(boundingBox.getWorldMatrix());
  81101. // VBOs
  81102. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._colorShader.getEffect());
  81103. if (this.showBackLines) {
  81104. // Back
  81105. engine.setDepthFunctionToGreaterOrEqual();
  81106. this._scene.resetCachedMaterial();
  81107. this._colorShader.setColor4("color", this.backColor.toColor4());
  81108. this._colorShader.bind(worldMatrix);
  81109. // Draw order
  81110. engine.drawElementsType(BABYLON.Material.LineListDrawMode, 0, 24);
  81111. }
  81112. // Front
  81113. engine.setDepthFunctionToLess();
  81114. this._scene.resetCachedMaterial();
  81115. this._colorShader.setColor4("color", this.frontColor.toColor4());
  81116. this._colorShader.bind(worldMatrix);
  81117. // Draw order
  81118. engine.drawElementsType(BABYLON.Material.LineListDrawMode, 0, 24);
  81119. }
  81120. this._colorShader.unbind();
  81121. engine.setDepthFunctionToLessOrEqual();
  81122. engine.setDepthWrite(true);
  81123. };
  81124. BoundingBoxRenderer.prototype.renderOcclusionBoundingBox = function (mesh) {
  81125. this._prepareRessources();
  81126. if (!this._colorShader.isReady() || !mesh._boundingInfo) {
  81127. return;
  81128. }
  81129. var engine = this._scene.getEngine();
  81130. engine.setDepthWrite(false);
  81131. engine.setColorWrite(false);
  81132. this._colorShader._preBind();
  81133. var boundingBox = mesh._boundingInfo.boundingBox;
  81134. var min = boundingBox.minimum;
  81135. var max = boundingBox.maximum;
  81136. var diff = max.subtract(min);
  81137. var median = min.add(diff.scale(0.5));
  81138. var worldMatrix = BABYLON.Matrix.Scaling(diff.x, diff.y, diff.z)
  81139. .multiply(BABYLON.Matrix.Translation(median.x, median.y, median.z))
  81140. .multiply(boundingBox.getWorldMatrix());
  81141. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._colorShader.getEffect());
  81142. engine.setDepthFunctionToLess();
  81143. this._scene.resetCachedMaterial();
  81144. this._colorShader.bind(worldMatrix);
  81145. engine.drawElementsType(BABYLON.Material.LineListDrawMode, 0, 24);
  81146. this._colorShader.unbind();
  81147. engine.setDepthFunctionToLessOrEqual();
  81148. engine.setDepthWrite(true);
  81149. engine.setColorWrite(true);
  81150. };
  81151. BoundingBoxRenderer.prototype.dispose = function () {
  81152. if (!this._colorShader) {
  81153. return;
  81154. }
  81155. this.renderList.dispose();
  81156. this._colorShader.dispose();
  81157. var buffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  81158. if (buffer) {
  81159. buffer.dispose();
  81160. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  81161. }
  81162. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  81163. };
  81164. return BoundingBoxRenderer;
  81165. }());
  81166. BABYLON.BoundingBoxRenderer = BoundingBoxRenderer;
  81167. })(BABYLON || (BABYLON = {}));
  81168. //# sourceMappingURL=babylon.boundingBoxRenderer.js.map
  81169. "use strict";
  81170. var BABYLON;
  81171. (function (BABYLON) {
  81172. var MorphTarget = /** @class */ (function () {
  81173. function MorphTarget(name, influence) {
  81174. if (influence === void 0) { influence = 0; }
  81175. this.name = name;
  81176. this.animations = new Array();
  81177. this._positions = null;
  81178. this._normals = null;
  81179. this._tangents = null;
  81180. this.onInfluenceChanged = new BABYLON.Observable();
  81181. this.influence = influence;
  81182. }
  81183. Object.defineProperty(MorphTarget.prototype, "influence", {
  81184. get: function () {
  81185. return this._influence;
  81186. },
  81187. set: function (influence) {
  81188. if (this._influence === influence) {
  81189. return;
  81190. }
  81191. var previous = this._influence;
  81192. this._influence = influence;
  81193. if (this.onInfluenceChanged.hasObservers) {
  81194. this.onInfluenceChanged.notifyObservers(previous === 0 || influence === 0);
  81195. }
  81196. },
  81197. enumerable: true,
  81198. configurable: true
  81199. });
  81200. Object.defineProperty(MorphTarget.prototype, "hasPositions", {
  81201. get: function () {
  81202. return !!this._positions;
  81203. },
  81204. enumerable: true,
  81205. configurable: true
  81206. });
  81207. Object.defineProperty(MorphTarget.prototype, "hasNormals", {
  81208. get: function () {
  81209. return !!this._normals;
  81210. },
  81211. enumerable: true,
  81212. configurable: true
  81213. });
  81214. Object.defineProperty(MorphTarget.prototype, "hasTangents", {
  81215. get: function () {
  81216. return !!this._tangents;
  81217. },
  81218. enumerable: true,
  81219. configurable: true
  81220. });
  81221. MorphTarget.prototype.setPositions = function (data) {
  81222. this._positions = data;
  81223. };
  81224. MorphTarget.prototype.getPositions = function () {
  81225. return this._positions;
  81226. };
  81227. MorphTarget.prototype.setNormals = function (data) {
  81228. this._normals = data;
  81229. };
  81230. MorphTarget.prototype.getNormals = function () {
  81231. return this._normals;
  81232. };
  81233. MorphTarget.prototype.setTangents = function (data) {
  81234. this._tangents = data;
  81235. };
  81236. MorphTarget.prototype.getTangents = function () {
  81237. return this._tangents;
  81238. };
  81239. /**
  81240. * Serializes the current target into a Serialization object.
  81241. * Returns the serialized object.
  81242. */
  81243. MorphTarget.prototype.serialize = function () {
  81244. var serializationObject = {};
  81245. serializationObject.name = this.name;
  81246. serializationObject.influence = this.influence;
  81247. serializationObject.positions = Array.prototype.slice.call(this.getPositions());
  81248. if (this.hasNormals) {
  81249. serializationObject.normals = Array.prototype.slice.call(this.getNormals());
  81250. }
  81251. if (this.hasTangents) {
  81252. serializationObject.tangents = Array.prototype.slice.call(this.getTangents());
  81253. }
  81254. // Animations
  81255. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  81256. return serializationObject;
  81257. };
  81258. // Statics
  81259. MorphTarget.Parse = function (serializationObject) {
  81260. var result = new MorphTarget(serializationObject.name, serializationObject.influence);
  81261. result.setPositions(serializationObject.positions);
  81262. if (serializationObject.normals) {
  81263. result.setNormals(serializationObject.normals);
  81264. }
  81265. if (serializationObject.tangents) {
  81266. result.setTangents(serializationObject.tangents);
  81267. }
  81268. // Animations
  81269. if (serializationObject.animations) {
  81270. for (var animationIndex = 0; animationIndex < serializationObject.animations.length; animationIndex++) {
  81271. var parsedAnimation = serializationObject.animations[animationIndex];
  81272. result.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  81273. }
  81274. }
  81275. return result;
  81276. };
  81277. MorphTarget.FromMesh = function (mesh, name, influence) {
  81278. if (!name) {
  81279. name = mesh.name;
  81280. }
  81281. var result = new MorphTarget(name, influence);
  81282. result.setPositions(mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind));
  81283. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  81284. result.setNormals(mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind));
  81285. }
  81286. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind)) {
  81287. result.setTangents(mesh.getVerticesData(BABYLON.VertexBuffer.TangentKind));
  81288. }
  81289. return result;
  81290. };
  81291. return MorphTarget;
  81292. }());
  81293. BABYLON.MorphTarget = MorphTarget;
  81294. })(BABYLON || (BABYLON = {}));
  81295. //# sourceMappingURL=babylon.morphTarget.js.map
  81296. "use strict";
  81297. var BABYLON;
  81298. (function (BABYLON) {
  81299. var MorphTargetManager = /** @class */ (function () {
  81300. function MorphTargetManager(scene) {
  81301. if (scene === void 0) { scene = null; }
  81302. this._targets = new Array();
  81303. this._targetObservable = new Array();
  81304. this._activeTargets = new BABYLON.SmartArray(16);
  81305. this._supportsNormals = false;
  81306. this._supportsTangents = false;
  81307. this._vertexCount = 0;
  81308. this._uniqueId = 0;
  81309. this._tempInfluences = new Array();
  81310. if (!scene) {
  81311. scene = BABYLON.Engine.LastCreatedScene;
  81312. }
  81313. this._scene = scene;
  81314. if (this._scene) {
  81315. this._scene.morphTargetManagers.push(this);
  81316. this._uniqueId = this._scene.getUniqueId();
  81317. }
  81318. }
  81319. Object.defineProperty(MorphTargetManager.prototype, "uniqueId", {
  81320. get: function () {
  81321. return this._uniqueId;
  81322. },
  81323. enumerable: true,
  81324. configurable: true
  81325. });
  81326. Object.defineProperty(MorphTargetManager.prototype, "vertexCount", {
  81327. get: function () {
  81328. return this._vertexCount;
  81329. },
  81330. enumerable: true,
  81331. configurable: true
  81332. });
  81333. Object.defineProperty(MorphTargetManager.prototype, "supportsNormals", {
  81334. get: function () {
  81335. return this._supportsNormals;
  81336. },
  81337. enumerable: true,
  81338. configurable: true
  81339. });
  81340. Object.defineProperty(MorphTargetManager.prototype, "supportsTangents", {
  81341. get: function () {
  81342. return this._supportsTangents;
  81343. },
  81344. enumerable: true,
  81345. configurable: true
  81346. });
  81347. Object.defineProperty(MorphTargetManager.prototype, "numTargets", {
  81348. get: function () {
  81349. return this._targets.length;
  81350. },
  81351. enumerable: true,
  81352. configurable: true
  81353. });
  81354. Object.defineProperty(MorphTargetManager.prototype, "numInfluencers", {
  81355. get: function () {
  81356. return this._activeTargets.length;
  81357. },
  81358. enumerable: true,
  81359. configurable: true
  81360. });
  81361. Object.defineProperty(MorphTargetManager.prototype, "influences", {
  81362. get: function () {
  81363. return this._influences;
  81364. },
  81365. enumerable: true,
  81366. configurable: true
  81367. });
  81368. MorphTargetManager.prototype.getActiveTarget = function (index) {
  81369. return this._activeTargets.data[index];
  81370. };
  81371. MorphTargetManager.prototype.getTarget = function (index) {
  81372. return this._targets[index];
  81373. };
  81374. MorphTargetManager.prototype.addTarget = function (target) {
  81375. var _this = this;
  81376. this._targets.push(target);
  81377. this._targetObservable.push(target.onInfluenceChanged.add(function (needUpdate) {
  81378. _this._syncActiveTargets(needUpdate);
  81379. }));
  81380. this._syncActiveTargets(true);
  81381. };
  81382. MorphTargetManager.prototype.removeTarget = function (target) {
  81383. var index = this._targets.indexOf(target);
  81384. if (index >= 0) {
  81385. this._targets.splice(index, 1);
  81386. target.onInfluenceChanged.remove(this._targetObservable.splice(index, 1)[0]);
  81387. this._syncActiveTargets(true);
  81388. }
  81389. };
  81390. /**
  81391. * Serializes the current manager into a Serialization object.
  81392. * Returns the serialized object.
  81393. */
  81394. MorphTargetManager.prototype.serialize = function () {
  81395. var serializationObject = {};
  81396. serializationObject.id = this.uniqueId;
  81397. serializationObject.targets = [];
  81398. for (var _i = 0, _a = this._targets; _i < _a.length; _i++) {
  81399. var target = _a[_i];
  81400. serializationObject.targets.push(target.serialize());
  81401. }
  81402. return serializationObject;
  81403. };
  81404. MorphTargetManager.prototype._syncActiveTargets = function (needUpdate) {
  81405. var influenceCount = 0;
  81406. this._activeTargets.reset();
  81407. this._supportsNormals = true;
  81408. this._supportsTangents = true;
  81409. this._vertexCount = 0;
  81410. for (var _i = 0, _a = this._targets; _i < _a.length; _i++) {
  81411. var target = _a[_i];
  81412. this._activeTargets.push(target);
  81413. this._tempInfluences[influenceCount++] = target.influence;
  81414. var positions = target.getPositions();
  81415. if (positions) {
  81416. this._supportsNormals = this._supportsNormals && target.hasNormals;
  81417. this._supportsTangents = this._supportsTangents && target.hasTangents;
  81418. var vertexCount = positions.length / 3;
  81419. if (this._vertexCount === 0) {
  81420. this._vertexCount = vertexCount;
  81421. }
  81422. else if (this._vertexCount !== vertexCount) {
  81423. BABYLON.Tools.Error("Incompatible target. Targets must all have the same vertices count.");
  81424. return;
  81425. }
  81426. }
  81427. }
  81428. if (!this._influences || this._influences.length !== influenceCount) {
  81429. this._influences = new Float32Array(influenceCount);
  81430. }
  81431. for (var index = 0; index < influenceCount; index++) {
  81432. this._influences[index] = this._tempInfluences[index];
  81433. }
  81434. if (needUpdate && this._scene) {
  81435. // Flag meshes as dirty to resync with the active targets
  81436. for (var _b = 0, _c = this._scene.meshes; _b < _c.length; _b++) {
  81437. var mesh = _c[_b];
  81438. if (mesh.morphTargetManager === this) {
  81439. mesh._syncGeometryWithMorphTargetManager();
  81440. }
  81441. }
  81442. }
  81443. };
  81444. // Statics
  81445. MorphTargetManager.Parse = function (serializationObject, scene) {
  81446. var result = new MorphTargetManager(scene);
  81447. result._uniqueId = serializationObject.id;
  81448. for (var _i = 0, _a = serializationObject.targets; _i < _a.length; _i++) {
  81449. var targetData = _a[_i];
  81450. result.addTarget(BABYLON.MorphTarget.Parse(targetData));
  81451. }
  81452. return result;
  81453. };
  81454. return MorphTargetManager;
  81455. }());
  81456. BABYLON.MorphTargetManager = MorphTargetManager;
  81457. })(BABYLON || (BABYLON = {}));
  81458. //# sourceMappingURL=babylon.morphTargetManager.js.map
  81459. "use strict";
  81460. var BABYLON;
  81461. (function (BABYLON) {
  81462. var Octree = /** @class */ (function () {
  81463. function Octree(creationFunc, maxBlockCapacity, maxDepth) {
  81464. if (maxDepth === void 0) { maxDepth = 2; }
  81465. this.maxDepth = maxDepth;
  81466. this.dynamicContent = new Array();
  81467. this._maxBlockCapacity = maxBlockCapacity || 64;
  81468. this._selectionContent = new BABYLON.SmartArrayNoDuplicate(1024);
  81469. this._creationFunc = creationFunc;
  81470. }
  81471. // Methods
  81472. Octree.prototype.update = function (worldMin, worldMax, entries) {
  81473. Octree._CreateBlocks(worldMin, worldMax, entries, this._maxBlockCapacity, 0, this.maxDepth, this, this._creationFunc);
  81474. };
  81475. Octree.prototype.addMesh = function (entry) {
  81476. for (var index = 0; index < this.blocks.length; index++) {
  81477. var block = this.blocks[index];
  81478. block.addEntry(entry);
  81479. }
  81480. };
  81481. Octree.prototype.select = function (frustumPlanes, allowDuplicate) {
  81482. this._selectionContent.reset();
  81483. for (var index = 0; index < this.blocks.length; index++) {
  81484. var block = this.blocks[index];
  81485. block.select(frustumPlanes, this._selectionContent, allowDuplicate);
  81486. }
  81487. if (allowDuplicate) {
  81488. this._selectionContent.concat(this.dynamicContent);
  81489. }
  81490. else {
  81491. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  81492. }
  81493. return this._selectionContent;
  81494. };
  81495. Octree.prototype.intersects = function (sphereCenter, sphereRadius, allowDuplicate) {
  81496. this._selectionContent.reset();
  81497. for (var index = 0; index < this.blocks.length; index++) {
  81498. var block = this.blocks[index];
  81499. block.intersects(sphereCenter, sphereRadius, this._selectionContent, allowDuplicate);
  81500. }
  81501. if (allowDuplicate) {
  81502. this._selectionContent.concat(this.dynamicContent);
  81503. }
  81504. else {
  81505. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  81506. }
  81507. return this._selectionContent;
  81508. };
  81509. Octree.prototype.intersectsRay = function (ray) {
  81510. this._selectionContent.reset();
  81511. for (var index = 0; index < this.blocks.length; index++) {
  81512. var block = this.blocks[index];
  81513. block.intersectsRay(ray, this._selectionContent);
  81514. }
  81515. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  81516. return this._selectionContent;
  81517. };
  81518. Octree._CreateBlocks = function (worldMin, worldMax, entries, maxBlockCapacity, currentDepth, maxDepth, target, creationFunc) {
  81519. target.blocks = new Array();
  81520. var blockSize = new BABYLON.Vector3((worldMax.x - worldMin.x) / 2, (worldMax.y - worldMin.y) / 2, (worldMax.z - worldMin.z) / 2);
  81521. // Segmenting space
  81522. for (var x = 0; x < 2; x++) {
  81523. for (var y = 0; y < 2; y++) {
  81524. for (var z = 0; z < 2; z++) {
  81525. var localMin = worldMin.add(blockSize.multiplyByFloats(x, y, z));
  81526. var localMax = worldMin.add(blockSize.multiplyByFloats(x + 1, y + 1, z + 1));
  81527. var block = new BABYLON.OctreeBlock(localMin, localMax, maxBlockCapacity, currentDepth + 1, maxDepth, creationFunc);
  81528. block.addEntries(entries);
  81529. target.blocks.push(block);
  81530. }
  81531. }
  81532. }
  81533. };
  81534. Octree.CreationFuncForMeshes = function (entry, block) {
  81535. var boundingInfo = entry.getBoundingInfo();
  81536. if (!entry.isBlocked && boundingInfo.boundingBox.intersectsMinMax(block.minPoint, block.maxPoint)) {
  81537. block.entries.push(entry);
  81538. }
  81539. };
  81540. Octree.CreationFuncForSubMeshes = function (entry, block) {
  81541. var boundingInfo = entry.getBoundingInfo();
  81542. if (boundingInfo.boundingBox.intersectsMinMax(block.minPoint, block.maxPoint)) {
  81543. block.entries.push(entry);
  81544. }
  81545. };
  81546. return Octree;
  81547. }());
  81548. BABYLON.Octree = Octree;
  81549. })(BABYLON || (BABYLON = {}));
  81550. //# sourceMappingURL=babylon.octree.js.map
  81551. "use strict";
  81552. var BABYLON;
  81553. (function (BABYLON) {
  81554. var OctreeBlock = /** @class */ (function () {
  81555. function OctreeBlock(minPoint, maxPoint, capacity, depth, maxDepth, creationFunc) {
  81556. this.entries = new Array();
  81557. this._boundingVectors = new Array();
  81558. this._capacity = capacity;
  81559. this._depth = depth;
  81560. this._maxDepth = maxDepth;
  81561. this._creationFunc = creationFunc;
  81562. this._minPoint = minPoint;
  81563. this._maxPoint = maxPoint;
  81564. this._boundingVectors.push(minPoint.clone());
  81565. this._boundingVectors.push(maxPoint.clone());
  81566. this._boundingVectors.push(minPoint.clone());
  81567. this._boundingVectors[2].x = maxPoint.x;
  81568. this._boundingVectors.push(minPoint.clone());
  81569. this._boundingVectors[3].y = maxPoint.y;
  81570. this._boundingVectors.push(minPoint.clone());
  81571. this._boundingVectors[4].z = maxPoint.z;
  81572. this._boundingVectors.push(maxPoint.clone());
  81573. this._boundingVectors[5].z = minPoint.z;
  81574. this._boundingVectors.push(maxPoint.clone());
  81575. this._boundingVectors[6].x = minPoint.x;
  81576. this._boundingVectors.push(maxPoint.clone());
  81577. this._boundingVectors[7].y = minPoint.y;
  81578. }
  81579. Object.defineProperty(OctreeBlock.prototype, "capacity", {
  81580. // Property
  81581. get: function () {
  81582. return this._capacity;
  81583. },
  81584. enumerable: true,
  81585. configurable: true
  81586. });
  81587. Object.defineProperty(OctreeBlock.prototype, "minPoint", {
  81588. get: function () {
  81589. return this._minPoint;
  81590. },
  81591. enumerable: true,
  81592. configurable: true
  81593. });
  81594. Object.defineProperty(OctreeBlock.prototype, "maxPoint", {
  81595. get: function () {
  81596. return this._maxPoint;
  81597. },
  81598. enumerable: true,
  81599. configurable: true
  81600. });
  81601. // Methods
  81602. OctreeBlock.prototype.addEntry = function (entry) {
  81603. if (this.blocks) {
  81604. for (var index = 0; index < this.blocks.length; index++) {
  81605. var block = this.blocks[index];
  81606. block.addEntry(entry);
  81607. }
  81608. return;
  81609. }
  81610. this._creationFunc(entry, this);
  81611. if (this.entries.length > this.capacity && this._depth < this._maxDepth) {
  81612. this.createInnerBlocks();
  81613. }
  81614. };
  81615. OctreeBlock.prototype.addEntries = function (entries) {
  81616. for (var index = 0; index < entries.length; index++) {
  81617. var mesh = entries[index];
  81618. this.addEntry(mesh);
  81619. }
  81620. };
  81621. OctreeBlock.prototype.select = function (frustumPlanes, selection, allowDuplicate) {
  81622. if (BABYLON.BoundingBox.IsInFrustum(this._boundingVectors, frustumPlanes)) {
  81623. if (this.blocks) {
  81624. for (var index = 0; index < this.blocks.length; index++) {
  81625. var block = this.blocks[index];
  81626. block.select(frustumPlanes, selection, allowDuplicate);
  81627. }
  81628. return;
  81629. }
  81630. if (allowDuplicate) {
  81631. selection.concat(this.entries);
  81632. }
  81633. else {
  81634. selection.concatWithNoDuplicate(this.entries);
  81635. }
  81636. }
  81637. };
  81638. OctreeBlock.prototype.intersects = function (sphereCenter, sphereRadius, selection, allowDuplicate) {
  81639. if (BABYLON.BoundingBox.IntersectsSphere(this._minPoint, this._maxPoint, sphereCenter, sphereRadius)) {
  81640. if (this.blocks) {
  81641. for (var index = 0; index < this.blocks.length; index++) {
  81642. var block = this.blocks[index];
  81643. block.intersects(sphereCenter, sphereRadius, selection, allowDuplicate);
  81644. }
  81645. return;
  81646. }
  81647. if (allowDuplicate) {
  81648. selection.concat(this.entries);
  81649. }
  81650. else {
  81651. selection.concatWithNoDuplicate(this.entries);
  81652. }
  81653. }
  81654. };
  81655. OctreeBlock.prototype.intersectsRay = function (ray, selection) {
  81656. if (ray.intersectsBoxMinMax(this._minPoint, this._maxPoint)) {
  81657. if (this.blocks) {
  81658. for (var index = 0; index < this.blocks.length; index++) {
  81659. var block = this.blocks[index];
  81660. block.intersectsRay(ray, selection);
  81661. }
  81662. return;
  81663. }
  81664. selection.concatWithNoDuplicate(this.entries);
  81665. }
  81666. };
  81667. OctreeBlock.prototype.createInnerBlocks = function () {
  81668. BABYLON.Octree._CreateBlocks(this._minPoint, this._maxPoint, this.entries, this._capacity, this._depth, this._maxDepth, this, this._creationFunc);
  81669. };
  81670. return OctreeBlock;
  81671. }());
  81672. BABYLON.OctreeBlock = OctreeBlock;
  81673. })(BABYLON || (BABYLON = {}));
  81674. //# sourceMappingURL=babylon.octreeBlock.js.map
  81675. "use strict";
  81676. var BABYLON;
  81677. (function (BABYLON) {
  81678. var VRDistortionCorrectionPostProcess = /** @class */ (function (_super) {
  81679. __extends(VRDistortionCorrectionPostProcess, _super);
  81680. function VRDistortionCorrectionPostProcess(name, camera, isRightEye, vrMetrics) {
  81681. var _this = _super.call(this, name, "vrDistortionCorrection", [
  81682. 'LensCenter',
  81683. 'Scale',
  81684. 'ScaleIn',
  81685. 'HmdWarpParam'
  81686. ], null, vrMetrics.postProcessScaleFactor, camera, BABYLON.Texture.BILINEAR_SAMPLINGMODE) || this;
  81687. _this._isRightEye = isRightEye;
  81688. _this._distortionFactors = vrMetrics.distortionK;
  81689. _this._postProcessScaleFactor = vrMetrics.postProcessScaleFactor;
  81690. _this._lensCenterOffset = vrMetrics.lensCenterOffset;
  81691. _this.adaptScaleToCurrentViewport = true;
  81692. _this.onSizeChangedObservable.add(function () {
  81693. _this._scaleIn = new BABYLON.Vector2(2, 2 / _this.aspectRatio);
  81694. _this._scaleFactor = new BABYLON.Vector2(.5 * (1 / _this._postProcessScaleFactor), .5 * (1 / _this._postProcessScaleFactor) * _this.aspectRatio);
  81695. _this._lensCenter = new BABYLON.Vector2(_this._isRightEye ? 0.5 - _this._lensCenterOffset * 0.5 : 0.5 + _this._lensCenterOffset * 0.5, 0.5);
  81696. });
  81697. _this.onApplyObservable.add(function (effect) {
  81698. effect.setFloat2("LensCenter", _this._lensCenter.x, _this._lensCenter.y);
  81699. effect.setFloat2("Scale", _this._scaleFactor.x, _this._scaleFactor.y);
  81700. effect.setFloat2("ScaleIn", _this._scaleIn.x, _this._scaleIn.y);
  81701. effect.setFloat4("HmdWarpParam", _this._distortionFactors[0], _this._distortionFactors[1], _this._distortionFactors[2], _this._distortionFactors[3]);
  81702. });
  81703. return _this;
  81704. }
  81705. return VRDistortionCorrectionPostProcess;
  81706. }(BABYLON.PostProcess));
  81707. BABYLON.VRDistortionCorrectionPostProcess = VRDistortionCorrectionPostProcess;
  81708. })(BABYLON || (BABYLON = {}));
  81709. //# sourceMappingURL=babylon.vrDistortionCorrectionPostProcess.js.map
  81710. "use strict";
  81711. var BABYLON;
  81712. (function (BABYLON) {
  81713. var AnaglyphPostProcess = /** @class */ (function (_super) {
  81714. __extends(AnaglyphPostProcess, _super);
  81715. function AnaglyphPostProcess(name, options, rigCameras, samplingMode, engine, reusable) {
  81716. var _this = _super.call(this, name, "anaglyph", null, ["leftSampler"], options, rigCameras[1], samplingMode, engine, reusable) || this;
  81717. _this._passedProcess = rigCameras[0]._rigPostProcess;
  81718. _this.onApplyObservable.add(function (effect) {
  81719. effect.setTextureFromPostProcess("leftSampler", _this._passedProcess);
  81720. });
  81721. return _this;
  81722. }
  81723. return AnaglyphPostProcess;
  81724. }(BABYLON.PostProcess));
  81725. BABYLON.AnaglyphPostProcess = AnaglyphPostProcess;
  81726. })(BABYLON || (BABYLON = {}));
  81727. //# sourceMappingURL=babylon.anaglyphPostProcess.js.map
  81728. "use strict";
  81729. var BABYLON;
  81730. (function (BABYLON) {
  81731. var StereoscopicInterlacePostProcess = /** @class */ (function (_super) {
  81732. __extends(StereoscopicInterlacePostProcess, _super);
  81733. function StereoscopicInterlacePostProcess(name, rigCameras, isStereoscopicHoriz, samplingMode, engine, reusable) {
  81734. var _this = _super.call(this, name, "stereoscopicInterlace", ['stepSize'], ['camASampler'], 1, rigCameras[1], samplingMode, engine, reusable, isStereoscopicHoriz ? "#define IS_STEREOSCOPIC_HORIZ 1" : undefined) || this;
  81735. _this._passedProcess = rigCameras[0]._rigPostProcess;
  81736. _this._stepSize = new BABYLON.Vector2(1 / _this.width, 1 / _this.height);
  81737. _this.onSizeChangedObservable.add(function () {
  81738. _this._stepSize = new BABYLON.Vector2(1 / _this.width, 1 / _this.height);
  81739. });
  81740. _this.onApplyObservable.add(function (effect) {
  81741. effect.setTextureFromPostProcess("camASampler", _this._passedProcess);
  81742. effect.setFloat2("stepSize", _this._stepSize.x, _this._stepSize.y);
  81743. });
  81744. return _this;
  81745. }
  81746. return StereoscopicInterlacePostProcess;
  81747. }(BABYLON.PostProcess));
  81748. BABYLON.StereoscopicInterlacePostProcess = StereoscopicInterlacePostProcess;
  81749. })(BABYLON || (BABYLON = {}));
  81750. //# sourceMappingURL=babylon.stereoscopicInterlacePostProcess.js.map
  81751. "use strict";
  81752. var BABYLON;
  81753. (function (BABYLON) {
  81754. /**
  81755. * Takes information about the orientation of the device as reported by the deviceorientation event to orient the camera.
  81756. * Screen rotation is taken into account.
  81757. */
  81758. var FreeCameraDeviceOrientationInput = /** @class */ (function () {
  81759. function FreeCameraDeviceOrientationInput() {
  81760. var _this = this;
  81761. this._screenOrientationAngle = 0;
  81762. this._screenQuaternion = new BABYLON.Quaternion();
  81763. this._alpha = 0;
  81764. this._beta = 0;
  81765. this._gamma = 0;
  81766. this._orientationChanged = function () {
  81767. _this._screenOrientationAngle = (window.orientation !== undefined ? +window.orientation : (window.screen.orientation && window.screen.orientation['angle'] ? window.screen.orientation.angle : 0));
  81768. _this._screenOrientationAngle = -BABYLON.Tools.ToRadians(_this._screenOrientationAngle / 2);
  81769. _this._screenQuaternion.copyFromFloats(0, Math.sin(_this._screenOrientationAngle), 0, Math.cos(_this._screenOrientationAngle));
  81770. };
  81771. this._deviceOrientation = function (evt) {
  81772. _this._alpha = evt.alpha !== null ? evt.alpha : 0;
  81773. _this._beta = evt.beta !== null ? evt.beta : 0;
  81774. _this._gamma = evt.gamma !== null ? evt.gamma : 0;
  81775. };
  81776. this._constantTranform = new BABYLON.Quaternion(-Math.sqrt(0.5), 0, 0, Math.sqrt(0.5));
  81777. this._orientationChanged();
  81778. }
  81779. Object.defineProperty(FreeCameraDeviceOrientationInput.prototype, "camera", {
  81780. get: function () {
  81781. return this._camera;
  81782. },
  81783. set: function (camera) {
  81784. this._camera = camera;
  81785. if (this._camera != null && !this._camera.rotationQuaternion) {
  81786. this._camera.rotationQuaternion = new BABYLON.Quaternion();
  81787. }
  81788. },
  81789. enumerable: true,
  81790. configurable: true
  81791. });
  81792. FreeCameraDeviceOrientationInput.prototype.attachControl = function (element, noPreventDefault) {
  81793. window.addEventListener("orientationchange", this._orientationChanged);
  81794. window.addEventListener("deviceorientation", this._deviceOrientation);
  81795. //In certain cases, the attach control is called AFTER orientation was changed,
  81796. //So this is needed.
  81797. this._orientationChanged();
  81798. };
  81799. FreeCameraDeviceOrientationInput.prototype.detachControl = function (element) {
  81800. window.removeEventListener("orientationchange", this._orientationChanged);
  81801. window.removeEventListener("deviceorientation", this._deviceOrientation);
  81802. };
  81803. FreeCameraDeviceOrientationInput.prototype.checkInputs = function () {
  81804. //if no device orientation provided, don't update the rotation.
  81805. //Only testing against alpha under the assumption thatnorientation will never be so exact when set.
  81806. if (!this._alpha)
  81807. return;
  81808. BABYLON.Quaternion.RotationYawPitchRollToRef(BABYLON.Tools.ToRadians(this._alpha), BABYLON.Tools.ToRadians(this._beta), -BABYLON.Tools.ToRadians(this._gamma), this.camera.rotationQuaternion);
  81809. this._camera.rotationQuaternion.multiplyInPlace(this._screenQuaternion);
  81810. this._camera.rotationQuaternion.multiplyInPlace(this._constantTranform);
  81811. //Mirror on XY Plane
  81812. this._camera.rotationQuaternion.z *= -1;
  81813. this._camera.rotationQuaternion.w *= -1;
  81814. };
  81815. FreeCameraDeviceOrientationInput.prototype.getClassName = function () {
  81816. return "FreeCameraDeviceOrientationInput";
  81817. };
  81818. FreeCameraDeviceOrientationInput.prototype.getSimpleName = function () {
  81819. return "deviceOrientation";
  81820. };
  81821. return FreeCameraDeviceOrientationInput;
  81822. }());
  81823. BABYLON.FreeCameraDeviceOrientationInput = FreeCameraDeviceOrientationInput;
  81824. BABYLON.CameraInputTypes["FreeCameraDeviceOrientationInput"] = FreeCameraDeviceOrientationInput;
  81825. })(BABYLON || (BABYLON = {}));
  81826. //# sourceMappingURL=babylon.freeCameraDeviceOrientationInput.js.map
  81827. "use strict";
  81828. var BABYLON;
  81829. (function (BABYLON) {
  81830. var ArcRotateCameraVRDeviceOrientationInput = /** @class */ (function () {
  81831. function ArcRotateCameraVRDeviceOrientationInput() {
  81832. this.alphaCorrection = 1;
  81833. this.betaCorrection = 1;
  81834. this.gammaCorrection = 1;
  81835. this._alpha = 0;
  81836. this._gamma = 0;
  81837. this._dirty = false;
  81838. this._deviceOrientationHandler = this._onOrientationEvent.bind(this);
  81839. }
  81840. ArcRotateCameraVRDeviceOrientationInput.prototype.attachControl = function (element, noPreventDefault) {
  81841. this.camera.attachControl(element, noPreventDefault);
  81842. window.addEventListener("deviceorientation", this._deviceOrientationHandler);
  81843. };
  81844. ArcRotateCameraVRDeviceOrientationInput.prototype._onOrientationEvent = function (evt) {
  81845. if (evt.alpha !== null) {
  81846. this._alpha = +evt.alpha | 0;
  81847. }
  81848. if (evt.gamma !== null) {
  81849. this._gamma = +evt.gamma | 0;
  81850. }
  81851. this._dirty = true;
  81852. };
  81853. ArcRotateCameraVRDeviceOrientationInput.prototype.checkInputs = function () {
  81854. if (this._dirty) {
  81855. this._dirty = false;
  81856. if (this._gamma < 0) {
  81857. this._gamma = 180 + this._gamma;
  81858. }
  81859. this.camera.alpha = (-this._alpha / 180.0 * Math.PI) % Math.PI * 2;
  81860. this.camera.beta = (this._gamma / 180.0 * Math.PI);
  81861. }
  81862. };
  81863. ArcRotateCameraVRDeviceOrientationInput.prototype.detachControl = function (element) {
  81864. window.removeEventListener("deviceorientation", this._deviceOrientationHandler);
  81865. };
  81866. ArcRotateCameraVRDeviceOrientationInput.prototype.getClassName = function () {
  81867. return "ArcRotateCameraVRDeviceOrientationInput";
  81868. };
  81869. ArcRotateCameraVRDeviceOrientationInput.prototype.getSimpleName = function () {
  81870. return "VRDeviceOrientation";
  81871. };
  81872. return ArcRotateCameraVRDeviceOrientationInput;
  81873. }());
  81874. BABYLON.ArcRotateCameraVRDeviceOrientationInput = ArcRotateCameraVRDeviceOrientationInput;
  81875. BABYLON.CameraInputTypes["ArcRotateCameraVRDeviceOrientationInput"] = ArcRotateCameraVRDeviceOrientationInput;
  81876. })(BABYLON || (BABYLON = {}));
  81877. //# sourceMappingURL=babylon.arcRotateCameraVRDeviceOrientationInput.js.map
  81878. "use strict";
  81879. var BABYLON;
  81880. (function (BABYLON) {
  81881. var VRCameraMetrics = /** @class */ (function () {
  81882. function VRCameraMetrics() {
  81883. this.compensateDistortion = true;
  81884. }
  81885. Object.defineProperty(VRCameraMetrics.prototype, "aspectRatio", {
  81886. get: function () {
  81887. return this.hResolution / (2 * this.vResolution);
  81888. },
  81889. enumerable: true,
  81890. configurable: true
  81891. });
  81892. Object.defineProperty(VRCameraMetrics.prototype, "aspectRatioFov", {
  81893. get: function () {
  81894. return (2 * Math.atan((this.postProcessScaleFactor * this.vScreenSize) / (2 * this.eyeToScreenDistance)));
  81895. },
  81896. enumerable: true,
  81897. configurable: true
  81898. });
  81899. Object.defineProperty(VRCameraMetrics.prototype, "leftHMatrix", {
  81900. get: function () {
  81901. var meters = (this.hScreenSize / 4) - (this.lensSeparationDistance / 2);
  81902. var h = (4 * meters) / this.hScreenSize;
  81903. return BABYLON.Matrix.Translation(h, 0, 0);
  81904. },
  81905. enumerable: true,
  81906. configurable: true
  81907. });
  81908. Object.defineProperty(VRCameraMetrics.prototype, "rightHMatrix", {
  81909. get: function () {
  81910. var meters = (this.hScreenSize / 4) - (this.lensSeparationDistance / 2);
  81911. var h = (4 * meters) / this.hScreenSize;
  81912. return BABYLON.Matrix.Translation(-h, 0, 0);
  81913. },
  81914. enumerable: true,
  81915. configurable: true
  81916. });
  81917. Object.defineProperty(VRCameraMetrics.prototype, "leftPreViewMatrix", {
  81918. get: function () {
  81919. return BABYLON.Matrix.Translation(0.5 * this.interpupillaryDistance, 0, 0);
  81920. },
  81921. enumerable: true,
  81922. configurable: true
  81923. });
  81924. Object.defineProperty(VRCameraMetrics.prototype, "rightPreViewMatrix", {
  81925. get: function () {
  81926. return BABYLON.Matrix.Translation(-0.5 * this.interpupillaryDistance, 0, 0);
  81927. },
  81928. enumerable: true,
  81929. configurable: true
  81930. });
  81931. VRCameraMetrics.GetDefault = function () {
  81932. var result = new VRCameraMetrics();
  81933. result.hResolution = 1280;
  81934. result.vResolution = 800;
  81935. result.hScreenSize = 0.149759993;
  81936. result.vScreenSize = 0.0935999975;
  81937. result.vScreenCenter = 0.0467999987;
  81938. result.eyeToScreenDistance = 0.0410000011;
  81939. result.lensSeparationDistance = 0.0635000020;
  81940. result.interpupillaryDistance = 0.0640000030;
  81941. result.distortionK = [1.0, 0.219999999, 0.239999995, 0.0];
  81942. result.chromaAbCorrection = [0.995999992, -0.00400000019, 1.01400006, 0.0];
  81943. result.postProcessScaleFactor = 1.714605507808412;
  81944. result.lensCenterOffset = 0.151976421;
  81945. return result;
  81946. };
  81947. return VRCameraMetrics;
  81948. }());
  81949. BABYLON.VRCameraMetrics = VRCameraMetrics;
  81950. })(BABYLON || (BABYLON = {}));
  81951. //# sourceMappingURL=babylon.vrCameraMetrics.js.map
  81952. "use strict";
  81953. var BABYLON;
  81954. (function (BABYLON) {
  81955. /**
  81956. * This represents a WebVR camera.
  81957. * The WebVR camera is Babylon's simple interface to interaction with Windows Mixed Reality, HTC Vive and Oculus Rift.
  81958. * @example http://doc.babylonjs.com/how_to/webvr_camera
  81959. */
  81960. var WebVRFreeCamera = /** @class */ (function (_super) {
  81961. __extends(WebVRFreeCamera, _super);
  81962. /**
  81963. * Instantiates a WebVRFreeCamera.
  81964. * @param name The name of the WebVRFreeCamera
  81965. * @param position The starting anchor position for the camera
  81966. * @param scene The scene the camera belongs to
  81967. * @param webVROptions a set of customizable options for the webVRCamera
  81968. */
  81969. function WebVRFreeCamera(name, position, scene, webVROptions) {
  81970. if (webVROptions === void 0) { webVROptions = {}; }
  81971. var _this = _super.call(this, name, position, scene) || this;
  81972. _this.webVROptions = webVROptions;
  81973. /**
  81974. * The vrDisplay tied to the camera. See https://developer.mozilla.org/en-US/docs/Web/API/VRDisplay
  81975. */
  81976. _this._vrDevice = null;
  81977. /**
  81978. * The rawPose of the vrDevice.
  81979. */
  81980. _this.rawPose = null;
  81981. _this._specsVersion = "1.1";
  81982. _this._attached = false;
  81983. _this._descendants = [];
  81984. // Represents device position and rotation in room space. Should only be used to help calculate babylon space values
  81985. _this._deviceRoomPosition = BABYLON.Vector3.Zero();
  81986. _this._deviceRoomRotationQuaternion = BABYLON.Quaternion.Identity();
  81987. _this._standingMatrix = null;
  81988. /**
  81989. * Represents device position in babylon space.
  81990. */
  81991. _this.devicePosition = BABYLON.Vector3.Zero();
  81992. /**
  81993. * Represents device rotation in babylon space.
  81994. */
  81995. _this.deviceRotationQuaternion = BABYLON.Quaternion.Identity();
  81996. /**
  81997. * The scale of the device to be used when translating from device space to babylon space.
  81998. */
  81999. _this.deviceScaleFactor = 1;
  82000. _this._deviceToWorld = BABYLON.Matrix.Identity();
  82001. _this._worldToDevice = BABYLON.Matrix.Identity();
  82002. /**
  82003. * References to the webVR controllers for the vrDevice.
  82004. */
  82005. _this.controllers = [];
  82006. /**
  82007. * Emits an event when a controller is attached.
  82008. */
  82009. _this.onControllersAttachedObservable = new BABYLON.Observable();
  82010. /**
  82011. * Emits an event when a controller's mesh has been loaded;
  82012. */
  82013. _this.onControllerMeshLoadedObservable = new BABYLON.Observable();
  82014. /**
  82015. * If the rig cameras be used as parent instead of this camera.
  82016. */
  82017. _this.rigParenting = true;
  82018. _this._defaultHeight = undefined;
  82019. _this._workingVector = BABYLON.Vector3.Zero();
  82020. _this._oneVector = BABYLON.Vector3.One();
  82021. _this._workingMatrix = BABYLON.Matrix.Identity();
  82022. _this._cache.position = BABYLON.Vector3.Zero();
  82023. if (webVROptions.defaultHeight) {
  82024. _this._defaultHeight = webVROptions.defaultHeight;
  82025. _this.position.y = _this._defaultHeight;
  82026. }
  82027. _this.minZ = 0.1;
  82028. //legacy support - the compensation boolean was removed.
  82029. if (arguments.length === 5) {
  82030. _this.webVROptions = arguments[4];
  82031. }
  82032. // default webVR options
  82033. if (_this.webVROptions.trackPosition == undefined) {
  82034. _this.webVROptions.trackPosition = true;
  82035. }
  82036. if (_this.webVROptions.controllerMeshes == undefined) {
  82037. _this.webVROptions.controllerMeshes = true;
  82038. }
  82039. if (_this.webVROptions.defaultLightingOnControllers == undefined) {
  82040. _this.webVROptions.defaultLightingOnControllers = true;
  82041. }
  82042. _this.rotationQuaternion = new BABYLON.Quaternion();
  82043. if (_this.webVROptions && _this.webVROptions.positionScale) {
  82044. _this.deviceScaleFactor = _this.webVROptions.positionScale;
  82045. }
  82046. //enable VR
  82047. var engine = _this.getEngine();
  82048. _this._onVREnabled = function (success) { if (success) {
  82049. _this.initControllers();
  82050. } };
  82051. engine.onVRRequestPresentComplete.add(_this._onVREnabled);
  82052. engine.initWebVR().add(function (event) {
  82053. if (!event.vrDisplay || _this._vrDevice === event.vrDisplay) {
  82054. return;
  82055. }
  82056. _this._vrDevice = event.vrDisplay;
  82057. //reset the rig parameters.
  82058. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_WEBVR, { parentCamera: _this, vrDisplay: _this._vrDevice, frameData: _this._frameData, specs: _this._specsVersion });
  82059. if (_this._attached) {
  82060. _this.getEngine().enableVR();
  82061. }
  82062. });
  82063. if (typeof (VRFrameData) !== "undefined")
  82064. _this._frameData = new VRFrameData();
  82065. /**
  82066. * The idea behind the following lines:
  82067. * objects that have the camera as parent should actually have the rig cameras as a parent.
  82068. * BUT, each of those cameras has a different view matrix, which means that if we set the parent to the first rig camera,
  82069. * the second will not show it correctly.
  82070. *
  82071. * To solve this - each object that has the camera as parent will be added to a protected array.
  82072. * When the rig camera renders, it will take this array and set all of those to be its children.
  82073. * This way, the right camera will be used as a parent, and the mesh will be rendered correctly.
  82074. * Amazing!
  82075. */
  82076. scene.onBeforeCameraRenderObservable.add(function (camera) {
  82077. if (camera.parent === _this && _this.rigParenting) {
  82078. _this._descendants = _this.getDescendants(true, function (n) {
  82079. // don't take the cameras or the controllers!
  82080. var isController = _this.controllers.some(function (controller) { return controller._mesh === n; });
  82081. var isRigCamera = _this._rigCameras.indexOf(n) !== -1;
  82082. return !isController && !isRigCamera;
  82083. });
  82084. _this._descendants.forEach(function (node) {
  82085. node.parent = camera;
  82086. });
  82087. }
  82088. });
  82089. scene.onAfterCameraRenderObservable.add(function (camera) {
  82090. if (camera.parent === _this && _this.rigParenting) {
  82091. _this._descendants.forEach(function (node) {
  82092. node.parent = _this;
  82093. });
  82094. }
  82095. });
  82096. return _this;
  82097. }
  82098. /**
  82099. * Gets the device distance from the ground in meters.
  82100. * @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.
  82101. */
  82102. WebVRFreeCamera.prototype.deviceDistanceToRoomGround = function () {
  82103. if (this._standingMatrix) {
  82104. // Add standing matrix offset to get real offset from ground in room
  82105. this._standingMatrix.getTranslationToRef(this._workingVector);
  82106. return this._deviceRoomPosition.y + this._workingVector.y;
  82107. }
  82108. //If VRDisplay does not inform stage parameters and no default height is set we fallback to zero.
  82109. return this._defaultHeight || 0;
  82110. };
  82111. /**
  82112. * Enables the standing matrix when supported. This can be used to position the user's view the correct height from the ground.
  82113. * @param callback will be called when the standing matrix is set. Callback parameter is if the standing matrix is supported.
  82114. */
  82115. WebVRFreeCamera.prototype.useStandingMatrix = function (callback) {
  82116. var _this = this;
  82117. if (callback === void 0) { callback = function (bool) { }; }
  82118. // Use standing matrix if available
  82119. this.getEngine().initWebVRAsync().then(function (result) {
  82120. if (!result.vrDisplay || !result.vrDisplay.stageParameters || !result.vrDisplay.stageParameters.sittingToStandingTransform) {
  82121. callback(false);
  82122. }
  82123. else {
  82124. _this._standingMatrix = new BABYLON.Matrix();
  82125. BABYLON.Matrix.FromFloat32ArrayToRefScaled(result.vrDisplay.stageParameters.sittingToStandingTransform, 0, 1, _this._standingMatrix);
  82126. if (!_this.getScene().useRightHandedSystem) {
  82127. [2, 6, 8, 9, 14].forEach(function (num) {
  82128. if (_this._standingMatrix) {
  82129. _this._standingMatrix.m[num] *= -1;
  82130. }
  82131. });
  82132. }
  82133. callback(true);
  82134. }
  82135. });
  82136. };
  82137. /**
  82138. * Enables the standing matrix when supported. This can be used to position the user's view the correct height from the ground.
  82139. * @returns A promise with a boolean set to if the standing matrix is supported.
  82140. */
  82141. WebVRFreeCamera.prototype.useStandingMatrixAsync = function () {
  82142. var _this = this;
  82143. return new Promise(function (res, rej) {
  82144. _this.useStandingMatrix(function (supported) {
  82145. res(supported);
  82146. });
  82147. });
  82148. };
  82149. /**
  82150. * Disposes the camera
  82151. */
  82152. WebVRFreeCamera.prototype.dispose = function () {
  82153. this.getEngine().onVRRequestPresentComplete.removeCallback(this._onVREnabled);
  82154. _super.prototype.dispose.call(this);
  82155. };
  82156. /**
  82157. * Gets a vrController by name.
  82158. * @param name The name of the controller to retreive
  82159. * @returns the controller matching the name specified or null if not found
  82160. */
  82161. WebVRFreeCamera.prototype.getControllerByName = function (name) {
  82162. for (var _i = 0, _a = this.controllers; _i < _a.length; _i++) {
  82163. var gp = _a[_i];
  82164. if (gp.hand === name) {
  82165. return gp;
  82166. }
  82167. }
  82168. return null;
  82169. };
  82170. Object.defineProperty(WebVRFreeCamera.prototype, "leftController", {
  82171. /**
  82172. * The controller corrisponding to the users left hand.
  82173. */
  82174. get: function () {
  82175. if (!this._leftController) {
  82176. this._leftController = this.getControllerByName("left");
  82177. }
  82178. return this._leftController;
  82179. },
  82180. enumerable: true,
  82181. configurable: true
  82182. });
  82183. ;
  82184. Object.defineProperty(WebVRFreeCamera.prototype, "rightController", {
  82185. /**
  82186. * The controller corrisponding to the users right hand.
  82187. */
  82188. get: function () {
  82189. if (!this._rightController) {
  82190. this._rightController = this.getControllerByName("right");
  82191. }
  82192. return this._rightController;
  82193. },
  82194. enumerable: true,
  82195. configurable: true
  82196. });
  82197. ;
  82198. /**
  82199. * Casts a ray forward from the vrCamera's gaze.
  82200. * @param length Length of the ray (default: 100)
  82201. * @returns the ray corrisponding to the gaze
  82202. */
  82203. WebVRFreeCamera.prototype.getForwardRay = function (length) {
  82204. if (length === void 0) { length = 100; }
  82205. if (this.leftCamera) {
  82206. // Use left eye to avoid computation to compute center on every call
  82207. return _super.prototype.getForwardRay.call(this, length, this.leftCamera.getWorldMatrix(), this.leftCamera.globalPosition); // Need the actual rendered camera
  82208. }
  82209. else {
  82210. return _super.prototype.getForwardRay.call(this, length);
  82211. }
  82212. };
  82213. /**
  82214. * Updates the camera based on device's frame data
  82215. */
  82216. WebVRFreeCamera.prototype._checkInputs = function () {
  82217. if (this._vrDevice && this._vrDevice.isPresenting) {
  82218. this._vrDevice.getFrameData(this._frameData);
  82219. this.updateFromDevice(this._frameData.pose);
  82220. }
  82221. _super.prototype._checkInputs.call(this);
  82222. };
  82223. /**
  82224. * Updates the poseControlled values based on the input device pose.
  82225. * @param poseData Pose coming from the device
  82226. */
  82227. WebVRFreeCamera.prototype.updateFromDevice = function (poseData) {
  82228. if (poseData && poseData.orientation) {
  82229. this.rawPose = poseData;
  82230. this._deviceRoomRotationQuaternion.copyFromFloats(poseData.orientation[0], poseData.orientation[1], -poseData.orientation[2], -poseData.orientation[3]);
  82231. if (this.getScene().useRightHandedSystem) {
  82232. this._deviceRoomRotationQuaternion.z *= -1;
  82233. this._deviceRoomRotationQuaternion.w *= -1;
  82234. }
  82235. if (this.webVROptions.trackPosition && this.rawPose.position) {
  82236. this._deviceRoomPosition.copyFromFloats(this.rawPose.position[0], this.rawPose.position[1], -this.rawPose.position[2]);
  82237. if (this.getScene().useRightHandedSystem) {
  82238. this._deviceRoomPosition.z *= -1;
  82239. }
  82240. }
  82241. }
  82242. };
  82243. /**
  82244. * WebVR's attach control will start broadcasting frames to the device.
  82245. * Note that in certain browsers (chrome for example) this function must be called
  82246. * within a user-interaction callback. Example:
  82247. * <pre> scene.onPointerDown = function() { camera.attachControl(canvas); }</pre>
  82248. *
  82249. * @param element html element to attach the vrDevice to
  82250. * @param noPreventDefault prevent the default html element operation when attaching the vrDevice
  82251. */
  82252. WebVRFreeCamera.prototype.attachControl = function (element, noPreventDefault) {
  82253. _super.prototype.attachControl.call(this, element, noPreventDefault);
  82254. this._attached = true;
  82255. noPreventDefault = BABYLON.Camera.ForceAttachControlToAlwaysPreventDefault ? false : noPreventDefault;
  82256. if (this._vrDevice) {
  82257. this.getEngine().enableVR();
  82258. }
  82259. };
  82260. /**
  82261. * Detaches the camera from the html element and disables VR
  82262. *
  82263. * @param element html element to detach from
  82264. */
  82265. WebVRFreeCamera.prototype.detachControl = function (element) {
  82266. this.getScene().gamepadManager.onGamepadConnectedObservable.remove(this._onGamepadConnectedObserver);
  82267. this.getScene().gamepadManager.onGamepadDisconnectedObservable.remove(this._onGamepadDisconnectedObserver);
  82268. _super.prototype.detachControl.call(this, element);
  82269. this._attached = false;
  82270. this.getEngine().disableVR();
  82271. };
  82272. /**
  82273. * @returns the name of this class
  82274. */
  82275. WebVRFreeCamera.prototype.getClassName = function () {
  82276. return "WebVRFreeCamera";
  82277. };
  82278. /**
  82279. * Calls resetPose on the vrDisplay
  82280. * See: https://developer.mozilla.org/en-US/docs/Web/API/VRDisplay/resetPose
  82281. */
  82282. WebVRFreeCamera.prototype.resetToCurrentRotation = function () {
  82283. //uses the vrDisplay's "resetPose()".
  82284. //pitch and roll won't be affected.
  82285. this._vrDevice.resetPose();
  82286. };
  82287. /**
  82288. * Updates the rig cameras (left and right eye)
  82289. */
  82290. WebVRFreeCamera.prototype._updateRigCameras = function () {
  82291. var camLeft = this._rigCameras[0];
  82292. var camRight = this._rigCameras[1];
  82293. camLeft.rotationQuaternion.copyFrom(this._deviceRoomRotationQuaternion);
  82294. camRight.rotationQuaternion.copyFrom(this._deviceRoomRotationQuaternion);
  82295. camLeft.position.copyFrom(this._deviceRoomPosition);
  82296. camRight.position.copyFrom(this._deviceRoomPosition);
  82297. };
  82298. /**
  82299. * Updates the cached values of the camera
  82300. * @param ignoreParentClass ignores updating the parent class's cache (default: false)
  82301. */
  82302. WebVRFreeCamera.prototype._updateCache = function (ignoreParentClass) {
  82303. var _this = this;
  82304. if (!this.rotationQuaternion.equals(this._cache.rotationQuaternion) || !this.position.equals(this._cache.position)) {
  82305. // Update to ensure devicePosition is up to date with most recent _deviceRoomPosition
  82306. if (!this.updateCacheCalled) {
  82307. // make sure it is only called once per loop. this.update() might cause an infinite loop.
  82308. this.updateCacheCalled = true;
  82309. this.update();
  82310. }
  82311. // Set working vector to the device position in room space rotated by the new rotation
  82312. this.rotationQuaternion.toRotationMatrix(this._workingMatrix);
  82313. BABYLON.Vector3.TransformCoordinatesToRef(this._deviceRoomPosition, this._workingMatrix, this._workingVector);
  82314. // Subtract this vector from the current device position in world to get the translation for the device world matrix
  82315. this.devicePosition.subtractToRef(this._workingVector, this._workingVector);
  82316. BABYLON.Matrix.ComposeToRef(this._oneVector, this.rotationQuaternion, this._workingVector, this._deviceToWorld);
  82317. // Add translation from anchor position
  82318. this._deviceToWorld.getTranslationToRef(this._workingVector);
  82319. this._workingVector.addInPlace(this.position);
  82320. this._workingVector.subtractInPlace(this._cache.position);
  82321. this._deviceToWorld.setTranslation(this._workingVector);
  82322. // Set an inverted matrix to be used when updating the camera
  82323. this._deviceToWorld.invertToRef(this._worldToDevice);
  82324. // Update the gamepad to ensure the mesh is updated on the same frame as camera
  82325. this.controllers.forEach(function (controller) {
  82326. controller._deviceToWorld.copyFrom(_this._deviceToWorld);
  82327. controller.update();
  82328. });
  82329. }
  82330. if (!ignoreParentClass) {
  82331. _super.prototype._updateCache.call(this);
  82332. }
  82333. this.updateCacheCalled = false;
  82334. };
  82335. /**
  82336. * Updates the current device position and rotation in the babylon world
  82337. */
  82338. WebVRFreeCamera.prototype.update = function () {
  82339. // Get current device position in babylon world
  82340. BABYLON.Vector3.TransformCoordinatesToRef(this._deviceRoomPosition, this._deviceToWorld, this.devicePosition);
  82341. // Get current device rotation in babylon world
  82342. BABYLON.Matrix.FromQuaternionToRef(this._deviceRoomRotationQuaternion, this._workingMatrix);
  82343. this._workingMatrix.multiplyToRef(this._deviceToWorld, this._workingMatrix);
  82344. BABYLON.Quaternion.FromRotationMatrixToRef(this._workingMatrix, this.deviceRotationQuaternion);
  82345. _super.prototype.update.call(this);
  82346. };
  82347. /**
  82348. * Gets the view matrix of this camera (Always set to identity as left and right eye cameras contain the actual view matrix)
  82349. * @returns an identity matrix
  82350. */
  82351. WebVRFreeCamera.prototype._getViewMatrix = function () {
  82352. return BABYLON.Matrix.Identity();
  82353. };
  82354. /**
  82355. * This function is called by the two RIG cameras.
  82356. * 'this' is the left or right camera (and NOT (!!!) the WebVRFreeCamera instance)
  82357. */
  82358. WebVRFreeCamera.prototype._getWebVRViewMatrix = function () {
  82359. var _this = this;
  82360. // Update the parent camera prior to using a child camera to avoid desynchronization
  82361. var parentCamera = this._cameraRigParams["parentCamera"];
  82362. parentCamera._updateCache();
  82363. //WebVR 1.1
  82364. var viewArray = this._cameraRigParams["left"] ? this._cameraRigParams["frameData"].leftViewMatrix : this._cameraRigParams["frameData"].rightViewMatrix;
  82365. BABYLON.Matrix.FromArrayToRef(viewArray, 0, this._webvrViewMatrix);
  82366. if (!this.getScene().useRightHandedSystem) {
  82367. [2, 6, 8, 9, 14].forEach(function (num) {
  82368. _this._webvrViewMatrix.m[num] *= -1;
  82369. });
  82370. }
  82371. // update the camera rotation matrix
  82372. this._webvrViewMatrix.getRotationMatrixToRef(this._cameraRotationMatrix);
  82373. BABYLON.Vector3.TransformCoordinatesToRef(this._referencePoint, this._cameraRotationMatrix, this._transformedReferencePoint);
  82374. // Computing target and final matrix
  82375. this.position.addToRef(this._transformedReferencePoint, this._currentTarget);
  82376. // should the view matrix be updated with scale and position offset?
  82377. if (parentCamera.deviceScaleFactor !== 1) {
  82378. this._webvrViewMatrix.invert();
  82379. // scale the position, if set
  82380. if (parentCamera.deviceScaleFactor) {
  82381. this._webvrViewMatrix.m[12] *= parentCamera.deviceScaleFactor;
  82382. this._webvrViewMatrix.m[13] *= parentCamera.deviceScaleFactor;
  82383. this._webvrViewMatrix.m[14] *= parentCamera.deviceScaleFactor;
  82384. }
  82385. this._webvrViewMatrix.invert();
  82386. }
  82387. parentCamera._worldToDevice.multiplyToRef(this._webvrViewMatrix, this._webvrViewMatrix);
  82388. return this._webvrViewMatrix;
  82389. };
  82390. WebVRFreeCamera.prototype._getWebVRProjectionMatrix = function () {
  82391. var _this = this;
  82392. var parentCamera = this.parent;
  82393. parentCamera._vrDevice.depthNear = parentCamera.minZ;
  82394. parentCamera._vrDevice.depthFar = parentCamera.maxZ;
  82395. var projectionArray = this._cameraRigParams["left"] ? this._cameraRigParams["frameData"].leftProjectionMatrix : this._cameraRigParams["frameData"].rightProjectionMatrix;
  82396. BABYLON.Matrix.FromArrayToRef(projectionArray, 0, this._projectionMatrix);
  82397. //babylon compatible matrix
  82398. if (!this.getScene().useRightHandedSystem) {
  82399. [8, 9, 10, 11].forEach(function (num) {
  82400. _this._projectionMatrix.m[num] *= -1;
  82401. });
  82402. }
  82403. return this._projectionMatrix;
  82404. };
  82405. /**
  82406. * Initializes the controllers and their meshes
  82407. */
  82408. WebVRFreeCamera.prototype.initControllers = function () {
  82409. var _this = this;
  82410. this.controllers = [];
  82411. var manager = this.getScene().gamepadManager;
  82412. this._onGamepadDisconnectedObserver = manager.onGamepadDisconnectedObservable.add(function (gamepad) {
  82413. if (gamepad.type === BABYLON.Gamepad.POSE_ENABLED) {
  82414. var webVrController = gamepad;
  82415. if (webVrController.defaultModel) {
  82416. webVrController.defaultModel.setEnabled(false);
  82417. }
  82418. if (webVrController.hand === "right") {
  82419. _this._rightController = null;
  82420. }
  82421. if (webVrController.hand === "left") {
  82422. _this._leftController = null;
  82423. }
  82424. var controllerIndex = _this.controllers.indexOf(webVrController);
  82425. if (controllerIndex !== -1) {
  82426. _this.controllers.splice(controllerIndex, 1);
  82427. }
  82428. }
  82429. });
  82430. this._onGamepadConnectedObserver = manager.onGamepadConnectedObservable.add(function (gamepad) {
  82431. if (gamepad.type === BABYLON.Gamepad.POSE_ENABLED) {
  82432. var webVrController_1 = gamepad;
  82433. webVrController_1.deviceScaleFactor = _this.deviceScaleFactor;
  82434. webVrController_1._deviceToWorld.copyFrom(_this._deviceToWorld);
  82435. if (_this.webVROptions.controllerMeshes) {
  82436. if (webVrController_1.defaultModel) {
  82437. webVrController_1.defaultModel.setEnabled(true);
  82438. }
  82439. else {
  82440. // Load the meshes
  82441. webVrController_1.initControllerMesh(_this.getScene(), function (loadedMesh) {
  82442. loadedMesh.scaling.scaleInPlace(_this.deviceScaleFactor);
  82443. _this.onControllerMeshLoadedObservable.notifyObservers(webVrController_1);
  82444. if (_this.webVROptions.defaultLightingOnControllers) {
  82445. if (!_this._lightOnControllers) {
  82446. _this._lightOnControllers = new BABYLON.HemisphericLight("vrControllersLight", new BABYLON.Vector3(0, 1, 0), _this.getScene());
  82447. }
  82448. var activateLightOnSubMeshes_1 = function (mesh, light) {
  82449. var children = mesh.getChildren();
  82450. if (children.length !== 0) {
  82451. children.forEach(function (mesh) {
  82452. light.includedOnlyMeshes.push(mesh);
  82453. activateLightOnSubMeshes_1(mesh, light);
  82454. });
  82455. }
  82456. };
  82457. _this._lightOnControllers.includedOnlyMeshes.push(loadedMesh);
  82458. activateLightOnSubMeshes_1(loadedMesh, _this._lightOnControllers);
  82459. }
  82460. });
  82461. }
  82462. }
  82463. webVrController_1.attachToPoseControlledCamera(_this);
  82464. // since this is async - sanity check. Is the controller already stored?
  82465. if (_this.controllers.indexOf(webVrController_1) === -1) {
  82466. //add to the controllers array
  82467. _this.controllers.push(webVrController_1);
  82468. // Forced to add some control code for Vive as it doesn't always fill properly the "hand" property
  82469. // Sometimes, both controllers are set correctly (left and right), sometimes none, sometimes only one of them...
  82470. // So we're overriding setting left & right manually to be sure
  82471. var firstViveWandDetected = false;
  82472. for (var i = 0; i < _this.controllers.length; i++) {
  82473. if (_this.controllers[i].controllerType === BABYLON.PoseEnabledControllerType.VIVE) {
  82474. if (!firstViveWandDetected) {
  82475. firstViveWandDetected = true;
  82476. _this.controllers[i].hand = "left";
  82477. }
  82478. else {
  82479. _this.controllers[i].hand = "right";
  82480. }
  82481. }
  82482. }
  82483. //did we find enough controllers? Great! let the developer know.
  82484. if (_this.controllers.length >= 2) {
  82485. _this.onControllersAttachedObservable.notifyObservers(_this.controllers);
  82486. }
  82487. }
  82488. }
  82489. });
  82490. };
  82491. return WebVRFreeCamera;
  82492. }(BABYLON.FreeCamera));
  82493. BABYLON.WebVRFreeCamera = WebVRFreeCamera;
  82494. })(BABYLON || (BABYLON = {}));
  82495. //# sourceMappingURL=babylon.webVRCamera.js.map
  82496. "use strict";
  82497. var BABYLON;
  82498. (function (BABYLON) {
  82499. // We're mainly based on the logic defined into the FreeCamera code
  82500. /**
  82501. * This is a camera specifically designed to react to device orientation events such as a modern mobile device
  82502. * being tilted forward or back and left or right.
  82503. */
  82504. var DeviceOrientationCamera = /** @class */ (function (_super) {
  82505. __extends(DeviceOrientationCamera, _super);
  82506. /**
  82507. * Creates a new device orientation camera
  82508. * @param name The name of the camera
  82509. * @param position The start position camera
  82510. * @param scene The scene the camera belongs to
  82511. */
  82512. function DeviceOrientationCamera(name, position, scene) {
  82513. var _this = _super.call(this, name, position, scene) || this;
  82514. _this._quaternionCache = new BABYLON.Quaternion();
  82515. _this.inputs.addDeviceOrientation();
  82516. return _this;
  82517. }
  82518. /**
  82519. * Gets the current instance class name ("DeviceOrientationCamera").
  82520. * This helps avoiding instanceof at run time.
  82521. * @returns the class name
  82522. */
  82523. DeviceOrientationCamera.prototype.getClassName = function () {
  82524. return "DeviceOrientationCamera";
  82525. };
  82526. /**
  82527. * Checks and applies the current values of the inputs to the camera. (Internal use only)
  82528. */
  82529. DeviceOrientationCamera.prototype._checkInputs = function () {
  82530. _super.prototype._checkInputs.call(this);
  82531. this._quaternionCache.copyFrom(this.rotationQuaternion);
  82532. if (this._initialQuaternion) {
  82533. this._initialQuaternion.multiplyToRef(this.rotationQuaternion, this.rotationQuaternion);
  82534. }
  82535. };
  82536. /**
  82537. * Reset the camera to its default orientation on the specified axis only.
  82538. * @param axis The axis to reset
  82539. */
  82540. DeviceOrientationCamera.prototype.resetToCurrentRotation = function (axis) {
  82541. var _this = this;
  82542. if (axis === void 0) { axis = BABYLON.Axis.Y; }
  82543. //can only work if this camera has a rotation quaternion already.
  82544. if (!this.rotationQuaternion)
  82545. return;
  82546. if (!this._initialQuaternion) {
  82547. this._initialQuaternion = new BABYLON.Quaternion();
  82548. }
  82549. this._initialQuaternion.copyFrom(this._quaternionCache || this.rotationQuaternion);
  82550. ['x', 'y', 'z'].forEach(function (axisName) {
  82551. if (!axis[axisName]) {
  82552. _this._initialQuaternion[axisName] = 0;
  82553. }
  82554. else {
  82555. _this._initialQuaternion[axisName] *= -1;
  82556. }
  82557. });
  82558. this._initialQuaternion.normalize();
  82559. //force rotation update
  82560. this._initialQuaternion.multiplyToRef(this.rotationQuaternion, this.rotationQuaternion);
  82561. };
  82562. return DeviceOrientationCamera;
  82563. }(BABYLON.FreeCamera));
  82564. BABYLON.DeviceOrientationCamera = DeviceOrientationCamera;
  82565. })(BABYLON || (BABYLON = {}));
  82566. //# sourceMappingURL=babylon.deviceOrientationCamera.js.map
  82567. "use strict";
  82568. var BABYLON;
  82569. (function (BABYLON) {
  82570. var VRDeviceOrientationFreeCamera = /** @class */ (function (_super) {
  82571. __extends(VRDeviceOrientationFreeCamera, _super);
  82572. function VRDeviceOrientationFreeCamera(name, position, scene, compensateDistortion, vrCameraMetrics) {
  82573. if (compensateDistortion === void 0) { compensateDistortion = true; }
  82574. if (vrCameraMetrics === void 0) { vrCameraMetrics = BABYLON.VRCameraMetrics.GetDefault(); }
  82575. var _this = _super.call(this, name, position, scene) || this;
  82576. vrCameraMetrics.compensateDistortion = compensateDistortion;
  82577. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_VR, { vrCameraMetrics: vrCameraMetrics });
  82578. return _this;
  82579. }
  82580. VRDeviceOrientationFreeCamera.prototype.getClassName = function () {
  82581. return "VRDeviceOrientationFreeCamera";
  82582. };
  82583. return VRDeviceOrientationFreeCamera;
  82584. }(BABYLON.DeviceOrientationCamera));
  82585. BABYLON.VRDeviceOrientationFreeCamera = VRDeviceOrientationFreeCamera;
  82586. var VRDeviceOrientationGamepadCamera = /** @class */ (function (_super) {
  82587. __extends(VRDeviceOrientationGamepadCamera, _super);
  82588. function VRDeviceOrientationGamepadCamera(name, position, scene, compensateDistortion, vrCameraMetrics) {
  82589. if (compensateDistortion === void 0) { compensateDistortion = true; }
  82590. if (vrCameraMetrics === void 0) { vrCameraMetrics = BABYLON.VRCameraMetrics.GetDefault(); }
  82591. var _this = _super.call(this, name, position, scene, compensateDistortion, vrCameraMetrics) || this;
  82592. _this.inputs.addGamepad();
  82593. return _this;
  82594. }
  82595. VRDeviceOrientationGamepadCamera.prototype.getClassName = function () {
  82596. return "VRDeviceOrientationGamepadCamera";
  82597. };
  82598. return VRDeviceOrientationGamepadCamera;
  82599. }(VRDeviceOrientationFreeCamera));
  82600. BABYLON.VRDeviceOrientationGamepadCamera = VRDeviceOrientationGamepadCamera;
  82601. var VRDeviceOrientationArcRotateCamera = /** @class */ (function (_super) {
  82602. __extends(VRDeviceOrientationArcRotateCamera, _super);
  82603. function VRDeviceOrientationArcRotateCamera(name, alpha, beta, radius, target, scene, compensateDistortion, vrCameraMetrics) {
  82604. if (compensateDistortion === void 0) { compensateDistortion = true; }
  82605. if (vrCameraMetrics === void 0) { vrCameraMetrics = BABYLON.VRCameraMetrics.GetDefault(); }
  82606. var _this = _super.call(this, name, alpha, beta, radius, target, scene) || this;
  82607. vrCameraMetrics.compensateDistortion = compensateDistortion;
  82608. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_VR, { vrCameraMetrics: vrCameraMetrics });
  82609. _this.inputs.addVRDeviceOrientation();
  82610. return _this;
  82611. }
  82612. VRDeviceOrientationArcRotateCamera.prototype.getClassName = function () {
  82613. return "VRDeviceOrientationArcRotateCamera";
  82614. };
  82615. return VRDeviceOrientationArcRotateCamera;
  82616. }(BABYLON.ArcRotateCamera));
  82617. BABYLON.VRDeviceOrientationArcRotateCamera = VRDeviceOrientationArcRotateCamera;
  82618. })(BABYLON || (BABYLON = {}));
  82619. //# sourceMappingURL=babylon.vrDeviceOrientationCamera.js.map
  82620. "use strict";
  82621. var BABYLON;
  82622. (function (BABYLON) {
  82623. var AnaglyphFreeCamera = /** @class */ (function (_super) {
  82624. __extends(AnaglyphFreeCamera, _super);
  82625. function AnaglyphFreeCamera(name, position, interaxialDistance, scene) {
  82626. var _this = _super.call(this, name, position, scene) || this;
  82627. _this.interaxialDistance = interaxialDistance;
  82628. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  82629. return _this;
  82630. }
  82631. AnaglyphFreeCamera.prototype.getClassName = function () {
  82632. return "AnaglyphFreeCamera";
  82633. };
  82634. return AnaglyphFreeCamera;
  82635. }(BABYLON.FreeCamera));
  82636. BABYLON.AnaglyphFreeCamera = AnaglyphFreeCamera;
  82637. var AnaglyphArcRotateCamera = /** @class */ (function (_super) {
  82638. __extends(AnaglyphArcRotateCamera, _super);
  82639. function AnaglyphArcRotateCamera(name, alpha, beta, radius, target, interaxialDistance, scene) {
  82640. var _this = _super.call(this, name, alpha, beta, radius, target, scene) || this;
  82641. _this.interaxialDistance = interaxialDistance;
  82642. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  82643. return _this;
  82644. }
  82645. AnaglyphArcRotateCamera.prototype.getClassName = function () {
  82646. return "AnaglyphArcRotateCamera";
  82647. };
  82648. return AnaglyphArcRotateCamera;
  82649. }(BABYLON.ArcRotateCamera));
  82650. BABYLON.AnaglyphArcRotateCamera = AnaglyphArcRotateCamera;
  82651. var AnaglyphGamepadCamera = /** @class */ (function (_super) {
  82652. __extends(AnaglyphGamepadCamera, _super);
  82653. function AnaglyphGamepadCamera(name, position, interaxialDistance, scene) {
  82654. var _this = _super.call(this, name, position, scene) || this;
  82655. _this.interaxialDistance = interaxialDistance;
  82656. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  82657. return _this;
  82658. }
  82659. AnaglyphGamepadCamera.prototype.getClassName = function () {
  82660. return "AnaglyphGamepadCamera";
  82661. };
  82662. return AnaglyphGamepadCamera;
  82663. }(BABYLON.GamepadCamera));
  82664. BABYLON.AnaglyphGamepadCamera = AnaglyphGamepadCamera;
  82665. var AnaglyphUniversalCamera = /** @class */ (function (_super) {
  82666. __extends(AnaglyphUniversalCamera, _super);
  82667. function AnaglyphUniversalCamera(name, position, interaxialDistance, scene) {
  82668. var _this = _super.call(this, name, position, scene) || this;
  82669. _this.interaxialDistance = interaxialDistance;
  82670. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  82671. return _this;
  82672. }
  82673. AnaglyphUniversalCamera.prototype.getClassName = function () {
  82674. return "AnaglyphUniversalCamera";
  82675. };
  82676. return AnaglyphUniversalCamera;
  82677. }(BABYLON.UniversalCamera));
  82678. BABYLON.AnaglyphUniversalCamera = AnaglyphUniversalCamera;
  82679. var StereoscopicFreeCamera = /** @class */ (function (_super) {
  82680. __extends(StereoscopicFreeCamera, _super);
  82681. function StereoscopicFreeCamera(name, position, interaxialDistance, isStereoscopicSideBySide, scene) {
  82682. var _this = _super.call(this, name, position, scene) || this;
  82683. _this.interaxialDistance = interaxialDistance;
  82684. _this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  82685. _this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  82686. return _this;
  82687. }
  82688. StereoscopicFreeCamera.prototype.getClassName = function () {
  82689. return "StereoscopicFreeCamera";
  82690. };
  82691. return StereoscopicFreeCamera;
  82692. }(BABYLON.FreeCamera));
  82693. BABYLON.StereoscopicFreeCamera = StereoscopicFreeCamera;
  82694. var StereoscopicArcRotateCamera = /** @class */ (function (_super) {
  82695. __extends(StereoscopicArcRotateCamera, _super);
  82696. function StereoscopicArcRotateCamera(name, alpha, beta, radius, target, interaxialDistance, isStereoscopicSideBySide, scene) {
  82697. var _this = _super.call(this, name, alpha, beta, radius, target, scene) || this;
  82698. _this.interaxialDistance = interaxialDistance;
  82699. _this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  82700. _this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  82701. return _this;
  82702. }
  82703. StereoscopicArcRotateCamera.prototype.getClassName = function () {
  82704. return "StereoscopicArcRotateCamera";
  82705. };
  82706. return StereoscopicArcRotateCamera;
  82707. }(BABYLON.ArcRotateCamera));
  82708. BABYLON.StereoscopicArcRotateCamera = StereoscopicArcRotateCamera;
  82709. var StereoscopicGamepadCamera = /** @class */ (function (_super) {
  82710. __extends(StereoscopicGamepadCamera, _super);
  82711. function StereoscopicGamepadCamera(name, position, interaxialDistance, isStereoscopicSideBySide, scene) {
  82712. var _this = _super.call(this, name, position, scene) || this;
  82713. _this.interaxialDistance = interaxialDistance;
  82714. _this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  82715. _this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  82716. return _this;
  82717. }
  82718. StereoscopicGamepadCamera.prototype.getClassName = function () {
  82719. return "StereoscopicGamepadCamera";
  82720. };
  82721. return StereoscopicGamepadCamera;
  82722. }(BABYLON.GamepadCamera));
  82723. BABYLON.StereoscopicGamepadCamera = StereoscopicGamepadCamera;
  82724. var StereoscopicUniversalCamera = /** @class */ (function (_super) {
  82725. __extends(StereoscopicUniversalCamera, _super);
  82726. function StereoscopicUniversalCamera(name, position, interaxialDistance, isStereoscopicSideBySide, scene) {
  82727. var _this = _super.call(this, name, position, scene) || this;
  82728. _this.interaxialDistance = interaxialDistance;
  82729. _this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  82730. _this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  82731. return _this;
  82732. }
  82733. StereoscopicUniversalCamera.prototype.getClassName = function () {
  82734. return "StereoscopicUniversalCamera";
  82735. };
  82736. return StereoscopicUniversalCamera;
  82737. }(BABYLON.UniversalCamera));
  82738. BABYLON.StereoscopicUniversalCamera = StereoscopicUniversalCamera;
  82739. })(BABYLON || (BABYLON = {}));
  82740. //# sourceMappingURL=babylon.stereoscopicCameras.js.map
  82741. "use strict";
  82742. var BABYLON;
  82743. (function (BABYLON) {
  82744. var VRExperienceHelperGazer = /** @class */ (function () {
  82745. function VRExperienceHelperGazer(scene, gazeTrackerToClone) {
  82746. if (gazeTrackerToClone === void 0) { gazeTrackerToClone = null; }
  82747. this.scene = scene;
  82748. this._pointerDownOnMeshAsked = false;
  82749. this._isActionableMesh = false;
  82750. this._teleportationRequestInitiated = false;
  82751. this._teleportationBackRequestInitiated = false;
  82752. this._dpadPressed = true;
  82753. this._activePointer = false;
  82754. this._id = VRExperienceHelperGazer._idCounter++;
  82755. // Gaze tracker
  82756. if (!gazeTrackerToClone) {
  82757. this._gazeTracker = BABYLON.Mesh.CreateTorus("gazeTracker", 0.0035, 0.0025, 20, scene, false);
  82758. this._gazeTracker.bakeCurrentTransformIntoVertices();
  82759. this._gazeTracker.isPickable = false;
  82760. this._gazeTracker.isVisible = false;
  82761. var targetMat = new BABYLON.StandardMaterial("targetMat", scene);
  82762. targetMat.specularColor = BABYLON.Color3.Black();
  82763. targetMat.emissiveColor = new BABYLON.Color3(0.7, 0.7, 0.7);
  82764. targetMat.backFaceCulling = false;
  82765. this._gazeTracker.material = targetMat;
  82766. }
  82767. else {
  82768. this._gazeTracker = gazeTrackerToClone.clone("gazeTracker");
  82769. }
  82770. }
  82771. VRExperienceHelperGazer.prototype._getForwardRay = function (length) {
  82772. return new BABYLON.Ray(BABYLON.Vector3.Zero(), new BABYLON.Vector3(0, 0, length));
  82773. };
  82774. VRExperienceHelperGazer.prototype._selectionPointerDown = function () {
  82775. this._pointerDownOnMeshAsked = true;
  82776. if (this._currentMeshSelected && this._currentHit) {
  82777. this.scene.simulatePointerDown(this._currentHit, { pointerId: this._id });
  82778. }
  82779. };
  82780. VRExperienceHelperGazer.prototype._selectionPointerUp = function () {
  82781. if (this._currentMeshSelected && this._currentHit) {
  82782. this.scene.simulatePointerUp(this._currentHit, { pointerId: this._id });
  82783. }
  82784. this._pointerDownOnMeshAsked = false;
  82785. };
  82786. VRExperienceHelperGazer.prototype._activatePointer = function () {
  82787. this._activePointer = true;
  82788. };
  82789. VRExperienceHelperGazer.prototype._deactivatePointer = function () {
  82790. this._activePointer = false;
  82791. };
  82792. VRExperienceHelperGazer.prototype._updatePointerDistance = function (distance) {
  82793. };
  82794. VRExperienceHelperGazer.prototype.dispose = function () {
  82795. this._interactionsEnabled = false;
  82796. this._teleportationEnabled = false;
  82797. };
  82798. VRExperienceHelperGazer._idCounter = 0;
  82799. return VRExperienceHelperGazer;
  82800. }());
  82801. var VRExperienceHelperControllerGazer = /** @class */ (function (_super) {
  82802. __extends(VRExperienceHelperControllerGazer, _super);
  82803. function VRExperienceHelperControllerGazer(webVRController, scene, gazeTrackerToClone) {
  82804. var _this = _super.call(this, scene, gazeTrackerToClone) || this;
  82805. _this.webVRController = webVRController;
  82806. // Laser pointer
  82807. _this._laserPointer = BABYLON.Mesh.CreateCylinder("laserPointer", 1, 0.004, 0.0002, 20, 1, scene, false);
  82808. var laserPointerMaterial = new BABYLON.StandardMaterial("laserPointerMat", scene);
  82809. laserPointerMaterial.emissiveColor = new BABYLON.Color3(0.7, 0.7, 0.7);
  82810. laserPointerMaterial.alpha = 0.6;
  82811. _this._laserPointer.material = laserPointerMaterial;
  82812. _this._laserPointer.rotation.x = Math.PI / 2;
  82813. _this._laserPointer.position.z = -0.5;
  82814. _this._laserPointer.isVisible = false;
  82815. if (!webVRController.mesh) {
  82816. // Create an empty mesh that is used prior to loading the high quality model
  82817. var preloadMesh = new BABYLON.Mesh("preloadControllerMesh", scene);
  82818. var preloadPointerPose = new BABYLON.Mesh(BABYLON.PoseEnabledController.POINTING_POSE, scene);
  82819. preloadPointerPose.rotation.x = -0.7;
  82820. preloadMesh.addChild(preloadPointerPose);
  82821. webVRController.attachToMesh(preloadMesh);
  82822. }
  82823. _this._setLaserPointerParent(webVRController.mesh);
  82824. return _this;
  82825. }
  82826. VRExperienceHelperControllerGazer.prototype._getForwardRay = function (length) {
  82827. return this.webVRController.getForwardRay(length);
  82828. };
  82829. VRExperienceHelperControllerGazer.prototype._activatePointer = function () {
  82830. _super.prototype._activatePointer.call(this);
  82831. this._laserPointer.isVisible = true;
  82832. };
  82833. VRExperienceHelperControllerGazer.prototype._deactivatePointer = function () {
  82834. _super.prototype._deactivatePointer.call(this);
  82835. this._laserPointer.isVisible = false;
  82836. };
  82837. VRExperienceHelperControllerGazer.prototype._setLaserPointerColor = function (color) {
  82838. this._laserPointer.material.emissiveColor = color;
  82839. };
  82840. VRExperienceHelperControllerGazer.prototype._setLaserPointerParent = function (mesh) {
  82841. var makeNotPick = function (root) {
  82842. root.name += " laserPointer";
  82843. root.getChildMeshes().forEach(function (c) {
  82844. makeNotPick(c);
  82845. });
  82846. };
  82847. makeNotPick(mesh);
  82848. var childMeshes = mesh.getChildMeshes();
  82849. this.webVRController._pointingPoseNode = null;
  82850. for (var i = 0; i < childMeshes.length; i++) {
  82851. if (childMeshes[i].name && childMeshes[i].name.indexOf(BABYLON.PoseEnabledController.POINTING_POSE) >= 0) {
  82852. mesh = childMeshes[i];
  82853. this.webVRController._pointingPoseNode = mesh;
  82854. break;
  82855. }
  82856. }
  82857. this._laserPointer.parent = mesh;
  82858. };
  82859. VRExperienceHelperControllerGazer.prototype._updatePointerDistance = function (distance) {
  82860. this._laserPointer.scaling.y = distance;
  82861. this._laserPointer.position.z = -distance / 2;
  82862. };
  82863. VRExperienceHelperControllerGazer.prototype.dispose = function () {
  82864. _super.prototype.dispose.call(this);
  82865. this._laserPointer.dispose();
  82866. };
  82867. return VRExperienceHelperControllerGazer;
  82868. }(VRExperienceHelperGazer));
  82869. var VRExperienceHelperCameraGazer = /** @class */ (function (_super) {
  82870. __extends(VRExperienceHelperCameraGazer, _super);
  82871. function VRExperienceHelperCameraGazer(getCamera, scene) {
  82872. var _this = _super.call(this, scene) || this;
  82873. _this.getCamera = getCamera;
  82874. return _this;
  82875. }
  82876. VRExperienceHelperCameraGazer.prototype._getForwardRay = function (length) {
  82877. var camera = this.getCamera();
  82878. if (camera) {
  82879. return camera.getForwardRay(length);
  82880. }
  82881. else {
  82882. return new BABYLON.Ray(BABYLON.Vector3.Zero(), BABYLON.Vector3.Forward());
  82883. }
  82884. };
  82885. return VRExperienceHelperCameraGazer;
  82886. }(VRExperienceHelperGazer));
  82887. /**
  82888. * Helps to quickly add VR support to an existing scene.
  82889. * See http://doc.babylonjs.com/how_to/webvr_helper
  82890. */
  82891. var VRExperienceHelper = /** @class */ (function () {
  82892. /**
  82893. * Instantiates a VRExperienceHelper.
  82894. * Helps to quickly add VR support to an existing scene.
  82895. * @param scene The scene the VRExperienceHelper belongs to.
  82896. * @param webVROptions Options to modify the vr experience helper's behavior.
  82897. */
  82898. function VRExperienceHelper(scene, /** Options to modify the vr experience helper's behavior. */ webVROptions) {
  82899. if (webVROptions === void 0) { webVROptions = {}; }
  82900. var _this = this;
  82901. this.webVROptions = webVROptions;
  82902. // Can the system support WebVR, even if a headset isn't plugged in?
  82903. this._webVRsupported = false;
  82904. // If WebVR is supported, is a headset plugged in and are we ready to present?
  82905. this._webVRready = false;
  82906. // Are we waiting for the requestPresent callback to complete?
  82907. this._webVRrequesting = false;
  82908. // Are we presenting to the headset right now?
  82909. this._webVRpresenting = false;
  82910. // Are we presenting in the fullscreen fallback?
  82911. this._fullscreenVRpresenting = false;
  82912. /**
  82913. * Observable raised when entering VR.
  82914. */
  82915. this.onEnteringVRObservable = new BABYLON.Observable();
  82916. /**
  82917. * Observable raised when exiting VR.
  82918. */
  82919. this.onExitingVRObservable = new BABYLON.Observable();
  82920. /**
  82921. * Observable raised when controller mesh is loaded.
  82922. */
  82923. this.onControllerMeshLoadedObservable = new BABYLON.Observable();
  82924. this._useCustomVRButton = false;
  82925. this._teleportationRequested = false;
  82926. this._teleportActive = false;
  82927. this._floorMeshesCollection = [];
  82928. this._rotationAllowed = true;
  82929. this._teleportBackwardsVector = new BABYLON.Vector3(0, -1, -1);
  82930. this._rotationRightAsked = false;
  82931. this._rotationLeftAsked = false;
  82932. this._isDefaultTeleportationTarget = true;
  82933. this._teleportationFillColor = "#444444";
  82934. this._teleportationBorderColor = "#FFFFFF";
  82935. this._rotationAngle = 0;
  82936. this._haloCenter = new BABYLON.Vector3(0, 0, 0);
  82937. this._padSensibilityUp = 0.65;
  82938. this._padSensibilityDown = 0.35;
  82939. this.leftController = null;
  82940. this.rightController = null;
  82941. /**
  82942. * Observable raised when a new mesh is selected based on meshSelectionPredicate
  82943. */
  82944. this.onNewMeshSelected = new BABYLON.Observable();
  82945. /**
  82946. * Observable raised when a new mesh is picked based on meshSelectionPredicate
  82947. */
  82948. this.onNewMeshPicked = new BABYLON.Observable();
  82949. /**
  82950. * Observable raised before camera teleportation
  82951. */
  82952. this.onBeforeCameraTeleport = new BABYLON.Observable();
  82953. /**
  82954. * Observable raised after camera teleportation
  82955. */
  82956. this.onAfterCameraTeleport = new BABYLON.Observable();
  82957. /**
  82958. * Observable raised when current selected mesh gets unselected
  82959. */
  82960. this.onSelectedMeshUnselected = new BABYLON.Observable();
  82961. /**
  82962. * Set teleportation enabled. If set to false camera teleportation will be disabled but camera rotation will be kept.
  82963. */
  82964. this.teleportationEnabled = true;
  82965. this._teleportationInitialized = false;
  82966. this._interactionsEnabled = false;
  82967. this._interactionsRequested = false;
  82968. this._displayGaze = true;
  82969. this._displayLaserPointer = true;
  82970. this._onResize = function () {
  82971. _this.moveButtonToBottomRight();
  82972. if (_this._fullscreenVRpresenting && _this._webVRready) {
  82973. _this.exitVR();
  82974. }
  82975. };
  82976. this._onFullscreenChange = function () {
  82977. if (document.fullscreen !== undefined) {
  82978. _this._fullscreenVRpresenting = document.fullscreen;
  82979. }
  82980. else if (document.mozFullScreen !== undefined) {
  82981. _this._fullscreenVRpresenting = document.mozFullScreen;
  82982. }
  82983. else if (document.webkitIsFullScreen !== undefined) {
  82984. _this._fullscreenVRpresenting = document.webkitIsFullScreen;
  82985. }
  82986. else if (document.msIsFullScreen !== undefined) {
  82987. _this._fullscreenVRpresenting = document.msIsFullScreen;
  82988. }
  82989. if (!_this._fullscreenVRpresenting && _this._canvas) {
  82990. _this.exitVR();
  82991. if (!_this._useCustomVRButton) {
  82992. _this._btnVR.style.top = _this._canvas.offsetTop + _this._canvas.offsetHeight - 70 + "px";
  82993. _this._btnVR.style.left = _this._canvas.offsetLeft + _this._canvas.offsetWidth - 100 + "px";
  82994. }
  82995. }
  82996. };
  82997. this.beforeRender = function () {
  82998. if (_this.leftController && _this.leftController._activePointer) {
  82999. _this._castRayAndSelectObject(_this.leftController);
  83000. }
  83001. if (_this.rightController && _this.rightController._activePointer) {
  83002. _this._castRayAndSelectObject(_this.rightController);
  83003. }
  83004. if (!(_this.leftController && _this.leftController._activePointer) && !(_this.rightController && _this.rightController._activePointer)) {
  83005. _this._castRayAndSelectObject(_this._cameraGazer);
  83006. }
  83007. else {
  83008. _this._cameraGazer._gazeTracker.isVisible = false;
  83009. }
  83010. };
  83011. this._onNewGamepadConnected = function (gamepad) {
  83012. if (gamepad.type !== BABYLON.Gamepad.POSE_ENABLED) {
  83013. if (gamepad.leftStick) {
  83014. gamepad.onleftstickchanged(function (stickValues) {
  83015. if (_this._teleportationInitialized && _this.teleportationEnabled) {
  83016. // Listening to classic/xbox gamepad only if no VR controller is active
  83017. if ((!_this.leftController && !_this.rightController) ||
  83018. ((_this.leftController && !_this.leftController._activePointer) &&
  83019. (_this.rightController && !_this.rightController._activePointer))) {
  83020. _this._checkTeleportWithRay(stickValues, _this._cameraGazer);
  83021. _this._checkTeleportBackwards(stickValues, _this._cameraGazer);
  83022. }
  83023. }
  83024. });
  83025. }
  83026. if (gamepad.rightStick) {
  83027. gamepad.onrightstickchanged(function (stickValues) {
  83028. if (_this._teleportationInitialized) {
  83029. _this._checkRotate(stickValues, _this._cameraGazer);
  83030. }
  83031. });
  83032. }
  83033. if (gamepad.type === BABYLON.Gamepad.XBOX) {
  83034. gamepad.onbuttondown(function (buttonPressed) {
  83035. if (_this._interactionsEnabled && buttonPressed === BABYLON.Xbox360Button.A) {
  83036. _this._cameraGazer._selectionPointerDown();
  83037. }
  83038. });
  83039. gamepad.onbuttonup(function (buttonPressed) {
  83040. if (_this._interactionsEnabled && buttonPressed === BABYLON.Xbox360Button.A) {
  83041. _this._cameraGazer._selectionPointerUp();
  83042. }
  83043. });
  83044. }
  83045. }
  83046. else {
  83047. var webVRController = gamepad;
  83048. var controller = new VRExperienceHelperControllerGazer(webVRController, _this._scene, _this._cameraGazer._gazeTracker);
  83049. if (webVRController.hand === "right" || (_this.leftController && _this.leftController.webVRController != webVRController)) {
  83050. _this.rightController = controller;
  83051. }
  83052. else {
  83053. _this.leftController = controller;
  83054. }
  83055. _this._tryEnableInteractionOnController(controller);
  83056. }
  83057. };
  83058. // 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
  83059. this._tryEnableInteractionOnController = function (controller) {
  83060. if (_this._interactionsRequested && !controller._interactionsEnabled) {
  83061. _this._enableInteractionOnController(controller);
  83062. }
  83063. if (_this._teleportationRequested && !controller._teleportationEnabled) {
  83064. _this._enableTeleportationOnController(controller);
  83065. }
  83066. };
  83067. this._onNewGamepadDisconnected = function (gamepad) {
  83068. if (gamepad instanceof BABYLON.WebVRController) {
  83069. if (gamepad.hand === "left" && _this.leftController != null) {
  83070. _this.leftController.dispose();
  83071. _this.leftController = null;
  83072. }
  83073. if (gamepad.hand === "right" && _this.rightController != null) {
  83074. _this.rightController.dispose();
  83075. _this.rightController = null;
  83076. }
  83077. }
  83078. };
  83079. this._workingVector = BABYLON.Vector3.Zero();
  83080. this._workingQuaternion = BABYLON.Quaternion.Identity();
  83081. this._workingMatrix = BABYLON.Matrix.Identity();
  83082. this._scene = scene;
  83083. this._canvas = scene.getEngine().getRenderingCanvas();
  83084. // Parse options
  83085. if (webVROptions.createFallbackVRDeviceOrientationFreeCamera === undefined) {
  83086. webVROptions.createFallbackVRDeviceOrientationFreeCamera = true;
  83087. }
  83088. if (webVROptions.createDeviceOrientationCamera === undefined) {
  83089. webVROptions.createDeviceOrientationCamera = true;
  83090. }
  83091. if (webVROptions.defaultHeight === undefined) {
  83092. webVROptions.defaultHeight = 1.7;
  83093. }
  83094. if (webVROptions.useCustomVRButton) {
  83095. this._useCustomVRButton = true;
  83096. if (webVROptions.customVRButton) {
  83097. this._btnVR = webVROptions.customVRButton;
  83098. }
  83099. }
  83100. if (webVROptions.rayLength) {
  83101. this._rayLength = webVROptions.rayLength;
  83102. }
  83103. this._defaultHeight = webVROptions.defaultHeight;
  83104. if (webVROptions.positionScale) {
  83105. this._rayLength *= webVROptions.positionScale;
  83106. this._defaultHeight *= webVROptions.positionScale;
  83107. }
  83108. // Set position
  83109. if (this._scene.activeCamera) {
  83110. this._position = this._scene.activeCamera.position.clone();
  83111. }
  83112. else {
  83113. this._position = new BABYLON.Vector3(0, this._defaultHeight, 0);
  83114. }
  83115. // Set non-vr camera
  83116. if (webVROptions.createDeviceOrientationCamera || !this._scene.activeCamera) {
  83117. this._deviceOrientationCamera = new BABYLON.DeviceOrientationCamera("deviceOrientationVRHelper", this._position.clone(), scene);
  83118. // Copy data from existing camera
  83119. if (this._scene.activeCamera) {
  83120. this._deviceOrientationCamera.minZ = this._scene.activeCamera.minZ;
  83121. this._deviceOrientationCamera.maxZ = this._scene.activeCamera.maxZ;
  83122. // Set rotation from previous camera
  83123. if (this._scene.activeCamera instanceof BABYLON.TargetCamera && this._scene.activeCamera.rotation) {
  83124. var targetCamera = this._scene.activeCamera;
  83125. if (targetCamera.rotationQuaternion) {
  83126. this._deviceOrientationCamera.rotationQuaternion.copyFrom(targetCamera.rotationQuaternion);
  83127. }
  83128. else {
  83129. this._deviceOrientationCamera.rotationQuaternion.copyFrom(BABYLON.Quaternion.RotationYawPitchRoll(targetCamera.rotation.y, targetCamera.rotation.x, targetCamera.rotation.z));
  83130. }
  83131. this._deviceOrientationCamera.rotation = targetCamera.rotation.clone();
  83132. }
  83133. }
  83134. this._scene.activeCamera = this._deviceOrientationCamera;
  83135. if (this._canvas) {
  83136. this._scene.activeCamera.attachControl(this._canvas);
  83137. }
  83138. }
  83139. else {
  83140. this._existingCamera = this._scene.activeCamera;
  83141. }
  83142. // Create VR cameras
  83143. if (webVROptions.createFallbackVRDeviceOrientationFreeCamera) {
  83144. this._vrDeviceOrientationCamera = new BABYLON.VRDeviceOrientationFreeCamera("VRDeviceOrientationVRHelper", this._position, this._scene);
  83145. }
  83146. this._webVRCamera = new BABYLON.WebVRFreeCamera("WebVRHelper", this._position, this._scene, webVROptions);
  83147. this._webVRCamera.useStandingMatrix();
  83148. this._cameraGazer = new VRExperienceHelperCameraGazer(function () { return _this.currentVRCamera; }, scene);
  83149. // Create default button
  83150. if (!this._useCustomVRButton) {
  83151. this._btnVR = document.createElement("BUTTON");
  83152. this._btnVR.className = "babylonVRicon";
  83153. this._btnVR.id = "babylonVRiconbtn";
  83154. this._btnVR.title = "Click to switch to VR";
  83155. 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) }";
  83156. css += ".babylonVRicon.vrdisplaypresenting { display: none; }";
  83157. // TODO: Add user feedback so that they know what state the VRDisplay is in (disconnected, connected, entering-VR)
  83158. // css += ".babylonVRicon.vrdisplaysupported { }";
  83159. // css += ".babylonVRicon.vrdisplayready { }";
  83160. // css += ".babylonVRicon.vrdisplayrequesting { }";
  83161. var style = document.createElement('style');
  83162. style.appendChild(document.createTextNode(css));
  83163. document.getElementsByTagName('head')[0].appendChild(style);
  83164. this.moveButtonToBottomRight();
  83165. }
  83166. // VR button click event
  83167. if (this._btnVR) {
  83168. this._btnVR.addEventListener("click", function () {
  83169. if (!_this.isInVRMode) {
  83170. _this.enterVR();
  83171. }
  83172. else {
  83173. _this.exitVR();
  83174. }
  83175. });
  83176. }
  83177. // Window events
  83178. window.addEventListener("resize", this._onResize);
  83179. document.addEventListener("fullscreenchange", this._onFullscreenChange, false);
  83180. document.addEventListener("mozfullscreenchange", this._onFullscreenChange, false);
  83181. document.addEventListener("webkitfullscreenchange", this._onFullscreenChange, false);
  83182. document.addEventListener("msfullscreenchange", this._onFullscreenChange, false);
  83183. // Display vr button when headset is connected
  83184. if (webVROptions.createFallbackVRDeviceOrientationFreeCamera) {
  83185. this.displayVRButton();
  83186. }
  83187. else {
  83188. this._scene.getEngine().onVRDisplayChangedObservable.add(function (e) {
  83189. if (e.vrDisplay) {
  83190. _this.displayVRButton();
  83191. }
  83192. });
  83193. }
  83194. // Exiting VR mode using 'ESC' key on desktop
  83195. this._onKeyDown = function (event) {
  83196. if (event.keyCode === 27 && _this.isInVRMode) {
  83197. _this.exitVR();
  83198. }
  83199. };
  83200. document.addEventListener("keydown", this._onKeyDown);
  83201. // Exiting VR mode double tapping the touch screen
  83202. this._scene.onPrePointerObservable.add(function (pointerInfo, eventState) {
  83203. if (_this.isInVRMode) {
  83204. _this.exitVR();
  83205. if (_this._fullscreenVRpresenting) {
  83206. _this._scene.getEngine().switchFullscreen(true);
  83207. }
  83208. }
  83209. }, BABYLON.PointerEventTypes.POINTERDOUBLETAP, false);
  83210. // Listen for WebVR display changes
  83211. this._onVRDisplayChanged = function (eventArgs) { return _this.onVRDisplayChanged(eventArgs); };
  83212. this._onVrDisplayPresentChange = function () { return _this.onVrDisplayPresentChange(); };
  83213. this._onVRRequestPresentStart = function () {
  83214. _this._webVRrequesting = true;
  83215. _this.updateButtonVisibility();
  83216. };
  83217. this._onVRRequestPresentComplete = function (success) {
  83218. _this._webVRrequesting = false;
  83219. _this.updateButtonVisibility();
  83220. };
  83221. scene.getEngine().onVRDisplayChangedObservable.add(this._onVRDisplayChanged);
  83222. scene.getEngine().onVRRequestPresentStart.add(this._onVRRequestPresentStart);
  83223. scene.getEngine().onVRRequestPresentComplete.add(this._onVRRequestPresentComplete);
  83224. window.addEventListener('vrdisplaypresentchange', this._onVrDisplayPresentChange);
  83225. scene.onDisposeObservable.add(function () {
  83226. _this.dispose();
  83227. });
  83228. // Gamepad connection events
  83229. this._webVRCamera.onControllerMeshLoadedObservable.add(function (webVRController) { return _this._onDefaultMeshLoaded(webVRController); });
  83230. this._scene.gamepadManager.onGamepadConnectedObservable.add(this._onNewGamepadConnected);
  83231. this._scene.gamepadManager.onGamepadDisconnectedObservable.add(this._onNewGamepadDisconnected);
  83232. this.updateButtonVisibility();
  83233. //create easing functions
  83234. this._circleEase = new BABYLON.CircleEase();
  83235. this._circleEase.setEasingMode(BABYLON.EasingFunction.EASINGMODE_EASEINOUT);
  83236. }
  83237. Object.defineProperty(VRExperienceHelper.prototype, "onEnteringVR", {
  83238. /** Return this.onEnteringVRObservable
  83239. * Note: This one is for backward compatibility. Please use onEnteringVRObservable directly
  83240. */
  83241. get: function () {
  83242. return this.onEnteringVRObservable;
  83243. },
  83244. enumerable: true,
  83245. configurable: true
  83246. });
  83247. Object.defineProperty(VRExperienceHelper.prototype, "onExitingVR", {
  83248. /** Return this.onExitingVRObservable
  83249. * Note: This one is for backward compatibility. Please use onExitingVRObservable directly
  83250. */
  83251. get: function () {
  83252. return this.onExitingVRObservable;
  83253. },
  83254. enumerable: true,
  83255. configurable: true
  83256. });
  83257. Object.defineProperty(VRExperienceHelper.prototype, "onControllerMeshLoaded", {
  83258. /** Return this.onControllerMeshLoadedObservable
  83259. * Note: This one is for backward compatibility. Please use onControllerMeshLoadedObservable directly
  83260. */
  83261. get: function () {
  83262. return this.onControllerMeshLoadedObservable;
  83263. },
  83264. enumerable: true,
  83265. configurable: true
  83266. });
  83267. Object.defineProperty(VRExperienceHelper.prototype, "teleportationTarget", {
  83268. /**
  83269. * The mesh used to display where the user is going to teleport.
  83270. */
  83271. get: function () {
  83272. return this._teleportationTarget;
  83273. },
  83274. /**
  83275. * Sets the mesh to be used to display where the user is going to teleport.
  83276. */
  83277. set: function (value) {
  83278. if (value) {
  83279. value.name = "teleportationTarget";
  83280. this._isDefaultTeleportationTarget = false;
  83281. this._teleportationTarget = value;
  83282. }
  83283. },
  83284. enumerable: true,
  83285. configurable: true
  83286. });
  83287. Object.defineProperty(VRExperienceHelper.prototype, "gazeTrackerMesh", {
  83288. /**
  83289. * The mesh used to display where the user is selecting,
  83290. * when set bakeCurrentTransformIntoVertices will be called on the mesh.
  83291. * See http://doc.babylonjs.com/resources/baking_transformations
  83292. */
  83293. get: function () {
  83294. return this._cameraGazer._gazeTracker;
  83295. },
  83296. set: function (value) {
  83297. if (value) {
  83298. this._cameraGazer._gazeTracker = value;
  83299. this._cameraGazer._gazeTracker.bakeCurrentTransformIntoVertices();
  83300. this._cameraGazer._gazeTracker.isPickable = false;
  83301. this._cameraGazer._gazeTracker.isVisible = false;
  83302. this._cameraGazer._gazeTracker.name = "gazeTracker";
  83303. if (this.leftController) {
  83304. this.leftController._gazeTracker = this._cameraGazer._gazeTracker.clone("gazeTracker");
  83305. }
  83306. if (this.rightController) {
  83307. this.rightController._gazeTracker = this._cameraGazer._gazeTracker.clone("gazeTracker");
  83308. }
  83309. }
  83310. },
  83311. enumerable: true,
  83312. configurable: true
  83313. });
  83314. Object.defineProperty(VRExperienceHelper.prototype, "displayGaze", {
  83315. /**
  83316. * If the ray of the gaze should be displayed.
  83317. */
  83318. get: function () {
  83319. return this._displayGaze;
  83320. },
  83321. /**
  83322. * Sets if the ray of the gaze should be displayed.
  83323. */
  83324. set: function (value) {
  83325. this._displayGaze = value;
  83326. if (!value) {
  83327. this._cameraGazer._gazeTracker.isVisible = false;
  83328. if (this.leftController) {
  83329. this.leftController._gazeTracker.isVisible = false;
  83330. }
  83331. if (this.rightController) {
  83332. this.rightController._gazeTracker.isVisible = false;
  83333. }
  83334. }
  83335. },
  83336. enumerable: true,
  83337. configurable: true
  83338. });
  83339. Object.defineProperty(VRExperienceHelper.prototype, "displayLaserPointer", {
  83340. /**
  83341. * If the ray of the LaserPointer should be displayed.
  83342. */
  83343. get: function () {
  83344. return this._displayLaserPointer;
  83345. },
  83346. /**
  83347. * Sets if the ray of the LaserPointer should be displayed.
  83348. */
  83349. set: function (value) {
  83350. this._displayLaserPointer = value;
  83351. if (!value) {
  83352. if (this.rightController) {
  83353. this.rightController._deactivatePointer();
  83354. this.rightController._gazeTracker.isVisible = false;
  83355. }
  83356. if (this.leftController) {
  83357. this.leftController._deactivatePointer();
  83358. this.leftController._gazeTracker.isVisible = false;
  83359. }
  83360. }
  83361. else {
  83362. if (this.rightController) {
  83363. this.rightController._activatePointer();
  83364. }
  83365. else if (this.leftController) {
  83366. this.leftController._activatePointer();
  83367. }
  83368. }
  83369. },
  83370. enumerable: true,
  83371. configurable: true
  83372. });
  83373. Object.defineProperty(VRExperienceHelper.prototype, "deviceOrientationCamera", {
  83374. /**
  83375. * The deviceOrientationCamera used as the camera when not in VR.
  83376. */
  83377. get: function () {
  83378. return this._deviceOrientationCamera;
  83379. },
  83380. enumerable: true,
  83381. configurable: true
  83382. });
  83383. Object.defineProperty(VRExperienceHelper.prototype, "currentVRCamera", {
  83384. /**
  83385. * Based on the current WebVR support, returns the current VR camera used.
  83386. */
  83387. get: function () {
  83388. if (this._webVRready) {
  83389. return this._webVRCamera;
  83390. }
  83391. else {
  83392. return this._scene.activeCamera;
  83393. }
  83394. },
  83395. enumerable: true,
  83396. configurable: true
  83397. });
  83398. Object.defineProperty(VRExperienceHelper.prototype, "webVRCamera", {
  83399. /**
  83400. * The webVRCamera which is used when in VR.
  83401. */
  83402. get: function () {
  83403. return this._webVRCamera;
  83404. },
  83405. enumerable: true,
  83406. configurable: true
  83407. });
  83408. Object.defineProperty(VRExperienceHelper.prototype, "vrDeviceOrientationCamera", {
  83409. /**
  83410. * The deviceOrientationCamera that is used as a fallback when vr device is not connected.
  83411. */
  83412. get: function () {
  83413. return this._vrDeviceOrientationCamera;
  83414. },
  83415. enumerable: true,
  83416. configurable: true
  83417. });
  83418. Object.defineProperty(VRExperienceHelper.prototype, "_teleportationRequestInitiated", {
  83419. get: function () {
  83420. var result = this._cameraGazer._teleportationRequestInitiated
  83421. || (this.leftController !== null && this.leftController._teleportationRequestInitiated)
  83422. || (this.rightController !== null && this.rightController._teleportationRequestInitiated);
  83423. return result;
  83424. },
  83425. enumerable: true,
  83426. configurable: true
  83427. });
  83428. // Raised when one of the controller has loaded successfully its associated default mesh
  83429. VRExperienceHelper.prototype._onDefaultMeshLoaded = function (webVRController) {
  83430. if (this.leftController && this.leftController.webVRController == webVRController) {
  83431. if (webVRController.mesh) {
  83432. this.leftController._setLaserPointerParent(webVRController.mesh);
  83433. }
  83434. }
  83435. if (this.rightController && this.rightController.webVRController == webVRController) {
  83436. if (webVRController.mesh) {
  83437. this.rightController._setLaserPointerParent(webVRController.mesh);
  83438. }
  83439. }
  83440. try {
  83441. this.onControllerMeshLoadedObservable.notifyObservers(webVRController);
  83442. }
  83443. catch (err) {
  83444. BABYLON.Tools.Warn("Error in your custom logic onControllerMeshLoaded: " + err);
  83445. }
  83446. };
  83447. Object.defineProperty(VRExperienceHelper.prototype, "isInVRMode", {
  83448. /**
  83449. * Gets a value indicating if we are currently in VR mode.
  83450. */
  83451. get: function () {
  83452. return this._webVRpresenting || this._fullscreenVRpresenting;
  83453. },
  83454. enumerable: true,
  83455. configurable: true
  83456. });
  83457. VRExperienceHelper.prototype.onVrDisplayPresentChange = function () {
  83458. var vrDisplay = this._scene.getEngine().getVRDevice();
  83459. if (vrDisplay) {
  83460. var wasPresenting = this._webVRpresenting;
  83461. // A VR display is connected
  83462. this._webVRpresenting = vrDisplay.isPresenting;
  83463. if (wasPresenting && !this._webVRpresenting)
  83464. this.exitVR();
  83465. }
  83466. else {
  83467. BABYLON.Tools.Warn('Detected VRDisplayPresentChange on an unknown VRDisplay. Did you can enterVR on the vrExperienceHelper?');
  83468. }
  83469. this.updateButtonVisibility();
  83470. };
  83471. VRExperienceHelper.prototype.onVRDisplayChanged = function (eventArgs) {
  83472. this._webVRsupported = eventArgs.vrSupported;
  83473. this._webVRready = !!eventArgs.vrDisplay;
  83474. this._webVRpresenting = eventArgs.vrDisplay && eventArgs.vrDisplay.isPresenting;
  83475. this.updateButtonVisibility();
  83476. };
  83477. VRExperienceHelper.prototype.moveButtonToBottomRight = function () {
  83478. if (this._canvas && !this._useCustomVRButton) {
  83479. this._btnVR.style.top = this._canvas.offsetTop + this._canvas.offsetHeight - 70 + "px";
  83480. this._btnVR.style.left = this._canvas.offsetLeft + this._canvas.offsetWidth - 100 + "px";
  83481. }
  83482. };
  83483. VRExperienceHelper.prototype.displayVRButton = function () {
  83484. if (!this._useCustomVRButton && !this._btnVRDisplayed) {
  83485. document.body.appendChild(this._btnVR);
  83486. this._btnVRDisplayed = true;
  83487. }
  83488. };
  83489. VRExperienceHelper.prototype.updateButtonVisibility = function () {
  83490. if (!this._btnVR || this._useCustomVRButton) {
  83491. return;
  83492. }
  83493. this._btnVR.className = "babylonVRicon";
  83494. if (this.isInVRMode) {
  83495. this._btnVR.className += " vrdisplaypresenting";
  83496. }
  83497. else {
  83498. if (this._webVRready)
  83499. this._btnVR.className += " vrdisplayready";
  83500. if (this._webVRsupported)
  83501. this._btnVR.className += " vrdisplaysupported";
  83502. if (this._webVRrequesting)
  83503. this._btnVR.className += " vrdisplayrequesting";
  83504. }
  83505. };
  83506. /**
  83507. * Attempt to enter VR. If a headset is connected and ready, will request present on that.
  83508. * Otherwise, will use the fullscreen API.
  83509. */
  83510. VRExperienceHelper.prototype.enterVR = function () {
  83511. if (this.onEnteringVRObservable) {
  83512. try {
  83513. this.onEnteringVRObservable.notifyObservers(this);
  83514. }
  83515. catch (err) {
  83516. BABYLON.Tools.Warn("Error in your custom logic onEnteringVR: " + err);
  83517. }
  83518. }
  83519. if (this._scene.activeCamera) {
  83520. this._position = this._scene.activeCamera.position.clone();
  83521. // make sure that we return to the last active camera
  83522. this._existingCamera = this._scene.activeCamera;
  83523. }
  83524. if (this._webVRrequesting)
  83525. return;
  83526. // If WebVR is supported and a headset is connected
  83527. if (this._webVRready) {
  83528. if (!this._webVRpresenting) {
  83529. this._webVRCamera.position = this._position;
  83530. this._scene.activeCamera = this._webVRCamera;
  83531. }
  83532. }
  83533. else if (this._vrDeviceOrientationCamera) {
  83534. this._vrDeviceOrientationCamera.position = this._position;
  83535. this._scene.activeCamera = this._vrDeviceOrientationCamera;
  83536. this._scene.getEngine().switchFullscreen(true);
  83537. this.updateButtonVisibility();
  83538. }
  83539. if (this._scene.activeCamera && this._canvas) {
  83540. this._scene.activeCamera.attachControl(this._canvas);
  83541. }
  83542. if (this._interactionsEnabled) {
  83543. this._scene.registerBeforeRender(this.beforeRender);
  83544. }
  83545. };
  83546. /**
  83547. * Attempt to exit VR, or fullscreen.
  83548. */
  83549. VRExperienceHelper.prototype.exitVR = function () {
  83550. if (this.onExitingVRObservable) {
  83551. try {
  83552. this.onExitingVRObservable.notifyObservers(this);
  83553. }
  83554. catch (err) {
  83555. BABYLON.Tools.Warn("Error in your custom logic onExitingVR: " + err);
  83556. }
  83557. }
  83558. if (this._webVRpresenting) {
  83559. this._scene.getEngine().disableVR();
  83560. }
  83561. if (this._scene.activeCamera) {
  83562. this._position = this._scene.activeCamera.position.clone();
  83563. }
  83564. if (this._deviceOrientationCamera) {
  83565. this._deviceOrientationCamera.position = this._position;
  83566. this._scene.activeCamera = this._deviceOrientationCamera;
  83567. if (this._canvas) {
  83568. this._scene.activeCamera.attachControl(this._canvas);
  83569. }
  83570. }
  83571. else if (this._existingCamera) {
  83572. this._existingCamera.position = this._position;
  83573. this._scene.activeCamera = this._existingCamera;
  83574. }
  83575. this.updateButtonVisibility();
  83576. if (this._interactionsEnabled) {
  83577. this._scene.unregisterBeforeRender(this.beforeRender);
  83578. }
  83579. };
  83580. Object.defineProperty(VRExperienceHelper.prototype, "position", {
  83581. /**
  83582. * The position of the vr experience helper.
  83583. */
  83584. get: function () {
  83585. return this._position;
  83586. },
  83587. /**
  83588. * Sets the position of the vr experience helper.
  83589. */
  83590. set: function (value) {
  83591. this._position = value;
  83592. if (this._scene.activeCamera) {
  83593. this._scene.activeCamera.position = value;
  83594. }
  83595. },
  83596. enumerable: true,
  83597. configurable: true
  83598. });
  83599. /**
  83600. * Enables controllers and user interactions suck as selecting and object or clicking on an object.
  83601. */
  83602. VRExperienceHelper.prototype.enableInteractions = function () {
  83603. var _this = this;
  83604. if (!this._interactionsEnabled) {
  83605. this._interactionsRequested = true;
  83606. if (this.leftController) {
  83607. this._enableInteractionOnController(this.leftController);
  83608. }
  83609. if (this.rightController) {
  83610. this._enableInteractionOnController(this.rightController);
  83611. }
  83612. this.raySelectionPredicate = function (mesh) {
  83613. return mesh.isVisible;
  83614. };
  83615. this.meshSelectionPredicate = function (mesh) {
  83616. return true;
  83617. };
  83618. this._raySelectionPredicate = function (mesh) {
  83619. if (_this._isTeleportationFloor(mesh) || (mesh.name.indexOf("gazeTracker") === -1
  83620. && mesh.name.indexOf("teleportationTarget") === -1
  83621. && mesh.name.indexOf("torusTeleportation") === -1
  83622. && mesh.name.indexOf("laserPointer") === -1)) {
  83623. return _this.raySelectionPredicate(mesh);
  83624. }
  83625. return false;
  83626. };
  83627. this._interactionsEnabled = true;
  83628. }
  83629. };
  83630. VRExperienceHelper.prototype._isTeleportationFloor = function (mesh) {
  83631. for (var i = 0; i < this._floorMeshesCollection.length; i++) {
  83632. if (this._floorMeshesCollection[i].id === mesh.id) {
  83633. return true;
  83634. }
  83635. }
  83636. if (this._floorMeshName && mesh.name === this._floorMeshName) {
  83637. return true;
  83638. }
  83639. return false;
  83640. };
  83641. /**
  83642. * Adds a floor mesh to be used for teleportation.
  83643. * @param floorMesh the mesh to be used for teleportation.
  83644. */
  83645. VRExperienceHelper.prototype.addFloorMesh = function (floorMesh) {
  83646. if (!this._floorMeshesCollection) {
  83647. return;
  83648. }
  83649. if (this._floorMeshesCollection.indexOf(floorMesh) > -1) {
  83650. return;
  83651. }
  83652. this._floorMeshesCollection.push(floorMesh);
  83653. };
  83654. /**
  83655. * Removes a floor mesh from being used for teleportation.
  83656. * @param floorMesh the mesh to be removed.
  83657. */
  83658. VRExperienceHelper.prototype.removeFloorMesh = function (floorMesh) {
  83659. if (!this._floorMeshesCollection) {
  83660. return;
  83661. }
  83662. var meshIndex = this._floorMeshesCollection.indexOf(floorMesh);
  83663. if (meshIndex !== -1) {
  83664. this._floorMeshesCollection.splice(meshIndex, 1);
  83665. }
  83666. };
  83667. /**
  83668. * Enables interactions and teleportation using the VR controllers and gaze.
  83669. * @param vrTeleportationOptions options to modify teleportation behavior.
  83670. */
  83671. VRExperienceHelper.prototype.enableTeleportation = function (vrTeleportationOptions) {
  83672. if (vrTeleportationOptions === void 0) { vrTeleportationOptions = {}; }
  83673. if (!this._teleportationInitialized) {
  83674. this._teleportationRequested = true;
  83675. this.enableInteractions();
  83676. if (vrTeleportationOptions.floorMeshName) {
  83677. this._floorMeshName = vrTeleportationOptions.floorMeshName;
  83678. }
  83679. if (vrTeleportationOptions.floorMeshes) {
  83680. this._floorMeshesCollection = vrTeleportationOptions.floorMeshes;
  83681. }
  83682. if (this.leftController != null) {
  83683. this._enableTeleportationOnController(this.leftController);
  83684. }
  83685. if (this.rightController != null) {
  83686. this._enableTeleportationOnController(this.rightController);
  83687. }
  83688. // Creates an image processing post process for the vignette not relying
  83689. // on the main scene configuration for image processing to reduce setup and spaces
  83690. // (gamma/linear) conflicts.
  83691. var imageProcessingConfiguration = new BABYLON.ImageProcessingConfiguration();
  83692. imageProcessingConfiguration.vignetteColor = new BABYLON.Color4(0, 0, 0, 0);
  83693. imageProcessingConfiguration.vignetteEnabled = true;
  83694. this._postProcessMove = new BABYLON.ImageProcessingPostProcess("postProcessMove", 1.0, this._webVRCamera, undefined, undefined, undefined, undefined, imageProcessingConfiguration);
  83695. this._webVRCamera.detachPostProcess(this._postProcessMove);
  83696. this._teleportationInitialized = true;
  83697. if (this._isDefaultTeleportationTarget) {
  83698. this._createTeleportationCircles();
  83699. this._teleportationTarget.scaling.scaleInPlace(this._webVRCamera.deviceScaleFactor);
  83700. }
  83701. }
  83702. };
  83703. VRExperienceHelper.prototype._enableInteractionOnController = function (controller) {
  83704. var _this = this;
  83705. var controllerMesh = controller.webVRController.mesh;
  83706. if (controllerMesh) {
  83707. controller._interactionsEnabled = true;
  83708. controller._activatePointer();
  83709. controller.webVRController.onMainButtonStateChangedObservable.add(function (stateObject) {
  83710. // Enabling / disabling laserPointer
  83711. if (_this._displayLaserPointer && stateObject.value === 1) {
  83712. if (controller._activePointer) {
  83713. controller._deactivatePointer();
  83714. }
  83715. else {
  83716. controller._activatePointer();
  83717. }
  83718. if (_this.displayGaze) {
  83719. controller._gazeTracker.isVisible = controller._activePointer;
  83720. }
  83721. }
  83722. });
  83723. controller.webVRController.onTriggerStateChangedObservable.add(function (stateObject) {
  83724. if (!controller._pointerDownOnMeshAsked) {
  83725. if (stateObject.value > _this._padSensibilityUp) {
  83726. controller._selectionPointerDown();
  83727. }
  83728. }
  83729. else if (stateObject.value < _this._padSensibilityDown) {
  83730. controller._selectionPointerUp();
  83731. }
  83732. });
  83733. }
  83734. };
  83735. VRExperienceHelper.prototype._checkTeleportWithRay = function (stateObject, gazer) {
  83736. // Dont teleport if another gaze already requested teleportation
  83737. if (this._teleportationRequestInitiated && !gazer._teleportationRequestInitiated) {
  83738. return;
  83739. }
  83740. if (!gazer._teleportationRequestInitiated) {
  83741. if (stateObject.y < -this._padSensibilityUp && gazer._dpadPressed) {
  83742. gazer._activatePointer();
  83743. gazer._teleportationRequestInitiated = true;
  83744. }
  83745. }
  83746. else {
  83747. // Listening to the proper controller values changes to confirm teleportation
  83748. if (Math.sqrt(stateObject.y * stateObject.y + stateObject.x * stateObject.x) < this._padSensibilityDown) {
  83749. if (this._teleportActive) {
  83750. this._teleportCamera(this._haloCenter);
  83751. }
  83752. gazer._teleportationRequestInitiated = false;
  83753. }
  83754. }
  83755. };
  83756. VRExperienceHelper.prototype._checkRotate = function (stateObject, gazer) {
  83757. // Only rotate when user is not currently selecting a teleportation location
  83758. if (gazer._teleportationRequestInitiated) {
  83759. return;
  83760. }
  83761. if (!this._rotationLeftAsked) {
  83762. if (stateObject.x < -this._padSensibilityUp && gazer._dpadPressed) {
  83763. this._rotationLeftAsked = true;
  83764. if (this._rotationAllowed) {
  83765. this._rotateCamera(false);
  83766. }
  83767. }
  83768. }
  83769. else {
  83770. if (stateObject.x > -this._padSensibilityDown) {
  83771. this._rotationLeftAsked = false;
  83772. }
  83773. }
  83774. if (!this._rotationRightAsked) {
  83775. if (stateObject.x > this._padSensibilityUp && gazer._dpadPressed) {
  83776. this._rotationRightAsked = true;
  83777. if (this._rotationAllowed) {
  83778. this._rotateCamera(true);
  83779. }
  83780. }
  83781. }
  83782. else {
  83783. if (stateObject.x < this._padSensibilityDown) {
  83784. this._rotationRightAsked = false;
  83785. }
  83786. }
  83787. };
  83788. VRExperienceHelper.prototype._checkTeleportBackwards = function (stateObject, gazer) {
  83789. // Only teleport backwards when user is not currently selecting a teleportation location
  83790. if (gazer._teleportationRequestInitiated) {
  83791. return;
  83792. }
  83793. // Teleport backwards
  83794. if (stateObject.y > this._padSensibilityUp && gazer._dpadPressed) {
  83795. if (!gazer._teleportationBackRequestInitiated) {
  83796. if (!this.currentVRCamera) {
  83797. return;
  83798. }
  83799. // Get rotation and position of the current camera
  83800. var rotation = BABYLON.Quaternion.FromRotationMatrix(this.currentVRCamera.getWorldMatrix().getRotationMatrix());
  83801. var position = this.currentVRCamera.position;
  83802. // If the camera has device position, use that instead
  83803. if (this.currentVRCamera.devicePosition && this.currentVRCamera.deviceRotationQuaternion) {
  83804. rotation = this.currentVRCamera.deviceRotationQuaternion;
  83805. position = this.currentVRCamera.devicePosition;
  83806. }
  83807. // Get matrix with only the y rotation of the device rotation
  83808. rotation.toEulerAnglesToRef(this._workingVector);
  83809. this._workingVector.z = 0;
  83810. this._workingVector.x = 0;
  83811. BABYLON.Quaternion.RotationYawPitchRollToRef(this._workingVector.y, this._workingVector.x, this._workingVector.z, this._workingQuaternion);
  83812. this._workingQuaternion.toRotationMatrix(this._workingMatrix);
  83813. // Rotate backwards ray by device rotation to cast at the ground behind the user
  83814. BABYLON.Vector3.TransformCoordinatesToRef(this._teleportBackwardsVector, this._workingMatrix, this._workingVector);
  83815. // Teleport if ray hit the ground and is not to far away eg. backwards off a cliff
  83816. var ray = new BABYLON.Ray(position, this._workingVector);
  83817. var hit = this._scene.pickWithRay(ray, this._raySelectionPredicate);
  83818. if (hit && hit.pickedPoint && hit.pickedMesh && this._isTeleportationFloor(hit.pickedMesh) && hit.distance < 5) {
  83819. this._teleportCamera(hit.pickedPoint);
  83820. }
  83821. gazer._teleportationBackRequestInitiated = true;
  83822. }
  83823. }
  83824. else {
  83825. gazer._teleportationBackRequestInitiated = false;
  83826. }
  83827. };
  83828. VRExperienceHelper.prototype._enableTeleportationOnController = function (controller) {
  83829. var _this = this;
  83830. var controllerMesh = controller.webVRController.mesh;
  83831. if (controllerMesh) {
  83832. if (!controller._interactionsEnabled) {
  83833. this._enableInteractionOnController(controller);
  83834. }
  83835. controller._interactionsEnabled = true;
  83836. controller._teleportationEnabled = true;
  83837. if (controller.webVRController.controllerType === BABYLON.PoseEnabledControllerType.VIVE) {
  83838. controller._dpadPressed = false;
  83839. controller.webVRController.onPadStateChangedObservable.add(function (stateObject) {
  83840. controller._dpadPressed = stateObject.pressed;
  83841. if (!controller._dpadPressed) {
  83842. _this._rotationLeftAsked = false;
  83843. _this._rotationRightAsked = false;
  83844. controller._teleportationBackRequestInitiated = false;
  83845. }
  83846. });
  83847. }
  83848. controller.webVRController.onPadValuesChangedObservable.add(function (stateObject) {
  83849. if (_this.teleportationEnabled) {
  83850. _this._checkTeleportBackwards(stateObject, controller);
  83851. _this._checkTeleportWithRay(stateObject, controller);
  83852. }
  83853. _this._checkRotate(stateObject, controller);
  83854. });
  83855. }
  83856. };
  83857. VRExperienceHelper.prototype._createTeleportationCircles = function () {
  83858. this._teleportationTarget = BABYLON.Mesh.CreateGround("teleportationTarget", 2, 2, 2, this._scene);
  83859. this._teleportationTarget.isPickable = false;
  83860. var length = 512;
  83861. var dynamicTexture = new BABYLON.DynamicTexture("DynamicTexture", length, this._scene, true);
  83862. dynamicTexture.hasAlpha = true;
  83863. var context = dynamicTexture.getContext();
  83864. var centerX = length / 2;
  83865. var centerY = length / 2;
  83866. var radius = 200;
  83867. context.beginPath();
  83868. context.arc(centerX, centerY, radius, 0, 2 * Math.PI, false);
  83869. context.fillStyle = this._teleportationFillColor;
  83870. context.fill();
  83871. context.lineWidth = 10;
  83872. context.strokeStyle = this._teleportationBorderColor;
  83873. context.stroke();
  83874. context.closePath();
  83875. dynamicTexture.update();
  83876. var teleportationCircleMaterial = new BABYLON.StandardMaterial("TextPlaneMaterial", this._scene);
  83877. teleportationCircleMaterial.diffuseTexture = dynamicTexture;
  83878. this._teleportationTarget.material = teleportationCircleMaterial;
  83879. var torus = BABYLON.Mesh.CreateTorus("torusTeleportation", 0.75, 0.1, 25, this._scene, false);
  83880. torus.isPickable = false;
  83881. torus.parent = this._teleportationTarget;
  83882. var animationInnerCircle = new BABYLON.Animation("animationInnerCircle", "position.y", 30, BABYLON.Animation.ANIMATIONTYPE_FLOAT, BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE);
  83883. var keys = [];
  83884. keys.push({
  83885. frame: 0,
  83886. value: 0
  83887. });
  83888. keys.push({
  83889. frame: 30,
  83890. value: 0.4
  83891. });
  83892. keys.push({
  83893. frame: 60,
  83894. value: 0
  83895. });
  83896. animationInnerCircle.setKeys(keys);
  83897. var easingFunction = new BABYLON.SineEase();
  83898. easingFunction.setEasingMode(BABYLON.EasingFunction.EASINGMODE_EASEINOUT);
  83899. animationInnerCircle.setEasingFunction(easingFunction);
  83900. torus.animations = [];
  83901. torus.animations.push(animationInnerCircle);
  83902. this._scene.beginAnimation(torus, 0, 60, true);
  83903. this._hideTeleportationTarget();
  83904. };
  83905. VRExperienceHelper.prototype._displayTeleportationTarget = function () {
  83906. this._teleportActive = true;
  83907. if (this._teleportationInitialized) {
  83908. this._teleportationTarget.isVisible = true;
  83909. if (this._isDefaultTeleportationTarget) {
  83910. this._teleportationTarget.getChildren()[0].isVisible = true;
  83911. }
  83912. }
  83913. };
  83914. VRExperienceHelper.prototype._hideTeleportationTarget = function () {
  83915. this._teleportActive = false;
  83916. if (this._teleportationInitialized) {
  83917. this._teleportationTarget.isVisible = false;
  83918. if (this._isDefaultTeleportationTarget) {
  83919. this._teleportationTarget.getChildren()[0].isVisible = false;
  83920. }
  83921. }
  83922. };
  83923. VRExperienceHelper.prototype._rotateCamera = function (right) {
  83924. var _this = this;
  83925. if (!(this.currentVRCamera instanceof BABYLON.FreeCamera)) {
  83926. return;
  83927. }
  83928. if (right) {
  83929. this._rotationAngle++;
  83930. }
  83931. else {
  83932. this._rotationAngle--;
  83933. }
  83934. this.currentVRCamera.animations = [];
  83935. var target = BABYLON.Quaternion.FromRotationMatrix(BABYLON.Matrix.RotationY(Math.PI / 4 * this._rotationAngle));
  83936. var animationRotation = new BABYLON.Animation("animationRotation", "rotationQuaternion", 90, BABYLON.Animation.ANIMATIONTYPE_QUATERNION, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  83937. var animationRotationKeys = [];
  83938. animationRotationKeys.push({
  83939. frame: 0,
  83940. value: this.currentVRCamera.rotationQuaternion
  83941. });
  83942. animationRotationKeys.push({
  83943. frame: 6,
  83944. value: target
  83945. });
  83946. animationRotation.setKeys(animationRotationKeys);
  83947. animationRotation.setEasingFunction(this._circleEase);
  83948. this.currentVRCamera.animations.push(animationRotation);
  83949. this._postProcessMove.animations = [];
  83950. var animationPP = new BABYLON.Animation("animationPP", "vignetteWeight", 90, BABYLON.Animation.ANIMATIONTYPE_FLOAT, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  83951. var vignetteWeightKeys = [];
  83952. vignetteWeightKeys.push({
  83953. frame: 0,
  83954. value: 0
  83955. });
  83956. vignetteWeightKeys.push({
  83957. frame: 3,
  83958. value: 4
  83959. });
  83960. vignetteWeightKeys.push({
  83961. frame: 6,
  83962. value: 0
  83963. });
  83964. animationPP.setKeys(vignetteWeightKeys);
  83965. animationPP.setEasingFunction(this._circleEase);
  83966. this._postProcessMove.animations.push(animationPP);
  83967. var animationPP2 = new BABYLON.Animation("animationPP2", "vignetteStretch", 90, BABYLON.Animation.ANIMATIONTYPE_FLOAT, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  83968. var vignetteStretchKeys = [];
  83969. vignetteStretchKeys.push({
  83970. frame: 0,
  83971. value: 0
  83972. });
  83973. vignetteStretchKeys.push({
  83974. frame: 3,
  83975. value: 10
  83976. });
  83977. vignetteStretchKeys.push({
  83978. frame: 6,
  83979. value: 0
  83980. });
  83981. animationPP2.setKeys(vignetteStretchKeys);
  83982. animationPP2.setEasingFunction(this._circleEase);
  83983. this._postProcessMove.animations.push(animationPP2);
  83984. this._postProcessMove.imageProcessingConfiguration.vignetteWeight = 0;
  83985. this._postProcessMove.imageProcessingConfiguration.vignetteStretch = 0;
  83986. this._postProcessMove.samples = 4;
  83987. this._webVRCamera.attachPostProcess(this._postProcessMove);
  83988. this._scene.beginAnimation(this._postProcessMove, 0, 6, false, 1, function () {
  83989. _this._webVRCamera.detachPostProcess(_this._postProcessMove);
  83990. });
  83991. this._scene.beginAnimation(this.currentVRCamera, 0, 6, false, 1);
  83992. };
  83993. VRExperienceHelper.prototype._moveTeleportationSelectorTo = function (hit, gazer) {
  83994. if (hit.pickedPoint) {
  83995. if (gazer._teleportationRequestInitiated) {
  83996. this._displayTeleportationTarget();
  83997. this._haloCenter.copyFrom(hit.pickedPoint);
  83998. this._teleportationTarget.position.copyFrom(hit.pickedPoint);
  83999. }
  84000. var pickNormal = hit.getNormal(true, false);
  84001. if (pickNormal) {
  84002. var axis1 = BABYLON.Vector3.Cross(BABYLON.Axis.Y, pickNormal);
  84003. var axis2 = BABYLON.Vector3.Cross(pickNormal, axis1);
  84004. BABYLON.Vector3.RotationFromAxisToRef(axis2, pickNormal, axis1, this._teleportationTarget.rotation);
  84005. }
  84006. this._teleportationTarget.position.y += 0.1;
  84007. }
  84008. };
  84009. VRExperienceHelper.prototype._teleportCamera = function (location) {
  84010. var _this = this;
  84011. if (!(this.currentVRCamera instanceof BABYLON.FreeCamera)) {
  84012. return;
  84013. }
  84014. // Teleport the hmd to where the user is looking by moving the anchor to where they are looking minus the
  84015. // offset of the headset from the anchor.
  84016. if (this.webVRCamera.leftCamera) {
  84017. this._workingVector.copyFrom(this.webVRCamera.leftCamera.globalPosition);
  84018. this._workingVector.subtractInPlace(this.webVRCamera.position);
  84019. location.subtractToRef(this._workingVector, this._workingVector);
  84020. }
  84021. else {
  84022. this._workingVector.copyFrom(location);
  84023. }
  84024. // Add height to account for user's height offset
  84025. if (this.isInVRMode) {
  84026. this._workingVector.y += this.webVRCamera.deviceDistanceToRoomGround() * this._webVRCamera.deviceScaleFactor;
  84027. }
  84028. else {
  84029. this._workingVector.y += this._defaultHeight;
  84030. }
  84031. this.onBeforeCameraTeleport.notifyObservers(this._workingVector);
  84032. // Create animation from the camera's position to the new location
  84033. this.currentVRCamera.animations = [];
  84034. var animationCameraTeleportation = new BABYLON.Animation("animationCameraTeleportation", "position", 90, BABYLON.Animation.ANIMATIONTYPE_VECTOR3, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  84035. var animationCameraTeleportationKeys = [{
  84036. frame: 0,
  84037. value: this.currentVRCamera.position
  84038. },
  84039. {
  84040. frame: 11,
  84041. value: this._workingVector
  84042. }
  84043. ];
  84044. animationCameraTeleportation.setKeys(animationCameraTeleportationKeys);
  84045. animationCameraTeleportation.setEasingFunction(this._circleEase);
  84046. this.currentVRCamera.animations.push(animationCameraTeleportation);
  84047. this._postProcessMove.animations = [];
  84048. var animationPP = new BABYLON.Animation("animationPP", "vignetteWeight", 90, BABYLON.Animation.ANIMATIONTYPE_FLOAT, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  84049. var vignetteWeightKeys = [];
  84050. vignetteWeightKeys.push({
  84051. frame: 0,
  84052. value: 0
  84053. });
  84054. vignetteWeightKeys.push({
  84055. frame: 5,
  84056. value: 8
  84057. });
  84058. vignetteWeightKeys.push({
  84059. frame: 11,
  84060. value: 0
  84061. });
  84062. animationPP.setKeys(vignetteWeightKeys);
  84063. this._postProcessMove.animations.push(animationPP);
  84064. var animationPP2 = new BABYLON.Animation("animationPP2", "vignetteStretch", 90, BABYLON.Animation.ANIMATIONTYPE_FLOAT, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  84065. var vignetteStretchKeys = [];
  84066. vignetteStretchKeys.push({
  84067. frame: 0,
  84068. value: 0
  84069. });
  84070. vignetteStretchKeys.push({
  84071. frame: 5,
  84072. value: 10
  84073. });
  84074. vignetteStretchKeys.push({
  84075. frame: 11,
  84076. value: 0
  84077. });
  84078. animationPP2.setKeys(vignetteStretchKeys);
  84079. this._postProcessMove.animations.push(animationPP2);
  84080. this._postProcessMove.imageProcessingConfiguration.vignetteWeight = 0;
  84081. this._postProcessMove.imageProcessingConfiguration.vignetteStretch = 0;
  84082. this._webVRCamera.attachPostProcess(this._postProcessMove);
  84083. this._scene.beginAnimation(this._postProcessMove, 0, 11, false, 1, function () {
  84084. _this._webVRCamera.detachPostProcess(_this._postProcessMove);
  84085. });
  84086. this._scene.beginAnimation(this.currentVRCamera, 0, 11, false, 1, function () {
  84087. _this.onAfterCameraTeleport.notifyObservers(_this._workingVector);
  84088. });
  84089. this._hideTeleportationTarget();
  84090. };
  84091. VRExperienceHelper.prototype._castRayAndSelectObject = function (gazer) {
  84092. if (!(this.currentVRCamera instanceof BABYLON.FreeCamera)) {
  84093. return;
  84094. }
  84095. var hit = this._scene.pickWithRay(gazer._getForwardRay(this._rayLength), this._raySelectionPredicate);
  84096. // Moving the gazeTracker on the mesh face targetted
  84097. if (hit && hit.pickedPoint) {
  84098. if (this._displayGaze) {
  84099. var multiplier = 1;
  84100. gazer._gazeTracker.isVisible = true;
  84101. if (gazer._isActionableMesh) {
  84102. multiplier = 3;
  84103. }
  84104. gazer._gazeTracker.scaling.x = hit.distance * multiplier;
  84105. gazer._gazeTracker.scaling.y = hit.distance * multiplier;
  84106. gazer._gazeTracker.scaling.z = hit.distance * multiplier;
  84107. var pickNormal = hit.getNormal();
  84108. // To avoid z-fighting
  84109. var deltaFighting = 0.002;
  84110. if (pickNormal) {
  84111. var axis1 = BABYLON.Vector3.Cross(BABYLON.Axis.Y, pickNormal);
  84112. var axis2 = BABYLON.Vector3.Cross(pickNormal, axis1);
  84113. BABYLON.Vector3.RotationFromAxisToRef(axis2, pickNormal, axis1, gazer._gazeTracker.rotation);
  84114. }
  84115. gazer._gazeTracker.position.copyFrom(hit.pickedPoint);
  84116. if (gazer._gazeTracker.position.x < 0) {
  84117. gazer._gazeTracker.position.x += deltaFighting;
  84118. }
  84119. else {
  84120. gazer._gazeTracker.position.x -= deltaFighting;
  84121. }
  84122. if (gazer._gazeTracker.position.y < 0) {
  84123. gazer._gazeTracker.position.y += deltaFighting;
  84124. }
  84125. else {
  84126. gazer._gazeTracker.position.y -= deltaFighting;
  84127. }
  84128. if (gazer._gazeTracker.position.z < 0) {
  84129. gazer._gazeTracker.position.z += deltaFighting;
  84130. }
  84131. else {
  84132. gazer._gazeTracker.position.z -= deltaFighting;
  84133. }
  84134. }
  84135. // Changing the size of the laser pointer based on the distance from the targetted point
  84136. gazer._updatePointerDistance(hit.distance);
  84137. }
  84138. else {
  84139. gazer._gazeTracker.isVisible = false;
  84140. }
  84141. if (hit && hit.pickedMesh) {
  84142. gazer._currentHit = hit;
  84143. if (gazer._pointerDownOnMeshAsked) {
  84144. this._scene.simulatePointerMove(gazer._currentHit, { pointerId: gazer._id });
  84145. }
  84146. // The object selected is the floor, we're in a teleportation scenario
  84147. if (this._teleportationInitialized && this._isTeleportationFloor(hit.pickedMesh) && hit.pickedPoint) {
  84148. // Moving the teleportation area to this targetted point
  84149. //Raise onSelectedMeshUnselected observable if ray collided floor mesh/meshes and a non floor mesh was previously selected
  84150. if (gazer._currentMeshSelected && !this._isTeleportationFloor(gazer._currentMeshSelected)) {
  84151. this._notifySelectedMeshUnselected(gazer._currentMeshSelected);
  84152. }
  84153. gazer._currentMeshSelected = null;
  84154. if (gazer._teleportationRequestInitiated) {
  84155. this._moveTeleportationSelectorTo(hit, gazer);
  84156. }
  84157. return;
  84158. }
  84159. // If not, we're in a selection scenario
  84160. //this._teleportationAllowed = false;
  84161. if (hit.pickedMesh !== gazer._currentMeshSelected) {
  84162. if (this.meshSelectionPredicate(hit.pickedMesh)) {
  84163. this.onNewMeshPicked.notifyObservers(hit);
  84164. gazer._currentMeshSelected = hit.pickedMesh;
  84165. if (hit.pickedMesh.isPickable && hit.pickedMesh.actionManager) {
  84166. this.changeGazeColor(new BABYLON.Color3(0, 0, 1));
  84167. this.changeLaserColor(new BABYLON.Color3(0.2, 0.2, 1));
  84168. gazer._isActionableMesh = true;
  84169. }
  84170. else {
  84171. this.changeGazeColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  84172. this.changeLaserColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  84173. gazer._isActionableMesh = false;
  84174. }
  84175. try {
  84176. this.onNewMeshSelected.notifyObservers(hit.pickedMesh);
  84177. }
  84178. catch (err) {
  84179. BABYLON.Tools.Warn("Error in your custom logic onNewMeshSelected: " + err);
  84180. }
  84181. }
  84182. else {
  84183. this._notifySelectedMeshUnselected(gazer._currentMeshSelected);
  84184. gazer._currentMeshSelected = null;
  84185. this.changeGazeColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  84186. this.changeLaserColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  84187. }
  84188. }
  84189. }
  84190. else {
  84191. gazer._currentHit = null;
  84192. this._notifySelectedMeshUnselected(gazer._currentMeshSelected);
  84193. gazer._currentMeshSelected = null;
  84194. //this._teleportationAllowed = false;
  84195. this.changeGazeColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  84196. this.changeLaserColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  84197. }
  84198. };
  84199. VRExperienceHelper.prototype._notifySelectedMeshUnselected = function (mesh) {
  84200. if (mesh) {
  84201. this.onSelectedMeshUnselected.notifyObservers(mesh);
  84202. }
  84203. };
  84204. /**
  84205. * Sets the color of the laser ray from the vr controllers.
  84206. * @param color new color for the ray.
  84207. */
  84208. VRExperienceHelper.prototype.changeLaserColor = function (color) {
  84209. if (this.leftController) {
  84210. this.leftController._setLaserPointerColor(color);
  84211. }
  84212. if (this.rightController) {
  84213. this.rightController._setLaserPointerColor(color);
  84214. }
  84215. };
  84216. /**
  84217. * Sets the color of the ray from the vr headsets gaze.
  84218. * @param color new color for the ray.
  84219. */
  84220. VRExperienceHelper.prototype.changeGazeColor = function (color) {
  84221. if (!this._cameraGazer._gazeTracker.material) {
  84222. return;
  84223. }
  84224. this._cameraGazer._gazeTracker.material.emissiveColor = color;
  84225. if (this.leftController) {
  84226. this.leftController._gazeTracker.material.emissiveColor = color;
  84227. }
  84228. if (this.rightController) {
  84229. this.rightController._gazeTracker.material.emissiveColor = color;
  84230. }
  84231. };
  84232. /**
  84233. * Exits VR and disposes of the vr experience helper
  84234. */
  84235. VRExperienceHelper.prototype.dispose = function () {
  84236. if (this.isInVRMode) {
  84237. this.exitVR();
  84238. }
  84239. if (this._postProcessMove) {
  84240. this._postProcessMove.dispose();
  84241. }
  84242. if (this._webVRCamera) {
  84243. this._webVRCamera.dispose();
  84244. }
  84245. if (this._vrDeviceOrientationCamera) {
  84246. this._vrDeviceOrientationCamera.dispose();
  84247. }
  84248. if (!this._useCustomVRButton && this._btnVR.parentNode) {
  84249. document.body.removeChild(this._btnVR);
  84250. }
  84251. if (this._deviceOrientationCamera && (this._scene.activeCamera != this._deviceOrientationCamera)) {
  84252. this._deviceOrientationCamera.dispose();
  84253. }
  84254. if (this._cameraGazer) {
  84255. this._cameraGazer.dispose();
  84256. }
  84257. if (this.leftController) {
  84258. this.leftController.dispose();
  84259. }
  84260. if (this.rightController) {
  84261. this.rightController.dispose();
  84262. }
  84263. if (this._teleportationTarget) {
  84264. this._teleportationTarget.dispose();
  84265. }
  84266. this._floorMeshesCollection = [];
  84267. document.removeEventListener("keydown", this._onKeyDown);
  84268. window.removeEventListener('vrdisplaypresentchange', this._onVrDisplayPresentChange);
  84269. window.removeEventListener("resize", this._onResize);
  84270. document.removeEventListener("fullscreenchange", this._onFullscreenChange);
  84271. document.removeEventListener("mozfullscreenchange", this._onFullscreenChange);
  84272. document.removeEventListener("webkitfullscreenchange", this._onFullscreenChange);
  84273. document.removeEventListener("msfullscreenchange", this._onFullscreenChange);
  84274. this._scene.getEngine().onVRDisplayChangedObservable.removeCallback(this._onVRDisplayChanged);
  84275. this._scene.getEngine().onVRRequestPresentStart.removeCallback(this._onVRRequestPresentStart);
  84276. this._scene.getEngine().onVRRequestPresentComplete.removeCallback(this._onVRRequestPresentComplete);
  84277. window.removeEventListener('vrdisplaypresentchange', this._onVrDisplayPresentChange);
  84278. this._scene.gamepadManager.onGamepadConnectedObservable.removeCallback(this._onNewGamepadConnected);
  84279. this._scene.gamepadManager.onGamepadDisconnectedObservable.removeCallback(this._onNewGamepadDisconnected);
  84280. this._scene.unregisterBeforeRender(this.beforeRender);
  84281. };
  84282. /**
  84283. * Gets the name of the VRExperienceHelper class
  84284. * @returns "VRExperienceHelper"
  84285. */
  84286. VRExperienceHelper.prototype.getClassName = function () {
  84287. return "VRExperienceHelper";
  84288. };
  84289. return VRExperienceHelper;
  84290. }());
  84291. BABYLON.VRExperienceHelper = VRExperienceHelper;
  84292. })(BABYLON || (BABYLON = {}));
  84293. //# sourceMappingURL=babylon.vrExperienceHelper.js.map
  84294. "use strict";
  84295. // Mainly based on these 2 articles :
  84296. // 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
  84297. // & on Seb Lee-Delisle original work: http://seb.ly/2011/04/multi-touch-game-controller-in-javascripthtml5-for-ipad/
  84298. var BABYLON;
  84299. (function (BABYLON) {
  84300. var JoystickAxis;
  84301. (function (JoystickAxis) {
  84302. JoystickAxis[JoystickAxis["X"] = 0] = "X";
  84303. JoystickAxis[JoystickAxis["Y"] = 1] = "Y";
  84304. JoystickAxis[JoystickAxis["Z"] = 2] = "Z";
  84305. })(JoystickAxis = BABYLON.JoystickAxis || (BABYLON.JoystickAxis = {}));
  84306. var VirtualJoystick = /** @class */ (function () {
  84307. function VirtualJoystick(leftJoystick) {
  84308. var _this = this;
  84309. if (leftJoystick) {
  84310. this._leftJoystick = true;
  84311. }
  84312. else {
  84313. this._leftJoystick = false;
  84314. }
  84315. VirtualJoystick._globalJoystickIndex++;
  84316. // By default left & right arrow keys are moving the X
  84317. // and up & down keys are moving the Y
  84318. this._axisTargetedByLeftAndRight = JoystickAxis.X;
  84319. this._axisTargetedByUpAndDown = JoystickAxis.Y;
  84320. this.reverseLeftRight = false;
  84321. this.reverseUpDown = false;
  84322. // collections of pointers
  84323. this._touches = new BABYLON.StringDictionary();
  84324. this.deltaPosition = BABYLON.Vector3.Zero();
  84325. this._joystickSensibility = 25;
  84326. this._inversedSensibility = 1 / (this._joystickSensibility / 1000);
  84327. this._onResize = function (evt) {
  84328. VirtualJoystick.vjCanvasWidth = window.innerWidth;
  84329. VirtualJoystick.vjCanvasHeight = window.innerHeight;
  84330. if (VirtualJoystick.vjCanvas) {
  84331. VirtualJoystick.vjCanvas.width = VirtualJoystick.vjCanvasWidth;
  84332. VirtualJoystick.vjCanvas.height = VirtualJoystick.vjCanvasHeight;
  84333. }
  84334. VirtualJoystick.halfWidth = VirtualJoystick.vjCanvasWidth / 2;
  84335. };
  84336. // injecting a canvas element on top of the canvas 3D game
  84337. if (!VirtualJoystick.vjCanvas) {
  84338. window.addEventListener("resize", this._onResize, false);
  84339. VirtualJoystick.vjCanvas = document.createElement("canvas");
  84340. VirtualJoystick.vjCanvasWidth = window.innerWidth;
  84341. VirtualJoystick.vjCanvasHeight = window.innerHeight;
  84342. VirtualJoystick.vjCanvas.width = window.innerWidth;
  84343. VirtualJoystick.vjCanvas.height = window.innerHeight;
  84344. VirtualJoystick.vjCanvas.style.width = "100%";
  84345. VirtualJoystick.vjCanvas.style.height = "100%";
  84346. VirtualJoystick.vjCanvas.style.position = "absolute";
  84347. VirtualJoystick.vjCanvas.style.backgroundColor = "transparent";
  84348. VirtualJoystick.vjCanvas.style.top = "0px";
  84349. VirtualJoystick.vjCanvas.style.left = "0px";
  84350. VirtualJoystick.vjCanvas.style.zIndex = "5";
  84351. VirtualJoystick.vjCanvas.style.msTouchAction = "none";
  84352. // Support for jQuery PEP polyfill
  84353. VirtualJoystick.vjCanvas.setAttribute("touch-action", "none");
  84354. var context = VirtualJoystick.vjCanvas.getContext('2d');
  84355. if (!context) {
  84356. throw new Error("Unable to create canvas for virtual joystick");
  84357. }
  84358. VirtualJoystick.vjCanvasContext = context;
  84359. VirtualJoystick.vjCanvasContext.strokeStyle = "#ffffff";
  84360. VirtualJoystick.vjCanvasContext.lineWidth = 2;
  84361. document.body.appendChild(VirtualJoystick.vjCanvas);
  84362. }
  84363. VirtualJoystick.halfWidth = VirtualJoystick.vjCanvas.width / 2;
  84364. this.pressed = false;
  84365. // default joystick color
  84366. this._joystickColor = "cyan";
  84367. this._joystickPointerID = -1;
  84368. // current joystick position
  84369. this._joystickPointerPos = new BABYLON.Vector2(0, 0);
  84370. this._joystickPreviousPointerPos = new BABYLON.Vector2(0, 0);
  84371. // origin joystick position
  84372. this._joystickPointerStartPos = new BABYLON.Vector2(0, 0);
  84373. this._deltaJoystickVector = new BABYLON.Vector2(0, 0);
  84374. this._onPointerDownHandlerRef = function (evt) {
  84375. _this._onPointerDown(evt);
  84376. };
  84377. this._onPointerMoveHandlerRef = function (evt) {
  84378. _this._onPointerMove(evt);
  84379. };
  84380. this._onPointerUpHandlerRef = function (evt) {
  84381. _this._onPointerUp(evt);
  84382. };
  84383. VirtualJoystick.vjCanvas.addEventListener('pointerdown', this._onPointerDownHandlerRef, false);
  84384. VirtualJoystick.vjCanvas.addEventListener('pointermove', this._onPointerMoveHandlerRef, false);
  84385. VirtualJoystick.vjCanvas.addEventListener('pointerup', this._onPointerUpHandlerRef, false);
  84386. VirtualJoystick.vjCanvas.addEventListener('pointerout', this._onPointerUpHandlerRef, false);
  84387. VirtualJoystick.vjCanvas.addEventListener("contextmenu", function (evt) {
  84388. evt.preventDefault(); // Disables system menu
  84389. }, false);
  84390. requestAnimationFrame(function () { _this._drawVirtualJoystick(); });
  84391. }
  84392. VirtualJoystick.prototype.setJoystickSensibility = function (newJoystickSensibility) {
  84393. this._joystickSensibility = newJoystickSensibility;
  84394. this._inversedSensibility = 1 / (this._joystickSensibility / 1000);
  84395. };
  84396. VirtualJoystick.prototype._onPointerDown = function (e) {
  84397. var positionOnScreenCondition;
  84398. e.preventDefault();
  84399. if (this._leftJoystick === true) {
  84400. positionOnScreenCondition = (e.clientX < VirtualJoystick.halfWidth);
  84401. }
  84402. else {
  84403. positionOnScreenCondition = (e.clientX > VirtualJoystick.halfWidth);
  84404. }
  84405. if (positionOnScreenCondition && this._joystickPointerID < 0) {
  84406. // First contact will be dedicated to the virtual joystick
  84407. this._joystickPointerID = e.pointerId;
  84408. this._joystickPointerStartPos.x = e.clientX;
  84409. this._joystickPointerStartPos.y = e.clientY;
  84410. this._joystickPointerPos = this._joystickPointerStartPos.clone();
  84411. this._joystickPreviousPointerPos = this._joystickPointerStartPos.clone();
  84412. this._deltaJoystickVector.x = 0;
  84413. this._deltaJoystickVector.y = 0;
  84414. this.pressed = true;
  84415. this._touches.add(e.pointerId.toString(), e);
  84416. }
  84417. else {
  84418. // You can only trigger the action buttons with a joystick declared
  84419. if (VirtualJoystick._globalJoystickIndex < 2 && this._action) {
  84420. this._action();
  84421. this._touches.add(e.pointerId.toString(), { x: e.clientX, y: e.clientY, prevX: e.clientX, prevY: e.clientY });
  84422. }
  84423. }
  84424. };
  84425. VirtualJoystick.prototype._onPointerMove = function (e) {
  84426. // If the current pointer is the one associated to the joystick (first touch contact)
  84427. if (this._joystickPointerID == e.pointerId) {
  84428. this._joystickPointerPos.x = e.clientX;
  84429. this._joystickPointerPos.y = e.clientY;
  84430. this._deltaJoystickVector = this._joystickPointerPos.clone();
  84431. this._deltaJoystickVector = this._deltaJoystickVector.subtract(this._joystickPointerStartPos);
  84432. var directionLeftRight = this.reverseLeftRight ? -1 : 1;
  84433. var deltaJoystickX = directionLeftRight * this._deltaJoystickVector.x / this._inversedSensibility;
  84434. switch (this._axisTargetedByLeftAndRight) {
  84435. case JoystickAxis.X:
  84436. this.deltaPosition.x = Math.min(1, Math.max(-1, deltaJoystickX));
  84437. break;
  84438. case JoystickAxis.Y:
  84439. this.deltaPosition.y = Math.min(1, Math.max(-1, deltaJoystickX));
  84440. break;
  84441. case JoystickAxis.Z:
  84442. this.deltaPosition.z = Math.min(1, Math.max(-1, deltaJoystickX));
  84443. break;
  84444. }
  84445. var directionUpDown = this.reverseUpDown ? 1 : -1;
  84446. var deltaJoystickY = directionUpDown * this._deltaJoystickVector.y / this._inversedSensibility;
  84447. switch (this._axisTargetedByUpAndDown) {
  84448. case JoystickAxis.X:
  84449. this.deltaPosition.x = Math.min(1, Math.max(-1, deltaJoystickY));
  84450. break;
  84451. case JoystickAxis.Y:
  84452. this.deltaPosition.y = Math.min(1, Math.max(-1, deltaJoystickY));
  84453. break;
  84454. case JoystickAxis.Z:
  84455. this.deltaPosition.z = Math.min(1, Math.max(-1, deltaJoystickY));
  84456. break;
  84457. }
  84458. }
  84459. else {
  84460. var data = this._touches.get(e.pointerId.toString());
  84461. if (data) {
  84462. data.x = e.clientX;
  84463. data.y = e.clientY;
  84464. }
  84465. }
  84466. };
  84467. VirtualJoystick.prototype._onPointerUp = function (e) {
  84468. if (this._joystickPointerID == e.pointerId) {
  84469. VirtualJoystick.vjCanvasContext.clearRect(this._joystickPointerStartPos.x - 64, this._joystickPointerStartPos.y - 64, 128, 128);
  84470. VirtualJoystick.vjCanvasContext.clearRect(this._joystickPreviousPointerPos.x - 42, this._joystickPreviousPointerPos.y - 42, 84, 84);
  84471. this._joystickPointerID = -1;
  84472. this.pressed = false;
  84473. }
  84474. else {
  84475. var touch = this._touches.get(e.pointerId.toString());
  84476. if (touch) {
  84477. VirtualJoystick.vjCanvasContext.clearRect(touch.prevX - 44, touch.prevY - 44, 88, 88);
  84478. }
  84479. }
  84480. this._deltaJoystickVector.x = 0;
  84481. this._deltaJoystickVector.y = 0;
  84482. this._touches.remove(e.pointerId.toString());
  84483. };
  84484. /**
  84485. * Change the color of the virtual joystick
  84486. * @param newColor a string that must be a CSS color value (like "red") or the hexa value (like "#FF0000")
  84487. */
  84488. VirtualJoystick.prototype.setJoystickColor = function (newColor) {
  84489. this._joystickColor = newColor;
  84490. };
  84491. VirtualJoystick.prototype.setActionOnTouch = function (action) {
  84492. this._action = action;
  84493. };
  84494. // Define which axis you'd like to control for left & right
  84495. VirtualJoystick.prototype.setAxisForLeftRight = function (axis) {
  84496. switch (axis) {
  84497. case JoystickAxis.X:
  84498. case JoystickAxis.Y:
  84499. case JoystickAxis.Z:
  84500. this._axisTargetedByLeftAndRight = axis;
  84501. break;
  84502. default:
  84503. this._axisTargetedByLeftAndRight = JoystickAxis.X;
  84504. break;
  84505. }
  84506. };
  84507. // Define which axis you'd like to control for up & down
  84508. VirtualJoystick.prototype.setAxisForUpDown = function (axis) {
  84509. switch (axis) {
  84510. case JoystickAxis.X:
  84511. case JoystickAxis.Y:
  84512. case JoystickAxis.Z:
  84513. this._axisTargetedByUpAndDown = axis;
  84514. break;
  84515. default:
  84516. this._axisTargetedByUpAndDown = JoystickAxis.Y;
  84517. break;
  84518. }
  84519. };
  84520. VirtualJoystick.prototype._drawVirtualJoystick = function () {
  84521. var _this = this;
  84522. if (this.pressed) {
  84523. this._touches.forEach(function (key, touch) {
  84524. if (touch.pointerId === _this._joystickPointerID) {
  84525. VirtualJoystick.vjCanvasContext.clearRect(_this._joystickPointerStartPos.x - 64, _this._joystickPointerStartPos.y - 64, 128, 128);
  84526. VirtualJoystick.vjCanvasContext.clearRect(_this._joystickPreviousPointerPos.x - 42, _this._joystickPreviousPointerPos.y - 42, 84, 84);
  84527. VirtualJoystick.vjCanvasContext.beginPath();
  84528. VirtualJoystick.vjCanvasContext.lineWidth = 6;
  84529. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  84530. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerStartPos.x, _this._joystickPointerStartPos.y, 40, 0, Math.PI * 2, true);
  84531. VirtualJoystick.vjCanvasContext.stroke();
  84532. VirtualJoystick.vjCanvasContext.closePath();
  84533. VirtualJoystick.vjCanvasContext.beginPath();
  84534. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  84535. VirtualJoystick.vjCanvasContext.lineWidth = 2;
  84536. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerStartPos.x, _this._joystickPointerStartPos.y, 60, 0, Math.PI * 2, true);
  84537. VirtualJoystick.vjCanvasContext.stroke();
  84538. VirtualJoystick.vjCanvasContext.closePath();
  84539. VirtualJoystick.vjCanvasContext.beginPath();
  84540. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  84541. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerPos.x, _this._joystickPointerPos.y, 40, 0, Math.PI * 2, true);
  84542. VirtualJoystick.vjCanvasContext.stroke();
  84543. VirtualJoystick.vjCanvasContext.closePath();
  84544. _this._joystickPreviousPointerPos = _this._joystickPointerPos.clone();
  84545. }
  84546. else {
  84547. VirtualJoystick.vjCanvasContext.clearRect(touch.prevX - 44, touch.prevY - 44, 88, 88);
  84548. VirtualJoystick.vjCanvasContext.beginPath();
  84549. VirtualJoystick.vjCanvasContext.fillStyle = "white";
  84550. VirtualJoystick.vjCanvasContext.beginPath();
  84551. VirtualJoystick.vjCanvasContext.strokeStyle = "red";
  84552. VirtualJoystick.vjCanvasContext.lineWidth = 6;
  84553. VirtualJoystick.vjCanvasContext.arc(touch.x, touch.y, 40, 0, Math.PI * 2, true);
  84554. VirtualJoystick.vjCanvasContext.stroke();
  84555. VirtualJoystick.vjCanvasContext.closePath();
  84556. touch.prevX = touch.x;
  84557. touch.prevY = touch.y;
  84558. }
  84559. ;
  84560. });
  84561. }
  84562. requestAnimationFrame(function () { _this._drawVirtualJoystick(); });
  84563. };
  84564. VirtualJoystick.prototype.releaseCanvas = function () {
  84565. if (VirtualJoystick.vjCanvas) {
  84566. VirtualJoystick.vjCanvas.removeEventListener('pointerdown', this._onPointerDownHandlerRef);
  84567. VirtualJoystick.vjCanvas.removeEventListener('pointermove', this._onPointerMoveHandlerRef);
  84568. VirtualJoystick.vjCanvas.removeEventListener('pointerup', this._onPointerUpHandlerRef);
  84569. VirtualJoystick.vjCanvas.removeEventListener('pointerout', this._onPointerUpHandlerRef);
  84570. window.removeEventListener("resize", this._onResize);
  84571. document.body.removeChild(VirtualJoystick.vjCanvas);
  84572. VirtualJoystick.vjCanvas = null;
  84573. }
  84574. };
  84575. // Used to draw the virtual joystick inside a 2D canvas on top of the WebGL rendering canvas
  84576. VirtualJoystick._globalJoystickIndex = 0;
  84577. return VirtualJoystick;
  84578. }());
  84579. BABYLON.VirtualJoystick = VirtualJoystick;
  84580. })(BABYLON || (BABYLON = {}));
  84581. //# sourceMappingURL=babylon.virtualJoystick.js.map
  84582. "use strict";
  84583. var BABYLON;
  84584. (function (BABYLON) {
  84585. // We're mainly based on the logic defined into the FreeCamera code
  84586. var VirtualJoysticksCamera = /** @class */ (function (_super) {
  84587. __extends(VirtualJoysticksCamera, _super);
  84588. function VirtualJoysticksCamera(name, position, scene) {
  84589. var _this = _super.call(this, name, position, scene) || this;
  84590. _this.inputs.addVirtualJoystick();
  84591. return _this;
  84592. }
  84593. VirtualJoysticksCamera.prototype.getClassName = function () {
  84594. return "VirtualJoysticksCamera";
  84595. };
  84596. return VirtualJoysticksCamera;
  84597. }(BABYLON.FreeCamera));
  84598. BABYLON.VirtualJoysticksCamera = VirtualJoysticksCamera;
  84599. })(BABYLON || (BABYLON = {}));
  84600. //# sourceMappingURL=babylon.virtualJoysticksCamera.js.map
  84601. "use strict";
  84602. var BABYLON;
  84603. (function (BABYLON) {
  84604. var FreeCameraVirtualJoystickInput = /** @class */ (function () {
  84605. function FreeCameraVirtualJoystickInput() {
  84606. }
  84607. FreeCameraVirtualJoystickInput.prototype.getLeftJoystick = function () {
  84608. return this._leftjoystick;
  84609. };
  84610. FreeCameraVirtualJoystickInput.prototype.getRightJoystick = function () {
  84611. return this._rightjoystick;
  84612. };
  84613. FreeCameraVirtualJoystickInput.prototype.checkInputs = function () {
  84614. if (this._leftjoystick) {
  84615. var camera = this.camera;
  84616. var speed = camera._computeLocalCameraSpeed() * 50;
  84617. var cameraTransform = BABYLON.Matrix.RotationYawPitchRoll(camera.rotation.y, camera.rotation.x, 0);
  84618. var deltaTransform = BABYLON.Vector3.TransformCoordinates(new BABYLON.Vector3(this._leftjoystick.deltaPosition.x * speed, this._leftjoystick.deltaPosition.y * speed, this._leftjoystick.deltaPosition.z * speed), cameraTransform);
  84619. camera.cameraDirection = camera.cameraDirection.add(deltaTransform);
  84620. camera.cameraRotation = camera.cameraRotation.addVector3(this._rightjoystick.deltaPosition);
  84621. if (!this._leftjoystick.pressed) {
  84622. this._leftjoystick.deltaPosition = this._leftjoystick.deltaPosition.scale(0.9);
  84623. }
  84624. if (!this._rightjoystick.pressed) {
  84625. this._rightjoystick.deltaPosition = this._rightjoystick.deltaPosition.scale(0.9);
  84626. }
  84627. }
  84628. };
  84629. FreeCameraVirtualJoystickInput.prototype.attachControl = function (element, noPreventDefault) {
  84630. this._leftjoystick = new BABYLON.VirtualJoystick(true);
  84631. this._leftjoystick.setAxisForUpDown(BABYLON.JoystickAxis.Z);
  84632. this._leftjoystick.setAxisForLeftRight(BABYLON.JoystickAxis.X);
  84633. this._leftjoystick.setJoystickSensibility(0.15);
  84634. this._rightjoystick = new BABYLON.VirtualJoystick(false);
  84635. this._rightjoystick.setAxisForUpDown(BABYLON.JoystickAxis.X);
  84636. this._rightjoystick.setAxisForLeftRight(BABYLON.JoystickAxis.Y);
  84637. this._rightjoystick.reverseUpDown = true;
  84638. this._rightjoystick.setJoystickSensibility(0.05);
  84639. this._rightjoystick.setJoystickColor("yellow");
  84640. };
  84641. FreeCameraVirtualJoystickInput.prototype.detachControl = function (element) {
  84642. this._leftjoystick.releaseCanvas();
  84643. this._rightjoystick.releaseCanvas();
  84644. };
  84645. FreeCameraVirtualJoystickInput.prototype.getClassName = function () {
  84646. return "FreeCameraVirtualJoystickInput";
  84647. };
  84648. FreeCameraVirtualJoystickInput.prototype.getSimpleName = function () {
  84649. return "virtualJoystick";
  84650. };
  84651. return FreeCameraVirtualJoystickInput;
  84652. }());
  84653. BABYLON.FreeCameraVirtualJoystickInput = FreeCameraVirtualJoystickInput;
  84654. BABYLON.CameraInputTypes["FreeCameraVirtualJoystickInput"] = FreeCameraVirtualJoystickInput;
  84655. })(BABYLON || (BABYLON = {}));
  84656. //# sourceMappingURL=babylon.freeCameraVirtualJoystickInput.js.map
  84657. "use strict";
  84658. var BABYLON;
  84659. (function (BABYLON) {
  84660. var SimplificationSettings = /** @class */ (function () {
  84661. function SimplificationSettings(quality, distance, optimizeMesh) {
  84662. this.quality = quality;
  84663. this.distance = distance;
  84664. this.optimizeMesh = optimizeMesh;
  84665. }
  84666. return SimplificationSettings;
  84667. }());
  84668. BABYLON.SimplificationSettings = SimplificationSettings;
  84669. var SimplificationQueue = /** @class */ (function () {
  84670. function SimplificationQueue() {
  84671. this.running = false;
  84672. this._simplificationArray = [];
  84673. }
  84674. SimplificationQueue.prototype.addTask = function (task) {
  84675. this._simplificationArray.push(task);
  84676. };
  84677. SimplificationQueue.prototype.executeNext = function () {
  84678. var task = this._simplificationArray.pop();
  84679. if (task) {
  84680. this.running = true;
  84681. this.runSimplification(task);
  84682. }
  84683. else {
  84684. this.running = false;
  84685. }
  84686. };
  84687. SimplificationQueue.prototype.runSimplification = function (task) {
  84688. var _this = this;
  84689. if (task.parallelProcessing) {
  84690. //parallel simplifier
  84691. task.settings.forEach(function (setting) {
  84692. var simplifier = _this.getSimplifier(task);
  84693. simplifier.simplify(setting, function (newMesh) {
  84694. task.mesh.addLODLevel(setting.distance, newMesh);
  84695. newMesh.isVisible = true;
  84696. //check if it is the last
  84697. if (setting.quality === task.settings[task.settings.length - 1].quality && task.successCallback) {
  84698. //all done, run the success callback.
  84699. task.successCallback();
  84700. }
  84701. _this.executeNext();
  84702. });
  84703. });
  84704. }
  84705. else {
  84706. //single simplifier.
  84707. var simplifier = this.getSimplifier(task);
  84708. var runDecimation = function (setting, callback) {
  84709. simplifier.simplify(setting, function (newMesh) {
  84710. task.mesh.addLODLevel(setting.distance, newMesh);
  84711. newMesh.isVisible = true;
  84712. //run the next quality level
  84713. callback();
  84714. });
  84715. };
  84716. BABYLON.AsyncLoop.Run(task.settings.length, function (loop) {
  84717. runDecimation(task.settings[loop.index], function () {
  84718. loop.executeNext();
  84719. });
  84720. }, function () {
  84721. //execution ended, run the success callback.
  84722. if (task.successCallback) {
  84723. task.successCallback();
  84724. }
  84725. _this.executeNext();
  84726. });
  84727. }
  84728. };
  84729. SimplificationQueue.prototype.getSimplifier = function (task) {
  84730. switch (task.simplificationType) {
  84731. case SimplificationType.QUADRATIC:
  84732. default:
  84733. return new QuadraticErrorSimplification(task.mesh);
  84734. }
  84735. };
  84736. return SimplificationQueue;
  84737. }());
  84738. BABYLON.SimplificationQueue = SimplificationQueue;
  84739. /**
  84740. * The implemented types of simplification.
  84741. * At the moment only Quadratic Error Decimation is implemented.
  84742. */
  84743. var SimplificationType;
  84744. (function (SimplificationType) {
  84745. SimplificationType[SimplificationType["QUADRATIC"] = 0] = "QUADRATIC";
  84746. })(SimplificationType = BABYLON.SimplificationType || (BABYLON.SimplificationType = {}));
  84747. var DecimationTriangle = /** @class */ (function () {
  84748. function DecimationTriangle(vertices) {
  84749. this.vertices = vertices;
  84750. this.error = new Array(4);
  84751. this.deleted = false;
  84752. this.isDirty = false;
  84753. this.deletePending = false;
  84754. this.borderFactor = 0;
  84755. }
  84756. return DecimationTriangle;
  84757. }());
  84758. BABYLON.DecimationTriangle = DecimationTriangle;
  84759. var DecimationVertex = /** @class */ (function () {
  84760. function DecimationVertex(position, id) {
  84761. this.position = position;
  84762. this.id = id;
  84763. this.isBorder = true;
  84764. this.q = new QuadraticMatrix();
  84765. this.triangleCount = 0;
  84766. this.triangleStart = 0;
  84767. this.originalOffsets = [];
  84768. }
  84769. DecimationVertex.prototype.updatePosition = function (newPosition) {
  84770. this.position.copyFrom(newPosition);
  84771. };
  84772. return DecimationVertex;
  84773. }());
  84774. BABYLON.DecimationVertex = DecimationVertex;
  84775. var QuadraticMatrix = /** @class */ (function () {
  84776. function QuadraticMatrix(data) {
  84777. this.data = new Array(10);
  84778. for (var i = 0; i < 10; ++i) {
  84779. if (data && data[i]) {
  84780. this.data[i] = data[i];
  84781. }
  84782. else {
  84783. this.data[i] = 0;
  84784. }
  84785. }
  84786. }
  84787. QuadraticMatrix.prototype.det = function (a11, a12, a13, a21, a22, a23, a31, a32, a33) {
  84788. var det = this.data[a11] * this.data[a22] * this.data[a33] + this.data[a13] * this.data[a21] * this.data[a32] +
  84789. this.data[a12] * this.data[a23] * this.data[a31] - this.data[a13] * this.data[a22] * this.data[a31] -
  84790. this.data[a11] * this.data[a23] * this.data[a32] - this.data[a12] * this.data[a21] * this.data[a33];
  84791. return det;
  84792. };
  84793. QuadraticMatrix.prototype.addInPlace = function (matrix) {
  84794. for (var i = 0; i < 10; ++i) {
  84795. this.data[i] += matrix.data[i];
  84796. }
  84797. };
  84798. QuadraticMatrix.prototype.addArrayInPlace = function (data) {
  84799. for (var i = 0; i < 10; ++i) {
  84800. this.data[i] += data[i];
  84801. }
  84802. };
  84803. QuadraticMatrix.prototype.add = function (matrix) {
  84804. var m = new QuadraticMatrix();
  84805. for (var i = 0; i < 10; ++i) {
  84806. m.data[i] = this.data[i] + matrix.data[i];
  84807. }
  84808. return m;
  84809. };
  84810. QuadraticMatrix.FromData = function (a, b, c, d) {
  84811. return new QuadraticMatrix(QuadraticMatrix.DataFromNumbers(a, b, c, d));
  84812. };
  84813. //returning an array to avoid garbage collection
  84814. QuadraticMatrix.DataFromNumbers = function (a, b, c, d) {
  84815. return [a * a, a * b, a * c, a * d, b * b, b * c, b * d, c * c, c * d, d * d];
  84816. };
  84817. return QuadraticMatrix;
  84818. }());
  84819. BABYLON.QuadraticMatrix = QuadraticMatrix;
  84820. var Reference = /** @class */ (function () {
  84821. function Reference(vertexId, triangleId) {
  84822. this.vertexId = vertexId;
  84823. this.triangleId = triangleId;
  84824. }
  84825. return Reference;
  84826. }());
  84827. BABYLON.Reference = Reference;
  84828. /**
  84829. * An implementation of the Quadratic Error simplification algorithm.
  84830. * Original paper : http://www1.cs.columbia.edu/~cs4162/html05s/garland97.pdf
  84831. * Ported mostly from QSlim and http://voxels.blogspot.de/2014/05/quadric-mesh-simplification-with-source.html to babylon JS
  84832. * @author RaananW
  84833. */
  84834. var QuadraticErrorSimplification = /** @class */ (function () {
  84835. function QuadraticErrorSimplification(_mesh) {
  84836. this._mesh = _mesh;
  84837. this.syncIterations = 5000;
  84838. this.aggressiveness = 7;
  84839. this.decimationIterations = 100;
  84840. this.boundingBoxEpsilon = BABYLON.Epsilon;
  84841. }
  84842. QuadraticErrorSimplification.prototype.simplify = function (settings, successCallback) {
  84843. var _this = this;
  84844. this.initDecimatedMesh();
  84845. //iterating through the submeshes array, one after the other.
  84846. BABYLON.AsyncLoop.Run(this._mesh.subMeshes.length, function (loop) {
  84847. _this.initWithMesh(loop.index, function () {
  84848. _this.runDecimation(settings, loop.index, function () {
  84849. loop.executeNext();
  84850. });
  84851. }, settings.optimizeMesh);
  84852. }, function () {
  84853. setTimeout(function () {
  84854. successCallback(_this._reconstructedMesh);
  84855. }, 0);
  84856. });
  84857. };
  84858. QuadraticErrorSimplification.prototype.runDecimation = function (settings, submeshIndex, successCallback) {
  84859. var _this = this;
  84860. var targetCount = ~~(this.triangles.length * settings.quality);
  84861. var deletedTriangles = 0;
  84862. var triangleCount = this.triangles.length;
  84863. var iterationFunction = function (iteration, callback) {
  84864. setTimeout(function () {
  84865. if (iteration % 5 === 0) {
  84866. _this.updateMesh(iteration === 0);
  84867. }
  84868. for (var i = 0; i < _this.triangles.length; ++i) {
  84869. _this.triangles[i].isDirty = false;
  84870. }
  84871. var threshold = 0.000000001 * Math.pow((iteration + 3), _this.aggressiveness);
  84872. var trianglesIterator = function (i) {
  84873. var tIdx = ~~(((_this.triangles.length / 2) + i) % _this.triangles.length);
  84874. var t = _this.triangles[tIdx];
  84875. if (!t)
  84876. return;
  84877. if (t.error[3] > threshold || t.deleted || t.isDirty) {
  84878. return;
  84879. }
  84880. for (var j = 0; j < 3; ++j) {
  84881. if (t.error[j] < threshold) {
  84882. var deleted0 = [];
  84883. var deleted1 = [];
  84884. var v0 = t.vertices[j];
  84885. var v1 = t.vertices[(j + 1) % 3];
  84886. if (v0.isBorder || v1.isBorder)
  84887. continue;
  84888. var p = BABYLON.Vector3.Zero();
  84889. var n = BABYLON.Vector3.Zero();
  84890. var uv = BABYLON.Vector2.Zero();
  84891. var color = new BABYLON.Color4(0, 0, 0, 1);
  84892. _this.calculateError(v0, v1, p, n, uv, color);
  84893. var delTr = new Array();
  84894. if (_this.isFlipped(v0, v1, p, deleted0, t.borderFactor, delTr))
  84895. continue;
  84896. if (_this.isFlipped(v1, v0, p, deleted1, t.borderFactor, delTr))
  84897. continue;
  84898. if (deleted0.indexOf(true) < 0 || deleted1.indexOf(true) < 0)
  84899. continue;
  84900. var uniqueArray = new Array();
  84901. delTr.forEach(function (deletedT) {
  84902. if (uniqueArray.indexOf(deletedT) === -1) {
  84903. deletedT.deletePending = true;
  84904. uniqueArray.push(deletedT);
  84905. }
  84906. });
  84907. if (uniqueArray.length % 2 !== 0) {
  84908. continue;
  84909. }
  84910. v0.q = v1.q.add(v0.q);
  84911. v0.updatePosition(p);
  84912. var tStart = _this.references.length;
  84913. deletedTriangles = _this.updateTriangles(v0, v0, deleted0, deletedTriangles);
  84914. deletedTriangles = _this.updateTriangles(v0, v1, deleted1, deletedTriangles);
  84915. var tCount = _this.references.length - tStart;
  84916. if (tCount <= v0.triangleCount) {
  84917. if (tCount) {
  84918. for (var c = 0; c < tCount; c++) {
  84919. _this.references[v0.triangleStart + c] = _this.references[tStart + c];
  84920. }
  84921. }
  84922. }
  84923. else {
  84924. v0.triangleStart = tStart;
  84925. }
  84926. v0.triangleCount = tCount;
  84927. break;
  84928. }
  84929. }
  84930. };
  84931. BABYLON.AsyncLoop.SyncAsyncForLoop(_this.triangles.length, _this.syncIterations, trianglesIterator, callback, function () { return (triangleCount - deletedTriangles <= targetCount); });
  84932. }, 0);
  84933. };
  84934. BABYLON.AsyncLoop.Run(this.decimationIterations, function (loop) {
  84935. if (triangleCount - deletedTriangles <= targetCount)
  84936. loop.breakLoop();
  84937. else {
  84938. iterationFunction(loop.index, function () {
  84939. loop.executeNext();
  84940. });
  84941. }
  84942. }, function () {
  84943. setTimeout(function () {
  84944. //reconstruct this part of the mesh
  84945. _this.reconstructMesh(submeshIndex);
  84946. successCallback();
  84947. }, 0);
  84948. });
  84949. };
  84950. QuadraticErrorSimplification.prototype.initWithMesh = function (submeshIndex, callback, optimizeMesh) {
  84951. var _this = this;
  84952. this.vertices = [];
  84953. this.triangles = [];
  84954. var positionData = this._mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  84955. var indices = this._mesh.getIndices();
  84956. var submesh = this._mesh.subMeshes[submeshIndex];
  84957. var findInVertices = function (positionToSearch) {
  84958. if (optimizeMesh) {
  84959. for (var ii = 0; ii < _this.vertices.length; ++ii) {
  84960. if (_this.vertices[ii].position.equals(positionToSearch)) {
  84961. return _this.vertices[ii];
  84962. }
  84963. }
  84964. }
  84965. return null;
  84966. };
  84967. var vertexReferences = [];
  84968. var vertexInit = function (i) {
  84969. if (!positionData) {
  84970. return;
  84971. }
  84972. var offset = i + submesh.verticesStart;
  84973. var position = BABYLON.Vector3.FromArray(positionData, offset * 3);
  84974. var vertex = findInVertices(position) || new DecimationVertex(position, _this.vertices.length);
  84975. vertex.originalOffsets.push(offset);
  84976. if (vertex.id === _this.vertices.length) {
  84977. _this.vertices.push(vertex);
  84978. }
  84979. vertexReferences.push(vertex.id);
  84980. };
  84981. //var totalVertices = mesh.getTotalVertices();
  84982. var totalVertices = submesh.verticesCount;
  84983. BABYLON.AsyncLoop.SyncAsyncForLoop(totalVertices, (this.syncIterations / 4) >> 0, vertexInit, function () {
  84984. var indicesInit = function (i) {
  84985. if (!indices) {
  84986. return;
  84987. }
  84988. var offset = (submesh.indexStart / 3) + i;
  84989. var pos = (offset * 3);
  84990. var i0 = indices[pos + 0];
  84991. var i1 = indices[pos + 1];
  84992. var i2 = indices[pos + 2];
  84993. var v0 = _this.vertices[vertexReferences[i0 - submesh.verticesStart]];
  84994. var v1 = _this.vertices[vertexReferences[i1 - submesh.verticesStart]];
  84995. var v2 = _this.vertices[vertexReferences[i2 - submesh.verticesStart]];
  84996. var triangle = new DecimationTriangle([v0, v1, v2]);
  84997. triangle.originalOffset = pos;
  84998. _this.triangles.push(triangle);
  84999. };
  85000. BABYLON.AsyncLoop.SyncAsyncForLoop(submesh.indexCount / 3, _this.syncIterations, indicesInit, function () {
  85001. _this.init(callback);
  85002. });
  85003. });
  85004. };
  85005. QuadraticErrorSimplification.prototype.init = function (callback) {
  85006. var _this = this;
  85007. var triangleInit1 = function (i) {
  85008. var t = _this.triangles[i];
  85009. t.normal = BABYLON.Vector3.Cross(t.vertices[1].position.subtract(t.vertices[0].position), t.vertices[2].position.subtract(t.vertices[0].position)).normalize();
  85010. for (var j = 0; j < 3; j++) {
  85011. 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))));
  85012. }
  85013. };
  85014. BABYLON.AsyncLoop.SyncAsyncForLoop(this.triangles.length, this.syncIterations, triangleInit1, function () {
  85015. var triangleInit2 = function (i) {
  85016. var t = _this.triangles[i];
  85017. for (var j = 0; j < 3; ++j) {
  85018. t.error[j] = _this.calculateError(t.vertices[j], t.vertices[(j + 1) % 3]);
  85019. }
  85020. t.error[3] = Math.min(t.error[0], t.error[1], t.error[2]);
  85021. };
  85022. BABYLON.AsyncLoop.SyncAsyncForLoop(_this.triangles.length, _this.syncIterations, triangleInit2, function () {
  85023. callback();
  85024. });
  85025. });
  85026. };
  85027. QuadraticErrorSimplification.prototype.reconstructMesh = function (submeshIndex) {
  85028. var newTriangles = [];
  85029. var i;
  85030. for (i = 0; i < this.vertices.length; ++i) {
  85031. this.vertices[i].triangleCount = 0;
  85032. }
  85033. var t;
  85034. var j;
  85035. for (i = 0; i < this.triangles.length; ++i) {
  85036. if (!this.triangles[i].deleted) {
  85037. t = this.triangles[i];
  85038. for (j = 0; j < 3; ++j) {
  85039. t.vertices[j].triangleCount = 1;
  85040. }
  85041. newTriangles.push(t);
  85042. }
  85043. }
  85044. var newPositionData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind) || []);
  85045. var newNormalData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind) || []);
  85046. var newUVsData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.UVKind) || []);
  85047. var newColorsData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.ColorKind) || []);
  85048. var normalData = this._mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  85049. var uvs = this._mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  85050. var colorsData = this._mesh.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  85051. var vertexCount = 0;
  85052. for (i = 0; i < this.vertices.length; ++i) {
  85053. var vertex = this.vertices[i];
  85054. vertex.id = vertexCount;
  85055. if (vertex.triangleCount) {
  85056. vertex.originalOffsets.forEach(function (originalOffset) {
  85057. if (!normalData) {
  85058. return;
  85059. }
  85060. newPositionData.push(vertex.position.x);
  85061. newPositionData.push(vertex.position.y);
  85062. newPositionData.push(vertex.position.z);
  85063. newNormalData.push(normalData[originalOffset * 3]);
  85064. newNormalData.push(normalData[(originalOffset * 3) + 1]);
  85065. newNormalData.push(normalData[(originalOffset * 3) + 2]);
  85066. if (uvs && uvs.length) {
  85067. newUVsData.push(uvs[(originalOffset * 2)]);
  85068. newUVsData.push(uvs[(originalOffset * 2) + 1]);
  85069. }
  85070. else if (colorsData && colorsData.length) {
  85071. newColorsData.push(colorsData[(originalOffset * 4)]);
  85072. newColorsData.push(colorsData[(originalOffset * 4) + 1]);
  85073. newColorsData.push(colorsData[(originalOffset * 4) + 2]);
  85074. newColorsData.push(colorsData[(originalOffset * 4) + 3]);
  85075. }
  85076. ++vertexCount;
  85077. });
  85078. }
  85079. }
  85080. var startingIndex = this._reconstructedMesh.getTotalIndices();
  85081. var startingVertex = this._reconstructedMesh.getTotalVertices();
  85082. var submeshesArray = this._reconstructedMesh.subMeshes;
  85083. this._reconstructedMesh.subMeshes = [];
  85084. var newIndicesArray = this._reconstructedMesh.getIndices(); //[];
  85085. var originalIndices = this._mesh.getIndices();
  85086. for (i = 0; i < newTriangles.length; ++i) {
  85087. t = newTriangles[i]; //now get the new referencing point for each vertex
  85088. [0, 1, 2].forEach(function (idx) {
  85089. var id = originalIndices[t.originalOffset + idx];
  85090. var offset = t.vertices[idx].originalOffsets.indexOf(id);
  85091. if (offset < 0)
  85092. offset = 0;
  85093. newIndicesArray.push(t.vertices[idx].id + offset + startingVertex);
  85094. });
  85095. }
  85096. //overwriting the old vertex buffers and indices.
  85097. this._reconstructedMesh.setIndices(newIndicesArray);
  85098. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, newPositionData);
  85099. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, newNormalData);
  85100. if (newUVsData.length > 0)
  85101. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.UVKind, newUVsData);
  85102. if (newColorsData.length > 0)
  85103. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, newColorsData);
  85104. //create submesh
  85105. var originalSubmesh = this._mesh.subMeshes[submeshIndex];
  85106. if (submeshIndex > 0) {
  85107. this._reconstructedMesh.subMeshes = [];
  85108. submeshesArray.forEach(function (submesh) {
  85109. BABYLON.SubMesh.AddToMesh(submesh.materialIndex, submesh.verticesStart, submesh.verticesCount, /* 0, newPositionData.length/3, */ submesh.indexStart, submesh.indexCount, submesh.getMesh());
  85110. });
  85111. BABYLON.SubMesh.AddToMesh(originalSubmesh.materialIndex, startingVertex, vertexCount, /* 0, newPositionData.length / 3, */ startingIndex, newTriangles.length * 3, this._reconstructedMesh);
  85112. }
  85113. };
  85114. QuadraticErrorSimplification.prototype.initDecimatedMesh = function () {
  85115. this._reconstructedMesh = new BABYLON.Mesh(this._mesh.name + "Decimated", this._mesh.getScene());
  85116. this._reconstructedMesh.material = this._mesh.material;
  85117. this._reconstructedMesh.parent = this._mesh.parent;
  85118. this._reconstructedMesh.isVisible = false;
  85119. this._reconstructedMesh.renderingGroupId = this._mesh.renderingGroupId;
  85120. };
  85121. QuadraticErrorSimplification.prototype.isFlipped = function (vertex1, vertex2, point, deletedArray, borderFactor, delTr) {
  85122. for (var i = 0; i < vertex1.triangleCount; ++i) {
  85123. var t = this.triangles[this.references[vertex1.triangleStart + i].triangleId];
  85124. if (t.deleted)
  85125. continue;
  85126. var s = this.references[vertex1.triangleStart + i].vertexId;
  85127. var v1 = t.vertices[(s + 1) % 3];
  85128. var v2 = t.vertices[(s + 2) % 3];
  85129. if ((v1 === vertex2 || v2 === vertex2)) {
  85130. deletedArray[i] = true;
  85131. delTr.push(t);
  85132. continue;
  85133. }
  85134. var d1 = v1.position.subtract(point);
  85135. d1 = d1.normalize();
  85136. var d2 = v2.position.subtract(point);
  85137. d2 = d2.normalize();
  85138. if (Math.abs(BABYLON.Vector3.Dot(d1, d2)) > 0.999)
  85139. return true;
  85140. var normal = BABYLON.Vector3.Cross(d1, d2).normalize();
  85141. deletedArray[i] = false;
  85142. if (BABYLON.Vector3.Dot(normal, t.normal) < 0.2)
  85143. return true;
  85144. }
  85145. return false;
  85146. };
  85147. QuadraticErrorSimplification.prototype.updateTriangles = function (origVertex, vertex, deletedArray, deletedTriangles) {
  85148. var newDeleted = deletedTriangles;
  85149. for (var i = 0; i < vertex.triangleCount; ++i) {
  85150. var ref = this.references[vertex.triangleStart + i];
  85151. var t = this.triangles[ref.triangleId];
  85152. if (t.deleted)
  85153. continue;
  85154. if (deletedArray[i] && t.deletePending) {
  85155. t.deleted = true;
  85156. newDeleted++;
  85157. continue;
  85158. }
  85159. t.vertices[ref.vertexId] = origVertex;
  85160. t.isDirty = true;
  85161. t.error[0] = this.calculateError(t.vertices[0], t.vertices[1]) + (t.borderFactor / 2);
  85162. t.error[1] = this.calculateError(t.vertices[1], t.vertices[2]) + (t.borderFactor / 2);
  85163. t.error[2] = this.calculateError(t.vertices[2], t.vertices[0]) + (t.borderFactor / 2);
  85164. t.error[3] = Math.min(t.error[0], t.error[1], t.error[2]);
  85165. this.references.push(ref);
  85166. }
  85167. return newDeleted;
  85168. };
  85169. QuadraticErrorSimplification.prototype.identifyBorder = function () {
  85170. for (var i = 0; i < this.vertices.length; ++i) {
  85171. var vCount = [];
  85172. var vId = [];
  85173. var v = this.vertices[i];
  85174. var j;
  85175. for (j = 0; j < v.triangleCount; ++j) {
  85176. var triangle = this.triangles[this.references[v.triangleStart + j].triangleId];
  85177. for (var ii = 0; ii < 3; ii++) {
  85178. var ofs = 0;
  85179. var vv = triangle.vertices[ii];
  85180. while (ofs < vCount.length) {
  85181. if (vId[ofs] === vv.id)
  85182. break;
  85183. ++ofs;
  85184. }
  85185. if (ofs === vCount.length) {
  85186. vCount.push(1);
  85187. vId.push(vv.id);
  85188. }
  85189. else {
  85190. vCount[ofs]++;
  85191. }
  85192. }
  85193. }
  85194. for (j = 0; j < vCount.length; ++j) {
  85195. if (vCount[j] === 1) {
  85196. this.vertices[vId[j]].isBorder = true;
  85197. }
  85198. else {
  85199. this.vertices[vId[j]].isBorder = false;
  85200. }
  85201. }
  85202. }
  85203. };
  85204. QuadraticErrorSimplification.prototype.updateMesh = function (identifyBorders) {
  85205. if (identifyBorders === void 0) { identifyBorders = false; }
  85206. var i;
  85207. if (!identifyBorders) {
  85208. var newTrianglesVector = [];
  85209. for (i = 0; i < this.triangles.length; ++i) {
  85210. if (!this.triangles[i].deleted) {
  85211. newTrianglesVector.push(this.triangles[i]);
  85212. }
  85213. }
  85214. this.triangles = newTrianglesVector;
  85215. }
  85216. for (i = 0; i < this.vertices.length; ++i) {
  85217. this.vertices[i].triangleCount = 0;
  85218. this.vertices[i].triangleStart = 0;
  85219. }
  85220. var t;
  85221. var j;
  85222. var v;
  85223. for (i = 0; i < this.triangles.length; ++i) {
  85224. t = this.triangles[i];
  85225. for (j = 0; j < 3; ++j) {
  85226. v = t.vertices[j];
  85227. v.triangleCount++;
  85228. }
  85229. }
  85230. var tStart = 0;
  85231. for (i = 0; i < this.vertices.length; ++i) {
  85232. this.vertices[i].triangleStart = tStart;
  85233. tStart += this.vertices[i].triangleCount;
  85234. this.vertices[i].triangleCount = 0;
  85235. }
  85236. var newReferences = new Array(this.triangles.length * 3);
  85237. for (i = 0; i < this.triangles.length; ++i) {
  85238. t = this.triangles[i];
  85239. for (j = 0; j < 3; ++j) {
  85240. v = t.vertices[j];
  85241. newReferences[v.triangleStart + v.triangleCount] = new Reference(j, i);
  85242. v.triangleCount++;
  85243. }
  85244. }
  85245. this.references = newReferences;
  85246. if (identifyBorders) {
  85247. this.identifyBorder();
  85248. }
  85249. };
  85250. QuadraticErrorSimplification.prototype.vertexError = function (q, point) {
  85251. var x = point.x;
  85252. var y = point.y;
  85253. var z = point.z;
  85254. 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
  85255. + 2 * q.data[5] * y * z + 2 * q.data[6] * y + q.data[7] * z * z + 2 * q.data[8] * z + q.data[9];
  85256. };
  85257. QuadraticErrorSimplification.prototype.calculateError = function (vertex1, vertex2, pointResult, normalResult, uvResult, colorResult) {
  85258. var q = vertex1.q.add(vertex2.q);
  85259. var border = vertex1.isBorder && vertex2.isBorder;
  85260. var error = 0;
  85261. var qDet = q.det(0, 1, 2, 1, 4, 5, 2, 5, 7);
  85262. if (qDet !== 0 && !border) {
  85263. if (!pointResult) {
  85264. pointResult = BABYLON.Vector3.Zero();
  85265. }
  85266. pointResult.x = -1 / qDet * (q.det(1, 2, 3, 4, 5, 6, 5, 7, 8));
  85267. pointResult.y = 1 / qDet * (q.det(0, 2, 3, 1, 5, 6, 2, 7, 8));
  85268. pointResult.z = -1 / qDet * (q.det(0, 1, 3, 1, 4, 6, 2, 5, 8));
  85269. error = this.vertexError(q, pointResult);
  85270. }
  85271. else {
  85272. var p3 = (vertex1.position.add(vertex2.position)).divide(new BABYLON.Vector3(2, 2, 2));
  85273. //var norm3 = (vertex1.normal.add(vertex2.normal)).divide(new Vector3(2, 2, 2)).normalize();
  85274. var error1 = this.vertexError(q, vertex1.position);
  85275. var error2 = this.vertexError(q, vertex2.position);
  85276. var error3 = this.vertexError(q, p3);
  85277. error = Math.min(error1, error2, error3);
  85278. if (error === error1) {
  85279. if (pointResult) {
  85280. pointResult.copyFrom(vertex1.position);
  85281. }
  85282. }
  85283. else if (error === error2) {
  85284. if (pointResult) {
  85285. pointResult.copyFrom(vertex2.position);
  85286. }
  85287. }
  85288. else {
  85289. if (pointResult) {
  85290. pointResult.copyFrom(p3);
  85291. }
  85292. }
  85293. }
  85294. return error;
  85295. };
  85296. return QuadraticErrorSimplification;
  85297. }());
  85298. BABYLON.QuadraticErrorSimplification = QuadraticErrorSimplification;
  85299. })(BABYLON || (BABYLON = {}));
  85300. //# sourceMappingURL=babylon.meshSimplification.js.map
  85301. "use strict";
  85302. var BABYLON;
  85303. (function (BABYLON) {
  85304. var MeshLODLevel = /** @class */ (function () {
  85305. function MeshLODLevel(distance, mesh) {
  85306. this.distance = distance;
  85307. this.mesh = mesh;
  85308. }
  85309. return MeshLODLevel;
  85310. }());
  85311. BABYLON.MeshLODLevel = MeshLODLevel;
  85312. })(BABYLON || (BABYLON = {}));
  85313. //# sourceMappingURL=babylon.meshLODLevel.js.map
  85314. "use strict";
  85315. var BABYLON;
  85316. (function (BABYLON) {
  85317. /**
  85318. * Defines the root class used to create scene optimization to use with SceneOptimizer
  85319. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  85320. */
  85321. var SceneOptimization = /** @class */ (function () {
  85322. /**
  85323. * Creates the SceneOptimization object
  85324. * @param priority defines the priority of this optimization (0 by default which means first in the list)
  85325. * @param desc defines the description associated with the optimization
  85326. */
  85327. function SceneOptimization(
  85328. /**
  85329. * Defines the priority of this optimization (0 by default which means first in the list)
  85330. */
  85331. priority) {
  85332. if (priority === void 0) { priority = 0; }
  85333. this.priority = priority;
  85334. }
  85335. /**
  85336. * Gets a string describing the action executed by the current optimization
  85337. * @returns description string
  85338. */
  85339. SceneOptimization.prototype.getDescription = function () {
  85340. return "";
  85341. };
  85342. /**
  85343. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  85344. * @param scene defines the current scene where to apply this optimization
  85345. * @param optimizer defines the current optimizer
  85346. * @returns true if everything that can be done was applied
  85347. */
  85348. SceneOptimization.prototype.apply = function (scene, optimizer) {
  85349. return true;
  85350. };
  85351. ;
  85352. return SceneOptimization;
  85353. }());
  85354. BABYLON.SceneOptimization = SceneOptimization;
  85355. /**
  85356. * Defines an optimization used to reduce the size of render target textures
  85357. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  85358. */
  85359. var TextureOptimization = /** @class */ (function (_super) {
  85360. __extends(TextureOptimization, _super);
  85361. /**
  85362. * Creates the TextureOptimization object
  85363. * @param priority defines the priority of this optimization (0 by default which means first in the list)
  85364. * @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
  85365. * @param step defines the factor (0.5 by default) used to scale down textures bigger than maximum sized allowed.
  85366. */
  85367. function TextureOptimization(
  85368. /**
  85369. * Defines the priority of this optimization (0 by default which means first in the list)
  85370. */
  85371. priority,
  85372. /**
  85373. * 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
  85374. */
  85375. maximumSize,
  85376. /**
  85377. * Defines the factor (0.5 by default) used to scale down textures bigger than maximum sized allowed.
  85378. */
  85379. step) {
  85380. if (priority === void 0) { priority = 0; }
  85381. if (maximumSize === void 0) { maximumSize = 1024; }
  85382. if (step === void 0) { step = 0.5; }
  85383. var _this = _super.call(this, priority) || this;
  85384. _this.priority = priority;
  85385. _this.maximumSize = maximumSize;
  85386. _this.step = step;
  85387. return _this;
  85388. }
  85389. /**
  85390. * Gets a string describing the action executed by the current optimization
  85391. * @returns description string
  85392. */
  85393. TextureOptimization.prototype.getDescription = function () {
  85394. return "Reducing render target texture size to " + this.maximumSize;
  85395. };
  85396. /**
  85397. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  85398. * @param scene defines the current scene where to apply this optimization
  85399. * @param optimizer defines the current optimizer
  85400. * @returns true if everything that can be done was applied
  85401. */
  85402. TextureOptimization.prototype.apply = function (scene, optimizer) {
  85403. var allDone = true;
  85404. for (var index = 0; index < scene.textures.length; index++) {
  85405. var texture = scene.textures[index];
  85406. if (!texture.canRescale || texture.getContext) {
  85407. continue;
  85408. }
  85409. var currentSize = texture.getSize();
  85410. var maxDimension = Math.max(currentSize.width, currentSize.height);
  85411. if (maxDimension > this.maximumSize) {
  85412. texture.scale(this.step);
  85413. allDone = false;
  85414. }
  85415. }
  85416. return allDone;
  85417. };
  85418. return TextureOptimization;
  85419. }(SceneOptimization));
  85420. BABYLON.TextureOptimization = TextureOptimization;
  85421. /**
  85422. * Defines an optimization used to increase or decrease the rendering resolution
  85423. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  85424. */
  85425. var HardwareScalingOptimization = /** @class */ (function (_super) {
  85426. __extends(HardwareScalingOptimization, _super);
  85427. /**
  85428. * Creates the HardwareScalingOptimization object
  85429. * @param priority defines the priority of this optimization (0 by default which means first in the list)
  85430. * @param maximumScale defines the maximum scale to use (2 by default)
  85431. * @param step defines the step to use between two passes (0.5 by default)
  85432. */
  85433. function HardwareScalingOptimization(
  85434. /**
  85435. * Defines the priority of this optimization (0 by default which means first in the list)
  85436. */
  85437. priority,
  85438. /**
  85439. * Defines the maximum scale to use (2 by default)
  85440. */
  85441. maximumScale,
  85442. /**
  85443. * Defines the step to use between two passes (0.5 by default)
  85444. */
  85445. step) {
  85446. if (priority === void 0) { priority = 0; }
  85447. if (maximumScale === void 0) { maximumScale = 2; }
  85448. if (step === void 0) { step = 0.25; }
  85449. var _this = _super.call(this, priority) || this;
  85450. _this.priority = priority;
  85451. _this.maximumScale = maximumScale;
  85452. _this.step = step;
  85453. _this._currentScale = -1;
  85454. _this._directionOffset = 1;
  85455. return _this;
  85456. }
  85457. /**
  85458. * Gets a string describing the action executed by the current optimization
  85459. * @return description string
  85460. */
  85461. HardwareScalingOptimization.prototype.getDescription = function () {
  85462. return "Setting hardware scaling level to " + this._currentScale;
  85463. };
  85464. /**
  85465. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  85466. * @param scene defines the current scene where to apply this optimization
  85467. * @param optimizer defines the current optimizer
  85468. * @returns true if everything that can be done was applied
  85469. */
  85470. HardwareScalingOptimization.prototype.apply = function (scene, optimizer) {
  85471. if (this._currentScale === -1) {
  85472. this._currentScale = scene.getEngine().getHardwareScalingLevel();
  85473. if (this._currentScale > this.maximumScale) {
  85474. this._directionOffset = -1;
  85475. }
  85476. }
  85477. this._currentScale += this._directionOffset * this.step;
  85478. scene.getEngine().setHardwareScalingLevel(this._currentScale);
  85479. return this._directionOffset === 1 ? this._currentScale >= this.maximumScale : this._currentScale <= this.maximumScale;
  85480. };
  85481. ;
  85482. return HardwareScalingOptimization;
  85483. }(SceneOptimization));
  85484. BABYLON.HardwareScalingOptimization = HardwareScalingOptimization;
  85485. /**
  85486. * Defines an optimization used to remove shadows
  85487. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  85488. */
  85489. var ShadowsOptimization = /** @class */ (function (_super) {
  85490. __extends(ShadowsOptimization, _super);
  85491. function ShadowsOptimization() {
  85492. return _super !== null && _super.apply(this, arguments) || this;
  85493. }
  85494. /**
  85495. * Gets a string describing the action executed by the current optimization
  85496. * @return description string
  85497. */
  85498. ShadowsOptimization.prototype.getDescription = function () {
  85499. return "Turning shadows on/off";
  85500. };
  85501. /**
  85502. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  85503. * @param scene defines the current scene where to apply this optimization
  85504. * @param optimizer defines the current optimizer
  85505. * @returns true if everything that can be done was applied
  85506. */
  85507. ShadowsOptimization.prototype.apply = function (scene, optimizer) {
  85508. scene.shadowsEnabled = optimizer.isInImprovementMode;
  85509. return true;
  85510. };
  85511. ;
  85512. return ShadowsOptimization;
  85513. }(SceneOptimization));
  85514. BABYLON.ShadowsOptimization = ShadowsOptimization;
  85515. /**
  85516. * Defines an optimization used to turn post-processes off
  85517. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  85518. */
  85519. var PostProcessesOptimization = /** @class */ (function (_super) {
  85520. __extends(PostProcessesOptimization, _super);
  85521. function PostProcessesOptimization() {
  85522. return _super !== null && _super.apply(this, arguments) || this;
  85523. }
  85524. /**
  85525. * Gets a string describing the action executed by the current optimization
  85526. * @return description string
  85527. */
  85528. PostProcessesOptimization.prototype.getDescription = function () {
  85529. return "Turning post-processes on/off";
  85530. };
  85531. /**
  85532. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  85533. * @param scene defines the current scene where to apply this optimization
  85534. * @param optimizer defines the current optimizer
  85535. * @returns true if everything that can be done was applied
  85536. */
  85537. PostProcessesOptimization.prototype.apply = function (scene, optimizer) {
  85538. scene.postProcessesEnabled = optimizer.isInImprovementMode;
  85539. return true;
  85540. };
  85541. ;
  85542. return PostProcessesOptimization;
  85543. }(SceneOptimization));
  85544. BABYLON.PostProcessesOptimization = PostProcessesOptimization;
  85545. /**
  85546. * Defines an optimization used to turn lens flares off
  85547. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  85548. */
  85549. var LensFlaresOptimization = /** @class */ (function (_super) {
  85550. __extends(LensFlaresOptimization, _super);
  85551. function LensFlaresOptimization() {
  85552. return _super !== null && _super.apply(this, arguments) || this;
  85553. }
  85554. /**
  85555. * Gets a string describing the action executed by the current optimization
  85556. * @return description string
  85557. */
  85558. LensFlaresOptimization.prototype.getDescription = function () {
  85559. return "Turning lens flares on/off";
  85560. };
  85561. /**
  85562. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  85563. * @param scene defines the current scene where to apply this optimization
  85564. * @param optimizer defines the current optimizer
  85565. * @returns true if everything that can be done was applied
  85566. */
  85567. LensFlaresOptimization.prototype.apply = function (scene, optimizer) {
  85568. scene.lensFlaresEnabled = optimizer.isInImprovementMode;
  85569. return true;
  85570. };
  85571. ;
  85572. return LensFlaresOptimization;
  85573. }(SceneOptimization));
  85574. BABYLON.LensFlaresOptimization = LensFlaresOptimization;
  85575. /**
  85576. * Defines an optimization based on user defined callback.
  85577. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  85578. */
  85579. var CustomOptimization = /** @class */ (function (_super) {
  85580. __extends(CustomOptimization, _super);
  85581. function CustomOptimization() {
  85582. return _super !== null && _super.apply(this, arguments) || this;
  85583. }
  85584. /**
  85585. * Gets a string describing the action executed by the current optimization
  85586. * @returns description string
  85587. */
  85588. CustomOptimization.prototype.getDescription = function () {
  85589. if (this.onGetDescription) {
  85590. return this.onGetDescription();
  85591. }
  85592. return "Running user defined callback";
  85593. };
  85594. /**
  85595. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  85596. * @param scene defines the current scene where to apply this optimization
  85597. * @param optimizer defines the current optimizer
  85598. * @returns true if everything that can be done was applied
  85599. */
  85600. CustomOptimization.prototype.apply = function (scene, optimizer) {
  85601. if (this.onApply) {
  85602. return this.onApply(scene, optimizer);
  85603. }
  85604. return true;
  85605. };
  85606. ;
  85607. return CustomOptimization;
  85608. }(SceneOptimization));
  85609. BABYLON.CustomOptimization = CustomOptimization;
  85610. /**
  85611. * Defines an optimization used to turn particles off
  85612. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  85613. */
  85614. var ParticlesOptimization = /** @class */ (function (_super) {
  85615. __extends(ParticlesOptimization, _super);
  85616. function ParticlesOptimization() {
  85617. return _super !== null && _super.apply(this, arguments) || this;
  85618. }
  85619. /**
  85620. * Gets a string describing the action executed by the current optimization
  85621. * @return description string
  85622. */
  85623. ParticlesOptimization.prototype.getDescription = function () {
  85624. return "Turning particles on/off";
  85625. };
  85626. /**
  85627. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  85628. * @param scene defines the current scene where to apply this optimization
  85629. * @param optimizer defines the current optimizer
  85630. * @returns true if everything that can be done was applied
  85631. */
  85632. ParticlesOptimization.prototype.apply = function (scene, optimizer) {
  85633. scene.particlesEnabled = optimizer.isInImprovementMode;
  85634. return true;
  85635. };
  85636. ;
  85637. return ParticlesOptimization;
  85638. }(SceneOptimization));
  85639. BABYLON.ParticlesOptimization = ParticlesOptimization;
  85640. /**
  85641. * Defines an optimization used to turn render targets off
  85642. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  85643. */
  85644. var RenderTargetsOptimization = /** @class */ (function (_super) {
  85645. __extends(RenderTargetsOptimization, _super);
  85646. function RenderTargetsOptimization() {
  85647. return _super !== null && _super.apply(this, arguments) || this;
  85648. }
  85649. /**
  85650. * Gets a string describing the action executed by the current optimization
  85651. * @return description string
  85652. */
  85653. RenderTargetsOptimization.prototype.getDescription = function () {
  85654. return "Turning render targets off";
  85655. };
  85656. /**
  85657. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  85658. * @param scene defines the current scene where to apply this optimization
  85659. * @param optimizer defines the current optimizer
  85660. * @returns true if everything that can be done was applied
  85661. */
  85662. RenderTargetsOptimization.prototype.apply = function (scene, optimizer) {
  85663. scene.renderTargetsEnabled = optimizer.isInImprovementMode;
  85664. return true;
  85665. };
  85666. ;
  85667. return RenderTargetsOptimization;
  85668. }(SceneOptimization));
  85669. BABYLON.RenderTargetsOptimization = RenderTargetsOptimization;
  85670. /**
  85671. * Defines an optimization used to merge meshes with compatible materials
  85672. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  85673. */
  85674. var MergeMeshesOptimization = /** @class */ (function (_super) {
  85675. __extends(MergeMeshesOptimization, _super);
  85676. function MergeMeshesOptimization() {
  85677. var _this = _super !== null && _super.apply(this, arguments) || this;
  85678. _this._canBeMerged = function (abstractMesh) {
  85679. if (!(abstractMesh instanceof BABYLON.Mesh)) {
  85680. return false;
  85681. }
  85682. var mesh = abstractMesh;
  85683. if (!mesh.isVisible || !mesh.isEnabled()) {
  85684. return false;
  85685. }
  85686. if (mesh.instances.length > 0) {
  85687. return false;
  85688. }
  85689. if (mesh.skeleton || mesh.hasLODLevels) {
  85690. return false;
  85691. }
  85692. if (mesh.parent) {
  85693. return false;
  85694. }
  85695. return true;
  85696. };
  85697. return _this;
  85698. }
  85699. Object.defineProperty(MergeMeshesOptimization, "UpdateSelectionTree", {
  85700. /**
  85701. * Gets or sets a boolean which defines if optimization octree has to be updated
  85702. */
  85703. get: function () {
  85704. return MergeMeshesOptimization._UpdateSelectionTree;
  85705. },
  85706. /**
  85707. * Gets or sets a boolean which defines if optimization octree has to be updated
  85708. */
  85709. set: function (value) {
  85710. MergeMeshesOptimization._UpdateSelectionTree = value;
  85711. },
  85712. enumerable: true,
  85713. configurable: true
  85714. });
  85715. /**
  85716. * Gets a string describing the action executed by the current optimization
  85717. * @return description string
  85718. */
  85719. MergeMeshesOptimization.prototype.getDescription = function () {
  85720. return "Merging similar meshes together";
  85721. };
  85722. /**
  85723. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  85724. * @param scene defines the current scene where to apply this optimization
  85725. * @param optimizer defines the current optimizer
  85726. * @param updateSelectionTree defines that the selection octree has to be updated (false by default)
  85727. * @returns true if everything that can be done was applied
  85728. */
  85729. MergeMeshesOptimization.prototype.apply = function (scene, optimizer, updateSelectionTree) {
  85730. var globalPool = scene.meshes.slice(0);
  85731. var globalLength = globalPool.length;
  85732. for (var index = 0; index < globalLength; index++) {
  85733. var currentPool = new Array();
  85734. var current = globalPool[index];
  85735. // Checks
  85736. if (!this._canBeMerged(current)) {
  85737. continue;
  85738. }
  85739. currentPool.push(current);
  85740. // Find compatible meshes
  85741. for (var subIndex = index + 1; subIndex < globalLength; subIndex++) {
  85742. var otherMesh = globalPool[subIndex];
  85743. if (!this._canBeMerged(otherMesh)) {
  85744. continue;
  85745. }
  85746. if (otherMesh.material !== current.material) {
  85747. continue;
  85748. }
  85749. if (otherMesh.checkCollisions !== current.checkCollisions) {
  85750. continue;
  85751. }
  85752. currentPool.push(otherMesh);
  85753. globalLength--;
  85754. globalPool.splice(subIndex, 1);
  85755. subIndex--;
  85756. }
  85757. if (currentPool.length < 2) {
  85758. continue;
  85759. }
  85760. // Merge meshes
  85761. BABYLON.Mesh.MergeMeshes(currentPool);
  85762. }
  85763. if (updateSelectionTree != undefined) {
  85764. if (updateSelectionTree) {
  85765. scene.createOrUpdateSelectionOctree();
  85766. }
  85767. }
  85768. else if (MergeMeshesOptimization.UpdateSelectionTree) {
  85769. scene.createOrUpdateSelectionOctree();
  85770. }
  85771. return true;
  85772. };
  85773. ;
  85774. MergeMeshesOptimization._UpdateSelectionTree = false;
  85775. return MergeMeshesOptimization;
  85776. }(SceneOptimization));
  85777. BABYLON.MergeMeshesOptimization = MergeMeshesOptimization;
  85778. /**
  85779. * Defines a list of options used by SceneOptimizer
  85780. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  85781. */
  85782. var SceneOptimizerOptions = /** @class */ (function () {
  85783. /**
  85784. * Creates a new list of options used by SceneOptimizer
  85785. * @param targetFrameRate defines the target frame rate to reach (60 by default)
  85786. * @param trackerDuration defines the interval between two checkes (2000ms by default)
  85787. */
  85788. function SceneOptimizerOptions(
  85789. /**
  85790. * Defines the target frame rate to reach (60 by default)
  85791. */
  85792. targetFrameRate,
  85793. /**
  85794. * Defines the interval between two checkes (2000ms by default)
  85795. */
  85796. trackerDuration) {
  85797. if (targetFrameRate === void 0) { targetFrameRate = 60; }
  85798. if (trackerDuration === void 0) { trackerDuration = 2000; }
  85799. this.targetFrameRate = targetFrameRate;
  85800. this.trackerDuration = trackerDuration;
  85801. /**
  85802. * Gets the list of optimizations to apply
  85803. */
  85804. this.optimizations = new Array();
  85805. }
  85806. /**
  85807. * Add a new optimization
  85808. * @param optimization defines the SceneOptimization to add to the list of active optimizations
  85809. * @returns the current SceneOptimizerOptions
  85810. */
  85811. SceneOptimizerOptions.prototype.addOptimization = function (optimization) {
  85812. this.optimizations.push(optimization);
  85813. return this;
  85814. };
  85815. /**
  85816. * Add a new custom optimization
  85817. * @param onApply defines the callback called to apply the custom optimization (true if everything that can be done was applied)
  85818. * @param onGetDescription defines the callback called to get the description attached with the optimization.
  85819. * @param priority defines the priority of this optimization (0 by default which means first in the list)
  85820. * @returns the current SceneOptimizerOptions
  85821. */
  85822. SceneOptimizerOptions.prototype.addCustomOptimization = function (onApply, onGetDescription, priority) {
  85823. if (priority === void 0) { priority = 0; }
  85824. var optimization = new CustomOptimization(priority);
  85825. optimization.onApply = onApply;
  85826. optimization.onGetDescription = onGetDescription;
  85827. this.optimizations.push(optimization);
  85828. return this;
  85829. };
  85830. /**
  85831. * Creates a list of pre-defined optimizations aimed to reduce the visual impact on the scene
  85832. * @param targetFrameRate defines the target frame rate (60 by default)
  85833. * @returns a SceneOptimizerOptions object
  85834. */
  85835. SceneOptimizerOptions.LowDegradationAllowed = function (targetFrameRate) {
  85836. var result = new SceneOptimizerOptions(targetFrameRate);
  85837. var priority = 0;
  85838. result.addOptimization(new MergeMeshesOptimization(priority));
  85839. result.addOptimization(new ShadowsOptimization(priority));
  85840. result.addOptimization(new LensFlaresOptimization(priority));
  85841. // Next priority
  85842. priority++;
  85843. result.addOptimization(new PostProcessesOptimization(priority));
  85844. result.addOptimization(new ParticlesOptimization(priority));
  85845. // Next priority
  85846. priority++;
  85847. result.addOptimization(new TextureOptimization(priority, 1024));
  85848. return result;
  85849. };
  85850. /**
  85851. * Creates a list of pre-defined optimizations aimed to have a moderate impact on the scene visual
  85852. * @param targetFrameRate defines the target frame rate (60 by default)
  85853. * @returns a SceneOptimizerOptions object
  85854. */
  85855. SceneOptimizerOptions.ModerateDegradationAllowed = function (targetFrameRate) {
  85856. var result = new SceneOptimizerOptions(targetFrameRate);
  85857. var priority = 0;
  85858. result.addOptimization(new MergeMeshesOptimization(priority));
  85859. result.addOptimization(new ShadowsOptimization(priority));
  85860. result.addOptimization(new LensFlaresOptimization(priority));
  85861. // Next priority
  85862. priority++;
  85863. result.addOptimization(new PostProcessesOptimization(priority));
  85864. result.addOptimization(new ParticlesOptimization(priority));
  85865. // Next priority
  85866. priority++;
  85867. result.addOptimization(new TextureOptimization(priority, 512));
  85868. // Next priority
  85869. priority++;
  85870. result.addOptimization(new RenderTargetsOptimization(priority));
  85871. // Next priority
  85872. priority++;
  85873. result.addOptimization(new HardwareScalingOptimization(priority, 2));
  85874. return result;
  85875. };
  85876. /**
  85877. * Creates a list of pre-defined optimizations aimed to have a big impact on the scene visual
  85878. * @param targetFrameRate defines the target frame rate (60 by default)
  85879. * @returns a SceneOptimizerOptions object
  85880. */
  85881. SceneOptimizerOptions.HighDegradationAllowed = function (targetFrameRate) {
  85882. var result = new SceneOptimizerOptions(targetFrameRate);
  85883. var priority = 0;
  85884. result.addOptimization(new MergeMeshesOptimization(priority));
  85885. result.addOptimization(new ShadowsOptimization(priority));
  85886. result.addOptimization(new LensFlaresOptimization(priority));
  85887. // Next priority
  85888. priority++;
  85889. result.addOptimization(new PostProcessesOptimization(priority));
  85890. result.addOptimization(new ParticlesOptimization(priority));
  85891. // Next priority
  85892. priority++;
  85893. result.addOptimization(new TextureOptimization(priority, 256));
  85894. // Next priority
  85895. priority++;
  85896. result.addOptimization(new RenderTargetsOptimization(priority));
  85897. // Next priority
  85898. priority++;
  85899. result.addOptimization(new HardwareScalingOptimization(priority, 4));
  85900. return result;
  85901. };
  85902. return SceneOptimizerOptions;
  85903. }());
  85904. BABYLON.SceneOptimizerOptions = SceneOptimizerOptions;
  85905. /**
  85906. * Class used to run optimizations in order to reach a target frame rate
  85907. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  85908. */
  85909. var SceneOptimizer = /** @class */ (function () {
  85910. /**
  85911. * Creates a new SceneOptimizer
  85912. * @param scene defines the scene to work on
  85913. * @param options defines the options to use with the SceneOptimizer
  85914. * @param autoGeneratePriorities defines if priorities must be generated and not read from SceneOptimization property (true by default)
  85915. * @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)
  85916. */
  85917. function SceneOptimizer(scene, options, autoGeneratePriorities, improvementMode) {
  85918. if (autoGeneratePriorities === void 0) { autoGeneratePriorities = true; }
  85919. if (improvementMode === void 0) { improvementMode = false; }
  85920. var _this = this;
  85921. this._isRunning = false;
  85922. this._currentPriorityLevel = 0;
  85923. this._targetFrameRate = 60;
  85924. this._trackerDuration = 2000;
  85925. this._currentFrameRate = 0;
  85926. this._improvementMode = false;
  85927. /**
  85928. * Defines an observable called when the optimizer reaches the target frame rate
  85929. */
  85930. this.onSuccessObservable = new BABYLON.Observable();
  85931. /**
  85932. * Defines an observable called when the optimizer enables an optimization
  85933. */
  85934. this.onNewOptimizationAppliedObservable = new BABYLON.Observable();
  85935. /**
  85936. * Defines an observable called when the optimizer is not able to reach the target frame rate
  85937. */
  85938. this.onFailureObservable = new BABYLON.Observable();
  85939. if (!options) {
  85940. this._options = new SceneOptimizerOptions();
  85941. }
  85942. else {
  85943. this._options = options;
  85944. }
  85945. if (this._options.targetFrameRate) {
  85946. this._targetFrameRate = this._options.targetFrameRate;
  85947. }
  85948. if (this._options.trackerDuration) {
  85949. this._trackerDuration = this._options.trackerDuration;
  85950. }
  85951. if (autoGeneratePriorities) {
  85952. var priority = 0;
  85953. for (var _i = 0, _a = this._options.optimizations; _i < _a.length; _i++) {
  85954. var optim = _a[_i];
  85955. optim.priority = priority++;
  85956. }
  85957. }
  85958. this._improvementMode = improvementMode;
  85959. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  85960. this._sceneDisposeObserver = this._scene.onDisposeObservable.add(function () {
  85961. _this._sceneDisposeObserver = null;
  85962. _this.dispose();
  85963. });
  85964. }
  85965. Object.defineProperty(SceneOptimizer.prototype, "isInImprovementMode", {
  85966. /**
  85967. * Gets a boolean indicating if the optimizer is in improvement mode
  85968. */
  85969. get: function () {
  85970. return this._improvementMode;
  85971. },
  85972. enumerable: true,
  85973. configurable: true
  85974. });
  85975. Object.defineProperty(SceneOptimizer.prototype, "currentPriorityLevel", {
  85976. /**
  85977. * Gets the current priority level (0 at start)
  85978. */
  85979. get: function () {
  85980. return this._currentPriorityLevel;
  85981. },
  85982. enumerable: true,
  85983. configurable: true
  85984. });
  85985. Object.defineProperty(SceneOptimizer.prototype, "currentFrameRate", {
  85986. /**
  85987. * Gets the current frame rate checked by the SceneOptimizer
  85988. */
  85989. get: function () {
  85990. return this._currentFrameRate;
  85991. },
  85992. enumerable: true,
  85993. configurable: true
  85994. });
  85995. Object.defineProperty(SceneOptimizer.prototype, "targetFrameRate", {
  85996. /**
  85997. * Gets or sets the current target frame rate (60 by default)
  85998. */
  85999. get: function () {
  86000. return this._targetFrameRate;
  86001. },
  86002. /**
  86003. * Gets or sets the current target frame rate (60 by default)
  86004. */
  86005. set: function (value) {
  86006. this._targetFrameRate = value;
  86007. },
  86008. enumerable: true,
  86009. configurable: true
  86010. });
  86011. Object.defineProperty(SceneOptimizer.prototype, "trackerDuration", {
  86012. /**
  86013. * Gets or sets the current interval between two checks (every 2000ms by default)
  86014. */
  86015. get: function () {
  86016. return this._trackerDuration;
  86017. },
  86018. /**
  86019. * Gets or sets the current interval between two checks (every 2000ms by default)
  86020. */
  86021. set: function (value) {
  86022. this._trackerDuration = value;
  86023. },
  86024. enumerable: true,
  86025. configurable: true
  86026. });
  86027. Object.defineProperty(SceneOptimizer.prototype, "optimizations", {
  86028. /**
  86029. * Gets the list of active optimizations
  86030. */
  86031. get: function () {
  86032. return this._options.optimizations;
  86033. },
  86034. enumerable: true,
  86035. configurable: true
  86036. });
  86037. /**
  86038. * Stops the current optimizer
  86039. */
  86040. SceneOptimizer.prototype.stop = function () {
  86041. this._isRunning = false;
  86042. };
  86043. /**
  86044. * Reset the optimizer to initial step (current priority level = 0)
  86045. */
  86046. SceneOptimizer.prototype.reset = function () {
  86047. this._currentPriorityLevel = 0;
  86048. };
  86049. /**
  86050. * Start the optimizer. By default it will try to reach a specific framerate
  86051. * but if the optimizer is set with improvementMode === true then it will run all optimiatiation while frame rate is above the target frame rate
  86052. */
  86053. SceneOptimizer.prototype.start = function () {
  86054. var _this = this;
  86055. if (this._isRunning) {
  86056. return;
  86057. }
  86058. this._isRunning = true;
  86059. // Let's wait for the scene to be ready before running our check
  86060. this._scene.executeWhenReady(function () {
  86061. setTimeout(function () {
  86062. _this._checkCurrentState();
  86063. }, _this._trackerDuration);
  86064. });
  86065. };
  86066. SceneOptimizer.prototype._checkCurrentState = function () {
  86067. var _this = this;
  86068. if (!this._isRunning) {
  86069. return;
  86070. }
  86071. var scene = this._scene;
  86072. var options = this._options;
  86073. this._currentFrameRate = Math.round(scene.getEngine().getFps());
  86074. if (this._improvementMode && this._currentFrameRate <= this._targetFrameRate ||
  86075. !this._improvementMode && this._currentFrameRate >= this._targetFrameRate) {
  86076. this._isRunning = false;
  86077. this.onSuccessObservable.notifyObservers(this);
  86078. return;
  86079. }
  86080. // Apply current level of optimizations
  86081. var allDone = true;
  86082. var noOptimizationApplied = true;
  86083. for (var index = 0; index < options.optimizations.length; index++) {
  86084. var optimization = options.optimizations[index];
  86085. if (optimization.priority === this._currentPriorityLevel) {
  86086. noOptimizationApplied = false;
  86087. allDone = allDone && optimization.apply(scene, this);
  86088. this.onNewOptimizationAppliedObservable.notifyObservers(optimization);
  86089. }
  86090. }
  86091. // If no optimization was applied, this is a failure :(
  86092. if (noOptimizationApplied) {
  86093. this._isRunning = false;
  86094. this.onFailureObservable.notifyObservers(this);
  86095. return;
  86096. }
  86097. // If all optimizations were done, move to next level
  86098. if (allDone) {
  86099. this._currentPriorityLevel++;
  86100. }
  86101. // Let's the system running for a specific amount of time before checking FPS
  86102. scene.executeWhenReady(function () {
  86103. setTimeout(function () {
  86104. _this._checkCurrentState();
  86105. }, _this._trackerDuration);
  86106. });
  86107. };
  86108. /**
  86109. * Release all resources
  86110. */
  86111. SceneOptimizer.prototype.dispose = function () {
  86112. this.stop();
  86113. this.onSuccessObservable.clear();
  86114. this.onFailureObservable.clear();
  86115. this.onNewOptimizationAppliedObservable.clear();
  86116. if (this._sceneDisposeObserver) {
  86117. this._scene.onDisposeObservable.remove(this._sceneDisposeObserver);
  86118. }
  86119. };
  86120. /**
  86121. * Helper function to create a SceneOptimizer with one single line of code
  86122. * @param scene defines the scene to work on
  86123. * @param options defines the options to use with the SceneOptimizer
  86124. * @param onSuccess defines a callback to call on success
  86125. * @param onFailure defines a callback to call on failure
  86126. * @returns the new SceneOptimizer object
  86127. */
  86128. SceneOptimizer.OptimizeAsync = function (scene, options, onSuccess, onFailure) {
  86129. var optimizer = new SceneOptimizer(scene, options || SceneOptimizerOptions.ModerateDegradationAllowed(), false);
  86130. if (onSuccess) {
  86131. optimizer.onSuccessObservable.add(function () {
  86132. onSuccess();
  86133. });
  86134. }
  86135. if (onFailure) {
  86136. optimizer.onFailureObservable.add(function () {
  86137. onFailure();
  86138. });
  86139. }
  86140. optimizer.start();
  86141. return optimizer;
  86142. };
  86143. return SceneOptimizer;
  86144. }());
  86145. BABYLON.SceneOptimizer = SceneOptimizer;
  86146. })(BABYLON || (BABYLON = {}));
  86147. //# sourceMappingURL=babylon.sceneOptimizer.js.map
  86148. "use strict";
  86149. var BABYLON;
  86150. (function (BABYLON) {
  86151. var OutlineRenderer = /** @class */ (function () {
  86152. function OutlineRenderer(scene) {
  86153. this.zOffset = 1;
  86154. this._scene = scene;
  86155. }
  86156. OutlineRenderer.prototype.render = function (subMesh, batch, useOverlay) {
  86157. var _this = this;
  86158. if (useOverlay === void 0) { useOverlay = false; }
  86159. var scene = this._scene;
  86160. var engine = this._scene.getEngine();
  86161. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  86162. if (!this.isReady(subMesh, hardwareInstancedRendering)) {
  86163. return;
  86164. }
  86165. var mesh = subMesh.getRenderingMesh();
  86166. var material = subMesh.getMaterial();
  86167. if (!material || !scene.activeCamera) {
  86168. return;
  86169. }
  86170. engine.enableEffect(this._effect);
  86171. // Logarithmic depth
  86172. if (material.useLogarithmicDepth) {
  86173. this._effect.setFloat("logarithmicDepthConstant", 2.0 / (Math.log(scene.activeCamera.maxZ + 1.0) / Math.LN2));
  86174. }
  86175. this._effect.setFloat("offset", useOverlay ? 0 : mesh.outlineWidth);
  86176. this._effect.setColor4("color", useOverlay ? mesh.overlayColor : mesh.outlineColor, useOverlay ? mesh.overlayAlpha : material.alpha);
  86177. this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  86178. // Bones
  86179. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  86180. this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  86181. }
  86182. mesh._bind(subMesh, this._effect, BABYLON.Material.TriangleFillMode);
  86183. // Alpha test
  86184. if (material && material.needAlphaTesting()) {
  86185. var alphaTexture = material.getAlphaTestTexture();
  86186. if (alphaTexture) {
  86187. this._effect.setTexture("diffuseSampler", alphaTexture);
  86188. this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  86189. }
  86190. }
  86191. engine.setZOffset(-this.zOffset);
  86192. mesh._processRendering(subMesh, this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { _this._effect.setMatrix("world", world); });
  86193. engine.setZOffset(0);
  86194. };
  86195. OutlineRenderer.prototype.isReady = function (subMesh, useInstances) {
  86196. var defines = [];
  86197. var attribs = [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.NormalKind];
  86198. var mesh = subMesh.getMesh();
  86199. var material = subMesh.getMaterial();
  86200. if (material) {
  86201. // Alpha test
  86202. if (material.needAlphaTesting()) {
  86203. defines.push("#define ALPHATEST");
  86204. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  86205. attribs.push(BABYLON.VertexBuffer.UVKind);
  86206. defines.push("#define UV1");
  86207. }
  86208. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  86209. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  86210. defines.push("#define UV2");
  86211. }
  86212. }
  86213. //Logarithmic depth
  86214. if (material.useLogarithmicDepth) {
  86215. defines.push("#define LOGARITHMICDEPTH");
  86216. }
  86217. }
  86218. // Bones
  86219. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  86220. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  86221. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  86222. if (mesh.numBoneInfluencers > 4) {
  86223. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  86224. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  86225. }
  86226. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  86227. defines.push("#define BonesPerMesh " + (mesh.skeleton ? mesh.skeleton.bones.length + 1 : 0));
  86228. }
  86229. else {
  86230. defines.push("#define NUM_BONE_INFLUENCERS 0");
  86231. }
  86232. // Instances
  86233. if (useInstances) {
  86234. defines.push("#define INSTANCES");
  86235. attribs.push("world0");
  86236. attribs.push("world1");
  86237. attribs.push("world2");
  86238. attribs.push("world3");
  86239. }
  86240. // Get correct effect
  86241. var join = defines.join("\n");
  86242. if (this._cachedDefines !== join) {
  86243. this._cachedDefines = join;
  86244. this._effect = this._scene.getEngine().createEffect("outline", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "offset", "color", "logarithmicDepthConstant"], ["diffuseSampler"], join);
  86245. }
  86246. return this._effect.isReady();
  86247. };
  86248. return OutlineRenderer;
  86249. }());
  86250. BABYLON.OutlineRenderer = OutlineRenderer;
  86251. })(BABYLON || (BABYLON = {}));
  86252. //# sourceMappingURL=babylon.outlineRenderer.js.map
  86253. "use strict";
  86254. var BABYLON;
  86255. (function (BABYLON) {
  86256. var FaceAdjacencies = /** @class */ (function () {
  86257. function FaceAdjacencies() {
  86258. this.edges = new Array();
  86259. this.edgesConnectedCount = 0;
  86260. }
  86261. return FaceAdjacencies;
  86262. }());
  86263. var EdgesRenderer = /** @class */ (function () {
  86264. // Beware when you use this class with complex objects as the adjacencies computation can be really long
  86265. function EdgesRenderer(source, epsilon, checkVerticesInsteadOfIndices) {
  86266. if (epsilon === void 0) { epsilon = 0.95; }
  86267. if (checkVerticesInsteadOfIndices === void 0) { checkVerticesInsteadOfIndices = false; }
  86268. this.edgesWidthScalerForOrthographic = 1000.0;
  86269. this.edgesWidthScalerForPerspective = 50.0;
  86270. this._linesPositions = new Array();
  86271. this._linesNormals = new Array();
  86272. this._linesIndices = new Array();
  86273. this._buffers = {};
  86274. this._checkVerticesInsteadOfIndices = false;
  86275. this._source = source;
  86276. this._checkVerticesInsteadOfIndices = checkVerticesInsteadOfIndices;
  86277. this._epsilon = epsilon;
  86278. this._prepareRessources();
  86279. this._generateEdgesLines();
  86280. }
  86281. EdgesRenderer.prototype._prepareRessources = function () {
  86282. if (this._lineShader) {
  86283. return;
  86284. }
  86285. this._lineShader = new BABYLON.ShaderMaterial("lineShader", this._source.getScene(), "line", {
  86286. attributes: ["position", "normal"],
  86287. uniforms: ["worldViewProjection", "color", "width", "aspectRatio"]
  86288. });
  86289. this._lineShader.disableDepthWrite = true;
  86290. this._lineShader.backFaceCulling = false;
  86291. };
  86292. EdgesRenderer.prototype._rebuild = function () {
  86293. var buffer = this._buffers[BABYLON.VertexBuffer.PositionKind];
  86294. if (buffer) {
  86295. buffer._rebuild();
  86296. }
  86297. buffer = this._buffers[BABYLON.VertexBuffer.NormalKind];
  86298. if (buffer) {
  86299. buffer._rebuild();
  86300. }
  86301. var scene = this._source.getScene();
  86302. var engine = scene.getEngine();
  86303. this._ib = engine.createIndexBuffer(this._linesIndices);
  86304. };
  86305. EdgesRenderer.prototype.dispose = function () {
  86306. var buffer = this._buffers[BABYLON.VertexBuffer.PositionKind];
  86307. if (buffer) {
  86308. buffer.dispose();
  86309. this._buffers[BABYLON.VertexBuffer.PositionKind] = null;
  86310. }
  86311. buffer = this._buffers[BABYLON.VertexBuffer.NormalKind];
  86312. if (buffer) {
  86313. buffer.dispose();
  86314. this._buffers[BABYLON.VertexBuffer.NormalKind] = null;
  86315. }
  86316. this._source.getScene().getEngine()._releaseBuffer(this._ib);
  86317. this._lineShader.dispose();
  86318. };
  86319. EdgesRenderer.prototype._processEdgeForAdjacencies = function (pa, pb, p0, p1, p2) {
  86320. if (pa === p0 && pb === p1 || pa === p1 && pb === p0) {
  86321. return 0;
  86322. }
  86323. if (pa === p1 && pb === p2 || pa === p2 && pb === p1) {
  86324. return 1;
  86325. }
  86326. if (pa === p2 && pb === p0 || pa === p0 && pb === p2) {
  86327. return 2;
  86328. }
  86329. return -1;
  86330. };
  86331. EdgesRenderer.prototype._processEdgeForAdjacenciesWithVertices = function (pa, pb, p0, p1, p2) {
  86332. if (pa.equalsWithEpsilon(p0) && pb.equalsWithEpsilon(p1) || pa.equalsWithEpsilon(p1) && pb.equalsWithEpsilon(p0)) {
  86333. return 0;
  86334. }
  86335. if (pa.equalsWithEpsilon(p1) && pb.equalsWithEpsilon(p2) || pa.equalsWithEpsilon(p2) && pb.equalsWithEpsilon(p1)) {
  86336. return 1;
  86337. }
  86338. if (pa.equalsWithEpsilon(p2) && pb.equalsWithEpsilon(p0) || pa.equalsWithEpsilon(p0) && pb.equalsWithEpsilon(p2)) {
  86339. return 2;
  86340. }
  86341. return -1;
  86342. };
  86343. EdgesRenderer.prototype._checkEdge = function (faceIndex, edge, faceNormals, p0, p1) {
  86344. var needToCreateLine;
  86345. if (edge === undefined) {
  86346. needToCreateLine = true;
  86347. }
  86348. else {
  86349. var dotProduct = BABYLON.Vector3.Dot(faceNormals[faceIndex], faceNormals[edge]);
  86350. needToCreateLine = dotProduct < this._epsilon;
  86351. }
  86352. if (needToCreateLine) {
  86353. var offset = this._linesPositions.length / 3;
  86354. var normal = p0.subtract(p1);
  86355. normal.normalize();
  86356. // Positions
  86357. this._linesPositions.push(p0.x);
  86358. this._linesPositions.push(p0.y);
  86359. this._linesPositions.push(p0.z);
  86360. this._linesPositions.push(p0.x);
  86361. this._linesPositions.push(p0.y);
  86362. this._linesPositions.push(p0.z);
  86363. this._linesPositions.push(p1.x);
  86364. this._linesPositions.push(p1.y);
  86365. this._linesPositions.push(p1.z);
  86366. this._linesPositions.push(p1.x);
  86367. this._linesPositions.push(p1.y);
  86368. this._linesPositions.push(p1.z);
  86369. // Normals
  86370. this._linesNormals.push(p1.x);
  86371. this._linesNormals.push(p1.y);
  86372. this._linesNormals.push(p1.z);
  86373. this._linesNormals.push(-1);
  86374. this._linesNormals.push(p1.x);
  86375. this._linesNormals.push(p1.y);
  86376. this._linesNormals.push(p1.z);
  86377. this._linesNormals.push(1);
  86378. this._linesNormals.push(p0.x);
  86379. this._linesNormals.push(p0.y);
  86380. this._linesNormals.push(p0.z);
  86381. this._linesNormals.push(-1);
  86382. this._linesNormals.push(p0.x);
  86383. this._linesNormals.push(p0.y);
  86384. this._linesNormals.push(p0.z);
  86385. this._linesNormals.push(1);
  86386. // Indices
  86387. this._linesIndices.push(offset);
  86388. this._linesIndices.push(offset + 1);
  86389. this._linesIndices.push(offset + 2);
  86390. this._linesIndices.push(offset);
  86391. this._linesIndices.push(offset + 2);
  86392. this._linesIndices.push(offset + 3);
  86393. }
  86394. };
  86395. EdgesRenderer.prototype._generateEdgesLines = function () {
  86396. var positions = this._source.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  86397. var indices = this._source.getIndices();
  86398. if (!indices || !positions) {
  86399. return;
  86400. }
  86401. // First let's find adjacencies
  86402. var adjacencies = new Array();
  86403. var faceNormals = new Array();
  86404. var index;
  86405. var faceAdjacencies;
  86406. // Prepare faces
  86407. for (index = 0; index < indices.length; index += 3) {
  86408. faceAdjacencies = new FaceAdjacencies();
  86409. var p0Index = indices[index];
  86410. var p1Index = indices[index + 1];
  86411. var p2Index = indices[index + 2];
  86412. faceAdjacencies.p0 = new BABYLON.Vector3(positions[p0Index * 3], positions[p0Index * 3 + 1], positions[p0Index * 3 + 2]);
  86413. faceAdjacencies.p1 = new BABYLON.Vector3(positions[p1Index * 3], positions[p1Index * 3 + 1], positions[p1Index * 3 + 2]);
  86414. faceAdjacencies.p2 = new BABYLON.Vector3(positions[p2Index * 3], positions[p2Index * 3 + 1], positions[p2Index * 3 + 2]);
  86415. var faceNormal = BABYLON.Vector3.Cross(faceAdjacencies.p1.subtract(faceAdjacencies.p0), faceAdjacencies.p2.subtract(faceAdjacencies.p1));
  86416. faceNormal.normalize();
  86417. faceNormals.push(faceNormal);
  86418. adjacencies.push(faceAdjacencies);
  86419. }
  86420. // Scan
  86421. for (index = 0; index < adjacencies.length; index++) {
  86422. faceAdjacencies = adjacencies[index];
  86423. for (var otherIndex = index + 1; otherIndex < adjacencies.length; otherIndex++) {
  86424. var otherFaceAdjacencies = adjacencies[otherIndex];
  86425. if (faceAdjacencies.edgesConnectedCount === 3) {
  86426. break;
  86427. }
  86428. if (otherFaceAdjacencies.edgesConnectedCount === 3) {
  86429. continue;
  86430. }
  86431. var otherP0 = indices[otherIndex * 3];
  86432. var otherP1 = indices[otherIndex * 3 + 1];
  86433. var otherP2 = indices[otherIndex * 3 + 2];
  86434. for (var edgeIndex = 0; edgeIndex < 3; edgeIndex++) {
  86435. var otherEdgeIndex = 0;
  86436. if (faceAdjacencies.edges[edgeIndex] !== undefined) {
  86437. continue;
  86438. }
  86439. switch (edgeIndex) {
  86440. case 0:
  86441. if (this._checkVerticesInsteadOfIndices) {
  86442. otherEdgeIndex = this._processEdgeForAdjacenciesWithVertices(faceAdjacencies.p0, faceAdjacencies.p1, otherFaceAdjacencies.p0, otherFaceAdjacencies.p1, otherFaceAdjacencies.p2);
  86443. }
  86444. else {
  86445. otherEdgeIndex = this._processEdgeForAdjacencies(indices[index * 3], indices[index * 3 + 1], otherP0, otherP1, otherP2);
  86446. }
  86447. break;
  86448. case 1:
  86449. if (this._checkVerticesInsteadOfIndices) {
  86450. otherEdgeIndex = this._processEdgeForAdjacenciesWithVertices(faceAdjacencies.p1, faceAdjacencies.p2, otherFaceAdjacencies.p0, otherFaceAdjacencies.p1, otherFaceAdjacencies.p2);
  86451. }
  86452. else {
  86453. otherEdgeIndex = this._processEdgeForAdjacencies(indices[index * 3 + 1], indices[index * 3 + 2], otherP0, otherP1, otherP2);
  86454. }
  86455. break;
  86456. case 2:
  86457. if (this._checkVerticesInsteadOfIndices) {
  86458. otherEdgeIndex = this._processEdgeForAdjacenciesWithVertices(faceAdjacencies.p2, faceAdjacencies.p0, otherFaceAdjacencies.p0, otherFaceAdjacencies.p1, otherFaceAdjacencies.p2);
  86459. }
  86460. else {
  86461. otherEdgeIndex = this._processEdgeForAdjacencies(indices[index * 3 + 2], indices[index * 3], otherP0, otherP1, otherP2);
  86462. }
  86463. break;
  86464. }
  86465. if (otherEdgeIndex === -1) {
  86466. continue;
  86467. }
  86468. faceAdjacencies.edges[edgeIndex] = otherIndex;
  86469. otherFaceAdjacencies.edges[otherEdgeIndex] = index;
  86470. faceAdjacencies.edgesConnectedCount++;
  86471. otherFaceAdjacencies.edgesConnectedCount++;
  86472. if (faceAdjacencies.edgesConnectedCount === 3) {
  86473. break;
  86474. }
  86475. }
  86476. }
  86477. }
  86478. // Create lines
  86479. for (index = 0; index < adjacencies.length; index++) {
  86480. // 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
  86481. var current = adjacencies[index];
  86482. this._checkEdge(index, current.edges[0], faceNormals, current.p0, current.p1);
  86483. this._checkEdge(index, current.edges[1], faceNormals, current.p1, current.p2);
  86484. this._checkEdge(index, current.edges[2], faceNormals, current.p2, current.p0);
  86485. }
  86486. // Merge into a single mesh
  86487. var engine = this._source.getScene().getEngine();
  86488. this._buffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(engine, this._linesPositions, BABYLON.VertexBuffer.PositionKind, false);
  86489. this._buffers[BABYLON.VertexBuffer.NormalKind] = new BABYLON.VertexBuffer(engine, this._linesNormals, BABYLON.VertexBuffer.NormalKind, false, false, 4);
  86490. this._ib = engine.createIndexBuffer(this._linesIndices);
  86491. this._indicesCount = this._linesIndices.length;
  86492. };
  86493. EdgesRenderer.prototype.render = function () {
  86494. var scene = this._source.getScene();
  86495. if (!this._lineShader.isReady() || !scene.activeCamera) {
  86496. return;
  86497. }
  86498. var engine = scene.getEngine();
  86499. this._lineShader._preBind();
  86500. // VBOs
  86501. engine.bindBuffers(this._buffers, this._ib, this._lineShader.getEffect());
  86502. scene.resetCachedMaterial();
  86503. this._lineShader.setColor4("color", this._source.edgesColor);
  86504. if (scene.activeCamera.mode === BABYLON.Camera.ORTHOGRAPHIC_CAMERA) {
  86505. this._lineShader.setFloat("width", this._source.edgesWidth / this.edgesWidthScalerForOrthographic);
  86506. }
  86507. else {
  86508. this._lineShader.setFloat("width", this._source.edgesWidth / this.edgesWidthScalerForPerspective);
  86509. }
  86510. this._lineShader.setFloat("aspectRatio", engine.getAspectRatio(scene.activeCamera));
  86511. this._lineShader.bind(this._source.getWorldMatrix());
  86512. // Draw order
  86513. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, this._indicesCount);
  86514. this._lineShader.unbind();
  86515. engine.setDepthWrite(true);
  86516. };
  86517. return EdgesRenderer;
  86518. }());
  86519. BABYLON.EdgesRenderer = EdgesRenderer;
  86520. })(BABYLON || (BABYLON = {}));
  86521. //# sourceMappingURL=babylon.edgesRenderer.js.map
  86522. "use strict";
  86523. var __assign = (this && this.__assign) || Object.assign || function(t) {
  86524. for (var s, i = 1, n = arguments.length; i < n; i++) {
  86525. s = arguments[i];
  86526. for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
  86527. t[p] = s[p];
  86528. }
  86529. return t;
  86530. };
  86531. var BABYLON;
  86532. (function (BABYLON) {
  86533. /**
  86534. * The effect layer Helps adding post process effect blended with the main pass.
  86535. *
  86536. * This can be for instance use to generate glow or higlight effects on the scene.
  86537. *
  86538. * The effect layer class can not be used directly and is intented to inherited from to be
  86539. * customized per effects.
  86540. */
  86541. var EffectLayer = /** @class */ (function () {
  86542. /**
  86543. * Instantiates a new effect Layer and references it in the scene.
  86544. * @param name The name of the layer
  86545. * @param scene The scene to use the layer in
  86546. */
  86547. function EffectLayer(
  86548. /** The Friendly of the effect in the scene */
  86549. name, scene) {
  86550. this.name = name;
  86551. this._vertexBuffers = {};
  86552. this._maxSize = 0;
  86553. this._mainTextureDesiredSize = { width: 0, height: 0 };
  86554. this._shouldRender = true;
  86555. this._postProcesses = [];
  86556. this._textures = [];
  86557. this._emissiveTextureAndColor = { texture: null, color: new BABYLON.Color4() };
  86558. /**
  86559. * The clear color of the texture used to generate the glow map.
  86560. */
  86561. this.neutralColor = new BABYLON.Color4();
  86562. /**
  86563. * Specifies wether the highlight layer is enabled or not.
  86564. */
  86565. this.isEnabled = true;
  86566. /**
  86567. * An event triggered when the effect layer has been disposed.
  86568. */
  86569. this.onDisposeObservable = new BABYLON.Observable();
  86570. /**
  86571. * An event triggered when the effect layer is about rendering the main texture with the glowy parts.
  86572. */
  86573. this.onBeforeRenderMainTextureObservable = new BABYLON.Observable();
  86574. /**
  86575. * An event triggered when the generated texture is being merged in the scene.
  86576. */
  86577. this.onBeforeComposeObservable = new BABYLON.Observable();
  86578. /**
  86579. * An event triggered when the generated texture has been merged in the scene.
  86580. */
  86581. this.onAfterComposeObservable = new BABYLON.Observable();
  86582. /**
  86583. * An event triggered when the efffect layer changes its size.
  86584. */
  86585. this.onSizeChangedObservable = new BABYLON.Observable();
  86586. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  86587. this._engine = scene.getEngine();
  86588. this._maxSize = this._engine.getCaps().maxTextureSize;
  86589. this._scene.effectLayers.push(this);
  86590. // Generate Buffers
  86591. this._generateIndexBuffer();
  86592. this._genrateVertexBuffer();
  86593. }
  86594. Object.defineProperty(EffectLayer.prototype, "camera", {
  86595. /**
  86596. * Gets the camera attached to the layer.
  86597. */
  86598. get: function () {
  86599. return this._effectLayerOptions.camera;
  86600. },
  86601. enumerable: true,
  86602. configurable: true
  86603. });
  86604. /**
  86605. * Initializes the effect layer with the required options.
  86606. * @param options Sets of none mandatory options to use with the layer (see IEffectLayerOptions for more information)
  86607. */
  86608. EffectLayer.prototype._init = function (options) {
  86609. // Adapt options
  86610. this._effectLayerOptions = __assign({ mainTextureRatio: 0.5, alphaBlendingMode: BABYLON.Engine.ALPHA_COMBINE, camera: null }, options);
  86611. this._setMainTextureSize();
  86612. this._createMainTexture();
  86613. this._createTextureAndPostProcesses();
  86614. this._mergeEffect = this._createMergeEffect();
  86615. };
  86616. /**
  86617. * Generates the index buffer of the full screen quad blending to the main canvas.
  86618. */
  86619. EffectLayer.prototype._generateIndexBuffer = function () {
  86620. // Indices
  86621. var indices = [];
  86622. indices.push(0);
  86623. indices.push(1);
  86624. indices.push(2);
  86625. indices.push(0);
  86626. indices.push(2);
  86627. indices.push(3);
  86628. this._indexBuffer = this._engine.createIndexBuffer(indices);
  86629. };
  86630. /**
  86631. * Generates the vertex buffer of the full screen quad blending to the main canvas.
  86632. */
  86633. EffectLayer.prototype._genrateVertexBuffer = function () {
  86634. // VBO
  86635. var vertices = [];
  86636. vertices.push(1, 1);
  86637. vertices.push(-1, 1);
  86638. vertices.push(-1, -1);
  86639. vertices.push(1, -1);
  86640. var vertexBuffer = new BABYLON.VertexBuffer(this._engine, vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  86641. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = vertexBuffer;
  86642. };
  86643. /**
  86644. * Sets the main texture desired size which is the closest power of two
  86645. * of the engine canvas size.
  86646. */
  86647. EffectLayer.prototype._setMainTextureSize = function () {
  86648. if (this._effectLayerOptions.mainTextureFixedSize) {
  86649. this._mainTextureDesiredSize.width = this._effectLayerOptions.mainTextureFixedSize;
  86650. this._mainTextureDesiredSize.height = this._effectLayerOptions.mainTextureFixedSize;
  86651. }
  86652. else {
  86653. this._mainTextureDesiredSize.width = this._engine.getRenderWidth() * this._effectLayerOptions.mainTextureRatio;
  86654. this._mainTextureDesiredSize.height = this._engine.getRenderHeight() * this._effectLayerOptions.mainTextureRatio;
  86655. this._mainTextureDesiredSize.width = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(this._mainTextureDesiredSize.width, this._maxSize) : this._mainTextureDesiredSize.width;
  86656. this._mainTextureDesiredSize.height = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(this._mainTextureDesiredSize.height, this._maxSize) : this._mainTextureDesiredSize.height;
  86657. }
  86658. this._mainTextureDesiredSize.width = Math.floor(this._mainTextureDesiredSize.width);
  86659. this._mainTextureDesiredSize.height = Math.floor(this._mainTextureDesiredSize.height);
  86660. };
  86661. /**
  86662. * Creates the main texture for the effect layer.
  86663. */
  86664. EffectLayer.prototype._createMainTexture = function () {
  86665. var _this = this;
  86666. this._mainTexture = new BABYLON.RenderTargetTexture("HighlightLayerMainRTT", {
  86667. width: this._mainTextureDesiredSize.width,
  86668. height: this._mainTextureDesiredSize.height
  86669. }, this._scene, false, true, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  86670. this._mainTexture.activeCamera = this._effectLayerOptions.camera;
  86671. this._mainTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  86672. this._mainTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  86673. this._mainTexture.anisotropicFilteringLevel = 1;
  86674. this._mainTexture.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  86675. this._mainTexture.renderParticles = false;
  86676. this._mainTexture.renderList = null;
  86677. this._mainTexture.ignoreCameraViewport = true;
  86678. // Custom render function
  86679. this._mainTexture.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes) {
  86680. _this.onBeforeRenderMainTextureObservable.notifyObservers(_this);
  86681. var index;
  86682. var engine = _this._scene.getEngine();
  86683. if (depthOnlySubMeshes.length) {
  86684. engine.setColorWrite(false);
  86685. for (index = 0; index < depthOnlySubMeshes.length; index++) {
  86686. _this._renderSubMesh(depthOnlySubMeshes.data[index]);
  86687. }
  86688. engine.setColorWrite(true);
  86689. }
  86690. for (index = 0; index < opaqueSubMeshes.length; index++) {
  86691. _this._renderSubMesh(opaqueSubMeshes.data[index]);
  86692. }
  86693. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  86694. _this._renderSubMesh(alphaTestSubMeshes.data[index]);
  86695. }
  86696. for (index = 0; index < transparentSubMeshes.length; index++) {
  86697. _this._renderSubMesh(transparentSubMeshes.data[index]);
  86698. }
  86699. };
  86700. this._mainTexture.onClearObservable.add(function (engine) {
  86701. engine.clear(_this.neutralColor, true, true, true);
  86702. });
  86703. };
  86704. /**
  86705. * Checks for the readiness of the element composing the layer.
  86706. * @param subMesh the mesh to check for
  86707. * @param useInstances specify wether or not to use instances to render the mesh
  86708. * @param emissiveTexture the associated emissive texture used to generate the glow
  86709. * @return true if ready otherwise, false
  86710. */
  86711. EffectLayer.prototype._isReady = function (subMesh, useInstances, emissiveTexture) {
  86712. var material = subMesh.getMaterial();
  86713. if (!material) {
  86714. return false;
  86715. }
  86716. if (!material.isReady(subMesh.getMesh(), useInstances)) {
  86717. return false;
  86718. }
  86719. var defines = [];
  86720. var attribs = [BABYLON.VertexBuffer.PositionKind];
  86721. var mesh = subMesh.getMesh();
  86722. var uv1 = false;
  86723. var uv2 = false;
  86724. // Alpha test
  86725. if (material && material.needAlphaTesting()) {
  86726. var alphaTexture = material.getAlphaTestTexture();
  86727. if (alphaTexture) {
  86728. defines.push("#define ALPHATEST");
  86729. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind) &&
  86730. alphaTexture.coordinatesIndex === 1) {
  86731. defines.push("#define DIFFUSEUV2");
  86732. uv2 = true;
  86733. }
  86734. else if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  86735. defines.push("#define DIFFUSEUV1");
  86736. uv1 = true;
  86737. }
  86738. }
  86739. }
  86740. // Emissive
  86741. if (emissiveTexture) {
  86742. defines.push("#define EMISSIVE");
  86743. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind) &&
  86744. emissiveTexture.coordinatesIndex === 1) {
  86745. defines.push("#define EMISSIVEUV2");
  86746. uv2 = true;
  86747. }
  86748. else if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  86749. defines.push("#define EMISSIVEUV1");
  86750. uv1 = true;
  86751. }
  86752. }
  86753. if (uv1) {
  86754. attribs.push(BABYLON.VertexBuffer.UVKind);
  86755. defines.push("#define UV1");
  86756. }
  86757. if (uv2) {
  86758. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  86759. defines.push("#define UV2");
  86760. }
  86761. // Bones
  86762. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  86763. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  86764. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  86765. if (mesh.numBoneInfluencers > 4) {
  86766. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  86767. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  86768. }
  86769. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  86770. defines.push("#define BonesPerMesh " + (mesh.skeleton ? (mesh.skeleton.bones.length + 1) : 0));
  86771. }
  86772. else {
  86773. defines.push("#define NUM_BONE_INFLUENCERS 0");
  86774. }
  86775. // Morph targets
  86776. var manager = mesh.morphTargetManager;
  86777. var morphInfluencers = 0;
  86778. if (manager) {
  86779. if (manager.numInfluencers > 0) {
  86780. defines.push("#define MORPHTARGETS");
  86781. morphInfluencers = manager.numInfluencers;
  86782. defines.push("#define NUM_MORPH_INFLUENCERS " + morphInfluencers);
  86783. BABYLON.MaterialHelper.PrepareAttributesForMorphTargets(attribs, mesh, { "NUM_MORPH_INFLUENCERS": morphInfluencers });
  86784. }
  86785. }
  86786. // Instances
  86787. if (useInstances) {
  86788. defines.push("#define INSTANCES");
  86789. attribs.push("world0");
  86790. attribs.push("world1");
  86791. attribs.push("world2");
  86792. attribs.push("world3");
  86793. }
  86794. // Get correct effect
  86795. var join = defines.join("\n");
  86796. if (this._cachedDefines !== join) {
  86797. this._cachedDefines = join;
  86798. this._effectLayerMapGenerationEffect = this._scene.getEngine().createEffect("glowMapGeneration", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "color", "emissiveMatrix", "morphTargetInfluences"], ["diffuseSampler", "emissiveSampler"], join, undefined, undefined, undefined, { maxSimultaneousMorphTargets: morphInfluencers });
  86799. }
  86800. return this._effectLayerMapGenerationEffect.isReady();
  86801. };
  86802. /**
  86803. * Renders the glowing part of the scene by blending the blurred glowing meshes on top of the rendered scene.
  86804. */
  86805. EffectLayer.prototype.render = function () {
  86806. var currentEffect = this._mergeEffect;
  86807. // Check
  86808. if (!currentEffect.isReady())
  86809. return;
  86810. for (var i = 0; i < this._postProcesses.length; i++) {
  86811. if (!this._postProcesses[i].isReady()) {
  86812. return;
  86813. }
  86814. }
  86815. var engine = this._scene.getEngine();
  86816. this.onBeforeComposeObservable.notifyObservers(this);
  86817. // Render
  86818. engine.enableEffect(currentEffect);
  86819. engine.setState(false);
  86820. // VBOs
  86821. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, currentEffect);
  86822. // Cache
  86823. var previousAlphaMode = engine.getAlphaMode();
  86824. // Go Blend.
  86825. engine.setAlphaMode(this._effectLayerOptions.alphaBlendingMode);
  86826. // Blends the map on the main canvas.
  86827. this._internalRender(currentEffect);
  86828. // Restore Alpha
  86829. engine.setAlphaMode(previousAlphaMode);
  86830. this.onAfterComposeObservable.notifyObservers(this);
  86831. // Handle size changes.
  86832. var size = this._mainTexture.getSize();
  86833. this._setMainTextureSize();
  86834. if (size.width !== this._mainTextureDesiredSize.width || size.height !== this._mainTextureDesiredSize.height) {
  86835. // Recreate RTT and post processes on size change.
  86836. this.onSizeChangedObservable.notifyObservers(this);
  86837. this._disposeTextureAndPostProcesses();
  86838. this._createMainTexture();
  86839. this._createTextureAndPostProcesses();
  86840. }
  86841. };
  86842. /**
  86843. * Determine if a given mesh will be used in the current effect.
  86844. * @param mesh mesh to test
  86845. * @returns true if the mesh will be used
  86846. */
  86847. EffectLayer.prototype.hasMesh = function (mesh) {
  86848. return true;
  86849. };
  86850. /**
  86851. * Returns true if the layer contains information to display, otherwise false.
  86852. * @returns true if the glow layer should be rendered
  86853. */
  86854. EffectLayer.prototype.shouldRender = function () {
  86855. return this.isEnabled && this._shouldRender;
  86856. };
  86857. /**
  86858. * Returns true if the mesh should render, otherwise false.
  86859. * @param mesh The mesh to render
  86860. * @returns true if it should render otherwise false
  86861. */
  86862. EffectLayer.prototype._shouldRenderMesh = function (mesh) {
  86863. return true;
  86864. };
  86865. /**
  86866. * Returns true if the mesh should render, otherwise false.
  86867. * @param mesh The mesh to render
  86868. * @returns true if it should render otherwise false
  86869. */
  86870. EffectLayer.prototype._shouldRenderEmissiveTextureForMesh = function (mesh) {
  86871. return true;
  86872. };
  86873. /**
  86874. * Renders the submesh passed in parameter to the generation map.
  86875. */
  86876. EffectLayer.prototype._renderSubMesh = function (subMesh) {
  86877. var _this = this;
  86878. if (!this.shouldRender()) {
  86879. return;
  86880. }
  86881. var material = subMesh.getMaterial();
  86882. var mesh = subMesh.getRenderingMesh();
  86883. var scene = this._scene;
  86884. var engine = scene.getEngine();
  86885. if (!material) {
  86886. return;
  86887. }
  86888. // Do not block in blend mode.
  86889. if (material.needAlphaBlendingForMesh(mesh)) {
  86890. return;
  86891. }
  86892. // Culling
  86893. engine.setState(material.backFaceCulling);
  86894. // Managing instances
  86895. var batch = mesh._getInstancesRenderList(subMesh._id);
  86896. if (batch.mustReturn) {
  86897. return;
  86898. }
  86899. // Early Exit per mesh
  86900. if (!this._shouldRenderMesh(mesh)) {
  86901. return;
  86902. }
  86903. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  86904. this._setEmissiveTextureAndColor(mesh, subMesh, material);
  86905. if (this._isReady(subMesh, hardwareInstancedRendering, this._emissiveTextureAndColor.texture)) {
  86906. engine.enableEffect(this._effectLayerMapGenerationEffect);
  86907. mesh._bind(subMesh, this._effectLayerMapGenerationEffect, BABYLON.Material.TriangleFillMode);
  86908. this._effectLayerMapGenerationEffect.setMatrix("viewProjection", scene.getTransformMatrix());
  86909. this._effectLayerMapGenerationEffect.setFloat4("color", this._emissiveTextureAndColor.color.r, this._emissiveTextureAndColor.color.g, this._emissiveTextureAndColor.color.b, this._emissiveTextureAndColor.color.a);
  86910. // Alpha test
  86911. if (material && material.needAlphaTesting()) {
  86912. var alphaTexture = material.getAlphaTestTexture();
  86913. if (alphaTexture) {
  86914. this._effectLayerMapGenerationEffect.setTexture("diffuseSampler", alphaTexture);
  86915. var textureMatrix = alphaTexture.getTextureMatrix();
  86916. if (textureMatrix) {
  86917. this._effectLayerMapGenerationEffect.setMatrix("diffuseMatrix", textureMatrix);
  86918. }
  86919. }
  86920. }
  86921. // Glow emissive only
  86922. if (this._emissiveTextureAndColor.texture) {
  86923. this._effectLayerMapGenerationEffect.setTexture("emissiveSampler", this._emissiveTextureAndColor.texture);
  86924. this._effectLayerMapGenerationEffect.setMatrix("emissiveMatrix", this._emissiveTextureAndColor.texture.getTextureMatrix());
  86925. }
  86926. // Bones
  86927. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  86928. this._effectLayerMapGenerationEffect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  86929. }
  86930. // Morph targets
  86931. BABYLON.MaterialHelper.BindMorphTargetParameters(mesh, this._effectLayerMapGenerationEffect);
  86932. // Draw
  86933. mesh._processRendering(subMesh, this._effectLayerMapGenerationEffect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effectLayerMapGenerationEffect.setMatrix("world", world); });
  86934. }
  86935. else {
  86936. // Need to reset refresh rate of the shadowMap
  86937. this._mainTexture.resetRefreshCounter();
  86938. }
  86939. };
  86940. /**
  86941. * Rebuild the required buffers.
  86942. * @ignore Internal use only.
  86943. */
  86944. EffectLayer.prototype._rebuild = function () {
  86945. var vb = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  86946. if (vb) {
  86947. vb._rebuild();
  86948. }
  86949. this._generateIndexBuffer();
  86950. };
  86951. /**
  86952. * Dispose only the render target textures and post process.
  86953. */
  86954. EffectLayer.prototype._disposeTextureAndPostProcesses = function () {
  86955. this._mainTexture.dispose();
  86956. for (var i = 0; i < this._postProcesses.length; i++) {
  86957. if (this._postProcesses[i]) {
  86958. this._postProcesses[i].dispose();
  86959. }
  86960. }
  86961. this._postProcesses = [];
  86962. for (var i = 0; i < this._textures.length; i++) {
  86963. if (this._textures[i]) {
  86964. this._textures[i].dispose();
  86965. }
  86966. }
  86967. this._textures = [];
  86968. };
  86969. /**
  86970. * Dispose the highlight layer and free resources.
  86971. */
  86972. EffectLayer.prototype.dispose = function () {
  86973. var vertexBuffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  86974. if (vertexBuffer) {
  86975. vertexBuffer.dispose();
  86976. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  86977. }
  86978. if (this._indexBuffer) {
  86979. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  86980. this._indexBuffer = null;
  86981. }
  86982. // Clean textures and post processes
  86983. this._disposeTextureAndPostProcesses();
  86984. // Remove from scene
  86985. var index = this._scene.effectLayers.indexOf(this, 0);
  86986. if (index > -1) {
  86987. this._scene.effectLayers.splice(index, 1);
  86988. }
  86989. // Callback
  86990. this.onDisposeObservable.notifyObservers(this);
  86991. this.onDisposeObservable.clear();
  86992. this.onBeforeRenderMainTextureObservable.clear();
  86993. this.onBeforeComposeObservable.clear();
  86994. this.onAfterComposeObservable.clear();
  86995. this.onSizeChangedObservable.clear();
  86996. };
  86997. return EffectLayer;
  86998. }());
  86999. BABYLON.EffectLayer = EffectLayer;
  87000. })(BABYLON || (BABYLON = {}));
  87001. //# sourceMappingURL=babylon.effectLayer.js.map
  87002. "use strict";
  87003. var BABYLON;
  87004. (function (BABYLON) {
  87005. /**
  87006. * Special Glow Blur post process only blurring the alpha channel
  87007. * It enforces keeping the most luminous color in the color channel.
  87008. */
  87009. var GlowBlurPostProcess = /** @class */ (function (_super) {
  87010. __extends(GlowBlurPostProcess, _super);
  87011. function GlowBlurPostProcess(name, direction, kernel, options, camera, samplingMode, engine, reusable) {
  87012. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  87013. var _this = _super.call(this, name, "glowBlurPostProcess", ["screenSize", "direction", "blurWidth"], null, options, camera, samplingMode, engine, reusable) || this;
  87014. _this.direction = direction;
  87015. _this.kernel = kernel;
  87016. _this.onApplyObservable.add(function (effect) {
  87017. effect.setFloat2("screenSize", _this.width, _this.height);
  87018. effect.setVector2("direction", _this.direction);
  87019. effect.setFloat("blurWidth", _this.kernel);
  87020. });
  87021. return _this;
  87022. }
  87023. return GlowBlurPostProcess;
  87024. }(BABYLON.PostProcess));
  87025. /**
  87026. * The highlight layer Helps adding a glow effect around a mesh.
  87027. *
  87028. * Once instantiated in a scene, simply use the pushMesh or removeMesh method to add or remove
  87029. * glowy meshes to your scene.
  87030. *
  87031. * !!! THIS REQUIRES AN ACTIVE STENCIL BUFFER ON THE CANVAS !!!
  87032. */
  87033. var HighlightLayer = /** @class */ (function (_super) {
  87034. __extends(HighlightLayer, _super);
  87035. /**
  87036. * Instantiates a new highlight Layer and references it to the scene..
  87037. * @param name The name of the layer
  87038. * @param scene The scene to use the layer in
  87039. * @param options Sets of none mandatory options to use with the layer (see IHighlightLayerOptions for more information)
  87040. */
  87041. function HighlightLayer(name, scene, options) {
  87042. var _this = _super.call(this, name, scene) || this;
  87043. _this.name = name;
  87044. /**
  87045. * Specifies whether or not the inner glow is ACTIVE in the layer.
  87046. */
  87047. _this.innerGlow = true;
  87048. /**
  87049. * Specifies whether or not the outer glow is ACTIVE in the layer.
  87050. */
  87051. _this.outerGlow = true;
  87052. /**
  87053. * An event triggered when the highlight layer is being blurred.
  87054. */
  87055. _this.onBeforeBlurObservable = new BABYLON.Observable();
  87056. /**
  87057. * An event triggered when the highlight layer has been blurred.
  87058. */
  87059. _this.onAfterBlurObservable = new BABYLON.Observable();
  87060. _this._instanceGlowingMeshStencilReference = HighlightLayer.GlowingMeshStencilReference++;
  87061. _this._meshes = {};
  87062. _this._excludedMeshes = {};
  87063. _this.neutralColor = HighlightLayer.NeutralColor;
  87064. // Warn on stencil
  87065. if (!_this._engine.isStencilEnable) {
  87066. 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 }");
  87067. }
  87068. // Adapt options
  87069. _this._options = __assign({ mainTextureRatio: 0.5, blurTextureSizeRatio: 0.5, blurHorizontalSize: 1.0, blurVerticalSize: 1.0, alphaBlendingMode: BABYLON.Engine.ALPHA_COMBINE, camera: null }, options);
  87070. // Initialize the layer
  87071. _this._init({
  87072. alphaBlendingMode: _this._options.alphaBlendingMode,
  87073. camera: _this._options.camera,
  87074. mainTextureFixedSize: _this._options.mainTextureFixedSize,
  87075. mainTextureRatio: _this._options.mainTextureRatio
  87076. });
  87077. // Do not render as long as no meshes have been added
  87078. _this._shouldRender = false;
  87079. return _this;
  87080. }
  87081. Object.defineProperty(HighlightLayer.prototype, "blurHorizontalSize", {
  87082. /**
  87083. * Gets the horizontal size of the blur.
  87084. */
  87085. get: function () {
  87086. return this._horizontalBlurPostprocess.kernel;
  87087. },
  87088. /**
  87089. * Specifies the horizontal size of the blur.
  87090. */
  87091. set: function (value) {
  87092. this._horizontalBlurPostprocess.kernel = value;
  87093. },
  87094. enumerable: true,
  87095. configurable: true
  87096. });
  87097. Object.defineProperty(HighlightLayer.prototype, "blurVerticalSize", {
  87098. /**
  87099. * Gets the vertical size of the blur.
  87100. */
  87101. get: function () {
  87102. return this._verticalBlurPostprocess.kernel;
  87103. },
  87104. /**
  87105. * Specifies the vertical size of the blur.
  87106. */
  87107. set: function (value) {
  87108. this._verticalBlurPostprocess.kernel = value;
  87109. },
  87110. enumerable: true,
  87111. configurable: true
  87112. });
  87113. /**
  87114. * Get the effect name of the layer.
  87115. * @return The effect name
  87116. */
  87117. HighlightLayer.prototype.getEffectName = function () {
  87118. return HighlightLayer.EffectName;
  87119. };
  87120. /**
  87121. * Create the merge effect. This is the shader use to blit the information back
  87122. * to the main canvas at the end of the scene rendering.
  87123. */
  87124. HighlightLayer.prototype._createMergeEffect = function () {
  87125. // Effect
  87126. return this._engine.createEffect("glowMapMerge", [BABYLON.VertexBuffer.PositionKind], ["offset"], ["textureSampler"], this._options.isStroke ? "#define STROKE \n" : undefined);
  87127. };
  87128. /**
  87129. * Creates the render target textures and post processes used in the highlight layer.
  87130. */
  87131. HighlightLayer.prototype._createTextureAndPostProcesses = function () {
  87132. var _this = this;
  87133. var blurTextureWidth = this._mainTextureDesiredSize.width * this._options.blurTextureSizeRatio;
  87134. var blurTextureHeight = this._mainTextureDesiredSize.height * this._options.blurTextureSizeRatio;
  87135. blurTextureWidth = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(blurTextureWidth, this._maxSize) : blurTextureWidth;
  87136. blurTextureHeight = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(blurTextureHeight, this._maxSize) : blurTextureHeight;
  87137. this._blurTexture = new BABYLON.RenderTargetTexture("HighlightLayerBlurRTT", {
  87138. width: blurTextureWidth,
  87139. height: blurTextureHeight
  87140. }, this._scene, false, true, BABYLON.Engine.TEXTURETYPE_HALF_FLOAT);
  87141. this._blurTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  87142. this._blurTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  87143. this._blurTexture.anisotropicFilteringLevel = 16;
  87144. this._blurTexture.updateSamplingMode(BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  87145. this._blurTexture.renderParticles = false;
  87146. this._blurTexture.ignoreCameraViewport = true;
  87147. this._textures = [this._blurTexture];
  87148. if (this._options.alphaBlendingMode === BABYLON.Engine.ALPHA_COMBINE) {
  87149. this._downSamplePostprocess = new BABYLON.PassPostProcess("HighlightLayerPPP", this._options.blurTextureSizeRatio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine());
  87150. this._downSamplePostprocess.onApplyObservable.add(function (effect) {
  87151. effect.setTexture("textureSampler", _this._mainTexture);
  87152. });
  87153. this._horizontalBlurPostprocess = new GlowBlurPostProcess("HighlightLayerHBP", new BABYLON.Vector2(1.0, 0), this._options.blurHorizontalSize, 1, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine());
  87154. this._horizontalBlurPostprocess.onApplyObservable.add(function (effect) {
  87155. effect.setFloat2("screenSize", blurTextureWidth, blurTextureHeight);
  87156. });
  87157. this._verticalBlurPostprocess = new GlowBlurPostProcess("HighlightLayerVBP", new BABYLON.Vector2(0, 1.0), this._options.blurVerticalSize, 1, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine());
  87158. this._verticalBlurPostprocess.onApplyObservable.add(function (effect) {
  87159. effect.setFloat2("screenSize", blurTextureWidth, blurTextureHeight);
  87160. });
  87161. this._postProcesses = [this._downSamplePostprocess, this._horizontalBlurPostprocess, this._verticalBlurPostprocess];
  87162. }
  87163. else {
  87164. this._horizontalBlurPostprocess = new BABYLON.BlurPostProcess("HighlightLayerHBP", new BABYLON.Vector2(1.0, 0), this._options.blurHorizontalSize / 2, {
  87165. width: blurTextureWidth,
  87166. height: blurTextureHeight
  87167. }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, BABYLON.Engine.TEXTURETYPE_HALF_FLOAT);
  87168. this._horizontalBlurPostprocess.width = blurTextureWidth;
  87169. this._horizontalBlurPostprocess.height = blurTextureHeight;
  87170. this._horizontalBlurPostprocess.onApplyObservable.add(function (effect) {
  87171. effect.setTexture("textureSampler", _this._mainTexture);
  87172. });
  87173. this._verticalBlurPostprocess = new BABYLON.BlurPostProcess("HighlightLayerVBP", new BABYLON.Vector2(0, 1.0), this._options.blurVerticalSize / 2, {
  87174. width: blurTextureWidth,
  87175. height: blurTextureHeight
  87176. }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, BABYLON.Engine.TEXTURETYPE_HALF_FLOAT);
  87177. this._postProcesses = [this._horizontalBlurPostprocess, this._verticalBlurPostprocess];
  87178. }
  87179. this._mainTexture.onAfterUnbindObservable.add(function () {
  87180. _this.onBeforeBlurObservable.notifyObservers(_this);
  87181. var internalTexture = _this._blurTexture.getInternalTexture();
  87182. if (internalTexture) {
  87183. _this._scene.postProcessManager.directRender(_this._postProcesses, internalTexture, true);
  87184. }
  87185. _this.onAfterBlurObservable.notifyObservers(_this);
  87186. });
  87187. // Prevent autoClear.
  87188. this._postProcesses.map(function (pp) { pp.autoClear = false; });
  87189. };
  87190. /**
  87191. * Returns wether or nood the layer needs stencil enabled during the mesh rendering.
  87192. */
  87193. HighlightLayer.prototype.needStencil = function () {
  87194. return true;
  87195. };
  87196. /**
  87197. * Checks for the readiness of the element composing the layer.
  87198. * @param subMesh the mesh to check for
  87199. * @param useInstances specify wether or not to use instances to render the mesh
  87200. * @param emissiveTexture the associated emissive texture used to generate the glow
  87201. * @return true if ready otherwise, false
  87202. */
  87203. HighlightLayer.prototype.isReady = function (subMesh, useInstances) {
  87204. var material = subMesh.getMaterial();
  87205. var mesh = subMesh.getRenderingMesh();
  87206. if (!material || !mesh || !this._meshes) {
  87207. return false;
  87208. }
  87209. var emissiveTexture = null;
  87210. var highlightLayerMesh = this._meshes[mesh.uniqueId];
  87211. if (highlightLayerMesh && highlightLayerMesh.glowEmissiveOnly && material) {
  87212. emissiveTexture = material.emissiveTexture;
  87213. }
  87214. return _super.prototype._isReady.call(this, subMesh, useInstances, emissiveTexture);
  87215. };
  87216. /**
  87217. * Implementation specific of rendering the generating effect on the main canvas.
  87218. * @param effect The effect used to render through
  87219. */
  87220. HighlightLayer.prototype._internalRender = function (effect) {
  87221. // Texture
  87222. effect.setTexture("textureSampler", this._blurTexture);
  87223. // Cache
  87224. var engine = this._engine;
  87225. var previousStencilBuffer = engine.getStencilBuffer();
  87226. var previousStencilFunction = engine.getStencilFunction();
  87227. var previousStencilMask = engine.getStencilMask();
  87228. var previousStencilOperationPass = engine.getStencilOperationPass();
  87229. var previousStencilOperationFail = engine.getStencilOperationFail();
  87230. var previousStencilOperationDepthFail = engine.getStencilOperationDepthFail();
  87231. var previousStencilReference = engine.getStencilFunctionReference();
  87232. // Stencil operations
  87233. engine.setStencilOperationPass(BABYLON.Engine.REPLACE);
  87234. engine.setStencilOperationFail(BABYLON.Engine.KEEP);
  87235. engine.setStencilOperationDepthFail(BABYLON.Engine.KEEP);
  87236. // Draw order
  87237. engine.setStencilMask(0x00);
  87238. engine.setStencilBuffer(true);
  87239. engine.setStencilFunctionReference(this._instanceGlowingMeshStencilReference);
  87240. // 2 passes inner outer
  87241. if (this.outerGlow) {
  87242. effect.setFloat("offset", 0);
  87243. engine.setStencilFunction(BABYLON.Engine.NOTEQUAL);
  87244. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  87245. }
  87246. if (this.innerGlow) {
  87247. effect.setFloat("offset", 1);
  87248. engine.setStencilFunction(BABYLON.Engine.EQUAL);
  87249. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  87250. }
  87251. // Restore Cache
  87252. engine.setStencilFunction(previousStencilFunction);
  87253. engine.setStencilMask(previousStencilMask);
  87254. engine.setStencilBuffer(previousStencilBuffer);
  87255. engine.setStencilOperationPass(previousStencilOperationPass);
  87256. engine.setStencilOperationFail(previousStencilOperationFail);
  87257. engine.setStencilOperationDepthFail(previousStencilOperationDepthFail);
  87258. engine.setStencilFunctionReference(previousStencilReference);
  87259. };
  87260. /**
  87261. * Returns true if the layer contains information to display, otherwise false.
  87262. */
  87263. HighlightLayer.prototype.shouldRender = function () {
  87264. if (_super.prototype.shouldRender.call(this)) {
  87265. return this._meshes ? true : false;
  87266. }
  87267. return false;
  87268. };
  87269. /**
  87270. * Returns true if the mesh should render, otherwise false.
  87271. * @param mesh The mesh to render
  87272. * @returns true if it should render otherwise false
  87273. */
  87274. HighlightLayer.prototype._shouldRenderMesh = function (mesh) {
  87275. // Excluded Mesh
  87276. if (this._excludedMeshes && this._excludedMeshes[mesh.uniqueId]) {
  87277. return false;
  87278. }
  87279. ;
  87280. return true;
  87281. };
  87282. /**
  87283. * Sets the required values for both the emissive texture and and the main color.
  87284. */
  87285. HighlightLayer.prototype._setEmissiveTextureAndColor = function (mesh, subMesh, material) {
  87286. var highlightLayerMesh = this._meshes[mesh.uniqueId];
  87287. if (highlightLayerMesh) {
  87288. this._emissiveTextureAndColor.color.set(highlightLayerMesh.color.r, highlightLayerMesh.color.g, highlightLayerMesh.color.b, 1.0);
  87289. }
  87290. else {
  87291. this._emissiveTextureAndColor.color.set(this.neutralColor.r, this.neutralColor.g, this.neutralColor.b, this.neutralColor.a);
  87292. }
  87293. if (highlightLayerMesh && highlightLayerMesh.glowEmissiveOnly && material) {
  87294. this._emissiveTextureAndColor.texture = material.emissiveTexture;
  87295. this._emissiveTextureAndColor.color.set(1.0, 1.0, 1.0, 1.0);
  87296. }
  87297. else {
  87298. this._emissiveTextureAndColor.texture = null;
  87299. }
  87300. };
  87301. /**
  87302. * Add a mesh in the exclusion list to prevent it to impact or being impacted by the highlight layer.
  87303. * @param mesh The mesh to exclude from the highlight layer
  87304. */
  87305. HighlightLayer.prototype.addExcludedMesh = function (mesh) {
  87306. if (!this._excludedMeshes) {
  87307. return;
  87308. }
  87309. var meshExcluded = this._excludedMeshes[mesh.uniqueId];
  87310. if (!meshExcluded) {
  87311. this._excludedMeshes[mesh.uniqueId] = {
  87312. mesh: mesh,
  87313. beforeRender: mesh.onBeforeRenderObservable.add(function (mesh) {
  87314. mesh.getEngine().setStencilBuffer(false);
  87315. }),
  87316. afterRender: mesh.onAfterRenderObservable.add(function (mesh) {
  87317. mesh.getEngine().setStencilBuffer(true);
  87318. }),
  87319. };
  87320. }
  87321. };
  87322. /**
  87323. * Remove a mesh from the exclusion list to let it impact or being impacted by the highlight layer.
  87324. * @param mesh The mesh to highlight
  87325. */
  87326. HighlightLayer.prototype.removeExcludedMesh = function (mesh) {
  87327. if (!this._excludedMeshes) {
  87328. return;
  87329. }
  87330. var meshExcluded = this._excludedMeshes[mesh.uniqueId];
  87331. if (meshExcluded) {
  87332. if (meshExcluded.beforeRender) {
  87333. mesh.onBeforeRenderObservable.remove(meshExcluded.beforeRender);
  87334. }
  87335. if (meshExcluded.afterRender) {
  87336. mesh.onAfterRenderObservable.remove(meshExcluded.afterRender);
  87337. }
  87338. }
  87339. this._excludedMeshes[mesh.uniqueId] = null;
  87340. };
  87341. /**
  87342. * Determine if a given mesh will be highlighted by the current HighlightLayer
  87343. * @param mesh mesh to test
  87344. * @returns true if the mesh will be highlighted by the current HighlightLayer
  87345. */
  87346. HighlightLayer.prototype.hasMesh = function (mesh) {
  87347. if (!this._meshes) {
  87348. return false;
  87349. }
  87350. return this._meshes[mesh.uniqueId] !== undefined && this._meshes[mesh.uniqueId] !== null;
  87351. };
  87352. /**
  87353. * Add a mesh in the highlight layer in order to make it glow with the chosen color.
  87354. * @param mesh The mesh to highlight
  87355. * @param color The color of the highlight
  87356. * @param glowEmissiveOnly Extract the glow from the emissive texture
  87357. */
  87358. HighlightLayer.prototype.addMesh = function (mesh, color, glowEmissiveOnly) {
  87359. var _this = this;
  87360. if (glowEmissiveOnly === void 0) { glowEmissiveOnly = false; }
  87361. if (!this._meshes) {
  87362. return;
  87363. }
  87364. var meshHighlight = this._meshes[mesh.uniqueId];
  87365. if (meshHighlight) {
  87366. meshHighlight.color = color;
  87367. }
  87368. else {
  87369. this._meshes[mesh.uniqueId] = {
  87370. mesh: mesh,
  87371. color: color,
  87372. // Lambda required for capture due to Observable this context
  87373. observerHighlight: mesh.onBeforeRenderObservable.add(function (mesh) {
  87374. if (_this._excludedMeshes && _this._excludedMeshes[mesh.uniqueId]) {
  87375. _this._defaultStencilReference(mesh);
  87376. }
  87377. else {
  87378. mesh.getScene().getEngine().setStencilFunctionReference(_this._instanceGlowingMeshStencilReference);
  87379. }
  87380. }),
  87381. observerDefault: mesh.onAfterRenderObservable.add(this._defaultStencilReference),
  87382. glowEmissiveOnly: glowEmissiveOnly
  87383. };
  87384. }
  87385. this._shouldRender = true;
  87386. };
  87387. /**
  87388. * Remove a mesh from the highlight layer in order to make it stop glowing.
  87389. * @param mesh The mesh to highlight
  87390. */
  87391. HighlightLayer.prototype.removeMesh = function (mesh) {
  87392. if (!this._meshes) {
  87393. return;
  87394. }
  87395. var meshHighlight = this._meshes[mesh.uniqueId];
  87396. if (meshHighlight) {
  87397. if (meshHighlight.observerHighlight) {
  87398. mesh.onBeforeRenderObservable.remove(meshHighlight.observerHighlight);
  87399. }
  87400. if (meshHighlight.observerDefault) {
  87401. mesh.onAfterRenderObservable.remove(meshHighlight.observerDefault);
  87402. }
  87403. delete this._meshes[mesh.uniqueId];
  87404. }
  87405. this._shouldRender = false;
  87406. for (var meshHighlightToCheck in this._meshes) {
  87407. if (this._meshes[meshHighlightToCheck]) {
  87408. this._shouldRender = true;
  87409. break;
  87410. }
  87411. }
  87412. };
  87413. /**
  87414. * Force the stencil to the normal expected value for none glowing parts
  87415. */
  87416. HighlightLayer.prototype._defaultStencilReference = function (mesh) {
  87417. mesh.getScene().getEngine().setStencilFunctionReference(HighlightLayer.NormalMeshStencilReference);
  87418. };
  87419. /**
  87420. * Free any resources and references associated to a mesh.
  87421. * Internal use
  87422. * @param mesh The mesh to free.
  87423. */
  87424. HighlightLayer.prototype._disposeMesh = function (mesh) {
  87425. this.removeMesh(mesh);
  87426. this.removeExcludedMesh(mesh);
  87427. };
  87428. /**
  87429. * Dispose the highlight layer and free resources.
  87430. */
  87431. HighlightLayer.prototype.dispose = function () {
  87432. if (this._meshes) {
  87433. // Clean mesh references
  87434. for (var id in this._meshes) {
  87435. var meshHighlight = this._meshes[id];
  87436. if (meshHighlight && meshHighlight.mesh) {
  87437. if (meshHighlight.observerHighlight) {
  87438. meshHighlight.mesh.onBeforeRenderObservable.remove(meshHighlight.observerHighlight);
  87439. }
  87440. if (meshHighlight.observerDefault) {
  87441. meshHighlight.mesh.onAfterRenderObservable.remove(meshHighlight.observerDefault);
  87442. }
  87443. }
  87444. }
  87445. this._meshes = null;
  87446. }
  87447. if (this._excludedMeshes) {
  87448. for (var id in this._excludedMeshes) {
  87449. var meshHighlight = this._excludedMeshes[id];
  87450. if (meshHighlight) {
  87451. if (meshHighlight.beforeRender) {
  87452. meshHighlight.mesh.onBeforeRenderObservable.remove(meshHighlight.beforeRender);
  87453. }
  87454. if (meshHighlight.afterRender) {
  87455. meshHighlight.mesh.onAfterRenderObservable.remove(meshHighlight.afterRender);
  87456. }
  87457. }
  87458. }
  87459. this._excludedMeshes = null;
  87460. }
  87461. _super.prototype.dispose.call(this);
  87462. };
  87463. /**
  87464. * Effect Name of the highlight layer.
  87465. */
  87466. HighlightLayer.EffectName = "HighlightLayer";
  87467. /**
  87468. * The neutral color used during the preparation of the glow effect.
  87469. * This is black by default as the blend operation is a blend operation.
  87470. */
  87471. HighlightLayer.NeutralColor = new BABYLON.Color4(0, 0, 0, 0);
  87472. /**
  87473. * Stencil value used for glowing meshes.
  87474. */
  87475. HighlightLayer.GlowingMeshStencilReference = 0x02;
  87476. /**
  87477. * Stencil value used for the other meshes in the scene.
  87478. */
  87479. HighlightLayer.NormalMeshStencilReference = 0x01;
  87480. return HighlightLayer;
  87481. }(BABYLON.EffectLayer));
  87482. BABYLON.HighlightLayer = HighlightLayer;
  87483. })(BABYLON || (BABYLON = {}));
  87484. //# sourceMappingURL=babylon.highlightLayer.js.map
  87485. "use strict";
  87486. var BABYLON;
  87487. (function (BABYLON) {
  87488. /**
  87489. * The glow layer Helps adding a glow effect around the emissive parts of a mesh.
  87490. *
  87491. * Once instantiated in a scene, simply use the pushMesh or removeMesh method to add or remove
  87492. * glowy meshes to your scene.
  87493. *
  87494. * Documentation: https://doc.babylonjs.com/how_to/glow_layer
  87495. */
  87496. var GlowLayer = /** @class */ (function (_super) {
  87497. __extends(GlowLayer, _super);
  87498. /**
  87499. * Instantiates a new glow Layer and references it to the scene.
  87500. * @param name The name of the layer
  87501. * @param scene The scene to use the layer in
  87502. * @param options Sets of none mandatory options to use with the layer (see IGlowLayerOptions for more information)
  87503. */
  87504. function GlowLayer(name, scene, options) {
  87505. var _this = _super.call(this, name, scene) || this;
  87506. _this.name = name;
  87507. _this._intensity = 1.0;
  87508. _this._includedOnlyMeshes = [];
  87509. _this._excludedMeshes = [];
  87510. _this.neutralColor = new BABYLON.Color4(0, 0, 0, 1);
  87511. // Adapt options
  87512. _this._options = __assign({ mainTextureRatio: GlowLayer.DefaultTextureRatio, blurKernelSize: 32, mainTextureFixedSize: undefined, camera: null, mainTextureSamples: 1 }, options);
  87513. // Initialize the layer
  87514. _this._init({
  87515. alphaBlendingMode: BABYLON.Engine.ALPHA_ADD,
  87516. camera: _this._options.camera,
  87517. mainTextureFixedSize: _this._options.mainTextureFixedSize,
  87518. mainTextureRatio: _this._options.mainTextureRatio
  87519. });
  87520. return _this;
  87521. }
  87522. Object.defineProperty(GlowLayer.prototype, "blurKernelSize", {
  87523. /**
  87524. * Gets the kernel size of the blur.
  87525. */
  87526. get: function () {
  87527. return this._horizontalBlurPostprocess1.kernel;
  87528. },
  87529. /**
  87530. * Sets the kernel size of the blur.
  87531. */
  87532. set: function (value) {
  87533. this._horizontalBlurPostprocess1.kernel = value;
  87534. this._verticalBlurPostprocess1.kernel = value;
  87535. this._horizontalBlurPostprocess2.kernel = value;
  87536. this._verticalBlurPostprocess2.kernel = value;
  87537. },
  87538. enumerable: true,
  87539. configurable: true
  87540. });
  87541. Object.defineProperty(GlowLayer.prototype, "intensity", {
  87542. /**
  87543. * Gets the glow intensity.
  87544. */
  87545. get: function () {
  87546. return this._intensity;
  87547. },
  87548. /**
  87549. * Sets the glow intensity.
  87550. */
  87551. set: function (value) {
  87552. this._intensity = value;
  87553. },
  87554. enumerable: true,
  87555. configurable: true
  87556. });
  87557. /**
  87558. * Get the effect name of the layer.
  87559. * @return The effect name
  87560. */
  87561. GlowLayer.prototype.getEffectName = function () {
  87562. return GlowLayer.EffectName;
  87563. };
  87564. /**
  87565. * Create the merge effect. This is the shader use to blit the information back
  87566. * to the main canvas at the end of the scene rendering.
  87567. */
  87568. GlowLayer.prototype._createMergeEffect = function () {
  87569. // Effect
  87570. return this._engine.createEffect("glowMapMerge", [BABYLON.VertexBuffer.PositionKind], ["offset"], ["textureSampler", "textureSampler2"], "#define EMISSIVE \n");
  87571. };
  87572. /**
  87573. * Creates the render target textures and post processes used in the glow layer.
  87574. */
  87575. GlowLayer.prototype._createTextureAndPostProcesses = function () {
  87576. var _this = this;
  87577. var blurTextureWidth = this._mainTextureDesiredSize.width;
  87578. var blurTextureHeight = this._mainTextureDesiredSize.height;
  87579. blurTextureWidth = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(blurTextureWidth, this._maxSize) : blurTextureWidth;
  87580. blurTextureHeight = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(blurTextureHeight, this._maxSize) : blurTextureHeight;
  87581. this._blurTexture1 = new BABYLON.RenderTargetTexture("GlowLayerBlurRTT", {
  87582. width: blurTextureWidth,
  87583. height: blurTextureHeight
  87584. }, this._scene, false, true, BABYLON.Engine.TEXTURETYPE_HALF_FLOAT);
  87585. this._blurTexture1.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  87586. this._blurTexture1.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  87587. this._blurTexture1.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  87588. this._blurTexture1.renderParticles = false;
  87589. this._blurTexture1.ignoreCameraViewport = true;
  87590. var blurTextureWidth2 = Math.floor(blurTextureWidth / 2);
  87591. var blurTextureHeight2 = Math.floor(blurTextureHeight / 2);
  87592. this._blurTexture2 = new BABYLON.RenderTargetTexture("GlowLayerBlurRTT2", {
  87593. width: blurTextureWidth2,
  87594. height: blurTextureHeight2
  87595. }, this._scene, false, true, BABYLON.Engine.TEXTURETYPE_HALF_FLOAT);
  87596. this._blurTexture2.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  87597. this._blurTexture2.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  87598. this._blurTexture2.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  87599. this._blurTexture2.renderParticles = false;
  87600. this._blurTexture2.ignoreCameraViewport = true;
  87601. this._textures = [this._blurTexture1, this._blurTexture2];
  87602. this._horizontalBlurPostprocess1 = new BABYLON.BlurPostProcess("GlowLayerHBP1", new BABYLON.Vector2(1.0, 0), this._options.blurKernelSize / 2, {
  87603. width: blurTextureWidth,
  87604. height: blurTextureHeight
  87605. }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, BABYLON.Engine.TEXTURETYPE_HALF_FLOAT);
  87606. this._horizontalBlurPostprocess1.width = blurTextureWidth;
  87607. this._horizontalBlurPostprocess1.height = blurTextureHeight;
  87608. this._horizontalBlurPostprocess1.onApplyObservable.add(function (effect) {
  87609. effect.setTexture("textureSampler", _this._mainTexture);
  87610. });
  87611. this._verticalBlurPostprocess1 = new BABYLON.BlurPostProcess("GlowLayerVBP1", new BABYLON.Vector2(0, 1.0), this._options.blurKernelSize / 2, {
  87612. width: blurTextureWidth,
  87613. height: blurTextureHeight
  87614. }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, BABYLON.Engine.TEXTURETYPE_HALF_FLOAT);
  87615. this._horizontalBlurPostprocess2 = new BABYLON.BlurPostProcess("GlowLayerHBP2", new BABYLON.Vector2(1.0, 0), this._options.blurKernelSize / 2, {
  87616. width: blurTextureWidth2,
  87617. height: blurTextureHeight2
  87618. }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, BABYLON.Engine.TEXTURETYPE_HALF_FLOAT);
  87619. this._horizontalBlurPostprocess2.width = blurTextureWidth2;
  87620. this._horizontalBlurPostprocess2.height = blurTextureHeight2;
  87621. this._horizontalBlurPostprocess2.onApplyObservable.add(function (effect) {
  87622. effect.setTexture("textureSampler", _this._blurTexture1);
  87623. });
  87624. this._verticalBlurPostprocess2 = new BABYLON.BlurPostProcess("GlowLayerVBP2", new BABYLON.Vector2(0, 1.0), this._options.blurKernelSize / 2, {
  87625. width: blurTextureWidth2,
  87626. height: blurTextureHeight2
  87627. }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, BABYLON.Engine.TEXTURETYPE_HALF_FLOAT);
  87628. this._postProcesses = [this._horizontalBlurPostprocess1, this._verticalBlurPostprocess1, this._horizontalBlurPostprocess2, this._verticalBlurPostprocess2];
  87629. this._postProcesses1 = [this._horizontalBlurPostprocess1, this._verticalBlurPostprocess1];
  87630. this._postProcesses2 = [this._horizontalBlurPostprocess2, this._verticalBlurPostprocess2];
  87631. this._mainTexture.samples = this._options.mainTextureSamples;
  87632. this._mainTexture.onAfterUnbindObservable.add(function () {
  87633. var internalTexture = _this._blurTexture1.getInternalTexture();
  87634. if (internalTexture) {
  87635. _this._scene.postProcessManager.directRender(_this._postProcesses1, internalTexture, true);
  87636. internalTexture = _this._blurTexture2.getInternalTexture();
  87637. if (internalTexture) {
  87638. _this._scene.postProcessManager.directRender(_this._postProcesses2, internalTexture, true);
  87639. }
  87640. }
  87641. });
  87642. // Prevent autoClear.
  87643. this._postProcesses.map(function (pp) { pp.autoClear = false; });
  87644. };
  87645. /**
  87646. * Checks for the readiness of the element composing the layer.
  87647. * @param subMesh the mesh to check for
  87648. * @param useInstances specify wether or not to use instances to render the mesh
  87649. * @param emissiveTexture the associated emissive texture used to generate the glow
  87650. * @return true if ready otherwise, false
  87651. */
  87652. GlowLayer.prototype.isReady = function (subMesh, useInstances) {
  87653. var material = subMesh.getMaterial();
  87654. var mesh = subMesh.getRenderingMesh();
  87655. if (!material || !mesh) {
  87656. return false;
  87657. }
  87658. var emissiveTexture = material.emissiveTexture;
  87659. return _super.prototype._isReady.call(this, subMesh, useInstances, emissiveTexture);
  87660. };
  87661. /**
  87662. * Returns wether or nood the layer needs stencil enabled during the mesh rendering.
  87663. */
  87664. GlowLayer.prototype.needStencil = function () {
  87665. return false;
  87666. };
  87667. /**
  87668. * Implementation specific of rendering the generating effect on the main canvas.
  87669. * @param effect The effect used to render through
  87670. */
  87671. GlowLayer.prototype._internalRender = function (effect) {
  87672. // Texture
  87673. effect.setTexture("textureSampler", this._blurTexture1);
  87674. effect.setTexture("textureSampler2", this._blurTexture2);
  87675. effect.setFloat("offset", this._intensity);
  87676. // Cache
  87677. var engine = this._engine;
  87678. var previousStencilBuffer = engine.getStencilBuffer();
  87679. // Draw order
  87680. engine.setStencilBuffer(false);
  87681. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  87682. // Draw order
  87683. engine.setStencilBuffer(previousStencilBuffer);
  87684. };
  87685. /**
  87686. * Sets the required values for both the emissive texture and and the main color.
  87687. */
  87688. GlowLayer.prototype._setEmissiveTextureAndColor = function (mesh, subMesh, material) {
  87689. var textureLevel = 1.0;
  87690. if (this.customEmissiveTextureSelector) {
  87691. this._emissiveTextureAndColor.texture = this.customEmissiveTextureSelector(mesh, subMesh, material);
  87692. }
  87693. else {
  87694. if (material) {
  87695. this._emissiveTextureAndColor.texture = material.emissiveTexture;
  87696. if (this._emissiveTextureAndColor.texture) {
  87697. textureLevel = this._emissiveTextureAndColor.texture.level;
  87698. }
  87699. }
  87700. else {
  87701. this._emissiveTextureAndColor.texture = null;
  87702. }
  87703. }
  87704. if (this.customEmissiveColorSelector) {
  87705. this.customEmissiveColorSelector(mesh, subMesh, material, this._emissiveTextureAndColor.color);
  87706. }
  87707. else {
  87708. if (material.emissiveColor) {
  87709. this._emissiveTextureAndColor.color.set(material.emissiveColor.r * textureLevel, material.emissiveColor.g * textureLevel, material.emissiveColor.b * textureLevel, 1.0);
  87710. }
  87711. else {
  87712. this._emissiveTextureAndColor.color.set(this.neutralColor.r, this.neutralColor.g, this.neutralColor.b, this.neutralColor.a);
  87713. }
  87714. }
  87715. };
  87716. /**
  87717. * Returns true if the mesh should render, otherwise false.
  87718. * @param mesh The mesh to render
  87719. * @returns true if it should render otherwise false
  87720. */
  87721. GlowLayer.prototype._shouldRenderMesh = function (mesh) {
  87722. return this.hasMesh(mesh);
  87723. };
  87724. /**
  87725. * Add a mesh in the exclusion list to prevent it to impact or being impacted by the glow layer.
  87726. * @param mesh The mesh to exclude from the glow layer
  87727. */
  87728. GlowLayer.prototype.addExcludedMesh = function (mesh) {
  87729. if (this._excludedMeshes.indexOf(mesh.uniqueId) === -1) {
  87730. this._excludedMeshes.push(mesh.uniqueId);
  87731. }
  87732. };
  87733. /**
  87734. * Remove a mesh from the exclusion list to let it impact or being impacted by the glow layer.
  87735. * @param mesh The mesh to remove
  87736. */
  87737. GlowLayer.prototype.removeExcludedMesh = function (mesh) {
  87738. var index = this._excludedMeshes.indexOf(mesh.uniqueId);
  87739. if (index !== -1) {
  87740. this._excludedMeshes.splice(index, 1);
  87741. }
  87742. };
  87743. /**
  87744. * Add a mesh in the inclusion list to impact or being impacted by the glow layer.
  87745. * @param mesh The mesh to include in the glow layer
  87746. */
  87747. GlowLayer.prototype.addIncludedOnlyMesh = function (mesh) {
  87748. if (this._includedOnlyMeshes.indexOf(mesh.uniqueId) === -1) {
  87749. this._includedOnlyMeshes.push(mesh.uniqueId);
  87750. }
  87751. };
  87752. /**
  87753. * Remove a mesh from the Inclusion list to prevent it to impact or being impacted by the glow layer.
  87754. * @param mesh The mesh to remove
  87755. */
  87756. GlowLayer.prototype.removeIncludedOnlyMesh = function (mesh) {
  87757. var index = this._includedOnlyMeshes.indexOf(mesh.uniqueId);
  87758. if (index !== -1) {
  87759. this._includedOnlyMeshes.splice(index, 1);
  87760. }
  87761. };
  87762. /**
  87763. * Determine if a given mesh will be used in the glow layer
  87764. * @param mesh The mesh to test
  87765. * @returns true if the mesh will be highlighted by the current glow layer
  87766. */
  87767. GlowLayer.prototype.hasMesh = function (mesh) {
  87768. // Included Mesh
  87769. if (this._includedOnlyMeshes.length) {
  87770. return this._includedOnlyMeshes.indexOf(mesh.uniqueId) !== -1;
  87771. }
  87772. ;
  87773. // Excluded Mesh
  87774. if (this._excludedMeshes.length) {
  87775. return this._excludedMeshes.indexOf(mesh.uniqueId) === -1;
  87776. }
  87777. ;
  87778. return true;
  87779. };
  87780. /**
  87781. * Free any resources and references associated to a mesh.
  87782. * Internal use
  87783. * @param mesh The mesh to free.
  87784. */
  87785. GlowLayer.prototype._disposeMesh = function (mesh) {
  87786. this.removeIncludedOnlyMesh(mesh);
  87787. this.removeExcludedMesh(mesh);
  87788. };
  87789. /**
  87790. * Effect Name of the layer.
  87791. */
  87792. GlowLayer.EffectName = "GlowLayer";
  87793. /**
  87794. * The default blur kernel size used for the glow.
  87795. */
  87796. GlowLayer.DefaultBlurKernelSize = 32;
  87797. /**
  87798. * The default texture size ratio used for the glow.
  87799. */
  87800. GlowLayer.DefaultTextureRatio = 0.5;
  87801. return GlowLayer;
  87802. }(BABYLON.EffectLayer));
  87803. BABYLON.GlowLayer = GlowLayer;
  87804. })(BABYLON || (BABYLON = {}));
  87805. //# sourceMappingURL=babylon.glowLayer.js.map
  87806. "use strict";
  87807. var BABYLON;
  87808. (function (BABYLON) {
  87809. /**
  87810. * Defines the list of states available for a task inside a {BABYLON.AssetsManager}
  87811. */
  87812. var AssetTaskState;
  87813. (function (AssetTaskState) {
  87814. /**
  87815. * Initialization
  87816. */
  87817. AssetTaskState[AssetTaskState["INIT"] = 0] = "INIT";
  87818. /**
  87819. * Running
  87820. */
  87821. AssetTaskState[AssetTaskState["RUNNING"] = 1] = "RUNNING";
  87822. /**
  87823. * Done
  87824. */
  87825. AssetTaskState[AssetTaskState["DONE"] = 2] = "DONE";
  87826. /**
  87827. * Error
  87828. */
  87829. AssetTaskState[AssetTaskState["ERROR"] = 3] = "ERROR";
  87830. })(AssetTaskState = BABYLON.AssetTaskState || (BABYLON.AssetTaskState = {}));
  87831. /**
  87832. * Define an abstract asset task used with a {BABYLON.AssetsManager} class to load assets into a scene
  87833. */
  87834. var AbstractAssetTask = /** @class */ (function () {
  87835. /**
  87836. * Creates a new {BABYLON.AssetsManager}
  87837. * @param name defines the name of the task
  87838. */
  87839. function AbstractAssetTask(
  87840. /**
  87841. * Task name
  87842. */ name) {
  87843. this.name = name;
  87844. this._isCompleted = false;
  87845. this._taskState = AssetTaskState.INIT;
  87846. }
  87847. Object.defineProperty(AbstractAssetTask.prototype, "isCompleted", {
  87848. /**
  87849. * Get if the task is completed
  87850. */
  87851. get: function () {
  87852. return this._isCompleted;
  87853. },
  87854. enumerable: true,
  87855. configurable: true
  87856. });
  87857. Object.defineProperty(AbstractAssetTask.prototype, "taskState", {
  87858. /**
  87859. * Gets the current state of the task
  87860. */
  87861. get: function () {
  87862. return this._taskState;
  87863. },
  87864. enumerable: true,
  87865. configurable: true
  87866. });
  87867. Object.defineProperty(AbstractAssetTask.prototype, "errorObject", {
  87868. /**
  87869. * Gets the current error object (if task is in error)
  87870. */
  87871. get: function () {
  87872. return this._errorObject;
  87873. },
  87874. enumerable: true,
  87875. configurable: true
  87876. });
  87877. /**
  87878. * Internal only
  87879. * @ignore
  87880. */
  87881. AbstractAssetTask.prototype._setErrorObject = function (message, exception) {
  87882. if (this._errorObject) {
  87883. return;
  87884. }
  87885. this._errorObject = {
  87886. message: message,
  87887. exception: exception
  87888. };
  87889. };
  87890. /**
  87891. * Execute the current task
  87892. * @param scene defines the scene where you want your assets to be loaded
  87893. * @param onSuccess is a callback called when the task is successfully executed
  87894. * @param onError is a callback called if an error occurs
  87895. */
  87896. AbstractAssetTask.prototype.run = function (scene, onSuccess, onError) {
  87897. var _this = this;
  87898. this._taskState = AssetTaskState.RUNNING;
  87899. this.runTask(scene, function () {
  87900. _this.onDoneCallback(onSuccess, onError);
  87901. }, function (msg, exception) {
  87902. _this.onErrorCallback(onError, msg, exception);
  87903. });
  87904. };
  87905. /**
  87906. * Execute the current task
  87907. * @param scene defines the scene where you want your assets to be loaded
  87908. * @param onSuccess is a callback called when the task is successfully executed
  87909. * @param onError is a callback called if an error occurs
  87910. */
  87911. AbstractAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  87912. throw new Error("runTask is not implemented");
  87913. };
  87914. AbstractAssetTask.prototype.onErrorCallback = function (onError, message, exception) {
  87915. this._taskState = AssetTaskState.ERROR;
  87916. this._errorObject = {
  87917. message: message,
  87918. exception: exception
  87919. };
  87920. if (this.onError) {
  87921. this.onError(this, message, exception);
  87922. }
  87923. onError();
  87924. };
  87925. AbstractAssetTask.prototype.onDoneCallback = function (onSuccess, onError) {
  87926. try {
  87927. this._taskState = AssetTaskState.DONE;
  87928. this._isCompleted = true;
  87929. if (this.onSuccess) {
  87930. this.onSuccess(this);
  87931. }
  87932. onSuccess();
  87933. }
  87934. catch (e) {
  87935. this.onErrorCallback(onError, "Task is done, error executing success callback(s)", e);
  87936. }
  87937. };
  87938. return AbstractAssetTask;
  87939. }());
  87940. BABYLON.AbstractAssetTask = AbstractAssetTask;
  87941. /**
  87942. * Class used to share progress information about assets loading
  87943. */
  87944. var AssetsProgressEvent = /** @class */ (function () {
  87945. /**
  87946. * Creates a {BABYLON.AssetsProgressEvent}
  87947. * @param remainingCount defines the number of remaining tasks to process
  87948. * @param totalCount defines the total number of tasks
  87949. * @param task defines the task that was just processed
  87950. */
  87951. function AssetsProgressEvent(remainingCount, totalCount, task) {
  87952. this.remainingCount = remainingCount;
  87953. this.totalCount = totalCount;
  87954. this.task = task;
  87955. }
  87956. return AssetsProgressEvent;
  87957. }());
  87958. BABYLON.AssetsProgressEvent = AssetsProgressEvent;
  87959. /**
  87960. * Define a task used by {BABYLON.AssetsManager} to load meshes
  87961. */
  87962. var MeshAssetTask = /** @class */ (function (_super) {
  87963. __extends(MeshAssetTask, _super);
  87964. /**
  87965. * Creates a new {BABYLON.MeshAssetTask}
  87966. * @param name defines the name of the task
  87967. * @param meshesNames defines the list of mesh's names you want to load
  87968. * @param rootUrl defines the root url to use as a base to load your meshes and associated resources
  87969. * @param sceneFilename defines the filename of the scene to load from
  87970. */
  87971. function MeshAssetTask(
  87972. /**
  87973. * Defines the name of the task
  87974. */
  87975. name,
  87976. /**
  87977. * Defines the list of mesh's names you want to load
  87978. */
  87979. meshesNames,
  87980. /**
  87981. * Defines the root url to use as a base to load your meshes and associated resources
  87982. */
  87983. rootUrl,
  87984. /**
  87985. * Defines the filename of the scene to load from
  87986. */
  87987. sceneFilename) {
  87988. var _this = _super.call(this, name) || this;
  87989. _this.name = name;
  87990. _this.meshesNames = meshesNames;
  87991. _this.rootUrl = rootUrl;
  87992. _this.sceneFilename = sceneFilename;
  87993. return _this;
  87994. }
  87995. /**
  87996. * Execute the current task
  87997. * @param scene defines the scene where you want your assets to be loaded
  87998. * @param onSuccess is a callback called when the task is successfully executed
  87999. * @param onError is a callback called if an error occurs
  88000. */
  88001. MeshAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  88002. var _this = this;
  88003. BABYLON.SceneLoader.ImportMesh(this.meshesNames, this.rootUrl, this.sceneFilename, scene, function (meshes, particleSystems, skeletons) {
  88004. _this.loadedMeshes = meshes;
  88005. _this.loadedParticleSystems = particleSystems;
  88006. _this.loadedSkeletons = skeletons;
  88007. onSuccess();
  88008. }, null, function (scene, message, exception) {
  88009. onError(message, exception);
  88010. });
  88011. };
  88012. return MeshAssetTask;
  88013. }(AbstractAssetTask));
  88014. BABYLON.MeshAssetTask = MeshAssetTask;
  88015. /**
  88016. * Define a task used by {BABYLON.AssetsManager} to load text content
  88017. */
  88018. var TextFileAssetTask = /** @class */ (function (_super) {
  88019. __extends(TextFileAssetTask, _super);
  88020. /**
  88021. * Creates a new TextFileAssetTask object
  88022. * @param name defines the name of the task
  88023. * @param url defines the location of the file to load
  88024. */
  88025. function TextFileAssetTask(
  88026. /**
  88027. * Defines the name of the task
  88028. */
  88029. name,
  88030. /**
  88031. * Defines the location of the file to load
  88032. */
  88033. url) {
  88034. var _this = _super.call(this, name) || this;
  88035. _this.name = name;
  88036. _this.url = url;
  88037. return _this;
  88038. }
  88039. /**
  88040. * Execute the current task
  88041. * @param scene defines the scene where you want your assets to be loaded
  88042. * @param onSuccess is a callback called when the task is successfully executed
  88043. * @param onError is a callback called if an error occurs
  88044. */
  88045. TextFileAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  88046. var _this = this;
  88047. scene._loadFile(this.url, function (data) {
  88048. _this.text = data;
  88049. onSuccess();
  88050. }, undefined, false, false, function (request, exception) {
  88051. if (request) {
  88052. onError(request.status + " " + request.statusText, exception);
  88053. }
  88054. });
  88055. };
  88056. return TextFileAssetTask;
  88057. }(AbstractAssetTask));
  88058. BABYLON.TextFileAssetTask = TextFileAssetTask;
  88059. /**
  88060. * Define a task used by {BABYLON.AssetsManager} to load binary data
  88061. */
  88062. var BinaryFileAssetTask = /** @class */ (function (_super) {
  88063. __extends(BinaryFileAssetTask, _super);
  88064. /**
  88065. * Creates a new BinaryFileAssetTask object
  88066. * @param name defines the name of the new task
  88067. * @param url defines the location of the file to load
  88068. */
  88069. function BinaryFileAssetTask(
  88070. /**
  88071. * Defines the name of the task
  88072. */
  88073. name,
  88074. /**
  88075. * Defines the location of the file to load
  88076. */
  88077. url) {
  88078. var _this = _super.call(this, name) || this;
  88079. _this.name = name;
  88080. _this.url = url;
  88081. return _this;
  88082. }
  88083. /**
  88084. * Execute the current task
  88085. * @param scene defines the scene where you want your assets to be loaded
  88086. * @param onSuccess is a callback called when the task is successfully executed
  88087. * @param onError is a callback called if an error occurs
  88088. */
  88089. BinaryFileAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  88090. var _this = this;
  88091. scene._loadFile(this.url, function (data) {
  88092. _this.data = data;
  88093. onSuccess();
  88094. }, undefined, true, true, function (request, exception) {
  88095. if (request) {
  88096. onError(request.status + " " + request.statusText, exception);
  88097. }
  88098. });
  88099. };
  88100. return BinaryFileAssetTask;
  88101. }(AbstractAssetTask));
  88102. BABYLON.BinaryFileAssetTask = BinaryFileAssetTask;
  88103. /**
  88104. * Define a task used by {BABYLON.AssetsManager} to load images
  88105. */
  88106. var ImageAssetTask = /** @class */ (function (_super) {
  88107. __extends(ImageAssetTask, _super);
  88108. /**
  88109. * Creates a new ImageAssetTask
  88110. * @param name defines the name of the task
  88111. * @param url defines the location of the image to load
  88112. */
  88113. function ImageAssetTask(
  88114. /**
  88115. * Defines the name of the task
  88116. */
  88117. name,
  88118. /**
  88119. * Defines the location of the image to load
  88120. */
  88121. url) {
  88122. var _this = _super.call(this, name) || this;
  88123. _this.name = name;
  88124. _this.url = url;
  88125. return _this;
  88126. }
  88127. /**
  88128. * Execute the current task
  88129. * @param scene defines the scene where you want your assets to be loaded
  88130. * @param onSuccess is a callback called when the task is successfully executed
  88131. * @param onError is a callback called if an error occurs
  88132. */
  88133. ImageAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  88134. var _this = this;
  88135. var img = new Image();
  88136. BABYLON.Tools.SetCorsBehavior(this.url, img);
  88137. img.onload = function () {
  88138. _this.image = img;
  88139. onSuccess();
  88140. };
  88141. img.onerror = function (err) {
  88142. onError("Error loading image", err);
  88143. };
  88144. img.src = this.url;
  88145. };
  88146. return ImageAssetTask;
  88147. }(AbstractAssetTask));
  88148. BABYLON.ImageAssetTask = ImageAssetTask;
  88149. /**
  88150. * Define a task used by {BABYLON.AssetsManager} to load 2D textures
  88151. */
  88152. var TextureAssetTask = /** @class */ (function (_super) {
  88153. __extends(TextureAssetTask, _super);
  88154. /**
  88155. * Creates a new TextureAssetTask object
  88156. * @param name defines the name of the task
  88157. * @param url defines the location of the file to load
  88158. * @param noMipmap defines if mipmap should not be generated (default is false)
  88159. * @param invertY defines if texture must be inverted on Y axis (default is false)
  88160. * @param samplingMode defines the sampling mode to use (default is BABYLON.Texture.TRILINEAR_SAMPLINGMODE)
  88161. */
  88162. function TextureAssetTask(
  88163. /**
  88164. * Defines the name of the task
  88165. */
  88166. name,
  88167. /**
  88168. * Defines the location of the file to load
  88169. */
  88170. url,
  88171. /**
  88172. * Defines if mipmap should not be generated (default is false)
  88173. */
  88174. noMipmap,
  88175. /**
  88176. * Defines if texture must be inverted on Y axis (default is false)
  88177. */
  88178. invertY,
  88179. /**
  88180. * Defines the sampling mode to use (default is BABYLON.Texture.TRILINEAR_SAMPLINGMODE)
  88181. */
  88182. samplingMode) {
  88183. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  88184. var _this = _super.call(this, name) || this;
  88185. _this.name = name;
  88186. _this.url = url;
  88187. _this.noMipmap = noMipmap;
  88188. _this.invertY = invertY;
  88189. _this.samplingMode = samplingMode;
  88190. return _this;
  88191. }
  88192. /**
  88193. * Execute the current task
  88194. * @param scene defines the scene where you want your assets to be loaded
  88195. * @param onSuccess is a callback called when the task is successfully executed
  88196. * @param onError is a callback called if an error occurs
  88197. */
  88198. TextureAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  88199. var onload = function () {
  88200. onSuccess();
  88201. };
  88202. var onerror = function (message, exception) {
  88203. onError(message, exception);
  88204. };
  88205. this.texture = new BABYLON.Texture(this.url, scene, this.noMipmap, this.invertY, this.samplingMode, onload, onerror);
  88206. };
  88207. return TextureAssetTask;
  88208. }(AbstractAssetTask));
  88209. BABYLON.TextureAssetTask = TextureAssetTask;
  88210. /**
  88211. * Define a task used by {BABYLON.AssetsManager} to load cube textures
  88212. */
  88213. var CubeTextureAssetTask = /** @class */ (function (_super) {
  88214. __extends(CubeTextureAssetTask, _super);
  88215. /**
  88216. * Creates a new CubeTextureAssetTask
  88217. * @param name defines the name of the task
  88218. * @param url defines the location of the files to load (You have to specify the folder where the files are + filename with no extension)
  88219. * @param extensions defines the extensions to use to load files (["_px", "_py", "_pz", "_nx", "_ny", "_nz"] by default)
  88220. * @param noMipmap defines if mipmaps should not be generated (default is false)
  88221. * @param files defines the explicit list of files (undefined by default)
  88222. */
  88223. function CubeTextureAssetTask(
  88224. /**
  88225. * Defines the name of the task
  88226. */
  88227. name,
  88228. /**
  88229. * Defines the location of the files to load (You have to specify the folder where the files are + filename with no extension)
  88230. */
  88231. url,
  88232. /**
  88233. * Defines the extensions to use to load files (["_px", "_py", "_pz", "_nx", "_ny", "_nz"] by default)
  88234. */
  88235. extensions,
  88236. /**
  88237. * Defines if mipmaps should not be generated (default is false)
  88238. */
  88239. noMipmap,
  88240. /**
  88241. * Defines the explicit list of files (undefined by default)
  88242. */
  88243. files) {
  88244. var _this = _super.call(this, name) || this;
  88245. _this.name = name;
  88246. _this.url = url;
  88247. _this.extensions = extensions;
  88248. _this.noMipmap = noMipmap;
  88249. _this.files = files;
  88250. return _this;
  88251. }
  88252. /**
  88253. * Execute the current task
  88254. * @param scene defines the scene where you want your assets to be loaded
  88255. * @param onSuccess is a callback called when the task is successfully executed
  88256. * @param onError is a callback called if an error occurs
  88257. */
  88258. CubeTextureAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  88259. var onload = function () {
  88260. onSuccess();
  88261. };
  88262. var onerror = function (message, exception) {
  88263. onError(message, exception);
  88264. };
  88265. this.texture = new BABYLON.CubeTexture(this.url, scene, this.extensions, this.noMipmap, this.files, onload, onerror);
  88266. };
  88267. return CubeTextureAssetTask;
  88268. }(AbstractAssetTask));
  88269. BABYLON.CubeTextureAssetTask = CubeTextureAssetTask;
  88270. /**
  88271. * Define a task used by {BABYLON.AssetsManager} to load HDR cube textures
  88272. */
  88273. var HDRCubeTextureAssetTask = /** @class */ (function (_super) {
  88274. __extends(HDRCubeTextureAssetTask, _super);
  88275. /**
  88276. * Creates a new HDRCubeTextureAssetTask object
  88277. * @param name defines the name of the task
  88278. * @param url defines the location of the file to load
  88279. * @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.
  88280. * @param noMipmap defines if mipmaps should not be generated (default is false)
  88281. * @param generateHarmonics specifies whether you want to extract the polynomial harmonics during the generation process (default is true)
  88282. * @param useInGammaSpace 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)
  88283. * @param usePMREMGenerator specifies whether or not to generate the CubeMap through CubeMapGen to avoid seams issue at run time (default is false)
  88284. */
  88285. function HDRCubeTextureAssetTask(
  88286. /**
  88287. * Defines the name of the task
  88288. */
  88289. name,
  88290. /**
  88291. * Defines the location of the file to load
  88292. */
  88293. url,
  88294. /**
  88295. * 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.
  88296. */
  88297. size,
  88298. /**
  88299. * Defines if mipmaps should not be generated (default is false)
  88300. */
  88301. noMipmap,
  88302. /**
  88303. * Specifies whether you want to extract the polynomial harmonics during the generation process (default is true)
  88304. */
  88305. generateHarmonics,
  88306. /**
  88307. * 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)
  88308. */
  88309. useInGammaSpace,
  88310. /**
  88311. * Specifies whether or not to generate the CubeMap through CubeMapGen to avoid seams issue at run time (default is false)
  88312. */
  88313. usePMREMGenerator) {
  88314. if (noMipmap === void 0) { noMipmap = false; }
  88315. if (generateHarmonics === void 0) { generateHarmonics = true; }
  88316. if (useInGammaSpace === void 0) { useInGammaSpace = false; }
  88317. if (usePMREMGenerator === void 0) { usePMREMGenerator = false; }
  88318. var _this = _super.call(this, name) || this;
  88319. _this.name = name;
  88320. _this.url = url;
  88321. _this.size = size;
  88322. _this.noMipmap = noMipmap;
  88323. _this.generateHarmonics = generateHarmonics;
  88324. _this.useInGammaSpace = useInGammaSpace;
  88325. _this.usePMREMGenerator = usePMREMGenerator;
  88326. return _this;
  88327. }
  88328. /**
  88329. * Execute the current task
  88330. * @param scene defines the scene where you want your assets to be loaded
  88331. * @param onSuccess is a callback called when the task is successfully executed
  88332. * @param onError is a callback called if an error occurs
  88333. */
  88334. HDRCubeTextureAssetTask.prototype.run = function (scene, onSuccess, onError) {
  88335. var onload = function () {
  88336. onSuccess();
  88337. };
  88338. var onerror = function (message, exception) {
  88339. onError(message, exception);
  88340. };
  88341. this.texture = new BABYLON.HDRCubeTexture(this.url, scene, this.size, this.noMipmap, this.generateHarmonics, this.useInGammaSpace, this.usePMREMGenerator, onload, onerror);
  88342. };
  88343. return HDRCubeTextureAssetTask;
  88344. }(AbstractAssetTask));
  88345. BABYLON.HDRCubeTextureAssetTask = HDRCubeTextureAssetTask;
  88346. /**
  88347. * This class can be used to easily import assets into a scene
  88348. * @see http://doc.babylonjs.com/how_to/how_to_use_assetsmanager
  88349. */
  88350. var AssetsManager = /** @class */ (function () {
  88351. /**
  88352. * Creates a new AssetsManager
  88353. * @param scene defines the scene to work on
  88354. */
  88355. function AssetsManager(scene) {
  88356. this._isLoading = false;
  88357. this._tasks = new Array();
  88358. this._waitingTasksCount = 0;
  88359. this._totalTasksCount = 0;
  88360. /**
  88361. * Observable called when all tasks are processed
  88362. */
  88363. this.onTaskSuccessObservable = new BABYLON.Observable();
  88364. /**
  88365. * Observable called when a task had an error
  88366. */
  88367. this.onTaskErrorObservable = new BABYLON.Observable();
  88368. /**
  88369. * Observable called when a task is successful
  88370. */
  88371. this.onTasksDoneObservable = new BABYLON.Observable();
  88372. /**
  88373. * Observable called when a task is done (whatever the result is)
  88374. */
  88375. this.onProgressObservable = new BABYLON.Observable();
  88376. /**
  88377. * Gets or sets a boolean defining if the {BABYLON.AssetsManager} should use the default loading screen
  88378. * @see http://doc.babylonjs.com/how_to/creating_a_custom_loading_screen
  88379. */
  88380. this.useDefaultLoadingScreen = true;
  88381. this._scene = scene;
  88382. }
  88383. /**
  88384. * Add a {BABYLON.MeshAssetTask} to the list of active tasks
  88385. * @param taskName defines the name of the new task
  88386. * @param meshesNames defines the name of meshes to load
  88387. * @param rootUrl defines the root url to use to locate files
  88388. * @param sceneFilename defines the filename of the scene file
  88389. * @returns a new {BABYLON.MeshAssetTask} object
  88390. */
  88391. AssetsManager.prototype.addMeshTask = function (taskName, meshesNames, rootUrl, sceneFilename) {
  88392. var task = new MeshAssetTask(taskName, meshesNames, rootUrl, sceneFilename);
  88393. this._tasks.push(task);
  88394. return task;
  88395. };
  88396. /**
  88397. * Add a {BABYLON.TextFileAssetTask} to the list of active tasks
  88398. * @param taskName defines the name of the new task
  88399. * @param url defines the url of the file to load
  88400. * @returns a new {BABYLON.TextFileAssetTask} object
  88401. */
  88402. AssetsManager.prototype.addTextFileTask = function (taskName, url) {
  88403. var task = new TextFileAssetTask(taskName, url);
  88404. this._tasks.push(task);
  88405. return task;
  88406. };
  88407. /**
  88408. * Add a {BABYLON.BinaryFileAssetTask} to the list of active tasks
  88409. * @param taskName defines the name of the new task
  88410. * @param url defines the url of the file to load
  88411. * @returns a new {BABYLON.BinaryFileAssetTask} object
  88412. */
  88413. AssetsManager.prototype.addBinaryFileTask = function (taskName, url) {
  88414. var task = new BinaryFileAssetTask(taskName, url);
  88415. this._tasks.push(task);
  88416. return task;
  88417. };
  88418. /**
  88419. * Add a {BABYLON.ImageAssetTask} to the list of active tasks
  88420. * @param taskName defines the name of the new task
  88421. * @param url defines the url of the file to load
  88422. * @returns a new {BABYLON.ImageAssetTask} object
  88423. */
  88424. AssetsManager.prototype.addImageTask = function (taskName, url) {
  88425. var task = new ImageAssetTask(taskName, url);
  88426. this._tasks.push(task);
  88427. return task;
  88428. };
  88429. /**
  88430. * Add a {BABYLON.TextureAssetTask} to the list of active tasks
  88431. * @param taskName defines the name of the new task
  88432. * @param url defines the url of the file to load
  88433. * @param noMipmap defines if the texture must not receive mipmaps (false by default)
  88434. * @param invertY defines if you want to invert Y axis of the loaded texture (false by default)
  88435. * @param samplingMode defines the sampling mode to use (BABYLON.Texture.TRILINEAR_SAMPLINGMODE by default)
  88436. * @returns a new {BABYLON.TextureAssetTask} object
  88437. */
  88438. AssetsManager.prototype.addTextureTask = function (taskName, url, noMipmap, invertY, samplingMode) {
  88439. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  88440. var task = new TextureAssetTask(taskName, url, noMipmap, invertY, samplingMode);
  88441. this._tasks.push(task);
  88442. return task;
  88443. };
  88444. /**
  88445. * Add a {BABYLON.CubeTextureAssetTask} to the list of active tasks
  88446. * @param taskName defines the name of the new task
  88447. * @param url defines the url of the file to load
  88448. * @param extensions defines the extension to use to load the cube map (can be null)
  88449. * @param noMipmap defines if the texture must not receive mipmaps (false by default)
  88450. * @param files defines the list of files to load (can be null)
  88451. * @returns a new {BABYLON.CubeTextureAssetTask} object
  88452. */
  88453. AssetsManager.prototype.addCubeTextureTask = function (taskName, url, extensions, noMipmap, files) {
  88454. var task = new CubeTextureAssetTask(taskName, url, extensions, noMipmap, files);
  88455. this._tasks.push(task);
  88456. return task;
  88457. };
  88458. /**
  88459. *
  88460. * Add a {BABYLON.HDRCubeTextureAssetTask} to the list of active tasks
  88461. * @param taskName defines the name of the new task
  88462. * @param url defines the url of the file to load
  88463. * @param size defines the size you want for the cubemap (can be null)
  88464. * @param noMipmap defines if the texture must not receive mipmaps (false by default)
  88465. * @param generateHarmonics defines if you want to automatically generate (true by default)
  88466. * @param useInGammaSpace defines if the texture must be considered in gamma space (false by default)
  88467. * @param usePMREMGenerator is a reserved parameter and must be set to false or ignored
  88468. * @returns a new {BABYLON.HDRCubeTextureAssetTask} object
  88469. */
  88470. AssetsManager.prototype.addHDRCubeTextureTask = function (taskName, url, size, noMipmap, generateHarmonics, useInGammaSpace, usePMREMGenerator) {
  88471. if (noMipmap === void 0) { noMipmap = false; }
  88472. if (generateHarmonics === void 0) { generateHarmonics = true; }
  88473. if (useInGammaSpace === void 0) { useInGammaSpace = false; }
  88474. if (usePMREMGenerator === void 0) { usePMREMGenerator = false; }
  88475. var task = new HDRCubeTextureAssetTask(taskName, url, size, noMipmap, generateHarmonics, useInGammaSpace, usePMREMGenerator);
  88476. this._tasks.push(task);
  88477. return task;
  88478. };
  88479. AssetsManager.prototype._decreaseWaitingTasksCount = function (task) {
  88480. var _this = this;
  88481. this._waitingTasksCount--;
  88482. try {
  88483. if (task.taskState === AssetTaskState.DONE) {
  88484. // Let's remove successfull tasks
  88485. BABYLON.Tools.SetImmediate(function () {
  88486. var index = _this._tasks.indexOf(task);
  88487. if (index > -1) {
  88488. _this._tasks.splice(index, 1);
  88489. }
  88490. });
  88491. }
  88492. if (this.onProgress) {
  88493. this.onProgress(this._waitingTasksCount, this._totalTasksCount, task);
  88494. }
  88495. this.onProgressObservable.notifyObservers(new AssetsProgressEvent(this._waitingTasksCount, this._totalTasksCount, task));
  88496. }
  88497. catch (e) {
  88498. BABYLON.Tools.Error("Error running progress callbacks.");
  88499. console.log(e);
  88500. }
  88501. if (this._waitingTasksCount === 0) {
  88502. try {
  88503. if (this.onFinish) {
  88504. this.onFinish(this._tasks);
  88505. }
  88506. this.onTasksDoneObservable.notifyObservers(this._tasks);
  88507. }
  88508. catch (e) {
  88509. BABYLON.Tools.Error("Error running tasks-done callbacks.");
  88510. console.log(e);
  88511. }
  88512. this._isLoading = false;
  88513. this._scene.getEngine().hideLoadingUI();
  88514. }
  88515. };
  88516. AssetsManager.prototype._runTask = function (task) {
  88517. var _this = this;
  88518. var done = function () {
  88519. try {
  88520. if (_this.onTaskSuccess) {
  88521. _this.onTaskSuccess(task);
  88522. }
  88523. _this.onTaskSuccessObservable.notifyObservers(task);
  88524. _this._decreaseWaitingTasksCount(task);
  88525. }
  88526. catch (e) {
  88527. error("Error executing task success callbacks", e);
  88528. }
  88529. };
  88530. var error = function (message, exception) {
  88531. task._setErrorObject(message, exception);
  88532. if (_this.onTaskError) {
  88533. _this.onTaskError(task);
  88534. }
  88535. _this.onTaskErrorObservable.notifyObservers(task);
  88536. _this._decreaseWaitingTasksCount(task);
  88537. };
  88538. task.run(this._scene, done, error);
  88539. };
  88540. /**
  88541. * Reset the {BABYLON.AssetsManager} and remove all tasks
  88542. * @return the current instance of the {BABYLON.AssetsManager}
  88543. */
  88544. AssetsManager.prototype.reset = function () {
  88545. this._isLoading = false;
  88546. this._tasks = new Array();
  88547. return this;
  88548. };
  88549. /**
  88550. * Start the loading process
  88551. * @return the current instance of the {BABYLON.AssetsManager}
  88552. */
  88553. AssetsManager.prototype.load = function () {
  88554. if (this._isLoading) {
  88555. return this;
  88556. }
  88557. this._isLoading = true;
  88558. this._waitingTasksCount = this._tasks.length;
  88559. this._totalTasksCount = this._tasks.length;
  88560. if (this._waitingTasksCount === 0) {
  88561. this._isLoading = false;
  88562. if (this.onFinish) {
  88563. this.onFinish(this._tasks);
  88564. }
  88565. this.onTasksDoneObservable.notifyObservers(this._tasks);
  88566. return this;
  88567. }
  88568. if (this.useDefaultLoadingScreen) {
  88569. this._scene.getEngine().displayLoadingUI();
  88570. }
  88571. for (var index = 0; index < this._tasks.length; index++) {
  88572. var task = this._tasks[index];
  88573. this._runTask(task);
  88574. }
  88575. return this;
  88576. };
  88577. return AssetsManager;
  88578. }());
  88579. BABYLON.AssetsManager = AssetsManager;
  88580. })(BABYLON || (BABYLON = {}));
  88581. //# sourceMappingURL=babylon.assetsManager.js.map
  88582. "use strict";
  88583. var BABYLON;
  88584. (function (BABYLON) {
  88585. var serializedGeometries = [];
  88586. var serializeGeometry = function (geometry, serializationGeometries) {
  88587. if (serializedGeometries[geometry.id]) {
  88588. return;
  88589. }
  88590. if (geometry.doNotSerialize) {
  88591. return;
  88592. }
  88593. if (geometry instanceof BABYLON.BoxGeometry) {
  88594. serializationGeometries.boxes.push(geometry.serialize());
  88595. }
  88596. else if (geometry instanceof BABYLON.SphereGeometry) {
  88597. serializationGeometries.spheres.push(geometry.serialize());
  88598. }
  88599. else if (geometry instanceof BABYLON.CylinderGeometry) {
  88600. serializationGeometries.cylinders.push(geometry.serialize());
  88601. }
  88602. else if (geometry instanceof BABYLON.TorusGeometry) {
  88603. serializationGeometries.toruses.push(geometry.serialize());
  88604. }
  88605. else if (geometry instanceof BABYLON.GroundGeometry) {
  88606. serializationGeometries.grounds.push(geometry.serialize());
  88607. }
  88608. else if (geometry instanceof BABYLON.Plane) {
  88609. serializationGeometries.planes.push(geometry.serialize());
  88610. }
  88611. else if (geometry instanceof BABYLON.TorusKnotGeometry) {
  88612. serializationGeometries.torusKnots.push(geometry.serialize());
  88613. }
  88614. else if (geometry instanceof BABYLON._PrimitiveGeometry) {
  88615. throw new Error("Unknown primitive type");
  88616. }
  88617. else {
  88618. serializationGeometries.vertexData.push(geometry.serializeVerticeData());
  88619. }
  88620. serializedGeometries[geometry.id] = true;
  88621. };
  88622. var serializeMesh = function (mesh, serializationScene) {
  88623. var serializationObject = {};
  88624. // Geometry
  88625. var geometry = mesh._geometry;
  88626. if (geometry) {
  88627. if (!mesh.getScene().getGeometryByID(geometry.id)) {
  88628. // 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
  88629. serializeGeometry(geometry, serializationScene.geometries);
  88630. }
  88631. }
  88632. // Custom
  88633. if (mesh.serialize) {
  88634. mesh.serialize(serializationObject);
  88635. }
  88636. return serializationObject;
  88637. };
  88638. var finalizeSingleMesh = function (mesh, serializationObject) {
  88639. //only works if the mesh is already loaded
  88640. if (mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE) {
  88641. //serialize material
  88642. if (mesh.material) {
  88643. if (mesh.material instanceof BABYLON.StandardMaterial) {
  88644. serializationObject.materials = serializationObject.materials || [];
  88645. if (!serializationObject.materials.some(function (mat) { return (mat.id === mesh.material.id); })) {
  88646. serializationObject.materials.push(mesh.material.serialize());
  88647. }
  88648. }
  88649. else if (mesh.material instanceof BABYLON.MultiMaterial) {
  88650. serializationObject.multiMaterials = serializationObject.multiMaterials || [];
  88651. if (!serializationObject.multiMaterials.some(function (mat) { return (mat.id === mesh.material.id); })) {
  88652. serializationObject.multiMaterials.push(mesh.material.serialize());
  88653. }
  88654. }
  88655. }
  88656. //serialize geometry
  88657. var geometry = mesh._geometry;
  88658. if (geometry) {
  88659. if (!serializationObject.geometries) {
  88660. serializationObject.geometries = {};
  88661. serializationObject.geometries.boxes = [];
  88662. serializationObject.geometries.spheres = [];
  88663. serializationObject.geometries.cylinders = [];
  88664. serializationObject.geometries.toruses = [];
  88665. serializationObject.geometries.grounds = [];
  88666. serializationObject.geometries.planes = [];
  88667. serializationObject.geometries.torusKnots = [];
  88668. serializationObject.geometries.vertexData = [];
  88669. }
  88670. serializeGeometry(geometry, serializationObject.geometries);
  88671. }
  88672. // Skeletons
  88673. if (mesh.skeleton) {
  88674. serializationObject.skeletons = serializationObject.skeletons || [];
  88675. serializationObject.skeletons.push(mesh.skeleton.serialize());
  88676. }
  88677. //serialize the actual mesh
  88678. serializationObject.meshes = serializationObject.meshes || [];
  88679. serializationObject.meshes.push(serializeMesh(mesh, serializationObject));
  88680. }
  88681. };
  88682. var SceneSerializer = /** @class */ (function () {
  88683. function SceneSerializer() {
  88684. }
  88685. SceneSerializer.ClearCache = function () {
  88686. serializedGeometries = [];
  88687. };
  88688. SceneSerializer.Serialize = function (scene) {
  88689. var serializationObject = {};
  88690. SceneSerializer.ClearCache();
  88691. // Scene
  88692. serializationObject.useDelayedTextureLoading = scene.useDelayedTextureLoading;
  88693. serializationObject.autoClear = scene.autoClear;
  88694. serializationObject.clearColor = scene.clearColor.asArray();
  88695. serializationObject.ambientColor = scene.ambientColor.asArray();
  88696. serializationObject.gravity = scene.gravity.asArray();
  88697. serializationObject.collisionsEnabled = scene.collisionsEnabled;
  88698. serializationObject.workerCollisions = scene.workerCollisions;
  88699. // Fog
  88700. if (scene.fogMode && scene.fogMode !== 0) {
  88701. serializationObject.fogMode = scene.fogMode;
  88702. serializationObject.fogColor = scene.fogColor.asArray();
  88703. serializationObject.fogStart = scene.fogStart;
  88704. serializationObject.fogEnd = scene.fogEnd;
  88705. serializationObject.fogDensity = scene.fogDensity;
  88706. }
  88707. //Physics
  88708. if (scene.isPhysicsEnabled()) {
  88709. var physicEngine = scene.getPhysicsEngine();
  88710. if (physicEngine) {
  88711. serializationObject.physicsEnabled = true;
  88712. serializationObject.physicsGravity = physicEngine.gravity.asArray();
  88713. serializationObject.physicsEngine = physicEngine.getPhysicsPluginName();
  88714. }
  88715. }
  88716. // Metadata
  88717. if (scene.metadata) {
  88718. serializationObject.metadata = scene.metadata;
  88719. }
  88720. // Morph targets
  88721. serializationObject.morphTargetManagers = [];
  88722. for (var _i = 0, _a = scene.meshes; _i < _a.length; _i++) {
  88723. var abstractMesh = _a[_i];
  88724. var manager = abstractMesh.morphTargetManager;
  88725. if (manager) {
  88726. serializationObject.morphTargetManagers.push(manager.serialize());
  88727. }
  88728. }
  88729. // Lights
  88730. serializationObject.lights = [];
  88731. var index;
  88732. var light;
  88733. for (index = 0; index < scene.lights.length; index++) {
  88734. light = scene.lights[index];
  88735. if (!light.doNotSerialize) {
  88736. serializationObject.lights.push(light.serialize());
  88737. }
  88738. }
  88739. // Cameras
  88740. serializationObject.cameras = [];
  88741. for (index = 0; index < scene.cameras.length; index++) {
  88742. var camera = scene.cameras[index];
  88743. if (!camera.doNotSerialize) {
  88744. serializationObject.cameras.push(camera.serialize());
  88745. }
  88746. }
  88747. if (scene.activeCamera) {
  88748. serializationObject.activeCameraID = scene.activeCamera.id;
  88749. }
  88750. // Animations
  88751. BABYLON.Animation.AppendSerializedAnimations(scene, serializationObject);
  88752. // Materials
  88753. serializationObject.materials = [];
  88754. serializationObject.multiMaterials = [];
  88755. var material;
  88756. for (index = 0; index < scene.materials.length; index++) {
  88757. material = scene.materials[index];
  88758. if (!material.doNotSerialize) {
  88759. serializationObject.materials.push(material.serialize());
  88760. }
  88761. }
  88762. // MultiMaterials
  88763. serializationObject.multiMaterials = [];
  88764. for (index = 0; index < scene.multiMaterials.length; index++) {
  88765. var multiMaterial = scene.multiMaterials[index];
  88766. serializationObject.multiMaterials.push(multiMaterial.serialize());
  88767. }
  88768. // Environment texture
  88769. if (scene.environmentTexture) {
  88770. serializationObject.environmentTexture = scene.environmentTexture.name;
  88771. }
  88772. // Skeletons
  88773. serializationObject.skeletons = [];
  88774. for (index = 0; index < scene.skeletons.length; index++) {
  88775. var skeleton = scene.skeletons[index];
  88776. if (!skeleton.doNotSerialize) {
  88777. serializationObject.skeletons.push(skeleton.serialize());
  88778. }
  88779. }
  88780. // Transform nodes
  88781. serializationObject.transformNodes = [];
  88782. for (index = 0; index < scene.transformNodes.length; index++) {
  88783. serializationObject.transformNodes.push(scene.transformNodes[index].serialize());
  88784. }
  88785. // Geometries
  88786. serializationObject.geometries = {};
  88787. serializationObject.geometries.boxes = [];
  88788. serializationObject.geometries.spheres = [];
  88789. serializationObject.geometries.cylinders = [];
  88790. serializationObject.geometries.toruses = [];
  88791. serializationObject.geometries.grounds = [];
  88792. serializationObject.geometries.planes = [];
  88793. serializationObject.geometries.torusKnots = [];
  88794. serializationObject.geometries.vertexData = [];
  88795. serializedGeometries = [];
  88796. var geometries = scene.getGeometries();
  88797. for (index = 0; index < geometries.length; index++) {
  88798. var geometry = geometries[index];
  88799. if (geometry.isReady()) {
  88800. serializeGeometry(geometry, serializationObject.geometries);
  88801. }
  88802. }
  88803. // Meshes
  88804. serializationObject.meshes = [];
  88805. for (index = 0; index < scene.meshes.length; index++) {
  88806. var abstractMesh = scene.meshes[index];
  88807. if (abstractMesh instanceof BABYLON.Mesh) {
  88808. var mesh = abstractMesh;
  88809. if (!mesh.doNotSerialize) {
  88810. if (mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE) {
  88811. serializationObject.meshes.push(serializeMesh(mesh, serializationObject));
  88812. }
  88813. }
  88814. }
  88815. }
  88816. // Particles Systems
  88817. serializationObject.particleSystems = [];
  88818. for (index = 0; index < scene.particleSystems.length; index++) {
  88819. serializationObject.particleSystems.push(scene.particleSystems[index].serialize());
  88820. }
  88821. // Lens flares
  88822. serializationObject.lensFlareSystems = [];
  88823. for (index = 0; index < scene.lensFlareSystems.length; index++) {
  88824. serializationObject.lensFlareSystems.push(scene.lensFlareSystems[index].serialize());
  88825. }
  88826. // Shadows
  88827. serializationObject.shadowGenerators = [];
  88828. for (index = 0; index < scene.lights.length; index++) {
  88829. light = scene.lights[index];
  88830. var shadowGenerator = light.getShadowGenerator();
  88831. if (shadowGenerator) {
  88832. serializationObject.shadowGenerators.push(shadowGenerator.serialize());
  88833. }
  88834. }
  88835. // Action Manager
  88836. if (scene.actionManager) {
  88837. serializationObject.actions = scene.actionManager.serialize("scene");
  88838. }
  88839. // Audio
  88840. serializationObject.sounds = [];
  88841. for (index = 0; index < scene.soundTracks.length; index++) {
  88842. var soundtrack = scene.soundTracks[index];
  88843. for (var soundId = 0; soundId < soundtrack.soundCollection.length; soundId++) {
  88844. serializationObject.sounds.push(soundtrack.soundCollection[soundId].serialize());
  88845. }
  88846. }
  88847. return serializationObject;
  88848. };
  88849. SceneSerializer.SerializeMesh = function (toSerialize /* Mesh || Mesh[] */, withParents, withChildren) {
  88850. if (withParents === void 0) { withParents = false; }
  88851. if (withChildren === void 0) { withChildren = false; }
  88852. var serializationObject = {};
  88853. SceneSerializer.ClearCache();
  88854. toSerialize = (toSerialize instanceof Array) ? toSerialize : [toSerialize];
  88855. if (withParents || withChildren) {
  88856. //deliberate for loop! not for each, appended should be processed as well.
  88857. for (var i = 0; i < toSerialize.length; ++i) {
  88858. if (withChildren) {
  88859. toSerialize[i].getDescendants().forEach(function (node) {
  88860. if (node instanceof BABYLON.Mesh && (toSerialize.indexOf(node) < 0)) {
  88861. toSerialize.push(node);
  88862. }
  88863. });
  88864. }
  88865. //make sure the array doesn't contain the object already
  88866. if (withParents && toSerialize[i].parent && (toSerialize.indexOf(toSerialize[i].parent) < 0)) {
  88867. toSerialize.push(toSerialize[i].parent);
  88868. }
  88869. }
  88870. }
  88871. toSerialize.forEach(function (mesh) {
  88872. finalizeSingleMesh(mesh, serializationObject);
  88873. });
  88874. return serializationObject;
  88875. };
  88876. return SceneSerializer;
  88877. }());
  88878. BABYLON.SceneSerializer = SceneSerializer;
  88879. })(BABYLON || (BABYLON = {}));
  88880. //# sourceMappingURL=babylon.sceneSerializer.js.map
  88881. "use strict";
  88882. var BABYLON;
  88883. (function (BABYLON) {
  88884. var ReflectionProbe = /** @class */ (function () {
  88885. function ReflectionProbe(name, size, scene, generateMipMaps) {
  88886. if (generateMipMaps === void 0) { generateMipMaps = true; }
  88887. var _this = this;
  88888. this.name = name;
  88889. this._viewMatrix = BABYLON.Matrix.Identity();
  88890. this._target = BABYLON.Vector3.Zero();
  88891. this._add = BABYLON.Vector3.Zero();
  88892. this._invertYAxis = false;
  88893. this.position = BABYLON.Vector3.Zero();
  88894. this._scene = scene;
  88895. this._scene.reflectionProbes.push(this);
  88896. this._renderTargetTexture = new BABYLON.RenderTargetTexture(name, size, scene, generateMipMaps, true, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT, true);
  88897. this._renderTargetTexture.onBeforeRenderObservable.add(function (faceIndex) {
  88898. switch (faceIndex) {
  88899. case 0:
  88900. _this._add.copyFromFloats(1, 0, 0);
  88901. break;
  88902. case 1:
  88903. _this._add.copyFromFloats(-1, 0, 0);
  88904. break;
  88905. case 2:
  88906. _this._add.copyFromFloats(0, _this._invertYAxis ? 1 : -1, 0);
  88907. break;
  88908. case 3:
  88909. _this._add.copyFromFloats(0, _this._invertYAxis ? -1 : 1, 0);
  88910. break;
  88911. case 4:
  88912. _this._add.copyFromFloats(0, 0, 1);
  88913. break;
  88914. case 5:
  88915. _this._add.copyFromFloats(0, 0, -1);
  88916. break;
  88917. }
  88918. if (_this._attachedMesh) {
  88919. _this.position.copyFrom(_this._attachedMesh.getAbsolutePosition());
  88920. }
  88921. _this.position.addToRef(_this._add, _this._target);
  88922. BABYLON.Matrix.LookAtLHToRef(_this.position, _this._target, BABYLON.Vector3.Up(), _this._viewMatrix);
  88923. scene.setTransformMatrix(_this._viewMatrix, _this._projectionMatrix);
  88924. scene._forcedViewPosition = _this.position;
  88925. });
  88926. this._renderTargetTexture.onAfterUnbindObservable.add(function () {
  88927. scene._forcedViewPosition = null;
  88928. scene.updateTransformMatrix(true);
  88929. });
  88930. if (scene.activeCamera) {
  88931. this._projectionMatrix = BABYLON.Matrix.PerspectiveFovLH(Math.PI / 2, 1, scene.activeCamera.minZ, scene.activeCamera.maxZ);
  88932. }
  88933. }
  88934. Object.defineProperty(ReflectionProbe.prototype, "samples", {
  88935. get: function () {
  88936. return this._renderTargetTexture.samples;
  88937. },
  88938. set: function (value) {
  88939. this._renderTargetTexture.samples = value;
  88940. },
  88941. enumerable: true,
  88942. configurable: true
  88943. });
  88944. Object.defineProperty(ReflectionProbe.prototype, "refreshRate", {
  88945. get: function () {
  88946. return this._renderTargetTexture.refreshRate;
  88947. },
  88948. set: function (value) {
  88949. this._renderTargetTexture.refreshRate = value;
  88950. },
  88951. enumerable: true,
  88952. configurable: true
  88953. });
  88954. ReflectionProbe.prototype.getScene = function () {
  88955. return this._scene;
  88956. };
  88957. Object.defineProperty(ReflectionProbe.prototype, "cubeTexture", {
  88958. get: function () {
  88959. return this._renderTargetTexture;
  88960. },
  88961. enumerable: true,
  88962. configurable: true
  88963. });
  88964. Object.defineProperty(ReflectionProbe.prototype, "renderList", {
  88965. get: function () {
  88966. return this._renderTargetTexture.renderList;
  88967. },
  88968. enumerable: true,
  88969. configurable: true
  88970. });
  88971. ReflectionProbe.prototype.attachToMesh = function (mesh) {
  88972. this._attachedMesh = mesh;
  88973. };
  88974. /**
  88975. * Specifies whether or not the stencil and depth buffer are cleared between two rendering groups.
  88976. *
  88977. * @param renderingGroupId The rendering group id corresponding to its index
  88978. * @param autoClearDepthStencil Automatically clears depth and stencil between groups if true.
  88979. */
  88980. ReflectionProbe.prototype.setRenderingAutoClearDepthStencil = function (renderingGroupId, autoClearDepthStencil) {
  88981. this._renderTargetTexture.setRenderingAutoClearDepthStencil(renderingGroupId, autoClearDepthStencil);
  88982. };
  88983. ReflectionProbe.prototype.dispose = function () {
  88984. var index = this._scene.reflectionProbes.indexOf(this);
  88985. if (index !== -1) {
  88986. // Remove from the scene if found
  88987. this._scene.reflectionProbes.splice(index, 1);
  88988. }
  88989. if (this._renderTargetTexture) {
  88990. this._renderTargetTexture.dispose();
  88991. this._renderTargetTexture = null;
  88992. }
  88993. };
  88994. return ReflectionProbe;
  88995. }());
  88996. BABYLON.ReflectionProbe = ReflectionProbe;
  88997. })(BABYLON || (BABYLON = {}));
  88998. //# sourceMappingURL=babylon.reflectionProbe.js.map
  88999. "use strict";
  89000. var BABYLON;
  89001. (function (BABYLON) {
  89002. var Layer = /** @class */ (function () {
  89003. function Layer(name, imgUrl, scene, isBackground, color) {
  89004. this.name = name;
  89005. this.scale = new BABYLON.Vector2(1, 1);
  89006. this.offset = new BABYLON.Vector2(0, 0);
  89007. this.alphaBlendingMode = BABYLON.Engine.ALPHA_COMBINE;
  89008. this.layerMask = 0x0FFFFFFF;
  89009. this._vertexBuffers = {};
  89010. // Events
  89011. /**
  89012. * An event triggered when the layer is disposed.
  89013. */
  89014. this.onDisposeObservable = new BABYLON.Observable();
  89015. /**
  89016. * An event triggered before rendering the scene
  89017. */
  89018. this.onBeforeRenderObservable = new BABYLON.Observable();
  89019. /**
  89020. * An event triggered after rendering the scene
  89021. */
  89022. this.onAfterRenderObservable = new BABYLON.Observable();
  89023. this.texture = imgUrl ? new BABYLON.Texture(imgUrl, scene, true) : null;
  89024. this.isBackground = isBackground === undefined ? true : isBackground;
  89025. this.color = color === undefined ? new BABYLON.Color4(1, 1, 1, 1) : color;
  89026. this._scene = (scene || BABYLON.Engine.LastCreatedScene);
  89027. this._scene.layers.push(this);
  89028. var engine = this._scene.getEngine();
  89029. // VBO
  89030. var vertices = [];
  89031. vertices.push(1, 1);
  89032. vertices.push(-1, 1);
  89033. vertices.push(-1, -1);
  89034. vertices.push(1, -1);
  89035. var vertexBuffer = new BABYLON.VertexBuffer(engine, vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  89036. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = vertexBuffer;
  89037. this._createIndexBuffer();
  89038. // Effects
  89039. this._effect = engine.createEffect("layer", [BABYLON.VertexBuffer.PositionKind], ["textureMatrix", "color", "scale", "offset"], ["textureSampler"], "");
  89040. this._alphaTestEffect = engine.createEffect("layer", [BABYLON.VertexBuffer.PositionKind], ["textureMatrix", "color", "scale", "offset"], ["textureSampler"], "#define ALPHATEST");
  89041. }
  89042. Object.defineProperty(Layer.prototype, "onDispose", {
  89043. set: function (callback) {
  89044. if (this._onDisposeObserver) {
  89045. this.onDisposeObservable.remove(this._onDisposeObserver);
  89046. }
  89047. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  89048. },
  89049. enumerable: true,
  89050. configurable: true
  89051. });
  89052. Object.defineProperty(Layer.prototype, "onBeforeRender", {
  89053. set: function (callback) {
  89054. if (this._onBeforeRenderObserver) {
  89055. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  89056. }
  89057. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  89058. },
  89059. enumerable: true,
  89060. configurable: true
  89061. });
  89062. Object.defineProperty(Layer.prototype, "onAfterRender", {
  89063. set: function (callback) {
  89064. if (this._onAfterRenderObserver) {
  89065. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  89066. }
  89067. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  89068. },
  89069. enumerable: true,
  89070. configurable: true
  89071. });
  89072. Layer.prototype._createIndexBuffer = function () {
  89073. var engine = this._scene.getEngine();
  89074. // Indices
  89075. var indices = [];
  89076. indices.push(0);
  89077. indices.push(1);
  89078. indices.push(2);
  89079. indices.push(0);
  89080. indices.push(2);
  89081. indices.push(3);
  89082. this._indexBuffer = engine.createIndexBuffer(indices);
  89083. };
  89084. Layer.prototype._rebuild = function () {
  89085. var vb = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  89086. if (vb) {
  89087. vb._rebuild();
  89088. }
  89089. this._createIndexBuffer();
  89090. };
  89091. Layer.prototype.render = function () {
  89092. var currentEffect = this.alphaTest ? this._alphaTestEffect : this._effect;
  89093. // Check
  89094. if (!currentEffect.isReady() || !this.texture || !this.texture.isReady())
  89095. return;
  89096. var engine = this._scene.getEngine();
  89097. this.onBeforeRenderObservable.notifyObservers(this);
  89098. // Render
  89099. engine.enableEffect(currentEffect);
  89100. engine.setState(false);
  89101. // Texture
  89102. currentEffect.setTexture("textureSampler", this.texture);
  89103. currentEffect.setMatrix("textureMatrix", this.texture.getTextureMatrix());
  89104. // Color
  89105. currentEffect.setFloat4("color", this.color.r, this.color.g, this.color.b, this.color.a);
  89106. // Scale / offset
  89107. currentEffect.setVector2("offset", this.offset);
  89108. currentEffect.setVector2("scale", this.scale);
  89109. // VBOs
  89110. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, currentEffect);
  89111. // Draw order
  89112. if (!this.alphaTest) {
  89113. engine.setAlphaMode(this.alphaBlendingMode);
  89114. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  89115. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  89116. }
  89117. else {
  89118. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  89119. }
  89120. this.onAfterRenderObservable.notifyObservers(this);
  89121. };
  89122. Layer.prototype.dispose = function () {
  89123. var vertexBuffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  89124. if (vertexBuffer) {
  89125. vertexBuffer.dispose();
  89126. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  89127. }
  89128. if (this._indexBuffer) {
  89129. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  89130. this._indexBuffer = null;
  89131. }
  89132. if (this.texture) {
  89133. this.texture.dispose();
  89134. this.texture = null;
  89135. }
  89136. // Remove from scene
  89137. var index = this._scene.layers.indexOf(this);
  89138. this._scene.layers.splice(index, 1);
  89139. // Callback
  89140. this.onDisposeObservable.notifyObservers(this);
  89141. this.onDisposeObservable.clear();
  89142. this.onAfterRenderObservable.clear();
  89143. this.onBeforeRenderObservable.clear();
  89144. };
  89145. return Layer;
  89146. }());
  89147. BABYLON.Layer = Layer;
  89148. })(BABYLON || (BABYLON = {}));
  89149. //# sourceMappingURL=babylon.layer.js.map
  89150. "use strict";
  89151. var BABYLON;
  89152. (function (BABYLON) {
  89153. var TextureTools = /** @class */ (function () {
  89154. function TextureTools() {
  89155. }
  89156. /**
  89157. * Uses the GPU to create a copy texture rescaled at a given size
  89158. * @param texture Texture to copy from
  89159. * @param width Desired width
  89160. * @param height Desired height
  89161. * @return Generated texture
  89162. */
  89163. TextureTools.CreateResizedCopy = function (texture, width, height, useBilinearMode) {
  89164. if (useBilinearMode === void 0) { useBilinearMode = true; }
  89165. var scene = texture.getScene();
  89166. var engine = scene.getEngine();
  89167. var rtt = new BABYLON.RenderTargetTexture('resized' + texture.name, { width: width, height: height }, scene, !texture.noMipmap, true, texture._texture.type, false, texture._samplingMode, false);
  89168. rtt.wrapU = texture.wrapU;
  89169. rtt.wrapV = texture.wrapV;
  89170. rtt.uOffset = texture.uOffset;
  89171. rtt.vOffset = texture.vOffset;
  89172. rtt.uScale = texture.uScale;
  89173. rtt.vScale = texture.vScale;
  89174. rtt.uAng = texture.uAng;
  89175. rtt.vAng = texture.vAng;
  89176. rtt.wAng = texture.wAng;
  89177. rtt.coordinatesIndex = texture.coordinatesIndex;
  89178. rtt.level = texture.level;
  89179. rtt.anisotropicFilteringLevel = texture.anisotropicFilteringLevel;
  89180. rtt._texture.isReady = false;
  89181. texture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  89182. texture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  89183. var passPostProcess = new BABYLON.PassPostProcess("pass", 1, null, useBilinearMode ? BABYLON.Texture.BILINEAR_SAMPLINGMODE : BABYLON.Texture.NEAREST_SAMPLINGMODE, engine, false, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  89184. passPostProcess.getEffect().executeWhenCompiled(function () {
  89185. passPostProcess.onApply = function (effect) {
  89186. effect.setTexture("textureSampler", texture);
  89187. };
  89188. var internalTexture = rtt.getInternalTexture();
  89189. if (internalTexture) {
  89190. scene.postProcessManager.directRender([passPostProcess], internalTexture);
  89191. engine.unBindFramebuffer(internalTexture);
  89192. rtt.disposeFramebufferObjects();
  89193. passPostProcess.dispose();
  89194. internalTexture.isReady = true;
  89195. }
  89196. });
  89197. return rtt;
  89198. };
  89199. TextureTools.GetEnvironmentBRDFTexture = function (scene) {
  89200. if (!scene._environmentBRDFTexture) {
  89201. var texture = BABYLON.Texture.CreateFromBase64String(this._environmentBRDFBase64Texture, "EnvironmentBRDFTexture", scene, true, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  89202. texture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  89203. texture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  89204. scene._environmentBRDFTexture = texture;
  89205. }
  89206. return scene._environmentBRDFTexture;
  89207. };
  89208. 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=";
  89209. return TextureTools;
  89210. }());
  89211. BABYLON.TextureTools = TextureTools;
  89212. })(BABYLON || (BABYLON = {}));
  89213. //# sourceMappingURL=babylon.textureTools.js.map
  89214. "use strict";
  89215. var BABYLON;
  89216. (function (BABYLON) {
  89217. var FramingBehavior = /** @class */ (function () {
  89218. function FramingBehavior() {
  89219. this._mode = FramingBehavior.FitFrustumSidesMode;
  89220. this._radiusScale = 1.0;
  89221. this._positionScale = 0.5;
  89222. this._defaultElevation = 0.3;
  89223. this._elevationReturnTime = 1500;
  89224. this._elevationReturnWaitTime = 1000;
  89225. this._zoomStopsAnimation = false;
  89226. this._framingTime = 1500;
  89227. this._isPointerDown = false;
  89228. this._lastInteractionTime = -Infinity;
  89229. // Framing control
  89230. this._animatables = new Array();
  89231. this._betaIsAnimating = false;
  89232. }
  89233. Object.defineProperty(FramingBehavior.prototype, "name", {
  89234. get: function () {
  89235. return "Framing";
  89236. },
  89237. enumerable: true,
  89238. configurable: true
  89239. });
  89240. Object.defineProperty(FramingBehavior.prototype, "mode", {
  89241. /**
  89242. * Gets current mode used by the behavior.
  89243. */
  89244. get: function () {
  89245. return this._mode;
  89246. },
  89247. /**
  89248. * Sets the current mode used by the behavior
  89249. */
  89250. set: function (mode) {
  89251. this._mode = mode;
  89252. },
  89253. enumerable: true,
  89254. configurable: true
  89255. });
  89256. Object.defineProperty(FramingBehavior.prototype, "radiusScale", {
  89257. /**
  89258. * Gets the scale applied to the radius
  89259. */
  89260. get: function () {
  89261. return this._radiusScale;
  89262. },
  89263. /**
  89264. * Sets the scale applied to the radius (1 by default)
  89265. */
  89266. set: function (radius) {
  89267. this._radiusScale = radius;
  89268. },
  89269. enumerable: true,
  89270. configurable: true
  89271. });
  89272. Object.defineProperty(FramingBehavior.prototype, "positionScale", {
  89273. /**
  89274. * Gets the scale to apply on Y axis to position camera focus. 0.5 by default which means the center of the bounding box.
  89275. */
  89276. get: function () {
  89277. return this._positionScale;
  89278. },
  89279. /**
  89280. * Sets the scale to apply on Y axis to position camera focus. 0.5 by default which means the center of the bounding box.
  89281. */
  89282. set: function (scale) {
  89283. this._positionScale = scale;
  89284. },
  89285. enumerable: true,
  89286. configurable: true
  89287. });
  89288. Object.defineProperty(FramingBehavior.prototype, "defaultElevation", {
  89289. /**
  89290. * Gets the angle above/below the horizontal plane to return to when the return to default elevation idle
  89291. * behaviour is triggered, in radians.
  89292. */
  89293. get: function () {
  89294. return this._defaultElevation;
  89295. },
  89296. /**
  89297. * Sets the angle above/below the horizontal plane to return to when the return to default elevation idle
  89298. * behaviour is triggered, in radians.
  89299. */
  89300. set: function (elevation) {
  89301. this._defaultElevation = elevation;
  89302. },
  89303. enumerable: true,
  89304. configurable: true
  89305. });
  89306. Object.defineProperty(FramingBehavior.prototype, "elevationReturnTime", {
  89307. /**
  89308. * Gets the time (in milliseconds) taken to return to the default beta position.
  89309. * Negative value indicates camera should not return to default.
  89310. */
  89311. get: function () {
  89312. return this._elevationReturnTime;
  89313. },
  89314. /**
  89315. * Sets the time (in milliseconds) taken to return to the default beta position.
  89316. * Negative value indicates camera should not return to default.
  89317. */
  89318. set: function (speed) {
  89319. this._elevationReturnTime = speed;
  89320. },
  89321. enumerable: true,
  89322. configurable: true
  89323. });
  89324. Object.defineProperty(FramingBehavior.prototype, "elevationReturnWaitTime", {
  89325. /**
  89326. * Gets the delay (in milliseconds) taken before the camera returns to the default beta position.
  89327. */
  89328. get: function () {
  89329. return this._elevationReturnWaitTime;
  89330. },
  89331. /**
  89332. * Sets the delay (in milliseconds) taken before the camera returns to the default beta position.
  89333. */
  89334. set: function (time) {
  89335. this._elevationReturnWaitTime = time;
  89336. },
  89337. enumerable: true,
  89338. configurable: true
  89339. });
  89340. Object.defineProperty(FramingBehavior.prototype, "zoomStopsAnimation", {
  89341. /**
  89342. * Gets the flag that indicates if user zooming should stop animation.
  89343. */
  89344. get: function () {
  89345. return this._zoomStopsAnimation;
  89346. },
  89347. /**
  89348. * Sets the flag that indicates if user zooming should stop animation.
  89349. */
  89350. set: function (flag) {
  89351. this._zoomStopsAnimation = flag;
  89352. },
  89353. enumerable: true,
  89354. configurable: true
  89355. });
  89356. Object.defineProperty(FramingBehavior.prototype, "framingTime", {
  89357. /**
  89358. * Gets the transition time when framing the mesh, in milliseconds
  89359. */
  89360. get: function () {
  89361. return this._framingTime;
  89362. },
  89363. /**
  89364. * Sets the transition time when framing the mesh, in milliseconds
  89365. */
  89366. set: function (time) {
  89367. this._framingTime = time;
  89368. },
  89369. enumerable: true,
  89370. configurable: true
  89371. });
  89372. FramingBehavior.prototype.init = function () {
  89373. // Do notihng
  89374. };
  89375. FramingBehavior.prototype.attach = function (camera) {
  89376. var _this = this;
  89377. this._attachedCamera = camera;
  89378. var scene = this._attachedCamera.getScene();
  89379. FramingBehavior.EasingFunction.setEasingMode(FramingBehavior.EasingMode);
  89380. this._onPrePointerObservableObserver = scene.onPrePointerObservable.add(function (pointerInfoPre) {
  89381. if (pointerInfoPre.type === BABYLON.PointerEventTypes.POINTERDOWN) {
  89382. _this._isPointerDown = true;
  89383. return;
  89384. }
  89385. if (pointerInfoPre.type === BABYLON.PointerEventTypes.POINTERUP) {
  89386. _this._isPointerDown = false;
  89387. }
  89388. });
  89389. this._onMeshTargetChangedObserver = camera.onMeshTargetChangedObservable.add(function (mesh) {
  89390. if (mesh) {
  89391. _this.zoomOnMesh(mesh);
  89392. }
  89393. });
  89394. this._onAfterCheckInputsObserver = camera.onAfterCheckInputsObservable.add(function () {
  89395. // Stop the animation if there is user interaction and the animation should stop for this interaction
  89396. _this._applyUserInteraction();
  89397. // Maintain the camera above the ground. If the user pulls the camera beneath the ground plane, lift it
  89398. // back to the default position after a given timeout
  89399. _this._maintainCameraAboveGround();
  89400. });
  89401. };
  89402. FramingBehavior.prototype.detach = function () {
  89403. if (!this._attachedCamera) {
  89404. return;
  89405. }
  89406. var scene = this._attachedCamera.getScene();
  89407. if (this._onPrePointerObservableObserver) {
  89408. scene.onPrePointerObservable.remove(this._onPrePointerObservableObserver);
  89409. }
  89410. if (this._onAfterCheckInputsObserver) {
  89411. this._attachedCamera.onAfterCheckInputsObservable.remove(this._onAfterCheckInputsObserver);
  89412. }
  89413. if (this._onMeshTargetChangedObserver) {
  89414. this._attachedCamera.onMeshTargetChangedObservable.remove(this._onMeshTargetChangedObserver);
  89415. }
  89416. this._attachedCamera = null;
  89417. };
  89418. /**
  89419. * Targets the given mesh and updates zoom level accordingly.
  89420. * @param mesh The mesh to target.
  89421. * @param radius Optional. If a cached radius position already exists, overrides default.
  89422. * @param framingPositionY Position on mesh to center camera focus where 0 corresponds bottom of its bounding box and 1, the top
  89423. * @param focusOnOriginXZ Determines if the camera should focus on 0 in the X and Z axis instead of the mesh
  89424. * @param onAnimationEnd Callback triggered at the end of the framing animation
  89425. */
  89426. FramingBehavior.prototype.zoomOnMesh = function (mesh, focusOnOriginXZ, onAnimationEnd) {
  89427. if (focusOnOriginXZ === void 0) { focusOnOriginXZ = false; }
  89428. if (onAnimationEnd === void 0) { onAnimationEnd = null; }
  89429. mesh.computeWorldMatrix(true);
  89430. var boundingBox = mesh.getBoundingInfo().boundingBox;
  89431. this.zoomOnBoundingInfo(boundingBox.minimumWorld, boundingBox.maximumWorld, focusOnOriginXZ, onAnimationEnd);
  89432. };
  89433. /**
  89434. * Targets the given mesh with its children and updates zoom level accordingly.
  89435. * @param mesh The mesh to target.
  89436. * @param radius Optional. If a cached radius position already exists, overrides default.
  89437. * @param framingPositionY Position on mesh to center camera focus where 0 corresponds bottom of its bounding box and 1, the top
  89438. * @param focusOnOriginXZ Determines if the camera should focus on 0 in the X and Z axis instead of the mesh
  89439. * @param onAnimationEnd Callback triggered at the end of the framing animation
  89440. */
  89441. FramingBehavior.prototype.zoomOnMeshHierarchy = function (mesh, focusOnOriginXZ, onAnimationEnd) {
  89442. if (focusOnOriginXZ === void 0) { focusOnOriginXZ = false; }
  89443. if (onAnimationEnd === void 0) { onAnimationEnd = null; }
  89444. mesh.computeWorldMatrix(true);
  89445. var boundingBox = mesh.getHierarchyBoundingVectors(true);
  89446. this.zoomOnBoundingInfo(boundingBox.min, boundingBox.max, focusOnOriginXZ, onAnimationEnd);
  89447. };
  89448. /**
  89449. * Targets the given meshes with their children and updates zoom level accordingly.
  89450. * @param meshes The mesh to target.
  89451. * @param radius Optional. If a cached radius position already exists, overrides default.
  89452. * @param framingPositionY Position on mesh to center camera focus where 0 corresponds bottom of its bounding box and 1, the top
  89453. * @param focusOnOriginXZ Determines if the camera should focus on 0 in the X and Z axis instead of the mesh
  89454. * @param onAnimationEnd Callback triggered at the end of the framing animation
  89455. */
  89456. FramingBehavior.prototype.zoomOnMeshesHierarchy = function (meshes, focusOnOriginXZ, onAnimationEnd) {
  89457. if (focusOnOriginXZ === void 0) { focusOnOriginXZ = false; }
  89458. if (onAnimationEnd === void 0) { onAnimationEnd = null; }
  89459. var min = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  89460. var max = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  89461. for (var i = 0; i < meshes.length; i++) {
  89462. var boundingInfo = meshes[i].getHierarchyBoundingVectors(true);
  89463. BABYLON.Tools.CheckExtends(boundingInfo.min, min, max);
  89464. BABYLON.Tools.CheckExtends(boundingInfo.max, min, max);
  89465. }
  89466. this.zoomOnBoundingInfo(min, max, focusOnOriginXZ, onAnimationEnd);
  89467. };
  89468. /**
  89469. * Targets the given mesh and updates zoom level accordingly.
  89470. * @param mesh The mesh to target.
  89471. * @param radius Optional. If a cached radius position already exists, overrides default.
  89472. * @param framingPositionY Position on mesh to center camera focus where 0 corresponds bottom of its bounding box and 1, the top
  89473. * @param focusOnOriginXZ Determines if the camera should focus on 0 in the X and Z axis instead of the mesh
  89474. * @param onAnimationEnd Callback triggered at the end of the framing animation
  89475. */
  89476. FramingBehavior.prototype.zoomOnBoundingInfo = function (minimumWorld, maximumWorld, focusOnOriginXZ, onAnimationEnd) {
  89477. var _this = this;
  89478. if (focusOnOriginXZ === void 0) { focusOnOriginXZ = false; }
  89479. if (onAnimationEnd === void 0) { onAnimationEnd = null; }
  89480. var zoomTarget;
  89481. if (!this._attachedCamera) {
  89482. return;
  89483. }
  89484. // Find target by interpolating from bottom of bounding box in world-space to top via framingPositionY
  89485. var bottom = minimumWorld.y;
  89486. var top = maximumWorld.y;
  89487. var zoomTargetY = bottom + (top - bottom) * this._positionScale;
  89488. var radiusWorld = maximumWorld.subtract(minimumWorld).scale(0.5);
  89489. if (focusOnOriginXZ) {
  89490. zoomTarget = new BABYLON.Vector3(0, zoomTargetY, 0);
  89491. }
  89492. else {
  89493. var centerWorld = minimumWorld.add(radiusWorld);
  89494. zoomTarget = new BABYLON.Vector3(centerWorld.x, zoomTargetY, centerWorld.z);
  89495. }
  89496. if (!this._vectorTransition) {
  89497. this._vectorTransition = BABYLON.Animation.CreateAnimation("target", BABYLON.Animation.ANIMATIONTYPE_VECTOR3, 60, FramingBehavior.EasingFunction);
  89498. }
  89499. this._betaIsAnimating = true;
  89500. var animatable = BABYLON.Animation.TransitionTo("target", zoomTarget, this._attachedCamera, this._attachedCamera.getScene(), 60, this._vectorTransition, this._framingTime);
  89501. if (animatable) {
  89502. this._animatables.push(animatable);
  89503. }
  89504. // sets the radius and lower radius bounds
  89505. // Small delta ensures camera is not always at lower zoom limit.
  89506. var radius = 0;
  89507. if (this._mode === FramingBehavior.FitFrustumSidesMode) {
  89508. var position = this._calculateLowerRadiusFromModelBoundingSphere(minimumWorld, maximumWorld);
  89509. this._attachedCamera.lowerRadiusLimit = radiusWorld.length() + this._attachedCamera.minZ;
  89510. radius = position;
  89511. }
  89512. else if (this._mode === FramingBehavior.IgnoreBoundsSizeMode) {
  89513. radius = this._calculateLowerRadiusFromModelBoundingSphere(minimumWorld, maximumWorld);
  89514. if (this._attachedCamera.lowerRadiusLimit === null) {
  89515. this._attachedCamera.lowerRadiusLimit = this._attachedCamera.minZ;
  89516. }
  89517. }
  89518. // Set sensibilities
  89519. var extend = maximumWorld.subtract(minimumWorld).length();
  89520. this._attachedCamera.panningSensibility = 5000 / extend;
  89521. this._attachedCamera.wheelPrecision = 100 / radius;
  89522. // transition to new radius
  89523. if (!this._radiusTransition) {
  89524. this._radiusTransition = BABYLON.Animation.CreateAnimation("radius", BABYLON.Animation.ANIMATIONTYPE_FLOAT, 60, FramingBehavior.EasingFunction);
  89525. }
  89526. animatable = BABYLON.Animation.TransitionTo("radius", radius, this._attachedCamera, this._attachedCamera.getScene(), 60, this._radiusTransition, this._framingTime, function () {
  89527. _this.stopAllAnimations();
  89528. if (onAnimationEnd) {
  89529. onAnimationEnd();
  89530. }
  89531. if (_this._attachedCamera) {
  89532. _this._attachedCamera.storeState();
  89533. }
  89534. });
  89535. if (animatable) {
  89536. this._animatables.push(animatable);
  89537. }
  89538. };
  89539. /**
  89540. * Calculates the lowest radius for the camera based on the bounding box of the mesh.
  89541. * @param mesh The mesh on which to base the calculation. mesh boundingInfo used to estimate necessary
  89542. * frustum width.
  89543. * @return The minimum distance from the primary mesh's center point at which the camera must be kept in order
  89544. * to fully enclose the mesh in the viewing frustum.
  89545. */
  89546. FramingBehavior.prototype._calculateLowerRadiusFromModelBoundingSphere = function (minimumWorld, maximumWorld) {
  89547. var size = maximumWorld.subtract(minimumWorld);
  89548. var boxVectorGlobalDiagonal = size.length();
  89549. var frustumSlope = this._getFrustumSlope();
  89550. // Formula for setting distance
  89551. // (Good explanation: http://stackoverflow.com/questions/2866350/move-camera-to-fit-3d-scene)
  89552. var radiusWithoutFraming = boxVectorGlobalDiagonal * 0.5;
  89553. // Horizon distance
  89554. var radius = radiusWithoutFraming * this._radiusScale;
  89555. var distanceForHorizontalFrustum = radius * Math.sqrt(1.0 + 1.0 / (frustumSlope.x * frustumSlope.x));
  89556. var distanceForVerticalFrustum = radius * Math.sqrt(1.0 + 1.0 / (frustumSlope.y * frustumSlope.y));
  89557. var distance = Math.max(distanceForHorizontalFrustum, distanceForVerticalFrustum);
  89558. var camera = this._attachedCamera;
  89559. if (!camera) {
  89560. return 0;
  89561. }
  89562. if (camera.lowerRadiusLimit && this._mode === FramingBehavior.IgnoreBoundsSizeMode) {
  89563. // Don't exceed the requested limit
  89564. distance = distance < camera.lowerRadiusLimit ? camera.lowerRadiusLimit : distance;
  89565. }
  89566. // Don't exceed the upper radius limit
  89567. if (camera.upperRadiusLimit) {
  89568. distance = distance > camera.upperRadiusLimit ? camera.upperRadiusLimit : distance;
  89569. }
  89570. return distance;
  89571. };
  89572. /**
  89573. * Keeps the camera above the ground plane. If the user pulls the camera below the ground plane, the camera
  89574. * is automatically returned to its default position (expected to be above ground plane).
  89575. */
  89576. FramingBehavior.prototype._maintainCameraAboveGround = function () {
  89577. var _this = this;
  89578. if (this._elevationReturnTime < 0) {
  89579. return;
  89580. }
  89581. var timeSinceInteraction = BABYLON.Tools.Now - this._lastInteractionTime;
  89582. var defaultBeta = Math.PI * 0.5 - this._defaultElevation;
  89583. var limitBeta = Math.PI * 0.5;
  89584. // Bring the camera back up if below the ground plane
  89585. if (this._attachedCamera && !this._betaIsAnimating && this._attachedCamera.beta > limitBeta && timeSinceInteraction >= this._elevationReturnWaitTime) {
  89586. this._betaIsAnimating = true;
  89587. //Transition to new position
  89588. this.stopAllAnimations();
  89589. if (!this._betaTransition) {
  89590. this._betaTransition = BABYLON.Animation.CreateAnimation("beta", BABYLON.Animation.ANIMATIONTYPE_FLOAT, 60, FramingBehavior.EasingFunction);
  89591. }
  89592. var animatabe = BABYLON.Animation.TransitionTo("beta", defaultBeta, this._attachedCamera, this._attachedCamera.getScene(), 60, this._betaTransition, this._elevationReturnTime, function () {
  89593. _this._clearAnimationLocks();
  89594. _this.stopAllAnimations();
  89595. });
  89596. if (animatabe) {
  89597. this._animatables.push(animatabe);
  89598. }
  89599. }
  89600. };
  89601. /**
  89602. * Returns the frustum slope based on the canvas ratio and camera FOV
  89603. * @returns The frustum slope represented as a Vector2 with X and Y slopes
  89604. */
  89605. FramingBehavior.prototype._getFrustumSlope = function () {
  89606. // Calculate the viewport ratio
  89607. // Aspect Ratio is Height/Width.
  89608. var camera = this._attachedCamera;
  89609. if (!camera) {
  89610. return BABYLON.Vector2.Zero();
  89611. }
  89612. var engine = camera.getScene().getEngine();
  89613. var aspectRatio = engine.getAspectRatio(camera);
  89614. // Camera FOV is the vertical field of view (top-bottom) in radians.
  89615. // Slope of the frustum top/bottom planes in view space, relative to the forward vector.
  89616. var frustumSlopeY = Math.tan(camera.fov / 2);
  89617. // Slope of the frustum left/right planes in view space, relative to the forward vector.
  89618. // Provides the amount that one side (e.g. left) of the frustum gets wider for every unit
  89619. // along the forward vector.
  89620. var frustumSlopeX = frustumSlopeY * aspectRatio;
  89621. return new BABYLON.Vector2(frustumSlopeX, frustumSlopeY);
  89622. };
  89623. /**
  89624. * Removes all animation locks. Allows new animations to be added to any of the arcCamera properties.
  89625. */
  89626. FramingBehavior.prototype._clearAnimationLocks = function () {
  89627. this._betaIsAnimating = false;
  89628. };
  89629. /**
  89630. * Applies any current user interaction to the camera. Takes into account maximum alpha rotation.
  89631. */
  89632. FramingBehavior.prototype._applyUserInteraction = function () {
  89633. if (this.isUserIsMoving) {
  89634. this._lastInteractionTime = BABYLON.Tools.Now;
  89635. this.stopAllAnimations();
  89636. this._clearAnimationLocks();
  89637. }
  89638. };
  89639. /**
  89640. * Stops and removes all animations that have been applied to the camera
  89641. */
  89642. FramingBehavior.prototype.stopAllAnimations = function () {
  89643. if (this._attachedCamera) {
  89644. this._attachedCamera.animations = [];
  89645. }
  89646. while (this._animatables.length) {
  89647. if (this._animatables[0]) {
  89648. this._animatables[0].onAnimationEnd = null;
  89649. this._animatables[0].stop();
  89650. }
  89651. this._animatables.shift();
  89652. }
  89653. };
  89654. Object.defineProperty(FramingBehavior.prototype, "isUserIsMoving", {
  89655. /**
  89656. * Gets a value indicating if the user is moving the camera
  89657. */
  89658. get: function () {
  89659. if (!this._attachedCamera) {
  89660. return false;
  89661. }
  89662. return this._attachedCamera.inertialAlphaOffset !== 0 ||
  89663. this._attachedCamera.inertialBetaOffset !== 0 ||
  89664. this._attachedCamera.inertialRadiusOffset !== 0 ||
  89665. this._attachedCamera.inertialPanningX !== 0 ||
  89666. this._attachedCamera.inertialPanningY !== 0 ||
  89667. this._isPointerDown;
  89668. },
  89669. enumerable: true,
  89670. configurable: true
  89671. });
  89672. /**
  89673. * The easing function used by animations
  89674. */
  89675. FramingBehavior.EasingFunction = new BABYLON.ExponentialEase();
  89676. /**
  89677. * The easing mode used by animations
  89678. */
  89679. FramingBehavior.EasingMode = BABYLON.EasingFunction.EASINGMODE_EASEINOUT;
  89680. // Statics
  89681. /**
  89682. * The camera can move all the way towards the mesh.
  89683. */
  89684. FramingBehavior.IgnoreBoundsSizeMode = 0;
  89685. /**
  89686. * The camera is not allowed to zoom closer to the mesh than the point at which the adjusted bounding sphere touches the frustum sides
  89687. */
  89688. FramingBehavior.FitFrustumSidesMode = 1;
  89689. return FramingBehavior;
  89690. }());
  89691. BABYLON.FramingBehavior = FramingBehavior;
  89692. })(BABYLON || (BABYLON = {}));
  89693. //# sourceMappingURL=babylon.framingBehavior.js.map
  89694. "use strict";
  89695. var BABYLON;
  89696. (function (BABYLON) {
  89697. /**
  89698. * Add a bouncing effect to an ArcRotateCamera when reaching a specified minimum and maximum radius
  89699. */
  89700. var BouncingBehavior = /** @class */ (function () {
  89701. function BouncingBehavior() {
  89702. /**
  89703. * The duration of the animation, in milliseconds
  89704. */
  89705. this.transitionDuration = 450;
  89706. /**
  89707. * Length of the distance animated by the transition when lower radius is reached
  89708. */
  89709. this.lowerRadiusTransitionRange = 2;
  89710. /**
  89711. * Length of the distance animated by the transition when upper radius is reached
  89712. */
  89713. this.upperRadiusTransitionRange = -2;
  89714. this._autoTransitionRange = false;
  89715. // Animations
  89716. this._radiusIsAnimating = false;
  89717. this._radiusBounceTransition = null;
  89718. this._animatables = new Array();
  89719. }
  89720. Object.defineProperty(BouncingBehavior.prototype, "name", {
  89721. get: function () {
  89722. return "Bouncing";
  89723. },
  89724. enumerable: true,
  89725. configurable: true
  89726. });
  89727. Object.defineProperty(BouncingBehavior.prototype, "autoTransitionRange", {
  89728. /**
  89729. * Gets a value indicating if the lowerRadiusTransitionRange and upperRadiusTransitionRange are defined automatically
  89730. */
  89731. get: function () {
  89732. return this._autoTransitionRange;
  89733. },
  89734. /**
  89735. * Sets a value indicating if the lowerRadiusTransitionRange and upperRadiusTransitionRange are defined automatically
  89736. * Transition ranges will be set to 5% of the bounding box diagonal in world space
  89737. */
  89738. set: function (value) {
  89739. var _this = this;
  89740. if (this._autoTransitionRange === value) {
  89741. return;
  89742. }
  89743. this._autoTransitionRange = value;
  89744. var camera = this._attachedCamera;
  89745. if (!camera) {
  89746. return;
  89747. }
  89748. if (value) {
  89749. this._onMeshTargetChangedObserver = camera.onMeshTargetChangedObservable.add(function (mesh) {
  89750. if (!mesh) {
  89751. return;
  89752. }
  89753. mesh.computeWorldMatrix(true);
  89754. var diagonal = mesh.getBoundingInfo().diagonalLength;
  89755. _this.lowerRadiusTransitionRange = diagonal * 0.05;
  89756. _this.upperRadiusTransitionRange = diagonal * 0.05;
  89757. });
  89758. }
  89759. else if (this._onMeshTargetChangedObserver) {
  89760. camera.onMeshTargetChangedObservable.remove(this._onMeshTargetChangedObserver);
  89761. }
  89762. },
  89763. enumerable: true,
  89764. configurable: true
  89765. });
  89766. BouncingBehavior.prototype.init = function () {
  89767. // Do notihng
  89768. };
  89769. BouncingBehavior.prototype.attach = function (camera) {
  89770. var _this = this;
  89771. this._attachedCamera = camera;
  89772. this._onAfterCheckInputsObserver = camera.onAfterCheckInputsObservable.add(function () {
  89773. if (!_this._attachedCamera) {
  89774. return;
  89775. }
  89776. // Add the bounce animation to the lower radius limit
  89777. if (_this._isRadiusAtLimit(_this._attachedCamera.lowerRadiusLimit)) {
  89778. _this._applyBoundRadiusAnimation(_this.lowerRadiusTransitionRange);
  89779. }
  89780. // Add the bounce animation to the upper radius limit
  89781. if (_this._isRadiusAtLimit(_this._attachedCamera.upperRadiusLimit)) {
  89782. _this._applyBoundRadiusAnimation(_this.upperRadiusTransitionRange);
  89783. }
  89784. });
  89785. };
  89786. BouncingBehavior.prototype.detach = function () {
  89787. if (!this._attachedCamera) {
  89788. return;
  89789. }
  89790. if (this._onAfterCheckInputsObserver) {
  89791. this._attachedCamera.onAfterCheckInputsObservable.remove(this._onAfterCheckInputsObserver);
  89792. }
  89793. if (this._onMeshTargetChangedObserver) {
  89794. this._attachedCamera.onMeshTargetChangedObservable.remove(this._onMeshTargetChangedObserver);
  89795. }
  89796. this._attachedCamera = null;
  89797. };
  89798. /**
  89799. * Checks if the camera radius is at the specified limit. Takes into account animation locks.
  89800. * @param radiusLimit The limit to check against.
  89801. * @return Bool to indicate if at limit.
  89802. */
  89803. BouncingBehavior.prototype._isRadiusAtLimit = function (radiusLimit) {
  89804. if (!this._attachedCamera) {
  89805. return false;
  89806. }
  89807. if (this._attachedCamera.radius === radiusLimit && !this._radiusIsAnimating) {
  89808. return true;
  89809. }
  89810. return false;
  89811. };
  89812. /**
  89813. * Applies an animation to the radius of the camera, extending by the radiusDelta.
  89814. * @param radiusDelta The delta by which to animate to. Can be negative.
  89815. */
  89816. BouncingBehavior.prototype._applyBoundRadiusAnimation = function (radiusDelta) {
  89817. var _this = this;
  89818. if (!this._attachedCamera) {
  89819. return;
  89820. }
  89821. if (!this._radiusBounceTransition) {
  89822. BouncingBehavior.EasingFunction.setEasingMode(BouncingBehavior.EasingMode);
  89823. this._radiusBounceTransition = BABYLON.Animation.CreateAnimation("radius", BABYLON.Animation.ANIMATIONTYPE_FLOAT, 60, BouncingBehavior.EasingFunction);
  89824. }
  89825. // Prevent zoom until bounce has completed
  89826. this._cachedWheelPrecision = this._attachedCamera.wheelPrecision;
  89827. this._attachedCamera.wheelPrecision = Infinity;
  89828. this._attachedCamera.inertialRadiusOffset = 0;
  89829. // Animate to the radius limit
  89830. this.stopAllAnimations();
  89831. this._radiusIsAnimating = true;
  89832. var animatable = BABYLON.Animation.TransitionTo("radius", this._attachedCamera.radius + radiusDelta, this._attachedCamera, this._attachedCamera.getScene(), 60, this._radiusBounceTransition, this.transitionDuration, function () { return _this._clearAnimationLocks(); });
  89833. if (animatable) {
  89834. this._animatables.push(animatable);
  89835. }
  89836. };
  89837. /**
  89838. * Removes all animation locks. Allows new animations to be added to any of the camera properties.
  89839. */
  89840. BouncingBehavior.prototype._clearAnimationLocks = function () {
  89841. this._radiusIsAnimating = false;
  89842. if (this._attachedCamera) {
  89843. this._attachedCamera.wheelPrecision = this._cachedWheelPrecision;
  89844. }
  89845. };
  89846. /**
  89847. * Stops and removes all animations that have been applied to the camera
  89848. */
  89849. BouncingBehavior.prototype.stopAllAnimations = function () {
  89850. if (this._attachedCamera) {
  89851. this._attachedCamera.animations = [];
  89852. }
  89853. while (this._animatables.length) {
  89854. this._animatables[0].onAnimationEnd = null;
  89855. this._animatables[0].stop();
  89856. this._animatables.shift();
  89857. }
  89858. };
  89859. /**
  89860. * The easing function used by animations
  89861. */
  89862. BouncingBehavior.EasingFunction = new BABYLON.BackEase(0.3);
  89863. /**
  89864. * The easing mode used by animations
  89865. */
  89866. BouncingBehavior.EasingMode = BABYLON.EasingFunction.EASINGMODE_EASEOUT;
  89867. return BouncingBehavior;
  89868. }());
  89869. BABYLON.BouncingBehavior = BouncingBehavior;
  89870. })(BABYLON || (BABYLON = {}));
  89871. //# sourceMappingURL=babylon.bouncingBehavior.js.map
  89872. "use strict";
  89873. var BABYLON;
  89874. (function (BABYLON) {
  89875. var AutoRotationBehavior = /** @class */ (function () {
  89876. function AutoRotationBehavior() {
  89877. this._zoomStopsAnimation = false;
  89878. this._idleRotationSpeed = 0.05;
  89879. this._idleRotationWaitTime = 2000;
  89880. this._idleRotationSpinupTime = 2000;
  89881. this._isPointerDown = false;
  89882. this._lastFrameTime = null;
  89883. this._lastInteractionTime = -Infinity;
  89884. this._cameraRotationSpeed = 0;
  89885. this._lastFrameRadius = 0;
  89886. }
  89887. Object.defineProperty(AutoRotationBehavior.prototype, "name", {
  89888. get: function () {
  89889. return "AutoRotation";
  89890. },
  89891. enumerable: true,
  89892. configurable: true
  89893. });
  89894. Object.defineProperty(AutoRotationBehavior.prototype, "zoomStopsAnimation", {
  89895. /**
  89896. * Gets the flag that indicates if user zooming should stop animation.
  89897. */
  89898. get: function () {
  89899. return this._zoomStopsAnimation;
  89900. },
  89901. /**
  89902. * Sets the flag that indicates if user zooming should stop animation.
  89903. */
  89904. set: function (flag) {
  89905. this._zoomStopsAnimation = flag;
  89906. },
  89907. enumerable: true,
  89908. configurable: true
  89909. });
  89910. Object.defineProperty(AutoRotationBehavior.prototype, "idleRotationSpeed", {
  89911. /**
  89912. * Gets the default speed at which the camera rotates around the model.
  89913. */
  89914. get: function () {
  89915. return this._idleRotationSpeed;
  89916. },
  89917. /**
  89918. * Sets the default speed at which the camera rotates around the model.
  89919. */
  89920. set: function (speed) {
  89921. this._idleRotationSpeed = speed;
  89922. },
  89923. enumerable: true,
  89924. configurable: true
  89925. });
  89926. Object.defineProperty(AutoRotationBehavior.prototype, "idleRotationWaitTime", {
  89927. /**
  89928. * Gets the time (milliseconds) to wait after user interaction before the camera starts rotating.
  89929. */
  89930. get: function () {
  89931. return this._idleRotationWaitTime;
  89932. },
  89933. /**
  89934. * Sets the time (in milliseconds) to wait after user interaction before the camera starts rotating.
  89935. */
  89936. set: function (time) {
  89937. this._idleRotationWaitTime = time;
  89938. },
  89939. enumerable: true,
  89940. configurable: true
  89941. });
  89942. Object.defineProperty(AutoRotationBehavior.prototype, "idleRotationSpinupTime", {
  89943. /**
  89944. * Gets the time (milliseconds) to take to spin up to the full idle rotation speed.
  89945. */
  89946. get: function () {
  89947. return this._idleRotationSpinupTime;
  89948. },
  89949. /**
  89950. * Sets the time (milliseconds) to take to spin up to the full idle rotation speed.
  89951. */
  89952. set: function (time) {
  89953. this._idleRotationSpinupTime = time;
  89954. },
  89955. enumerable: true,
  89956. configurable: true
  89957. });
  89958. Object.defineProperty(AutoRotationBehavior.prototype, "rotationInProgress", {
  89959. /**
  89960. * Gets a value indicating if the camera is currently rotating because of this behavior
  89961. */
  89962. get: function () {
  89963. return Math.abs(this._cameraRotationSpeed) > 0;
  89964. },
  89965. enumerable: true,
  89966. configurable: true
  89967. });
  89968. AutoRotationBehavior.prototype.init = function () {
  89969. // Do notihng
  89970. };
  89971. AutoRotationBehavior.prototype.attach = function (camera) {
  89972. var _this = this;
  89973. this._attachedCamera = camera;
  89974. var scene = this._attachedCamera.getScene();
  89975. this._onPrePointerObservableObserver = scene.onPrePointerObservable.add(function (pointerInfoPre) {
  89976. if (pointerInfoPre.type === BABYLON.PointerEventTypes.POINTERDOWN) {
  89977. _this._isPointerDown = true;
  89978. return;
  89979. }
  89980. if (pointerInfoPre.type === BABYLON.PointerEventTypes.POINTERUP) {
  89981. _this._isPointerDown = false;
  89982. }
  89983. });
  89984. this._onAfterCheckInputsObserver = camera.onAfterCheckInputsObservable.add(function () {
  89985. var now = BABYLON.Tools.Now;
  89986. var dt = 0;
  89987. if (_this._lastFrameTime != null) {
  89988. dt = now - _this._lastFrameTime;
  89989. }
  89990. _this._lastFrameTime = now;
  89991. // Stop the animation if there is user interaction and the animation should stop for this interaction
  89992. _this._applyUserInteraction();
  89993. var timeToRotation = now - _this._lastInteractionTime - _this._idleRotationWaitTime;
  89994. var scale = Math.max(Math.min(timeToRotation / (_this._idleRotationSpinupTime), 1), 0);
  89995. _this._cameraRotationSpeed = _this._idleRotationSpeed * scale;
  89996. // Step camera rotation by rotation speed
  89997. if (_this._attachedCamera) {
  89998. _this._attachedCamera.alpha -= _this._cameraRotationSpeed * (dt / 1000);
  89999. }
  90000. });
  90001. };
  90002. AutoRotationBehavior.prototype.detach = function () {
  90003. if (!this._attachedCamera) {
  90004. return;
  90005. }
  90006. var scene = this._attachedCamera.getScene();
  90007. if (this._onPrePointerObservableObserver) {
  90008. scene.onPrePointerObservable.remove(this._onPrePointerObservableObserver);
  90009. }
  90010. this._attachedCamera.onAfterCheckInputsObservable.remove(this._onAfterCheckInputsObserver);
  90011. this._attachedCamera = null;
  90012. };
  90013. /**
  90014. * Returns true if user is scrolling.
  90015. * @return true if user is scrolling.
  90016. */
  90017. AutoRotationBehavior.prototype._userIsZooming = function () {
  90018. if (!this._attachedCamera) {
  90019. return false;
  90020. }
  90021. return this._attachedCamera.inertialRadiusOffset !== 0;
  90022. };
  90023. AutoRotationBehavior.prototype._shouldAnimationStopForInteraction = function () {
  90024. if (!this._attachedCamera) {
  90025. return false;
  90026. }
  90027. var zoomHasHitLimit = false;
  90028. if (this._lastFrameRadius === this._attachedCamera.radius && this._attachedCamera.inertialRadiusOffset !== 0) {
  90029. zoomHasHitLimit = true;
  90030. }
  90031. // Update the record of previous radius - works as an approx. indicator of hitting radius limits
  90032. this._lastFrameRadius = this._attachedCamera.radius;
  90033. return this._zoomStopsAnimation ? zoomHasHitLimit : this._userIsZooming();
  90034. };
  90035. /**
  90036. * Applies any current user interaction to the camera. Takes into account maximum alpha rotation.
  90037. */
  90038. AutoRotationBehavior.prototype._applyUserInteraction = function () {
  90039. if (this._userIsMoving() && !this._shouldAnimationStopForInteraction()) {
  90040. this._lastInteractionTime = BABYLON.Tools.Now;
  90041. }
  90042. };
  90043. // Tools
  90044. AutoRotationBehavior.prototype._userIsMoving = function () {
  90045. if (!this._attachedCamera) {
  90046. return false;
  90047. }
  90048. return this._attachedCamera.inertialAlphaOffset !== 0 ||
  90049. this._attachedCamera.inertialBetaOffset !== 0 ||
  90050. this._attachedCamera.inertialRadiusOffset !== 0 ||
  90051. this._attachedCamera.inertialPanningX !== 0 ||
  90052. this._attachedCamera.inertialPanningY !== 0 ||
  90053. this._isPointerDown;
  90054. };
  90055. return AutoRotationBehavior;
  90056. }());
  90057. BABYLON.AutoRotationBehavior = AutoRotationBehavior;
  90058. })(BABYLON || (BABYLON = {}));
  90059. //# sourceMappingURL=babylon.autoRotationBehavior.js.map
  90060. "use strict";
  90061. var BABYLON;
  90062. (function (BABYLON) {
  90063. var NullEngineOptions = /** @class */ (function () {
  90064. function NullEngineOptions() {
  90065. this.renderWidth = 512;
  90066. this.renderHeight = 256;
  90067. this.textureSize = 512;
  90068. this.deterministicLockstep = false;
  90069. this.lockstepMaxSteps = 4;
  90070. }
  90071. return NullEngineOptions;
  90072. }());
  90073. BABYLON.NullEngineOptions = NullEngineOptions;
  90074. /**
  90075. * The null engine class provides support for headless version of babylon.js.
  90076. * This can be used in server side scenario or for testing purposes
  90077. */
  90078. var NullEngine = /** @class */ (function (_super) {
  90079. __extends(NullEngine, _super);
  90080. function NullEngine(options) {
  90081. if (options === void 0) { options = new NullEngineOptions(); }
  90082. var _this = _super.call(this, null) || this;
  90083. if (options.deterministicLockstep === undefined) {
  90084. options.deterministicLockstep = false;
  90085. }
  90086. if (options.lockstepMaxSteps === undefined) {
  90087. options.lockstepMaxSteps = 4;
  90088. }
  90089. _this._options = options;
  90090. // Init caps
  90091. // We consider we are on a webgl1 capable device
  90092. _this._caps = new BABYLON.EngineCapabilities();
  90093. _this._caps.maxTexturesImageUnits = 16;
  90094. _this._caps.maxVertexTextureImageUnits = 16;
  90095. _this._caps.maxTextureSize = 512;
  90096. _this._caps.maxCubemapTextureSize = 512;
  90097. _this._caps.maxRenderTextureSize = 512;
  90098. _this._caps.maxVertexAttribs = 16;
  90099. _this._caps.maxVaryingVectors = 16;
  90100. _this._caps.maxFragmentUniformVectors = 16;
  90101. _this._caps.maxVertexUniformVectors = 16;
  90102. // Extensions
  90103. _this._caps.standardDerivatives = false;
  90104. _this._caps.astc = null;
  90105. _this._caps.s3tc = null;
  90106. _this._caps.pvrtc = null;
  90107. _this._caps.etc1 = null;
  90108. _this._caps.etc2 = null;
  90109. _this._caps.textureAnisotropicFilterExtension = null;
  90110. _this._caps.maxAnisotropy = 0;
  90111. _this._caps.uintIndices = false;
  90112. _this._caps.fragmentDepthSupported = false;
  90113. _this._caps.highPrecisionShaderSupported = true;
  90114. _this._caps.colorBufferFloat = false;
  90115. _this._caps.textureFloat = false;
  90116. _this._caps.textureFloatLinearFiltering = false;
  90117. _this._caps.textureFloatRender = false;
  90118. _this._caps.textureHalfFloat = false;
  90119. _this._caps.textureHalfFloatLinearFiltering = false;
  90120. _this._caps.textureHalfFloatRender = false;
  90121. _this._caps.textureLOD = false;
  90122. _this._caps.drawBuffersExtension = false;
  90123. _this._caps.depthTextureExtension = false;
  90124. _this._caps.vertexArrayObject = false;
  90125. _this._caps.instancedArrays = false;
  90126. BABYLON.Tools.Log("Babylon.js null engine (v" + BABYLON.Engine.Version + ") launched");
  90127. // Wrappers
  90128. if (typeof URL === "undefined") {
  90129. URL = {
  90130. createObjectURL: function () { },
  90131. revokeObjectURL: function () { }
  90132. };
  90133. }
  90134. if (typeof Blob === "undefined") {
  90135. Blob = function () { };
  90136. }
  90137. return _this;
  90138. }
  90139. NullEngine.prototype.isDeterministicLockStep = function () {
  90140. return this._options.deterministicLockstep;
  90141. };
  90142. NullEngine.prototype.getLockstepMaxSteps = function () {
  90143. return this._options.lockstepMaxSteps;
  90144. };
  90145. NullEngine.prototype.getHardwareScalingLevel = function () {
  90146. return 1.0;
  90147. };
  90148. NullEngine.prototype.createVertexBuffer = function (vertices) {
  90149. return {
  90150. capacity: 0,
  90151. references: 1,
  90152. is32Bits: false
  90153. };
  90154. };
  90155. NullEngine.prototype.createIndexBuffer = function (indices) {
  90156. return {
  90157. capacity: 0,
  90158. references: 1,
  90159. is32Bits: false
  90160. };
  90161. };
  90162. NullEngine.prototype.clear = function (color, backBuffer, depth, stencil) {
  90163. if (stencil === void 0) { stencil = false; }
  90164. };
  90165. NullEngine.prototype.getRenderWidth = function (useScreen) {
  90166. if (useScreen === void 0) { useScreen = false; }
  90167. if (!useScreen && this._currentRenderTarget) {
  90168. return this._currentRenderTarget.width;
  90169. }
  90170. return this._options.renderWidth;
  90171. };
  90172. NullEngine.prototype.getRenderHeight = function (useScreen) {
  90173. if (useScreen === void 0) { useScreen = false; }
  90174. if (!useScreen && this._currentRenderTarget) {
  90175. return this._currentRenderTarget.height;
  90176. }
  90177. return this._options.renderHeight;
  90178. };
  90179. NullEngine.prototype.setViewport = function (viewport, requiredWidth, requiredHeight) {
  90180. this._cachedViewport = viewport;
  90181. };
  90182. NullEngine.prototype.createShaderProgram = function (vertexCode, fragmentCode, defines, context) {
  90183. return {
  90184. transformFeedback: null,
  90185. __SPECTOR_rebuildProgram: null
  90186. };
  90187. };
  90188. NullEngine.prototype.getUniforms = function (shaderProgram, uniformsNames) {
  90189. return [];
  90190. };
  90191. NullEngine.prototype.getAttributes = function (shaderProgram, attributesNames) {
  90192. return [];
  90193. };
  90194. NullEngine.prototype.bindSamplers = function (effect) {
  90195. this._currentEffect = null;
  90196. };
  90197. NullEngine.prototype.enableEffect = function (effect) {
  90198. this._currentEffect = effect;
  90199. if (effect.onBind) {
  90200. effect.onBind(effect);
  90201. }
  90202. effect.onBindObservable.notifyObservers(effect);
  90203. };
  90204. NullEngine.prototype.setState = function (culling, zOffset, force, reverseSide) {
  90205. if (zOffset === void 0) { zOffset = 0; }
  90206. if (reverseSide === void 0) { reverseSide = false; }
  90207. };
  90208. NullEngine.prototype.setIntArray = function (uniform, array) {
  90209. };
  90210. NullEngine.prototype.setIntArray2 = function (uniform, array) {
  90211. };
  90212. NullEngine.prototype.setIntArray3 = function (uniform, array) {
  90213. };
  90214. NullEngine.prototype.setIntArray4 = function (uniform, array) {
  90215. };
  90216. NullEngine.prototype.setFloatArray = function (uniform, array) {
  90217. };
  90218. NullEngine.prototype.setFloatArray2 = function (uniform, array) {
  90219. };
  90220. NullEngine.prototype.setFloatArray3 = function (uniform, array) {
  90221. };
  90222. NullEngine.prototype.setFloatArray4 = function (uniform, array) {
  90223. };
  90224. NullEngine.prototype.setArray = function (uniform, array) {
  90225. };
  90226. NullEngine.prototype.setArray2 = function (uniform, array) {
  90227. };
  90228. NullEngine.prototype.setArray3 = function (uniform, array) {
  90229. };
  90230. NullEngine.prototype.setArray4 = function (uniform, array) {
  90231. };
  90232. NullEngine.prototype.setMatrices = function (uniform, matrices) {
  90233. };
  90234. NullEngine.prototype.setMatrix = function (uniform, matrix) {
  90235. };
  90236. NullEngine.prototype.setMatrix3x3 = function (uniform, matrix) {
  90237. };
  90238. NullEngine.prototype.setMatrix2x2 = function (uniform, matrix) {
  90239. };
  90240. NullEngine.prototype.setFloat = function (uniform, value) {
  90241. };
  90242. NullEngine.prototype.setFloat2 = function (uniform, x, y) {
  90243. };
  90244. NullEngine.prototype.setFloat3 = function (uniform, x, y, z) {
  90245. };
  90246. NullEngine.prototype.setBool = function (uniform, bool) {
  90247. };
  90248. NullEngine.prototype.setFloat4 = function (uniform, x, y, z, w) {
  90249. };
  90250. NullEngine.prototype.setColor3 = function (uniform, color3) {
  90251. };
  90252. NullEngine.prototype.setColor4 = function (uniform, color3, alpha) {
  90253. };
  90254. NullEngine.prototype.setAlphaMode = function (mode, noDepthWriteChange) {
  90255. if (noDepthWriteChange === void 0) { noDepthWriteChange = false; }
  90256. if (this._alphaMode === mode) {
  90257. return;
  90258. }
  90259. this._alphaState.alphaBlend = (mode !== BABYLON.Engine.ALPHA_DISABLE);
  90260. if (!noDepthWriteChange) {
  90261. this.setDepthWrite(mode === BABYLON.Engine.ALPHA_DISABLE);
  90262. }
  90263. this._alphaMode = mode;
  90264. };
  90265. NullEngine.prototype.bindBuffers = function (vertexBuffers, indexBuffer, effect) {
  90266. };
  90267. NullEngine.prototype.wipeCaches = function (bruteForce) {
  90268. if (this.preventCacheWipeBetweenFrames) {
  90269. return;
  90270. }
  90271. this.resetTextureCache();
  90272. this._currentEffect = null;
  90273. if (bruteForce) {
  90274. this._currentProgram = null;
  90275. this._stencilState.reset();
  90276. this._depthCullingState.reset();
  90277. this._alphaState.reset();
  90278. }
  90279. this._cachedVertexBuffers = null;
  90280. this._cachedIndexBuffer = null;
  90281. this._cachedEffectForVertexBuffers = null;
  90282. };
  90283. NullEngine.prototype.draw = function (useTriangles, indexStart, indexCount, instancesCount) {
  90284. };
  90285. NullEngine.prototype.drawElementsType = function (fillMode, indexStart, indexCount, instancesCount) {
  90286. };
  90287. NullEngine.prototype.drawArraysType = function (fillMode, verticesStart, verticesCount, instancesCount) {
  90288. };
  90289. NullEngine.prototype._createTexture = function () {
  90290. return {};
  90291. };
  90292. NullEngine.prototype.createTexture = function (urlArg, noMipmap, invertY, scene, samplingMode, onLoad, onError, buffer, fallBack, format) {
  90293. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  90294. if (onLoad === void 0) { onLoad = null; }
  90295. if (onError === void 0) { onError = null; }
  90296. if (buffer === void 0) { buffer = null; }
  90297. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_URL);
  90298. var url = String(urlArg);
  90299. texture.url = url;
  90300. texture.generateMipMaps = !noMipmap;
  90301. texture.samplingMode = samplingMode;
  90302. texture.invertY = invertY;
  90303. texture.baseWidth = this._options.textureSize;
  90304. texture.baseHeight = this._options.textureSize;
  90305. texture.width = this._options.textureSize;
  90306. texture.height = this._options.textureSize;
  90307. if (format) {
  90308. texture.format = format;
  90309. }
  90310. texture.isReady = true;
  90311. if (onLoad) {
  90312. onLoad();
  90313. }
  90314. return texture;
  90315. };
  90316. NullEngine.prototype.createRenderTargetTexture = function (size, options) {
  90317. var fullOptions = new BABYLON.RenderTargetCreationOptions();
  90318. if (options !== undefined && typeof options === "object") {
  90319. fullOptions.generateMipMaps = options.generateMipMaps;
  90320. fullOptions.generateDepthBuffer = options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  90321. fullOptions.generateStencilBuffer = fullOptions.generateDepthBuffer && options.generateStencilBuffer;
  90322. fullOptions.type = options.type === undefined ? BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT : options.type;
  90323. fullOptions.samplingMode = options.samplingMode === undefined ? BABYLON.Texture.TRILINEAR_SAMPLINGMODE : options.samplingMode;
  90324. }
  90325. else {
  90326. fullOptions.generateMipMaps = options;
  90327. fullOptions.generateDepthBuffer = true;
  90328. fullOptions.generateStencilBuffer = false;
  90329. fullOptions.type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  90330. fullOptions.samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE;
  90331. }
  90332. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_RENDERTARGET);
  90333. var width = size.width || size;
  90334. var height = size.height || size;
  90335. texture._depthStencilBuffer = {};
  90336. texture._framebuffer = {};
  90337. texture.baseWidth = width;
  90338. texture.baseHeight = height;
  90339. texture.width = width;
  90340. texture.height = height;
  90341. texture.isReady = true;
  90342. texture.samples = 1;
  90343. texture.generateMipMaps = fullOptions.generateMipMaps ? true : false;
  90344. texture.samplingMode = fullOptions.samplingMode;
  90345. texture.type = fullOptions.type;
  90346. texture._generateDepthBuffer = fullOptions.generateDepthBuffer;
  90347. texture._generateStencilBuffer = fullOptions.generateStencilBuffer ? true : false;
  90348. return texture;
  90349. };
  90350. NullEngine.prototype.updateTextureSamplingMode = function (samplingMode, texture) {
  90351. texture.samplingMode = samplingMode;
  90352. };
  90353. NullEngine.prototype.bindFramebuffer = function (texture, faceIndex, requiredWidth, requiredHeight, forceFullscreenViewport) {
  90354. if (this._currentRenderTarget) {
  90355. this.unBindFramebuffer(this._currentRenderTarget);
  90356. }
  90357. this._currentRenderTarget = texture;
  90358. this._currentFramebuffer = texture._MSAAFramebuffer ? texture._MSAAFramebuffer : texture._framebuffer;
  90359. if (this._cachedViewport && !forceFullscreenViewport) {
  90360. this.setViewport(this._cachedViewport, requiredWidth, requiredHeight);
  90361. }
  90362. };
  90363. NullEngine.prototype.unBindFramebuffer = function (texture, disableGenerateMipMaps, onBeforeUnbind) {
  90364. if (disableGenerateMipMaps === void 0) { disableGenerateMipMaps = false; }
  90365. this._currentRenderTarget = null;
  90366. if (onBeforeUnbind) {
  90367. if (texture._MSAAFramebuffer) {
  90368. this._currentFramebuffer = texture._framebuffer;
  90369. }
  90370. onBeforeUnbind();
  90371. }
  90372. this._currentFramebuffer = null;
  90373. };
  90374. NullEngine.prototype.createDynamicVertexBuffer = function (vertices) {
  90375. var vbo = {
  90376. capacity: 1,
  90377. references: 1,
  90378. is32Bits: false
  90379. };
  90380. return vbo;
  90381. };
  90382. NullEngine.prototype.updateDynamicIndexBuffer = function (indexBuffer, indices, offset) {
  90383. if (offset === void 0) { offset = 0; }
  90384. };
  90385. NullEngine.prototype.updateDynamicVertexBuffer = function (vertexBuffer, vertices, offset, count) {
  90386. };
  90387. NullEngine.prototype._bindTextureDirectly = function (target, texture) {
  90388. if (this._boundTexturesCache[this._activeChannel] !== texture) {
  90389. this._boundTexturesCache[this._activeChannel] = texture;
  90390. }
  90391. };
  90392. NullEngine.prototype._bindTexture = function (channel, texture) {
  90393. if (channel < 0) {
  90394. return;
  90395. }
  90396. this._bindTextureDirectly(0, texture);
  90397. };
  90398. NullEngine.prototype._releaseBuffer = function (buffer) {
  90399. buffer.references--;
  90400. if (buffer.references === 0) {
  90401. return true;
  90402. }
  90403. return false;
  90404. };
  90405. return NullEngine;
  90406. }(BABYLON.Engine));
  90407. BABYLON.NullEngine = NullEngine;
  90408. })(BABYLON || (BABYLON = {}));
  90409. //# sourceMappingURL=babylon.nullEngine.js.map
  90410. "use strict";
  90411. var BABYLON;
  90412. (function (BABYLON) {
  90413. /**
  90414. * This class can be used to get instrumentation data from a Babylon engine
  90415. */
  90416. var EngineInstrumentation = /** @class */ (function () {
  90417. function EngineInstrumentation(engine) {
  90418. this.engine = engine;
  90419. this._captureGPUFrameTime = false;
  90420. this._gpuFrameTime = new BABYLON.PerfCounter();
  90421. this._captureShaderCompilationTime = false;
  90422. this._shaderCompilationTime = new BABYLON.PerfCounter();
  90423. // Observers
  90424. this._onBeginFrameObserver = null;
  90425. this._onEndFrameObserver = null;
  90426. this._onBeforeShaderCompilationObserver = null;
  90427. this._onAfterShaderCompilationObserver = null;
  90428. }
  90429. Object.defineProperty(EngineInstrumentation.prototype, "gpuFrameTimeCounter", {
  90430. // Properties
  90431. /**
  90432. * Gets the perf counter used for GPU frame time
  90433. */
  90434. get: function () {
  90435. return this._gpuFrameTime;
  90436. },
  90437. enumerable: true,
  90438. configurable: true
  90439. });
  90440. Object.defineProperty(EngineInstrumentation.prototype, "captureGPUFrameTime", {
  90441. /**
  90442. * Gets the GPU frame time capture status
  90443. */
  90444. get: function () {
  90445. return this._captureGPUFrameTime;
  90446. },
  90447. /**
  90448. * Enable or disable the GPU frame time capture
  90449. */
  90450. set: function (value) {
  90451. var _this = this;
  90452. if (value === this._captureGPUFrameTime) {
  90453. return;
  90454. }
  90455. this._captureGPUFrameTime = value;
  90456. if (value) {
  90457. this._onBeginFrameObserver = this.engine.onBeginFrameObservable.add(function () {
  90458. if (!_this._gpuFrameTimeToken) {
  90459. _this._gpuFrameTimeToken = _this.engine.startTimeQuery();
  90460. }
  90461. });
  90462. this._onEndFrameObserver = this.engine.onEndFrameObservable.add(function () {
  90463. if (!_this._gpuFrameTimeToken) {
  90464. return;
  90465. }
  90466. var time = _this.engine.endTimeQuery(_this._gpuFrameTimeToken);
  90467. if (time > -1) {
  90468. _this._gpuFrameTimeToken = null;
  90469. _this._gpuFrameTime.fetchNewFrame();
  90470. _this._gpuFrameTime.addCount(time, true);
  90471. }
  90472. });
  90473. }
  90474. else {
  90475. this.engine.onBeginFrameObservable.remove(this._onBeginFrameObserver);
  90476. this._onBeginFrameObserver = null;
  90477. this.engine.onEndFrameObservable.remove(this._onEndFrameObserver);
  90478. this._onEndFrameObserver = null;
  90479. }
  90480. },
  90481. enumerable: true,
  90482. configurable: true
  90483. });
  90484. Object.defineProperty(EngineInstrumentation.prototype, "shaderCompilationTimeCounter", {
  90485. /**
  90486. * Gets the perf counter used for shader compilation time
  90487. */
  90488. get: function () {
  90489. return this._shaderCompilationTime;
  90490. },
  90491. enumerable: true,
  90492. configurable: true
  90493. });
  90494. Object.defineProperty(EngineInstrumentation.prototype, "captureShaderCompilationTime", {
  90495. /**
  90496. * Gets the shader compilation time capture status
  90497. */
  90498. get: function () {
  90499. return this._captureShaderCompilationTime;
  90500. },
  90501. /**
  90502. * Enable or disable the shader compilation time capture
  90503. */
  90504. set: function (value) {
  90505. var _this = this;
  90506. if (value === this._captureShaderCompilationTime) {
  90507. return;
  90508. }
  90509. this._captureShaderCompilationTime = value;
  90510. if (value) {
  90511. this._onBeforeShaderCompilationObserver = this.engine.onBeforeShaderCompilationObservable.add(function () {
  90512. _this._shaderCompilationTime.fetchNewFrame();
  90513. _this._shaderCompilationTime.beginMonitoring();
  90514. });
  90515. this._onAfterShaderCompilationObserver = this.engine.onAfterShaderCompilationObservable.add(function () {
  90516. _this._shaderCompilationTime.endMonitoring();
  90517. });
  90518. }
  90519. else {
  90520. this.engine.onBeforeShaderCompilationObservable.remove(this._onBeforeShaderCompilationObserver);
  90521. this._onBeforeShaderCompilationObserver = null;
  90522. this.engine.onAfterShaderCompilationObservable.remove(this._onAfterShaderCompilationObserver);
  90523. this._onAfterShaderCompilationObserver = null;
  90524. }
  90525. },
  90526. enumerable: true,
  90527. configurable: true
  90528. });
  90529. EngineInstrumentation.prototype.dispose = function () {
  90530. this.engine.onBeginFrameObservable.remove(this._onBeginFrameObserver);
  90531. this._onBeginFrameObserver = null;
  90532. this.engine.onEndFrameObservable.remove(this._onEndFrameObserver);
  90533. this._onEndFrameObserver = null;
  90534. this.engine.onBeforeShaderCompilationObservable.remove(this._onBeforeShaderCompilationObserver);
  90535. this._onBeforeShaderCompilationObserver = null;
  90536. this.engine.onAfterShaderCompilationObservable.remove(this._onAfterShaderCompilationObserver);
  90537. this._onAfterShaderCompilationObserver = null;
  90538. this.engine = null;
  90539. };
  90540. return EngineInstrumentation;
  90541. }());
  90542. BABYLON.EngineInstrumentation = EngineInstrumentation;
  90543. })(BABYLON || (BABYLON = {}));
  90544. //# sourceMappingURL=babylon.engineInstrumentation.js.map
  90545. "use strict";
  90546. var BABYLON;
  90547. (function (BABYLON) {
  90548. /**
  90549. * This class can be used to get instrumentation data from a Babylon engine
  90550. */
  90551. var SceneInstrumentation = /** @class */ (function () {
  90552. function SceneInstrumentation(scene) {
  90553. var _this = this;
  90554. this.scene = scene;
  90555. this._captureActiveMeshesEvaluationTime = false;
  90556. this._activeMeshesEvaluationTime = new BABYLON.PerfCounter();
  90557. this._captureRenderTargetsRenderTime = false;
  90558. this._renderTargetsRenderTime = new BABYLON.PerfCounter();
  90559. this._captureFrameTime = false;
  90560. this._frameTime = new BABYLON.PerfCounter();
  90561. this._captureRenderTime = false;
  90562. this._renderTime = new BABYLON.PerfCounter();
  90563. this._captureInterFrameTime = false;
  90564. this._interFrameTime = new BABYLON.PerfCounter();
  90565. this._captureParticlesRenderTime = false;
  90566. this._particlesRenderTime = new BABYLON.PerfCounter();
  90567. this._captureSpritesRenderTime = false;
  90568. this._spritesRenderTime = new BABYLON.PerfCounter();
  90569. this._capturePhysicsTime = false;
  90570. this._physicsTime = new BABYLON.PerfCounter();
  90571. this._captureAnimationsTime = false;
  90572. this._animationsTime = new BABYLON.PerfCounter();
  90573. // Observers
  90574. this._onBeforeActiveMeshesEvaluationObserver = null;
  90575. this._onAfterActiveMeshesEvaluationObserver = null;
  90576. this._onBeforeRenderTargetsRenderObserver = null;
  90577. this._onAfterRenderTargetsRenderObserver = null;
  90578. this._onAfterRenderObserver = null;
  90579. this._onBeforeDrawPhaseObserver = null;
  90580. this._onAfterDrawPhaseObserver = null;
  90581. this._onBeforeAnimationsObserver = null;
  90582. this._onBeforeParticlesRenderingObserver = null;
  90583. this._onAfterParticlesRenderingObserver = null;
  90584. this._onBeforeSpritesRenderingObserver = null;
  90585. this._onAfterSpritesRenderingObserver = null;
  90586. this._onBeforePhysicsObserver = null;
  90587. this._onAfterPhysicsObserver = null;
  90588. this._onAfterAnimationsObserver = null;
  90589. // Before render
  90590. this._onBeforeAnimationsObserver = scene.onBeforeAnimationsObservable.add(function () {
  90591. if (_this._captureActiveMeshesEvaluationTime) {
  90592. _this._activeMeshesEvaluationTime.fetchNewFrame();
  90593. }
  90594. if (_this._captureRenderTargetsRenderTime) {
  90595. _this._renderTargetsRenderTime.fetchNewFrame();
  90596. }
  90597. if (_this._captureFrameTime) {
  90598. BABYLON.Tools.StartPerformanceCounter("Scene rendering");
  90599. _this._frameTime.beginMonitoring();
  90600. }
  90601. if (_this._captureInterFrameTime) {
  90602. _this._interFrameTime.endMonitoring();
  90603. }
  90604. if (_this._captureParticlesRenderTime) {
  90605. _this._particlesRenderTime.fetchNewFrame();
  90606. }
  90607. if (_this._captureSpritesRenderTime) {
  90608. _this._spritesRenderTime.fetchNewFrame();
  90609. }
  90610. if (_this._captureAnimationsTime) {
  90611. _this._animationsTime.beginMonitoring();
  90612. }
  90613. _this.scene.getEngine()._drawCalls.fetchNewFrame();
  90614. _this.scene.getEngine()._textureCollisions.fetchNewFrame();
  90615. });
  90616. // After render
  90617. this._onAfterRenderObserver = scene.onAfterRenderObservable.add(function () {
  90618. if (_this._captureFrameTime) {
  90619. BABYLON.Tools.EndPerformanceCounter("Scene rendering");
  90620. _this._frameTime.endMonitoring();
  90621. }
  90622. if (_this._captureRenderTime) {
  90623. _this._renderTime.endMonitoring(false);
  90624. }
  90625. if (_this._captureInterFrameTime) {
  90626. _this._interFrameTime.beginMonitoring();
  90627. }
  90628. });
  90629. }
  90630. Object.defineProperty(SceneInstrumentation.prototype, "activeMeshesEvaluationTimeCounter", {
  90631. // Properties
  90632. /**
  90633. * Gets the perf counter used for active meshes evaluation time
  90634. */
  90635. get: function () {
  90636. return this._activeMeshesEvaluationTime;
  90637. },
  90638. enumerable: true,
  90639. configurable: true
  90640. });
  90641. Object.defineProperty(SceneInstrumentation.prototype, "captureActiveMeshesEvaluationTime", {
  90642. /**
  90643. * Gets the active meshes evaluation time capture status
  90644. */
  90645. get: function () {
  90646. return this._captureActiveMeshesEvaluationTime;
  90647. },
  90648. /**
  90649. * Enable or disable the active meshes evaluation time capture
  90650. */
  90651. set: function (value) {
  90652. var _this = this;
  90653. if (value === this._captureActiveMeshesEvaluationTime) {
  90654. return;
  90655. }
  90656. this._captureActiveMeshesEvaluationTime = value;
  90657. if (value) {
  90658. this._onBeforeActiveMeshesEvaluationObserver = this.scene.onBeforeActiveMeshesEvaluationObservable.add(function () {
  90659. BABYLON.Tools.StartPerformanceCounter("Active meshes evaluation");
  90660. _this._activeMeshesEvaluationTime.beginMonitoring();
  90661. });
  90662. this._onAfterActiveMeshesEvaluationObserver = this.scene.onAfterActiveMeshesEvaluationObservable.add(function () {
  90663. BABYLON.Tools.EndPerformanceCounter("Active meshes evaluation");
  90664. _this._activeMeshesEvaluationTime.endMonitoring();
  90665. });
  90666. }
  90667. else {
  90668. this.scene.onBeforeActiveMeshesEvaluationObservable.remove(this._onBeforeActiveMeshesEvaluationObserver);
  90669. this._onBeforeActiveMeshesEvaluationObserver = null;
  90670. this.scene.onAfterActiveMeshesEvaluationObservable.remove(this._onAfterActiveMeshesEvaluationObserver);
  90671. this._onAfterActiveMeshesEvaluationObserver = null;
  90672. }
  90673. },
  90674. enumerable: true,
  90675. configurable: true
  90676. });
  90677. Object.defineProperty(SceneInstrumentation.prototype, "renderTargetsRenderTimeCounter", {
  90678. /**
  90679. * Gets the perf counter used for render targets render time
  90680. */
  90681. get: function () {
  90682. return this._renderTargetsRenderTime;
  90683. },
  90684. enumerable: true,
  90685. configurable: true
  90686. });
  90687. Object.defineProperty(SceneInstrumentation.prototype, "captureRenderTargetsRenderTime", {
  90688. /**
  90689. * Gets the render targets render time capture status
  90690. */
  90691. get: function () {
  90692. return this._captureRenderTargetsRenderTime;
  90693. },
  90694. /**
  90695. * Enable or disable the render targets render time capture
  90696. */
  90697. set: function (value) {
  90698. var _this = this;
  90699. if (value === this._captureRenderTargetsRenderTime) {
  90700. return;
  90701. }
  90702. this._captureRenderTargetsRenderTime = value;
  90703. if (value) {
  90704. this._onBeforeRenderTargetsRenderObserver = this.scene.OnBeforeRenderTargetsRenderObservable.add(function () {
  90705. BABYLON.Tools.StartPerformanceCounter("Render targets rendering");
  90706. _this._renderTargetsRenderTime.beginMonitoring();
  90707. });
  90708. this._onAfterRenderTargetsRenderObserver = this.scene.OnAfterRenderTargetsRenderObservable.add(function () {
  90709. BABYLON.Tools.EndPerformanceCounter("Render targets rendering");
  90710. _this._renderTargetsRenderTime.endMonitoring(false);
  90711. });
  90712. }
  90713. else {
  90714. this.scene.OnBeforeRenderTargetsRenderObservable.remove(this._onBeforeRenderTargetsRenderObserver);
  90715. this._onBeforeRenderTargetsRenderObserver = null;
  90716. this.scene.OnAfterRenderTargetsRenderObservable.remove(this._onAfterRenderTargetsRenderObserver);
  90717. this._onAfterRenderTargetsRenderObserver = null;
  90718. }
  90719. },
  90720. enumerable: true,
  90721. configurable: true
  90722. });
  90723. Object.defineProperty(SceneInstrumentation.prototype, "particlesRenderTimeCounter", {
  90724. /**
  90725. * Gets the perf counter used for particles render time
  90726. */
  90727. get: function () {
  90728. return this._particlesRenderTime;
  90729. },
  90730. enumerable: true,
  90731. configurable: true
  90732. });
  90733. Object.defineProperty(SceneInstrumentation.prototype, "captureParticlesRenderTime", {
  90734. /**
  90735. * Gets the particles render time capture status
  90736. */
  90737. get: function () {
  90738. return this._captureParticlesRenderTime;
  90739. },
  90740. /**
  90741. * Enable or disable the particles render time capture
  90742. */
  90743. set: function (value) {
  90744. var _this = this;
  90745. if (value === this._captureParticlesRenderTime) {
  90746. return;
  90747. }
  90748. this._captureParticlesRenderTime = value;
  90749. if (value) {
  90750. this._onBeforeParticlesRenderingObserver = this.scene.onBeforeParticlesRenderingObservable.add(function () {
  90751. BABYLON.Tools.StartPerformanceCounter("Particles");
  90752. _this._particlesRenderTime.beginMonitoring();
  90753. });
  90754. this._onAfterParticlesRenderingObserver = this.scene.onAfterParticlesRenderingObservable.add(function () {
  90755. BABYLON.Tools.EndPerformanceCounter("Particles");
  90756. _this._particlesRenderTime.endMonitoring(false);
  90757. });
  90758. }
  90759. else {
  90760. this.scene.onBeforeParticlesRenderingObservable.remove(this._onBeforeParticlesRenderingObserver);
  90761. this._onBeforeParticlesRenderingObserver = null;
  90762. this.scene.onAfterParticlesRenderingObservable.remove(this._onAfterParticlesRenderingObserver);
  90763. this._onAfterParticlesRenderingObserver = null;
  90764. }
  90765. },
  90766. enumerable: true,
  90767. configurable: true
  90768. });
  90769. Object.defineProperty(SceneInstrumentation.prototype, "spritesRenderTimeCounter", {
  90770. /**
  90771. * Gets the perf counter used for sprites render time
  90772. */
  90773. get: function () {
  90774. return this._spritesRenderTime;
  90775. },
  90776. enumerable: true,
  90777. configurable: true
  90778. });
  90779. Object.defineProperty(SceneInstrumentation.prototype, "captureSpritesRenderTime", {
  90780. /**
  90781. * Gets the sprites render time capture status
  90782. */
  90783. get: function () {
  90784. return this._captureSpritesRenderTime;
  90785. },
  90786. /**
  90787. * Enable or disable the sprites render time capture
  90788. */
  90789. set: function (value) {
  90790. var _this = this;
  90791. if (value === this._captureSpritesRenderTime) {
  90792. return;
  90793. }
  90794. this._captureSpritesRenderTime = value;
  90795. if (value) {
  90796. this._onBeforeSpritesRenderingObserver = this.scene.onBeforeSpritesRenderingObservable.add(function () {
  90797. BABYLON.Tools.StartPerformanceCounter("Sprites");
  90798. _this._spritesRenderTime.beginMonitoring();
  90799. });
  90800. this._onAfterSpritesRenderingObserver = this.scene.onAfterSpritesRenderingObservable.add(function () {
  90801. BABYLON.Tools.EndPerformanceCounter("Sprites");
  90802. _this._spritesRenderTime.endMonitoring(false);
  90803. });
  90804. }
  90805. else {
  90806. this.scene.onBeforeSpritesRenderingObservable.remove(this._onBeforeSpritesRenderingObserver);
  90807. this._onBeforeSpritesRenderingObserver = null;
  90808. this.scene.onAfterSpritesRenderingObservable.remove(this._onAfterSpritesRenderingObserver);
  90809. this._onAfterSpritesRenderingObserver = null;
  90810. }
  90811. },
  90812. enumerable: true,
  90813. configurable: true
  90814. });
  90815. Object.defineProperty(SceneInstrumentation.prototype, "physicsTimeCounter", {
  90816. /**
  90817. * Gets the perf counter used for physics time
  90818. */
  90819. get: function () {
  90820. return this._physicsTime;
  90821. },
  90822. enumerable: true,
  90823. configurable: true
  90824. });
  90825. Object.defineProperty(SceneInstrumentation.prototype, "capturePhysicsTime", {
  90826. /**
  90827. * Gets the physics time capture status
  90828. */
  90829. get: function () {
  90830. return this._capturePhysicsTime;
  90831. },
  90832. /**
  90833. * Enable or disable the physics time capture
  90834. */
  90835. set: function (value) {
  90836. var _this = this;
  90837. if (value === this._capturePhysicsTime) {
  90838. return;
  90839. }
  90840. this._capturePhysicsTime = value;
  90841. if (value) {
  90842. this._onBeforePhysicsObserver = this.scene.onBeforePhysicsObservable.add(function () {
  90843. BABYLON.Tools.StartPerformanceCounter("Physics");
  90844. _this._physicsTime.beginMonitoring();
  90845. });
  90846. this._onAfterPhysicsObserver = this.scene.onAfterPhysicsObservable.add(function () {
  90847. BABYLON.Tools.EndPerformanceCounter("Physics");
  90848. _this._physicsTime.endMonitoring();
  90849. });
  90850. }
  90851. else {
  90852. this.scene.onBeforePhysicsObservable.remove(this._onBeforePhysicsObserver);
  90853. this._onBeforePhysicsObserver = null;
  90854. this.scene.onAfterPhysicsObservable.remove(this._onAfterPhysicsObserver);
  90855. this._onAfterPhysicsObserver = null;
  90856. }
  90857. },
  90858. enumerable: true,
  90859. configurable: true
  90860. });
  90861. Object.defineProperty(SceneInstrumentation.prototype, "animationsTimeCounter", {
  90862. /**
  90863. * Gets the perf counter used for animations time
  90864. */
  90865. get: function () {
  90866. return this._animationsTime;
  90867. },
  90868. enumerable: true,
  90869. configurable: true
  90870. });
  90871. Object.defineProperty(SceneInstrumentation.prototype, "captureAnimationsTime", {
  90872. /**
  90873. * Gets the animations time capture status
  90874. */
  90875. get: function () {
  90876. return this._captureAnimationsTime;
  90877. },
  90878. /**
  90879. * Enable or disable the animations time capture
  90880. */
  90881. set: function (value) {
  90882. var _this = this;
  90883. if (value === this._captureAnimationsTime) {
  90884. return;
  90885. }
  90886. this._captureAnimationsTime = value;
  90887. if (value) {
  90888. this._onAfterAnimationsObserver = this.scene.onAfterAnimationsObservable.add(function () {
  90889. _this._animationsTime.endMonitoring();
  90890. });
  90891. }
  90892. else {
  90893. this.scene.onAfterAnimationsObservable.remove(this._onAfterAnimationsObserver);
  90894. this._onAfterAnimationsObserver = null;
  90895. }
  90896. },
  90897. enumerable: true,
  90898. configurable: true
  90899. });
  90900. Object.defineProperty(SceneInstrumentation.prototype, "frameTimeCounter", {
  90901. /**
  90902. * Gets the perf counter used for frame time capture
  90903. */
  90904. get: function () {
  90905. return this._frameTime;
  90906. },
  90907. enumerable: true,
  90908. configurable: true
  90909. });
  90910. Object.defineProperty(SceneInstrumentation.prototype, "captureFrameTime", {
  90911. /**
  90912. * Gets the frame time capture status
  90913. */
  90914. get: function () {
  90915. return this._captureFrameTime;
  90916. },
  90917. /**
  90918. * Enable or disable the frame time capture
  90919. */
  90920. set: function (value) {
  90921. this._captureFrameTime = value;
  90922. },
  90923. enumerable: true,
  90924. configurable: true
  90925. });
  90926. Object.defineProperty(SceneInstrumentation.prototype, "interFrameTimeCounter", {
  90927. /**
  90928. * Gets the perf counter used for inter-frames time capture
  90929. */
  90930. get: function () {
  90931. return this._interFrameTime;
  90932. },
  90933. enumerable: true,
  90934. configurable: true
  90935. });
  90936. Object.defineProperty(SceneInstrumentation.prototype, "captureInterFrameTime", {
  90937. /**
  90938. * Gets the inter-frames time capture status
  90939. */
  90940. get: function () {
  90941. return this._captureInterFrameTime;
  90942. },
  90943. /**
  90944. * Enable or disable the inter-frames time capture
  90945. */
  90946. set: function (value) {
  90947. this._captureInterFrameTime = value;
  90948. },
  90949. enumerable: true,
  90950. configurable: true
  90951. });
  90952. Object.defineProperty(SceneInstrumentation.prototype, "renderTimeCounter", {
  90953. /**
  90954. * Gets the perf counter used for render time capture
  90955. */
  90956. get: function () {
  90957. return this._renderTime;
  90958. },
  90959. enumerable: true,
  90960. configurable: true
  90961. });
  90962. Object.defineProperty(SceneInstrumentation.prototype, "captureRenderTime", {
  90963. /**
  90964. * Gets the render time capture status
  90965. */
  90966. get: function () {
  90967. return this._captureRenderTime;
  90968. },
  90969. /**
  90970. * Enable or disable the render time capture
  90971. */
  90972. set: function (value) {
  90973. var _this = this;
  90974. if (value === this._captureRenderTime) {
  90975. return;
  90976. }
  90977. this._captureRenderTime = value;
  90978. if (value) {
  90979. this._onBeforeDrawPhaseObserver = this.scene.onBeforeDrawPhaseObservable.add(function () {
  90980. _this._renderTime.beginMonitoring();
  90981. BABYLON.Tools.StartPerformanceCounter("Main render");
  90982. });
  90983. this._onAfterDrawPhaseObserver = this.scene.onAfterDrawPhaseObservable.add(function () {
  90984. _this._renderTime.endMonitoring(false);
  90985. BABYLON.Tools.EndPerformanceCounter("Main render");
  90986. });
  90987. }
  90988. else {
  90989. this.scene.onBeforeDrawPhaseObservable.remove(this._onBeforeDrawPhaseObserver);
  90990. this._onBeforeDrawPhaseObserver = null;
  90991. this.scene.onAfterDrawPhaseObservable.remove(this._onAfterDrawPhaseObserver);
  90992. this._onAfterDrawPhaseObserver = null;
  90993. }
  90994. },
  90995. enumerable: true,
  90996. configurable: true
  90997. });
  90998. Object.defineProperty(SceneInstrumentation.prototype, "drawCallsCounter", {
  90999. /**
  91000. * Gets the perf counter used for draw calls
  91001. */
  91002. get: function () {
  91003. return this.scene.getEngine()._drawCalls;
  91004. },
  91005. enumerable: true,
  91006. configurable: true
  91007. });
  91008. Object.defineProperty(SceneInstrumentation.prototype, "textureCollisionsCounter", {
  91009. /**
  91010. * Gets the perf counter used for texture collisions
  91011. */
  91012. get: function () {
  91013. return this.scene.getEngine()._textureCollisions;
  91014. },
  91015. enumerable: true,
  91016. configurable: true
  91017. });
  91018. SceneInstrumentation.prototype.dispose = function () {
  91019. this.scene.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  91020. this._onAfterRenderObserver = null;
  91021. this.scene.onBeforeActiveMeshesEvaluationObservable.remove(this._onBeforeActiveMeshesEvaluationObserver);
  91022. this._onBeforeActiveMeshesEvaluationObserver = null;
  91023. this.scene.onAfterActiveMeshesEvaluationObservable.remove(this._onAfterActiveMeshesEvaluationObserver);
  91024. this._onAfterActiveMeshesEvaluationObserver = null;
  91025. this.scene.OnBeforeRenderTargetsRenderObservable.remove(this._onBeforeRenderTargetsRenderObserver);
  91026. this._onBeforeRenderTargetsRenderObserver = null;
  91027. this.scene.OnAfterRenderTargetsRenderObservable.remove(this._onAfterRenderTargetsRenderObserver);
  91028. this._onAfterRenderTargetsRenderObserver = null;
  91029. this.scene.onBeforeAnimationsObservable.remove(this._onBeforeAnimationsObserver);
  91030. this._onBeforeAnimationsObserver = null;
  91031. this.scene.onBeforeParticlesRenderingObservable.remove(this._onBeforeParticlesRenderingObserver);
  91032. this._onBeforeParticlesRenderingObserver = null;
  91033. this.scene.onAfterParticlesRenderingObservable.remove(this._onAfterParticlesRenderingObserver);
  91034. this._onAfterParticlesRenderingObserver = null;
  91035. this.scene.onBeforeSpritesRenderingObservable.remove(this._onBeforeSpritesRenderingObserver);
  91036. this._onBeforeSpritesRenderingObserver = null;
  91037. this.scene.onAfterSpritesRenderingObservable.remove(this._onAfterSpritesRenderingObserver);
  91038. this._onAfterSpritesRenderingObserver = null;
  91039. this.scene.onBeforeDrawPhaseObservable.remove(this._onBeforeDrawPhaseObserver);
  91040. this._onBeforeDrawPhaseObserver = null;
  91041. this.scene.onAfterDrawPhaseObservable.remove(this._onAfterDrawPhaseObserver);
  91042. this._onAfterDrawPhaseObserver = null;
  91043. this.scene.onBeforePhysicsObservable.remove(this._onBeforePhysicsObserver);
  91044. this._onBeforePhysicsObserver = null;
  91045. this.scene.onAfterPhysicsObservable.remove(this._onAfterPhysicsObserver);
  91046. this._onAfterPhysicsObserver = null;
  91047. this.scene.onAfterAnimationsObservable.remove(this._onAfterAnimationsObserver);
  91048. this._onAfterAnimationsObserver = null;
  91049. this.scene = null;
  91050. };
  91051. return SceneInstrumentation;
  91052. }());
  91053. BABYLON.SceneInstrumentation = SceneInstrumentation;
  91054. })(BABYLON || (BABYLON = {}));
  91055. //# sourceMappingURL=babylon.sceneInstrumentation.js.map
  91056. "use strict";
  91057. var BABYLON;
  91058. (function (BABYLON) {
  91059. var _TimeToken = /** @class */ (function () {
  91060. function _TimeToken() {
  91061. this._timeElapsedQueryEnded = false;
  91062. }
  91063. return _TimeToken;
  91064. }());
  91065. BABYLON._TimeToken = _TimeToken;
  91066. })(BABYLON || (BABYLON = {}));
  91067. //# sourceMappingURL=babylon.timeToken.js.map
  91068. "use strict";
  91069. var BABYLON;
  91070. (function (BABYLON) {
  91071. /**
  91072. * Background material defines definition.
  91073. * @ignore Mainly internal Use
  91074. */
  91075. var BackgroundMaterialDefines = /** @class */ (function (_super) {
  91076. __extends(BackgroundMaterialDefines, _super);
  91077. /**
  91078. * Constructor of the defines.
  91079. */
  91080. function BackgroundMaterialDefines() {
  91081. var _this = _super.call(this) || this;
  91082. /**
  91083. * True if the diffuse texture is in use.
  91084. */
  91085. _this.DIFFUSE = false;
  91086. /**
  91087. * The direct UV channel to use.
  91088. */
  91089. _this.DIFFUSEDIRECTUV = 0;
  91090. /**
  91091. * True if the diffuse texture is in gamma space.
  91092. */
  91093. _this.GAMMADIFFUSE = false;
  91094. /**
  91095. * True if the diffuse texture has opacity in the alpha channel.
  91096. */
  91097. _this.DIFFUSEHASALPHA = false;
  91098. /**
  91099. * True if you want the material to fade to transparent at grazing angle.
  91100. */
  91101. _this.OPACITYFRESNEL = false;
  91102. /**
  91103. * True if an extra blur needs to be added in the reflection.
  91104. */
  91105. _this.REFLECTIONBLUR = false;
  91106. /**
  91107. * True if you want the material to fade to reflection at grazing angle.
  91108. */
  91109. _this.REFLECTIONFRESNEL = false;
  91110. /**
  91111. * True if you want the material to falloff as far as you move away from the scene center.
  91112. */
  91113. _this.REFLECTIONFALLOFF = false;
  91114. /**
  91115. * False if the current Webgl implementation does not support the texture lod extension.
  91116. */
  91117. _this.TEXTURELODSUPPORT = false;
  91118. /**
  91119. * True to ensure the data are premultiplied.
  91120. */
  91121. _this.PREMULTIPLYALPHA = false;
  91122. /**
  91123. * True if the texture contains cooked RGB values and not gray scaled multipliers.
  91124. */
  91125. _this.USERGBCOLOR = false;
  91126. /**
  91127. * True to add noise in order to reduce the banding effect.
  91128. */
  91129. _this.NOISE = false;
  91130. /**
  91131. * is the reflection texture in BGR color scheme?
  91132. * Mainly used to solve a bug in ios10 video tag
  91133. */
  91134. _this.REFLECTIONBGR = false;
  91135. _this.IMAGEPROCESSING = false;
  91136. _this.VIGNETTE = false;
  91137. _this.VIGNETTEBLENDMODEMULTIPLY = false;
  91138. _this.VIGNETTEBLENDMODEOPAQUE = false;
  91139. _this.TONEMAPPING = false;
  91140. _this.CONTRAST = false;
  91141. _this.COLORCURVES = false;
  91142. _this.COLORGRADING = false;
  91143. _this.COLORGRADING3D = false;
  91144. _this.SAMPLER3DGREENDEPTH = false;
  91145. _this.SAMPLER3DBGRMAP = false;
  91146. _this.IMAGEPROCESSINGPOSTPROCESS = false;
  91147. _this.EXPOSURE = false;
  91148. // Reflection.
  91149. _this.REFLECTION = false;
  91150. _this.REFLECTIONMAP_3D = false;
  91151. _this.REFLECTIONMAP_SPHERICAL = false;
  91152. _this.REFLECTIONMAP_PLANAR = false;
  91153. _this.REFLECTIONMAP_CUBIC = false;
  91154. _this.REFLECTIONMAP_PROJECTION = false;
  91155. _this.REFLECTIONMAP_SKYBOX = false;
  91156. _this.REFLECTIONMAP_EXPLICIT = false;
  91157. _this.REFLECTIONMAP_EQUIRECTANGULAR = false;
  91158. _this.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  91159. _this.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  91160. _this.INVERTCUBICMAP = false;
  91161. _this.REFLECTIONMAP_OPPOSITEZ = false;
  91162. _this.LODINREFLECTIONALPHA = false;
  91163. _this.GAMMAREFLECTION = false;
  91164. _this.EQUIRECTANGULAR_RELFECTION_FOV = false;
  91165. // Default BJS.
  91166. _this.MAINUV1 = false;
  91167. _this.MAINUV2 = false;
  91168. _this.UV1 = false;
  91169. _this.UV2 = false;
  91170. _this.CLIPPLANE = false;
  91171. _this.POINTSIZE = false;
  91172. _this.FOG = false;
  91173. _this.NORMAL = false;
  91174. _this.NUM_BONE_INFLUENCERS = 0;
  91175. _this.BonesPerMesh = 0;
  91176. _this.INSTANCES = false;
  91177. _this.SHADOWFLOAT = false;
  91178. _this.rebuild();
  91179. return _this;
  91180. }
  91181. return BackgroundMaterialDefines;
  91182. }(BABYLON.MaterialDefines));
  91183. /**
  91184. * Background material used to create an efficient environement around your scene.
  91185. */
  91186. var BackgroundMaterial = /** @class */ (function (_super) {
  91187. __extends(BackgroundMaterial, _super);
  91188. /**
  91189. * Instantiates a Background Material in the given scene
  91190. * @param name The friendly name of the material
  91191. * @param scene The scene to add the material to
  91192. */
  91193. function BackgroundMaterial(name, scene) {
  91194. var _this = _super.call(this, name, scene) || this;
  91195. /**
  91196. * Key light Color (multiply against the R channel of the environement texture)
  91197. */
  91198. _this.primaryColor = BABYLON.Color3.White();
  91199. /**
  91200. * Key light Level (allowing HDR output of the background)
  91201. */
  91202. _this.primaryLevel = 1;
  91203. /**
  91204. * Secondary light Color (multiply against the G channel of the environement texture)
  91205. */
  91206. _this.secondaryColor = BABYLON.Color3.Gray();
  91207. /**
  91208. * Secondary light Level (allowing HDR output of the background)
  91209. */
  91210. _this.secondaryLevel = 1;
  91211. /**
  91212. * Tertiary light Color (multiply against the B channel of the environement texture)
  91213. */
  91214. _this.tertiaryColor = BABYLON.Color3.Black();
  91215. /**
  91216. * Tertiary light Level (allowing HDR output of the background)
  91217. */
  91218. _this.tertiaryLevel = 1;
  91219. /**
  91220. * Reflection Texture used in the material.
  91221. * Should be author in a specific way for the best result (refer to the documentation).
  91222. */
  91223. _this.reflectionTexture = null;
  91224. /**
  91225. * Reflection Texture level of blur.
  91226. *
  91227. * Can be use to reuse an existing HDR Texture and target a specific LOD to prevent authoring the
  91228. * texture twice.
  91229. */
  91230. _this.reflectionBlur = 0;
  91231. /**
  91232. * Diffuse Texture used in the material.
  91233. * Should be author in a specific way for the best result (refer to the documentation).
  91234. */
  91235. _this.diffuseTexture = null;
  91236. _this._shadowLights = null;
  91237. /**
  91238. * Specify the list of lights casting shadow on the material.
  91239. * All scene shadow lights will be included if null.
  91240. */
  91241. _this.shadowLights = null;
  91242. /**
  91243. * For the lights having a blurred shadow generator, this can add a second blur pass in order to reach
  91244. * soft lighting on the background.
  91245. */
  91246. _this.shadowBlurScale = 1;
  91247. /**
  91248. * Helps adjusting the shadow to a softer level if required.
  91249. * 0 means black shadows and 1 means no shadows.
  91250. */
  91251. _this.shadowLevel = 0;
  91252. /**
  91253. * In case of opacity Fresnel or reflection falloff, this is use as a scene center.
  91254. * It is usually zero but might be interesting to modify according to your setup.
  91255. */
  91256. _this.sceneCenter = BABYLON.Vector3.Zero();
  91257. /**
  91258. * This helps specifying that the material is falling off to the sky box at grazing angle.
  91259. * This helps ensuring a nice transition when the camera goes under the ground.
  91260. */
  91261. _this.opacityFresnel = true;
  91262. /**
  91263. * This helps specifying that the material is falling off from diffuse to the reflection texture at grazing angle.
  91264. * This helps adding a mirror texture on the ground.
  91265. */
  91266. _this.reflectionFresnel = false;
  91267. /**
  91268. * This helps specifying the falloff radius off the reflection texture from the sceneCenter.
  91269. * This helps adding a nice falloff effect to the reflection if used as a mirror for instance.
  91270. */
  91271. _this.reflectionFalloffDistance = 0.0;
  91272. /**
  91273. * This specifies the weight of the reflection against the background in case of reflection Fresnel.
  91274. */
  91275. _this.reflectionAmount = 1.0;
  91276. /**
  91277. * This specifies the weight of the reflection at grazing angle.
  91278. */
  91279. _this.reflectionReflectance0 = 0.05;
  91280. /**
  91281. * This specifies the weight of the reflection at a perpendicular point of view.
  91282. */
  91283. _this.reflectionReflectance90 = 0.5;
  91284. /**
  91285. * Helps to directly use the maps channels instead of their level.
  91286. */
  91287. _this.useRGBColor = true;
  91288. /**
  91289. * This helps reducing the banding effect that could occur on the background.
  91290. */
  91291. _this.enableNoise = false;
  91292. _this._fovMultiplier = 1.0;
  91293. /**
  91294. * Enable the FOV adjustment feature controlled by fovMultiplier.
  91295. */
  91296. _this.useEquirectangularFOV = false;
  91297. _this._maxSimultaneousLights = 4;
  91298. /**
  91299. * Number of Simultaneous lights allowed on the material.
  91300. */
  91301. _this.maxSimultaneousLights = 4;
  91302. /**
  91303. * Keep track of the image processing observer to allow dispose and replace.
  91304. */
  91305. _this._imageProcessingObserver = null;
  91306. /**
  91307. * Due to a bug in iOS10, video tags (which are using the background material) are in BGR and not RGB.
  91308. * Setting this flag to true (not done automatically!) will convert it back to RGB.
  91309. */
  91310. _this.switchToBGR = false;
  91311. // Temp values kept as cache in the material.
  91312. _this._renderTargets = new BABYLON.SmartArray(16);
  91313. _this._reflectionControls = BABYLON.Vector4.Zero();
  91314. // Setup the default processing configuration to the scene.
  91315. _this._attachImageProcessingConfiguration(null);
  91316. _this.getRenderTargetTextures = function () {
  91317. _this._renderTargets.reset();
  91318. if (_this._diffuseTexture && _this._diffuseTexture.isRenderTarget) {
  91319. _this._renderTargets.push(_this._diffuseTexture);
  91320. }
  91321. if (_this._reflectionTexture && _this._reflectionTexture.isRenderTarget) {
  91322. _this._renderTargets.push(_this._reflectionTexture);
  91323. }
  91324. return _this._renderTargets;
  91325. };
  91326. return _this;
  91327. }
  91328. Object.defineProperty(BackgroundMaterial.prototype, "reflectionStandardFresnelWeight", {
  91329. /**
  91330. * Sets the reflection reflectance fresnel values according to the default standard
  91331. * empirically know to work well :-)
  91332. */
  91333. set: function (value) {
  91334. var reflectionWeight = value;
  91335. if (reflectionWeight < 0.5) {
  91336. reflectionWeight = reflectionWeight * 2.0;
  91337. this.reflectionReflectance0 = BackgroundMaterial.StandardReflectance0 * reflectionWeight;
  91338. this.reflectionReflectance90 = BackgroundMaterial.StandardReflectance90 * reflectionWeight;
  91339. }
  91340. else {
  91341. reflectionWeight = reflectionWeight * 2.0 - 1.0;
  91342. this.reflectionReflectance0 = BackgroundMaterial.StandardReflectance0 + (1.0 - BackgroundMaterial.StandardReflectance0) * reflectionWeight;
  91343. this.reflectionReflectance90 = BackgroundMaterial.StandardReflectance90 + (1.0 - BackgroundMaterial.StandardReflectance90) * reflectionWeight;
  91344. }
  91345. },
  91346. enumerable: true,
  91347. configurable: true
  91348. });
  91349. Object.defineProperty(BackgroundMaterial.prototype, "fovMultiplier", {
  91350. /**
  91351. * The current fov(field of view) multiplier, 0.0 - 2.0. Defaults to 1.0. Lower values "zoom in" and higher values "zoom out".
  91352. * Best used when trying to implement visual zoom effects like fish-eye or binoculars while not adjusting camera fov.
  91353. * Recommended to be keep at 1.0 except for special cases.
  91354. */
  91355. get: function () {
  91356. return this._fovMultiplier;
  91357. },
  91358. set: function (value) {
  91359. if (isNaN(value)) {
  91360. value = 1.0;
  91361. }
  91362. this._fovMultiplier = Math.max(0.0, Math.min(2.0, value));
  91363. },
  91364. enumerable: true,
  91365. configurable: true
  91366. });
  91367. /**
  91368. * Attaches a new image processing configuration to the PBR Material.
  91369. * @param configuration (if null the scene configuration will be use)
  91370. */
  91371. BackgroundMaterial.prototype._attachImageProcessingConfiguration = function (configuration) {
  91372. var _this = this;
  91373. if (configuration === this._imageProcessingConfiguration) {
  91374. return;
  91375. }
  91376. // Detaches observer.
  91377. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  91378. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  91379. }
  91380. // Pick the scene configuration if needed.
  91381. if (!configuration) {
  91382. this._imageProcessingConfiguration = this.getScene().imageProcessingConfiguration;
  91383. }
  91384. else {
  91385. this._imageProcessingConfiguration = configuration;
  91386. }
  91387. // Attaches observer.
  91388. this._imageProcessingObserver = this._imageProcessingConfiguration.onUpdateParameters.add(function (conf) {
  91389. _this._markAllSubMeshesAsImageProcessingDirty();
  91390. });
  91391. };
  91392. Object.defineProperty(BackgroundMaterial.prototype, "imageProcessingConfiguration", {
  91393. /**
  91394. * Gets the image processing configuration used either in this material.
  91395. */
  91396. get: function () {
  91397. return this._imageProcessingConfiguration;
  91398. },
  91399. /**
  91400. * Sets the Default image processing configuration used either in the this material.
  91401. *
  91402. * If sets to null, the scene one is in use.
  91403. */
  91404. set: function (value) {
  91405. this._attachImageProcessingConfiguration(value);
  91406. // Ensure the effect will be rebuilt.
  91407. this._markAllSubMeshesAsTexturesDirty();
  91408. },
  91409. enumerable: true,
  91410. configurable: true
  91411. });
  91412. Object.defineProperty(BackgroundMaterial.prototype, "cameraColorCurvesEnabled", {
  91413. /**
  91414. * Gets wether the color curves effect is enabled.
  91415. */
  91416. get: function () {
  91417. return this.imageProcessingConfiguration.colorCurvesEnabled;
  91418. },
  91419. /**
  91420. * Sets wether the color curves effect is enabled.
  91421. */
  91422. set: function (value) {
  91423. this.imageProcessingConfiguration.colorCurvesEnabled = value;
  91424. },
  91425. enumerable: true,
  91426. configurable: true
  91427. });
  91428. Object.defineProperty(BackgroundMaterial.prototype, "cameraColorGradingEnabled", {
  91429. /**
  91430. * Gets wether the color grading effect is enabled.
  91431. */
  91432. get: function () {
  91433. return this.imageProcessingConfiguration.colorGradingEnabled;
  91434. },
  91435. /**
  91436. * Gets wether the color grading effect is enabled.
  91437. */
  91438. set: function (value) {
  91439. this.imageProcessingConfiguration.colorGradingEnabled = value;
  91440. },
  91441. enumerable: true,
  91442. configurable: true
  91443. });
  91444. Object.defineProperty(BackgroundMaterial.prototype, "cameraToneMappingEnabled", {
  91445. /**
  91446. * Gets wether tonemapping is enabled or not.
  91447. */
  91448. get: function () {
  91449. return this._imageProcessingConfiguration.toneMappingEnabled;
  91450. },
  91451. /**
  91452. * Sets wether tonemapping is enabled or not
  91453. */
  91454. set: function (value) {
  91455. this._imageProcessingConfiguration.toneMappingEnabled = value;
  91456. },
  91457. enumerable: true,
  91458. configurable: true
  91459. });
  91460. ;
  91461. ;
  91462. Object.defineProperty(BackgroundMaterial.prototype, "cameraExposure", {
  91463. /**
  91464. * The camera exposure used on this material.
  91465. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  91466. * This corresponds to a photographic exposure.
  91467. */
  91468. get: function () {
  91469. return this._imageProcessingConfiguration.exposure;
  91470. },
  91471. /**
  91472. * The camera exposure used on this material.
  91473. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  91474. * This corresponds to a photographic exposure.
  91475. */
  91476. set: function (value) {
  91477. this._imageProcessingConfiguration.exposure = value;
  91478. },
  91479. enumerable: true,
  91480. configurable: true
  91481. });
  91482. ;
  91483. ;
  91484. Object.defineProperty(BackgroundMaterial.prototype, "cameraContrast", {
  91485. /**
  91486. * Gets The camera contrast used on this material.
  91487. */
  91488. get: function () {
  91489. return this._imageProcessingConfiguration.contrast;
  91490. },
  91491. /**
  91492. * Sets The camera contrast used on this material.
  91493. */
  91494. set: function (value) {
  91495. this._imageProcessingConfiguration.contrast = value;
  91496. },
  91497. enumerable: true,
  91498. configurable: true
  91499. });
  91500. Object.defineProperty(BackgroundMaterial.prototype, "cameraColorGradingTexture", {
  91501. /**
  91502. * Gets the Color Grading 2D Lookup Texture.
  91503. */
  91504. get: function () {
  91505. return this._imageProcessingConfiguration.colorGradingTexture;
  91506. },
  91507. /**
  91508. * Sets the Color Grading 2D Lookup Texture.
  91509. */
  91510. set: function (value) {
  91511. this.imageProcessingConfiguration.colorGradingTexture = value;
  91512. },
  91513. enumerable: true,
  91514. configurable: true
  91515. });
  91516. Object.defineProperty(BackgroundMaterial.prototype, "cameraColorCurves", {
  91517. /**
  91518. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  91519. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  91520. * 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;
  91521. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  91522. */
  91523. get: function () {
  91524. return this.imageProcessingConfiguration.colorCurves;
  91525. },
  91526. /**
  91527. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  91528. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  91529. * 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;
  91530. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  91531. */
  91532. set: function (value) {
  91533. this.imageProcessingConfiguration.colorCurves = value;
  91534. },
  91535. enumerable: true,
  91536. configurable: true
  91537. });
  91538. /**
  91539. * The entire material has been created in order to prevent overdraw.
  91540. * @returns false
  91541. */
  91542. BackgroundMaterial.prototype.needAlphaTesting = function () {
  91543. return true;
  91544. };
  91545. /**
  91546. * The entire material has been created in order to prevent overdraw.
  91547. * @returns true if blending is enable
  91548. */
  91549. BackgroundMaterial.prototype.needAlphaBlending = function () {
  91550. return ((this.alpha < 0) || (this._diffuseTexture != null && this._diffuseTexture.hasAlpha));
  91551. };
  91552. /**
  91553. * Checks wether the material is ready to be rendered for a given mesh.
  91554. * @param mesh The mesh to render
  91555. * @param subMesh The submesh to check against
  91556. * @param useInstances Specify wether or not the material is used with instances
  91557. * @returns true if all the dependencies are ready (Textures, Effects...)
  91558. */
  91559. BackgroundMaterial.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  91560. var _this = this;
  91561. if (useInstances === void 0) { useInstances = false; }
  91562. if (subMesh.effect && this.isFrozen) {
  91563. if (this._wasPreviouslyReady) {
  91564. return true;
  91565. }
  91566. }
  91567. if (!subMesh._materialDefines) {
  91568. subMesh._materialDefines = new BackgroundMaterialDefines();
  91569. }
  91570. var scene = this.getScene();
  91571. var defines = subMesh._materialDefines;
  91572. if (!this.checkReadyOnEveryCall && subMesh.effect) {
  91573. if (defines._renderId === scene.getRenderId()) {
  91574. return true;
  91575. }
  91576. }
  91577. var engine = scene.getEngine();
  91578. // Lights
  91579. BABYLON.MaterialHelper.PrepareDefinesForLights(scene, mesh, defines, false, this._maxSimultaneousLights);
  91580. defines._needNormals = true;
  91581. // Textures
  91582. if (defines._areTexturesDirty) {
  91583. defines._needUVs = false;
  91584. if (scene.texturesEnabled) {
  91585. if (scene.getEngine().getCaps().textureLOD) {
  91586. defines.TEXTURELODSUPPORT = true;
  91587. }
  91588. if (this._diffuseTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  91589. if (!this._diffuseTexture.isReadyOrNotBlocking()) {
  91590. return false;
  91591. }
  91592. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._diffuseTexture, defines, "DIFFUSE");
  91593. defines.DIFFUSEHASALPHA = this._diffuseTexture.hasAlpha;
  91594. defines.GAMMADIFFUSE = this._diffuseTexture.gammaSpace;
  91595. defines.OPACITYFRESNEL = this._opacityFresnel;
  91596. }
  91597. else {
  91598. defines.DIFFUSE = false;
  91599. defines.DIFFUSEHASALPHA = false;
  91600. defines.GAMMADIFFUSE = false;
  91601. defines.OPACITYFRESNEL = false;
  91602. }
  91603. var reflectionTexture = this._reflectionTexture;
  91604. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  91605. if (!reflectionTexture.isReadyOrNotBlocking()) {
  91606. return false;
  91607. }
  91608. defines.REFLECTION = true;
  91609. defines.GAMMAREFLECTION = reflectionTexture.gammaSpace;
  91610. defines.REFLECTIONBLUR = this._reflectionBlur > 0;
  91611. defines.REFLECTIONMAP_OPPOSITEZ = this.getScene().useRightHandedSystem ? !reflectionTexture.invertZ : reflectionTexture.invertZ;
  91612. defines.LODINREFLECTIONALPHA = reflectionTexture.lodLevelInAlpha;
  91613. defines.EQUIRECTANGULAR_RELFECTION_FOV = this.useEquirectangularFOV;
  91614. defines.REFLECTIONBGR = this.switchToBGR;
  91615. if (reflectionTexture.coordinatesMode === BABYLON.Texture.INVCUBIC_MODE) {
  91616. defines.INVERTCUBICMAP = true;
  91617. }
  91618. defines.REFLECTIONMAP_3D = reflectionTexture.isCube;
  91619. switch (reflectionTexture.coordinatesMode) {
  91620. case BABYLON.Texture.CUBIC_MODE:
  91621. case BABYLON.Texture.INVCUBIC_MODE:
  91622. defines.REFLECTIONMAP_CUBIC = true;
  91623. break;
  91624. case BABYLON.Texture.EXPLICIT_MODE:
  91625. defines.REFLECTIONMAP_EXPLICIT = true;
  91626. break;
  91627. case BABYLON.Texture.PLANAR_MODE:
  91628. defines.REFLECTIONMAP_PLANAR = true;
  91629. break;
  91630. case BABYLON.Texture.PROJECTION_MODE:
  91631. defines.REFLECTIONMAP_PROJECTION = true;
  91632. break;
  91633. case BABYLON.Texture.SKYBOX_MODE:
  91634. defines.REFLECTIONMAP_SKYBOX = true;
  91635. break;
  91636. case BABYLON.Texture.SPHERICAL_MODE:
  91637. defines.REFLECTIONMAP_SPHERICAL = true;
  91638. break;
  91639. case BABYLON.Texture.EQUIRECTANGULAR_MODE:
  91640. defines.REFLECTIONMAP_EQUIRECTANGULAR = true;
  91641. break;
  91642. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MODE:
  91643. defines.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = true;
  91644. break;
  91645. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE:
  91646. defines.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = true;
  91647. break;
  91648. }
  91649. if (this.reflectionFresnel) {
  91650. defines.REFLECTIONFRESNEL = true;
  91651. defines.REFLECTIONFALLOFF = this.reflectionFalloffDistance > 0;
  91652. this._reflectionControls.x = this.reflectionAmount;
  91653. this._reflectionControls.y = this.reflectionReflectance0;
  91654. this._reflectionControls.z = this.reflectionReflectance90;
  91655. this._reflectionControls.w = 1 / this.reflectionFalloffDistance;
  91656. }
  91657. else {
  91658. defines.REFLECTIONFRESNEL = false;
  91659. defines.REFLECTIONFALLOFF = false;
  91660. }
  91661. }
  91662. else {
  91663. defines.REFLECTION = false;
  91664. defines.REFLECTIONFALLOFF = false;
  91665. defines.REFLECTIONBLUR = false;
  91666. defines.REFLECTIONMAP_3D = false;
  91667. defines.REFLECTIONMAP_SPHERICAL = false;
  91668. defines.REFLECTIONMAP_PLANAR = false;
  91669. defines.REFLECTIONMAP_CUBIC = false;
  91670. defines.REFLECTIONMAP_PROJECTION = false;
  91671. defines.REFLECTIONMAP_SKYBOX = false;
  91672. defines.REFLECTIONMAP_EXPLICIT = false;
  91673. defines.REFLECTIONMAP_EQUIRECTANGULAR = false;
  91674. defines.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  91675. defines.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  91676. defines.INVERTCUBICMAP = false;
  91677. defines.REFLECTIONMAP_OPPOSITEZ = false;
  91678. defines.LODINREFLECTIONALPHA = false;
  91679. defines.GAMMAREFLECTION = false;
  91680. }
  91681. }
  91682. defines.PREMULTIPLYALPHA = (this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED || this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED_PORTERDUFF);
  91683. defines.USERGBCOLOR = this._useRGBColor;
  91684. defines.NOISE = this._enableNoise;
  91685. }
  91686. if (defines._areImageProcessingDirty) {
  91687. if (!this._imageProcessingConfiguration.isReady()) {
  91688. return false;
  91689. }
  91690. this._imageProcessingConfiguration.prepareDefines(defines);
  91691. }
  91692. // Misc.
  91693. BABYLON.MaterialHelper.PrepareDefinesForMisc(mesh, scene, false, this.pointsCloud, this.fogEnabled, this._shouldTurnAlphaTestOn(mesh), defines);
  91694. // Values that need to be evaluated on every frame
  91695. BABYLON.MaterialHelper.PrepareDefinesForFrameBoundValues(scene, engine, defines, useInstances);
  91696. // Attribs
  91697. if (BABYLON.MaterialHelper.PrepareDefinesForAttributes(mesh, defines, false, true, false)) {
  91698. if (mesh) {
  91699. if (!scene.getEngine().getCaps().standardDerivatives && !mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  91700. mesh.createNormals(true);
  91701. BABYLON.Tools.Warn("BackgroundMaterial: Normals have been created for the mesh: " + mesh.name);
  91702. }
  91703. }
  91704. }
  91705. // Get correct effect
  91706. if (defines.isDirty) {
  91707. defines.markAsProcessed();
  91708. scene.resetCachedMaterial();
  91709. // Fallbacks
  91710. var fallbacks = new BABYLON.EffectFallbacks();
  91711. if (defines.FOG) {
  91712. fallbacks.addFallback(0, "FOG");
  91713. }
  91714. if (defines.POINTSIZE) {
  91715. fallbacks.addFallback(1, "POINTSIZE");
  91716. }
  91717. BABYLON.MaterialHelper.HandleFallbacksForShadows(defines, fallbacks, this._maxSimultaneousLights);
  91718. if (defines.NUM_BONE_INFLUENCERS > 0) {
  91719. fallbacks.addCPUSkinningFallback(0, mesh);
  91720. }
  91721. //Attributes
  91722. var attribs = [BABYLON.VertexBuffer.PositionKind];
  91723. if (defines.NORMAL) {
  91724. attribs.push(BABYLON.VertexBuffer.NormalKind);
  91725. }
  91726. if (defines.UV1) {
  91727. attribs.push(BABYLON.VertexBuffer.UVKind);
  91728. }
  91729. if (defines.UV2) {
  91730. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  91731. }
  91732. BABYLON.MaterialHelper.PrepareAttributesForBones(attribs, mesh, defines, fallbacks);
  91733. BABYLON.MaterialHelper.PrepareAttributesForInstances(attribs, defines);
  91734. var uniforms = ["world", "view", "viewProjection", "vEyePosition", "vLightsType",
  91735. "vFogInfos", "vFogColor", "pointSize",
  91736. "vClipPlane", "mBones",
  91737. "vPrimaryColor", "vSecondaryColor", "vTertiaryColor",
  91738. "vReflectionInfos", "reflectionMatrix", "vReflectionMicrosurfaceInfos", "fFovMultiplier",
  91739. "shadowLevel", "alpha",
  91740. "vBackgroundCenter", "vReflectionControl",
  91741. "vDiffuseInfos", "diffuseMatrix",
  91742. ];
  91743. var samplers = ["diffuseSampler", "reflectionSampler", "reflectionSamplerLow", "reflectionSamplerHigh"];
  91744. var uniformBuffers = ["Material", "Scene"];
  91745. BABYLON.ImageProcessingConfiguration.PrepareUniforms(uniforms, defines);
  91746. BABYLON.ImageProcessingConfiguration.PrepareSamplers(samplers, defines);
  91747. BABYLON.MaterialHelper.PrepareUniformsAndSamplersList({
  91748. uniformsNames: uniforms,
  91749. uniformBuffersNames: uniformBuffers,
  91750. samplers: samplers,
  91751. defines: defines,
  91752. maxSimultaneousLights: this._maxSimultaneousLights
  91753. });
  91754. var onCompiled = function (effect) {
  91755. if (_this.onCompiled) {
  91756. _this.onCompiled(effect);
  91757. }
  91758. _this.bindSceneUniformBuffer(effect, scene.getSceneUniformBuffer());
  91759. };
  91760. var join = defines.toString();
  91761. subMesh.setEffect(scene.getEngine().createEffect("background", {
  91762. attributes: attribs,
  91763. uniformsNames: uniforms,
  91764. uniformBuffersNames: uniformBuffers,
  91765. samplers: samplers,
  91766. defines: join,
  91767. fallbacks: fallbacks,
  91768. onCompiled: onCompiled,
  91769. onError: this.onError,
  91770. indexParameters: { maxSimultaneousLights: this._maxSimultaneousLights }
  91771. }, engine), defines);
  91772. this.buildUniformLayout();
  91773. }
  91774. if (!subMesh.effect || !subMesh.effect.isReady()) {
  91775. return false;
  91776. }
  91777. defines._renderId = scene.getRenderId();
  91778. this._wasPreviouslyReady = true;
  91779. return true;
  91780. };
  91781. /**
  91782. * Build the uniform buffer used in the material.
  91783. */
  91784. BackgroundMaterial.prototype.buildUniformLayout = function () {
  91785. // Order is important !
  91786. this._uniformBuffer.addUniform("vPrimaryColor", 4);
  91787. this._uniformBuffer.addUniform("vSecondaryColor", 4);
  91788. this._uniformBuffer.addUniform("vTertiaryColor", 4);
  91789. this._uniformBuffer.addUniform("vDiffuseInfos", 2);
  91790. this._uniformBuffer.addUniform("vReflectionInfos", 2);
  91791. this._uniformBuffer.addUniform("diffuseMatrix", 16);
  91792. this._uniformBuffer.addUniform("reflectionMatrix", 16);
  91793. this._uniformBuffer.addUniform("vReflectionMicrosurfaceInfos", 3);
  91794. this._uniformBuffer.addUniform("fFovMultiplier", 1);
  91795. this._uniformBuffer.addUniform("pointSize", 1);
  91796. this._uniformBuffer.addUniform("shadowLevel", 1);
  91797. this._uniformBuffer.addUniform("alpha", 1);
  91798. this._uniformBuffer.addUniform("vBackgroundCenter", 3);
  91799. this._uniformBuffer.addUniform("vReflectionControl", 4);
  91800. this._uniformBuffer.create();
  91801. };
  91802. /**
  91803. * Unbind the material.
  91804. */
  91805. BackgroundMaterial.prototype.unbind = function () {
  91806. if (this._diffuseTexture && this._diffuseTexture.isRenderTarget) {
  91807. this._uniformBuffer.setTexture("diffuseSampler", null);
  91808. }
  91809. if (this._reflectionTexture && this._reflectionTexture.isRenderTarget) {
  91810. this._uniformBuffer.setTexture("reflectionSampler", null);
  91811. }
  91812. _super.prototype.unbind.call(this);
  91813. };
  91814. /**
  91815. * Bind only the world matrix to the material.
  91816. * @param world The world matrix to bind.
  91817. */
  91818. BackgroundMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  91819. this._activeEffect.setMatrix("world", world);
  91820. };
  91821. /**
  91822. * Bind the material for a dedicated submeh (every used meshes will be considered opaque).
  91823. * @param world The world matrix to bind.
  91824. * @param subMesh The submesh to bind for.
  91825. */
  91826. BackgroundMaterial.prototype.bindForSubMesh = function (world, mesh, subMesh) {
  91827. var scene = this.getScene();
  91828. var defines = subMesh._materialDefines;
  91829. if (!defines) {
  91830. return;
  91831. }
  91832. var effect = subMesh.effect;
  91833. if (!effect) {
  91834. return;
  91835. }
  91836. this._activeEffect = effect;
  91837. // Matrices
  91838. this.bindOnlyWorldMatrix(world);
  91839. // Bones
  91840. BABYLON.MaterialHelper.BindBonesParameters(mesh, this._activeEffect);
  91841. var mustRebind = this._mustRebind(scene, effect, mesh.visibility);
  91842. if (mustRebind) {
  91843. this._uniformBuffer.bindToEffect(effect, "Material");
  91844. this.bindViewProjection(effect);
  91845. var reflectionTexture = this._reflectionTexture;
  91846. if (!this._uniformBuffer.useUbo || !this.isFrozen || !this._uniformBuffer.isSync) {
  91847. // Texture uniforms
  91848. if (scene.texturesEnabled) {
  91849. if (this._diffuseTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  91850. this._uniformBuffer.updateFloat2("vDiffuseInfos", this._diffuseTexture.coordinatesIndex, this._diffuseTexture.level);
  91851. BABYLON.MaterialHelper.BindTextureMatrix(this._diffuseTexture, this._uniformBuffer, "diffuse");
  91852. }
  91853. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  91854. this._uniformBuffer.updateMatrix("reflectionMatrix", reflectionTexture.getReflectionTextureMatrix());
  91855. this._uniformBuffer.updateFloat2("vReflectionInfos", reflectionTexture.level, this._reflectionBlur);
  91856. this._uniformBuffer.updateFloat3("vReflectionMicrosurfaceInfos", reflectionTexture.getSize().width, reflectionTexture.lodGenerationScale, reflectionTexture.lodGenerationOffset);
  91857. }
  91858. }
  91859. if (this.shadowLevel > 0) {
  91860. this._uniformBuffer.updateFloat("shadowLevel", this.shadowLevel);
  91861. }
  91862. this._uniformBuffer.updateFloat("alpha", this.alpha);
  91863. // Point size
  91864. if (this.pointsCloud) {
  91865. this._uniformBuffer.updateFloat("pointSize", this.pointSize);
  91866. }
  91867. this._uniformBuffer.updateColor4("vPrimaryColor", this._primaryColor, this._primaryLevel);
  91868. this._uniformBuffer.updateColor4("vSecondaryColor", this._secondaryColor, this._secondaryLevel);
  91869. this._uniformBuffer.updateColor4("vTertiaryColor", this._tertiaryColor, this._tertiaryLevel);
  91870. }
  91871. this._uniformBuffer.updateFloat("fFovMultiplier", this._fovMultiplier);
  91872. // Textures
  91873. if (scene.texturesEnabled) {
  91874. if (this._diffuseTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  91875. this._uniformBuffer.setTexture("diffuseSampler", this._diffuseTexture);
  91876. }
  91877. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  91878. if (defines.REFLECTIONBLUR && defines.TEXTURELODSUPPORT) {
  91879. this._uniformBuffer.setTexture("reflectionSampler", reflectionTexture);
  91880. }
  91881. else if (!defines.REFLECTIONBLUR) {
  91882. this._uniformBuffer.setTexture("reflectionSampler", reflectionTexture);
  91883. }
  91884. else {
  91885. this._uniformBuffer.setTexture("reflectionSampler", reflectionTexture._lodTextureMid || reflectionTexture);
  91886. this._uniformBuffer.setTexture("reflectionSamplerLow", reflectionTexture._lodTextureLow || reflectionTexture);
  91887. this._uniformBuffer.setTexture("reflectionSamplerHigh", reflectionTexture._lodTextureHigh || reflectionTexture);
  91888. }
  91889. if (defines.REFLECTIONFRESNEL) {
  91890. this._uniformBuffer.updateFloat3("vBackgroundCenter", this.sceneCenter.x, this.sceneCenter.y, this.sceneCenter.z);
  91891. this._uniformBuffer.updateFloat4("vReflectionControl", this._reflectionControls.x, this._reflectionControls.y, this._reflectionControls.z, this._reflectionControls.w);
  91892. }
  91893. }
  91894. }
  91895. // Clip plane
  91896. BABYLON.MaterialHelper.BindClipPlane(this._activeEffect, scene);
  91897. BABYLON.MaterialHelper.BindEyePosition(effect, scene);
  91898. }
  91899. if (mustRebind || !this.isFrozen) {
  91900. if (scene.lightsEnabled) {
  91901. BABYLON.MaterialHelper.BindLights(scene, mesh, this._activeEffect, defines, this._maxSimultaneousLights, false);
  91902. }
  91903. // View
  91904. this.bindView(effect);
  91905. // Fog
  91906. BABYLON.MaterialHelper.BindFogParameters(scene, mesh, this._activeEffect);
  91907. // image processing
  91908. this._imageProcessingConfiguration.bind(this._activeEffect);
  91909. }
  91910. this._uniformBuffer.update();
  91911. this._afterBind(mesh);
  91912. };
  91913. /**
  91914. * Dispose the material.
  91915. * @param forceDisposeEffect Force disposal of the associated effect.
  91916. * @param forceDisposeTextures Force disposal of the associated textures.
  91917. */
  91918. BackgroundMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  91919. if (forceDisposeEffect === void 0) { forceDisposeEffect = false; }
  91920. if (forceDisposeTextures === void 0) { forceDisposeTextures = false; }
  91921. if (forceDisposeTextures) {
  91922. if (this.diffuseTexture) {
  91923. this.diffuseTexture.dispose();
  91924. }
  91925. if (this.reflectionTexture) {
  91926. this.reflectionTexture.dispose();
  91927. }
  91928. }
  91929. this._renderTargets.dispose();
  91930. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  91931. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  91932. }
  91933. _super.prototype.dispose.call(this, forceDisposeEffect);
  91934. };
  91935. /**
  91936. * Clones the material.
  91937. * @param name The cloned name.
  91938. * @returns The cloned material.
  91939. */
  91940. BackgroundMaterial.prototype.clone = function (name) {
  91941. var _this = this;
  91942. return BABYLON.SerializationHelper.Clone(function () { return new BackgroundMaterial(name, _this.getScene()); }, this);
  91943. };
  91944. /**
  91945. * Serializes the current material to its JSON representation.
  91946. * @returns The JSON representation.
  91947. */
  91948. BackgroundMaterial.prototype.serialize = function () {
  91949. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  91950. serializationObject.customType = "BABYLON.BackgroundMaterial";
  91951. return serializationObject;
  91952. };
  91953. /**
  91954. * Gets the class name of the material
  91955. * @returns "BackgroundMaterial"
  91956. */
  91957. BackgroundMaterial.prototype.getClassName = function () {
  91958. return "BackgroundMaterial";
  91959. };
  91960. /**
  91961. * Parse a JSON input to create back a background material.
  91962. * @param source The JSON data to parse
  91963. * @param scene The scene to create the parsed material in
  91964. * @param rootUrl The root url of the assets the material depends upon
  91965. * @returns the instantiated BackgroundMaterial.
  91966. */
  91967. BackgroundMaterial.Parse = function (source, scene, rootUrl) {
  91968. return BABYLON.SerializationHelper.Parse(function () { return new BackgroundMaterial(source.name, scene); }, source, scene, rootUrl);
  91969. };
  91970. /**
  91971. * Standard reflectance value at parallel view angle.
  91972. */
  91973. BackgroundMaterial.StandardReflectance0 = 0.05;
  91974. /**
  91975. * Standard reflectance value at grazing angle.
  91976. */
  91977. BackgroundMaterial.StandardReflectance90 = 0.5;
  91978. __decorate([
  91979. BABYLON.serializeAsColor3()
  91980. ], BackgroundMaterial.prototype, "_primaryColor", void 0);
  91981. __decorate([
  91982. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  91983. ], BackgroundMaterial.prototype, "primaryColor", void 0);
  91984. __decorate([
  91985. BABYLON.serialize()
  91986. ], BackgroundMaterial.prototype, "_primaryLevel", void 0);
  91987. __decorate([
  91988. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  91989. ], BackgroundMaterial.prototype, "primaryLevel", void 0);
  91990. __decorate([
  91991. BABYLON.serializeAsColor3()
  91992. ], BackgroundMaterial.prototype, "_secondaryColor", void 0);
  91993. __decorate([
  91994. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  91995. ], BackgroundMaterial.prototype, "secondaryColor", void 0);
  91996. __decorate([
  91997. BABYLON.serialize()
  91998. ], BackgroundMaterial.prototype, "_secondaryLevel", void 0);
  91999. __decorate([
  92000. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  92001. ], BackgroundMaterial.prototype, "secondaryLevel", void 0);
  92002. __decorate([
  92003. BABYLON.serializeAsColor3()
  92004. ], BackgroundMaterial.prototype, "_tertiaryColor", void 0);
  92005. __decorate([
  92006. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  92007. ], BackgroundMaterial.prototype, "tertiaryColor", void 0);
  92008. __decorate([
  92009. BABYLON.serialize()
  92010. ], BackgroundMaterial.prototype, "_tertiaryLevel", void 0);
  92011. __decorate([
  92012. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  92013. ], BackgroundMaterial.prototype, "tertiaryLevel", void 0);
  92014. __decorate([
  92015. BABYLON.serializeAsTexture()
  92016. ], BackgroundMaterial.prototype, "_reflectionTexture", void 0);
  92017. __decorate([
  92018. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  92019. ], BackgroundMaterial.prototype, "reflectionTexture", void 0);
  92020. __decorate([
  92021. BABYLON.serialize()
  92022. ], BackgroundMaterial.prototype, "_reflectionBlur", void 0);
  92023. __decorate([
  92024. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  92025. ], BackgroundMaterial.prototype, "reflectionBlur", void 0);
  92026. __decorate([
  92027. BABYLON.serializeAsTexture()
  92028. ], BackgroundMaterial.prototype, "_diffuseTexture", void 0);
  92029. __decorate([
  92030. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  92031. ], BackgroundMaterial.prototype, "diffuseTexture", void 0);
  92032. __decorate([
  92033. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  92034. ], BackgroundMaterial.prototype, "shadowLights", void 0);
  92035. __decorate([
  92036. BABYLON.serialize()
  92037. ], BackgroundMaterial.prototype, "_shadowBlurScale", void 0);
  92038. __decorate([
  92039. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  92040. ], BackgroundMaterial.prototype, "shadowBlurScale", void 0);
  92041. __decorate([
  92042. BABYLON.serialize()
  92043. ], BackgroundMaterial.prototype, "_shadowLevel", void 0);
  92044. __decorate([
  92045. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  92046. ], BackgroundMaterial.prototype, "shadowLevel", void 0);
  92047. __decorate([
  92048. BABYLON.serializeAsVector3()
  92049. ], BackgroundMaterial.prototype, "_sceneCenter", void 0);
  92050. __decorate([
  92051. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  92052. ], BackgroundMaterial.prototype, "sceneCenter", void 0);
  92053. __decorate([
  92054. BABYLON.serialize()
  92055. ], BackgroundMaterial.prototype, "_opacityFresnel", void 0);
  92056. __decorate([
  92057. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  92058. ], BackgroundMaterial.prototype, "opacityFresnel", void 0);
  92059. __decorate([
  92060. BABYLON.serialize()
  92061. ], BackgroundMaterial.prototype, "_reflectionFresnel", void 0);
  92062. __decorate([
  92063. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  92064. ], BackgroundMaterial.prototype, "reflectionFresnel", void 0);
  92065. __decorate([
  92066. BABYLON.serialize()
  92067. ], BackgroundMaterial.prototype, "_reflectionFalloffDistance", void 0);
  92068. __decorate([
  92069. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  92070. ], BackgroundMaterial.prototype, "reflectionFalloffDistance", void 0);
  92071. __decorate([
  92072. BABYLON.serialize()
  92073. ], BackgroundMaterial.prototype, "_reflectionAmount", void 0);
  92074. __decorate([
  92075. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  92076. ], BackgroundMaterial.prototype, "reflectionAmount", void 0);
  92077. __decorate([
  92078. BABYLON.serialize()
  92079. ], BackgroundMaterial.prototype, "_reflectionReflectance0", void 0);
  92080. __decorate([
  92081. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  92082. ], BackgroundMaterial.prototype, "reflectionReflectance0", void 0);
  92083. __decorate([
  92084. BABYLON.serialize()
  92085. ], BackgroundMaterial.prototype, "_reflectionReflectance90", void 0);
  92086. __decorate([
  92087. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  92088. ], BackgroundMaterial.prototype, "reflectionReflectance90", void 0);
  92089. __decorate([
  92090. BABYLON.serialize()
  92091. ], BackgroundMaterial.prototype, "_useRGBColor", void 0);
  92092. __decorate([
  92093. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  92094. ], BackgroundMaterial.prototype, "useRGBColor", void 0);
  92095. __decorate([
  92096. BABYLON.serialize()
  92097. ], BackgroundMaterial.prototype, "_enableNoise", void 0);
  92098. __decorate([
  92099. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  92100. ], BackgroundMaterial.prototype, "enableNoise", void 0);
  92101. __decorate([
  92102. BABYLON.serialize()
  92103. ], BackgroundMaterial.prototype, "_maxSimultaneousLights", void 0);
  92104. __decorate([
  92105. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  92106. ], BackgroundMaterial.prototype, "maxSimultaneousLights", void 0);
  92107. __decorate([
  92108. BABYLON.serializeAsImageProcessingConfiguration()
  92109. ], BackgroundMaterial.prototype, "_imageProcessingConfiguration", void 0);
  92110. return BackgroundMaterial;
  92111. }(BABYLON.PushMaterial));
  92112. BABYLON.BackgroundMaterial = BackgroundMaterial;
  92113. })(BABYLON || (BABYLON = {}));
  92114. //# sourceMappingURL=babylon.backgroundMaterial.js.map
  92115. "use strict";
  92116. var __assign = (this && this.__assign) || Object.assign || function(t) {
  92117. for (var s, i = 1, n = arguments.length; i < n; i++) {
  92118. s = arguments[i];
  92119. for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
  92120. t[p] = s[p];
  92121. }
  92122. return t;
  92123. };
  92124. var BABYLON;
  92125. (function (BABYLON) {
  92126. /**
  92127. * The Environment helper class can be used to add a fully featuread none expensive background to your scene.
  92128. * It includes by default a skybox and a ground relying on the BackgroundMaterial.
  92129. * It also helps with the default setup of your imageProcessing configuration.
  92130. */
  92131. var EnvironmentHelper = /** @class */ (function () {
  92132. /**
  92133. * constructor
  92134. * @param options
  92135. * @param scene The scene to add the material to
  92136. */
  92137. function EnvironmentHelper(options, scene) {
  92138. var _this = this;
  92139. this._errorHandler = function (message, exception) {
  92140. _this.onErrorObservable.notifyObservers({ message: message, exception: exception });
  92141. };
  92142. this._options = __assign({}, EnvironmentHelper._getDefaultOptions(), options);
  92143. this._scene = scene;
  92144. this.onErrorObservable = new BABYLON.Observable();
  92145. this._setupBackground();
  92146. this._setupImageProcessing();
  92147. }
  92148. /**
  92149. * Creates the default options for the helper.
  92150. */
  92151. EnvironmentHelper._getDefaultOptions = function () {
  92152. return {
  92153. createGround: true,
  92154. groundSize: 15,
  92155. groundTexture: this._groundTextureCDNUrl,
  92156. groundColor: new BABYLON.Color3(0.2, 0.2, 0.3).toLinearSpace().scale(3),
  92157. groundOpacity: 0.9,
  92158. enableGroundShadow: true,
  92159. groundShadowLevel: 0.5,
  92160. enableGroundMirror: false,
  92161. groundMirrorSizeRatio: 0.3,
  92162. groundMirrorBlurKernel: 64,
  92163. groundMirrorAmount: 1,
  92164. groundMirrorFresnelWeight: 1,
  92165. groundMirrorFallOffDistance: 0,
  92166. groundMirrorTextureType: BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT,
  92167. groundYBias: 0.00001,
  92168. createSkybox: true,
  92169. skyboxSize: 20,
  92170. skyboxTexture: this._skyboxTextureCDNUrl,
  92171. skyboxColor: new BABYLON.Color3(0.2, 0.2, 0.3).toLinearSpace().scale(3),
  92172. backgroundYRotation: 0,
  92173. sizeAuto: true,
  92174. rootPosition: BABYLON.Vector3.Zero(),
  92175. setupImageProcessing: true,
  92176. environmentTexture: this._environmentTextureCDNUrl,
  92177. cameraExposure: 0.8,
  92178. cameraContrast: 1.2,
  92179. toneMappingEnabled: true,
  92180. };
  92181. };
  92182. Object.defineProperty(EnvironmentHelper.prototype, "rootMesh", {
  92183. /**
  92184. * Gets the root mesh created by the helper.
  92185. */
  92186. get: function () {
  92187. return this._rootMesh;
  92188. },
  92189. enumerable: true,
  92190. configurable: true
  92191. });
  92192. Object.defineProperty(EnvironmentHelper.prototype, "skybox", {
  92193. /**
  92194. * Gets the skybox created by the helper.
  92195. */
  92196. get: function () {
  92197. return this._skybox;
  92198. },
  92199. enumerable: true,
  92200. configurable: true
  92201. });
  92202. Object.defineProperty(EnvironmentHelper.prototype, "skyboxTexture", {
  92203. /**
  92204. * Gets the skybox texture created by the helper.
  92205. */
  92206. get: function () {
  92207. return this._skyboxTexture;
  92208. },
  92209. enumerable: true,
  92210. configurable: true
  92211. });
  92212. Object.defineProperty(EnvironmentHelper.prototype, "skyboxMaterial", {
  92213. /**
  92214. * Gets the skybox material created by the helper.
  92215. */
  92216. get: function () {
  92217. return this._skyboxMaterial;
  92218. },
  92219. enumerable: true,
  92220. configurable: true
  92221. });
  92222. Object.defineProperty(EnvironmentHelper.prototype, "ground", {
  92223. /**
  92224. * Gets the ground mesh created by the helper.
  92225. */
  92226. get: function () {
  92227. return this._ground;
  92228. },
  92229. enumerable: true,
  92230. configurable: true
  92231. });
  92232. Object.defineProperty(EnvironmentHelper.prototype, "groundTexture", {
  92233. /**
  92234. * Gets the ground texture created by the helper.
  92235. */
  92236. get: function () {
  92237. return this._groundTexture;
  92238. },
  92239. enumerable: true,
  92240. configurable: true
  92241. });
  92242. Object.defineProperty(EnvironmentHelper.prototype, "groundMirror", {
  92243. /**
  92244. * Gets the ground mirror created by the helper.
  92245. */
  92246. get: function () {
  92247. return this._groundMirror;
  92248. },
  92249. enumerable: true,
  92250. configurable: true
  92251. });
  92252. Object.defineProperty(EnvironmentHelper.prototype, "groundMirrorRenderList", {
  92253. /**
  92254. * Gets the ground mirror render list to helps pushing the meshes
  92255. * you wish in the ground reflection.
  92256. */
  92257. get: function () {
  92258. if (this._groundMirror) {
  92259. return this._groundMirror.renderList;
  92260. }
  92261. return null;
  92262. },
  92263. enumerable: true,
  92264. configurable: true
  92265. });
  92266. Object.defineProperty(EnvironmentHelper.prototype, "groundMaterial", {
  92267. /**
  92268. * Gets the ground material created by the helper.
  92269. */
  92270. get: function () {
  92271. return this._groundMaterial;
  92272. },
  92273. enumerable: true,
  92274. configurable: true
  92275. });
  92276. /**
  92277. * Updates the background according to the new options
  92278. * @param options
  92279. */
  92280. EnvironmentHelper.prototype.updateOptions = function (options) {
  92281. var newOptions = __assign({}, this._options, options);
  92282. if (this._ground && !newOptions.createGround) {
  92283. this._ground.dispose();
  92284. this._ground = null;
  92285. }
  92286. if (this._groundMaterial && !newOptions.createGround) {
  92287. this._groundMaterial.dispose();
  92288. this._groundMaterial = null;
  92289. }
  92290. if (this._groundTexture) {
  92291. if (this._options.groundTexture != newOptions.groundTexture) {
  92292. this._groundTexture.dispose();
  92293. this._groundTexture = null;
  92294. }
  92295. }
  92296. if (this._skybox && !newOptions.createSkybox) {
  92297. this._skybox.dispose();
  92298. this._skybox = null;
  92299. }
  92300. if (this._skyboxMaterial && !newOptions.createSkybox) {
  92301. this._skyboxMaterial.dispose();
  92302. this._skyboxMaterial = null;
  92303. }
  92304. if (this._skyboxTexture) {
  92305. if (this._options.skyboxTexture != newOptions.skyboxTexture) {
  92306. this._skyboxTexture.dispose();
  92307. this._skyboxTexture = null;
  92308. }
  92309. }
  92310. if (this._groundMirror && !newOptions.enableGroundMirror) {
  92311. this._groundMirror.dispose();
  92312. this._groundMirror = null;
  92313. }
  92314. if (this._scene.environmentTexture) {
  92315. if (this._options.environmentTexture != newOptions.environmentTexture) {
  92316. this._scene.environmentTexture.dispose();
  92317. }
  92318. }
  92319. this._options = newOptions;
  92320. this._setupBackground();
  92321. this._setupImageProcessing();
  92322. };
  92323. /**
  92324. * Sets the primary color of all the available elements.
  92325. * @param color
  92326. */
  92327. EnvironmentHelper.prototype.setMainColor = function (color) {
  92328. if (this.groundMaterial) {
  92329. this.groundMaterial.primaryColor = color;
  92330. }
  92331. if (this.skyboxMaterial) {
  92332. this.skyboxMaterial.primaryColor = color;
  92333. }
  92334. if (this.groundMirror) {
  92335. this.groundMirror.clearColor = new BABYLON.Color4(color.r, color.g, color.b, 1.0);
  92336. }
  92337. };
  92338. /**
  92339. * Setup the image processing according to the specified options.
  92340. */
  92341. EnvironmentHelper.prototype._setupImageProcessing = function () {
  92342. if (this._options.setupImageProcessing) {
  92343. this._scene.imageProcessingConfiguration.contrast = this._options.cameraContrast;
  92344. this._scene.imageProcessingConfiguration.exposure = this._options.cameraExposure;
  92345. this._scene.imageProcessingConfiguration.toneMappingEnabled = this._options.toneMappingEnabled;
  92346. this._setupEnvironmentTexture();
  92347. }
  92348. };
  92349. /**
  92350. * Setup the environment texture according to the specified options.
  92351. */
  92352. EnvironmentHelper.prototype._setupEnvironmentTexture = function () {
  92353. if (this._scene.environmentTexture) {
  92354. return;
  92355. }
  92356. if (this._options.environmentTexture instanceof BABYLON.BaseTexture) {
  92357. this._scene.environmentTexture = this._options.environmentTexture;
  92358. return;
  92359. }
  92360. var environmentTexture = BABYLON.CubeTexture.CreateFromPrefilteredData(this._options.environmentTexture, this._scene);
  92361. this._scene.environmentTexture = environmentTexture;
  92362. };
  92363. /**
  92364. * Setup the background according to the specified options.
  92365. */
  92366. EnvironmentHelper.prototype._setupBackground = function () {
  92367. if (!this._rootMesh) {
  92368. this._rootMesh = new BABYLON.Mesh("BackgroundHelper", this._scene);
  92369. }
  92370. this._rootMesh.rotation.y = this._options.backgroundYRotation;
  92371. var sceneSize = this._getSceneSize();
  92372. if (this._options.createGround) {
  92373. this._setupGround(sceneSize);
  92374. this._setupGroundMaterial();
  92375. this._setupGroundDiffuseTexture();
  92376. if (this._options.enableGroundMirror) {
  92377. this._setupGroundMirrorTexture(sceneSize);
  92378. }
  92379. this._setupMirrorInGroundMaterial();
  92380. }
  92381. if (this._options.createSkybox) {
  92382. this._setupSkybox(sceneSize);
  92383. this._setupSkyboxMaterial();
  92384. this._setupSkyboxReflectionTexture();
  92385. }
  92386. this._rootMesh.position.x = sceneSize.rootPosition.x;
  92387. this._rootMesh.position.z = sceneSize.rootPosition.z;
  92388. this._rootMesh.position.y = sceneSize.rootPosition.y;
  92389. };
  92390. /**
  92391. * Get the scene sizes according to the setup.
  92392. */
  92393. EnvironmentHelper.prototype._getSceneSize = function () {
  92394. var _this = this;
  92395. var groundSize = this._options.groundSize;
  92396. var skyboxSize = this._options.skyboxSize;
  92397. var rootPosition = this._options.rootPosition;
  92398. if (!this._scene.meshes || this._scene.meshes.length === 1) {
  92399. return { groundSize: groundSize, skyboxSize: skyboxSize, rootPosition: rootPosition };
  92400. }
  92401. var sceneExtends = this._scene.getWorldExtends(function (mesh) {
  92402. return (mesh !== _this._ground && mesh !== _this._rootMesh && mesh !== _this._skybox);
  92403. });
  92404. var sceneDiagonal = sceneExtends.max.subtract(sceneExtends.min);
  92405. if (this._options.sizeAuto) {
  92406. if (this._scene.activeCamera instanceof BABYLON.ArcRotateCamera &&
  92407. this._scene.activeCamera.upperRadiusLimit) {
  92408. groundSize = this._scene.activeCamera.upperRadiusLimit * 2;
  92409. skyboxSize = groundSize;
  92410. }
  92411. var sceneDiagonalLenght = sceneDiagonal.length();
  92412. if (sceneDiagonalLenght > groundSize) {
  92413. groundSize = sceneDiagonalLenght * 2;
  92414. skyboxSize = groundSize;
  92415. }
  92416. // 10 % bigger.
  92417. groundSize *= 1.1;
  92418. skyboxSize *= 1.5;
  92419. rootPosition = sceneExtends.min.add(sceneDiagonal.scale(0.5));
  92420. rootPosition.y = sceneExtends.min.y - this._options.groundYBias;
  92421. }
  92422. return { groundSize: groundSize, skyboxSize: skyboxSize, rootPosition: rootPosition };
  92423. };
  92424. /**
  92425. * Setup the ground according to the specified options.
  92426. */
  92427. EnvironmentHelper.prototype._setupGround = function (sceneSize) {
  92428. var _this = this;
  92429. if (!this._ground) {
  92430. this._ground = BABYLON.Mesh.CreatePlane("BackgroundPlane", sceneSize.groundSize, this._scene);
  92431. this._ground.rotation.x = Math.PI / 2; // Face up by default.
  92432. this._ground.parent = this._rootMesh;
  92433. this._ground.onDisposeObservable.add(function () { _this._ground = null; });
  92434. }
  92435. this._ground.receiveShadows = this._options.enableGroundShadow;
  92436. };
  92437. /**
  92438. * Setup the ground material according to the specified options.
  92439. */
  92440. EnvironmentHelper.prototype._setupGroundMaterial = function () {
  92441. if (!this._groundMaterial) {
  92442. this._groundMaterial = new BABYLON.BackgroundMaterial("BackgroundPlaneMaterial", this._scene);
  92443. }
  92444. this._groundMaterial.alpha = this._options.groundOpacity;
  92445. this._groundMaterial.alphaMode = BABYLON.Engine.ALPHA_PREMULTIPLIED_PORTERDUFF;
  92446. this._groundMaterial.shadowLevel = this._options.groundShadowLevel;
  92447. this._groundMaterial.primaryLevel = 1;
  92448. this._groundMaterial.primaryColor = this._options.groundColor;
  92449. this._groundMaterial.secondaryLevel = 0;
  92450. this._groundMaterial.tertiaryLevel = 0;
  92451. this._groundMaterial.useRGBColor = false;
  92452. this._groundMaterial.enableNoise = true;
  92453. if (this._ground) {
  92454. this._ground.material = this._groundMaterial;
  92455. }
  92456. };
  92457. /**
  92458. * Setup the ground diffuse texture according to the specified options.
  92459. */
  92460. EnvironmentHelper.prototype._setupGroundDiffuseTexture = function () {
  92461. if (!this._groundMaterial) {
  92462. return;
  92463. }
  92464. if (this._groundTexture) {
  92465. return;
  92466. }
  92467. if (this._options.groundTexture instanceof BABYLON.BaseTexture) {
  92468. this._groundMaterial.diffuseTexture = this._options.groundTexture;
  92469. return;
  92470. }
  92471. var diffuseTexture = new BABYLON.Texture(this._options.groundTexture, this._scene, undefined, undefined, undefined, undefined, this._errorHandler);
  92472. diffuseTexture.gammaSpace = false;
  92473. diffuseTexture.hasAlpha = true;
  92474. this._groundMaterial.diffuseTexture = diffuseTexture;
  92475. };
  92476. /**
  92477. * Setup the ground mirror texture according to the specified options.
  92478. */
  92479. EnvironmentHelper.prototype._setupGroundMirrorTexture = function (sceneSize) {
  92480. var wrapping = BABYLON.Texture.CLAMP_ADDRESSMODE;
  92481. if (!this._groundMirror) {
  92482. this._groundMirror = new BABYLON.MirrorTexture("BackgroundPlaneMirrorTexture", { ratio: this._options.groundMirrorSizeRatio }, this._scene, false, this._options.groundMirrorTextureType, BABYLON.Texture.BILINEAR_SAMPLINGMODE, true);
  92483. this._groundMirror.mirrorPlane = new BABYLON.Plane(0, -1, 0, sceneSize.rootPosition.y);
  92484. this._groundMirror.anisotropicFilteringLevel = 1;
  92485. this._groundMirror.wrapU = wrapping;
  92486. this._groundMirror.wrapV = wrapping;
  92487. this._groundMirror.gammaSpace = false;
  92488. if (this._groundMirror.renderList) {
  92489. for (var i = 0; i < this._scene.meshes.length; i++) {
  92490. var mesh = this._scene.meshes[i];
  92491. if (mesh !== this._ground &&
  92492. mesh !== this._skybox &&
  92493. mesh !== this._rootMesh) {
  92494. this._groundMirror.renderList.push(mesh);
  92495. }
  92496. }
  92497. }
  92498. }
  92499. this._groundMirror.clearColor = new BABYLON.Color4(this._options.groundColor.r, this._options.groundColor.g, this._options.groundColor.b, 1);
  92500. this._groundMirror.adaptiveBlurKernel = this._options.groundMirrorBlurKernel;
  92501. };
  92502. /**
  92503. * Setup the ground to receive the mirror texture.
  92504. */
  92505. EnvironmentHelper.prototype._setupMirrorInGroundMaterial = function () {
  92506. if (this._groundMaterial) {
  92507. this._groundMaterial.reflectionTexture = this._groundMirror;
  92508. this._groundMaterial.reflectionFresnel = true;
  92509. this._groundMaterial.reflectionAmount = this._options.groundMirrorAmount;
  92510. this._groundMaterial.reflectionStandardFresnelWeight = this._options.groundMirrorFresnelWeight;
  92511. this._groundMaterial.reflectionFalloffDistance = this._options.groundMirrorFallOffDistance;
  92512. }
  92513. };
  92514. /**
  92515. * Setup the skybox according to the specified options.
  92516. */
  92517. EnvironmentHelper.prototype._setupSkybox = function (sceneSize) {
  92518. var _this = this;
  92519. if (!this._skybox) {
  92520. this._skybox = BABYLON.Mesh.CreateBox("BackgroundSkybox", sceneSize.skyboxSize, this._scene, undefined, BABYLON.Mesh.BACKSIDE);
  92521. this._skybox.onDisposeObservable.add(function () { _this._skybox = null; });
  92522. }
  92523. this._skybox.parent = this._rootMesh;
  92524. };
  92525. /**
  92526. * Setup the skybox material according to the specified options.
  92527. */
  92528. EnvironmentHelper.prototype._setupSkyboxMaterial = function () {
  92529. if (!this._skybox) {
  92530. return;
  92531. }
  92532. if (!this._skyboxMaterial) {
  92533. this._skyboxMaterial = new BABYLON.BackgroundMaterial("BackgroundSkyboxMaterial", this._scene);
  92534. }
  92535. this._skyboxMaterial.useRGBColor = false;
  92536. this._skyboxMaterial.primaryLevel = 1;
  92537. this._skyboxMaterial.primaryColor = this._options.skyboxColor;
  92538. this._skyboxMaterial.secondaryLevel = 0;
  92539. this._skyboxMaterial.tertiaryLevel = 0;
  92540. this._skyboxMaterial.enableNoise = true;
  92541. this._skybox.material = this._skyboxMaterial;
  92542. };
  92543. /**
  92544. * Setup the skybox reflection texture according to the specified options.
  92545. */
  92546. EnvironmentHelper.prototype._setupSkyboxReflectionTexture = function () {
  92547. if (!this._skyboxMaterial) {
  92548. return;
  92549. }
  92550. if (this._skyboxTexture) {
  92551. return;
  92552. }
  92553. if (this._options.skyboxTexture instanceof BABYLON.BaseTexture) {
  92554. this._skyboxMaterial.reflectionTexture = this._skyboxTexture;
  92555. return;
  92556. }
  92557. this._skyboxTexture = new BABYLON.CubeTexture(this._options.skyboxTexture, this._scene, undefined, undefined, undefined, undefined, this._errorHandler);
  92558. this._skyboxTexture.coordinatesMode = BABYLON.Texture.SKYBOX_MODE;
  92559. this._skyboxTexture.gammaSpace = false;
  92560. this._skyboxMaterial.reflectionTexture = this._skyboxTexture;
  92561. };
  92562. /**
  92563. * Dispose all the elements created by the Helper.
  92564. */
  92565. EnvironmentHelper.prototype.dispose = function () {
  92566. if (this._groundMaterial) {
  92567. this._groundMaterial.dispose(true, true);
  92568. }
  92569. if (this._skyboxMaterial) {
  92570. this._skyboxMaterial.dispose(true, true);
  92571. }
  92572. this._rootMesh.dispose(false);
  92573. };
  92574. /**
  92575. * Default ground texture URL.
  92576. */
  92577. EnvironmentHelper._groundTextureCDNUrl = "https://assets.babylonjs.com/environments/backgroundGround.png";
  92578. /**
  92579. * Default skybox texture URL.
  92580. */
  92581. EnvironmentHelper._skyboxTextureCDNUrl = "https://assets.babylonjs.com/environments/backgroundSkybox.dds";
  92582. /**
  92583. * Default environment texture URL.
  92584. */
  92585. EnvironmentHelper._environmentTextureCDNUrl = "https://assets.babylonjs.com/environments/environmentSpecular.dds";
  92586. return EnvironmentHelper;
  92587. }());
  92588. BABYLON.EnvironmentHelper = EnvironmentHelper;
  92589. })(BABYLON || (BABYLON = {}));
  92590. //# sourceMappingURL=babylon.environmentHelper.js.map
  92591. "use strict";
  92592. var BABYLON;
  92593. (function (BABYLON) {
  92594. /**
  92595. * Display a 360 degree video on an approximately spherical surface, useful for VR applications or skyboxes.
  92596. * As a subclass of Node, this allow parenting to the camera or multiple videos with different locations in the scene.
  92597. * This class achieves its effect with a VideoTexture and a correctly configured BackgroundMaterial on an inverted sphere.
  92598. * Potential additions to this helper include zoom and and non-infinite distance rendering effects.
  92599. */
  92600. var VideoDome = /** @class */ (function (_super) {
  92601. __extends(VideoDome, _super);
  92602. /**
  92603. * Create an instance of this class and pass through the parameters to the relevant classes, VideoTexture, StandardMaterial, and Mesh.
  92604. * @param name Element's name, child elements will append suffixes for their own names.
  92605. * @param urlsOrVideo
  92606. * @param options An object containing optional or exposed sub element properties:
  92607. * @param options **resolution=12** Integer, lower resolutions have more artifacts at extreme fovs
  92608. * @param options **clickToPlay=false** Add a click to play listener to the video, does not prevent autoplay.
  92609. * @param options **autoPlay=true** Automatically attempt to being playing the video.
  92610. * @param options **loop=true** Automatically loop video on end.
  92611. * @param options **size=1000** Physical radius to create the dome at, defaults to approximately half the far clip plane.
  92612. */
  92613. function VideoDome(name, urlsOrVideo, options, scene) {
  92614. var _this = _super.call(this, name, scene) || this;
  92615. // set defaults and manage values
  92616. name = name || "videoDome";
  92617. options.resolution = (Math.abs(options.resolution) | 0) || 12;
  92618. options.clickToPlay = Boolean(options.clickToPlay);
  92619. options.autoPlay = options.autoPlay === undefined ? true : Boolean(options.autoPlay);
  92620. options.loop = options.loop === undefined ? true : Boolean(options.loop);
  92621. options.size = Math.abs(options.size) || (scene.activeCamera ? scene.activeCamera.maxZ * 0.48 : 1000);
  92622. // create
  92623. var tempOptions = { loop: options.loop, autoPlay: options.autoPlay, autoUpdateTexture: true };
  92624. var material = _this._material = new BABYLON.BackgroundMaterial(name + "_material", scene);
  92625. var texture = _this._videoTexture = new BABYLON.VideoTexture(name + "_texture", urlsOrVideo, scene, false, false, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, tempOptions);
  92626. _this._mesh = BABYLON.MeshBuilder.CreateIcoSphere(name + "_mesh", {
  92627. flat: false,
  92628. radius: options.size,
  92629. subdivisions: options.resolution,
  92630. sideOrientation: BABYLON.Mesh.BACKSIDE // needs to be inside out
  92631. }, scene);
  92632. // configure material
  92633. texture.coordinatesMode = BABYLON.Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE; // matches orientation
  92634. texture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE; // always clamp the up/down
  92635. material.reflectionTexture = _this._videoTexture;
  92636. material.useEquirectangularFOV = true;
  92637. material.fovMultiplier = 1.0;
  92638. // configure mesh
  92639. _this._mesh.material = material;
  92640. _this._mesh.parent = _this;
  92641. // optional configuration
  92642. if (options.clickToPlay) {
  92643. scene.onPointerUp = function () {
  92644. _this._videoTexture.video.play();
  92645. };
  92646. }
  92647. return _this;
  92648. }
  92649. Object.defineProperty(VideoDome.prototype, "fovMultiplier", {
  92650. /**
  92651. * The current fov(field of view) multiplier, 0.0 - 2.0. Defaults to 1.0. Lower values "zoom in" and higher values "zoom out".
  92652. * Also see the options.resolution property.
  92653. */
  92654. get: function () {
  92655. return this._material.fovMultiplier;
  92656. },
  92657. set: function (value) {
  92658. this._material.fovMultiplier = value;
  92659. },
  92660. enumerable: true,
  92661. configurable: true
  92662. });
  92663. /**
  92664. * Releases resources associated with this node.
  92665. * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default)
  92666. * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default)
  92667. */
  92668. VideoDome.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  92669. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  92670. this._videoTexture.dispose();
  92671. this._mesh.dispose();
  92672. this._material.dispose();
  92673. _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
  92674. };
  92675. return VideoDome;
  92676. }(BABYLON.Node));
  92677. BABYLON.VideoDome = VideoDome;
  92678. })(BABYLON || (BABYLON = {}));
  92679. //# sourceMappingURL=babylon.videoDome.js.map
  92680. 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\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<0.4)\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)\n{\nrefractionColor=textureCube(refractionCubeSampler,refractionVector).rgb*vRefractionInfos.x;\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*vRefractionInfos.x;\n#endif\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*vReflectionInfos.x;\n#else\nreflectionColor=textureCube(reflectionCubeSampler,vReflectionUVW).rgb*vReflectionInfos.x;\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*vReflectionInfos.x;\n#endif\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)\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#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\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(reflectionCoords,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;\nvarying vec2 vUV;\nvoid main(void) {\nvec4 ssaoColor=texture2D(textureSampler,vUV);\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);\nif(range<rangeMaxClamped) \n{\ngl_FragColor=rgbyM;\nreturn;\n}\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}\ngl_FragColor=texture2D(textureSampler,posM,0.0);\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}\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{\n#ifdef DOF\nfloat sumOfWeights=0.0; \nfloat sampleDepth=0.0;\nfloat factor=0.0;\nfloat centerSampleDepth=sampleDistance(sampleCenter);\n#endif\nfloat computedWeight=0.0;\n#ifdef PACKEDFLOAT \nfloat blend=0.;\n#else\nvec4 blend=vec4(0.);\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\n\nif(sumOfWeights == 0.0){\ngl_FragColor=vec4(0.0,0.0,0.0,1.0);\n}\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{\ngl_FragColor=texture2D(textureSampler,vUV);\nfloat coc=texture2D(circleOfConfusionSampler,vUV).r;\nvec4 original=texture2D(textureSampler,vUV);\n#if BLUR_LEVEL == 0\nvec4 blurred0=texture2D(blurStep0,vUV);\ngl_FragColor=mix(original,blurred0,coc);\n#endif\n#if BLUR_LEVEL == 1\nvec4 blurred0=texture2D(blurStep0,vUV); \nvec4 blurred1=texture2D(blurStep1,vUV);\nif(coc<0.5){\ngl_FragColor=mix(original,blurred1,coc/0.5);\n}else{\ngl_FragColor=mix(blurred1,blurred0,(coc-0.5)/0.5);\n}\n#endif\n#if BLUR_LEVEL == 2\nvec4 blurred0=texture2D(blurStep0,vUV);\nvec4 blurred1=texture2D(blurStep1,vUV);\nvec4 blurred2=texture2D(blurStep2,vUV);\nif(coc<0.33){\ngl_FragColor=mix(original,blurred2,coc/0.33);\n}else if(coc<0.66){\ngl_FragColor=mix(blurred2,blurred1,(coc-0.33)/0.33);\n}else{\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;\nfloat sampleDistance(const in vec2 offset) {\nfloat depth=texture2D(depthSampler,offset).r; \nreturn (cameraMinMaxZ.x+(cameraMinMaxZ.y-cameraMinMaxZ.x)*depth)*1000.0; \n}\nvoid main(void)\n{\nfloat pixelDistance=sampleDistance(vUV);\nfloat coc=abs(cocPrecalculation* ((focusDistance-pixelDistance)/pixelDistance));\ncoc=clamp(coc,0.0,1.0);\ngl_FragColor=vec4(coc,texture2D(depthSampler,vUV).r,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\nvec3 finalColor=colorBase.r*vPrimaryColor.rgb*vPrimaryColor.a;\nfinalColor+=colorBase.g*vSecondaryColor.rgb*vSecondaryColor.a;\nfinalColor+=colorBase.b*vTertiaryColor.rgb*vTertiaryColor.a;\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"};
  92681. 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;\n#ifdef PBR\ntextureColor=toLinearSpace(textureColor);\n#endif\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,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,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,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)\n{\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 reflection,vec3 normal) {\n\n#ifdef REFLECTIONMAP_OPPOSITEZ\nreflection.z*=-1.0;\n#endif\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,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);\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,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);\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,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);\nresult.specular=specTerm*diffuseColor;\n#endif\nreturn result;\n}","kernelBlurFragment":"#ifdef DOF\nsampleDepth=sampleDistance(sampleCoord{X});\nfactor=clamp(1.0-((centerSampleDepth-sampleDepth)/centerSampleDepth),0.0,1.0);\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\nsampleDepth=sampleDistance(sampleCoord{X});\nfactor=clamp(1.0-((centerSampleDepth-sampleDepth)/centerSampleDepth),0.0,1.0);\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;\nuniform vec4 vSecondaryColor;\nuniform vec4 vTertiaryColor;\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 vSecondaryColor;\nuniform vec4 vTertiaryColor;\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);
  92682. globalObject["BABYLON"] = BABYLON;
  92683. 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 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 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 Debug = BABYLON.Debug;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 JoystickAxis = BABYLON.JoystickAxis ;var SimplificationType = BABYLON.SimplificationType ;var AssetTaskState = BABYLON.AssetTaskState ;
  92684. 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,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,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,Debug,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 ,JoystickAxis ,SimplificationType ,AssetTaskState };