es6.js 4.4 MB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605660666076608660966106611661266136614661566166617661866196620662166226623662466256626662766286629663066316632663366346635663666376638663966406641664266436644664566466647664866496650665166526653665466556656665766586659666066616662666366646665666666676668666966706671667266736674667566766677667866796680668166826683668466856686668766886689669066916692669366946695669666976698669967006701670267036704670567066707670867096710671167126713671467156716671767186719672067216722672367246725672667276728672967306731673267336734673567366737673867396740674167426743674467456746674767486749675067516752675367546755675667576758675967606761676267636764676567666767676867696770677167726773677467756776677767786779678067816782678367846785678667876788678967906791679267936794679567966797679867996800680168026803680468056806680768086809681068116812681368146815681668176818681968206821682268236824682568266827682868296830683168326833683468356836683768386839684068416842684368446845684668476848684968506851685268536854685568566857685868596860686168626863686468656866686768686869687068716872687368746875687668776878687968806881688268836884688568866887688868896890689168926893689468956896689768986899690069016902690369046905690669076908690969106911691269136914691569166917691869196920692169226923692469256926692769286929693069316932693369346935693669376938693969406941694269436944694569466947694869496950695169526953695469556956695769586959696069616962696369646965696669676968696969706971697269736974697569766977697869796980698169826983698469856986698769886989699069916992699369946995699669976998699970007001700270037004700570067007700870097010701170127013701470157016701770187019702070217022702370247025702670277028702970307031703270337034703570367037703870397040704170427043704470457046704770487049705070517052705370547055705670577058705970607061706270637064706570667067706870697070707170727073707470757076707770787079708070817082708370847085708670877088708970907091709270937094709570967097709870997100710171027103710471057106710771087109711071117112711371147115711671177118711971207121712271237124712571267127712871297130713171327133713471357136713771387139714071417142714371447145714671477148714971507151715271537154715571567157715871597160716171627163716471657166716771687169717071717172717371747175717671777178717971807181718271837184718571867187718871897190719171927193719471957196719771987199720072017202720372047205720672077208720972107211721272137214721572167217721872197220722172227223722472257226722772287229723072317232723372347235723672377238723972407241724272437244724572467247724872497250725172527253725472557256725772587259726072617262726372647265726672677268726972707271727272737274727572767277727872797280728172827283728472857286728772887289729072917292729372947295729672977298729973007301730273037304730573067307730873097310731173127313731473157316731773187319732073217322732373247325732673277328732973307331733273337334733573367337733873397340734173427343734473457346734773487349735073517352735373547355735673577358735973607361736273637364736573667367736873697370737173727373737473757376737773787379738073817382738373847385738673877388738973907391739273937394739573967397739873997400740174027403740474057406740774087409741074117412741374147415741674177418741974207421742274237424742574267427742874297430743174327433743474357436743774387439744074417442744374447445744674477448744974507451745274537454745574567457745874597460746174627463746474657466746774687469747074717472747374747475747674777478747974807481748274837484748574867487748874897490749174927493749474957496749774987499750075017502750375047505750675077508750975107511751275137514751575167517751875197520752175227523752475257526752775287529753075317532753375347535753675377538753975407541754275437544754575467547754875497550755175527553755475557556755775587559756075617562756375647565756675677568756975707571757275737574757575767577757875797580758175827583758475857586758775887589759075917592759375947595759675977598759976007601760276037604760576067607760876097610761176127613761476157616761776187619762076217622762376247625762676277628762976307631763276337634763576367637763876397640764176427643764476457646764776487649765076517652765376547655765676577658765976607661766276637664766576667667766876697670767176727673767476757676767776787679768076817682768376847685768676877688768976907691769276937694769576967697769876997700770177027703770477057706770777087709771077117712771377147715771677177718771977207721772277237724772577267727772877297730773177327733773477357736773777387739774077417742774377447745774677477748774977507751775277537754775577567757775877597760776177627763776477657766776777687769777077717772777377747775777677777778777977807781778277837784778577867787778877897790779177927793779477957796779777987799780078017802780378047805780678077808780978107811781278137814781578167817781878197820782178227823782478257826782778287829783078317832783378347835783678377838783978407841784278437844784578467847784878497850785178527853785478557856785778587859786078617862786378647865786678677868786978707871787278737874787578767877787878797880788178827883788478857886788778887889789078917892789378947895789678977898789979007901790279037904790579067907790879097910791179127913791479157916791779187919792079217922792379247925792679277928792979307931793279337934793579367937793879397940794179427943794479457946794779487949795079517952795379547955795679577958795979607961796279637964796579667967796879697970797179727973797479757976797779787979798079817982798379847985798679877988798979907991799279937994799579967997799879998000800180028003800480058006800780088009801080118012801380148015801680178018801980208021802280238024802580268027802880298030803180328033803480358036803780388039804080418042804380448045804680478048804980508051805280538054805580568057805880598060806180628063806480658066806780688069807080718072807380748075807680778078807980808081808280838084808580868087808880898090809180928093809480958096809780988099810081018102810381048105810681078108810981108111811281138114811581168117811881198120812181228123812481258126812781288129813081318132813381348135813681378138813981408141814281438144814581468147814881498150815181528153815481558156815781588159816081618162816381648165816681678168816981708171817281738174817581768177817881798180818181828183818481858186818781888189819081918192819381948195819681978198819982008201820282038204820582068207820882098210821182128213821482158216821782188219822082218222822382248225822682278228822982308231823282338234823582368237823882398240824182428243824482458246824782488249825082518252825382548255825682578258825982608261826282638264826582668267826882698270827182728273827482758276827782788279828082818282828382848285828682878288828982908291829282938294829582968297829882998300830183028303830483058306830783088309831083118312831383148315831683178318831983208321832283238324832583268327832883298330833183328333833483358336833783388339834083418342834383448345834683478348834983508351835283538354835583568357835883598360836183628363836483658366836783688369837083718372837383748375837683778378837983808381838283838384838583868387838883898390839183928393839483958396839783988399840084018402840384048405840684078408840984108411841284138414841584168417841884198420842184228423842484258426842784288429843084318432843384348435843684378438843984408441844284438444844584468447844884498450845184528453845484558456845784588459846084618462846384648465846684678468846984708471847284738474847584768477847884798480848184828483848484858486848784888489849084918492849384948495849684978498849985008501850285038504850585068507850885098510851185128513851485158516851785188519852085218522852385248525852685278528852985308531853285338534853585368537853885398540854185428543854485458546854785488549855085518552855385548555855685578558855985608561856285638564856585668567856885698570857185728573857485758576857785788579858085818582858385848585858685878588858985908591859285938594859585968597859885998600860186028603860486058606860786088609861086118612861386148615861686178618861986208621862286238624862586268627862886298630863186328633863486358636863786388639864086418642864386448645864686478648864986508651865286538654865586568657865886598660866186628663866486658666866786688669867086718672867386748675867686778678867986808681868286838684868586868687868886898690869186928693869486958696869786988699870087018702870387048705870687078708870987108711871287138714871587168717871887198720872187228723872487258726872787288729873087318732873387348735873687378738873987408741874287438744874587468747874887498750875187528753875487558756875787588759876087618762876387648765876687678768876987708771877287738774877587768777877887798780878187828783878487858786878787888789879087918792879387948795879687978798879988008801880288038804880588068807880888098810881188128813881488158816881788188819882088218822882388248825882688278828882988308831883288338834883588368837883888398840884188428843884488458846884788488849885088518852885388548855885688578858885988608861886288638864886588668867886888698870887188728873887488758876887788788879888088818882888388848885888688878888888988908891889288938894889588968897889888998900890189028903890489058906890789088909891089118912891389148915891689178918891989208921892289238924892589268927892889298930893189328933893489358936893789388939894089418942894389448945894689478948894989508951895289538954895589568957895889598960896189628963896489658966896789688969897089718972897389748975897689778978897989808981898289838984898589868987898889898990899189928993899489958996899789988999900090019002900390049005900690079008900990109011901290139014901590169017901890199020902190229023902490259026902790289029903090319032903390349035903690379038903990409041904290439044904590469047904890499050905190529053905490559056905790589059906090619062906390649065906690679068906990709071907290739074907590769077907890799080908190829083908490859086908790889089909090919092909390949095909690979098909991009101910291039104910591069107910891099110911191129113911491159116911791189119912091219122912391249125912691279128912991309131913291339134913591369137913891399140914191429143914491459146914791489149915091519152915391549155915691579158915991609161916291639164916591669167916891699170917191729173917491759176917791789179918091819182918391849185918691879188918991909191919291939194919591969197919891999200920192029203920492059206920792089209921092119212921392149215921692179218921992209221922292239224922592269227922892299230923192329233923492359236923792389239924092419242924392449245924692479248924992509251925292539254925592569257925892599260926192629263926492659266926792689269927092719272927392749275927692779278927992809281928292839284928592869287928892899290929192929293929492959296929792989299930093019302930393049305930693079308930993109311931293139314931593169317931893199320932193229323932493259326932793289329933093319332933393349335933693379338933993409341934293439344934593469347934893499350935193529353935493559356935793589359936093619362936393649365936693679368936993709371937293739374937593769377937893799380938193829383938493859386938793889389939093919392939393949395939693979398939994009401940294039404940594069407940894099410941194129413941494159416941794189419942094219422942394249425942694279428942994309431943294339434943594369437943894399440944194429443944494459446944794489449945094519452945394549455945694579458945994609461946294639464946594669467946894699470947194729473947494759476947794789479948094819482948394849485948694879488948994909491949294939494949594969497949894999500950195029503950495059506950795089509951095119512951395149515951695179518951995209521952295239524952595269527952895299530953195329533953495359536953795389539954095419542954395449545954695479548954995509551955295539554955595569557955895599560956195629563956495659566956795689569957095719572957395749575957695779578957995809581958295839584958595869587958895899590959195929593959495959596959795989599960096019602960396049605960696079608960996109611961296139614961596169617961896199620962196229623962496259626962796289629963096319632963396349635963696379638963996409641964296439644964596469647964896499650965196529653965496559656965796589659966096619662966396649665966696679668966996709671967296739674967596769677967896799680968196829683968496859686968796889689969096919692969396949695969696979698969997009701970297039704970597069707970897099710971197129713971497159716971797189719972097219722972397249725972697279728972997309731973297339734973597369737973897399740974197429743974497459746974797489749975097519752975397549755975697579758975997609761976297639764976597669767976897699770977197729773977497759776977797789779978097819782978397849785978697879788978997909791979297939794979597969797979897999800980198029803980498059806980798089809981098119812981398149815981698179818981998209821982298239824982598269827982898299830983198329833983498359836983798389839984098419842984398449845984698479848984998509851985298539854985598569857985898599860986198629863986498659866986798689869987098719872987398749875987698779878987998809881988298839884988598869887988898899890989198929893989498959896989798989899990099019902990399049905990699079908990999109911991299139914991599169917991899199920992199229923992499259926992799289929993099319932993399349935993699379938993999409941994299439944994599469947994899499950995199529953995499559956995799589959996099619962996399649965996699679968996999709971997299739974997599769977997899799980998199829983998499859986998799889989999099919992999399949995999699979998999910000100011000210003100041000510006100071000810009100101001110012100131001410015100161001710018100191002010021100221002310024100251002610027100281002910030100311003210033100341003510036100371003810039100401004110042100431004410045100461004710048100491005010051100521005310054100551005610057100581005910060100611006210063100641006510066100671006810069100701007110072100731007410075100761007710078100791008010081100821008310084100851008610087100881008910090100911009210093100941009510096100971009810099101001010110102101031010410105101061010710108101091011010111101121011310114101151011610117101181011910120101211012210123101241012510126101271012810129101301013110132101331013410135101361013710138101391014010141101421014310144101451014610147101481014910150101511015210153101541015510156101571015810159101601016110162101631016410165101661016710168101691017010171101721017310174101751017610177101781017910180101811018210183101841018510186101871018810189101901019110192101931019410195101961019710198101991020010201102021020310204102051020610207102081020910210102111021210213102141021510216102171021810219102201022110222102231022410225102261022710228102291023010231102321023310234102351023610237102381023910240102411024210243102441024510246102471024810249102501025110252102531025410255102561025710258102591026010261102621026310264102651026610267102681026910270102711027210273102741027510276102771027810279102801028110282102831028410285102861028710288102891029010291102921029310294102951029610297102981029910300103011030210303103041030510306103071030810309103101031110312103131031410315103161031710318103191032010321103221032310324103251032610327103281032910330103311033210333103341033510336103371033810339103401034110342103431034410345103461034710348103491035010351103521035310354103551035610357103581035910360103611036210363103641036510366103671036810369103701037110372103731037410375103761037710378103791038010381103821038310384103851038610387103881038910390103911039210393103941039510396103971039810399104001040110402104031040410405104061040710408104091041010411104121041310414104151041610417104181041910420104211042210423104241042510426104271042810429104301043110432104331043410435104361043710438104391044010441104421044310444104451044610447104481044910450104511045210453104541045510456104571045810459104601046110462104631046410465104661046710468104691047010471104721047310474104751047610477104781047910480104811048210483104841048510486104871048810489104901049110492104931049410495104961049710498104991050010501105021050310504105051050610507105081050910510105111051210513105141051510516105171051810519105201052110522105231052410525105261052710528105291053010531105321053310534105351053610537105381053910540105411054210543105441054510546105471054810549105501055110552105531055410555105561055710558105591056010561105621056310564105651056610567105681056910570105711057210573105741057510576105771057810579105801058110582105831058410585105861058710588105891059010591105921059310594105951059610597105981059910600106011060210603106041060510606106071060810609106101061110612106131061410615106161061710618106191062010621106221062310624106251062610627106281062910630106311063210633106341063510636106371063810639106401064110642106431064410645106461064710648106491065010651106521065310654106551065610657106581065910660106611066210663106641066510666106671066810669106701067110672106731067410675106761067710678106791068010681106821068310684106851068610687106881068910690106911069210693106941069510696106971069810699107001070110702107031070410705107061070710708107091071010711107121071310714107151071610717107181071910720107211072210723107241072510726107271072810729107301073110732107331073410735107361073710738107391074010741107421074310744107451074610747107481074910750107511075210753107541075510756107571075810759107601076110762107631076410765107661076710768107691077010771107721077310774107751077610777107781077910780107811078210783107841078510786107871078810789107901079110792107931079410795107961079710798107991080010801108021080310804108051080610807108081080910810108111081210813108141081510816108171081810819108201082110822108231082410825108261082710828108291083010831108321083310834108351083610837108381083910840108411084210843108441084510846108471084810849108501085110852108531085410855108561085710858108591086010861108621086310864108651086610867108681086910870108711087210873108741087510876108771087810879108801088110882108831088410885108861088710888108891089010891108921089310894108951089610897108981089910900109011090210903109041090510906109071090810909109101091110912109131091410915109161091710918109191092010921109221092310924109251092610927109281092910930109311093210933109341093510936109371093810939109401094110942109431094410945109461094710948109491095010951109521095310954109551095610957109581095910960109611096210963109641096510966109671096810969109701097110972109731097410975109761097710978109791098010981109821098310984109851098610987109881098910990109911099210993109941099510996109971099810999110001100111002110031100411005110061100711008110091101011011110121101311014110151101611017110181101911020110211102211023110241102511026110271102811029110301103111032110331103411035110361103711038110391104011041110421104311044110451104611047110481104911050110511105211053110541105511056110571105811059110601106111062110631106411065110661106711068110691107011071110721107311074110751107611077110781107911080110811108211083110841108511086110871108811089110901109111092110931109411095110961109711098110991110011101111021110311104111051110611107111081110911110111111111211113111141111511116111171111811119111201112111122111231112411125111261112711128111291113011131111321113311134111351113611137111381113911140111411114211143111441114511146111471114811149111501115111152111531115411155111561115711158111591116011161111621116311164111651116611167111681116911170111711117211173111741117511176111771117811179111801118111182111831118411185111861118711188111891119011191111921119311194111951119611197111981119911200112011120211203112041120511206112071120811209112101121111212112131121411215112161121711218112191122011221112221122311224112251122611227112281122911230112311123211233112341123511236112371123811239112401124111242112431124411245112461124711248112491125011251112521125311254112551125611257112581125911260112611126211263112641126511266112671126811269112701127111272112731127411275112761127711278112791128011281112821128311284112851128611287112881128911290112911129211293112941129511296112971129811299113001130111302113031130411305113061130711308113091131011311113121131311314113151131611317113181131911320113211132211323113241132511326113271132811329113301133111332113331133411335113361133711338113391134011341113421134311344113451134611347113481134911350113511135211353113541135511356113571135811359113601136111362113631136411365113661136711368113691137011371113721137311374113751137611377113781137911380113811138211383113841138511386113871138811389113901139111392113931139411395113961139711398113991140011401114021140311404114051140611407114081140911410114111141211413114141141511416114171141811419114201142111422114231142411425114261142711428114291143011431114321143311434114351143611437114381143911440114411144211443114441144511446114471144811449114501145111452114531145411455114561145711458114591146011461114621146311464114651146611467114681146911470114711147211473114741147511476114771147811479114801148111482114831148411485114861148711488114891149011491114921149311494114951149611497114981149911500115011150211503115041150511506115071150811509115101151111512115131151411515115161151711518115191152011521115221152311524115251152611527115281152911530115311153211533115341153511536115371153811539115401154111542115431154411545115461154711548115491155011551115521155311554115551155611557115581155911560115611156211563115641156511566115671156811569115701157111572115731157411575115761157711578115791158011581115821158311584115851158611587115881158911590115911159211593115941159511596115971159811599116001160111602116031160411605116061160711608116091161011611116121161311614116151161611617116181161911620116211162211623116241162511626116271162811629116301163111632116331163411635116361163711638116391164011641116421164311644116451164611647116481164911650116511165211653116541165511656116571165811659116601166111662116631166411665116661166711668116691167011671116721167311674116751167611677116781167911680116811168211683116841168511686116871168811689116901169111692116931169411695116961169711698116991170011701117021170311704117051170611707117081170911710117111171211713117141171511716117171171811719117201172111722117231172411725117261172711728117291173011731117321173311734117351173611737117381173911740117411174211743117441174511746117471174811749117501175111752117531175411755117561175711758117591176011761117621176311764117651176611767117681176911770117711177211773117741177511776117771177811779117801178111782117831178411785117861178711788117891179011791117921179311794117951179611797117981179911800118011180211803118041180511806118071180811809118101181111812118131181411815118161181711818118191182011821118221182311824118251182611827118281182911830118311183211833118341183511836118371183811839118401184111842118431184411845118461184711848118491185011851118521185311854118551185611857118581185911860118611186211863118641186511866118671186811869118701187111872118731187411875118761187711878118791188011881118821188311884118851188611887118881188911890118911189211893118941189511896118971189811899119001190111902119031190411905119061190711908119091191011911119121191311914119151191611917119181191911920119211192211923119241192511926119271192811929119301193111932119331193411935119361193711938119391194011941119421194311944119451194611947119481194911950119511195211953119541195511956119571195811959119601196111962119631196411965119661196711968119691197011971119721197311974119751197611977119781197911980119811198211983119841198511986119871198811989119901199111992119931199411995119961199711998119991200012001120021200312004120051200612007120081200912010120111201212013120141201512016120171201812019120201202112022120231202412025120261202712028120291203012031120321203312034120351203612037120381203912040120411204212043120441204512046120471204812049120501205112052120531205412055120561205712058120591206012061120621206312064120651206612067120681206912070120711207212073120741207512076120771207812079120801208112082120831208412085120861208712088120891209012091120921209312094120951209612097120981209912100121011210212103121041210512106121071210812109121101211112112121131211412115121161211712118121191212012121121221212312124121251212612127121281212912130121311213212133121341213512136121371213812139121401214112142121431214412145121461214712148121491215012151121521215312154121551215612157121581215912160121611216212163121641216512166121671216812169121701217112172121731217412175121761217712178121791218012181121821218312184121851218612187121881218912190121911219212193121941219512196121971219812199122001220112202122031220412205122061220712208122091221012211122121221312214122151221612217122181221912220122211222212223122241222512226122271222812229122301223112232122331223412235122361223712238122391224012241122421224312244122451224612247122481224912250122511225212253122541225512256122571225812259122601226112262122631226412265122661226712268122691227012271122721227312274122751227612277122781227912280122811228212283122841228512286122871228812289122901229112292122931229412295122961229712298122991230012301123021230312304123051230612307123081230912310123111231212313123141231512316123171231812319123201232112322123231232412325123261232712328123291233012331123321233312334123351233612337123381233912340123411234212343123441234512346123471234812349123501235112352123531235412355123561235712358123591236012361123621236312364123651236612367123681236912370123711237212373123741237512376123771237812379123801238112382123831238412385123861238712388123891239012391123921239312394123951239612397123981239912400124011240212403124041240512406124071240812409124101241112412124131241412415124161241712418124191242012421124221242312424124251242612427124281242912430124311243212433124341243512436124371243812439124401244112442124431244412445124461244712448124491245012451124521245312454124551245612457124581245912460124611246212463124641246512466124671246812469124701247112472124731247412475124761247712478124791248012481124821248312484124851248612487124881248912490124911249212493124941249512496124971249812499125001250112502125031250412505125061250712508125091251012511125121251312514125151251612517125181251912520125211252212523125241252512526125271252812529125301253112532125331253412535125361253712538125391254012541125421254312544125451254612547125481254912550125511255212553125541255512556125571255812559125601256112562125631256412565125661256712568125691257012571125721257312574125751257612577125781257912580125811258212583125841258512586125871258812589125901259112592125931259412595125961259712598125991260012601126021260312604126051260612607126081260912610126111261212613126141261512616126171261812619126201262112622126231262412625126261262712628126291263012631126321263312634126351263612637126381263912640126411264212643126441264512646126471264812649126501265112652126531265412655126561265712658126591266012661126621266312664126651266612667126681266912670126711267212673126741267512676126771267812679126801268112682126831268412685126861268712688126891269012691126921269312694126951269612697126981269912700127011270212703127041270512706127071270812709127101271112712127131271412715127161271712718127191272012721127221272312724127251272612727127281272912730127311273212733127341273512736127371273812739127401274112742127431274412745127461274712748127491275012751127521275312754127551275612757127581275912760127611276212763127641276512766127671276812769127701277112772127731277412775127761277712778127791278012781127821278312784127851278612787127881278912790127911279212793127941279512796127971279812799128001280112802128031280412805128061280712808128091281012811128121281312814128151281612817128181281912820128211282212823128241282512826128271282812829128301283112832128331283412835128361283712838128391284012841128421284312844128451284612847128481284912850128511285212853128541285512856128571285812859128601286112862128631286412865128661286712868128691287012871128721287312874128751287612877128781287912880128811288212883128841288512886128871288812889128901289112892128931289412895128961289712898128991290012901129021290312904129051290612907129081290912910129111291212913129141291512916129171291812919129201292112922129231292412925129261292712928129291293012931129321293312934129351293612937129381293912940129411294212943129441294512946129471294812949129501295112952129531295412955129561295712958129591296012961129621296312964129651296612967129681296912970129711297212973129741297512976129771297812979129801298112982129831298412985129861298712988129891299012991129921299312994129951299612997129981299913000130011300213003130041300513006130071300813009130101301113012130131301413015130161301713018130191302013021130221302313024130251302613027130281302913030130311303213033130341303513036130371303813039130401304113042130431304413045130461304713048130491305013051130521305313054130551305613057130581305913060130611306213063130641306513066130671306813069130701307113072130731307413075130761307713078130791308013081130821308313084130851308613087130881308913090130911309213093130941309513096130971309813099131001310113102131031310413105131061310713108131091311013111131121311313114131151311613117131181311913120131211312213123131241312513126131271312813129131301313113132131331313413135131361313713138131391314013141131421314313144131451314613147131481314913150131511315213153131541315513156131571315813159131601316113162131631316413165131661316713168131691317013171131721317313174131751317613177131781317913180131811318213183131841318513186131871318813189131901319113192131931319413195131961319713198131991320013201132021320313204132051320613207132081320913210132111321213213132141321513216132171321813219132201322113222132231322413225132261322713228132291323013231132321323313234132351323613237132381323913240132411324213243132441324513246132471324813249132501325113252132531325413255132561325713258132591326013261132621326313264132651326613267132681326913270132711327213273132741327513276132771327813279132801328113282132831328413285132861328713288132891329013291132921329313294132951329613297132981329913300133011330213303133041330513306133071330813309133101331113312133131331413315133161331713318133191332013321133221332313324133251332613327133281332913330133311333213333133341333513336133371333813339133401334113342133431334413345133461334713348133491335013351133521335313354133551335613357133581335913360133611336213363133641336513366133671336813369133701337113372133731337413375133761337713378133791338013381133821338313384133851338613387133881338913390133911339213393133941339513396133971339813399134001340113402134031340413405134061340713408134091341013411134121341313414134151341613417134181341913420134211342213423134241342513426134271342813429134301343113432134331343413435134361343713438134391344013441134421344313444134451344613447134481344913450134511345213453134541345513456134571345813459134601346113462134631346413465134661346713468134691347013471134721347313474134751347613477134781347913480134811348213483134841348513486134871348813489134901349113492134931349413495134961349713498134991350013501135021350313504135051350613507135081350913510135111351213513135141351513516135171351813519135201352113522135231352413525135261352713528135291353013531135321353313534135351353613537135381353913540135411354213543135441354513546135471354813549135501355113552135531355413555135561355713558135591356013561135621356313564135651356613567135681356913570135711357213573135741357513576135771357813579135801358113582135831358413585135861358713588135891359013591135921359313594135951359613597135981359913600136011360213603136041360513606136071360813609136101361113612136131361413615136161361713618136191362013621136221362313624136251362613627136281362913630136311363213633136341363513636136371363813639136401364113642136431364413645136461364713648136491365013651136521365313654136551365613657136581365913660136611366213663136641366513666136671366813669136701367113672136731367413675136761367713678136791368013681136821368313684136851368613687136881368913690136911369213693136941369513696136971369813699137001370113702137031370413705137061370713708137091371013711137121371313714137151371613717137181371913720137211372213723137241372513726137271372813729137301373113732137331373413735137361373713738137391374013741137421374313744137451374613747137481374913750137511375213753137541375513756137571375813759137601376113762137631376413765137661376713768137691377013771137721377313774137751377613777137781377913780137811378213783137841378513786137871378813789137901379113792137931379413795137961379713798137991380013801138021380313804138051380613807138081380913810138111381213813138141381513816138171381813819138201382113822138231382413825138261382713828138291383013831138321383313834138351383613837138381383913840138411384213843138441384513846138471384813849138501385113852138531385413855138561385713858138591386013861138621386313864138651386613867138681386913870138711387213873138741387513876138771387813879138801388113882138831388413885138861388713888138891389013891138921389313894138951389613897138981389913900139011390213903139041390513906139071390813909139101391113912139131391413915139161391713918139191392013921139221392313924139251392613927139281392913930139311393213933139341393513936139371393813939139401394113942139431394413945139461394713948139491395013951139521395313954139551395613957139581395913960139611396213963139641396513966139671396813969139701397113972139731397413975139761397713978139791398013981139821398313984139851398613987139881398913990139911399213993139941399513996139971399813999140001400114002140031400414005140061400714008140091401014011140121401314014140151401614017140181401914020140211402214023140241402514026140271402814029140301403114032140331403414035140361403714038140391404014041140421404314044140451404614047140481404914050140511405214053140541405514056140571405814059140601406114062140631406414065140661406714068140691407014071140721407314074140751407614077140781407914080140811408214083140841408514086140871408814089140901409114092140931409414095140961409714098140991410014101141021410314104141051410614107141081410914110141111411214113141141411514116141171411814119141201412114122141231412414125141261412714128141291413014131141321413314134141351413614137141381413914140141411414214143141441414514146141471414814149141501415114152141531415414155141561415714158141591416014161141621416314164141651416614167141681416914170141711417214173141741417514176141771417814179141801418114182141831418414185141861418714188141891419014191141921419314194141951419614197141981419914200142011420214203142041420514206142071420814209142101421114212142131421414215142161421714218142191422014221142221422314224142251422614227142281422914230142311423214233142341423514236142371423814239142401424114242142431424414245142461424714248142491425014251142521425314254142551425614257142581425914260142611426214263142641426514266142671426814269142701427114272142731427414275142761427714278142791428014281142821428314284142851428614287142881428914290142911429214293142941429514296142971429814299143001430114302143031430414305143061430714308143091431014311143121431314314143151431614317143181431914320143211432214323143241432514326143271432814329143301433114332143331433414335143361433714338143391434014341143421434314344143451434614347143481434914350143511435214353143541435514356143571435814359143601436114362143631436414365143661436714368143691437014371143721437314374143751437614377143781437914380143811438214383143841438514386143871438814389143901439114392143931439414395143961439714398143991440014401144021440314404144051440614407144081440914410144111441214413144141441514416144171441814419144201442114422144231442414425144261442714428144291443014431144321443314434144351443614437144381443914440144411444214443144441444514446144471444814449144501445114452144531445414455144561445714458144591446014461144621446314464144651446614467144681446914470144711447214473144741447514476144771447814479144801448114482144831448414485144861448714488144891449014491144921449314494144951449614497144981449914500145011450214503145041450514506145071450814509145101451114512145131451414515145161451714518145191452014521145221452314524145251452614527145281452914530145311453214533145341453514536145371453814539145401454114542145431454414545145461454714548145491455014551145521455314554145551455614557145581455914560145611456214563145641456514566145671456814569145701457114572145731457414575145761457714578145791458014581145821458314584145851458614587145881458914590145911459214593145941459514596145971459814599146001460114602146031460414605146061460714608146091461014611146121461314614146151461614617146181461914620146211462214623146241462514626146271462814629146301463114632146331463414635146361463714638146391464014641146421464314644146451464614647146481464914650146511465214653146541465514656146571465814659146601466114662146631466414665146661466714668146691467014671146721467314674146751467614677146781467914680146811468214683146841468514686146871468814689146901469114692146931469414695146961469714698146991470014701147021470314704147051470614707147081470914710147111471214713147141471514716147171471814719147201472114722147231472414725147261472714728147291473014731147321473314734147351473614737147381473914740147411474214743147441474514746147471474814749147501475114752147531475414755147561475714758147591476014761147621476314764147651476614767147681476914770147711477214773147741477514776147771477814779147801478114782147831478414785147861478714788147891479014791147921479314794147951479614797147981479914800148011480214803148041480514806148071480814809148101481114812148131481414815148161481714818148191482014821148221482314824148251482614827148281482914830148311483214833148341483514836148371483814839148401484114842148431484414845148461484714848148491485014851148521485314854148551485614857148581485914860148611486214863148641486514866148671486814869148701487114872148731487414875148761487714878148791488014881148821488314884148851488614887148881488914890148911489214893148941489514896148971489814899149001490114902149031490414905149061490714908149091491014911149121491314914149151491614917149181491914920149211492214923149241492514926149271492814929149301493114932149331493414935149361493714938149391494014941149421494314944149451494614947149481494914950149511495214953149541495514956149571495814959149601496114962149631496414965149661496714968149691497014971149721497314974149751497614977149781497914980149811498214983149841498514986149871498814989149901499114992149931499414995149961499714998149991500015001150021500315004150051500615007150081500915010150111501215013150141501515016150171501815019150201502115022150231502415025150261502715028150291503015031150321503315034150351503615037150381503915040150411504215043150441504515046150471504815049150501505115052150531505415055150561505715058150591506015061150621506315064150651506615067150681506915070150711507215073150741507515076150771507815079150801508115082150831508415085150861508715088150891509015091150921509315094150951509615097150981509915100151011510215103151041510515106151071510815109151101511115112151131511415115151161511715118151191512015121151221512315124151251512615127151281512915130151311513215133151341513515136151371513815139151401514115142151431514415145151461514715148151491515015151151521515315154151551515615157151581515915160151611516215163151641516515166151671516815169151701517115172151731517415175151761517715178151791518015181151821518315184151851518615187151881518915190151911519215193151941519515196151971519815199152001520115202152031520415205152061520715208152091521015211152121521315214152151521615217152181521915220152211522215223152241522515226152271522815229152301523115232152331523415235152361523715238152391524015241152421524315244152451524615247152481524915250152511525215253152541525515256152571525815259152601526115262152631526415265152661526715268152691527015271152721527315274152751527615277152781527915280152811528215283152841528515286152871528815289152901529115292152931529415295152961529715298152991530015301153021530315304153051530615307153081530915310153111531215313153141531515316153171531815319153201532115322153231532415325153261532715328153291533015331153321533315334153351533615337153381533915340153411534215343153441534515346153471534815349153501535115352153531535415355153561535715358153591536015361153621536315364153651536615367153681536915370153711537215373153741537515376153771537815379153801538115382153831538415385153861538715388153891539015391153921539315394153951539615397153981539915400154011540215403154041540515406154071540815409154101541115412154131541415415154161541715418154191542015421154221542315424154251542615427154281542915430154311543215433154341543515436154371543815439154401544115442154431544415445154461544715448154491545015451154521545315454154551545615457154581545915460154611546215463154641546515466154671546815469154701547115472154731547415475154761547715478154791548015481154821548315484154851548615487154881548915490154911549215493154941549515496154971549815499155001550115502155031550415505155061550715508155091551015511155121551315514155151551615517155181551915520155211552215523155241552515526155271552815529155301553115532155331553415535155361553715538155391554015541155421554315544155451554615547155481554915550155511555215553155541555515556155571555815559155601556115562155631556415565155661556715568155691557015571155721557315574155751557615577155781557915580155811558215583155841558515586155871558815589155901559115592155931559415595155961559715598155991560015601156021560315604156051560615607156081560915610156111561215613156141561515616156171561815619156201562115622156231562415625156261562715628156291563015631156321563315634156351563615637156381563915640156411564215643156441564515646156471564815649156501565115652156531565415655156561565715658156591566015661156621566315664156651566615667156681566915670156711567215673156741567515676156771567815679156801568115682156831568415685156861568715688156891569015691156921569315694156951569615697156981569915700157011570215703157041570515706157071570815709157101571115712157131571415715157161571715718157191572015721157221572315724157251572615727157281572915730157311573215733157341573515736157371573815739157401574115742157431574415745157461574715748157491575015751157521575315754157551575615757157581575915760157611576215763157641576515766157671576815769157701577115772157731577415775157761577715778157791578015781157821578315784157851578615787157881578915790157911579215793157941579515796157971579815799158001580115802158031580415805158061580715808158091581015811158121581315814158151581615817158181581915820158211582215823158241582515826158271582815829158301583115832158331583415835158361583715838158391584015841158421584315844158451584615847158481584915850158511585215853158541585515856158571585815859158601586115862158631586415865158661586715868158691587015871158721587315874158751587615877158781587915880158811588215883158841588515886158871588815889158901589115892158931589415895158961589715898158991590015901159021590315904159051590615907159081590915910159111591215913159141591515916159171591815919159201592115922159231592415925159261592715928159291593015931159321593315934159351593615937159381593915940159411594215943159441594515946159471594815949159501595115952159531595415955159561595715958159591596015961159621596315964159651596615967159681596915970159711597215973159741597515976159771597815979159801598115982159831598415985159861598715988159891599015991159921599315994159951599615997159981599916000160011600216003160041600516006160071600816009160101601116012160131601416015160161601716018160191602016021160221602316024160251602616027160281602916030160311603216033160341603516036160371603816039160401604116042160431604416045160461604716048160491605016051160521605316054160551605616057160581605916060160611606216063160641606516066160671606816069160701607116072160731607416075160761607716078160791608016081160821608316084160851608616087160881608916090160911609216093160941609516096160971609816099161001610116102161031610416105161061610716108161091611016111161121611316114161151611616117161181611916120161211612216123161241612516126161271612816129161301613116132161331613416135161361613716138161391614016141161421614316144161451614616147161481614916150161511615216153161541615516156161571615816159161601616116162161631616416165161661616716168161691617016171161721617316174161751617616177161781617916180161811618216183161841618516186161871618816189161901619116192161931619416195161961619716198161991620016201162021620316204162051620616207162081620916210162111621216213162141621516216162171621816219162201622116222162231622416225162261622716228162291623016231162321623316234162351623616237162381623916240162411624216243162441624516246162471624816249162501625116252162531625416255162561625716258162591626016261162621626316264162651626616267162681626916270162711627216273162741627516276162771627816279162801628116282162831628416285162861628716288162891629016291162921629316294162951629616297162981629916300163011630216303163041630516306163071630816309163101631116312163131631416315163161631716318163191632016321163221632316324163251632616327163281632916330163311633216333163341633516336163371633816339163401634116342163431634416345163461634716348163491635016351163521635316354163551635616357163581635916360163611636216363163641636516366163671636816369163701637116372163731637416375163761637716378163791638016381163821638316384163851638616387163881638916390163911639216393163941639516396163971639816399164001640116402164031640416405164061640716408164091641016411164121641316414164151641616417164181641916420164211642216423164241642516426164271642816429164301643116432164331643416435164361643716438164391644016441164421644316444164451644616447164481644916450164511645216453164541645516456164571645816459164601646116462164631646416465164661646716468164691647016471164721647316474164751647616477164781647916480164811648216483164841648516486164871648816489164901649116492164931649416495164961649716498164991650016501165021650316504165051650616507165081650916510165111651216513165141651516516165171651816519165201652116522165231652416525165261652716528165291653016531165321653316534165351653616537165381653916540165411654216543165441654516546165471654816549165501655116552165531655416555165561655716558165591656016561165621656316564165651656616567165681656916570165711657216573165741657516576165771657816579165801658116582165831658416585165861658716588165891659016591165921659316594165951659616597165981659916600166011660216603166041660516606166071660816609166101661116612166131661416615166161661716618166191662016621166221662316624166251662616627166281662916630166311663216633166341663516636166371663816639166401664116642166431664416645166461664716648166491665016651166521665316654166551665616657166581665916660166611666216663166641666516666166671666816669166701667116672166731667416675166761667716678166791668016681166821668316684166851668616687166881668916690166911669216693166941669516696166971669816699167001670116702167031670416705167061670716708167091671016711167121671316714167151671616717167181671916720167211672216723167241672516726167271672816729167301673116732167331673416735167361673716738167391674016741167421674316744167451674616747167481674916750167511675216753167541675516756167571675816759167601676116762167631676416765167661676716768167691677016771167721677316774167751677616777167781677916780167811678216783167841678516786167871678816789167901679116792167931679416795167961679716798167991680016801168021680316804168051680616807168081680916810168111681216813168141681516816168171681816819168201682116822168231682416825168261682716828168291683016831168321683316834168351683616837168381683916840168411684216843168441684516846168471684816849168501685116852168531685416855168561685716858168591686016861168621686316864168651686616867168681686916870168711687216873168741687516876168771687816879168801688116882168831688416885168861688716888168891689016891168921689316894168951689616897168981689916900169011690216903169041690516906169071690816909169101691116912169131691416915169161691716918169191692016921169221692316924169251692616927169281692916930169311693216933169341693516936169371693816939169401694116942169431694416945169461694716948169491695016951169521695316954169551695616957169581695916960169611696216963169641696516966169671696816969169701697116972169731697416975169761697716978169791698016981169821698316984169851698616987169881698916990169911699216993169941699516996169971699816999170001700117002170031700417005170061700717008170091701017011170121701317014170151701617017170181701917020170211702217023170241702517026170271702817029170301703117032170331703417035170361703717038170391704017041170421704317044170451704617047170481704917050170511705217053170541705517056170571705817059170601706117062170631706417065170661706717068170691707017071170721707317074170751707617077170781707917080170811708217083170841708517086170871708817089170901709117092170931709417095170961709717098170991710017101171021710317104171051710617107171081710917110171111711217113171141711517116171171711817119171201712117122171231712417125171261712717128171291713017131171321713317134171351713617137171381713917140171411714217143171441714517146171471714817149171501715117152171531715417155171561715717158171591716017161171621716317164171651716617167171681716917170171711717217173171741717517176171771717817179171801718117182171831718417185171861718717188171891719017191171921719317194171951719617197171981719917200172011720217203172041720517206172071720817209172101721117212172131721417215172161721717218172191722017221172221722317224172251722617227172281722917230172311723217233172341723517236172371723817239172401724117242172431724417245172461724717248172491725017251172521725317254172551725617257172581725917260172611726217263172641726517266172671726817269172701727117272172731727417275172761727717278172791728017281172821728317284172851728617287172881728917290172911729217293172941729517296172971729817299173001730117302173031730417305173061730717308173091731017311173121731317314173151731617317173181731917320173211732217323173241732517326173271732817329173301733117332173331733417335173361733717338173391734017341173421734317344173451734617347173481734917350173511735217353173541735517356173571735817359173601736117362173631736417365173661736717368173691737017371173721737317374173751737617377173781737917380173811738217383173841738517386173871738817389173901739117392173931739417395173961739717398173991740017401174021740317404174051740617407174081740917410174111741217413174141741517416174171741817419174201742117422174231742417425174261742717428174291743017431174321743317434174351743617437174381743917440174411744217443174441744517446174471744817449174501745117452174531745417455174561745717458174591746017461174621746317464174651746617467174681746917470174711747217473174741747517476174771747817479174801748117482174831748417485174861748717488174891749017491174921749317494174951749617497174981749917500175011750217503175041750517506175071750817509175101751117512175131751417515175161751717518175191752017521175221752317524175251752617527175281752917530175311753217533175341753517536175371753817539175401754117542175431754417545175461754717548175491755017551175521755317554175551755617557175581755917560175611756217563175641756517566175671756817569175701757117572175731757417575175761757717578175791758017581175821758317584175851758617587175881758917590175911759217593175941759517596175971759817599176001760117602176031760417605176061760717608176091761017611176121761317614176151761617617176181761917620176211762217623176241762517626176271762817629176301763117632176331763417635176361763717638176391764017641176421764317644176451764617647176481764917650176511765217653176541765517656176571765817659176601766117662176631766417665176661766717668176691767017671176721767317674176751767617677176781767917680176811768217683176841768517686176871768817689176901769117692176931769417695176961769717698176991770017701177021770317704177051770617707177081770917710177111771217713177141771517716177171771817719177201772117722177231772417725177261772717728177291773017731177321773317734177351773617737177381773917740177411774217743177441774517746177471774817749177501775117752177531775417755177561775717758177591776017761177621776317764177651776617767177681776917770177711777217773177741777517776177771777817779177801778117782177831778417785177861778717788177891779017791177921779317794177951779617797177981779917800178011780217803178041780517806178071780817809178101781117812178131781417815178161781717818178191782017821178221782317824178251782617827178281782917830178311783217833178341783517836178371783817839178401784117842178431784417845178461784717848178491785017851178521785317854178551785617857178581785917860178611786217863178641786517866178671786817869178701787117872178731787417875178761787717878178791788017881178821788317884178851788617887178881788917890178911789217893178941789517896178971789817899179001790117902179031790417905179061790717908179091791017911179121791317914179151791617917179181791917920179211792217923179241792517926179271792817929179301793117932179331793417935179361793717938179391794017941179421794317944179451794617947179481794917950179511795217953179541795517956179571795817959179601796117962179631796417965179661796717968179691797017971179721797317974179751797617977179781797917980179811798217983179841798517986179871798817989179901799117992179931799417995179961799717998179991800018001180021800318004180051800618007180081800918010180111801218013180141801518016180171801818019180201802118022180231802418025180261802718028180291803018031180321803318034180351803618037180381803918040180411804218043180441804518046180471804818049180501805118052180531805418055180561805718058180591806018061180621806318064180651806618067180681806918070180711807218073180741807518076180771807818079180801808118082180831808418085180861808718088180891809018091180921809318094180951809618097180981809918100181011810218103181041810518106181071810818109181101811118112181131811418115181161811718118181191812018121181221812318124181251812618127181281812918130181311813218133181341813518136181371813818139181401814118142181431814418145181461814718148181491815018151181521815318154181551815618157181581815918160181611816218163181641816518166181671816818169181701817118172181731817418175181761817718178181791818018181181821818318184181851818618187181881818918190181911819218193181941819518196181971819818199182001820118202182031820418205182061820718208182091821018211182121821318214182151821618217182181821918220182211822218223182241822518226182271822818229182301823118232182331823418235182361823718238182391824018241182421824318244182451824618247182481824918250182511825218253182541825518256182571825818259182601826118262182631826418265182661826718268182691827018271182721827318274182751827618277182781827918280182811828218283182841828518286182871828818289182901829118292182931829418295182961829718298182991830018301183021830318304183051830618307183081830918310183111831218313183141831518316183171831818319183201832118322183231832418325183261832718328183291833018331183321833318334183351833618337183381833918340183411834218343183441834518346183471834818349183501835118352183531835418355183561835718358183591836018361183621836318364183651836618367183681836918370183711837218373183741837518376183771837818379183801838118382183831838418385183861838718388183891839018391183921839318394183951839618397183981839918400184011840218403184041840518406184071840818409184101841118412184131841418415184161841718418184191842018421184221842318424184251842618427184281842918430184311843218433184341843518436184371843818439184401844118442184431844418445184461844718448184491845018451184521845318454184551845618457184581845918460184611846218463184641846518466184671846818469184701847118472184731847418475184761847718478184791848018481184821848318484184851848618487184881848918490184911849218493184941849518496184971849818499185001850118502185031850418505185061850718508185091851018511185121851318514185151851618517185181851918520185211852218523185241852518526185271852818529185301853118532185331853418535185361853718538185391854018541185421854318544185451854618547185481854918550185511855218553185541855518556185571855818559185601856118562185631856418565185661856718568185691857018571185721857318574185751857618577185781857918580185811858218583185841858518586185871858818589185901859118592185931859418595185961859718598185991860018601186021860318604186051860618607186081860918610186111861218613186141861518616186171861818619186201862118622186231862418625186261862718628186291863018631186321863318634186351863618637186381863918640186411864218643186441864518646186471864818649186501865118652186531865418655186561865718658186591866018661186621866318664186651866618667186681866918670186711867218673186741867518676186771867818679186801868118682186831868418685186861868718688186891869018691186921869318694186951869618697186981869918700187011870218703187041870518706187071870818709187101871118712187131871418715187161871718718187191872018721187221872318724187251872618727187281872918730187311873218733187341873518736187371873818739187401874118742187431874418745187461874718748187491875018751187521875318754187551875618757187581875918760187611876218763187641876518766187671876818769187701877118772187731877418775187761877718778187791878018781187821878318784187851878618787187881878918790187911879218793187941879518796187971879818799188001880118802188031880418805188061880718808188091881018811188121881318814188151881618817188181881918820188211882218823188241882518826188271882818829188301883118832188331883418835188361883718838188391884018841188421884318844188451884618847188481884918850188511885218853188541885518856188571885818859188601886118862188631886418865188661886718868188691887018871188721887318874188751887618877188781887918880188811888218883188841888518886188871888818889188901889118892188931889418895188961889718898188991890018901189021890318904189051890618907189081890918910189111891218913189141891518916189171891818919189201892118922189231892418925189261892718928189291893018931189321893318934189351893618937189381893918940189411894218943189441894518946189471894818949189501895118952189531895418955189561895718958189591896018961189621896318964189651896618967189681896918970189711897218973189741897518976189771897818979189801898118982189831898418985189861898718988189891899018991189921899318994189951899618997189981899919000190011900219003190041900519006190071900819009190101901119012190131901419015190161901719018190191902019021190221902319024190251902619027190281902919030190311903219033190341903519036190371903819039190401904119042190431904419045190461904719048190491905019051190521905319054190551905619057190581905919060190611906219063190641906519066190671906819069190701907119072190731907419075190761907719078190791908019081190821908319084190851908619087190881908919090190911909219093190941909519096190971909819099191001910119102191031910419105191061910719108191091911019111191121911319114191151911619117191181911919120191211912219123191241912519126191271912819129191301913119132191331913419135191361913719138191391914019141191421914319144191451914619147191481914919150191511915219153191541915519156191571915819159191601916119162191631916419165191661916719168191691917019171191721917319174191751917619177191781917919180191811918219183191841918519186191871918819189191901919119192191931919419195191961919719198191991920019201192021920319204192051920619207192081920919210192111921219213192141921519216192171921819219192201922119222192231922419225192261922719228192291923019231192321923319234192351923619237192381923919240192411924219243192441924519246192471924819249192501925119252192531925419255192561925719258192591926019261192621926319264192651926619267192681926919270192711927219273192741927519276192771927819279192801928119282192831928419285192861928719288192891929019291192921929319294192951929619297192981929919300193011930219303193041930519306193071930819309193101931119312193131931419315193161931719318193191932019321193221932319324193251932619327193281932919330193311933219333193341933519336193371933819339193401934119342193431934419345193461934719348193491935019351193521935319354193551935619357193581935919360193611936219363193641936519366193671936819369193701937119372193731937419375193761937719378193791938019381193821938319384193851938619387193881938919390193911939219393193941939519396193971939819399194001940119402194031940419405194061940719408194091941019411194121941319414194151941619417194181941919420194211942219423194241942519426194271942819429194301943119432194331943419435194361943719438194391944019441194421944319444194451944619447194481944919450194511945219453194541945519456194571945819459194601946119462194631946419465194661946719468194691947019471194721947319474194751947619477194781947919480194811948219483194841948519486194871948819489194901949119492194931949419495194961949719498194991950019501195021950319504195051950619507195081950919510195111951219513195141951519516195171951819519195201952119522195231952419525195261952719528195291953019531195321953319534195351953619537195381953919540195411954219543195441954519546195471954819549195501955119552195531955419555195561955719558195591956019561195621956319564195651956619567195681956919570195711957219573195741957519576195771957819579195801958119582195831958419585195861958719588195891959019591195921959319594195951959619597195981959919600196011960219603196041960519606196071960819609196101961119612196131961419615196161961719618196191962019621196221962319624196251962619627196281962919630196311963219633196341963519636196371963819639196401964119642196431964419645196461964719648196491965019651196521965319654196551965619657196581965919660196611966219663196641966519666196671966819669196701967119672196731967419675196761967719678196791968019681196821968319684196851968619687196881968919690196911969219693196941969519696196971969819699197001970119702197031970419705197061970719708197091971019711197121971319714197151971619717197181971919720197211972219723197241972519726197271972819729197301973119732197331973419735197361973719738197391974019741197421974319744197451974619747197481974919750197511975219753197541975519756197571975819759197601976119762197631976419765197661976719768197691977019771197721977319774197751977619777197781977919780197811978219783197841978519786197871978819789197901979119792197931979419795197961979719798197991980019801198021980319804198051980619807198081980919810198111981219813198141981519816198171981819819198201982119822198231982419825198261982719828198291983019831198321983319834198351983619837198381983919840198411984219843198441984519846198471984819849198501985119852198531985419855198561985719858198591986019861198621986319864198651986619867198681986919870198711987219873198741987519876198771987819879198801988119882198831988419885198861988719888198891989019891198921989319894198951989619897198981989919900199011990219903199041990519906199071990819909199101991119912199131991419915199161991719918199191992019921199221992319924199251992619927199281992919930199311993219933199341993519936199371993819939199401994119942199431994419945199461994719948199491995019951199521995319954199551995619957199581995919960199611996219963199641996519966199671996819969199701997119972199731997419975199761997719978199791998019981199821998319984199851998619987199881998919990199911999219993199941999519996199971999819999200002000120002200032000420005200062000720008200092001020011200122001320014200152001620017200182001920020200212002220023200242002520026200272002820029200302003120032200332003420035200362003720038200392004020041200422004320044200452004620047200482004920050200512005220053200542005520056200572005820059200602006120062200632006420065200662006720068200692007020071200722007320074200752007620077200782007920080200812008220083200842008520086200872008820089200902009120092200932009420095200962009720098200992010020101201022010320104201052010620107201082010920110201112011220113201142011520116201172011820119201202012120122201232012420125201262012720128201292013020131201322013320134201352013620137201382013920140201412014220143201442014520146201472014820149201502015120152201532015420155201562015720158201592016020161201622016320164201652016620167201682016920170201712017220173201742017520176201772017820179201802018120182201832018420185201862018720188201892019020191201922019320194201952019620197201982019920200202012020220203202042020520206202072020820209202102021120212202132021420215202162021720218202192022020221202222022320224202252022620227202282022920230202312023220233202342023520236202372023820239202402024120242202432024420245202462024720248202492025020251202522025320254202552025620257202582025920260202612026220263202642026520266202672026820269202702027120272202732027420275202762027720278202792028020281202822028320284202852028620287202882028920290202912029220293202942029520296202972029820299203002030120302203032030420305203062030720308203092031020311203122031320314203152031620317203182031920320203212032220323203242032520326203272032820329203302033120332203332033420335203362033720338203392034020341203422034320344203452034620347203482034920350203512035220353203542035520356203572035820359203602036120362203632036420365203662036720368203692037020371203722037320374203752037620377203782037920380203812038220383203842038520386203872038820389203902039120392203932039420395203962039720398203992040020401204022040320404204052040620407204082040920410204112041220413204142041520416204172041820419204202042120422204232042420425204262042720428204292043020431204322043320434204352043620437204382043920440204412044220443204442044520446204472044820449204502045120452204532045420455204562045720458204592046020461204622046320464204652046620467204682046920470204712047220473204742047520476204772047820479204802048120482204832048420485204862048720488204892049020491204922049320494204952049620497204982049920500205012050220503205042050520506205072050820509205102051120512205132051420515205162051720518205192052020521205222052320524205252052620527205282052920530205312053220533205342053520536205372053820539205402054120542205432054420545205462054720548205492055020551205522055320554205552055620557205582055920560205612056220563205642056520566205672056820569205702057120572205732057420575205762057720578205792058020581205822058320584205852058620587205882058920590205912059220593205942059520596205972059820599206002060120602206032060420605206062060720608206092061020611206122061320614206152061620617206182061920620206212062220623206242062520626206272062820629206302063120632206332063420635206362063720638206392064020641206422064320644206452064620647206482064920650206512065220653206542065520656206572065820659206602066120662206632066420665206662066720668206692067020671206722067320674206752067620677206782067920680206812068220683206842068520686206872068820689206902069120692206932069420695206962069720698206992070020701207022070320704207052070620707207082070920710207112071220713207142071520716207172071820719207202072120722207232072420725207262072720728207292073020731207322073320734207352073620737207382073920740207412074220743207442074520746207472074820749207502075120752207532075420755207562075720758207592076020761207622076320764207652076620767207682076920770207712077220773207742077520776207772077820779207802078120782207832078420785207862078720788207892079020791207922079320794207952079620797207982079920800208012080220803208042080520806208072080820809208102081120812208132081420815208162081720818208192082020821208222082320824208252082620827208282082920830208312083220833208342083520836208372083820839208402084120842208432084420845208462084720848208492085020851208522085320854208552085620857208582085920860208612086220863208642086520866208672086820869208702087120872208732087420875208762087720878208792088020881208822088320884208852088620887208882088920890208912089220893208942089520896208972089820899209002090120902209032090420905209062090720908209092091020911209122091320914209152091620917209182091920920209212092220923209242092520926209272092820929209302093120932209332093420935209362093720938209392094020941209422094320944209452094620947209482094920950209512095220953209542095520956209572095820959209602096120962209632096420965209662096720968209692097020971209722097320974209752097620977209782097920980209812098220983209842098520986209872098820989209902099120992209932099420995209962099720998209992100021001210022100321004210052100621007210082100921010210112101221013210142101521016210172101821019210202102121022210232102421025210262102721028210292103021031210322103321034210352103621037210382103921040210412104221043210442104521046210472104821049210502105121052210532105421055210562105721058210592106021061210622106321064210652106621067210682106921070210712107221073210742107521076210772107821079210802108121082210832108421085210862108721088210892109021091210922109321094210952109621097210982109921100211012110221103211042110521106211072110821109211102111121112211132111421115211162111721118211192112021121211222112321124211252112621127211282112921130211312113221133211342113521136211372113821139211402114121142211432114421145211462114721148211492115021151211522115321154211552115621157211582115921160211612116221163211642116521166211672116821169211702117121172211732117421175211762117721178211792118021181211822118321184211852118621187211882118921190211912119221193211942119521196211972119821199212002120121202212032120421205212062120721208212092121021211212122121321214212152121621217212182121921220212212122221223212242122521226212272122821229212302123121232212332123421235212362123721238212392124021241212422124321244212452124621247212482124921250212512125221253212542125521256212572125821259212602126121262212632126421265212662126721268212692127021271212722127321274212752127621277212782127921280212812128221283212842128521286212872128821289212902129121292212932129421295212962129721298212992130021301213022130321304213052130621307213082130921310213112131221313213142131521316213172131821319213202132121322213232132421325213262132721328213292133021331213322133321334213352133621337213382133921340213412134221343213442134521346213472134821349213502135121352213532135421355213562135721358213592136021361213622136321364213652136621367213682136921370213712137221373213742137521376213772137821379213802138121382213832138421385213862138721388213892139021391213922139321394213952139621397213982139921400214012140221403214042140521406214072140821409214102141121412214132141421415214162141721418214192142021421214222142321424214252142621427214282142921430214312143221433214342143521436214372143821439214402144121442214432144421445214462144721448214492145021451214522145321454214552145621457214582145921460214612146221463214642146521466214672146821469214702147121472214732147421475214762147721478214792148021481214822148321484214852148621487214882148921490214912149221493214942149521496214972149821499215002150121502215032150421505215062150721508215092151021511215122151321514215152151621517215182151921520215212152221523215242152521526215272152821529215302153121532215332153421535215362153721538215392154021541215422154321544215452154621547215482154921550215512155221553215542155521556215572155821559215602156121562215632156421565215662156721568215692157021571215722157321574215752157621577215782157921580215812158221583215842158521586215872158821589215902159121592215932159421595215962159721598215992160021601216022160321604216052160621607216082160921610216112161221613216142161521616216172161821619216202162121622216232162421625216262162721628216292163021631216322163321634216352163621637216382163921640216412164221643216442164521646216472164821649216502165121652216532165421655216562165721658216592166021661216622166321664216652166621667216682166921670216712167221673216742167521676216772167821679216802168121682216832168421685216862168721688216892169021691216922169321694216952169621697216982169921700217012170221703217042170521706217072170821709217102171121712217132171421715217162171721718217192172021721217222172321724217252172621727217282172921730217312173221733217342173521736217372173821739217402174121742217432174421745217462174721748217492175021751217522175321754217552175621757217582175921760217612176221763217642176521766217672176821769217702177121772217732177421775217762177721778217792178021781217822178321784217852178621787217882178921790217912179221793217942179521796217972179821799218002180121802218032180421805218062180721808218092181021811218122181321814218152181621817218182181921820218212182221823218242182521826218272182821829218302183121832218332183421835218362183721838218392184021841218422184321844218452184621847218482184921850218512185221853218542185521856218572185821859218602186121862218632186421865218662186721868218692187021871218722187321874218752187621877218782187921880218812188221883218842188521886218872188821889218902189121892218932189421895218962189721898218992190021901219022190321904219052190621907219082190921910219112191221913219142191521916219172191821919219202192121922219232192421925219262192721928219292193021931219322193321934219352193621937219382193921940219412194221943219442194521946219472194821949219502195121952219532195421955219562195721958219592196021961219622196321964219652196621967219682196921970219712197221973219742197521976219772197821979219802198121982219832198421985219862198721988219892199021991219922199321994219952199621997219982199922000220012200222003220042200522006220072200822009220102201122012220132201422015220162201722018220192202022021220222202322024220252202622027220282202922030220312203222033220342203522036220372203822039220402204122042220432204422045220462204722048220492205022051220522205322054220552205622057220582205922060220612206222063220642206522066220672206822069220702207122072220732207422075220762207722078220792208022081220822208322084220852208622087220882208922090220912209222093220942209522096220972209822099221002210122102221032210422105221062210722108221092211022111221122211322114221152211622117221182211922120221212212222123221242212522126221272212822129221302213122132221332213422135221362213722138221392214022141221422214322144221452214622147221482214922150221512215222153221542215522156221572215822159221602216122162221632216422165221662216722168221692217022171221722217322174221752217622177221782217922180221812218222183221842218522186221872218822189221902219122192221932219422195221962219722198221992220022201222022220322204222052220622207222082220922210222112221222213222142221522216222172221822219222202222122222222232222422225222262222722228222292223022231222322223322234222352223622237222382223922240222412224222243222442224522246222472224822249222502225122252222532225422255222562225722258222592226022261222622226322264222652226622267222682226922270222712227222273222742227522276222772227822279222802228122282222832228422285222862228722288222892229022291222922229322294222952229622297222982229922300223012230222303223042230522306223072230822309223102231122312223132231422315223162231722318223192232022321223222232322324223252232622327223282232922330223312233222333223342233522336223372233822339223402234122342223432234422345223462234722348223492235022351223522235322354223552235622357223582235922360223612236222363223642236522366223672236822369223702237122372223732237422375223762237722378223792238022381223822238322384223852238622387223882238922390223912239222393223942239522396223972239822399224002240122402224032240422405224062240722408224092241022411224122241322414224152241622417224182241922420224212242222423224242242522426224272242822429224302243122432224332243422435224362243722438224392244022441224422244322444224452244622447224482244922450224512245222453224542245522456224572245822459224602246122462224632246422465224662246722468224692247022471224722247322474224752247622477224782247922480224812248222483224842248522486224872248822489224902249122492224932249422495224962249722498224992250022501225022250322504225052250622507225082250922510225112251222513225142251522516225172251822519225202252122522225232252422525225262252722528225292253022531225322253322534225352253622537225382253922540225412254222543225442254522546225472254822549225502255122552225532255422555225562255722558225592256022561225622256322564225652256622567225682256922570225712257222573225742257522576225772257822579225802258122582225832258422585225862258722588225892259022591225922259322594225952259622597225982259922600226012260222603226042260522606226072260822609226102261122612226132261422615226162261722618226192262022621226222262322624226252262622627226282262922630226312263222633226342263522636226372263822639226402264122642226432264422645226462264722648226492265022651226522265322654226552265622657226582265922660226612266222663226642266522666226672266822669226702267122672226732267422675226762267722678226792268022681226822268322684226852268622687226882268922690226912269222693226942269522696226972269822699227002270122702227032270422705227062270722708227092271022711227122271322714227152271622717227182271922720227212272222723227242272522726227272272822729227302273122732227332273422735227362273722738227392274022741227422274322744227452274622747227482274922750227512275222753227542275522756227572275822759227602276122762227632276422765227662276722768227692277022771227722277322774227752277622777227782277922780227812278222783227842278522786227872278822789227902279122792227932279422795227962279722798227992280022801228022280322804228052280622807228082280922810228112281222813228142281522816228172281822819228202282122822228232282422825228262282722828228292283022831228322283322834228352283622837228382283922840228412284222843228442284522846228472284822849228502285122852228532285422855228562285722858228592286022861228622286322864228652286622867228682286922870228712287222873228742287522876228772287822879228802288122882228832288422885228862288722888228892289022891228922289322894228952289622897228982289922900229012290222903229042290522906229072290822909229102291122912229132291422915229162291722918229192292022921229222292322924229252292622927229282292922930229312293222933229342293522936229372293822939229402294122942229432294422945229462294722948229492295022951229522295322954229552295622957229582295922960229612296222963229642296522966229672296822969229702297122972229732297422975229762297722978229792298022981229822298322984229852298622987229882298922990229912299222993229942299522996229972299822999230002300123002230032300423005230062300723008230092301023011230122301323014230152301623017230182301923020230212302223023230242302523026230272302823029230302303123032230332303423035230362303723038230392304023041230422304323044230452304623047230482304923050230512305223053230542305523056230572305823059230602306123062230632306423065230662306723068230692307023071230722307323074230752307623077230782307923080230812308223083230842308523086230872308823089230902309123092230932309423095230962309723098230992310023101231022310323104231052310623107231082310923110231112311223113231142311523116231172311823119231202312123122231232312423125231262312723128231292313023131231322313323134231352313623137231382313923140231412314223143231442314523146231472314823149231502315123152231532315423155231562315723158231592316023161231622316323164231652316623167231682316923170231712317223173231742317523176231772317823179231802318123182231832318423185231862318723188231892319023191231922319323194231952319623197231982319923200232012320223203232042320523206232072320823209232102321123212232132321423215232162321723218232192322023221232222322323224232252322623227232282322923230232312323223233232342323523236232372323823239232402324123242232432324423245232462324723248232492325023251232522325323254232552325623257232582325923260232612326223263232642326523266232672326823269232702327123272232732327423275232762327723278232792328023281232822328323284232852328623287232882328923290232912329223293232942329523296232972329823299233002330123302233032330423305233062330723308233092331023311233122331323314233152331623317233182331923320233212332223323233242332523326233272332823329233302333123332233332333423335233362333723338233392334023341233422334323344233452334623347233482334923350233512335223353233542335523356233572335823359233602336123362233632336423365233662336723368233692337023371233722337323374233752337623377233782337923380233812338223383233842338523386233872338823389233902339123392233932339423395233962339723398233992340023401234022340323404234052340623407234082340923410234112341223413234142341523416234172341823419234202342123422234232342423425234262342723428234292343023431234322343323434234352343623437234382343923440234412344223443234442344523446234472344823449234502345123452234532345423455234562345723458234592346023461234622346323464234652346623467234682346923470234712347223473234742347523476234772347823479234802348123482234832348423485234862348723488234892349023491234922349323494234952349623497234982349923500235012350223503235042350523506235072350823509235102351123512235132351423515235162351723518235192352023521235222352323524235252352623527235282352923530235312353223533235342353523536235372353823539235402354123542235432354423545235462354723548235492355023551235522355323554235552355623557235582355923560235612356223563235642356523566235672356823569235702357123572235732357423575235762357723578235792358023581235822358323584235852358623587235882358923590235912359223593235942359523596235972359823599236002360123602236032360423605236062360723608236092361023611236122361323614236152361623617236182361923620236212362223623236242362523626236272362823629236302363123632236332363423635236362363723638236392364023641236422364323644236452364623647236482364923650236512365223653236542365523656236572365823659236602366123662236632366423665236662366723668236692367023671236722367323674236752367623677236782367923680236812368223683236842368523686236872368823689236902369123692236932369423695236962369723698236992370023701237022370323704237052370623707237082370923710237112371223713237142371523716237172371823719237202372123722237232372423725237262372723728237292373023731237322373323734237352373623737237382373923740237412374223743237442374523746237472374823749237502375123752237532375423755237562375723758237592376023761237622376323764237652376623767237682376923770237712377223773237742377523776237772377823779237802378123782237832378423785237862378723788237892379023791237922379323794237952379623797237982379923800238012380223803238042380523806238072380823809238102381123812238132381423815238162381723818238192382023821238222382323824238252382623827238282382923830238312383223833238342383523836238372383823839238402384123842238432384423845238462384723848238492385023851238522385323854238552385623857238582385923860238612386223863238642386523866238672386823869238702387123872238732387423875238762387723878238792388023881238822388323884238852388623887238882388923890238912389223893238942389523896238972389823899239002390123902239032390423905239062390723908239092391023911239122391323914239152391623917239182391923920239212392223923239242392523926239272392823929239302393123932239332393423935239362393723938239392394023941239422394323944239452394623947239482394923950239512395223953239542395523956239572395823959239602396123962239632396423965239662396723968239692397023971239722397323974239752397623977239782397923980239812398223983239842398523986239872398823989239902399123992239932399423995239962399723998239992400024001240022400324004240052400624007240082400924010240112401224013240142401524016240172401824019240202402124022240232402424025240262402724028240292403024031240322403324034240352403624037240382403924040240412404224043240442404524046240472404824049240502405124052240532405424055240562405724058240592406024061240622406324064240652406624067240682406924070240712407224073240742407524076240772407824079240802408124082240832408424085240862408724088240892409024091240922409324094240952409624097240982409924100241012410224103241042410524106241072410824109241102411124112241132411424115241162411724118241192412024121241222412324124241252412624127241282412924130241312413224133241342413524136241372413824139241402414124142241432414424145241462414724148241492415024151241522415324154241552415624157241582415924160241612416224163241642416524166241672416824169241702417124172241732417424175241762417724178241792418024181241822418324184241852418624187241882418924190241912419224193241942419524196241972419824199242002420124202242032420424205242062420724208242092421024211242122421324214242152421624217242182421924220242212422224223242242422524226242272422824229242302423124232242332423424235242362423724238242392424024241242422424324244242452424624247242482424924250242512425224253242542425524256242572425824259242602426124262242632426424265242662426724268242692427024271242722427324274242752427624277242782427924280242812428224283242842428524286242872428824289242902429124292242932429424295242962429724298242992430024301243022430324304243052430624307243082430924310243112431224313243142431524316243172431824319243202432124322243232432424325243262432724328243292433024331243322433324334243352433624337243382433924340243412434224343243442434524346243472434824349243502435124352243532435424355243562435724358243592436024361243622436324364243652436624367243682436924370243712437224373243742437524376243772437824379243802438124382243832438424385243862438724388243892439024391243922439324394243952439624397243982439924400244012440224403244042440524406244072440824409244102441124412244132441424415244162441724418244192442024421244222442324424244252442624427244282442924430244312443224433244342443524436244372443824439244402444124442244432444424445244462444724448244492445024451244522445324454244552445624457244582445924460244612446224463244642446524466244672446824469244702447124472244732447424475244762447724478244792448024481244822448324484244852448624487244882448924490244912449224493244942449524496244972449824499245002450124502245032450424505245062450724508245092451024511245122451324514245152451624517245182451924520245212452224523245242452524526245272452824529245302453124532245332453424535245362453724538245392454024541245422454324544245452454624547245482454924550245512455224553245542455524556245572455824559245602456124562245632456424565245662456724568245692457024571245722457324574245752457624577245782457924580245812458224583245842458524586245872458824589245902459124592245932459424595245962459724598245992460024601246022460324604246052460624607246082460924610246112461224613246142461524616246172461824619246202462124622246232462424625246262462724628246292463024631246322463324634246352463624637246382463924640246412464224643246442464524646246472464824649246502465124652246532465424655246562465724658246592466024661246622466324664246652466624667246682466924670246712467224673246742467524676246772467824679246802468124682246832468424685246862468724688246892469024691246922469324694246952469624697246982469924700247012470224703247042470524706247072470824709247102471124712247132471424715247162471724718247192472024721247222472324724247252472624727247282472924730247312473224733247342473524736247372473824739247402474124742247432474424745247462474724748247492475024751247522475324754247552475624757247582475924760247612476224763247642476524766247672476824769247702477124772247732477424775247762477724778247792478024781247822478324784247852478624787247882478924790247912479224793247942479524796247972479824799248002480124802248032480424805248062480724808248092481024811248122481324814248152481624817248182481924820248212482224823248242482524826248272482824829248302483124832248332483424835248362483724838248392484024841248422484324844248452484624847248482484924850248512485224853248542485524856248572485824859248602486124862248632486424865248662486724868248692487024871248722487324874248752487624877248782487924880248812488224883248842488524886248872488824889248902489124892248932489424895248962489724898248992490024901249022490324904249052490624907249082490924910249112491224913249142491524916249172491824919249202492124922249232492424925249262492724928249292493024931249322493324934249352493624937249382493924940249412494224943249442494524946249472494824949249502495124952249532495424955249562495724958249592496024961249622496324964249652496624967249682496924970249712497224973249742497524976249772497824979249802498124982249832498424985249862498724988249892499024991249922499324994249952499624997249982499925000250012500225003250042500525006250072500825009250102501125012250132501425015250162501725018250192502025021250222502325024250252502625027250282502925030250312503225033250342503525036250372503825039250402504125042250432504425045250462504725048250492505025051250522505325054250552505625057250582505925060250612506225063250642506525066250672506825069250702507125072250732507425075250762507725078250792508025081250822508325084250852508625087250882508925090250912509225093250942509525096250972509825099251002510125102251032510425105251062510725108251092511025111251122511325114251152511625117251182511925120251212512225123251242512525126251272512825129251302513125132251332513425135251362513725138251392514025141251422514325144251452514625147251482514925150251512515225153251542515525156251572515825159251602516125162251632516425165251662516725168251692517025171251722517325174251752517625177251782517925180251812518225183251842518525186251872518825189251902519125192251932519425195251962519725198251992520025201252022520325204252052520625207252082520925210252112521225213252142521525216252172521825219252202522125222252232522425225252262522725228252292523025231252322523325234252352523625237252382523925240252412524225243252442524525246252472524825249252502525125252252532525425255252562525725258252592526025261252622526325264252652526625267252682526925270252712527225273252742527525276252772527825279252802528125282252832528425285252862528725288252892529025291252922529325294252952529625297252982529925300253012530225303253042530525306253072530825309253102531125312253132531425315253162531725318253192532025321253222532325324253252532625327253282532925330253312533225333253342533525336253372533825339253402534125342253432534425345253462534725348253492535025351253522535325354253552535625357253582535925360253612536225363253642536525366253672536825369253702537125372253732537425375253762537725378253792538025381253822538325384253852538625387253882538925390253912539225393253942539525396253972539825399254002540125402254032540425405254062540725408254092541025411254122541325414254152541625417254182541925420254212542225423254242542525426254272542825429254302543125432254332543425435254362543725438254392544025441254422544325444254452544625447254482544925450254512545225453254542545525456254572545825459254602546125462254632546425465254662546725468254692547025471254722547325474254752547625477254782547925480254812548225483254842548525486254872548825489254902549125492254932549425495254962549725498254992550025501255022550325504255052550625507255082550925510255112551225513255142551525516255172551825519255202552125522255232552425525255262552725528255292553025531255322553325534255352553625537255382553925540255412554225543255442554525546255472554825549255502555125552255532555425555255562555725558255592556025561255622556325564255652556625567255682556925570255712557225573255742557525576255772557825579255802558125582255832558425585255862558725588255892559025591255922559325594255952559625597255982559925600256012560225603256042560525606256072560825609256102561125612256132561425615256162561725618256192562025621256222562325624256252562625627256282562925630256312563225633256342563525636256372563825639256402564125642256432564425645256462564725648256492565025651256522565325654256552565625657256582565925660256612566225663256642566525666256672566825669256702567125672256732567425675256762567725678256792568025681256822568325684256852568625687256882568925690256912569225693256942569525696256972569825699257002570125702257032570425705257062570725708257092571025711257122571325714257152571625717257182571925720257212572225723257242572525726257272572825729257302573125732257332573425735257362573725738257392574025741257422574325744257452574625747257482574925750257512575225753257542575525756257572575825759257602576125762257632576425765257662576725768257692577025771257722577325774257752577625777257782577925780257812578225783257842578525786257872578825789257902579125792257932579425795257962579725798257992580025801258022580325804258052580625807258082580925810258112581225813258142581525816258172581825819258202582125822258232582425825258262582725828258292583025831258322583325834258352583625837258382583925840258412584225843258442584525846258472584825849258502585125852258532585425855258562585725858258592586025861258622586325864258652586625867258682586925870258712587225873258742587525876258772587825879258802588125882258832588425885258862588725888258892589025891258922589325894258952589625897258982589925900259012590225903259042590525906259072590825909259102591125912259132591425915259162591725918259192592025921259222592325924259252592625927259282592925930259312593225933259342593525936259372593825939259402594125942259432594425945259462594725948259492595025951259522595325954259552595625957259582595925960259612596225963259642596525966259672596825969259702597125972259732597425975259762597725978259792598025981259822598325984259852598625987259882598925990259912599225993259942599525996259972599825999260002600126002260032600426005260062600726008260092601026011260122601326014260152601626017260182601926020260212602226023260242602526026260272602826029260302603126032260332603426035260362603726038260392604026041260422604326044260452604626047260482604926050260512605226053260542605526056260572605826059260602606126062260632606426065260662606726068260692607026071260722607326074260752607626077260782607926080260812608226083260842608526086260872608826089260902609126092260932609426095260962609726098260992610026101261022610326104261052610626107261082610926110261112611226113261142611526116261172611826119261202612126122261232612426125261262612726128261292613026131261322613326134261352613626137261382613926140261412614226143261442614526146261472614826149261502615126152261532615426155261562615726158261592616026161261622616326164261652616626167261682616926170261712617226173261742617526176261772617826179261802618126182261832618426185261862618726188261892619026191261922619326194261952619626197261982619926200262012620226203262042620526206262072620826209262102621126212262132621426215262162621726218262192622026221262222622326224262252622626227262282622926230262312623226233262342623526236262372623826239262402624126242262432624426245262462624726248262492625026251262522625326254262552625626257262582625926260262612626226263262642626526266262672626826269262702627126272262732627426275262762627726278262792628026281262822628326284262852628626287262882628926290262912629226293262942629526296262972629826299263002630126302263032630426305263062630726308263092631026311263122631326314263152631626317263182631926320263212632226323263242632526326263272632826329263302633126332263332633426335263362633726338263392634026341263422634326344263452634626347263482634926350263512635226353263542635526356263572635826359263602636126362263632636426365263662636726368263692637026371263722637326374263752637626377263782637926380263812638226383263842638526386263872638826389263902639126392263932639426395263962639726398263992640026401264022640326404264052640626407264082640926410264112641226413264142641526416264172641826419264202642126422264232642426425264262642726428264292643026431264322643326434264352643626437264382643926440264412644226443264442644526446264472644826449264502645126452264532645426455264562645726458264592646026461264622646326464264652646626467264682646926470264712647226473264742647526476264772647826479264802648126482264832648426485264862648726488264892649026491264922649326494264952649626497264982649926500265012650226503265042650526506265072650826509265102651126512265132651426515265162651726518265192652026521265222652326524265252652626527265282652926530265312653226533265342653526536265372653826539265402654126542265432654426545265462654726548265492655026551265522655326554265552655626557265582655926560265612656226563265642656526566265672656826569265702657126572265732657426575265762657726578265792658026581265822658326584265852658626587265882658926590265912659226593265942659526596265972659826599266002660126602266032660426605266062660726608266092661026611266122661326614266152661626617266182661926620266212662226623266242662526626266272662826629266302663126632266332663426635266362663726638266392664026641266422664326644266452664626647266482664926650266512665226653266542665526656266572665826659266602666126662266632666426665266662666726668266692667026671266722667326674266752667626677266782667926680266812668226683266842668526686266872668826689266902669126692266932669426695266962669726698266992670026701267022670326704267052670626707267082670926710267112671226713267142671526716267172671826719267202672126722267232672426725267262672726728267292673026731267322673326734267352673626737267382673926740267412674226743267442674526746267472674826749267502675126752267532675426755267562675726758267592676026761267622676326764267652676626767267682676926770267712677226773267742677526776267772677826779267802678126782267832678426785267862678726788267892679026791267922679326794267952679626797267982679926800268012680226803268042680526806268072680826809268102681126812268132681426815268162681726818268192682026821268222682326824268252682626827268282682926830268312683226833268342683526836268372683826839268402684126842268432684426845268462684726848268492685026851268522685326854268552685626857268582685926860268612686226863268642686526866268672686826869268702687126872268732687426875268762687726878268792688026881268822688326884268852688626887268882688926890268912689226893268942689526896268972689826899269002690126902269032690426905269062690726908269092691026911269122691326914269152691626917269182691926920269212692226923269242692526926269272692826929269302693126932269332693426935269362693726938269392694026941269422694326944269452694626947269482694926950269512695226953269542695526956269572695826959269602696126962269632696426965269662696726968269692697026971269722697326974269752697626977269782697926980269812698226983269842698526986269872698826989269902699126992269932699426995269962699726998269992700027001270022700327004270052700627007270082700927010270112701227013270142701527016270172701827019270202702127022270232702427025270262702727028270292703027031270322703327034270352703627037270382703927040270412704227043270442704527046270472704827049270502705127052270532705427055270562705727058270592706027061270622706327064270652706627067270682706927070270712707227073270742707527076270772707827079270802708127082270832708427085270862708727088270892709027091270922709327094270952709627097270982709927100271012710227103271042710527106271072710827109271102711127112271132711427115271162711727118271192712027121271222712327124271252712627127271282712927130271312713227133271342713527136271372713827139271402714127142271432714427145271462714727148271492715027151271522715327154271552715627157271582715927160271612716227163271642716527166271672716827169271702717127172271732717427175271762717727178271792718027181271822718327184271852718627187271882718927190271912719227193271942719527196271972719827199272002720127202272032720427205272062720727208272092721027211272122721327214272152721627217272182721927220272212722227223272242722527226272272722827229272302723127232272332723427235272362723727238272392724027241272422724327244272452724627247272482724927250272512725227253272542725527256272572725827259272602726127262272632726427265272662726727268272692727027271272722727327274272752727627277272782727927280272812728227283272842728527286272872728827289272902729127292272932729427295272962729727298272992730027301273022730327304273052730627307273082730927310273112731227313273142731527316273172731827319273202732127322273232732427325273262732727328273292733027331273322733327334273352733627337273382733927340273412734227343273442734527346273472734827349273502735127352273532735427355273562735727358273592736027361273622736327364273652736627367273682736927370273712737227373273742737527376273772737827379273802738127382273832738427385273862738727388273892739027391273922739327394273952739627397273982739927400274012740227403274042740527406274072740827409274102741127412274132741427415274162741727418274192742027421274222742327424274252742627427274282742927430274312743227433274342743527436274372743827439274402744127442274432744427445274462744727448274492745027451274522745327454274552745627457274582745927460274612746227463274642746527466274672746827469274702747127472274732747427475274762747727478274792748027481274822748327484274852748627487274882748927490274912749227493274942749527496274972749827499275002750127502275032750427505275062750727508275092751027511275122751327514275152751627517275182751927520275212752227523275242752527526275272752827529275302753127532275332753427535275362753727538275392754027541275422754327544275452754627547275482754927550275512755227553275542755527556275572755827559275602756127562275632756427565275662756727568275692757027571275722757327574275752757627577275782757927580275812758227583275842758527586275872758827589275902759127592275932759427595275962759727598275992760027601276022760327604276052760627607276082760927610276112761227613276142761527616276172761827619276202762127622276232762427625276262762727628276292763027631276322763327634276352763627637276382763927640276412764227643276442764527646276472764827649276502765127652276532765427655276562765727658276592766027661276622766327664276652766627667276682766927670276712767227673276742767527676276772767827679276802768127682276832768427685276862768727688276892769027691276922769327694276952769627697276982769927700277012770227703277042770527706277072770827709277102771127712277132771427715277162771727718277192772027721277222772327724277252772627727277282772927730277312773227733277342773527736277372773827739277402774127742277432774427745277462774727748277492775027751277522775327754277552775627757277582775927760277612776227763277642776527766277672776827769277702777127772277732777427775277762777727778277792778027781277822778327784277852778627787277882778927790277912779227793277942779527796277972779827799278002780127802278032780427805278062780727808278092781027811278122781327814278152781627817278182781927820278212782227823278242782527826278272782827829278302783127832278332783427835278362783727838278392784027841278422784327844278452784627847278482784927850278512785227853278542785527856278572785827859278602786127862278632786427865278662786727868278692787027871278722787327874278752787627877278782787927880278812788227883278842788527886278872788827889278902789127892278932789427895278962789727898278992790027901279022790327904279052790627907279082790927910279112791227913279142791527916279172791827919279202792127922279232792427925279262792727928279292793027931279322793327934279352793627937279382793927940279412794227943279442794527946279472794827949279502795127952279532795427955279562795727958279592796027961279622796327964279652796627967279682796927970279712797227973279742797527976279772797827979279802798127982279832798427985279862798727988279892799027991279922799327994279952799627997279982799928000280012800228003280042800528006280072800828009280102801128012280132801428015280162801728018280192802028021280222802328024280252802628027280282802928030280312803228033280342803528036280372803828039280402804128042280432804428045280462804728048280492805028051280522805328054280552805628057280582805928060280612806228063280642806528066280672806828069280702807128072280732807428075280762807728078280792808028081280822808328084280852808628087280882808928090280912809228093280942809528096280972809828099281002810128102281032810428105281062810728108281092811028111281122811328114281152811628117281182811928120281212812228123281242812528126281272812828129281302813128132281332813428135281362813728138281392814028141281422814328144281452814628147281482814928150281512815228153281542815528156281572815828159281602816128162281632816428165281662816728168281692817028171281722817328174281752817628177281782817928180281812818228183281842818528186281872818828189281902819128192281932819428195281962819728198281992820028201282022820328204282052820628207282082820928210282112821228213282142821528216282172821828219282202822128222282232822428225282262822728228282292823028231282322823328234282352823628237282382823928240282412824228243282442824528246282472824828249282502825128252282532825428255282562825728258282592826028261282622826328264282652826628267282682826928270282712827228273282742827528276282772827828279282802828128282282832828428285282862828728288282892829028291282922829328294282952829628297282982829928300283012830228303283042830528306283072830828309283102831128312283132831428315283162831728318283192832028321283222832328324283252832628327283282832928330283312833228333283342833528336283372833828339283402834128342283432834428345283462834728348283492835028351283522835328354283552835628357283582835928360283612836228363283642836528366283672836828369283702837128372283732837428375283762837728378283792838028381283822838328384283852838628387283882838928390283912839228393283942839528396283972839828399284002840128402284032840428405284062840728408284092841028411284122841328414284152841628417284182841928420284212842228423284242842528426284272842828429284302843128432284332843428435284362843728438284392844028441284422844328444284452844628447284482844928450284512845228453284542845528456284572845828459284602846128462284632846428465284662846728468284692847028471284722847328474284752847628477284782847928480284812848228483284842848528486284872848828489284902849128492284932849428495284962849728498284992850028501285022850328504285052850628507285082850928510285112851228513285142851528516285172851828519285202852128522285232852428525285262852728528285292853028531285322853328534285352853628537285382853928540285412854228543285442854528546285472854828549285502855128552285532855428555285562855728558285592856028561285622856328564285652856628567285682856928570285712857228573285742857528576285772857828579285802858128582285832858428585285862858728588285892859028591285922859328594285952859628597285982859928600286012860228603286042860528606286072860828609286102861128612286132861428615286162861728618286192862028621286222862328624286252862628627286282862928630286312863228633286342863528636286372863828639286402864128642286432864428645286462864728648286492865028651286522865328654286552865628657286582865928660286612866228663286642866528666286672866828669286702867128672286732867428675286762867728678286792868028681286822868328684286852868628687286882868928690286912869228693286942869528696286972869828699287002870128702287032870428705287062870728708287092871028711287122871328714287152871628717287182871928720287212872228723287242872528726287272872828729287302873128732287332873428735287362873728738287392874028741287422874328744287452874628747287482874928750287512875228753287542875528756287572875828759287602876128762287632876428765287662876728768287692877028771287722877328774287752877628777287782877928780287812878228783287842878528786287872878828789287902879128792287932879428795287962879728798287992880028801288022880328804288052880628807288082880928810288112881228813288142881528816288172881828819288202882128822288232882428825288262882728828288292883028831288322883328834288352883628837288382883928840288412884228843288442884528846288472884828849288502885128852288532885428855288562885728858288592886028861288622886328864288652886628867288682886928870288712887228873288742887528876288772887828879288802888128882288832888428885288862888728888288892889028891288922889328894288952889628897288982889928900289012890228903289042890528906289072890828909289102891128912289132891428915289162891728918289192892028921289222892328924289252892628927289282892928930289312893228933289342893528936289372893828939289402894128942289432894428945289462894728948289492895028951289522895328954289552895628957289582895928960289612896228963289642896528966289672896828969289702897128972289732897428975289762897728978289792898028981289822898328984289852898628987289882898928990289912899228993289942899528996289972899828999290002900129002290032900429005290062900729008290092901029011290122901329014290152901629017290182901929020290212902229023290242902529026290272902829029290302903129032290332903429035290362903729038290392904029041290422904329044290452904629047290482904929050290512905229053290542905529056290572905829059290602906129062290632906429065290662906729068290692907029071290722907329074290752907629077290782907929080290812908229083290842908529086290872908829089290902909129092290932909429095290962909729098290992910029101291022910329104291052910629107291082910929110291112911229113291142911529116291172911829119291202912129122291232912429125291262912729128291292913029131291322913329134291352913629137291382913929140291412914229143291442914529146291472914829149291502915129152291532915429155291562915729158291592916029161291622916329164291652916629167291682916929170291712917229173291742917529176291772917829179291802918129182291832918429185291862918729188291892919029191291922919329194291952919629197291982919929200292012920229203292042920529206292072920829209292102921129212292132921429215292162921729218292192922029221292222922329224292252922629227292282922929230292312923229233292342923529236292372923829239292402924129242292432924429245292462924729248292492925029251292522925329254292552925629257292582925929260292612926229263292642926529266292672926829269292702927129272292732927429275292762927729278292792928029281292822928329284292852928629287292882928929290292912929229293292942929529296292972929829299293002930129302293032930429305293062930729308293092931029311293122931329314293152931629317293182931929320293212932229323293242932529326293272932829329293302933129332293332933429335293362933729338293392934029341293422934329344293452934629347293482934929350293512935229353293542935529356293572935829359293602936129362293632936429365293662936729368293692937029371293722937329374293752937629377293782937929380293812938229383293842938529386293872938829389293902939129392293932939429395293962939729398293992940029401294022940329404294052940629407294082940929410294112941229413294142941529416294172941829419294202942129422294232942429425294262942729428294292943029431294322943329434294352943629437294382943929440294412944229443294442944529446294472944829449294502945129452294532945429455294562945729458294592946029461294622946329464294652946629467294682946929470294712947229473294742947529476294772947829479294802948129482294832948429485294862948729488294892949029491294922949329494294952949629497294982949929500295012950229503295042950529506295072950829509295102951129512295132951429515295162951729518295192952029521295222952329524295252952629527295282952929530295312953229533295342953529536295372953829539295402954129542295432954429545295462954729548295492955029551295522955329554295552955629557295582955929560295612956229563295642956529566295672956829569295702957129572295732957429575295762957729578295792958029581295822958329584295852958629587295882958929590295912959229593295942959529596295972959829599296002960129602296032960429605296062960729608296092961029611296122961329614296152961629617296182961929620296212962229623296242962529626296272962829629296302963129632296332963429635296362963729638296392964029641296422964329644296452964629647296482964929650296512965229653296542965529656296572965829659296602966129662296632966429665296662966729668296692967029671296722967329674296752967629677296782967929680296812968229683296842968529686296872968829689296902969129692296932969429695296962969729698296992970029701297022970329704297052970629707297082970929710297112971229713297142971529716297172971829719297202972129722297232972429725297262972729728297292973029731297322973329734297352973629737297382973929740297412974229743297442974529746297472974829749297502975129752297532975429755297562975729758297592976029761297622976329764297652976629767297682976929770297712977229773297742977529776297772977829779297802978129782297832978429785297862978729788297892979029791297922979329794297952979629797297982979929800298012980229803298042980529806298072980829809298102981129812298132981429815298162981729818298192982029821298222982329824298252982629827298282982929830298312983229833298342983529836298372983829839298402984129842298432984429845298462984729848298492985029851298522985329854298552985629857298582985929860298612986229863298642986529866298672986829869298702987129872298732987429875298762987729878298792988029881298822988329884298852988629887298882988929890298912989229893298942989529896298972989829899299002990129902299032990429905299062990729908299092991029911299122991329914299152991629917299182991929920299212992229923299242992529926299272992829929299302993129932299332993429935299362993729938299392994029941299422994329944299452994629947299482994929950299512995229953299542995529956299572995829959299602996129962299632996429965299662996729968299692997029971299722997329974299752997629977299782997929980299812998229983299842998529986299872998829989299902999129992299932999429995299962999729998299993000030001300023000330004300053000630007300083000930010300113001230013300143001530016300173001830019300203002130022300233002430025300263002730028300293003030031300323003330034300353003630037300383003930040300413004230043300443004530046300473004830049300503005130052300533005430055300563005730058300593006030061300623006330064300653006630067300683006930070300713007230073300743007530076300773007830079300803008130082300833008430085300863008730088300893009030091300923009330094300953009630097300983009930100301013010230103301043010530106301073010830109301103011130112301133011430115301163011730118301193012030121301223012330124301253012630127301283012930130301313013230133301343013530136301373013830139301403014130142301433014430145301463014730148301493015030151301523015330154301553015630157301583015930160301613016230163301643016530166301673016830169301703017130172301733017430175301763017730178301793018030181301823018330184301853018630187301883018930190301913019230193301943019530196301973019830199302003020130202302033020430205302063020730208302093021030211302123021330214302153021630217302183021930220302213022230223302243022530226302273022830229302303023130232302333023430235302363023730238302393024030241302423024330244302453024630247302483024930250302513025230253302543025530256302573025830259302603026130262302633026430265302663026730268302693027030271302723027330274302753027630277302783027930280302813028230283302843028530286302873028830289302903029130292302933029430295302963029730298302993030030301303023030330304303053030630307303083030930310303113031230313303143031530316303173031830319303203032130322303233032430325303263032730328303293033030331303323033330334303353033630337303383033930340303413034230343303443034530346303473034830349303503035130352303533035430355303563035730358303593036030361303623036330364303653036630367303683036930370303713037230373303743037530376303773037830379303803038130382303833038430385303863038730388303893039030391303923039330394303953039630397303983039930400304013040230403304043040530406304073040830409304103041130412304133041430415304163041730418304193042030421304223042330424304253042630427304283042930430304313043230433304343043530436304373043830439304403044130442304433044430445304463044730448304493045030451304523045330454304553045630457304583045930460304613046230463304643046530466304673046830469304703047130472304733047430475304763047730478304793048030481304823048330484304853048630487304883048930490304913049230493304943049530496304973049830499305003050130502305033050430505305063050730508305093051030511305123051330514305153051630517305183051930520305213052230523305243052530526305273052830529305303053130532305333053430535305363053730538305393054030541305423054330544305453054630547305483054930550305513055230553305543055530556305573055830559305603056130562305633056430565305663056730568305693057030571305723057330574305753057630577305783057930580305813058230583305843058530586305873058830589305903059130592305933059430595305963059730598305993060030601306023060330604306053060630607306083060930610306113061230613306143061530616306173061830619306203062130622306233062430625306263062730628306293063030631306323063330634306353063630637306383063930640306413064230643306443064530646306473064830649306503065130652306533065430655306563065730658306593066030661306623066330664306653066630667306683066930670306713067230673306743067530676306773067830679306803068130682306833068430685306863068730688306893069030691306923069330694306953069630697306983069930700307013070230703307043070530706307073070830709307103071130712307133071430715307163071730718307193072030721307223072330724307253072630727307283072930730307313073230733307343073530736307373073830739307403074130742307433074430745307463074730748307493075030751307523075330754307553075630757307583075930760307613076230763307643076530766307673076830769307703077130772307733077430775307763077730778307793078030781307823078330784307853078630787307883078930790307913079230793307943079530796307973079830799308003080130802308033080430805308063080730808308093081030811308123081330814308153081630817308183081930820308213082230823308243082530826308273082830829308303083130832308333083430835308363083730838308393084030841308423084330844308453084630847308483084930850308513085230853308543085530856308573085830859308603086130862308633086430865308663086730868308693087030871308723087330874308753087630877308783087930880308813088230883308843088530886308873088830889308903089130892308933089430895308963089730898308993090030901309023090330904309053090630907309083090930910309113091230913309143091530916309173091830919309203092130922309233092430925309263092730928309293093030931309323093330934309353093630937309383093930940309413094230943309443094530946309473094830949309503095130952309533095430955309563095730958309593096030961309623096330964309653096630967309683096930970309713097230973309743097530976309773097830979309803098130982309833098430985309863098730988309893099030991309923099330994309953099630997309983099931000310013100231003310043100531006310073100831009310103101131012310133101431015310163101731018310193102031021310223102331024310253102631027310283102931030310313103231033310343103531036310373103831039310403104131042310433104431045310463104731048310493105031051310523105331054310553105631057310583105931060310613106231063310643106531066310673106831069310703107131072310733107431075310763107731078310793108031081310823108331084310853108631087310883108931090310913109231093310943109531096310973109831099311003110131102311033110431105311063110731108311093111031111311123111331114311153111631117311183111931120311213112231123311243112531126311273112831129311303113131132311333113431135311363113731138311393114031141311423114331144311453114631147311483114931150311513115231153311543115531156311573115831159311603116131162311633116431165311663116731168311693117031171311723117331174311753117631177311783117931180311813118231183311843118531186311873118831189311903119131192311933119431195311963119731198311993120031201312023120331204312053120631207312083120931210312113121231213312143121531216312173121831219312203122131222312233122431225312263122731228312293123031231312323123331234312353123631237312383123931240312413124231243312443124531246312473124831249312503125131252312533125431255312563125731258312593126031261312623126331264312653126631267312683126931270312713127231273312743127531276312773127831279312803128131282312833128431285312863128731288312893129031291312923129331294312953129631297312983129931300313013130231303313043130531306313073130831309313103131131312313133131431315313163131731318313193132031321313223132331324313253132631327313283132931330313313133231333313343133531336313373133831339313403134131342313433134431345313463134731348313493135031351313523135331354313553135631357313583135931360313613136231363313643136531366313673136831369313703137131372313733137431375313763137731378313793138031381313823138331384313853138631387313883138931390313913139231393313943139531396313973139831399314003140131402314033140431405314063140731408314093141031411314123141331414314153141631417314183141931420314213142231423314243142531426314273142831429314303143131432314333143431435314363143731438314393144031441314423144331444314453144631447314483144931450314513145231453314543145531456314573145831459314603146131462314633146431465314663146731468314693147031471314723147331474314753147631477314783147931480314813148231483314843148531486314873148831489314903149131492314933149431495314963149731498314993150031501315023150331504315053150631507315083150931510315113151231513315143151531516315173151831519315203152131522315233152431525315263152731528315293153031531315323153331534315353153631537315383153931540315413154231543315443154531546315473154831549315503155131552315533155431555315563155731558315593156031561315623156331564315653156631567315683156931570315713157231573315743157531576315773157831579315803158131582315833158431585315863158731588315893159031591315923159331594315953159631597315983159931600316013160231603316043160531606316073160831609316103161131612316133161431615316163161731618316193162031621316223162331624316253162631627316283162931630316313163231633316343163531636316373163831639316403164131642316433164431645316463164731648316493165031651316523165331654316553165631657316583165931660316613166231663316643166531666316673166831669316703167131672316733167431675316763167731678316793168031681316823168331684316853168631687316883168931690316913169231693316943169531696316973169831699317003170131702317033170431705317063170731708317093171031711317123171331714317153171631717317183171931720317213172231723317243172531726317273172831729317303173131732317333173431735317363173731738317393174031741317423174331744317453174631747317483174931750317513175231753317543175531756317573175831759317603176131762317633176431765317663176731768317693177031771317723177331774317753177631777317783177931780317813178231783317843178531786317873178831789317903179131792317933179431795317963179731798317993180031801318023180331804318053180631807318083180931810318113181231813318143181531816318173181831819318203182131822318233182431825318263182731828318293183031831318323183331834318353183631837318383183931840318413184231843318443184531846318473184831849318503185131852318533185431855318563185731858318593186031861318623186331864318653186631867318683186931870318713187231873318743187531876318773187831879318803188131882318833188431885318863188731888318893189031891318923189331894318953189631897318983189931900319013190231903319043190531906319073190831909319103191131912319133191431915319163191731918319193192031921319223192331924319253192631927319283192931930319313193231933319343193531936319373193831939319403194131942319433194431945319463194731948319493195031951319523195331954319553195631957319583195931960319613196231963319643196531966319673196831969319703197131972319733197431975319763197731978319793198031981319823198331984319853198631987319883198931990319913199231993319943199531996319973199831999320003200132002320033200432005320063200732008320093201032011320123201332014320153201632017320183201932020320213202232023320243202532026320273202832029320303203132032320333203432035320363203732038320393204032041320423204332044320453204632047320483204932050320513205232053320543205532056320573205832059320603206132062320633206432065320663206732068320693207032071320723207332074320753207632077320783207932080320813208232083320843208532086320873208832089320903209132092320933209432095320963209732098320993210032101321023210332104321053210632107321083210932110321113211232113321143211532116321173211832119321203212132122321233212432125321263212732128321293213032131321323213332134321353213632137321383213932140321413214232143321443214532146321473214832149321503215132152321533215432155321563215732158321593216032161321623216332164321653216632167321683216932170321713217232173321743217532176321773217832179321803218132182321833218432185321863218732188321893219032191321923219332194321953219632197321983219932200322013220232203322043220532206322073220832209322103221132212322133221432215322163221732218322193222032221322223222332224322253222632227322283222932230322313223232233322343223532236322373223832239322403224132242322433224432245322463224732248322493225032251322523225332254322553225632257322583225932260322613226232263322643226532266322673226832269322703227132272322733227432275322763227732278322793228032281322823228332284322853228632287322883228932290322913229232293322943229532296322973229832299323003230132302323033230432305323063230732308323093231032311323123231332314323153231632317323183231932320323213232232323323243232532326323273232832329323303233132332323333233432335323363233732338323393234032341323423234332344323453234632347323483234932350323513235232353323543235532356323573235832359323603236132362323633236432365323663236732368323693237032371323723237332374323753237632377323783237932380323813238232383323843238532386323873238832389323903239132392323933239432395323963239732398323993240032401324023240332404324053240632407324083240932410324113241232413324143241532416324173241832419324203242132422324233242432425324263242732428324293243032431324323243332434324353243632437324383243932440324413244232443324443244532446324473244832449324503245132452324533245432455324563245732458324593246032461324623246332464324653246632467324683246932470324713247232473324743247532476324773247832479324803248132482324833248432485324863248732488324893249032491324923249332494324953249632497324983249932500325013250232503325043250532506325073250832509325103251132512325133251432515325163251732518325193252032521325223252332524325253252632527325283252932530325313253232533325343253532536325373253832539325403254132542325433254432545325463254732548325493255032551325523255332554325553255632557325583255932560325613256232563325643256532566325673256832569325703257132572325733257432575325763257732578325793258032581325823258332584325853258632587325883258932590325913259232593325943259532596325973259832599326003260132602326033260432605326063260732608326093261032611326123261332614326153261632617326183261932620326213262232623326243262532626326273262832629326303263132632326333263432635326363263732638326393264032641326423264332644326453264632647326483264932650326513265232653326543265532656326573265832659326603266132662326633266432665326663266732668326693267032671326723267332674326753267632677326783267932680326813268232683326843268532686326873268832689326903269132692326933269432695326963269732698326993270032701327023270332704327053270632707327083270932710327113271232713327143271532716327173271832719327203272132722327233272432725327263272732728327293273032731327323273332734327353273632737327383273932740327413274232743327443274532746327473274832749327503275132752327533275432755327563275732758327593276032761327623276332764327653276632767327683276932770327713277232773327743277532776327773277832779327803278132782327833278432785327863278732788327893279032791327923279332794327953279632797327983279932800328013280232803328043280532806328073280832809328103281132812328133281432815328163281732818328193282032821328223282332824328253282632827328283282932830328313283232833328343283532836328373283832839328403284132842328433284432845328463284732848328493285032851328523285332854328553285632857328583285932860328613286232863328643286532866328673286832869328703287132872328733287432875328763287732878328793288032881328823288332884328853288632887328883288932890328913289232893328943289532896328973289832899329003290132902329033290432905329063290732908329093291032911329123291332914329153291632917329183291932920329213292232923329243292532926329273292832929329303293132932329333293432935329363293732938329393294032941329423294332944329453294632947329483294932950329513295232953329543295532956329573295832959329603296132962329633296432965329663296732968329693297032971329723297332974329753297632977329783297932980329813298232983329843298532986329873298832989329903299132992329933299432995329963299732998329993300033001330023300333004330053300633007330083300933010330113301233013330143301533016330173301833019330203302133022330233302433025330263302733028330293303033031330323303333034330353303633037330383303933040330413304233043330443304533046330473304833049330503305133052330533305433055330563305733058330593306033061330623306333064330653306633067330683306933070330713307233073330743307533076330773307833079330803308133082330833308433085330863308733088330893309033091330923309333094330953309633097330983309933100331013310233103331043310533106331073310833109331103311133112331133311433115331163311733118331193312033121331223312333124331253312633127331283312933130331313313233133331343313533136331373313833139331403314133142331433314433145331463314733148331493315033151331523315333154331553315633157331583315933160331613316233163331643316533166331673316833169331703317133172331733317433175331763317733178331793318033181331823318333184331853318633187331883318933190331913319233193331943319533196331973319833199332003320133202332033320433205332063320733208332093321033211332123321333214332153321633217332183321933220332213322233223332243322533226332273322833229332303323133232332333323433235332363323733238332393324033241332423324333244332453324633247332483324933250332513325233253332543325533256332573325833259332603326133262332633326433265332663326733268332693327033271332723327333274332753327633277332783327933280332813328233283332843328533286332873328833289332903329133292332933329433295332963329733298332993330033301333023330333304333053330633307333083330933310333113331233313333143331533316333173331833319333203332133322333233332433325333263332733328333293333033331333323333333334333353333633337333383333933340333413334233343333443334533346333473334833349333503335133352333533335433355333563335733358333593336033361333623336333364333653336633367333683336933370333713337233373333743337533376333773337833379333803338133382333833338433385333863338733388333893339033391333923339333394333953339633397333983339933400334013340233403334043340533406334073340833409334103341133412334133341433415334163341733418334193342033421334223342333424334253342633427334283342933430334313343233433334343343533436334373343833439334403344133442334433344433445334463344733448334493345033451334523345333454334553345633457334583345933460334613346233463334643346533466334673346833469334703347133472334733347433475334763347733478334793348033481334823348333484334853348633487334883348933490334913349233493334943349533496334973349833499335003350133502335033350433505335063350733508335093351033511335123351333514335153351633517335183351933520335213352233523335243352533526335273352833529335303353133532335333353433535335363353733538335393354033541335423354333544335453354633547335483354933550335513355233553335543355533556335573355833559335603356133562335633356433565335663356733568335693357033571335723357333574335753357633577335783357933580335813358233583335843358533586335873358833589335903359133592335933359433595335963359733598335993360033601336023360333604336053360633607336083360933610336113361233613336143361533616336173361833619336203362133622336233362433625336263362733628336293363033631336323363333634336353363633637336383363933640336413364233643336443364533646336473364833649336503365133652336533365433655336563365733658336593366033661336623366333664336653366633667336683366933670336713367233673336743367533676336773367833679336803368133682336833368433685336863368733688336893369033691336923369333694336953369633697336983369933700337013370233703337043370533706337073370833709337103371133712337133371433715337163371733718337193372033721337223372333724337253372633727337283372933730337313373233733337343373533736337373373833739337403374133742337433374433745337463374733748337493375033751337523375333754337553375633757337583375933760337613376233763337643376533766337673376833769337703377133772337733377433775337763377733778337793378033781337823378333784337853378633787337883378933790337913379233793337943379533796337973379833799338003380133802338033380433805338063380733808338093381033811338123381333814338153381633817338183381933820338213382233823338243382533826338273382833829338303383133832338333383433835338363383733838338393384033841338423384333844338453384633847338483384933850338513385233853338543385533856338573385833859338603386133862338633386433865338663386733868338693387033871338723387333874338753387633877338783387933880338813388233883338843388533886338873388833889338903389133892338933389433895338963389733898338993390033901339023390333904339053390633907339083390933910339113391233913339143391533916339173391833919339203392133922339233392433925339263392733928339293393033931339323393333934339353393633937339383393933940339413394233943339443394533946339473394833949339503395133952339533395433955339563395733958339593396033961339623396333964339653396633967339683396933970339713397233973339743397533976339773397833979339803398133982339833398433985339863398733988339893399033991339923399333994339953399633997339983399934000340013400234003340043400534006340073400834009340103401134012340133401434015340163401734018340193402034021340223402334024340253402634027340283402934030340313403234033340343403534036340373403834039340403404134042340433404434045340463404734048340493405034051340523405334054340553405634057340583405934060340613406234063340643406534066340673406834069340703407134072340733407434075340763407734078340793408034081340823408334084340853408634087340883408934090340913409234093340943409534096340973409834099341003410134102341033410434105341063410734108341093411034111341123411334114341153411634117341183411934120341213412234123341243412534126341273412834129341303413134132341333413434135341363413734138341393414034141341423414334144341453414634147341483414934150341513415234153341543415534156341573415834159341603416134162341633416434165341663416734168341693417034171341723417334174341753417634177341783417934180341813418234183341843418534186341873418834189341903419134192341933419434195341963419734198341993420034201342023420334204342053420634207342083420934210342113421234213342143421534216342173421834219342203422134222342233422434225342263422734228342293423034231342323423334234342353423634237342383423934240342413424234243342443424534246342473424834249342503425134252342533425434255342563425734258342593426034261342623426334264342653426634267342683426934270342713427234273342743427534276342773427834279342803428134282342833428434285342863428734288342893429034291342923429334294342953429634297342983429934300343013430234303343043430534306343073430834309343103431134312343133431434315343163431734318343193432034321343223432334324343253432634327343283432934330343313433234333343343433534336343373433834339343403434134342343433434434345343463434734348343493435034351343523435334354343553435634357343583435934360343613436234363343643436534366343673436834369343703437134372343733437434375343763437734378343793438034381343823438334384343853438634387343883438934390343913439234393343943439534396343973439834399344003440134402344033440434405344063440734408344093441034411344123441334414344153441634417344183441934420344213442234423344243442534426344273442834429344303443134432344333443434435344363443734438344393444034441344423444334444344453444634447344483444934450344513445234453344543445534456344573445834459344603446134462344633446434465344663446734468344693447034471344723447334474344753447634477344783447934480344813448234483344843448534486344873448834489344903449134492344933449434495344963449734498344993450034501345023450334504345053450634507345083450934510345113451234513345143451534516345173451834519345203452134522345233452434525345263452734528345293453034531345323453334534345353453634537345383453934540345413454234543345443454534546345473454834549345503455134552345533455434555345563455734558345593456034561345623456334564345653456634567345683456934570345713457234573345743457534576345773457834579345803458134582345833458434585345863458734588345893459034591345923459334594345953459634597345983459934600346013460234603346043460534606346073460834609346103461134612346133461434615346163461734618346193462034621346223462334624346253462634627346283462934630346313463234633346343463534636346373463834639346403464134642346433464434645346463464734648346493465034651346523465334654346553465634657346583465934660346613466234663346643466534666346673466834669346703467134672346733467434675346763467734678346793468034681346823468334684346853468634687346883468934690346913469234693346943469534696346973469834699347003470134702347033470434705347063470734708347093471034711347123471334714347153471634717347183471934720347213472234723347243472534726347273472834729347303473134732347333473434735347363473734738347393474034741347423474334744347453474634747347483474934750347513475234753347543475534756347573475834759347603476134762347633476434765347663476734768347693477034771347723477334774347753477634777347783477934780347813478234783347843478534786347873478834789347903479134792347933479434795347963479734798347993480034801348023480334804348053480634807348083480934810348113481234813348143481534816348173481834819348203482134822348233482434825348263482734828348293483034831348323483334834348353483634837348383483934840348413484234843348443484534846348473484834849348503485134852348533485434855348563485734858348593486034861348623486334864348653486634867348683486934870348713487234873348743487534876348773487834879348803488134882348833488434885348863488734888348893489034891348923489334894348953489634897348983489934900349013490234903349043490534906349073490834909349103491134912349133491434915349163491734918349193492034921349223492334924349253492634927349283492934930349313493234933349343493534936349373493834939349403494134942349433494434945349463494734948349493495034951349523495334954349553495634957349583495934960349613496234963349643496534966349673496834969349703497134972349733497434975349763497734978349793498034981349823498334984349853498634987349883498934990349913499234993349943499534996349973499834999350003500135002350033500435005350063500735008350093501035011350123501335014350153501635017350183501935020350213502235023350243502535026350273502835029350303503135032350333503435035350363503735038350393504035041350423504335044350453504635047350483504935050350513505235053350543505535056350573505835059350603506135062350633506435065350663506735068350693507035071350723507335074350753507635077350783507935080350813508235083350843508535086350873508835089350903509135092350933509435095350963509735098350993510035101351023510335104351053510635107351083510935110351113511235113351143511535116351173511835119351203512135122351233512435125351263512735128351293513035131351323513335134351353513635137351383513935140351413514235143351443514535146351473514835149351503515135152351533515435155351563515735158351593516035161351623516335164351653516635167351683516935170351713517235173351743517535176351773517835179351803518135182351833518435185351863518735188351893519035191351923519335194351953519635197351983519935200352013520235203352043520535206352073520835209352103521135212352133521435215352163521735218352193522035221352223522335224352253522635227352283522935230352313523235233352343523535236352373523835239352403524135242352433524435245352463524735248352493525035251352523525335254352553525635257352583525935260352613526235263352643526535266352673526835269352703527135272352733527435275352763527735278352793528035281352823528335284352853528635287352883528935290352913529235293352943529535296352973529835299353003530135302353033530435305353063530735308353093531035311353123531335314353153531635317353183531935320353213532235323353243532535326353273532835329353303533135332353333533435335353363533735338353393534035341353423534335344353453534635347353483534935350353513535235353353543535535356353573535835359353603536135362353633536435365353663536735368353693537035371353723537335374353753537635377353783537935380353813538235383353843538535386353873538835389353903539135392353933539435395353963539735398353993540035401354023540335404354053540635407354083540935410354113541235413354143541535416354173541835419354203542135422354233542435425354263542735428354293543035431354323543335434354353543635437354383543935440354413544235443354443544535446354473544835449354503545135452354533545435455354563545735458354593546035461354623546335464354653546635467354683546935470354713547235473354743547535476354773547835479354803548135482354833548435485354863548735488354893549035491354923549335494354953549635497354983549935500355013550235503355043550535506355073550835509355103551135512355133551435515355163551735518355193552035521355223552335524355253552635527355283552935530355313553235533355343553535536355373553835539355403554135542355433554435545355463554735548355493555035551355523555335554355553555635557355583555935560355613556235563355643556535566355673556835569355703557135572355733557435575355763557735578355793558035581355823558335584355853558635587355883558935590355913559235593355943559535596355973559835599356003560135602356033560435605356063560735608356093561035611356123561335614356153561635617356183561935620356213562235623356243562535626356273562835629356303563135632356333563435635356363563735638356393564035641356423564335644356453564635647356483564935650356513565235653356543565535656356573565835659356603566135662356633566435665356663566735668356693567035671356723567335674356753567635677356783567935680356813568235683356843568535686356873568835689356903569135692356933569435695356963569735698356993570035701357023570335704357053570635707357083570935710357113571235713357143571535716357173571835719357203572135722357233572435725357263572735728357293573035731357323573335734357353573635737357383573935740357413574235743357443574535746357473574835749357503575135752357533575435755357563575735758357593576035761357623576335764357653576635767357683576935770357713577235773357743577535776357773577835779357803578135782357833578435785357863578735788357893579035791357923579335794357953579635797357983579935800358013580235803358043580535806358073580835809358103581135812358133581435815358163581735818358193582035821358223582335824358253582635827358283582935830358313583235833358343583535836358373583835839358403584135842358433584435845358463584735848358493585035851358523585335854358553585635857358583585935860358613586235863358643586535866358673586835869358703587135872358733587435875358763587735878358793588035881358823588335884358853588635887358883588935890358913589235893358943589535896358973589835899359003590135902359033590435905359063590735908359093591035911359123591335914359153591635917359183591935920359213592235923359243592535926359273592835929359303593135932359333593435935359363593735938359393594035941359423594335944359453594635947359483594935950359513595235953359543595535956359573595835959359603596135962359633596435965359663596735968359693597035971359723597335974359753597635977359783597935980359813598235983359843598535986359873598835989359903599135992359933599435995359963599735998359993600036001360023600336004360053600636007360083600936010360113601236013360143601536016360173601836019360203602136022360233602436025360263602736028360293603036031360323603336034360353603636037360383603936040360413604236043360443604536046360473604836049360503605136052360533605436055360563605736058360593606036061360623606336064360653606636067360683606936070360713607236073360743607536076360773607836079360803608136082360833608436085360863608736088360893609036091360923609336094360953609636097360983609936100361013610236103361043610536106361073610836109361103611136112361133611436115361163611736118361193612036121361223612336124361253612636127361283612936130361313613236133361343613536136361373613836139361403614136142361433614436145361463614736148361493615036151361523615336154361553615636157361583615936160361613616236163361643616536166361673616836169361703617136172361733617436175361763617736178361793618036181361823618336184361853618636187361883618936190361913619236193361943619536196361973619836199362003620136202362033620436205362063620736208362093621036211362123621336214362153621636217362183621936220362213622236223362243622536226362273622836229362303623136232362333623436235362363623736238362393624036241362423624336244362453624636247362483624936250362513625236253362543625536256362573625836259362603626136262362633626436265362663626736268362693627036271362723627336274362753627636277362783627936280362813628236283362843628536286362873628836289362903629136292362933629436295362963629736298362993630036301363023630336304363053630636307363083630936310363113631236313363143631536316363173631836319363203632136322363233632436325363263632736328363293633036331363323633336334363353633636337363383633936340363413634236343363443634536346363473634836349363503635136352363533635436355363563635736358363593636036361363623636336364363653636636367363683636936370363713637236373363743637536376363773637836379363803638136382363833638436385363863638736388363893639036391363923639336394363953639636397363983639936400364013640236403364043640536406364073640836409364103641136412364133641436415364163641736418364193642036421364223642336424364253642636427364283642936430364313643236433364343643536436364373643836439364403644136442364433644436445364463644736448364493645036451364523645336454364553645636457364583645936460364613646236463364643646536466364673646836469364703647136472364733647436475364763647736478364793648036481364823648336484364853648636487364883648936490364913649236493364943649536496364973649836499365003650136502365033650436505365063650736508365093651036511365123651336514365153651636517365183651936520365213652236523365243652536526365273652836529365303653136532365333653436535365363653736538365393654036541365423654336544365453654636547365483654936550365513655236553365543655536556365573655836559365603656136562365633656436565365663656736568365693657036571365723657336574365753657636577365783657936580365813658236583365843658536586365873658836589365903659136592365933659436595365963659736598365993660036601366023660336604366053660636607366083660936610366113661236613366143661536616366173661836619366203662136622366233662436625366263662736628366293663036631366323663336634366353663636637366383663936640366413664236643366443664536646366473664836649366503665136652366533665436655366563665736658366593666036661366623666336664366653666636667366683666936670366713667236673366743667536676366773667836679366803668136682366833668436685366863668736688366893669036691366923669336694366953669636697366983669936700367013670236703367043670536706367073670836709367103671136712367133671436715367163671736718367193672036721367223672336724367253672636727367283672936730367313673236733367343673536736367373673836739367403674136742367433674436745367463674736748367493675036751367523675336754367553675636757367583675936760367613676236763367643676536766367673676836769367703677136772367733677436775367763677736778367793678036781367823678336784367853678636787367883678936790367913679236793367943679536796367973679836799368003680136802368033680436805368063680736808368093681036811368123681336814368153681636817368183681936820368213682236823368243682536826368273682836829368303683136832368333683436835368363683736838368393684036841368423684336844368453684636847368483684936850368513685236853368543685536856368573685836859368603686136862368633686436865368663686736868368693687036871368723687336874368753687636877368783687936880368813688236883368843688536886368873688836889368903689136892368933689436895368963689736898368993690036901369023690336904369053690636907369083690936910369113691236913369143691536916369173691836919369203692136922369233692436925369263692736928369293693036931369323693336934369353693636937369383693936940369413694236943369443694536946369473694836949369503695136952369533695436955369563695736958369593696036961369623696336964369653696636967369683696936970369713697236973369743697536976369773697836979369803698136982369833698436985369863698736988369893699036991369923699336994369953699636997369983699937000370013700237003370043700537006370073700837009370103701137012370133701437015370163701737018370193702037021370223702337024370253702637027370283702937030370313703237033370343703537036370373703837039370403704137042370433704437045370463704737048370493705037051370523705337054370553705637057370583705937060370613706237063370643706537066370673706837069370703707137072370733707437075370763707737078370793708037081370823708337084370853708637087370883708937090370913709237093370943709537096370973709837099371003710137102371033710437105371063710737108371093711037111371123711337114371153711637117371183711937120371213712237123371243712537126371273712837129371303713137132371333713437135371363713737138371393714037141371423714337144371453714637147371483714937150371513715237153371543715537156371573715837159371603716137162371633716437165371663716737168371693717037171371723717337174371753717637177371783717937180371813718237183371843718537186371873718837189371903719137192371933719437195371963719737198371993720037201372023720337204372053720637207372083720937210372113721237213372143721537216372173721837219372203722137222372233722437225372263722737228372293723037231372323723337234372353723637237372383723937240372413724237243372443724537246372473724837249372503725137252372533725437255372563725737258372593726037261372623726337264372653726637267372683726937270372713727237273372743727537276372773727837279372803728137282372833728437285372863728737288372893729037291372923729337294372953729637297372983729937300373013730237303373043730537306373073730837309373103731137312373133731437315373163731737318373193732037321373223732337324373253732637327373283732937330373313733237333373343733537336373373733837339373403734137342373433734437345373463734737348373493735037351373523735337354373553735637357373583735937360373613736237363373643736537366373673736837369373703737137372373733737437375373763737737378373793738037381373823738337384373853738637387373883738937390373913739237393373943739537396373973739837399374003740137402374033740437405374063740737408374093741037411374123741337414374153741637417374183741937420374213742237423374243742537426374273742837429374303743137432374333743437435374363743737438374393744037441374423744337444374453744637447374483744937450374513745237453374543745537456374573745837459374603746137462374633746437465374663746737468374693747037471374723747337474374753747637477374783747937480374813748237483374843748537486374873748837489374903749137492374933749437495374963749737498374993750037501375023750337504375053750637507375083750937510375113751237513375143751537516375173751837519375203752137522375233752437525375263752737528375293753037531375323753337534375353753637537375383753937540375413754237543375443754537546375473754837549375503755137552375533755437555375563755737558375593756037561375623756337564375653756637567375683756937570375713757237573375743757537576375773757837579375803758137582375833758437585375863758737588375893759037591375923759337594375953759637597375983759937600376013760237603376043760537606376073760837609376103761137612376133761437615376163761737618376193762037621376223762337624376253762637627376283762937630376313763237633376343763537636376373763837639376403764137642376433764437645376463764737648376493765037651376523765337654376553765637657376583765937660376613766237663376643766537666376673766837669376703767137672376733767437675376763767737678376793768037681376823768337684376853768637687376883768937690376913769237693376943769537696376973769837699377003770137702377033770437705377063770737708377093771037711377123771337714377153771637717377183771937720377213772237723377243772537726377273772837729377303773137732377333773437735377363773737738377393774037741377423774337744377453774637747377483774937750377513775237753377543775537756377573775837759377603776137762377633776437765377663776737768377693777037771377723777337774377753777637777377783777937780377813778237783377843778537786377873778837789377903779137792377933779437795377963779737798377993780037801378023780337804378053780637807378083780937810378113781237813378143781537816378173781837819378203782137822378233782437825378263782737828378293783037831378323783337834378353783637837378383783937840378413784237843378443784537846378473784837849378503785137852378533785437855378563785737858378593786037861378623786337864378653786637867378683786937870378713787237873378743787537876378773787837879378803788137882378833788437885378863788737888378893789037891378923789337894378953789637897378983789937900379013790237903379043790537906379073790837909379103791137912379133791437915379163791737918379193792037921379223792337924379253792637927379283792937930379313793237933379343793537936379373793837939379403794137942379433794437945379463794737948379493795037951379523795337954379553795637957379583795937960379613796237963379643796537966379673796837969379703797137972379733797437975379763797737978379793798037981379823798337984379853798637987379883798937990379913799237993379943799537996379973799837999380003800138002380033800438005380063800738008380093801038011380123801338014380153801638017380183801938020380213802238023380243802538026380273802838029380303803138032380333803438035380363803738038380393804038041380423804338044380453804638047380483804938050380513805238053380543805538056380573805838059380603806138062380633806438065380663806738068380693807038071380723807338074380753807638077380783807938080380813808238083380843808538086380873808838089380903809138092380933809438095380963809738098380993810038101381023810338104381053810638107381083810938110381113811238113381143811538116381173811838119381203812138122381233812438125381263812738128381293813038131381323813338134381353813638137381383813938140381413814238143381443814538146381473814838149381503815138152381533815438155381563815738158381593816038161381623816338164381653816638167381683816938170381713817238173381743817538176381773817838179381803818138182381833818438185381863818738188381893819038191381923819338194381953819638197381983819938200382013820238203382043820538206382073820838209382103821138212382133821438215382163821738218382193822038221382223822338224382253822638227382283822938230382313823238233382343823538236382373823838239382403824138242382433824438245382463824738248382493825038251382523825338254382553825638257382583825938260382613826238263382643826538266382673826838269382703827138272382733827438275382763827738278382793828038281382823828338284382853828638287382883828938290382913829238293382943829538296382973829838299383003830138302383033830438305383063830738308383093831038311383123831338314383153831638317383183831938320383213832238323383243832538326383273832838329383303833138332383333833438335383363833738338383393834038341383423834338344383453834638347383483834938350383513835238353383543835538356383573835838359383603836138362383633836438365383663836738368383693837038371383723837338374383753837638377383783837938380383813838238383383843838538386383873838838389383903839138392383933839438395383963839738398383993840038401384023840338404384053840638407384083840938410384113841238413384143841538416384173841838419384203842138422384233842438425384263842738428384293843038431384323843338434384353843638437384383843938440384413844238443384443844538446384473844838449384503845138452384533845438455384563845738458384593846038461384623846338464384653846638467384683846938470384713847238473384743847538476384773847838479384803848138482384833848438485384863848738488384893849038491384923849338494384953849638497384983849938500385013850238503385043850538506385073850838509385103851138512385133851438515385163851738518385193852038521385223852338524385253852638527385283852938530385313853238533385343853538536385373853838539385403854138542385433854438545385463854738548385493855038551385523855338554385553855638557385583855938560385613856238563385643856538566385673856838569385703857138572385733857438575385763857738578385793858038581385823858338584385853858638587385883858938590385913859238593385943859538596385973859838599386003860138602386033860438605386063860738608386093861038611386123861338614386153861638617386183861938620386213862238623386243862538626386273862838629386303863138632386333863438635386363863738638386393864038641386423864338644386453864638647386483864938650386513865238653386543865538656386573865838659386603866138662386633866438665386663866738668386693867038671386723867338674386753867638677386783867938680386813868238683386843868538686386873868838689386903869138692386933869438695386963869738698386993870038701387023870338704387053870638707387083870938710387113871238713387143871538716387173871838719387203872138722387233872438725387263872738728387293873038731387323873338734387353873638737387383873938740387413874238743387443874538746387473874838749387503875138752387533875438755387563875738758387593876038761387623876338764387653876638767387683876938770387713877238773387743877538776387773877838779387803878138782387833878438785387863878738788387893879038791387923879338794387953879638797387983879938800388013880238803388043880538806388073880838809388103881138812388133881438815388163881738818388193882038821388223882338824388253882638827388283882938830388313883238833388343883538836388373883838839388403884138842388433884438845388463884738848388493885038851388523885338854388553885638857388583885938860388613886238863388643886538866388673886838869388703887138872388733887438875388763887738878388793888038881388823888338884388853888638887388883888938890388913889238893388943889538896388973889838899389003890138902389033890438905389063890738908389093891038911389123891338914389153891638917389183891938920389213892238923389243892538926389273892838929389303893138932389333893438935389363893738938389393894038941389423894338944389453894638947389483894938950389513895238953389543895538956389573895838959389603896138962389633896438965389663896738968389693897038971389723897338974389753897638977389783897938980389813898238983389843898538986389873898838989389903899138992389933899438995389963899738998389993900039001390023900339004390053900639007390083900939010390113901239013390143901539016390173901839019390203902139022390233902439025390263902739028390293903039031390323903339034390353903639037390383903939040390413904239043390443904539046390473904839049390503905139052390533905439055390563905739058390593906039061390623906339064390653906639067390683906939070390713907239073390743907539076390773907839079390803908139082390833908439085390863908739088390893909039091390923909339094390953909639097390983909939100391013910239103391043910539106391073910839109391103911139112391133911439115391163911739118391193912039121391223912339124391253912639127391283912939130391313913239133391343913539136391373913839139391403914139142391433914439145391463914739148391493915039151391523915339154391553915639157391583915939160391613916239163391643916539166391673916839169391703917139172391733917439175391763917739178391793918039181391823918339184391853918639187391883918939190391913919239193391943919539196391973919839199392003920139202392033920439205392063920739208392093921039211392123921339214392153921639217392183921939220392213922239223392243922539226392273922839229392303923139232392333923439235392363923739238392393924039241392423924339244392453924639247392483924939250392513925239253392543925539256392573925839259392603926139262392633926439265392663926739268392693927039271392723927339274392753927639277392783927939280392813928239283392843928539286392873928839289392903929139292392933929439295392963929739298392993930039301393023930339304393053930639307393083930939310393113931239313393143931539316393173931839319393203932139322393233932439325393263932739328393293933039331393323933339334393353933639337393383933939340393413934239343393443934539346393473934839349393503935139352393533935439355393563935739358393593936039361393623936339364393653936639367393683936939370393713937239373393743937539376393773937839379393803938139382393833938439385393863938739388393893939039391393923939339394393953939639397393983939939400394013940239403394043940539406394073940839409394103941139412394133941439415394163941739418394193942039421394223942339424394253942639427394283942939430394313943239433394343943539436394373943839439394403944139442394433944439445394463944739448394493945039451394523945339454394553945639457394583945939460394613946239463394643946539466394673946839469394703947139472394733947439475394763947739478394793948039481394823948339484394853948639487394883948939490394913949239493394943949539496394973949839499395003950139502395033950439505395063950739508395093951039511395123951339514395153951639517395183951939520395213952239523395243952539526395273952839529395303953139532395333953439535395363953739538395393954039541395423954339544395453954639547395483954939550395513955239553395543955539556395573955839559395603956139562395633956439565395663956739568395693957039571395723957339574395753957639577395783957939580395813958239583395843958539586395873958839589395903959139592395933959439595395963959739598395993960039601396023960339604396053960639607396083960939610396113961239613396143961539616396173961839619396203962139622396233962439625396263962739628396293963039631396323963339634396353963639637396383963939640396413964239643396443964539646396473964839649396503965139652396533965439655396563965739658396593966039661396623966339664396653966639667396683966939670396713967239673396743967539676396773967839679396803968139682396833968439685396863968739688396893969039691396923969339694396953969639697396983969939700397013970239703397043970539706397073970839709397103971139712397133971439715397163971739718397193972039721397223972339724397253972639727397283972939730397313973239733397343973539736397373973839739397403974139742397433974439745397463974739748397493975039751397523975339754397553975639757397583975939760397613976239763397643976539766397673976839769397703977139772397733977439775397763977739778397793978039781397823978339784397853978639787397883978939790397913979239793397943979539796397973979839799398003980139802398033980439805398063980739808398093981039811398123981339814398153981639817398183981939820398213982239823398243982539826398273982839829398303983139832398333983439835398363983739838398393984039841398423984339844398453984639847398483984939850398513985239853398543985539856398573985839859398603986139862398633986439865398663986739868398693987039871398723987339874398753987639877398783987939880398813988239883398843988539886398873988839889398903989139892398933989439895398963989739898398993990039901399023990339904399053990639907399083990939910399113991239913399143991539916399173991839919399203992139922399233992439925399263992739928399293993039931399323993339934399353993639937399383993939940399413994239943399443994539946399473994839949399503995139952399533995439955399563995739958399593996039961399623996339964399653996639967399683996939970399713997239973399743997539976399773997839979399803998139982399833998439985399863998739988399893999039991399923999339994399953999639997399983999940000400014000240003400044000540006400074000840009400104001140012400134001440015400164001740018400194002040021400224002340024400254002640027400284002940030400314003240033400344003540036400374003840039400404004140042400434004440045400464004740048400494005040051400524005340054400554005640057400584005940060400614006240063400644006540066400674006840069400704007140072400734007440075400764007740078400794008040081400824008340084400854008640087400884008940090400914009240093400944009540096400974009840099401004010140102401034010440105401064010740108401094011040111401124011340114401154011640117401184011940120401214012240123401244012540126401274012840129401304013140132401334013440135401364013740138401394014040141401424014340144401454014640147401484014940150401514015240153401544015540156401574015840159401604016140162401634016440165401664016740168401694017040171401724017340174401754017640177401784017940180401814018240183401844018540186401874018840189401904019140192401934019440195401964019740198401994020040201402024020340204402054020640207402084020940210402114021240213402144021540216402174021840219402204022140222402234022440225402264022740228402294023040231402324023340234402354023640237402384023940240402414024240243402444024540246402474024840249402504025140252402534025440255402564025740258402594026040261402624026340264402654026640267402684026940270402714027240273402744027540276402774027840279402804028140282402834028440285402864028740288402894029040291402924029340294402954029640297402984029940300403014030240303403044030540306403074030840309403104031140312403134031440315403164031740318403194032040321403224032340324403254032640327403284032940330403314033240333403344033540336403374033840339403404034140342403434034440345403464034740348403494035040351403524035340354403554035640357403584035940360403614036240363403644036540366403674036840369403704037140372403734037440375403764037740378403794038040381403824038340384403854038640387403884038940390403914039240393403944039540396403974039840399404004040140402404034040440405404064040740408404094041040411404124041340414404154041640417404184041940420404214042240423404244042540426404274042840429404304043140432404334043440435404364043740438404394044040441404424044340444404454044640447404484044940450404514045240453404544045540456404574045840459404604046140462404634046440465404664046740468404694047040471404724047340474404754047640477404784047940480404814048240483404844048540486404874048840489404904049140492404934049440495404964049740498404994050040501405024050340504405054050640507405084050940510405114051240513405144051540516405174051840519405204052140522405234052440525405264052740528405294053040531405324053340534405354053640537405384053940540405414054240543405444054540546405474054840549405504055140552405534055440555405564055740558405594056040561405624056340564405654056640567405684056940570405714057240573405744057540576405774057840579405804058140582405834058440585405864058740588405894059040591405924059340594405954059640597405984059940600406014060240603406044060540606406074060840609406104061140612406134061440615406164061740618406194062040621406224062340624406254062640627406284062940630406314063240633406344063540636406374063840639406404064140642406434064440645406464064740648406494065040651406524065340654406554065640657406584065940660406614066240663406644066540666406674066840669406704067140672406734067440675406764067740678406794068040681406824068340684406854068640687406884068940690406914069240693406944069540696406974069840699407004070140702407034070440705407064070740708407094071040711407124071340714407154071640717407184071940720407214072240723407244072540726407274072840729407304073140732407334073440735407364073740738407394074040741407424074340744407454074640747407484074940750407514075240753407544075540756407574075840759407604076140762407634076440765407664076740768407694077040771407724077340774407754077640777407784077940780407814078240783407844078540786407874078840789407904079140792407934079440795407964079740798407994080040801408024080340804408054080640807408084080940810408114081240813408144081540816408174081840819408204082140822408234082440825408264082740828408294083040831408324083340834408354083640837408384083940840408414084240843408444084540846408474084840849408504085140852408534085440855408564085740858408594086040861408624086340864408654086640867408684086940870408714087240873408744087540876408774087840879408804088140882408834088440885408864088740888408894089040891408924089340894408954089640897408984089940900409014090240903409044090540906409074090840909409104091140912409134091440915409164091740918409194092040921409224092340924409254092640927409284092940930409314093240933409344093540936409374093840939409404094140942409434094440945409464094740948409494095040951409524095340954409554095640957409584095940960409614096240963409644096540966409674096840969409704097140972409734097440975409764097740978409794098040981409824098340984409854098640987409884098940990409914099240993409944099540996409974099840999410004100141002410034100441005410064100741008410094101041011410124101341014410154101641017410184101941020410214102241023410244102541026410274102841029410304103141032410334103441035410364103741038410394104041041410424104341044410454104641047410484104941050410514105241053410544105541056410574105841059410604106141062410634106441065410664106741068410694107041071410724107341074410754107641077410784107941080410814108241083410844108541086410874108841089410904109141092410934109441095410964109741098410994110041101411024110341104411054110641107411084110941110411114111241113411144111541116411174111841119411204112141122411234112441125411264112741128411294113041131411324113341134411354113641137411384113941140411414114241143411444114541146411474114841149411504115141152411534115441155411564115741158411594116041161411624116341164411654116641167411684116941170411714117241173411744117541176411774117841179411804118141182411834118441185411864118741188411894119041191411924119341194411954119641197411984119941200412014120241203412044120541206412074120841209412104121141212412134121441215412164121741218412194122041221412224122341224412254122641227412284122941230412314123241233412344123541236412374123841239412404124141242412434124441245412464124741248412494125041251412524125341254412554125641257412584125941260412614126241263412644126541266412674126841269412704127141272412734127441275412764127741278412794128041281412824128341284412854128641287412884128941290412914129241293412944129541296412974129841299413004130141302413034130441305413064130741308413094131041311413124131341314413154131641317413184131941320413214132241323413244132541326413274132841329413304133141332413334133441335413364133741338413394134041341413424134341344413454134641347413484134941350413514135241353413544135541356413574135841359413604136141362413634136441365413664136741368413694137041371413724137341374413754137641377413784137941380413814138241383413844138541386413874138841389413904139141392413934139441395413964139741398413994140041401414024140341404414054140641407414084140941410414114141241413414144141541416414174141841419414204142141422414234142441425414264142741428414294143041431414324143341434414354143641437414384143941440414414144241443414444144541446414474144841449414504145141452414534145441455414564145741458414594146041461414624146341464414654146641467414684146941470414714147241473414744147541476414774147841479414804148141482414834148441485414864148741488414894149041491414924149341494414954149641497414984149941500415014150241503415044150541506415074150841509415104151141512415134151441515415164151741518415194152041521415224152341524415254152641527415284152941530415314153241533415344153541536415374153841539415404154141542415434154441545415464154741548415494155041551415524155341554415554155641557415584155941560415614156241563415644156541566415674156841569415704157141572415734157441575415764157741578415794158041581415824158341584415854158641587415884158941590415914159241593415944159541596415974159841599416004160141602416034160441605416064160741608416094161041611416124161341614416154161641617416184161941620416214162241623416244162541626416274162841629416304163141632416334163441635416364163741638416394164041641416424164341644416454164641647416484164941650416514165241653416544165541656416574165841659416604166141662416634166441665416664166741668416694167041671416724167341674416754167641677416784167941680416814168241683416844168541686416874168841689416904169141692416934169441695416964169741698416994170041701417024170341704417054170641707417084170941710417114171241713417144171541716417174171841719417204172141722417234172441725417264172741728417294173041731417324173341734417354173641737417384173941740417414174241743417444174541746417474174841749417504175141752417534175441755417564175741758417594176041761417624176341764417654176641767417684176941770417714177241773417744177541776417774177841779417804178141782417834178441785417864178741788417894179041791417924179341794417954179641797417984179941800418014180241803418044180541806418074180841809418104181141812418134181441815418164181741818418194182041821418224182341824418254182641827418284182941830418314183241833418344183541836418374183841839418404184141842418434184441845418464184741848418494185041851418524185341854418554185641857418584185941860418614186241863418644186541866418674186841869418704187141872418734187441875418764187741878418794188041881418824188341884418854188641887418884188941890418914189241893418944189541896418974189841899419004190141902419034190441905419064190741908419094191041911419124191341914419154191641917419184191941920419214192241923419244192541926419274192841929419304193141932419334193441935419364193741938419394194041941419424194341944419454194641947419484194941950419514195241953419544195541956419574195841959419604196141962419634196441965419664196741968419694197041971419724197341974419754197641977419784197941980419814198241983419844198541986419874198841989419904199141992419934199441995419964199741998419994200042001420024200342004420054200642007420084200942010420114201242013420144201542016420174201842019420204202142022420234202442025420264202742028420294203042031420324203342034420354203642037420384203942040420414204242043420444204542046420474204842049420504205142052420534205442055420564205742058420594206042061420624206342064420654206642067420684206942070420714207242073420744207542076420774207842079420804208142082420834208442085420864208742088420894209042091420924209342094420954209642097420984209942100421014210242103421044210542106421074210842109421104211142112421134211442115421164211742118421194212042121421224212342124421254212642127421284212942130421314213242133421344213542136421374213842139421404214142142421434214442145421464214742148421494215042151421524215342154421554215642157421584215942160421614216242163421644216542166421674216842169421704217142172421734217442175421764217742178421794218042181421824218342184421854218642187421884218942190421914219242193421944219542196421974219842199422004220142202422034220442205422064220742208422094221042211422124221342214422154221642217422184221942220422214222242223422244222542226422274222842229422304223142232422334223442235422364223742238422394224042241422424224342244422454224642247422484224942250422514225242253422544225542256422574225842259422604226142262422634226442265422664226742268422694227042271422724227342274422754227642277422784227942280422814228242283422844228542286422874228842289422904229142292422934229442295422964229742298422994230042301423024230342304423054230642307423084230942310423114231242313423144231542316423174231842319423204232142322423234232442325423264232742328423294233042331423324233342334423354233642337423384233942340423414234242343423444234542346423474234842349423504235142352423534235442355423564235742358423594236042361423624236342364423654236642367423684236942370423714237242373423744237542376423774237842379423804238142382423834238442385423864238742388423894239042391423924239342394423954239642397423984239942400424014240242403424044240542406424074240842409424104241142412424134241442415424164241742418424194242042421424224242342424424254242642427424284242942430424314243242433424344243542436424374243842439424404244142442424434244442445424464244742448424494245042451424524245342454424554245642457424584245942460424614246242463424644246542466424674246842469424704247142472424734247442475424764247742478424794248042481424824248342484424854248642487424884248942490424914249242493424944249542496424974249842499425004250142502425034250442505425064250742508425094251042511425124251342514425154251642517425184251942520425214252242523425244252542526425274252842529425304253142532425334253442535425364253742538425394254042541425424254342544425454254642547425484254942550425514255242553425544255542556425574255842559425604256142562425634256442565425664256742568425694257042571425724257342574425754257642577425784257942580425814258242583425844258542586425874258842589425904259142592425934259442595425964259742598425994260042601426024260342604426054260642607426084260942610426114261242613426144261542616426174261842619426204262142622426234262442625426264262742628426294263042631426324263342634426354263642637426384263942640426414264242643426444264542646426474264842649426504265142652426534265442655426564265742658426594266042661426624266342664426654266642667426684266942670426714267242673426744267542676426774267842679426804268142682426834268442685426864268742688426894269042691426924269342694426954269642697426984269942700427014270242703427044270542706427074270842709427104271142712427134271442715427164271742718427194272042721427224272342724427254272642727427284272942730427314273242733427344273542736427374273842739427404274142742427434274442745427464274742748427494275042751427524275342754427554275642757427584275942760427614276242763427644276542766427674276842769427704277142772427734277442775427764277742778427794278042781427824278342784427854278642787427884278942790427914279242793427944279542796427974279842799428004280142802428034280442805428064280742808428094281042811428124281342814428154281642817428184281942820428214282242823428244282542826428274282842829428304283142832428334283442835428364283742838428394284042841428424284342844428454284642847428484284942850428514285242853428544285542856428574285842859428604286142862428634286442865428664286742868428694287042871428724287342874428754287642877428784287942880428814288242883428844288542886428874288842889428904289142892428934289442895428964289742898428994290042901429024290342904429054290642907429084290942910429114291242913429144291542916429174291842919429204292142922429234292442925429264292742928429294293042931429324293342934429354293642937429384293942940429414294242943429444294542946429474294842949429504295142952429534295442955429564295742958429594296042961429624296342964429654296642967429684296942970429714297242973429744297542976429774297842979429804298142982429834298442985429864298742988429894299042991429924299342994429954299642997429984299943000430014300243003430044300543006430074300843009430104301143012430134301443015430164301743018430194302043021430224302343024430254302643027430284302943030430314303243033430344303543036430374303843039430404304143042430434304443045430464304743048430494305043051430524305343054430554305643057430584305943060430614306243063430644306543066430674306843069430704307143072430734307443075430764307743078430794308043081430824308343084430854308643087430884308943090430914309243093430944309543096430974309843099431004310143102431034310443105431064310743108431094311043111431124311343114431154311643117431184311943120431214312243123431244312543126431274312843129431304313143132431334313443135431364313743138431394314043141431424314343144431454314643147431484314943150431514315243153431544315543156431574315843159431604316143162431634316443165431664316743168431694317043171431724317343174431754317643177431784317943180431814318243183431844318543186431874318843189431904319143192431934319443195431964319743198431994320043201432024320343204432054320643207432084320943210432114321243213432144321543216432174321843219432204322143222432234322443225432264322743228432294323043231432324323343234432354323643237432384323943240432414324243243432444324543246432474324843249432504325143252432534325443255432564325743258432594326043261432624326343264432654326643267432684326943270432714327243273432744327543276432774327843279432804328143282432834328443285432864328743288432894329043291432924329343294432954329643297432984329943300433014330243303433044330543306433074330843309433104331143312433134331443315433164331743318433194332043321433224332343324433254332643327433284332943330433314333243333433344333543336433374333843339433404334143342433434334443345433464334743348433494335043351433524335343354433554335643357433584335943360433614336243363433644336543366433674336843369433704337143372433734337443375433764337743378433794338043381433824338343384433854338643387433884338943390433914339243393433944339543396433974339843399434004340143402434034340443405434064340743408434094341043411434124341343414434154341643417434184341943420434214342243423434244342543426434274342843429434304343143432434334343443435434364343743438434394344043441434424344343444434454344643447434484344943450434514345243453434544345543456434574345843459434604346143462434634346443465434664346743468434694347043471434724347343474434754347643477434784347943480434814348243483434844348543486434874348843489434904349143492434934349443495434964349743498434994350043501435024350343504435054350643507435084350943510435114351243513435144351543516435174351843519435204352143522435234352443525435264352743528435294353043531435324353343534435354353643537435384353943540435414354243543435444354543546435474354843549435504355143552435534355443555435564355743558435594356043561435624356343564435654356643567435684356943570435714357243573435744357543576435774357843579435804358143582435834358443585435864358743588435894359043591435924359343594435954359643597435984359943600436014360243603436044360543606436074360843609436104361143612436134361443615436164361743618436194362043621436224362343624436254362643627436284362943630436314363243633436344363543636436374363843639436404364143642436434364443645436464364743648436494365043651436524365343654436554365643657436584365943660436614366243663436644366543666436674366843669436704367143672436734367443675436764367743678436794368043681436824368343684436854368643687436884368943690436914369243693436944369543696436974369843699437004370143702437034370443705437064370743708437094371043711437124371343714437154371643717437184371943720437214372243723437244372543726437274372843729437304373143732437334373443735437364373743738437394374043741437424374343744437454374643747437484374943750437514375243753437544375543756437574375843759437604376143762437634376443765437664376743768437694377043771437724377343774437754377643777437784377943780437814378243783437844378543786437874378843789437904379143792437934379443795437964379743798437994380043801438024380343804438054380643807438084380943810438114381243813438144381543816438174381843819438204382143822438234382443825438264382743828438294383043831438324383343834438354383643837438384383943840438414384243843438444384543846438474384843849438504385143852438534385443855438564385743858438594386043861438624386343864438654386643867438684386943870438714387243873438744387543876438774387843879438804388143882438834388443885438864388743888438894389043891438924389343894438954389643897438984389943900439014390243903439044390543906439074390843909439104391143912439134391443915439164391743918439194392043921439224392343924439254392643927439284392943930439314393243933439344393543936439374393843939439404394143942439434394443945439464394743948439494395043951439524395343954439554395643957439584395943960439614396243963439644396543966439674396843969439704397143972439734397443975439764397743978439794398043981439824398343984439854398643987439884398943990439914399243993439944399543996439974399843999440004400144002440034400444005440064400744008440094401044011440124401344014440154401644017440184401944020440214402244023440244402544026440274402844029440304403144032440334403444035440364403744038440394404044041440424404344044440454404644047440484404944050440514405244053440544405544056440574405844059440604406144062440634406444065440664406744068440694407044071440724407344074440754407644077440784407944080440814408244083440844408544086440874408844089440904409144092440934409444095440964409744098440994410044101441024410344104441054410644107441084410944110441114411244113441144411544116441174411844119441204412144122441234412444125441264412744128441294413044131441324413344134441354413644137441384413944140441414414244143441444414544146441474414844149441504415144152441534415444155441564415744158441594416044161441624416344164441654416644167441684416944170441714417244173441744417544176441774417844179441804418144182441834418444185441864418744188441894419044191441924419344194441954419644197441984419944200442014420244203442044420544206442074420844209442104421144212442134421444215442164421744218442194422044221442224422344224442254422644227442284422944230442314423244233442344423544236442374423844239442404424144242442434424444245442464424744248442494425044251442524425344254442554425644257442584425944260442614426244263442644426544266442674426844269442704427144272442734427444275442764427744278442794428044281442824428344284442854428644287442884428944290442914429244293442944429544296442974429844299443004430144302443034430444305443064430744308443094431044311443124431344314443154431644317443184431944320443214432244323443244432544326443274432844329443304433144332443334433444335443364433744338443394434044341443424434344344443454434644347443484434944350443514435244353443544435544356443574435844359443604436144362443634436444365443664436744368443694437044371443724437344374443754437644377443784437944380443814438244383443844438544386443874438844389443904439144392443934439444395443964439744398443994440044401444024440344404444054440644407444084440944410444114441244413444144441544416444174441844419444204442144422444234442444425444264442744428444294443044431444324443344434444354443644437444384443944440444414444244443444444444544446444474444844449444504445144452444534445444455444564445744458444594446044461444624446344464444654446644467444684446944470444714447244473444744447544476444774447844479444804448144482444834448444485444864448744488444894449044491444924449344494444954449644497444984449944500445014450244503445044450544506445074450844509445104451144512445134451444515445164451744518445194452044521445224452344524445254452644527445284452944530445314453244533445344453544536445374453844539445404454144542445434454444545445464454744548445494455044551445524455344554445554455644557445584455944560445614456244563445644456544566445674456844569445704457144572445734457444575445764457744578445794458044581445824458344584445854458644587445884458944590445914459244593445944459544596445974459844599446004460144602446034460444605446064460744608446094461044611446124461344614446154461644617446184461944620446214462244623446244462544626446274462844629446304463144632446334463444635446364463744638446394464044641446424464344644446454464644647446484464944650446514465244653446544465544656446574465844659446604466144662446634466444665446664466744668446694467044671446724467344674446754467644677446784467944680446814468244683446844468544686446874468844689446904469144692446934469444695446964469744698446994470044701447024470344704447054470644707447084470944710447114471244713447144471544716447174471844719447204472144722447234472444725447264472744728447294473044731447324473344734447354473644737447384473944740447414474244743447444474544746447474474844749447504475144752447534475444755447564475744758447594476044761447624476344764447654476644767447684476944770447714477244773447744477544776447774477844779447804478144782447834478444785447864478744788447894479044791447924479344794447954479644797447984479944800448014480244803448044480544806448074480844809448104481144812448134481444815448164481744818448194482044821448224482344824448254482644827448284482944830448314483244833448344483544836448374483844839448404484144842448434484444845448464484744848448494485044851448524485344854448554485644857448584485944860448614486244863448644486544866448674486844869448704487144872448734487444875448764487744878448794488044881448824488344884448854488644887448884488944890448914489244893448944489544896448974489844899449004490144902449034490444905449064490744908449094491044911449124491344914449154491644917449184491944920449214492244923449244492544926449274492844929449304493144932449334493444935449364493744938449394494044941449424494344944449454494644947449484494944950449514495244953449544495544956449574495844959449604496144962449634496444965449664496744968449694497044971449724497344974449754497644977449784497944980449814498244983449844498544986449874498844989449904499144992449934499444995449964499744998449994500045001450024500345004450054500645007450084500945010450114501245013450144501545016450174501845019450204502145022450234502445025450264502745028450294503045031450324503345034450354503645037450384503945040450414504245043450444504545046450474504845049450504505145052450534505445055450564505745058450594506045061450624506345064450654506645067450684506945070450714507245073450744507545076450774507845079450804508145082450834508445085450864508745088450894509045091450924509345094450954509645097450984509945100451014510245103451044510545106451074510845109451104511145112451134511445115451164511745118451194512045121451224512345124451254512645127451284512945130451314513245133451344513545136451374513845139451404514145142451434514445145451464514745148451494515045151451524515345154451554515645157451584515945160451614516245163451644516545166451674516845169451704517145172451734517445175451764517745178451794518045181451824518345184451854518645187451884518945190451914519245193451944519545196451974519845199452004520145202452034520445205452064520745208452094521045211452124521345214452154521645217452184521945220452214522245223452244522545226452274522845229452304523145232452334523445235452364523745238452394524045241452424524345244452454524645247452484524945250452514525245253452544525545256452574525845259452604526145262452634526445265452664526745268452694527045271452724527345274452754527645277452784527945280452814528245283452844528545286452874528845289452904529145292452934529445295452964529745298452994530045301453024530345304453054530645307453084530945310453114531245313453144531545316453174531845319453204532145322453234532445325453264532745328453294533045331453324533345334453354533645337453384533945340453414534245343453444534545346453474534845349453504535145352453534535445355453564535745358453594536045361453624536345364453654536645367453684536945370453714537245373453744537545376453774537845379453804538145382453834538445385453864538745388453894539045391453924539345394453954539645397453984539945400454014540245403454044540545406454074540845409454104541145412454134541445415454164541745418454194542045421454224542345424454254542645427454284542945430454314543245433454344543545436454374543845439454404544145442454434544445445454464544745448454494545045451454524545345454454554545645457454584545945460454614546245463454644546545466454674546845469454704547145472454734547445475454764547745478454794548045481454824548345484454854548645487454884548945490454914549245493454944549545496454974549845499455004550145502455034550445505455064550745508455094551045511455124551345514455154551645517455184551945520455214552245523455244552545526455274552845529455304553145532455334553445535455364553745538455394554045541455424554345544455454554645547455484554945550455514555245553455544555545556455574555845559455604556145562455634556445565455664556745568455694557045571455724557345574455754557645577455784557945580455814558245583455844558545586455874558845589455904559145592455934559445595455964559745598455994560045601456024560345604456054560645607456084560945610456114561245613456144561545616456174561845619456204562145622456234562445625456264562745628456294563045631456324563345634456354563645637456384563945640456414564245643456444564545646456474564845649456504565145652456534565445655456564565745658456594566045661456624566345664456654566645667456684566945670456714567245673456744567545676456774567845679456804568145682456834568445685456864568745688456894569045691456924569345694456954569645697456984569945700457014570245703457044570545706457074570845709457104571145712457134571445715457164571745718457194572045721457224572345724457254572645727457284572945730457314573245733457344573545736457374573845739457404574145742457434574445745457464574745748457494575045751457524575345754457554575645757457584575945760457614576245763457644576545766457674576845769457704577145772457734577445775457764577745778457794578045781457824578345784457854578645787457884578945790457914579245793457944579545796457974579845799458004580145802458034580445805458064580745808458094581045811458124581345814458154581645817458184581945820458214582245823458244582545826458274582845829458304583145832458334583445835458364583745838458394584045841458424584345844458454584645847458484584945850458514585245853458544585545856458574585845859458604586145862458634586445865458664586745868458694587045871458724587345874458754587645877458784587945880458814588245883458844588545886458874588845889458904589145892458934589445895458964589745898458994590045901459024590345904459054590645907459084590945910459114591245913459144591545916459174591845919459204592145922459234592445925459264592745928459294593045931459324593345934459354593645937459384593945940459414594245943459444594545946459474594845949459504595145952459534595445955459564595745958459594596045961459624596345964459654596645967459684596945970459714597245973459744597545976459774597845979459804598145982459834598445985459864598745988459894599045991459924599345994459954599645997459984599946000460014600246003460044600546006460074600846009460104601146012460134601446015460164601746018460194602046021460224602346024460254602646027460284602946030460314603246033460344603546036460374603846039460404604146042460434604446045460464604746048460494605046051460524605346054460554605646057460584605946060460614606246063460644606546066460674606846069460704607146072460734607446075460764607746078460794608046081460824608346084460854608646087460884608946090460914609246093460944609546096460974609846099461004610146102461034610446105461064610746108461094611046111461124611346114461154611646117461184611946120461214612246123461244612546126461274612846129461304613146132461334613446135461364613746138461394614046141461424614346144461454614646147461484614946150461514615246153461544615546156461574615846159461604616146162461634616446165461664616746168461694617046171461724617346174461754617646177461784617946180461814618246183461844618546186461874618846189461904619146192461934619446195461964619746198461994620046201462024620346204462054620646207462084620946210462114621246213462144621546216462174621846219462204622146222462234622446225462264622746228462294623046231462324623346234462354623646237462384623946240462414624246243462444624546246462474624846249462504625146252462534625446255462564625746258462594626046261462624626346264462654626646267462684626946270462714627246273462744627546276462774627846279462804628146282462834628446285462864628746288462894629046291462924629346294462954629646297462984629946300463014630246303463044630546306463074630846309463104631146312463134631446315463164631746318463194632046321463224632346324463254632646327463284632946330463314633246333463344633546336463374633846339463404634146342463434634446345463464634746348463494635046351463524635346354463554635646357463584635946360463614636246363463644636546366463674636846369463704637146372463734637446375463764637746378463794638046381463824638346384463854638646387463884638946390463914639246393463944639546396463974639846399464004640146402464034640446405464064640746408464094641046411464124641346414464154641646417464184641946420464214642246423464244642546426464274642846429464304643146432464334643446435464364643746438464394644046441464424644346444464454644646447464484644946450464514645246453464544645546456464574645846459464604646146462464634646446465464664646746468464694647046471464724647346474464754647646477464784647946480464814648246483464844648546486464874648846489464904649146492464934649446495464964649746498464994650046501465024650346504465054650646507465084650946510465114651246513465144651546516465174651846519465204652146522465234652446525465264652746528465294653046531465324653346534465354653646537465384653946540465414654246543465444654546546465474654846549465504655146552465534655446555465564655746558465594656046561465624656346564465654656646567465684656946570465714657246573465744657546576465774657846579465804658146582465834658446585465864658746588465894659046591465924659346594465954659646597465984659946600466014660246603466044660546606466074660846609466104661146612466134661446615466164661746618466194662046621466224662346624466254662646627466284662946630466314663246633466344663546636466374663846639466404664146642466434664446645466464664746648466494665046651466524665346654466554665646657466584665946660466614666246663466644666546666466674666846669466704667146672466734667446675466764667746678466794668046681466824668346684466854668646687466884668946690466914669246693466944669546696466974669846699467004670146702467034670446705467064670746708467094671046711467124671346714467154671646717467184671946720467214672246723467244672546726467274672846729467304673146732467334673446735467364673746738467394674046741467424674346744467454674646747467484674946750467514675246753467544675546756467574675846759467604676146762467634676446765467664676746768467694677046771467724677346774467754677646777467784677946780467814678246783467844678546786467874678846789467904679146792467934679446795467964679746798467994680046801468024680346804468054680646807468084680946810468114681246813468144681546816468174681846819468204682146822468234682446825468264682746828468294683046831468324683346834468354683646837468384683946840468414684246843468444684546846468474684846849468504685146852468534685446855468564685746858468594686046861468624686346864468654686646867468684686946870468714687246873468744687546876468774687846879468804688146882468834688446885468864688746888468894689046891468924689346894468954689646897468984689946900469014690246903469044690546906469074690846909469104691146912469134691446915469164691746918469194692046921469224692346924469254692646927469284692946930469314693246933469344693546936469374693846939469404694146942469434694446945469464694746948469494695046951469524695346954469554695646957469584695946960469614696246963469644696546966469674696846969469704697146972469734697446975469764697746978469794698046981469824698346984469854698646987469884698946990469914699246993469944699546996469974699846999470004700147002470034700447005470064700747008470094701047011470124701347014470154701647017470184701947020470214702247023470244702547026470274702847029470304703147032470334703447035470364703747038470394704047041470424704347044470454704647047470484704947050470514705247053470544705547056470574705847059470604706147062470634706447065470664706747068470694707047071470724707347074470754707647077470784707947080470814708247083470844708547086470874708847089470904709147092470934709447095470964709747098470994710047101471024710347104471054710647107471084710947110471114711247113471144711547116471174711847119471204712147122471234712447125471264712747128471294713047131471324713347134471354713647137471384713947140471414714247143471444714547146471474714847149471504715147152471534715447155471564715747158471594716047161471624716347164471654716647167471684716947170471714717247173471744717547176471774717847179471804718147182471834718447185471864718747188471894719047191471924719347194471954719647197471984719947200472014720247203472044720547206472074720847209472104721147212472134721447215472164721747218472194722047221472224722347224472254722647227472284722947230472314723247233472344723547236472374723847239472404724147242472434724447245472464724747248472494725047251472524725347254472554725647257472584725947260472614726247263472644726547266472674726847269472704727147272472734727447275472764727747278472794728047281472824728347284472854728647287472884728947290472914729247293472944729547296472974729847299473004730147302473034730447305473064730747308473094731047311473124731347314473154731647317473184731947320473214732247323473244732547326473274732847329473304733147332473334733447335473364733747338473394734047341473424734347344473454734647347473484734947350473514735247353473544735547356473574735847359473604736147362473634736447365473664736747368473694737047371473724737347374473754737647377473784737947380473814738247383473844738547386473874738847389473904739147392473934739447395473964739747398473994740047401474024740347404474054740647407474084740947410474114741247413474144741547416474174741847419474204742147422474234742447425474264742747428474294743047431474324743347434474354743647437474384743947440474414744247443474444744547446474474744847449474504745147452474534745447455474564745747458474594746047461474624746347464474654746647467474684746947470474714747247473474744747547476474774747847479474804748147482474834748447485474864748747488474894749047491474924749347494474954749647497474984749947500475014750247503475044750547506475074750847509475104751147512475134751447515475164751747518475194752047521475224752347524475254752647527475284752947530475314753247533475344753547536475374753847539475404754147542475434754447545475464754747548475494755047551475524755347554475554755647557475584755947560475614756247563475644756547566475674756847569475704757147572475734757447575475764757747578475794758047581475824758347584475854758647587475884758947590475914759247593475944759547596475974759847599476004760147602476034760447605476064760747608476094761047611476124761347614476154761647617476184761947620476214762247623476244762547626476274762847629476304763147632476334763447635476364763747638476394764047641476424764347644476454764647647476484764947650476514765247653476544765547656476574765847659476604766147662476634766447665476664766747668476694767047671476724767347674476754767647677476784767947680476814768247683476844768547686476874768847689476904769147692476934769447695476964769747698476994770047701477024770347704477054770647707477084770947710477114771247713477144771547716477174771847719477204772147722477234772447725477264772747728477294773047731477324773347734477354773647737477384773947740477414774247743477444774547746477474774847749477504775147752477534775447755477564775747758477594776047761477624776347764477654776647767477684776947770477714777247773477744777547776477774777847779477804778147782477834778447785477864778747788477894779047791477924779347794477954779647797477984779947800478014780247803478044780547806478074780847809478104781147812478134781447815478164781747818478194782047821478224782347824478254782647827478284782947830478314783247833478344783547836478374783847839478404784147842478434784447845478464784747848478494785047851478524785347854478554785647857478584785947860478614786247863478644786547866478674786847869478704787147872478734787447875478764787747878478794788047881478824788347884478854788647887478884788947890478914789247893478944789547896478974789847899479004790147902479034790447905479064790747908479094791047911479124791347914479154791647917479184791947920479214792247923479244792547926479274792847929479304793147932479334793447935479364793747938479394794047941479424794347944479454794647947479484794947950479514795247953479544795547956479574795847959479604796147962479634796447965479664796747968479694797047971479724797347974479754797647977479784797947980479814798247983479844798547986479874798847989479904799147992479934799447995479964799747998479994800048001480024800348004480054800648007480084800948010480114801248013480144801548016480174801848019480204802148022480234802448025480264802748028480294803048031480324803348034480354803648037480384803948040480414804248043480444804548046480474804848049480504805148052480534805448055480564805748058480594806048061480624806348064480654806648067480684806948070480714807248073480744807548076480774807848079480804808148082480834808448085480864808748088480894809048091480924809348094480954809648097480984809948100481014810248103481044810548106481074810848109481104811148112481134811448115481164811748118481194812048121481224812348124481254812648127481284812948130481314813248133481344813548136481374813848139481404814148142481434814448145481464814748148481494815048151481524815348154481554815648157481584815948160481614816248163481644816548166481674816848169481704817148172481734817448175481764817748178481794818048181481824818348184481854818648187481884818948190481914819248193481944819548196481974819848199482004820148202482034820448205482064820748208482094821048211482124821348214482154821648217482184821948220482214822248223482244822548226482274822848229482304823148232482334823448235482364823748238482394824048241482424824348244482454824648247482484824948250482514825248253482544825548256482574825848259482604826148262482634826448265482664826748268482694827048271482724827348274482754827648277482784827948280482814828248283482844828548286482874828848289482904829148292482934829448295482964829748298482994830048301483024830348304483054830648307483084830948310483114831248313483144831548316483174831848319483204832148322483234832448325483264832748328483294833048331483324833348334483354833648337483384833948340483414834248343483444834548346483474834848349483504835148352483534835448355483564835748358483594836048361483624836348364483654836648367483684836948370483714837248373483744837548376483774837848379483804838148382483834838448385483864838748388483894839048391483924839348394483954839648397483984839948400484014840248403484044840548406484074840848409484104841148412484134841448415484164841748418484194842048421484224842348424484254842648427484284842948430484314843248433484344843548436484374843848439484404844148442484434844448445484464844748448484494845048451484524845348454484554845648457484584845948460484614846248463484644846548466484674846848469484704847148472484734847448475484764847748478484794848048481484824848348484484854848648487484884848948490484914849248493484944849548496484974849848499485004850148502485034850448505485064850748508485094851048511485124851348514485154851648517485184851948520485214852248523485244852548526485274852848529485304853148532485334853448535485364853748538485394854048541485424854348544485454854648547485484854948550485514855248553485544855548556485574855848559485604856148562485634856448565485664856748568485694857048571485724857348574485754857648577485784857948580485814858248583485844858548586485874858848589485904859148592485934859448595485964859748598485994860048601486024860348604486054860648607486084860948610486114861248613486144861548616486174861848619486204862148622486234862448625486264862748628486294863048631486324863348634486354863648637486384863948640486414864248643486444864548646486474864848649486504865148652486534865448655486564865748658486594866048661486624866348664486654866648667486684866948670486714867248673486744867548676486774867848679486804868148682486834868448685486864868748688486894869048691486924869348694486954869648697486984869948700487014870248703487044870548706487074870848709487104871148712487134871448715487164871748718487194872048721487224872348724487254872648727487284872948730487314873248733487344873548736487374873848739487404874148742487434874448745487464874748748487494875048751487524875348754487554875648757487584875948760487614876248763487644876548766487674876848769487704877148772487734877448775487764877748778487794878048781487824878348784487854878648787487884878948790487914879248793487944879548796487974879848799488004880148802488034880448805488064880748808488094881048811488124881348814488154881648817488184881948820488214882248823488244882548826488274882848829488304883148832488334883448835488364883748838488394884048841488424884348844488454884648847488484884948850488514885248853488544885548856488574885848859488604886148862488634886448865488664886748868488694887048871488724887348874488754887648877488784887948880488814888248883488844888548886488874888848889488904889148892488934889448895488964889748898488994890048901489024890348904489054890648907489084890948910489114891248913489144891548916489174891848919489204892148922489234892448925489264892748928489294893048931489324893348934489354893648937489384893948940489414894248943489444894548946489474894848949489504895148952489534895448955489564895748958489594896048961489624896348964489654896648967489684896948970489714897248973489744897548976489774897848979489804898148982489834898448985489864898748988489894899048991489924899348994489954899648997489984899949000490014900249003490044900549006490074900849009490104901149012490134901449015490164901749018490194902049021490224902349024490254902649027490284902949030490314903249033490344903549036490374903849039490404904149042490434904449045490464904749048490494905049051490524905349054490554905649057490584905949060490614906249063490644906549066490674906849069490704907149072490734907449075490764907749078490794908049081490824908349084490854908649087490884908949090490914909249093490944909549096490974909849099491004910149102491034910449105491064910749108491094911049111491124911349114491154911649117491184911949120491214912249123491244912549126491274912849129491304913149132491334913449135491364913749138491394914049141491424914349144491454914649147491484914949150491514915249153491544915549156491574915849159491604916149162491634916449165491664916749168491694917049171491724917349174491754917649177491784917949180491814918249183491844918549186491874918849189491904919149192491934919449195491964919749198491994920049201492024920349204492054920649207492084920949210492114921249213492144921549216492174921849219492204922149222492234922449225492264922749228492294923049231492324923349234492354923649237492384923949240492414924249243492444924549246492474924849249492504925149252492534925449255492564925749258492594926049261492624926349264492654926649267492684926949270492714927249273492744927549276492774927849279492804928149282492834928449285492864928749288492894929049291492924929349294492954929649297492984929949300493014930249303493044930549306493074930849309493104931149312493134931449315493164931749318493194932049321493224932349324493254932649327493284932949330493314933249333493344933549336493374933849339493404934149342493434934449345493464934749348493494935049351493524935349354493554935649357493584935949360493614936249363493644936549366493674936849369493704937149372493734937449375493764937749378493794938049381493824938349384493854938649387493884938949390493914939249393493944939549396493974939849399494004940149402494034940449405494064940749408494094941049411494124941349414494154941649417494184941949420494214942249423494244942549426494274942849429494304943149432494334943449435494364943749438494394944049441494424944349444494454944649447494484944949450494514945249453494544945549456494574945849459494604946149462494634946449465494664946749468494694947049471494724947349474494754947649477494784947949480494814948249483494844948549486494874948849489494904949149492494934949449495494964949749498494994950049501495024950349504495054950649507495084950949510495114951249513495144951549516495174951849519495204952149522495234952449525495264952749528495294953049531495324953349534495354953649537495384953949540495414954249543495444954549546495474954849549495504955149552495534955449555495564955749558495594956049561495624956349564495654956649567495684956949570495714957249573495744957549576495774957849579495804958149582495834958449585495864958749588495894959049591495924959349594495954959649597495984959949600496014960249603496044960549606496074960849609496104961149612496134961449615496164961749618496194962049621496224962349624496254962649627496284962949630496314963249633496344963549636496374963849639496404964149642496434964449645496464964749648496494965049651496524965349654496554965649657496584965949660496614966249663496644966549666496674966849669496704967149672496734967449675496764967749678496794968049681496824968349684496854968649687496884968949690496914969249693496944969549696496974969849699497004970149702497034970449705497064970749708497094971049711497124971349714497154971649717497184971949720497214972249723497244972549726497274972849729497304973149732497334973449735497364973749738497394974049741497424974349744497454974649747497484974949750497514975249753497544975549756497574975849759497604976149762497634976449765497664976749768497694977049771497724977349774497754977649777497784977949780497814978249783497844978549786497874978849789497904979149792497934979449795497964979749798497994980049801498024980349804498054980649807498084980949810498114981249813498144981549816498174981849819498204982149822498234982449825498264982749828498294983049831498324983349834498354983649837498384983949840498414984249843498444984549846498474984849849498504985149852498534985449855498564985749858498594986049861498624986349864498654986649867498684986949870498714987249873498744987549876498774987849879498804988149882498834988449885498864988749888498894989049891498924989349894498954989649897498984989949900499014990249903499044990549906499074990849909499104991149912499134991449915499164991749918499194992049921499224992349924499254992649927499284992949930499314993249933499344993549936499374993849939499404994149942499434994449945499464994749948499494995049951499524995349954499554995649957499584995949960499614996249963499644996549966499674996849969499704997149972499734997449975499764997749978499794998049981499824998349984499854998649987499884998949990499914999249993499944999549996499974999849999500005000150002500035000450005500065000750008500095001050011500125001350014500155001650017500185001950020500215002250023500245002550026500275002850029500305003150032500335003450035500365003750038500395004050041500425004350044500455004650047500485004950050500515005250053500545005550056500575005850059500605006150062500635006450065500665006750068500695007050071500725007350074500755007650077500785007950080500815008250083500845008550086500875008850089500905009150092500935009450095500965009750098500995010050101501025010350104501055010650107501085010950110501115011250113501145011550116501175011850119501205012150122501235012450125501265012750128501295013050131501325013350134501355013650137501385013950140501415014250143501445014550146501475014850149501505015150152501535015450155501565015750158501595016050161501625016350164501655016650167501685016950170501715017250173501745017550176501775017850179501805018150182501835018450185501865018750188501895019050191501925019350194501955019650197501985019950200502015020250203502045020550206502075020850209502105021150212502135021450215502165021750218502195022050221502225022350224502255022650227502285022950230502315023250233502345023550236502375023850239502405024150242502435024450245502465024750248502495025050251502525025350254502555025650257502585025950260502615026250263502645026550266502675026850269502705027150272502735027450275502765027750278502795028050281502825028350284502855028650287502885028950290502915029250293502945029550296502975029850299503005030150302503035030450305503065030750308503095031050311503125031350314503155031650317503185031950320503215032250323503245032550326503275032850329503305033150332503335033450335503365033750338503395034050341503425034350344503455034650347503485034950350503515035250353503545035550356503575035850359503605036150362503635036450365503665036750368503695037050371503725037350374503755037650377503785037950380503815038250383503845038550386503875038850389503905039150392503935039450395503965039750398503995040050401504025040350404504055040650407504085040950410504115041250413504145041550416504175041850419504205042150422504235042450425504265042750428504295043050431504325043350434504355043650437504385043950440504415044250443504445044550446504475044850449504505045150452504535045450455504565045750458504595046050461504625046350464504655046650467504685046950470504715047250473504745047550476504775047850479504805048150482504835048450485504865048750488504895049050491504925049350494504955049650497504985049950500505015050250503505045050550506505075050850509505105051150512505135051450515505165051750518505195052050521505225052350524505255052650527505285052950530505315053250533505345053550536505375053850539505405054150542505435054450545505465054750548505495055050551505525055350554505555055650557505585055950560505615056250563505645056550566505675056850569505705057150572505735057450575505765057750578505795058050581505825058350584505855058650587505885058950590505915059250593505945059550596505975059850599506005060150602506035060450605506065060750608506095061050611506125061350614506155061650617506185061950620506215062250623506245062550626506275062850629506305063150632506335063450635506365063750638506395064050641506425064350644506455064650647506485064950650506515065250653506545065550656506575065850659506605066150662506635066450665506665066750668506695067050671506725067350674506755067650677506785067950680506815068250683506845068550686506875068850689506905069150692506935069450695506965069750698506995070050701507025070350704507055070650707507085070950710507115071250713507145071550716507175071850719507205072150722507235072450725507265072750728507295073050731507325073350734507355073650737507385073950740507415074250743507445074550746507475074850749507505075150752507535075450755507565075750758507595076050761507625076350764507655076650767507685076950770507715077250773507745077550776507775077850779507805078150782507835078450785507865078750788507895079050791507925079350794507955079650797507985079950800508015080250803508045080550806508075080850809508105081150812508135081450815508165081750818508195082050821508225082350824508255082650827508285082950830508315083250833508345083550836508375083850839508405084150842508435084450845508465084750848508495085050851508525085350854508555085650857508585085950860508615086250863508645086550866508675086850869508705087150872508735087450875508765087750878508795088050881508825088350884508855088650887508885088950890508915089250893508945089550896508975089850899509005090150902509035090450905509065090750908509095091050911509125091350914509155091650917509185091950920509215092250923509245092550926509275092850929509305093150932509335093450935509365093750938509395094050941509425094350944509455094650947509485094950950509515095250953509545095550956509575095850959509605096150962509635096450965509665096750968509695097050971509725097350974509755097650977509785097950980509815098250983509845098550986509875098850989509905099150992509935099450995509965099750998509995100051001510025100351004510055100651007510085100951010510115101251013510145101551016510175101851019510205102151022510235102451025510265102751028510295103051031510325103351034510355103651037510385103951040510415104251043510445104551046510475104851049510505105151052510535105451055510565105751058510595106051061510625106351064510655106651067510685106951070510715107251073510745107551076510775107851079510805108151082510835108451085510865108751088510895109051091510925109351094510955109651097510985109951100511015110251103511045110551106511075110851109511105111151112511135111451115511165111751118511195112051121511225112351124511255112651127511285112951130511315113251133511345113551136511375113851139511405114151142511435114451145511465114751148511495115051151511525115351154511555115651157511585115951160511615116251163511645116551166511675116851169511705117151172511735117451175511765117751178511795118051181511825118351184511855118651187511885118951190511915119251193511945119551196511975119851199512005120151202512035120451205512065120751208512095121051211512125121351214512155121651217512185121951220512215122251223512245122551226512275122851229512305123151232512335123451235512365123751238512395124051241512425124351244512455124651247512485124951250512515125251253512545125551256512575125851259512605126151262512635126451265512665126751268512695127051271512725127351274512755127651277512785127951280512815128251283512845128551286512875128851289512905129151292512935129451295512965129751298512995130051301513025130351304513055130651307513085130951310513115131251313513145131551316513175131851319513205132151322513235132451325513265132751328513295133051331513325133351334513355133651337513385133951340513415134251343513445134551346513475134851349513505135151352513535135451355513565135751358513595136051361513625136351364513655136651367513685136951370513715137251373513745137551376513775137851379513805138151382513835138451385513865138751388513895139051391513925139351394513955139651397513985139951400514015140251403514045140551406514075140851409514105141151412514135141451415514165141751418514195142051421514225142351424514255142651427514285142951430514315143251433514345143551436514375143851439514405144151442514435144451445514465144751448514495145051451514525145351454514555145651457514585145951460514615146251463514645146551466514675146851469514705147151472514735147451475514765147751478514795148051481514825148351484514855148651487514885148951490514915149251493514945149551496514975149851499515005150151502515035150451505515065150751508515095151051511515125151351514515155151651517515185151951520515215152251523515245152551526515275152851529515305153151532515335153451535515365153751538515395154051541515425154351544515455154651547515485154951550515515155251553515545155551556515575155851559515605156151562515635156451565515665156751568515695157051571515725157351574515755157651577515785157951580515815158251583515845158551586515875158851589515905159151592515935159451595515965159751598515995160051601516025160351604516055160651607516085160951610516115161251613516145161551616516175161851619516205162151622516235162451625516265162751628516295163051631516325163351634516355163651637516385163951640516415164251643516445164551646516475164851649516505165151652516535165451655516565165751658516595166051661516625166351664516655166651667516685166951670516715167251673516745167551676516775167851679516805168151682516835168451685516865168751688516895169051691516925169351694516955169651697516985169951700517015170251703517045170551706517075170851709517105171151712517135171451715517165171751718517195172051721517225172351724517255172651727517285172951730517315173251733517345173551736517375173851739517405174151742517435174451745517465174751748517495175051751517525175351754517555175651757517585175951760517615176251763517645176551766517675176851769517705177151772517735177451775517765177751778517795178051781517825178351784517855178651787517885178951790517915179251793517945179551796517975179851799518005180151802518035180451805518065180751808518095181051811518125181351814518155181651817518185181951820518215182251823518245182551826518275182851829518305183151832518335183451835518365183751838518395184051841518425184351844518455184651847518485184951850518515185251853518545185551856518575185851859518605186151862518635186451865518665186751868518695187051871518725187351874518755187651877518785187951880518815188251883518845188551886518875188851889518905189151892518935189451895518965189751898518995190051901519025190351904519055190651907519085190951910519115191251913519145191551916519175191851919519205192151922519235192451925519265192751928519295193051931519325193351934519355193651937519385193951940519415194251943519445194551946519475194851949519505195151952519535195451955519565195751958519595196051961519625196351964519655196651967519685196951970519715197251973519745197551976519775197851979519805198151982519835198451985519865198751988519895199051991519925199351994519955199651997519985199952000520015200252003520045200552006520075200852009520105201152012520135201452015520165201752018520195202052021520225202352024520255202652027520285202952030520315203252033520345203552036520375203852039520405204152042520435204452045520465204752048520495205052051520525205352054520555205652057520585205952060520615206252063520645206552066520675206852069520705207152072520735207452075520765207752078520795208052081520825208352084520855208652087520885208952090520915209252093520945209552096520975209852099521005210152102521035210452105521065210752108521095211052111521125211352114521155211652117521185211952120521215212252123521245212552126521275212852129521305213152132521335213452135521365213752138521395214052141521425214352144521455214652147521485214952150521515215252153521545215552156521575215852159521605216152162521635216452165521665216752168521695217052171521725217352174521755217652177521785217952180521815218252183521845218552186521875218852189521905219152192521935219452195521965219752198521995220052201522025220352204522055220652207522085220952210522115221252213522145221552216522175221852219522205222152222522235222452225522265222752228522295223052231522325223352234522355223652237522385223952240522415224252243522445224552246522475224852249522505225152252522535225452255522565225752258522595226052261522625226352264522655226652267522685226952270522715227252273522745227552276522775227852279522805228152282522835228452285522865228752288522895229052291522925229352294522955229652297522985229952300523015230252303523045230552306523075230852309523105231152312523135231452315523165231752318523195232052321523225232352324523255232652327523285232952330523315233252333523345233552336523375233852339523405234152342523435234452345523465234752348523495235052351523525235352354523555235652357523585235952360523615236252363523645236552366523675236852369523705237152372523735237452375523765237752378523795238052381523825238352384523855238652387523885238952390523915239252393523945239552396523975239852399524005240152402524035240452405524065240752408524095241052411524125241352414524155241652417524185241952420524215242252423524245242552426524275242852429524305243152432524335243452435524365243752438524395244052441524425244352444524455244652447524485244952450524515245252453524545245552456524575245852459524605246152462524635246452465524665246752468524695247052471524725247352474524755247652477524785247952480524815248252483524845248552486524875248852489524905249152492524935249452495524965249752498524995250052501525025250352504525055250652507525085250952510525115251252513525145251552516525175251852519525205252152522525235252452525525265252752528525295253052531525325253352534525355253652537525385253952540525415254252543525445254552546525475254852549525505255152552525535255452555525565255752558525595256052561525625256352564525655256652567525685256952570525715257252573525745257552576525775257852579525805258152582525835258452585525865258752588525895259052591525925259352594525955259652597525985259952600526015260252603526045260552606526075260852609526105261152612526135261452615526165261752618526195262052621526225262352624526255262652627526285262952630526315263252633526345263552636526375263852639526405264152642526435264452645526465264752648526495265052651526525265352654526555265652657526585265952660526615266252663526645266552666526675266852669526705267152672526735267452675526765267752678526795268052681526825268352684526855268652687526885268952690526915269252693526945269552696526975269852699527005270152702527035270452705527065270752708527095271052711527125271352714527155271652717527185271952720527215272252723527245272552726527275272852729527305273152732527335273452735527365273752738527395274052741527425274352744527455274652747527485274952750527515275252753527545275552756527575275852759527605276152762527635276452765527665276752768527695277052771527725277352774527755277652777527785277952780527815278252783527845278552786527875278852789527905279152792527935279452795527965279752798527995280052801528025280352804528055280652807528085280952810528115281252813528145281552816528175281852819528205282152822528235282452825528265282752828528295283052831528325283352834528355283652837528385283952840528415284252843528445284552846528475284852849528505285152852528535285452855528565285752858528595286052861528625286352864528655286652867528685286952870528715287252873528745287552876528775287852879528805288152882528835288452885528865288752888528895289052891528925289352894528955289652897528985289952900529015290252903529045290552906529075290852909529105291152912529135291452915529165291752918529195292052921529225292352924529255292652927529285292952930529315293252933529345293552936529375293852939529405294152942529435294452945529465294752948529495295052951529525295352954529555295652957529585295952960529615296252963529645296552966529675296852969529705297152972529735297452975529765297752978529795298052981529825298352984529855298652987529885298952990529915299252993529945299552996529975299852999530005300153002530035300453005530065300753008530095301053011530125301353014530155301653017530185301953020530215302253023530245302553026530275302853029530305303153032530335303453035530365303753038530395304053041530425304353044530455304653047530485304953050530515305253053530545305553056530575305853059530605306153062530635306453065530665306753068530695307053071530725307353074530755307653077530785307953080530815308253083530845308553086530875308853089530905309153092530935309453095530965309753098530995310053101531025310353104531055310653107531085310953110531115311253113531145311553116531175311853119531205312153122531235312453125531265312753128531295313053131531325313353134531355313653137531385313953140531415314253143531445314553146531475314853149531505315153152531535315453155531565315753158531595316053161531625316353164531655316653167531685316953170531715317253173531745317553176531775317853179531805318153182531835318453185531865318753188531895319053191531925319353194531955319653197531985319953200532015320253203532045320553206532075320853209532105321153212532135321453215532165321753218532195322053221532225322353224532255322653227532285322953230532315323253233532345323553236532375323853239532405324153242532435324453245532465324753248532495325053251532525325353254532555325653257532585325953260532615326253263532645326553266532675326853269532705327153272532735327453275532765327753278532795328053281532825328353284532855328653287532885328953290532915329253293532945329553296532975329853299533005330153302533035330453305533065330753308533095331053311533125331353314533155331653317533185331953320533215332253323533245332553326533275332853329533305333153332533335333453335533365333753338533395334053341533425334353344533455334653347533485334953350533515335253353533545335553356533575335853359533605336153362533635336453365533665336753368533695337053371533725337353374533755337653377533785337953380533815338253383533845338553386533875338853389533905339153392533935339453395533965339753398533995340053401534025340353404534055340653407534085340953410534115341253413534145341553416534175341853419534205342153422534235342453425534265342753428534295343053431534325343353434534355343653437534385343953440534415344253443534445344553446534475344853449534505345153452534535345453455534565345753458534595346053461534625346353464534655346653467534685346953470534715347253473534745347553476534775347853479534805348153482534835348453485534865348753488534895349053491534925349353494534955349653497534985349953500535015350253503535045350553506535075350853509535105351153512535135351453515535165351753518535195352053521535225352353524535255352653527535285352953530535315353253533535345353553536535375353853539535405354153542535435354453545535465354753548535495355053551535525355353554535555355653557535585355953560535615356253563535645356553566535675356853569535705357153572535735357453575535765357753578535795358053581535825358353584535855358653587535885358953590535915359253593535945359553596535975359853599536005360153602536035360453605536065360753608536095361053611536125361353614536155361653617536185361953620536215362253623536245362553626536275362853629536305363153632536335363453635536365363753638536395364053641536425364353644536455364653647536485364953650536515365253653536545365553656536575365853659536605366153662536635366453665536665366753668536695367053671536725367353674536755367653677536785367953680536815368253683536845368553686536875368853689536905369153692536935369453695536965369753698536995370053701537025370353704537055370653707537085370953710537115371253713537145371553716537175371853719537205372153722537235372453725537265372753728537295373053731537325373353734537355373653737537385373953740537415374253743537445374553746537475374853749537505375153752537535375453755537565375753758537595376053761537625376353764537655376653767537685376953770537715377253773537745377553776537775377853779537805378153782537835378453785537865378753788537895379053791537925379353794537955379653797537985379953800538015380253803538045380553806538075380853809538105381153812538135381453815538165381753818538195382053821538225382353824538255382653827538285382953830538315383253833538345383553836538375383853839538405384153842538435384453845538465384753848538495385053851538525385353854538555385653857538585385953860538615386253863538645386553866538675386853869538705387153872538735387453875538765387753878538795388053881538825388353884538855388653887538885388953890538915389253893538945389553896538975389853899539005390153902539035390453905539065390753908539095391053911539125391353914539155391653917539185391953920539215392253923539245392553926539275392853929539305393153932539335393453935539365393753938539395394053941539425394353944539455394653947539485394953950539515395253953539545395553956539575395853959539605396153962539635396453965539665396753968539695397053971539725397353974539755397653977539785397953980539815398253983539845398553986539875398853989539905399153992539935399453995539965399753998539995400054001540025400354004540055400654007540085400954010540115401254013540145401554016540175401854019540205402154022540235402454025540265402754028540295403054031540325403354034540355403654037540385403954040540415404254043540445404554046540475404854049540505405154052540535405454055540565405754058540595406054061540625406354064540655406654067540685406954070540715407254073540745407554076540775407854079540805408154082540835408454085540865408754088540895409054091540925409354094540955409654097540985409954100541015410254103541045410554106541075410854109541105411154112541135411454115541165411754118541195412054121541225412354124541255412654127541285412954130541315413254133541345413554136541375413854139541405414154142541435414454145541465414754148541495415054151541525415354154541555415654157541585415954160541615416254163541645416554166541675416854169541705417154172541735417454175541765417754178541795418054181541825418354184541855418654187541885418954190541915419254193541945419554196541975419854199542005420154202542035420454205542065420754208542095421054211542125421354214542155421654217542185421954220542215422254223542245422554226542275422854229542305423154232542335423454235542365423754238542395424054241542425424354244542455424654247542485424954250542515425254253542545425554256542575425854259542605426154262542635426454265542665426754268542695427054271542725427354274542755427654277542785427954280542815428254283542845428554286542875428854289542905429154292542935429454295542965429754298542995430054301543025430354304543055430654307543085430954310543115431254313543145431554316543175431854319543205432154322543235432454325543265432754328543295433054331543325433354334543355433654337543385433954340543415434254343543445434554346543475434854349543505435154352543535435454355543565435754358543595436054361543625436354364543655436654367543685436954370543715437254373543745437554376543775437854379543805438154382543835438454385543865438754388543895439054391543925439354394543955439654397543985439954400544015440254403544045440554406544075440854409544105441154412544135441454415544165441754418544195442054421544225442354424544255442654427544285442954430544315443254433544345443554436544375443854439544405444154442544435444454445544465444754448544495445054451544525445354454544555445654457544585445954460544615446254463544645446554466544675446854469544705447154472544735447454475544765447754478544795448054481544825448354484544855448654487544885448954490544915449254493544945449554496544975449854499545005450154502545035450454505545065450754508545095451054511545125451354514545155451654517545185451954520545215452254523545245452554526545275452854529545305453154532545335453454535545365453754538545395454054541545425454354544545455454654547545485454954550545515455254553545545455554556545575455854559545605456154562545635456454565545665456754568545695457054571545725457354574545755457654577545785457954580545815458254583545845458554586545875458854589545905459154592545935459454595545965459754598545995460054601546025460354604546055460654607546085460954610546115461254613546145461554616546175461854619546205462154622546235462454625546265462754628546295463054631546325463354634546355463654637546385463954640546415464254643546445464554646546475464854649546505465154652546535465454655546565465754658546595466054661546625466354664546655466654667546685466954670546715467254673546745467554676546775467854679546805468154682546835468454685546865468754688546895469054691546925469354694546955469654697546985469954700547015470254703547045470554706547075470854709547105471154712547135471454715547165471754718547195472054721547225472354724547255472654727547285472954730547315473254733547345473554736547375473854739547405474154742547435474454745547465474754748547495475054751547525475354754547555475654757547585475954760547615476254763547645476554766547675476854769547705477154772547735477454775547765477754778547795478054781547825478354784547855478654787547885478954790547915479254793547945479554796547975479854799548005480154802548035480454805548065480754808548095481054811548125481354814548155481654817548185481954820548215482254823548245482554826548275482854829548305483154832548335483454835548365483754838548395484054841548425484354844548455484654847548485484954850548515485254853548545485554856548575485854859548605486154862548635486454865548665486754868548695487054871548725487354874548755487654877548785487954880548815488254883548845488554886548875488854889548905489154892548935489454895548965489754898548995490054901549025490354904549055490654907549085490954910549115491254913549145491554916549175491854919549205492154922549235492454925549265492754928549295493054931549325493354934549355493654937549385493954940549415494254943549445494554946549475494854949549505495154952549535495454955549565495754958549595496054961549625496354964549655496654967549685496954970549715497254973549745497554976549775497854979549805498154982549835498454985549865498754988549895499054991549925499354994549955499654997549985499955000550015500255003550045500555006550075500855009550105501155012550135501455015550165501755018550195502055021550225502355024550255502655027550285502955030550315503255033550345503555036550375503855039550405504155042550435504455045550465504755048550495505055051550525505355054550555505655057550585505955060550615506255063550645506555066550675506855069550705507155072550735507455075550765507755078550795508055081550825508355084550855508655087550885508955090550915509255093550945509555096550975509855099551005510155102551035510455105551065510755108551095511055111551125511355114551155511655117551185511955120551215512255123551245512555126551275512855129551305513155132551335513455135551365513755138551395514055141551425514355144551455514655147551485514955150551515515255153551545515555156551575515855159551605516155162551635516455165551665516755168551695517055171551725517355174551755517655177551785517955180551815518255183551845518555186551875518855189551905519155192551935519455195551965519755198551995520055201552025520355204552055520655207552085520955210552115521255213552145521555216552175521855219552205522155222552235522455225552265522755228552295523055231552325523355234552355523655237552385523955240552415524255243552445524555246552475524855249552505525155252552535525455255552565525755258552595526055261552625526355264552655526655267552685526955270552715527255273552745527555276552775527855279552805528155282552835528455285552865528755288552895529055291552925529355294552955529655297552985529955300553015530255303553045530555306553075530855309553105531155312553135531455315553165531755318553195532055321553225532355324553255532655327553285532955330553315533255333553345533555336553375533855339553405534155342553435534455345553465534755348553495535055351553525535355354553555535655357553585535955360553615536255363553645536555366553675536855369553705537155372553735537455375553765537755378553795538055381553825538355384553855538655387553885538955390553915539255393553945539555396553975539855399554005540155402554035540455405554065540755408554095541055411554125541355414554155541655417554185541955420554215542255423554245542555426554275542855429554305543155432554335543455435554365543755438554395544055441554425544355444554455544655447554485544955450554515545255453554545545555456554575545855459554605546155462554635546455465554665546755468554695547055471554725547355474554755547655477554785547955480554815548255483554845548555486554875548855489554905549155492554935549455495554965549755498554995550055501555025550355504555055550655507555085550955510555115551255513555145551555516555175551855519555205552155522555235552455525555265552755528555295553055531555325553355534555355553655537555385553955540555415554255543555445554555546555475554855549555505555155552555535555455555555565555755558555595556055561555625556355564555655556655567555685556955570555715557255573555745557555576555775557855579555805558155582555835558455585555865558755588555895559055591555925559355594555955559655597555985559955600556015560255603556045560555606556075560855609556105561155612556135561455615556165561755618556195562055621556225562355624556255562655627556285562955630556315563255633556345563555636556375563855639556405564155642556435564455645556465564755648556495565055651556525565355654556555565655657556585565955660556615566255663556645566555666556675566855669556705567155672556735567455675556765567755678556795568055681556825568355684556855568655687556885568955690556915569255693556945569555696556975569855699557005570155702557035570455705557065570755708557095571055711557125571355714557155571655717557185571955720557215572255723557245572555726557275572855729557305573155732557335573455735557365573755738557395574055741557425574355744557455574655747557485574955750557515575255753557545575555756557575575855759557605576155762557635576455765557665576755768557695577055771557725577355774557755577655777557785577955780557815578255783557845578555786557875578855789557905579155792557935579455795557965579755798557995580055801558025580355804558055580655807558085580955810558115581255813558145581555816558175581855819558205582155822558235582455825558265582755828558295583055831558325583355834558355583655837558385583955840558415584255843558445584555846558475584855849558505585155852558535585455855558565585755858558595586055861558625586355864558655586655867558685586955870558715587255873558745587555876558775587855879558805588155882558835588455885558865588755888558895589055891558925589355894558955589655897558985589955900559015590255903559045590555906559075590855909559105591155912559135591455915559165591755918559195592055921559225592355924559255592655927559285592955930559315593255933559345593555936559375593855939559405594155942559435594455945559465594755948559495595055951559525595355954559555595655957559585595955960559615596255963559645596555966559675596855969559705597155972559735597455975559765597755978559795598055981559825598355984559855598655987559885598955990559915599255993559945599555996559975599855999560005600156002560035600456005560065600756008560095601056011560125601356014560155601656017560185601956020560215602256023560245602556026560275602856029560305603156032560335603456035560365603756038560395604056041560425604356044560455604656047560485604956050560515605256053560545605556056560575605856059560605606156062560635606456065560665606756068560695607056071560725607356074560755607656077560785607956080560815608256083560845608556086560875608856089560905609156092560935609456095560965609756098560995610056101561025610356104561055610656107561085610956110561115611256113561145611556116561175611856119561205612156122561235612456125561265612756128561295613056131561325613356134561355613656137561385613956140561415614256143561445614556146561475614856149561505615156152561535615456155561565615756158561595616056161561625616356164561655616656167561685616956170561715617256173561745617556176561775617856179561805618156182561835618456185561865618756188561895619056191561925619356194561955619656197561985619956200562015620256203562045620556206562075620856209562105621156212562135621456215562165621756218562195622056221562225622356224562255622656227562285622956230562315623256233562345623556236562375623856239562405624156242562435624456245562465624756248562495625056251562525625356254562555625656257562585625956260562615626256263562645626556266562675626856269562705627156272562735627456275562765627756278562795628056281562825628356284562855628656287562885628956290562915629256293562945629556296562975629856299563005630156302563035630456305563065630756308563095631056311563125631356314563155631656317563185631956320563215632256323563245632556326563275632856329563305633156332563335633456335563365633756338563395634056341563425634356344563455634656347563485634956350563515635256353563545635556356563575635856359563605636156362563635636456365563665636756368563695637056371563725637356374563755637656377563785637956380563815638256383563845638556386563875638856389563905639156392563935639456395563965639756398563995640056401564025640356404564055640656407564085640956410564115641256413564145641556416564175641856419564205642156422564235642456425564265642756428564295643056431564325643356434564355643656437564385643956440564415644256443564445644556446564475644856449564505645156452564535645456455564565645756458564595646056461564625646356464564655646656467564685646956470564715647256473564745647556476564775647856479564805648156482564835648456485564865648756488564895649056491564925649356494564955649656497564985649956500565015650256503565045650556506565075650856509565105651156512565135651456515565165651756518565195652056521565225652356524565255652656527565285652956530565315653256533565345653556536565375653856539565405654156542565435654456545565465654756548565495655056551565525655356554565555655656557565585655956560565615656256563565645656556566565675656856569565705657156572565735657456575565765657756578565795658056581565825658356584565855658656587565885658956590565915659256593565945659556596565975659856599566005660156602566035660456605566065660756608566095661056611566125661356614566155661656617566185661956620566215662256623566245662556626566275662856629566305663156632566335663456635566365663756638566395664056641566425664356644566455664656647566485664956650566515665256653566545665556656566575665856659566605666156662566635666456665566665666756668566695667056671566725667356674566755667656677566785667956680566815668256683566845668556686566875668856689566905669156692566935669456695566965669756698566995670056701567025670356704567055670656707567085670956710567115671256713567145671556716567175671856719567205672156722567235672456725567265672756728567295673056731567325673356734567355673656737567385673956740567415674256743567445674556746567475674856749567505675156752567535675456755567565675756758567595676056761567625676356764567655676656767567685676956770567715677256773567745677556776567775677856779567805678156782567835678456785567865678756788567895679056791567925679356794567955679656797567985679956800568015680256803568045680556806568075680856809568105681156812568135681456815568165681756818568195682056821568225682356824568255682656827568285682956830568315683256833568345683556836568375683856839568405684156842568435684456845568465684756848568495685056851568525685356854568555685656857568585685956860568615686256863568645686556866568675686856869568705687156872568735687456875568765687756878568795688056881568825688356884568855688656887568885688956890568915689256893568945689556896568975689856899569005690156902569035690456905569065690756908569095691056911569125691356914569155691656917569185691956920569215692256923569245692556926569275692856929569305693156932569335693456935569365693756938569395694056941569425694356944569455694656947569485694956950569515695256953569545695556956569575695856959569605696156962569635696456965569665696756968569695697056971569725697356974569755697656977569785697956980569815698256983569845698556986569875698856989569905699156992569935699456995569965699756998569995700057001570025700357004570055700657007570085700957010570115701257013570145701557016570175701857019570205702157022570235702457025570265702757028570295703057031570325703357034570355703657037570385703957040570415704257043570445704557046570475704857049570505705157052570535705457055570565705757058570595706057061570625706357064570655706657067570685706957070570715707257073570745707557076570775707857079570805708157082570835708457085570865708757088570895709057091570925709357094570955709657097570985709957100571015710257103571045710557106571075710857109571105711157112571135711457115571165711757118571195712057121571225712357124571255712657127571285712957130571315713257133571345713557136571375713857139571405714157142571435714457145571465714757148571495715057151571525715357154571555715657157571585715957160571615716257163571645716557166571675716857169571705717157172571735717457175571765717757178571795718057181571825718357184571855718657187571885718957190571915719257193571945719557196571975719857199572005720157202572035720457205572065720757208572095721057211572125721357214572155721657217572185721957220572215722257223572245722557226572275722857229572305723157232572335723457235572365723757238572395724057241572425724357244572455724657247572485724957250572515725257253572545725557256572575725857259572605726157262572635726457265572665726757268572695727057271572725727357274572755727657277572785727957280572815728257283572845728557286572875728857289572905729157292572935729457295572965729757298572995730057301573025730357304573055730657307573085730957310573115731257313573145731557316573175731857319573205732157322573235732457325573265732757328573295733057331573325733357334573355733657337573385733957340573415734257343573445734557346573475734857349573505735157352573535735457355573565735757358573595736057361573625736357364573655736657367573685736957370573715737257373573745737557376573775737857379573805738157382573835738457385573865738757388573895739057391573925739357394573955739657397573985739957400574015740257403574045740557406574075740857409574105741157412574135741457415574165741757418574195742057421574225742357424574255742657427574285742957430574315743257433574345743557436574375743857439574405744157442574435744457445574465744757448574495745057451574525745357454574555745657457574585745957460574615746257463574645746557466574675746857469574705747157472574735747457475574765747757478574795748057481574825748357484574855748657487574885748957490574915749257493574945749557496574975749857499575005750157502575035750457505575065750757508575095751057511575125751357514575155751657517575185751957520575215752257523575245752557526575275752857529575305753157532575335753457535575365753757538575395754057541575425754357544575455754657547575485754957550575515755257553575545755557556575575755857559575605756157562575635756457565575665756757568575695757057571575725757357574575755757657577575785757957580575815758257583575845758557586575875758857589575905759157592575935759457595575965759757598575995760057601576025760357604576055760657607576085760957610576115761257613576145761557616576175761857619576205762157622576235762457625576265762757628576295763057631576325763357634576355763657637576385763957640576415764257643576445764557646576475764857649576505765157652576535765457655576565765757658576595766057661576625766357664576655766657667576685766957670576715767257673576745767557676576775767857679576805768157682576835768457685576865768757688576895769057691576925769357694576955769657697576985769957700577015770257703577045770557706577075770857709577105771157712577135771457715577165771757718577195772057721577225772357724577255772657727577285772957730577315773257733577345773557736577375773857739577405774157742577435774457745577465774757748577495775057751577525775357754577555775657757577585775957760577615776257763577645776557766577675776857769577705777157772577735777457775577765777757778577795778057781577825778357784577855778657787577885778957790577915779257793577945779557796577975779857799578005780157802578035780457805578065780757808578095781057811578125781357814578155781657817578185781957820578215782257823578245782557826578275782857829578305783157832578335783457835578365783757838578395784057841578425784357844578455784657847578485784957850578515785257853578545785557856578575785857859578605786157862578635786457865578665786757868578695787057871578725787357874578755787657877578785787957880578815788257883578845788557886578875788857889578905789157892578935789457895578965789757898578995790057901579025790357904579055790657907579085790957910579115791257913579145791557916579175791857919579205792157922579235792457925579265792757928579295793057931579325793357934579355793657937579385793957940579415794257943579445794557946579475794857949579505795157952579535795457955579565795757958579595796057961579625796357964579655796657967579685796957970579715797257973579745797557976579775797857979579805798157982579835798457985579865798757988579895799057991579925799357994579955799657997579985799958000580015800258003580045800558006580075800858009580105801158012580135801458015580165801758018580195802058021580225802358024580255802658027580285802958030580315803258033580345803558036580375803858039580405804158042580435804458045580465804758048580495805058051580525805358054580555805658057580585805958060580615806258063580645806558066580675806858069580705807158072580735807458075580765807758078580795808058081580825808358084580855808658087580885808958090580915809258093580945809558096580975809858099581005810158102581035810458105581065810758108581095811058111581125811358114581155811658117581185811958120581215812258123581245812558126581275812858129581305813158132581335813458135581365813758138581395814058141581425814358144581455814658147581485814958150581515815258153581545815558156581575815858159581605816158162581635816458165581665816758168581695817058171581725817358174581755817658177581785817958180581815818258183581845818558186581875818858189581905819158192581935819458195581965819758198581995820058201582025820358204582055820658207582085820958210582115821258213582145821558216582175821858219582205822158222582235822458225582265822758228582295823058231582325823358234582355823658237582385823958240582415824258243582445824558246582475824858249582505825158252582535825458255582565825758258582595826058261582625826358264582655826658267582685826958270582715827258273582745827558276582775827858279582805828158282582835828458285582865828758288582895829058291582925829358294582955829658297582985829958300583015830258303583045830558306583075830858309583105831158312583135831458315583165831758318583195832058321583225832358324583255832658327583285832958330583315833258333583345833558336583375833858339583405834158342583435834458345583465834758348583495835058351583525835358354583555835658357583585835958360583615836258363583645836558366583675836858369583705837158372583735837458375583765837758378583795838058381583825838358384583855838658387583885838958390583915839258393583945839558396583975839858399584005840158402584035840458405584065840758408584095841058411584125841358414584155841658417584185841958420584215842258423584245842558426584275842858429584305843158432584335843458435584365843758438584395844058441584425844358444584455844658447584485844958450584515845258453584545845558456584575845858459584605846158462584635846458465584665846758468584695847058471584725847358474584755847658477584785847958480584815848258483584845848558486584875848858489584905849158492584935849458495584965849758498584995850058501585025850358504585055850658507585085850958510585115851258513585145851558516585175851858519585205852158522585235852458525585265852758528585295853058531585325853358534585355853658537585385853958540585415854258543585445854558546585475854858549585505855158552585535855458555585565855758558585595856058561585625856358564585655856658567585685856958570585715857258573585745857558576585775857858579585805858158582585835858458585585865858758588585895859058591585925859358594585955859658597585985859958600586015860258603586045860558606586075860858609586105861158612586135861458615586165861758618586195862058621586225862358624586255862658627586285862958630586315863258633586345863558636586375863858639586405864158642586435864458645586465864758648586495865058651586525865358654586555865658657586585865958660586615866258663586645866558666586675866858669586705867158672586735867458675586765867758678586795868058681586825868358684586855868658687586885868958690586915869258693586945869558696586975869858699587005870158702587035870458705587065870758708587095871058711587125871358714587155871658717587185871958720587215872258723587245872558726587275872858729587305873158732587335873458735587365873758738587395874058741587425874358744587455874658747587485874958750587515875258753587545875558756587575875858759587605876158762587635876458765587665876758768587695877058771587725877358774587755877658777587785877958780587815878258783587845878558786587875878858789587905879158792587935879458795587965879758798587995880058801588025880358804588055880658807588085880958810588115881258813588145881558816588175881858819588205882158822588235882458825588265882758828588295883058831588325883358834588355883658837588385883958840588415884258843588445884558846588475884858849588505885158852588535885458855588565885758858588595886058861588625886358864588655886658867588685886958870588715887258873588745887558876588775887858879588805888158882588835888458885588865888758888588895889058891588925889358894588955889658897588985889958900589015890258903589045890558906589075890858909589105891158912589135891458915589165891758918589195892058921589225892358924589255892658927589285892958930589315893258933589345893558936589375893858939589405894158942589435894458945589465894758948589495895058951589525895358954589555895658957589585895958960589615896258963589645896558966589675896858969589705897158972589735897458975589765897758978589795898058981589825898358984589855898658987589885898958990589915899258993589945899558996589975899858999590005900159002590035900459005590065900759008590095901059011590125901359014590155901659017590185901959020590215902259023590245902559026590275902859029590305903159032590335903459035590365903759038590395904059041590425904359044590455904659047590485904959050590515905259053590545905559056590575905859059590605906159062590635906459065590665906759068590695907059071590725907359074590755907659077590785907959080590815908259083590845908559086590875908859089590905909159092590935909459095590965909759098590995910059101591025910359104591055910659107591085910959110591115911259113591145911559116591175911859119591205912159122591235912459125591265912759128591295913059131591325913359134591355913659137591385913959140591415914259143591445914559146591475914859149591505915159152591535915459155591565915759158591595916059161591625916359164591655916659167591685916959170591715917259173591745917559176591775917859179591805918159182591835918459185591865918759188591895919059191591925919359194591955919659197591985919959200592015920259203592045920559206592075920859209592105921159212592135921459215592165921759218592195922059221592225922359224592255922659227592285922959230592315923259233592345923559236592375923859239592405924159242592435924459245592465924759248592495925059251592525925359254592555925659257592585925959260592615926259263592645926559266592675926859269592705927159272592735927459275592765927759278592795928059281592825928359284592855928659287592885928959290592915929259293592945929559296592975929859299593005930159302593035930459305593065930759308593095931059311593125931359314593155931659317593185931959320593215932259323593245932559326593275932859329593305933159332593335933459335593365933759338593395934059341593425934359344593455934659347593485934959350593515935259353593545935559356593575935859359593605936159362593635936459365593665936759368593695937059371593725937359374593755937659377593785937959380593815938259383593845938559386593875938859389593905939159392593935939459395593965939759398593995940059401594025940359404594055940659407594085940959410594115941259413594145941559416594175941859419594205942159422594235942459425594265942759428594295943059431594325943359434594355943659437594385943959440594415944259443594445944559446594475944859449594505945159452594535945459455594565945759458594595946059461594625946359464594655946659467594685946959470594715947259473594745947559476594775947859479594805948159482594835948459485594865948759488594895949059491594925949359494594955949659497594985949959500595015950259503595045950559506595075950859509595105951159512595135951459515595165951759518595195952059521595225952359524595255952659527595285952959530595315953259533595345953559536595375953859539595405954159542595435954459545595465954759548595495955059551595525955359554595555955659557595585955959560595615956259563595645956559566595675956859569595705957159572595735957459575595765957759578595795958059581595825958359584595855958659587595885958959590595915959259593595945959559596595975959859599596005960159602596035960459605596065960759608596095961059611596125961359614596155961659617596185961959620596215962259623596245962559626596275962859629596305963159632596335963459635596365963759638596395964059641596425964359644596455964659647596485964959650596515965259653596545965559656596575965859659596605966159662596635966459665596665966759668596695967059671596725967359674596755967659677596785967959680596815968259683596845968559686596875968859689596905969159692596935969459695596965969759698596995970059701597025970359704597055970659707597085970959710597115971259713597145971559716597175971859719597205972159722597235972459725597265972759728597295973059731597325973359734597355973659737597385973959740597415974259743597445974559746597475974859749597505975159752597535975459755597565975759758597595976059761597625976359764597655976659767597685976959770597715977259773597745977559776597775977859779597805978159782597835978459785597865978759788597895979059791597925979359794597955979659797597985979959800598015980259803598045980559806598075980859809598105981159812598135981459815598165981759818598195982059821598225982359824598255982659827598285982959830598315983259833598345983559836598375983859839598405984159842598435984459845598465984759848598495985059851598525985359854598555985659857598585985959860598615986259863598645986559866598675986859869598705987159872598735987459875598765987759878598795988059881598825988359884598855988659887598885988959890598915989259893598945989559896598975989859899599005990159902599035990459905599065990759908599095991059911599125991359914599155991659917599185991959920599215992259923599245992559926599275992859929599305993159932599335993459935599365993759938599395994059941599425994359944599455994659947599485994959950599515995259953599545995559956599575995859959599605996159962599635996459965599665996759968599695997059971599725997359974599755997659977599785997959980599815998259983599845998559986599875998859989599905999159992599935999459995599965999759998599996000060001600026000360004600056000660007600086000960010600116001260013600146001560016600176001860019600206002160022600236002460025600266002760028600296003060031600326003360034600356003660037600386003960040600416004260043600446004560046600476004860049600506005160052600536005460055600566005760058600596006060061600626006360064600656006660067600686006960070600716007260073600746007560076600776007860079600806008160082600836008460085600866008760088600896009060091600926009360094600956009660097600986009960100601016010260103601046010560106601076010860109601106011160112601136011460115601166011760118601196012060121601226012360124601256012660127601286012960130601316013260133601346013560136601376013860139601406014160142601436014460145601466014760148601496015060151601526015360154601556015660157601586015960160601616016260163601646016560166601676016860169601706017160172601736017460175601766017760178601796018060181601826018360184601856018660187601886018960190601916019260193601946019560196601976019860199602006020160202602036020460205602066020760208602096021060211602126021360214602156021660217602186021960220602216022260223602246022560226602276022860229602306023160232602336023460235602366023760238602396024060241602426024360244602456024660247602486024960250602516025260253602546025560256602576025860259602606026160262602636026460265602666026760268602696027060271602726027360274602756027660277602786027960280602816028260283602846028560286602876028860289602906029160292602936029460295602966029760298602996030060301603026030360304603056030660307603086030960310603116031260313603146031560316603176031860319603206032160322603236032460325603266032760328603296033060331603326033360334603356033660337603386033960340603416034260343603446034560346603476034860349603506035160352603536035460355603566035760358603596036060361603626036360364603656036660367603686036960370603716037260373603746037560376603776037860379603806038160382603836038460385603866038760388603896039060391603926039360394603956039660397603986039960400604016040260403604046040560406604076040860409604106041160412604136041460415604166041760418604196042060421604226042360424604256042660427604286042960430604316043260433604346043560436604376043860439604406044160442604436044460445604466044760448604496045060451604526045360454604556045660457604586045960460604616046260463604646046560466604676046860469604706047160472604736047460475604766047760478604796048060481604826048360484604856048660487604886048960490604916049260493604946049560496604976049860499605006050160502605036050460505605066050760508605096051060511605126051360514605156051660517605186051960520605216052260523605246052560526605276052860529605306053160532605336053460535605366053760538605396054060541605426054360544605456054660547605486054960550605516055260553605546055560556605576055860559605606056160562605636056460565605666056760568605696057060571605726057360574605756057660577605786057960580605816058260583605846058560586605876058860589605906059160592605936059460595605966059760598605996060060601606026060360604606056060660607606086060960610606116061260613606146061560616606176061860619606206062160622606236062460625606266062760628606296063060631606326063360634606356063660637606386063960640606416064260643606446064560646606476064860649606506065160652606536065460655606566065760658606596066060661606626066360664606656066660667606686066960670606716067260673606746067560676606776067860679606806068160682606836068460685606866068760688606896069060691606926069360694606956069660697606986069960700607016070260703607046070560706607076070860709607106071160712607136071460715607166071760718607196072060721607226072360724607256072660727607286072960730607316073260733607346073560736607376073860739607406074160742607436074460745607466074760748607496075060751607526075360754607556075660757607586075960760607616076260763607646076560766607676076860769607706077160772607736077460775607766077760778607796078060781607826078360784607856078660787607886078960790607916079260793607946079560796607976079860799608006080160802608036080460805608066080760808608096081060811608126081360814608156081660817608186081960820608216082260823608246082560826608276082860829608306083160832608336083460835608366083760838608396084060841608426084360844608456084660847608486084960850608516085260853608546085560856608576085860859608606086160862608636086460865608666086760868608696087060871608726087360874608756087660877608786087960880608816088260883608846088560886608876088860889608906089160892608936089460895608966089760898608996090060901609026090360904609056090660907609086090960910609116091260913609146091560916609176091860919609206092160922609236092460925609266092760928609296093060931609326093360934609356093660937609386093960940609416094260943609446094560946609476094860949609506095160952609536095460955609566095760958609596096060961609626096360964609656096660967609686096960970609716097260973609746097560976609776097860979609806098160982609836098460985609866098760988609896099060991609926099360994609956099660997609986099961000610016100261003610046100561006610076100861009610106101161012610136101461015610166101761018610196102061021610226102361024610256102661027610286102961030610316103261033610346103561036610376103861039610406104161042610436104461045610466104761048610496105061051610526105361054610556105661057610586105961060610616106261063610646106561066610676106861069610706107161072610736107461075610766107761078610796108061081610826108361084610856108661087610886108961090610916109261093610946109561096610976109861099611006110161102611036110461105611066110761108611096111061111611126111361114611156111661117611186111961120611216112261123611246112561126611276112861129611306113161132611336113461135611366113761138611396114061141611426114361144611456114661147611486114961150611516115261153611546115561156611576115861159611606116161162611636116461165611666116761168611696117061171611726117361174611756117661177611786117961180611816118261183611846118561186611876118861189611906119161192611936119461195611966119761198611996120061201612026120361204612056120661207612086120961210612116121261213612146121561216612176121861219612206122161222612236122461225612266122761228612296123061231612326123361234612356123661237612386123961240612416124261243612446124561246612476124861249612506125161252612536125461255612566125761258612596126061261612626126361264612656126661267612686126961270612716127261273612746127561276612776127861279612806128161282612836128461285612866128761288612896129061291612926129361294612956129661297612986129961300613016130261303613046130561306613076130861309613106131161312613136131461315613166131761318613196132061321613226132361324613256132661327613286132961330613316133261333613346133561336613376133861339613406134161342613436134461345613466134761348613496135061351613526135361354613556135661357613586135961360613616136261363613646136561366613676136861369613706137161372613736137461375613766137761378613796138061381613826138361384613856138661387613886138961390613916139261393613946139561396613976139861399614006140161402614036140461405614066140761408614096141061411614126141361414614156141661417614186141961420614216142261423614246142561426614276142861429614306143161432614336143461435614366143761438614396144061441614426144361444614456144661447614486144961450614516145261453614546145561456614576145861459614606146161462614636146461465614666146761468614696147061471614726147361474614756147661477614786147961480614816148261483614846148561486614876148861489614906149161492614936149461495614966149761498614996150061501615026150361504615056150661507615086150961510615116151261513615146151561516615176151861519615206152161522615236152461525615266152761528615296153061531615326153361534615356153661537615386153961540615416154261543615446154561546615476154861549615506155161552615536155461555615566155761558615596156061561615626156361564615656156661567615686156961570615716157261573615746157561576615776157861579615806158161582615836158461585615866158761588615896159061591615926159361594615956159661597615986159961600616016160261603616046160561606616076160861609616106161161612616136161461615616166161761618616196162061621616226162361624616256162661627616286162961630616316163261633616346163561636616376163861639616406164161642616436164461645616466164761648616496165061651616526165361654616556165661657616586165961660616616166261663616646166561666616676166861669616706167161672616736167461675616766167761678616796168061681616826168361684616856168661687616886168961690616916169261693616946169561696616976169861699617006170161702617036170461705617066170761708617096171061711617126171361714617156171661717617186171961720617216172261723617246172561726617276172861729617306173161732617336173461735617366173761738617396174061741617426174361744617456174661747617486174961750617516175261753617546175561756617576175861759617606176161762617636176461765617666176761768617696177061771617726177361774617756177661777617786177961780617816178261783617846178561786617876178861789617906179161792617936179461795617966179761798617996180061801618026180361804618056180661807618086180961810618116181261813618146181561816618176181861819618206182161822618236182461825618266182761828618296183061831618326183361834618356183661837618386183961840618416184261843618446184561846618476184861849618506185161852618536185461855618566185761858618596186061861618626186361864618656186661867618686186961870618716187261873618746187561876618776187861879618806188161882618836188461885618866188761888618896189061891618926189361894618956189661897618986189961900619016190261903619046190561906619076190861909619106191161912619136191461915619166191761918619196192061921619226192361924619256192661927619286192961930619316193261933619346193561936619376193861939619406194161942619436194461945619466194761948619496195061951619526195361954619556195661957619586195961960619616196261963619646196561966619676196861969619706197161972619736197461975619766197761978619796198061981619826198361984619856198661987619886198961990619916199261993619946199561996619976199861999620006200162002620036200462005620066200762008620096201062011620126201362014620156201662017620186201962020620216202262023620246202562026620276202862029620306203162032620336203462035620366203762038620396204062041620426204362044620456204662047620486204962050620516205262053620546205562056620576205862059620606206162062620636206462065620666206762068620696207062071620726207362074620756207662077620786207962080620816208262083620846208562086620876208862089620906209162092620936209462095620966209762098620996210062101621026210362104621056210662107621086210962110621116211262113621146211562116621176211862119621206212162122621236212462125621266212762128621296213062131621326213362134621356213662137621386213962140621416214262143621446214562146621476214862149621506215162152621536215462155621566215762158621596216062161621626216362164621656216662167621686216962170621716217262173621746217562176621776217862179621806218162182621836218462185621866218762188621896219062191621926219362194621956219662197621986219962200622016220262203622046220562206622076220862209622106221162212622136221462215622166221762218622196222062221622226222362224622256222662227622286222962230622316223262233622346223562236622376223862239622406224162242622436224462245622466224762248622496225062251622526225362254622556225662257622586225962260622616226262263622646226562266622676226862269622706227162272622736227462275622766227762278622796228062281622826228362284622856228662287622886228962290622916229262293622946229562296622976229862299623006230162302623036230462305623066230762308623096231062311623126231362314623156231662317623186231962320623216232262323623246232562326623276232862329623306233162332623336233462335623366233762338623396234062341623426234362344623456234662347623486234962350623516235262353623546235562356623576235862359623606236162362623636236462365623666236762368623696237062371623726237362374623756237662377623786237962380623816238262383623846238562386623876238862389623906239162392623936239462395623966239762398623996240062401624026240362404624056240662407624086240962410624116241262413624146241562416624176241862419624206242162422624236242462425624266242762428624296243062431624326243362434624356243662437624386243962440624416244262443624446244562446624476244862449624506245162452624536245462455624566245762458624596246062461624626246362464624656246662467624686246962470624716247262473624746247562476624776247862479624806248162482624836248462485624866248762488624896249062491624926249362494624956249662497624986249962500625016250262503625046250562506625076250862509625106251162512625136251462515625166251762518625196252062521625226252362524625256252662527625286252962530625316253262533625346253562536625376253862539625406254162542625436254462545625466254762548625496255062551625526255362554625556255662557625586255962560625616256262563625646256562566625676256862569625706257162572625736257462575625766257762578625796258062581625826258362584625856258662587625886258962590625916259262593625946259562596625976259862599626006260162602626036260462605626066260762608626096261062611626126261362614626156261662617626186261962620626216262262623626246262562626626276262862629626306263162632626336263462635626366263762638626396264062641626426264362644626456264662647626486264962650626516265262653626546265562656626576265862659626606266162662626636266462665626666266762668626696267062671626726267362674626756267662677626786267962680626816268262683626846268562686626876268862689626906269162692626936269462695626966269762698626996270062701627026270362704627056270662707627086270962710627116271262713627146271562716627176271862719627206272162722627236272462725627266272762728627296273062731627326273362734627356273662737627386273962740627416274262743627446274562746627476274862749627506275162752627536275462755627566275762758627596276062761627626276362764627656276662767627686276962770627716277262773627746277562776627776277862779627806278162782627836278462785627866278762788627896279062791627926279362794627956279662797627986279962800628016280262803628046280562806628076280862809628106281162812628136281462815628166281762818628196282062821628226282362824628256282662827628286282962830628316283262833628346283562836628376283862839628406284162842628436284462845628466284762848628496285062851628526285362854628556285662857628586285962860628616286262863628646286562866628676286862869628706287162872628736287462875628766287762878628796288062881628826288362884628856288662887628886288962890628916289262893628946289562896628976289862899629006290162902629036290462905629066290762908629096291062911629126291362914629156291662917629186291962920629216292262923629246292562926629276292862929629306293162932629336293462935629366293762938629396294062941629426294362944629456294662947629486294962950629516295262953629546295562956629576295862959629606296162962629636296462965629666296762968629696297062971629726297362974629756297662977629786297962980629816298262983629846298562986629876298862989629906299162992629936299462995629966299762998629996300063001630026300363004630056300663007630086300963010630116301263013630146301563016630176301863019630206302163022630236302463025630266302763028630296303063031630326303363034630356303663037630386303963040630416304263043630446304563046630476304863049630506305163052630536305463055630566305763058630596306063061630626306363064630656306663067630686306963070630716307263073630746307563076630776307863079630806308163082630836308463085630866308763088630896309063091630926309363094630956309663097630986309963100631016310263103631046310563106631076310863109631106311163112631136311463115631166311763118631196312063121631226312363124631256312663127631286312963130631316313263133631346313563136631376313863139631406314163142631436314463145631466314763148631496315063151631526315363154631556315663157631586315963160631616316263163631646316563166631676316863169631706317163172631736317463175631766317763178631796318063181631826318363184631856318663187631886318963190631916319263193631946319563196631976319863199632006320163202632036320463205632066320763208632096321063211632126321363214632156321663217632186321963220632216322263223632246322563226632276322863229632306323163232632336323463235632366323763238632396324063241632426324363244632456324663247632486324963250632516325263253632546325563256632576325863259632606326163262632636326463265632666326763268632696327063271632726327363274632756327663277632786327963280632816328263283632846328563286632876328863289632906329163292632936329463295632966329763298632996330063301633026330363304633056330663307633086330963310633116331263313633146331563316633176331863319633206332163322633236332463325633266332763328633296333063331633326333363334633356333663337633386333963340633416334263343633446334563346633476334863349633506335163352633536335463355633566335763358633596336063361633626336363364633656336663367633686336963370633716337263373633746337563376633776337863379633806338163382633836338463385633866338763388633896339063391633926339363394633956339663397633986339963400634016340263403634046340563406634076340863409634106341163412634136341463415634166341763418634196342063421634226342363424634256342663427634286342963430634316343263433634346343563436634376343863439634406344163442634436344463445634466344763448634496345063451634526345363454634556345663457634586345963460634616346263463634646346563466634676346863469634706347163472634736347463475634766347763478634796348063481634826348363484634856348663487634886348963490634916349263493634946349563496634976349863499635006350163502635036350463505635066350763508635096351063511635126351363514635156351663517635186351963520635216352263523635246352563526635276352863529635306353163532635336353463535635366353763538635396354063541635426354363544635456354663547635486354963550635516355263553635546355563556635576355863559635606356163562635636356463565635666356763568635696357063571635726357363574635756357663577635786357963580635816358263583635846358563586635876358863589635906359163592635936359463595635966359763598635996360063601636026360363604636056360663607636086360963610636116361263613636146361563616636176361863619636206362163622636236362463625636266362763628636296363063631636326363363634636356363663637636386363963640636416364263643636446364563646636476364863649636506365163652636536365463655636566365763658636596366063661636626366363664636656366663667636686366963670636716367263673636746367563676636776367863679636806368163682636836368463685636866368763688636896369063691636926369363694636956369663697636986369963700637016370263703637046370563706637076370863709637106371163712637136371463715637166371763718637196372063721637226372363724637256372663727637286372963730637316373263733637346373563736637376373863739637406374163742637436374463745637466374763748637496375063751637526375363754637556375663757637586375963760637616376263763637646376563766637676376863769637706377163772637736377463775637766377763778637796378063781637826378363784637856378663787637886378963790637916379263793637946379563796637976379863799638006380163802638036380463805638066380763808638096381063811638126381363814638156381663817638186381963820638216382263823638246382563826638276382863829638306383163832638336383463835638366383763838638396384063841638426384363844638456384663847638486384963850638516385263853638546385563856638576385863859638606386163862638636386463865638666386763868638696387063871638726387363874638756387663877638786387963880638816388263883638846388563886638876388863889638906389163892638936389463895638966389763898638996390063901639026390363904639056390663907639086390963910639116391263913639146391563916639176391863919639206392163922639236392463925639266392763928639296393063931639326393363934639356393663937639386393963940639416394263943639446394563946639476394863949639506395163952639536395463955639566395763958639596396063961639626396363964639656396663967639686396963970639716397263973639746397563976639776397863979639806398163982639836398463985639866398763988639896399063991639926399363994639956399663997639986399964000640016400264003640046400564006640076400864009640106401164012640136401464015640166401764018640196402064021640226402364024640256402664027640286402964030640316403264033640346403564036640376403864039640406404164042640436404464045640466404764048640496405064051640526405364054640556405664057640586405964060640616406264063640646406564066640676406864069640706407164072640736407464075640766407764078640796408064081640826408364084640856408664087640886408964090640916409264093640946409564096640976409864099641006410164102641036410464105641066410764108641096411064111641126411364114641156411664117641186411964120641216412264123641246412564126641276412864129641306413164132641336413464135641366413764138641396414064141641426414364144641456414664147641486414964150641516415264153641546415564156641576415864159641606416164162641636416464165641666416764168641696417064171641726417364174641756417664177641786417964180641816418264183641846418564186641876418864189641906419164192641936419464195641966419764198641996420064201642026420364204642056420664207642086420964210642116421264213642146421564216642176421864219642206422164222642236422464225642266422764228642296423064231642326423364234642356423664237642386423964240642416424264243642446424564246642476424864249642506425164252642536425464255642566425764258642596426064261642626426364264642656426664267642686426964270642716427264273642746427564276642776427864279642806428164282642836428464285642866428764288642896429064291642926429364294642956429664297642986429964300643016430264303643046430564306643076430864309643106431164312643136431464315643166431764318643196432064321643226432364324643256432664327643286432964330643316433264333643346433564336643376433864339643406434164342643436434464345643466434764348643496435064351643526435364354643556435664357643586435964360643616436264363643646436564366643676436864369643706437164372643736437464375643766437764378643796438064381643826438364384643856438664387643886438964390643916439264393643946439564396643976439864399644006440164402644036440464405644066440764408644096441064411644126441364414644156441664417644186441964420644216442264423644246442564426644276442864429644306443164432644336443464435644366443764438644396444064441644426444364444644456444664447644486444964450644516445264453644546445564456644576445864459644606446164462644636446464465644666446764468644696447064471644726447364474644756447664477644786447964480644816448264483644846448564486644876448864489644906449164492644936449464495644966449764498644996450064501645026450364504645056450664507645086450964510645116451264513645146451564516645176451864519645206452164522645236452464525645266452764528645296453064531645326453364534645356453664537645386453964540645416454264543645446454564546645476454864549645506455164552645536455464555645566455764558645596456064561645626456364564645656456664567645686456964570645716457264573645746457564576645776457864579645806458164582645836458464585645866458764588645896459064591645926459364594645956459664597645986459964600646016460264603646046460564606646076460864609646106461164612646136461464615646166461764618646196462064621646226462364624646256462664627646286462964630646316463264633646346463564636646376463864639646406464164642646436464464645646466464764648646496465064651646526465364654646556465664657646586465964660646616466264663646646466564666646676466864669646706467164672646736467464675646766467764678646796468064681646826468364684646856468664687646886468964690646916469264693646946469564696646976469864699647006470164702647036470464705647066470764708647096471064711647126471364714647156471664717647186471964720647216472264723647246472564726647276472864729647306473164732647336473464735647366473764738647396474064741647426474364744647456474664747647486474964750647516475264753647546475564756647576475864759647606476164762647636476464765647666476764768647696477064771647726477364774647756477664777647786477964780647816478264783647846478564786647876478864789647906479164792647936479464795647966479764798647996480064801648026480364804648056480664807648086480964810648116481264813648146481564816648176481864819648206482164822648236482464825648266482764828648296483064831648326483364834648356483664837648386483964840648416484264843648446484564846648476484864849648506485164852648536485464855648566485764858648596486064861648626486364864648656486664867648686486964870648716487264873648746487564876648776487864879648806488164882648836488464885648866488764888648896489064891648926489364894648956489664897648986489964900649016490264903649046490564906649076490864909649106491164912649136491464915649166491764918649196492064921649226492364924649256492664927649286492964930649316493264933649346493564936649376493864939649406494164942649436494464945649466494764948649496495064951649526495364954649556495664957649586495964960649616496264963649646496564966649676496864969649706497164972649736497464975649766497764978649796498064981649826498364984649856498664987649886498964990649916499264993649946499564996649976499864999650006500165002650036500465005650066500765008650096501065011650126501365014650156501665017650186501965020650216502265023650246502565026650276502865029650306503165032650336503465035650366503765038650396504065041650426504365044650456504665047650486504965050650516505265053650546505565056650576505865059650606506165062650636506465065650666506765068650696507065071650726507365074650756507665077650786507965080650816508265083650846508565086650876508865089650906509165092650936509465095650966509765098650996510065101651026510365104651056510665107651086510965110651116511265113651146511565116651176511865119651206512165122651236512465125651266512765128651296513065131651326513365134651356513665137651386513965140651416514265143651446514565146651476514865149651506515165152651536515465155651566515765158651596516065161651626516365164651656516665167651686516965170651716517265173651746517565176651776517865179651806518165182651836518465185651866518765188651896519065191651926519365194651956519665197651986519965200652016520265203652046520565206652076520865209652106521165212652136521465215652166521765218652196522065221652226522365224652256522665227652286522965230652316523265233652346523565236652376523865239652406524165242652436524465245652466524765248652496525065251652526525365254652556525665257652586525965260652616526265263652646526565266652676526865269652706527165272652736527465275652766527765278652796528065281652826528365284652856528665287652886528965290652916529265293652946529565296652976529865299653006530165302653036530465305653066530765308653096531065311653126531365314653156531665317653186531965320653216532265323653246532565326653276532865329653306533165332653336533465335653366533765338653396534065341653426534365344653456534665347653486534965350653516535265353653546535565356653576535865359653606536165362653636536465365653666536765368653696537065371653726537365374653756537665377653786537965380653816538265383653846538565386653876538865389653906539165392653936539465395653966539765398653996540065401654026540365404654056540665407654086540965410654116541265413654146541565416654176541865419654206542165422654236542465425654266542765428654296543065431654326543365434654356543665437654386543965440654416544265443654446544565446654476544865449654506545165452654536545465455654566545765458654596546065461654626546365464654656546665467654686546965470654716547265473654746547565476654776547865479654806548165482654836548465485654866548765488654896549065491654926549365494654956549665497654986549965500655016550265503655046550565506655076550865509655106551165512655136551465515655166551765518655196552065521655226552365524655256552665527655286552965530655316553265533655346553565536655376553865539655406554165542655436554465545655466554765548655496555065551655526555365554655556555665557655586555965560655616556265563655646556565566655676556865569655706557165572655736557465575655766557765578655796558065581655826558365584655856558665587655886558965590655916559265593655946559565596655976559865599656006560165602656036560465605656066560765608656096561065611656126561365614656156561665617656186561965620656216562265623656246562565626656276562865629656306563165632656336563465635656366563765638656396564065641656426564365644656456564665647656486564965650656516565265653656546565565656656576565865659656606566165662656636566465665656666566765668656696567065671656726567365674656756567665677656786567965680656816568265683656846568565686656876568865689656906569165692656936569465695656966569765698656996570065701657026570365704657056570665707657086570965710657116571265713657146571565716657176571865719657206572165722657236572465725657266572765728657296573065731657326573365734657356573665737657386573965740657416574265743657446574565746657476574865749657506575165752657536575465755657566575765758657596576065761657626576365764657656576665767657686576965770657716577265773657746577565776657776577865779657806578165782657836578465785657866578765788657896579065791657926579365794657956579665797657986579965800658016580265803658046580565806658076580865809658106581165812658136581465815658166581765818658196582065821658226582365824658256582665827658286582965830658316583265833658346583565836658376583865839658406584165842658436584465845658466584765848658496585065851658526585365854658556585665857658586585965860658616586265863658646586565866658676586865869658706587165872658736587465875658766587765878658796588065881658826588365884658856588665887658886588965890658916589265893658946589565896658976589865899659006590165902659036590465905659066590765908659096591065911659126591365914659156591665917659186591965920659216592265923659246592565926659276592865929659306593165932659336593465935659366593765938659396594065941659426594365944659456594665947659486594965950659516595265953659546595565956659576595865959659606596165962659636596465965659666596765968659696597065971659726597365974659756597665977659786597965980659816598265983659846598565986659876598865989659906599165992659936599465995659966599765998659996600066001660026600366004660056600666007660086600966010660116601266013660146601566016660176601866019660206602166022660236602466025660266602766028660296603066031660326603366034660356603666037660386603966040660416604266043660446604566046660476604866049660506605166052660536605466055660566605766058660596606066061660626606366064660656606666067660686606966070660716607266073660746607566076660776607866079660806608166082660836608466085660866608766088660896609066091660926609366094660956609666097660986609966100661016610266103661046610566106661076610866109661106611166112661136611466115661166611766118661196612066121661226612366124661256612666127661286612966130661316613266133661346613566136661376613866139661406614166142661436614466145661466614766148661496615066151661526615366154661556615666157661586615966160661616616266163661646616566166661676616866169661706617166172661736617466175661766617766178661796618066181661826618366184661856618666187661886618966190661916619266193661946619566196661976619866199662006620166202662036620466205662066620766208662096621066211662126621366214662156621666217662186621966220662216622266223662246622566226662276622866229662306623166232662336623466235662366623766238662396624066241662426624366244662456624666247662486624966250662516625266253662546625566256662576625866259662606626166262662636626466265662666626766268662696627066271662726627366274662756627666277662786627966280662816628266283662846628566286662876628866289662906629166292662936629466295662966629766298662996630066301663026630366304663056630666307663086630966310663116631266313663146631566316663176631866319663206632166322663236632466325663266632766328663296633066331663326633366334663356633666337663386633966340663416634266343663446634566346663476634866349663506635166352663536635466355663566635766358663596636066361663626636366364663656636666367663686636966370663716637266373663746637566376663776637866379663806638166382663836638466385663866638766388663896639066391663926639366394663956639666397663986639966400664016640266403664046640566406664076640866409664106641166412664136641466415664166641766418664196642066421664226642366424664256642666427664286642966430664316643266433664346643566436664376643866439664406644166442664436644466445664466644766448664496645066451664526645366454664556645666457664586645966460664616646266463664646646566466664676646866469664706647166472664736647466475664766647766478664796648066481664826648366484664856648666487664886648966490664916649266493664946649566496664976649866499665006650166502665036650466505665066650766508665096651066511665126651366514665156651666517665186651966520665216652266523665246652566526665276652866529665306653166532665336653466535665366653766538665396654066541665426654366544665456654666547665486654966550665516655266553665546655566556665576655866559665606656166562665636656466565665666656766568665696657066571665726657366574665756657666577665786657966580665816658266583665846658566586665876658866589665906659166592665936659466595665966659766598665996660066601666026660366604666056660666607666086660966610666116661266613666146661566616666176661866619666206662166622666236662466625666266662766628666296663066631666326663366634666356663666637666386663966640666416664266643666446664566646666476664866649666506665166652666536665466655666566665766658666596666066661666626666366664666656666666667666686666966670666716667266673666746667566676666776667866679666806668166682666836668466685666866668766688666896669066691666926669366694666956669666697666986669966700667016670266703667046670566706667076670866709667106671166712667136671466715667166671766718667196672066721667226672366724667256672666727667286672966730667316673266733667346673566736667376673866739667406674166742667436674466745667466674766748667496675066751667526675366754667556675666757667586675966760667616676266763667646676566766667676676866769667706677166772667736677466775667766677766778667796678066781667826678366784667856678666787667886678966790667916679266793667946679566796667976679866799668006680166802668036680466805668066680766808668096681066811668126681366814668156681666817668186681966820668216682266823668246682566826668276682866829668306683166832668336683466835668366683766838668396684066841668426684366844668456684666847668486684966850668516685266853668546685566856668576685866859668606686166862668636686466865668666686766868668696687066871668726687366874668756687666877668786687966880668816688266883668846688566886668876688866889668906689166892668936689466895668966689766898668996690066901669026690366904669056690666907669086690966910669116691266913669146691566916669176691866919669206692166922669236692466925669266692766928669296693066931669326693366934669356693666937669386693966940669416694266943669446694566946669476694866949669506695166952669536695466955669566695766958669596696066961669626696366964669656696666967669686696966970669716697266973669746697566976669776697866979669806698166982669836698466985669866698766988669896699066991669926699366994669956699666997669986699967000670016700267003670046700567006670076700867009670106701167012670136701467015670166701767018670196702067021670226702367024670256702667027670286702967030670316703267033670346703567036670376703867039670406704167042670436704467045670466704767048670496705067051670526705367054670556705667057670586705967060670616706267063670646706567066670676706867069670706707167072670736707467075670766707767078670796708067081670826708367084670856708667087670886708967090670916709267093670946709567096670976709867099671006710167102671036710467105671066710767108671096711067111671126711367114671156711667117671186711967120671216712267123671246712567126671276712867129671306713167132671336713467135671366713767138671396714067141671426714367144671456714667147671486714967150671516715267153671546715567156671576715867159671606716167162671636716467165671666716767168671696717067171671726717367174671756717667177671786717967180671816718267183671846718567186671876718867189671906719167192671936719467195671966719767198671996720067201672026720367204672056720667207672086720967210672116721267213672146721567216672176721867219672206722167222672236722467225672266722767228672296723067231672326723367234672356723667237672386723967240672416724267243672446724567246672476724867249672506725167252672536725467255672566725767258672596726067261672626726367264672656726667267672686726967270672716727267273672746727567276672776727867279672806728167282672836728467285672866728767288672896729067291672926729367294672956729667297672986729967300673016730267303673046730567306673076730867309673106731167312673136731467315673166731767318673196732067321673226732367324673256732667327673286732967330673316733267333673346733567336673376733867339673406734167342673436734467345673466734767348673496735067351673526735367354673556735667357673586735967360673616736267363673646736567366673676736867369673706737167372673736737467375673766737767378673796738067381673826738367384673856738667387673886738967390673916739267393673946739567396673976739867399674006740167402674036740467405674066740767408674096741067411674126741367414674156741667417674186741967420674216742267423674246742567426674276742867429674306743167432674336743467435674366743767438674396744067441674426744367444674456744667447674486744967450674516745267453674546745567456674576745867459674606746167462674636746467465674666746767468674696747067471674726747367474674756747667477674786747967480674816748267483674846748567486674876748867489674906749167492674936749467495674966749767498674996750067501675026750367504675056750667507675086750967510675116751267513675146751567516675176751867519675206752167522675236752467525675266752767528675296753067531675326753367534675356753667537675386753967540675416754267543675446754567546675476754867549675506755167552675536755467555675566755767558675596756067561675626756367564675656756667567675686756967570675716757267573675746757567576675776757867579675806758167582675836758467585675866758767588675896759067591675926759367594675956759667597675986759967600676016760267603676046760567606676076760867609676106761167612676136761467615676166761767618676196762067621676226762367624676256762667627676286762967630676316763267633676346763567636676376763867639676406764167642676436764467645676466764767648676496765067651676526765367654676556765667657676586765967660676616766267663676646766567666676676766867669676706767167672676736767467675676766767767678676796768067681676826768367684676856768667687676886768967690676916769267693676946769567696676976769867699677006770167702677036770467705677066770767708677096771067711677126771367714677156771667717677186771967720677216772267723677246772567726677276772867729677306773167732677336773467735677366773767738677396774067741677426774367744677456774667747677486774967750677516775267753677546775567756677576775867759677606776167762677636776467765677666776767768677696777067771677726777367774677756777667777677786777967780677816778267783677846778567786677876778867789677906779167792677936779467795677966779767798677996780067801678026780367804678056780667807678086780967810678116781267813678146781567816678176781867819678206782167822678236782467825678266782767828678296783067831678326783367834678356783667837678386783967840678416784267843678446784567846678476784867849678506785167852678536785467855678566785767858678596786067861678626786367864678656786667867678686786967870678716787267873678746787567876678776787867879678806788167882678836788467885678866788767888678896789067891678926789367894678956789667897678986789967900679016790267903679046790567906679076790867909679106791167912679136791467915679166791767918679196792067921679226792367924679256792667927679286792967930679316793267933679346793567936679376793867939679406794167942679436794467945679466794767948679496795067951679526795367954679556795667957679586795967960679616796267963679646796567966679676796867969679706797167972679736797467975679766797767978679796798067981679826798367984679856798667987679886798967990679916799267993679946799567996679976799867999680006800168002680036800468005680066800768008680096801068011680126801368014680156801668017680186801968020680216802268023680246802568026680276802868029680306803168032680336803468035680366803768038680396804068041680426804368044680456804668047680486804968050680516805268053680546805568056680576805868059680606806168062680636806468065680666806768068680696807068071680726807368074680756807668077680786807968080680816808268083680846808568086680876808868089680906809168092680936809468095680966809768098680996810068101681026810368104681056810668107681086810968110681116811268113681146811568116681176811868119681206812168122681236812468125681266812768128681296813068131681326813368134681356813668137681386813968140681416814268143681446814568146681476814868149681506815168152681536815468155681566815768158681596816068161681626816368164681656816668167681686816968170681716817268173681746817568176681776817868179681806818168182681836818468185681866818768188681896819068191681926819368194681956819668197681986819968200682016820268203682046820568206682076820868209682106821168212682136821468215682166821768218682196822068221682226822368224682256822668227682286822968230682316823268233682346823568236682376823868239682406824168242682436824468245682466824768248682496825068251682526825368254682556825668257682586825968260682616826268263682646826568266682676826868269682706827168272682736827468275682766827768278682796828068281682826828368284682856828668287682886828968290682916829268293682946829568296682976829868299683006830168302683036830468305683066830768308683096831068311683126831368314683156831668317683186831968320683216832268323683246832568326683276832868329683306833168332683336833468335683366833768338683396834068341683426834368344683456834668347683486834968350683516835268353683546835568356683576835868359683606836168362683636836468365683666836768368683696837068371683726837368374683756837668377683786837968380683816838268383683846838568386683876838868389683906839168392683936839468395683966839768398683996840068401684026840368404684056840668407684086840968410684116841268413684146841568416684176841868419684206842168422684236842468425684266842768428684296843068431684326843368434684356843668437684386843968440684416844268443684446844568446684476844868449684506845168452684536845468455684566845768458684596846068461684626846368464684656846668467684686846968470684716847268473684746847568476684776847868479684806848168482684836848468485684866848768488684896849068491684926849368494684956849668497684986849968500685016850268503685046850568506685076850868509685106851168512685136851468515685166851768518685196852068521685226852368524685256852668527685286852968530685316853268533685346853568536685376853868539685406854168542685436854468545685466854768548685496855068551685526855368554685556855668557685586855968560685616856268563685646856568566685676856868569685706857168572685736857468575685766857768578685796858068581685826858368584685856858668587685886858968590685916859268593685946859568596685976859868599686006860168602686036860468605686066860768608686096861068611686126861368614686156861668617686186861968620686216862268623686246862568626686276862868629686306863168632686336863468635686366863768638686396864068641686426864368644686456864668647686486864968650686516865268653686546865568656686576865868659686606866168662686636866468665686666866768668686696867068671686726867368674686756867668677686786867968680686816868268683686846868568686686876868868689686906869168692686936869468695686966869768698686996870068701687026870368704687056870668707687086870968710687116871268713687146871568716687176871868719687206872168722687236872468725687266872768728687296873068731687326873368734687356873668737687386873968740687416874268743687446874568746687476874868749687506875168752687536875468755687566875768758687596876068761687626876368764687656876668767687686876968770687716877268773687746877568776687776877868779687806878168782687836878468785687866878768788687896879068791687926879368794687956879668797687986879968800688016880268803688046880568806688076880868809688106881168812688136881468815688166881768818688196882068821688226882368824688256882668827688286882968830688316883268833688346883568836688376883868839688406884168842688436884468845688466884768848688496885068851688526885368854688556885668857688586885968860688616886268863688646886568866688676886868869688706887168872688736887468875688766887768878688796888068881688826888368884688856888668887688886888968890688916889268893688946889568896688976889868899689006890168902689036890468905689066890768908689096891068911689126891368914689156891668917689186891968920689216892268923689246892568926689276892868929689306893168932689336893468935689366893768938689396894068941689426894368944689456894668947689486894968950689516895268953689546895568956689576895868959689606896168962689636896468965689666896768968689696897068971689726897368974689756897668977689786897968980689816898268983689846898568986689876898868989689906899168992689936899468995689966899768998689996900069001690026900369004690056900669007690086900969010690116901269013690146901569016690176901869019690206902169022690236902469025690266902769028690296903069031690326903369034690356903669037690386903969040690416904269043690446904569046690476904869049690506905169052690536905469055690566905769058690596906069061690626906369064690656906669067690686906969070690716907269073690746907569076690776907869079690806908169082690836908469085690866908769088690896909069091690926909369094690956909669097690986909969100691016910269103691046910569106691076910869109691106911169112691136911469115691166911769118691196912069121691226912369124691256912669127691286912969130691316913269133691346913569136691376913869139691406914169142691436914469145691466914769148691496915069151691526915369154691556915669157691586915969160691616916269163691646916569166691676916869169691706917169172691736917469175691766917769178691796918069181691826918369184691856918669187691886918969190691916919269193691946919569196691976919869199692006920169202692036920469205692066920769208692096921069211692126921369214692156921669217692186921969220692216922269223692246922569226692276922869229692306923169232692336923469235692366923769238692396924069241692426924369244692456924669247692486924969250692516925269253692546925569256692576925869259692606926169262692636926469265692666926769268692696927069271692726927369274692756927669277692786927969280692816928269283692846928569286692876928869289692906929169292692936929469295692966929769298692996930069301693026930369304693056930669307693086930969310693116931269313693146931569316693176931869319693206932169322693236932469325693266932769328693296933069331693326933369334693356933669337693386933969340693416934269343693446934569346693476934869349693506935169352693536935469355693566935769358693596936069361693626936369364693656936669367693686936969370693716937269373693746937569376693776937869379693806938169382693836938469385693866938769388693896939069391693926939369394693956939669397693986939969400694016940269403694046940569406694076940869409694106941169412694136941469415694166941769418694196942069421694226942369424694256942669427694286942969430694316943269433694346943569436694376943869439694406944169442694436944469445694466944769448694496945069451694526945369454694556945669457694586945969460694616946269463694646946569466694676946869469694706947169472694736947469475694766947769478694796948069481694826948369484694856948669487694886948969490694916949269493694946949569496694976949869499695006950169502695036950469505695066950769508695096951069511695126951369514695156951669517695186951969520695216952269523695246952569526695276952869529695306953169532695336953469535695366953769538695396954069541695426954369544695456954669547695486954969550695516955269553695546955569556695576955869559695606956169562695636956469565695666956769568695696957069571695726957369574695756957669577695786957969580695816958269583695846958569586695876958869589695906959169592695936959469595695966959769598695996960069601696026960369604696056960669607696086960969610696116961269613696146961569616696176961869619696206962169622696236962469625696266962769628696296963069631696326963369634696356963669637696386963969640696416964269643696446964569646696476964869649696506965169652696536965469655696566965769658696596966069661696626966369664696656966669667696686966969670696716967269673696746967569676696776967869679696806968169682696836968469685696866968769688696896969069691696926969369694696956969669697696986969969700697016970269703697046970569706697076970869709697106971169712697136971469715697166971769718697196972069721697226972369724697256972669727697286972969730697316973269733697346973569736697376973869739697406974169742697436974469745697466974769748697496975069751697526975369754697556975669757697586975969760697616976269763697646976569766697676976869769697706977169772697736977469775697766977769778697796978069781697826978369784697856978669787697886978969790697916979269793697946979569796697976979869799698006980169802698036980469805698066980769808698096981069811698126981369814698156981669817698186981969820698216982269823698246982569826698276982869829698306983169832698336983469835698366983769838698396984069841698426984369844698456984669847698486984969850698516985269853698546985569856698576985869859698606986169862698636986469865698666986769868698696987069871698726987369874698756987669877698786987969880698816988269883698846988569886698876988869889698906989169892698936989469895698966989769898698996990069901699026990369904699056990669907699086990969910699116991269913699146991569916699176991869919699206992169922699236992469925699266992769928699296993069931699326993369934699356993669937699386993969940699416994269943699446994569946699476994869949699506995169952699536995469955699566995769958699596996069961699626996369964699656996669967699686996969970699716997269973699746997569976699776997869979699806998169982699836998469985699866998769988699896999069991699926999369994699956999669997699986999970000700017000270003700047000570006700077000870009700107001170012700137001470015700167001770018700197002070021700227002370024700257002670027700287002970030700317003270033700347003570036700377003870039700407004170042700437004470045700467004770048700497005070051700527005370054700557005670057700587005970060700617006270063700647006570066700677006870069700707007170072700737007470075700767007770078700797008070081700827008370084700857008670087700887008970090700917009270093700947009570096700977009870099701007010170102701037010470105701067010770108701097011070111701127011370114701157011670117701187011970120701217012270123701247012570126701277012870129701307013170132701337013470135701367013770138701397014070141701427014370144701457014670147701487014970150701517015270153701547015570156701577015870159701607016170162701637016470165701667016770168701697017070171701727017370174701757017670177701787017970180701817018270183701847018570186701877018870189701907019170192701937019470195701967019770198701997020070201702027020370204702057020670207702087020970210702117021270213702147021570216702177021870219702207022170222702237022470225702267022770228702297023070231702327023370234702357023670237702387023970240702417024270243702447024570246702477024870249702507025170252702537025470255702567025770258702597026070261702627026370264702657026670267702687026970270702717027270273702747027570276702777027870279702807028170282702837028470285702867028770288702897029070291702927029370294702957029670297702987029970300703017030270303703047030570306703077030870309703107031170312703137031470315703167031770318703197032070321703227032370324703257032670327703287032970330703317033270333703347033570336703377033870339703407034170342703437034470345703467034770348703497035070351703527035370354703557035670357703587035970360703617036270363703647036570366703677036870369703707037170372703737037470375703767037770378703797038070381703827038370384703857038670387703887038970390703917039270393703947039570396703977039870399704007040170402704037040470405704067040770408704097041070411704127041370414704157041670417704187041970420704217042270423704247042570426704277042870429704307043170432704337043470435704367043770438704397044070441704427044370444704457044670447704487044970450704517045270453704547045570456704577045870459704607046170462704637046470465704667046770468704697047070471704727047370474704757047670477704787047970480704817048270483704847048570486704877048870489704907049170492704937049470495704967049770498704997050070501705027050370504705057050670507705087050970510705117051270513705147051570516705177051870519705207052170522705237052470525705267052770528705297053070531705327053370534705357053670537705387053970540705417054270543705447054570546705477054870549705507055170552705537055470555705567055770558705597056070561705627056370564705657056670567705687056970570705717057270573705747057570576705777057870579705807058170582705837058470585705867058770588705897059070591705927059370594705957059670597705987059970600706017060270603706047060570606706077060870609706107061170612706137061470615706167061770618706197062070621706227062370624706257062670627706287062970630706317063270633706347063570636706377063870639706407064170642706437064470645706467064770648706497065070651706527065370654706557065670657706587065970660706617066270663706647066570666706677066870669706707067170672706737067470675706767067770678706797068070681706827068370684706857068670687706887068970690706917069270693706947069570696706977069870699707007070170702707037070470705707067070770708707097071070711707127071370714707157071670717707187071970720707217072270723707247072570726707277072870729707307073170732707337073470735707367073770738707397074070741707427074370744707457074670747707487074970750707517075270753707547075570756707577075870759707607076170762707637076470765707667076770768707697077070771707727077370774707757077670777707787077970780707817078270783707847078570786707877078870789707907079170792707937079470795707967079770798707997080070801708027080370804708057080670807708087080970810708117081270813708147081570816708177081870819708207082170822708237082470825708267082770828708297083070831708327083370834708357083670837708387083970840708417084270843708447084570846708477084870849708507085170852708537085470855708567085770858708597086070861708627086370864708657086670867708687086970870708717087270873708747087570876708777087870879708807088170882708837088470885708867088770888708897089070891708927089370894708957089670897708987089970900709017090270903709047090570906709077090870909709107091170912709137091470915709167091770918709197092070921709227092370924709257092670927709287092970930709317093270933709347093570936709377093870939709407094170942709437094470945709467094770948709497095070951709527095370954709557095670957709587095970960709617096270963709647096570966709677096870969709707097170972709737097470975709767097770978709797098070981709827098370984709857098670987709887098970990709917099270993709947099570996709977099870999710007100171002710037100471005710067100771008710097101071011710127101371014710157101671017710187101971020710217102271023710247102571026710277102871029710307103171032710337103471035710367103771038710397104071041710427104371044710457104671047710487104971050710517105271053710547105571056710577105871059710607106171062710637106471065710667106771068710697107071071710727107371074710757107671077710787107971080710817108271083710847108571086710877108871089710907109171092710937109471095710967109771098710997110071101711027110371104711057110671107711087110971110711117111271113711147111571116711177111871119711207112171122711237112471125711267112771128711297113071131711327113371134711357113671137711387113971140711417114271143711447114571146711477114871149711507115171152711537115471155711567115771158711597116071161711627116371164711657116671167711687116971170711717117271173711747117571176711777117871179711807118171182711837118471185711867118771188711897119071191711927119371194711957119671197711987119971200712017120271203712047120571206712077120871209712107121171212712137121471215712167121771218712197122071221712227122371224712257122671227712287122971230712317123271233712347123571236712377123871239712407124171242712437124471245712467124771248712497125071251712527125371254712557125671257712587125971260712617126271263712647126571266712677126871269712707127171272712737127471275712767127771278712797128071281712827128371284712857128671287712887128971290712917129271293712947129571296712977129871299713007130171302713037130471305713067130771308713097131071311713127131371314713157131671317713187131971320713217132271323713247132571326713277132871329713307133171332713337133471335713367133771338713397134071341713427134371344713457134671347713487134971350713517135271353713547135571356713577135871359713607136171362713637136471365713667136771368713697137071371713727137371374713757137671377713787137971380713817138271383713847138571386713877138871389713907139171392713937139471395713967139771398713997140071401714027140371404714057140671407714087140971410714117141271413714147141571416714177141871419714207142171422714237142471425714267142771428714297143071431714327143371434714357143671437714387143971440714417144271443714447144571446714477144871449714507145171452714537145471455714567145771458714597146071461714627146371464714657146671467714687146971470714717147271473714747147571476714777147871479714807148171482714837148471485714867148771488714897149071491714927149371494714957149671497714987149971500715017150271503715047150571506715077150871509715107151171512715137151471515715167151771518715197152071521715227152371524715257152671527715287152971530715317153271533715347153571536715377153871539715407154171542715437154471545715467154771548715497155071551715527155371554715557155671557715587155971560715617156271563715647156571566715677156871569715707157171572715737157471575715767157771578715797158071581715827158371584715857158671587715887158971590715917159271593715947159571596715977159871599716007160171602716037160471605716067160771608716097161071611716127161371614716157161671617716187161971620716217162271623716247162571626716277162871629716307163171632716337163471635716367163771638716397164071641716427164371644716457164671647716487164971650716517165271653716547165571656716577165871659716607166171662716637166471665716667166771668716697167071671716727167371674716757167671677716787167971680716817168271683716847168571686716877168871689716907169171692716937169471695716967169771698716997170071701717027170371704717057170671707717087170971710717117171271713717147171571716717177171871719717207172171722717237172471725717267172771728717297173071731717327173371734717357173671737717387173971740717417174271743717447174571746717477174871749717507175171752717537175471755717567175771758717597176071761717627176371764717657176671767717687176971770717717177271773717747177571776717777177871779717807178171782717837178471785717867178771788717897179071791717927179371794717957179671797717987179971800718017180271803718047180571806718077180871809718107181171812718137181471815718167181771818718197182071821718227182371824718257182671827718287182971830718317183271833718347183571836718377183871839718407184171842718437184471845718467184771848718497185071851718527185371854718557185671857718587185971860718617186271863718647186571866718677186871869718707187171872718737187471875718767187771878718797188071881718827188371884718857188671887718887188971890718917189271893718947189571896718977189871899719007190171902719037190471905719067190771908719097191071911719127191371914719157191671917719187191971920719217192271923719247192571926719277192871929719307193171932719337193471935719367193771938719397194071941719427194371944719457194671947719487194971950719517195271953719547195571956719577195871959719607196171962719637196471965719667196771968719697197071971719727197371974719757197671977719787197971980719817198271983719847198571986719877198871989719907199171992719937199471995719967199771998719997200072001720027200372004720057200672007720087200972010720117201272013720147201572016720177201872019720207202172022720237202472025720267202772028720297203072031720327203372034720357203672037720387203972040720417204272043720447204572046720477204872049720507205172052720537205472055720567205772058720597206072061720627206372064720657206672067720687206972070720717207272073720747207572076720777207872079720807208172082720837208472085720867208772088720897209072091720927209372094720957209672097720987209972100721017210272103721047210572106721077210872109721107211172112721137211472115721167211772118721197212072121721227212372124721257212672127721287212972130721317213272133721347213572136721377213872139721407214172142721437214472145721467214772148721497215072151721527215372154721557215672157721587215972160721617216272163721647216572166721677216872169721707217172172721737217472175721767217772178721797218072181721827218372184721857218672187721887218972190721917219272193721947219572196721977219872199722007220172202722037220472205722067220772208722097221072211722127221372214722157221672217722187221972220722217222272223722247222572226722277222872229722307223172232722337223472235722367223772238722397224072241722427224372244722457224672247722487224972250722517225272253722547225572256722577225872259722607226172262722637226472265722667226772268722697227072271722727227372274722757227672277722787227972280722817228272283722847228572286722877228872289722907229172292722937229472295722967229772298722997230072301723027230372304723057230672307723087230972310723117231272313723147231572316723177231872319723207232172322723237232472325723267232772328723297233072331723327233372334723357233672337723387233972340723417234272343723447234572346723477234872349723507235172352723537235472355723567235772358723597236072361723627236372364723657236672367723687236972370723717237272373723747237572376723777237872379723807238172382723837238472385723867238772388723897239072391723927239372394723957239672397723987239972400724017240272403724047240572406724077240872409724107241172412724137241472415724167241772418724197242072421724227242372424724257242672427724287242972430724317243272433724347243572436724377243872439724407244172442724437244472445724467244772448724497245072451724527245372454724557245672457724587245972460724617246272463724647246572466724677246872469724707247172472724737247472475724767247772478724797248072481724827248372484724857248672487724887248972490724917249272493724947249572496724977249872499725007250172502725037250472505725067250772508725097251072511725127251372514725157251672517725187251972520725217252272523725247252572526725277252872529725307253172532725337253472535725367253772538725397254072541725427254372544725457254672547725487254972550725517255272553725547255572556725577255872559725607256172562725637256472565725667256772568725697257072571725727257372574725757257672577725787257972580725817258272583725847258572586725877258872589725907259172592725937259472595725967259772598725997260072601726027260372604726057260672607726087260972610726117261272613726147261572616726177261872619726207262172622726237262472625726267262772628726297263072631726327263372634726357263672637726387263972640726417264272643726447264572646726477264872649726507265172652726537265472655726567265772658726597266072661726627266372664726657266672667726687266972670726717267272673726747267572676726777267872679726807268172682726837268472685726867268772688726897269072691726927269372694726957269672697726987269972700727017270272703727047270572706727077270872709727107271172712727137271472715727167271772718727197272072721727227272372724727257272672727727287272972730727317273272733727347273572736727377273872739727407274172742727437274472745727467274772748727497275072751727527275372754727557275672757727587275972760727617276272763727647276572766727677276872769727707277172772727737277472775727767277772778727797278072781727827278372784727857278672787727887278972790727917279272793727947279572796727977279872799728007280172802728037280472805728067280772808728097281072811728127281372814728157281672817728187281972820728217282272823728247282572826728277282872829728307283172832728337283472835728367283772838728397284072841728427284372844728457284672847728487284972850728517285272853728547285572856728577285872859728607286172862728637286472865728667286772868728697287072871728727287372874728757287672877728787287972880728817288272883728847288572886728877288872889728907289172892728937289472895728967289772898728997290072901729027290372904729057290672907729087290972910729117291272913729147291572916729177291872919729207292172922729237292472925729267292772928729297293072931729327293372934729357293672937729387293972940729417294272943729447294572946729477294872949729507295172952729537295472955729567295772958729597296072961729627296372964729657296672967729687296972970729717297272973729747297572976729777297872979729807298172982729837298472985729867298772988729897299072991729927299372994729957299672997729987299973000730017300273003730047300573006730077300873009730107301173012730137301473015730167301773018730197302073021730227302373024730257302673027730287302973030730317303273033730347303573036730377303873039730407304173042730437304473045730467304773048730497305073051730527305373054730557305673057730587305973060730617306273063730647306573066730677306873069730707307173072730737307473075730767307773078730797308073081730827308373084730857308673087730887308973090730917309273093730947309573096730977309873099731007310173102731037310473105731067310773108731097311073111731127311373114731157311673117731187311973120731217312273123731247312573126731277312873129731307313173132731337313473135731367313773138731397314073141731427314373144731457314673147731487314973150731517315273153731547315573156731577315873159731607316173162731637316473165731667316773168731697317073171731727317373174731757317673177731787317973180731817318273183731847318573186731877318873189731907319173192731937319473195731967319773198731997320073201732027320373204732057320673207732087320973210732117321273213732147321573216732177321873219732207322173222732237322473225732267322773228732297323073231732327323373234732357323673237732387323973240732417324273243732447324573246732477324873249732507325173252732537325473255732567325773258732597326073261732627326373264732657326673267732687326973270732717327273273732747327573276732777327873279732807328173282732837328473285732867328773288732897329073291732927329373294732957329673297732987329973300733017330273303733047330573306733077330873309733107331173312733137331473315733167331773318733197332073321733227332373324733257332673327733287332973330733317333273333733347333573336733377333873339733407334173342733437334473345733467334773348733497335073351733527335373354733557335673357733587335973360733617336273363733647336573366733677336873369733707337173372733737337473375733767337773378733797338073381733827338373384733857338673387733887338973390733917339273393733947339573396733977339873399734007340173402734037340473405734067340773408734097341073411734127341373414734157341673417734187341973420734217342273423734247342573426734277342873429734307343173432734337343473435734367343773438734397344073441734427344373444734457344673447734487344973450734517345273453734547345573456734577345873459734607346173462734637346473465734667346773468734697347073471734727347373474734757347673477734787347973480734817348273483734847348573486734877348873489734907349173492734937349473495734967349773498734997350073501735027350373504735057350673507735087350973510735117351273513735147351573516735177351873519735207352173522735237352473525735267352773528735297353073531735327353373534735357353673537735387353973540735417354273543735447354573546735477354873549735507355173552735537355473555735567355773558735597356073561735627356373564735657356673567735687356973570735717357273573735747357573576735777357873579735807358173582735837358473585735867358773588735897359073591735927359373594735957359673597735987359973600736017360273603736047360573606736077360873609736107361173612736137361473615736167361773618736197362073621736227362373624736257362673627736287362973630736317363273633736347363573636736377363873639736407364173642736437364473645736467364773648736497365073651736527365373654736557365673657736587365973660736617366273663736647366573666736677366873669736707367173672736737367473675736767367773678736797368073681736827368373684736857368673687736887368973690736917369273693736947369573696736977369873699737007370173702737037370473705737067370773708737097371073711737127371373714737157371673717737187371973720737217372273723737247372573726737277372873729737307373173732737337373473735737367373773738737397374073741737427374373744737457374673747737487374973750737517375273753737547375573756737577375873759737607376173762737637376473765737667376773768737697377073771737727377373774737757377673777737787377973780737817378273783737847378573786737877378873789737907379173792737937379473795737967379773798737997380073801738027380373804738057380673807738087380973810738117381273813738147381573816738177381873819738207382173822738237382473825738267382773828738297383073831738327383373834738357383673837738387383973840738417384273843738447384573846738477384873849738507385173852738537385473855738567385773858738597386073861738627386373864738657386673867738687386973870738717387273873738747387573876738777387873879738807388173882738837388473885738867388773888738897389073891738927389373894738957389673897738987389973900739017390273903739047390573906739077390873909739107391173912739137391473915739167391773918739197392073921739227392373924739257392673927739287392973930739317393273933739347393573936739377393873939739407394173942739437394473945739467394773948739497395073951739527395373954739557395673957739587395973960739617396273963739647396573966739677396873969739707397173972739737397473975739767397773978739797398073981739827398373984739857398673987739887398973990739917399273993739947399573996739977399873999740007400174002740037400474005740067400774008740097401074011740127401374014740157401674017740187401974020740217402274023740247402574026740277402874029740307403174032740337403474035740367403774038740397404074041740427404374044740457404674047740487404974050740517405274053740547405574056740577405874059740607406174062740637406474065740667406774068740697407074071740727407374074740757407674077740787407974080740817408274083740847408574086740877408874089740907409174092740937409474095740967409774098740997410074101741027410374104741057410674107741087410974110741117411274113741147411574116741177411874119741207412174122741237412474125741267412774128741297413074131741327413374134741357413674137741387413974140741417414274143741447414574146741477414874149741507415174152741537415474155741567415774158741597416074161741627416374164741657416674167741687416974170741717417274173741747417574176741777417874179741807418174182741837418474185741867418774188741897419074191741927419374194741957419674197741987419974200742017420274203742047420574206742077420874209742107421174212742137421474215742167421774218742197422074221742227422374224742257422674227742287422974230742317423274233742347423574236742377423874239742407424174242742437424474245742467424774248742497425074251742527425374254742557425674257742587425974260742617426274263742647426574266742677426874269742707427174272742737427474275742767427774278742797428074281742827428374284742857428674287742887428974290742917429274293742947429574296742977429874299743007430174302743037430474305743067430774308743097431074311743127431374314743157431674317743187431974320743217432274323743247432574326743277432874329743307433174332743337433474335743367433774338743397434074341743427434374344743457434674347743487434974350743517435274353743547435574356743577435874359743607436174362743637436474365743667436774368743697437074371743727437374374743757437674377743787437974380743817438274383743847438574386743877438874389743907439174392743937439474395743967439774398743997440074401744027440374404744057440674407744087440974410744117441274413744147441574416744177441874419744207442174422744237442474425744267442774428744297443074431744327443374434744357443674437744387443974440744417444274443744447444574446744477444874449744507445174452744537445474455744567445774458744597446074461744627446374464744657446674467744687446974470744717447274473744747447574476744777447874479744807448174482744837448474485744867448774488744897449074491744927449374494744957449674497744987449974500745017450274503745047450574506745077450874509745107451174512745137451474515745167451774518745197452074521745227452374524745257452674527745287452974530745317453274533745347453574536745377453874539745407454174542745437454474545745467454774548745497455074551745527455374554745557455674557745587455974560745617456274563745647456574566745677456874569745707457174572745737457474575745767457774578745797458074581745827458374584745857458674587745887458974590745917459274593745947459574596745977459874599746007460174602746037460474605746067460774608746097461074611746127461374614746157461674617746187461974620746217462274623746247462574626746277462874629746307463174632746337463474635746367463774638746397464074641746427464374644746457464674647746487464974650746517465274653746547465574656746577465874659746607466174662746637466474665746667466774668746697467074671746727467374674746757467674677746787467974680746817468274683746847468574686746877468874689746907469174692746937469474695746967469774698746997470074701747027470374704747057470674707747087470974710747117471274713747147471574716747177471874719747207472174722747237472474725747267472774728747297473074731747327473374734747357473674737747387473974740747417474274743747447474574746747477474874749747507475174752747537475474755747567475774758747597476074761747627476374764747657476674767747687476974770747717477274773747747477574776747777477874779747807478174782747837478474785747867478774788747897479074791747927479374794747957479674797747987479974800748017480274803748047480574806748077480874809748107481174812748137481474815748167481774818748197482074821748227482374824748257482674827748287482974830748317483274833748347483574836748377483874839748407484174842748437484474845748467484774848748497485074851748527485374854748557485674857748587485974860748617486274863748647486574866748677486874869748707487174872748737487474875748767487774878748797488074881748827488374884748857488674887748887488974890748917489274893748947489574896748977489874899749007490174902749037490474905749067490774908749097491074911749127491374914749157491674917749187491974920749217492274923749247492574926749277492874929749307493174932749337493474935749367493774938749397494074941749427494374944749457494674947749487494974950749517495274953749547495574956749577495874959749607496174962749637496474965749667496774968749697497074971749727497374974749757497674977749787497974980749817498274983749847498574986749877498874989749907499174992749937499474995749967499774998749997500075001750027500375004750057500675007750087500975010750117501275013750147501575016750177501875019750207502175022750237502475025750267502775028750297503075031750327503375034750357503675037750387503975040750417504275043750447504575046750477504875049750507505175052750537505475055750567505775058750597506075061750627506375064750657506675067750687506975070750717507275073750747507575076750777507875079750807508175082750837508475085750867508775088750897509075091750927509375094750957509675097750987509975100751017510275103751047510575106751077510875109751107511175112751137511475115751167511775118751197512075121751227512375124751257512675127751287512975130751317513275133751347513575136751377513875139751407514175142751437514475145751467514775148751497515075151751527515375154751557515675157751587515975160751617516275163751647516575166751677516875169751707517175172751737517475175751767517775178751797518075181751827518375184751857518675187751887518975190751917519275193751947519575196751977519875199752007520175202752037520475205752067520775208752097521075211752127521375214752157521675217752187521975220752217522275223752247522575226752277522875229752307523175232752337523475235752367523775238752397524075241752427524375244752457524675247752487524975250752517525275253752547525575256752577525875259752607526175262752637526475265752667526775268752697527075271752727527375274752757527675277752787527975280752817528275283752847528575286752877528875289752907529175292752937529475295752967529775298752997530075301753027530375304753057530675307753087530975310753117531275313753147531575316753177531875319753207532175322753237532475325753267532775328753297533075331753327533375334753357533675337753387533975340753417534275343753447534575346753477534875349753507535175352753537535475355753567535775358753597536075361753627536375364753657536675367753687536975370753717537275373753747537575376753777537875379753807538175382753837538475385753867538775388753897539075391753927539375394753957539675397753987539975400754017540275403754047540575406754077540875409754107541175412754137541475415754167541775418754197542075421754227542375424754257542675427754287542975430754317543275433754347543575436754377543875439754407544175442754437544475445754467544775448754497545075451754527545375454754557545675457754587545975460754617546275463754647546575466754677546875469754707547175472754737547475475754767547775478754797548075481754827548375484754857548675487754887548975490754917549275493754947549575496754977549875499755007550175502755037550475505755067550775508755097551075511755127551375514755157551675517755187551975520755217552275523755247552575526755277552875529755307553175532755337553475535755367553775538755397554075541755427554375544755457554675547755487554975550755517555275553755547555575556755577555875559755607556175562755637556475565755667556775568755697557075571755727557375574755757557675577755787557975580755817558275583755847558575586755877558875589755907559175592755937559475595755967559775598755997560075601756027560375604756057560675607756087560975610756117561275613756147561575616756177561875619756207562175622756237562475625756267562775628756297563075631756327563375634756357563675637756387563975640756417564275643756447564575646756477564875649756507565175652756537565475655756567565775658756597566075661756627566375664756657566675667756687566975670756717567275673756747567575676756777567875679756807568175682756837568475685756867568775688756897569075691756927569375694756957569675697756987569975700757017570275703757047570575706757077570875709757107571175712757137571475715757167571775718757197572075721757227572375724757257572675727757287572975730757317573275733757347573575736757377573875739757407574175742757437574475745757467574775748757497575075751757527575375754757557575675757757587575975760757617576275763757647576575766757677576875769757707577175772757737577475775757767577775778757797578075781757827578375784757857578675787757887578975790757917579275793757947579575796757977579875799758007580175802758037580475805758067580775808758097581075811758127581375814758157581675817758187581975820758217582275823758247582575826758277582875829758307583175832758337583475835758367583775838758397584075841758427584375844758457584675847758487584975850758517585275853758547585575856758577585875859758607586175862758637586475865758667586775868758697587075871758727587375874758757587675877758787587975880758817588275883758847588575886758877588875889758907589175892758937589475895758967589775898758997590075901759027590375904759057590675907759087590975910759117591275913759147591575916759177591875919759207592175922759237592475925759267592775928759297593075931759327593375934759357593675937759387593975940759417594275943759447594575946759477594875949759507595175952759537595475955759567595775958759597596075961759627596375964759657596675967759687596975970759717597275973759747597575976759777597875979759807598175982759837598475985759867598775988759897599075991759927599375994759957599675997759987599976000760017600276003760047600576006760077600876009760107601176012760137601476015760167601776018760197602076021760227602376024760257602676027760287602976030760317603276033760347603576036760377603876039760407604176042760437604476045760467604776048760497605076051760527605376054760557605676057760587605976060760617606276063760647606576066760677606876069760707607176072760737607476075760767607776078760797608076081760827608376084760857608676087760887608976090760917609276093760947609576096760977609876099761007610176102761037610476105761067610776108761097611076111761127611376114761157611676117761187611976120761217612276123761247612576126761277612876129761307613176132761337613476135761367613776138761397614076141761427614376144761457614676147761487614976150761517615276153761547615576156761577615876159761607616176162761637616476165761667616776168761697617076171761727617376174761757617676177761787617976180761817618276183761847618576186761877618876189761907619176192761937619476195761967619776198761997620076201762027620376204762057620676207762087620976210762117621276213762147621576216762177621876219762207622176222762237622476225762267622776228762297623076231762327623376234762357623676237762387623976240762417624276243762447624576246762477624876249762507625176252762537625476255762567625776258762597626076261762627626376264762657626676267762687626976270762717627276273762747627576276762777627876279762807628176282762837628476285762867628776288762897629076291762927629376294762957629676297762987629976300763017630276303763047630576306763077630876309763107631176312763137631476315763167631776318763197632076321763227632376324763257632676327763287632976330763317633276333763347633576336763377633876339763407634176342763437634476345763467634776348763497635076351763527635376354763557635676357763587635976360763617636276363763647636576366763677636876369763707637176372763737637476375763767637776378763797638076381763827638376384763857638676387763887638976390763917639276393763947639576396763977639876399764007640176402764037640476405764067640776408764097641076411764127641376414764157641676417764187641976420764217642276423764247642576426764277642876429764307643176432764337643476435764367643776438764397644076441764427644376444764457644676447764487644976450764517645276453764547645576456764577645876459764607646176462764637646476465764667646776468764697647076471764727647376474764757647676477764787647976480764817648276483764847648576486764877648876489764907649176492764937649476495764967649776498764997650076501765027650376504765057650676507765087650976510765117651276513765147651576516765177651876519765207652176522765237652476525765267652776528765297653076531765327653376534765357653676537765387653976540765417654276543765447654576546765477654876549765507655176552765537655476555765567655776558765597656076561765627656376564765657656676567765687656976570765717657276573765747657576576765777657876579765807658176582765837658476585765867658776588765897659076591765927659376594765957659676597765987659976600766017660276603766047660576606766077660876609766107661176612766137661476615766167661776618766197662076621766227662376624766257662676627766287662976630766317663276633766347663576636766377663876639766407664176642766437664476645766467664776648766497665076651766527665376654766557665676657766587665976660766617666276663766647666576666766677666876669766707667176672766737667476675766767667776678766797668076681766827668376684766857668676687766887668976690766917669276693766947669576696766977669876699767007670176702767037670476705767067670776708767097671076711767127671376714767157671676717767187671976720767217672276723767247672576726767277672876729767307673176732767337673476735767367673776738767397674076741767427674376744767457674676747767487674976750767517675276753767547675576756767577675876759767607676176762767637676476765767667676776768767697677076771767727677376774767757677676777767787677976780767817678276783767847678576786767877678876789767907679176792767937679476795767967679776798767997680076801768027680376804768057680676807768087680976810768117681276813768147681576816768177681876819768207682176822768237682476825768267682776828768297683076831768327683376834768357683676837768387683976840768417684276843768447684576846768477684876849768507685176852768537685476855768567685776858768597686076861768627686376864768657686676867768687686976870768717687276873768747687576876768777687876879768807688176882768837688476885768867688776888768897689076891768927689376894768957689676897768987689976900769017690276903769047690576906769077690876909769107691176912769137691476915769167691776918769197692076921769227692376924769257692676927769287692976930769317693276933769347693576936769377693876939769407694176942769437694476945769467694776948769497695076951769527695376954769557695676957769587695976960769617696276963769647696576966769677696876969769707697176972769737697476975769767697776978769797698076981769827698376984769857698676987769887698976990769917699276993769947699576996769977699876999770007700177002770037700477005770067700777008770097701077011770127701377014770157701677017770187701977020770217702277023770247702577026770277702877029770307703177032770337703477035770367703777038770397704077041770427704377044770457704677047770487704977050770517705277053770547705577056770577705877059770607706177062770637706477065770667706777068770697707077071770727707377074770757707677077770787707977080770817708277083770847708577086770877708877089770907709177092770937709477095770967709777098770997710077101771027710377104771057710677107771087710977110771117711277113771147711577116771177711877119771207712177122771237712477125771267712777128771297713077131771327713377134771357713677137771387713977140771417714277143771447714577146771477714877149771507715177152771537715477155771567715777158771597716077161771627716377164771657716677167771687716977170771717717277173771747717577176771777717877179771807718177182771837718477185771867718777188771897719077191771927719377194771957719677197771987719977200772017720277203772047720577206772077720877209772107721177212772137721477215772167721777218772197722077221772227722377224772257722677227772287722977230772317723277233772347723577236772377723877239772407724177242772437724477245772467724777248772497725077251772527725377254772557725677257772587725977260772617726277263772647726577266772677726877269772707727177272772737727477275772767727777278772797728077281772827728377284772857728677287772887728977290772917729277293772947729577296772977729877299773007730177302773037730477305773067730777308773097731077311773127731377314773157731677317773187731977320773217732277323773247732577326773277732877329773307733177332773337733477335773367733777338773397734077341773427734377344773457734677347773487734977350773517735277353773547735577356773577735877359773607736177362773637736477365773667736777368773697737077371773727737377374773757737677377773787737977380773817738277383773847738577386773877738877389773907739177392773937739477395773967739777398773997740077401774027740377404774057740677407774087740977410774117741277413774147741577416774177741877419774207742177422774237742477425774267742777428774297743077431774327743377434774357743677437774387743977440774417744277443774447744577446774477744877449774507745177452774537745477455774567745777458774597746077461774627746377464774657746677467774687746977470774717747277473774747747577476774777747877479774807748177482774837748477485774867748777488774897749077491774927749377494774957749677497774987749977500775017750277503775047750577506775077750877509775107751177512775137751477515775167751777518775197752077521775227752377524775257752677527775287752977530775317753277533775347753577536775377753877539775407754177542775437754477545775467754777548775497755077551775527755377554775557755677557775587755977560775617756277563775647756577566775677756877569775707757177572775737757477575775767757777578775797758077581775827758377584775857758677587775887758977590775917759277593775947759577596775977759877599776007760177602776037760477605776067760777608776097761077611776127761377614776157761677617776187761977620776217762277623776247762577626776277762877629776307763177632776337763477635776367763777638776397764077641776427764377644776457764677647776487764977650776517765277653776547765577656776577765877659776607766177662776637766477665776667766777668776697767077671776727767377674776757767677677776787767977680776817768277683776847768577686776877768877689776907769177692776937769477695776967769777698776997770077701777027770377704777057770677707777087770977710777117771277713777147771577716777177771877719777207772177722777237772477725777267772777728777297773077731777327773377734777357773677737777387773977740777417774277743777447774577746777477774877749777507775177752777537775477755777567775777758777597776077761777627776377764777657776677767777687776977770777717777277773777747777577776777777777877779777807778177782777837778477785777867778777788777897779077791777927779377794777957779677797777987779977800778017780277803778047780577806778077780877809778107781177812778137781477815778167781777818778197782077821778227782377824778257782677827778287782977830778317783277833778347783577836778377783877839778407784177842778437784477845778467784777848778497785077851778527785377854778557785677857778587785977860778617786277863778647786577866778677786877869778707787177872778737787477875778767787777878778797788077881778827788377884778857788677887778887788977890778917789277893778947789577896778977789877899779007790177902779037790477905779067790777908779097791077911779127791377914779157791677917779187791977920779217792277923779247792577926779277792877929779307793177932779337793477935779367793777938779397794077941779427794377944779457794677947779487794977950779517795277953779547795577956779577795877959779607796177962779637796477965779667796777968779697797077971779727797377974779757797677977779787797977980779817798277983779847798577986779877798877989779907799177992779937799477995779967799777998779997800078001780027800378004780057800678007780087800978010780117801278013780147801578016780177801878019780207802178022780237802478025780267802778028780297803078031780327803378034780357803678037780387803978040780417804278043780447804578046780477804878049780507805178052780537805478055780567805778058780597806078061780627806378064780657806678067780687806978070780717807278073780747807578076780777807878079780807808178082780837808478085780867808778088780897809078091780927809378094780957809678097780987809978100781017810278103781047810578106781077810878109781107811178112781137811478115781167811778118781197812078121781227812378124781257812678127781287812978130781317813278133781347813578136781377813878139781407814178142781437814478145781467814778148781497815078151781527815378154781557815678157781587815978160781617816278163781647816578166781677816878169781707817178172781737817478175781767817778178781797818078181781827818378184781857818678187781887818978190781917819278193781947819578196781977819878199782007820178202782037820478205782067820778208782097821078211782127821378214782157821678217782187821978220782217822278223782247822578226782277822878229782307823178232782337823478235782367823778238782397824078241782427824378244782457824678247782487824978250782517825278253782547825578256782577825878259782607826178262782637826478265782667826778268782697827078271782727827378274782757827678277782787827978280782817828278283782847828578286782877828878289782907829178292782937829478295782967829778298782997830078301783027830378304783057830678307783087830978310783117831278313783147831578316783177831878319783207832178322783237832478325783267832778328783297833078331783327833378334783357833678337783387833978340783417834278343783447834578346783477834878349783507835178352783537835478355783567835778358783597836078361783627836378364783657836678367783687836978370783717837278373783747837578376783777837878379783807838178382783837838478385783867838778388783897839078391783927839378394783957839678397783987839978400784017840278403784047840578406784077840878409784107841178412784137841478415784167841778418784197842078421784227842378424784257842678427784287842978430784317843278433784347843578436784377843878439784407844178442784437844478445784467844778448784497845078451784527845378454784557845678457784587845978460784617846278463784647846578466784677846878469784707847178472784737847478475784767847778478784797848078481784827848378484784857848678487784887848978490784917849278493784947849578496784977849878499785007850178502785037850478505785067850778508785097851078511785127851378514785157851678517785187851978520785217852278523785247852578526785277852878529785307853178532785337853478535785367853778538785397854078541785427854378544785457854678547785487854978550785517855278553785547855578556785577855878559785607856178562785637856478565785667856778568785697857078571785727857378574785757857678577785787857978580785817858278583785847858578586785877858878589785907859178592785937859478595785967859778598785997860078601786027860378604786057860678607786087860978610786117861278613786147861578616786177861878619786207862178622786237862478625786267862778628786297863078631786327863378634786357863678637786387863978640786417864278643786447864578646786477864878649786507865178652786537865478655786567865778658786597866078661786627866378664786657866678667786687866978670786717867278673786747867578676786777867878679786807868178682786837868478685786867868778688786897869078691786927869378694786957869678697786987869978700787017870278703787047870578706787077870878709787107871178712787137871478715787167871778718787197872078721787227872378724787257872678727787287872978730787317873278733787347873578736787377873878739787407874178742787437874478745787467874778748787497875078751787527875378754787557875678757787587875978760787617876278763787647876578766787677876878769787707877178772787737877478775787767877778778787797878078781787827878378784787857878678787787887878978790787917879278793787947879578796787977879878799788007880178802788037880478805788067880778808788097881078811788127881378814788157881678817788187881978820788217882278823788247882578826788277882878829788307883178832788337883478835788367883778838788397884078841788427884378844788457884678847788487884978850788517885278853788547885578856788577885878859788607886178862788637886478865788667886778868788697887078871788727887378874788757887678877788787887978880788817888278883788847888578886788877888878889788907889178892788937889478895788967889778898788997890078901789027890378904789057890678907789087890978910789117891278913789147891578916789177891878919789207892178922789237892478925789267892778928789297893078931789327893378934789357893678937789387893978940789417894278943789447894578946789477894878949789507895178952789537895478955789567895778958789597896078961789627896378964789657896678967789687896978970789717897278973789747897578976789777897878979789807898178982789837898478985789867898778988789897899078991789927899378994789957899678997789987899979000790017900279003790047900579006790077900879009790107901179012790137901479015790167901779018790197902079021790227902379024790257902679027790287902979030790317903279033790347903579036790377903879039790407904179042790437904479045790467904779048790497905079051790527905379054790557905679057790587905979060790617906279063790647906579066790677906879069790707907179072790737907479075790767907779078790797908079081790827908379084790857908679087790887908979090790917909279093790947909579096790977909879099791007910179102791037910479105791067910779108791097911079111791127911379114791157911679117791187911979120791217912279123791247912579126791277912879129791307913179132791337913479135791367913779138791397914079141791427914379144791457914679147791487914979150791517915279153791547915579156791577915879159791607916179162791637916479165791667916779168791697917079171791727917379174791757917679177791787917979180791817918279183791847918579186791877918879189791907919179192791937919479195791967919779198791997920079201792027920379204792057920679207792087920979210792117921279213792147921579216792177921879219792207922179222792237922479225792267922779228792297923079231792327923379234792357923679237792387923979240792417924279243792447924579246792477924879249792507925179252792537925479255792567925779258792597926079261792627926379264792657926679267792687926979270792717927279273792747927579276792777927879279792807928179282792837928479285792867928779288792897929079291792927929379294792957929679297792987929979300793017930279303793047930579306793077930879309793107931179312793137931479315793167931779318793197932079321793227932379324793257932679327793287932979330793317933279333793347933579336793377933879339793407934179342793437934479345793467934779348793497935079351793527935379354793557935679357793587935979360793617936279363793647936579366793677936879369793707937179372793737937479375793767937779378793797938079381793827938379384793857938679387793887938979390793917939279393793947939579396793977939879399794007940179402794037940479405794067940779408794097941079411794127941379414794157941679417794187941979420794217942279423794247942579426794277942879429794307943179432794337943479435794367943779438794397944079441794427944379444794457944679447794487944979450794517945279453794547945579456794577945879459794607946179462794637946479465794667946779468794697947079471794727947379474794757947679477794787947979480794817948279483794847948579486794877948879489794907949179492794937949479495794967949779498794997950079501795027950379504795057950679507795087950979510795117951279513795147951579516795177951879519795207952179522795237952479525795267952779528795297953079531795327953379534795357953679537795387953979540795417954279543795447954579546795477954879549795507955179552795537955479555795567955779558795597956079561795627956379564795657956679567795687956979570795717957279573795747957579576795777957879579795807958179582795837958479585795867958779588795897959079591795927959379594795957959679597795987959979600796017960279603796047960579606796077960879609796107961179612796137961479615796167961779618796197962079621796227962379624796257962679627796287962979630796317963279633796347963579636796377963879639796407964179642796437964479645796467964779648796497965079651796527965379654796557965679657796587965979660796617966279663796647966579666796677966879669796707967179672796737967479675796767967779678796797968079681796827968379684796857968679687796887968979690796917969279693796947969579696796977969879699797007970179702797037970479705797067970779708797097971079711797127971379714797157971679717797187971979720797217972279723797247972579726797277972879729797307973179732797337973479735797367973779738797397974079741797427974379744797457974679747797487974979750797517975279753797547975579756797577975879759797607976179762797637976479765797667976779768797697977079771797727977379774797757977679777797787977979780797817978279783797847978579786797877978879789797907979179792797937979479795797967979779798797997980079801798027980379804798057980679807798087980979810798117981279813798147981579816798177981879819798207982179822798237982479825798267982779828798297983079831798327983379834798357983679837798387983979840798417984279843798447984579846798477984879849798507985179852798537985479855798567985779858798597986079861798627986379864798657986679867798687986979870798717987279873798747987579876798777987879879798807988179882798837988479885798867988779888798897989079891798927989379894798957989679897798987989979900799017990279903799047990579906799077990879909799107991179912799137991479915799167991779918799197992079921799227992379924799257992679927799287992979930799317993279933799347993579936799377993879939799407994179942799437994479945799467994779948799497995079951799527995379954799557995679957799587995979960799617996279963799647996579966799677996879969799707997179972799737997479975799767997779978799797998079981799827998379984799857998679987799887998979990799917999279993799947999579996799977999879999800008000180002800038000480005800068000780008800098001080011800128001380014800158001680017800188001980020800218002280023800248002580026800278002880029800308003180032800338003480035800368003780038800398004080041800428004380044800458004680047800488004980050800518005280053800548005580056800578005880059800608006180062800638006480065800668006780068800698007080071800728007380074800758007680077800788007980080800818008280083800848008580086800878008880089800908009180092800938009480095800968009780098800998010080101801028010380104801058010680107801088010980110801118011280113801148011580116801178011880119801208012180122801238012480125801268012780128801298013080131801328013380134801358013680137801388013980140801418014280143801448014580146801478014880149801508015180152801538015480155801568015780158801598016080161801628016380164801658016680167801688016980170801718017280173801748017580176801778017880179801808018180182801838018480185801868018780188801898019080191801928019380194801958019680197801988019980200802018020280203802048020580206802078020880209802108021180212802138021480215802168021780218802198022080221802228022380224802258022680227802288022980230802318023280233802348023580236802378023880239802408024180242802438024480245802468024780248802498025080251802528025380254802558025680257802588025980260802618026280263802648026580266802678026880269802708027180272802738027480275802768027780278802798028080281802828028380284802858028680287802888028980290802918029280293802948029580296802978029880299803008030180302803038030480305803068030780308803098031080311803128031380314803158031680317803188031980320803218032280323803248032580326803278032880329803308033180332803338033480335803368033780338803398034080341803428034380344803458034680347803488034980350803518035280353803548035580356803578035880359803608036180362803638036480365803668036780368803698037080371803728037380374803758037680377803788037980380803818038280383803848038580386803878038880389803908039180392803938039480395803968039780398803998040080401804028040380404804058040680407804088040980410804118041280413804148041580416804178041880419804208042180422804238042480425804268042780428804298043080431804328043380434804358043680437804388043980440804418044280443804448044580446804478044880449804508045180452804538045480455804568045780458804598046080461804628046380464804658046680467804688046980470804718047280473804748047580476804778047880479804808048180482804838048480485804868048780488804898049080491804928049380494804958049680497804988049980500805018050280503805048050580506805078050880509805108051180512805138051480515805168051780518805198052080521805228052380524805258052680527805288052980530805318053280533805348053580536805378053880539805408054180542805438054480545805468054780548805498055080551805528055380554805558055680557805588055980560805618056280563805648056580566805678056880569805708057180572805738057480575805768057780578805798058080581805828058380584805858058680587805888058980590805918059280593805948059580596805978059880599806008060180602806038060480605806068060780608806098061080611806128061380614806158061680617806188061980620806218062280623806248062580626806278062880629806308063180632806338063480635806368063780638806398064080641806428064380644806458064680647806488064980650806518065280653806548065580656806578065880659806608066180662806638066480665806668066780668806698067080671806728067380674806758067680677806788067980680806818068280683806848068580686806878068880689806908069180692806938069480695806968069780698806998070080701807028070380704807058070680707807088070980710807118071280713807148071580716807178071880719807208072180722807238072480725807268072780728807298073080731807328073380734807358073680737807388073980740807418074280743807448074580746807478074880749807508075180752807538075480755807568075780758807598076080761807628076380764807658076680767807688076980770807718077280773807748077580776807778077880779807808078180782807838078480785807868078780788807898079080791807928079380794807958079680797807988079980800808018080280803808048080580806808078080880809808108081180812808138081480815808168081780818808198082080821808228082380824808258082680827808288082980830808318083280833808348083580836808378083880839808408084180842808438084480845808468084780848808498085080851808528085380854808558085680857808588085980860808618086280863808648086580866808678086880869808708087180872808738087480875808768087780878808798088080881808828088380884808858088680887808888088980890808918089280893808948089580896808978089880899809008090180902809038090480905809068090780908809098091080911809128091380914809158091680917809188091980920809218092280923809248092580926809278092880929809308093180932809338093480935809368093780938809398094080941809428094380944809458094680947809488094980950809518095280953809548095580956809578095880959809608096180962809638096480965809668096780968809698097080971809728097380974809758097680977809788097980980809818098280983809848098580986809878098880989809908099180992809938099480995809968099780998809998100081001810028100381004810058100681007810088100981010810118101281013810148101581016810178101881019810208102181022810238102481025810268102781028810298103081031810328103381034810358103681037810388103981040810418104281043810448104581046810478104881049810508105181052810538105481055810568105781058810598106081061810628106381064810658106681067810688106981070810718107281073810748107581076810778107881079810808108181082810838108481085810868108781088810898109081091810928109381094810958109681097810988109981100811018110281103811048110581106811078110881109811108111181112811138111481115811168111781118811198112081121811228112381124811258112681127811288112981130811318113281133811348113581136811378113881139811408114181142811438114481145811468114781148811498115081151811528115381154811558115681157811588115981160811618116281163811648116581166811678116881169811708117181172811738117481175811768117781178811798118081181811828118381184811858118681187811888118981190811918119281193811948119581196811978119881199812008120181202812038120481205812068120781208812098121081211812128121381214812158121681217812188121981220812218122281223812248122581226812278122881229812308123181232812338123481235812368123781238812398124081241812428124381244812458124681247812488124981250812518125281253812548125581256812578125881259812608126181262812638126481265812668126781268812698127081271812728127381274812758127681277812788127981280812818128281283812848128581286812878128881289812908129181292812938129481295812968129781298812998130081301813028130381304813058130681307813088130981310813118131281313813148131581316813178131881319813208132181322813238132481325813268132781328813298133081331813328133381334813358133681337813388133981340813418134281343813448134581346813478134881349813508135181352813538135481355813568135781358813598136081361813628136381364813658136681367813688136981370813718137281373813748137581376813778137881379813808138181382813838138481385813868138781388813898139081391813928139381394813958139681397813988139981400814018140281403814048140581406814078140881409814108141181412814138141481415814168141781418814198142081421814228142381424814258142681427814288142981430814318143281433814348143581436814378143881439814408144181442814438144481445814468144781448814498145081451814528145381454814558145681457814588145981460814618146281463814648146581466814678146881469814708147181472814738147481475814768147781478814798148081481814828148381484814858148681487814888148981490814918149281493814948149581496814978149881499815008150181502815038150481505815068150781508815098151081511815128151381514815158151681517815188151981520815218152281523815248152581526815278152881529815308153181532815338153481535815368153781538815398154081541815428154381544815458154681547815488154981550815518155281553815548155581556815578155881559815608156181562815638156481565815668156781568815698157081571815728157381574815758157681577815788157981580815818158281583815848158581586815878158881589815908159181592815938159481595815968159781598815998160081601816028160381604816058160681607816088160981610816118161281613816148161581616816178161881619816208162181622816238162481625816268162781628816298163081631816328163381634816358163681637816388163981640816418164281643816448164581646816478164881649816508165181652816538165481655816568165781658816598166081661816628166381664816658166681667816688166981670816718167281673816748167581676816778167881679816808168181682816838168481685816868168781688816898169081691816928169381694816958169681697816988169981700817018170281703817048170581706817078170881709817108171181712817138171481715817168171781718817198172081721817228172381724817258172681727817288172981730817318173281733817348173581736817378173881739817408174181742817438174481745817468174781748817498175081751817528175381754817558175681757817588175981760817618176281763817648176581766817678176881769817708177181772817738177481775817768177781778817798178081781817828178381784817858178681787817888178981790817918179281793817948179581796817978179881799818008180181802818038180481805818068180781808818098181081811818128181381814818158181681817818188181981820818218182281823818248182581826818278182881829818308183181832818338183481835818368183781838818398184081841818428184381844818458184681847818488184981850818518185281853818548185581856818578185881859818608186181862818638186481865818668186781868818698187081871818728187381874818758187681877818788187981880818818188281883818848188581886818878188881889818908189181892818938189481895818968189781898818998190081901819028190381904819058190681907819088190981910819118191281913819148191581916819178191881919819208192181922819238192481925819268192781928819298193081931819328193381934819358193681937819388193981940819418194281943819448194581946819478194881949819508195181952819538195481955819568195781958819598196081961819628196381964819658196681967819688196981970819718197281973819748197581976819778197881979819808198181982819838198481985819868198781988819898199081991819928199381994819958199681997819988199982000820018200282003820048200582006820078200882009820108201182012820138201482015820168201782018820198202082021820228202382024820258202682027820288202982030820318203282033820348203582036820378203882039820408204182042820438204482045820468204782048820498205082051820528205382054820558205682057820588205982060820618206282063820648206582066820678206882069820708207182072820738207482075820768207782078820798208082081820828208382084820858208682087820888208982090820918209282093820948209582096820978209882099821008210182102821038210482105821068210782108821098211082111821128211382114821158211682117821188211982120821218212282123821248212582126821278212882129821308213182132821338213482135821368213782138821398214082141821428214382144821458214682147821488214982150821518215282153821548215582156821578215882159821608216182162821638216482165821668216782168821698217082171821728217382174821758217682177821788217982180821818218282183821848218582186821878218882189821908219182192821938219482195821968219782198821998220082201822028220382204822058220682207822088220982210822118221282213822148221582216822178221882219822208222182222822238222482225822268222782228822298223082231822328223382234822358223682237822388223982240822418224282243822448224582246822478224882249822508225182252822538225482255822568225782258822598226082261822628226382264822658226682267822688226982270822718227282273822748227582276822778227882279822808228182282822838228482285822868228782288822898229082291822928229382294822958229682297822988229982300823018230282303823048230582306823078230882309823108231182312823138231482315823168231782318823198232082321823228232382324823258232682327823288232982330823318233282333823348233582336823378233882339823408234182342823438234482345823468234782348823498235082351823528235382354823558235682357823588235982360823618236282363823648236582366823678236882369823708237182372823738237482375823768237782378823798238082381823828238382384823858238682387823888238982390823918239282393823948239582396823978239882399824008240182402824038240482405824068240782408824098241082411824128241382414824158241682417824188241982420824218242282423824248242582426824278242882429824308243182432824338243482435824368243782438824398244082441824428244382444824458244682447824488244982450824518245282453824548245582456824578245882459824608246182462824638246482465824668246782468824698247082471824728247382474824758247682477824788247982480824818248282483824848248582486824878248882489824908249182492824938249482495824968249782498824998250082501825028250382504825058250682507825088250982510825118251282513825148251582516825178251882519825208252182522825238252482525825268252782528825298253082531825328253382534825358253682537825388253982540825418254282543825448254582546825478254882549825508255182552825538255482555825568255782558825598256082561825628256382564825658256682567825688256982570825718257282573825748257582576825778257882579825808258182582825838258482585825868258782588825898259082591825928259382594825958259682597825988259982600826018260282603826048260582606826078260882609826108261182612826138261482615826168261782618826198262082621826228262382624826258262682627826288262982630826318263282633826348263582636826378263882639826408264182642826438264482645826468264782648826498265082651826528265382654826558265682657826588265982660826618266282663826648266582666826678266882669826708267182672826738267482675826768267782678826798268082681826828268382684826858268682687826888268982690826918269282693826948269582696826978269882699827008270182702827038270482705827068270782708827098271082711827128271382714827158271682717827188271982720827218272282723827248272582726827278272882729827308273182732827338273482735827368273782738827398274082741827428274382744827458274682747827488274982750827518275282753827548275582756827578275882759827608276182762827638276482765827668276782768827698277082771827728277382774827758277682777827788277982780827818278282783827848278582786827878278882789827908279182792827938279482795827968279782798827998280082801828028280382804828058280682807828088280982810828118281282813828148281582816828178281882819828208282182822828238282482825828268282782828828298283082831828328283382834828358283682837828388283982840828418284282843828448284582846828478284882849828508285182852828538285482855828568285782858828598286082861828628286382864828658286682867828688286982870828718287282873828748287582876828778287882879828808288182882828838288482885828868288782888828898289082891828928289382894828958289682897828988289982900829018290282903829048290582906829078290882909829108291182912829138291482915829168291782918829198292082921829228292382924829258292682927829288292982930829318293282933829348293582936829378293882939829408294182942829438294482945829468294782948829498295082951829528295382954829558295682957829588295982960829618296282963829648296582966829678296882969829708297182972829738297482975829768297782978829798298082981829828298382984829858298682987829888298982990829918299282993829948299582996829978299882999830008300183002830038300483005830068300783008830098301083011830128301383014830158301683017830188301983020830218302283023830248302583026830278302883029830308303183032830338303483035830368303783038830398304083041830428304383044830458304683047830488304983050830518305283053830548305583056830578305883059830608306183062830638306483065830668306783068830698307083071830728307383074830758307683077830788307983080830818308283083830848308583086830878308883089830908309183092830938309483095830968309783098830998310083101831028310383104831058310683107831088310983110831118311283113831148311583116831178311883119831208312183122831238312483125831268312783128831298313083131831328313383134831358313683137831388313983140831418314283143831448314583146831478314883149831508315183152831538315483155831568315783158831598316083161831628316383164831658316683167831688316983170831718317283173831748317583176831778317883179831808318183182831838318483185831868318783188831898319083191831928319383194831958319683197831988319983200832018320283203832048320583206832078320883209832108321183212832138321483215832168321783218832198322083221832228322383224832258322683227832288322983230832318323283233832348323583236832378323883239832408324183242832438324483245832468324783248832498325083251832528325383254832558325683257832588325983260832618326283263832648326583266832678326883269832708327183272832738327483275832768327783278832798328083281832828328383284832858328683287832888328983290832918329283293832948329583296832978329883299833008330183302833038330483305833068330783308833098331083311833128331383314833158331683317833188331983320833218332283323833248332583326833278332883329833308333183332833338333483335833368333783338833398334083341833428334383344833458334683347833488334983350833518335283353833548335583356833578335883359833608336183362833638336483365833668336783368833698337083371833728337383374833758337683377833788337983380833818338283383833848338583386833878338883389833908339183392833938339483395833968339783398833998340083401834028340383404834058340683407834088340983410834118341283413834148341583416834178341883419834208342183422834238342483425834268342783428834298343083431834328343383434834358343683437834388343983440834418344283443834448344583446834478344883449834508345183452834538345483455834568345783458834598346083461834628346383464834658346683467834688346983470834718347283473834748347583476834778347883479834808348183482834838348483485834868348783488834898349083491834928349383494834958349683497834988349983500835018350283503835048350583506835078350883509835108351183512835138351483515835168351783518835198352083521835228352383524835258352683527835288352983530835318353283533835348353583536835378353883539835408354183542835438354483545835468354783548835498355083551835528355383554835558355683557835588355983560835618356283563835648356583566835678356883569835708357183572835738357483575835768357783578835798358083581835828358383584835858358683587835888358983590835918359283593835948359583596835978359883599836008360183602836038360483605836068360783608836098361083611836128361383614836158361683617836188361983620836218362283623836248362583626836278362883629836308363183632836338363483635836368363783638836398364083641836428364383644836458364683647836488364983650836518365283653836548365583656836578365883659836608366183662836638366483665836668366783668836698367083671836728367383674836758367683677836788367983680836818368283683836848368583686836878368883689836908369183692836938369483695836968369783698836998370083701837028370383704837058370683707837088370983710837118371283713837148371583716837178371883719837208372183722837238372483725837268372783728837298373083731837328373383734837358373683737837388373983740837418374283743837448374583746837478374883749837508375183752837538375483755837568375783758837598376083761837628376383764837658376683767837688376983770837718377283773837748377583776837778377883779837808378183782837838378483785837868378783788837898379083791837928379383794837958379683797837988379983800838018380283803838048380583806838078380883809838108381183812838138381483815838168381783818838198382083821838228382383824838258382683827838288382983830838318383283833838348383583836838378383883839838408384183842838438384483845838468384783848838498385083851838528385383854838558385683857838588385983860838618386283863838648386583866838678386883869838708387183872838738387483875838768387783878838798388083881838828388383884838858388683887838888388983890838918389283893838948389583896838978389883899839008390183902839038390483905839068390783908839098391083911839128391383914839158391683917839188391983920839218392283923839248392583926839278392883929839308393183932839338393483935839368393783938839398394083941839428394383944839458394683947839488394983950839518395283953839548395583956839578395883959839608396183962839638396483965839668396783968839698397083971839728397383974839758397683977839788397983980839818398283983839848398583986839878398883989839908399183992839938399483995839968399783998839998400084001840028400384004840058400684007840088400984010840118401284013840148401584016840178401884019840208402184022840238402484025840268402784028840298403084031840328403384034840358403684037840388403984040840418404284043840448404584046840478404884049840508405184052840538405484055840568405784058840598406084061840628406384064840658406684067840688406984070840718407284073840748407584076840778407884079840808408184082840838408484085840868408784088840898409084091840928409384094840958409684097840988409984100841018410284103841048410584106841078410884109841108411184112841138411484115841168411784118841198412084121841228412384124841258412684127841288412984130841318413284133841348413584136841378413884139841408414184142841438414484145841468414784148841498415084151841528415384154841558415684157841588415984160841618416284163841648416584166841678416884169841708417184172841738417484175841768417784178841798418084181841828418384184841858418684187841888418984190841918419284193841948419584196841978419884199842008420184202842038420484205842068420784208842098421084211842128421384214842158421684217842188421984220842218422284223842248422584226842278422884229842308423184232842338423484235842368423784238842398424084241842428424384244842458424684247842488424984250842518425284253842548425584256842578425884259842608426184262842638426484265842668426784268842698427084271842728427384274842758427684277842788427984280842818428284283842848428584286842878428884289842908429184292842938429484295842968429784298842998430084301843028430384304843058430684307843088430984310843118431284313843148431584316843178431884319843208432184322843238432484325843268432784328843298433084331843328433384334843358433684337843388433984340843418434284343843448434584346843478434884349843508435184352843538435484355843568435784358843598436084361843628436384364843658436684367843688436984370843718437284373843748437584376843778437884379843808438184382843838438484385843868438784388843898439084391843928439384394843958439684397843988439984400844018440284403844048440584406844078440884409844108441184412844138441484415844168441784418844198442084421844228442384424844258442684427844288442984430844318443284433844348443584436844378443884439844408444184442844438444484445844468444784448844498445084451844528445384454844558445684457844588445984460844618446284463844648446584466844678446884469844708447184472844738447484475844768447784478844798448084481844828448384484844858448684487844888448984490844918449284493844948449584496844978449884499845008450184502845038450484505845068450784508845098451084511845128451384514845158451684517845188451984520845218452284523845248452584526845278452884529845308453184532845338453484535845368453784538845398454084541845428454384544845458454684547845488454984550845518455284553845548455584556845578455884559845608456184562845638456484565845668456784568845698457084571845728457384574845758457684577845788457984580845818458284583845848458584586845878458884589845908459184592845938459484595845968459784598845998460084601846028460384604846058460684607846088460984610846118461284613846148461584616846178461884619846208462184622846238462484625846268462784628846298463084631846328463384634846358463684637846388463984640846418464284643846448464584646846478464884649846508465184652846538465484655846568465784658846598466084661846628466384664846658466684667846688466984670846718467284673846748467584676846778467884679846808468184682846838468484685846868468784688846898469084691846928469384694846958469684697846988469984700847018470284703847048470584706847078470884709847108471184712847138471484715847168471784718847198472084721847228472384724847258472684727847288472984730847318473284733847348473584736847378473884739847408474184742847438474484745847468474784748847498475084751847528475384754847558475684757847588475984760847618476284763847648476584766847678476884769847708477184772847738477484775847768477784778847798478084781847828478384784847858478684787847888478984790847918479284793847948479584796847978479884799848008480184802848038480484805848068480784808848098481084811848128481384814848158481684817848188481984820848218482284823848248482584826848278482884829848308483184832848338483484835848368483784838848398484084841848428484384844848458484684847848488484984850848518485284853848548485584856848578485884859848608486184862848638486484865848668486784868848698487084871848728487384874848758487684877848788487984880848818488284883848848488584886848878488884889848908489184892848938489484895848968489784898848998490084901849028490384904849058490684907849088490984910849118491284913849148491584916849178491884919849208492184922849238492484925849268492784928849298493084931849328493384934849358493684937849388493984940849418494284943849448494584946849478494884949849508495184952849538495484955849568495784958849598496084961849628496384964849658496684967849688496984970849718497284973849748497584976849778497884979849808498184982849838498484985849868498784988849898499084991849928499384994849958499684997849988499985000850018500285003850048500585006850078500885009850108501185012850138501485015850168501785018850198502085021850228502385024850258502685027850288502985030850318503285033850348503585036850378503885039850408504185042850438504485045850468504785048850498505085051850528505385054850558505685057850588505985060850618506285063850648506585066850678506885069850708507185072850738507485075850768507785078850798508085081850828508385084850858508685087850888508985090850918509285093850948509585096850978509885099851008510185102851038510485105851068510785108851098511085111851128511385114851158511685117851188511985120851218512285123851248512585126851278512885129851308513185132851338513485135851368513785138851398514085141851428514385144851458514685147851488514985150851518515285153851548515585156851578515885159851608516185162851638516485165851668516785168851698517085171851728517385174851758517685177851788517985180851818518285183851848518585186851878518885189851908519185192851938519485195851968519785198851998520085201852028520385204852058520685207852088520985210852118521285213852148521585216852178521885219852208522185222852238522485225852268522785228852298523085231852328523385234852358523685237852388523985240852418524285243852448524585246852478524885249852508525185252852538525485255852568525785258852598526085261852628526385264852658526685267852688526985270852718527285273852748527585276852778527885279852808528185282852838528485285852868528785288852898529085291852928529385294852958529685297852988529985300853018530285303853048530585306853078530885309853108531185312853138531485315853168531785318853198532085321853228532385324853258532685327853288532985330853318533285333853348533585336853378533885339853408534185342853438534485345853468534785348853498535085351853528535385354853558535685357853588535985360853618536285363853648536585366853678536885369853708537185372853738537485375853768537785378853798538085381853828538385384853858538685387853888538985390853918539285393853948539585396853978539885399854008540185402854038540485405854068540785408854098541085411854128541385414854158541685417854188541985420854218542285423854248542585426854278542885429854308543185432854338543485435854368543785438854398544085441854428544385444854458544685447854488544985450854518545285453854548545585456854578545885459854608546185462854638546485465854668546785468854698547085471854728547385474854758547685477854788547985480854818548285483854848548585486854878548885489854908549185492854938549485495854968549785498854998550085501855028550385504855058550685507855088550985510855118551285513855148551585516855178551885519855208552185522855238552485525855268552785528855298553085531855328553385534855358553685537855388553985540855418554285543855448554585546855478554885549855508555185552855538555485555855568555785558855598556085561855628556385564855658556685567855688556985570855718557285573855748557585576855778557885579855808558185582855838558485585855868558785588855898559085591855928559385594855958559685597855988559985600856018560285603856048560585606856078560885609856108561185612856138561485615856168561785618856198562085621856228562385624856258562685627856288562985630856318563285633856348563585636856378563885639856408564185642856438564485645856468564785648856498565085651856528565385654856558565685657856588565985660856618566285663856648566585666856678566885669856708567185672856738567485675856768567785678856798568085681856828568385684856858568685687856888568985690856918569285693856948569585696856978569885699857008570185702857038570485705857068570785708857098571085711857128571385714857158571685717857188571985720857218572285723857248572585726857278572885729857308573185732857338573485735857368573785738857398574085741857428574385744857458574685747857488574985750857518575285753857548575585756857578575885759857608576185762857638576485765857668576785768857698577085771857728577385774857758577685777857788577985780857818578285783857848578585786857878578885789857908579185792857938579485795857968579785798857998580085801858028580385804858058580685807858088580985810858118581285813858148581585816858178581885819858208582185822858238582485825858268582785828858298583085831858328583385834858358583685837858388583985840858418584285843858448584585846858478584885849858508585185852858538585485855858568585785858858598586085861858628586385864858658586685867858688586985870858718587285873858748587585876858778587885879858808588185882858838588485885858868588785888858898589085891858928589385894858958589685897858988589985900859018590285903859048590585906859078590885909859108591185912859138591485915859168591785918859198592085921859228592385924859258592685927859288592985930859318593285933859348593585936859378593885939859408594185942859438594485945859468594785948859498595085951859528595385954859558595685957859588595985960859618596285963859648596585966859678596885969859708597185972859738597485975859768597785978859798598085981859828598385984859858598685987859888598985990859918599285993859948599585996859978599885999860008600186002860038600486005860068600786008860098601086011860128601386014860158601686017860188601986020860218602286023860248602586026860278602886029860308603186032860338603486035860368603786038860398604086041860428604386044860458604686047860488604986050860518605286053860548605586056860578605886059860608606186062860638606486065860668606786068860698607086071860728607386074860758607686077860788607986080860818608286083860848608586086860878608886089860908609186092860938609486095860968609786098860998610086101861028610386104861058610686107861088610986110861118611286113861148611586116861178611886119861208612186122861238612486125861268612786128861298613086131861328613386134861358613686137861388613986140861418614286143861448614586146861478614886149861508615186152861538615486155861568615786158861598616086161861628616386164861658616686167861688616986170861718617286173861748617586176861778617886179861808618186182861838618486185861868618786188861898619086191861928619386194861958619686197861988619986200862018620286203862048620586206862078620886209862108621186212862138621486215862168621786218862198622086221862228622386224862258622686227862288622986230862318623286233862348623586236862378623886239862408624186242862438624486245862468624786248862498625086251862528625386254862558625686257862588625986260862618626286263862648626586266862678626886269862708627186272862738627486275862768627786278862798628086281862828628386284862858628686287862888628986290862918629286293862948629586296862978629886299863008630186302863038630486305863068630786308863098631086311863128631386314863158631686317863188631986320863218632286323863248632586326863278632886329863308633186332863338633486335863368633786338863398634086341863428634386344863458634686347863488634986350863518635286353863548635586356863578635886359863608636186362863638636486365863668636786368863698637086371863728637386374863758637686377863788637986380863818638286383863848638586386863878638886389863908639186392863938639486395863968639786398863998640086401864028640386404864058640686407864088640986410864118641286413864148641586416864178641886419864208642186422864238642486425864268642786428864298643086431864328643386434864358643686437864388643986440864418644286443864448644586446864478644886449864508645186452864538645486455864568645786458864598646086461864628646386464864658646686467864688646986470864718647286473864748647586476864778647886479864808648186482864838648486485864868648786488864898649086491864928649386494864958649686497864988649986500865018650286503865048650586506865078650886509865108651186512865138651486515865168651786518865198652086521865228652386524865258652686527865288652986530865318653286533865348653586536865378653886539865408654186542865438654486545865468654786548865498655086551865528655386554865558655686557865588655986560865618656286563865648656586566865678656886569865708657186572865738657486575865768657786578865798658086581865828658386584865858658686587865888658986590865918659286593865948659586596865978659886599866008660186602866038660486605866068660786608866098661086611866128661386614866158661686617866188661986620866218662286623866248662586626866278662886629866308663186632866338663486635866368663786638866398664086641866428664386644866458664686647866488664986650866518665286653866548665586656866578665886659866608666186662866638666486665866668666786668866698667086671866728667386674866758667686677866788667986680866818668286683866848668586686866878668886689866908669186692866938669486695866968669786698866998670086701867028670386704867058670686707867088670986710867118671286713867148671586716867178671886719867208672186722867238672486725867268672786728867298673086731867328673386734867358673686737867388673986740867418674286743867448674586746867478674886749867508675186752867538675486755867568675786758867598676086761867628676386764867658676686767867688676986770867718677286773867748677586776867778677886779867808678186782867838678486785867868678786788867898679086791867928679386794867958679686797867988679986800868018680286803868048680586806868078680886809868108681186812868138681486815868168681786818868198682086821868228682386824868258682686827868288682986830868318683286833868348683586836868378683886839868408684186842868438684486845868468684786848868498685086851868528685386854868558685686857868588685986860868618686286863868648686586866868678686886869868708687186872868738687486875868768687786878868798688086881868828688386884868858688686887868888688986890868918689286893868948689586896868978689886899869008690186902869038690486905869068690786908869098691086911869128691386914869158691686917869188691986920869218692286923869248692586926869278692886929869308693186932869338693486935869368693786938869398694086941869428694386944869458694686947869488694986950869518695286953869548695586956869578695886959869608696186962869638696486965869668696786968869698697086971869728697386974869758697686977869788697986980869818698286983869848698586986869878698886989869908699186992869938699486995869968699786998869998700087001870028700387004870058700687007870088700987010870118701287013870148701587016870178701887019870208702187022870238702487025870268702787028870298703087031870328703387034870358703687037870388703987040870418704287043870448704587046870478704887049870508705187052870538705487055870568705787058870598706087061870628706387064870658706687067870688706987070870718707287073870748707587076870778707887079870808708187082870838708487085870868708787088870898709087091870928709387094870958709687097870988709987100871018710287103871048710587106871078710887109871108711187112871138711487115871168711787118871198712087121871228712387124871258712687127871288712987130871318713287133871348713587136871378713887139871408714187142871438714487145871468714787148871498715087151871528715387154871558715687157871588715987160871618716287163871648716587166871678716887169871708717187172871738717487175871768717787178871798718087181871828718387184871858718687187871888718987190871918719287193871948719587196871978719887199872008720187202872038720487205872068720787208872098721087211872128721387214872158721687217872188721987220872218722287223872248722587226872278722887229872308723187232872338723487235872368723787238872398724087241872428724387244872458724687247872488724987250872518725287253872548725587256872578725887259872608726187262872638726487265872668726787268872698727087271872728727387274872758727687277872788727987280872818728287283872848728587286872878728887289872908729187292872938729487295872968729787298872998730087301873028730387304873058730687307873088730987310873118731287313873148731587316873178731887319873208732187322873238732487325873268732787328873298733087331873328733387334873358733687337873388733987340873418734287343873448734587346873478734887349873508735187352873538735487355873568735787358873598736087361873628736387364873658736687367873688736987370873718737287373873748737587376873778737887379873808738187382873838738487385873868738787388873898739087391873928739387394873958739687397873988739987400874018740287403874048740587406874078740887409874108741187412874138741487415874168741787418874198742087421874228742387424874258742687427874288742987430874318743287433874348743587436874378743887439874408744187442874438744487445874468744787448874498745087451874528745387454874558745687457874588745987460874618746287463874648746587466874678746887469874708747187472874738747487475874768747787478874798748087481874828748387484874858748687487874888748987490874918749287493874948749587496874978749887499875008750187502875038750487505875068750787508875098751087511875128751387514875158751687517875188751987520875218752287523875248752587526875278752887529875308753187532875338753487535875368753787538875398754087541875428754387544875458754687547875488754987550875518755287553875548755587556875578755887559875608756187562875638756487565875668756787568875698757087571875728757387574875758757687577875788757987580875818758287583875848758587586875878758887589875908759187592875938759487595875968759787598875998760087601876028760387604876058760687607876088760987610876118761287613876148761587616876178761887619876208762187622876238762487625876268762787628876298763087631876328763387634876358763687637876388763987640876418764287643876448764587646876478764887649876508765187652876538765487655876568765787658876598766087661876628766387664876658766687667876688766987670876718767287673876748767587676876778767887679876808768187682876838768487685876868768787688876898769087691876928769387694876958769687697876988769987700877018770287703877048770587706877078770887709877108771187712877138771487715877168771787718877198772087721877228772387724877258772687727877288772987730877318773287733877348773587736877378773887739877408774187742877438774487745877468774787748877498775087751877528775387754877558775687757877588775987760877618776287763877648776587766877678776887769877708777187772877738777487775877768777787778877798778087781877828778387784877858778687787877888778987790877918779287793877948779587796877978779887799878008780187802878038780487805878068780787808878098781087811878128781387814878158781687817878188781987820878218782287823878248782587826878278782887829878308783187832878338783487835878368783787838878398784087841878428784387844878458784687847878488784987850878518785287853878548785587856878578785887859878608786187862878638786487865878668786787868878698787087871878728787387874878758787687877878788787987880878818788287883878848788587886878878788887889878908789187892878938789487895878968789787898878998790087901879028790387904879058790687907879088790987910879118791287913879148791587916879178791887919879208792187922879238792487925879268792787928879298793087931879328793387934879358793687937879388793987940879418794287943879448794587946879478794887949879508795187952879538795487955879568795787958879598796087961879628796387964879658796687967879688796987970879718797287973879748797587976879778797887979879808798187982879838798487985879868798787988879898799087991879928799387994879958799687997879988799988000880018800288003880048800588006880078800888009880108801188012880138801488015880168801788018880198802088021880228802388024880258802688027880288802988030880318803288033880348803588036880378803888039880408804188042880438804488045880468804788048880498805088051880528805388054880558805688057880588805988060880618806288063880648806588066880678806888069880708807188072880738807488075880768807788078880798808088081880828808388084880858808688087880888808988090880918809288093880948809588096880978809888099881008810188102881038810488105881068810788108881098811088111881128811388114881158811688117881188811988120881218812288123881248812588126881278812888129881308813188132881338813488135881368813788138881398814088141881428814388144881458814688147881488814988150881518815288153881548815588156881578815888159881608816188162881638816488165881668816788168881698817088171881728817388174881758817688177881788817988180881818818288183881848818588186881878818888189881908819188192881938819488195881968819788198881998820088201882028820388204882058820688207882088820988210882118821288213882148821588216882178821888219882208822188222882238822488225882268822788228882298823088231882328823388234882358823688237882388823988240882418824288243882448824588246882478824888249882508825188252882538825488255882568825788258882598826088261882628826388264882658826688267882688826988270882718827288273882748827588276882778827888279882808828188282882838828488285882868828788288882898829088291882928829388294882958829688297882988829988300883018830288303883048830588306883078830888309883108831188312883138831488315883168831788318883198832088321883228832388324883258832688327883288832988330883318833288333883348833588336883378833888339883408834188342883438834488345883468834788348883498835088351883528835388354883558835688357883588835988360883618836288363883648836588366883678836888369883708837188372883738837488375883768837788378883798838088381883828838388384883858838688387883888838988390883918839288393883948839588396883978839888399884008840188402884038840488405884068840788408884098841088411884128841388414884158841688417884188841988420884218842288423884248842588426884278842888429884308843188432884338843488435884368843788438884398844088441884428844388444884458844688447884488844988450884518845288453884548845588456884578845888459884608846188462884638846488465884668846788468884698847088471884728847388474884758847688477884788847988480884818848288483884848848588486884878848888489884908849188492884938849488495884968849788498884998850088501885028850388504885058850688507885088850988510885118851288513885148851588516885178851888519885208852188522885238852488525885268852788528885298853088531885328853388534885358853688537885388853988540885418854288543885448854588546885478854888549885508855188552885538855488555885568855788558885598856088561885628856388564885658856688567885688856988570885718857288573885748857588576885778857888579885808858188582885838858488585885868858788588885898859088591885928859388594885958859688597885988859988600886018860288603886048860588606886078860888609886108861188612886138861488615886168861788618886198862088621886228862388624886258862688627886288862988630886318863288633886348863588636886378863888639886408864188642886438864488645886468864788648886498865088651886528865388654886558865688657886588865988660886618866288663886648866588666886678866888669886708867188672886738867488675886768867788678886798868088681886828868388684886858868688687886888868988690886918869288693886948869588696886978869888699887008870188702887038870488705887068870788708887098871088711887128871388714887158871688717887188871988720887218872288723887248872588726887278872888729887308873188732887338873488735887368873788738887398874088741887428874388744887458874688747887488874988750887518875288753887548875588756887578875888759887608876188762887638876488765887668876788768887698877088771887728877388774887758877688777887788877988780887818878288783887848878588786887878878888789887908879188792887938879488795887968879788798887998880088801888028880388804888058880688807888088880988810888118881288813888148881588816888178881888819888208882188822888238882488825888268882788828888298883088831888328883388834888358883688837888388883988840888418884288843888448884588846888478884888849888508885188852888538885488855888568885788858888598886088861888628886388864888658886688867888688886988870888718887288873888748887588876888778887888879888808888188882888838888488885888868888788888888898889088891888928889388894888958889688897888988889988900889018890288903889048890588906889078890888909889108891188912889138891488915889168891788918889198892088921889228892388924889258892688927889288892988930889318893288933889348893588936889378893888939889408894188942889438894488945889468894788948889498895088951889528895388954889558895688957889588895988960889618896288963889648896588966889678896888969889708897188972889738897488975889768897788978889798898088981889828898388984889858898688987889888898988990889918899288993889948899588996889978899888999890008900189002890038900489005890068900789008890098901089011890128901389014890158901689017890188901989020890218902289023890248902589026890278902889029890308903189032890338903489035890368903789038890398904089041890428904389044890458904689047890488904989050890518905289053890548905589056890578905889059890608906189062890638906489065890668906789068890698907089071890728907389074890758907689077890788907989080890818908289083890848908589086890878908889089890908909189092890938909489095890968909789098890998910089101891028910389104891058910689107891088910989110891118911289113891148911589116891178911889119891208912189122891238912489125891268912789128891298913089131891328913389134891358913689137891388913989140891418914289143891448914589146891478914889149891508915189152891538915489155891568915789158891598916089161891628916389164891658916689167891688916989170891718917289173891748917589176891778917889179891808918189182891838918489185891868918789188891898919089191891928919389194891958919689197891988919989200892018920289203892048920589206892078920889209892108921189212892138921489215892168921789218892198922089221892228922389224892258922689227892288922989230892318923289233892348923589236892378923889239892408924189242892438924489245892468924789248892498925089251892528925389254892558925689257892588925989260892618926289263892648926589266892678926889269892708927189272892738927489275892768927789278892798928089281892828928389284892858928689287892888928989290892918929289293892948929589296892978929889299893008930189302893038930489305893068930789308893098931089311893128931389314893158931689317893188931989320893218932289323893248932589326893278932889329893308933189332893338933489335893368933789338893398934089341893428934389344893458934689347893488934989350893518935289353893548935589356893578935889359893608936189362893638936489365893668936789368893698937089371893728937389374893758937689377893788937989380893818938289383893848938589386893878938889389893908939189392893938939489395893968939789398893998940089401894028940389404894058940689407894088940989410894118941289413894148941589416894178941889419894208942189422894238942489425894268942789428894298943089431894328943389434894358943689437894388943989440894418944289443894448944589446894478944889449894508945189452894538945489455894568945789458894598946089461894628946389464894658946689467894688946989470894718947289473894748947589476894778947889479894808948189482894838948489485894868948789488894898949089491894928949389494894958949689497894988949989500895018950289503895048950589506895078950889509895108951189512895138951489515895168951789518895198952089521895228952389524895258952689527895288952989530895318953289533895348953589536895378953889539895408954189542895438954489545895468954789548895498955089551895528955389554895558955689557895588955989560895618956289563895648956589566895678956889569895708957189572895738957489575895768957789578895798958089581895828958389584895858958689587895888958989590895918959289593895948959589596895978959889599896008960189602896038960489605896068960789608896098961089611896128961389614896158961689617896188961989620896218962289623896248962589626896278962889629896308963189632896338963489635896368963789638896398964089641896428964389644896458964689647896488964989650896518965289653896548965589656896578965889659896608966189662896638966489665896668966789668896698967089671896728967389674896758967689677896788967989680896818968289683896848968589686896878968889689896908969189692896938969489695896968969789698896998970089701897028970389704897058970689707897088970989710897118971289713897148971589716897178971889719897208972189722897238972489725897268972789728897298973089731897328973389734897358973689737897388973989740897418974289743897448974589746897478974889749897508975189752897538975489755897568975789758897598976089761897628976389764897658976689767897688976989770897718977289773897748977589776897778977889779897808978189782897838978489785897868978789788897898979089791897928979389794897958979689797897988979989800898018980289803898048980589806898078980889809898108981189812898138981489815898168981789818898198982089821898228982389824898258982689827898288982989830898318983289833898348983589836898378983889839898408984189842898438984489845898468984789848898498985089851898528985389854898558985689857898588985989860898618986289863898648986589866898678986889869898708987189872898738987489875898768987789878898798988089881898828988389884898858988689887898888988989890898918989289893898948989589896898978989889899899008990189902899038990489905899068990789908899098991089911899128991389914899158991689917899188991989920899218992289923899248992589926899278992889929899308993189932899338993489935899368993789938899398994089941899428994389944899458994689947899488994989950899518995289953899548995589956899578995889959899608996189962899638996489965899668996789968899698997089971899728997389974899758997689977899788997989980899818998289983899848998589986899878998889989899908999189992899938999489995899968999789998899999000090001900029000390004900059000690007900089000990010900119001290013900149001590016900179001890019900209002190022900239002490025900269002790028900299003090031900329003390034900359003690037900389003990040900419004290043900449004590046900479004890049900509005190052900539005490055900569005790058900599006090061900629006390064900659006690067900689006990070900719007290073900749007590076900779007890079900809008190082900839008490085900869008790088900899009090091900929009390094900959009690097900989009990100901019010290103901049010590106901079010890109901109011190112901139011490115901169011790118901199012090121901229012390124901259012690127901289012990130901319013290133901349013590136901379013890139901409014190142901439014490145901469014790148901499015090151901529015390154901559015690157901589015990160901619016290163901649016590166901679016890169901709017190172901739017490175901769017790178901799018090181901829018390184901859018690187901889018990190901919019290193901949019590196901979019890199902009020190202902039020490205902069020790208902099021090211902129021390214902159021690217902189021990220902219022290223902249022590226902279022890229902309023190232902339023490235902369023790238902399024090241902429024390244902459024690247902489024990250902519025290253902549025590256902579025890259902609026190262902639026490265902669026790268902699027090271902729027390274902759027690277902789027990280902819028290283902849028590286902879028890289902909029190292902939029490295902969029790298902999030090301903029030390304903059030690307903089030990310903119031290313903149031590316903179031890319903209032190322903239032490325903269032790328903299033090331903329033390334903359033690337903389033990340903419034290343903449034590346903479034890349903509035190352903539035490355903569035790358903599036090361903629036390364903659036690367903689036990370903719037290373903749037590376903779037890379903809038190382903839038490385903869038790388903899039090391903929039390394903959039690397903989039990400904019040290403904049040590406904079040890409904109041190412904139041490415904169041790418904199042090421904229042390424904259042690427904289042990430904319043290433904349043590436904379043890439904409044190442904439044490445904469044790448904499045090451904529045390454904559045690457904589045990460904619046290463904649046590466904679046890469904709047190472904739047490475904769047790478904799048090481904829048390484904859048690487904889048990490904919049290493904949049590496904979049890499905009050190502905039050490505905069050790508905099051090511905129051390514905159051690517905189051990520905219052290523905249052590526905279052890529905309053190532905339053490535905369053790538905399054090541905429054390544905459054690547905489054990550905519055290553905549055590556905579055890559905609056190562905639056490565905669056790568905699057090571905729057390574905759057690577905789057990580905819058290583905849058590586905879058890589905909059190592905939059490595905969059790598905999060090601906029060390604906059060690607906089060990610906119061290613906149061590616906179061890619906209062190622906239062490625906269062790628906299063090631906329063390634906359063690637906389063990640906419064290643906449064590646906479064890649906509065190652906539065490655906569065790658906599066090661906629066390664906659066690667906689066990670906719067290673906749067590676906779067890679906809068190682906839068490685906869068790688906899069090691906929069390694906959069690697906989069990700907019070290703907049070590706907079070890709907109071190712907139071490715907169071790718907199072090721907229072390724907259072690727907289072990730907319073290733907349073590736907379073890739907409074190742907439074490745907469074790748907499075090751907529075390754907559075690757907589075990760907619076290763907649076590766907679076890769907709077190772907739077490775907769077790778907799078090781907829078390784907859078690787907889078990790907919079290793907949079590796907979079890799908009080190802908039080490805908069080790808908099081090811908129081390814908159081690817908189081990820908219082290823908249082590826908279082890829908309083190832908339083490835908369083790838908399084090841908429084390844908459084690847908489084990850908519085290853908549085590856908579085890859908609086190862908639086490865908669086790868908699087090871908729087390874908759087690877908789087990880908819088290883908849088590886908879088890889908909089190892908939089490895908969089790898908999090090901909029090390904909059090690907909089090990910909119091290913909149091590916909179091890919909209092190922909239092490925909269092790928909299093090931909329093390934909359093690937909389093990940909419094290943909449094590946909479094890949909509095190952909539095490955909569095790958909599096090961909629096390964909659096690967909689096990970909719097290973909749097590976909779097890979909809098190982909839098490985909869098790988909899099090991909929099390994909959099690997909989099991000910019100291003910049100591006910079100891009910109101191012910139101491015910169101791018910199102091021910229102391024910259102691027910289102991030910319103291033910349103591036910379103891039910409104191042910439104491045910469104791048910499105091051910529105391054910559105691057910589105991060910619106291063910649106591066910679106891069910709107191072910739107491075910769107791078910799108091081910829108391084910859108691087910889108991090910919109291093910949109591096910979109891099911009110191102911039110491105911069110791108911099111091111911129111391114911159111691117911189111991120911219112291123911249112591126911279112891129911309113191132911339113491135911369113791138911399114091141911429114391144911459114691147911489114991150911519115291153911549115591156911579115891159911609116191162911639116491165911669116791168911699117091171911729117391174911759117691177911789117991180911819118291183911849118591186911879118891189911909119191192911939119491195911969119791198911999120091201912029120391204912059120691207912089120991210912119121291213912149121591216912179121891219912209122191222912239122491225912269122791228912299123091231912329123391234912359123691237912389123991240912419124291243912449124591246912479124891249912509125191252912539125491255912569125791258912599126091261912629126391264912659126691267912689126991270912719127291273912749127591276912779127891279912809128191282912839128491285912869128791288912899129091291912929129391294912959129691297912989129991300913019130291303913049130591306913079130891309913109131191312913139131491315913169131791318913199132091321913229132391324913259132691327913289132991330913319133291333913349133591336913379133891339913409134191342913439134491345913469134791348913499135091351913529135391354913559135691357913589135991360913619136291363913649136591366913679136891369913709137191372913739137491375913769137791378913799138091381913829138391384913859138691387913889138991390913919139291393913949139591396913979139891399914009140191402914039140491405914069140791408914099141091411914129141391414914159141691417914189141991420914219142291423914249142591426914279142891429914309143191432914339143491435914369143791438914399144091441914429144391444914459144691447914489144991450914519145291453914549145591456914579145891459914609146191462914639146491465914669146791468914699147091471914729147391474914759147691477914789147991480914819148291483914849148591486914879148891489914909149191492914939149491495914969149791498914999150091501915029150391504915059150691507915089150991510915119151291513915149151591516915179151891519915209152191522915239152491525915269152791528915299153091531915329153391534915359153691537915389153991540915419154291543915449154591546915479154891549915509155191552915539155491555915569155791558915599156091561915629156391564915659156691567915689156991570915719157291573915749157591576915779157891579915809158191582915839158491585915869158791588915899159091591915929159391594915959159691597915989159991600916019160291603916049160591606916079160891609916109161191612916139161491615916169161791618916199162091621916229162391624916259162691627916289162991630916319163291633916349163591636916379163891639916409164191642916439164491645916469164791648916499165091651916529165391654916559165691657916589165991660916619166291663916649166591666916679166891669916709167191672916739167491675916769167791678916799168091681916829168391684916859168691687916889168991690916919169291693916949169591696916979169891699917009170191702917039170491705917069170791708917099171091711917129171391714917159171691717917189171991720917219172291723917249172591726917279172891729
  1. var __decorate=this&&this.__decorate||function(e,t,r,c){var o,f=arguments.length,n=f<3?t:null===c?c=Object.getOwnPropertyDescriptor(t,r):c;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)n=Reflect.decorate(e,t,r,c);else for(var l=e.length-1;l>=0;l--)(o=e[l])&&(n=(f<3?o(n):f>3?o(t,r,n):o(t,r))||n);return f>3&&n&&Object.defineProperty(t,r,n),n};
  2. var __extends=this&&this.__extends||function(){var t=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(t,o){t.__proto__=o}||function(t,o){for(var n in o)o.hasOwnProperty(n)&&(t[n]=o[n])};return function(o,n){function r(){this.constructor=o}t(o,n),o.prototype=null===n?Object.create(n):(r.prototype=n.prototype,new r)}}();
  3. var BABYLON;
  4. (function (BABYLON) {
  5. /**
  6. * EffectFallbacks can be used to add fallbacks (properties to disable) to certain properties when desired to improve performance.
  7. * (Eg. Start at high quality with reflection and fog, if fps is low, remove reflection, if still low remove fog)
  8. */
  9. var EffectFallbacks = /** @class */ (function () {
  10. function EffectFallbacks() {
  11. this._defines = {};
  12. this._currentRank = 32;
  13. this._maxRank = -1;
  14. }
  15. /**
  16. * Removes the fallback from the bound mesh.
  17. */
  18. EffectFallbacks.prototype.unBindMesh = function () {
  19. this._mesh = null;
  20. };
  21. /**
  22. * Adds a fallback on the specified property.
  23. * @param rank The rank of the fallback (Lower ranks will be fallbacked to first)
  24. * @param define The name of the define in the shader
  25. */
  26. EffectFallbacks.prototype.addFallback = function (rank, define) {
  27. if (!this._defines[rank]) {
  28. if (rank < this._currentRank) {
  29. this._currentRank = rank;
  30. }
  31. if (rank > this._maxRank) {
  32. this._maxRank = rank;
  33. }
  34. this._defines[rank] = new Array();
  35. }
  36. this._defines[rank].push(define);
  37. };
  38. /**
  39. * Sets the mesh to use CPU skinning when needing to fallback.
  40. * @param rank The rank of the fallback (Lower ranks will be fallbacked to first)
  41. * @param mesh The mesh to use the fallbacks.
  42. */
  43. EffectFallbacks.prototype.addCPUSkinningFallback = function (rank, mesh) {
  44. this._mesh = mesh;
  45. if (rank < this._currentRank) {
  46. this._currentRank = rank;
  47. }
  48. if (rank > this._maxRank) {
  49. this._maxRank = rank;
  50. }
  51. };
  52. Object.defineProperty(EffectFallbacks.prototype, "isMoreFallbacks", {
  53. /**
  54. * Checks to see if more fallbacks are still availible.
  55. */
  56. get: function () {
  57. return this._currentRank <= this._maxRank;
  58. },
  59. enumerable: true,
  60. configurable: true
  61. });
  62. /**
  63. * Removes the defines that shoould be removed when falling back.
  64. * @param currentDefines defines the current define statements for the shader.
  65. * @param effect defines the current effect we try to compile
  66. * @returns The resulting defines with defines of the current rank removed.
  67. */
  68. EffectFallbacks.prototype.reduce = function (currentDefines, effect) {
  69. // First we try to switch to CPU skinning
  70. if (this._mesh && this._mesh.computeBonesUsingShaders && this._mesh.numBoneInfluencers > 0 && this._mesh.material) {
  71. this._mesh.computeBonesUsingShaders = false;
  72. currentDefines = currentDefines.replace("#define NUM_BONE_INFLUENCERS " + this._mesh.numBoneInfluencers, "#define NUM_BONE_INFLUENCERS 0");
  73. var scene = this._mesh.getScene();
  74. for (var index = 0; index < scene.meshes.length; index++) {
  75. var otherMesh = scene.meshes[index];
  76. if (!otherMesh.material) {
  77. continue;
  78. }
  79. if (!otherMesh.computeBonesUsingShaders || otherMesh.numBoneInfluencers === 0) {
  80. continue;
  81. }
  82. if (otherMesh.material.getEffect() === effect) {
  83. otherMesh.computeBonesUsingShaders = false;
  84. }
  85. else {
  86. for (var _i = 0, _a = otherMesh.subMeshes; _i < _a.length; _i++) {
  87. var subMesh = _a[_i];
  88. var subMeshEffect = subMesh.effect;
  89. if (subMeshEffect === effect) {
  90. otherMesh.computeBonesUsingShaders = false;
  91. break;
  92. }
  93. }
  94. }
  95. }
  96. }
  97. else {
  98. var currentFallbacks = this._defines[this._currentRank];
  99. if (currentFallbacks) {
  100. for (var index = 0; index < currentFallbacks.length; index++) {
  101. currentDefines = currentDefines.replace("#define " + currentFallbacks[index], "");
  102. }
  103. }
  104. this._currentRank++;
  105. }
  106. return currentDefines;
  107. };
  108. return EffectFallbacks;
  109. }());
  110. BABYLON.EffectFallbacks = EffectFallbacks;
  111. /**
  112. * Options to be used when creating an effect.
  113. */
  114. var EffectCreationOptions = /** @class */ (function () {
  115. function EffectCreationOptions() {
  116. }
  117. return EffectCreationOptions;
  118. }());
  119. BABYLON.EffectCreationOptions = EffectCreationOptions;
  120. /**
  121. * Effect containing vertex and fragment shader that can be executed on an object.
  122. */
  123. var Effect = /** @class */ (function () {
  124. /**
  125. * Instantiates an effect.
  126. * An effect can be used to create/manage/execute vertex and fragment shaders.
  127. * @param baseName Name of the effect.
  128. * @param attributesNamesOrOptions List of attribute names that will be passed to the shader or set of all options to create the effect.
  129. * @param uniformsNamesOrEngine List of uniform variable names that will be passed to the shader or the engine that will be used to render effect.
  130. * @param samplers List of sampler variables that will be passed to the shader.
  131. * @param engine Engine to be used to render the effect
  132. * @param defines Define statements to be added to the shader.
  133. * @param fallbacks Possible fallbacks for this effect to improve performance when needed.
  134. * @param onCompiled Callback that will be called when the shader is compiled.
  135. * @param onError Callback that will be called if an error occurs during shader compilation.
  136. * @param indexParameters Parameters to be used with Babylons include syntax to iterate over an array (eg. {lights: 10})
  137. */
  138. function Effect(baseName, attributesNamesOrOptions, uniformsNamesOrEngine, samplers, engine, defines, fallbacks, onCompiled, onError, indexParameters) {
  139. if (samplers === void 0) { samplers = null; }
  140. if (defines === void 0) { defines = null; }
  141. if (fallbacks === void 0) { fallbacks = null; }
  142. if (onCompiled === void 0) { onCompiled = null; }
  143. if (onError === void 0) { onError = null; }
  144. var _this = this;
  145. /**
  146. * Unique ID of the effect.
  147. */
  148. this.uniqueId = 0;
  149. /**
  150. * Observable that will be called when the shader is compiled.
  151. */
  152. this.onCompileObservable = new BABYLON.Observable();
  153. /**
  154. * Observable that will be called if an error occurs during shader compilation.
  155. */
  156. this.onErrorObservable = new BABYLON.Observable();
  157. /**
  158. * Observable that will be called when effect is bound.
  159. */
  160. this.onBindObservable = new BABYLON.Observable();
  161. this._uniformBuffersNames = {};
  162. this._isReady = false;
  163. this._compilationError = "";
  164. this.name = baseName;
  165. if (attributesNamesOrOptions.attributes) {
  166. var options = attributesNamesOrOptions;
  167. this._engine = uniformsNamesOrEngine;
  168. this._attributesNames = options.attributes;
  169. this._uniformsNames = options.uniformsNames.concat(options.samplers);
  170. this._samplers = options.samplers;
  171. this.defines = options.defines;
  172. this.onError = options.onError;
  173. this.onCompiled = options.onCompiled;
  174. this._fallbacks = options.fallbacks;
  175. this._indexParameters = options.indexParameters;
  176. this._transformFeedbackVaryings = options.transformFeedbackVaryings;
  177. if (options.uniformBuffersNames) {
  178. for (var i = 0; i < options.uniformBuffersNames.length; i++) {
  179. this._uniformBuffersNames[options.uniformBuffersNames[i]] = i;
  180. }
  181. }
  182. }
  183. else {
  184. this._engine = engine;
  185. this.defines = defines;
  186. this._uniformsNames = uniformsNamesOrEngine.concat(samplers);
  187. this._samplers = samplers;
  188. this._attributesNames = attributesNamesOrOptions;
  189. this.onError = onError;
  190. this.onCompiled = onCompiled;
  191. this._indexParameters = indexParameters;
  192. this._fallbacks = fallbacks;
  193. }
  194. this.uniqueId = Effect._uniqueIdSeed++;
  195. if (this._getFromCache(baseName)) {
  196. this._prepareEffect();
  197. return;
  198. }
  199. var vertexSource;
  200. var fragmentSource;
  201. if (baseName.vertexElement) {
  202. vertexSource = document.getElementById(baseName.vertexElement);
  203. if (!vertexSource) {
  204. vertexSource = baseName.vertexElement;
  205. }
  206. }
  207. else {
  208. vertexSource = baseName.vertex || baseName;
  209. }
  210. if (baseName.fragmentElement) {
  211. fragmentSource = document.getElementById(baseName.fragmentElement);
  212. if (!fragmentSource) {
  213. fragmentSource = baseName.fragmentElement;
  214. }
  215. }
  216. else {
  217. fragmentSource = baseName.fragment || baseName;
  218. }
  219. var finalVertexCode;
  220. this._loadVertexShaderAsync(vertexSource)
  221. .then(function (vertexCode) {
  222. return _this._processIncludesAsync(vertexCode);
  223. })
  224. .then(function (vertexCodeWithIncludes) {
  225. finalVertexCode = _this._processShaderConversion(vertexCodeWithIncludes, false);
  226. return _this._loadFragmentShaderAsync(fragmentSource);
  227. })
  228. .then(function (fragmentCode) {
  229. return _this._processIncludesAsync(fragmentCode);
  230. })
  231. .then(function (fragmentCodeWithIncludes) {
  232. var migratedFragmentCode = _this._processShaderConversion(fragmentCodeWithIncludes, true);
  233. if (baseName) {
  234. var vertex = baseName.vertexElement || baseName.vertex || baseName;
  235. var fragment = baseName.fragmentElement || baseName.fragment || baseName;
  236. _this._vertexSourceCode = "#define SHADER_NAME vertex:" + vertex + "\n" + finalVertexCode;
  237. _this._fragmentSourceCode = "#define SHADER_NAME fragment:" + fragment + "\n" + migratedFragmentCode;
  238. }
  239. else {
  240. _this._vertexSourceCode = finalVertexCode;
  241. _this._fragmentSourceCode = migratedFragmentCode;
  242. }
  243. _this._setInCache(baseName);
  244. _this._prepareEffect();
  245. });
  246. }
  247. Effect.prototype._getSourceCacheKey = function (baseName) {
  248. var cacheKey = baseName;
  249. if (this._indexParameters) {
  250. for (var key in this._indexParameters) {
  251. if (this._indexParameters.hasOwnProperty(key)) {
  252. cacheKey += "|";
  253. cacheKey += key;
  254. cacheKey += "_";
  255. cacheKey += this._indexParameters[key];
  256. }
  257. }
  258. }
  259. return cacheKey;
  260. };
  261. Effect.prototype._getFromCache = function (baseName) {
  262. if (typeof baseName !== "string") {
  263. return false;
  264. }
  265. var cacheKey = this._getSourceCacheKey(baseName);
  266. var sources = Effect._sourceCache[cacheKey];
  267. if (!sources) {
  268. return false;
  269. }
  270. this._vertexSourceCode = sources.vertex;
  271. this._fragmentSourceCode = sources.fragment;
  272. return true;
  273. };
  274. Effect.prototype._setInCache = function (baseName) {
  275. if (typeof baseName !== "string") {
  276. return;
  277. }
  278. var cacheKey = this._getSourceCacheKey(baseName);
  279. Effect._sourceCache[cacheKey] = {
  280. vertex: this._vertexSourceCode,
  281. fragment: this._fragmentSourceCode
  282. };
  283. };
  284. Object.defineProperty(Effect.prototype, "key", {
  285. /**
  286. * Unique key for this effect
  287. */
  288. get: function () {
  289. return this._key;
  290. },
  291. enumerable: true,
  292. configurable: true
  293. });
  294. /**
  295. * If the effect has been compiled and prepared.
  296. * @returns if the effect is compiled and prepared.
  297. */
  298. Effect.prototype.isReady = function () {
  299. return this._isReady;
  300. };
  301. /**
  302. * The engine the effect was initialized with.
  303. * @returns the engine.
  304. */
  305. Effect.prototype.getEngine = function () {
  306. return this._engine;
  307. };
  308. /**
  309. * The compiled webGL program for the effect
  310. * @returns the webGL program.
  311. */
  312. Effect.prototype.getProgram = function () {
  313. return this._program;
  314. };
  315. /**
  316. * The set of names of attribute variables for the shader.
  317. * @returns An array of attribute names.
  318. */
  319. Effect.prototype.getAttributesNames = function () {
  320. return this._attributesNames;
  321. };
  322. /**
  323. * Returns the attribute at the given index.
  324. * @param index The index of the attribute.
  325. * @returns The location of the attribute.
  326. */
  327. Effect.prototype.getAttributeLocation = function (index) {
  328. return this._attributes[index];
  329. };
  330. /**
  331. * Returns the attribute based on the name of the variable.
  332. * @param name of the attribute to look up.
  333. * @returns the attribute location.
  334. */
  335. Effect.prototype.getAttributeLocationByName = function (name) {
  336. var index = this._attributesNames.indexOf(name);
  337. return this._attributes[index];
  338. };
  339. /**
  340. * The number of attributes.
  341. * @returns the numnber of attributes.
  342. */
  343. Effect.prototype.getAttributesCount = function () {
  344. return this._attributes.length;
  345. };
  346. /**
  347. * Gets the index of a uniform variable.
  348. * @param uniformName of the uniform to look up.
  349. * @returns the index.
  350. */
  351. Effect.prototype.getUniformIndex = function (uniformName) {
  352. return this._uniformsNames.indexOf(uniformName);
  353. };
  354. /**
  355. * Returns the attribute based on the name of the variable.
  356. * @param uniformName of the uniform to look up.
  357. * @returns the location of the uniform.
  358. */
  359. Effect.prototype.getUniform = function (uniformName) {
  360. return this._uniforms[this._uniformsNames.indexOf(uniformName)];
  361. };
  362. /**
  363. * Returns an array of sampler variable names
  364. * @returns The array of sampler variable neames.
  365. */
  366. Effect.prototype.getSamplers = function () {
  367. return this._samplers;
  368. };
  369. /**
  370. * The error from the last compilation.
  371. * @returns the error string.
  372. */
  373. Effect.prototype.getCompilationError = function () {
  374. return this._compilationError;
  375. };
  376. /**
  377. * Adds a callback to the onCompiled observable and call the callback imediatly if already ready.
  378. * @param func The callback to be used.
  379. */
  380. Effect.prototype.executeWhenCompiled = function (func) {
  381. if (this.isReady()) {
  382. func(this);
  383. return;
  384. }
  385. this.onCompileObservable.add(function (effect) {
  386. func(effect);
  387. });
  388. };
  389. /** @ignore */
  390. Effect.prototype._loadVertexShaderAsync = function (vertex) {
  391. if (BABYLON.Tools.IsWindowObjectExist()) {
  392. // DOM element ?
  393. if (vertex instanceof HTMLElement) {
  394. var vertexCode = BABYLON.Tools.GetDOMTextContent(vertex);
  395. return Promise.resolve(vertexCode);
  396. }
  397. }
  398. // Base64 encoded ?
  399. if (vertex.substr(0, 7) === "base64:") {
  400. var vertexBinary = window.atob(vertex.substr(7));
  401. return Promise.resolve(vertexBinary);
  402. }
  403. // Is in local store ?
  404. if (Effect.ShadersStore[vertex + "VertexShader"]) {
  405. return Promise.resolve(Effect.ShadersStore[vertex + "VertexShader"]);
  406. }
  407. var vertexShaderUrl;
  408. if (vertex[0] === "." || vertex[0] === "/" || vertex.indexOf("http") > -1) {
  409. vertexShaderUrl = vertex;
  410. }
  411. else {
  412. vertexShaderUrl = BABYLON.Engine.ShadersRepository + vertex;
  413. }
  414. // Vertex shader
  415. return this._engine._loadFileAsync(vertexShaderUrl + ".vertex.fx");
  416. };
  417. /** @ignore */
  418. Effect.prototype._loadFragmentShaderAsync = function (fragment) {
  419. if (BABYLON.Tools.IsWindowObjectExist()) {
  420. // DOM element ?
  421. if (fragment instanceof HTMLElement) {
  422. var fragmentCode = BABYLON.Tools.GetDOMTextContent(fragment);
  423. return Promise.resolve(fragmentCode);
  424. }
  425. }
  426. // Base64 encoded ?
  427. if (fragment.substr(0, 7) === "base64:") {
  428. var fragmentBinary = window.atob(fragment.substr(7));
  429. return Promise.resolve(fragmentBinary);
  430. }
  431. // Is in local store ?
  432. if (Effect.ShadersStore[fragment + "PixelShader"]) {
  433. return Promise.resolve(Effect.ShadersStore[fragment + "PixelShader"]);
  434. }
  435. if (Effect.ShadersStore[fragment + "FragmentShader"]) {
  436. return Promise.resolve(Effect.ShadersStore[fragment + "FragmentShader"]);
  437. }
  438. var fragmentShaderUrl;
  439. if (fragment[0] === "." || fragment[0] === "/" || fragment.indexOf("http") > -1) {
  440. fragmentShaderUrl = fragment;
  441. }
  442. else {
  443. fragmentShaderUrl = BABYLON.Engine.ShadersRepository + fragment;
  444. }
  445. // Fragment shader
  446. return this._engine._loadFileAsync(fragmentShaderUrl + ".fragment.fx");
  447. };
  448. Effect.prototype._dumpShadersSource = function (vertexCode, fragmentCode, defines) {
  449. // Rebuild shaders source code
  450. var shaderVersion = (this._engine.webGLVersion > 1) ? "#version 300 es\n" : "";
  451. var prefix = shaderVersion + (defines ? defines + "\n" : "");
  452. vertexCode = prefix + vertexCode;
  453. fragmentCode = prefix + fragmentCode;
  454. // Number lines of shaders source code
  455. var i = 2;
  456. var regex = /\n/gm;
  457. var formattedVertexCode = "\n1\t" + vertexCode.replace(regex, function () { return "\n" + (i++) + "\t"; });
  458. i = 2;
  459. var formattedFragmentCode = "\n1\t" + fragmentCode.replace(regex, function () { return "\n" + (i++) + "\t"; });
  460. // Dump shaders name and formatted source code
  461. if (this.name.vertexElement) {
  462. BABYLON.Tools.Error("Vertex shader: " + this.name.vertexElement + formattedVertexCode);
  463. BABYLON.Tools.Error("Fragment shader: " + this.name.fragmentElement + formattedFragmentCode);
  464. }
  465. else if (this.name.vertex) {
  466. BABYLON.Tools.Error("Vertex shader: " + this.name.vertex + formattedVertexCode);
  467. BABYLON.Tools.Error("Fragment shader: " + this.name.fragment + formattedFragmentCode);
  468. }
  469. else {
  470. BABYLON.Tools.Error("Vertex shader: " + this.name + formattedVertexCode);
  471. BABYLON.Tools.Error("Fragment shader: " + this.name + formattedFragmentCode);
  472. }
  473. };
  474. ;
  475. Effect.prototype._processShaderConversion = function (sourceCode, isFragment) {
  476. var preparedSourceCode = this._processPrecision(sourceCode);
  477. if (this._engine.webGLVersion == 1) {
  478. return preparedSourceCode;
  479. }
  480. // Already converted
  481. if (preparedSourceCode.indexOf("#version 3") !== -1) {
  482. return preparedSourceCode.replace("#version 300 es", "");
  483. }
  484. var hasDrawBuffersExtension = preparedSourceCode.search(/#extension.+GL_EXT_draw_buffers.+require/) !== -1;
  485. // Remove extensions
  486. // #extension GL_OES_standard_derivatives : enable
  487. // #extension GL_EXT_shader_texture_lod : enable
  488. // #extension GL_EXT_frag_depth : enable
  489. // #extension GL_EXT_draw_buffers : require
  490. var regex = /#extension.+(GL_OES_standard_derivatives|GL_EXT_shader_texture_lod|GL_EXT_frag_depth|GL_EXT_draw_buffers).+(enable|require)/g;
  491. var result = preparedSourceCode.replace(regex, "");
  492. // Migrate to GLSL v300
  493. result = result.replace(/varying(?![\n\r])\s/g, isFragment ? "in " : "out ");
  494. result = result.replace(/attribute[ \t]/g, "in ");
  495. result = result.replace(/[ \t]attribute/g, " in");
  496. if (isFragment) {
  497. result = result.replace(/texture2DLodEXT\s*\(/g, "textureLod(");
  498. result = result.replace(/textureCubeLodEXT\s*\(/g, "textureLod(");
  499. result = result.replace(/texture2D\s*\(/g, "texture(");
  500. result = result.replace(/textureCube\s*\(/g, "texture(");
  501. result = result.replace(/gl_FragDepthEXT/g, "gl_FragDepth");
  502. result = result.replace(/gl_FragColor/g, "glFragColor");
  503. result = result.replace(/gl_FragData/g, "glFragData");
  504. result = result.replace(/void\s+?main\s*\(/g, (hasDrawBuffersExtension ? "" : "out vec4 glFragColor;\n") + "void main(");
  505. }
  506. return result;
  507. };
  508. Effect.prototype._processIncludesAsync = function (sourceCode) {
  509. var _this = this;
  510. return new Promise(function (resolve, reject) {
  511. var regex = /#include<(.+)>(\((.*)\))*(\[(.*)\])*/g;
  512. var match = regex.exec(sourceCode);
  513. var returnValue = sourceCode;
  514. while (match != null) {
  515. var includeFile = match[1];
  516. // Uniform declaration
  517. if (includeFile.indexOf("__decl__") !== -1) {
  518. includeFile = includeFile.replace(/__decl__/, "");
  519. if (_this._engine.supportsUniformBuffers) {
  520. includeFile = includeFile.replace(/Vertex/, "Ubo");
  521. includeFile = includeFile.replace(/Fragment/, "Ubo");
  522. }
  523. includeFile = includeFile + "Declaration";
  524. }
  525. if (Effect.IncludesShadersStore[includeFile]) {
  526. // Substitution
  527. var includeContent = Effect.IncludesShadersStore[includeFile];
  528. if (match[2]) {
  529. var splits = match[3].split(",");
  530. for (var index = 0; index < splits.length; index += 2) {
  531. var source = new RegExp(splits[index], "g");
  532. var dest = splits[index + 1];
  533. includeContent = includeContent.replace(source, dest);
  534. }
  535. }
  536. if (match[4]) {
  537. var indexString = match[5];
  538. if (indexString.indexOf("..") !== -1) {
  539. var indexSplits = indexString.split("..");
  540. var minIndex = parseInt(indexSplits[0]);
  541. var maxIndex = parseInt(indexSplits[1]);
  542. var sourceIncludeContent = includeContent.slice(0);
  543. includeContent = "";
  544. if (isNaN(maxIndex)) {
  545. maxIndex = _this._indexParameters[indexSplits[1]];
  546. }
  547. for (var i = minIndex; i < maxIndex; i++) {
  548. if (!_this._engine.supportsUniformBuffers) {
  549. // Ubo replacement
  550. sourceIncludeContent = sourceIncludeContent.replace(/light\{X\}.(\w*)/g, function (str, p1) {
  551. return p1 + "{X}";
  552. });
  553. }
  554. includeContent += sourceIncludeContent.replace(/\{X\}/g, i.toString()) + "\n";
  555. }
  556. }
  557. else {
  558. if (!_this._engine.supportsUniformBuffers) {
  559. // Ubo replacement
  560. includeContent = includeContent.replace(/light\{X\}.(\w*)/g, function (str, p1) {
  561. return p1 + "{X}";
  562. });
  563. }
  564. includeContent = includeContent.replace(/\{X\}/g, indexString);
  565. }
  566. }
  567. // Replace
  568. returnValue = returnValue.replace(match[0], includeContent);
  569. }
  570. else {
  571. var includeShaderUrl = BABYLON.Engine.ShadersRepository + "ShadersInclude/" + includeFile + ".fx";
  572. _this._engine._loadFileAsync(includeShaderUrl)
  573. .then(function (fileContent) {
  574. Effect.IncludesShadersStore[includeFile] = fileContent;
  575. return _this._processIncludesAsync(returnValue);
  576. })
  577. .then(function (returnValue) {
  578. resolve(returnValue);
  579. });
  580. return;
  581. }
  582. match = regex.exec(sourceCode);
  583. }
  584. resolve(returnValue);
  585. });
  586. };
  587. Effect.prototype._processPrecision = function (source) {
  588. if (source.indexOf("precision highp float") === -1) {
  589. if (!this._engine.getCaps().highPrecisionShaderSupported) {
  590. source = "precision mediump float;\n" + source;
  591. }
  592. else {
  593. source = "precision highp float;\n" + source;
  594. }
  595. }
  596. else {
  597. if (!this._engine.getCaps().highPrecisionShaderSupported) {
  598. source = source.replace("precision highp float", "precision mediump float");
  599. }
  600. }
  601. return source;
  602. };
  603. /**
  604. * Recompiles the webGL program
  605. * @param vertexSourceCode The source code for the vertex shader.
  606. * @param fragmentSourceCode The source code for the fragment shader.
  607. * @param onCompiled Callback called when completed.
  608. * @param onError Callback called on error.
  609. */
  610. Effect.prototype._rebuildProgram = function (vertexSourceCode, fragmentSourceCode, onCompiled, onError) {
  611. var _this = this;
  612. this._isReady = false;
  613. this._vertexSourceCodeOverride = vertexSourceCode;
  614. this._fragmentSourceCodeOverride = fragmentSourceCode;
  615. this.onError = function (effect, error) {
  616. if (onError) {
  617. onError(error);
  618. }
  619. };
  620. this.onCompiled = function () {
  621. var scenes = _this.getEngine().scenes;
  622. for (var i = 0; i < scenes.length; i++) {
  623. scenes[i].markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  624. }
  625. if (onCompiled) {
  626. onCompiled(_this._program);
  627. }
  628. };
  629. this._fallbacks = null;
  630. this._prepareEffect();
  631. };
  632. /**
  633. * Gets the uniform locations of the the specified variable names
  634. * @param names THe names of the variables to lookup.
  635. * @returns Array of locations in the same order as variable names.
  636. */
  637. Effect.prototype.getSpecificUniformLocations = function (names) {
  638. var engine = this._engine;
  639. return engine.getUniforms(this._program, names);
  640. };
  641. /**
  642. * Prepares the effect
  643. */
  644. Effect.prototype._prepareEffect = function () {
  645. var attributesNames = this._attributesNames;
  646. var defines = this.defines;
  647. var fallbacks = this._fallbacks;
  648. this._valueCache = {};
  649. var previousProgram = this._program;
  650. try {
  651. var engine = this._engine;
  652. if (this._vertexSourceCodeOverride && this._fragmentSourceCodeOverride) {
  653. this._program = engine.createRawShaderProgram(this._vertexSourceCodeOverride, this._fragmentSourceCodeOverride, undefined, this._transformFeedbackVaryings);
  654. }
  655. else {
  656. this._program = engine.createShaderProgram(this._vertexSourceCode, this._fragmentSourceCode, defines, undefined, this._transformFeedbackVaryings);
  657. }
  658. this._program.__SPECTOR_rebuildProgram = this._rebuildProgram.bind(this);
  659. if (engine.supportsUniformBuffers) {
  660. for (var name in this._uniformBuffersNames) {
  661. this.bindUniformBlock(name, this._uniformBuffersNames[name]);
  662. }
  663. }
  664. this._uniforms = engine.getUniforms(this._program, this._uniformsNames);
  665. this._attributes = engine.getAttributes(this._program, attributesNames);
  666. var index;
  667. for (index = 0; index < this._samplers.length; index++) {
  668. var sampler = this.getUniform(this._samplers[index]);
  669. if (sampler == null) {
  670. this._samplers.splice(index, 1);
  671. index--;
  672. }
  673. }
  674. engine.bindSamplers(this);
  675. this._compilationError = "";
  676. this._isReady = true;
  677. if (this.onCompiled) {
  678. this.onCompiled(this);
  679. }
  680. this.onCompileObservable.notifyObservers(this);
  681. this.onCompileObservable.clear();
  682. // Unbind mesh reference in fallbacks
  683. if (this._fallbacks) {
  684. this._fallbacks.unBindMesh();
  685. }
  686. if (previousProgram) {
  687. this.getEngine()._deleteProgram(previousProgram);
  688. }
  689. }
  690. catch (e) {
  691. this._compilationError = e.message;
  692. // Let's go through fallbacks then
  693. BABYLON.Tools.Error("Unable to compile effect:");
  694. BABYLON.Tools.Error("Uniforms: " + this._uniformsNames.map(function (uniform) {
  695. return " " + uniform;
  696. }));
  697. BABYLON.Tools.Error("Attributes: " + attributesNames.map(function (attribute) {
  698. return " " + attribute;
  699. }));
  700. this._dumpShadersSource(this._vertexSourceCode, this._fragmentSourceCode, defines);
  701. BABYLON.Tools.Error("Error: " + this._compilationError);
  702. if (previousProgram) {
  703. this._program = previousProgram;
  704. this._isReady = true;
  705. if (this.onError) {
  706. this.onError(this, this._compilationError);
  707. }
  708. this.onErrorObservable.notifyObservers(this);
  709. }
  710. if (fallbacks && fallbacks.isMoreFallbacks) {
  711. BABYLON.Tools.Error("Trying next fallback.");
  712. this.defines = fallbacks.reduce(this.defines, this);
  713. this._prepareEffect();
  714. }
  715. else {
  716. if (this.onError) {
  717. this.onError(this, this._compilationError);
  718. }
  719. this.onErrorObservable.notifyObservers(this);
  720. this.onErrorObservable.clear();
  721. // Unbind mesh reference in fallbacks
  722. if (this._fallbacks) {
  723. this._fallbacks.unBindMesh();
  724. }
  725. }
  726. }
  727. };
  728. Object.defineProperty(Effect.prototype, "isSupported", {
  729. /**
  730. * Checks if the effect is supported. (Must be called after compilation)
  731. */
  732. get: function () {
  733. return this._compilationError === "";
  734. },
  735. enumerable: true,
  736. configurable: true
  737. });
  738. /**
  739. * Binds a texture to the engine to be used as output of the shader.
  740. * @param channel Name of the output variable.
  741. * @param texture Texture to bind.
  742. */
  743. Effect.prototype._bindTexture = function (channel, texture) {
  744. this._engine._bindTexture(this._samplers.indexOf(channel), texture);
  745. };
  746. /**
  747. * Sets a texture on the engine to be used in the shader.
  748. * @param channel Name of the sampler variable.
  749. * @param texture Texture to set.
  750. */
  751. Effect.prototype.setTexture = function (channel, texture) {
  752. this._engine.setTexture(this._samplers.indexOf(channel), this.getUniform(channel), texture);
  753. };
  754. /**
  755. * Sets an array of textures on the engine to be used in the shader.
  756. * @param channel Name of the variable.
  757. * @param textures Textures to set.
  758. */
  759. Effect.prototype.setTextureArray = function (channel, textures) {
  760. if (this._samplers.indexOf(channel + "Ex") === -1) {
  761. var initialPos = this._samplers.indexOf(channel);
  762. for (var index = 1; index < textures.length; index++) {
  763. this._samplers.splice(initialPos + index, 0, channel + "Ex");
  764. }
  765. }
  766. this._engine.setTextureArray(this._samplers.indexOf(channel), this.getUniform(channel), textures);
  767. };
  768. /**
  769. * 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)
  770. * @param channel Name of the sampler variable.
  771. * @param postProcess Post process to get the input texture from.
  772. */
  773. Effect.prototype.setTextureFromPostProcess = function (channel, postProcess) {
  774. this._engine.setTextureFromPostProcess(this._samplers.indexOf(channel), postProcess);
  775. };
  776. /** @ignore */
  777. Effect.prototype._cacheMatrix = function (uniformName, matrix) {
  778. var cache = this._valueCache[uniformName];
  779. var flag = matrix.updateFlag;
  780. if (cache !== undefined && cache === flag) {
  781. return false;
  782. }
  783. this._valueCache[uniformName] = flag;
  784. return true;
  785. };
  786. /** @ignore */
  787. Effect.prototype._cacheFloat2 = function (uniformName, x, y) {
  788. var cache = this._valueCache[uniformName];
  789. if (!cache) {
  790. cache = [x, y];
  791. this._valueCache[uniformName] = cache;
  792. return true;
  793. }
  794. var changed = false;
  795. if (cache[0] !== x) {
  796. cache[0] = x;
  797. changed = true;
  798. }
  799. if (cache[1] !== y) {
  800. cache[1] = y;
  801. changed = true;
  802. }
  803. return changed;
  804. };
  805. /** @ignore */
  806. Effect.prototype._cacheFloat3 = function (uniformName, x, y, z) {
  807. var cache = this._valueCache[uniformName];
  808. if (!cache) {
  809. cache = [x, y, z];
  810. this._valueCache[uniformName] = cache;
  811. return true;
  812. }
  813. var changed = false;
  814. if (cache[0] !== x) {
  815. cache[0] = x;
  816. changed = true;
  817. }
  818. if (cache[1] !== y) {
  819. cache[1] = y;
  820. changed = true;
  821. }
  822. if (cache[2] !== z) {
  823. cache[2] = z;
  824. changed = true;
  825. }
  826. return changed;
  827. };
  828. /** @ignore */
  829. Effect.prototype._cacheFloat4 = function (uniformName, x, y, z, w) {
  830. var cache = this._valueCache[uniformName];
  831. if (!cache) {
  832. cache = [x, y, z, w];
  833. this._valueCache[uniformName] = cache;
  834. return true;
  835. }
  836. var changed = false;
  837. if (cache[0] !== x) {
  838. cache[0] = x;
  839. changed = true;
  840. }
  841. if (cache[1] !== y) {
  842. cache[1] = y;
  843. changed = true;
  844. }
  845. if (cache[2] !== z) {
  846. cache[2] = z;
  847. changed = true;
  848. }
  849. if (cache[3] !== w) {
  850. cache[3] = w;
  851. changed = true;
  852. }
  853. return changed;
  854. };
  855. /**
  856. * Binds a buffer to a uniform.
  857. * @param buffer Buffer to bind.
  858. * @param name Name of the uniform variable to bind to.
  859. */
  860. Effect.prototype.bindUniformBuffer = function (buffer, name) {
  861. var bufferName = this._uniformBuffersNames[name];
  862. if (bufferName === undefined || Effect._baseCache[bufferName] === buffer) {
  863. return;
  864. }
  865. Effect._baseCache[bufferName] = buffer;
  866. this._engine.bindUniformBufferBase(buffer, bufferName);
  867. };
  868. /**
  869. * Binds block to a uniform.
  870. * @param blockName Name of the block to bind.
  871. * @param index Index to bind.
  872. */
  873. Effect.prototype.bindUniformBlock = function (blockName, index) {
  874. this._engine.bindUniformBlock(this._program, blockName, index);
  875. };
  876. /**
  877. * Sets an interger value on a uniform variable.
  878. * @param uniformName Name of the variable.
  879. * @param value Value to be set.
  880. * @returns this effect.
  881. */
  882. Effect.prototype.setInt = function (uniformName, value) {
  883. var cache = this._valueCache[uniformName];
  884. if (cache !== undefined && cache === value)
  885. return this;
  886. this._valueCache[uniformName] = value;
  887. this._engine.setInt(this.getUniform(uniformName), value);
  888. return this;
  889. };
  890. /**
  891. * Sets an int array on a uniform variable.
  892. * @param uniformName Name of the variable.
  893. * @param array array to be set.
  894. * @returns this effect.
  895. */
  896. Effect.prototype.setIntArray = function (uniformName, array) {
  897. this._valueCache[uniformName] = null;
  898. this._engine.setIntArray(this.getUniform(uniformName), array);
  899. return this;
  900. };
  901. /**
  902. * 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)
  903. * @param uniformName Name of the variable.
  904. * @param array array to be set.
  905. * @returns this effect.
  906. */
  907. Effect.prototype.setIntArray2 = function (uniformName, array) {
  908. this._valueCache[uniformName] = null;
  909. this._engine.setIntArray2(this.getUniform(uniformName), array);
  910. return this;
  911. };
  912. /**
  913. * 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)
  914. * @param uniformName Name of the variable.
  915. * @param array array to be set.
  916. * @returns this effect.
  917. */
  918. Effect.prototype.setIntArray3 = function (uniformName, array) {
  919. this._valueCache[uniformName] = null;
  920. this._engine.setIntArray3(this.getUniform(uniformName), array);
  921. return this;
  922. };
  923. /**
  924. * 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)
  925. * @param uniformName Name of the variable.
  926. * @param array array to be set.
  927. * @returns this effect.
  928. */
  929. Effect.prototype.setIntArray4 = function (uniformName, array) {
  930. this._valueCache[uniformName] = null;
  931. this._engine.setIntArray4(this.getUniform(uniformName), array);
  932. return this;
  933. };
  934. /**
  935. * Sets an float array on a uniform variable.
  936. * @param uniformName Name of the variable.
  937. * @param array array to be set.
  938. * @returns this effect.
  939. */
  940. Effect.prototype.setFloatArray = function (uniformName, array) {
  941. this._valueCache[uniformName] = null;
  942. this._engine.setFloatArray(this.getUniform(uniformName), array);
  943. return this;
  944. };
  945. /**
  946. * 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)
  947. * @param uniformName Name of the variable.
  948. * @param array array to be set.
  949. * @returns this effect.
  950. */
  951. Effect.prototype.setFloatArray2 = function (uniformName, array) {
  952. this._valueCache[uniformName] = null;
  953. this._engine.setFloatArray2(this.getUniform(uniformName), array);
  954. return this;
  955. };
  956. /**
  957. * 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)
  958. * @param uniformName Name of the variable.
  959. * @param array array to be set.
  960. * @returns this effect.
  961. */
  962. Effect.prototype.setFloatArray3 = function (uniformName, array) {
  963. this._valueCache[uniformName] = null;
  964. this._engine.setFloatArray3(this.getUniform(uniformName), array);
  965. return this;
  966. };
  967. /**
  968. * 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)
  969. * @param uniformName Name of the variable.
  970. * @param array array to be set.
  971. * @returns this effect.
  972. */
  973. Effect.prototype.setFloatArray4 = function (uniformName, array) {
  974. this._valueCache[uniformName] = null;
  975. this._engine.setFloatArray4(this.getUniform(uniformName), array);
  976. return this;
  977. };
  978. /**
  979. * Sets an array on a uniform variable.
  980. * @param uniformName Name of the variable.
  981. * @param array array to be set.
  982. * @returns this effect.
  983. */
  984. Effect.prototype.setArray = function (uniformName, array) {
  985. this._valueCache[uniformName] = null;
  986. this._engine.setArray(this.getUniform(uniformName), array);
  987. return this;
  988. };
  989. /**
  990. * 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)
  991. * @param uniformName Name of the variable.
  992. * @param array array to be set.
  993. * @returns this effect.
  994. */
  995. Effect.prototype.setArray2 = function (uniformName, array) {
  996. this._valueCache[uniformName] = null;
  997. this._engine.setArray2(this.getUniform(uniformName), array);
  998. return this;
  999. };
  1000. /**
  1001. * 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)
  1002. * @param uniformName Name of the variable.
  1003. * @param array array to be set.
  1004. * @returns this effect.
  1005. */
  1006. Effect.prototype.setArray3 = function (uniformName, array) {
  1007. this._valueCache[uniformName] = null;
  1008. this._engine.setArray3(this.getUniform(uniformName), array);
  1009. return this;
  1010. };
  1011. /**
  1012. * 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)
  1013. * @param uniformName Name of the variable.
  1014. * @param array array to be set.
  1015. * @returns this effect.
  1016. */
  1017. Effect.prototype.setArray4 = function (uniformName, array) {
  1018. this._valueCache[uniformName] = null;
  1019. this._engine.setArray4(this.getUniform(uniformName), array);
  1020. return this;
  1021. };
  1022. /**
  1023. * Sets matrices on a uniform variable.
  1024. * @param uniformName Name of the variable.
  1025. * @param matrices matrices to be set.
  1026. * @returns this effect.
  1027. */
  1028. Effect.prototype.setMatrices = function (uniformName, matrices) {
  1029. if (!matrices) {
  1030. return this;
  1031. }
  1032. this._valueCache[uniformName] = null;
  1033. this._engine.setMatrices(this.getUniform(uniformName), matrices);
  1034. return this;
  1035. };
  1036. /**
  1037. * Sets matrix on a uniform variable.
  1038. * @param uniformName Name of the variable.
  1039. * @param matrix matrix to be set.
  1040. * @returns this effect.
  1041. */
  1042. Effect.prototype.setMatrix = function (uniformName, matrix) {
  1043. if (this._cacheMatrix(uniformName, matrix)) {
  1044. this._engine.setMatrix(this.getUniform(uniformName), matrix);
  1045. }
  1046. return this;
  1047. };
  1048. /**
  1049. * 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)
  1050. * @param uniformName Name of the variable.
  1051. * @param matrix matrix to be set.
  1052. * @returns this effect.
  1053. */
  1054. Effect.prototype.setMatrix3x3 = function (uniformName, matrix) {
  1055. this._valueCache[uniformName] = null;
  1056. this._engine.setMatrix3x3(this.getUniform(uniformName), matrix);
  1057. return this;
  1058. };
  1059. /**
  1060. * Sets a 2x2 matrix on a uniform variable. (Speicified as [1,2,3,4] will result in [1,2][3,4] matrix)
  1061. * @param uniformName Name of the variable.
  1062. * @param matrix matrix to be set.
  1063. * @returns this effect.
  1064. */
  1065. Effect.prototype.setMatrix2x2 = function (uniformName, matrix) {
  1066. this._valueCache[uniformName] = null;
  1067. this._engine.setMatrix2x2(this.getUniform(uniformName), matrix);
  1068. return this;
  1069. };
  1070. /**
  1071. * Sets a float on a uniform variable.
  1072. * @param uniformName Name of the variable.
  1073. * @param value value to be set.
  1074. * @returns this effect.
  1075. */
  1076. Effect.prototype.setFloat = function (uniformName, value) {
  1077. var cache = this._valueCache[uniformName];
  1078. if (cache !== undefined && cache === value)
  1079. return this;
  1080. this._valueCache[uniformName] = value;
  1081. this._engine.setFloat(this.getUniform(uniformName), value);
  1082. return this;
  1083. };
  1084. /**
  1085. * Sets a boolean on a uniform variable.
  1086. * @param uniformName Name of the variable.
  1087. * @param bool value to be set.
  1088. * @returns this effect.
  1089. */
  1090. Effect.prototype.setBool = function (uniformName, bool) {
  1091. var cache = this._valueCache[uniformName];
  1092. if (cache !== undefined && cache === bool)
  1093. return this;
  1094. this._valueCache[uniformName] = bool;
  1095. this._engine.setBool(this.getUniform(uniformName), bool ? 1 : 0);
  1096. return this;
  1097. };
  1098. /**
  1099. * Sets a Vector2 on a uniform variable.
  1100. * @param uniformName Name of the variable.
  1101. * @param vector2 vector2 to be set.
  1102. * @returns this effect.
  1103. */
  1104. Effect.prototype.setVector2 = function (uniformName, vector2) {
  1105. if (this._cacheFloat2(uniformName, vector2.x, vector2.y)) {
  1106. this._engine.setFloat2(this.getUniform(uniformName), vector2.x, vector2.y);
  1107. }
  1108. return this;
  1109. };
  1110. /**
  1111. * Sets a float2 on a uniform variable.
  1112. * @param uniformName Name of the variable.
  1113. * @param x First float in float2.
  1114. * @param y Second float in float2.
  1115. * @returns this effect.
  1116. */
  1117. Effect.prototype.setFloat2 = function (uniformName, x, y) {
  1118. if (this._cacheFloat2(uniformName, x, y)) {
  1119. this._engine.setFloat2(this.getUniform(uniformName), x, y);
  1120. }
  1121. return this;
  1122. };
  1123. /**
  1124. * Sets a Vector3 on a uniform variable.
  1125. * @param uniformName Name of the variable.
  1126. * @param vector3 Value to be set.
  1127. * @returns this effect.
  1128. */
  1129. Effect.prototype.setVector3 = function (uniformName, vector3) {
  1130. if (this._cacheFloat3(uniformName, vector3.x, vector3.y, vector3.z)) {
  1131. this._engine.setFloat3(this.getUniform(uniformName), vector3.x, vector3.y, vector3.z);
  1132. }
  1133. return this;
  1134. };
  1135. /**
  1136. * Sets a float3 on a uniform variable.
  1137. * @param uniformName Name of the variable.
  1138. * @param x First float in float3.
  1139. * @param y Second float in float3.
  1140. * @param z Third float in float3.
  1141. * @returns this effect.
  1142. */
  1143. Effect.prototype.setFloat3 = function (uniformName, x, y, z) {
  1144. if (this._cacheFloat3(uniformName, x, y, z)) {
  1145. this._engine.setFloat3(this.getUniform(uniformName), x, y, z);
  1146. }
  1147. return this;
  1148. };
  1149. /**
  1150. * Sets a Vector4 on a uniform variable.
  1151. * @param uniformName Name of the variable.
  1152. * @param vector4 Value to be set.
  1153. * @returns this effect.
  1154. */
  1155. Effect.prototype.setVector4 = function (uniformName, vector4) {
  1156. if (this._cacheFloat4(uniformName, vector4.x, vector4.y, vector4.z, vector4.w)) {
  1157. this._engine.setFloat4(this.getUniform(uniformName), vector4.x, vector4.y, vector4.z, vector4.w);
  1158. }
  1159. return this;
  1160. };
  1161. /**
  1162. * Sets a float4 on a uniform variable.
  1163. * @param uniformName Name of the variable.
  1164. * @param x First float in float4.
  1165. * @param y Second float in float4.
  1166. * @param z Third float in float4.
  1167. * @param w Fourth float in float4.
  1168. * @returns this effect.
  1169. */
  1170. Effect.prototype.setFloat4 = function (uniformName, x, y, z, w) {
  1171. if (this._cacheFloat4(uniformName, x, y, z, w)) {
  1172. this._engine.setFloat4(this.getUniform(uniformName), x, y, z, w);
  1173. }
  1174. return this;
  1175. };
  1176. /**
  1177. * Sets a Color3 on a uniform variable.
  1178. * @param uniformName Name of the variable.
  1179. * @param color3 Value to be set.
  1180. * @returns this effect.
  1181. */
  1182. Effect.prototype.setColor3 = function (uniformName, color3) {
  1183. if (this._cacheFloat3(uniformName, color3.r, color3.g, color3.b)) {
  1184. this._engine.setColor3(this.getUniform(uniformName), color3);
  1185. }
  1186. return this;
  1187. };
  1188. /**
  1189. * Sets a Color4 on a uniform variable.
  1190. * @param uniformName Name of the variable.
  1191. * @param color3 Value to be set.
  1192. * @param alpha Alpha value to be set.
  1193. * @returns this effect.
  1194. */
  1195. Effect.prototype.setColor4 = function (uniformName, color3, alpha) {
  1196. if (this._cacheFloat4(uniformName, color3.r, color3.g, color3.b, alpha)) {
  1197. this._engine.setColor4(this.getUniform(uniformName), color3, alpha);
  1198. }
  1199. return this;
  1200. };
  1201. /**
  1202. * Sets a Color4 on a uniform variable
  1203. * @param uniformName defines the name of the variable
  1204. * @param color4 defines the value to be set
  1205. * @returns this effect.
  1206. */
  1207. Effect.prototype.setDirectColor4 = function (uniformName, color4) {
  1208. if (this._cacheFloat4(uniformName, color4.r, color4.g, color4.b, color4.a)) {
  1209. this._engine.setDirectColor4(this.getUniform(uniformName), color4);
  1210. }
  1211. return this;
  1212. };
  1213. /**
  1214. * Resets the cache of effects.
  1215. */
  1216. Effect.ResetCache = function () {
  1217. Effect._baseCache = {};
  1218. };
  1219. Effect._uniqueIdSeed = 0;
  1220. Effect._baseCache = {};
  1221. Effect._sourceCache = {};
  1222. // Statics
  1223. /**
  1224. * Store of each shader (The can be looked up using effect.key)
  1225. */
  1226. Effect.ShadersStore = {};
  1227. /**
  1228. * Store of each included file for a shader (The can be looked up using effect.key)
  1229. */
  1230. Effect.IncludesShadersStore = {};
  1231. return Effect;
  1232. }());
  1233. BABYLON.Effect = Effect;
  1234. })(BABYLON || (BABYLON = {}));
  1235. //# sourceMappingURL=babylon.effect.js.map
  1236. //# sourceMappingURL=babylon.types.js.map
  1237. var BABYLON;
  1238. (function (BABYLON) {
  1239. var KeyboardEventTypes = /** @class */ (function () {
  1240. function KeyboardEventTypes() {
  1241. }
  1242. Object.defineProperty(KeyboardEventTypes, "KEYDOWN", {
  1243. get: function () {
  1244. return KeyboardEventTypes._KEYDOWN;
  1245. },
  1246. enumerable: true,
  1247. configurable: true
  1248. });
  1249. Object.defineProperty(KeyboardEventTypes, "KEYUP", {
  1250. get: function () {
  1251. return KeyboardEventTypes._KEYUP;
  1252. },
  1253. enumerable: true,
  1254. configurable: true
  1255. });
  1256. KeyboardEventTypes._KEYDOWN = 0x01;
  1257. KeyboardEventTypes._KEYUP = 0x02;
  1258. return KeyboardEventTypes;
  1259. }());
  1260. BABYLON.KeyboardEventTypes = KeyboardEventTypes;
  1261. var KeyboardInfo = /** @class */ (function () {
  1262. function KeyboardInfo(type, event) {
  1263. this.type = type;
  1264. this.event = event;
  1265. }
  1266. return KeyboardInfo;
  1267. }());
  1268. BABYLON.KeyboardInfo = KeyboardInfo;
  1269. /**
  1270. * This class is used to store keyboard related info for the onPreKeyboardObservable event.
  1271. * Set the skipOnKeyboardObservable property to true if you want the engine to stop any process after this event is triggered, even not calling onKeyboardObservable
  1272. */
  1273. var KeyboardInfoPre = /** @class */ (function (_super) {
  1274. __extends(KeyboardInfoPre, _super);
  1275. function KeyboardInfoPre(type, event) {
  1276. var _this = _super.call(this, type, event) || this;
  1277. _this.skipOnPointerObservable = false;
  1278. return _this;
  1279. }
  1280. return KeyboardInfoPre;
  1281. }(KeyboardInfo));
  1282. BABYLON.KeyboardInfoPre = KeyboardInfoPre;
  1283. })(BABYLON || (BABYLON = {}));
  1284. //# sourceMappingURL=babylon.keyboardEvents.js.map
  1285. var BABYLON;
  1286. (function (BABYLON) {
  1287. var PointerEventTypes = /** @class */ (function () {
  1288. function PointerEventTypes() {
  1289. }
  1290. Object.defineProperty(PointerEventTypes, "POINTERDOWN", {
  1291. get: function () {
  1292. return PointerEventTypes._POINTERDOWN;
  1293. },
  1294. enumerable: true,
  1295. configurable: true
  1296. });
  1297. Object.defineProperty(PointerEventTypes, "POINTERUP", {
  1298. get: function () {
  1299. return PointerEventTypes._POINTERUP;
  1300. },
  1301. enumerable: true,
  1302. configurable: true
  1303. });
  1304. Object.defineProperty(PointerEventTypes, "POINTERMOVE", {
  1305. get: function () {
  1306. return PointerEventTypes._POINTERMOVE;
  1307. },
  1308. enumerable: true,
  1309. configurable: true
  1310. });
  1311. Object.defineProperty(PointerEventTypes, "POINTERWHEEL", {
  1312. get: function () {
  1313. return PointerEventTypes._POINTERWHEEL;
  1314. },
  1315. enumerable: true,
  1316. configurable: true
  1317. });
  1318. Object.defineProperty(PointerEventTypes, "POINTERPICK", {
  1319. get: function () {
  1320. return PointerEventTypes._POINTERPICK;
  1321. },
  1322. enumerable: true,
  1323. configurable: true
  1324. });
  1325. Object.defineProperty(PointerEventTypes, "POINTERTAP", {
  1326. get: function () {
  1327. return PointerEventTypes._POINTERTAP;
  1328. },
  1329. enumerable: true,
  1330. configurable: true
  1331. });
  1332. Object.defineProperty(PointerEventTypes, "POINTERDOUBLETAP", {
  1333. get: function () {
  1334. return PointerEventTypes._POINTERDOUBLETAP;
  1335. },
  1336. enumerable: true,
  1337. configurable: true
  1338. });
  1339. PointerEventTypes._POINTERDOWN = 0x01;
  1340. PointerEventTypes._POINTERUP = 0x02;
  1341. PointerEventTypes._POINTERMOVE = 0x04;
  1342. PointerEventTypes._POINTERWHEEL = 0x08;
  1343. PointerEventTypes._POINTERPICK = 0x10;
  1344. PointerEventTypes._POINTERTAP = 0x20;
  1345. PointerEventTypes._POINTERDOUBLETAP = 0x40;
  1346. return PointerEventTypes;
  1347. }());
  1348. BABYLON.PointerEventTypes = PointerEventTypes;
  1349. var PointerInfoBase = /** @class */ (function () {
  1350. function PointerInfoBase(type, event) {
  1351. this.type = type;
  1352. this.event = event;
  1353. }
  1354. return PointerInfoBase;
  1355. }());
  1356. BABYLON.PointerInfoBase = PointerInfoBase;
  1357. /**
  1358. * This class is used to store pointer related info for the onPrePointerObservable event.
  1359. * Set the skipOnPointerObservable property to true if you want the engine to stop any process after this event is triggered, even not calling onPointerObservable
  1360. */
  1361. var PointerInfoPre = /** @class */ (function (_super) {
  1362. __extends(PointerInfoPre, _super);
  1363. function PointerInfoPre(type, event, localX, localY) {
  1364. var _this = _super.call(this, type, event) || this;
  1365. _this.skipOnPointerObservable = false;
  1366. _this.localPosition = new BABYLON.Vector2(localX, localY);
  1367. return _this;
  1368. }
  1369. return PointerInfoPre;
  1370. }(PointerInfoBase));
  1371. BABYLON.PointerInfoPre = PointerInfoPre;
  1372. /**
  1373. * This type contains all the data related to a pointer event in Babylon.js.
  1374. * 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.
  1375. */
  1376. var PointerInfo = /** @class */ (function (_super) {
  1377. __extends(PointerInfo, _super);
  1378. function PointerInfo(type, event, pickInfo) {
  1379. var _this = _super.call(this, type, event) || this;
  1380. _this.pickInfo = pickInfo;
  1381. return _this;
  1382. }
  1383. return PointerInfo;
  1384. }(PointerInfoBase));
  1385. BABYLON.PointerInfo = PointerInfo;
  1386. })(BABYLON || (BABYLON = {}));
  1387. //# sourceMappingURL=babylon.pointerEvents.js.map
  1388. var BABYLON;
  1389. (function (BABYLON) {
  1390. BABYLON.ToGammaSpace = 1 / 2.2;
  1391. BABYLON.ToLinearSpace = 2.2;
  1392. BABYLON.Epsilon = 0.001;
  1393. /**
  1394. * Class used to hold a RBG color
  1395. */
  1396. var Color3 = /** @class */ (function () {
  1397. /**
  1398. * Creates a new Color3 object from red, green, blue values, all between 0 and 1
  1399. * @param r defines the red component (between 0 and 1, default is 0)
  1400. * @param g defines the green component (between 0 and 1, default is 0)
  1401. * @param b defines the blue component (between 0 and 1, default is 0)
  1402. */
  1403. function Color3(
  1404. /**
  1405. * Defines the red component (between 0 and 1, default is 0)
  1406. */
  1407. r,
  1408. /**
  1409. * Defines the green component (between 0 and 1, default is 0)
  1410. */
  1411. g,
  1412. /**
  1413. * Defines the blue component (between 0 and 1, default is 0)
  1414. */
  1415. b) {
  1416. if (r === void 0) { r = 0; }
  1417. if (g === void 0) { g = 0; }
  1418. if (b === void 0) { b = 0; }
  1419. this.r = r;
  1420. this.g = g;
  1421. this.b = b;
  1422. }
  1423. /**
  1424. * Creates a string with the Color3 current values
  1425. * @returns the string representation of the Color3 object
  1426. */
  1427. Color3.prototype.toString = function () {
  1428. return "{R: " + this.r + " G:" + this.g + " B:" + this.b + "}";
  1429. };
  1430. /**
  1431. * Returns the string "Color3"
  1432. * @returns "Color3"
  1433. */
  1434. Color3.prototype.getClassName = function () {
  1435. return "Color3";
  1436. };
  1437. /**
  1438. * Compute the Color3 hash code
  1439. * @returns an unique number that can be used to hash Color3 objects
  1440. */
  1441. Color3.prototype.getHashCode = function () {
  1442. var hash = this.r || 0;
  1443. hash = (hash * 397) ^ (this.g || 0);
  1444. hash = (hash * 397) ^ (this.b || 0);
  1445. return hash;
  1446. };
  1447. // Operators
  1448. /**
  1449. * Stores in the passed array from the passed starting index the red, green, blue values as successive elements
  1450. * @param array defines the array where to store the r,g,b components
  1451. * @param index defines an optional index in the target array to define where to start storing values
  1452. * @returns the current Color3 object
  1453. */
  1454. Color3.prototype.toArray = function (array, index) {
  1455. if (index === undefined) {
  1456. index = 0;
  1457. }
  1458. array[index] = this.r;
  1459. array[index + 1] = this.g;
  1460. array[index + 2] = this.b;
  1461. return this;
  1462. };
  1463. /**
  1464. * Returns a new {BABYLON.Color4} object from the current Color3 and the passed alpha
  1465. * @param alpha defines the alpha component on the new {BABYLON.Color4} object (default is 1)
  1466. * @returns a new {BABYLON.Color4} object
  1467. */
  1468. Color3.prototype.toColor4 = function (alpha) {
  1469. if (alpha === void 0) { alpha = 1; }
  1470. return new Color4(this.r, this.g, this.b, alpha);
  1471. };
  1472. /**
  1473. * Returns a new array populated with 3 numeric elements : red, green and blue values
  1474. * @returns the new array
  1475. */
  1476. Color3.prototype.asArray = function () {
  1477. var result = new Array();
  1478. this.toArray(result, 0);
  1479. return result;
  1480. };
  1481. /**
  1482. * Returns the luminance value
  1483. * @returns a float value
  1484. */
  1485. Color3.prototype.toLuminance = function () {
  1486. return this.r * 0.3 + this.g * 0.59 + this.b * 0.11;
  1487. };
  1488. /**
  1489. * Multiply each Color3 rgb values by the passed Color3 rgb values in a new Color3 object
  1490. * @param otherColor defines the second operand
  1491. * @returns the new Color3 object
  1492. */
  1493. Color3.prototype.multiply = function (otherColor) {
  1494. return new Color3(this.r * otherColor.r, this.g * otherColor.g, this.b * otherColor.b);
  1495. };
  1496. /**
  1497. * Multiply the rgb values of the Color3 and the passed Color3 and stores the result in the object "result"
  1498. * @param otherColor defines the second operand
  1499. * @param result defines the Color3 object where to store the result
  1500. * @returns the current Color3
  1501. */
  1502. Color3.prototype.multiplyToRef = function (otherColor, result) {
  1503. result.r = this.r * otherColor.r;
  1504. result.g = this.g * otherColor.g;
  1505. result.b = this.b * otherColor.b;
  1506. return this;
  1507. };
  1508. /**
  1509. * Determines equality between Color3 objects
  1510. * @param otherColor defines the second operand
  1511. * @returns true if the rgb values are equal to the passed ones
  1512. */
  1513. Color3.prototype.equals = function (otherColor) {
  1514. return otherColor && this.r === otherColor.r && this.g === otherColor.g && this.b === otherColor.b;
  1515. };
  1516. /**
  1517. * Determines equality between the current Color3 object and a set of r,b,g values
  1518. * @param r defines the red component to check
  1519. * @param g defines the green component to check
  1520. * @param b defines the blue component to check
  1521. * @returns true if the rgb values are equal to the passed ones
  1522. */
  1523. Color3.prototype.equalsFloats = function (r, g, b) {
  1524. return this.r === r && this.g === g && this.b === b;
  1525. };
  1526. /**
  1527. * Multiplies in place each rgb value by scale
  1528. * @param scale defines the scaling factor
  1529. * @returns the updated Color3.
  1530. */
  1531. Color3.prototype.scale = function (scale) {
  1532. return new Color3(this.r * scale, this.g * scale, this.b * scale);
  1533. };
  1534. /**
  1535. * Multiplies the rgb values by scale and stores the result into "result"
  1536. * @param scale defines the scaling factor
  1537. * @param result defines the Color3 object where to store the result
  1538. * @returns the unmodified current Color3.
  1539. */
  1540. Color3.prototype.scaleToRef = function (scale, result) {
  1541. result.r = this.r * scale;
  1542. result.g = this.g * scale;
  1543. result.b = this.b * scale;
  1544. return this;
  1545. };
  1546. /**
  1547. * Clamps the rgb values by the min and max values and stores the result into "result"
  1548. * @param min defines minimum clamping value (default is 0)
  1549. * @param max defines maximum clamping value (default is 1)
  1550. * @param result defines color to store the result into
  1551. * @returns the original Color3
  1552. */
  1553. Color3.prototype.clampToRef = function (min, max, result) {
  1554. if (min === void 0) { min = 0; }
  1555. if (max === void 0) { max = 1; }
  1556. result.r = BABYLON.Scalar.Clamp(this.r, min, max);
  1557. result.g = BABYLON.Scalar.Clamp(this.g, min, max);
  1558. result.b = BABYLON.Scalar.Clamp(this.b, min, max);
  1559. return this;
  1560. };
  1561. /**
  1562. * Creates a new Color3 set with the added values of the current Color3 and of the passed one
  1563. * @param otherColor defines the second operand
  1564. * @returns the new Color3
  1565. */
  1566. Color3.prototype.add = function (otherColor) {
  1567. return new Color3(this.r + otherColor.r, this.g + otherColor.g, this.b + otherColor.b);
  1568. };
  1569. /**
  1570. * Stores the result of the addition of the current Color3 and passed one rgb values into "result"
  1571. * @param otherColor defines the second operand
  1572. * @param result defines Color3 object to store the result into
  1573. * @returns the unmodified current Color3
  1574. */
  1575. Color3.prototype.addToRef = function (otherColor, result) {
  1576. result.r = this.r + otherColor.r;
  1577. result.g = this.g + otherColor.g;
  1578. result.b = this.b + otherColor.b;
  1579. return this;
  1580. };
  1581. /**
  1582. * Returns a new Color3 set with the subtracted values of the passed one from the current Color3
  1583. * @param otherColor defines the second operand
  1584. * @returns the new Color3
  1585. */
  1586. Color3.prototype.subtract = function (otherColor) {
  1587. return new Color3(this.r - otherColor.r, this.g - otherColor.g, this.b - otherColor.b);
  1588. };
  1589. /**
  1590. * Stores the result of the subtraction of passed one from the current Color3 rgb values into "result"
  1591. * @param otherColor defines the second operand
  1592. * @param result defines Color3 object to store the result into
  1593. * @returns the unmodified current Color3
  1594. */
  1595. Color3.prototype.subtractToRef = function (otherColor, result) {
  1596. result.r = this.r - otherColor.r;
  1597. result.g = this.g - otherColor.g;
  1598. result.b = this.b - otherColor.b;
  1599. return this;
  1600. };
  1601. /**
  1602. * Copy the current object
  1603. * @returns a new Color3 copied the current one
  1604. */
  1605. Color3.prototype.clone = function () {
  1606. return new Color3(this.r, this.g, this.b);
  1607. };
  1608. /**
  1609. * Copies the rgb values from the source in the current Color3
  1610. * @param source defines the source Color3 object
  1611. * @returns the updated Color3 object
  1612. */
  1613. Color3.prototype.copyFrom = function (source) {
  1614. this.r = source.r;
  1615. this.g = source.g;
  1616. this.b = source.b;
  1617. return this;
  1618. };
  1619. /**
  1620. * Updates the Color3 rgb values from the passed floats
  1621. * @param r defines the red component to read from
  1622. * @param g defines the green component to read from
  1623. * @param b defines the blue component to read from
  1624. * @returns the current Color3 object
  1625. */
  1626. Color3.prototype.copyFromFloats = function (r, g, b) {
  1627. this.r = r;
  1628. this.g = g;
  1629. this.b = b;
  1630. return this;
  1631. };
  1632. /**
  1633. * Updates the Color3 rgb values from the passed floats
  1634. * @param r defines the red component to read from
  1635. * @param g defines the green component to read from
  1636. * @param b defines the blue component to read from
  1637. * @returns the current Color3 object
  1638. */
  1639. Color3.prototype.set = function (r, g, b) {
  1640. return this.copyFromFloats(r, g, b);
  1641. };
  1642. /**
  1643. * Compute the Color3 hexadecimal code as a string
  1644. * @returns a string containing the hexadecimal representation of the Color3 object
  1645. */
  1646. Color3.prototype.toHexString = function () {
  1647. var intR = (this.r * 255) | 0;
  1648. var intG = (this.g * 255) | 0;
  1649. var intB = (this.b * 255) | 0;
  1650. return "#" + BABYLON.Scalar.ToHex(intR) + BABYLON.Scalar.ToHex(intG) + BABYLON.Scalar.ToHex(intB);
  1651. };
  1652. /**
  1653. * Computes a new Color3 converted from the current one to linear space
  1654. * @returns a new Color3 object
  1655. */
  1656. Color3.prototype.toLinearSpace = function () {
  1657. var convertedColor = new Color3();
  1658. this.toLinearSpaceToRef(convertedColor);
  1659. return convertedColor;
  1660. };
  1661. /**
  1662. * Converts the Color3 values to linear space and stores the result in "convertedColor"
  1663. * @param convertedColor defines the Color3 object where to store the linear space version
  1664. * @returns the unmodified Color3
  1665. */
  1666. Color3.prototype.toLinearSpaceToRef = function (convertedColor) {
  1667. convertedColor.r = Math.pow(this.r, BABYLON.ToLinearSpace);
  1668. convertedColor.g = Math.pow(this.g, BABYLON.ToLinearSpace);
  1669. convertedColor.b = Math.pow(this.b, BABYLON.ToLinearSpace);
  1670. return this;
  1671. };
  1672. /**
  1673. * Computes a new Color3 converted from the current one to gamma space
  1674. * @returns a new Color3 object
  1675. */
  1676. Color3.prototype.toGammaSpace = function () {
  1677. var convertedColor = new Color3();
  1678. this.toGammaSpaceToRef(convertedColor);
  1679. return convertedColor;
  1680. };
  1681. /**
  1682. * Converts the Color3 values to gamma space and stores the result in "convertedColor"
  1683. * @param convertedColor defines the Color3 object where to store the gamma space version
  1684. * @returns the unmodified Color3
  1685. */
  1686. Color3.prototype.toGammaSpaceToRef = function (convertedColor) {
  1687. convertedColor.r = Math.pow(this.r, BABYLON.ToGammaSpace);
  1688. convertedColor.g = Math.pow(this.g, BABYLON.ToGammaSpace);
  1689. convertedColor.b = Math.pow(this.b, BABYLON.ToGammaSpace);
  1690. return this;
  1691. };
  1692. // Statics
  1693. /**
  1694. * Creates a new Color3 from the string containing valid hexadecimal values
  1695. * @param hex defines a string containing valid hexadecimal values
  1696. * @returns a new Color3 object
  1697. */
  1698. Color3.FromHexString = function (hex) {
  1699. if (hex.substring(0, 1) !== "#" || hex.length !== 7) {
  1700. return new Color3(0, 0, 0);
  1701. }
  1702. var r = parseInt(hex.substring(1, 3), 16);
  1703. var g = parseInt(hex.substring(3, 5), 16);
  1704. var b = parseInt(hex.substring(5, 7), 16);
  1705. return Color3.FromInts(r, g, b);
  1706. };
  1707. /**
  1708. * Creates a new Vector3 from the starting index of the passed array
  1709. * @param array defines the source array
  1710. * @param offset defines an offset in the source array
  1711. * @returns a new Color3 object
  1712. */
  1713. Color3.FromArray = function (array, offset) {
  1714. if (offset === void 0) { offset = 0; }
  1715. return new Color3(array[offset], array[offset + 1], array[offset + 2]);
  1716. };
  1717. /**
  1718. * Creates a new Color3 from integer values (< 256)
  1719. * @param r defines the red component to read from (value between 0 and 255)
  1720. * @param g defines the green component to read from (value between 0 and 255)
  1721. * @param b defines the blue component to read from (value between 0 and 255)
  1722. * @returns a new Color3 object
  1723. */
  1724. Color3.FromInts = function (r, g, b) {
  1725. return new Color3(r / 255.0, g / 255.0, b / 255.0);
  1726. };
  1727. /**
  1728. * Creates a new Color3 with values linearly interpolated of "amount" between the start Color3 and the end Color3
  1729. * @param start defines the start Color3 value
  1730. * @param end defines the end Color3 value
  1731. * @param amount defines the gradient value between start and end
  1732. * @returns a new Color3 object
  1733. */
  1734. Color3.Lerp = function (start, end, amount) {
  1735. var r = start.r + ((end.r - start.r) * amount);
  1736. var g = start.g + ((end.g - start.g) * amount);
  1737. var b = start.b + ((end.b - start.b) * amount);
  1738. return new Color3(r, g, b);
  1739. };
  1740. /**
  1741. * Returns a Color3 value containing a red color
  1742. * @returns a new Color3 object
  1743. */
  1744. Color3.Red = function () { return new Color3(1, 0, 0); };
  1745. /**
  1746. * Returns a Color3 value containing a green color
  1747. * @returns a new Color3 object
  1748. */
  1749. Color3.Green = function () { return new Color3(0, 1, 0); };
  1750. /**
  1751. * Returns a Color3 value containing a blue color
  1752. * @returns a new Color3 object
  1753. */
  1754. Color3.Blue = function () { return new Color3(0, 0, 1); };
  1755. /**
  1756. * Returns a Color3 value containing a black color
  1757. * @returns a new Color3 object
  1758. */
  1759. Color3.Black = function () { return new Color3(0, 0, 0); };
  1760. /**
  1761. * Returns a Color3 value containing a white color
  1762. * @returns a new Color3 object
  1763. */
  1764. Color3.White = function () { return new Color3(1, 1, 1); };
  1765. /**
  1766. * Returns a Color3 value containing a purple color
  1767. * @returns a new Color3 object
  1768. */
  1769. Color3.Purple = function () { return new Color3(0.5, 0, 0.5); };
  1770. /**
  1771. * Returns a Color3 value containing a magenta color
  1772. * @returns a new Color3 object
  1773. */
  1774. Color3.Magenta = function () { return new Color3(1, 0, 1); };
  1775. /**
  1776. * Returns a Color3 value containing a yellow color
  1777. * @returns a new Color3 object
  1778. */
  1779. Color3.Yellow = function () { return new Color3(1, 1, 0); };
  1780. /**
  1781. * Returns a Color3 value containing a gray color
  1782. * @returns a new Color3 object
  1783. */
  1784. Color3.Gray = function () { return new Color3(0.5, 0.5, 0.5); };
  1785. /**
  1786. * Returns a Color3 value containing a teal color
  1787. * @returns a new Color3 object
  1788. */
  1789. Color3.Teal = function () { return new Color3(0, 1.0, 1.0); };
  1790. /**
  1791. * Returns a Color3 value containing a random color
  1792. * @returns a new Color3 object
  1793. */
  1794. Color3.Random = function () { return new Color3(Math.random(), Math.random(), Math.random()); };
  1795. return Color3;
  1796. }());
  1797. BABYLON.Color3 = Color3;
  1798. /**
  1799. * Class used to hold a RBGA color
  1800. */
  1801. var Color4 = /** @class */ (function () {
  1802. /**
  1803. * Creates a new Color4 object from red, green, blue values, all between 0 and 1
  1804. * @param r defines the red component (between 0 and 1, default is 0)
  1805. * @param g defines the green component (between 0 and 1, default is 0)
  1806. * @param b defines the blue component (between 0 and 1, default is 0)
  1807. * @param a defines the alpha component (between 0 and 1, default is 1)
  1808. */
  1809. function Color4(
  1810. /**
  1811. * Defines the red component (between 0 and 1, default is 0)
  1812. */
  1813. r,
  1814. /**
  1815. * Defines the green component (between 0 and 1, default is 0)
  1816. */
  1817. g,
  1818. /**
  1819. * Defines the blue component (between 0 and 1, default is 0)
  1820. */
  1821. b,
  1822. /**
  1823. * Defines the alpha component (between 0 and 1, default is 1)
  1824. */
  1825. a) {
  1826. if (r === void 0) { r = 0; }
  1827. if (g === void 0) { g = 0; }
  1828. if (b === void 0) { b = 0; }
  1829. if (a === void 0) { a = 1; }
  1830. this.r = r;
  1831. this.g = g;
  1832. this.b = b;
  1833. this.a = a;
  1834. }
  1835. // Operators
  1836. /**
  1837. * Adds in place the passed Color4 values to the current Color4 object
  1838. * @param right defines the second operand
  1839. * @returns the current updated Color4 object
  1840. */
  1841. Color4.prototype.addInPlace = function (right) {
  1842. this.r += right.r;
  1843. this.g += right.g;
  1844. this.b += right.b;
  1845. this.a += right.a;
  1846. return this;
  1847. };
  1848. /**
  1849. * Creates a new array populated with 4 numeric elements : red, green, blue, alpha values
  1850. * @returns the new array
  1851. */
  1852. Color4.prototype.asArray = function () {
  1853. var result = new Array();
  1854. this.toArray(result, 0);
  1855. return result;
  1856. };
  1857. /**
  1858. * Stores from the starting index in the passed array the Color4 successive values
  1859. * @param array defines the array where to store the r,g,b components
  1860. * @param index defines an optional index in the target array to define where to start storing values
  1861. * @returns the current Color4 object
  1862. */
  1863. Color4.prototype.toArray = function (array, index) {
  1864. if (index === undefined) {
  1865. index = 0;
  1866. }
  1867. array[index] = this.r;
  1868. array[index + 1] = this.g;
  1869. array[index + 2] = this.b;
  1870. array[index + 3] = this.a;
  1871. return this;
  1872. };
  1873. /**
  1874. * Creates a new Color4 set with the added values of the current Color4 and of the passed one
  1875. * @param right defines the second operand
  1876. * @returns a new Color4 object
  1877. */
  1878. Color4.prototype.add = function (right) {
  1879. return new Color4(this.r + right.r, this.g + right.g, this.b + right.b, this.a + right.a);
  1880. };
  1881. /**
  1882. * Creates a new Color4 set with the subtracted values of the passed one from the current Color4
  1883. * @param right defines the second operand
  1884. * @returns a new Color4 object
  1885. */
  1886. Color4.prototype.subtract = function (right) {
  1887. return new Color4(this.r - right.r, this.g - right.g, this.b - right.b, this.a - right.a);
  1888. };
  1889. /**
  1890. * Subtracts the passed ones from the current Color4 values and stores the results in "result"
  1891. * @param right defines the second operand
  1892. * @param result defines the Color4 object where to store the result
  1893. * @returns the current Color4 object
  1894. */
  1895. Color4.prototype.subtractToRef = function (right, result) {
  1896. result.r = this.r - right.r;
  1897. result.g = this.g - right.g;
  1898. result.b = this.b - right.b;
  1899. result.a = this.a - right.a;
  1900. return this;
  1901. };
  1902. /**
  1903. * Creates a new Color4 with the current Color4 values multiplied by scale
  1904. * @param scale defines the scaling factor to apply
  1905. * @returns a new Color4 object
  1906. */
  1907. Color4.prototype.scale = function (scale) {
  1908. return new Color4(this.r * scale, this.g * scale, this.b * scale, this.a * scale);
  1909. };
  1910. /**
  1911. * Multiplies the current Color4 values by scale and stores the result in "result"
  1912. * @param scale defines the scaling factor to apply
  1913. * @param result defines the Color4 object where to store the result
  1914. * @returns the current Color4.
  1915. */
  1916. Color4.prototype.scaleToRef = function (scale, result) {
  1917. result.r = this.r * scale;
  1918. result.g = this.g * scale;
  1919. result.b = this.b * scale;
  1920. result.a = this.a * scale;
  1921. return this;
  1922. };
  1923. /**
  1924. * Clamps the rgb values by the min and max values and stores the result into "result"
  1925. * @param min defines minimum clamping value (default is 0)
  1926. * @param max defines maximum clamping value (default is 1)
  1927. * @param result defines color to store the result into.
  1928. * @returns the cuurent Color4
  1929. */
  1930. Color4.prototype.clampToRef = function (min, max, result) {
  1931. if (min === void 0) { min = 0; }
  1932. if (max === void 0) { max = 1; }
  1933. result.r = BABYLON.Scalar.Clamp(this.r, min, max);
  1934. result.g = BABYLON.Scalar.Clamp(this.g, min, max);
  1935. result.b = BABYLON.Scalar.Clamp(this.b, min, max);
  1936. result.a = BABYLON.Scalar.Clamp(this.a, min, max);
  1937. return this;
  1938. };
  1939. /**
  1940. * Multipy an Color4 value by another and return a new Color4 object
  1941. * @param color defines the Color4 value to multiply by
  1942. * @returns a new Color4 object
  1943. */
  1944. Color4.prototype.multiply = function (color) {
  1945. return new Color4(this.r * color.r, this.g * color.g, this.b * color.b, this.a * color.a);
  1946. };
  1947. /**
  1948. * Multipy a Color4 value by another and push the result in a reference value
  1949. * @param color defines the Color4 value to multiply by
  1950. * @param result defines the Color4 to fill the result in
  1951. * @returns the result Color4
  1952. */
  1953. Color4.prototype.multiplyToRef = function (color, result) {
  1954. result.r = this.r * color.r;
  1955. result.g = this.g * color.g;
  1956. result.b = this.b * color.b;
  1957. result.a = this.a * color.a;
  1958. return result;
  1959. };
  1960. /**
  1961. * Creates a string with the Color4 current values
  1962. * @returns the string representation of the Color4 object
  1963. */
  1964. Color4.prototype.toString = function () {
  1965. return "{R: " + this.r + " G:" + this.g + " B:" + this.b + " A:" + this.a + "}";
  1966. };
  1967. /**
  1968. * Returns the string "Color4"
  1969. * @returns "Color4"
  1970. */
  1971. Color4.prototype.getClassName = function () {
  1972. return "Color4";
  1973. };
  1974. /**
  1975. * Compute the Color4 hash code
  1976. * @returns an unique number that can be used to hash Color4 objects
  1977. */
  1978. Color4.prototype.getHashCode = function () {
  1979. var hash = this.r || 0;
  1980. hash = (hash * 397) ^ (this.g || 0);
  1981. hash = (hash * 397) ^ (this.b || 0);
  1982. hash = (hash * 397) ^ (this.a || 0);
  1983. return hash;
  1984. };
  1985. /**
  1986. * Creates a new Color4 copied from the current one
  1987. * @returns a new Color4 object
  1988. */
  1989. Color4.prototype.clone = function () {
  1990. return new Color4(this.r, this.g, this.b, this.a);
  1991. };
  1992. /**
  1993. * Copies the passed Color4 values into the current one
  1994. * @param source defines the source Color4 object
  1995. * @returns the current updated Color4 object
  1996. */
  1997. Color4.prototype.copyFrom = function (source) {
  1998. this.r = source.r;
  1999. this.g = source.g;
  2000. this.b = source.b;
  2001. this.a = source.a;
  2002. return this;
  2003. };
  2004. /**
  2005. * Copies the passed float values into the current one
  2006. * @param r defines the red component to read from
  2007. * @param g defines the green component to read from
  2008. * @param b defines the blue component to read from
  2009. * @param a defines the alpha component to read from
  2010. * @returns the current updated Color4 object
  2011. */
  2012. Color4.prototype.copyFromFloats = function (r, g, b, a) {
  2013. this.r = r;
  2014. this.g = g;
  2015. this.b = b;
  2016. this.a = a;
  2017. return this;
  2018. };
  2019. /**
  2020. * Copies the passed float values into the current one
  2021. * @param r defines the red component to read from
  2022. * @param g defines the green component to read from
  2023. * @param b defines the blue component to read from
  2024. * @param a defines the alpha component to read from
  2025. * @returns the current updated Color4 object
  2026. */
  2027. Color4.prototype.set = function (r, g, b, a) {
  2028. return this.copyFromFloats(r, g, b, a);
  2029. };
  2030. /**
  2031. * Compute the Color4 hexadecimal code as a string
  2032. * @returns a string containing the hexadecimal representation of the Color4 object
  2033. */
  2034. Color4.prototype.toHexString = function () {
  2035. var intR = (this.r * 255) | 0;
  2036. var intG = (this.g * 255) | 0;
  2037. var intB = (this.b * 255) | 0;
  2038. var intA = (this.a * 255) | 0;
  2039. return "#" + BABYLON.Scalar.ToHex(intR) + BABYLON.Scalar.ToHex(intG) + BABYLON.Scalar.ToHex(intB) + BABYLON.Scalar.ToHex(intA);
  2040. };
  2041. /**
  2042. * Computes a new Color4 converted from the current one to linear space
  2043. * @returns a new Color4 object
  2044. */
  2045. Color4.prototype.toLinearSpace = function () {
  2046. var convertedColor = new Color4();
  2047. this.toLinearSpaceToRef(convertedColor);
  2048. return convertedColor;
  2049. };
  2050. /**
  2051. * Converts the Color4 values to linear space and stores the result in "convertedColor"
  2052. * @param convertedColor defines the Color4 object where to store the linear space version
  2053. * @returns the unmodified Color4
  2054. */
  2055. Color4.prototype.toLinearSpaceToRef = function (convertedColor) {
  2056. convertedColor.r = Math.pow(this.r, BABYLON.ToLinearSpace);
  2057. convertedColor.g = Math.pow(this.g, BABYLON.ToLinearSpace);
  2058. convertedColor.b = Math.pow(this.b, BABYLON.ToLinearSpace);
  2059. convertedColor.a = this.a;
  2060. return this;
  2061. };
  2062. /**
  2063. * Computes a new Color4 converted from the current one to gamma space
  2064. * @returns a new Color4 object
  2065. */
  2066. Color4.prototype.toGammaSpace = function () {
  2067. var convertedColor = new Color4();
  2068. this.toGammaSpaceToRef(convertedColor);
  2069. return convertedColor;
  2070. };
  2071. /**
  2072. * Converts the Color4 values to gamma space and stores the result in "convertedColor"
  2073. * @param convertedColor defines the Color4 object where to store the gamma space version
  2074. * @returns the unmodified Color4
  2075. */
  2076. Color4.prototype.toGammaSpaceToRef = function (convertedColor) {
  2077. convertedColor.r = Math.pow(this.r, BABYLON.ToGammaSpace);
  2078. convertedColor.g = Math.pow(this.g, BABYLON.ToGammaSpace);
  2079. convertedColor.b = Math.pow(this.b, BABYLON.ToGammaSpace);
  2080. convertedColor.a = this.a;
  2081. return this;
  2082. };
  2083. // Statics
  2084. /**
  2085. * Creates a new Color4 from the string containing valid hexadecimal values
  2086. * @param hex defines a string containing valid hexadecimal values
  2087. * @returns a new Color4 object
  2088. */
  2089. Color4.FromHexString = function (hex) {
  2090. if (hex.substring(0, 1) !== "#" || hex.length !== 9) {
  2091. return new Color4(0.0, 0.0, 0.0, 0.0);
  2092. }
  2093. var r = parseInt(hex.substring(1, 3), 16);
  2094. var g = parseInt(hex.substring(3, 5), 16);
  2095. var b = parseInt(hex.substring(5, 7), 16);
  2096. var a = parseInt(hex.substring(7, 9), 16);
  2097. return Color4.FromInts(r, g, b, a);
  2098. };
  2099. /**
  2100. * Creates a new Color4 object set with the linearly interpolated values of "amount" between the left Color4 object and the right Color4 object
  2101. * @param left defines the start value
  2102. * @param right defines the end value
  2103. * @param amount defines the gradient factor
  2104. * @returns a new Color4 object
  2105. */
  2106. Color4.Lerp = function (left, right, amount) {
  2107. var result = new Color4(0.0, 0.0, 0.0, 0.0);
  2108. Color4.LerpToRef(left, right, amount, result);
  2109. return result;
  2110. };
  2111. /**
  2112. * Set the passed "result" with the linearly interpolated values of "amount" between the left Color4 object and the right Color4 object
  2113. * @param left defines the start value
  2114. * @param right defines the end value
  2115. * @param amount defines the gradient factor
  2116. * @param result defines the Color4 object where to store data
  2117. */
  2118. Color4.LerpToRef = function (left, right, amount, result) {
  2119. result.r = left.r + (right.r - left.r) * amount;
  2120. result.g = left.g + (right.g - left.g) * amount;
  2121. result.b = left.b + (right.b - left.b) * amount;
  2122. result.a = left.a + (right.a - left.a) * amount;
  2123. };
  2124. /**
  2125. * Creates a new Color4 from the starting index element of the passed array
  2126. * @param array defines the source array to read from
  2127. * @param offset defines the offset in the source array
  2128. * @returns a new Color4 object
  2129. */
  2130. Color4.FromArray = function (array, offset) {
  2131. if (offset === void 0) { offset = 0; }
  2132. return new Color4(array[offset], array[offset + 1], array[offset + 2], array[offset + 3]);
  2133. };
  2134. /**
  2135. * Creates a new Color3 from integer values (< 256)
  2136. * @param r defines the red component to read from (value between 0 and 255)
  2137. * @param g defines the green component to read from (value between 0 and 255)
  2138. * @param b defines the blue component to read from (value between 0 and 255)
  2139. * @param a defines the alpha component to read from (value between 0 and 255)
  2140. * @returns a new Color3 object
  2141. */
  2142. Color4.FromInts = function (r, g, b, a) {
  2143. return new Color4(r / 255.0, g / 255.0, b / 255.0, a / 255.0);
  2144. };
  2145. /**
  2146. * Check the content of a given array and convert it to an array containing RGBA data
  2147. * If the original array was already containing count * 4 values then it is returned directly
  2148. * @param colors defines the array to check
  2149. * @param count defines the number of RGBA data to expect
  2150. * @returns an array containing count * 4 values (RGBA)
  2151. */
  2152. Color4.CheckColors4 = function (colors, count) {
  2153. // Check if color3 was used
  2154. if (colors.length === count * 3) {
  2155. var colors4 = [];
  2156. for (var index = 0; index < colors.length; index += 3) {
  2157. var newIndex = (index / 3) * 4;
  2158. colors4[newIndex] = colors[index];
  2159. colors4[newIndex + 1] = colors[index + 1];
  2160. colors4[newIndex + 2] = colors[index + 2];
  2161. colors4[newIndex + 3] = 1.0;
  2162. }
  2163. return colors4;
  2164. }
  2165. return colors;
  2166. };
  2167. return Color4;
  2168. }());
  2169. BABYLON.Color4 = Color4;
  2170. var Vector2 = /** @class */ (function () {
  2171. /**
  2172. * Creates a new Vector2 from the passed x and y coordinates.
  2173. */
  2174. function Vector2(x, y) {
  2175. this.x = x;
  2176. this.y = y;
  2177. }
  2178. /**
  2179. * Returns a string with the Vector2 coordinates.
  2180. */
  2181. Vector2.prototype.toString = function () {
  2182. return "{X: " + this.x + " Y:" + this.y + "}";
  2183. };
  2184. /**
  2185. * Returns the string "Vector2"
  2186. */
  2187. Vector2.prototype.getClassName = function () {
  2188. return "Vector2";
  2189. };
  2190. /**
  2191. * Returns the Vector2 hash code as a number.
  2192. */
  2193. Vector2.prototype.getHashCode = function () {
  2194. var hash = this.x || 0;
  2195. hash = (hash * 397) ^ (this.y || 0);
  2196. return hash;
  2197. };
  2198. // Operators
  2199. /**
  2200. * Sets the Vector2 coordinates in the passed array or Float32Array from the passed index.
  2201. * Returns the Vector2.
  2202. */
  2203. Vector2.prototype.toArray = function (array, index) {
  2204. if (index === void 0) { index = 0; }
  2205. array[index] = this.x;
  2206. array[index + 1] = this.y;
  2207. return this;
  2208. };
  2209. /**
  2210. * Returns a new array with 2 elements : the Vector2 coordinates.
  2211. */
  2212. Vector2.prototype.asArray = function () {
  2213. var result = new Array();
  2214. this.toArray(result, 0);
  2215. return result;
  2216. };
  2217. /**
  2218. * Sets the Vector2 coordinates with the passed Vector2 coordinates.
  2219. * Returns the updated Vector2.
  2220. */
  2221. Vector2.prototype.copyFrom = function (source) {
  2222. this.x = source.x;
  2223. this.y = source.y;
  2224. return this;
  2225. };
  2226. /**
  2227. * Sets the Vector2 coordinates with the passed floats.
  2228. * Returns the updated Vector2.
  2229. */
  2230. Vector2.prototype.copyFromFloats = function (x, y) {
  2231. this.x = x;
  2232. this.y = y;
  2233. return this;
  2234. };
  2235. /**
  2236. * Sets the Vector2 coordinates with the passed floats.
  2237. * Returns the updated Vector2.
  2238. */
  2239. Vector2.prototype.set = function (x, y) {
  2240. return this.copyFromFloats(x, y);
  2241. };
  2242. /**
  2243. * Returns a new Vector2 set with the addition of the current Vector2 and the passed one coordinates.
  2244. */
  2245. Vector2.prototype.add = function (otherVector) {
  2246. return new Vector2(this.x + otherVector.x, this.y + otherVector.y);
  2247. };
  2248. /**
  2249. * Sets the "result" coordinates with the addition of the current Vector2 and the passed one coordinates.
  2250. * Returns the Vector2.
  2251. */
  2252. Vector2.prototype.addToRef = function (otherVector, result) {
  2253. result.x = this.x + otherVector.x;
  2254. result.y = this.y + otherVector.y;
  2255. return this;
  2256. };
  2257. /**
  2258. * Set the Vector2 coordinates by adding the passed Vector2 coordinates.
  2259. * Returns the updated Vector2.
  2260. */
  2261. Vector2.prototype.addInPlace = function (otherVector) {
  2262. this.x += otherVector.x;
  2263. this.y += otherVector.y;
  2264. return this;
  2265. };
  2266. /**
  2267. * Returns a new Vector2 by adding the current Vector2 coordinates to the passed Vector3 x, y coordinates.
  2268. */
  2269. Vector2.prototype.addVector3 = function (otherVector) {
  2270. return new Vector2(this.x + otherVector.x, this.y + otherVector.y);
  2271. };
  2272. /**
  2273. * Returns a new Vector2 set with the subtracted coordinates of the passed one from the current Vector2.
  2274. */
  2275. Vector2.prototype.subtract = function (otherVector) {
  2276. return new Vector2(this.x - otherVector.x, this.y - otherVector.y);
  2277. };
  2278. /**
  2279. * Sets the "result" coordinates with the subtraction of the passed one from the current Vector2 coordinates.
  2280. * Returns the Vector2.
  2281. */
  2282. Vector2.prototype.subtractToRef = function (otherVector, result) {
  2283. result.x = this.x - otherVector.x;
  2284. result.y = this.y - otherVector.y;
  2285. return this;
  2286. };
  2287. /**
  2288. * Sets the current Vector2 coordinates by subtracting from it the passed one coordinates.
  2289. * Returns the updated Vector2.
  2290. */
  2291. Vector2.prototype.subtractInPlace = function (otherVector) {
  2292. this.x -= otherVector.x;
  2293. this.y -= otherVector.y;
  2294. return this;
  2295. };
  2296. /**
  2297. * Multiplies in place the current Vector2 coordinates by the passed ones.
  2298. * Returns the updated Vector2.
  2299. */
  2300. Vector2.prototype.multiplyInPlace = function (otherVector) {
  2301. this.x *= otherVector.x;
  2302. this.y *= otherVector.y;
  2303. return this;
  2304. };
  2305. /**
  2306. * Returns a new Vector2 set with the multiplication of the current Vector2 and the passed one coordinates.
  2307. */
  2308. Vector2.prototype.multiply = function (otherVector) {
  2309. return new Vector2(this.x * otherVector.x, this.y * otherVector.y);
  2310. };
  2311. /**
  2312. * Sets "result" coordinates with the multiplication of the current Vector2 and the passed one coordinates.
  2313. * Returns the Vector2.
  2314. */
  2315. Vector2.prototype.multiplyToRef = function (otherVector, result) {
  2316. result.x = this.x * otherVector.x;
  2317. result.y = this.y * otherVector.y;
  2318. return this;
  2319. };
  2320. /**
  2321. * Returns a new Vector2 set with the Vector2 coordinates multiplied by the passed floats.
  2322. */
  2323. Vector2.prototype.multiplyByFloats = function (x, y) {
  2324. return new Vector2(this.x * x, this.y * y);
  2325. };
  2326. /**
  2327. * Returns a new Vector2 set with the Vector2 coordinates divided by the passed one coordinates.
  2328. */
  2329. Vector2.prototype.divide = function (otherVector) {
  2330. return new Vector2(this.x / otherVector.x, this.y / otherVector.y);
  2331. };
  2332. /**
  2333. * Sets the "result" coordinates with the Vector2 divided by the passed one coordinates.
  2334. * Returns the Vector2.
  2335. */
  2336. Vector2.prototype.divideToRef = function (otherVector, result) {
  2337. result.x = this.x / otherVector.x;
  2338. result.y = this.y / otherVector.y;
  2339. return this;
  2340. };
  2341. /**
  2342. * Divides the current Vector3 coordinates by the passed ones.
  2343. * Returns the updated Vector3.
  2344. */
  2345. Vector2.prototype.divideInPlace = function (otherVector) {
  2346. return this.divideToRef(otherVector, this);
  2347. };
  2348. /**
  2349. * Returns a new Vector2 with current Vector2 negated coordinates.
  2350. */
  2351. Vector2.prototype.negate = function () {
  2352. return new Vector2(-this.x, -this.y);
  2353. };
  2354. /**
  2355. * Multiply the Vector2 coordinates by scale.
  2356. * Returns the updated Vector2.
  2357. */
  2358. Vector2.prototype.scaleInPlace = function (scale) {
  2359. this.x *= scale;
  2360. this.y *= scale;
  2361. return this;
  2362. };
  2363. /**
  2364. * Returns a new Vector2 scaled by "scale" from the current Vector2.
  2365. */
  2366. Vector2.prototype.scale = function (scale) {
  2367. return new Vector2(this.x * scale, this.y * scale);
  2368. };
  2369. /**
  2370. * Boolean : True if the passed vector coordinates strictly equal the current Vector2 ones.
  2371. */
  2372. Vector2.prototype.equals = function (otherVector) {
  2373. return otherVector && this.x === otherVector.x && this.y === otherVector.y;
  2374. };
  2375. /**
  2376. * Boolean : True if the passed vector coordinates are close to the current ones by a distance of epsilon.
  2377. */
  2378. Vector2.prototype.equalsWithEpsilon = function (otherVector, epsilon) {
  2379. if (epsilon === void 0) { epsilon = BABYLON.Epsilon; }
  2380. return otherVector && BABYLON.Scalar.WithinEpsilon(this.x, otherVector.x, epsilon) && BABYLON.Scalar.WithinEpsilon(this.y, otherVector.y, epsilon);
  2381. };
  2382. // Properties
  2383. /**
  2384. * Returns the vector length (float).
  2385. */
  2386. Vector2.prototype.length = function () {
  2387. return Math.sqrt(this.x * this.x + this.y * this.y);
  2388. };
  2389. /**
  2390. * Returns the vector squared length (float);
  2391. */
  2392. Vector2.prototype.lengthSquared = function () {
  2393. return (this.x * this.x + this.y * this.y);
  2394. };
  2395. // Methods
  2396. /**
  2397. * Normalize the vector.
  2398. * Returns the updated Vector2.
  2399. */
  2400. Vector2.prototype.normalize = function () {
  2401. var len = this.length();
  2402. if (len === 0)
  2403. return this;
  2404. var num = 1.0 / len;
  2405. this.x *= num;
  2406. this.y *= num;
  2407. return this;
  2408. };
  2409. /**
  2410. * Returns a new Vector2 copied from the Vector2.
  2411. */
  2412. Vector2.prototype.clone = function () {
  2413. return new Vector2(this.x, this.y);
  2414. };
  2415. // Statics
  2416. /**
  2417. * Returns a new Vector2(0, 0)
  2418. */
  2419. Vector2.Zero = function () {
  2420. return new Vector2(0, 0);
  2421. };
  2422. /**
  2423. * Returns a new Vector2(1, 1)
  2424. */
  2425. Vector2.One = function () {
  2426. return new Vector2(1, 1);
  2427. };
  2428. /**
  2429. * Returns a new Vector2 set from the passed index element of the passed array.
  2430. */
  2431. Vector2.FromArray = function (array, offset) {
  2432. if (offset === void 0) { offset = 0; }
  2433. return new Vector2(array[offset], array[offset + 1]);
  2434. };
  2435. /**
  2436. * Sets "result" from the passed index element of the passed array.
  2437. */
  2438. Vector2.FromArrayToRef = function (array, offset, result) {
  2439. result.x = array[offset];
  2440. result.y = array[offset + 1];
  2441. };
  2442. /**
  2443. * Retuns a new Vector2 located for "amount" (float) on the CatmullRom spline defined by the passed four Vector2.
  2444. */
  2445. Vector2.CatmullRom = function (value1, value2, value3, value4, amount) {
  2446. var squared = amount * amount;
  2447. var cubed = amount * squared;
  2448. var x = 0.5 * ((((2.0 * value2.x) + ((-value1.x + value3.x) * amount)) +
  2449. (((((2.0 * value1.x) - (5.0 * value2.x)) + (4.0 * value3.x)) - value4.x) * squared)) +
  2450. ((((-value1.x + (3.0 * value2.x)) - (3.0 * value3.x)) + value4.x) * cubed));
  2451. var y = 0.5 * ((((2.0 * value2.y) + ((-value1.y + value3.y) * amount)) +
  2452. (((((2.0 * value1.y) - (5.0 * value2.y)) + (4.0 * value3.y)) - value4.y) * squared)) +
  2453. ((((-value1.y + (3.0 * value2.y)) - (3.0 * value3.y)) + value4.y) * cubed));
  2454. return new Vector2(x, y);
  2455. };
  2456. /**
  2457. * 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".
  2458. * If a coordinate of "value" is lower than "min" coordinates, the returned Vector2 is given this "min" coordinate.
  2459. * If a coordinate of "value" is greater than "max" coordinates, the returned Vector2 is given this "max" coordinate.
  2460. */
  2461. Vector2.Clamp = function (value, min, max) {
  2462. var x = value.x;
  2463. x = (x > max.x) ? max.x : x;
  2464. x = (x < min.x) ? min.x : x;
  2465. var y = value.y;
  2466. y = (y > max.y) ? max.y : y;
  2467. y = (y < min.y) ? min.y : y;
  2468. return new Vector2(x, y);
  2469. };
  2470. /**
  2471. * Returns a new Vector2 located for "amount" (float) on the Hermite spline defined by the vectors "value1", "value3", "tangent1", "tangent2".
  2472. */
  2473. Vector2.Hermite = function (value1, tangent1, value2, tangent2, amount) {
  2474. var squared = amount * amount;
  2475. var cubed = amount * squared;
  2476. var part1 = ((2.0 * cubed) - (3.0 * squared)) + 1.0;
  2477. var part2 = (-2.0 * cubed) + (3.0 * squared);
  2478. var part3 = (cubed - (2.0 * squared)) + amount;
  2479. var part4 = cubed - squared;
  2480. var x = (((value1.x * part1) + (value2.x * part2)) + (tangent1.x * part3)) + (tangent2.x * part4);
  2481. var y = (((value1.y * part1) + (value2.y * part2)) + (tangent1.y * part3)) + (tangent2.y * part4);
  2482. return new Vector2(x, y);
  2483. };
  2484. /**
  2485. * Returns a new Vector2 located for "amount" (float) on the linear interpolation between the vector "start" adn the vector "end".
  2486. */
  2487. Vector2.Lerp = function (start, end, amount) {
  2488. var x = start.x + ((end.x - start.x) * amount);
  2489. var y = start.y + ((end.y - start.y) * amount);
  2490. return new Vector2(x, y);
  2491. };
  2492. /**
  2493. * Returns the dot product (float) of the vector "left" and the vector "right".
  2494. */
  2495. Vector2.Dot = function (left, right) {
  2496. return left.x * right.x + left.y * right.y;
  2497. };
  2498. /**
  2499. * Returns a new Vector2 equal to the normalized passed vector.
  2500. */
  2501. Vector2.Normalize = function (vector) {
  2502. var newVector = vector.clone();
  2503. newVector.normalize();
  2504. return newVector;
  2505. };
  2506. /**
  2507. * Returns a new Vecto2 set with the minimal coordinate values from the "left" and "right" vectors.
  2508. */
  2509. Vector2.Minimize = function (left, right) {
  2510. var x = (left.x < right.x) ? left.x : right.x;
  2511. var y = (left.y < right.y) ? left.y : right.y;
  2512. return new Vector2(x, y);
  2513. };
  2514. /**
  2515. * Returns a new Vecto2 set with the maximal coordinate values from the "left" and "right" vectors.
  2516. */
  2517. Vector2.Maximize = function (left, right) {
  2518. var x = (left.x > right.x) ? left.x : right.x;
  2519. var y = (left.y > right.y) ? left.y : right.y;
  2520. return new Vector2(x, y);
  2521. };
  2522. /**
  2523. * Returns a new Vecto2 set with the transformed coordinates of the passed vector by the passed transformation matrix.
  2524. */
  2525. Vector2.Transform = function (vector, transformation) {
  2526. var r = Vector2.Zero();
  2527. Vector2.TransformToRef(vector, transformation, r);
  2528. return r;
  2529. };
  2530. /**
  2531. * Transforms the passed vector coordinates by the passed transformation matrix and stores the result in the vector "result" coordinates.
  2532. */
  2533. Vector2.TransformToRef = function (vector, transformation, result) {
  2534. var x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]) + transformation.m[12];
  2535. var y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]) + transformation.m[13];
  2536. result.x = x;
  2537. result.y = y;
  2538. };
  2539. /**
  2540. * Boolean : True if the point "p" is in the triangle defined by the vertors "p0", "p1", "p2"
  2541. */
  2542. Vector2.PointInTriangle = function (p, p0, p1, p2) {
  2543. var a = 1 / 2 * (-p1.y * p2.x + p0.y * (-p1.x + p2.x) + p0.x * (p1.y - p2.y) + p1.x * p2.y);
  2544. var sign = a < 0 ? -1 : 1;
  2545. var s = (p0.y * p2.x - p0.x * p2.y + (p2.y - p0.y) * p.x + (p0.x - p2.x) * p.y) * sign;
  2546. var t = (p0.x * p1.y - p0.y * p1.x + (p0.y - p1.y) * p.x + (p1.x - p0.x) * p.y) * sign;
  2547. return s > 0 && t > 0 && (s + t) < 2 * a * sign;
  2548. };
  2549. /**
  2550. * Returns the distance (float) between the vectors "value1" and "value2".
  2551. */
  2552. Vector2.Distance = function (value1, value2) {
  2553. return Math.sqrt(Vector2.DistanceSquared(value1, value2));
  2554. };
  2555. /**
  2556. * Returns the squared distance (float) between the vectors "value1" and "value2".
  2557. */
  2558. Vector2.DistanceSquared = function (value1, value2) {
  2559. var x = value1.x - value2.x;
  2560. var y = value1.y - value2.y;
  2561. return (x * x) + (y * y);
  2562. };
  2563. /**
  2564. * Returns a new Vecto2 located at the center of the vectors "value1" and "value2".
  2565. */
  2566. Vector2.Center = function (value1, value2) {
  2567. var center = value1.add(value2);
  2568. center.scaleInPlace(0.5);
  2569. return center;
  2570. };
  2571. /**
  2572. * Returns the shortest distance (float) between the point "p" and the segment defined by the two points "segA" and "segB".
  2573. */
  2574. Vector2.DistanceOfPointFromSegment = function (p, segA, segB) {
  2575. var l2 = Vector2.DistanceSquared(segA, segB);
  2576. if (l2 === 0.0) {
  2577. return Vector2.Distance(p, segA);
  2578. }
  2579. var v = segB.subtract(segA);
  2580. var t = Math.max(0, Math.min(1, Vector2.Dot(p.subtract(segA), v) / l2));
  2581. var proj = segA.add(v.multiplyByFloats(t, t));
  2582. return Vector2.Distance(p, proj);
  2583. };
  2584. return Vector2;
  2585. }());
  2586. BABYLON.Vector2 = Vector2;
  2587. /**
  2588. * Classed used to store (x,y,z) vector representation
  2589. * A Vector3 is the main object used in 3D geometry
  2590. * It can represent etiher the coordinates of a point the space, either a direction
  2591. * Reminder: Babylon.js uses a left handed forward facing system
  2592. */
  2593. var Vector3 = /** @class */ (function () {
  2594. /**
  2595. * Creates a new Vector3 object from the passed x, y, z (floats) coordinates.
  2596. * @param x defines the first coordinates (on X axis)
  2597. * @param y defines the second coordinates (on Y axis)
  2598. * @param z defines the third coordinates (on Z axis)
  2599. */
  2600. function Vector3(
  2601. /**
  2602. * Defines the first coordinates (on X axis)
  2603. */
  2604. x,
  2605. /**
  2606. * Defines the second coordinates (on Y axis)
  2607. */
  2608. y,
  2609. /**
  2610. * Defines the third coordinates (on Z axis)
  2611. */
  2612. z) {
  2613. this.x = x;
  2614. this.y = y;
  2615. this.z = z;
  2616. }
  2617. /**
  2618. * Creates a string representation of the Vector3
  2619. * @returns a string with the Vector3 coordinates.
  2620. */
  2621. Vector3.prototype.toString = function () {
  2622. return "{X: " + this.x + " Y:" + this.y + " Z:" + this.z + "}";
  2623. };
  2624. /**
  2625. * Gets the class name
  2626. * @returns the string "Vector3"
  2627. */
  2628. Vector3.prototype.getClassName = function () {
  2629. return "Vector3";
  2630. };
  2631. /**
  2632. * Creates the Vector3 hash code
  2633. * @returns a number which tends to be unique between Vector3 instances
  2634. */
  2635. Vector3.prototype.getHashCode = function () {
  2636. var hash = this.x || 0;
  2637. hash = (hash * 397) ^ (this.y || 0);
  2638. hash = (hash * 397) ^ (this.z || 0);
  2639. return hash;
  2640. };
  2641. // Operators
  2642. /**
  2643. * Creates an array containing three elements : the coordinates of the Vector3
  2644. * @returns a new array of numbers
  2645. */
  2646. Vector3.prototype.asArray = function () {
  2647. var result = [];
  2648. this.toArray(result, 0);
  2649. return result;
  2650. };
  2651. /**
  2652. * Populates the passed array or Float32Array from the passed index with the successive coordinates of the Vector3
  2653. * @param array defines the destination array
  2654. * @param index defines the offset in the destination array
  2655. * @returns the current Vector3
  2656. */
  2657. Vector3.prototype.toArray = function (array, index) {
  2658. if (index === void 0) { index = 0; }
  2659. array[index] = this.x;
  2660. array[index + 1] = this.y;
  2661. array[index + 2] = this.z;
  2662. return this;
  2663. };
  2664. /**
  2665. * Converts the current Vector3 into a quaternion (considering that the Vector3 contains Euler angles representation of a rotation)
  2666. * @returns a new Quaternion object, computed from the Vector3 coordinates
  2667. */
  2668. Vector3.prototype.toQuaternion = function () {
  2669. var result = new Quaternion(0.0, 0.0, 0.0, 1.0);
  2670. var cosxPlusz = Math.cos((this.x + this.z) * 0.5);
  2671. var sinxPlusz = Math.sin((this.x + this.z) * 0.5);
  2672. var coszMinusx = Math.cos((this.z - this.x) * 0.5);
  2673. var sinzMinusx = Math.sin((this.z - this.x) * 0.5);
  2674. var cosy = Math.cos(this.y * 0.5);
  2675. var siny = Math.sin(this.y * 0.5);
  2676. result.x = coszMinusx * siny;
  2677. result.y = -sinzMinusx * siny;
  2678. result.z = sinxPlusz * cosy;
  2679. result.w = cosxPlusz * cosy;
  2680. return result;
  2681. };
  2682. /**
  2683. * Adds the passed vector to the current Vector3
  2684. * @param otherVector defines the second operand
  2685. * @returns the current updated Vector3
  2686. */
  2687. Vector3.prototype.addInPlace = function (otherVector) {
  2688. this.x += otherVector.x;
  2689. this.y += otherVector.y;
  2690. this.z += otherVector.z;
  2691. return this;
  2692. };
  2693. /**
  2694. * Gets a new Vector3, result of the addition the current Vector3 and the passed vector
  2695. * @param otherVector defines the second operand
  2696. * @returns the resulting Vector3
  2697. */
  2698. Vector3.prototype.add = function (otherVector) {
  2699. return new Vector3(this.x + otherVector.x, this.y + otherVector.y, this.z + otherVector.z);
  2700. };
  2701. /**
  2702. * Adds the current Vector3 to the passed one and stores the result in the vector "result"
  2703. * @param otherVector defines the second operand
  2704. * @param result defines the Vector3 object where to store the result
  2705. * @returns the current Vector3
  2706. */
  2707. Vector3.prototype.addToRef = function (otherVector, result) {
  2708. result.x = this.x + otherVector.x;
  2709. result.y = this.y + otherVector.y;
  2710. result.z = this.z + otherVector.z;
  2711. return this;
  2712. };
  2713. /**
  2714. * Subtract the passed vector from the current Vector3
  2715. * @param otherVector defines the second operand
  2716. * @returns the current updated Vector3
  2717. */
  2718. Vector3.prototype.subtractInPlace = function (otherVector) {
  2719. this.x -= otherVector.x;
  2720. this.y -= otherVector.y;
  2721. this.z -= otherVector.z;
  2722. return this;
  2723. };
  2724. /**
  2725. * Returns a new Vector3, result of the subtraction of the passed vector from the current Vector3
  2726. * @param otherVector defines the second operand
  2727. * @returns the resulting Vector3
  2728. */
  2729. Vector3.prototype.subtract = function (otherVector) {
  2730. return new Vector3(this.x - otherVector.x, this.y - otherVector.y, this.z - otherVector.z);
  2731. };
  2732. /**
  2733. * Subtracts the passed vector from the current Vector3 and stores the result in the vector "result".
  2734. * @param otherVector defines the second operand
  2735. * @param result defines the Vector3 object where to store the result
  2736. * @returns the current Vector3
  2737. */
  2738. Vector3.prototype.subtractToRef = function (otherVector, result) {
  2739. result.x = this.x - otherVector.x;
  2740. result.y = this.y - otherVector.y;
  2741. result.z = this.z - otherVector.z;
  2742. return this;
  2743. };
  2744. /**
  2745. * Returns a new Vector3 set with the subtraction of the passed floats from the current Vector3 coordinates
  2746. * @param x defines the x coordinate of the operand
  2747. * @param y defines the y coordinate of the operand
  2748. * @param z defines the z coordinate of the operand
  2749. * @returns the resulting Vector3
  2750. */
  2751. Vector3.prototype.subtractFromFloats = function (x, y, z) {
  2752. return new Vector3(this.x - x, this.y - y, this.z - z);
  2753. };
  2754. /**
  2755. * Subtracts the passed floats from the current Vector3 coordinates and set the passed vector "result" with this result
  2756. * @param x defines the x coordinate of the operand
  2757. * @param y defines the y coordinate of the operand
  2758. * @param z defines the z coordinate of the operand
  2759. * @param result defines the Vector3 object where to store the result
  2760. * @returns the current Vector3
  2761. */
  2762. Vector3.prototype.subtractFromFloatsToRef = function (x, y, z, result) {
  2763. result.x = this.x - x;
  2764. result.y = this.y - y;
  2765. result.z = this.z - z;
  2766. return this;
  2767. };
  2768. /**
  2769. * Gets a new Vector3 set with the current Vector3 negated coordinates
  2770. * @returns a new Vector3
  2771. */
  2772. Vector3.prototype.negate = function () {
  2773. return new Vector3(-this.x, -this.y, -this.z);
  2774. };
  2775. /**
  2776. * Multiplies the Vector3 coordinates by the float "scale"
  2777. * @param scale defines the multiplier factor
  2778. * @returns the current updated Vector3
  2779. */
  2780. Vector3.prototype.scaleInPlace = function (scale) {
  2781. this.x *= scale;
  2782. this.y *= scale;
  2783. this.z *= scale;
  2784. return this;
  2785. };
  2786. /**
  2787. * Returns a new Vector3 set with the current Vector3 coordinates multiplied by the float "scale"
  2788. * @param scale defines the multiplier factor
  2789. * @returns a new Vector3
  2790. */
  2791. Vector3.prototype.scale = function (scale) {
  2792. return new Vector3(this.x * scale, this.y * scale, this.z * scale);
  2793. };
  2794. /**
  2795. * Multiplies the current Vector3 coordinates by the float "scale" and stores the result in the passed vector "result" coordinates
  2796. * @param scale defines the multiplier factor
  2797. * @param result defines the Vector3 object where to store the result
  2798. * @returns the current Vector3
  2799. */
  2800. Vector3.prototype.scaleToRef = function (scale, result) {
  2801. result.x = this.x * scale;
  2802. result.y = this.y * scale;
  2803. result.z = this.z * scale;
  2804. return this;
  2805. };
  2806. /**
  2807. * Returns true if the current Vector3 and the passed vector coordinates are strictly equal
  2808. * @param otherVector defines the second operand
  2809. * @returns true if both vectors are equals
  2810. */
  2811. Vector3.prototype.equals = function (otherVector) {
  2812. return otherVector && this.x === otherVector.x && this.y === otherVector.y && this.z === otherVector.z;
  2813. };
  2814. /**
  2815. * Returns true if the current Vector3 and the passed vector coordinates are distant less than epsilon
  2816. * @param otherVector defines the second operand
  2817. * @param epsilon defines the minimal distance to define values as equals
  2818. * @returns true if both vectors are distant less than epsilon
  2819. */
  2820. Vector3.prototype.equalsWithEpsilon = function (otherVector, epsilon) {
  2821. if (epsilon === void 0) { epsilon = BABYLON.Epsilon; }
  2822. 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);
  2823. };
  2824. /**
  2825. * Returns true if the current Vector3 coordinates equals the passed floats
  2826. * @param x defines the x coordinate of the operand
  2827. * @param y defines the y coordinate of the operand
  2828. * @param z defines the z coordinate of the operand
  2829. * @returns true if both vectors are equals
  2830. */
  2831. Vector3.prototype.equalsToFloats = function (x, y, z) {
  2832. return this.x === x && this.y === y && this.z === z;
  2833. };
  2834. /**
  2835. * Multiplies the current Vector3 coordinates by the passed ones
  2836. * @param otherVector defines the second operand
  2837. * @returns the current updated Vector3
  2838. */
  2839. Vector3.prototype.multiplyInPlace = function (otherVector) {
  2840. this.x *= otherVector.x;
  2841. this.y *= otherVector.y;
  2842. this.z *= otherVector.z;
  2843. return this;
  2844. };
  2845. /**
  2846. * Returns a new Vector3, result of the multiplication of the current Vector3 by the passed vector
  2847. * @param otherVector defines the second operand
  2848. * @returns the new Vector3
  2849. */
  2850. Vector3.prototype.multiply = function (otherVector) {
  2851. return new Vector3(this.x * otherVector.x, this.y * otherVector.y, this.z * otherVector.z);
  2852. };
  2853. /**
  2854. * Multiplies the current Vector3 by the passed one and stores the result in the passed vector "result"
  2855. * @param otherVector defines the second operand
  2856. * @param result defines the Vector3 object where to store the result
  2857. * @returns the current Vector3
  2858. */
  2859. Vector3.prototype.multiplyToRef = function (otherVector, result) {
  2860. result.x = this.x * otherVector.x;
  2861. result.y = this.y * otherVector.y;
  2862. result.z = this.z * otherVector.z;
  2863. return this;
  2864. };
  2865. /**
  2866. * Returns a new Vector3 set with the result of the mulliplication of the current Vector3 coordinates by the passed floats
  2867. * @param x defines the x coordinate of the operand
  2868. * @param y defines the y coordinate of the operand
  2869. * @param z defines the z coordinate of the operand
  2870. * @returns the new Vector3
  2871. */
  2872. Vector3.prototype.multiplyByFloats = function (x, y, z) {
  2873. return new Vector3(this.x * x, this.y * y, this.z * z);
  2874. };
  2875. /**
  2876. * Returns a new Vector3 set with the result of the division of the current Vector3 coordinates by the passed ones
  2877. * @param otherVector defines the second operand
  2878. * @returns the new Vector3
  2879. */
  2880. Vector3.prototype.divide = function (otherVector) {
  2881. return new Vector3(this.x / otherVector.x, this.y / otherVector.y, this.z / otherVector.z);
  2882. };
  2883. /**
  2884. * Divides the current Vector3 coordinates by the passed ones and stores the result in the passed vector "result"
  2885. * @param otherVector defines the second operand
  2886. * @param result defines the Vector3 object where to store the result
  2887. * @returns the current Vector3
  2888. */
  2889. Vector3.prototype.divideToRef = function (otherVector, result) {
  2890. result.x = this.x / otherVector.x;
  2891. result.y = this.y / otherVector.y;
  2892. result.z = this.z / otherVector.z;
  2893. return this;
  2894. };
  2895. /**
  2896. * Divides the current Vector3 coordinates by the passed ones.
  2897. * @param otherVector defines the second operand
  2898. * @returns the current updated Vector3
  2899. */
  2900. Vector3.prototype.divideInPlace = function (otherVector) {
  2901. return this.divideToRef(otherVector, this);
  2902. };
  2903. /**
  2904. * Updates the current Vector3 with the minimal coordinate values between its and the passed vector ones
  2905. * @param other defines the second operand
  2906. * @returns the current updated Vector3
  2907. */
  2908. Vector3.prototype.minimizeInPlace = function (other) {
  2909. if (other.x < this.x)
  2910. this.x = other.x;
  2911. if (other.y < this.y)
  2912. this.y = other.y;
  2913. if (other.z < this.z)
  2914. this.z = other.z;
  2915. return this;
  2916. };
  2917. /**
  2918. * Updates the current Vector3 with the maximal coordinate values between its and the passed vector ones.
  2919. * @param other defines the second operand
  2920. * @returns the current updated Vector3
  2921. */
  2922. Vector3.prototype.maximizeInPlace = function (other) {
  2923. if (other.x > this.x)
  2924. this.x = other.x;
  2925. if (other.y > this.y)
  2926. this.y = other.y;
  2927. if (other.z > this.z)
  2928. this.z = other.z;
  2929. return this;
  2930. };
  2931. Object.defineProperty(Vector3.prototype, "isNonUniform", {
  2932. /**
  2933. * Gets a boolean indicating that the vector is non uniform meaning x, y or z are not all the same
  2934. */
  2935. get: function () {
  2936. var absX = Math.abs(this.x);
  2937. var absY = Math.abs(this.y);
  2938. if (absX !== absY) {
  2939. return true;
  2940. }
  2941. var absZ = Math.abs(this.z);
  2942. if (absX !== absZ) {
  2943. return true;
  2944. }
  2945. if (absY !== absZ) {
  2946. return true;
  2947. }
  2948. return false;
  2949. },
  2950. enumerable: true,
  2951. configurable: true
  2952. });
  2953. // Properties
  2954. /**
  2955. * Gets the length of the Vector3
  2956. * @returns the length of the Vecto3
  2957. */
  2958. Vector3.prototype.length = function () {
  2959. return Math.sqrt(this.x * this.x + this.y * this.y + this.z * this.z);
  2960. };
  2961. /**
  2962. * Gets the squared length of the Vector3
  2963. * @returns squared length of the Vector3
  2964. */
  2965. Vector3.prototype.lengthSquared = function () {
  2966. return (this.x * this.x + this.y * this.y + this.z * this.z);
  2967. };
  2968. /**
  2969. * Normalize the current Vector3.
  2970. * Please note that this is an in place operation.
  2971. * @returns the current updated Vector3
  2972. */
  2973. Vector3.prototype.normalize = function () {
  2974. var len = this.length();
  2975. if (len === 0 || len === 1.0)
  2976. return this;
  2977. var num = 1.0 / len;
  2978. this.x *= num;
  2979. this.y *= num;
  2980. this.z *= num;
  2981. return this;
  2982. };
  2983. /**
  2984. * Normalize the current Vector3 to a new vector
  2985. * @returns the new Vector3
  2986. */
  2987. Vector3.prototype.normalizeToNew = function () {
  2988. var normalized = new Vector3(0, 0, 0);
  2989. this.normalizeToRef(normalized);
  2990. return normalized;
  2991. };
  2992. /**
  2993. * Normalize the current Vector3 to the reference
  2994. * @param reference define the Vector3 to update
  2995. * @returns the updated Vector3
  2996. */
  2997. Vector3.prototype.normalizeToRef = function (reference) {
  2998. var len = this.length();
  2999. if (len === 0 || len === 1.0) {
  3000. reference.set(this.x, this.y, this.z);
  3001. return reference;
  3002. }
  3003. var scale = 1.0 / len;
  3004. this.scaleToRef(scale, reference);
  3005. return reference;
  3006. };
  3007. /**
  3008. * Creates a new Vector3 copied from the current Vector3
  3009. * @returns the new Vector3
  3010. */
  3011. Vector3.prototype.clone = function () {
  3012. return new Vector3(this.x, this.y, this.z);
  3013. };
  3014. /**
  3015. * Copies the passed vector coordinates to the current Vector3 ones
  3016. * @param source defines the source Vector3
  3017. * @returns the current updated Vector3
  3018. */
  3019. Vector3.prototype.copyFrom = function (source) {
  3020. this.x = source.x;
  3021. this.y = source.y;
  3022. this.z = source.z;
  3023. return this;
  3024. };
  3025. /**
  3026. * Copies the passed floats to the current Vector3 coordinates
  3027. * @param x defines the x coordinate of the operand
  3028. * @param y defines the y coordinate of the operand
  3029. * @param z defines the z coordinate of the operand
  3030. * @returns the current updated Vector3
  3031. */
  3032. Vector3.prototype.copyFromFloats = function (x, y, z) {
  3033. this.x = x;
  3034. this.y = y;
  3035. this.z = z;
  3036. return this;
  3037. };
  3038. /**
  3039. * Copies the passed floats to the current Vector3 coordinates
  3040. * @param x defines the x coordinate of the operand
  3041. * @param y defines the y coordinate of the operand
  3042. * @param z defines the z coordinate of the operand
  3043. * @returns the current updated Vector3
  3044. */
  3045. Vector3.prototype.set = function (x, y, z) {
  3046. return this.copyFromFloats(x, y, z);
  3047. };
  3048. // Statics
  3049. /**
  3050. * Get the clip factor between two vectors
  3051. * @param vector0 defines the first operand
  3052. * @param vector1 defines the second operand
  3053. * @param axis defines the axis to use
  3054. * @param size defines the size along the axis
  3055. * @returns the clip factor
  3056. */
  3057. Vector3.GetClipFactor = function (vector0, vector1, axis, size) {
  3058. var d0 = Vector3.Dot(vector0, axis) - size;
  3059. var d1 = Vector3.Dot(vector1, axis) - size;
  3060. var s = d0 / (d0 - d1);
  3061. return s;
  3062. };
  3063. /**
  3064. * Get angle between two vectors
  3065. * @param vector0 angle between vector0 and vector1
  3066. * @param vector1 angle between vector0 and vector1
  3067. * @param normal direction of the normal
  3068. * @return the angle between vector0 and vector1
  3069. */
  3070. Vector3.GetAngleBetweenVectors = function (vector0, vector1, normal) {
  3071. var v0 = vector0.clone().normalize();
  3072. var v1 = vector1.clone().normalize();
  3073. var dot = Vector3.Dot(v0, v1);
  3074. var n = Vector3.Cross(v0, v1);
  3075. if (Vector3.Dot(n, normal) > 0) {
  3076. return Math.acos(dot);
  3077. }
  3078. return -Math.acos(dot);
  3079. };
  3080. /**
  3081. * Returns a new Vector3 set from the index "offset" of the passed array
  3082. * @param array defines the source array
  3083. * @param offset defines the offset in the source array
  3084. * @returns the new Vector3
  3085. */
  3086. Vector3.FromArray = function (array, offset) {
  3087. if (!offset) {
  3088. offset = 0;
  3089. }
  3090. return new Vector3(array[offset], array[offset + 1], array[offset + 2]);
  3091. };
  3092. /**
  3093. * Returns a new Vector3 set from the index "offset" of the passed Float32Array
  3094. * This function is deprecated. Use FromArray instead
  3095. * @param array defines the source array
  3096. * @param offset defines the offset in the source array
  3097. * @returns the new Vector3
  3098. */
  3099. Vector3.FromFloatArray = function (array, offset) {
  3100. return Vector3.FromArray(array, offset);
  3101. };
  3102. /**
  3103. * Sets the passed vector "result" with the element values from the index "offset" of the passed array
  3104. * @param array defines the source array
  3105. * @param offset defines the offset in the source array
  3106. * @param result defines the Vector3 where to store the result
  3107. */
  3108. Vector3.FromArrayToRef = function (array, offset, result) {
  3109. result.x = array[offset];
  3110. result.y = array[offset + 1];
  3111. result.z = array[offset + 2];
  3112. };
  3113. /**
  3114. * Sets the passed vector "result" with the element values from the index "offset" of the passed Float32Array
  3115. * This function is deprecated. Use FromArrayToRef instead.
  3116. * @param array defines the source array
  3117. * @param offset defines the offset in the source array
  3118. * @param result defines the Vector3 where to store the result
  3119. */
  3120. Vector3.FromFloatArrayToRef = function (array, offset, result) {
  3121. return Vector3.FromArrayToRef(array, offset, result);
  3122. };
  3123. /**
  3124. * Sets the passed vector "result" with the passed floats.
  3125. * @param x defines the x coordinate of the source
  3126. * @param y defines the y coordinate of the source
  3127. * @param z defines the z coordinate of the source
  3128. * @param result defines the Vector3 where to store the result
  3129. */
  3130. Vector3.FromFloatsToRef = function (x, y, z, result) {
  3131. result.x = x;
  3132. result.y = y;
  3133. result.z = z;
  3134. };
  3135. /**
  3136. * Returns a new Vector3 set to (0.0, 0.0, 0.0)
  3137. * @returns a new empty Vector3
  3138. */
  3139. Vector3.Zero = function () {
  3140. return new Vector3(0.0, 0.0, 0.0);
  3141. };
  3142. /**
  3143. * Returns a new Vector3 set to (1.0, 1.0, 1.0)
  3144. * @returns a new unit Vector3
  3145. */
  3146. Vector3.One = function () {
  3147. return new Vector3(1.0, 1.0, 1.0);
  3148. };
  3149. /**
  3150. * Returns a new Vector3 set to (0.0, 1.0, 0.0)
  3151. * @returns a new up Vector3
  3152. */
  3153. Vector3.Up = function () {
  3154. return new Vector3(0.0, 1.0, 0.0);
  3155. };
  3156. /**
  3157. * Returns a new Vector3 set to (0.0, 0.0, 1.0)
  3158. * @returns a new forward Vector3
  3159. */
  3160. Vector3.Forward = function () {
  3161. return new Vector3(0.0, 0.0, 1.0);
  3162. };
  3163. /**
  3164. * Returns a new Vector3 set to (1.0, 0.0, 0.0)
  3165. * @returns a new right Vector3
  3166. */
  3167. Vector3.Right = function () {
  3168. return new Vector3(1.0, 0.0, 0.0);
  3169. };
  3170. /**
  3171. * Returns a new Vector3 set to (-1.0, 0.0, 0.0)
  3172. * @returns a new left Vector3
  3173. */
  3174. Vector3.Left = function () {
  3175. return new Vector3(-1.0, 0.0, 0.0);
  3176. };
  3177. /**
  3178. * Returns a new Vector3 set with the result of the transformation by the passed matrix of the passed vector.
  3179. * This method computes tranformed coordinates only, not transformed direction vectors (ie. it takes translation in account)
  3180. * @param vector defines the Vector3 to transform
  3181. * @param transformation defines the transformation matrix
  3182. * @returns the transformed Vector3
  3183. */
  3184. Vector3.TransformCoordinates = function (vector, transformation) {
  3185. var result = Vector3.Zero();
  3186. Vector3.TransformCoordinatesToRef(vector, transformation, result);
  3187. return result;
  3188. };
  3189. /**
  3190. * Sets the passed vector "result" coordinates with the result of the transformation by the passed matrix of the passed vector
  3191. * This method computes tranformed coordinates only, not transformed direction vectors (ie. it takes translation in account)
  3192. * @param vector defines the Vector3 to transform
  3193. * @param transformation defines the transformation matrix
  3194. * @param result defines the Vector3 where to store the result
  3195. */
  3196. Vector3.TransformCoordinatesToRef = function (vector, transformation, result) {
  3197. var x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]) + (vector.z * transformation.m[8]) + transformation.m[12];
  3198. var y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]) + (vector.z * transformation.m[9]) + transformation.m[13];
  3199. var z = (vector.x * transformation.m[2]) + (vector.y * transformation.m[6]) + (vector.z * transformation.m[10]) + transformation.m[14];
  3200. var w = (vector.x * transformation.m[3]) + (vector.y * transformation.m[7]) + (vector.z * transformation.m[11]) + transformation.m[15];
  3201. result.x = x / w;
  3202. result.y = y / w;
  3203. result.z = z / w;
  3204. };
  3205. /**
  3206. * Sets the passed vector "result" coordinates with the result of the transformation by the passed matrix of the passed floats (x, y, z)
  3207. * This method computes tranformed coordinates only, not transformed direction vectors
  3208. * @param x define the x coordinate of the source vector
  3209. * @param y define the y coordinate of the source vector
  3210. * @param z define the z coordinate of the source vector
  3211. * @param transformation defines the transformation matrix
  3212. * @param result defines the Vector3 where to store the result
  3213. */
  3214. Vector3.TransformCoordinatesFromFloatsToRef = function (x, y, z, transformation, result) {
  3215. var rx = (x * transformation.m[0]) + (y * transformation.m[4]) + (z * transformation.m[8]) + transformation.m[12];
  3216. var ry = (x * transformation.m[1]) + (y * transformation.m[5]) + (z * transformation.m[9]) + transformation.m[13];
  3217. var rz = (x * transformation.m[2]) + (y * transformation.m[6]) + (z * transformation.m[10]) + transformation.m[14];
  3218. var rw = (x * transformation.m[3]) + (y * transformation.m[7]) + (z * transformation.m[11]) + transformation.m[15];
  3219. result.x = rx / rw;
  3220. result.y = ry / rw;
  3221. result.z = rz / rw;
  3222. };
  3223. /**
  3224. * Returns a new Vector3 set with the result of the normal transformation by the passed matrix of the passed vector
  3225. * This methods computes transformed normalized direction vectors only (ie. it does not apply translation)
  3226. * @param vector defines the Vector3 to transform
  3227. * @param transformation defines the transformation matrix
  3228. * @returns the new Vector3
  3229. */
  3230. Vector3.TransformNormal = function (vector, transformation) {
  3231. var result = Vector3.Zero();
  3232. Vector3.TransformNormalToRef(vector, transformation, result);
  3233. return result;
  3234. };
  3235. /**
  3236. * Sets the passed vector "result" with the result of the normal transformation by the passed matrix of the passed vector
  3237. * This methods computes transformed normalized direction vectors only (ie. it does not apply translation)
  3238. * @param vector defines the Vector3 to transform
  3239. * @param transformation defines the transformation matrix
  3240. * @param result defines the Vector3 where to store the result
  3241. */
  3242. Vector3.TransformNormalToRef = function (vector, transformation, result) {
  3243. var x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]) + (vector.z * transformation.m[8]);
  3244. var y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]) + (vector.z * transformation.m[9]);
  3245. var z = (vector.x * transformation.m[2]) + (vector.y * transformation.m[6]) + (vector.z * transformation.m[10]);
  3246. result.x = x;
  3247. result.y = y;
  3248. result.z = z;
  3249. };
  3250. /**
  3251. * Sets the passed vector "result" with the result of the normal transformation by the passed matrix of the passed floats (x, y, z)
  3252. * This methods computes transformed normalized direction vectors only (ie. it does not apply translation)
  3253. * @param x define the x coordinate of the source vector
  3254. * @param y define the y coordinate of the source vector
  3255. * @param z define the z coordinate of the source vector
  3256. * @param transformation defines the transformation matrix
  3257. * @param result defines the Vector3 where to store the result
  3258. */
  3259. Vector3.TransformNormalFromFloatsToRef = function (x, y, z, transformation, result) {
  3260. result.x = (x * transformation.m[0]) + (y * transformation.m[4]) + (z * transformation.m[8]);
  3261. result.y = (x * transformation.m[1]) + (y * transformation.m[5]) + (z * transformation.m[9]);
  3262. result.z = (x * transformation.m[2]) + (y * transformation.m[6]) + (z * transformation.m[10]);
  3263. };
  3264. /**
  3265. * Returns a new Vector3 located for "amount" on the CatmullRom interpolation spline defined by the vectors "value1", "value2", "value3", "value4"
  3266. * @param value1 defines the first control point
  3267. * @param value2 defines the second control point
  3268. * @param value3 defines the third control point
  3269. * @param value4 defines the fourth control point
  3270. * @param amount defines the amount on the spline to use
  3271. * @returns the new Vector3
  3272. */
  3273. Vector3.CatmullRom = function (value1, value2, value3, value4, amount) {
  3274. var squared = amount * amount;
  3275. var cubed = amount * squared;
  3276. var x = 0.5 * ((((2.0 * value2.x) + ((-value1.x + value3.x) * amount)) +
  3277. (((((2.0 * value1.x) - (5.0 * value2.x)) + (4.0 * value3.x)) - value4.x) * squared)) +
  3278. ((((-value1.x + (3.0 * value2.x)) - (3.0 * value3.x)) + value4.x) * cubed));
  3279. var y = 0.5 * ((((2.0 * value2.y) + ((-value1.y + value3.y) * amount)) +
  3280. (((((2.0 * value1.y) - (5.0 * value2.y)) + (4.0 * value3.y)) - value4.y) * squared)) +
  3281. ((((-value1.y + (3.0 * value2.y)) - (3.0 * value3.y)) + value4.y) * cubed));
  3282. var z = 0.5 * ((((2.0 * value2.z) + ((-value1.z + value3.z) * amount)) +
  3283. (((((2.0 * value1.z) - (5.0 * value2.z)) + (4.0 * value3.z)) - value4.z) * squared)) +
  3284. ((((-value1.z + (3.0 * value2.z)) - (3.0 * value3.z)) + value4.z) * cubed));
  3285. return new Vector3(x, y, z);
  3286. };
  3287. /**
  3288. * 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"
  3289. * If a coordinate value of "value" is lower than one of the "min" coordinate, then this "value" coordinate is set with the "min" one
  3290. * If a coordinate value of "value" is greater than one of the "max" coordinate, then this "value" coordinate is set with the "max" one
  3291. * @param value defines the current value
  3292. * @param min defines the lower range value
  3293. * @param max defines the upper range value
  3294. * @returns the new Vector3
  3295. */
  3296. Vector3.Clamp = function (value, min, max) {
  3297. var x = value.x;
  3298. x = (x > max.x) ? max.x : x;
  3299. x = (x < min.x) ? min.x : x;
  3300. var y = value.y;
  3301. y = (y > max.y) ? max.y : y;
  3302. y = (y < min.y) ? min.y : y;
  3303. var z = value.z;
  3304. z = (z > max.z) ? max.z : z;
  3305. z = (z < min.z) ? min.z : z;
  3306. return new Vector3(x, y, z);
  3307. };
  3308. /**
  3309. * Returns a new Vector3 located for "amount" (float) on the Hermite interpolation spline defined by the vectors "value1", "tangent1", "value2", "tangent2"
  3310. * @param value1 defines the first control point
  3311. * @param tangent1 defines the first tangent vector
  3312. * @param value2 defines the second control point
  3313. * @param tangent2 defines the second tangent vector
  3314. * @param amount defines the amount on the interpolation spline (between 0 and 1)
  3315. * @returns the new Vector3
  3316. */
  3317. Vector3.Hermite = function (value1, tangent1, value2, tangent2, amount) {
  3318. var squared = amount * amount;
  3319. var cubed = amount * squared;
  3320. var part1 = ((2.0 * cubed) - (3.0 * squared)) + 1.0;
  3321. var part2 = (-2.0 * cubed) + (3.0 * squared);
  3322. var part3 = (cubed - (2.0 * squared)) + amount;
  3323. var part4 = cubed - squared;
  3324. var x = (((value1.x * part1) + (value2.x * part2)) + (tangent1.x * part3)) + (tangent2.x * part4);
  3325. var y = (((value1.y * part1) + (value2.y * part2)) + (tangent1.y * part3)) + (tangent2.y * part4);
  3326. var z = (((value1.z * part1) + (value2.z * part2)) + (tangent1.z * part3)) + (tangent2.z * part4);
  3327. return new Vector3(x, y, z);
  3328. };
  3329. /**
  3330. * Returns a new Vector3 located for "amount" (float) on the linear interpolation between the vectors "start" and "end"
  3331. * @param start defines the start value
  3332. * @param end defines the end value
  3333. * @param amount max defines amount between both (between 0 and 1)
  3334. * @returns the new Vector3
  3335. */
  3336. Vector3.Lerp = function (start, end, amount) {
  3337. var result = new Vector3(0, 0, 0);
  3338. Vector3.LerpToRef(start, end, amount, result);
  3339. return result;
  3340. };
  3341. /**
  3342. * Sets the passed vector "result" with the result of the linear interpolation from the vector "start" for "amount" to the vector "end"
  3343. * @param start defines the start value
  3344. * @param end defines the end value
  3345. * @param amount max defines amount between both (between 0 and 1)
  3346. * @param result defines the Vector3 where to store the result
  3347. */
  3348. Vector3.LerpToRef = function (start, end, amount, result) {
  3349. result.x = start.x + ((end.x - start.x) * amount);
  3350. result.y = start.y + ((end.y - start.y) * amount);
  3351. result.z = start.z + ((end.z - start.z) * amount);
  3352. };
  3353. /**
  3354. * Returns the dot product (float) between the vectors "left" and "right"
  3355. * @param left defines the left operand
  3356. * @param right defines the right operand
  3357. * @returns the dot product
  3358. */
  3359. Vector3.Dot = function (left, right) {
  3360. return (left.x * right.x + left.y * right.y + left.z * right.z);
  3361. };
  3362. /**
  3363. * Returns a new Vector3 as the cross product of the vectors "left" and "right"
  3364. * The cross product is then orthogonal to both "left" and "right"
  3365. * @param left defines the left operand
  3366. * @param right defines the right operand
  3367. * @returns the cross product
  3368. */
  3369. Vector3.Cross = function (left, right) {
  3370. var result = Vector3.Zero();
  3371. Vector3.CrossToRef(left, right, result);
  3372. return result;
  3373. };
  3374. /**
  3375. * Sets the passed vector "result" with the cross product of "left" and "right"
  3376. * The cross product is then orthogonal to both "left" and "right"
  3377. * @param left defines the left operand
  3378. * @param right defines the right operand
  3379. * @param result defines the Vector3 where to store the result
  3380. */
  3381. Vector3.CrossToRef = function (left, right, result) {
  3382. MathTmp.Vector3[0].x = left.y * right.z - left.z * right.y;
  3383. MathTmp.Vector3[0].y = left.z * right.x - left.x * right.z;
  3384. MathTmp.Vector3[0].z = left.x * right.y - left.y * right.x;
  3385. result.copyFrom(MathTmp.Vector3[0]);
  3386. };
  3387. /**
  3388. * Returns a new Vector3 as the normalization of the passed vector
  3389. * @param vector defines the Vector3 to normalize
  3390. * @returns the new Vector3
  3391. */
  3392. Vector3.Normalize = function (vector) {
  3393. var result = Vector3.Zero();
  3394. Vector3.NormalizeToRef(vector, result);
  3395. return result;
  3396. };
  3397. /**
  3398. * Sets the passed vector "result" with the normalization of the passed first vector
  3399. * @param vector defines the Vector3 to normalize
  3400. * @param result defines the Vector3 where to store the result
  3401. */
  3402. Vector3.NormalizeToRef = function (vector, result) {
  3403. result.copyFrom(vector);
  3404. result.normalize();
  3405. };
  3406. /**
  3407. * Project a Vector3 onto screen space
  3408. * @param vector defines the Vector3 to project
  3409. * @param world defines the world matrix to use
  3410. * @param transform defines the transform (view x projection) matrix to use
  3411. * @param viewport defines the screen viewport to use
  3412. * @returns the new Vector3
  3413. */
  3414. Vector3.Project = function (vector, world, transform, viewport) {
  3415. var cw = viewport.width;
  3416. var ch = viewport.height;
  3417. var cx = viewport.x;
  3418. var cy = viewport.y;
  3419. var viewportMatrix = Vector3._viewportMatrixCache ? Vector3._viewportMatrixCache : (Vector3._viewportMatrixCache = new Matrix());
  3420. 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);
  3421. var matrix = MathTmp.Matrix[0];
  3422. world.multiplyToRef(transform, matrix);
  3423. matrix.multiplyToRef(viewportMatrix, matrix);
  3424. return Vector3.TransformCoordinates(vector, matrix);
  3425. };
  3426. /**
  3427. * Unproject from screen space to object space
  3428. * @param source defines the screen space Vector3 to use
  3429. * @param viewportWidth defines the current width of the viewport
  3430. * @param viewportHeight defines the current height of the viewport
  3431. * @param world defines the world matrix to use (can be set to Identity to go to world space)
  3432. * @param transform defines the transform (view x projection) matrix to use
  3433. * @returns the new Vector3
  3434. */
  3435. Vector3.UnprojectFromTransform = function (source, viewportWidth, viewportHeight, world, transform) {
  3436. var matrix = MathTmp.Matrix[0];
  3437. world.multiplyToRef(transform, matrix);
  3438. matrix.invert();
  3439. source.x = source.x / viewportWidth * 2 - 1;
  3440. source.y = -(source.y / viewportHeight * 2 - 1);
  3441. var vector = Vector3.TransformCoordinates(source, matrix);
  3442. var num = source.x * matrix.m[3] + source.y * matrix.m[7] + source.z * matrix.m[11] + matrix.m[15];
  3443. if (BABYLON.Scalar.WithinEpsilon(num, 1.0)) {
  3444. vector = vector.scale(1.0 / num);
  3445. }
  3446. return vector;
  3447. };
  3448. /**
  3449. * Unproject from screen space to object space
  3450. * @param source defines the screen space Vector3 to use
  3451. * @param viewportWidth defines the current width of the viewport
  3452. * @param viewportHeight defines the current height of the viewport
  3453. * @param world defines the world matrix to use (can be set to Identity to go to world space)
  3454. * @param view defines the view matrix to use
  3455. * @param projection defines the projection matrix to use
  3456. * @returns the new Vector3
  3457. */
  3458. Vector3.Unproject = function (source, viewportWidth, viewportHeight, world, view, projection) {
  3459. var result = Vector3.Zero();
  3460. Vector3.UnprojectToRef(source, viewportWidth, viewportHeight, world, view, projection, result);
  3461. return result;
  3462. };
  3463. /**
  3464. * Unproject from screen space to object space
  3465. * @param source defines the screen space Vector3 to use
  3466. * @param viewportWidth defines the current width of the viewport
  3467. * @param viewportHeight defines the current height of the viewport
  3468. * @param world defines the world matrix to use (can be set to Identity to go to world space)
  3469. * @param view defines the view matrix to use
  3470. * @param projection defines the projection matrix to use
  3471. * @param result defines the Vector3 where to store the result
  3472. */
  3473. Vector3.UnprojectToRef = function (source, viewportWidth, viewportHeight, world, view, projection, result) {
  3474. Vector3.UnprojectFloatsToRef(source.x, source.y, source.z, viewportWidth, viewportHeight, world, view, projection, result);
  3475. };
  3476. /**
  3477. * Unproject from screen space to object space
  3478. * @param sourceX defines the screen space x coordinate to use
  3479. * @param sourceY defines the screen space y coordinate to use
  3480. * @param sourceZ defines the screen space z coordinate to use
  3481. * @param viewportWidth defines the current width of the viewport
  3482. * @param viewportHeight defines the current height of the viewport
  3483. * @param world defines the world matrix to use (can be set to Identity to go to world space)
  3484. * @param view defines the view matrix to use
  3485. * @param projection defines the projection matrix to use
  3486. * @param result defines the Vector3 where to store the result
  3487. */
  3488. Vector3.UnprojectFloatsToRef = function (sourceX, sourceY, sourceZ, viewportWidth, viewportHeight, world, view, projection, result) {
  3489. var matrix = MathTmp.Matrix[0];
  3490. world.multiplyToRef(view, matrix);
  3491. matrix.multiplyToRef(projection, matrix);
  3492. matrix.invert();
  3493. var screenSource = MathTmp.Vector3[0];
  3494. screenSource.x = sourceX / viewportWidth * 2 - 1;
  3495. screenSource.y = -(sourceY / viewportHeight * 2 - 1);
  3496. screenSource.z = 2 * sourceZ - 1.0;
  3497. Vector3.TransformCoordinatesToRef(screenSource, matrix, result);
  3498. var num = screenSource.x * matrix.m[3] + screenSource.y * matrix.m[7] + screenSource.z * matrix.m[11] + matrix.m[15];
  3499. if (BABYLON.Scalar.WithinEpsilon(num, 1.0)) {
  3500. result.scaleInPlace(1.0 / num);
  3501. }
  3502. };
  3503. /**
  3504. * Gets the minimal coordinate values between two Vector3
  3505. * @param left defines the first operand
  3506. * @param right defines the second operand
  3507. * @returns the new Vector3
  3508. */
  3509. Vector3.Minimize = function (left, right) {
  3510. var min = left.clone();
  3511. min.minimizeInPlace(right);
  3512. return min;
  3513. };
  3514. /**
  3515. * Gets the maximal coordinate values between two Vector3
  3516. * @param left defines the first operand
  3517. * @param right defines the second operand
  3518. * @returns the new Vector3
  3519. */
  3520. Vector3.Maximize = function (left, right) {
  3521. var max = left.clone();
  3522. max.maximizeInPlace(right);
  3523. return max;
  3524. };
  3525. /**
  3526. * Returns the distance between the vectors "value1" and "value2"
  3527. * @param value1 defines the first operand
  3528. * @param value2 defines the second operand
  3529. * @returns the distance
  3530. */
  3531. Vector3.Distance = function (value1, value2) {
  3532. return Math.sqrt(Vector3.DistanceSquared(value1, value2));
  3533. };
  3534. /**
  3535. * Returns the squared distance between the vectors "value1" and "value2"
  3536. * @param value1 defines the first operand
  3537. * @param value2 defines the second operand
  3538. * @returns the squared distance
  3539. */
  3540. Vector3.DistanceSquared = function (value1, value2) {
  3541. var x = value1.x - value2.x;
  3542. var y = value1.y - value2.y;
  3543. var z = value1.z - value2.z;
  3544. return (x * x) + (y * y) + (z * z);
  3545. };
  3546. /**
  3547. * Returns a new Vector3 located at the center between "value1" and "value2"
  3548. * @param value1 defines the first operand
  3549. * @param value2 defines the second operand
  3550. * @returns the new Vector3
  3551. */
  3552. Vector3.Center = function (value1, value2) {
  3553. var center = value1.add(value2);
  3554. center.scaleInPlace(0.5);
  3555. return center;
  3556. };
  3557. /**
  3558. * Given three orthogonal normalized left-handed oriented Vector3 axis in space (target system),
  3559. * RotationFromAxis() returns the rotation Euler angles (ex : rotation.x, rotation.y, rotation.z) to apply
  3560. * to something in order to rotate it from its local system to the given target system
  3561. * Note: axis1, axis2 and axis3 are normalized during this operation
  3562. * @param axis1 defines the first axis
  3563. * @param axis2 defines the second axis
  3564. * @param axis3 defines the third axis
  3565. * @returns a new Vector3
  3566. */
  3567. Vector3.RotationFromAxis = function (axis1, axis2, axis3) {
  3568. var rotation = Vector3.Zero();
  3569. Vector3.RotationFromAxisToRef(axis1, axis2, axis3, rotation);
  3570. return rotation;
  3571. };
  3572. /**
  3573. * The same than RotationFromAxis but updates the passed ref Vector3 parameter instead of returning a new Vector3
  3574. * @param axis1 defines the first axis
  3575. * @param axis2 defines the second axis
  3576. * @param axis3 defines the third axis
  3577. * @param ref defines the Vector3 where to store the result
  3578. */
  3579. Vector3.RotationFromAxisToRef = function (axis1, axis2, axis3, ref) {
  3580. var quat = MathTmp.Quaternion[0];
  3581. Quaternion.RotationQuaternionFromAxisToRef(axis1, axis2, axis3, quat);
  3582. quat.toEulerAnglesToRef(ref);
  3583. };
  3584. return Vector3;
  3585. }());
  3586. BABYLON.Vector3 = Vector3;
  3587. //Vector4 class created for EulerAngle class conversion to Quaternion
  3588. var Vector4 = /** @class */ (function () {
  3589. /**
  3590. * Creates a Vector4 object from the passed floats.
  3591. */
  3592. function Vector4(x, y, z, w) {
  3593. this.x = x;
  3594. this.y = y;
  3595. this.z = z;
  3596. this.w = w;
  3597. }
  3598. /**
  3599. * Returns the string with the Vector4 coordinates.
  3600. */
  3601. Vector4.prototype.toString = function () {
  3602. return "{X: " + this.x + " Y:" + this.y + " Z:" + this.z + " W:" + this.w + "}";
  3603. };
  3604. /**
  3605. * Returns the string "Vector4".
  3606. */
  3607. Vector4.prototype.getClassName = function () {
  3608. return "Vector4";
  3609. };
  3610. /**
  3611. * Returns the Vector4 hash code.
  3612. */
  3613. Vector4.prototype.getHashCode = function () {
  3614. var hash = this.x || 0;
  3615. hash = (hash * 397) ^ (this.y || 0);
  3616. hash = (hash * 397) ^ (this.z || 0);
  3617. hash = (hash * 397) ^ (this.w || 0);
  3618. return hash;
  3619. };
  3620. // Operators
  3621. /**
  3622. * Returns a new array populated with 4 elements : the Vector4 coordinates.
  3623. */
  3624. Vector4.prototype.asArray = function () {
  3625. var result = new Array();
  3626. this.toArray(result, 0);
  3627. return result;
  3628. };
  3629. /**
  3630. * Populates the passed array from the passed index with the Vector4 coordinates.
  3631. * Returns the Vector4.
  3632. */
  3633. Vector4.prototype.toArray = function (array, index) {
  3634. if (index === undefined) {
  3635. index = 0;
  3636. }
  3637. array[index] = this.x;
  3638. array[index + 1] = this.y;
  3639. array[index + 2] = this.z;
  3640. array[index + 3] = this.w;
  3641. return this;
  3642. };
  3643. /**
  3644. * Adds the passed vector to the current Vector4.
  3645. * Returns the updated Vector4.
  3646. */
  3647. Vector4.prototype.addInPlace = function (otherVector) {
  3648. this.x += otherVector.x;
  3649. this.y += otherVector.y;
  3650. this.z += otherVector.z;
  3651. this.w += otherVector.w;
  3652. return this;
  3653. };
  3654. /**
  3655. * Returns a new Vector4 as the result of the addition of the current Vector4 and the passed one.
  3656. */
  3657. Vector4.prototype.add = function (otherVector) {
  3658. return new Vector4(this.x + otherVector.x, this.y + otherVector.y, this.z + otherVector.z, this.w + otherVector.w);
  3659. };
  3660. /**
  3661. * Updates the passed vector "result" with the result of the addition of the current Vector4 and the passed one.
  3662. * Returns the current Vector4.
  3663. */
  3664. Vector4.prototype.addToRef = function (otherVector, result) {
  3665. result.x = this.x + otherVector.x;
  3666. result.y = this.y + otherVector.y;
  3667. result.z = this.z + otherVector.z;
  3668. result.w = this.w + otherVector.w;
  3669. return this;
  3670. };
  3671. /**
  3672. * Subtract in place the passed vector from the current Vector4.
  3673. * Returns the updated Vector4.
  3674. */
  3675. Vector4.prototype.subtractInPlace = function (otherVector) {
  3676. this.x -= otherVector.x;
  3677. this.y -= otherVector.y;
  3678. this.z -= otherVector.z;
  3679. this.w -= otherVector.w;
  3680. return this;
  3681. };
  3682. /**
  3683. * Returns a new Vector4 with the result of the subtraction of the passed vector from the current Vector4.
  3684. */
  3685. Vector4.prototype.subtract = function (otherVector) {
  3686. return new Vector4(this.x - otherVector.x, this.y - otherVector.y, this.z - otherVector.z, this.w - otherVector.w);
  3687. };
  3688. /**
  3689. * Sets the passed vector "result" with the result of the subtraction of the passed vector from the current Vector4.
  3690. * Returns the current Vector4.
  3691. */
  3692. Vector4.prototype.subtractToRef = function (otherVector, result) {
  3693. result.x = this.x - otherVector.x;
  3694. result.y = this.y - otherVector.y;
  3695. result.z = this.z - otherVector.z;
  3696. result.w = this.w - otherVector.w;
  3697. return this;
  3698. };
  3699. /**
  3700. * Returns a new Vector4 set with the result of the subtraction of the passed floats from the current Vector4 coordinates.
  3701. */
  3702. Vector4.prototype.subtractFromFloats = function (x, y, z, w) {
  3703. return new Vector4(this.x - x, this.y - y, this.z - z, this.w - w);
  3704. };
  3705. /**
  3706. * Sets the passed vector "result" set with the result of the subtraction of the passed floats from the current Vector4 coordinates.
  3707. * Returns the current Vector4.
  3708. */
  3709. Vector4.prototype.subtractFromFloatsToRef = function (x, y, z, w, result) {
  3710. result.x = this.x - x;
  3711. result.y = this.y - y;
  3712. result.z = this.z - z;
  3713. result.w = this.w - w;
  3714. return this;
  3715. };
  3716. /**
  3717. * Returns a new Vector4 set with the current Vector4 negated coordinates.
  3718. */
  3719. Vector4.prototype.negate = function () {
  3720. return new Vector4(-this.x, -this.y, -this.z, -this.w);
  3721. };
  3722. /**
  3723. * Multiplies the current Vector4 coordinates by scale (float).
  3724. * Returns the updated Vector4.
  3725. */
  3726. Vector4.prototype.scaleInPlace = function (scale) {
  3727. this.x *= scale;
  3728. this.y *= scale;
  3729. this.z *= scale;
  3730. this.w *= scale;
  3731. return this;
  3732. };
  3733. /**
  3734. * Returns a new Vector4 set with the current Vector4 coordinates multiplied by scale (float).
  3735. */
  3736. Vector4.prototype.scale = function (scale) {
  3737. return new Vector4(this.x * scale, this.y * scale, this.z * scale, this.w * scale);
  3738. };
  3739. /**
  3740. * Sets the passed vector "result" with the current Vector4 coordinates multiplied by scale (float).
  3741. * Returns the current Vector4.
  3742. */
  3743. Vector4.prototype.scaleToRef = function (scale, result) {
  3744. result.x = this.x * scale;
  3745. result.y = this.y * scale;
  3746. result.z = this.z * scale;
  3747. result.w = this.w * scale;
  3748. return this;
  3749. };
  3750. /**
  3751. * Boolean : True if the current Vector4 coordinates are stricly equal to the passed ones.
  3752. */
  3753. Vector4.prototype.equals = function (otherVector) {
  3754. return otherVector && this.x === otherVector.x && this.y === otherVector.y && this.z === otherVector.z && this.w === otherVector.w;
  3755. };
  3756. /**
  3757. * Boolean : True if the current Vector4 coordinates are each beneath the distance "epsilon" from the passed vector ones.
  3758. */
  3759. Vector4.prototype.equalsWithEpsilon = function (otherVector, epsilon) {
  3760. if (epsilon === void 0) { epsilon = BABYLON.Epsilon; }
  3761. return otherVector
  3762. && BABYLON.Scalar.WithinEpsilon(this.x, otherVector.x, epsilon)
  3763. && BABYLON.Scalar.WithinEpsilon(this.y, otherVector.y, epsilon)
  3764. && BABYLON.Scalar.WithinEpsilon(this.z, otherVector.z, epsilon)
  3765. && BABYLON.Scalar.WithinEpsilon(this.w, otherVector.w, epsilon);
  3766. };
  3767. /**
  3768. * Boolean : True if the passed floats are strictly equal to the current Vector4 coordinates.
  3769. */
  3770. Vector4.prototype.equalsToFloats = function (x, y, z, w) {
  3771. return this.x === x && this.y === y && this.z === z && this.w === w;
  3772. };
  3773. /**
  3774. * Multiplies in place the current Vector4 by the passed one.
  3775. * Returns the updated Vector4.
  3776. */
  3777. Vector4.prototype.multiplyInPlace = function (otherVector) {
  3778. this.x *= otherVector.x;
  3779. this.y *= otherVector.y;
  3780. this.z *= otherVector.z;
  3781. this.w *= otherVector.w;
  3782. return this;
  3783. };
  3784. /**
  3785. * Returns a new Vector4 set with the multiplication result of the current Vector4 and the passed one.
  3786. */
  3787. Vector4.prototype.multiply = function (otherVector) {
  3788. return new Vector4(this.x * otherVector.x, this.y * otherVector.y, this.z * otherVector.z, this.w * otherVector.w);
  3789. };
  3790. /**
  3791. * Updates the passed vector "result" with the multiplication result of the current Vector4 and the passed one.
  3792. * Returns the current Vector4.
  3793. */
  3794. Vector4.prototype.multiplyToRef = function (otherVector, result) {
  3795. result.x = this.x * otherVector.x;
  3796. result.y = this.y * otherVector.y;
  3797. result.z = this.z * otherVector.z;
  3798. result.w = this.w * otherVector.w;
  3799. return this;
  3800. };
  3801. /**
  3802. * Returns a new Vector4 set with the multiplication result of the passed floats and the current Vector4 coordinates.
  3803. */
  3804. Vector4.prototype.multiplyByFloats = function (x, y, z, w) {
  3805. return new Vector4(this.x * x, this.y * y, this.z * z, this.w * w);
  3806. };
  3807. /**
  3808. * Returns a new Vector4 set with the division result of the current Vector4 by the passed one.
  3809. */
  3810. Vector4.prototype.divide = function (otherVector) {
  3811. return new Vector4(this.x / otherVector.x, this.y / otherVector.y, this.z / otherVector.z, this.w / otherVector.w);
  3812. };
  3813. /**
  3814. * Updates the passed vector "result" with the division result of the current Vector4 by the passed one.
  3815. * Returns the current Vector4.
  3816. */
  3817. Vector4.prototype.divideToRef = function (otherVector, result) {
  3818. result.x = this.x / otherVector.x;
  3819. result.y = this.y / otherVector.y;
  3820. result.z = this.z / otherVector.z;
  3821. result.w = this.w / otherVector.w;
  3822. return this;
  3823. };
  3824. /**
  3825. * Divides the current Vector3 coordinates by the passed ones.
  3826. * @returns the updated Vector3.
  3827. */
  3828. Vector4.prototype.divideInPlace = function (otherVector) {
  3829. return this.divideToRef(otherVector, this);
  3830. };
  3831. /**
  3832. * Updates the Vector4 coordinates with the minimum values between its own and the passed vector ones
  3833. * @param other defines the second operand
  3834. * @returns the current updated Vector4
  3835. */
  3836. Vector4.prototype.minimizeInPlace = function (other) {
  3837. if (other.x < this.x)
  3838. this.x = other.x;
  3839. if (other.y < this.y)
  3840. this.y = other.y;
  3841. if (other.z < this.z)
  3842. this.z = other.z;
  3843. if (other.w < this.w)
  3844. this.w = other.w;
  3845. return this;
  3846. };
  3847. /**
  3848. * Updates the Vector4 coordinates with the maximum values between its own and the passed vector ones
  3849. * @param other defines the second operand
  3850. * @returns the current updated Vector4
  3851. */
  3852. Vector4.prototype.maximizeInPlace = function (other) {
  3853. if (other.x > this.x)
  3854. this.x = other.x;
  3855. if (other.y > this.y)
  3856. this.y = other.y;
  3857. if (other.z > this.z)
  3858. this.z = other.z;
  3859. if (other.w > this.w)
  3860. this.w = other.w;
  3861. return this;
  3862. };
  3863. // Properties
  3864. /**
  3865. * Returns the Vector4 length (float).
  3866. */
  3867. Vector4.prototype.length = function () {
  3868. return Math.sqrt(this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w);
  3869. };
  3870. /**
  3871. * Returns the Vector4 squared length (float).
  3872. */
  3873. Vector4.prototype.lengthSquared = function () {
  3874. return (this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w);
  3875. };
  3876. // Methods
  3877. /**
  3878. * Normalizes in place the Vector4.
  3879. * Returns the updated Vector4.
  3880. */
  3881. Vector4.prototype.normalize = function () {
  3882. var len = this.length();
  3883. if (len === 0)
  3884. return this;
  3885. var num = 1.0 / len;
  3886. this.x *= num;
  3887. this.y *= num;
  3888. this.z *= num;
  3889. this.w *= num;
  3890. return this;
  3891. };
  3892. /**
  3893. * Returns a new Vector3 from the Vector4 (x, y, z) coordinates.
  3894. */
  3895. Vector4.prototype.toVector3 = function () {
  3896. return new Vector3(this.x, this.y, this.z);
  3897. };
  3898. /**
  3899. * Returns a new Vector4 copied from the current one.
  3900. */
  3901. Vector4.prototype.clone = function () {
  3902. return new Vector4(this.x, this.y, this.z, this.w);
  3903. };
  3904. /**
  3905. * Updates the current Vector4 with the passed one coordinates.
  3906. * Returns the updated Vector4.
  3907. */
  3908. Vector4.prototype.copyFrom = function (source) {
  3909. this.x = source.x;
  3910. this.y = source.y;
  3911. this.z = source.z;
  3912. this.w = source.w;
  3913. return this;
  3914. };
  3915. /**
  3916. * Updates the current Vector4 coordinates with the passed floats.
  3917. * Returns the updated Vector4.
  3918. */
  3919. Vector4.prototype.copyFromFloats = function (x, y, z, w) {
  3920. this.x = x;
  3921. this.y = y;
  3922. this.z = z;
  3923. this.w = w;
  3924. return this;
  3925. };
  3926. /**
  3927. * Updates the current Vector4 coordinates with the passed floats.
  3928. * Returns the updated Vector4.
  3929. */
  3930. Vector4.prototype.set = function (x, y, z, w) {
  3931. return this.copyFromFloats(x, y, z, w);
  3932. };
  3933. // Statics
  3934. /**
  3935. * Returns a new Vector4 set from the starting index of the passed array.
  3936. */
  3937. Vector4.FromArray = function (array, offset) {
  3938. if (!offset) {
  3939. offset = 0;
  3940. }
  3941. return new Vector4(array[offset], array[offset + 1], array[offset + 2], array[offset + 3]);
  3942. };
  3943. /**
  3944. * Updates the passed vector "result" from the starting index of the passed array.
  3945. */
  3946. Vector4.FromArrayToRef = function (array, offset, result) {
  3947. result.x = array[offset];
  3948. result.y = array[offset + 1];
  3949. result.z = array[offset + 2];
  3950. result.w = array[offset + 3];
  3951. };
  3952. /**
  3953. * Updates the passed vector "result" from the starting index of the passed Float32Array.
  3954. */
  3955. Vector4.FromFloatArrayToRef = function (array, offset, result) {
  3956. Vector4.FromArrayToRef(array, offset, result);
  3957. };
  3958. /**
  3959. * Updates the passed vector "result" coordinates from the passed floats.
  3960. */
  3961. Vector4.FromFloatsToRef = function (x, y, z, w, result) {
  3962. result.x = x;
  3963. result.y = y;
  3964. result.z = z;
  3965. result.w = w;
  3966. };
  3967. /**
  3968. * Returns a new Vector4 set to (0.0, 0.0, 0.0, 0.0)
  3969. */
  3970. Vector4.Zero = function () {
  3971. return new Vector4(0.0, 0.0, 0.0, 0.0);
  3972. };
  3973. /**
  3974. * Returns a new Vector4 set to (1.0, 1.0, 1.0, 1.0)
  3975. */
  3976. Vector4.One = function () {
  3977. return new Vector4(1.0, 1.0, 1.0, 1.0);
  3978. };
  3979. /**
  3980. * Returns a new normalized Vector4 from the passed one.
  3981. */
  3982. Vector4.Normalize = function (vector) {
  3983. var result = Vector4.Zero();
  3984. Vector4.NormalizeToRef(vector, result);
  3985. return result;
  3986. };
  3987. /**
  3988. * Updates the passed vector "result" from the normalization of the passed one.
  3989. */
  3990. Vector4.NormalizeToRef = function (vector, result) {
  3991. result.copyFrom(vector);
  3992. result.normalize();
  3993. };
  3994. Vector4.Minimize = function (left, right) {
  3995. var min = left.clone();
  3996. min.minimizeInPlace(right);
  3997. return min;
  3998. };
  3999. Vector4.Maximize = function (left, right) {
  4000. var max = left.clone();
  4001. max.maximizeInPlace(right);
  4002. return max;
  4003. };
  4004. /**
  4005. * Returns the distance (float) between the vectors "value1" and "value2".
  4006. */
  4007. Vector4.Distance = function (value1, value2) {
  4008. return Math.sqrt(Vector4.DistanceSquared(value1, value2));
  4009. };
  4010. /**
  4011. * Returns the squared distance (float) between the vectors "value1" and "value2".
  4012. */
  4013. Vector4.DistanceSquared = function (value1, value2) {
  4014. var x = value1.x - value2.x;
  4015. var y = value1.y - value2.y;
  4016. var z = value1.z - value2.z;
  4017. var w = value1.w - value2.w;
  4018. return (x * x) + (y * y) + (z * z) + (w * w);
  4019. };
  4020. /**
  4021. * Returns a new Vector4 located at the center between the vectors "value1" and "value2".
  4022. */
  4023. Vector4.Center = function (value1, value2) {
  4024. var center = value1.add(value2);
  4025. center.scaleInPlace(0.5);
  4026. return center;
  4027. };
  4028. /**
  4029. * Returns a new Vector4 set with the result of the normal transformation by the passed matrix of the passed vector.
  4030. * This methods computes transformed normalized direction vectors only.
  4031. */
  4032. Vector4.TransformNormal = function (vector, transformation) {
  4033. var result = Vector4.Zero();
  4034. Vector4.TransformNormalToRef(vector, transformation, result);
  4035. return result;
  4036. };
  4037. /**
  4038. * Sets the passed vector "result" with the result of the normal transformation by the passed matrix of the passed vector.
  4039. * This methods computes transformed normalized direction vectors only.
  4040. */
  4041. Vector4.TransformNormalToRef = function (vector, transformation, result) {
  4042. var x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]) + (vector.z * transformation.m[8]);
  4043. var y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]) + (vector.z * transformation.m[9]);
  4044. var z = (vector.x * transformation.m[2]) + (vector.y * transformation.m[6]) + (vector.z * transformation.m[10]);
  4045. result.x = x;
  4046. result.y = y;
  4047. result.z = z;
  4048. result.w = vector.w;
  4049. };
  4050. /**
  4051. * Sets the passed vector "result" with the result of the normal transformation by the passed matrix of the passed floats (x, y, z, w).
  4052. * This methods computes transformed normalized direction vectors only.
  4053. */
  4054. Vector4.TransformNormalFromFloatsToRef = function (x, y, z, w, transformation, result) {
  4055. result.x = (x * transformation.m[0]) + (y * transformation.m[4]) + (z * transformation.m[8]);
  4056. result.y = (x * transformation.m[1]) + (y * transformation.m[5]) + (z * transformation.m[9]);
  4057. result.z = (x * transformation.m[2]) + (y * transformation.m[6]) + (z * transformation.m[10]);
  4058. result.w = w;
  4059. };
  4060. return Vector4;
  4061. }());
  4062. BABYLON.Vector4 = Vector4;
  4063. var Size = /** @class */ (function () {
  4064. /**
  4065. * Creates a Size object from the passed width and height (floats).
  4066. */
  4067. function Size(width, height) {
  4068. this.width = width;
  4069. this.height = height;
  4070. }
  4071. // Returns a string with the Size width and height.
  4072. Size.prototype.toString = function () {
  4073. return "{W: " + this.width + ", H: " + this.height + "}";
  4074. };
  4075. /**
  4076. * Returns the string "Size"
  4077. */
  4078. Size.prototype.getClassName = function () {
  4079. return "Size";
  4080. };
  4081. /**
  4082. * Returns the Size hash code.
  4083. */
  4084. Size.prototype.getHashCode = function () {
  4085. var hash = this.width || 0;
  4086. hash = (hash * 397) ^ (this.height || 0);
  4087. return hash;
  4088. };
  4089. /**
  4090. * Updates the current size from the passed one.
  4091. * Returns the updated Size.
  4092. */
  4093. Size.prototype.copyFrom = function (src) {
  4094. this.width = src.width;
  4095. this.height = src.height;
  4096. };
  4097. /**
  4098. * Updates in place the current Size from the passed floats.
  4099. * Returns the updated Size.
  4100. */
  4101. Size.prototype.copyFromFloats = function (width, height) {
  4102. this.width = width;
  4103. this.height = height;
  4104. return this;
  4105. };
  4106. /**
  4107. * Updates in place the current Size from the passed floats.
  4108. * Returns the updated Size.
  4109. */
  4110. Size.prototype.set = function (width, height) {
  4111. return this.copyFromFloats(width, height);
  4112. };
  4113. /**
  4114. * Returns a new Size set with the multiplication result of the current Size and the passed floats.
  4115. */
  4116. Size.prototype.multiplyByFloats = function (w, h) {
  4117. return new Size(this.width * w, this.height * h);
  4118. };
  4119. /**
  4120. * Returns a new Size copied from the passed one.
  4121. */
  4122. Size.prototype.clone = function () {
  4123. return new Size(this.width, this.height);
  4124. };
  4125. /**
  4126. * Boolean : True if the current Size and the passed one width and height are strictly equal.
  4127. */
  4128. Size.prototype.equals = function (other) {
  4129. if (!other) {
  4130. return false;
  4131. }
  4132. return (this.width === other.width) && (this.height === other.height);
  4133. };
  4134. Object.defineProperty(Size.prototype, "surface", {
  4135. /**
  4136. * Returns the surface of the Size : width * height (float).
  4137. */
  4138. get: function () {
  4139. return this.width * this.height;
  4140. },
  4141. enumerable: true,
  4142. configurable: true
  4143. });
  4144. /**
  4145. * Returns a new Size set to (0.0, 0.0)
  4146. */
  4147. Size.Zero = function () {
  4148. return new Size(0.0, 0.0);
  4149. };
  4150. /**
  4151. * Returns a new Size set as the addition result of the current Size and the passed one.
  4152. */
  4153. Size.prototype.add = function (otherSize) {
  4154. var r = new Size(this.width + otherSize.width, this.height + otherSize.height);
  4155. return r;
  4156. };
  4157. /**
  4158. * Returns a new Size set as the subtraction result of the passed one from the current Size.
  4159. */
  4160. Size.prototype.subtract = function (otherSize) {
  4161. var r = new Size(this.width - otherSize.width, this.height - otherSize.height);
  4162. return r;
  4163. };
  4164. /**
  4165. * Returns a new Size set at the linear interpolation "amount" between "start" and "end".
  4166. */
  4167. Size.Lerp = function (start, end, amount) {
  4168. var w = start.width + ((end.width - start.width) * amount);
  4169. var h = start.height + ((end.height - start.height) * amount);
  4170. return new Size(w, h);
  4171. };
  4172. return Size;
  4173. }());
  4174. BABYLON.Size = Size;
  4175. var Quaternion = /** @class */ (function () {
  4176. /**
  4177. * Creates a new Quaternion from the passed floats.
  4178. */
  4179. function Quaternion(x, y, z, w) {
  4180. if (x === void 0) { x = 0.0; }
  4181. if (y === void 0) { y = 0.0; }
  4182. if (z === void 0) { z = 0.0; }
  4183. if (w === void 0) { w = 1.0; }
  4184. this.x = x;
  4185. this.y = y;
  4186. this.z = z;
  4187. this.w = w;
  4188. }
  4189. /**
  4190. * Returns a string with the Quaternion coordinates.
  4191. */
  4192. Quaternion.prototype.toString = function () {
  4193. return "{X: " + this.x + " Y:" + this.y + " Z:" + this.z + " W:" + this.w + "}";
  4194. };
  4195. /**
  4196. * Returns the string "Quaternion".
  4197. */
  4198. Quaternion.prototype.getClassName = function () {
  4199. return "Quaternion";
  4200. };
  4201. /**
  4202. * Returns the Quaternion hash code.
  4203. */
  4204. Quaternion.prototype.getHashCode = function () {
  4205. var hash = this.x || 0;
  4206. hash = (hash * 397) ^ (this.y || 0);
  4207. hash = (hash * 397) ^ (this.z || 0);
  4208. hash = (hash * 397) ^ (this.w || 0);
  4209. return hash;
  4210. };
  4211. /**
  4212. * Returns a new array populated with 4 elements : the Quaternion coordinates.
  4213. */
  4214. Quaternion.prototype.asArray = function () {
  4215. return [this.x, this.y, this.z, this.w];
  4216. };
  4217. /**
  4218. * Boolean : True if the current Quaterion and the passed one coordinates are strictly equal.
  4219. */
  4220. Quaternion.prototype.equals = function (otherQuaternion) {
  4221. return otherQuaternion && this.x === otherQuaternion.x && this.y === otherQuaternion.y && this.z === otherQuaternion.z && this.w === otherQuaternion.w;
  4222. };
  4223. /**
  4224. * Returns a new Quaternion copied from the current one.
  4225. */
  4226. Quaternion.prototype.clone = function () {
  4227. return new Quaternion(this.x, this.y, this.z, this.w);
  4228. };
  4229. /**
  4230. * Updates the current Quaternion from the passed one coordinates.
  4231. * Returns the updated Quaterion.
  4232. */
  4233. Quaternion.prototype.copyFrom = function (other) {
  4234. this.x = other.x;
  4235. this.y = other.y;
  4236. this.z = other.z;
  4237. this.w = other.w;
  4238. return this;
  4239. };
  4240. /**
  4241. * Updates the current Quaternion from the passed float coordinates.
  4242. * Returns the updated Quaterion.
  4243. */
  4244. Quaternion.prototype.copyFromFloats = function (x, y, z, w) {
  4245. this.x = x;
  4246. this.y = y;
  4247. this.z = z;
  4248. this.w = w;
  4249. return this;
  4250. };
  4251. /**
  4252. * Updates the current Quaternion from the passed float coordinates.
  4253. * Returns the updated Quaterion.
  4254. */
  4255. Quaternion.prototype.set = function (x, y, z, w) {
  4256. return this.copyFromFloats(x, y, z, w);
  4257. };
  4258. /**
  4259. * Returns a new Quaternion as the addition result of the passed one and the current Quaternion.
  4260. */
  4261. Quaternion.prototype.add = function (other) {
  4262. return new Quaternion(this.x + other.x, this.y + other.y, this.z + other.z, this.w + other.w);
  4263. };
  4264. /**
  4265. * Returns a new Quaternion as the subtraction result of the passed one from the current Quaternion.
  4266. */
  4267. Quaternion.prototype.subtract = function (other) {
  4268. return new Quaternion(this.x - other.x, this.y - other.y, this.z - other.z, this.w - other.w);
  4269. };
  4270. /**
  4271. * Returns a new Quaternion set by multiplying the current Quaterion coordinates by the float "scale".
  4272. */
  4273. Quaternion.prototype.scale = function (value) {
  4274. return new Quaternion(this.x * value, this.y * value, this.z * value, this.w * value);
  4275. };
  4276. /**
  4277. * Returns a new Quaternion set as the quaternion mulplication result of the current one with the passed one "q1".
  4278. */
  4279. Quaternion.prototype.multiply = function (q1) {
  4280. var result = new Quaternion(0, 0, 0, 1.0);
  4281. this.multiplyToRef(q1, result);
  4282. return result;
  4283. };
  4284. /**
  4285. * Sets the passed "result" as the quaternion mulplication result of the current one with the passed one "q1".
  4286. * Returns the current Quaternion.
  4287. */
  4288. Quaternion.prototype.multiplyToRef = function (q1, result) {
  4289. var x = this.x * q1.w + this.y * q1.z - this.z * q1.y + this.w * q1.x;
  4290. var y = -this.x * q1.z + this.y * q1.w + this.z * q1.x + this.w * q1.y;
  4291. var z = this.x * q1.y - this.y * q1.x + this.z * q1.w + this.w * q1.z;
  4292. var w = -this.x * q1.x - this.y * q1.y - this.z * q1.z + this.w * q1.w;
  4293. result.copyFromFloats(x, y, z, w);
  4294. return this;
  4295. };
  4296. /**
  4297. * Updates the current Quaternion with the quaternion mulplication result of itself with the passed one "q1".
  4298. * Returns the updated Quaternion.
  4299. */
  4300. Quaternion.prototype.multiplyInPlace = function (q1) {
  4301. this.multiplyToRef(q1, this);
  4302. return this;
  4303. };
  4304. /**
  4305. * Sets the passed "ref" with the conjugation of the current Quaternion.
  4306. * Returns the current Quaternion.
  4307. */
  4308. Quaternion.prototype.conjugateToRef = function (ref) {
  4309. ref.copyFromFloats(-this.x, -this.y, -this.z, this.w);
  4310. return this;
  4311. };
  4312. /**
  4313. * Conjugates in place the current Quaternion.
  4314. * Returns the updated Quaternion.
  4315. */
  4316. Quaternion.prototype.conjugateInPlace = function () {
  4317. this.x *= -1;
  4318. this.y *= -1;
  4319. this.z *= -1;
  4320. return this;
  4321. };
  4322. /**
  4323. * Returns a new Quaternion as the conjugate of the current Quaternion.
  4324. */
  4325. Quaternion.prototype.conjugate = function () {
  4326. var result = new Quaternion(-this.x, -this.y, -this.z, this.w);
  4327. return result;
  4328. };
  4329. /**
  4330. * Returns the Quaternion length (float).
  4331. */
  4332. Quaternion.prototype.length = function () {
  4333. return Math.sqrt((this.x * this.x) + (this.y * this.y) + (this.z * this.z) + (this.w * this.w));
  4334. };
  4335. /**
  4336. * Normalize in place the current Quaternion.
  4337. * Returns the updated Quaternion.
  4338. */
  4339. Quaternion.prototype.normalize = function () {
  4340. var length = 1.0 / this.length();
  4341. this.x *= length;
  4342. this.y *= length;
  4343. this.z *= length;
  4344. this.w *= length;
  4345. return this;
  4346. };
  4347. /**
  4348. * Returns a new Vector3 set with the Euler angles translated from the current Quaternion.
  4349. */
  4350. Quaternion.prototype.toEulerAngles = function (order) {
  4351. if (order === void 0) { order = "YZX"; }
  4352. var result = Vector3.Zero();
  4353. this.toEulerAnglesToRef(result, order);
  4354. return result;
  4355. };
  4356. /**
  4357. * Sets the passed vector3 "result" with the Euler angles translated from the current Quaternion.
  4358. * Returns the current Quaternion.
  4359. */
  4360. Quaternion.prototype.toEulerAnglesToRef = function (result, order) {
  4361. if (order === void 0) { order = "YZX"; }
  4362. var qz = this.z;
  4363. var qx = this.x;
  4364. var qy = this.y;
  4365. var qw = this.w;
  4366. var sqw = qw * qw;
  4367. var sqz = qz * qz;
  4368. var sqx = qx * qx;
  4369. var sqy = qy * qy;
  4370. var zAxisY = qy * qz - qx * qw;
  4371. var limit = .4999999;
  4372. if (zAxisY < -limit) {
  4373. result.y = 2 * Math.atan2(qy, qw);
  4374. result.x = Math.PI / 2;
  4375. result.z = 0;
  4376. }
  4377. else if (zAxisY > limit) {
  4378. result.y = 2 * Math.atan2(qy, qw);
  4379. result.x = -Math.PI / 2;
  4380. result.z = 0;
  4381. }
  4382. else {
  4383. result.z = Math.atan2(2.0 * (qx * qy + qz * qw), (-sqz - sqx + sqy + sqw));
  4384. result.x = Math.asin(-2.0 * (qz * qy - qx * qw));
  4385. result.y = Math.atan2(2.0 * (qz * qx + qy * qw), (sqz - sqx - sqy + sqw));
  4386. }
  4387. return this;
  4388. };
  4389. /**
  4390. * Updates the passed rotation matrix with the current Quaternion values.
  4391. * Returns the current Quaternion.
  4392. */
  4393. Quaternion.prototype.toRotationMatrix = function (result) {
  4394. var xx = this.x * this.x;
  4395. var yy = this.y * this.y;
  4396. var zz = this.z * this.z;
  4397. var xy = this.x * this.y;
  4398. var zw = this.z * this.w;
  4399. var zx = this.z * this.x;
  4400. var yw = this.y * this.w;
  4401. var yz = this.y * this.z;
  4402. var xw = this.x * this.w;
  4403. result.m[0] = 1.0 - (2.0 * (yy + zz));
  4404. result.m[1] = 2.0 * (xy + zw);
  4405. result.m[2] = 2.0 * (zx - yw);
  4406. result.m[3] = 0;
  4407. result.m[4] = 2.0 * (xy - zw);
  4408. result.m[5] = 1.0 - (2.0 * (zz + xx));
  4409. result.m[6] = 2.0 * (yz + xw);
  4410. result.m[7] = 0;
  4411. result.m[8] = 2.0 * (zx + yw);
  4412. result.m[9] = 2.0 * (yz - xw);
  4413. result.m[10] = 1.0 - (2.0 * (yy + xx));
  4414. result.m[11] = 0;
  4415. result.m[12] = 0;
  4416. result.m[13] = 0;
  4417. result.m[14] = 0;
  4418. result.m[15] = 1.0;
  4419. result._markAsUpdated();
  4420. return this;
  4421. };
  4422. /**
  4423. * Updates the current Quaternion from the passed rotation matrix values.
  4424. * Returns the updated Quaternion.
  4425. */
  4426. Quaternion.prototype.fromRotationMatrix = function (matrix) {
  4427. Quaternion.FromRotationMatrixToRef(matrix, this);
  4428. return this;
  4429. };
  4430. // Statics
  4431. /**
  4432. * Returns a new Quaternion set from the passed rotation matrix values.
  4433. */
  4434. Quaternion.FromRotationMatrix = function (matrix) {
  4435. var result = new Quaternion();
  4436. Quaternion.FromRotationMatrixToRef(matrix, result);
  4437. return result;
  4438. };
  4439. /**
  4440. * Updates the passed quaternion "result" with the passed rotation matrix values.
  4441. */
  4442. Quaternion.FromRotationMatrixToRef = function (matrix, result) {
  4443. var data = matrix.m;
  4444. var m11 = data[0], m12 = data[4], m13 = data[8];
  4445. var m21 = data[1], m22 = data[5], m23 = data[9];
  4446. var m31 = data[2], m32 = data[6], m33 = data[10];
  4447. var trace = m11 + m22 + m33;
  4448. var s;
  4449. if (trace > 0) {
  4450. s = 0.5 / Math.sqrt(trace + 1.0);
  4451. result.w = 0.25 / s;
  4452. result.x = (m32 - m23) * s;
  4453. result.y = (m13 - m31) * s;
  4454. result.z = (m21 - m12) * s;
  4455. }
  4456. else if (m11 > m22 && m11 > m33) {
  4457. s = 2.0 * Math.sqrt(1.0 + m11 - m22 - m33);
  4458. result.w = (m32 - m23) / s;
  4459. result.x = 0.25 * s;
  4460. result.y = (m12 + m21) / s;
  4461. result.z = (m13 + m31) / s;
  4462. }
  4463. else if (m22 > m33) {
  4464. s = 2.0 * Math.sqrt(1.0 + m22 - m11 - m33);
  4465. result.w = (m13 - m31) / s;
  4466. result.x = (m12 + m21) / s;
  4467. result.y = 0.25 * s;
  4468. result.z = (m23 + m32) / s;
  4469. }
  4470. else {
  4471. s = 2.0 * Math.sqrt(1.0 + m33 - m11 - m22);
  4472. result.w = (m21 - m12) / s;
  4473. result.x = (m13 + m31) / s;
  4474. result.y = (m23 + m32) / s;
  4475. result.z = 0.25 * s;
  4476. }
  4477. };
  4478. /**
  4479. * Returns a new Quaternion set to (0.0, 0.0, 0.0).
  4480. */
  4481. Quaternion.Zero = function () {
  4482. return new Quaternion(0.0, 0.0, 0.0, 0.0);
  4483. };
  4484. /**
  4485. * Returns a new Quaternion as the inverted current Quaternion.
  4486. */
  4487. Quaternion.Inverse = function (q) {
  4488. return new Quaternion(-q.x, -q.y, -q.z, q.w);
  4489. };
  4490. /**
  4491. * Returns the identity Quaternion.
  4492. */
  4493. Quaternion.Identity = function () {
  4494. return new Quaternion(0.0, 0.0, 0.0, 1.0);
  4495. };
  4496. Quaternion.IsIdentity = function (quaternion) {
  4497. return quaternion && quaternion.x === 0 && quaternion.y === 0 && quaternion.z === 0 && quaternion.w === 1;
  4498. };
  4499. /**
  4500. * Returns a new Quaternion set from the passed axis (Vector3) and angle in radians (float).
  4501. */
  4502. Quaternion.RotationAxis = function (axis, angle) {
  4503. return Quaternion.RotationAxisToRef(axis, angle, new Quaternion());
  4504. };
  4505. /**
  4506. * Sets the passed quaternion "result" from the passed axis (Vector3) and angle in radians (float).
  4507. */
  4508. Quaternion.RotationAxisToRef = function (axis, angle, result) {
  4509. var sin = Math.sin(angle / 2);
  4510. axis.normalize();
  4511. result.w = Math.cos(angle / 2);
  4512. result.x = axis.x * sin;
  4513. result.y = axis.y * sin;
  4514. result.z = axis.z * sin;
  4515. return result;
  4516. };
  4517. /**
  4518. * Retuns a new Quaternion set from the starting index of the passed array.
  4519. */
  4520. Quaternion.FromArray = function (array, offset) {
  4521. if (!offset) {
  4522. offset = 0;
  4523. }
  4524. return new Quaternion(array[offset], array[offset + 1], array[offset + 2], array[offset + 3]);
  4525. };
  4526. /**
  4527. * Returns a new Quaternion set from the passed Euler float angles (y, x, z).
  4528. */
  4529. Quaternion.RotationYawPitchRoll = function (yaw, pitch, roll) {
  4530. var q = new Quaternion();
  4531. Quaternion.RotationYawPitchRollToRef(yaw, pitch, roll, q);
  4532. return q;
  4533. };
  4534. /**
  4535. * Sets the passed quaternion "result" from the passed float Euler angles (y, x, z).
  4536. */
  4537. Quaternion.RotationYawPitchRollToRef = function (yaw, pitch, roll, result) {
  4538. // Produces a quaternion from Euler angles in the z-y-x orientation (Tait-Bryan angles)
  4539. var halfRoll = roll * 0.5;
  4540. var halfPitch = pitch * 0.5;
  4541. var halfYaw = yaw * 0.5;
  4542. var sinRoll = Math.sin(halfRoll);
  4543. var cosRoll = Math.cos(halfRoll);
  4544. var sinPitch = Math.sin(halfPitch);
  4545. var cosPitch = Math.cos(halfPitch);
  4546. var sinYaw = Math.sin(halfYaw);
  4547. var cosYaw = Math.cos(halfYaw);
  4548. result.x = (cosYaw * sinPitch * cosRoll) + (sinYaw * cosPitch * sinRoll);
  4549. result.y = (sinYaw * cosPitch * cosRoll) - (cosYaw * sinPitch * sinRoll);
  4550. result.z = (cosYaw * cosPitch * sinRoll) - (sinYaw * sinPitch * cosRoll);
  4551. result.w = (cosYaw * cosPitch * cosRoll) + (sinYaw * sinPitch * sinRoll);
  4552. };
  4553. /**
  4554. * Returns a new Quaternion from the passed float Euler angles expressed in z-x-z orientation
  4555. */
  4556. Quaternion.RotationAlphaBetaGamma = function (alpha, beta, gamma) {
  4557. var result = new Quaternion();
  4558. Quaternion.RotationAlphaBetaGammaToRef(alpha, beta, gamma, result);
  4559. return result;
  4560. };
  4561. /**
  4562. * Sets the passed quaternion "result" from the passed float Euler angles expressed in z-x-z orientation
  4563. */
  4564. Quaternion.RotationAlphaBetaGammaToRef = function (alpha, beta, gamma, result) {
  4565. // Produces a quaternion from Euler angles in the z-x-z orientation
  4566. var halfGammaPlusAlpha = (gamma + alpha) * 0.5;
  4567. var halfGammaMinusAlpha = (gamma - alpha) * 0.5;
  4568. var halfBeta = beta * 0.5;
  4569. result.x = Math.cos(halfGammaMinusAlpha) * Math.sin(halfBeta);
  4570. result.y = Math.sin(halfGammaMinusAlpha) * Math.sin(halfBeta);
  4571. result.z = Math.sin(halfGammaPlusAlpha) * Math.cos(halfBeta);
  4572. result.w = Math.cos(halfGammaPlusAlpha) * Math.cos(halfBeta);
  4573. };
  4574. /**
  4575. * Returns a new Quaternion as the quaternion rotation value to reach the target (axis1, axis2, axis3) orientation as a rotated XYZ system.
  4576. * cf to Vector3.RotationFromAxis() documentation.
  4577. * Note : axis1, axis2 and axis3 are normalized during this operation.
  4578. */
  4579. Quaternion.RotationQuaternionFromAxis = function (axis1, axis2, axis3, ref) {
  4580. var quat = new Quaternion(0.0, 0.0, 0.0, 0.0);
  4581. Quaternion.RotationQuaternionFromAxisToRef(axis1, axis2, axis3, quat);
  4582. return quat;
  4583. };
  4584. /**
  4585. * Sets the passed quaternion "ref" with the quaternion rotation value to reach the target (axis1, axis2, axis3) orientation as a rotated XYZ system.
  4586. * cf to Vector3.RotationFromAxis() documentation.
  4587. * Note : axis1, axis2 and axis3 are normalized during this operation.
  4588. */
  4589. Quaternion.RotationQuaternionFromAxisToRef = function (axis1, axis2, axis3, ref) {
  4590. var rotMat = MathTmp.Matrix[0];
  4591. Matrix.FromXYZAxesToRef(axis1.normalize(), axis2.normalize(), axis3.normalize(), rotMat);
  4592. Quaternion.FromRotationMatrixToRef(rotMat, ref);
  4593. };
  4594. Quaternion.Slerp = function (left, right, amount) {
  4595. var result = Quaternion.Identity();
  4596. Quaternion.SlerpToRef(left, right, amount, result);
  4597. return result;
  4598. };
  4599. Quaternion.SlerpToRef = function (left, right, amount, result) {
  4600. var num2;
  4601. var num3;
  4602. var num = amount;
  4603. var num4 = (((left.x * right.x) + (left.y * right.y)) + (left.z * right.z)) + (left.w * right.w);
  4604. var flag = false;
  4605. if (num4 < 0) {
  4606. flag = true;
  4607. num4 = -num4;
  4608. }
  4609. if (num4 > 0.999999) {
  4610. num3 = 1 - num;
  4611. num2 = flag ? -num : num;
  4612. }
  4613. else {
  4614. var num5 = Math.acos(num4);
  4615. var num6 = (1.0 / Math.sin(num5));
  4616. num3 = (Math.sin((1.0 - num) * num5)) * num6;
  4617. num2 = flag ? ((-Math.sin(num * num5)) * num6) : ((Math.sin(num * num5)) * num6);
  4618. }
  4619. result.x = (num3 * left.x) + (num2 * right.x);
  4620. result.y = (num3 * left.y) + (num2 * right.y);
  4621. result.z = (num3 * left.z) + (num2 * right.z);
  4622. result.w = (num3 * left.w) + (num2 * right.w);
  4623. };
  4624. /**
  4625. * Returns a new Quaternion located for "amount" (float) on the Hermite interpolation spline defined by the vectors "value1", "tangent1", "value2", "tangent2".
  4626. */
  4627. Quaternion.Hermite = function (value1, tangent1, value2, tangent2, amount) {
  4628. var squared = amount * amount;
  4629. var cubed = amount * squared;
  4630. var part1 = ((2.0 * cubed) - (3.0 * squared)) + 1.0;
  4631. var part2 = (-2.0 * cubed) + (3.0 * squared);
  4632. var part3 = (cubed - (2.0 * squared)) + amount;
  4633. var part4 = cubed - squared;
  4634. var x = (((value1.x * part1) + (value2.x * part2)) + (tangent1.x * part3)) + (tangent2.x * part4);
  4635. var y = (((value1.y * part1) + (value2.y * part2)) + (tangent1.y * part3)) + (tangent2.y * part4);
  4636. var z = (((value1.z * part1) + (value2.z * part2)) + (tangent1.z * part3)) + (tangent2.z * part4);
  4637. var w = (((value1.w * part1) + (value2.w * part2)) + (tangent1.w * part3)) + (tangent2.w * part4);
  4638. return new Quaternion(x, y, z, w);
  4639. };
  4640. return Quaternion;
  4641. }());
  4642. BABYLON.Quaternion = Quaternion;
  4643. var Matrix = /** @class */ (function () {
  4644. function Matrix() {
  4645. this._isIdentity = false;
  4646. this._isIdentityDirty = true;
  4647. this.m = new Float32Array(16);
  4648. this._markAsUpdated();
  4649. }
  4650. Matrix.prototype._markAsUpdated = function () {
  4651. this.updateFlag = Matrix._updateFlagSeed++;
  4652. this._isIdentityDirty = true;
  4653. };
  4654. // Properties
  4655. /**
  4656. * Boolean : True is the matrix is the identity matrix
  4657. */
  4658. Matrix.prototype.isIdentity = function (considerAsTextureMatrix) {
  4659. if (considerAsTextureMatrix === void 0) { considerAsTextureMatrix = false; }
  4660. if (this._isIdentityDirty) {
  4661. this._isIdentityDirty = false;
  4662. if (this.m[0] !== 1.0 || this.m[5] !== 1.0 || this.m[15] !== 1.0) {
  4663. this._isIdentity = false;
  4664. }
  4665. else if (this.m[1] !== 0.0 || this.m[2] !== 0.0 || this.m[3] !== 0.0 ||
  4666. this.m[4] !== 0.0 || this.m[6] !== 0.0 || this.m[7] !== 0.0 ||
  4667. this.m[8] !== 0.0 || this.m[9] !== 0.0 || this.m[11] !== 0.0 ||
  4668. this.m[12] !== 0.0 || this.m[13] !== 0.0 || this.m[14] !== 0.0) {
  4669. this._isIdentity = false;
  4670. }
  4671. else {
  4672. this._isIdentity = true;
  4673. }
  4674. if (!considerAsTextureMatrix && this.m[10] !== 1.0) {
  4675. this._isIdentity = false;
  4676. }
  4677. }
  4678. return this._isIdentity;
  4679. };
  4680. /**
  4681. * Returns the matrix determinant (float).
  4682. */
  4683. Matrix.prototype.determinant = function () {
  4684. var temp1 = (this.m[10] * this.m[15]) - (this.m[11] * this.m[14]);
  4685. var temp2 = (this.m[9] * this.m[15]) - (this.m[11] * this.m[13]);
  4686. var temp3 = (this.m[9] * this.m[14]) - (this.m[10] * this.m[13]);
  4687. var temp4 = (this.m[8] * this.m[15]) - (this.m[11] * this.m[12]);
  4688. var temp5 = (this.m[8] * this.m[14]) - (this.m[10] * this.m[12]);
  4689. var temp6 = (this.m[8] * this.m[13]) - (this.m[9] * this.m[12]);
  4690. return ((((this.m[0] * (((this.m[5] * temp1) - (this.m[6] * temp2)) + (this.m[7] * temp3))) - (this.m[1] * (((this.m[4] * temp1) -
  4691. (this.m[6] * temp4)) + (this.m[7] * temp5)))) + (this.m[2] * (((this.m[4] * temp2) - (this.m[5] * temp4)) + (this.m[7] * temp6)))) -
  4692. (this.m[3] * (((this.m[4] * temp3) - (this.m[5] * temp5)) + (this.m[6] * temp6))));
  4693. };
  4694. // Methods
  4695. /**
  4696. * Returns the matrix underlying array.
  4697. */
  4698. Matrix.prototype.toArray = function () {
  4699. return this.m;
  4700. };
  4701. /**
  4702. * Returns the matrix underlying array.
  4703. */
  4704. Matrix.prototype.asArray = function () {
  4705. return this.toArray();
  4706. };
  4707. /**
  4708. * Inverts in place the Matrix.
  4709. * Returns the Matrix inverted.
  4710. */
  4711. Matrix.prototype.invert = function () {
  4712. this.invertToRef(this);
  4713. return this;
  4714. };
  4715. /**
  4716. * Sets all the matrix elements to zero.
  4717. * Returns the Matrix.
  4718. */
  4719. Matrix.prototype.reset = function () {
  4720. for (var index = 0; index < 16; index++) {
  4721. this.m[index] = 0.0;
  4722. }
  4723. this._markAsUpdated();
  4724. return this;
  4725. };
  4726. /**
  4727. * Returns a new Matrix as the addition result of the current Matrix and the passed one.
  4728. */
  4729. Matrix.prototype.add = function (other) {
  4730. var result = new Matrix();
  4731. this.addToRef(other, result);
  4732. return result;
  4733. };
  4734. /**
  4735. * Sets the passed matrix "result" with the ddition result of the current Matrix and the passed one.
  4736. * Returns the Matrix.
  4737. */
  4738. Matrix.prototype.addToRef = function (other, result) {
  4739. for (var index = 0; index < 16; index++) {
  4740. result.m[index] = this.m[index] + other.m[index];
  4741. }
  4742. result._markAsUpdated();
  4743. return this;
  4744. };
  4745. /**
  4746. * Adds in place the passed matrix to the current Matrix.
  4747. * Returns the updated Matrix.
  4748. */
  4749. Matrix.prototype.addToSelf = function (other) {
  4750. for (var index = 0; index < 16; index++) {
  4751. this.m[index] += other.m[index];
  4752. }
  4753. this._markAsUpdated();
  4754. return this;
  4755. };
  4756. /**
  4757. * Sets the passed matrix with the current inverted Matrix.
  4758. * Returns the unmodified current Matrix.
  4759. */
  4760. Matrix.prototype.invertToRef = function (other) {
  4761. var l1 = this.m[0];
  4762. var l2 = this.m[1];
  4763. var l3 = this.m[2];
  4764. var l4 = this.m[3];
  4765. var l5 = this.m[4];
  4766. var l6 = this.m[5];
  4767. var l7 = this.m[6];
  4768. var l8 = this.m[7];
  4769. var l9 = this.m[8];
  4770. var l10 = this.m[9];
  4771. var l11 = this.m[10];
  4772. var l12 = this.m[11];
  4773. var l13 = this.m[12];
  4774. var l14 = this.m[13];
  4775. var l15 = this.m[14];
  4776. var l16 = this.m[15];
  4777. var l17 = (l11 * l16) - (l12 * l15);
  4778. var l18 = (l10 * l16) - (l12 * l14);
  4779. var l19 = (l10 * l15) - (l11 * l14);
  4780. var l20 = (l9 * l16) - (l12 * l13);
  4781. var l21 = (l9 * l15) - (l11 * l13);
  4782. var l22 = (l9 * l14) - (l10 * l13);
  4783. var l23 = ((l6 * l17) - (l7 * l18)) + (l8 * l19);
  4784. var l24 = -(((l5 * l17) - (l7 * l20)) + (l8 * l21));
  4785. var l25 = ((l5 * l18) - (l6 * l20)) + (l8 * l22);
  4786. var l26 = -(((l5 * l19) - (l6 * l21)) + (l7 * l22));
  4787. var l27 = 1.0 / ((((l1 * l23) + (l2 * l24)) + (l3 * l25)) + (l4 * l26));
  4788. var l28 = (l7 * l16) - (l8 * l15);
  4789. var l29 = (l6 * l16) - (l8 * l14);
  4790. var l30 = (l6 * l15) - (l7 * l14);
  4791. var l31 = (l5 * l16) - (l8 * l13);
  4792. var l32 = (l5 * l15) - (l7 * l13);
  4793. var l33 = (l5 * l14) - (l6 * l13);
  4794. var l34 = (l7 * l12) - (l8 * l11);
  4795. var l35 = (l6 * l12) - (l8 * l10);
  4796. var l36 = (l6 * l11) - (l7 * l10);
  4797. var l37 = (l5 * l12) - (l8 * l9);
  4798. var l38 = (l5 * l11) - (l7 * l9);
  4799. var l39 = (l5 * l10) - (l6 * l9);
  4800. other.m[0] = l23 * l27;
  4801. other.m[4] = l24 * l27;
  4802. other.m[8] = l25 * l27;
  4803. other.m[12] = l26 * l27;
  4804. other.m[1] = -(((l2 * l17) - (l3 * l18)) + (l4 * l19)) * l27;
  4805. other.m[5] = (((l1 * l17) - (l3 * l20)) + (l4 * l21)) * l27;
  4806. other.m[9] = -(((l1 * l18) - (l2 * l20)) + (l4 * l22)) * l27;
  4807. other.m[13] = (((l1 * l19) - (l2 * l21)) + (l3 * l22)) * l27;
  4808. other.m[2] = (((l2 * l28) - (l3 * l29)) + (l4 * l30)) * l27;
  4809. other.m[6] = -(((l1 * l28) - (l3 * l31)) + (l4 * l32)) * l27;
  4810. other.m[10] = (((l1 * l29) - (l2 * l31)) + (l4 * l33)) * l27;
  4811. other.m[14] = -(((l1 * l30) - (l2 * l32)) + (l3 * l33)) * l27;
  4812. other.m[3] = -(((l2 * l34) - (l3 * l35)) + (l4 * l36)) * l27;
  4813. other.m[7] = (((l1 * l34) - (l3 * l37)) + (l4 * l38)) * l27;
  4814. other.m[11] = -(((l1 * l35) - (l2 * l37)) + (l4 * l39)) * l27;
  4815. other.m[15] = (((l1 * l36) - (l2 * l38)) + (l3 * l39)) * l27;
  4816. other._markAsUpdated();
  4817. return this;
  4818. };
  4819. /**
  4820. * Inserts the translation vector (using 3 x floats) in the current Matrix.
  4821. * Returns the updated Matrix.
  4822. */
  4823. Matrix.prototype.setTranslationFromFloats = function (x, y, z) {
  4824. this.m[12] = x;
  4825. this.m[13] = y;
  4826. this.m[14] = z;
  4827. this._markAsUpdated();
  4828. return this;
  4829. };
  4830. /**
  4831. * Inserts the translation vector in the current Matrix.
  4832. * Returns the updated Matrix.
  4833. */
  4834. Matrix.prototype.setTranslation = function (vector3) {
  4835. this.m[12] = vector3.x;
  4836. this.m[13] = vector3.y;
  4837. this.m[14] = vector3.z;
  4838. this._markAsUpdated();
  4839. return this;
  4840. };
  4841. /**
  4842. * Returns a new Vector3 as the extracted translation from the Matrix.
  4843. */
  4844. Matrix.prototype.getTranslation = function () {
  4845. return new Vector3(this.m[12], this.m[13], this.m[14]);
  4846. };
  4847. /**
  4848. * Fill a Vector3 with the extracted translation from the Matrix.
  4849. */
  4850. Matrix.prototype.getTranslationToRef = function (result) {
  4851. result.x = this.m[12];
  4852. result.y = this.m[13];
  4853. result.z = this.m[14];
  4854. return this;
  4855. };
  4856. /**
  4857. * Remove rotation and scaling part from the Matrix.
  4858. * Returns the updated Matrix.
  4859. */
  4860. Matrix.prototype.removeRotationAndScaling = function () {
  4861. this.setRowFromFloats(0, 1, 0, 0, 0);
  4862. this.setRowFromFloats(1, 0, 1, 0, 0);
  4863. this.setRowFromFloats(2, 0, 0, 1, 0);
  4864. return this;
  4865. };
  4866. /**
  4867. * Returns a new Matrix set with the multiplication result of the current Matrix and the passed one.
  4868. */
  4869. Matrix.prototype.multiply = function (other) {
  4870. var result = new Matrix();
  4871. this.multiplyToRef(other, result);
  4872. return result;
  4873. };
  4874. /**
  4875. * Updates the current Matrix from the passed one values.
  4876. * Returns the updated Matrix.
  4877. */
  4878. Matrix.prototype.copyFrom = function (other) {
  4879. for (var index = 0; index < 16; index++) {
  4880. this.m[index] = other.m[index];
  4881. }
  4882. this._markAsUpdated();
  4883. return this;
  4884. };
  4885. /**
  4886. * Populates the passed array from the starting index with the Matrix values.
  4887. * Returns the Matrix.
  4888. */
  4889. Matrix.prototype.copyToArray = function (array, offset) {
  4890. if (offset === void 0) { offset = 0; }
  4891. for (var index = 0; index < 16; index++) {
  4892. array[offset + index] = this.m[index];
  4893. }
  4894. return this;
  4895. };
  4896. /**
  4897. * Sets the passed matrix "result" with the multiplication result of the current Matrix and the passed one.
  4898. */
  4899. Matrix.prototype.multiplyToRef = function (other, result) {
  4900. this.multiplyToArray(other, result.m, 0);
  4901. result._markAsUpdated();
  4902. return this;
  4903. };
  4904. /**
  4905. * Sets the Float32Array "result" from the passed index "offset" with the multiplication result of the current Matrix and the passed one.
  4906. */
  4907. Matrix.prototype.multiplyToArray = function (other, result, offset) {
  4908. var tm0 = this.m[0];
  4909. var tm1 = this.m[1];
  4910. var tm2 = this.m[2];
  4911. var tm3 = this.m[3];
  4912. var tm4 = this.m[4];
  4913. var tm5 = this.m[5];
  4914. var tm6 = this.m[6];
  4915. var tm7 = this.m[7];
  4916. var tm8 = this.m[8];
  4917. var tm9 = this.m[9];
  4918. var tm10 = this.m[10];
  4919. var tm11 = this.m[11];
  4920. var tm12 = this.m[12];
  4921. var tm13 = this.m[13];
  4922. var tm14 = this.m[14];
  4923. var tm15 = this.m[15];
  4924. var om0 = other.m[0];
  4925. var om1 = other.m[1];
  4926. var om2 = other.m[2];
  4927. var om3 = other.m[3];
  4928. var om4 = other.m[4];
  4929. var om5 = other.m[5];
  4930. var om6 = other.m[6];
  4931. var om7 = other.m[7];
  4932. var om8 = other.m[8];
  4933. var om9 = other.m[9];
  4934. var om10 = other.m[10];
  4935. var om11 = other.m[11];
  4936. var om12 = other.m[12];
  4937. var om13 = other.m[13];
  4938. var om14 = other.m[14];
  4939. var om15 = other.m[15];
  4940. result[offset] = tm0 * om0 + tm1 * om4 + tm2 * om8 + tm3 * om12;
  4941. result[offset + 1] = tm0 * om1 + tm1 * om5 + tm2 * om9 + tm3 * om13;
  4942. result[offset + 2] = tm0 * om2 + tm1 * om6 + tm2 * om10 + tm3 * om14;
  4943. result[offset + 3] = tm0 * om3 + tm1 * om7 + tm2 * om11 + tm3 * om15;
  4944. result[offset + 4] = tm4 * om0 + tm5 * om4 + tm6 * om8 + tm7 * om12;
  4945. result[offset + 5] = tm4 * om1 + tm5 * om5 + tm6 * om9 + tm7 * om13;
  4946. result[offset + 6] = tm4 * om2 + tm5 * om6 + tm6 * om10 + tm7 * om14;
  4947. result[offset + 7] = tm4 * om3 + tm5 * om7 + tm6 * om11 + tm7 * om15;
  4948. result[offset + 8] = tm8 * om0 + tm9 * om4 + tm10 * om8 + tm11 * om12;
  4949. result[offset + 9] = tm8 * om1 + tm9 * om5 + tm10 * om9 + tm11 * om13;
  4950. result[offset + 10] = tm8 * om2 + tm9 * om6 + tm10 * om10 + tm11 * om14;
  4951. result[offset + 11] = tm8 * om3 + tm9 * om7 + tm10 * om11 + tm11 * om15;
  4952. result[offset + 12] = tm12 * om0 + tm13 * om4 + tm14 * om8 + tm15 * om12;
  4953. result[offset + 13] = tm12 * om1 + tm13 * om5 + tm14 * om9 + tm15 * om13;
  4954. result[offset + 14] = tm12 * om2 + tm13 * om6 + tm14 * om10 + tm15 * om14;
  4955. result[offset + 15] = tm12 * om3 + tm13 * om7 + tm14 * om11 + tm15 * om15;
  4956. return this;
  4957. };
  4958. /**
  4959. * Boolean : True is the current Matrix and the passed one values are strictly equal.
  4960. */
  4961. Matrix.prototype.equals = function (value) {
  4962. return value &&
  4963. (this.m[0] === value.m[0] && this.m[1] === value.m[1] && this.m[2] === value.m[2] && this.m[3] === value.m[3] &&
  4964. this.m[4] === value.m[4] && this.m[5] === value.m[5] && this.m[6] === value.m[6] && this.m[7] === value.m[7] &&
  4965. this.m[8] === value.m[8] && this.m[9] === value.m[9] && this.m[10] === value.m[10] && this.m[11] === value.m[11] &&
  4966. this.m[12] === value.m[12] && this.m[13] === value.m[13] && this.m[14] === value.m[14] && this.m[15] === value.m[15]);
  4967. };
  4968. /**
  4969. * Returns a new Matrix from the current Matrix.
  4970. */
  4971. Matrix.prototype.clone = function () {
  4972. 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]);
  4973. };
  4974. /**
  4975. * Returns the string "Matrix"
  4976. */
  4977. Matrix.prototype.getClassName = function () {
  4978. return "Matrix";
  4979. };
  4980. /**
  4981. * Returns the Matrix hash code.
  4982. */
  4983. Matrix.prototype.getHashCode = function () {
  4984. var hash = this.m[0] || 0;
  4985. for (var i = 1; i < 16; i++) {
  4986. hash = (hash * 397) ^ (this.m[i] || 0);
  4987. }
  4988. return hash;
  4989. };
  4990. /**
  4991. * Decomposes the current Matrix into :
  4992. * - a scale vector3 passed as a reference to update,
  4993. * - a rotation quaternion passed as a reference to update,
  4994. * - a translation vector3 passed as a reference to update.
  4995. * Returns the true if operation was successful.
  4996. */
  4997. Matrix.prototype.decompose = function (scale, rotation, translation) {
  4998. translation.x = this.m[12];
  4999. translation.y = this.m[13];
  5000. translation.z = this.m[14];
  5001. scale.x = Math.sqrt(this.m[0] * this.m[0] + this.m[1] * this.m[1] + this.m[2] * this.m[2]);
  5002. scale.y = Math.sqrt(this.m[4] * this.m[4] + this.m[5] * this.m[5] + this.m[6] * this.m[6]);
  5003. scale.z = Math.sqrt(this.m[8] * this.m[8] + this.m[9] * this.m[9] + this.m[10] * this.m[10]);
  5004. if (this.determinant() <= 0) {
  5005. scale.y *= -1;
  5006. }
  5007. if (scale.x === 0 || scale.y === 0 || scale.z === 0) {
  5008. rotation.x = 0;
  5009. rotation.y = 0;
  5010. rotation.z = 0;
  5011. rotation.w = 1;
  5012. return false;
  5013. }
  5014. 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]);
  5015. Quaternion.FromRotationMatrixToRef(MathTmp.Matrix[0], rotation);
  5016. return true;
  5017. };
  5018. /**
  5019. * Writes to the given matrix a normal matrix, computed from this one (using values from identity matrix for fourth row and column).
  5020. * @param ref matrix to store the result
  5021. */
  5022. Matrix.prototype.toNormalMatrix = function (ref) {
  5023. this.invertToRef(ref);
  5024. ref.transpose();
  5025. var m = ref.m;
  5026. 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);
  5027. };
  5028. /**
  5029. * Returns a new Matrix as the extracted rotation matrix from the current one.
  5030. */
  5031. Matrix.prototype.getRotationMatrix = function () {
  5032. var result = Matrix.Identity();
  5033. this.getRotationMatrixToRef(result);
  5034. return result;
  5035. };
  5036. /**
  5037. * Extracts the rotation matrix from the current one and sets it as the passed "result".
  5038. * Returns the current Matrix.
  5039. */
  5040. Matrix.prototype.getRotationMatrixToRef = function (result) {
  5041. var m = this.m;
  5042. var xs = m[0] * m[1] * m[2] * m[3] < 0 ? -1 : 1;
  5043. var ys = m[4] * m[5] * m[6] * m[7] < 0 ? -1 : 1;
  5044. var zs = m[8] * m[9] * m[10] * m[11] < 0 ? -1 : 1;
  5045. var sx = xs * Math.sqrt(m[0] * m[0] + m[1] * m[1] + m[2] * m[2]);
  5046. var sy = ys * Math.sqrt(m[4] * m[4] + m[5] * m[5] + m[6] * m[6]);
  5047. var sz = zs * Math.sqrt(m[8] * m[8] + m[9] * m[9] + m[10] * m[10]);
  5048. 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);
  5049. return this;
  5050. };
  5051. // Statics
  5052. /**
  5053. * Returns a new Matrix set from the starting index of the passed array.
  5054. */
  5055. Matrix.FromArray = function (array, offset) {
  5056. var result = new Matrix();
  5057. if (!offset) {
  5058. offset = 0;
  5059. }
  5060. Matrix.FromArrayToRef(array, offset, result);
  5061. return result;
  5062. };
  5063. /**
  5064. * Sets the passed "result" matrix from the starting index of the passed array.
  5065. */
  5066. Matrix.FromArrayToRef = function (array, offset, result) {
  5067. for (var index = 0; index < 16; index++) {
  5068. result.m[index] = array[index + offset];
  5069. }
  5070. result._markAsUpdated();
  5071. };
  5072. /**
  5073. * Sets the passed "result" matrix from the starting index of the passed Float32Array by multiplying each element by the float "scale".
  5074. */
  5075. Matrix.FromFloat32ArrayToRefScaled = function (array, offset, scale, result) {
  5076. for (var index = 0; index < 16; index++) {
  5077. result.m[index] = array[index + offset] * scale;
  5078. }
  5079. result._markAsUpdated();
  5080. };
  5081. /**
  5082. * Sets the passed matrix "result" with the 16 passed floats.
  5083. */
  5084. Matrix.FromValuesToRef = function (initialM11, initialM12, initialM13, initialM14, initialM21, initialM22, initialM23, initialM24, initialM31, initialM32, initialM33, initialM34, initialM41, initialM42, initialM43, initialM44, result) {
  5085. result.m[0] = initialM11;
  5086. result.m[1] = initialM12;
  5087. result.m[2] = initialM13;
  5088. result.m[3] = initialM14;
  5089. result.m[4] = initialM21;
  5090. result.m[5] = initialM22;
  5091. result.m[6] = initialM23;
  5092. result.m[7] = initialM24;
  5093. result.m[8] = initialM31;
  5094. result.m[9] = initialM32;
  5095. result.m[10] = initialM33;
  5096. result.m[11] = initialM34;
  5097. result.m[12] = initialM41;
  5098. result.m[13] = initialM42;
  5099. result.m[14] = initialM43;
  5100. result.m[15] = initialM44;
  5101. result._markAsUpdated();
  5102. };
  5103. /**
  5104. * Returns the index-th row of the current matrix as a new Vector4.
  5105. */
  5106. Matrix.prototype.getRow = function (index) {
  5107. if (index < 0 || index > 3) {
  5108. return null;
  5109. }
  5110. var i = index * 4;
  5111. return new Vector4(this.m[i + 0], this.m[i + 1], this.m[i + 2], this.m[i + 3]);
  5112. };
  5113. /**
  5114. * Sets the index-th row of the current matrix with the passed Vector4 values.
  5115. * Returns the updated Matrix.
  5116. */
  5117. Matrix.prototype.setRow = function (index, row) {
  5118. if (index < 0 || index > 3) {
  5119. return this;
  5120. }
  5121. var i = index * 4;
  5122. this.m[i + 0] = row.x;
  5123. this.m[i + 1] = row.y;
  5124. this.m[i + 2] = row.z;
  5125. this.m[i + 3] = row.w;
  5126. this._markAsUpdated();
  5127. return this;
  5128. };
  5129. /**
  5130. * Compute the transpose of the matrix.
  5131. * Returns a new Matrix.
  5132. */
  5133. Matrix.prototype.transpose = function () {
  5134. return Matrix.Transpose(this);
  5135. };
  5136. /**
  5137. * Compute the transpose of the matrix.
  5138. * Returns the current matrix.
  5139. */
  5140. Matrix.prototype.transposeToRef = function (result) {
  5141. Matrix.TransposeToRef(this, result);
  5142. return this;
  5143. };
  5144. /**
  5145. * Sets the index-th row of the current matrix with the passed 4 x float values.
  5146. * Returns the updated Matrix.
  5147. */
  5148. Matrix.prototype.setRowFromFloats = function (index, x, y, z, w) {
  5149. if (index < 0 || index > 3) {
  5150. return this;
  5151. }
  5152. var i = index * 4;
  5153. this.m[i + 0] = x;
  5154. this.m[i + 1] = y;
  5155. this.m[i + 2] = z;
  5156. this.m[i + 3] = w;
  5157. this._markAsUpdated();
  5158. return this;
  5159. };
  5160. Object.defineProperty(Matrix, "IdentityReadOnly", {
  5161. /**
  5162. * Static identity matrix to be used as readonly matrix
  5163. * Must not be updated.
  5164. */
  5165. get: function () {
  5166. return Matrix._identityReadOnly;
  5167. },
  5168. enumerable: true,
  5169. configurable: true
  5170. });
  5171. /**
  5172. * Returns a new Matrix set from the 16 passed floats.
  5173. */
  5174. Matrix.FromValues = function (initialM11, initialM12, initialM13, initialM14, initialM21, initialM22, initialM23, initialM24, initialM31, initialM32, initialM33, initialM34, initialM41, initialM42, initialM43, initialM44) {
  5175. var result = new Matrix();
  5176. result.m[0] = initialM11;
  5177. result.m[1] = initialM12;
  5178. result.m[2] = initialM13;
  5179. result.m[3] = initialM14;
  5180. result.m[4] = initialM21;
  5181. result.m[5] = initialM22;
  5182. result.m[6] = initialM23;
  5183. result.m[7] = initialM24;
  5184. result.m[8] = initialM31;
  5185. result.m[9] = initialM32;
  5186. result.m[10] = initialM33;
  5187. result.m[11] = initialM34;
  5188. result.m[12] = initialM41;
  5189. result.m[13] = initialM42;
  5190. result.m[14] = initialM43;
  5191. result.m[15] = initialM44;
  5192. return result;
  5193. };
  5194. /**
  5195. * Returns a new Matrix composed by the passed scale (vector3), rotation (quaternion) and translation (vector3).
  5196. */
  5197. Matrix.Compose = function (scale, rotation, translation) {
  5198. var result = Matrix.Identity();
  5199. Matrix.ComposeToRef(scale, rotation, translation, result);
  5200. return result;
  5201. };
  5202. /**
  5203. * Update a Matrix with values composed by the passed scale (vector3), rotation (quaternion) and translation (vector3).
  5204. */
  5205. Matrix.ComposeToRef = function (scale, rotation, translation, result) {
  5206. Matrix.FromValuesToRef(scale.x, 0, 0, 0, 0, scale.y, 0, 0, 0, 0, scale.z, 0, 0, 0, 0, 1, MathTmp.Matrix[1]);
  5207. rotation.toRotationMatrix(MathTmp.Matrix[0]);
  5208. MathTmp.Matrix[1].multiplyToRef(MathTmp.Matrix[0], result);
  5209. result.setTranslation(translation);
  5210. };
  5211. /**
  5212. * Returns a new indentity Matrix.
  5213. */
  5214. Matrix.Identity = function () {
  5215. 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);
  5216. };
  5217. /**
  5218. * Sets the passed "result" as an identity matrix.
  5219. */
  5220. Matrix.IdentityToRef = function (result) {
  5221. 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);
  5222. };
  5223. /**
  5224. * Returns a new zero Matrix.
  5225. */
  5226. Matrix.Zero = function () {
  5227. 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);
  5228. };
  5229. /**
  5230. * Returns a new rotation matrix for "angle" radians around the X axis.
  5231. */
  5232. Matrix.RotationX = function (angle) {
  5233. var result = new Matrix();
  5234. Matrix.RotationXToRef(angle, result);
  5235. return result;
  5236. };
  5237. /**
  5238. * Returns a new Matrix as the passed inverted one.
  5239. */
  5240. Matrix.Invert = function (source) {
  5241. var result = new Matrix();
  5242. source.invertToRef(result);
  5243. return result;
  5244. };
  5245. /**
  5246. * Sets the passed matrix "result" as a rotation matrix for "angle" radians around the X axis.
  5247. */
  5248. Matrix.RotationXToRef = function (angle, result) {
  5249. var s = Math.sin(angle);
  5250. var c = Math.cos(angle);
  5251. result.m[0] = 1.0;
  5252. result.m[15] = 1.0;
  5253. result.m[5] = c;
  5254. result.m[10] = c;
  5255. result.m[9] = -s;
  5256. result.m[6] = s;
  5257. result.m[1] = 0.0;
  5258. result.m[2] = 0.0;
  5259. result.m[3] = 0.0;
  5260. result.m[4] = 0.0;
  5261. result.m[7] = 0.0;
  5262. result.m[8] = 0.0;
  5263. result.m[11] = 0.0;
  5264. result.m[12] = 0.0;
  5265. result.m[13] = 0.0;
  5266. result.m[14] = 0.0;
  5267. result._markAsUpdated();
  5268. };
  5269. /**
  5270. * Returns a new rotation matrix for "angle" radians around the Y axis.
  5271. */
  5272. Matrix.RotationY = function (angle) {
  5273. var result = new Matrix();
  5274. Matrix.RotationYToRef(angle, result);
  5275. return result;
  5276. };
  5277. /**
  5278. * Sets the passed matrix "result" as a rotation matrix for "angle" radians around the Y axis.
  5279. */
  5280. Matrix.RotationYToRef = function (angle, result) {
  5281. var s = Math.sin(angle);
  5282. var c = Math.cos(angle);
  5283. result.m[5] = 1.0;
  5284. result.m[15] = 1.0;
  5285. result.m[0] = c;
  5286. result.m[2] = -s;
  5287. result.m[8] = s;
  5288. result.m[10] = c;
  5289. result.m[1] = 0.0;
  5290. result.m[3] = 0.0;
  5291. result.m[4] = 0.0;
  5292. result.m[6] = 0.0;
  5293. result.m[7] = 0.0;
  5294. result.m[9] = 0.0;
  5295. result.m[11] = 0.0;
  5296. result.m[12] = 0.0;
  5297. result.m[13] = 0.0;
  5298. result.m[14] = 0.0;
  5299. result._markAsUpdated();
  5300. };
  5301. /**
  5302. * Returns a new rotation matrix for "angle" radians around the Z axis.
  5303. */
  5304. Matrix.RotationZ = function (angle) {
  5305. var result = new Matrix();
  5306. Matrix.RotationZToRef(angle, result);
  5307. return result;
  5308. };
  5309. /**
  5310. * Sets the passed matrix "result" as a rotation matrix for "angle" radians around the Z axis.
  5311. */
  5312. Matrix.RotationZToRef = function (angle, result) {
  5313. var s = Math.sin(angle);
  5314. var c = Math.cos(angle);
  5315. result.m[10] = 1.0;
  5316. result.m[15] = 1.0;
  5317. result.m[0] = c;
  5318. result.m[1] = s;
  5319. result.m[4] = -s;
  5320. result.m[5] = c;
  5321. result.m[2] = 0.0;
  5322. result.m[3] = 0.0;
  5323. result.m[6] = 0.0;
  5324. result.m[7] = 0.0;
  5325. result.m[8] = 0.0;
  5326. result.m[9] = 0.0;
  5327. result.m[11] = 0.0;
  5328. result.m[12] = 0.0;
  5329. result.m[13] = 0.0;
  5330. result.m[14] = 0.0;
  5331. result._markAsUpdated();
  5332. };
  5333. /**
  5334. * Returns a new rotation matrix for "angle" radians around the passed axis.
  5335. */
  5336. Matrix.RotationAxis = function (axis, angle) {
  5337. var result = Matrix.Zero();
  5338. Matrix.RotationAxisToRef(axis, angle, result);
  5339. return result;
  5340. };
  5341. /**
  5342. * Sets the passed matrix "result" as a rotation matrix for "angle" radians around the passed axis.
  5343. */
  5344. Matrix.RotationAxisToRef = function (axis, angle, result) {
  5345. var s = Math.sin(-angle);
  5346. var c = Math.cos(-angle);
  5347. var c1 = 1 - c;
  5348. axis.normalize();
  5349. result.m[0] = (axis.x * axis.x) * c1 + c;
  5350. result.m[1] = (axis.x * axis.y) * c1 - (axis.z * s);
  5351. result.m[2] = (axis.x * axis.z) * c1 + (axis.y * s);
  5352. result.m[3] = 0.0;
  5353. result.m[4] = (axis.y * axis.x) * c1 + (axis.z * s);
  5354. result.m[5] = (axis.y * axis.y) * c1 + c;
  5355. result.m[6] = (axis.y * axis.z) * c1 - (axis.x * s);
  5356. result.m[7] = 0.0;
  5357. result.m[8] = (axis.z * axis.x) * c1 - (axis.y * s);
  5358. result.m[9] = (axis.z * axis.y) * c1 + (axis.x * s);
  5359. result.m[10] = (axis.z * axis.z) * c1 + c;
  5360. result.m[11] = 0.0;
  5361. result.m[15] = 1.0;
  5362. result._markAsUpdated();
  5363. };
  5364. /**
  5365. * Returns a new Matrix as a rotation matrix from the Euler angles (y, x, z).
  5366. */
  5367. Matrix.RotationYawPitchRoll = function (yaw, pitch, roll) {
  5368. var result = new Matrix();
  5369. Matrix.RotationYawPitchRollToRef(yaw, pitch, roll, result);
  5370. return result;
  5371. };
  5372. /**
  5373. * Sets the passed matrix "result" as a rotation matrix from the Euler angles (y, x, z).
  5374. */
  5375. Matrix.RotationYawPitchRollToRef = function (yaw, pitch, roll, result) {
  5376. Quaternion.RotationYawPitchRollToRef(yaw, pitch, roll, this._tempQuaternion);
  5377. this._tempQuaternion.toRotationMatrix(result);
  5378. };
  5379. /**
  5380. * Returns a new Matrix as a scaling matrix from the passed floats (x, y, z).
  5381. */
  5382. Matrix.Scaling = function (x, y, z) {
  5383. var result = Matrix.Zero();
  5384. Matrix.ScalingToRef(x, y, z, result);
  5385. return result;
  5386. };
  5387. /**
  5388. * Sets the passed matrix "result" as a scaling matrix from the passed floats (x, y, z).
  5389. */
  5390. Matrix.ScalingToRef = function (x, y, z, result) {
  5391. result.m[0] = x;
  5392. result.m[1] = 0.0;
  5393. result.m[2] = 0.0;
  5394. result.m[3] = 0.0;
  5395. result.m[4] = 0.0;
  5396. result.m[5] = y;
  5397. result.m[6] = 0.0;
  5398. result.m[7] = 0.0;
  5399. result.m[8] = 0.0;
  5400. result.m[9] = 0.0;
  5401. result.m[10] = z;
  5402. result.m[11] = 0.0;
  5403. result.m[12] = 0.0;
  5404. result.m[13] = 0.0;
  5405. result.m[14] = 0.0;
  5406. result.m[15] = 1.0;
  5407. result._markAsUpdated();
  5408. };
  5409. /**
  5410. * Returns a new Matrix as a translation matrix from the passed floats (x, y, z).
  5411. */
  5412. Matrix.Translation = function (x, y, z) {
  5413. var result = Matrix.Identity();
  5414. Matrix.TranslationToRef(x, y, z, result);
  5415. return result;
  5416. };
  5417. /**
  5418. * Sets the passed matrix "result" as a translation matrix from the passed floats (x, y, z).
  5419. */
  5420. Matrix.TranslationToRef = function (x, y, z, result) {
  5421. 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);
  5422. };
  5423. /**
  5424. * Returns a new Matrix whose values are the interpolated values for "gradient" (float) between the ones of the matrices "startValue" and "endValue".
  5425. * @param startValue defines the start value
  5426. * @param endValue defines the end value
  5427. * @param gradient defines the gradient factor
  5428. * @returns the new matrix
  5429. */
  5430. Matrix.Lerp = function (startValue, endValue, gradient) {
  5431. var result = Matrix.Zero();
  5432. Matrix.LerpToRef(startValue, endValue, gradient, result);
  5433. return result;
  5434. };
  5435. /**
  5436. * Set the passed matrix "result" as the interpolated values for "gradient" (float) between the ones of the matrices "startValue" and "endValue".
  5437. * @param startValue defines the start value
  5438. * @param endValue defines the end value
  5439. * @param gradient defines the gradient factor
  5440. * @param result defines the Matrix object where to store data
  5441. */
  5442. Matrix.LerpToRef = function (startValue, endValue, gradient, result) {
  5443. for (var index = 0; index < 16; index++) {
  5444. result.m[index] = startValue.m[index] * (1.0 - gradient) + endValue.m[index] * gradient;
  5445. }
  5446. result._markAsUpdated();
  5447. };
  5448. /**
  5449. * Returns a new Matrix whose values are computed by :
  5450. * - decomposing the the "startValue" and "endValue" matrices into their respective scale, rotation and translation matrices,
  5451. * - interpolating for "gradient" (float) the values between each of these decomposed matrices between the start and the end,
  5452. * - recomposing a new matrix from these 3 interpolated scale, rotation and translation matrices.
  5453. */
  5454. Matrix.DecomposeLerp = function (startValue, endValue, gradient) {
  5455. var startScale = new Vector3(0, 0, 0);
  5456. var startRotation = new Quaternion();
  5457. var startTranslation = new Vector3(0, 0, 0);
  5458. startValue.decompose(startScale, startRotation, startTranslation);
  5459. var endScale = new Vector3(0, 0, 0);
  5460. var endRotation = new Quaternion();
  5461. var endTranslation = new Vector3(0, 0, 0);
  5462. endValue.decompose(endScale, endRotation, endTranslation);
  5463. var resultScale = Vector3.Lerp(startScale, endScale, gradient);
  5464. var resultRotation = Quaternion.Slerp(startRotation, endRotation, gradient);
  5465. var resultTranslation = Vector3.Lerp(startTranslation, endTranslation, gradient);
  5466. return Matrix.Compose(resultScale, resultRotation, resultTranslation);
  5467. };
  5468. /**
  5469. * 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".
  5470. * This methods works for a Left-Handed system.
  5471. */
  5472. Matrix.LookAtLH = function (eye, target, up) {
  5473. var result = Matrix.Zero();
  5474. Matrix.LookAtLHToRef(eye, target, up, result);
  5475. return result;
  5476. };
  5477. /**
  5478. * 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".
  5479. * This methods works for a Left-Handed system.
  5480. */
  5481. Matrix.LookAtLHToRef = function (eye, target, up, result) {
  5482. // Z axis
  5483. target.subtractToRef(eye, this._zAxis);
  5484. this._zAxis.normalize();
  5485. // X axis
  5486. Vector3.CrossToRef(up, this._zAxis, this._xAxis);
  5487. if (this._xAxis.lengthSquared() === 0) {
  5488. this._xAxis.x = 1.0;
  5489. }
  5490. else {
  5491. this._xAxis.normalize();
  5492. }
  5493. // Y axis
  5494. Vector3.CrossToRef(this._zAxis, this._xAxis, this._yAxis);
  5495. this._yAxis.normalize();
  5496. // Eye angles
  5497. var ex = -Vector3.Dot(this._xAxis, eye);
  5498. var ey = -Vector3.Dot(this._yAxis, eye);
  5499. var ez = -Vector3.Dot(this._zAxis, eye);
  5500. 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);
  5501. };
  5502. /**
  5503. * 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".
  5504. * This methods works for a Right-Handed system.
  5505. */
  5506. Matrix.LookAtRH = function (eye, target, up) {
  5507. var result = Matrix.Zero();
  5508. Matrix.LookAtRHToRef(eye, target, up, result);
  5509. return result;
  5510. };
  5511. /**
  5512. * 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".
  5513. * This methods works for a Left-Handed system.
  5514. */
  5515. Matrix.LookAtRHToRef = function (eye, target, up, result) {
  5516. // Z axis
  5517. eye.subtractToRef(target, this._zAxis);
  5518. this._zAxis.normalize();
  5519. // X axis
  5520. Vector3.CrossToRef(up, this._zAxis, this._xAxis);
  5521. if (this._xAxis.lengthSquared() === 0) {
  5522. this._xAxis.x = 1.0;
  5523. }
  5524. else {
  5525. this._xAxis.normalize();
  5526. }
  5527. // Y axis
  5528. Vector3.CrossToRef(this._zAxis, this._xAxis, this._yAxis);
  5529. this._yAxis.normalize();
  5530. // Eye angles
  5531. var ex = -Vector3.Dot(this._xAxis, eye);
  5532. var ey = -Vector3.Dot(this._yAxis, eye);
  5533. var ez = -Vector3.Dot(this._zAxis, eye);
  5534. 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);
  5535. };
  5536. /**
  5537. * 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.
  5538. */
  5539. Matrix.OrthoLH = function (width, height, znear, zfar) {
  5540. var matrix = Matrix.Zero();
  5541. Matrix.OrthoLHToRef(width, height, znear, zfar, matrix);
  5542. return matrix;
  5543. };
  5544. /**
  5545. * 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.
  5546. */
  5547. Matrix.OrthoLHToRef = function (width, height, znear, zfar, result) {
  5548. var n = znear;
  5549. var f = zfar;
  5550. var a = 2.0 / width;
  5551. var b = 2.0 / height;
  5552. var c = 2.0 / (f - n);
  5553. var d = -(f + n) / (f - n);
  5554. 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);
  5555. };
  5556. /**
  5557. * 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.
  5558. */
  5559. Matrix.OrthoOffCenterLH = function (left, right, bottom, top, znear, zfar) {
  5560. var matrix = Matrix.Zero();
  5561. Matrix.OrthoOffCenterLHToRef(left, right, bottom, top, znear, zfar, matrix);
  5562. return matrix;
  5563. };
  5564. /**
  5565. * 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.
  5566. */
  5567. Matrix.OrthoOffCenterLHToRef = function (left, right, bottom, top, znear, zfar, result) {
  5568. var n = znear;
  5569. var f = zfar;
  5570. var a = 2.0 / (right - left);
  5571. var b = 2.0 / (top - bottom);
  5572. var c = 2.0 / (f - n);
  5573. var d = -(f + n) / (f - n);
  5574. var i0 = (left + right) / (left - right);
  5575. var i1 = (top + bottom) / (bottom - top);
  5576. 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);
  5577. };
  5578. /**
  5579. * 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.
  5580. */
  5581. Matrix.OrthoOffCenterRH = function (left, right, bottom, top, znear, zfar) {
  5582. var matrix = Matrix.Zero();
  5583. Matrix.OrthoOffCenterRHToRef(left, right, bottom, top, znear, zfar, matrix);
  5584. return matrix;
  5585. };
  5586. /**
  5587. * 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.
  5588. */
  5589. Matrix.OrthoOffCenterRHToRef = function (left, right, bottom, top, znear, zfar, result) {
  5590. Matrix.OrthoOffCenterLHToRef(left, right, bottom, top, znear, zfar, result);
  5591. result.m[10] *= -1.0;
  5592. };
  5593. /**
  5594. * 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.
  5595. */
  5596. Matrix.PerspectiveLH = function (width, height, znear, zfar) {
  5597. var matrix = Matrix.Zero();
  5598. var n = znear;
  5599. var f = zfar;
  5600. var a = 2.0 * n / width;
  5601. var b = 2.0 * n / height;
  5602. var c = (f + n) / (f - n);
  5603. var d = -2.0 * f * n / (f - n);
  5604. 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);
  5605. return matrix;
  5606. };
  5607. /**
  5608. * 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.
  5609. */
  5610. Matrix.PerspectiveFovLH = function (fov, aspect, znear, zfar) {
  5611. var matrix = Matrix.Zero();
  5612. Matrix.PerspectiveFovLHToRef(fov, aspect, znear, zfar, matrix);
  5613. return matrix;
  5614. };
  5615. /**
  5616. * 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.
  5617. */
  5618. Matrix.PerspectiveFovLHToRef = function (fov, aspect, znear, zfar, result, isVerticalFovFixed) {
  5619. if (isVerticalFovFixed === void 0) { isVerticalFovFixed = true; }
  5620. var n = znear;
  5621. var f = zfar;
  5622. var t = 1.0 / (Math.tan(fov * 0.5));
  5623. var a = isVerticalFovFixed ? (t / aspect) : t;
  5624. var b = isVerticalFovFixed ? t : (t * aspect);
  5625. var c = (f + n) / (f - n);
  5626. var d = -2.0 * f * n / (f - n);
  5627. 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);
  5628. };
  5629. /**
  5630. * 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.
  5631. */
  5632. Matrix.PerspectiveFovRH = function (fov, aspect, znear, zfar) {
  5633. var matrix = Matrix.Zero();
  5634. Matrix.PerspectiveFovRHToRef(fov, aspect, znear, zfar, matrix);
  5635. return matrix;
  5636. };
  5637. /**
  5638. * 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.
  5639. */
  5640. Matrix.PerspectiveFovRHToRef = function (fov, aspect, znear, zfar, result, isVerticalFovFixed) {
  5641. //alternatively this could be expressed as:
  5642. // m = PerspectiveFovLHToRef
  5643. // m[10] *= -1.0;
  5644. // m[11] *= -1.0;
  5645. if (isVerticalFovFixed === void 0) { isVerticalFovFixed = true; }
  5646. var n = znear;
  5647. var f = zfar;
  5648. var t = 1.0 / (Math.tan(fov * 0.5));
  5649. var a = isVerticalFovFixed ? (t / aspect) : t;
  5650. var b = isVerticalFovFixed ? t : (t * aspect);
  5651. var c = -(f + n) / (f - n);
  5652. var d = -2 * f * n / (f - n);
  5653. 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);
  5654. };
  5655. /**
  5656. * 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.
  5657. */
  5658. Matrix.PerspectiveFovWebVRToRef = function (fov, znear, zfar, result, rightHanded) {
  5659. if (rightHanded === void 0) { rightHanded = false; }
  5660. var rightHandedFactor = rightHanded ? -1 : 1;
  5661. var upTan = Math.tan(fov.upDegrees * Math.PI / 180.0);
  5662. var downTan = Math.tan(fov.downDegrees * Math.PI / 180.0);
  5663. var leftTan = Math.tan(fov.leftDegrees * Math.PI / 180.0);
  5664. var rightTan = Math.tan(fov.rightDegrees * Math.PI / 180.0);
  5665. var xScale = 2.0 / (leftTan + rightTan);
  5666. var yScale = 2.0 / (upTan + downTan);
  5667. result.m[0] = xScale;
  5668. result.m[1] = result.m[2] = result.m[3] = result.m[4] = 0.0;
  5669. result.m[5] = yScale;
  5670. result.m[6] = result.m[7] = 0.0;
  5671. result.m[8] = ((leftTan - rightTan) * xScale * 0.5); // * rightHandedFactor;
  5672. result.m[9] = -((upTan - downTan) * yScale * 0.5); // * rightHandedFactor;
  5673. //result.m[10] = -(znear + zfar) / (zfar - znear) * rightHandedFactor;
  5674. result.m[10] = -zfar / (znear - zfar);
  5675. result.m[11] = 1.0 * rightHandedFactor;
  5676. result.m[12] = result.m[13] = result.m[15] = 0.0;
  5677. result.m[14] = -(2.0 * zfar * znear) / (zfar - znear);
  5678. // result.m[14] = (znear * zfar) / (znear - zfar);
  5679. result._markAsUpdated();
  5680. };
  5681. /**
  5682. * Returns the final transformation matrix : world * view * projection * viewport
  5683. */
  5684. Matrix.GetFinalMatrix = function (viewport, world, view, projection, zmin, zmax) {
  5685. var cw = viewport.width;
  5686. var ch = viewport.height;
  5687. var cx = viewport.x;
  5688. var cy = viewport.y;
  5689. 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);
  5690. return world.multiply(view).multiply(projection).multiply(viewportMatrix);
  5691. };
  5692. /**
  5693. * Returns a new Float32Array array with 4 elements : the 2x2 matrix extracted from the passed Matrix.
  5694. */
  5695. Matrix.GetAsMatrix2x2 = function (matrix) {
  5696. return new Float32Array([
  5697. matrix.m[0], matrix.m[1],
  5698. matrix.m[4], matrix.m[5]
  5699. ]);
  5700. };
  5701. /**
  5702. * Returns a new Float32Array array with 9 elements : the 3x3 matrix extracted from the passed Matrix.
  5703. */
  5704. Matrix.GetAsMatrix3x3 = function (matrix) {
  5705. return new Float32Array([
  5706. matrix.m[0], matrix.m[1], matrix.m[2],
  5707. matrix.m[4], matrix.m[5], matrix.m[6],
  5708. matrix.m[8], matrix.m[9], matrix.m[10]
  5709. ]);
  5710. };
  5711. /**
  5712. * Compute the transpose of the passed Matrix.
  5713. * Returns a new Matrix.
  5714. */
  5715. Matrix.Transpose = function (matrix) {
  5716. var result = new Matrix();
  5717. Matrix.TransposeToRef(matrix, result);
  5718. return result;
  5719. };
  5720. /**
  5721. * Compute the transpose of the passed Matrix and store it in the result matrix.
  5722. */
  5723. Matrix.TransposeToRef = function (matrix, result) {
  5724. result.m[0] = matrix.m[0];
  5725. result.m[1] = matrix.m[4];
  5726. result.m[2] = matrix.m[8];
  5727. result.m[3] = matrix.m[12];
  5728. result.m[4] = matrix.m[1];
  5729. result.m[5] = matrix.m[5];
  5730. result.m[6] = matrix.m[9];
  5731. result.m[7] = matrix.m[13];
  5732. result.m[8] = matrix.m[2];
  5733. result.m[9] = matrix.m[6];
  5734. result.m[10] = matrix.m[10];
  5735. result.m[11] = matrix.m[14];
  5736. result.m[12] = matrix.m[3];
  5737. result.m[13] = matrix.m[7];
  5738. result.m[14] = matrix.m[11];
  5739. result.m[15] = matrix.m[15];
  5740. };
  5741. /**
  5742. * Returns a new Matrix as the reflection matrix across the passed plane.
  5743. */
  5744. Matrix.Reflection = function (plane) {
  5745. var matrix = new Matrix();
  5746. Matrix.ReflectionToRef(plane, matrix);
  5747. return matrix;
  5748. };
  5749. /**
  5750. * Sets the passed matrix "result" as the reflection matrix across the passed plane.
  5751. */
  5752. Matrix.ReflectionToRef = function (plane, result) {
  5753. plane.normalize();
  5754. var x = plane.normal.x;
  5755. var y = plane.normal.y;
  5756. var z = plane.normal.z;
  5757. var temp = -2 * x;
  5758. var temp2 = -2 * y;
  5759. var temp3 = -2 * z;
  5760. result.m[0] = (temp * x) + 1;
  5761. result.m[1] = temp2 * x;
  5762. result.m[2] = temp3 * x;
  5763. result.m[3] = 0.0;
  5764. result.m[4] = temp * y;
  5765. result.m[5] = (temp2 * y) + 1;
  5766. result.m[6] = temp3 * y;
  5767. result.m[7] = 0.0;
  5768. result.m[8] = temp * z;
  5769. result.m[9] = temp2 * z;
  5770. result.m[10] = (temp3 * z) + 1;
  5771. result.m[11] = 0.0;
  5772. result.m[12] = temp * plane.d;
  5773. result.m[13] = temp2 * plane.d;
  5774. result.m[14] = temp3 * plane.d;
  5775. result.m[15] = 1.0;
  5776. result._markAsUpdated();
  5777. };
  5778. /**
  5779. * Sets the passed matrix "mat" as a rotation matrix composed from the 3 passed left handed axis.
  5780. */
  5781. Matrix.FromXYZAxesToRef = function (xaxis, yaxis, zaxis, result) {
  5782. result.m[0] = xaxis.x;
  5783. result.m[1] = xaxis.y;
  5784. result.m[2] = xaxis.z;
  5785. result.m[3] = 0.0;
  5786. result.m[4] = yaxis.x;
  5787. result.m[5] = yaxis.y;
  5788. result.m[6] = yaxis.z;
  5789. result.m[7] = 0.0;
  5790. result.m[8] = zaxis.x;
  5791. result.m[9] = zaxis.y;
  5792. result.m[10] = zaxis.z;
  5793. result.m[11] = 0.0;
  5794. result.m[12] = 0.0;
  5795. result.m[13] = 0.0;
  5796. result.m[14] = 0.0;
  5797. result.m[15] = 1.0;
  5798. result._markAsUpdated();
  5799. };
  5800. /**
  5801. * Sets the passed matrix "result" as a rotation matrix according to the passed quaternion.
  5802. */
  5803. Matrix.FromQuaternionToRef = function (quat, result) {
  5804. var xx = quat.x * quat.x;
  5805. var yy = quat.y * quat.y;
  5806. var zz = quat.z * quat.z;
  5807. var xy = quat.x * quat.y;
  5808. var zw = quat.z * quat.w;
  5809. var zx = quat.z * quat.x;
  5810. var yw = quat.y * quat.w;
  5811. var yz = quat.y * quat.z;
  5812. var xw = quat.x * quat.w;
  5813. result.m[0] = 1.0 - (2.0 * (yy + zz));
  5814. result.m[1] = 2.0 * (xy + zw);
  5815. result.m[2] = 2.0 * (zx - yw);
  5816. result.m[3] = 0.0;
  5817. result.m[4] = 2.0 * (xy - zw);
  5818. result.m[5] = 1.0 - (2.0 * (zz + xx));
  5819. result.m[6] = 2.0 * (yz + xw);
  5820. result.m[7] = 0.0;
  5821. result.m[8] = 2.0 * (zx + yw);
  5822. result.m[9] = 2.0 * (yz - xw);
  5823. result.m[10] = 1.0 - (2.0 * (yy + xx));
  5824. result.m[11] = 0.0;
  5825. result.m[12] = 0.0;
  5826. result.m[13] = 0.0;
  5827. result.m[14] = 0.0;
  5828. result.m[15] = 1.0;
  5829. result._markAsUpdated();
  5830. };
  5831. Matrix._tempQuaternion = new Quaternion();
  5832. Matrix._xAxis = Vector3.Zero();
  5833. Matrix._yAxis = Vector3.Zero();
  5834. Matrix._zAxis = Vector3.Zero();
  5835. Matrix._updateFlagSeed = 0;
  5836. Matrix._identityReadOnly = Matrix.Identity();
  5837. return Matrix;
  5838. }());
  5839. BABYLON.Matrix = Matrix;
  5840. var Plane = /** @class */ (function () {
  5841. /**
  5842. * Creates a Plane object according to the passed floats a, b, c, d and the plane equation : ax + by + cz + d = 0
  5843. */
  5844. function Plane(a, b, c, d) {
  5845. this.normal = new Vector3(a, b, c);
  5846. this.d = d;
  5847. }
  5848. /**
  5849. * Returns the plane coordinates as a new array of 4 elements [a, b, c, d].
  5850. */
  5851. Plane.prototype.asArray = function () {
  5852. return [this.normal.x, this.normal.y, this.normal.z, this.d];
  5853. };
  5854. // Methods
  5855. /**
  5856. * Returns a new plane copied from the current Plane.
  5857. */
  5858. Plane.prototype.clone = function () {
  5859. return new Plane(this.normal.x, this.normal.y, this.normal.z, this.d);
  5860. };
  5861. /**
  5862. * Returns the string "Plane".
  5863. */
  5864. Plane.prototype.getClassName = function () {
  5865. return "Plane";
  5866. };
  5867. /**
  5868. * Returns the Plane hash code.
  5869. */
  5870. Plane.prototype.getHashCode = function () {
  5871. var hash = this.normal.getHashCode();
  5872. hash = (hash * 397) ^ (this.d || 0);
  5873. return hash;
  5874. };
  5875. /**
  5876. * Normalize the current Plane in place.
  5877. * Returns the updated Plane.
  5878. */
  5879. Plane.prototype.normalize = function () {
  5880. var norm = (Math.sqrt((this.normal.x * this.normal.x) + (this.normal.y * this.normal.y) + (this.normal.z * this.normal.z)));
  5881. var magnitude = 0.0;
  5882. if (norm !== 0) {
  5883. magnitude = 1.0 / norm;
  5884. }
  5885. this.normal.x *= magnitude;
  5886. this.normal.y *= magnitude;
  5887. this.normal.z *= magnitude;
  5888. this.d *= magnitude;
  5889. return this;
  5890. };
  5891. /**
  5892. * Returns a new Plane as the result of the transformation of the current Plane by the passed matrix.
  5893. */
  5894. Plane.prototype.transform = function (transformation) {
  5895. var transposedMatrix = Matrix.Transpose(transformation);
  5896. var x = this.normal.x;
  5897. var y = this.normal.y;
  5898. var z = this.normal.z;
  5899. var d = this.d;
  5900. var normalX = (((x * transposedMatrix.m[0]) + (y * transposedMatrix.m[1])) + (z * transposedMatrix.m[2])) + (d * transposedMatrix.m[3]);
  5901. var normalY = (((x * transposedMatrix.m[4]) + (y * transposedMatrix.m[5])) + (z * transposedMatrix.m[6])) + (d * transposedMatrix.m[7]);
  5902. var normalZ = (((x * transposedMatrix.m[8]) + (y * transposedMatrix.m[9])) + (z * transposedMatrix.m[10])) + (d * transposedMatrix.m[11]);
  5903. var finalD = (((x * transposedMatrix.m[12]) + (y * transposedMatrix.m[13])) + (z * transposedMatrix.m[14])) + (d * transposedMatrix.m[15]);
  5904. return new Plane(normalX, normalY, normalZ, finalD);
  5905. };
  5906. /**
  5907. * Returns the dot product (float) of the point coordinates and the plane normal.
  5908. */
  5909. Plane.prototype.dotCoordinate = function (point) {
  5910. return ((((this.normal.x * point.x) + (this.normal.y * point.y)) + (this.normal.z * point.z)) + this.d);
  5911. };
  5912. /**
  5913. * Updates the current Plane from the plane defined by the three passed points.
  5914. * Returns the updated Plane.
  5915. */
  5916. Plane.prototype.copyFromPoints = function (point1, point2, point3) {
  5917. var x1 = point2.x - point1.x;
  5918. var y1 = point2.y - point1.y;
  5919. var z1 = point2.z - point1.z;
  5920. var x2 = point3.x - point1.x;
  5921. var y2 = point3.y - point1.y;
  5922. var z2 = point3.z - point1.z;
  5923. var yz = (y1 * z2) - (z1 * y2);
  5924. var xz = (z1 * x2) - (x1 * z2);
  5925. var xy = (x1 * y2) - (y1 * x2);
  5926. var pyth = (Math.sqrt((yz * yz) + (xz * xz) + (xy * xy)));
  5927. var invPyth;
  5928. if (pyth !== 0) {
  5929. invPyth = 1.0 / pyth;
  5930. }
  5931. else {
  5932. invPyth = 0.0;
  5933. }
  5934. this.normal.x = yz * invPyth;
  5935. this.normal.y = xz * invPyth;
  5936. this.normal.z = xy * invPyth;
  5937. this.d = -((this.normal.x * point1.x) + (this.normal.y * point1.y) + (this.normal.z * point1.z));
  5938. return this;
  5939. };
  5940. /**
  5941. * Boolean : True is the vector "direction" is the same side than the plane normal.
  5942. */
  5943. Plane.prototype.isFrontFacingTo = function (direction, epsilon) {
  5944. var dot = Vector3.Dot(this.normal, direction);
  5945. return (dot <= epsilon);
  5946. };
  5947. /**
  5948. * Returns the signed distance (float) from the passed point to the Plane.
  5949. */
  5950. Plane.prototype.signedDistanceTo = function (point) {
  5951. return Vector3.Dot(point, this.normal) + this.d;
  5952. };
  5953. // Statics
  5954. /**
  5955. * Returns a new Plane from the passed array.
  5956. */
  5957. Plane.FromArray = function (array) {
  5958. return new Plane(array[0], array[1], array[2], array[3]);
  5959. };
  5960. /**
  5961. * Returns a new Plane defined by the three passed points.
  5962. */
  5963. Plane.FromPoints = function (point1, point2, point3) {
  5964. var result = new Plane(0.0, 0.0, 0.0, 0.0);
  5965. result.copyFromPoints(point1, point2, point3);
  5966. return result;
  5967. };
  5968. /**
  5969. * Returns a new Plane the normal vector to this plane at the passed origin point.
  5970. * Note : the vector "normal" is updated because normalized.
  5971. */
  5972. Plane.FromPositionAndNormal = function (origin, normal) {
  5973. var result = new Plane(0.0, 0.0, 0.0, 0.0);
  5974. normal.normalize();
  5975. result.normal = normal;
  5976. result.d = -(normal.x * origin.x + normal.y * origin.y + normal.z * origin.z);
  5977. return result;
  5978. };
  5979. /**
  5980. * Returns the signed distance between the plane defined by the normal vector at the "origin"" point and the passed other point.
  5981. */
  5982. Plane.SignedDistanceToPlaneFromPositionAndNormal = function (origin, normal, point) {
  5983. var d = -(normal.x * origin.x + normal.y * origin.y + normal.z * origin.z);
  5984. return Vector3.Dot(point, normal) + d;
  5985. };
  5986. return Plane;
  5987. }());
  5988. BABYLON.Plane = Plane;
  5989. var Viewport = /** @class */ (function () {
  5990. /**
  5991. * Creates a Viewport object located at (x, y) and sized (width, height).
  5992. */
  5993. function Viewport(x, y, width, height) {
  5994. this.x = x;
  5995. this.y = y;
  5996. this.width = width;
  5997. this.height = height;
  5998. }
  5999. Viewport.prototype.toGlobal = function (renderWidthOrEngine, renderHeight) {
  6000. if (renderWidthOrEngine.getRenderWidth) {
  6001. var engine = renderWidthOrEngine;
  6002. return this.toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  6003. }
  6004. var renderWidth = renderWidthOrEngine;
  6005. return new Viewport(this.x * renderWidth, this.y * renderHeight, this.width * renderWidth, this.height * renderHeight);
  6006. };
  6007. /**
  6008. * Returns a new Viewport copied from the current one.
  6009. */
  6010. Viewport.prototype.clone = function () {
  6011. return new Viewport(this.x, this.y, this.width, this.height);
  6012. };
  6013. return Viewport;
  6014. }());
  6015. BABYLON.Viewport = Viewport;
  6016. var Frustum = /** @class */ (function () {
  6017. function Frustum() {
  6018. }
  6019. /**
  6020. * Returns a new array of 6 Frustum planes computed by the passed transformation matrix.
  6021. */
  6022. Frustum.GetPlanes = function (transform) {
  6023. var frustumPlanes = [];
  6024. for (var index = 0; index < 6; index++) {
  6025. frustumPlanes.push(new Plane(0.0, 0.0, 0.0, 0.0));
  6026. }
  6027. Frustum.GetPlanesToRef(transform, frustumPlanes);
  6028. return frustumPlanes;
  6029. };
  6030. Frustum.GetNearPlaneToRef = function (transform, frustumPlane) {
  6031. frustumPlane.normal.x = transform.m[3] + transform.m[2];
  6032. frustumPlane.normal.y = transform.m[7] + transform.m[6];
  6033. frustumPlane.normal.z = transform.m[11] + transform.m[10];
  6034. frustumPlane.d = transform.m[15] + transform.m[14];
  6035. frustumPlane.normalize();
  6036. };
  6037. Frustum.GetFarPlaneToRef = function (transform, frustumPlane) {
  6038. frustumPlane.normal.x = transform.m[3] - transform.m[2];
  6039. frustumPlane.normal.y = transform.m[7] - transform.m[6];
  6040. frustumPlane.normal.z = transform.m[11] - transform.m[10];
  6041. frustumPlane.d = transform.m[15] - transform.m[14];
  6042. frustumPlane.normalize();
  6043. };
  6044. Frustum.GetLeftPlaneToRef = function (transform, frustumPlane) {
  6045. frustumPlane.normal.x = transform.m[3] + transform.m[0];
  6046. frustumPlane.normal.y = transform.m[7] + transform.m[4];
  6047. frustumPlane.normal.z = transform.m[11] + transform.m[8];
  6048. frustumPlane.d = transform.m[15] + transform.m[12];
  6049. frustumPlane.normalize();
  6050. };
  6051. Frustum.GetRightPlaneToRef = function (transform, frustumPlane) {
  6052. frustumPlane.normal.x = transform.m[3] - transform.m[0];
  6053. frustumPlane.normal.y = transform.m[7] - transform.m[4];
  6054. frustumPlane.normal.z = transform.m[11] - transform.m[8];
  6055. frustumPlane.d = transform.m[15] - transform.m[12];
  6056. frustumPlane.normalize();
  6057. };
  6058. Frustum.GetTopPlaneToRef = function (transform, frustumPlane) {
  6059. frustumPlane.normal.x = transform.m[3] - transform.m[1];
  6060. frustumPlane.normal.y = transform.m[7] - transform.m[5];
  6061. frustumPlane.normal.z = transform.m[11] - transform.m[9];
  6062. frustumPlane.d = transform.m[15] - transform.m[13];
  6063. frustumPlane.normalize();
  6064. };
  6065. Frustum.GetBottomPlaneToRef = function (transform, frustumPlane) {
  6066. frustumPlane.normal.x = transform.m[3] + transform.m[1];
  6067. frustumPlane.normal.y = transform.m[7] + transform.m[5];
  6068. frustumPlane.normal.z = transform.m[11] + transform.m[9];
  6069. frustumPlane.d = transform.m[15] + transform.m[13];
  6070. frustumPlane.normalize();
  6071. };
  6072. /**
  6073. * Sets the passed array "frustumPlanes" with the 6 Frustum planes computed by the passed transformation matrix.
  6074. */
  6075. Frustum.GetPlanesToRef = function (transform, frustumPlanes) {
  6076. // Near
  6077. Frustum.GetNearPlaneToRef(transform, frustumPlanes[0]);
  6078. // Far
  6079. Frustum.GetFarPlaneToRef(transform, frustumPlanes[1]);
  6080. // Left
  6081. Frustum.GetLeftPlaneToRef(transform, frustumPlanes[2]);
  6082. // Right
  6083. Frustum.GetRightPlaneToRef(transform, frustumPlanes[3]);
  6084. // Top
  6085. Frustum.GetTopPlaneToRef(transform, frustumPlanes[4]);
  6086. // Bottom
  6087. Frustum.GetBottomPlaneToRef(transform, frustumPlanes[5]);
  6088. };
  6089. return Frustum;
  6090. }());
  6091. BABYLON.Frustum = Frustum;
  6092. var Space;
  6093. (function (Space) {
  6094. Space[Space["LOCAL"] = 0] = "LOCAL";
  6095. Space[Space["WORLD"] = 1] = "WORLD";
  6096. Space[Space["BONE"] = 2] = "BONE";
  6097. })(Space = BABYLON.Space || (BABYLON.Space = {}));
  6098. var Axis = /** @class */ (function () {
  6099. function Axis() {
  6100. }
  6101. Axis.X = new Vector3(1.0, 0.0, 0.0);
  6102. Axis.Y = new Vector3(0.0, 1.0, 0.0);
  6103. Axis.Z = new Vector3(0.0, 0.0, 1.0);
  6104. return Axis;
  6105. }());
  6106. BABYLON.Axis = Axis;
  6107. ;
  6108. var BezierCurve = /** @class */ (function () {
  6109. function BezierCurve() {
  6110. }
  6111. /**
  6112. * Returns the cubic Bezier interpolated value (float) at "t" (float) from the passed x1, y1, x2, y2 floats.
  6113. */
  6114. BezierCurve.interpolate = function (t, x1, y1, x2, y2) {
  6115. // Extract X (which is equal to time here)
  6116. var f0 = 1 - 3 * x2 + 3 * x1;
  6117. var f1 = 3 * x2 - 6 * x1;
  6118. var f2 = 3 * x1;
  6119. var refinedT = t;
  6120. for (var i = 0; i < 5; i++) {
  6121. var refinedT2 = refinedT * refinedT;
  6122. var refinedT3 = refinedT2 * refinedT;
  6123. var x = f0 * refinedT3 + f1 * refinedT2 + f2 * refinedT;
  6124. var slope = 1.0 / (3.0 * f0 * refinedT2 + 2.0 * f1 * refinedT + f2);
  6125. refinedT -= (x - t) * slope;
  6126. refinedT = Math.min(1, Math.max(0, refinedT));
  6127. }
  6128. // Resolve cubic bezier for the given x
  6129. return 3 * Math.pow(1 - refinedT, 2) * refinedT * y1 +
  6130. 3 * (1 - refinedT) * Math.pow(refinedT, 2) * y2 +
  6131. Math.pow(refinedT, 3);
  6132. };
  6133. return BezierCurve;
  6134. }());
  6135. BABYLON.BezierCurve = BezierCurve;
  6136. var Orientation;
  6137. (function (Orientation) {
  6138. Orientation[Orientation["CW"] = 0] = "CW";
  6139. Orientation[Orientation["CCW"] = 1] = "CCW";
  6140. })(Orientation = BABYLON.Orientation || (BABYLON.Orientation = {}));
  6141. var Angle = /** @class */ (function () {
  6142. /**
  6143. * Creates an Angle object of "radians" radians (float).
  6144. */
  6145. function Angle(radians) {
  6146. var _this = this;
  6147. /**
  6148. * Returns the Angle value in degrees (float).
  6149. */
  6150. this.degrees = function () { return _this._radians * 180.0 / Math.PI; };
  6151. /**
  6152. * Returns the Angle value in radians (float).
  6153. */
  6154. this.radians = function () { return _this._radians; };
  6155. this._radians = radians;
  6156. if (this._radians < 0.0)
  6157. this._radians += (2.0 * Math.PI);
  6158. }
  6159. /**
  6160. * Returns a new Angle object valued with the angle value in radians between the two passed vectors.
  6161. */
  6162. Angle.BetweenTwoPoints = function (a, b) {
  6163. var delta = b.subtract(a);
  6164. var theta = Math.atan2(delta.y, delta.x);
  6165. return new Angle(theta);
  6166. };
  6167. /**
  6168. * Returns a new Angle object from the passed float in radians.
  6169. */
  6170. Angle.FromRadians = function (radians) {
  6171. return new Angle(radians);
  6172. };
  6173. /**
  6174. * Returns a new Angle object from the passed float in degrees.
  6175. */
  6176. Angle.FromDegrees = function (degrees) {
  6177. return new Angle(degrees * Math.PI / 180.0);
  6178. };
  6179. return Angle;
  6180. }());
  6181. BABYLON.Angle = Angle;
  6182. var Arc2 = /** @class */ (function () {
  6183. /**
  6184. * Creates an Arc object from the three passed points : start, middle and end.
  6185. */
  6186. function Arc2(startPoint, midPoint, endPoint) {
  6187. this.startPoint = startPoint;
  6188. this.midPoint = midPoint;
  6189. this.endPoint = endPoint;
  6190. var temp = Math.pow(midPoint.x, 2) + Math.pow(midPoint.y, 2);
  6191. var startToMid = (Math.pow(startPoint.x, 2) + Math.pow(startPoint.y, 2) - temp) / 2.;
  6192. var midToEnd = (temp - Math.pow(endPoint.x, 2) - Math.pow(endPoint.y, 2)) / 2.;
  6193. var det = (startPoint.x - midPoint.x) * (midPoint.y - endPoint.y) - (midPoint.x - endPoint.x) * (startPoint.y - midPoint.y);
  6194. 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);
  6195. this.radius = this.centerPoint.subtract(this.startPoint).length();
  6196. this.startAngle = Angle.BetweenTwoPoints(this.centerPoint, this.startPoint);
  6197. var a1 = this.startAngle.degrees();
  6198. var a2 = Angle.BetweenTwoPoints(this.centerPoint, this.midPoint).degrees();
  6199. var a3 = Angle.BetweenTwoPoints(this.centerPoint, this.endPoint).degrees();
  6200. // angles correction
  6201. if (a2 - a1 > +180.0)
  6202. a2 -= 360.0;
  6203. if (a2 - a1 < -180.0)
  6204. a2 += 360.0;
  6205. if (a3 - a2 > +180.0)
  6206. a3 -= 360.0;
  6207. if (a3 - a2 < -180.0)
  6208. a3 += 360.0;
  6209. this.orientation = (a2 - a1) < 0 ? Orientation.CW : Orientation.CCW;
  6210. this.angle = Angle.FromDegrees(this.orientation === Orientation.CW ? a1 - a3 : a3 - a1);
  6211. }
  6212. return Arc2;
  6213. }());
  6214. BABYLON.Arc2 = Arc2;
  6215. var Path2 = /** @class */ (function () {
  6216. /**
  6217. * Creates a Path2 object from the starting 2D coordinates x and y.
  6218. */
  6219. function Path2(x, y) {
  6220. this._points = new Array();
  6221. this._length = 0.0;
  6222. this.closed = false;
  6223. this._points.push(new Vector2(x, y));
  6224. }
  6225. /**
  6226. * Adds a new segment until the passed coordinates (x, y) to the current Path2.
  6227. * Returns the updated Path2.
  6228. */
  6229. Path2.prototype.addLineTo = function (x, y) {
  6230. if (this.closed) {
  6231. return this;
  6232. }
  6233. var newPoint = new Vector2(x, y);
  6234. var previousPoint = this._points[this._points.length - 1];
  6235. this._points.push(newPoint);
  6236. this._length += newPoint.subtract(previousPoint).length();
  6237. return this;
  6238. };
  6239. /**
  6240. * 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.
  6241. * Returns the updated Path2.
  6242. */
  6243. Path2.prototype.addArcTo = function (midX, midY, endX, endY, numberOfSegments) {
  6244. if (numberOfSegments === void 0) { numberOfSegments = 36; }
  6245. if (this.closed) {
  6246. return this;
  6247. }
  6248. var startPoint = this._points[this._points.length - 1];
  6249. var midPoint = new Vector2(midX, midY);
  6250. var endPoint = new Vector2(endX, endY);
  6251. var arc = new Arc2(startPoint, midPoint, endPoint);
  6252. var increment = arc.angle.radians() / numberOfSegments;
  6253. if (arc.orientation === Orientation.CW)
  6254. increment *= -1;
  6255. var currentAngle = arc.startAngle.radians() + increment;
  6256. for (var i = 0; i < numberOfSegments; i++) {
  6257. var x = Math.cos(currentAngle) * arc.radius + arc.centerPoint.x;
  6258. var y = Math.sin(currentAngle) * arc.radius + arc.centerPoint.y;
  6259. this.addLineTo(x, y);
  6260. currentAngle += increment;
  6261. }
  6262. return this;
  6263. };
  6264. /**
  6265. * Closes the Path2.
  6266. * Returns the Path2.
  6267. */
  6268. Path2.prototype.close = function () {
  6269. this.closed = true;
  6270. return this;
  6271. };
  6272. /**
  6273. * Returns the Path2 total length (float).
  6274. */
  6275. Path2.prototype.length = function () {
  6276. var result = this._length;
  6277. if (!this.closed) {
  6278. var lastPoint = this._points[this._points.length - 1];
  6279. var firstPoint = this._points[0];
  6280. result += (firstPoint.subtract(lastPoint).length());
  6281. }
  6282. return result;
  6283. };
  6284. /**
  6285. * Returns the Path2 internal array of points.
  6286. */
  6287. Path2.prototype.getPoints = function () {
  6288. return this._points;
  6289. };
  6290. /**
  6291. * Returns a new Vector2 located at a percentage of the Path2 total length on this path.
  6292. */
  6293. Path2.prototype.getPointAtLengthPosition = function (normalizedLengthPosition) {
  6294. if (normalizedLengthPosition < 0 || normalizedLengthPosition > 1) {
  6295. return Vector2.Zero();
  6296. }
  6297. var lengthPosition = normalizedLengthPosition * this.length();
  6298. var previousOffset = 0;
  6299. for (var i = 0; i < this._points.length; i++) {
  6300. var j = (i + 1) % this._points.length;
  6301. var a = this._points[i];
  6302. var b = this._points[j];
  6303. var bToA = b.subtract(a);
  6304. var nextOffset = (bToA.length() + previousOffset);
  6305. if (lengthPosition >= previousOffset && lengthPosition <= nextOffset) {
  6306. var dir = bToA.normalize();
  6307. var localOffset = lengthPosition - previousOffset;
  6308. return new Vector2(a.x + (dir.x * localOffset), a.y + (dir.y * localOffset));
  6309. }
  6310. previousOffset = nextOffset;
  6311. }
  6312. return Vector2.Zero();
  6313. };
  6314. /**
  6315. * Returns a new Path2 starting at the coordinates (x, y).
  6316. */
  6317. Path2.StartingAt = function (x, y) {
  6318. return new Path2(x, y);
  6319. };
  6320. return Path2;
  6321. }());
  6322. BABYLON.Path2 = Path2;
  6323. var Path3D = /** @class */ (function () {
  6324. /**
  6325. * new Path3D(path, normal, raw)
  6326. * Creates a Path3D. A Path3D is a logical math object, so not a mesh.
  6327. * please read the description in the tutorial : http://doc.babylonjs.com/tutorials/How_to_use_Path3D
  6328. * path : an array of Vector3, the curve axis of the Path3D
  6329. * normal (optional) : Vector3, the first wanted normal to the curve. Ex (0, 1, 0) for a vertical normal.
  6330. * raw (optional, default false) : boolean, if true the returned Path3D isn't normalized. Useful to depict path acceleration or speed.
  6331. */
  6332. function Path3D(path, firstNormal, raw) {
  6333. if (firstNormal === void 0) { firstNormal = null; }
  6334. this.path = path;
  6335. this._curve = new Array();
  6336. this._distances = new Array();
  6337. this._tangents = new Array();
  6338. this._normals = new Array();
  6339. this._binormals = new Array();
  6340. for (var p = 0; p < path.length; p++) {
  6341. this._curve[p] = path[p].clone(); // hard copy
  6342. }
  6343. this._raw = raw || false;
  6344. this._compute(firstNormal);
  6345. }
  6346. /**
  6347. * Returns the Path3D array of successive Vector3 designing its curve.
  6348. */
  6349. Path3D.prototype.getCurve = function () {
  6350. return this._curve;
  6351. };
  6352. /**
  6353. * Returns an array populated with tangent vectors on each Path3D curve point.
  6354. */
  6355. Path3D.prototype.getTangents = function () {
  6356. return this._tangents;
  6357. };
  6358. /**
  6359. * Returns an array populated with normal vectors on each Path3D curve point.
  6360. */
  6361. Path3D.prototype.getNormals = function () {
  6362. return this._normals;
  6363. };
  6364. /**
  6365. * Returns an array populated with binormal vectors on each Path3D curve point.
  6366. */
  6367. Path3D.prototype.getBinormals = function () {
  6368. return this._binormals;
  6369. };
  6370. /**
  6371. * Returns an array populated with distances (float) of the i-th point from the first curve point.
  6372. */
  6373. Path3D.prototype.getDistances = function () {
  6374. return this._distances;
  6375. };
  6376. /**
  6377. * Forces the Path3D tangent, normal, binormal and distance recomputation.
  6378. * Returns the same object updated.
  6379. */
  6380. Path3D.prototype.update = function (path, firstNormal) {
  6381. if (firstNormal === void 0) { firstNormal = null; }
  6382. for (var p = 0; p < path.length; p++) {
  6383. this._curve[p].x = path[p].x;
  6384. this._curve[p].y = path[p].y;
  6385. this._curve[p].z = path[p].z;
  6386. }
  6387. this._compute(firstNormal);
  6388. return this;
  6389. };
  6390. // private function compute() : computes tangents, normals and binormals
  6391. Path3D.prototype._compute = function (firstNormal) {
  6392. var l = this._curve.length;
  6393. // first and last tangents
  6394. this._tangents[0] = this._getFirstNonNullVector(0);
  6395. if (!this._raw) {
  6396. this._tangents[0].normalize();
  6397. }
  6398. this._tangents[l - 1] = this._curve[l - 1].subtract(this._curve[l - 2]);
  6399. if (!this._raw) {
  6400. this._tangents[l - 1].normalize();
  6401. }
  6402. // normals and binormals at first point : arbitrary vector with _normalVector()
  6403. var tg0 = this._tangents[0];
  6404. var pp0 = this._normalVector(this._curve[0], tg0, firstNormal);
  6405. this._normals[0] = pp0;
  6406. if (!this._raw) {
  6407. this._normals[0].normalize();
  6408. }
  6409. this._binormals[0] = Vector3.Cross(tg0, this._normals[0]);
  6410. if (!this._raw) {
  6411. this._binormals[0].normalize();
  6412. }
  6413. this._distances[0] = 0.0;
  6414. // normals and binormals : next points
  6415. var prev; // previous vector (segment)
  6416. var cur; // current vector (segment)
  6417. var curTang; // current tangent
  6418. // previous normal
  6419. var prevBinor; // previous binormal
  6420. for (var i = 1; i < l; i++) {
  6421. // tangents
  6422. prev = this._getLastNonNullVector(i);
  6423. if (i < l - 1) {
  6424. cur = this._getFirstNonNullVector(i);
  6425. this._tangents[i] = prev.add(cur);
  6426. this._tangents[i].normalize();
  6427. }
  6428. this._distances[i] = this._distances[i - 1] + prev.length();
  6429. // normals and binormals
  6430. // http://www.cs.cmu.edu/afs/andrew/scs/cs/15-462/web/old/asst2camera.html
  6431. curTang = this._tangents[i];
  6432. prevBinor = this._binormals[i - 1];
  6433. this._normals[i] = Vector3.Cross(prevBinor, curTang);
  6434. if (!this._raw) {
  6435. this._normals[i].normalize();
  6436. }
  6437. this._binormals[i] = Vector3.Cross(curTang, this._normals[i]);
  6438. if (!this._raw) {
  6439. this._binormals[i].normalize();
  6440. }
  6441. }
  6442. };
  6443. // private function getFirstNonNullVector(index)
  6444. // returns the first non null vector from index : curve[index + N].subtract(curve[index])
  6445. Path3D.prototype._getFirstNonNullVector = function (index) {
  6446. var i = 1;
  6447. var nNVector = this._curve[index + i].subtract(this._curve[index]);
  6448. while (nNVector.length() === 0 && index + i + 1 < this._curve.length) {
  6449. i++;
  6450. nNVector = this._curve[index + i].subtract(this._curve[index]);
  6451. }
  6452. return nNVector;
  6453. };
  6454. // private function getLastNonNullVector(index)
  6455. // returns the last non null vector from index : curve[index].subtract(curve[index - N])
  6456. Path3D.prototype._getLastNonNullVector = function (index) {
  6457. var i = 1;
  6458. var nLVector = this._curve[index].subtract(this._curve[index - i]);
  6459. while (nLVector.length() === 0 && index > i + 1) {
  6460. i++;
  6461. nLVector = this._curve[index].subtract(this._curve[index - i]);
  6462. }
  6463. return nLVector;
  6464. };
  6465. // private function normalVector(v0, vt, va) :
  6466. // returns an arbitrary point in the plane defined by the point v0 and the vector vt orthogonal to this plane
  6467. // if va is passed, it returns the va projection on the plane orthogonal to vt at the point v0
  6468. Path3D.prototype._normalVector = function (v0, vt, va) {
  6469. var normal0;
  6470. var tgl = vt.length();
  6471. if (tgl === 0.0) {
  6472. tgl = 1.0;
  6473. }
  6474. if (va === undefined || va === null) {
  6475. var point;
  6476. if (!BABYLON.Scalar.WithinEpsilon(Math.abs(vt.y) / tgl, 1.0, BABYLON.Epsilon)) {
  6477. point = new Vector3(0.0, -1.0, 0.0);
  6478. }
  6479. else if (!BABYLON.Scalar.WithinEpsilon(Math.abs(vt.x) / tgl, 1.0, BABYLON.Epsilon)) {
  6480. point = new Vector3(1.0, 0.0, 0.0);
  6481. }
  6482. else if (!BABYLON.Scalar.WithinEpsilon(Math.abs(vt.z) / tgl, 1.0, BABYLON.Epsilon)) {
  6483. point = new Vector3(0.0, 0.0, 1.0);
  6484. }
  6485. else {
  6486. point = Vector3.Zero();
  6487. }
  6488. normal0 = Vector3.Cross(vt, point);
  6489. }
  6490. else {
  6491. normal0 = Vector3.Cross(vt, va);
  6492. Vector3.CrossToRef(normal0, vt, normal0);
  6493. }
  6494. normal0.normalize();
  6495. return normal0;
  6496. };
  6497. return Path3D;
  6498. }());
  6499. BABYLON.Path3D = Path3D;
  6500. var Curve3 = /** @class */ (function () {
  6501. /**
  6502. * A Curve3 object is a logical object, so not a mesh, to handle curves in the 3D geometric space.
  6503. * A Curve3 is designed from a series of successive Vector3.
  6504. * Tuto : http://doc.babylonjs.com/tutorials/How_to_use_Curve3#curve3-object
  6505. */
  6506. function Curve3(points) {
  6507. this._length = 0.0;
  6508. this._points = points;
  6509. this._length = this._computeLength(points);
  6510. }
  6511. /**
  6512. * Returns a Curve3 object along a Quadratic Bezier curve : http://doc.babylonjs.com/tutorials/How_to_use_Curve3#quadratic-bezier-curve
  6513. * @param v0 (Vector3) the origin point of the Quadratic Bezier
  6514. * @param v1 (Vector3) the control point
  6515. * @param v2 (Vector3) the end point of the Quadratic Bezier
  6516. * @param nbPoints (integer) the wanted number of points in the curve
  6517. */
  6518. Curve3.CreateQuadraticBezier = function (v0, v1, v2, nbPoints) {
  6519. nbPoints = nbPoints > 2 ? nbPoints : 3;
  6520. var bez = new Array();
  6521. var equation = function (t, val0, val1, val2) {
  6522. var res = (1.0 - t) * (1.0 - t) * val0 + 2.0 * t * (1.0 - t) * val1 + t * t * val2;
  6523. return res;
  6524. };
  6525. for (var i = 0; i <= nbPoints; i++) {
  6526. 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)));
  6527. }
  6528. return new Curve3(bez);
  6529. };
  6530. /**
  6531. * Returns a Curve3 object along a Cubic Bezier curve : http://doc.babylonjs.com/tutorials/How_to_use_Curve3#cubic-bezier-curve
  6532. * @param v0 (Vector3) the origin point of the Cubic Bezier
  6533. * @param v1 (Vector3) the first control point
  6534. * @param v2 (Vector3) the second control point
  6535. * @param v3 (Vector3) the end point of the Cubic Bezier
  6536. * @param nbPoints (integer) the wanted number of points in the curve
  6537. */
  6538. Curve3.CreateCubicBezier = function (v0, v1, v2, v3, nbPoints) {
  6539. nbPoints = nbPoints > 3 ? nbPoints : 4;
  6540. var bez = new Array();
  6541. var equation = function (t, val0, val1, val2, val3) {
  6542. 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;
  6543. return res;
  6544. };
  6545. for (var i = 0; i <= nbPoints; i++) {
  6546. 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)));
  6547. }
  6548. return new Curve3(bez);
  6549. };
  6550. /**
  6551. * Returns a Curve3 object along a Hermite Spline curve : http://doc.babylonjs.com/tutorials/How_to_use_Curve3#hermite-spline
  6552. * @param p1 (Vector3) the origin point of the Hermite Spline
  6553. * @param t1 (Vector3) the tangent vector at the origin point
  6554. * @param p2 (Vector3) the end point of the Hermite Spline
  6555. * @param t2 (Vector3) the tangent vector at the end point
  6556. * @param nbPoints (integer) the wanted number of points in the curve
  6557. */
  6558. Curve3.CreateHermiteSpline = function (p1, t1, p2, t2, nbPoints) {
  6559. var hermite = new Array();
  6560. var step = 1.0 / nbPoints;
  6561. for (var i = 0; i <= nbPoints; i++) {
  6562. hermite.push(Vector3.Hermite(p1, t1, p2, t2, i * step));
  6563. }
  6564. return new Curve3(hermite);
  6565. };
  6566. /**
  6567. * Returns a Curve3 object along a CatmullRom Spline curve :
  6568. * @param points (array of Vector3) the points the spline must pass through. At least, four points required.
  6569. * @param nbPoints (integer) the wanted number of points between each curve control points.
  6570. */
  6571. Curve3.CreateCatmullRomSpline = function (points, nbPoints) {
  6572. var totalPoints = new Array();
  6573. totalPoints.push(points[0].clone());
  6574. Array.prototype.push.apply(totalPoints, points);
  6575. totalPoints.push(points[points.length - 1].clone());
  6576. var catmullRom = new Array();
  6577. var step = 1.0 / nbPoints;
  6578. var amount = 0.0;
  6579. for (var i = 0; i < totalPoints.length - 3; i++) {
  6580. amount = 0;
  6581. for (var c = 0; c < nbPoints; c++) {
  6582. catmullRom.push(Vector3.CatmullRom(totalPoints[i], totalPoints[i + 1], totalPoints[i + 2], totalPoints[i + 3], amount));
  6583. amount += step;
  6584. }
  6585. }
  6586. i--;
  6587. catmullRom.push(Vector3.CatmullRom(totalPoints[i], totalPoints[i + 1], totalPoints[i + 2], totalPoints[i + 3], amount));
  6588. return new Curve3(catmullRom);
  6589. };
  6590. /**
  6591. * Returns the Curve3 stored array of successive Vector3
  6592. */
  6593. Curve3.prototype.getPoints = function () {
  6594. return this._points;
  6595. };
  6596. /**
  6597. * Returns the computed length (float) of the curve.
  6598. */
  6599. Curve3.prototype.length = function () {
  6600. return this._length;
  6601. };
  6602. /**
  6603. * Returns a new instance of Curve3 object : var curve = curveA.continue(curveB);
  6604. * This new Curve3 is built by translating and sticking the curveB at the end of the curveA.
  6605. * curveA and curveB keep unchanged.
  6606. */
  6607. Curve3.prototype.continue = function (curve) {
  6608. var lastPoint = this._points[this._points.length - 1];
  6609. var continuedPoints = this._points.slice();
  6610. var curvePoints = curve.getPoints();
  6611. for (var i = 1; i < curvePoints.length; i++) {
  6612. continuedPoints.push(curvePoints[i].subtract(curvePoints[0]).add(lastPoint));
  6613. }
  6614. var continuedCurve = new Curve3(continuedPoints);
  6615. return continuedCurve;
  6616. };
  6617. Curve3.prototype._computeLength = function (path) {
  6618. var l = 0;
  6619. for (var i = 1; i < path.length; i++) {
  6620. l += (path[i].subtract(path[i - 1])).length();
  6621. }
  6622. return l;
  6623. };
  6624. return Curve3;
  6625. }());
  6626. BABYLON.Curve3 = Curve3;
  6627. // Vertex formats
  6628. var PositionNormalVertex = /** @class */ (function () {
  6629. function PositionNormalVertex(position, normal) {
  6630. if (position === void 0) { position = Vector3.Zero(); }
  6631. if (normal === void 0) { normal = Vector3.Up(); }
  6632. this.position = position;
  6633. this.normal = normal;
  6634. }
  6635. PositionNormalVertex.prototype.clone = function () {
  6636. return new PositionNormalVertex(this.position.clone(), this.normal.clone());
  6637. };
  6638. return PositionNormalVertex;
  6639. }());
  6640. BABYLON.PositionNormalVertex = PositionNormalVertex;
  6641. var PositionNormalTextureVertex = /** @class */ (function () {
  6642. function PositionNormalTextureVertex(position, normal, uv) {
  6643. if (position === void 0) { position = Vector3.Zero(); }
  6644. if (normal === void 0) { normal = Vector3.Up(); }
  6645. if (uv === void 0) { uv = Vector2.Zero(); }
  6646. this.position = position;
  6647. this.normal = normal;
  6648. this.uv = uv;
  6649. }
  6650. PositionNormalTextureVertex.prototype.clone = function () {
  6651. return new PositionNormalTextureVertex(this.position.clone(), this.normal.clone(), this.uv.clone());
  6652. };
  6653. return PositionNormalTextureVertex;
  6654. }());
  6655. BABYLON.PositionNormalTextureVertex = PositionNormalTextureVertex;
  6656. // Temporary pre-allocated objects for engine internal use
  6657. // usage in any internal function :
  6658. // var tmp = Tmp.Vector3[0]; <= gets access to the first pre-created Vector3
  6659. // There's a Tmp array per object type : int, float, Vector2, Vector3, Vector4, Quaternion, Matrix
  6660. var Tmp = /** @class */ (function () {
  6661. function Tmp() {
  6662. }
  6663. Tmp.Color3 = [Color3.Black(), Color3.Black(), Color3.Black()];
  6664. Tmp.Vector2 = [Vector2.Zero(), Vector2.Zero(), Vector2.Zero()]; // 3 temp Vector2 at once should be enough
  6665. Tmp.Vector3 = [Vector3.Zero(), Vector3.Zero(), Vector3.Zero(),
  6666. Vector3.Zero(), Vector3.Zero(), Vector3.Zero(), Vector3.Zero(), Vector3.Zero(), Vector3.Zero()]; // 9 temp Vector3 at once should be enough
  6667. Tmp.Vector4 = [Vector4.Zero(), Vector4.Zero(), Vector4.Zero()]; // 3 temp Vector4 at once should be enough
  6668. Tmp.Quaternion = [Quaternion.Zero(), Quaternion.Zero()]; // 2 temp Quaternion at once should be enough
  6669. Tmp.Matrix = [Matrix.Zero(), Matrix.Zero(),
  6670. Matrix.Zero(), Matrix.Zero(),
  6671. Matrix.Zero(), Matrix.Zero(),
  6672. Matrix.Zero(), Matrix.Zero()]; // 6 temp Matrices at once should be enough
  6673. return Tmp;
  6674. }());
  6675. BABYLON.Tmp = Tmp;
  6676. // Same as Tmp but not exported to keep it onyl for math functions to avoid conflicts
  6677. var MathTmp = /** @class */ (function () {
  6678. function MathTmp() {
  6679. }
  6680. MathTmp.Vector3 = [Vector3.Zero()];
  6681. MathTmp.Matrix = [Matrix.Zero(), Matrix.Zero()];
  6682. MathTmp.Quaternion = [Quaternion.Zero()];
  6683. return MathTmp;
  6684. }());
  6685. })(BABYLON || (BABYLON = {}));
  6686. //# sourceMappingURL=babylon.math.js.map
  6687. var BABYLON;
  6688. (function (BABYLON) {
  6689. var Scalar = /** @class */ (function () {
  6690. function Scalar() {
  6691. }
  6692. /**
  6693. * Boolean : true if the absolute difference between a and b is lower than epsilon (default = 1.401298E-45)
  6694. */
  6695. Scalar.WithinEpsilon = function (a, b, epsilon) {
  6696. if (epsilon === void 0) { epsilon = 1.401298E-45; }
  6697. var num = a - b;
  6698. return -epsilon <= num && num <= epsilon;
  6699. };
  6700. /**
  6701. * Returns a string : the upper case translation of the number i to hexadecimal.
  6702. */
  6703. Scalar.ToHex = function (i) {
  6704. var str = i.toString(16);
  6705. if (i <= 15) {
  6706. return ("0" + str).toUpperCase();
  6707. }
  6708. return str.toUpperCase();
  6709. };
  6710. /**
  6711. * Returns -1 if value is negative and +1 is value is positive.
  6712. * Returns the value itself if it's equal to zero.
  6713. */
  6714. Scalar.Sign = function (value) {
  6715. value = +value; // convert to a number
  6716. if (value === 0 || isNaN(value))
  6717. return value;
  6718. return value > 0 ? 1 : -1;
  6719. };
  6720. /**
  6721. * Returns the value itself if it's between min and max.
  6722. * Returns min if the value is lower than min.
  6723. * Returns max if the value is greater than max.
  6724. */
  6725. Scalar.Clamp = function (value, min, max) {
  6726. if (min === void 0) { min = 0; }
  6727. if (max === void 0) { max = 1; }
  6728. return Math.min(max, Math.max(min, value));
  6729. };
  6730. /**
  6731. * Returns the log2 of value.
  6732. */
  6733. Scalar.Log2 = function (value) {
  6734. return Math.log(value) * Math.LOG2E;
  6735. };
  6736. /**
  6737. * Loops the value, so that it is never larger than length and never smaller than 0.
  6738. *
  6739. * This is similar to the modulo operator but it works with floating point numbers.
  6740. * For example, using 3.0 for t and 2.5 for length, the result would be 0.5.
  6741. * With t = 5 and length = 2.5, the result would be 0.0.
  6742. * Note, however, that the behaviour is not defined for negative numbers as it is for the modulo operator
  6743. */
  6744. Scalar.Repeat = function (value, length) {
  6745. return value - Math.floor(value / length) * length;
  6746. };
  6747. /**
  6748. * Normalize the value between 0.0 and 1.0 using min and max values
  6749. */
  6750. Scalar.Normalize = function (value, min, max) {
  6751. return (value - min) / (max - min);
  6752. };
  6753. /**
  6754. * Denormalize the value from 0.0 and 1.0 using min and max values
  6755. */
  6756. Scalar.Denormalize = function (normalized, min, max) {
  6757. return (normalized * (max - min) + min);
  6758. };
  6759. /**
  6760. * Calculates the shortest difference between two given angles given in degrees.
  6761. */
  6762. Scalar.DeltaAngle = function (current, target) {
  6763. var num = Scalar.Repeat(target - current, 360.0);
  6764. if (num > 180.0) {
  6765. num -= 360.0;
  6766. }
  6767. return num;
  6768. };
  6769. /**
  6770. * PingPongs the value t, so that it is never larger than length and never smaller than 0.
  6771. *
  6772. * The returned value will move back and forth between 0 and length
  6773. */
  6774. Scalar.PingPong = function (tx, length) {
  6775. var t = Scalar.Repeat(tx, length * 2.0);
  6776. return length - Math.abs(t - length);
  6777. };
  6778. /**
  6779. * Interpolates between min and max with smoothing at the limits.
  6780. *
  6781. * This function interpolates between min and max in a similar way to Lerp. However, the interpolation will gradually speed up
  6782. * from the start and slow down toward the end. This is useful for creating natural-looking animation, fading and other transitions.
  6783. */
  6784. Scalar.SmoothStep = function (from, to, tx) {
  6785. var t = Scalar.Clamp(tx);
  6786. t = -2.0 * t * t * t + 3.0 * t * t;
  6787. return to * t + from * (1.0 - t);
  6788. };
  6789. /**
  6790. * Moves a value current towards target.
  6791. *
  6792. * This is essentially the same as Mathf.Lerp but instead the function will ensure that the speed never exceeds maxDelta.
  6793. * Negative values of maxDelta pushes the value away from target.
  6794. */
  6795. Scalar.MoveTowards = function (current, target, maxDelta) {
  6796. var result = 0;
  6797. if (Math.abs(target - current) <= maxDelta) {
  6798. result = target;
  6799. }
  6800. else {
  6801. result = current + Scalar.Sign(target - current) * maxDelta;
  6802. }
  6803. return result;
  6804. };
  6805. /**
  6806. * Same as MoveTowards but makes sure the values interpolate correctly when they wrap around 360 degrees.
  6807. *
  6808. * Variables current and target are assumed to be in degrees. For optimization reasons, negative values of maxDelta
  6809. * are not supported and may cause oscillation. To push current away from a target angle, add 180 to that angle instead.
  6810. */
  6811. Scalar.MoveTowardsAngle = function (current, target, maxDelta) {
  6812. var num = Scalar.DeltaAngle(current, target);
  6813. var result = 0;
  6814. if (-maxDelta < num && num < maxDelta) {
  6815. result = target;
  6816. }
  6817. else {
  6818. target = current + num;
  6819. result = Scalar.MoveTowards(current, target, maxDelta);
  6820. }
  6821. return result;
  6822. };
  6823. /**
  6824. * Creates a new scalar with values linearly interpolated of "amount" between the start scalar and the end scalar.
  6825. */
  6826. Scalar.Lerp = function (start, end, amount) {
  6827. return start + ((end - start) * amount);
  6828. };
  6829. /**
  6830. * Same as Lerp but makes sure the values interpolate correctly when they wrap around 360 degrees.
  6831. * The parameter t is clamped to the range [0, 1]. Variables a and b are assumed to be in degrees.
  6832. */
  6833. Scalar.LerpAngle = function (start, end, amount) {
  6834. var num = Scalar.Repeat(end - start, 360.0);
  6835. if (num > 180.0) {
  6836. num -= 360.0;
  6837. }
  6838. return start + num * Scalar.Clamp(amount);
  6839. };
  6840. /**
  6841. * Calculates the linear parameter t that produces the interpolant value within the range [a, b].
  6842. */
  6843. Scalar.InverseLerp = function (a, b, value) {
  6844. var result = 0;
  6845. if (a != b) {
  6846. result = Scalar.Clamp((value - a) / (b - a));
  6847. }
  6848. else {
  6849. result = 0.0;
  6850. }
  6851. return result;
  6852. };
  6853. /**
  6854. * Returns a new scalar located for "amount" (float) on the Hermite spline defined by the scalars "value1", "value3", "tangent1", "tangent2".
  6855. */
  6856. Scalar.Hermite = function (value1, tangent1, value2, tangent2, amount) {
  6857. var squared = amount * amount;
  6858. var cubed = amount * squared;
  6859. var part1 = ((2.0 * cubed) - (3.0 * squared)) + 1.0;
  6860. var part2 = (-2.0 * cubed) + (3.0 * squared);
  6861. var part3 = (cubed - (2.0 * squared)) + amount;
  6862. var part4 = cubed - squared;
  6863. return (((value1 * part1) + (value2 * part2)) + (tangent1 * part3)) + (tangent2 * part4);
  6864. };
  6865. /**
  6866. * Returns a random float number between and min and max values
  6867. */
  6868. Scalar.RandomRange = function (min, max) {
  6869. if (min === max)
  6870. return min;
  6871. return ((Math.random() * (max - min)) + min);
  6872. };
  6873. /**
  6874. * This function returns percentage of a number in a given range.
  6875. *
  6876. * RangeToPercent(40,20,60) will return 0.5 (50%)
  6877. * RangeToPercent(34,0,100) will return 0.34 (34%)
  6878. */
  6879. Scalar.RangeToPercent = function (number, min, max) {
  6880. return ((number - min) / (max - min));
  6881. };
  6882. /**
  6883. * This function returns number that corresponds to the percentage in a given range.
  6884. *
  6885. * PercentToRange(0.34,0,100) will return 34.
  6886. */
  6887. Scalar.PercentToRange = function (percent, min, max) {
  6888. return ((max - min) * percent + min);
  6889. };
  6890. /**
  6891. * Returns the angle converted to equivalent value between -Math.PI and Math.PI radians.
  6892. * @param angle The angle to normalize in radian.
  6893. * @return The converted angle.
  6894. */
  6895. Scalar.NormalizeRadians = function (angle) {
  6896. // More precise but slower version kept for reference.
  6897. // angle = angle % Tools.TwoPi;
  6898. // angle = (angle + Tools.TwoPi) % Tools.TwoPi;
  6899. //if (angle > Math.PI) {
  6900. // angle -= Tools.TwoPi;
  6901. //}
  6902. angle -= (Scalar.TwoPi * Math.floor((angle + Math.PI) / Scalar.TwoPi));
  6903. return angle;
  6904. };
  6905. /**
  6906. * Two pi constants convenient for computation.
  6907. */
  6908. Scalar.TwoPi = Math.PI * 2;
  6909. return Scalar;
  6910. }());
  6911. BABYLON.Scalar = Scalar;
  6912. })(BABYLON || (BABYLON = {}));
  6913. //# sourceMappingURL=babylon.math.scalar.js.map
  6914. //# sourceMappingURL=babylon.mixins.js.map
  6915. // Type definitions for WebGL 2, Editor's Draft Fri Feb 24 16:10:18 2017 -0800
  6916. // Project: https://www.khronos.org/registry/webgl/specs/latest/2.0/
  6917. // Definitions by: Nico Kemnitz <https://github.com/nkemnitz/>
  6918. // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
  6919. //# sourceMappingURL=babylon.webgl2.js.map
  6920. var BABYLON;
  6921. (function (BABYLON) {
  6922. var __decoratorInitialStore = {};
  6923. var __mergedStore = {};
  6924. var _copySource = function (creationFunction, source, instanciate) {
  6925. var destination = creationFunction();
  6926. // Tags
  6927. if (BABYLON.Tags) {
  6928. BABYLON.Tags.AddTagsTo(destination, source.tags);
  6929. }
  6930. var classStore = getMergedStore(destination);
  6931. // Properties
  6932. for (var property in classStore) {
  6933. var propertyDescriptor = classStore[property];
  6934. var sourceProperty = source[property];
  6935. var propertyType = propertyDescriptor.type;
  6936. if (sourceProperty !== undefined && sourceProperty !== null) {
  6937. switch (propertyType) {
  6938. case 0: // Value
  6939. case 6:// Mesh reference
  6940. destination[property] = sourceProperty;
  6941. break;
  6942. case 1:// Texture
  6943. destination[property] = (instanciate || sourceProperty.isRenderTarget) ? sourceProperty : sourceProperty.clone();
  6944. break;
  6945. case 2: // Color3
  6946. case 3: // FresnelParameters
  6947. case 4: // Vector2
  6948. case 5: // Vector3
  6949. case 7: // Color Curves
  6950. case 10:// Quaternion
  6951. destination[property] = instanciate ? sourceProperty : sourceProperty.clone();
  6952. break;
  6953. }
  6954. }
  6955. }
  6956. return destination;
  6957. };
  6958. function getDirectStore(target) {
  6959. var classKey = target.getClassName();
  6960. if (!__decoratorInitialStore[classKey]) {
  6961. __decoratorInitialStore[classKey] = {};
  6962. }
  6963. return __decoratorInitialStore[classKey];
  6964. }
  6965. /**
  6966. * Return the list of properties flagged as serializable
  6967. * @param target: host object
  6968. */
  6969. function getMergedStore(target) {
  6970. var classKey = target.getClassName();
  6971. if (__mergedStore[classKey]) {
  6972. return __mergedStore[classKey];
  6973. }
  6974. __mergedStore[classKey] = {};
  6975. var store = __mergedStore[classKey];
  6976. var currentTarget = target;
  6977. var currentKey = classKey;
  6978. while (currentKey) {
  6979. var initialStore = __decoratorInitialStore[currentKey];
  6980. for (var property in initialStore) {
  6981. store[property] = initialStore[property];
  6982. }
  6983. var parent_1 = void 0;
  6984. var done = false;
  6985. do {
  6986. parent_1 = Object.getPrototypeOf(currentTarget);
  6987. if (!parent_1.getClassName) {
  6988. done = true;
  6989. break;
  6990. }
  6991. if (parent_1.getClassName() !== currentKey) {
  6992. break;
  6993. }
  6994. currentTarget = parent_1;
  6995. } while (parent_1);
  6996. if (done) {
  6997. break;
  6998. }
  6999. currentKey = parent_1.getClassName();
  7000. currentTarget = parent_1;
  7001. }
  7002. return store;
  7003. }
  7004. function generateSerializableMember(type, sourceName) {
  7005. return function (target, propertyKey) {
  7006. var classStore = getDirectStore(target);
  7007. if (!classStore[propertyKey]) {
  7008. classStore[propertyKey] = { type: type, sourceName: sourceName };
  7009. }
  7010. };
  7011. }
  7012. function generateExpandMember(setCallback, targetKey) {
  7013. if (targetKey === void 0) { targetKey = null; }
  7014. return function (target, propertyKey) {
  7015. var key = targetKey || ("_" + propertyKey);
  7016. Object.defineProperty(target, propertyKey, {
  7017. get: function () {
  7018. return this[key];
  7019. },
  7020. set: function (value) {
  7021. if (this[key] === value) {
  7022. return;
  7023. }
  7024. this[key] = value;
  7025. target[setCallback].apply(this);
  7026. },
  7027. enumerable: true,
  7028. configurable: true
  7029. });
  7030. };
  7031. }
  7032. function expandToProperty(callback, targetKey) {
  7033. if (targetKey === void 0) { targetKey = null; }
  7034. return generateExpandMember(callback, targetKey);
  7035. }
  7036. BABYLON.expandToProperty = expandToProperty;
  7037. function serialize(sourceName) {
  7038. return generateSerializableMember(0, sourceName); // value member
  7039. }
  7040. BABYLON.serialize = serialize;
  7041. function serializeAsTexture(sourceName) {
  7042. return generateSerializableMember(1, sourceName); // texture member
  7043. }
  7044. BABYLON.serializeAsTexture = serializeAsTexture;
  7045. function serializeAsColor3(sourceName) {
  7046. return generateSerializableMember(2, sourceName); // color3 member
  7047. }
  7048. BABYLON.serializeAsColor3 = serializeAsColor3;
  7049. function serializeAsFresnelParameters(sourceName) {
  7050. return generateSerializableMember(3, sourceName); // fresnel parameters member
  7051. }
  7052. BABYLON.serializeAsFresnelParameters = serializeAsFresnelParameters;
  7053. function serializeAsVector2(sourceName) {
  7054. return generateSerializableMember(4, sourceName); // vector2 member
  7055. }
  7056. BABYLON.serializeAsVector2 = serializeAsVector2;
  7057. function serializeAsVector3(sourceName) {
  7058. return generateSerializableMember(5, sourceName); // vector3 member
  7059. }
  7060. BABYLON.serializeAsVector3 = serializeAsVector3;
  7061. function serializeAsMeshReference(sourceName) {
  7062. return generateSerializableMember(6, sourceName); // mesh reference member
  7063. }
  7064. BABYLON.serializeAsMeshReference = serializeAsMeshReference;
  7065. function serializeAsColorCurves(sourceName) {
  7066. return generateSerializableMember(7, sourceName); // color curves
  7067. }
  7068. BABYLON.serializeAsColorCurves = serializeAsColorCurves;
  7069. function serializeAsColor4(sourceName) {
  7070. return generateSerializableMember(8, sourceName); // color 4
  7071. }
  7072. BABYLON.serializeAsColor4 = serializeAsColor4;
  7073. function serializeAsImageProcessingConfiguration(sourceName) {
  7074. return generateSerializableMember(9, sourceName); // image processing
  7075. }
  7076. BABYLON.serializeAsImageProcessingConfiguration = serializeAsImageProcessingConfiguration;
  7077. function serializeAsQuaternion(sourceName) {
  7078. return generateSerializableMember(10, sourceName); // quaternion member
  7079. }
  7080. BABYLON.serializeAsQuaternion = serializeAsQuaternion;
  7081. var SerializationHelper = /** @class */ (function () {
  7082. function SerializationHelper() {
  7083. }
  7084. SerializationHelper.Serialize = function (entity, serializationObject) {
  7085. if (!serializationObject) {
  7086. serializationObject = {};
  7087. }
  7088. // Tags
  7089. if (BABYLON.Tags) {
  7090. serializationObject.tags = BABYLON.Tags.GetTags(entity);
  7091. }
  7092. var serializedProperties = getMergedStore(entity);
  7093. // Properties
  7094. for (var property in serializedProperties) {
  7095. var propertyDescriptor = serializedProperties[property];
  7096. var targetPropertyName = propertyDescriptor.sourceName || property;
  7097. var propertyType = propertyDescriptor.type;
  7098. var sourceProperty = entity[property];
  7099. if (sourceProperty !== undefined && sourceProperty !== null) {
  7100. switch (propertyType) {
  7101. case 0:// Value
  7102. serializationObject[targetPropertyName] = sourceProperty;
  7103. break;
  7104. case 1:// Texture
  7105. serializationObject[targetPropertyName] = sourceProperty.serialize();
  7106. break;
  7107. case 2:// Color3
  7108. serializationObject[targetPropertyName] = sourceProperty.asArray();
  7109. break;
  7110. case 3:// FresnelParameters
  7111. serializationObject[targetPropertyName] = sourceProperty.serialize();
  7112. break;
  7113. case 4:// Vector2
  7114. serializationObject[targetPropertyName] = sourceProperty.asArray();
  7115. break;
  7116. case 5:// Vector3
  7117. serializationObject[targetPropertyName] = sourceProperty.asArray();
  7118. break;
  7119. case 6:// Mesh reference
  7120. serializationObject[targetPropertyName] = sourceProperty.id;
  7121. break;
  7122. case 7:// Color Curves
  7123. serializationObject[targetPropertyName] = sourceProperty.serialize();
  7124. break;
  7125. case 8:// Color 4
  7126. serializationObject[targetPropertyName] = sourceProperty.asArray();
  7127. break;
  7128. case 9:// Image Processing
  7129. serializationObject[targetPropertyName] = sourceProperty.serialize();
  7130. break;
  7131. }
  7132. }
  7133. }
  7134. return serializationObject;
  7135. };
  7136. SerializationHelper.Parse = function (creationFunction, source, scene, rootUrl) {
  7137. if (rootUrl === void 0) { rootUrl = null; }
  7138. var destination = creationFunction();
  7139. if (!rootUrl) {
  7140. rootUrl = "";
  7141. }
  7142. // Tags
  7143. if (BABYLON.Tags) {
  7144. BABYLON.Tags.AddTagsTo(destination, source.tags);
  7145. }
  7146. var classStore = getMergedStore(destination);
  7147. // Properties
  7148. for (var property in classStore) {
  7149. var propertyDescriptor = classStore[property];
  7150. var sourceProperty = source[propertyDescriptor.sourceName || property];
  7151. var propertyType = propertyDescriptor.type;
  7152. if (sourceProperty !== undefined && sourceProperty !== null) {
  7153. var dest = destination;
  7154. switch (propertyType) {
  7155. case 0:// Value
  7156. dest[property] = sourceProperty;
  7157. break;
  7158. case 1:// Texture
  7159. if (scene) {
  7160. dest[property] = BABYLON.Texture.Parse(sourceProperty, scene, rootUrl);
  7161. }
  7162. break;
  7163. case 2:// Color3
  7164. dest[property] = BABYLON.Color3.FromArray(sourceProperty);
  7165. break;
  7166. case 3:// FresnelParameters
  7167. dest[property] = BABYLON.FresnelParameters.Parse(sourceProperty);
  7168. break;
  7169. case 4:// Vector2
  7170. dest[property] = BABYLON.Vector2.FromArray(sourceProperty);
  7171. break;
  7172. case 5:// Vector3
  7173. dest[property] = BABYLON.Vector3.FromArray(sourceProperty);
  7174. break;
  7175. case 6:// Mesh reference
  7176. if (scene) {
  7177. dest[property] = scene.getLastMeshByID(sourceProperty);
  7178. }
  7179. break;
  7180. case 7:// Color Curves
  7181. dest[property] = BABYLON.ColorCurves.Parse(sourceProperty);
  7182. break;
  7183. case 8:// Color 4
  7184. dest[property] = BABYLON.Color4.FromArray(sourceProperty);
  7185. break;
  7186. case 9:// Image Processing
  7187. dest[property] = BABYLON.ImageProcessingConfiguration.Parse(sourceProperty);
  7188. break;
  7189. }
  7190. }
  7191. }
  7192. return destination;
  7193. };
  7194. SerializationHelper.Clone = function (creationFunction, source) {
  7195. return _copySource(creationFunction, source, false);
  7196. };
  7197. SerializationHelper.Instanciate = function (creationFunction, source) {
  7198. return _copySource(creationFunction, source, true);
  7199. };
  7200. return SerializationHelper;
  7201. }());
  7202. BABYLON.SerializationHelper = SerializationHelper;
  7203. })(BABYLON || (BABYLON = {}));
  7204. //# sourceMappingURL=babylon.decorators.js.map
  7205. var BABYLON;
  7206. (function (BABYLON) {
  7207. /**
  7208. * Wrapper class for promise with external resolve and reject.
  7209. */
  7210. var Deferred = /** @class */ (function () {
  7211. /**
  7212. * Constructor for this deferred object.
  7213. */
  7214. function Deferred() {
  7215. var _this = this;
  7216. this.promise = new Promise(function (resolve, reject) {
  7217. _this._resolve = resolve;
  7218. _this._reject = reject;
  7219. });
  7220. }
  7221. Object.defineProperty(Deferred.prototype, "resolve", {
  7222. /**
  7223. * The resolve method of the promise associated with this deferred object.
  7224. */
  7225. get: function () {
  7226. return this._resolve;
  7227. },
  7228. enumerable: true,
  7229. configurable: true
  7230. });
  7231. Object.defineProperty(Deferred.prototype, "reject", {
  7232. /**
  7233. * The reject method of the promise associated with this deferred object.
  7234. */
  7235. get: function () {
  7236. return this._reject;
  7237. },
  7238. enumerable: true,
  7239. configurable: true
  7240. });
  7241. return Deferred;
  7242. }());
  7243. BABYLON.Deferred = Deferred;
  7244. })(BABYLON || (BABYLON = {}));
  7245. //# sourceMappingURL=babylon.deferred.js.map
  7246. var BABYLON;
  7247. (function (BABYLON) {
  7248. /**
  7249. * A class serves as a medium between the observable and its observers
  7250. */
  7251. var EventState = /** @class */ (function () {
  7252. /**
  7253. * Create a new EventState
  7254. * @param mask defines the mask associated with this state
  7255. * @param skipNextObservers defines a flag which will instruct the observable to skip following observers when set to true
  7256. * @param target defines the original target of the state
  7257. * @param currentTarget defines the current target of the state
  7258. */
  7259. function EventState(mask, skipNextObservers, target, currentTarget) {
  7260. if (skipNextObservers === void 0) { skipNextObservers = false; }
  7261. this.initalize(mask, skipNextObservers, target, currentTarget);
  7262. }
  7263. /**
  7264. * Initialize the current event state
  7265. * @param mask defines the mask associated with this state
  7266. * @param skipNextObservers defines a flag which will instruct the observable to skip following observers when set to true
  7267. * @param target defines the original target of the state
  7268. * @param currentTarget defines the current target of the state
  7269. * @returns the current event state
  7270. */
  7271. EventState.prototype.initalize = function (mask, skipNextObservers, target, currentTarget) {
  7272. if (skipNextObservers === void 0) { skipNextObservers = false; }
  7273. this.mask = mask;
  7274. this.skipNextObservers = skipNextObservers;
  7275. this.target = target;
  7276. this.currentTarget = currentTarget;
  7277. return this;
  7278. };
  7279. return EventState;
  7280. }());
  7281. BABYLON.EventState = EventState;
  7282. /**
  7283. * Represent an Observer registered to a given Observable object.
  7284. */
  7285. var Observer = /** @class */ (function () {
  7286. /**
  7287. * Creates a new observer
  7288. * @param callback defines the callback to call when the observer is notified
  7289. * @param mask defines the mask of the observer (used to filter notifications)
  7290. * @param scope defines the current scope used to restore the JS context
  7291. */
  7292. function Observer(
  7293. /**
  7294. * Defines the callback to call when the observer is notified
  7295. */
  7296. callback,
  7297. /**
  7298. * Defines the mask of the observer (used to filter notifications)
  7299. */
  7300. mask,
  7301. /**
  7302. * Defines the current scope used to restore the JS context
  7303. */
  7304. scope) {
  7305. if (scope === void 0) { scope = null; }
  7306. this.callback = callback;
  7307. this.mask = mask;
  7308. this.scope = scope;
  7309. /** @ignore */
  7310. this._willBeUnregistered = false;
  7311. /**
  7312. * Gets or sets a property defining that the observer as to be unregistered after the next notification
  7313. */
  7314. this.unregisterOnNextCall = false;
  7315. }
  7316. return Observer;
  7317. }());
  7318. BABYLON.Observer = Observer;
  7319. /**
  7320. * Represent a list of observers registered to multiple Observables object.
  7321. */
  7322. var MultiObserver = /** @class */ (function () {
  7323. function MultiObserver() {
  7324. }
  7325. /**
  7326. * Release associated resources
  7327. */
  7328. MultiObserver.prototype.dispose = function () {
  7329. if (this._observers && this._observables) {
  7330. for (var index = 0; index < this._observers.length; index++) {
  7331. this._observables[index].remove(this._observers[index]);
  7332. }
  7333. }
  7334. this._observers = null;
  7335. this._observables = null;
  7336. };
  7337. /**
  7338. * Raise a callback when one of the observable will notify
  7339. * @param observables defines a list of observables to watch
  7340. * @param callback defines the callback to call on notification
  7341. * @param mask defines the mask used to filter notifications
  7342. * @param scope defines the current scope used to restore the JS context
  7343. * @returns the new MultiObserver
  7344. */
  7345. MultiObserver.Watch = function (observables, callback, mask, scope) {
  7346. if (mask === void 0) { mask = -1; }
  7347. if (scope === void 0) { scope = null; }
  7348. var result = new MultiObserver();
  7349. result._observers = new Array();
  7350. result._observables = observables;
  7351. for (var _i = 0, observables_1 = observables; _i < observables_1.length; _i++) {
  7352. var observable = observables_1[_i];
  7353. var observer = observable.add(callback, mask, false, scope);
  7354. if (observer) {
  7355. result._observers.push(observer);
  7356. }
  7357. }
  7358. return result;
  7359. };
  7360. return MultiObserver;
  7361. }());
  7362. BABYLON.MultiObserver = MultiObserver;
  7363. /**
  7364. * The Observable class is a simple implementation of the Observable pattern.
  7365. * 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.
  7366. * This enable a more fine grained execution without having to rely on multiple different Observable objects.
  7367. * 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).
  7368. * 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.
  7369. */
  7370. var Observable = /** @class */ (function () {
  7371. /**
  7372. * Creates a new observable
  7373. * @param onObserverAdded defines a callback to call when a new observer is added
  7374. */
  7375. function Observable(onObserverAdded) {
  7376. this._observers = new Array();
  7377. this._eventState = new EventState(0);
  7378. if (onObserverAdded) {
  7379. this._onObserverAdded = onObserverAdded;
  7380. }
  7381. }
  7382. /**
  7383. * Create a new Observer with the specified callback
  7384. * @param callback the callback that will be executed for that Observer
  7385. * @param mask the mask used to filter observers
  7386. * @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.
  7387. * @param scope optional scope for the callback to be called from
  7388. * @param unregisterOnFirstCall defines if the observer as to be unregistered after the next notification
  7389. * @returns the new observer created for the callback
  7390. */
  7391. Observable.prototype.add = function (callback, mask, insertFirst, scope, unregisterOnFirstCall) {
  7392. if (mask === void 0) { mask = -1; }
  7393. if (insertFirst === void 0) { insertFirst = false; }
  7394. if (scope === void 0) { scope = null; }
  7395. if (unregisterOnFirstCall === void 0) { unregisterOnFirstCall = false; }
  7396. if (!callback) {
  7397. return null;
  7398. }
  7399. var observer = new Observer(callback, mask, scope);
  7400. observer.unregisterOnNextCall = unregisterOnFirstCall;
  7401. if (insertFirst) {
  7402. this._observers.unshift(observer);
  7403. }
  7404. else {
  7405. this._observers.push(observer);
  7406. }
  7407. if (this._onObserverAdded) {
  7408. this._onObserverAdded(observer);
  7409. }
  7410. return observer;
  7411. };
  7412. /**
  7413. * Remove an Observer from the Observable object
  7414. * @param observer the instance of the Observer to remove
  7415. * @returns false if it doesn't belong to this Observable
  7416. */
  7417. Observable.prototype.remove = function (observer) {
  7418. if (!observer) {
  7419. return false;
  7420. }
  7421. var index = this._observers.indexOf(observer);
  7422. if (index !== -1) {
  7423. this._observers.splice(index, 1);
  7424. return true;
  7425. }
  7426. return false;
  7427. };
  7428. /**
  7429. * Remove a callback from the Observable object
  7430. * @param callback the callback to remove
  7431. * @param scope optional scope. If used only the callbacks with this scope will be removed
  7432. * @returns false if it doesn't belong to this Observable
  7433. */
  7434. Observable.prototype.removeCallback = function (callback, scope) {
  7435. for (var index = 0; index < this._observers.length; index++) {
  7436. if (this._observers[index].callback === callback && (!scope || scope === this._observers[index].scope)) {
  7437. this._observers.splice(index, 1);
  7438. return true;
  7439. }
  7440. }
  7441. return false;
  7442. };
  7443. Observable.prototype._deferUnregister = function (observer) {
  7444. var _this = this;
  7445. observer.unregisterOnNextCall = false;
  7446. observer._willBeUnregistered = true;
  7447. BABYLON.Tools.SetImmediate(function () {
  7448. _this.remove(observer);
  7449. });
  7450. };
  7451. /**
  7452. * Notify all Observers by calling their respective callback with the given data
  7453. * Will return true if all observers were executed, false if an observer set skipNextObservers to true, then prevent the subsequent ones to execute
  7454. * @param eventData defines the data to send to all observers
  7455. * @param mask defines the mask of the current notification (observers with incompatible mask (ie mask & observer.mask === 0) will not be notified)
  7456. * @param target defines the original target of the state
  7457. * @param currentTarget defines the current target of the state
  7458. * @returns false if the complete observer chain was not processed (because one observer set the skipNextObservers to true)
  7459. */
  7460. Observable.prototype.notifyObservers = function (eventData, mask, target, currentTarget) {
  7461. if (mask === void 0) { mask = -1; }
  7462. if (!this._observers.length) {
  7463. return true;
  7464. }
  7465. var state = this._eventState;
  7466. state.mask = mask;
  7467. state.target = target;
  7468. state.currentTarget = currentTarget;
  7469. state.skipNextObservers = false;
  7470. state.lastReturnValue = eventData;
  7471. for (var _i = 0, _a = this._observers; _i < _a.length; _i++) {
  7472. var obs = _a[_i];
  7473. if (obs._willBeUnregistered) {
  7474. continue;
  7475. }
  7476. if (obs.mask & mask) {
  7477. if (obs.scope) {
  7478. state.lastReturnValue = obs.callback.apply(obs.scope, [eventData, state]);
  7479. }
  7480. else {
  7481. state.lastReturnValue = obs.callback(eventData, state);
  7482. }
  7483. if (obs.unregisterOnNextCall) {
  7484. this._deferUnregister(obs);
  7485. }
  7486. }
  7487. if (state.skipNextObservers) {
  7488. return false;
  7489. }
  7490. }
  7491. return true;
  7492. };
  7493. /**
  7494. * Calling this will execute each callback, expecting it to be a promise or return a value.
  7495. * If at any point in the chain one function fails, the promise will fail and the execution will not continue.
  7496. * This is useful when a chain of events (sometimes async events) is needed to initialize a certain object
  7497. * and it is crucial that all callbacks will be executed.
  7498. * The order of the callbacks is kept, callbacks are not executed parallel.
  7499. *
  7500. * @param eventData The data to be sent to each callback
  7501. * @param mask is used to filter observers defaults to -1
  7502. * @param target defines the callback target (see EventState)
  7503. * @param currentTarget defines he current object in the bubbling phase
  7504. * @returns {Promise<T>} will return a Promise than resolves when all callbacks executed successfully.
  7505. */
  7506. Observable.prototype.notifyObserversWithPromise = function (eventData, mask, target, currentTarget) {
  7507. var _this = this;
  7508. if (mask === void 0) { mask = -1; }
  7509. // create an empty promise
  7510. var p = Promise.resolve(eventData);
  7511. // no observers? return this promise.
  7512. if (!this._observers.length) {
  7513. return p;
  7514. }
  7515. var state = this._eventState;
  7516. state.mask = mask;
  7517. state.target = target;
  7518. state.currentTarget = currentTarget;
  7519. state.skipNextObservers = false;
  7520. // execute one callback after another (not using Promise.all, the order is important)
  7521. this._observers.forEach(function (obs) {
  7522. if (state.skipNextObservers) {
  7523. return;
  7524. }
  7525. if (obs._willBeUnregistered) {
  7526. return;
  7527. }
  7528. if (obs.mask & mask) {
  7529. if (obs.scope) {
  7530. p = p.then(function (lastReturnedValue) {
  7531. state.lastReturnValue = lastReturnedValue;
  7532. return obs.callback.apply(obs.scope, [eventData, state]);
  7533. });
  7534. }
  7535. else {
  7536. p = p.then(function (lastReturnedValue) {
  7537. state.lastReturnValue = lastReturnedValue;
  7538. return obs.callback(eventData, state);
  7539. });
  7540. }
  7541. if (obs.unregisterOnNextCall) {
  7542. _this._deferUnregister(obs);
  7543. }
  7544. }
  7545. });
  7546. // return the eventData
  7547. return p.then(function () { return eventData; });
  7548. };
  7549. /**
  7550. * Notify a specific observer
  7551. * @param observer defines the observer to notify
  7552. * @param eventData defines the data to be sent to each callback
  7553. * @param mask is used to filter observers defaults to -1
  7554. */
  7555. Observable.prototype.notifyObserver = function (observer, eventData, mask) {
  7556. if (mask === void 0) { mask = -1; }
  7557. var state = this._eventState;
  7558. state.mask = mask;
  7559. state.skipNextObservers = false;
  7560. observer.callback(eventData, state);
  7561. };
  7562. /**
  7563. * Gets a boolean indicating if the observable has at least one observer
  7564. * @returns true is the Observable has at least one Observer registered
  7565. */
  7566. Observable.prototype.hasObservers = function () {
  7567. return this._observers.length > 0;
  7568. };
  7569. /**
  7570. * Clear the list of observers
  7571. */
  7572. Observable.prototype.clear = function () {
  7573. this._observers = new Array();
  7574. this._onObserverAdded = null;
  7575. };
  7576. /**
  7577. * Clone the current observable
  7578. * @returns a new observable
  7579. */
  7580. Observable.prototype.clone = function () {
  7581. var result = new Observable();
  7582. result._observers = this._observers.slice(0);
  7583. return result;
  7584. };
  7585. /**
  7586. * Does this observable handles observer registered with a given mask
  7587. * @param mask defines the mask to be tested
  7588. * @return whether or not one observer registered with the given mask is handeled
  7589. **/
  7590. Observable.prototype.hasSpecificMask = function (mask) {
  7591. if (mask === void 0) { mask = -1; }
  7592. for (var _i = 0, _a = this._observers; _i < _a.length; _i++) {
  7593. var obs = _a[_i];
  7594. if (obs.mask & mask || obs.mask === mask) {
  7595. return true;
  7596. }
  7597. }
  7598. return false;
  7599. };
  7600. return Observable;
  7601. }());
  7602. BABYLON.Observable = Observable;
  7603. })(BABYLON || (BABYLON = {}));
  7604. //# sourceMappingURL=babylon.observable.js.map
  7605. var BABYLON;
  7606. (function (BABYLON) {
  7607. var SmartArray = /** @class */ (function () {
  7608. function SmartArray(capacity) {
  7609. this.length = 0;
  7610. this.data = new Array(capacity);
  7611. this._id = SmartArray._GlobalId++;
  7612. }
  7613. SmartArray.prototype.push = function (value) {
  7614. this.data[this.length++] = value;
  7615. if (this.length > this.data.length) {
  7616. this.data.length *= 2;
  7617. }
  7618. };
  7619. SmartArray.prototype.forEach = function (func) {
  7620. for (var index = 0; index < this.length; index++) {
  7621. func(this.data[index]);
  7622. }
  7623. };
  7624. SmartArray.prototype.sort = function (compareFn) {
  7625. this.data.sort(compareFn);
  7626. };
  7627. SmartArray.prototype.reset = function () {
  7628. this.length = 0;
  7629. };
  7630. SmartArray.prototype.dispose = function () {
  7631. this.reset();
  7632. if (this.data) {
  7633. this.data.length = 0;
  7634. this.data = [];
  7635. }
  7636. };
  7637. SmartArray.prototype.concat = function (array) {
  7638. if (array.length === 0) {
  7639. return;
  7640. }
  7641. if (this.length + array.length > this.data.length) {
  7642. this.data.length = (this.length + array.length) * 2;
  7643. }
  7644. for (var index = 0; index < array.length; index++) {
  7645. this.data[this.length++] = (array.data || array)[index];
  7646. }
  7647. };
  7648. SmartArray.prototype.indexOf = function (value) {
  7649. var position = this.data.indexOf(value);
  7650. if (position >= this.length) {
  7651. return -1;
  7652. }
  7653. return position;
  7654. };
  7655. SmartArray.prototype.contains = function (value) {
  7656. return this.data.indexOf(value) !== -1;
  7657. };
  7658. // Statics
  7659. SmartArray._GlobalId = 0;
  7660. return SmartArray;
  7661. }());
  7662. BABYLON.SmartArray = SmartArray;
  7663. var SmartArrayNoDuplicate = /** @class */ (function (_super) {
  7664. __extends(SmartArrayNoDuplicate, _super);
  7665. function SmartArrayNoDuplicate() {
  7666. var _this = _super !== null && _super.apply(this, arguments) || this;
  7667. _this._duplicateId = 0;
  7668. return _this;
  7669. }
  7670. SmartArrayNoDuplicate.prototype.push = function (value) {
  7671. _super.prototype.push.call(this, value);
  7672. if (!value.__smartArrayFlags) {
  7673. value.__smartArrayFlags = {};
  7674. }
  7675. value.__smartArrayFlags[this._id] = this._duplicateId;
  7676. };
  7677. SmartArrayNoDuplicate.prototype.pushNoDuplicate = function (value) {
  7678. if (value.__smartArrayFlags && value.__smartArrayFlags[this._id] === this._duplicateId) {
  7679. return false;
  7680. }
  7681. this.push(value);
  7682. return true;
  7683. };
  7684. SmartArrayNoDuplicate.prototype.reset = function () {
  7685. _super.prototype.reset.call(this);
  7686. this._duplicateId++;
  7687. };
  7688. SmartArrayNoDuplicate.prototype.concatWithNoDuplicate = function (array) {
  7689. if (array.length === 0) {
  7690. return;
  7691. }
  7692. if (this.length + array.length > this.data.length) {
  7693. this.data.length = (this.length + array.length) * 2;
  7694. }
  7695. for (var index = 0; index < array.length; index++) {
  7696. var item = (array.data || array)[index];
  7697. this.pushNoDuplicate(item);
  7698. }
  7699. };
  7700. return SmartArrayNoDuplicate;
  7701. }(SmartArray));
  7702. BABYLON.SmartArrayNoDuplicate = SmartArrayNoDuplicate;
  7703. })(BABYLON || (BABYLON = {}));
  7704. //# sourceMappingURL=babylon.smartArray.js.map
  7705. var BABYLON;
  7706. (function (BABYLON) {
  7707. // See https://stackoverflow.com/questions/12915412/how-do-i-extend-a-host-object-e-g-error-in-typescript
  7708. // and https://github.com/Microsoft/TypeScript/wiki/Breaking-Changes#extending-built-ins-like-error-array-and-map-may-no-longer-work
  7709. var LoadFileError = /** @class */ (function (_super) {
  7710. __extends(LoadFileError, _super);
  7711. function LoadFileError(message, request) {
  7712. var _this = _super.call(this, message) || this;
  7713. _this.request = request;
  7714. _this.name = "LoadFileError";
  7715. LoadFileError._setPrototypeOf(_this, LoadFileError.prototype);
  7716. return _this;
  7717. }
  7718. // Polyfill for Object.setPrototypeOf if necessary.
  7719. LoadFileError._setPrototypeOf = Object.setPrototypeOf || (function (o, proto) { o.__proto__ = proto; return o; });
  7720. return LoadFileError;
  7721. }(Error));
  7722. BABYLON.LoadFileError = LoadFileError;
  7723. var RetryStrategy = /** @class */ (function () {
  7724. function RetryStrategy() {
  7725. }
  7726. RetryStrategy.ExponentialBackoff = function (maxRetries, baseInterval) {
  7727. if (maxRetries === void 0) { maxRetries = 3; }
  7728. if (baseInterval === void 0) { baseInterval = 500; }
  7729. return function (url, request, retryIndex) {
  7730. if (request.status !== 0 || retryIndex >= maxRetries || url.indexOf("file:") !== -1) {
  7731. return -1;
  7732. }
  7733. return Math.pow(2, retryIndex) * baseInterval;
  7734. };
  7735. };
  7736. return RetryStrategy;
  7737. }());
  7738. BABYLON.RetryStrategy = RetryStrategy;
  7739. // Screenshots
  7740. var screenshotCanvas;
  7741. var cloneValue = function (source, destinationObject) {
  7742. if (!source)
  7743. return null;
  7744. if (source instanceof BABYLON.Mesh) {
  7745. return null;
  7746. }
  7747. if (source instanceof BABYLON.SubMesh) {
  7748. return source.clone(destinationObject);
  7749. }
  7750. else if (source.clone) {
  7751. return source.clone();
  7752. }
  7753. return null;
  7754. };
  7755. var Tools = /** @class */ (function () {
  7756. function Tools() {
  7757. }
  7758. /**
  7759. * Interpolates between a and b via alpha
  7760. * @param a The lower value (returned when alpha = 0)
  7761. * @param b The upper value (returned when alpha = 1)
  7762. * @param alpha The interpolation-factor
  7763. * @return The mixed value
  7764. */
  7765. Tools.Mix = function (a, b, alpha) {
  7766. return a * (1 - alpha) + b * alpha;
  7767. };
  7768. Tools.Instantiate = function (className) {
  7769. if (Tools.RegisteredExternalClasses && Tools.RegisteredExternalClasses[className]) {
  7770. return Tools.RegisteredExternalClasses[className];
  7771. }
  7772. var arr = className.split(".");
  7773. var fn = (window || this);
  7774. for (var i = 0, len = arr.length; i < len; i++) {
  7775. fn = fn[arr[i]];
  7776. }
  7777. if (typeof fn !== "function") {
  7778. return null;
  7779. }
  7780. return fn;
  7781. };
  7782. /**
  7783. * Provides a slice function that will work even on IE
  7784. * @param data defines the array to slice
  7785. * @returns the new sliced array
  7786. */
  7787. Tools.Slice = function (data) {
  7788. if (data.slice) {
  7789. return data.slice();
  7790. }
  7791. return Array.prototype.slice.call(data);
  7792. };
  7793. Tools.SetImmediate = function (action) {
  7794. if (window.setImmediate) {
  7795. window.setImmediate(action);
  7796. }
  7797. else {
  7798. setTimeout(action, 1);
  7799. }
  7800. };
  7801. Tools.IsExponentOfTwo = function (value) {
  7802. var count = 1;
  7803. do {
  7804. count *= 2;
  7805. } while (count < value);
  7806. return count === value;
  7807. };
  7808. /**
  7809. * Find the next highest power of two.
  7810. * @param x Number to start search from.
  7811. * @return Next highest power of two.
  7812. */
  7813. Tools.CeilingPOT = function (x) {
  7814. x--;
  7815. x |= x >> 1;
  7816. x |= x >> 2;
  7817. x |= x >> 4;
  7818. x |= x >> 8;
  7819. x |= x >> 16;
  7820. x++;
  7821. return x;
  7822. };
  7823. /**
  7824. * Find the next lowest power of two.
  7825. * @param x Number to start search from.
  7826. * @return Next lowest power of two.
  7827. */
  7828. Tools.FloorPOT = function (x) {
  7829. x = x | (x >> 1);
  7830. x = x | (x >> 2);
  7831. x = x | (x >> 4);
  7832. x = x | (x >> 8);
  7833. x = x | (x >> 16);
  7834. return x - (x >> 1);
  7835. };
  7836. /**
  7837. * Find the nearest power of two.
  7838. * @param x Number to start search from.
  7839. * @return Next nearest power of two.
  7840. */
  7841. Tools.NearestPOT = function (x) {
  7842. var c = Tools.CeilingPOT(x);
  7843. var f = Tools.FloorPOT(x);
  7844. return (c - x) > (x - f) ? f : c;
  7845. };
  7846. Tools.GetExponentOfTwo = function (value, max, mode) {
  7847. if (mode === void 0) { mode = BABYLON.Engine.SCALEMODE_NEAREST; }
  7848. var pot;
  7849. switch (mode) {
  7850. case BABYLON.Engine.SCALEMODE_FLOOR:
  7851. pot = Tools.FloorPOT(value);
  7852. break;
  7853. case BABYLON.Engine.SCALEMODE_NEAREST:
  7854. pot = Tools.NearestPOT(value);
  7855. break;
  7856. case BABYLON.Engine.SCALEMODE_CEILING:
  7857. default:
  7858. pot = Tools.CeilingPOT(value);
  7859. break;
  7860. }
  7861. return Math.min(pot, max);
  7862. };
  7863. Tools.GetFilename = function (path) {
  7864. var index = path.lastIndexOf("/");
  7865. if (index < 0)
  7866. return path;
  7867. return path.substring(index + 1);
  7868. };
  7869. /**
  7870. * Extracts the "folder" part of a path (everything before the filename).
  7871. * @param uri The URI to extract the info from
  7872. * @param returnUnchangedIfNoSlash Do not touch the URI if no slashes are present
  7873. * @returns The "folder" part of the path
  7874. */
  7875. Tools.GetFolderPath = function (uri, returnUnchangedIfNoSlash) {
  7876. if (returnUnchangedIfNoSlash === void 0) { returnUnchangedIfNoSlash = false; }
  7877. var index = uri.lastIndexOf("/");
  7878. if (index < 0) {
  7879. if (returnUnchangedIfNoSlash) {
  7880. return uri;
  7881. }
  7882. return "";
  7883. }
  7884. return uri.substring(0, index + 1);
  7885. };
  7886. Tools.GetDOMTextContent = function (element) {
  7887. var result = "";
  7888. var child = element.firstChild;
  7889. while (child) {
  7890. if (child.nodeType === 3) {
  7891. result += child.textContent;
  7892. }
  7893. child = child.nextSibling;
  7894. }
  7895. return result;
  7896. };
  7897. Tools.ToDegrees = function (angle) {
  7898. return angle * 180 / Math.PI;
  7899. };
  7900. Tools.ToRadians = function (angle) {
  7901. return angle * Math.PI / 180;
  7902. };
  7903. Tools.EncodeArrayBufferTobase64 = function (buffer) {
  7904. var keyStr = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";
  7905. var output = "";
  7906. var chr1, chr2, chr3, enc1, enc2, enc3, enc4;
  7907. var i = 0;
  7908. var bytes = new Uint8Array(buffer);
  7909. while (i < bytes.length) {
  7910. chr1 = bytes[i++];
  7911. chr2 = i < bytes.length ? bytes[i++] : Number.NaN; // Not sure if the index
  7912. chr3 = i < bytes.length ? bytes[i++] : Number.NaN; // checks are needed here
  7913. enc1 = chr1 >> 2;
  7914. enc2 = ((chr1 & 3) << 4) | (chr2 >> 4);
  7915. enc3 = ((chr2 & 15) << 2) | (chr3 >> 6);
  7916. enc4 = chr3 & 63;
  7917. if (isNaN(chr2)) {
  7918. enc3 = enc4 = 64;
  7919. }
  7920. else if (isNaN(chr3)) {
  7921. enc4 = 64;
  7922. }
  7923. output += keyStr.charAt(enc1) + keyStr.charAt(enc2) +
  7924. keyStr.charAt(enc3) + keyStr.charAt(enc4);
  7925. }
  7926. return "data:image/png;base64," + output;
  7927. };
  7928. Tools.ExtractMinAndMaxIndexed = function (positions, indices, indexStart, indexCount, bias) {
  7929. if (bias === void 0) { bias = null; }
  7930. var minimum = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  7931. var maximum = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  7932. for (var index = indexStart; index < indexStart + indexCount; index++) {
  7933. var current = new BABYLON.Vector3(positions[indices[index] * 3], positions[indices[index] * 3 + 1], positions[indices[index] * 3 + 2]);
  7934. minimum = BABYLON.Vector3.Minimize(current, minimum);
  7935. maximum = BABYLON.Vector3.Maximize(current, maximum);
  7936. }
  7937. if (bias) {
  7938. minimum.x -= minimum.x * bias.x + bias.y;
  7939. minimum.y -= minimum.y * bias.x + bias.y;
  7940. minimum.z -= minimum.z * bias.x + bias.y;
  7941. maximum.x += maximum.x * bias.x + bias.y;
  7942. maximum.y += maximum.y * bias.x + bias.y;
  7943. maximum.z += maximum.z * bias.x + bias.y;
  7944. }
  7945. return {
  7946. minimum: minimum,
  7947. maximum: maximum
  7948. };
  7949. };
  7950. Tools.ExtractMinAndMax = function (positions, start, count, bias, stride) {
  7951. if (bias === void 0) { bias = null; }
  7952. var minimum = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  7953. var maximum = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  7954. if (!stride) {
  7955. stride = 3;
  7956. }
  7957. for (var index = start; index < start + count; index++) {
  7958. var current = new BABYLON.Vector3(positions[index * stride], positions[index * stride + 1], positions[index * stride + 2]);
  7959. minimum = BABYLON.Vector3.Minimize(current, minimum);
  7960. maximum = BABYLON.Vector3.Maximize(current, maximum);
  7961. }
  7962. if (bias) {
  7963. minimum.x -= minimum.x * bias.x + bias.y;
  7964. minimum.y -= minimum.y * bias.x + bias.y;
  7965. minimum.z -= minimum.z * bias.x + bias.y;
  7966. maximum.x += maximum.x * bias.x + bias.y;
  7967. maximum.y += maximum.y * bias.x + bias.y;
  7968. maximum.z += maximum.z * bias.x + bias.y;
  7969. }
  7970. return {
  7971. minimum: minimum,
  7972. maximum: maximum
  7973. };
  7974. };
  7975. Tools.Vector2ArrayFeeder = function (array) {
  7976. return function (index) {
  7977. var isFloatArray = (array.BYTES_PER_ELEMENT !== undefined);
  7978. var length = isFloatArray ? array.length / 2 : array.length;
  7979. if (index >= length) {
  7980. return null;
  7981. }
  7982. if (isFloatArray) {
  7983. var fa = array;
  7984. return new BABYLON.Vector2(fa[index * 2 + 0], fa[index * 2 + 1]);
  7985. }
  7986. var a = array;
  7987. return a[index];
  7988. };
  7989. };
  7990. Tools.ExtractMinAndMaxVector2 = function (feeder, bias) {
  7991. if (bias === void 0) { bias = null; }
  7992. var minimum = new BABYLON.Vector2(Number.MAX_VALUE, Number.MAX_VALUE);
  7993. var maximum = new BABYLON.Vector2(-Number.MAX_VALUE, -Number.MAX_VALUE);
  7994. var i = 0;
  7995. var cur = feeder(i++);
  7996. while (cur) {
  7997. minimum = BABYLON.Vector2.Minimize(cur, minimum);
  7998. maximum = BABYLON.Vector2.Maximize(cur, maximum);
  7999. cur = feeder(i++);
  8000. }
  8001. if (bias) {
  8002. minimum.x -= minimum.x * bias.x + bias.y;
  8003. minimum.y -= minimum.y * bias.x + bias.y;
  8004. maximum.x += maximum.x * bias.x + bias.y;
  8005. maximum.y += maximum.y * bias.x + bias.y;
  8006. }
  8007. return {
  8008. minimum: minimum,
  8009. maximum: maximum
  8010. };
  8011. };
  8012. Tools.MakeArray = function (obj, allowsNullUndefined) {
  8013. if (allowsNullUndefined !== true && (obj === undefined || obj == null))
  8014. return null;
  8015. return Array.isArray(obj) ? obj : [obj];
  8016. };
  8017. // Misc.
  8018. Tools.GetPointerPrefix = function () {
  8019. var eventPrefix = "pointer";
  8020. // Check if pointer events are supported
  8021. if (Tools.IsWindowObjectExist() && !window.PointerEvent && !navigator.pointerEnabled) {
  8022. eventPrefix = "mouse";
  8023. }
  8024. return eventPrefix;
  8025. };
  8026. /**
  8027. * @param func - the function to be called
  8028. * @param requester - the object that will request the next frame. Falls back to window.
  8029. */
  8030. Tools.QueueNewFrame = function (func, requester) {
  8031. if (!Tools.IsWindowObjectExist()) {
  8032. return setTimeout(func, 16);
  8033. }
  8034. if (!requester) {
  8035. requester = window;
  8036. }
  8037. if (requester.requestAnimationFrame) {
  8038. return requester.requestAnimationFrame(func);
  8039. }
  8040. else if (requester.msRequestAnimationFrame) {
  8041. return requester.msRequestAnimationFrame(func);
  8042. }
  8043. else if (requester.webkitRequestAnimationFrame) {
  8044. return requester.webkitRequestAnimationFrame(func);
  8045. }
  8046. else if (requester.mozRequestAnimationFrame) {
  8047. return requester.mozRequestAnimationFrame(func);
  8048. }
  8049. else if (requester.oRequestAnimationFrame) {
  8050. return requester.oRequestAnimationFrame(func);
  8051. }
  8052. else {
  8053. return window.setTimeout(func, 16);
  8054. }
  8055. };
  8056. Tools.RequestFullscreen = function (element) {
  8057. var requestFunction = element.requestFullscreen || element.msRequestFullscreen || element.webkitRequestFullscreen || element.mozRequestFullScreen;
  8058. if (!requestFunction)
  8059. return;
  8060. requestFunction.call(element);
  8061. };
  8062. Tools.ExitFullscreen = function () {
  8063. if (document.exitFullscreen) {
  8064. document.exitFullscreen();
  8065. }
  8066. else if (document.mozCancelFullScreen) {
  8067. document.mozCancelFullScreen();
  8068. }
  8069. else if (document.webkitCancelFullScreen) {
  8070. document.webkitCancelFullScreen();
  8071. }
  8072. else if (document.msCancelFullScreen) {
  8073. document.msCancelFullScreen();
  8074. }
  8075. };
  8076. Tools.SetCorsBehavior = function (url, element) {
  8077. if (url && url.indexOf("data:") === 0) {
  8078. return;
  8079. }
  8080. if (Tools.CorsBehavior) {
  8081. if (typeof (Tools.CorsBehavior) === 'string' || Tools.CorsBehavior instanceof String) {
  8082. element.crossOrigin = Tools.CorsBehavior;
  8083. }
  8084. else {
  8085. var result = Tools.CorsBehavior(url);
  8086. if (result) {
  8087. element.crossOrigin = result;
  8088. }
  8089. }
  8090. }
  8091. };
  8092. // External files
  8093. Tools.CleanUrl = function (url) {
  8094. url = url.replace(/#/mg, "%23");
  8095. return url;
  8096. };
  8097. Tools.LoadImage = function (url, onLoad, onError, database) {
  8098. if (url instanceof ArrayBuffer) {
  8099. url = Tools.EncodeArrayBufferTobase64(url);
  8100. }
  8101. url = Tools.CleanUrl(url);
  8102. url = Tools.PreprocessUrl(url);
  8103. var img = new Image();
  8104. Tools.SetCorsBehavior(url, img);
  8105. var loadHandler = function () {
  8106. img.removeEventListener("load", loadHandler);
  8107. img.removeEventListener("error", errorHandler);
  8108. onLoad(img);
  8109. };
  8110. var errorHandler = function (err) {
  8111. img.removeEventListener("load", loadHandler);
  8112. img.removeEventListener("error", errorHandler);
  8113. Tools.Error("Error while trying to load image: " + url);
  8114. if (onError) {
  8115. onError("Error while trying to load image: " + url, err);
  8116. }
  8117. };
  8118. img.addEventListener("load", loadHandler);
  8119. img.addEventListener("error", errorHandler);
  8120. var noIndexedDB = function () {
  8121. img.src = url;
  8122. };
  8123. var loadFromIndexedDB = function () {
  8124. if (database) {
  8125. database.loadImageFromDB(url, img);
  8126. }
  8127. };
  8128. //ANY database to do!
  8129. if (url.substr(0, 5) !== "data:" && database && database.enableTexturesOffline && BABYLON.Database.IsUASupportingBlobStorage) {
  8130. database.openAsync(loadFromIndexedDB, noIndexedDB);
  8131. }
  8132. else {
  8133. if (url.indexOf("file:") !== -1) {
  8134. var textureName = decodeURIComponent(url.substring(5).toLowerCase());
  8135. if (BABYLON.FilesInput.FilesToLoad[textureName]) {
  8136. try {
  8137. var blobURL;
  8138. try {
  8139. blobURL = URL.createObjectURL(BABYLON.FilesInput.FilesToLoad[textureName], { oneTimeOnly: true });
  8140. }
  8141. catch (ex) {
  8142. // Chrome doesn't support oneTimeOnly parameter
  8143. blobURL = URL.createObjectURL(BABYLON.FilesInput.FilesToLoad[textureName]);
  8144. }
  8145. img.src = blobURL;
  8146. }
  8147. catch (e) {
  8148. img.src = "";
  8149. }
  8150. return img;
  8151. }
  8152. }
  8153. noIndexedDB();
  8154. }
  8155. return img;
  8156. };
  8157. Tools.LoadFile = function (url, onSuccess, onProgress, database, useArrayBuffer, onError) {
  8158. url = Tools.CleanUrl(url);
  8159. url = Tools.PreprocessUrl(url);
  8160. // If file and file input are set
  8161. if (url.indexOf("file:") !== -1) {
  8162. var fileName = decodeURIComponent(url.substring(5).toLowerCase());
  8163. if (BABYLON.FilesInput.FilesToLoad[fileName]) {
  8164. return Tools.ReadFile(BABYLON.FilesInput.FilesToLoad[fileName], onSuccess, onProgress, useArrayBuffer);
  8165. }
  8166. }
  8167. var loadUrl = Tools.BaseUrl + url;
  8168. var aborted = false;
  8169. var fileRequest = {
  8170. onCompleteObservable: new BABYLON.Observable(),
  8171. abort: function () { return aborted = true; },
  8172. };
  8173. var requestFile = function () {
  8174. var request = new XMLHttpRequest();
  8175. var retryHandle = null;
  8176. fileRequest.abort = function () {
  8177. aborted = true;
  8178. if (request.readyState !== (XMLHttpRequest.DONE || 4)) {
  8179. request.abort();
  8180. }
  8181. if (retryHandle !== null) {
  8182. clearTimeout(retryHandle);
  8183. retryHandle = null;
  8184. }
  8185. };
  8186. var retryLoop = function (retryIndex) {
  8187. request.open('GET', loadUrl, true);
  8188. if (useArrayBuffer) {
  8189. request.responseType = "arraybuffer";
  8190. }
  8191. if (onProgress) {
  8192. request.addEventListener("progress", onProgress);
  8193. }
  8194. var onLoadEnd = function () {
  8195. request.removeEventListener("loadend", onLoadEnd);
  8196. fileRequest.onCompleteObservable.notifyObservers(fileRequest);
  8197. fileRequest.onCompleteObservable.clear();
  8198. };
  8199. request.addEventListener("loadend", onLoadEnd);
  8200. var onReadyStateChange = function () {
  8201. if (aborted) {
  8202. return;
  8203. }
  8204. // In case of undefined state in some browsers.
  8205. if (request.readyState === (XMLHttpRequest.DONE || 4)) {
  8206. // Some browsers have issues where onreadystatechange can be called multiple times with the same value.
  8207. request.removeEventListener("readystatechange", onReadyStateChange);
  8208. if (request.status >= 200 && request.status < 300 || (!Tools.IsWindowObjectExist() && (request.status === 0))) {
  8209. onSuccess(!useArrayBuffer ? request.responseText : request.response, request.responseURL);
  8210. return;
  8211. }
  8212. var retryStrategy = Tools.DefaultRetryStrategy;
  8213. if (retryStrategy) {
  8214. var waitTime = retryStrategy(loadUrl, request, retryIndex);
  8215. if (waitTime !== -1) {
  8216. // Prevent the request from completing for retry.
  8217. request.removeEventListener("loadend", onLoadEnd);
  8218. request = new XMLHttpRequest();
  8219. retryHandle = setTimeout(function () { return retryLoop(retryIndex + 1); }, waitTime);
  8220. return;
  8221. }
  8222. }
  8223. var e = new LoadFileError("Error status: " + request.status + " " + request.statusText + " - Unable to load " + loadUrl, request);
  8224. if (onError) {
  8225. onError(request, e);
  8226. }
  8227. else {
  8228. throw e;
  8229. }
  8230. }
  8231. };
  8232. request.addEventListener("readystatechange", onReadyStateChange);
  8233. request.send();
  8234. };
  8235. retryLoop(0);
  8236. };
  8237. // Caching all files
  8238. if (database && database.enableSceneOffline) {
  8239. var noIndexedDB_1 = function () {
  8240. if (!aborted) {
  8241. requestFile();
  8242. }
  8243. };
  8244. var loadFromIndexedDB = function () {
  8245. // TODO: database needs to support aborting and should return a IFileRequest
  8246. if (aborted) {
  8247. return;
  8248. }
  8249. if (database) {
  8250. database.loadFileFromDB(url, function (data) {
  8251. if (!aborted) {
  8252. onSuccess(data);
  8253. }
  8254. fileRequest.onCompleteObservable.notifyObservers(fileRequest);
  8255. }, onProgress ? function (event) {
  8256. if (!aborted) {
  8257. onProgress(event);
  8258. }
  8259. } : undefined, noIndexedDB_1, useArrayBuffer);
  8260. }
  8261. };
  8262. database.openAsync(loadFromIndexedDB, noIndexedDB_1);
  8263. }
  8264. else {
  8265. requestFile();
  8266. }
  8267. return fileRequest;
  8268. };
  8269. /**
  8270. * Load a script (identified by an url). When the url returns, the
  8271. * content of this file is added into a new script element, attached to the DOM (body element)
  8272. */
  8273. Tools.LoadScript = function (scriptUrl, onSuccess, onError) {
  8274. var head = document.getElementsByTagName('head')[0];
  8275. var script = document.createElement('script');
  8276. script.type = 'text/javascript';
  8277. script.src = scriptUrl;
  8278. script.onload = function () {
  8279. if (onSuccess) {
  8280. onSuccess();
  8281. }
  8282. };
  8283. script.onerror = function (e) {
  8284. if (onError) {
  8285. onError("Unable to load script", e);
  8286. }
  8287. };
  8288. head.appendChild(script);
  8289. };
  8290. Tools.ReadFileAsDataURL = function (fileToLoad, callback, progressCallback) {
  8291. var reader = new FileReader();
  8292. var request = {
  8293. onCompleteObservable: new BABYLON.Observable(),
  8294. abort: function () { return reader.abort(); },
  8295. };
  8296. reader.onloadend = function (e) {
  8297. request.onCompleteObservable.notifyObservers(request);
  8298. };
  8299. reader.onload = function (e) {
  8300. //target doesn't have result from ts 1.3
  8301. callback(e.target['result']);
  8302. };
  8303. reader.onprogress = progressCallback;
  8304. reader.readAsDataURL(fileToLoad);
  8305. return request;
  8306. };
  8307. Tools.ReadFile = function (fileToLoad, callback, progressCallBack, useArrayBuffer) {
  8308. var reader = new FileReader();
  8309. var request = {
  8310. onCompleteObservable: new BABYLON.Observable(),
  8311. abort: function () { return reader.abort(); },
  8312. };
  8313. reader.onloadend = function (e) { return request.onCompleteObservable.notifyObservers(request); };
  8314. reader.onerror = function (e) {
  8315. Tools.Log("Error while reading file: " + fileToLoad.name);
  8316. callback(JSON.stringify({ autoClear: true, clearColor: [1, 0, 0], ambientColor: [0, 0, 0], gravity: [0, -9.807, 0], meshes: [], cameras: [], lights: [] }));
  8317. };
  8318. reader.onload = function (e) {
  8319. //target doesn't have result from ts 1.3
  8320. callback(e.target['result']);
  8321. };
  8322. if (progressCallBack) {
  8323. reader.onprogress = progressCallBack;
  8324. }
  8325. if (!useArrayBuffer) {
  8326. // Asynchronous read
  8327. reader.readAsText(fileToLoad);
  8328. }
  8329. else {
  8330. reader.readAsArrayBuffer(fileToLoad);
  8331. }
  8332. return request;
  8333. };
  8334. //returns a downloadable url to a file content.
  8335. Tools.FileAsURL = function (content) {
  8336. var fileBlob = new Blob([content]);
  8337. var url = window.URL || window.webkitURL;
  8338. var link = url.createObjectURL(fileBlob);
  8339. return link;
  8340. };
  8341. // Misc.
  8342. Tools.Format = function (value, decimals) {
  8343. if (decimals === void 0) { decimals = 2; }
  8344. return value.toFixed(decimals);
  8345. };
  8346. Tools.CheckExtends = function (v, min, max) {
  8347. if (v.x < min.x)
  8348. min.x = v.x;
  8349. if (v.y < min.y)
  8350. min.y = v.y;
  8351. if (v.z < min.z)
  8352. min.z = v.z;
  8353. if (v.x > max.x)
  8354. max.x = v.x;
  8355. if (v.y > max.y)
  8356. max.y = v.y;
  8357. if (v.z > max.z)
  8358. max.z = v.z;
  8359. };
  8360. Tools.DeepCopy = function (source, destination, doNotCopyList, mustCopyList) {
  8361. for (var prop in source) {
  8362. if (prop[0] === "_" && (!mustCopyList || mustCopyList.indexOf(prop) === -1)) {
  8363. continue;
  8364. }
  8365. if (doNotCopyList && doNotCopyList.indexOf(prop) !== -1) {
  8366. continue;
  8367. }
  8368. var sourceValue = source[prop];
  8369. var typeOfSourceValue = typeof sourceValue;
  8370. if (typeOfSourceValue === "function") {
  8371. continue;
  8372. }
  8373. if (typeOfSourceValue === "object") {
  8374. if (sourceValue instanceof Array) {
  8375. destination[prop] = [];
  8376. if (sourceValue.length > 0) {
  8377. if (typeof sourceValue[0] == "object") {
  8378. for (var index = 0; index < sourceValue.length; index++) {
  8379. var clonedValue = cloneValue(sourceValue[index], destination);
  8380. if (destination[prop].indexOf(clonedValue) === -1) {
  8381. destination[prop].push(clonedValue);
  8382. }
  8383. }
  8384. }
  8385. else {
  8386. destination[prop] = sourceValue.slice(0);
  8387. }
  8388. }
  8389. }
  8390. else {
  8391. destination[prop] = cloneValue(sourceValue, destination);
  8392. }
  8393. }
  8394. else {
  8395. destination[prop] = sourceValue;
  8396. }
  8397. }
  8398. };
  8399. Tools.IsEmpty = function (obj) {
  8400. for (var i in obj) {
  8401. if (obj.hasOwnProperty(i)) {
  8402. return false;
  8403. }
  8404. }
  8405. return true;
  8406. };
  8407. Tools.RegisterTopRootEvents = function (events) {
  8408. for (var index = 0; index < events.length; index++) {
  8409. var event = events[index];
  8410. window.addEventListener(event.name, event.handler, false);
  8411. try {
  8412. if (window.parent) {
  8413. window.parent.addEventListener(event.name, event.handler, false);
  8414. }
  8415. }
  8416. catch (e) {
  8417. // Silently fails...
  8418. }
  8419. }
  8420. };
  8421. Tools.UnregisterTopRootEvents = function (events) {
  8422. for (var index = 0; index < events.length; index++) {
  8423. var event = events[index];
  8424. window.removeEventListener(event.name, event.handler);
  8425. try {
  8426. if (window.parent) {
  8427. window.parent.removeEventListener(event.name, event.handler);
  8428. }
  8429. }
  8430. catch (e) {
  8431. // Silently fails...
  8432. }
  8433. }
  8434. };
  8435. Tools.DumpFramebuffer = function (width, height, engine, successCallback, mimeType, fileName) {
  8436. if (mimeType === void 0) { mimeType = "image/png"; }
  8437. // Read the contents of the framebuffer
  8438. var numberOfChannelsByLine = width * 4;
  8439. var halfHeight = height / 2;
  8440. //Reading datas from WebGL
  8441. var data = engine.readPixels(0, 0, width, height);
  8442. //To flip image on Y axis.
  8443. for (var i = 0; i < halfHeight; i++) {
  8444. for (var j = 0; j < numberOfChannelsByLine; j++) {
  8445. var currentCell = j + i * numberOfChannelsByLine;
  8446. var targetLine = height - i - 1;
  8447. var targetCell = j + targetLine * numberOfChannelsByLine;
  8448. var temp = data[currentCell];
  8449. data[currentCell] = data[targetCell];
  8450. data[targetCell] = temp;
  8451. }
  8452. }
  8453. // Create a 2D canvas to store the result
  8454. if (!screenshotCanvas) {
  8455. screenshotCanvas = document.createElement('canvas');
  8456. }
  8457. screenshotCanvas.width = width;
  8458. screenshotCanvas.height = height;
  8459. var context = screenshotCanvas.getContext('2d');
  8460. if (context) {
  8461. // Copy the pixels to a 2D canvas
  8462. var imageData = context.createImageData(width, height);
  8463. var castData = (imageData.data);
  8464. castData.set(data);
  8465. context.putImageData(imageData, 0, 0);
  8466. Tools.EncodeScreenshotCanvasData(successCallback, mimeType, fileName);
  8467. }
  8468. };
  8469. Tools.EncodeScreenshotCanvasData = function (successCallback, mimeType, fileName) {
  8470. if (mimeType === void 0) { mimeType = "image/png"; }
  8471. var base64Image = screenshotCanvas.toDataURL(mimeType);
  8472. if (successCallback) {
  8473. successCallback(base64Image);
  8474. }
  8475. else {
  8476. // We need HTMLCanvasElement.toBlob for HD screenshots
  8477. if (!screenshotCanvas.toBlob) {
  8478. // low performance polyfill based on toDataURL (https://developer.mozilla.org/en-US/docs/Web/API/HTMLCanvasElement/toBlob)
  8479. screenshotCanvas.toBlob = function (callback, type, quality) {
  8480. var _this = this;
  8481. setTimeout(function () {
  8482. var binStr = atob(_this.toDataURL(type, quality).split(',')[1]), len = binStr.length, arr = new Uint8Array(len);
  8483. for (var i = 0; i < len; i++) {
  8484. arr[i] = binStr.charCodeAt(i);
  8485. }
  8486. callback(new Blob([arr], { type: type || 'image/png' }));
  8487. });
  8488. };
  8489. }
  8490. screenshotCanvas.toBlob(function (blob) {
  8491. var url = URL.createObjectURL(blob);
  8492. //Creating a link if the browser have the download attribute on the a tag, to automatically start download generated image.
  8493. if (("download" in document.createElement("a"))) {
  8494. var a = window.document.createElement("a");
  8495. a.href = url;
  8496. if (fileName) {
  8497. a.setAttribute("download", fileName);
  8498. }
  8499. else {
  8500. var date = new Date();
  8501. var stringDate = (date.getFullYear() + "-" + (date.getMonth() + 1)).slice(-2) + "-" + date.getDate() + "_" + date.getHours() + "-" + ('0' + date.getMinutes()).slice(-2);
  8502. a.setAttribute("download", "screenshot_" + stringDate + ".png");
  8503. }
  8504. window.document.body.appendChild(a);
  8505. a.addEventListener("click", function () {
  8506. if (a.parentElement) {
  8507. a.parentElement.removeChild(a);
  8508. }
  8509. });
  8510. a.click();
  8511. }
  8512. else {
  8513. var newWindow = window.open("");
  8514. if (!newWindow)
  8515. return;
  8516. var img = newWindow.document.createElement("img");
  8517. img.onload = function () {
  8518. // no longer need to read the blob so it's revoked
  8519. URL.revokeObjectURL(url);
  8520. };
  8521. img.src = url;
  8522. newWindow.document.body.appendChild(img);
  8523. }
  8524. });
  8525. }
  8526. };
  8527. Tools.CreateScreenshot = function (engine, camera, size, successCallback, mimeType) {
  8528. if (mimeType === void 0) { mimeType = "image/png"; }
  8529. var width;
  8530. var height;
  8531. // If a precision value is specified
  8532. if (size.precision) {
  8533. width = Math.round(engine.getRenderWidth() * size.precision);
  8534. height = Math.round(width / engine.getAspectRatio(camera));
  8535. }
  8536. else if (size.width && size.height) {
  8537. width = size.width;
  8538. height = size.height;
  8539. }
  8540. else if (size.width && !size.height) {
  8541. width = size.width;
  8542. height = Math.round(width / engine.getAspectRatio(camera));
  8543. }
  8544. else if (size.height && !size.width) {
  8545. height = size.height;
  8546. width = Math.round(height * engine.getAspectRatio(camera));
  8547. }
  8548. else if (!isNaN(size)) {
  8549. height = size;
  8550. width = size;
  8551. }
  8552. else {
  8553. Tools.Error("Invalid 'size' parameter !");
  8554. return;
  8555. }
  8556. if (!screenshotCanvas) {
  8557. screenshotCanvas = document.createElement('canvas');
  8558. }
  8559. screenshotCanvas.width = width;
  8560. screenshotCanvas.height = height;
  8561. var renderContext = screenshotCanvas.getContext("2d");
  8562. var ratio = engine.getRenderWidth() / engine.getRenderHeight();
  8563. var newWidth = width;
  8564. var newHeight = newWidth / ratio;
  8565. if (newHeight > height) {
  8566. newHeight = height;
  8567. newWidth = newHeight * ratio;
  8568. }
  8569. var offsetX = Math.max(0, width - newWidth) / 2;
  8570. var offsetY = Math.max(0, height - newHeight) / 2;
  8571. var renderingCanvas = engine.getRenderingCanvas();
  8572. if (renderContext && renderingCanvas) {
  8573. renderContext.drawImage(renderingCanvas, offsetX, offsetY, newWidth, newHeight);
  8574. }
  8575. Tools.EncodeScreenshotCanvasData(successCallback, mimeType);
  8576. };
  8577. /**
  8578. * Generates an image screenshot from the specified camera.
  8579. *
  8580. * @param engine The engine to use for rendering
  8581. * @param camera The camera to use for rendering
  8582. * @param size This parameter can be set to a single number or to an object with the
  8583. * following (optional) properties: precision, width, height. If a single number is passed,
  8584. * it will be used for both width and height. If an object is passed, the screenshot size
  8585. * will be derived from the parameters. The precision property is a multiplier allowing
  8586. * rendering at a higher or lower resolution.
  8587. * @param successCallback The callback receives a single parameter which contains the
  8588. * screenshot as a string of base64-encoded characters. This string can be assigned to the
  8589. * src parameter of an <img> to display it.
  8590. * @param mimeType The MIME type of the screenshot image (default: image/png).
  8591. * Check your browser for supported MIME types.
  8592. * @param samples Texture samples (default: 1)
  8593. * @param antialiasing Whether antialiasing should be turned on or not (default: false)
  8594. * @param fileName A name for for the downloaded file.
  8595. * @constructor
  8596. */
  8597. Tools.CreateScreenshotUsingRenderTarget = function (engine, camera, size, successCallback, mimeType, samples, antialiasing, fileName) {
  8598. if (mimeType === void 0) { mimeType = "image/png"; }
  8599. if (samples === void 0) { samples = 1; }
  8600. if (antialiasing === void 0) { antialiasing = false; }
  8601. var width;
  8602. var height;
  8603. //If a precision value is specified
  8604. if (size.precision) {
  8605. width = Math.round(engine.getRenderWidth() * size.precision);
  8606. height = Math.round(width / engine.getAspectRatio(camera));
  8607. size = { width: width, height: height };
  8608. }
  8609. else if (size.width && size.height) {
  8610. width = size.width;
  8611. height = size.height;
  8612. }
  8613. else if (size.width && !size.height) {
  8614. width = size.width;
  8615. height = Math.round(width / engine.getAspectRatio(camera));
  8616. size = { width: width, height: height };
  8617. }
  8618. else if (size.height && !size.width) {
  8619. height = size.height;
  8620. width = Math.round(height * engine.getAspectRatio(camera));
  8621. size = { width: width, height: height };
  8622. }
  8623. else if (!isNaN(size)) {
  8624. height = size;
  8625. width = size;
  8626. }
  8627. else {
  8628. Tools.Error("Invalid 'size' parameter !");
  8629. return;
  8630. }
  8631. var scene = camera.getScene();
  8632. var previousCamera = null;
  8633. if (scene.activeCamera !== camera) {
  8634. previousCamera = scene.activeCamera;
  8635. scene.activeCamera = camera;
  8636. }
  8637. //At this point size can be a number, or an object (according to engine.prototype.createRenderTargetTexture method)
  8638. var texture = new BABYLON.RenderTargetTexture("screenShot", size, scene, false, false, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT, false, BABYLON.Texture.NEAREST_SAMPLINGMODE);
  8639. texture.renderList = null;
  8640. texture.samples = samples;
  8641. if (antialiasing) {
  8642. texture.addPostProcess(new BABYLON.FxaaPostProcess('antialiasing', 1.0, scene.activeCamera));
  8643. }
  8644. texture.onAfterRenderObservable.add(function () {
  8645. Tools.DumpFramebuffer(width, height, engine, successCallback, mimeType, fileName);
  8646. });
  8647. scene.incrementRenderId();
  8648. scene.resetCachedMaterial();
  8649. texture.render(true);
  8650. texture.dispose();
  8651. if (previousCamera) {
  8652. scene.activeCamera = previousCamera;
  8653. }
  8654. camera.getProjectionMatrix(true); // Force cache refresh;
  8655. };
  8656. // XHR response validator for local file scenario
  8657. Tools.ValidateXHRData = function (xhr, dataType) {
  8658. // 1 for text (.babylon, manifest and shaders), 2 for TGA, 4 for DDS, 7 for all
  8659. if (dataType === void 0) { dataType = 7; }
  8660. try {
  8661. if (dataType & 1) {
  8662. if (xhr.responseText && xhr.responseText.length > 0) {
  8663. return true;
  8664. }
  8665. else if (dataType === 1) {
  8666. return false;
  8667. }
  8668. }
  8669. if (dataType & 2) {
  8670. // Check header width and height since there is no "TGA" magic number
  8671. var tgaHeader = BABYLON.TGATools.GetTGAHeader(xhr.response);
  8672. if (tgaHeader.width && tgaHeader.height && tgaHeader.width > 0 && tgaHeader.height > 0) {
  8673. return true;
  8674. }
  8675. else if (dataType === 2) {
  8676. return false;
  8677. }
  8678. }
  8679. if (dataType & 4) {
  8680. // Check for the "DDS" magic number
  8681. var ddsHeader = new Uint8Array(xhr.response, 0, 3);
  8682. if (ddsHeader[0] === 68 && ddsHeader[1] === 68 && ddsHeader[2] === 83) {
  8683. return true;
  8684. }
  8685. else {
  8686. return false;
  8687. }
  8688. }
  8689. }
  8690. catch (e) {
  8691. // Global protection
  8692. }
  8693. return false;
  8694. };
  8695. /**
  8696. * Implementation from http://stackoverflow.com/questions/105034/how-to-create-a-guid-uuid-in-javascript/2117523#answer-2117523
  8697. * Be aware Math.random() could cause collisions, but:
  8698. * "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"
  8699. */
  8700. Tools.RandomId = function () {
  8701. return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function (c) {
  8702. var r = Math.random() * 16 | 0, v = c === 'x' ? r : (r & 0x3 | 0x8);
  8703. return v.toString(16);
  8704. });
  8705. };
  8706. /**
  8707. * Test if the given uri is a base64 string.
  8708. * @param uri The uri to test
  8709. * @return True if the uri is a base64 string or false otherwise.
  8710. */
  8711. Tools.IsBase64 = function (uri) {
  8712. return uri.length < 5 ? false : uri.substr(0, 5) === "data:";
  8713. };
  8714. /**
  8715. * Decode the given base64 uri.
  8716. * @param uri The uri to decode
  8717. * @return The decoded base64 data.
  8718. */
  8719. Tools.DecodeBase64 = function (uri) {
  8720. var decodedString = atob(uri.split(",")[1]);
  8721. var bufferLength = decodedString.length;
  8722. var bufferView = new Uint8Array(new ArrayBuffer(bufferLength));
  8723. for (var i = 0; i < bufferLength; i++) {
  8724. bufferView[i] = decodedString.charCodeAt(i);
  8725. }
  8726. return bufferView.buffer;
  8727. };
  8728. Object.defineProperty(Tools, "NoneLogLevel", {
  8729. get: function () {
  8730. return Tools._NoneLogLevel;
  8731. },
  8732. enumerable: true,
  8733. configurable: true
  8734. });
  8735. Object.defineProperty(Tools, "MessageLogLevel", {
  8736. get: function () {
  8737. return Tools._MessageLogLevel;
  8738. },
  8739. enumerable: true,
  8740. configurable: true
  8741. });
  8742. Object.defineProperty(Tools, "WarningLogLevel", {
  8743. get: function () {
  8744. return Tools._WarningLogLevel;
  8745. },
  8746. enumerable: true,
  8747. configurable: true
  8748. });
  8749. Object.defineProperty(Tools, "ErrorLogLevel", {
  8750. get: function () {
  8751. return Tools._ErrorLogLevel;
  8752. },
  8753. enumerable: true,
  8754. configurable: true
  8755. });
  8756. Object.defineProperty(Tools, "AllLogLevel", {
  8757. get: function () {
  8758. return Tools._MessageLogLevel | Tools._WarningLogLevel | Tools._ErrorLogLevel;
  8759. },
  8760. enumerable: true,
  8761. configurable: true
  8762. });
  8763. Tools._AddLogEntry = function (entry) {
  8764. Tools._LogCache = entry + Tools._LogCache;
  8765. if (Tools.OnNewCacheEntry) {
  8766. Tools.OnNewCacheEntry(entry);
  8767. }
  8768. };
  8769. Tools._FormatMessage = function (message) {
  8770. var padStr = function (i) { return (i < 10) ? "0" + i : "" + i; };
  8771. var date = new Date();
  8772. return "[" + padStr(date.getHours()) + ":" + padStr(date.getMinutes()) + ":" + padStr(date.getSeconds()) + "]: " + message;
  8773. };
  8774. Tools._LogDisabled = function (message) {
  8775. // nothing to do
  8776. };
  8777. Tools._LogEnabled = function (message) {
  8778. var formattedMessage = Tools._FormatMessage(message);
  8779. console.log("BJS - " + formattedMessage);
  8780. var entry = "<div style='color:white'>" + formattedMessage + "</div><br>";
  8781. Tools._AddLogEntry(entry);
  8782. };
  8783. Tools._WarnDisabled = function (message) {
  8784. // nothing to do
  8785. };
  8786. Tools._WarnEnabled = function (message) {
  8787. var formattedMessage = Tools._FormatMessage(message);
  8788. console.warn("BJS - " + formattedMessage);
  8789. var entry = "<div style='color:orange'>" + formattedMessage + "</div><br>";
  8790. Tools._AddLogEntry(entry);
  8791. };
  8792. Tools._ErrorDisabled = function (message) {
  8793. // nothing to do
  8794. };
  8795. Tools._ErrorEnabled = function (message) {
  8796. Tools.errorsCount++;
  8797. var formattedMessage = Tools._FormatMessage(message);
  8798. console.error("BJS - " + formattedMessage);
  8799. var entry = "<div style='color:red'>" + formattedMessage + "</div><br>";
  8800. Tools._AddLogEntry(entry);
  8801. };
  8802. Object.defineProperty(Tools, "LogCache", {
  8803. get: function () {
  8804. return Tools._LogCache;
  8805. },
  8806. enumerable: true,
  8807. configurable: true
  8808. });
  8809. Tools.ClearLogCache = function () {
  8810. Tools._LogCache = "";
  8811. Tools.errorsCount = 0;
  8812. };
  8813. Object.defineProperty(Tools, "LogLevels", {
  8814. set: function (level) {
  8815. if ((level & Tools.MessageLogLevel) === Tools.MessageLogLevel) {
  8816. Tools.Log = Tools._LogEnabled;
  8817. }
  8818. else {
  8819. Tools.Log = Tools._LogDisabled;
  8820. }
  8821. if ((level & Tools.WarningLogLevel) === Tools.WarningLogLevel) {
  8822. Tools.Warn = Tools._WarnEnabled;
  8823. }
  8824. else {
  8825. Tools.Warn = Tools._WarnDisabled;
  8826. }
  8827. if ((level & Tools.ErrorLogLevel) === Tools.ErrorLogLevel) {
  8828. Tools.Error = Tools._ErrorEnabled;
  8829. }
  8830. else {
  8831. Tools.Error = Tools._ErrorDisabled;
  8832. }
  8833. },
  8834. enumerable: true,
  8835. configurable: true
  8836. });
  8837. Tools.IsWindowObjectExist = function () {
  8838. return (typeof window) !== "undefined";
  8839. };
  8840. Object.defineProperty(Tools, "PerformanceNoneLogLevel", {
  8841. get: function () {
  8842. return Tools._PerformanceNoneLogLevel;
  8843. },
  8844. enumerable: true,
  8845. configurable: true
  8846. });
  8847. Object.defineProperty(Tools, "PerformanceUserMarkLogLevel", {
  8848. get: function () {
  8849. return Tools._PerformanceUserMarkLogLevel;
  8850. },
  8851. enumerable: true,
  8852. configurable: true
  8853. });
  8854. Object.defineProperty(Tools, "PerformanceConsoleLogLevel", {
  8855. get: function () {
  8856. return Tools._PerformanceConsoleLogLevel;
  8857. },
  8858. enumerable: true,
  8859. configurable: true
  8860. });
  8861. Object.defineProperty(Tools, "PerformanceLogLevel", {
  8862. set: function (level) {
  8863. if ((level & Tools.PerformanceUserMarkLogLevel) === Tools.PerformanceUserMarkLogLevel) {
  8864. Tools.StartPerformanceCounter = Tools._StartUserMark;
  8865. Tools.EndPerformanceCounter = Tools._EndUserMark;
  8866. return;
  8867. }
  8868. if ((level & Tools.PerformanceConsoleLogLevel) === Tools.PerformanceConsoleLogLevel) {
  8869. Tools.StartPerformanceCounter = Tools._StartPerformanceConsole;
  8870. Tools.EndPerformanceCounter = Tools._EndPerformanceConsole;
  8871. return;
  8872. }
  8873. Tools.StartPerformanceCounter = Tools._StartPerformanceCounterDisabled;
  8874. Tools.EndPerformanceCounter = Tools._EndPerformanceCounterDisabled;
  8875. },
  8876. enumerable: true,
  8877. configurable: true
  8878. });
  8879. Tools._StartPerformanceCounterDisabled = function (counterName, condition) {
  8880. };
  8881. Tools._EndPerformanceCounterDisabled = function (counterName, condition) {
  8882. };
  8883. Tools._StartUserMark = function (counterName, condition) {
  8884. if (condition === void 0) { condition = true; }
  8885. if (!Tools._performance) {
  8886. if (!Tools.IsWindowObjectExist()) {
  8887. return;
  8888. }
  8889. Tools._performance = window.performance;
  8890. }
  8891. if (!condition || !Tools._performance.mark) {
  8892. return;
  8893. }
  8894. Tools._performance.mark(counterName + "-Begin");
  8895. };
  8896. Tools._EndUserMark = function (counterName, condition) {
  8897. if (condition === void 0) { condition = true; }
  8898. if (!condition || !Tools._performance.mark) {
  8899. return;
  8900. }
  8901. Tools._performance.mark(counterName + "-End");
  8902. Tools._performance.measure(counterName, counterName + "-Begin", counterName + "-End");
  8903. };
  8904. Tools._StartPerformanceConsole = function (counterName, condition) {
  8905. if (condition === void 0) { condition = true; }
  8906. if (!condition) {
  8907. return;
  8908. }
  8909. Tools._StartUserMark(counterName, condition);
  8910. if (console.time) {
  8911. console.time(counterName);
  8912. }
  8913. };
  8914. Tools._EndPerformanceConsole = function (counterName, condition) {
  8915. if (condition === void 0) { condition = true; }
  8916. if (!condition) {
  8917. return;
  8918. }
  8919. Tools._EndUserMark(counterName, condition);
  8920. if (console.time) {
  8921. console.timeEnd(counterName);
  8922. }
  8923. };
  8924. Object.defineProperty(Tools, "Now", {
  8925. get: function () {
  8926. if (Tools.IsWindowObjectExist() && window.performance && window.performance.now) {
  8927. return window.performance.now();
  8928. }
  8929. return new Date().getTime();
  8930. },
  8931. enumerable: true,
  8932. configurable: true
  8933. });
  8934. /**
  8935. * This method will return the name of the class used to create the instance of the given object.
  8936. * It will works only on Javascript basic data types (number, string, ...) and instance of class declared with the @className decorator.
  8937. * @param object the object to get the class name from
  8938. * @return the name of the class, will be "object" for a custom data type not using the @className decorator
  8939. */
  8940. Tools.GetClassName = function (object, isType) {
  8941. if (isType === void 0) { isType = false; }
  8942. var name = null;
  8943. if (!isType && object.getClassName) {
  8944. name = object.getClassName();
  8945. }
  8946. else {
  8947. if (object instanceof Object) {
  8948. var classObj = isType ? object : Object.getPrototypeOf(object);
  8949. name = classObj.constructor["__bjsclassName__"];
  8950. }
  8951. if (!name) {
  8952. name = typeof object;
  8953. }
  8954. }
  8955. return name;
  8956. };
  8957. Tools.First = function (array, predicate) {
  8958. for (var _i = 0, array_1 = array; _i < array_1.length; _i++) {
  8959. var el = array_1[_i];
  8960. if (predicate(el)) {
  8961. return el;
  8962. }
  8963. }
  8964. return null;
  8965. };
  8966. /**
  8967. * This method will return the name of the full name of the class, including its owning module (if any).
  8968. * 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).
  8969. * @param object the object to get the class name from
  8970. * @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.
  8971. */
  8972. Tools.getFullClassName = function (object, isType) {
  8973. if (isType === void 0) { isType = false; }
  8974. var className = null;
  8975. var moduleName = null;
  8976. if (!isType && object.getClassName) {
  8977. className = object.getClassName();
  8978. }
  8979. else {
  8980. if (object instanceof Object) {
  8981. var classObj = isType ? object : Object.getPrototypeOf(object);
  8982. className = classObj.constructor["__bjsclassName__"];
  8983. moduleName = classObj.constructor["__bjsmoduleName__"];
  8984. }
  8985. if (!className) {
  8986. className = typeof object;
  8987. }
  8988. }
  8989. if (!className) {
  8990. return null;
  8991. }
  8992. return ((moduleName != null) ? (moduleName + ".") : "") + className;
  8993. };
  8994. /**
  8995. * 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.
  8996. * @param array
  8997. */
  8998. Tools.arrayOrStringFeeder = function (array) {
  8999. return function (index) {
  9000. if (index >= array.length) {
  9001. return null;
  9002. }
  9003. var val = array.charCodeAt ? array.charCodeAt(index) : array[index];
  9004. if (val && val.getHashCode) {
  9005. val = val.getHashCode();
  9006. }
  9007. if (typeof val === "string") {
  9008. return Tools.hashCodeFromStream(Tools.arrayOrStringFeeder(val));
  9009. }
  9010. return val;
  9011. };
  9012. };
  9013. /**
  9014. * Compute the hashCode of a stream of number
  9015. * To compute the HashCode on a string or an Array of data types implementing the getHashCode() method, use the arrayOrStringFeeder method.
  9016. * @param feeder a callback that will be called until it returns null, each valid returned values will be used to compute the hash code.
  9017. * @return the hash code computed
  9018. */
  9019. Tools.hashCodeFromStream = function (feeder) {
  9020. // Based from here: http://stackoverflow.com/a/7616484/802124
  9021. var hash = 0;
  9022. var index = 0;
  9023. var chr = feeder(index++);
  9024. while (chr != null) {
  9025. hash = ((hash << 5) - hash) + chr;
  9026. hash |= 0; // Convert to 32bit integer
  9027. chr = feeder(index++);
  9028. }
  9029. return hash;
  9030. };
  9031. /**
  9032. * Returns a promise that resolves after the given amount of time.
  9033. * @param delay Number of milliseconds to delay
  9034. * @returns Promise that resolves after the given amount of time
  9035. */
  9036. Tools.DelayAsync = function (delay) {
  9037. return new Promise(function (resolve) {
  9038. setTimeout(function () {
  9039. resolve();
  9040. }, delay);
  9041. });
  9042. };
  9043. Tools.BaseUrl = "";
  9044. Tools.DefaultRetryStrategy = RetryStrategy.ExponentialBackoff();
  9045. /**
  9046. * Default behaviour for cors in the application.
  9047. * It can be a string if the expected behavior is identical in the entire app.
  9048. * Or a callback to be able to set it per url or on a group of them (in case of Video source for instance)
  9049. */
  9050. Tools.CorsBehavior = "anonymous";
  9051. Tools.UseFallbackTexture = true;
  9052. /**
  9053. * Use this object to register external classes like custom textures or material
  9054. * to allow the laoders to instantiate them
  9055. */
  9056. Tools.RegisteredExternalClasses = {};
  9057. // Used in case of a texture loading problem
  9058. 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";
  9059. Tools.PreprocessUrl = function (url) {
  9060. return url;
  9061. };
  9062. // Logs
  9063. Tools._NoneLogLevel = 0;
  9064. Tools._MessageLogLevel = 1;
  9065. Tools._WarningLogLevel = 2;
  9066. Tools._ErrorLogLevel = 4;
  9067. Tools._LogCache = "";
  9068. Tools.errorsCount = 0;
  9069. Tools.Log = Tools._LogEnabled;
  9070. Tools.Warn = Tools._WarnEnabled;
  9071. Tools.Error = Tools._ErrorEnabled;
  9072. // Performances
  9073. Tools._PerformanceNoneLogLevel = 0;
  9074. Tools._PerformanceUserMarkLogLevel = 1;
  9075. Tools._PerformanceConsoleLogLevel = 2;
  9076. Tools.StartPerformanceCounter = Tools._StartPerformanceCounterDisabled;
  9077. Tools.EndPerformanceCounter = Tools._EndPerformanceCounterDisabled;
  9078. return Tools;
  9079. }());
  9080. BABYLON.Tools = Tools;
  9081. /**
  9082. * This class is used to track a performance counter which is number based.
  9083. * The user has access to many properties which give statistics of different nature
  9084. *
  9085. * The implementer can track two kinds of Performance Counter: time and count
  9086. * 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.
  9087. * 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.
  9088. */
  9089. var PerfCounter = /** @class */ (function () {
  9090. function PerfCounter() {
  9091. this._startMonitoringTime = 0;
  9092. this._min = 0;
  9093. this._max = 0;
  9094. this._average = 0;
  9095. this._lastSecAverage = 0;
  9096. this._current = 0;
  9097. this._totalValueCount = 0;
  9098. this._totalAccumulated = 0;
  9099. this._lastSecAccumulated = 0;
  9100. this._lastSecTime = 0;
  9101. this._lastSecValueCount = 0;
  9102. }
  9103. Object.defineProperty(PerfCounter.prototype, "min", {
  9104. /**
  9105. * Returns the smallest value ever
  9106. */
  9107. get: function () {
  9108. return this._min;
  9109. },
  9110. enumerable: true,
  9111. configurable: true
  9112. });
  9113. Object.defineProperty(PerfCounter.prototype, "max", {
  9114. /**
  9115. * Returns the biggest value ever
  9116. */
  9117. get: function () {
  9118. return this._max;
  9119. },
  9120. enumerable: true,
  9121. configurable: true
  9122. });
  9123. Object.defineProperty(PerfCounter.prototype, "average", {
  9124. /**
  9125. * Returns the average value since the performance counter is running
  9126. */
  9127. get: function () {
  9128. return this._average;
  9129. },
  9130. enumerable: true,
  9131. configurable: true
  9132. });
  9133. Object.defineProperty(PerfCounter.prototype, "lastSecAverage", {
  9134. /**
  9135. * Returns the average value of the last second the counter was monitored
  9136. */
  9137. get: function () {
  9138. return this._lastSecAverage;
  9139. },
  9140. enumerable: true,
  9141. configurable: true
  9142. });
  9143. Object.defineProperty(PerfCounter.prototype, "current", {
  9144. /**
  9145. * Returns the current value
  9146. */
  9147. get: function () {
  9148. return this._current;
  9149. },
  9150. enumerable: true,
  9151. configurable: true
  9152. });
  9153. Object.defineProperty(PerfCounter.prototype, "total", {
  9154. get: function () {
  9155. return this._totalAccumulated;
  9156. },
  9157. enumerable: true,
  9158. configurable: true
  9159. });
  9160. Object.defineProperty(PerfCounter.prototype, "count", {
  9161. get: function () {
  9162. return this._totalValueCount;
  9163. },
  9164. enumerable: true,
  9165. configurable: true
  9166. });
  9167. /**
  9168. * Call this method to start monitoring a new frame.
  9169. * 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.
  9170. */
  9171. PerfCounter.prototype.fetchNewFrame = function () {
  9172. this._totalValueCount++;
  9173. this._current = 0;
  9174. this._lastSecValueCount++;
  9175. };
  9176. /**
  9177. * Call this method to monitor a count of something (e.g. mesh drawn in viewport count)
  9178. * @param newCount the count value to add to the monitored count
  9179. * @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.
  9180. */
  9181. PerfCounter.prototype.addCount = function (newCount, fetchResult) {
  9182. if (!PerfCounter.Enabled) {
  9183. return;
  9184. }
  9185. this._current += newCount;
  9186. if (fetchResult) {
  9187. this._fetchResult();
  9188. }
  9189. };
  9190. /**
  9191. * Start monitoring this performance counter
  9192. */
  9193. PerfCounter.prototype.beginMonitoring = function () {
  9194. if (!PerfCounter.Enabled) {
  9195. return;
  9196. }
  9197. this._startMonitoringTime = Tools.Now;
  9198. };
  9199. /**
  9200. * Compute the time lapsed since the previous beginMonitoring() call.
  9201. * @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
  9202. */
  9203. PerfCounter.prototype.endMonitoring = function (newFrame) {
  9204. if (newFrame === void 0) { newFrame = true; }
  9205. if (!PerfCounter.Enabled) {
  9206. return;
  9207. }
  9208. if (newFrame) {
  9209. this.fetchNewFrame();
  9210. }
  9211. var currentTime = Tools.Now;
  9212. this._current = currentTime - this._startMonitoringTime;
  9213. if (newFrame) {
  9214. this._fetchResult();
  9215. }
  9216. };
  9217. PerfCounter.prototype._fetchResult = function () {
  9218. this._totalAccumulated += this._current;
  9219. this._lastSecAccumulated += this._current;
  9220. // Min/Max update
  9221. this._min = Math.min(this._min, this._current);
  9222. this._max = Math.max(this._max, this._current);
  9223. this._average = this._totalAccumulated / this._totalValueCount;
  9224. // Reset last sec?
  9225. var now = Tools.Now;
  9226. if ((now - this._lastSecTime) > 1000) {
  9227. this._lastSecAverage = this._lastSecAccumulated / this._lastSecValueCount;
  9228. this._lastSecTime = now;
  9229. this._lastSecAccumulated = 0;
  9230. this._lastSecValueCount = 0;
  9231. }
  9232. };
  9233. PerfCounter.Enabled = true;
  9234. return PerfCounter;
  9235. }());
  9236. BABYLON.PerfCounter = PerfCounter;
  9237. /**
  9238. * Use this className as a decorator on a given class definition to add it a name and optionally its module.
  9239. * You can then use the Tools.getClassName(obj) on an instance to retrieve its class name.
  9240. * This method is the only way to get it done in all cases, even if the .js file declaring the class is minified
  9241. * @param name The name of the class, case should be preserved
  9242. * @param module The name of the Module hosting the class, optional, but strongly recommended to specify if possible. Case should be preserved.
  9243. */
  9244. function className(name, module) {
  9245. return function (target) {
  9246. target["__bjsclassName__"] = name;
  9247. target["__bjsmoduleName__"] = (module != null) ? module : null;
  9248. };
  9249. }
  9250. BABYLON.className = className;
  9251. /**
  9252. * An implementation of a loop for asynchronous functions.
  9253. */
  9254. var AsyncLoop = /** @class */ (function () {
  9255. /**
  9256. * Constroctor.
  9257. * @param iterations the number of iterations.
  9258. * @param _fn the function to run each iteration
  9259. * @param _successCallback the callback that will be called upon succesful execution
  9260. * @param offset starting offset.
  9261. */
  9262. function AsyncLoop(iterations, _fn, _successCallback, offset) {
  9263. if (offset === void 0) { offset = 0; }
  9264. this.iterations = iterations;
  9265. this._fn = _fn;
  9266. this._successCallback = _successCallback;
  9267. this.index = offset - 1;
  9268. this._done = false;
  9269. }
  9270. /**
  9271. * Execute the next iteration. Must be called after the last iteration was finished.
  9272. */
  9273. AsyncLoop.prototype.executeNext = function () {
  9274. if (!this._done) {
  9275. if (this.index + 1 < this.iterations) {
  9276. ++this.index;
  9277. this._fn(this);
  9278. }
  9279. else {
  9280. this.breakLoop();
  9281. }
  9282. }
  9283. };
  9284. /**
  9285. * Break the loop and run the success callback.
  9286. */
  9287. AsyncLoop.prototype.breakLoop = function () {
  9288. this._done = true;
  9289. this._successCallback();
  9290. };
  9291. /**
  9292. * Helper function
  9293. */
  9294. AsyncLoop.Run = function (iterations, _fn, _successCallback, offset) {
  9295. if (offset === void 0) { offset = 0; }
  9296. var loop = new AsyncLoop(iterations, _fn, _successCallback, offset);
  9297. loop.executeNext();
  9298. return loop;
  9299. };
  9300. /**
  9301. * A for-loop that will run a given number of iterations synchronous and the rest async.
  9302. * @param iterations total number of iterations
  9303. * @param syncedIterations number of synchronous iterations in each async iteration.
  9304. * @param fn the function to call each iteration.
  9305. * @param callback a success call back that will be called when iterating stops.
  9306. * @param breakFunction a break condition (optional)
  9307. * @param timeout timeout settings for the setTimeout function. default - 0.
  9308. * @constructor
  9309. */
  9310. AsyncLoop.SyncAsyncForLoop = function (iterations, syncedIterations, fn, callback, breakFunction, timeout) {
  9311. if (timeout === void 0) { timeout = 0; }
  9312. AsyncLoop.Run(Math.ceil(iterations / syncedIterations), function (loop) {
  9313. if (breakFunction && breakFunction())
  9314. loop.breakLoop();
  9315. else {
  9316. setTimeout(function () {
  9317. for (var i = 0; i < syncedIterations; ++i) {
  9318. var iteration = (loop.index * syncedIterations) + i;
  9319. if (iteration >= iterations)
  9320. break;
  9321. fn(iteration);
  9322. if (breakFunction && breakFunction()) {
  9323. loop.breakLoop();
  9324. break;
  9325. }
  9326. }
  9327. loop.executeNext();
  9328. }, timeout);
  9329. }
  9330. }, callback);
  9331. };
  9332. return AsyncLoop;
  9333. }());
  9334. BABYLON.AsyncLoop = AsyncLoop;
  9335. })(BABYLON || (BABYLON = {}));
  9336. //# sourceMappingURL=babylon.tools.js.map
  9337. var BABYLON;
  9338. (function (BABYLON) {
  9339. var PromiseStates;
  9340. (function (PromiseStates) {
  9341. PromiseStates[PromiseStates["Pending"] = 0] = "Pending";
  9342. PromiseStates[PromiseStates["Fulfilled"] = 1] = "Fulfilled";
  9343. PromiseStates[PromiseStates["Rejected"] = 2] = "Rejected";
  9344. })(PromiseStates || (PromiseStates = {}));
  9345. var FulFillmentAgregator = /** @class */ (function () {
  9346. function FulFillmentAgregator() {
  9347. this.count = 0;
  9348. this.target = 0;
  9349. this.results = [];
  9350. }
  9351. return FulFillmentAgregator;
  9352. }());
  9353. var InternalPromise = /** @class */ (function () {
  9354. function InternalPromise(resolver) {
  9355. var _this = this;
  9356. this._state = PromiseStates.Pending;
  9357. this._children = new Array();
  9358. this._rejectWasConsumed = false;
  9359. if (!resolver) {
  9360. return;
  9361. }
  9362. try {
  9363. resolver(function (value) {
  9364. _this._resolve(value);
  9365. }, function (reason) {
  9366. _this._reject(reason);
  9367. });
  9368. }
  9369. catch (e) {
  9370. this._reject(e);
  9371. }
  9372. }
  9373. InternalPromise.prototype.catch = function (onRejected) {
  9374. return this.then(undefined, onRejected);
  9375. };
  9376. InternalPromise.prototype.then = function (onFulfilled, onRejected) {
  9377. var _this = this;
  9378. var newPromise = new InternalPromise();
  9379. newPromise._onFulfilled = onFulfilled;
  9380. newPromise._onRejected = onRejected;
  9381. // Composition
  9382. this._children.push(newPromise);
  9383. if (this._state !== PromiseStates.Pending) {
  9384. BABYLON.Tools.SetImmediate(function () {
  9385. if (_this._state === PromiseStates.Fulfilled || _this._rejectWasConsumed) {
  9386. var returnedValue = newPromise._resolve(_this._result);
  9387. if (returnedValue !== undefined && returnedValue !== null) {
  9388. if (returnedValue._state !== undefined) {
  9389. var returnedPromise = returnedValue;
  9390. newPromise._children.push(returnedPromise);
  9391. newPromise = returnedPromise;
  9392. }
  9393. else {
  9394. newPromise._result = returnedValue;
  9395. }
  9396. }
  9397. }
  9398. else {
  9399. newPromise._reject(_this._reason);
  9400. }
  9401. });
  9402. }
  9403. return newPromise;
  9404. };
  9405. InternalPromise.prototype._moveChildren = function (children) {
  9406. (_a = this._children).push.apply(_a, children.splice(0, children.length));
  9407. if (this._state === PromiseStates.Fulfilled) {
  9408. for (var _i = 0, _b = this._children; _i < _b.length; _i++) {
  9409. var child = _b[_i];
  9410. child._resolve(this._result);
  9411. }
  9412. }
  9413. else if (this._state === PromiseStates.Rejected) {
  9414. for (var _c = 0, _d = this._children; _c < _d.length; _c++) {
  9415. var child = _d[_c];
  9416. child._reject(this._reason);
  9417. }
  9418. }
  9419. var _a;
  9420. };
  9421. InternalPromise.prototype._resolve = function (value) {
  9422. try {
  9423. this._state = PromiseStates.Fulfilled;
  9424. this._result = value;
  9425. var returnedValue = null;
  9426. if (this._onFulfilled) {
  9427. returnedValue = this._onFulfilled(value);
  9428. }
  9429. if (returnedValue !== undefined && returnedValue !== null) {
  9430. if (returnedValue._state !== undefined) {
  9431. // Transmit children
  9432. var returnedPromise = returnedValue;
  9433. returnedPromise._moveChildren(this._children);
  9434. }
  9435. else {
  9436. value = returnedValue;
  9437. }
  9438. }
  9439. for (var _i = 0, _a = this._children; _i < _a.length; _i++) {
  9440. var child = _a[_i];
  9441. child._resolve(value);
  9442. }
  9443. this._children.length = 0;
  9444. delete this._onFulfilled;
  9445. delete this._onRejected;
  9446. return returnedValue;
  9447. }
  9448. catch (e) {
  9449. this._reject(e, true);
  9450. }
  9451. return null;
  9452. };
  9453. InternalPromise.prototype._reject = function (reason, onLocalThrow) {
  9454. if (onLocalThrow === void 0) { onLocalThrow = false; }
  9455. this._state = PromiseStates.Rejected;
  9456. this._reason = reason;
  9457. if (this._onRejected && !onLocalThrow) {
  9458. try {
  9459. this._onRejected(reason);
  9460. this._rejectWasConsumed = true;
  9461. }
  9462. catch (e) {
  9463. reason = e;
  9464. }
  9465. }
  9466. for (var _i = 0, _a = this._children; _i < _a.length; _i++) {
  9467. var child = _a[_i];
  9468. if (this._rejectWasConsumed) {
  9469. child._resolve(null);
  9470. }
  9471. else {
  9472. child._reject(reason);
  9473. }
  9474. }
  9475. this._children.length = 0;
  9476. delete this._onFulfilled;
  9477. delete this._onRejected;
  9478. };
  9479. InternalPromise.resolve = function (value) {
  9480. var newPromise = new InternalPromise();
  9481. newPromise._resolve(value);
  9482. return newPromise;
  9483. };
  9484. InternalPromise._RegisterForFulfillment = function (promise, agregator, index) {
  9485. promise.then(function (value) {
  9486. agregator.results[index] = value;
  9487. agregator.count++;
  9488. if (agregator.count === agregator.target) {
  9489. agregator.rootPromise._resolve(agregator.results);
  9490. }
  9491. return null;
  9492. }, function (reason) {
  9493. if (agregator.rootPromise._state !== PromiseStates.Rejected) {
  9494. agregator.rootPromise._reject(reason);
  9495. }
  9496. });
  9497. };
  9498. InternalPromise.all = function (promises) {
  9499. var newPromise = new InternalPromise();
  9500. var agregator = new FulFillmentAgregator();
  9501. agregator.target = promises.length;
  9502. agregator.rootPromise = newPromise;
  9503. if (promises.length) {
  9504. for (var index = 0; index < promises.length; index++) {
  9505. InternalPromise._RegisterForFulfillment(promises[index], agregator, index);
  9506. }
  9507. }
  9508. else {
  9509. newPromise._resolve([]);
  9510. }
  9511. return newPromise;
  9512. };
  9513. InternalPromise.race = function (promises) {
  9514. var newPromise = new InternalPromise();
  9515. if (promises.length) {
  9516. for (var _i = 0, promises_1 = promises; _i < promises_1.length; _i++) {
  9517. var promise = promises_1[_i];
  9518. promise.then(function (value) {
  9519. if (newPromise) {
  9520. newPromise._resolve(value);
  9521. newPromise = null;
  9522. }
  9523. return null;
  9524. }, function (reason) {
  9525. if (newPromise) {
  9526. newPromise._reject(reason);
  9527. newPromise = null;
  9528. }
  9529. });
  9530. }
  9531. }
  9532. return newPromise;
  9533. };
  9534. return InternalPromise;
  9535. }());
  9536. /**
  9537. * Helper class that provides a small promise polyfill
  9538. */
  9539. var PromisePolyfill = /** @class */ (function () {
  9540. function PromisePolyfill() {
  9541. }
  9542. /**
  9543. * Static function used to check if the polyfill is required
  9544. * If this is the case then the function will inject the polyfill to window.Promise
  9545. * @param force defines a boolean used to force the injection (mostly for testing purposes)
  9546. */
  9547. PromisePolyfill.Apply = function (force) {
  9548. if (force === void 0) { force = false; }
  9549. if (force || typeof Promise === 'undefined') {
  9550. var root = window;
  9551. root.Promise = InternalPromise;
  9552. }
  9553. };
  9554. return PromisePolyfill;
  9555. }());
  9556. BABYLON.PromisePolyfill = PromisePolyfill;
  9557. })(BABYLON || (BABYLON = {}));
  9558. //# sourceMappingURL=babylon.promise.js.map
  9559. /// <reference path="../../../dist/preview release/babylon.d.ts" />
  9560. var BABYLON;
  9561. (function (BABYLON) {
  9562. /**
  9563. * Helper class to push actions to a pool of workers.
  9564. */
  9565. var WorkerPool = /** @class */ (function () {
  9566. /**
  9567. * Constructor
  9568. * @param workers Array of workers to use for actions
  9569. */
  9570. function WorkerPool(workers) {
  9571. this._pendingActions = new Array();
  9572. this._workerInfos = workers.map(function (worker) { return ({
  9573. worker: worker,
  9574. active: false
  9575. }); });
  9576. }
  9577. /**
  9578. * Terminates all workers and clears any pending actions.
  9579. */
  9580. WorkerPool.prototype.dispose = function () {
  9581. for (var _i = 0, _a = this._workerInfos; _i < _a.length; _i++) {
  9582. var workerInfo = _a[_i];
  9583. workerInfo.worker.terminate();
  9584. }
  9585. delete this._workerInfos;
  9586. delete this._pendingActions;
  9587. };
  9588. /**
  9589. * Pushes an action to the worker pool. If all the workers are active, the action will be
  9590. * pended until a worker has completed its action.
  9591. * @param action The action to perform. Call onComplete when the action is complete.
  9592. */
  9593. WorkerPool.prototype.push = function (action) {
  9594. for (var _i = 0, _a = this._workerInfos; _i < _a.length; _i++) {
  9595. var workerInfo = _a[_i];
  9596. if (!workerInfo.active) {
  9597. this._execute(workerInfo, action);
  9598. return;
  9599. }
  9600. }
  9601. this._pendingActions.push(action);
  9602. };
  9603. WorkerPool.prototype._execute = function (workerInfo, action) {
  9604. var _this = this;
  9605. workerInfo.active = true;
  9606. action(workerInfo.worker, function () {
  9607. workerInfo.active = false;
  9608. var nextAction = _this._pendingActions.shift();
  9609. if (nextAction) {
  9610. _this._execute(workerInfo, nextAction);
  9611. }
  9612. });
  9613. };
  9614. return WorkerPool;
  9615. }());
  9616. BABYLON.WorkerPool = WorkerPool;
  9617. })(BABYLON || (BABYLON = {}));
  9618. //# sourceMappingURL=babylon.workerPool.js.map
  9619. var BABYLON;
  9620. (function (BABYLON) {
  9621. var _AlphaState = /** @class */ (function () {
  9622. /**
  9623. * Initializes the state.
  9624. */
  9625. function _AlphaState() {
  9626. this._isAlphaBlendDirty = false;
  9627. this._isBlendFunctionParametersDirty = false;
  9628. this._isBlendEquationParametersDirty = false;
  9629. this._isBlendConstantsDirty = false;
  9630. this._alphaBlend = false;
  9631. this._blendFunctionParameters = new Array(4);
  9632. this._blendEquationParameters = new Array(2);
  9633. this._blendConstants = new Array(4);
  9634. this.reset();
  9635. }
  9636. Object.defineProperty(_AlphaState.prototype, "isDirty", {
  9637. get: function () {
  9638. return this._isAlphaBlendDirty || this._isBlendFunctionParametersDirty;
  9639. },
  9640. enumerable: true,
  9641. configurable: true
  9642. });
  9643. Object.defineProperty(_AlphaState.prototype, "alphaBlend", {
  9644. get: function () {
  9645. return this._alphaBlend;
  9646. },
  9647. set: function (value) {
  9648. if (this._alphaBlend === value) {
  9649. return;
  9650. }
  9651. this._alphaBlend = value;
  9652. this._isAlphaBlendDirty = true;
  9653. },
  9654. enumerable: true,
  9655. configurable: true
  9656. });
  9657. _AlphaState.prototype.setAlphaBlendConstants = function (r, g, b, a) {
  9658. if (this._blendConstants[0] === r &&
  9659. this._blendConstants[1] === g &&
  9660. this._blendConstants[2] === b &&
  9661. this._blendConstants[3] === a) {
  9662. return;
  9663. }
  9664. this._blendConstants[0] = r;
  9665. this._blendConstants[1] = g;
  9666. this._blendConstants[2] = b;
  9667. this._blendConstants[3] = a;
  9668. this._isBlendConstantsDirty = true;
  9669. };
  9670. _AlphaState.prototype.setAlphaBlendFunctionParameters = function (value0, value1, value2, value3) {
  9671. if (this._blendFunctionParameters[0] === value0 &&
  9672. this._blendFunctionParameters[1] === value1 &&
  9673. this._blendFunctionParameters[2] === value2 &&
  9674. this._blendFunctionParameters[3] === value3) {
  9675. return;
  9676. }
  9677. this._blendFunctionParameters[0] = value0;
  9678. this._blendFunctionParameters[1] = value1;
  9679. this._blendFunctionParameters[2] = value2;
  9680. this._blendFunctionParameters[3] = value3;
  9681. this._isBlendFunctionParametersDirty = true;
  9682. };
  9683. _AlphaState.prototype.setAlphaEquationParameters = function (rgb, alpha) {
  9684. if (this._blendEquationParameters[0] === rgb &&
  9685. this._blendEquationParameters[1] === alpha) {
  9686. return;
  9687. }
  9688. this._blendEquationParameters[0] = rgb;
  9689. this._blendEquationParameters[1] = alpha;
  9690. this._isBlendEquationParametersDirty = true;
  9691. };
  9692. _AlphaState.prototype.reset = function () {
  9693. this._alphaBlend = false;
  9694. this._blendFunctionParameters[0] = null;
  9695. this._blendFunctionParameters[1] = null;
  9696. this._blendFunctionParameters[2] = null;
  9697. this._blendFunctionParameters[3] = null;
  9698. this._blendEquationParameters[0] = null;
  9699. this._blendEquationParameters[1] = null;
  9700. this._blendConstants[0] = null;
  9701. this._blendConstants[1] = null;
  9702. this._blendConstants[2] = null;
  9703. this._blendConstants[3] = null;
  9704. this._isAlphaBlendDirty = true;
  9705. this._isBlendFunctionParametersDirty = false;
  9706. this._isBlendEquationParametersDirty = false;
  9707. this._isBlendConstantsDirty = false;
  9708. };
  9709. _AlphaState.prototype.apply = function (gl) {
  9710. if (!this.isDirty) {
  9711. return;
  9712. }
  9713. // Alpha blend
  9714. if (this._isAlphaBlendDirty) {
  9715. if (this._alphaBlend) {
  9716. gl.enable(gl.BLEND);
  9717. }
  9718. else {
  9719. gl.disable(gl.BLEND);
  9720. }
  9721. this._isAlphaBlendDirty = false;
  9722. }
  9723. // Alpha function
  9724. if (this._isBlendFunctionParametersDirty) {
  9725. gl.blendFuncSeparate(this._blendFunctionParameters[0], this._blendFunctionParameters[1], this._blendFunctionParameters[2], this._blendFunctionParameters[3]);
  9726. this._isBlendFunctionParametersDirty = false;
  9727. }
  9728. // Alpha equation
  9729. if (this._isBlendEquationParametersDirty) {
  9730. gl.blendEquationSeparate(this._isBlendEquationParametersDirty[0], this._isBlendEquationParametersDirty[1]);
  9731. this._isBlendEquationParametersDirty = false;
  9732. }
  9733. // Constants
  9734. if (this._isBlendConstantsDirty) {
  9735. gl.blendColor(this._blendConstants[0], this._blendConstants[1], this._blendConstants[2], this._blendConstants[3]);
  9736. this._isBlendConstantsDirty = false;
  9737. }
  9738. };
  9739. return _AlphaState;
  9740. }());
  9741. BABYLON._AlphaState = _AlphaState;
  9742. })(BABYLON || (BABYLON = {}));
  9743. //# sourceMappingURL=babylon.alphaCullingState.js.map
  9744. var BABYLON;
  9745. (function (BABYLON) {
  9746. var _DepthCullingState = /** @class */ (function () {
  9747. /**
  9748. * Initializes the state.
  9749. */
  9750. function _DepthCullingState() {
  9751. this._isDepthTestDirty = false;
  9752. this._isDepthMaskDirty = false;
  9753. this._isDepthFuncDirty = false;
  9754. this._isCullFaceDirty = false;
  9755. this._isCullDirty = false;
  9756. this._isZOffsetDirty = false;
  9757. this._isFrontFaceDirty = false;
  9758. this.reset();
  9759. }
  9760. Object.defineProperty(_DepthCullingState.prototype, "isDirty", {
  9761. get: function () {
  9762. return this._isDepthFuncDirty || this._isDepthTestDirty || this._isDepthMaskDirty || this._isCullFaceDirty || this._isCullDirty || this._isZOffsetDirty || this._isFrontFaceDirty;
  9763. },
  9764. enumerable: true,
  9765. configurable: true
  9766. });
  9767. Object.defineProperty(_DepthCullingState.prototype, "zOffset", {
  9768. get: function () {
  9769. return this._zOffset;
  9770. },
  9771. set: function (value) {
  9772. if (this._zOffset === value) {
  9773. return;
  9774. }
  9775. this._zOffset = value;
  9776. this._isZOffsetDirty = true;
  9777. },
  9778. enumerable: true,
  9779. configurable: true
  9780. });
  9781. Object.defineProperty(_DepthCullingState.prototype, "cullFace", {
  9782. get: function () {
  9783. return this._cullFace;
  9784. },
  9785. set: function (value) {
  9786. if (this._cullFace === value) {
  9787. return;
  9788. }
  9789. this._cullFace = value;
  9790. this._isCullFaceDirty = true;
  9791. },
  9792. enumerable: true,
  9793. configurable: true
  9794. });
  9795. Object.defineProperty(_DepthCullingState.prototype, "cull", {
  9796. get: function () {
  9797. return this._cull;
  9798. },
  9799. set: function (value) {
  9800. if (this._cull === value) {
  9801. return;
  9802. }
  9803. this._cull = value;
  9804. this._isCullDirty = true;
  9805. },
  9806. enumerable: true,
  9807. configurable: true
  9808. });
  9809. Object.defineProperty(_DepthCullingState.prototype, "depthFunc", {
  9810. get: function () {
  9811. return this._depthFunc;
  9812. },
  9813. set: function (value) {
  9814. if (this._depthFunc === value) {
  9815. return;
  9816. }
  9817. this._depthFunc = value;
  9818. this._isDepthFuncDirty = true;
  9819. },
  9820. enumerable: true,
  9821. configurable: true
  9822. });
  9823. Object.defineProperty(_DepthCullingState.prototype, "depthMask", {
  9824. get: function () {
  9825. return this._depthMask;
  9826. },
  9827. set: function (value) {
  9828. if (this._depthMask === value) {
  9829. return;
  9830. }
  9831. this._depthMask = value;
  9832. this._isDepthMaskDirty = true;
  9833. },
  9834. enumerable: true,
  9835. configurable: true
  9836. });
  9837. Object.defineProperty(_DepthCullingState.prototype, "depthTest", {
  9838. get: function () {
  9839. return this._depthTest;
  9840. },
  9841. set: function (value) {
  9842. if (this._depthTest === value) {
  9843. return;
  9844. }
  9845. this._depthTest = value;
  9846. this._isDepthTestDirty = true;
  9847. },
  9848. enumerable: true,
  9849. configurable: true
  9850. });
  9851. Object.defineProperty(_DepthCullingState.prototype, "frontFace", {
  9852. get: function () {
  9853. return this._frontFace;
  9854. },
  9855. set: function (value) {
  9856. if (this._frontFace === value) {
  9857. return;
  9858. }
  9859. this._frontFace = value;
  9860. this._isFrontFaceDirty = true;
  9861. },
  9862. enumerable: true,
  9863. configurable: true
  9864. });
  9865. _DepthCullingState.prototype.reset = function () {
  9866. this._depthMask = true;
  9867. this._depthTest = true;
  9868. this._depthFunc = null;
  9869. this._cullFace = null;
  9870. this._cull = null;
  9871. this._zOffset = 0;
  9872. this._frontFace = null;
  9873. this._isDepthTestDirty = true;
  9874. this._isDepthMaskDirty = true;
  9875. this._isDepthFuncDirty = false;
  9876. this._isCullFaceDirty = false;
  9877. this._isCullDirty = false;
  9878. this._isZOffsetDirty = false;
  9879. this._isFrontFaceDirty = false;
  9880. };
  9881. _DepthCullingState.prototype.apply = function (gl) {
  9882. if (!this.isDirty) {
  9883. return;
  9884. }
  9885. // Cull
  9886. if (this._isCullDirty) {
  9887. if (this.cull) {
  9888. gl.enable(gl.CULL_FACE);
  9889. }
  9890. else {
  9891. gl.disable(gl.CULL_FACE);
  9892. }
  9893. this._isCullDirty = false;
  9894. }
  9895. // Cull face
  9896. if (this._isCullFaceDirty) {
  9897. gl.cullFace(this.cullFace);
  9898. this._isCullFaceDirty = false;
  9899. }
  9900. // Depth mask
  9901. if (this._isDepthMaskDirty) {
  9902. gl.depthMask(this.depthMask);
  9903. this._isDepthMaskDirty = false;
  9904. }
  9905. // Depth test
  9906. if (this._isDepthTestDirty) {
  9907. if (this.depthTest) {
  9908. gl.enable(gl.DEPTH_TEST);
  9909. }
  9910. else {
  9911. gl.disable(gl.DEPTH_TEST);
  9912. }
  9913. this._isDepthTestDirty = false;
  9914. }
  9915. // Depth func
  9916. if (this._isDepthFuncDirty) {
  9917. gl.depthFunc(this.depthFunc);
  9918. this._isDepthFuncDirty = false;
  9919. }
  9920. // zOffset
  9921. if (this._isZOffsetDirty) {
  9922. if (this.zOffset) {
  9923. gl.enable(gl.POLYGON_OFFSET_FILL);
  9924. gl.polygonOffset(this.zOffset, 0);
  9925. }
  9926. else {
  9927. gl.disable(gl.POLYGON_OFFSET_FILL);
  9928. }
  9929. this._isZOffsetDirty = false;
  9930. }
  9931. // Front face
  9932. if (this._isFrontFaceDirty) {
  9933. gl.frontFace(this.frontFace);
  9934. this._isFrontFaceDirty = false;
  9935. }
  9936. };
  9937. return _DepthCullingState;
  9938. }());
  9939. BABYLON._DepthCullingState = _DepthCullingState;
  9940. })(BABYLON || (BABYLON = {}));
  9941. //# sourceMappingURL=babylon.depthCullingState.js.map
  9942. var BABYLON;
  9943. (function (BABYLON) {
  9944. var _StencilState = /** @class */ (function () {
  9945. function _StencilState() {
  9946. this._isStencilTestDirty = false;
  9947. this._isStencilMaskDirty = false;
  9948. this._isStencilFuncDirty = false;
  9949. this._isStencilOpDirty = false;
  9950. this.reset();
  9951. }
  9952. Object.defineProperty(_StencilState.prototype, "isDirty", {
  9953. get: function () {
  9954. return this._isStencilTestDirty || this._isStencilMaskDirty || this._isStencilFuncDirty || this._isStencilOpDirty;
  9955. },
  9956. enumerable: true,
  9957. configurable: true
  9958. });
  9959. Object.defineProperty(_StencilState.prototype, "stencilFunc", {
  9960. get: function () {
  9961. return this._stencilFunc;
  9962. },
  9963. set: function (value) {
  9964. if (this._stencilFunc === value) {
  9965. return;
  9966. }
  9967. this._stencilFunc = value;
  9968. this._isStencilFuncDirty = true;
  9969. },
  9970. enumerable: true,
  9971. configurable: true
  9972. });
  9973. Object.defineProperty(_StencilState.prototype, "stencilFuncRef", {
  9974. get: function () {
  9975. return this._stencilFuncRef;
  9976. },
  9977. set: function (value) {
  9978. if (this._stencilFuncRef === value) {
  9979. return;
  9980. }
  9981. this._stencilFuncRef = value;
  9982. this._isStencilFuncDirty = true;
  9983. },
  9984. enumerable: true,
  9985. configurable: true
  9986. });
  9987. Object.defineProperty(_StencilState.prototype, "stencilFuncMask", {
  9988. get: function () {
  9989. return this._stencilFuncMask;
  9990. },
  9991. set: function (value) {
  9992. if (this._stencilFuncMask === value) {
  9993. return;
  9994. }
  9995. this._stencilFuncMask = value;
  9996. this._isStencilFuncDirty = true;
  9997. },
  9998. enumerable: true,
  9999. configurable: true
  10000. });
  10001. Object.defineProperty(_StencilState.prototype, "stencilOpStencilFail", {
  10002. get: function () {
  10003. return this._stencilOpStencilFail;
  10004. },
  10005. set: function (value) {
  10006. if (this._stencilOpStencilFail === value) {
  10007. return;
  10008. }
  10009. this._stencilOpStencilFail = value;
  10010. this._isStencilOpDirty = true;
  10011. },
  10012. enumerable: true,
  10013. configurable: true
  10014. });
  10015. Object.defineProperty(_StencilState.prototype, "stencilOpDepthFail", {
  10016. get: function () {
  10017. return this._stencilOpDepthFail;
  10018. },
  10019. set: function (value) {
  10020. if (this._stencilOpDepthFail === value) {
  10021. return;
  10022. }
  10023. this._stencilOpDepthFail = value;
  10024. this._isStencilOpDirty = true;
  10025. },
  10026. enumerable: true,
  10027. configurable: true
  10028. });
  10029. Object.defineProperty(_StencilState.prototype, "stencilOpStencilDepthPass", {
  10030. get: function () {
  10031. return this._stencilOpStencilDepthPass;
  10032. },
  10033. set: function (value) {
  10034. if (this._stencilOpStencilDepthPass === value) {
  10035. return;
  10036. }
  10037. this._stencilOpStencilDepthPass = value;
  10038. this._isStencilOpDirty = true;
  10039. },
  10040. enumerable: true,
  10041. configurable: true
  10042. });
  10043. Object.defineProperty(_StencilState.prototype, "stencilMask", {
  10044. get: function () {
  10045. return this._stencilMask;
  10046. },
  10047. set: function (value) {
  10048. if (this._stencilMask === value) {
  10049. return;
  10050. }
  10051. this._stencilMask = value;
  10052. this._isStencilMaskDirty = true;
  10053. },
  10054. enumerable: true,
  10055. configurable: true
  10056. });
  10057. Object.defineProperty(_StencilState.prototype, "stencilTest", {
  10058. get: function () {
  10059. return this._stencilTest;
  10060. },
  10061. set: function (value) {
  10062. if (this._stencilTest === value) {
  10063. return;
  10064. }
  10065. this._stencilTest = value;
  10066. this._isStencilTestDirty = true;
  10067. },
  10068. enumerable: true,
  10069. configurable: true
  10070. });
  10071. _StencilState.prototype.reset = function () {
  10072. this._stencilTest = false;
  10073. this._stencilMask = 0xFF;
  10074. this._stencilFunc = BABYLON.Engine.ALWAYS;
  10075. this._stencilFuncRef = 1;
  10076. this._stencilFuncMask = 0xFF;
  10077. this._stencilOpStencilFail = BABYLON.Engine.KEEP;
  10078. this._stencilOpDepthFail = BABYLON.Engine.KEEP;
  10079. this._stencilOpStencilDepthPass = BABYLON.Engine.REPLACE;
  10080. this._isStencilTestDirty = true;
  10081. this._isStencilMaskDirty = true;
  10082. this._isStencilFuncDirty = true;
  10083. this._isStencilOpDirty = true;
  10084. };
  10085. _StencilState.prototype.apply = function (gl) {
  10086. if (!this.isDirty) {
  10087. return;
  10088. }
  10089. // Stencil test
  10090. if (this._isStencilTestDirty) {
  10091. if (this.stencilTest) {
  10092. gl.enable(gl.STENCIL_TEST);
  10093. }
  10094. else {
  10095. gl.disable(gl.STENCIL_TEST);
  10096. }
  10097. this._isStencilTestDirty = false;
  10098. }
  10099. // Stencil mask
  10100. if (this._isStencilMaskDirty) {
  10101. gl.stencilMask(this.stencilMask);
  10102. this._isStencilMaskDirty = false;
  10103. }
  10104. // Stencil func
  10105. if (this._isStencilFuncDirty) {
  10106. gl.stencilFunc(this.stencilFunc, this.stencilFuncRef, this.stencilFuncMask);
  10107. this._isStencilFuncDirty = false;
  10108. }
  10109. // Stencil op
  10110. if (this._isStencilOpDirty) {
  10111. gl.stencilOp(this.stencilOpStencilFail, this.stencilOpDepthFail, this.stencilOpStencilDepthPass);
  10112. this._isStencilOpDirty = false;
  10113. }
  10114. };
  10115. return _StencilState;
  10116. }());
  10117. BABYLON._StencilState = _StencilState;
  10118. })(BABYLON || (BABYLON = {}));
  10119. //# sourceMappingURL=babylon.stencilState.js.map
  10120. var __assign = (this && this.__assign) || Object.assign || function(t) {
  10121. for (var s, i = 1, n = arguments.length; i < n; i++) {
  10122. s = arguments[i];
  10123. for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
  10124. t[p] = s[p];
  10125. }
  10126. return t;
  10127. };
  10128. var BABYLON;
  10129. (function (BABYLON) {
  10130. var compileShader = function (gl, source, type, defines, shaderVersion) {
  10131. return compileRawShader(gl, shaderVersion + (defines ? defines + "\n" : "") + source, type);
  10132. };
  10133. var compileRawShader = function (gl, source, type) {
  10134. var shader = gl.createShader(type === "vertex" ? gl.VERTEX_SHADER : gl.FRAGMENT_SHADER);
  10135. gl.shaderSource(shader, source);
  10136. gl.compileShader(shader);
  10137. if (!gl.getShaderParameter(shader, gl.COMPILE_STATUS)) {
  10138. var log = gl.getShaderInfoLog(shader);
  10139. if (log) {
  10140. throw new Error(log);
  10141. }
  10142. }
  10143. if (!shader) {
  10144. throw new Error("Something went wrong while compile the shader.");
  10145. }
  10146. return shader;
  10147. };
  10148. var getSamplingParameters = function (samplingMode, generateMipMaps, gl) {
  10149. var magFilter = gl.NEAREST;
  10150. var minFilter = gl.NEAREST;
  10151. switch (samplingMode) {
  10152. case BABYLON.Texture.BILINEAR_SAMPLINGMODE:
  10153. magFilter = gl.LINEAR;
  10154. if (generateMipMaps) {
  10155. minFilter = gl.LINEAR_MIPMAP_NEAREST;
  10156. }
  10157. else {
  10158. minFilter = gl.LINEAR;
  10159. }
  10160. break;
  10161. case BABYLON.Texture.TRILINEAR_SAMPLINGMODE:
  10162. magFilter = gl.LINEAR;
  10163. if (generateMipMaps) {
  10164. minFilter = gl.LINEAR_MIPMAP_LINEAR;
  10165. }
  10166. else {
  10167. minFilter = gl.LINEAR;
  10168. }
  10169. break;
  10170. case BABYLON.Texture.NEAREST_SAMPLINGMODE:
  10171. magFilter = gl.NEAREST;
  10172. if (generateMipMaps) {
  10173. minFilter = gl.NEAREST_MIPMAP_LINEAR;
  10174. }
  10175. else {
  10176. minFilter = gl.NEAREST;
  10177. }
  10178. break;
  10179. case BABYLON.Texture.NEAREST_NEAREST_MIPNEAREST:
  10180. magFilter = gl.NEAREST;
  10181. if (generateMipMaps) {
  10182. minFilter = gl.NEAREST_MIPMAP_NEAREST;
  10183. }
  10184. else {
  10185. minFilter = gl.NEAREST;
  10186. }
  10187. break;
  10188. case BABYLON.Texture.NEAREST_LINEAR_MIPNEAREST:
  10189. magFilter = gl.NEAREST;
  10190. if (generateMipMaps) {
  10191. minFilter = gl.LINEAR_MIPMAP_NEAREST;
  10192. }
  10193. else {
  10194. minFilter = gl.LINEAR;
  10195. }
  10196. break;
  10197. case BABYLON.Texture.NEAREST_LINEAR_MIPLINEAR:
  10198. magFilter = gl.NEAREST;
  10199. if (generateMipMaps) {
  10200. minFilter = gl.LINEAR_MIPMAP_LINEAR;
  10201. }
  10202. else {
  10203. minFilter = gl.LINEAR;
  10204. }
  10205. break;
  10206. case BABYLON.Texture.NEAREST_LINEAR:
  10207. magFilter = gl.NEAREST;
  10208. minFilter = gl.LINEAR;
  10209. break;
  10210. case BABYLON.Texture.NEAREST_NEAREST:
  10211. magFilter = gl.NEAREST;
  10212. minFilter = gl.NEAREST;
  10213. break;
  10214. case BABYLON.Texture.LINEAR_NEAREST_MIPNEAREST:
  10215. magFilter = gl.LINEAR;
  10216. if (generateMipMaps) {
  10217. minFilter = gl.NEAREST_MIPMAP_NEAREST;
  10218. }
  10219. else {
  10220. minFilter = gl.NEAREST;
  10221. }
  10222. break;
  10223. case BABYLON.Texture.LINEAR_NEAREST_MIPLINEAR:
  10224. magFilter = gl.LINEAR;
  10225. if (generateMipMaps) {
  10226. minFilter = gl.NEAREST_MIPMAP_LINEAR;
  10227. }
  10228. else {
  10229. minFilter = gl.NEAREST;
  10230. }
  10231. break;
  10232. case BABYLON.Texture.LINEAR_LINEAR:
  10233. magFilter = gl.LINEAR;
  10234. minFilter = gl.LINEAR;
  10235. break;
  10236. case BABYLON.Texture.LINEAR_NEAREST:
  10237. magFilter = gl.LINEAR;
  10238. minFilter = gl.NEAREST;
  10239. break;
  10240. }
  10241. return {
  10242. min: minFilter,
  10243. mag: magFilter
  10244. };
  10245. };
  10246. var partialLoadImg = function (url, index, loadedImages, scene, onfinish, onErrorCallBack) {
  10247. if (onErrorCallBack === void 0) { onErrorCallBack = null; }
  10248. var img;
  10249. var onload = function () {
  10250. loadedImages[index] = img;
  10251. loadedImages._internalCount++;
  10252. if (scene) {
  10253. scene._removePendingData(img);
  10254. }
  10255. if (loadedImages._internalCount === 6) {
  10256. onfinish(loadedImages);
  10257. }
  10258. };
  10259. var onerror = function (message, exception) {
  10260. if (scene) {
  10261. scene._removePendingData(img);
  10262. }
  10263. if (onErrorCallBack) {
  10264. onErrorCallBack(message, exception);
  10265. }
  10266. };
  10267. img = BABYLON.Tools.LoadImage(url, onload, onerror, scene ? scene.database : null);
  10268. if (scene) {
  10269. scene._addPendingData(img);
  10270. }
  10271. };
  10272. var cascadeLoadImgs = function (rootUrl, scene, onfinish, files, onError) {
  10273. if (onError === void 0) { onError = null; }
  10274. var loadedImages = [];
  10275. loadedImages._internalCount = 0;
  10276. for (var index = 0; index < 6; index++) {
  10277. partialLoadImg(files[index], index, loadedImages, scene, onfinish, onError);
  10278. }
  10279. };
  10280. var BufferPointer = /** @class */ (function () {
  10281. function BufferPointer() {
  10282. }
  10283. return BufferPointer;
  10284. }());
  10285. var InstancingAttributeInfo = /** @class */ (function () {
  10286. function InstancingAttributeInfo() {
  10287. }
  10288. return InstancingAttributeInfo;
  10289. }());
  10290. BABYLON.InstancingAttributeInfo = InstancingAttributeInfo;
  10291. /**
  10292. * Define options used to create a render target texture
  10293. */
  10294. var RenderTargetCreationOptions = /** @class */ (function () {
  10295. function RenderTargetCreationOptions() {
  10296. }
  10297. return RenderTargetCreationOptions;
  10298. }());
  10299. BABYLON.RenderTargetCreationOptions = RenderTargetCreationOptions;
  10300. /**
  10301. * Define options used to create a depth texture
  10302. */
  10303. var DepthTextureCreationOptions = /** @class */ (function () {
  10304. function DepthTextureCreationOptions() {
  10305. }
  10306. return DepthTextureCreationOptions;
  10307. }());
  10308. BABYLON.DepthTextureCreationOptions = DepthTextureCreationOptions;
  10309. /**
  10310. * Regroup several parameters relative to the browser in use
  10311. */
  10312. var EngineCapabilities = /** @class */ (function () {
  10313. function EngineCapabilities() {
  10314. }
  10315. return EngineCapabilities;
  10316. }());
  10317. BABYLON.EngineCapabilities = EngineCapabilities;
  10318. /**
  10319. * The engine class is responsible for interfacing with all lower-level APIs such as WebGL and Audio.
  10320. */
  10321. var Engine = /** @class */ (function () {
  10322. /**
  10323. * @constructor
  10324. * @param canvasOrContext defines the canvas or WebGL context to use for rendering
  10325. * @param antialias defines enable antialiasing (default: false)
  10326. * @param options defines further options to be sent to the getContext() function
  10327. * @param adaptToDeviceRatio defines whether to adapt to the device's viewport characteristics (default: false)
  10328. */
  10329. function Engine(canvasOrContext, antialias, options, adaptToDeviceRatio) {
  10330. if (adaptToDeviceRatio === void 0) { adaptToDeviceRatio = false; }
  10331. var _this = this;
  10332. // Public members
  10333. this.forcePOTTextures = false;
  10334. this.isFullscreen = false;
  10335. this.isPointerLock = false;
  10336. this.cullBackFaces = true;
  10337. this.renderEvenInBackground = true;
  10338. this.preventCacheWipeBetweenFrames = false;
  10339. // To enable/disable IDB support and avoid XHR on .manifest
  10340. this.enableOfflineSupport = false;
  10341. this.scenes = new Array();
  10342. this.postProcesses = new Array();
  10343. // Observables
  10344. /**
  10345. * Observable event triggered each time the rendering canvas is resized
  10346. */
  10347. this.onResizeObservable = new BABYLON.Observable();
  10348. /**
  10349. * Observable event triggered each time the canvas loses focus
  10350. */
  10351. this.onCanvasBlurObservable = new BABYLON.Observable();
  10352. /**
  10353. * Observable event triggered each time the canvas gains focus
  10354. */
  10355. this.onCanvasFocusObservable = new BABYLON.Observable();
  10356. /**
  10357. * Observable event triggered each time the canvas receives pointerout event
  10358. */
  10359. this.onCanvasPointerOutObservable = new BABYLON.Observable();
  10360. /**
  10361. * Observable event triggered before each texture is initialized
  10362. */
  10363. this.onBeforeTextureInitObservable = new BABYLON.Observable();
  10364. //WebVR
  10365. this._vrDisplay = undefined;
  10366. this._vrSupported = false;
  10367. this._vrExclusivePointerMode = false;
  10368. // Uniform buffers list
  10369. this.disableUniformBuffers = false;
  10370. this._uniformBuffers = new Array();
  10371. // Observables
  10372. /**
  10373. * Observable raised when the engine begins a new frame
  10374. */
  10375. this.onBeginFrameObservable = new BABYLON.Observable();
  10376. /**
  10377. * Observable raised when the engine ends the current frame
  10378. */
  10379. this.onEndFrameObservable = new BABYLON.Observable();
  10380. /**
  10381. * Observable raised when the engine is about to compile a shader
  10382. */
  10383. this.onBeforeShaderCompilationObservable = new BABYLON.Observable();
  10384. /**
  10385. * Observable raised when the engine has jsut compiled a shader
  10386. */
  10387. this.onAfterShaderCompilationObservable = new BABYLON.Observable();
  10388. this._windowIsBackground = false;
  10389. this._webGLVersion = 1.0;
  10390. this._badOS = false;
  10391. this._badDesktopOS = false;
  10392. /**
  10393. * Gets or sets a value indicating if we want to disable texture binding optmization.
  10394. * This could be required on some buggy drivers which wants to have textures bound in a progressive order
  10395. * By default Babylon.js will try to let textures bound where they are and only update the samplers to point where the texture is.
  10396. */
  10397. this.disableTextureBindingOptimization = false;
  10398. this.onVRDisplayChangedObservable = new BABYLON.Observable();
  10399. this.onVRRequestPresentComplete = new BABYLON.Observable();
  10400. this.onVRRequestPresentStart = new BABYLON.Observable();
  10401. this._colorWrite = true;
  10402. this._drawCalls = new BABYLON.PerfCounter();
  10403. this._textureCollisions = new BABYLON.PerfCounter();
  10404. this._renderingQueueLaunched = false;
  10405. this._activeRenderLoops = new Array();
  10406. // Deterministic lockstepMaxSteps
  10407. this._deterministicLockstep = false;
  10408. this._lockstepMaxSteps = 4;
  10409. // Lost context
  10410. this.onContextLostObservable = new BABYLON.Observable();
  10411. this.onContextRestoredObservable = new BABYLON.Observable();
  10412. this._contextWasLost = false;
  10413. this._doNotHandleContextLost = false;
  10414. // FPS
  10415. this._performanceMonitor = new BABYLON.PerformanceMonitor();
  10416. this._fps = 60;
  10417. this._deltaTime = 0;
  10418. /**
  10419. * Turn this value on if you want to pause FPS computation when in background
  10420. */
  10421. this.disablePerformanceMonitorInBackground = false;
  10422. // States
  10423. this._depthCullingState = new BABYLON._DepthCullingState();
  10424. this._stencilState = new BABYLON._StencilState();
  10425. this._alphaState = new BABYLON._AlphaState();
  10426. this._alphaMode = Engine.ALPHA_DISABLE;
  10427. // Cache
  10428. this._internalTexturesCache = new Array();
  10429. this._activeChannel = 0;
  10430. this._currentTextureChannel = -1;
  10431. this._boundTexturesCache = {};
  10432. this._compiledEffects = {};
  10433. this._vertexAttribArraysEnabled = [];
  10434. this._uintIndicesCurrentlySet = false;
  10435. this._currentBoundBuffer = new Array();
  10436. this._currentBufferPointers = new Array();
  10437. this._currentInstanceLocations = new Array();
  10438. this._currentInstanceBuffers = new Array();
  10439. this._firstBoundInternalTextureTracker = new BABYLON.DummyInternalTextureTracker();
  10440. this._lastBoundInternalTextureTracker = new BABYLON.DummyInternalTextureTracker();
  10441. this._vaoRecordInProgress = false;
  10442. this._mustWipeVertexAttributes = false;
  10443. this._nextFreeTextureSlots = new Array();
  10444. this._maxSimultaneousTextures = 0;
  10445. this._activeRequests = new Array();
  10446. // Hardware supported Compressed Textures
  10447. this._texturesSupported = new Array();
  10448. this._onVRFullScreenTriggered = function () {
  10449. if (_this._vrDisplay && _this._vrDisplay.isPresenting) {
  10450. //get the old size before we change
  10451. _this._oldSize = new BABYLON.Size(_this.getRenderWidth(), _this.getRenderHeight());
  10452. _this._oldHardwareScaleFactor = _this.getHardwareScalingLevel();
  10453. //get the width and height, change the render size
  10454. var leftEye = _this._vrDisplay.getEyeParameters('left');
  10455. _this.setHardwareScalingLevel(1);
  10456. _this.setSize(leftEye.renderWidth * 2, leftEye.renderHeight);
  10457. }
  10458. else {
  10459. _this.setHardwareScalingLevel(_this._oldHardwareScaleFactor);
  10460. _this.setSize(_this._oldSize.width, _this._oldSize.height);
  10461. }
  10462. };
  10463. this._boundUniforms = {};
  10464. // Register promises
  10465. BABYLON.PromisePolyfill.Apply();
  10466. var canvas = null;
  10467. Engine.Instances.push(this);
  10468. if (!canvasOrContext) {
  10469. return;
  10470. }
  10471. options = options || {};
  10472. if (canvasOrContext.getContext) {
  10473. canvas = canvasOrContext;
  10474. this._renderingCanvas = canvas;
  10475. if (antialias != null) {
  10476. options.antialias = antialias;
  10477. }
  10478. if (options.deterministicLockstep === undefined) {
  10479. options.deterministicLockstep = false;
  10480. }
  10481. if (options.lockstepMaxSteps === undefined) {
  10482. options.lockstepMaxSteps = 4;
  10483. }
  10484. if (options.preserveDrawingBuffer === undefined) {
  10485. options.preserveDrawingBuffer = false;
  10486. }
  10487. if (options.audioEngine === undefined) {
  10488. options.audioEngine = true;
  10489. }
  10490. if (options.stencil === undefined) {
  10491. options.stencil = true;
  10492. }
  10493. this._deterministicLockstep = options.deterministicLockstep;
  10494. this._lockstepMaxSteps = options.lockstepMaxSteps;
  10495. this._doNotHandleContextLost = options.doNotHandleContextLost ? true : false;
  10496. // Exceptions
  10497. if (navigator && navigator.userAgent) {
  10498. var ua = navigator.userAgent;
  10499. for (var _i = 0, _a = Engine.ExceptionList; _i < _a.length; _i++) {
  10500. var exception = _a[_i];
  10501. var key = exception.key;
  10502. var targets = exception.targets;
  10503. if (ua.indexOf(key) > -1) {
  10504. if (exception.capture && exception.captureConstraint) {
  10505. var capture = exception.capture;
  10506. var constraint = exception.captureConstraint;
  10507. var regex = new RegExp(capture);
  10508. var matches = regex.exec(ua);
  10509. if (matches && matches.length > 0) {
  10510. var capturedValue = parseInt(matches[matches.length - 1]);
  10511. if (capturedValue >= constraint) {
  10512. continue;
  10513. }
  10514. }
  10515. }
  10516. for (var _b = 0, targets_1 = targets; _b < targets_1.length; _b++) {
  10517. var target = targets_1[_b];
  10518. switch (target) {
  10519. case "uniformBuffer":
  10520. this.disableUniformBuffers = true;
  10521. break;
  10522. case "textureBindingOptimization":
  10523. this.disableTextureBindingOptimization = true;
  10524. break;
  10525. }
  10526. }
  10527. break;
  10528. }
  10529. }
  10530. }
  10531. // GL
  10532. if (!options.disableWebGL2Support) {
  10533. try {
  10534. this._gl = (canvas.getContext("webgl2", options) || canvas.getContext("experimental-webgl2", options));
  10535. if (this._gl) {
  10536. this._webGLVersion = 2.0;
  10537. }
  10538. }
  10539. catch (e) {
  10540. // Do nothing
  10541. }
  10542. }
  10543. if (!this._gl) {
  10544. if (!canvas) {
  10545. throw new Error("The provided canvas is null or undefined.");
  10546. }
  10547. try {
  10548. this._gl = (canvas.getContext("webgl", options) || canvas.getContext("experimental-webgl", options));
  10549. }
  10550. catch (e) {
  10551. throw new Error("WebGL not supported");
  10552. }
  10553. }
  10554. if (!this._gl) {
  10555. throw new Error("WebGL not supported");
  10556. }
  10557. this._onCanvasFocus = function () {
  10558. _this.onCanvasFocusObservable.notifyObservers(_this);
  10559. };
  10560. this._onCanvasBlur = function () {
  10561. _this.onCanvasBlurObservable.notifyObservers(_this);
  10562. };
  10563. canvas.addEventListener("focus", this._onCanvasFocus);
  10564. canvas.addEventListener("blur", this._onCanvasBlur);
  10565. this._onBlur = function () {
  10566. if (_this.disablePerformanceMonitorInBackground) {
  10567. _this._performanceMonitor.disable();
  10568. }
  10569. _this._windowIsBackground = true;
  10570. };
  10571. this._onFocus = function () {
  10572. if (_this.disablePerformanceMonitorInBackground) {
  10573. _this._performanceMonitor.enable();
  10574. }
  10575. _this._windowIsBackground = false;
  10576. };
  10577. this._onCanvasPointerOut = function (ev) {
  10578. _this.onCanvasPointerOutObservable.notifyObservers(ev);
  10579. };
  10580. window.addEventListener("blur", this._onBlur);
  10581. window.addEventListener("focus", this._onFocus);
  10582. canvas.addEventListener("pointerout", this._onCanvasPointerOut);
  10583. // Context lost
  10584. if (!this._doNotHandleContextLost) {
  10585. this._onContextLost = function (evt) {
  10586. evt.preventDefault();
  10587. _this._contextWasLost = true;
  10588. BABYLON.Tools.Warn("WebGL context lost.");
  10589. _this.onContextLostObservable.notifyObservers(_this);
  10590. };
  10591. this._onContextRestored = function (evt) {
  10592. // Adding a timeout to avoid race condition at browser level
  10593. setTimeout(function () {
  10594. // Rebuild gl context
  10595. _this._initGLContext();
  10596. // Rebuild effects
  10597. _this._rebuildEffects();
  10598. // Rebuild textures
  10599. _this._rebuildInternalTextures();
  10600. // Rebuild buffers
  10601. _this._rebuildBuffers();
  10602. // Cache
  10603. _this.wipeCaches(true);
  10604. BABYLON.Tools.Warn("WebGL context successfully restored.");
  10605. _this.onContextRestoredObservable.notifyObservers(_this);
  10606. _this._contextWasLost = false;
  10607. }, 0);
  10608. };
  10609. canvas.addEventListener("webglcontextlost", this._onContextLost, false);
  10610. canvas.addEventListener("webglcontextrestored", this._onContextRestored, false);
  10611. }
  10612. }
  10613. else {
  10614. this._gl = canvasOrContext;
  10615. this._renderingCanvas = this._gl.canvas;
  10616. if (this._gl.renderbufferStorageMultisample) {
  10617. this._webGLVersion = 2.0;
  10618. }
  10619. options.stencil = this._gl.getContextAttributes().stencil;
  10620. }
  10621. // Viewport
  10622. var limitDeviceRatio = options.limitDeviceRatio || window.devicePixelRatio || 1.0;
  10623. this._hardwareScalingLevel = adaptToDeviceRatio ? 1.0 / Math.min(limitDeviceRatio, window.devicePixelRatio || 1.0) : 1.0;
  10624. this.resize();
  10625. this._isStencilEnable = options.stencil ? true : false;
  10626. this._initGLContext();
  10627. if (canvas) {
  10628. // Fullscreen
  10629. this._onFullscreenChange = function () {
  10630. if (document.fullscreen !== undefined) {
  10631. _this.isFullscreen = document.fullscreen;
  10632. }
  10633. else if (document.mozFullScreen !== undefined) {
  10634. _this.isFullscreen = document.mozFullScreen;
  10635. }
  10636. else if (document.webkitIsFullScreen !== undefined) {
  10637. _this.isFullscreen = document.webkitIsFullScreen;
  10638. }
  10639. else if (document.msIsFullScreen !== undefined) {
  10640. _this.isFullscreen = document.msIsFullScreen;
  10641. }
  10642. // Pointer lock
  10643. if (_this.isFullscreen && _this._pointerLockRequested && canvas) {
  10644. canvas.requestPointerLock = canvas.requestPointerLock ||
  10645. canvas.msRequestPointerLock ||
  10646. canvas.mozRequestPointerLock ||
  10647. canvas.webkitRequestPointerLock;
  10648. if (canvas.requestPointerLock) {
  10649. canvas.requestPointerLock();
  10650. }
  10651. }
  10652. };
  10653. document.addEventListener("fullscreenchange", this._onFullscreenChange, false);
  10654. document.addEventListener("mozfullscreenchange", this._onFullscreenChange, false);
  10655. document.addEventListener("webkitfullscreenchange", this._onFullscreenChange, false);
  10656. document.addEventListener("msfullscreenchange", this._onFullscreenChange, false);
  10657. // Pointer lock
  10658. this._onPointerLockChange = function () {
  10659. _this.isPointerLock = (document.mozPointerLockElement === canvas ||
  10660. document.webkitPointerLockElement === canvas ||
  10661. document.msPointerLockElement === canvas ||
  10662. document.pointerLockElement === canvas);
  10663. };
  10664. document.addEventListener("pointerlockchange", this._onPointerLockChange, false);
  10665. document.addEventListener("mspointerlockchange", this._onPointerLockChange, false);
  10666. document.addEventListener("mozpointerlockchange", this._onPointerLockChange, false);
  10667. document.addEventListener("webkitpointerlockchange", this._onPointerLockChange, false);
  10668. this._onVRDisplayPointerRestricted = function () {
  10669. if (canvas) {
  10670. canvas.requestPointerLock();
  10671. }
  10672. };
  10673. this._onVRDisplayPointerUnrestricted = function () {
  10674. document.exitPointerLock();
  10675. };
  10676. window.addEventListener('vrdisplaypointerrestricted', this._onVRDisplayPointerRestricted, false);
  10677. window.addEventListener('vrdisplaypointerunrestricted', this._onVRDisplayPointerUnrestricted, false);
  10678. }
  10679. if (options.audioEngine && BABYLON.AudioEngine && !Engine.audioEngine) {
  10680. Engine.audioEngine = new BABYLON.AudioEngine();
  10681. }
  10682. // Prepare buffer pointers
  10683. for (var i = 0; i < this._caps.maxVertexAttribs; i++) {
  10684. this._currentBufferPointers[i] = new BufferPointer();
  10685. }
  10686. this._linkTrackers(this._firstBoundInternalTextureTracker, this._lastBoundInternalTextureTracker);
  10687. // Load WebVR Devices
  10688. if (options.autoEnableWebVR) {
  10689. this.initWebVR();
  10690. }
  10691. // Detect if we are running on a faulty buggy OS.
  10692. this._badOS = /iPad/i.test(navigator.userAgent) || /iPhone/i.test(navigator.userAgent);
  10693. // Detect if we are running on a faulty buggy desktop OS.
  10694. this._badDesktopOS = /^((?!chrome|android).)*safari/i.test(navigator.userAgent);
  10695. BABYLON.Tools.Log("Babylon.js engine (v" + Engine.Version + ") launched");
  10696. this.enableOfflineSupport = (BABYLON.Database !== undefined);
  10697. }
  10698. Object.defineProperty(Engine, "LastCreatedEngine", {
  10699. get: function () {
  10700. if (Engine.Instances.length === 0) {
  10701. return null;
  10702. }
  10703. return Engine.Instances[Engine.Instances.length - 1];
  10704. },
  10705. enumerable: true,
  10706. configurable: true
  10707. });
  10708. Object.defineProperty(Engine, "LastCreatedScene", {
  10709. get: function () {
  10710. var lastCreatedEngine = Engine.LastCreatedEngine;
  10711. if (!lastCreatedEngine) {
  10712. return null;
  10713. }
  10714. if (lastCreatedEngine.scenes.length === 0) {
  10715. return null;
  10716. }
  10717. return lastCreatedEngine.scenes[lastCreatedEngine.scenes.length - 1];
  10718. },
  10719. enumerable: true,
  10720. configurable: true
  10721. });
  10722. /**
  10723. * Will flag all materials in all scenes in all engines as dirty to trigger new shader compilation
  10724. */
  10725. Engine.MarkAllMaterialsAsDirty = function (flag, predicate) {
  10726. for (var engineIndex = 0; engineIndex < Engine.Instances.length; engineIndex++) {
  10727. var engine = Engine.Instances[engineIndex];
  10728. for (var sceneIndex = 0; sceneIndex < engine.scenes.length; sceneIndex++) {
  10729. engine.scenes[sceneIndex].markAllMaterialsAsDirty(flag, predicate);
  10730. }
  10731. }
  10732. };
  10733. Object.defineProperty(Engine, "NEVER", {
  10734. get: function () {
  10735. return Engine._NEVER;
  10736. },
  10737. enumerable: true,
  10738. configurable: true
  10739. });
  10740. Object.defineProperty(Engine, "ALWAYS", {
  10741. get: function () {
  10742. return Engine._ALWAYS;
  10743. },
  10744. enumerable: true,
  10745. configurable: true
  10746. });
  10747. Object.defineProperty(Engine, "LESS", {
  10748. get: function () {
  10749. return Engine._LESS;
  10750. },
  10751. enumerable: true,
  10752. configurable: true
  10753. });
  10754. Object.defineProperty(Engine, "EQUAL", {
  10755. get: function () {
  10756. return Engine._EQUAL;
  10757. },
  10758. enumerable: true,
  10759. configurable: true
  10760. });
  10761. Object.defineProperty(Engine, "LEQUAL", {
  10762. get: function () {
  10763. return Engine._LEQUAL;
  10764. },
  10765. enumerable: true,
  10766. configurable: true
  10767. });
  10768. Object.defineProperty(Engine, "GREATER", {
  10769. get: function () {
  10770. return Engine._GREATER;
  10771. },
  10772. enumerable: true,
  10773. configurable: true
  10774. });
  10775. Object.defineProperty(Engine, "GEQUAL", {
  10776. get: function () {
  10777. return Engine._GEQUAL;
  10778. },
  10779. enumerable: true,
  10780. configurable: true
  10781. });
  10782. Object.defineProperty(Engine, "NOTEQUAL", {
  10783. get: function () {
  10784. return Engine._NOTEQUAL;
  10785. },
  10786. enumerable: true,
  10787. configurable: true
  10788. });
  10789. Object.defineProperty(Engine, "KEEP", {
  10790. get: function () {
  10791. return Engine._KEEP;
  10792. },
  10793. enumerable: true,
  10794. configurable: true
  10795. });
  10796. Object.defineProperty(Engine, "REPLACE", {
  10797. get: function () {
  10798. return Engine._REPLACE;
  10799. },
  10800. enumerable: true,
  10801. configurable: true
  10802. });
  10803. Object.defineProperty(Engine, "INCR", {
  10804. get: function () {
  10805. return Engine._INCR;
  10806. },
  10807. enumerable: true,
  10808. configurable: true
  10809. });
  10810. Object.defineProperty(Engine, "DECR", {
  10811. get: function () {
  10812. return Engine._DECR;
  10813. },
  10814. enumerable: true,
  10815. configurable: true
  10816. });
  10817. Object.defineProperty(Engine, "INVERT", {
  10818. get: function () {
  10819. return Engine._INVERT;
  10820. },
  10821. enumerable: true,
  10822. configurable: true
  10823. });
  10824. Object.defineProperty(Engine, "INCR_WRAP", {
  10825. get: function () {
  10826. return Engine._INCR_WRAP;
  10827. },
  10828. enumerable: true,
  10829. configurable: true
  10830. });
  10831. Object.defineProperty(Engine, "DECR_WRAP", {
  10832. get: function () {
  10833. return Engine._DECR_WRAP;
  10834. },
  10835. enumerable: true,
  10836. configurable: true
  10837. });
  10838. Object.defineProperty(Engine, "ALPHA_DISABLE", {
  10839. get: function () {
  10840. return Engine._ALPHA_DISABLE;
  10841. },
  10842. enumerable: true,
  10843. configurable: true
  10844. });
  10845. Object.defineProperty(Engine, "ALPHA_ONEONE", {
  10846. get: function () {
  10847. return Engine._ALPHA_ONEONE;
  10848. },
  10849. enumerable: true,
  10850. configurable: true
  10851. });
  10852. Object.defineProperty(Engine, "ALPHA_ADD", {
  10853. get: function () {
  10854. return Engine._ALPHA_ADD;
  10855. },
  10856. enumerable: true,
  10857. configurable: true
  10858. });
  10859. Object.defineProperty(Engine, "ALPHA_COMBINE", {
  10860. get: function () {
  10861. return Engine._ALPHA_COMBINE;
  10862. },
  10863. enumerable: true,
  10864. configurable: true
  10865. });
  10866. Object.defineProperty(Engine, "ALPHA_SUBTRACT", {
  10867. get: function () {
  10868. return Engine._ALPHA_SUBTRACT;
  10869. },
  10870. enumerable: true,
  10871. configurable: true
  10872. });
  10873. Object.defineProperty(Engine, "ALPHA_MULTIPLY", {
  10874. get: function () {
  10875. return Engine._ALPHA_MULTIPLY;
  10876. },
  10877. enumerable: true,
  10878. configurable: true
  10879. });
  10880. Object.defineProperty(Engine, "ALPHA_MAXIMIZED", {
  10881. get: function () {
  10882. return Engine._ALPHA_MAXIMIZED;
  10883. },
  10884. enumerable: true,
  10885. configurable: true
  10886. });
  10887. Object.defineProperty(Engine, "ALPHA_PREMULTIPLIED", {
  10888. get: function () {
  10889. return Engine._ALPHA_PREMULTIPLIED;
  10890. },
  10891. enumerable: true,
  10892. configurable: true
  10893. });
  10894. Object.defineProperty(Engine, "ALPHA_PREMULTIPLIED_PORTERDUFF", {
  10895. get: function () {
  10896. return Engine._ALPHA_PREMULTIPLIED_PORTERDUFF;
  10897. },
  10898. enumerable: true,
  10899. configurable: true
  10900. });
  10901. Object.defineProperty(Engine, "ALPHA_INTERPOLATE", {
  10902. get: function () {
  10903. return Engine._ALPHA_INTERPOLATE;
  10904. },
  10905. enumerable: true,
  10906. configurable: true
  10907. });
  10908. Object.defineProperty(Engine, "ALPHA_SCREENMODE", {
  10909. get: function () {
  10910. return Engine._ALPHA_SCREENMODE;
  10911. },
  10912. enumerable: true,
  10913. configurable: true
  10914. });
  10915. Object.defineProperty(Engine, "DELAYLOADSTATE_NONE", {
  10916. get: function () {
  10917. return Engine._DELAYLOADSTATE_NONE;
  10918. },
  10919. enumerable: true,
  10920. configurable: true
  10921. });
  10922. Object.defineProperty(Engine, "DELAYLOADSTATE_LOADED", {
  10923. get: function () {
  10924. return Engine._DELAYLOADSTATE_LOADED;
  10925. },
  10926. enumerable: true,
  10927. configurable: true
  10928. });
  10929. Object.defineProperty(Engine, "DELAYLOADSTATE_LOADING", {
  10930. get: function () {
  10931. return Engine._DELAYLOADSTATE_LOADING;
  10932. },
  10933. enumerable: true,
  10934. configurable: true
  10935. });
  10936. Object.defineProperty(Engine, "DELAYLOADSTATE_NOTLOADED", {
  10937. get: function () {
  10938. return Engine._DELAYLOADSTATE_NOTLOADED;
  10939. },
  10940. enumerable: true,
  10941. configurable: true
  10942. });
  10943. Object.defineProperty(Engine, "TEXTUREFORMAT_ALPHA", {
  10944. get: function () {
  10945. return Engine._TEXTUREFORMAT_ALPHA;
  10946. },
  10947. enumerable: true,
  10948. configurable: true
  10949. });
  10950. Object.defineProperty(Engine, "TEXTUREFORMAT_LUMINANCE", {
  10951. get: function () {
  10952. return Engine._TEXTUREFORMAT_LUMINANCE;
  10953. },
  10954. enumerable: true,
  10955. configurable: true
  10956. });
  10957. Object.defineProperty(Engine, "TEXTUREFORMAT_R32F", {
  10958. /**
  10959. * R32F
  10960. */
  10961. get: function () {
  10962. return Engine._TEXTUREFORMAT_R32F;
  10963. },
  10964. enumerable: true,
  10965. configurable: true
  10966. });
  10967. Object.defineProperty(Engine, "TEXTUREFORMAT_RG32F", {
  10968. /**
  10969. * RG32F
  10970. */
  10971. get: function () {
  10972. return Engine._TEXTUREFORMAT_RG32F;
  10973. },
  10974. enumerable: true,
  10975. configurable: true
  10976. });
  10977. Object.defineProperty(Engine, "TEXTUREFORMAT_RGB32F", {
  10978. /**
  10979. * RGB32F
  10980. */
  10981. get: function () {
  10982. return Engine._TEXTUREFORMAT_RGB32F;
  10983. },
  10984. enumerable: true,
  10985. configurable: true
  10986. });
  10987. Object.defineProperty(Engine, "TEXTUREFORMAT_RGBA32F", {
  10988. /**
  10989. * RGBA32F
  10990. */
  10991. get: function () {
  10992. return Engine._TEXTUREFORMAT_RGBA32F;
  10993. },
  10994. enumerable: true,
  10995. configurable: true
  10996. });
  10997. Object.defineProperty(Engine, "TEXTUREFORMAT_LUMINANCE_ALPHA", {
  10998. get: function () {
  10999. return Engine._TEXTUREFORMAT_LUMINANCE_ALPHA;
  11000. },
  11001. enumerable: true,
  11002. configurable: true
  11003. });
  11004. Object.defineProperty(Engine, "TEXTUREFORMAT_RGB", {
  11005. get: function () {
  11006. return Engine._TEXTUREFORMAT_RGB;
  11007. },
  11008. enumerable: true,
  11009. configurable: true
  11010. });
  11011. Object.defineProperty(Engine, "TEXTUREFORMAT_RGBA", {
  11012. get: function () {
  11013. return Engine._TEXTUREFORMAT_RGBA;
  11014. },
  11015. enumerable: true,
  11016. configurable: true
  11017. });
  11018. Object.defineProperty(Engine, "TEXTURETYPE_UNSIGNED_INT", {
  11019. get: function () {
  11020. return Engine._TEXTURETYPE_UNSIGNED_INT;
  11021. },
  11022. enumerable: true,
  11023. configurable: true
  11024. });
  11025. Object.defineProperty(Engine, "TEXTURETYPE_FLOAT", {
  11026. get: function () {
  11027. return Engine._TEXTURETYPE_FLOAT;
  11028. },
  11029. enumerable: true,
  11030. configurable: true
  11031. });
  11032. Object.defineProperty(Engine, "TEXTURETYPE_HALF_FLOAT", {
  11033. get: function () {
  11034. return Engine._TEXTURETYPE_HALF_FLOAT;
  11035. },
  11036. enumerable: true,
  11037. configurable: true
  11038. });
  11039. Object.defineProperty(Engine, "SCALEMODE_FLOOR", {
  11040. get: function () {
  11041. return Engine._SCALEMODE_FLOOR;
  11042. },
  11043. enumerable: true,
  11044. configurable: true
  11045. });
  11046. Object.defineProperty(Engine, "SCALEMODE_NEAREST", {
  11047. get: function () {
  11048. return Engine._SCALEMODE_NEAREST;
  11049. },
  11050. enumerable: true,
  11051. configurable: true
  11052. });
  11053. Object.defineProperty(Engine, "SCALEMODE_CEILING", {
  11054. get: function () {
  11055. return Engine._SCALEMODE_CEILING;
  11056. },
  11057. enumerable: true,
  11058. configurable: true
  11059. });
  11060. Object.defineProperty(Engine, "Version", {
  11061. get: function () {
  11062. return "3.2.0-alphaB";
  11063. },
  11064. enumerable: true,
  11065. configurable: true
  11066. });
  11067. Object.defineProperty(Engine.prototype, "isInVRExclusivePointerMode", {
  11068. get: function () {
  11069. return this._vrExclusivePointerMode;
  11070. },
  11071. enumerable: true,
  11072. configurable: true
  11073. });
  11074. Object.defineProperty(Engine.prototype, "supportsUniformBuffers", {
  11075. get: function () {
  11076. return this.webGLVersion > 1 && !this.disableUniformBuffers;
  11077. },
  11078. enumerable: true,
  11079. configurable: true
  11080. });
  11081. Object.defineProperty(Engine.prototype, "needPOTTextures", {
  11082. get: function () {
  11083. return this._webGLVersion < 2 || this.forcePOTTextures;
  11084. },
  11085. enumerable: true,
  11086. configurable: true
  11087. });
  11088. Object.defineProperty(Engine.prototype, "badOS", {
  11089. get: function () {
  11090. return this._badOS;
  11091. },
  11092. enumerable: true,
  11093. configurable: true
  11094. });
  11095. Object.defineProperty(Engine.prototype, "badDesktopOS", {
  11096. get: function () {
  11097. return this._badDesktopOS;
  11098. },
  11099. enumerable: true,
  11100. configurable: true
  11101. });
  11102. Object.defineProperty(Engine.prototype, "performanceMonitor", {
  11103. get: function () {
  11104. return this._performanceMonitor;
  11105. },
  11106. enumerable: true,
  11107. configurable: true
  11108. });
  11109. Object.defineProperty(Engine.prototype, "texturesSupported", {
  11110. get: function () {
  11111. return this._texturesSupported;
  11112. },
  11113. enumerable: true,
  11114. configurable: true
  11115. });
  11116. Object.defineProperty(Engine.prototype, "textureFormatInUse", {
  11117. get: function () {
  11118. return this._textureFormatInUse;
  11119. },
  11120. enumerable: true,
  11121. configurable: true
  11122. });
  11123. Object.defineProperty(Engine.prototype, "currentViewport", {
  11124. get: function () {
  11125. return this._cachedViewport;
  11126. },
  11127. enumerable: true,
  11128. configurable: true
  11129. });
  11130. Object.defineProperty(Engine.prototype, "emptyTexture", {
  11131. // Empty texture
  11132. get: function () {
  11133. if (!this._emptyTexture) {
  11134. this._emptyTexture = this.createRawTexture(new Uint8Array(4), 1, 1, Engine.TEXTUREFORMAT_RGBA, false, false, BABYLON.Texture.NEAREST_SAMPLINGMODE);
  11135. }
  11136. return this._emptyTexture;
  11137. },
  11138. enumerable: true,
  11139. configurable: true
  11140. });
  11141. Object.defineProperty(Engine.prototype, "emptyTexture3D", {
  11142. get: function () {
  11143. if (!this._emptyTexture3D) {
  11144. this._emptyTexture3D = this.createRawTexture3D(new Uint8Array(4), 1, 1, 1, Engine.TEXTUREFORMAT_RGBA, false, false, BABYLON.Texture.NEAREST_SAMPLINGMODE);
  11145. }
  11146. return this._emptyTexture3D;
  11147. },
  11148. enumerable: true,
  11149. configurable: true
  11150. });
  11151. Object.defineProperty(Engine.prototype, "emptyCubeTexture", {
  11152. get: function () {
  11153. if (!this._emptyCubeTexture) {
  11154. var faceData = new Uint8Array(4);
  11155. var cubeData = [faceData, faceData, faceData, faceData, faceData, faceData];
  11156. this._emptyCubeTexture = this.createRawCubeTexture(cubeData, 1, Engine.TEXTUREFORMAT_RGBA, Engine.TEXTURETYPE_UNSIGNED_INT, false, false, BABYLON.Texture.NEAREST_SAMPLINGMODE);
  11157. }
  11158. return this._emptyCubeTexture;
  11159. },
  11160. enumerable: true,
  11161. configurable: true
  11162. });
  11163. Engine.prototype._rebuildInternalTextures = function () {
  11164. var currentState = this._internalTexturesCache.slice(); // Do a copy because the rebuild will add proxies
  11165. for (var _i = 0, currentState_1 = currentState; _i < currentState_1.length; _i++) {
  11166. var internalTexture = currentState_1[_i];
  11167. internalTexture._rebuild();
  11168. }
  11169. };
  11170. Engine.prototype._rebuildEffects = function () {
  11171. for (var key in this._compiledEffects) {
  11172. var effect = this._compiledEffects[key];
  11173. effect._prepareEffect();
  11174. }
  11175. BABYLON.Effect.ResetCache();
  11176. };
  11177. Engine.prototype._rebuildBuffers = function () {
  11178. // Index / Vertex
  11179. for (var _i = 0, _a = this.scenes; _i < _a.length; _i++) {
  11180. var scene = _a[_i];
  11181. scene.resetCachedMaterial();
  11182. scene._rebuildGeometries();
  11183. scene._rebuildTextures();
  11184. }
  11185. // Uniforms
  11186. for (var _b = 0, _c = this._uniformBuffers; _b < _c.length; _b++) {
  11187. var uniformBuffer = _c[_b];
  11188. uniformBuffer._rebuild();
  11189. }
  11190. };
  11191. Engine.prototype._initGLContext = function () {
  11192. // Caps
  11193. this._caps = new EngineCapabilities();
  11194. this._caps.maxTexturesImageUnits = this._gl.getParameter(this._gl.MAX_TEXTURE_IMAGE_UNITS);
  11195. this._caps.maxCombinedTexturesImageUnits = this._gl.getParameter(this._gl.MAX_COMBINED_TEXTURE_IMAGE_UNITS);
  11196. this._caps.maxVertexTextureImageUnits = this._gl.getParameter(this._gl.MAX_VERTEX_TEXTURE_IMAGE_UNITS);
  11197. this._caps.maxTextureSize = this._gl.getParameter(this._gl.MAX_TEXTURE_SIZE);
  11198. this._caps.maxCubemapTextureSize = this._gl.getParameter(this._gl.MAX_CUBE_MAP_TEXTURE_SIZE);
  11199. this._caps.maxRenderTextureSize = this._gl.getParameter(this._gl.MAX_RENDERBUFFER_SIZE);
  11200. this._caps.maxVertexAttribs = this._gl.getParameter(this._gl.MAX_VERTEX_ATTRIBS);
  11201. this._caps.maxVaryingVectors = this._gl.getParameter(this._gl.MAX_VARYING_VECTORS);
  11202. this._caps.maxFragmentUniformVectors = this._gl.getParameter(this._gl.MAX_FRAGMENT_UNIFORM_VECTORS);
  11203. this._caps.maxVertexUniformVectors = this._gl.getParameter(this._gl.MAX_VERTEX_UNIFORM_VECTORS);
  11204. // Infos
  11205. this._glVersion = this._gl.getParameter(this._gl.VERSION);
  11206. var rendererInfo = this._gl.getExtension("WEBGL_debug_renderer_info");
  11207. if (rendererInfo != null) {
  11208. this._glRenderer = this._gl.getParameter(rendererInfo.UNMASKED_RENDERER_WEBGL);
  11209. this._glVendor = this._gl.getParameter(rendererInfo.UNMASKED_VENDOR_WEBGL);
  11210. }
  11211. if (!this._glVendor) {
  11212. this._glVendor = "Unknown vendor";
  11213. }
  11214. if (!this._glRenderer) {
  11215. this._glRenderer = "Unknown renderer";
  11216. }
  11217. // Constants
  11218. this._gl.HALF_FLOAT_OES = 0x8D61; // Half floating-point type (16-bit).
  11219. if (this._gl.RGBA16F !== 0x881A) {
  11220. this._gl.RGBA16F = 0x881A; // RGBA 16-bit floating-point color-renderable internal sized format.
  11221. }
  11222. if (this._gl.RGBA32F !== 0x8814) {
  11223. this._gl.RGBA32F = 0x8814; // RGBA 32-bit floating-point color-renderable internal sized format.
  11224. }
  11225. if (this._gl.DEPTH24_STENCIL8 !== 35056) {
  11226. this._gl.DEPTH24_STENCIL8 = 35056;
  11227. }
  11228. // Extensions
  11229. this._caps.standardDerivatives = this._webGLVersion > 1 || (this._gl.getExtension('OES_standard_derivatives') !== null);
  11230. this._caps.astc = this._gl.getExtension('WEBGL_compressed_texture_astc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_astc');
  11231. this._caps.s3tc = this._gl.getExtension('WEBGL_compressed_texture_s3tc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_s3tc');
  11232. this._caps.pvrtc = this._gl.getExtension('WEBGL_compressed_texture_pvrtc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_pvrtc');
  11233. this._caps.etc1 = this._gl.getExtension('WEBGL_compressed_texture_etc1') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_etc1');
  11234. this._caps.etc2 = this._gl.getExtension('WEBGL_compressed_texture_etc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_etc') ||
  11235. this._gl.getExtension('WEBGL_compressed_texture_es3_0'); // also a requirement of OpenGL ES 3
  11236. 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');
  11237. this._caps.maxAnisotropy = this._caps.textureAnisotropicFilterExtension ? this._gl.getParameter(this._caps.textureAnisotropicFilterExtension.MAX_TEXTURE_MAX_ANISOTROPY_EXT) : 0;
  11238. this._caps.uintIndices = this._webGLVersion > 1 || this._gl.getExtension('OES_element_index_uint') !== null;
  11239. this._caps.fragmentDepthSupported = this._webGLVersion > 1 || this._gl.getExtension('EXT_frag_depth') !== null;
  11240. this._caps.highPrecisionShaderSupported = true;
  11241. this._caps.timerQuery = this._gl.getExtension('EXT_disjoint_timer_query_webgl2') || this._gl.getExtension("EXT_disjoint_timer_query");
  11242. if (this._caps.timerQuery) {
  11243. if (this._webGLVersion === 1) {
  11244. this._gl.getQuery = this._caps.timerQuery.getQueryEXT.bind(this._caps.timerQuery);
  11245. }
  11246. this._caps.canUseTimestampForTimerQuery = this._gl.getQuery(this._caps.timerQuery.TIMESTAMP_EXT, this._caps.timerQuery.QUERY_COUNTER_BITS_EXT) > 0;
  11247. }
  11248. // Checks if some of the format renders first to allow the use of webgl inspector.
  11249. this._caps.colorBufferFloat = this._webGLVersion > 1 && this._gl.getExtension('EXT_color_buffer_float');
  11250. this._caps.textureFloat = this._webGLVersion > 1 || this._gl.getExtension('OES_texture_float');
  11251. this._caps.textureFloatLinearFiltering = this._caps.textureFloat && this._gl.getExtension('OES_texture_float_linear');
  11252. this._caps.textureFloatRender = this._caps.textureFloat && this._canRenderToFloatFramebuffer();
  11253. this._caps.textureHalfFloat = this._webGLVersion > 1 || this._gl.getExtension('OES_texture_half_float');
  11254. this._caps.textureHalfFloatLinearFiltering = this._webGLVersion > 1 || (this._caps.textureHalfFloat && this._gl.getExtension('OES_texture_half_float_linear'));
  11255. if (this._webGLVersion > 1) {
  11256. this._gl.HALF_FLOAT_OES = 0x140B;
  11257. }
  11258. this._caps.textureHalfFloatRender = this._caps.textureHalfFloat && this._canRenderToHalfFloatFramebuffer();
  11259. this._caps.textureLOD = this._webGLVersion > 1 || this._gl.getExtension('EXT_shader_texture_lod');
  11260. // Draw buffers
  11261. if (this._webGLVersion > 1) {
  11262. this._caps.drawBuffersExtension = true;
  11263. }
  11264. else {
  11265. var drawBuffersExtension = this._gl.getExtension('WEBGL_draw_buffers');
  11266. if (drawBuffersExtension !== null) {
  11267. this._caps.drawBuffersExtension = true;
  11268. this._gl.drawBuffers = drawBuffersExtension.drawBuffersWEBGL.bind(drawBuffersExtension);
  11269. this._gl.DRAW_FRAMEBUFFER = this._gl.FRAMEBUFFER;
  11270. for (var i = 0; i < 16; i++) {
  11271. this._gl["COLOR_ATTACHMENT" + i + "_WEBGL"] = drawBuffersExtension["COLOR_ATTACHMENT" + i + "_WEBGL"];
  11272. }
  11273. }
  11274. else {
  11275. this._caps.drawBuffersExtension = false;
  11276. }
  11277. }
  11278. // Depth Texture
  11279. if (this._webGLVersion > 1) {
  11280. this._caps.depthTextureExtension = true;
  11281. }
  11282. else {
  11283. var depthTextureExtension = this._gl.getExtension('WEBGL_depth_texture');
  11284. if (depthTextureExtension != null) {
  11285. this._caps.depthTextureExtension = true;
  11286. this._gl.UNSIGNED_INT_24_8 = depthTextureExtension.UNSIGNED_INT_24_8_WEBGL;
  11287. }
  11288. }
  11289. // Vertex array object
  11290. if (this._webGLVersion > 1) {
  11291. this._caps.vertexArrayObject = true;
  11292. }
  11293. else {
  11294. var vertexArrayObjectExtension = this._gl.getExtension('OES_vertex_array_object');
  11295. if (vertexArrayObjectExtension != null) {
  11296. this._caps.vertexArrayObject = true;
  11297. this._gl.createVertexArray = vertexArrayObjectExtension.createVertexArrayOES.bind(vertexArrayObjectExtension);
  11298. this._gl.bindVertexArray = vertexArrayObjectExtension.bindVertexArrayOES.bind(vertexArrayObjectExtension);
  11299. this._gl.deleteVertexArray = vertexArrayObjectExtension.deleteVertexArrayOES.bind(vertexArrayObjectExtension);
  11300. }
  11301. else {
  11302. this._caps.vertexArrayObject = false;
  11303. }
  11304. }
  11305. // Instances count
  11306. if (this._webGLVersion > 1) {
  11307. this._caps.instancedArrays = true;
  11308. }
  11309. else {
  11310. var instanceExtension = this._gl.getExtension('ANGLE_instanced_arrays');
  11311. if (instanceExtension != null) {
  11312. this._caps.instancedArrays = true;
  11313. this._gl.drawArraysInstanced = instanceExtension.drawArraysInstancedANGLE.bind(instanceExtension);
  11314. this._gl.drawElementsInstanced = instanceExtension.drawElementsInstancedANGLE.bind(instanceExtension);
  11315. this._gl.vertexAttribDivisor = instanceExtension.vertexAttribDivisorANGLE.bind(instanceExtension);
  11316. }
  11317. else {
  11318. this._caps.instancedArrays = false;
  11319. }
  11320. }
  11321. // Intelligently add supported compressed formats in order to check for.
  11322. // Check for ASTC support first as it is most powerful and to be very cross platform.
  11323. // Next PVRTC & DXT, which are probably superior to ETC1/2.
  11324. // Likely no hardware which supports both PVR & DXT, so order matters little.
  11325. // ETC2 is newer and handles ETC1 (no alpha capability), so check for first.
  11326. if (this._caps.astc)
  11327. this.texturesSupported.push('-astc.ktx');
  11328. if (this._caps.s3tc)
  11329. this.texturesSupported.push('-dxt.ktx');
  11330. if (this._caps.pvrtc)
  11331. this.texturesSupported.push('-pvrtc.ktx');
  11332. if (this._caps.etc2)
  11333. this.texturesSupported.push('-etc2.ktx');
  11334. if (this._caps.etc1)
  11335. this.texturesSupported.push('-etc1.ktx');
  11336. if (this._gl.getShaderPrecisionFormat) {
  11337. var highp = this._gl.getShaderPrecisionFormat(this._gl.FRAGMENT_SHADER, this._gl.HIGH_FLOAT);
  11338. if (highp) {
  11339. this._caps.highPrecisionShaderSupported = highp.precision !== 0;
  11340. }
  11341. }
  11342. // Depth buffer
  11343. this.setDepthBuffer(true);
  11344. this.setDepthFunctionToLessOrEqual();
  11345. this.setDepthWrite(true);
  11346. // Texture maps
  11347. this._maxSimultaneousTextures = this._caps.maxCombinedTexturesImageUnits;
  11348. for (var slot = 0; slot < this._maxSimultaneousTextures; slot++) {
  11349. this._nextFreeTextureSlots.push(slot);
  11350. }
  11351. };
  11352. Object.defineProperty(Engine.prototype, "webGLVersion", {
  11353. get: function () {
  11354. return this._webGLVersion;
  11355. },
  11356. enumerable: true,
  11357. configurable: true
  11358. });
  11359. Object.defineProperty(Engine.prototype, "isStencilEnable", {
  11360. /**
  11361. * Returns true if the stencil buffer has been enabled through the creation option of the context.
  11362. */
  11363. get: function () {
  11364. return this._isStencilEnable;
  11365. },
  11366. enumerable: true,
  11367. configurable: true
  11368. });
  11369. Engine.prototype._prepareWorkingCanvas = function () {
  11370. if (this._workingCanvas) {
  11371. return;
  11372. }
  11373. this._workingCanvas = document.createElement("canvas");
  11374. var context = this._workingCanvas.getContext("2d");
  11375. if (context) {
  11376. this._workingContext = context;
  11377. }
  11378. };
  11379. Engine.prototype.resetTextureCache = function () {
  11380. for (var key in this._boundTexturesCache) {
  11381. var boundTexture = this._boundTexturesCache[key];
  11382. if (boundTexture) {
  11383. this._removeDesignatedSlot(boundTexture);
  11384. }
  11385. this._boundTexturesCache[key] = null;
  11386. }
  11387. if (!this.disableTextureBindingOptimization) {
  11388. this._nextFreeTextureSlots = [];
  11389. for (var slot = 0; slot < this._maxSimultaneousTextures; slot++) {
  11390. this._nextFreeTextureSlots.push(slot);
  11391. }
  11392. }
  11393. this._currentTextureChannel = -1;
  11394. };
  11395. Engine.prototype.isDeterministicLockStep = function () {
  11396. return this._deterministicLockstep;
  11397. };
  11398. Engine.prototype.getLockstepMaxSteps = function () {
  11399. return this._lockstepMaxSteps;
  11400. };
  11401. Engine.prototype.getGlInfo = function () {
  11402. return {
  11403. vendor: this._glVendor,
  11404. renderer: this._glRenderer,
  11405. version: this._glVersion
  11406. };
  11407. };
  11408. Engine.prototype.getAspectRatio = function (camera, useScreen) {
  11409. if (useScreen === void 0) { useScreen = false; }
  11410. var viewport = camera.viewport;
  11411. return (this.getRenderWidth(useScreen) * viewport.width) / (this.getRenderHeight(useScreen) * viewport.height);
  11412. };
  11413. Engine.prototype.getRenderWidth = function (useScreen) {
  11414. if (useScreen === void 0) { useScreen = false; }
  11415. if (!useScreen && this._currentRenderTarget) {
  11416. return this._currentRenderTarget.width;
  11417. }
  11418. return this._gl.drawingBufferWidth;
  11419. };
  11420. Engine.prototype.getRenderHeight = function (useScreen) {
  11421. if (useScreen === void 0) { useScreen = false; }
  11422. if (!useScreen && this._currentRenderTarget) {
  11423. return this._currentRenderTarget.height;
  11424. }
  11425. return this._gl.drawingBufferHeight;
  11426. };
  11427. Engine.prototype.getRenderingCanvas = function () {
  11428. return this._renderingCanvas;
  11429. };
  11430. Engine.prototype.getRenderingCanvasClientRect = function () {
  11431. if (!this._renderingCanvas) {
  11432. return null;
  11433. }
  11434. return this._renderingCanvas.getBoundingClientRect();
  11435. };
  11436. Engine.prototype.setHardwareScalingLevel = function (level) {
  11437. this._hardwareScalingLevel = level;
  11438. this.resize();
  11439. };
  11440. Engine.prototype.getHardwareScalingLevel = function () {
  11441. return this._hardwareScalingLevel;
  11442. };
  11443. Engine.prototype.getLoadedTexturesCache = function () {
  11444. return this._internalTexturesCache;
  11445. };
  11446. Engine.prototype.getCaps = function () {
  11447. return this._caps;
  11448. };
  11449. Object.defineProperty(Engine.prototype, "drawCalls", {
  11450. /** The number of draw calls submitted last frame */
  11451. get: function () {
  11452. BABYLON.Tools.Warn("drawCalls is deprecated. Please use SceneInstrumentation class");
  11453. return 0;
  11454. },
  11455. enumerable: true,
  11456. configurable: true
  11457. });
  11458. Object.defineProperty(Engine.prototype, "drawCallsPerfCounter", {
  11459. get: function () {
  11460. BABYLON.Tools.Warn("drawCallsPerfCounter is deprecated. Please use SceneInstrumentation class");
  11461. return null;
  11462. },
  11463. enumerable: true,
  11464. configurable: true
  11465. });
  11466. Engine.prototype.getDepthFunction = function () {
  11467. return this._depthCullingState.depthFunc;
  11468. };
  11469. Engine.prototype.setDepthFunction = function (depthFunc) {
  11470. this._depthCullingState.depthFunc = depthFunc;
  11471. };
  11472. Engine.prototype.setDepthFunctionToGreater = function () {
  11473. this._depthCullingState.depthFunc = this._gl.GREATER;
  11474. };
  11475. Engine.prototype.setDepthFunctionToGreaterOrEqual = function () {
  11476. this._depthCullingState.depthFunc = this._gl.GEQUAL;
  11477. };
  11478. Engine.prototype.setDepthFunctionToLess = function () {
  11479. this._depthCullingState.depthFunc = this._gl.LESS;
  11480. };
  11481. Engine.prototype.setDepthFunctionToLessOrEqual = function () {
  11482. this._depthCullingState.depthFunc = this._gl.LEQUAL;
  11483. };
  11484. Engine.prototype.getStencilBuffer = function () {
  11485. return this._stencilState.stencilTest;
  11486. };
  11487. Engine.prototype.setStencilBuffer = function (enable) {
  11488. this._stencilState.stencilTest = enable;
  11489. };
  11490. Engine.prototype.getStencilMask = function () {
  11491. return this._stencilState.stencilMask;
  11492. };
  11493. Engine.prototype.setStencilMask = function (mask) {
  11494. this._stencilState.stencilMask = mask;
  11495. };
  11496. Engine.prototype.getStencilFunction = function () {
  11497. return this._stencilState.stencilFunc;
  11498. };
  11499. Engine.prototype.getStencilFunctionReference = function () {
  11500. return this._stencilState.stencilFuncRef;
  11501. };
  11502. Engine.prototype.getStencilFunctionMask = function () {
  11503. return this._stencilState.stencilFuncMask;
  11504. };
  11505. Engine.prototype.setStencilFunction = function (stencilFunc) {
  11506. this._stencilState.stencilFunc = stencilFunc;
  11507. };
  11508. Engine.prototype.setStencilFunctionReference = function (reference) {
  11509. this._stencilState.stencilFuncRef = reference;
  11510. };
  11511. Engine.prototype.setStencilFunctionMask = function (mask) {
  11512. this._stencilState.stencilFuncMask = mask;
  11513. };
  11514. Engine.prototype.getStencilOperationFail = function () {
  11515. return this._stencilState.stencilOpStencilFail;
  11516. };
  11517. Engine.prototype.getStencilOperationDepthFail = function () {
  11518. return this._stencilState.stencilOpDepthFail;
  11519. };
  11520. Engine.prototype.getStencilOperationPass = function () {
  11521. return this._stencilState.stencilOpStencilDepthPass;
  11522. };
  11523. Engine.prototype.setStencilOperationFail = function (operation) {
  11524. this._stencilState.stencilOpStencilFail = operation;
  11525. };
  11526. Engine.prototype.setStencilOperationDepthFail = function (operation) {
  11527. this._stencilState.stencilOpDepthFail = operation;
  11528. };
  11529. Engine.prototype.setStencilOperationPass = function (operation) {
  11530. this._stencilState.stencilOpStencilDepthPass = operation;
  11531. };
  11532. Engine.prototype.setDitheringState = function (value) {
  11533. if (value) {
  11534. this._gl.enable(this._gl.DITHER);
  11535. }
  11536. else {
  11537. this._gl.disable(this._gl.DITHER);
  11538. }
  11539. };
  11540. Engine.prototype.setRasterizerState = function (value) {
  11541. if (value) {
  11542. this._gl.disable(this._gl.RASTERIZER_DISCARD);
  11543. }
  11544. else {
  11545. this._gl.enable(this._gl.RASTERIZER_DISCARD);
  11546. }
  11547. };
  11548. /**
  11549. * stop executing a render loop function and remove it from the execution array
  11550. * @param {Function} [renderFunction] the function to be removed. If not provided all functions will be removed.
  11551. */
  11552. Engine.prototype.stopRenderLoop = function (renderFunction) {
  11553. if (!renderFunction) {
  11554. this._activeRenderLoops = [];
  11555. return;
  11556. }
  11557. var index = this._activeRenderLoops.indexOf(renderFunction);
  11558. if (index >= 0) {
  11559. this._activeRenderLoops.splice(index, 1);
  11560. }
  11561. };
  11562. Engine.prototype._renderLoop = function () {
  11563. if (!this._contextWasLost) {
  11564. var shouldRender = true;
  11565. if (!this.renderEvenInBackground && this._windowIsBackground) {
  11566. shouldRender = false;
  11567. }
  11568. if (shouldRender) {
  11569. // Start new frame
  11570. this.beginFrame();
  11571. for (var index = 0; index < this._activeRenderLoops.length; index++) {
  11572. var renderFunction = this._activeRenderLoops[index];
  11573. renderFunction();
  11574. }
  11575. // Present
  11576. this.endFrame();
  11577. }
  11578. }
  11579. if (this._activeRenderLoops.length > 0) {
  11580. // Register new frame
  11581. var requester = null;
  11582. if (this._vrDisplay && this._vrDisplay.isPresenting)
  11583. requester = this._vrDisplay;
  11584. this._frameHandler = BABYLON.Tools.QueueNewFrame(this._bindedRenderFunction, requester);
  11585. }
  11586. else {
  11587. this._renderingQueueLaunched = false;
  11588. }
  11589. };
  11590. /**
  11591. * Register and execute a render loop. The engine can have more than one render function.
  11592. * @param {Function} renderFunction - the function to continuously execute starting the next render loop.
  11593. * @example
  11594. * engine.runRenderLoop(function () {
  11595. * scene.render()
  11596. * })
  11597. */
  11598. Engine.prototype.runRenderLoop = function (renderFunction) {
  11599. if (this._activeRenderLoops.indexOf(renderFunction) !== -1) {
  11600. return;
  11601. }
  11602. this._activeRenderLoops.push(renderFunction);
  11603. if (!this._renderingQueueLaunched) {
  11604. this._renderingQueueLaunched = true;
  11605. this._bindedRenderFunction = this._renderLoop.bind(this);
  11606. this._frameHandler = BABYLON.Tools.QueueNewFrame(this._bindedRenderFunction);
  11607. }
  11608. };
  11609. /**
  11610. * Toggle full screen mode.
  11611. * @param {boolean} requestPointerLock - should a pointer lock be requested from the user
  11612. * @param {any} options - an options object to be sent to the requestFullscreen function
  11613. */
  11614. Engine.prototype.switchFullscreen = function (requestPointerLock) {
  11615. if (this.isFullscreen) {
  11616. BABYLON.Tools.ExitFullscreen();
  11617. }
  11618. else {
  11619. this._pointerLockRequested = requestPointerLock;
  11620. if (this._renderingCanvas) {
  11621. BABYLON.Tools.RequestFullscreen(this._renderingCanvas);
  11622. }
  11623. }
  11624. };
  11625. Engine.prototype.clear = function (color, backBuffer, depth, stencil) {
  11626. if (stencil === void 0) { stencil = false; }
  11627. this.applyStates();
  11628. var mode = 0;
  11629. if (backBuffer && color) {
  11630. this._gl.clearColor(color.r, color.g, color.b, color.a !== undefined ? color.a : 1.0);
  11631. mode |= this._gl.COLOR_BUFFER_BIT;
  11632. }
  11633. if (depth) {
  11634. this._gl.clearDepth(1.0);
  11635. mode |= this._gl.DEPTH_BUFFER_BIT;
  11636. }
  11637. if (stencil) {
  11638. this._gl.clearStencil(0);
  11639. mode |= this._gl.STENCIL_BUFFER_BIT;
  11640. }
  11641. this._gl.clear(mode);
  11642. };
  11643. Engine.prototype.scissorClear = function (x, y, width, height, clearColor) {
  11644. var gl = this._gl;
  11645. // Save state
  11646. var curScissor = gl.getParameter(gl.SCISSOR_TEST);
  11647. var curScissorBox = gl.getParameter(gl.SCISSOR_BOX);
  11648. // Change state
  11649. gl.enable(gl.SCISSOR_TEST);
  11650. gl.scissor(x, y, width, height);
  11651. // Clear
  11652. this.clear(clearColor, true, true, true);
  11653. // Restore state
  11654. gl.scissor(curScissorBox[0], curScissorBox[1], curScissorBox[2], curScissorBox[3]);
  11655. if (curScissor === true) {
  11656. gl.enable(gl.SCISSOR_TEST);
  11657. }
  11658. else {
  11659. gl.disable(gl.SCISSOR_TEST);
  11660. }
  11661. };
  11662. /**
  11663. * Set the WebGL's viewport
  11664. * @param {BABYLON.Viewport} viewport - the viewport element to be used.
  11665. * @param {number} [requiredWidth] - the width required for rendering. If not provided the rendering canvas' width is used.
  11666. * @param {number} [requiredHeight] - the height required for rendering. If not provided the rendering canvas' height is used.
  11667. */
  11668. Engine.prototype.setViewport = function (viewport, requiredWidth, requiredHeight) {
  11669. var width = requiredWidth || this.getRenderWidth();
  11670. var height = requiredHeight || this.getRenderHeight();
  11671. var x = viewport.x || 0;
  11672. var y = viewport.y || 0;
  11673. this._cachedViewport = viewport;
  11674. this._gl.viewport(x * width, y * height, width * viewport.width, height * viewport.height);
  11675. };
  11676. /**
  11677. * Directly set the WebGL Viewport
  11678. * The x, y, width & height are directly passed to the WebGL call
  11679. * @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.
  11680. */
  11681. Engine.prototype.setDirectViewport = function (x, y, width, height) {
  11682. var currentViewport = this._cachedViewport;
  11683. this._cachedViewport = null;
  11684. this._gl.viewport(x, y, width, height);
  11685. return currentViewport;
  11686. };
  11687. Engine.prototype.beginFrame = function () {
  11688. this.onBeginFrameObservable.notifyObservers(this);
  11689. this._measureFps();
  11690. };
  11691. Engine.prototype.endFrame = function () {
  11692. //force a flush in case we are using a bad OS.
  11693. if (this._badOS) {
  11694. this.flushFramebuffer();
  11695. }
  11696. //submit frame to the vr device, if enabled
  11697. if (this._vrDisplay && this._vrDisplay.isPresenting) {
  11698. // TODO: We should only submit the frame if we read frameData successfully.
  11699. this._vrDisplay.submitFrame();
  11700. }
  11701. this.onEndFrameObservable.notifyObservers(this);
  11702. };
  11703. /**
  11704. * resize the view according to the canvas' size.
  11705. * @example
  11706. * window.addEventListener("resize", function () {
  11707. * engine.resize();
  11708. * });
  11709. */
  11710. Engine.prototype.resize = function () {
  11711. // We're not resizing the size of the canvas while in VR mode & presenting
  11712. if (!(this._vrDisplay && this._vrDisplay.isPresenting)) {
  11713. var width = this._renderingCanvas ? this._renderingCanvas.clientWidth : window.innerWidth;
  11714. var height = this._renderingCanvas ? this._renderingCanvas.clientHeight : window.innerHeight;
  11715. this.setSize(width / this._hardwareScalingLevel, height / this._hardwareScalingLevel);
  11716. }
  11717. };
  11718. /**
  11719. * force a specific size of the canvas
  11720. * @param {number} width - the new canvas' width
  11721. * @param {number} height - the new canvas' height
  11722. */
  11723. Engine.prototype.setSize = function (width, height) {
  11724. if (!this._renderingCanvas) {
  11725. return;
  11726. }
  11727. if (this._renderingCanvas.width === width && this._renderingCanvas.height === height) {
  11728. return;
  11729. }
  11730. this._renderingCanvas.width = width;
  11731. this._renderingCanvas.height = height;
  11732. for (var index = 0; index < this.scenes.length; index++) {
  11733. var scene = this.scenes[index];
  11734. for (var camIndex = 0; camIndex < scene.cameras.length; camIndex++) {
  11735. var cam = scene.cameras[camIndex];
  11736. cam._currentRenderId = 0;
  11737. }
  11738. }
  11739. if (this.onResizeObservable.hasObservers) {
  11740. this.onResizeObservable.notifyObservers(this);
  11741. }
  11742. };
  11743. // WebVR functions
  11744. Engine.prototype.isVRDevicePresent = function () {
  11745. return !!this._vrDisplay;
  11746. };
  11747. Engine.prototype.getVRDevice = function () {
  11748. return this._vrDisplay;
  11749. };
  11750. /**
  11751. * Initializes a webVR display and starts listening to display change events.
  11752. * The onVRDisplayChangedObservable will be notified upon these changes.
  11753. * @returns The onVRDisplayChangedObservable.
  11754. */
  11755. Engine.prototype.initWebVR = function () {
  11756. this.initWebVRAsync();
  11757. return this.onVRDisplayChangedObservable;
  11758. };
  11759. /**
  11760. * Initializes a webVR display and starts listening to display change events.
  11761. * The onVRDisplayChangedObservable will be notified upon these changes.
  11762. * @returns A promise containing a VRDisplay and if vr is supported.
  11763. */
  11764. Engine.prototype.initWebVRAsync = function () {
  11765. var _this = this;
  11766. var notifyObservers = function () {
  11767. var eventArgs = {
  11768. vrDisplay: _this._vrDisplay,
  11769. vrSupported: _this._vrSupported
  11770. };
  11771. _this.onVRDisplayChangedObservable.notifyObservers(eventArgs);
  11772. _this._webVRInitPromise = new Promise(function (res) { res(eventArgs); });
  11773. };
  11774. if (!this._onVrDisplayConnect) {
  11775. this._onVrDisplayConnect = function (event) {
  11776. _this._vrDisplay = event.display;
  11777. notifyObservers();
  11778. };
  11779. this._onVrDisplayDisconnect = function () {
  11780. _this._vrDisplay.cancelAnimationFrame(_this._frameHandler);
  11781. _this._vrDisplay = undefined;
  11782. _this._frameHandler = BABYLON.Tools.QueueNewFrame(_this._bindedRenderFunction);
  11783. notifyObservers();
  11784. };
  11785. this._onVrDisplayPresentChange = function () {
  11786. _this._vrExclusivePointerMode = _this._vrDisplay && _this._vrDisplay.isPresenting;
  11787. };
  11788. window.addEventListener('vrdisplayconnect', this._onVrDisplayConnect);
  11789. window.addEventListener('vrdisplaydisconnect', this._onVrDisplayDisconnect);
  11790. window.addEventListener('vrdisplaypresentchange', this._onVrDisplayPresentChange);
  11791. }
  11792. this._webVRInitPromise = this._webVRInitPromise || this._getVRDisplaysAsync();
  11793. this._webVRInitPromise.then(notifyObservers);
  11794. return this._webVRInitPromise;
  11795. };
  11796. Engine.prototype.enableVR = function () {
  11797. var _this = this;
  11798. if (this._vrDisplay && !this._vrDisplay.isPresenting) {
  11799. var onResolved = function () {
  11800. _this.onVRRequestPresentComplete.notifyObservers(true);
  11801. _this._onVRFullScreenTriggered();
  11802. };
  11803. var onRejected = function () {
  11804. _this.onVRRequestPresentComplete.notifyObservers(false);
  11805. };
  11806. this.onVRRequestPresentStart.notifyObservers(this);
  11807. this._vrDisplay.requestPresent([{ source: this.getRenderingCanvas() }]).then(onResolved).catch(onRejected);
  11808. }
  11809. };
  11810. Engine.prototype.disableVR = function () {
  11811. if (this._vrDisplay && this._vrDisplay.isPresenting) {
  11812. this._vrDisplay.exitPresent().then(this._onVRFullScreenTriggered).catch(this._onVRFullScreenTriggered);
  11813. }
  11814. };
  11815. Engine.prototype._getVRDisplaysAsync = function () {
  11816. var _this = this;
  11817. return new Promise(function (res, rej) {
  11818. if (navigator.getVRDisplays) {
  11819. navigator.getVRDisplays().then(function (devices) {
  11820. _this._vrSupported = true;
  11821. // note that devices may actually be an empty array. This is fine;
  11822. // we expect this._vrDisplay to be undefined in this case.
  11823. _this._vrDisplay = devices[0];
  11824. res({
  11825. vrDisplay: _this._vrDisplay,
  11826. vrSupported: _this._vrSupported
  11827. });
  11828. });
  11829. }
  11830. else {
  11831. _this._vrDisplay = undefined;
  11832. _this._vrSupported = false;
  11833. res({
  11834. vrDisplay: _this._vrDisplay,
  11835. vrSupported: _this._vrSupported
  11836. });
  11837. }
  11838. });
  11839. };
  11840. /**
  11841. * Binds the frame buffer to the specified texture.
  11842. * @param texture The texture to render to or null for the default canvas
  11843. * @param faceIndex The face of the texture to render to in case of cube texture
  11844. * @param requiredWidth The width of the target to render to
  11845. * @param requiredHeight The height of the target to render to
  11846. * @param forceFullscreenViewport Forces the viewport to be the entire texture/screen if true
  11847. * @param depthStencilTexture The depth stencil texture to use to render
  11848. */
  11849. Engine.prototype.bindFramebuffer = function (texture, faceIndex, requiredWidth, requiredHeight, forceFullscreenViewport, depthStencilTexture) {
  11850. if (this._currentRenderTarget) {
  11851. this.unBindFramebuffer(this._currentRenderTarget);
  11852. }
  11853. this._currentRenderTarget = texture;
  11854. this.bindUnboundFramebuffer(texture._MSAAFramebuffer ? texture._MSAAFramebuffer : texture._framebuffer);
  11855. var gl = this._gl;
  11856. if (texture.isCube) {
  11857. if (faceIndex === undefined) {
  11858. faceIndex = 0;
  11859. }
  11860. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, texture._webGLTexture, 0);
  11861. if (depthStencilTexture) {
  11862. if (depthStencilTexture._generateStencilBuffer) {
  11863. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_STENCIL_ATTACHMENT, gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, depthStencilTexture, 0);
  11864. }
  11865. else {
  11866. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, depthStencilTexture, 0);
  11867. }
  11868. }
  11869. }
  11870. if (this._cachedViewport && !forceFullscreenViewport) {
  11871. this.setViewport(this._cachedViewport, requiredWidth, requiredHeight);
  11872. }
  11873. else {
  11874. gl.viewport(0, 0, requiredWidth || texture.width, requiredHeight || texture.height);
  11875. }
  11876. this.wipeCaches();
  11877. };
  11878. Engine.prototype.bindUnboundFramebuffer = function (framebuffer) {
  11879. if (this._currentFramebuffer !== framebuffer) {
  11880. this._gl.bindFramebuffer(this._gl.FRAMEBUFFER, framebuffer);
  11881. this._currentFramebuffer = framebuffer;
  11882. }
  11883. };
  11884. Engine.prototype.unBindFramebuffer = function (texture, disableGenerateMipMaps, onBeforeUnbind) {
  11885. if (disableGenerateMipMaps === void 0) { disableGenerateMipMaps = false; }
  11886. this._currentRenderTarget = null;
  11887. // If MSAA, we need to bitblt back to main texture
  11888. var gl = this._gl;
  11889. if (texture._MSAAFramebuffer) {
  11890. gl.bindFramebuffer(gl.READ_FRAMEBUFFER, texture._MSAAFramebuffer);
  11891. gl.bindFramebuffer(gl.DRAW_FRAMEBUFFER, texture._framebuffer);
  11892. gl.blitFramebuffer(0, 0, texture.width, texture.height, 0, 0, texture.width, texture.height, gl.COLOR_BUFFER_BIT, gl.NEAREST);
  11893. }
  11894. if (texture.generateMipMaps && !disableGenerateMipMaps && !texture.isCube) {
  11895. this._bindTextureDirectly(gl.TEXTURE_2D, texture, true);
  11896. gl.generateMipmap(gl.TEXTURE_2D);
  11897. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  11898. }
  11899. if (onBeforeUnbind) {
  11900. if (texture._MSAAFramebuffer) {
  11901. // Bind the correct framebuffer
  11902. this.bindUnboundFramebuffer(texture._framebuffer);
  11903. }
  11904. onBeforeUnbind();
  11905. }
  11906. this.bindUnboundFramebuffer(null);
  11907. };
  11908. Engine.prototype.unBindMultiColorAttachmentFramebuffer = function (textures, disableGenerateMipMaps, onBeforeUnbind) {
  11909. if (disableGenerateMipMaps === void 0) { disableGenerateMipMaps = false; }
  11910. this._currentRenderTarget = null;
  11911. // If MSAA, we need to bitblt back to main texture
  11912. var gl = this._gl;
  11913. if (textures[0]._MSAAFramebuffer) {
  11914. gl.bindFramebuffer(gl.READ_FRAMEBUFFER, textures[0]._MSAAFramebuffer);
  11915. gl.bindFramebuffer(gl.DRAW_FRAMEBUFFER, textures[0]._framebuffer);
  11916. var attachments = textures[0]._attachments;
  11917. if (!attachments) {
  11918. attachments = new Array(textures.length);
  11919. textures[0]._attachments = attachments;
  11920. }
  11921. for (var i = 0; i < textures.length; i++) {
  11922. var texture = textures[i];
  11923. for (var j = 0; j < attachments.length; j++) {
  11924. attachments[j] = gl.NONE;
  11925. }
  11926. attachments[i] = gl[this.webGLVersion > 1 ? "COLOR_ATTACHMENT" + i : "COLOR_ATTACHMENT" + i + "_WEBGL"];
  11927. gl.readBuffer(attachments[i]);
  11928. gl.drawBuffers(attachments);
  11929. gl.blitFramebuffer(0, 0, texture.width, texture.height, 0, 0, texture.width, texture.height, gl.COLOR_BUFFER_BIT, gl.NEAREST);
  11930. }
  11931. for (var i = 0; i < attachments.length; i++) {
  11932. attachments[i] = gl[this.webGLVersion > 1 ? "COLOR_ATTACHMENT" + i : "COLOR_ATTACHMENT" + i + "_WEBGL"];
  11933. }
  11934. gl.drawBuffers(attachments);
  11935. }
  11936. for (var i = 0; i < textures.length; i++) {
  11937. var texture = textures[i];
  11938. if (texture.generateMipMaps && !disableGenerateMipMaps && !texture.isCube) {
  11939. this._bindTextureDirectly(gl.TEXTURE_2D, texture);
  11940. gl.generateMipmap(gl.TEXTURE_2D);
  11941. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  11942. }
  11943. }
  11944. if (onBeforeUnbind) {
  11945. if (textures[0]._MSAAFramebuffer) {
  11946. // Bind the correct framebuffer
  11947. this.bindUnboundFramebuffer(textures[0]._framebuffer);
  11948. }
  11949. onBeforeUnbind();
  11950. }
  11951. this.bindUnboundFramebuffer(null);
  11952. };
  11953. Engine.prototype.generateMipMapsForCubemap = function (texture) {
  11954. if (texture.generateMipMaps) {
  11955. var gl = this._gl;
  11956. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  11957. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  11958. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  11959. }
  11960. };
  11961. Engine.prototype.flushFramebuffer = function () {
  11962. this._gl.flush();
  11963. };
  11964. Engine.prototype.restoreDefaultFramebuffer = function () {
  11965. if (this._currentRenderTarget) {
  11966. this.unBindFramebuffer(this._currentRenderTarget);
  11967. }
  11968. else {
  11969. this.bindUnboundFramebuffer(null);
  11970. }
  11971. if (this._cachedViewport) {
  11972. this.setViewport(this._cachedViewport);
  11973. }
  11974. this.wipeCaches();
  11975. };
  11976. // UBOs
  11977. Engine.prototype.createUniformBuffer = function (elements) {
  11978. var ubo = this._gl.createBuffer();
  11979. if (!ubo) {
  11980. throw new Error("Unable to create uniform buffer");
  11981. }
  11982. this.bindUniformBuffer(ubo);
  11983. if (elements instanceof Float32Array) {
  11984. this._gl.bufferData(this._gl.UNIFORM_BUFFER, elements, this._gl.STATIC_DRAW);
  11985. }
  11986. else {
  11987. this._gl.bufferData(this._gl.UNIFORM_BUFFER, new Float32Array(elements), this._gl.STATIC_DRAW);
  11988. }
  11989. this.bindUniformBuffer(null);
  11990. ubo.references = 1;
  11991. return ubo;
  11992. };
  11993. Engine.prototype.createDynamicUniformBuffer = function (elements) {
  11994. var ubo = this._gl.createBuffer();
  11995. if (!ubo) {
  11996. throw new Error("Unable to create dynamic uniform buffer");
  11997. }
  11998. this.bindUniformBuffer(ubo);
  11999. if (elements instanceof Float32Array) {
  12000. this._gl.bufferData(this._gl.UNIFORM_BUFFER, elements, this._gl.DYNAMIC_DRAW);
  12001. }
  12002. else {
  12003. this._gl.bufferData(this._gl.UNIFORM_BUFFER, new Float32Array(elements), this._gl.DYNAMIC_DRAW);
  12004. }
  12005. this.bindUniformBuffer(null);
  12006. ubo.references = 1;
  12007. return ubo;
  12008. };
  12009. Engine.prototype.updateUniformBuffer = function (uniformBuffer, elements, offset, count) {
  12010. this.bindUniformBuffer(uniformBuffer);
  12011. if (offset === undefined) {
  12012. offset = 0;
  12013. }
  12014. if (count === undefined) {
  12015. if (elements instanceof Float32Array) {
  12016. this._gl.bufferSubData(this._gl.UNIFORM_BUFFER, offset, elements);
  12017. }
  12018. else {
  12019. this._gl.bufferSubData(this._gl.UNIFORM_BUFFER, offset, new Float32Array(elements));
  12020. }
  12021. }
  12022. else {
  12023. if (elements instanceof Float32Array) {
  12024. this._gl.bufferSubData(this._gl.UNIFORM_BUFFER, 0, elements.subarray(offset, offset + count));
  12025. }
  12026. else {
  12027. this._gl.bufferSubData(this._gl.UNIFORM_BUFFER, 0, new Float32Array(elements).subarray(offset, offset + count));
  12028. }
  12029. }
  12030. this.bindUniformBuffer(null);
  12031. };
  12032. // VBOs
  12033. Engine.prototype._resetVertexBufferBinding = function () {
  12034. this.bindArrayBuffer(null);
  12035. this._cachedVertexBuffers = null;
  12036. };
  12037. Engine.prototype.createVertexBuffer = function (vertices) {
  12038. var vbo = this._gl.createBuffer();
  12039. if (!vbo) {
  12040. throw new Error("Unable to create vertex buffer");
  12041. }
  12042. this.bindArrayBuffer(vbo);
  12043. if (vertices instanceof Float32Array) {
  12044. this._gl.bufferData(this._gl.ARRAY_BUFFER, vertices, this._gl.STATIC_DRAW);
  12045. }
  12046. else {
  12047. this._gl.bufferData(this._gl.ARRAY_BUFFER, new Float32Array(vertices), this._gl.STATIC_DRAW);
  12048. }
  12049. this._resetVertexBufferBinding();
  12050. vbo.references = 1;
  12051. return vbo;
  12052. };
  12053. Engine.prototype.createDynamicVertexBuffer = function (vertices) {
  12054. var vbo = this._gl.createBuffer();
  12055. if (!vbo) {
  12056. throw new Error("Unable to create dynamic vertex buffer");
  12057. }
  12058. this.bindArrayBuffer(vbo);
  12059. if (vertices instanceof Float32Array) {
  12060. this._gl.bufferData(this._gl.ARRAY_BUFFER, vertices, this._gl.DYNAMIC_DRAW);
  12061. }
  12062. else {
  12063. this._gl.bufferData(this._gl.ARRAY_BUFFER, new Float32Array(vertices), this._gl.DYNAMIC_DRAW);
  12064. }
  12065. this._resetVertexBufferBinding();
  12066. vbo.references = 1;
  12067. return vbo;
  12068. };
  12069. Engine.prototype.updateDynamicIndexBuffer = function (indexBuffer, indices, offset) {
  12070. if (offset === void 0) { offset = 0; }
  12071. // Force cache update
  12072. this._currentBoundBuffer[this._gl.ELEMENT_ARRAY_BUFFER] = null;
  12073. this.bindIndexBuffer(indexBuffer);
  12074. var arrayBuffer;
  12075. if (indices instanceof Uint16Array || indices instanceof Uint32Array) {
  12076. arrayBuffer = indices;
  12077. }
  12078. else {
  12079. arrayBuffer = indexBuffer.is32Bits ? new Uint32Array(indices) : new Uint16Array(indices);
  12080. }
  12081. this._gl.bufferData(this._gl.ELEMENT_ARRAY_BUFFER, arrayBuffer, this._gl.DYNAMIC_DRAW);
  12082. this._resetIndexBufferBinding();
  12083. };
  12084. Engine.prototype.updateDynamicVertexBuffer = function (vertexBuffer, vertices, offset, count) {
  12085. this.bindArrayBuffer(vertexBuffer);
  12086. if (offset === undefined) {
  12087. offset = 0;
  12088. }
  12089. if (count === undefined) {
  12090. if (vertices instanceof Float32Array) {
  12091. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, offset, vertices);
  12092. }
  12093. else {
  12094. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, offset, new Float32Array(vertices));
  12095. }
  12096. }
  12097. else {
  12098. if (vertices instanceof Float32Array) {
  12099. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, vertices.subarray(offset, offset + count));
  12100. }
  12101. else {
  12102. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, new Float32Array(vertices).subarray(offset, offset + count));
  12103. }
  12104. }
  12105. this._resetVertexBufferBinding();
  12106. };
  12107. Engine.prototype._resetIndexBufferBinding = function () {
  12108. this.bindIndexBuffer(null);
  12109. this._cachedIndexBuffer = null;
  12110. };
  12111. Engine.prototype.createIndexBuffer = function (indices, updatable) {
  12112. var vbo = this._gl.createBuffer();
  12113. if (!vbo) {
  12114. throw new Error("Unable to create index buffer");
  12115. }
  12116. this.bindIndexBuffer(vbo);
  12117. // Check for 32 bits indices
  12118. var arrayBuffer;
  12119. var need32Bits = false;
  12120. if (indices instanceof Uint16Array) {
  12121. arrayBuffer = indices;
  12122. }
  12123. else {
  12124. //check 32 bit support
  12125. if (this._caps.uintIndices) {
  12126. if (indices instanceof Uint32Array) {
  12127. arrayBuffer = indices;
  12128. need32Bits = true;
  12129. }
  12130. else {
  12131. //number[] or Int32Array, check if 32 bit is necessary
  12132. for (var index = 0; index < indices.length; index++) {
  12133. if (indices[index] > 65535) {
  12134. need32Bits = true;
  12135. break;
  12136. }
  12137. }
  12138. arrayBuffer = need32Bits ? new Uint32Array(indices) : new Uint16Array(indices);
  12139. }
  12140. }
  12141. else {
  12142. //no 32 bit support, force conversion to 16 bit (values greater 16 bit are lost)
  12143. arrayBuffer = new Uint16Array(indices);
  12144. }
  12145. }
  12146. this._gl.bufferData(this._gl.ELEMENT_ARRAY_BUFFER, arrayBuffer, updatable ? this._gl.DYNAMIC_DRAW : this._gl.STATIC_DRAW);
  12147. this._resetIndexBufferBinding();
  12148. vbo.references = 1;
  12149. vbo.is32Bits = need32Bits;
  12150. return vbo;
  12151. };
  12152. Engine.prototype.bindArrayBuffer = function (buffer) {
  12153. if (!this._vaoRecordInProgress) {
  12154. this._unbindVertexArrayObject();
  12155. }
  12156. this.bindBuffer(buffer, this._gl.ARRAY_BUFFER);
  12157. };
  12158. Engine.prototype.bindUniformBuffer = function (buffer) {
  12159. this._gl.bindBuffer(this._gl.UNIFORM_BUFFER, buffer);
  12160. };
  12161. Engine.prototype.bindUniformBufferBase = function (buffer, location) {
  12162. this._gl.bindBufferBase(this._gl.UNIFORM_BUFFER, location, buffer);
  12163. };
  12164. Engine.prototype.bindUniformBlock = function (shaderProgram, blockName, index) {
  12165. var uniformLocation = this._gl.getUniformBlockIndex(shaderProgram, blockName);
  12166. this._gl.uniformBlockBinding(shaderProgram, uniformLocation, index);
  12167. };
  12168. ;
  12169. Engine.prototype.bindIndexBuffer = function (buffer) {
  12170. if (!this._vaoRecordInProgress) {
  12171. this._unbindVertexArrayObject();
  12172. }
  12173. this.bindBuffer(buffer, this._gl.ELEMENT_ARRAY_BUFFER);
  12174. };
  12175. Engine.prototype.bindBuffer = function (buffer, target) {
  12176. if (this._vaoRecordInProgress || this._currentBoundBuffer[target] !== buffer) {
  12177. this._gl.bindBuffer(target, buffer);
  12178. this._currentBoundBuffer[target] = buffer;
  12179. }
  12180. };
  12181. Engine.prototype.updateArrayBuffer = function (data) {
  12182. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, data);
  12183. };
  12184. Engine.prototype.vertexAttribPointer = function (buffer, indx, size, type, normalized, stride, offset) {
  12185. var pointer = this._currentBufferPointers[indx];
  12186. var changed = false;
  12187. if (!pointer.active) {
  12188. changed = true;
  12189. pointer.active = true;
  12190. pointer.index = indx;
  12191. pointer.size = size;
  12192. pointer.type = type;
  12193. pointer.normalized = normalized;
  12194. pointer.stride = stride;
  12195. pointer.offset = offset;
  12196. pointer.buffer = buffer;
  12197. }
  12198. else {
  12199. if (pointer.buffer !== buffer) {
  12200. pointer.buffer = buffer;
  12201. changed = true;
  12202. }
  12203. if (pointer.size !== size) {
  12204. pointer.size = size;
  12205. changed = true;
  12206. }
  12207. if (pointer.type !== type) {
  12208. pointer.type = type;
  12209. changed = true;
  12210. }
  12211. if (pointer.normalized !== normalized) {
  12212. pointer.normalized = normalized;
  12213. changed = true;
  12214. }
  12215. if (pointer.stride !== stride) {
  12216. pointer.stride = stride;
  12217. changed = true;
  12218. }
  12219. if (pointer.offset !== offset) {
  12220. pointer.offset = offset;
  12221. changed = true;
  12222. }
  12223. }
  12224. if (changed || this._vaoRecordInProgress) {
  12225. this.bindArrayBuffer(buffer);
  12226. this._gl.vertexAttribPointer(indx, size, type, normalized, stride, offset);
  12227. }
  12228. };
  12229. Engine.prototype._bindIndexBufferWithCache = function (indexBuffer) {
  12230. if (indexBuffer == null) {
  12231. return;
  12232. }
  12233. if (this._cachedIndexBuffer !== indexBuffer) {
  12234. this._cachedIndexBuffer = indexBuffer;
  12235. this.bindIndexBuffer(indexBuffer);
  12236. this._uintIndicesCurrentlySet = indexBuffer.is32Bits;
  12237. }
  12238. };
  12239. Engine.prototype._bindVertexBuffersAttributes = function (vertexBuffers, effect) {
  12240. var attributes = effect.getAttributesNames();
  12241. if (!this._vaoRecordInProgress) {
  12242. this._unbindVertexArrayObject();
  12243. }
  12244. this.unbindAllAttributes();
  12245. for (var index = 0; index < attributes.length; index++) {
  12246. var order = effect.getAttributeLocation(index);
  12247. if (order >= 0) {
  12248. var vertexBuffer = vertexBuffers[attributes[index]];
  12249. if (!vertexBuffer) {
  12250. continue;
  12251. }
  12252. this._gl.enableVertexAttribArray(order);
  12253. if (!this._vaoRecordInProgress) {
  12254. this._vertexAttribArraysEnabled[order] = true;
  12255. }
  12256. var buffer = vertexBuffer.getBuffer();
  12257. if (buffer) {
  12258. this.vertexAttribPointer(buffer, order, vertexBuffer.getSize(), this._gl.FLOAT, false, vertexBuffer.getStrideSize() * 4, vertexBuffer.getOffset() * 4);
  12259. if (vertexBuffer.getIsInstanced()) {
  12260. this._gl.vertexAttribDivisor(order, vertexBuffer.getInstanceDivisor());
  12261. if (!this._vaoRecordInProgress) {
  12262. this._currentInstanceLocations.push(order);
  12263. this._currentInstanceBuffers.push(buffer);
  12264. }
  12265. }
  12266. }
  12267. }
  12268. }
  12269. };
  12270. Engine.prototype.recordVertexArrayObject = function (vertexBuffers, indexBuffer, effect) {
  12271. var vao = this._gl.createVertexArray();
  12272. this._vaoRecordInProgress = true;
  12273. this._gl.bindVertexArray(vao);
  12274. this._mustWipeVertexAttributes = true;
  12275. this._bindVertexBuffersAttributes(vertexBuffers, effect);
  12276. this.bindIndexBuffer(indexBuffer);
  12277. this._vaoRecordInProgress = false;
  12278. this._gl.bindVertexArray(null);
  12279. return vao;
  12280. };
  12281. Engine.prototype.bindVertexArrayObject = function (vertexArrayObject, indexBuffer) {
  12282. if (this._cachedVertexArrayObject !== vertexArrayObject) {
  12283. this._cachedVertexArrayObject = vertexArrayObject;
  12284. this._gl.bindVertexArray(vertexArrayObject);
  12285. this._cachedVertexBuffers = null;
  12286. this._cachedIndexBuffer = null;
  12287. this._uintIndicesCurrentlySet = indexBuffer != null && indexBuffer.is32Bits;
  12288. this._mustWipeVertexAttributes = true;
  12289. }
  12290. };
  12291. Engine.prototype.bindBuffersDirectly = function (vertexBuffer, indexBuffer, vertexDeclaration, vertexStrideSize, effect) {
  12292. if (this._cachedVertexBuffers !== vertexBuffer || this._cachedEffectForVertexBuffers !== effect) {
  12293. this._cachedVertexBuffers = vertexBuffer;
  12294. this._cachedEffectForVertexBuffers = effect;
  12295. var attributesCount = effect.getAttributesCount();
  12296. this._unbindVertexArrayObject();
  12297. this.unbindAllAttributes();
  12298. var offset = 0;
  12299. for (var index = 0; index < attributesCount; index++) {
  12300. if (index < vertexDeclaration.length) {
  12301. var order = effect.getAttributeLocation(index);
  12302. if (order >= 0) {
  12303. this._gl.enableVertexAttribArray(order);
  12304. this._vertexAttribArraysEnabled[order] = true;
  12305. this.vertexAttribPointer(vertexBuffer, order, vertexDeclaration[index], this._gl.FLOAT, false, vertexStrideSize, offset);
  12306. }
  12307. offset += vertexDeclaration[index] * 4;
  12308. }
  12309. }
  12310. }
  12311. this._bindIndexBufferWithCache(indexBuffer);
  12312. };
  12313. Engine.prototype._unbindVertexArrayObject = function () {
  12314. if (!this._cachedVertexArrayObject) {
  12315. return;
  12316. }
  12317. this._cachedVertexArrayObject = null;
  12318. this._gl.bindVertexArray(null);
  12319. };
  12320. Engine.prototype.bindBuffers = function (vertexBuffers, indexBuffer, effect) {
  12321. if (this._cachedVertexBuffers !== vertexBuffers || this._cachedEffectForVertexBuffers !== effect) {
  12322. this._cachedVertexBuffers = vertexBuffers;
  12323. this._cachedEffectForVertexBuffers = effect;
  12324. this._bindVertexBuffersAttributes(vertexBuffers, effect);
  12325. }
  12326. this._bindIndexBufferWithCache(indexBuffer);
  12327. };
  12328. Engine.prototype.unbindInstanceAttributes = function () {
  12329. var boundBuffer;
  12330. for (var i = 0, ul = this._currentInstanceLocations.length; i < ul; i++) {
  12331. var instancesBuffer = this._currentInstanceBuffers[i];
  12332. if (boundBuffer != instancesBuffer && instancesBuffer.references) {
  12333. boundBuffer = instancesBuffer;
  12334. this.bindArrayBuffer(instancesBuffer);
  12335. }
  12336. var offsetLocation = this._currentInstanceLocations[i];
  12337. this._gl.vertexAttribDivisor(offsetLocation, 0);
  12338. }
  12339. this._currentInstanceBuffers.length = 0;
  12340. this._currentInstanceLocations.length = 0;
  12341. };
  12342. Engine.prototype.releaseVertexArrayObject = function (vao) {
  12343. this._gl.deleteVertexArray(vao);
  12344. };
  12345. Engine.prototype._releaseBuffer = function (buffer) {
  12346. buffer.references--;
  12347. if (buffer.references === 0) {
  12348. this._gl.deleteBuffer(buffer);
  12349. return true;
  12350. }
  12351. return false;
  12352. };
  12353. Engine.prototype.createInstancesBuffer = function (capacity) {
  12354. var buffer = this._gl.createBuffer();
  12355. if (!buffer) {
  12356. throw new Error("Unable to create instance buffer");
  12357. }
  12358. buffer.capacity = capacity;
  12359. this.bindArrayBuffer(buffer);
  12360. this._gl.bufferData(this._gl.ARRAY_BUFFER, capacity, this._gl.DYNAMIC_DRAW);
  12361. return buffer;
  12362. };
  12363. Engine.prototype.deleteInstancesBuffer = function (buffer) {
  12364. this._gl.deleteBuffer(buffer);
  12365. };
  12366. Engine.prototype.updateAndBindInstancesBuffer = function (instancesBuffer, data, offsetLocations) {
  12367. this.bindArrayBuffer(instancesBuffer);
  12368. if (data) {
  12369. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, data);
  12370. }
  12371. if (offsetLocations[0].index !== undefined) {
  12372. var stride = 0;
  12373. for (var i = 0; i < offsetLocations.length; i++) {
  12374. var ai = offsetLocations[i];
  12375. stride += ai.attributeSize * 4;
  12376. }
  12377. for (var i = 0; i < offsetLocations.length; i++) {
  12378. var ai = offsetLocations[i];
  12379. if (!this._vertexAttribArraysEnabled[ai.index]) {
  12380. this._gl.enableVertexAttribArray(ai.index);
  12381. this._vertexAttribArraysEnabled[ai.index] = true;
  12382. }
  12383. this.vertexAttribPointer(instancesBuffer, ai.index, ai.attributeSize, ai.attribyteType || this._gl.FLOAT, ai.normalized || false, stride, ai.offset);
  12384. this._gl.vertexAttribDivisor(ai.index, 1);
  12385. this._currentInstanceLocations.push(ai.index);
  12386. this._currentInstanceBuffers.push(instancesBuffer);
  12387. }
  12388. }
  12389. else {
  12390. for (var index = 0; index < 4; index++) {
  12391. var offsetLocation = offsetLocations[index];
  12392. if (!this._vertexAttribArraysEnabled[offsetLocation]) {
  12393. this._gl.enableVertexAttribArray(offsetLocation);
  12394. this._vertexAttribArraysEnabled[offsetLocation] = true;
  12395. }
  12396. this.vertexAttribPointer(instancesBuffer, offsetLocation, 4, this._gl.FLOAT, false, 64, index * 16);
  12397. this._gl.vertexAttribDivisor(offsetLocation, 1);
  12398. this._currentInstanceLocations.push(offsetLocation);
  12399. this._currentInstanceBuffers.push(instancesBuffer);
  12400. }
  12401. }
  12402. };
  12403. Engine.prototype.applyStates = function () {
  12404. this._depthCullingState.apply(this._gl);
  12405. this._stencilState.apply(this._gl);
  12406. this._alphaState.apply(this._gl);
  12407. };
  12408. Engine.prototype.draw = function (useTriangles, indexStart, indexCount, instancesCount) {
  12409. this.drawElementsType(useTriangles ? BABYLON.Material.TriangleFillMode : BABYLON.Material.WireFrameFillMode, indexStart, indexCount, instancesCount);
  12410. };
  12411. Engine.prototype.drawPointClouds = function (verticesStart, verticesCount, instancesCount) {
  12412. this.drawArraysType(BABYLON.Material.PointFillMode, verticesStart, verticesCount, instancesCount);
  12413. };
  12414. Engine.prototype.drawUnIndexed = function (useTriangles, verticesStart, verticesCount, instancesCount) {
  12415. this.drawArraysType(useTriangles ? BABYLON.Material.TriangleFillMode : BABYLON.Material.WireFrameFillMode, verticesStart, verticesCount, instancesCount);
  12416. };
  12417. Engine.prototype.drawElementsType = function (fillMode, indexStart, indexCount, instancesCount) {
  12418. // Apply states
  12419. this.applyStates();
  12420. this._drawCalls.addCount(1, false);
  12421. // Render
  12422. var drawMode = this.DrawMode(fillMode);
  12423. var indexFormat = this._uintIndicesCurrentlySet ? this._gl.UNSIGNED_INT : this._gl.UNSIGNED_SHORT;
  12424. var mult = this._uintIndicesCurrentlySet ? 4 : 2;
  12425. if (instancesCount) {
  12426. this._gl.drawElementsInstanced(drawMode, indexCount, indexFormat, indexStart * mult, instancesCount);
  12427. }
  12428. else {
  12429. this._gl.drawElements(drawMode, indexCount, indexFormat, indexStart * mult);
  12430. }
  12431. };
  12432. Engine.prototype.drawArraysType = function (fillMode, verticesStart, verticesCount, instancesCount) {
  12433. // Apply states
  12434. this.applyStates();
  12435. this._drawCalls.addCount(1, false);
  12436. var drawMode = this.DrawMode(fillMode);
  12437. if (instancesCount) {
  12438. this._gl.drawArraysInstanced(drawMode, verticesStart, verticesCount, instancesCount);
  12439. }
  12440. else {
  12441. this._gl.drawArrays(drawMode, verticesStart, verticesCount);
  12442. }
  12443. };
  12444. Engine.prototype.DrawMode = function (fillMode) {
  12445. switch (fillMode) {
  12446. // Triangle views
  12447. case BABYLON.Material.TriangleFillMode:
  12448. return this._gl.TRIANGLES;
  12449. case BABYLON.Material.PointFillMode:
  12450. return this._gl.POINTS;
  12451. case BABYLON.Material.WireFrameFillMode:
  12452. return this._gl.LINES;
  12453. // Draw modes
  12454. case BABYLON.Material.PointListDrawMode:
  12455. return this._gl.POINTS;
  12456. case BABYLON.Material.LineListDrawMode:
  12457. return this._gl.LINES;
  12458. case BABYLON.Material.LineLoopDrawMode:
  12459. return this._gl.LINE_LOOP;
  12460. case BABYLON.Material.LineStripDrawMode:
  12461. return this._gl.LINE_STRIP;
  12462. case BABYLON.Material.TriangleStripDrawMode:
  12463. return this._gl.TRIANGLE_STRIP;
  12464. case BABYLON.Material.TriangleFanDrawMode:
  12465. return this._gl.TRIANGLE_FAN;
  12466. default:
  12467. return this._gl.TRIANGLES;
  12468. }
  12469. };
  12470. // Shaders
  12471. Engine.prototype._releaseEffect = function (effect) {
  12472. if (this._compiledEffects[effect._key]) {
  12473. delete this._compiledEffects[effect._key];
  12474. this._deleteProgram(effect.getProgram());
  12475. }
  12476. };
  12477. Engine.prototype._deleteProgram = function (program) {
  12478. if (program) {
  12479. program.__SPECTOR_rebuildProgram = null;
  12480. if (program.transformFeedback) {
  12481. this.deleteTransformFeedback(program.transformFeedback);
  12482. program.transformFeedback = null;
  12483. }
  12484. this._gl.deleteProgram(program);
  12485. }
  12486. };
  12487. /**
  12488. * @param baseName The base name of the effect (The name of file without .fragment.fx or .vertex.fx)
  12489. * @param samplers An array of string used to represent textures
  12490. */
  12491. Engine.prototype.createEffect = function (baseName, attributesNamesOrOptions, uniformsNamesOrEngine, samplers, defines, fallbacks, onCompiled, onError, indexParameters) {
  12492. var vertex = baseName.vertexElement || baseName.vertex || baseName;
  12493. var fragment = baseName.fragmentElement || baseName.fragment || baseName;
  12494. var name = vertex + "+" + fragment + "@" + (defines ? defines : attributesNamesOrOptions.defines);
  12495. if (this._compiledEffects[name]) {
  12496. var compiledEffect = this._compiledEffects[name];
  12497. if (onCompiled && compiledEffect.isReady()) {
  12498. onCompiled(compiledEffect);
  12499. }
  12500. return compiledEffect;
  12501. }
  12502. var effect = new BABYLON.Effect(baseName, attributesNamesOrOptions, uniformsNamesOrEngine, samplers, this, defines, fallbacks, onCompiled, onError, indexParameters);
  12503. effect._key = name;
  12504. this._compiledEffects[name] = effect;
  12505. return effect;
  12506. };
  12507. Engine.prototype.createEffectForParticles = function (fragmentName, uniformsNames, samplers, defines, fallbacks, onCompiled, onError) {
  12508. if (uniformsNames === void 0) { uniformsNames = []; }
  12509. if (samplers === void 0) { samplers = []; }
  12510. if (defines === void 0) { defines = ""; }
  12511. return this.createEffect({
  12512. vertex: "particles",
  12513. fragmentElement: fragmentName
  12514. }, ["position", "color", "options"], ["view", "projection"].concat(uniformsNames), ["diffuseSampler"].concat(samplers), defines, fallbacks, onCompiled, onError);
  12515. };
  12516. Engine.prototype.createRawShaderProgram = function (vertexCode, fragmentCode, context, transformFeedbackVaryings) {
  12517. if (transformFeedbackVaryings === void 0) { transformFeedbackVaryings = null; }
  12518. context = context || this._gl;
  12519. var vertexShader = compileRawShader(context, vertexCode, "vertex");
  12520. var fragmentShader = compileRawShader(context, fragmentCode, "fragment");
  12521. return this._createShaderProgram(vertexShader, fragmentShader, context, transformFeedbackVaryings);
  12522. };
  12523. Engine.prototype.createShaderProgram = function (vertexCode, fragmentCode, defines, context, transformFeedbackVaryings) {
  12524. if (transformFeedbackVaryings === void 0) { transformFeedbackVaryings = null; }
  12525. context = context || this._gl;
  12526. this.onBeforeShaderCompilationObservable.notifyObservers(this);
  12527. var shaderVersion = (this._webGLVersion > 1) ? "#version 300 es\n" : "";
  12528. var vertexShader = compileShader(context, vertexCode, "vertex", defines, shaderVersion);
  12529. var fragmentShader = compileShader(context, fragmentCode, "fragment", defines, shaderVersion);
  12530. var program = this._createShaderProgram(vertexShader, fragmentShader, context, transformFeedbackVaryings);
  12531. this.onAfterShaderCompilationObservable.notifyObservers(this);
  12532. return program;
  12533. };
  12534. Engine.prototype._createShaderProgram = function (vertexShader, fragmentShader, context, transformFeedbackVaryings) {
  12535. if (transformFeedbackVaryings === void 0) { transformFeedbackVaryings = null; }
  12536. var shaderProgram = context.createProgram();
  12537. if (!shaderProgram) {
  12538. throw new Error("Unable to create program");
  12539. }
  12540. context.attachShader(shaderProgram, vertexShader);
  12541. context.attachShader(shaderProgram, fragmentShader);
  12542. if (this.webGLVersion > 1 && transformFeedbackVaryings) {
  12543. var transformFeedback = this.createTransformFeedback();
  12544. this.bindTransformFeedback(transformFeedback);
  12545. this.setTranformFeedbackVaryings(shaderProgram, transformFeedbackVaryings);
  12546. shaderProgram.transformFeedback = transformFeedback;
  12547. }
  12548. context.linkProgram(shaderProgram);
  12549. if (this.webGLVersion > 1 && transformFeedbackVaryings) {
  12550. this.bindTransformFeedback(null);
  12551. }
  12552. var linked = context.getProgramParameter(shaderProgram, context.LINK_STATUS);
  12553. if (!linked) {
  12554. context.validateProgram(shaderProgram);
  12555. var error = context.getProgramInfoLog(shaderProgram);
  12556. if (error) {
  12557. throw new Error(error);
  12558. }
  12559. }
  12560. context.deleteShader(vertexShader);
  12561. context.deleteShader(fragmentShader);
  12562. return shaderProgram;
  12563. };
  12564. Engine.prototype.getUniforms = function (shaderProgram, uniformsNames) {
  12565. var results = new Array();
  12566. for (var index = 0; index < uniformsNames.length; index++) {
  12567. results.push(this._gl.getUniformLocation(shaderProgram, uniformsNames[index]));
  12568. }
  12569. return results;
  12570. };
  12571. Engine.prototype.getAttributes = function (shaderProgram, attributesNames) {
  12572. var results = [];
  12573. for (var index = 0; index < attributesNames.length; index++) {
  12574. try {
  12575. results.push(this._gl.getAttribLocation(shaderProgram, attributesNames[index]));
  12576. }
  12577. catch (e) {
  12578. results.push(-1);
  12579. }
  12580. }
  12581. return results;
  12582. };
  12583. Engine.prototype.enableEffect = function (effect) {
  12584. if (!effect) {
  12585. return;
  12586. }
  12587. // Use program
  12588. this.bindSamplers(effect);
  12589. this._currentEffect = effect;
  12590. if (effect.onBind) {
  12591. effect.onBind(effect);
  12592. }
  12593. effect.onBindObservable.notifyObservers(effect);
  12594. };
  12595. Engine.prototype.setIntArray = function (uniform, array) {
  12596. if (!uniform)
  12597. return;
  12598. this._gl.uniform1iv(uniform, array);
  12599. };
  12600. Engine.prototype.setIntArray2 = function (uniform, array) {
  12601. if (!uniform || array.length % 2 !== 0)
  12602. return;
  12603. this._gl.uniform2iv(uniform, array);
  12604. };
  12605. Engine.prototype.setIntArray3 = function (uniform, array) {
  12606. if (!uniform || array.length % 3 !== 0)
  12607. return;
  12608. this._gl.uniform3iv(uniform, array);
  12609. };
  12610. Engine.prototype.setIntArray4 = function (uniform, array) {
  12611. if (!uniform || array.length % 4 !== 0)
  12612. return;
  12613. this._gl.uniform4iv(uniform, array);
  12614. };
  12615. Engine.prototype.setFloatArray = function (uniform, array) {
  12616. if (!uniform)
  12617. return;
  12618. this._gl.uniform1fv(uniform, array);
  12619. };
  12620. Engine.prototype.setFloatArray2 = function (uniform, array) {
  12621. if (!uniform || array.length % 2 !== 0)
  12622. return;
  12623. this._gl.uniform2fv(uniform, array);
  12624. };
  12625. Engine.prototype.setFloatArray3 = function (uniform, array) {
  12626. if (!uniform || array.length % 3 !== 0)
  12627. return;
  12628. this._gl.uniform3fv(uniform, array);
  12629. };
  12630. Engine.prototype.setFloatArray4 = function (uniform, array) {
  12631. if (!uniform || array.length % 4 !== 0)
  12632. return;
  12633. this._gl.uniform4fv(uniform, array);
  12634. };
  12635. Engine.prototype.setArray = function (uniform, array) {
  12636. if (!uniform)
  12637. return;
  12638. this._gl.uniform1fv(uniform, array);
  12639. };
  12640. Engine.prototype.setArray2 = function (uniform, array) {
  12641. if (!uniform || array.length % 2 !== 0)
  12642. return;
  12643. this._gl.uniform2fv(uniform, array);
  12644. };
  12645. Engine.prototype.setArray3 = function (uniform, array) {
  12646. if (!uniform || array.length % 3 !== 0)
  12647. return;
  12648. this._gl.uniform3fv(uniform, array);
  12649. };
  12650. Engine.prototype.setArray4 = function (uniform, array) {
  12651. if (!uniform || array.length % 4 !== 0)
  12652. return;
  12653. this._gl.uniform4fv(uniform, array);
  12654. };
  12655. Engine.prototype.setMatrices = function (uniform, matrices) {
  12656. if (!uniform)
  12657. return;
  12658. this._gl.uniformMatrix4fv(uniform, false, matrices);
  12659. };
  12660. Engine.prototype.setMatrix = function (uniform, matrix) {
  12661. if (!uniform)
  12662. return;
  12663. this._gl.uniformMatrix4fv(uniform, false, matrix.toArray());
  12664. };
  12665. Engine.prototype.setMatrix3x3 = function (uniform, matrix) {
  12666. if (!uniform)
  12667. return;
  12668. this._gl.uniformMatrix3fv(uniform, false, matrix);
  12669. };
  12670. Engine.prototype.setMatrix2x2 = function (uniform, matrix) {
  12671. if (!uniform)
  12672. return;
  12673. this._gl.uniformMatrix2fv(uniform, false, matrix);
  12674. };
  12675. Engine.prototype.setInt = function (uniform, value) {
  12676. if (!uniform)
  12677. return;
  12678. this._gl.uniform1i(uniform, value);
  12679. };
  12680. Engine.prototype.setFloat = function (uniform, value) {
  12681. if (!uniform)
  12682. return;
  12683. this._gl.uniform1f(uniform, value);
  12684. };
  12685. Engine.prototype.setFloat2 = function (uniform, x, y) {
  12686. if (!uniform)
  12687. return;
  12688. this._gl.uniform2f(uniform, x, y);
  12689. };
  12690. Engine.prototype.setFloat3 = function (uniform, x, y, z) {
  12691. if (!uniform)
  12692. return;
  12693. this._gl.uniform3f(uniform, x, y, z);
  12694. };
  12695. Engine.prototype.setBool = function (uniform, bool) {
  12696. if (!uniform)
  12697. return;
  12698. this._gl.uniform1i(uniform, bool);
  12699. };
  12700. Engine.prototype.setFloat4 = function (uniform, x, y, z, w) {
  12701. if (!uniform)
  12702. return;
  12703. this._gl.uniform4f(uniform, x, y, z, w);
  12704. };
  12705. Engine.prototype.setColor3 = function (uniform, color3) {
  12706. if (!uniform)
  12707. return;
  12708. this._gl.uniform3f(uniform, color3.r, color3.g, color3.b);
  12709. };
  12710. Engine.prototype.setColor4 = function (uniform, color3, alpha) {
  12711. if (!uniform)
  12712. return;
  12713. this._gl.uniform4f(uniform, color3.r, color3.g, color3.b, alpha);
  12714. };
  12715. /**
  12716. * Sets a Color4 on a uniform variable
  12717. * @param uniform defines the uniform location
  12718. * @param color4 defines the value to be set
  12719. */
  12720. Engine.prototype.setDirectColor4 = function (uniform, color4) {
  12721. if (!uniform)
  12722. return;
  12723. this._gl.uniform4f(uniform, color4.r, color4.g, color4.b, color4.a);
  12724. };
  12725. // States
  12726. Engine.prototype.setState = function (culling, zOffset, force, reverseSide) {
  12727. if (zOffset === void 0) { zOffset = 0; }
  12728. if (reverseSide === void 0) { reverseSide = false; }
  12729. // Culling
  12730. if (this._depthCullingState.cull !== culling || force) {
  12731. this._depthCullingState.cull = culling;
  12732. }
  12733. // Cull face
  12734. var cullFace = this.cullBackFaces ? this._gl.BACK : this._gl.FRONT;
  12735. if (this._depthCullingState.cullFace !== cullFace || force) {
  12736. this._depthCullingState.cullFace = cullFace;
  12737. }
  12738. // Z offset
  12739. this.setZOffset(zOffset);
  12740. // Front face
  12741. var frontFace = reverseSide ? this._gl.CW : this._gl.CCW;
  12742. if (this._depthCullingState.frontFace !== frontFace || force) {
  12743. this._depthCullingState.frontFace = frontFace;
  12744. }
  12745. };
  12746. Engine.prototype.setZOffset = function (value) {
  12747. this._depthCullingState.zOffset = value;
  12748. };
  12749. Engine.prototype.getZOffset = function () {
  12750. return this._depthCullingState.zOffset;
  12751. };
  12752. Engine.prototype.setDepthBuffer = function (enable) {
  12753. this._depthCullingState.depthTest = enable;
  12754. };
  12755. Engine.prototype.getDepthWrite = function () {
  12756. return this._depthCullingState.depthMask;
  12757. };
  12758. Engine.prototype.setDepthWrite = function (enable) {
  12759. this._depthCullingState.depthMask = enable;
  12760. };
  12761. Engine.prototype.setColorWrite = function (enable) {
  12762. this._gl.colorMask(enable, enable, enable, enable);
  12763. this._colorWrite = enable;
  12764. };
  12765. Engine.prototype.getColorWrite = function () {
  12766. return this._colorWrite;
  12767. };
  12768. Engine.prototype.setAlphaConstants = function (r, g, b, a) {
  12769. this._alphaState.setAlphaBlendConstants(r, g, b, a);
  12770. };
  12771. Engine.prototype.setAlphaMode = function (mode, noDepthWriteChange) {
  12772. if (noDepthWriteChange === void 0) { noDepthWriteChange = false; }
  12773. if (this._alphaMode === mode) {
  12774. return;
  12775. }
  12776. switch (mode) {
  12777. case Engine.ALPHA_DISABLE:
  12778. this._alphaState.alphaBlend = false;
  12779. break;
  12780. case Engine.ALPHA_PREMULTIPLIED:
  12781. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA, this._gl.ONE, this._gl.ONE);
  12782. this._alphaState.alphaBlend = true;
  12783. break;
  12784. case Engine.ALPHA_PREMULTIPLIED_PORTERDUFF:
  12785. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA, this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA);
  12786. this._alphaState.alphaBlend = true;
  12787. break;
  12788. case Engine.ALPHA_COMBINE:
  12789. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE_MINUS_SRC_ALPHA, this._gl.ONE, this._gl.ONE);
  12790. this._alphaState.alphaBlend = true;
  12791. break;
  12792. case Engine.ALPHA_ONEONE:
  12793. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE, this._gl.ZERO, this._gl.ONE);
  12794. this._alphaState.alphaBlend = true;
  12795. break;
  12796. case Engine.ALPHA_ADD:
  12797. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE, this._gl.ZERO, this._gl.ONE);
  12798. this._alphaState.alphaBlend = true;
  12799. break;
  12800. case Engine.ALPHA_SUBTRACT:
  12801. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ZERO, this._gl.ONE_MINUS_SRC_COLOR, this._gl.ONE, this._gl.ONE);
  12802. this._alphaState.alphaBlend = true;
  12803. break;
  12804. case Engine.ALPHA_MULTIPLY:
  12805. this._alphaState.setAlphaBlendFunctionParameters(this._gl.DST_COLOR, this._gl.ZERO, this._gl.ONE, this._gl.ONE);
  12806. this._alphaState.alphaBlend = true;
  12807. break;
  12808. case Engine.ALPHA_MAXIMIZED:
  12809. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE_MINUS_SRC_COLOR, this._gl.ONE, this._gl.ONE);
  12810. this._alphaState.alphaBlend = true;
  12811. break;
  12812. case Engine.ALPHA_INTERPOLATE:
  12813. this._alphaState.setAlphaBlendFunctionParameters(this._gl.CONSTANT_COLOR, this._gl.ONE_MINUS_CONSTANT_COLOR, this._gl.CONSTANT_ALPHA, this._gl.ONE_MINUS_CONSTANT_ALPHA);
  12814. this._alphaState.alphaBlend = true;
  12815. break;
  12816. case Engine.ALPHA_SCREENMODE:
  12817. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE_MINUS_SRC_COLOR, this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA);
  12818. this._alphaState.alphaBlend = true;
  12819. break;
  12820. }
  12821. if (!noDepthWriteChange) {
  12822. this.setDepthWrite(mode === Engine.ALPHA_DISABLE);
  12823. }
  12824. this._alphaMode = mode;
  12825. };
  12826. Engine.prototype.getAlphaMode = function () {
  12827. return this._alphaMode;
  12828. };
  12829. // Textures
  12830. Engine.prototype.wipeCaches = function (bruteForce) {
  12831. if (this.preventCacheWipeBetweenFrames && !bruteForce) {
  12832. return;
  12833. }
  12834. this._currentEffect = null;
  12835. // 6/8/2017: deltakosh: Should not be required anymore.
  12836. // This message is then mostly for the future myself who will scream out loud when seeing that it was actually required :)
  12837. if (bruteForce) {
  12838. this.resetTextureCache();
  12839. this._currentProgram = null;
  12840. this._stencilState.reset();
  12841. this._depthCullingState.reset();
  12842. this.setDepthFunctionToLessOrEqual();
  12843. this._alphaState.reset();
  12844. }
  12845. this._resetVertexBufferBinding();
  12846. this._cachedIndexBuffer = null;
  12847. this._cachedEffectForVertexBuffers = null;
  12848. this._unbindVertexArrayObject();
  12849. this.bindIndexBuffer(null);
  12850. };
  12851. /**
  12852. * Set the compressed texture format to use, based on the formats you have, and the formats
  12853. * supported by the hardware / browser.
  12854. *
  12855. * Khronos Texture Container (.ktx) files are used to support this. This format has the
  12856. * advantage of being specifically designed for OpenGL. Header elements directly correspond
  12857. * to API arguments needed to compressed textures. This puts the burden on the container
  12858. * generator to house the arcane code for determining these for current & future formats.
  12859. *
  12860. * for description see https://www.khronos.org/opengles/sdk/tools/KTX/
  12861. * for file layout see https://www.khronos.org/opengles/sdk/tools/KTX/file_format_spec/
  12862. *
  12863. * Note: The result of this call is not taken into account when a texture is base64.
  12864. *
  12865. * @param {Array<string>} formatsAvailable- The list of those format families you have created
  12866. * on your server. Syntax: '-' + format family + '.ktx'. (Case and order do not matter.)
  12867. *
  12868. * Current families are astc, dxt, pvrtc, etc2, & etc1.
  12869. * @returns The extension selected.
  12870. */
  12871. Engine.prototype.setTextureFormatToUse = function (formatsAvailable) {
  12872. for (var i = 0, len1 = this.texturesSupported.length; i < len1; i++) {
  12873. for (var j = 0, len2 = formatsAvailable.length; j < len2; j++) {
  12874. if (this._texturesSupported[i] === formatsAvailable[j].toLowerCase()) {
  12875. return this._textureFormatInUse = this._texturesSupported[i];
  12876. }
  12877. }
  12878. }
  12879. // actively set format to nothing, to allow this to be called more than once
  12880. // and possibly fail the 2nd time
  12881. this._textureFormatInUse = null;
  12882. return null;
  12883. };
  12884. Engine.prototype._createTexture = function () {
  12885. var texture = this._gl.createTexture();
  12886. if (!texture) {
  12887. throw new Error("Unable to create texture");
  12888. }
  12889. return texture;
  12890. };
  12891. /**
  12892. * Usually called from BABYLON.Texture.ts. Passed information to create a WebGLTexture.
  12893. * @param {string} urlArg- This contains one of the following:
  12894. * 1. A conventional http URL, e.g. 'http://...' or 'file://...'
  12895. * 2. A base64 string of in-line texture data, e.g. 'data:image/jpg;base64,/...'
  12896. * 3. An indicator that data being passed using the buffer parameter, e.g. 'data:mytexture.jpg'
  12897. *
  12898. * @param {boolean} noMipmap- When true, no mipmaps shall be generated. Ignored for compressed textures. They must be in the file.
  12899. * @param {boolean} invertY- When true, image is flipped when loaded. You probably want true. Ignored for compressed textures. Must be flipped in the file.
  12900. * @param {Scene} scene- Needed for loading to the correct scene.
  12901. * @param {number} samplingMode- Mode with should be used sample / access the texture. Default: TRILINEAR
  12902. * @param {callback} onLoad- Optional callback to be called upon successful completion.
  12903. * @param {callback} onError- Optional callback to be called upon failure.
  12904. * @param {ArrayBuffer | HTMLImageElement} buffer- A source of a file previously fetched as either an ArrayBuffer (compressed or image format) or HTMLImageElement (image format)
  12905. * @param {WebGLTexture} fallback- An internal argument in case the function must be called again, due to etc1 not having alpha capabilities.
  12906. * @param {number} format- Internal format. Default: RGB when extension is '.jpg' else RGBA. Ignored for compressed textures.
  12907. *
  12908. * @returns {WebGLTexture} for assignment back into BABYLON.Texture
  12909. */
  12910. Engine.prototype.createTexture = function (urlArg, noMipmap, invertY, scene, samplingMode, onLoad, onError, buffer, fallBack, format) {
  12911. var _this = this;
  12912. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  12913. if (onLoad === void 0) { onLoad = null; }
  12914. if (onError === void 0) { onError = null; }
  12915. if (buffer === void 0) { buffer = null; }
  12916. if (fallBack === void 0) { fallBack = null; }
  12917. if (format === void 0) { format = null; }
  12918. var url = String(urlArg); // assign a new string, so that the original is still available in case of fallback
  12919. var fromData = url.substr(0, 5) === "data:";
  12920. var fromBlob = url.substr(0, 5) === "blob:";
  12921. var isBase64 = fromData && url.indexOf("base64") !== -1;
  12922. var texture = fallBack ? fallBack : new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_URL);
  12923. // establish the file extension, if possible
  12924. var lastDot = url.lastIndexOf('.');
  12925. var extension = (lastDot > 0) ? url.substring(lastDot).toLowerCase() : "";
  12926. var isDDS = this.getCaps().s3tc && (extension.indexOf(".dds") === 0);
  12927. var isTGA = (extension.indexOf(".tga") === 0);
  12928. // determine if a ktx file should be substituted
  12929. var isKTX = false;
  12930. if (this._textureFormatInUse && !isBase64 && !fallBack) {
  12931. url = url.substring(0, lastDot) + this._textureFormatInUse;
  12932. isKTX = true;
  12933. }
  12934. if (scene) {
  12935. scene._addPendingData(texture);
  12936. }
  12937. texture.url = url;
  12938. texture.generateMipMaps = !noMipmap;
  12939. texture.samplingMode = samplingMode;
  12940. texture.invertY = invertY;
  12941. if (!this._doNotHandleContextLost) {
  12942. // Keep a link to the buffer only if we plan to handle context lost
  12943. texture._buffer = buffer;
  12944. }
  12945. var onLoadObserver = null;
  12946. if (onLoad && !fallBack) {
  12947. onLoadObserver = texture.onLoadedObservable.add(onLoad);
  12948. }
  12949. if (!fallBack)
  12950. this._internalTexturesCache.push(texture);
  12951. var onerror = function (message, exception) {
  12952. if (scene) {
  12953. scene._removePendingData(texture);
  12954. }
  12955. if (onLoadObserver) {
  12956. texture.onLoadedObservable.remove(onLoadObserver);
  12957. }
  12958. // fallback for when compressed file not found to try again. For instance, etc1 does not have an alpha capable type
  12959. if (isKTX) {
  12960. _this.createTexture(urlArg, noMipmap, invertY, scene, samplingMode, null, onError, buffer, texture);
  12961. }
  12962. else if (BABYLON.Tools.UseFallbackTexture) {
  12963. _this.createTexture(BABYLON.Tools.fallbackTexture, noMipmap, invertY, scene, samplingMode, null, onError, buffer, texture);
  12964. }
  12965. if (onError) {
  12966. onError(message || "Unknown error", exception);
  12967. }
  12968. };
  12969. var callback = null;
  12970. // processing for non-image formats
  12971. if (isKTX || isTGA || isDDS) {
  12972. if (isKTX) {
  12973. callback = function (data) {
  12974. var ktx = new BABYLON.KhronosTextureContainer(data, 1);
  12975. _this._prepareWebGLTexture(texture, scene, ktx.pixelWidth, ktx.pixelHeight, invertY, false, true, function () {
  12976. ktx.uploadLevels(_this._gl, !noMipmap);
  12977. return false;
  12978. }, samplingMode);
  12979. };
  12980. }
  12981. else if (isTGA) {
  12982. callback = function (arrayBuffer) {
  12983. var data = new Uint8Array(arrayBuffer);
  12984. var header = BABYLON.TGATools.GetTGAHeader(data);
  12985. _this._prepareWebGLTexture(texture, scene, header.width, header.height, invertY, noMipmap, false, function () {
  12986. BABYLON.TGATools.UploadContent(_this._gl, data);
  12987. return false;
  12988. }, samplingMode);
  12989. };
  12990. }
  12991. else if (isDDS) {
  12992. callback = function (data) {
  12993. var info = BABYLON.DDSTools.GetDDSInfo(data);
  12994. var loadMipmap = (info.isRGB || info.isLuminance || info.mipmapCount > 1) && !noMipmap && ((info.width >> (info.mipmapCount - 1)) === 1);
  12995. _this._prepareWebGLTexture(texture, scene, info.width, info.height, invertY, !loadMipmap, info.isFourCC, function () {
  12996. BABYLON.DDSTools.UploadDDSLevels(_this, _this._gl, data, info, loadMipmap, 1);
  12997. return false;
  12998. }, samplingMode);
  12999. };
  13000. }
  13001. if (!buffer) {
  13002. this._loadFile(url, function (data) {
  13003. if (callback) {
  13004. callback(data);
  13005. }
  13006. }, undefined, scene ? scene.database : undefined, true, function (request, exception) {
  13007. onerror("Unable to load " + (request ? request.responseURL : url, exception));
  13008. });
  13009. }
  13010. else {
  13011. if (callback) {
  13012. callback(buffer);
  13013. }
  13014. }
  13015. // image format processing
  13016. }
  13017. else {
  13018. var onload = function (img) {
  13019. if (fromBlob && !_this._doNotHandleContextLost) {
  13020. // We need to store the image if we need to rebuild the texture
  13021. // in case of a webgl context lost
  13022. texture._buffer = img;
  13023. }
  13024. _this._prepareWebGLTexture(texture, scene, img.width, img.height, invertY, noMipmap, false, function (potWidth, potHeight, continuationCallback) {
  13025. var gl = _this._gl;
  13026. var isPot = (img.width === potWidth && img.height === potHeight);
  13027. var internalFormat = format ? _this._getInternalFormat(format) : ((extension === ".jpg") ? gl.RGB : gl.RGBA);
  13028. if (isPot) {
  13029. gl.texImage2D(gl.TEXTURE_2D, 0, internalFormat, internalFormat, gl.UNSIGNED_BYTE, img);
  13030. return false;
  13031. }
  13032. // Using shaders to rescale because canvas.drawImage is lossy
  13033. var source = new BABYLON.InternalTexture(_this, BABYLON.InternalTexture.DATASOURCE_TEMP);
  13034. _this._bindTextureDirectly(gl.TEXTURE_2D, source, true);
  13035. gl.texImage2D(gl.TEXTURE_2D, 0, internalFormat, internalFormat, gl.UNSIGNED_BYTE, img);
  13036. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  13037. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.LINEAR);
  13038. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  13039. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  13040. _this._rescaleTexture(source, texture, scene, internalFormat, function () {
  13041. _this._releaseTexture(source);
  13042. _this._bindTextureDirectly(gl.TEXTURE_2D, texture, true);
  13043. continuationCallback();
  13044. });
  13045. return true;
  13046. }, samplingMode);
  13047. };
  13048. if (!fromData || isBase64)
  13049. if (buffer instanceof HTMLImageElement) {
  13050. onload(buffer);
  13051. }
  13052. else {
  13053. BABYLON.Tools.LoadImage(url, onload, onerror, scene ? scene.database : null);
  13054. }
  13055. else if (buffer instanceof Array || typeof buffer === "string" || buffer instanceof ArrayBuffer)
  13056. BABYLON.Tools.LoadImage(buffer, onload, onerror, scene ? scene.database : null);
  13057. else
  13058. onload(buffer);
  13059. }
  13060. return texture;
  13061. };
  13062. Engine.prototype._rescaleTexture = function (source, destination, scene, internalFormat, onComplete) {
  13063. var _this = this;
  13064. var rtt = this.createRenderTargetTexture({
  13065. width: destination.width,
  13066. height: destination.height,
  13067. }, {
  13068. generateMipMaps: false,
  13069. type: Engine.TEXTURETYPE_UNSIGNED_INT,
  13070. samplingMode: BABYLON.Texture.BILINEAR_SAMPLINGMODE,
  13071. generateDepthBuffer: false,
  13072. generateStencilBuffer: false
  13073. });
  13074. if (!this._rescalePostProcess) {
  13075. this._rescalePostProcess = new BABYLON.PassPostProcess("rescale", 1, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this, false, Engine.TEXTURETYPE_UNSIGNED_INT);
  13076. }
  13077. this._rescalePostProcess.getEffect().executeWhenCompiled(function () {
  13078. _this._rescalePostProcess.onApply = function (effect) {
  13079. effect._bindTexture("textureSampler", source);
  13080. };
  13081. var hostingScene = scene;
  13082. if (!hostingScene) {
  13083. hostingScene = _this.scenes[_this.scenes.length - 1];
  13084. }
  13085. hostingScene.postProcessManager.directRender([_this._rescalePostProcess], rtt, true);
  13086. _this._bindTextureDirectly(_this._gl.TEXTURE_2D, destination, true);
  13087. _this._gl.copyTexImage2D(_this._gl.TEXTURE_2D, 0, internalFormat, 0, 0, destination.width, destination.height, 0);
  13088. _this.unBindFramebuffer(rtt);
  13089. _this._releaseTexture(rtt);
  13090. if (onComplete) {
  13091. onComplete();
  13092. }
  13093. });
  13094. };
  13095. Engine.prototype._getInternalFormat = function (format) {
  13096. var internalFormat = this._gl.RGBA;
  13097. switch (format) {
  13098. case Engine.TEXTUREFORMAT_ALPHA:
  13099. internalFormat = this._gl.ALPHA;
  13100. break;
  13101. case Engine.TEXTUREFORMAT_LUMINANCE:
  13102. internalFormat = this._gl.LUMINANCE;
  13103. break;
  13104. case Engine.TEXTUREFORMAT_LUMINANCE_ALPHA:
  13105. internalFormat = this._gl.LUMINANCE_ALPHA;
  13106. break;
  13107. case Engine.TEXTUREFORMAT_RGB:
  13108. case Engine.TEXTUREFORMAT_RGB32F:
  13109. internalFormat = this._gl.RGB;
  13110. break;
  13111. case Engine.TEXTUREFORMAT_RGBA:
  13112. case Engine.TEXTUREFORMAT_RGBA32F:
  13113. internalFormat = this._gl.RGBA;
  13114. break;
  13115. case Engine.TEXTUREFORMAT_R32F:
  13116. internalFormat = this._gl.RED;
  13117. break;
  13118. case Engine.TEXTUREFORMAT_RG32F:
  13119. internalFormat = this._gl.RG;
  13120. break;
  13121. }
  13122. return internalFormat;
  13123. };
  13124. Engine.prototype.updateRawTexture = function (texture, data, format, invertY, compression, type) {
  13125. if (compression === void 0) { compression = null; }
  13126. if (type === void 0) { type = Engine.TEXTURETYPE_UNSIGNED_INT; }
  13127. if (!texture) {
  13128. return;
  13129. }
  13130. var internalSizedFomat = this._getRGBABufferInternalSizedFormat(type, format);
  13131. var internalFormat = this._getInternalFormat(format);
  13132. var textureType = this._getWebGLTextureType(type);
  13133. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture, true);
  13134. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY === undefined ? 1 : (invertY ? 1 : 0));
  13135. if (!this._doNotHandleContextLost) {
  13136. texture._bufferView = data;
  13137. texture.format = format;
  13138. texture.type = type;
  13139. texture.invertY = invertY;
  13140. texture._compression = compression;
  13141. }
  13142. if (texture.width % 4 !== 0) {
  13143. this._gl.pixelStorei(this._gl.UNPACK_ALIGNMENT, 1);
  13144. }
  13145. if (compression && data) {
  13146. this._gl.compressedTexImage2D(this._gl.TEXTURE_2D, 0, this.getCaps().s3tc[compression], texture.width, texture.height, 0, data);
  13147. }
  13148. else {
  13149. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, internalSizedFomat, texture.width, texture.height, 0, internalFormat, textureType, data);
  13150. }
  13151. if (texture.generateMipMaps) {
  13152. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  13153. }
  13154. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  13155. // this.resetTextureCache();
  13156. texture.isReady = true;
  13157. };
  13158. Engine.prototype.createRawTexture = function (data, width, height, format, generateMipMaps, invertY, samplingMode, compression, type) {
  13159. if (compression === void 0) { compression = null; }
  13160. if (type === void 0) { type = Engine.TEXTURETYPE_UNSIGNED_INT; }
  13161. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_RAW);
  13162. texture.baseWidth = width;
  13163. texture.baseHeight = height;
  13164. texture.width = width;
  13165. texture.height = height;
  13166. texture.format = format;
  13167. texture.generateMipMaps = generateMipMaps;
  13168. texture.samplingMode = samplingMode;
  13169. texture.invertY = invertY;
  13170. texture._compression = compression;
  13171. texture.type = type;
  13172. if (!this._doNotHandleContextLost) {
  13173. texture._bufferView = data;
  13174. }
  13175. this.updateRawTexture(texture, data, format, invertY, compression, type);
  13176. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture, true);
  13177. // Filters
  13178. var filters = getSamplingParameters(samplingMode, generateMipMaps, this._gl);
  13179. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  13180. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  13181. if (generateMipMaps) {
  13182. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  13183. }
  13184. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  13185. this._internalTexturesCache.push(texture);
  13186. return texture;
  13187. };
  13188. Engine.prototype.createDynamicTexture = function (width, height, generateMipMaps, samplingMode) {
  13189. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_DYNAMIC);
  13190. texture.baseWidth = width;
  13191. texture.baseHeight = height;
  13192. if (generateMipMaps) {
  13193. width = this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(width, this._caps.maxTextureSize) : width;
  13194. height = this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(height, this._caps.maxTextureSize) : height;
  13195. }
  13196. // this.resetTextureCache();
  13197. texture.width = width;
  13198. texture.height = height;
  13199. texture.isReady = false;
  13200. texture.generateMipMaps = generateMipMaps;
  13201. texture.samplingMode = samplingMode;
  13202. this.updateTextureSamplingMode(samplingMode, texture);
  13203. this._internalTexturesCache.push(texture);
  13204. return texture;
  13205. };
  13206. Engine.prototype.updateTextureSamplingMode = function (samplingMode, texture) {
  13207. var filters = getSamplingParameters(samplingMode, texture.generateMipMaps, this._gl);
  13208. if (texture.isCube) {
  13209. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, texture, true);
  13210. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  13211. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_MIN_FILTER, filters.min);
  13212. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  13213. }
  13214. else if (texture.is3D) {
  13215. this._bindTextureDirectly(this._gl.TEXTURE_3D, texture, true);
  13216. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  13217. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  13218. this._bindTextureDirectly(this._gl.TEXTURE_3D, null);
  13219. }
  13220. else {
  13221. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture, true);
  13222. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  13223. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  13224. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  13225. }
  13226. texture.samplingMode = samplingMode;
  13227. };
  13228. Engine.prototype.updateDynamicTexture = function (texture, canvas, invertY, premulAlpha, format) {
  13229. if (premulAlpha === void 0) { premulAlpha = false; }
  13230. if (!texture) {
  13231. return;
  13232. }
  13233. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture, true);
  13234. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY ? 1 : 0);
  13235. if (premulAlpha) {
  13236. this._gl.pixelStorei(this._gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, 1);
  13237. }
  13238. var internalFormat = format ? this._getInternalFormat(format) : this._gl.RGBA;
  13239. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, internalFormat, internalFormat, this._gl.UNSIGNED_BYTE, canvas);
  13240. if (texture.generateMipMaps) {
  13241. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  13242. }
  13243. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  13244. if (premulAlpha) {
  13245. this._gl.pixelStorei(this._gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, 0);
  13246. }
  13247. texture.isReady = true;
  13248. };
  13249. Engine.prototype.updateVideoTexture = function (texture, video, invertY) {
  13250. if (!texture || texture._isDisabled) {
  13251. return;
  13252. }
  13253. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture, true);
  13254. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY ? 0 : 1); // Video are upside down by default
  13255. try {
  13256. // Testing video texture support
  13257. if (this._videoTextureSupported === undefined) {
  13258. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, video);
  13259. if (this._gl.getError() !== 0) {
  13260. this._videoTextureSupported = false;
  13261. }
  13262. else {
  13263. this._videoTextureSupported = true;
  13264. }
  13265. }
  13266. // Copy video through the current working canvas if video texture is not supported
  13267. if (!this._videoTextureSupported) {
  13268. if (!texture._workingCanvas) {
  13269. texture._workingCanvas = document.createElement("canvas");
  13270. var context = texture._workingCanvas.getContext("2d");
  13271. if (!context) {
  13272. throw new Error("Unable to get 2d context");
  13273. }
  13274. texture._workingContext = context;
  13275. texture._workingCanvas.width = texture.width;
  13276. texture._workingCanvas.height = texture.height;
  13277. }
  13278. texture._workingContext.drawImage(video, 0, 0, video.videoWidth, video.videoHeight, 0, 0, texture.width, texture.height);
  13279. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, texture._workingCanvas);
  13280. }
  13281. else {
  13282. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, video);
  13283. }
  13284. if (texture.generateMipMaps) {
  13285. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  13286. }
  13287. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  13288. // this.resetTextureCache();
  13289. texture.isReady = true;
  13290. }
  13291. catch (ex) {
  13292. // Something unexpected
  13293. // Let's disable the texture
  13294. texture._isDisabled = true;
  13295. }
  13296. };
  13297. /**
  13298. * Updates a depth texture Comparison Mode and Function.
  13299. * If the comparison Function is equal to 0, the mode will be set to none.
  13300. * Otherwise, this only works in webgl 2 and requires a shadow sampler in the shader.
  13301. * @param texture The texture to set the comparison function for
  13302. * @param comparisonFunction The comparison function to set, 0 if no comparison required
  13303. */
  13304. Engine.prototype.updateTextureComparisonFunction = function (texture, comparisonFunction) {
  13305. if (this.webGLVersion === 1) {
  13306. BABYLON.Tools.Error("WebGL 1 does not support texture comparison.");
  13307. return;
  13308. }
  13309. var gl = this._gl;
  13310. if (texture.isCube) {
  13311. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, texture, true);
  13312. if (comparisonFunction === 0) {
  13313. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_COMPARE_FUNC, Engine.LEQUAL);
  13314. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_COMPARE_MODE, gl.NONE);
  13315. }
  13316. else {
  13317. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_COMPARE_FUNC, comparisonFunction);
  13318. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_COMPARE_MODE, gl.COMPARE_REF_TO_TEXTURE);
  13319. }
  13320. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  13321. }
  13322. else {
  13323. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture, true);
  13324. if (comparisonFunction === 0) {
  13325. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_COMPARE_FUNC, Engine.LEQUAL);
  13326. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_COMPARE_MODE, gl.NONE);
  13327. }
  13328. else {
  13329. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_COMPARE_FUNC, comparisonFunction);
  13330. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_COMPARE_MODE, gl.COMPARE_REF_TO_TEXTURE);
  13331. }
  13332. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  13333. }
  13334. texture._comparisonFunction = comparisonFunction;
  13335. };
  13336. Engine.prototype._setupDepthStencilTexture = function (internalTexture, size, generateStencil, bilinearFiltering, comparisonFunction) {
  13337. var width = size.width || size;
  13338. var height = size.height || size;
  13339. internalTexture.baseWidth = width;
  13340. internalTexture.baseHeight = height;
  13341. internalTexture.width = width;
  13342. internalTexture.height = height;
  13343. internalTexture.isReady = true;
  13344. internalTexture.samples = 1;
  13345. internalTexture.generateMipMaps = false;
  13346. internalTexture._generateDepthBuffer = true;
  13347. internalTexture._generateStencilBuffer = generateStencil;
  13348. internalTexture.samplingMode = bilinearFiltering ? BABYLON.Texture.NEAREST_SAMPLINGMODE : BABYLON.Texture.BILINEAR_SAMPLINGMODE;
  13349. internalTexture.type = Engine.TEXTURETYPE_UNSIGNED_INT;
  13350. internalTexture._comparisonFunction = comparisonFunction;
  13351. var gl = this._gl;
  13352. var target = internalTexture.isCube ? gl.TEXTURE_CUBE_MAP : gl.TEXTURE_2D;
  13353. var samplingParameters = getSamplingParameters(internalTexture.samplingMode, false, gl);
  13354. gl.texParameteri(target, gl.TEXTURE_MAG_FILTER, samplingParameters.mag);
  13355. gl.texParameteri(target, gl.TEXTURE_MIN_FILTER, samplingParameters.min);
  13356. gl.texParameteri(target, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  13357. gl.texParameteri(target, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  13358. if (comparisonFunction === 0) {
  13359. gl.texParameteri(target, gl.TEXTURE_COMPARE_FUNC, Engine.LEQUAL);
  13360. gl.texParameteri(target, gl.TEXTURE_COMPARE_MODE, gl.NONE);
  13361. }
  13362. else {
  13363. gl.texParameteri(target, gl.TEXTURE_COMPARE_FUNC, comparisonFunction);
  13364. gl.texParameteri(target, gl.TEXTURE_COMPARE_MODE, gl.COMPARE_REF_TO_TEXTURE);
  13365. }
  13366. };
  13367. /**
  13368. * Creates a depth stencil texture.
  13369. * This is only available in WebGL 2 or with the depth texture extension available.
  13370. * @param size The size of face edge in the texture.
  13371. * @param options The options defining the texture.
  13372. * @returns The texture
  13373. */
  13374. Engine.prototype.createDepthStencilTexture = function (size, options) {
  13375. var internalTexture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_DEPTHTEXTURE);
  13376. if (!this._caps.depthTextureExtension) {
  13377. BABYLON.Tools.Error("Depth texture is not supported by your browser or hardware.");
  13378. return internalTexture;
  13379. }
  13380. var internalOptions = __assign({ bilinearFiltering: false, comparisonFunction: 0, generateStencil: false }, options);
  13381. var gl = this._gl;
  13382. this._bindTextureDirectly(gl.TEXTURE_2D, internalTexture, true);
  13383. this._setupDepthStencilTexture(internalTexture, size, internalOptions.generateStencil, internalOptions.bilinearFiltering, internalOptions.comparisonFunction);
  13384. if (this.webGLVersion > 1) {
  13385. if (internalOptions.generateStencil) {
  13386. gl.texImage2D(gl.TEXTURE_2D, 0, gl.DEPTH24_STENCIL8, internalTexture.width, internalTexture.height, 0, gl.DEPTH_STENCIL, gl.UNSIGNED_INT_24_8, null);
  13387. }
  13388. else {
  13389. gl.texImage2D(gl.TEXTURE_2D, 0, gl.DEPTH_COMPONENT24, internalTexture.width, internalTexture.height, 0, gl.DEPTH_COMPONENT, gl.UNSIGNED_INT, null);
  13390. }
  13391. }
  13392. else {
  13393. if (internalOptions.generateStencil) {
  13394. gl.texImage2D(gl.TEXTURE_2D, 0, gl.DEPTH_STENCIL, internalTexture.width, internalTexture.height, 0, gl.DEPTH_STENCIL, gl.UNSIGNED_INT_24_8, null);
  13395. }
  13396. else {
  13397. gl.texImage2D(gl.TEXTURE_2D, 0, gl.DEPTH_COMPONENT, internalTexture.width, internalTexture.height, 0, gl.DEPTH_COMPONENT, gl.UNSIGNED_INT, null);
  13398. }
  13399. }
  13400. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  13401. return internalTexture;
  13402. };
  13403. /**
  13404. * Creates a depth stencil cube texture.
  13405. * This is only available in WebGL 2.
  13406. * @param size The size of face edge in the cube texture.
  13407. * @param options The options defining the cube texture.
  13408. * @returns The cube texture
  13409. */
  13410. Engine.prototype.createDepthStencilCubeTexture = function (size, options) {
  13411. var internalTexture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_UNKNOWN);
  13412. internalTexture.isCube = true;
  13413. if (this.webGLVersion === 1) {
  13414. BABYLON.Tools.Error("Depth cube texture is not supported by WebGL 1.");
  13415. return internalTexture;
  13416. }
  13417. var internalOptions = __assign({ bilinearFiltering: false, comparisonFunction: 0, generateStencil: false }, options);
  13418. var gl = this._gl;
  13419. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, internalTexture, true);
  13420. this._setupDepthStencilTexture(internalTexture, size, internalOptions.generateStencil, internalOptions.bilinearFiltering, internalOptions.comparisonFunction);
  13421. // Create the depth/stencil buffer
  13422. for (var face = 0; face < 6; face++) {
  13423. if (internalOptions.generateStencil) {
  13424. 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);
  13425. }
  13426. else {
  13427. gl.texImage2D(gl.TEXTURE_CUBE_MAP_POSITIVE_X + face, 0, gl.DEPTH_COMPONENT24, size, size, 0, gl.DEPTH_COMPONENT, gl.UNSIGNED_INT, null);
  13428. }
  13429. }
  13430. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  13431. return internalTexture;
  13432. };
  13433. /**
  13434. * Sets the frame buffer Depth / Stencil attachement of the render target to the defined depth stencil texture.
  13435. * @param renderTarget The render target to set the frame buffer for
  13436. */
  13437. Engine.prototype.setFrameBufferDepthStencilTexture = function (renderTarget) {
  13438. // Create the framebuffer
  13439. var internalTexture = renderTarget.getInternalTexture();
  13440. if (!internalTexture || !internalTexture._framebuffer || !renderTarget.depthStencilTexture) {
  13441. return;
  13442. }
  13443. var gl = this._gl;
  13444. var depthStencilTexture = renderTarget.depthStencilTexture;
  13445. this.bindUnboundFramebuffer(internalTexture._framebuffer);
  13446. if (depthStencilTexture.isCube) {
  13447. if (depthStencilTexture._generateStencilBuffer) {
  13448. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_STENCIL_ATTACHMENT, gl.TEXTURE_CUBE_MAP_POSITIVE_X, depthStencilTexture, 0);
  13449. }
  13450. else {
  13451. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.TEXTURE_CUBE_MAP_POSITIVE_X, depthStencilTexture, 0);
  13452. }
  13453. }
  13454. else {
  13455. if (depthStencilTexture._generateStencilBuffer) {
  13456. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_STENCIL_ATTACHMENT, gl.TEXTURE_2D, depthStencilTexture, 0);
  13457. }
  13458. else {
  13459. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.TEXTURE_2D, depthStencilTexture, 0);
  13460. }
  13461. }
  13462. this.bindUnboundFramebuffer(null);
  13463. };
  13464. Engine.prototype.createRenderTargetTexture = function (size, options) {
  13465. var fullOptions = new RenderTargetCreationOptions();
  13466. if (options !== undefined && typeof options === "object") {
  13467. fullOptions.generateMipMaps = options.generateMipMaps;
  13468. fullOptions.generateDepthBuffer = options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  13469. fullOptions.generateStencilBuffer = fullOptions.generateDepthBuffer && options.generateStencilBuffer;
  13470. fullOptions.type = options.type === undefined ? Engine.TEXTURETYPE_UNSIGNED_INT : options.type;
  13471. fullOptions.samplingMode = options.samplingMode === undefined ? BABYLON.Texture.TRILINEAR_SAMPLINGMODE : options.samplingMode;
  13472. }
  13473. else {
  13474. fullOptions.generateMipMaps = options;
  13475. fullOptions.generateDepthBuffer = true;
  13476. fullOptions.generateStencilBuffer = false;
  13477. fullOptions.type = Engine.TEXTURETYPE_UNSIGNED_INT;
  13478. fullOptions.samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE;
  13479. }
  13480. if (fullOptions.type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloatLinearFiltering) {
  13481. // if floating point linear (gl.FLOAT) then force to NEAREST_SAMPLINGMODE
  13482. fullOptions.samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  13483. }
  13484. else if (fullOptions.type === Engine.TEXTURETYPE_HALF_FLOAT && !this._caps.textureHalfFloatLinearFiltering) {
  13485. // if floating point linear (HALF_FLOAT) then force to NEAREST_SAMPLINGMODE
  13486. fullOptions.samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  13487. }
  13488. var gl = this._gl;
  13489. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_RENDERTARGET);
  13490. this._bindTextureDirectly(gl.TEXTURE_2D, texture, true);
  13491. var width = size.width || size;
  13492. var height = size.height || size;
  13493. var filters = getSamplingParameters(fullOptions.samplingMode, fullOptions.generateMipMaps ? true : false, gl);
  13494. if (fullOptions.type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloat) {
  13495. fullOptions.type = Engine.TEXTURETYPE_UNSIGNED_INT;
  13496. BABYLON.Tools.Warn("Float textures are not supported. Render target forced to TEXTURETYPE_UNSIGNED_BYTE type");
  13497. }
  13498. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  13499. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  13500. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  13501. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  13502. gl.texImage2D(gl.TEXTURE_2D, 0, this._getRGBABufferInternalSizedFormat(fullOptions.type), width, height, 0, gl.RGBA, this._getWebGLTextureType(fullOptions.type), null);
  13503. // Create the framebuffer
  13504. var framebuffer = gl.createFramebuffer();
  13505. this.bindUnboundFramebuffer(framebuffer);
  13506. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texture._webGLTexture, 0);
  13507. texture._depthStencilBuffer = this._setupFramebufferDepthAttachments(fullOptions.generateStencilBuffer ? true : false, fullOptions.generateDepthBuffer, width, height);
  13508. if (fullOptions.generateMipMaps) {
  13509. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  13510. }
  13511. // Unbind
  13512. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  13513. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  13514. this.bindUnboundFramebuffer(null);
  13515. texture._framebuffer = framebuffer;
  13516. texture.baseWidth = width;
  13517. texture.baseHeight = height;
  13518. texture.width = width;
  13519. texture.height = height;
  13520. texture.isReady = true;
  13521. texture.samples = 1;
  13522. texture.generateMipMaps = fullOptions.generateMipMaps ? true : false;
  13523. texture.samplingMode = fullOptions.samplingMode;
  13524. texture.type = fullOptions.type;
  13525. texture._generateDepthBuffer = fullOptions.generateDepthBuffer;
  13526. texture._generateStencilBuffer = fullOptions.generateStencilBuffer ? true : false;
  13527. // this.resetTextureCache();
  13528. this._internalTexturesCache.push(texture);
  13529. return texture;
  13530. };
  13531. Engine.prototype.createMultipleRenderTarget = function (size, options) {
  13532. var generateMipMaps = false;
  13533. var generateDepthBuffer = true;
  13534. var generateStencilBuffer = false;
  13535. var generateDepthTexture = false;
  13536. var textureCount = 1;
  13537. var defaultType = Engine.TEXTURETYPE_UNSIGNED_INT;
  13538. var defaultSamplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE;
  13539. var types = [], samplingModes = [];
  13540. if (options !== undefined) {
  13541. generateMipMaps = options.generateMipMaps;
  13542. generateDepthBuffer = options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  13543. generateStencilBuffer = options.generateStencilBuffer;
  13544. generateDepthTexture = options.generateDepthTexture;
  13545. textureCount = options.textureCount || 1;
  13546. if (options.types) {
  13547. types = options.types;
  13548. }
  13549. if (options.samplingModes) {
  13550. samplingModes = options.samplingModes;
  13551. }
  13552. }
  13553. var gl = this._gl;
  13554. // Create the framebuffer
  13555. var framebuffer = gl.createFramebuffer();
  13556. this.bindUnboundFramebuffer(framebuffer);
  13557. var width = size.width || size;
  13558. var height = size.height || size;
  13559. var textures = [];
  13560. var attachments = [];
  13561. var depthStencilBuffer = this._setupFramebufferDepthAttachments(generateStencilBuffer, generateDepthBuffer, width, height);
  13562. for (var i = 0; i < textureCount; i++) {
  13563. var samplingMode = samplingModes[i] || defaultSamplingMode;
  13564. var type = types[i] || defaultType;
  13565. if (type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloatLinearFiltering) {
  13566. // if floating point linear (gl.FLOAT) then force to NEAREST_SAMPLINGMODE
  13567. samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  13568. }
  13569. else if (type === Engine.TEXTURETYPE_HALF_FLOAT && !this._caps.textureHalfFloatLinearFiltering) {
  13570. // if floating point linear (HALF_FLOAT) then force to NEAREST_SAMPLINGMODE
  13571. samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  13572. }
  13573. var filters = getSamplingParameters(samplingMode, generateMipMaps, gl);
  13574. if (type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloat) {
  13575. type = Engine.TEXTURETYPE_UNSIGNED_INT;
  13576. BABYLON.Tools.Warn("Float textures are not supported. Render target forced to TEXTURETYPE_UNSIGNED_BYTE type");
  13577. }
  13578. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_MULTIRENDERTARGET);
  13579. var attachment = gl[this.webGLVersion > 1 ? "COLOR_ATTACHMENT" + i : "COLOR_ATTACHMENT" + i + "_WEBGL"];
  13580. textures.push(texture);
  13581. attachments.push(attachment);
  13582. gl.activeTexture(gl["TEXTURE" + i]);
  13583. gl.bindTexture(gl.TEXTURE_2D, texture._webGLTexture);
  13584. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  13585. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  13586. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  13587. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  13588. gl.texImage2D(gl.TEXTURE_2D, 0, this._getRGBABufferInternalSizedFormat(type), width, height, 0, gl.RGBA, this._getWebGLTextureType(type), null);
  13589. gl.framebufferTexture2D(gl.DRAW_FRAMEBUFFER, attachment, gl.TEXTURE_2D, texture._webGLTexture, 0);
  13590. if (generateMipMaps) {
  13591. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  13592. }
  13593. // Unbind
  13594. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  13595. texture._framebuffer = framebuffer;
  13596. texture._depthStencilBuffer = depthStencilBuffer;
  13597. texture.baseWidth = width;
  13598. texture.baseHeight = height;
  13599. texture.width = width;
  13600. texture.height = height;
  13601. texture.isReady = true;
  13602. texture.samples = 1;
  13603. texture.generateMipMaps = generateMipMaps;
  13604. texture.samplingMode = samplingMode;
  13605. texture.type = type;
  13606. texture._generateDepthBuffer = generateDepthBuffer;
  13607. texture._generateStencilBuffer = generateStencilBuffer;
  13608. texture._attachments = attachments;
  13609. this._internalTexturesCache.push(texture);
  13610. }
  13611. if (generateDepthTexture && this._caps.depthTextureExtension) {
  13612. // Depth texture
  13613. var depthTexture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_MULTIRENDERTARGET);
  13614. gl.activeTexture(gl.TEXTURE0);
  13615. gl.bindTexture(gl.TEXTURE_2D, depthTexture._webGLTexture);
  13616. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  13617. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  13618. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  13619. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  13620. 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);
  13621. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.TEXTURE_2D, depthTexture._webGLTexture, 0);
  13622. depthTexture._framebuffer = framebuffer;
  13623. depthTexture.baseWidth = width;
  13624. depthTexture.baseHeight = height;
  13625. depthTexture.width = width;
  13626. depthTexture.height = height;
  13627. depthTexture.isReady = true;
  13628. depthTexture.samples = 1;
  13629. depthTexture.generateMipMaps = generateMipMaps;
  13630. depthTexture.samplingMode = gl.NEAREST;
  13631. depthTexture._generateDepthBuffer = generateDepthBuffer;
  13632. depthTexture._generateStencilBuffer = generateStencilBuffer;
  13633. textures.push(depthTexture);
  13634. this._internalTexturesCache.push(depthTexture);
  13635. }
  13636. gl.drawBuffers(attachments);
  13637. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  13638. this.bindUnboundFramebuffer(null);
  13639. this.resetTextureCache();
  13640. return textures;
  13641. };
  13642. Engine.prototype._setupFramebufferDepthAttachments = function (generateStencilBuffer, generateDepthBuffer, width, height, samples) {
  13643. if (samples === void 0) { samples = 1; }
  13644. var depthStencilBuffer = null;
  13645. var gl = this._gl;
  13646. // Create the depth/stencil buffer
  13647. if (generateStencilBuffer) {
  13648. depthStencilBuffer = gl.createRenderbuffer();
  13649. gl.bindRenderbuffer(gl.RENDERBUFFER, depthStencilBuffer);
  13650. if (samples > 1) {
  13651. gl.renderbufferStorageMultisample(gl.RENDERBUFFER, samples, gl.DEPTH24_STENCIL8, width, height);
  13652. }
  13653. else {
  13654. gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_STENCIL, width, height);
  13655. }
  13656. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.DEPTH_STENCIL_ATTACHMENT, gl.RENDERBUFFER, depthStencilBuffer);
  13657. }
  13658. else if (generateDepthBuffer) {
  13659. depthStencilBuffer = gl.createRenderbuffer();
  13660. gl.bindRenderbuffer(gl.RENDERBUFFER, depthStencilBuffer);
  13661. if (samples > 1) {
  13662. gl.renderbufferStorageMultisample(gl.RENDERBUFFER, samples, gl.DEPTH_COMPONENT16, width, height);
  13663. }
  13664. else {
  13665. gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_COMPONENT16, width, height);
  13666. }
  13667. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.RENDERBUFFER, depthStencilBuffer);
  13668. }
  13669. return depthStencilBuffer;
  13670. };
  13671. Engine.prototype.updateRenderTargetTextureSampleCount = function (texture, samples) {
  13672. if (this.webGLVersion < 2 || !texture) {
  13673. return 1;
  13674. }
  13675. if (texture.samples === samples) {
  13676. return samples;
  13677. }
  13678. var gl = this._gl;
  13679. samples = Math.min(samples, gl.getParameter(gl.MAX_SAMPLES));
  13680. // Dispose previous render buffers
  13681. if (texture._depthStencilBuffer) {
  13682. gl.deleteRenderbuffer(texture._depthStencilBuffer);
  13683. texture._depthStencilBuffer = null;
  13684. }
  13685. if (texture._MSAAFramebuffer) {
  13686. gl.deleteFramebuffer(texture._MSAAFramebuffer);
  13687. texture._MSAAFramebuffer = null;
  13688. }
  13689. if (texture._MSAARenderBuffer) {
  13690. gl.deleteRenderbuffer(texture._MSAARenderBuffer);
  13691. texture._MSAARenderBuffer = null;
  13692. }
  13693. if (samples > 1) {
  13694. var framebuffer = gl.createFramebuffer();
  13695. if (!framebuffer) {
  13696. throw new Error("Unable to create multi sampled framebuffer");
  13697. }
  13698. texture._MSAAFramebuffer = framebuffer;
  13699. this.bindUnboundFramebuffer(texture._MSAAFramebuffer);
  13700. var colorRenderbuffer = gl.createRenderbuffer();
  13701. if (!colorRenderbuffer) {
  13702. throw new Error("Unable to create multi sampled framebuffer");
  13703. }
  13704. gl.bindRenderbuffer(gl.RENDERBUFFER, colorRenderbuffer);
  13705. gl.renderbufferStorageMultisample(gl.RENDERBUFFER, samples, this._getRGBAMultiSampleBufferFormat(texture.type), texture.width, texture.height);
  13706. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.RENDERBUFFER, colorRenderbuffer);
  13707. texture._MSAARenderBuffer = colorRenderbuffer;
  13708. }
  13709. else {
  13710. this.bindUnboundFramebuffer(texture._framebuffer);
  13711. }
  13712. texture.samples = samples;
  13713. texture._depthStencilBuffer = this._setupFramebufferDepthAttachments(texture._generateStencilBuffer, texture._generateDepthBuffer, texture.width, texture.height, samples);
  13714. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  13715. this.bindUnboundFramebuffer(null);
  13716. return samples;
  13717. };
  13718. Engine.prototype.updateMultipleRenderTargetTextureSampleCount = function (textures, samples) {
  13719. if (this.webGLVersion < 2 || !textures || textures.length == 0) {
  13720. return 1;
  13721. }
  13722. if (textures[0].samples === samples) {
  13723. return samples;
  13724. }
  13725. var gl = this._gl;
  13726. samples = Math.min(samples, gl.getParameter(gl.MAX_SAMPLES));
  13727. // Dispose previous render buffers
  13728. if (textures[0]._depthStencilBuffer) {
  13729. gl.deleteRenderbuffer(textures[0]._depthStencilBuffer);
  13730. textures[0]._depthStencilBuffer = null;
  13731. }
  13732. if (textures[0]._MSAAFramebuffer) {
  13733. gl.deleteFramebuffer(textures[0]._MSAAFramebuffer);
  13734. textures[0]._MSAAFramebuffer = null;
  13735. }
  13736. for (var i = 0; i < textures.length; i++) {
  13737. if (textures[i]._MSAARenderBuffer) {
  13738. gl.deleteRenderbuffer(textures[i]._MSAARenderBuffer);
  13739. textures[i]._MSAARenderBuffer = null;
  13740. }
  13741. }
  13742. if (samples > 1) {
  13743. var framebuffer = gl.createFramebuffer();
  13744. if (!framebuffer) {
  13745. throw new Error("Unable to create multi sampled framebuffer");
  13746. }
  13747. this.bindUnboundFramebuffer(framebuffer);
  13748. var depthStencilBuffer = this._setupFramebufferDepthAttachments(textures[0]._generateStencilBuffer, textures[0]._generateDepthBuffer, textures[0].width, textures[0].height, samples);
  13749. var attachments = [];
  13750. for (var i = 0; i < textures.length; i++) {
  13751. var texture = textures[i];
  13752. var attachment = gl[this.webGLVersion > 1 ? "COLOR_ATTACHMENT" + i : "COLOR_ATTACHMENT" + i + "_WEBGL"];
  13753. var colorRenderbuffer = gl.createRenderbuffer();
  13754. if (!colorRenderbuffer) {
  13755. throw new Error("Unable to create multi sampled framebuffer");
  13756. }
  13757. gl.bindRenderbuffer(gl.RENDERBUFFER, colorRenderbuffer);
  13758. gl.renderbufferStorageMultisample(gl.RENDERBUFFER, samples, this._getRGBAMultiSampleBufferFormat(texture.type), texture.width, texture.height);
  13759. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, attachment, gl.RENDERBUFFER, colorRenderbuffer);
  13760. texture._MSAAFramebuffer = framebuffer;
  13761. texture._MSAARenderBuffer = colorRenderbuffer;
  13762. texture.samples = samples;
  13763. texture._depthStencilBuffer = depthStencilBuffer;
  13764. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  13765. attachments.push(attachment);
  13766. }
  13767. gl.drawBuffers(attachments);
  13768. }
  13769. else {
  13770. this.bindUnboundFramebuffer(textures[0]._framebuffer);
  13771. }
  13772. this.bindUnboundFramebuffer(null);
  13773. return samples;
  13774. };
  13775. Engine.prototype._uploadDataToTexture = function (target, lod, internalFormat, width, height, format, type, data) {
  13776. this._gl.texImage2D(target, lod, internalFormat, width, height, 0, format, type, data);
  13777. };
  13778. Engine.prototype._uploadCompressedDataToTexture = function (target, lod, internalFormat, width, height, data) {
  13779. this._gl.compressedTexImage2D(target, lod, internalFormat, width, height, 0, data);
  13780. };
  13781. Engine.prototype.createRenderTargetCubeTexture = function (size, options) {
  13782. var fullOptions = __assign({ generateMipMaps: true, generateDepthBuffer: true, generateStencilBuffer: false, type: Engine.TEXTURETYPE_UNSIGNED_INT, samplingMode: BABYLON.Texture.TRILINEAR_SAMPLINGMODE }, options);
  13783. fullOptions.generateStencilBuffer = fullOptions.generateDepthBuffer && fullOptions.generateStencilBuffer;
  13784. if (fullOptions.type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloatLinearFiltering) {
  13785. // if floating point linear (gl.FLOAT) then force to NEAREST_SAMPLINGMODE
  13786. fullOptions.samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  13787. }
  13788. else if (fullOptions.type === Engine.TEXTURETYPE_HALF_FLOAT && !this._caps.textureHalfFloatLinearFiltering) {
  13789. // if floating point linear (HALF_FLOAT) then force to NEAREST_SAMPLINGMODE
  13790. fullOptions.samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  13791. }
  13792. var gl = this._gl;
  13793. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_RENDERTARGET);
  13794. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  13795. var filters = getSamplingParameters(fullOptions.samplingMode, fullOptions.generateMipMaps, gl);
  13796. if (fullOptions.type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloat) {
  13797. fullOptions.type = Engine.TEXTURETYPE_UNSIGNED_INT;
  13798. BABYLON.Tools.Warn("Float textures are not supported. Cube render target forced to TEXTURETYPE_UNESIGNED_BYTE type");
  13799. }
  13800. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, filters.mag);
  13801. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, filters.min);
  13802. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  13803. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  13804. for (var face = 0; face < 6; face++) {
  13805. gl.texImage2D((gl.TEXTURE_CUBE_MAP_POSITIVE_X + face), 0, this._getRGBABufferInternalSizedFormat(fullOptions.type), size, size, 0, gl.RGBA, this._getWebGLTextureType(fullOptions.type), null);
  13806. }
  13807. // Create the framebuffer
  13808. var framebuffer = gl.createFramebuffer();
  13809. this.bindUnboundFramebuffer(framebuffer);
  13810. texture._depthStencilBuffer = this._setupFramebufferDepthAttachments(fullOptions.generateStencilBuffer, fullOptions.generateDepthBuffer, size, size);
  13811. // MipMaps
  13812. if (fullOptions.generateMipMaps) {
  13813. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  13814. }
  13815. // Unbind
  13816. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  13817. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  13818. this.bindUnboundFramebuffer(null);
  13819. texture._framebuffer = framebuffer;
  13820. texture.width = size;
  13821. texture.height = size;
  13822. texture.isReady = true;
  13823. texture.isCube = true;
  13824. texture.samples = 1;
  13825. texture.generateMipMaps = fullOptions.generateMipMaps;
  13826. texture.samplingMode = fullOptions.samplingMode;
  13827. texture.type = fullOptions.type;
  13828. texture._generateDepthBuffer = fullOptions.generateDepthBuffer;
  13829. texture._generateStencilBuffer = fullOptions.generateStencilBuffer;
  13830. this._internalTexturesCache.push(texture);
  13831. return texture;
  13832. };
  13833. Engine.prototype.createPrefilteredCubeTexture = function (rootUrl, scene, scale, offset, onLoad, onError, format, forcedExtension) {
  13834. var _this = this;
  13835. if (onLoad === void 0) { onLoad = null; }
  13836. if (onError === void 0) { onError = null; }
  13837. if (forcedExtension === void 0) { forcedExtension = null; }
  13838. var callback = function (loadData) {
  13839. if (!loadData) {
  13840. if (onLoad) {
  13841. onLoad(null);
  13842. }
  13843. return;
  13844. }
  13845. var texture = loadData.texture;
  13846. texture._dataSource = BABYLON.InternalTexture.DATASOURCE_CUBEPREFILTERED;
  13847. texture._lodGenerationScale = scale;
  13848. texture._lodGenerationOffset = offset;
  13849. if (_this._caps.textureLOD) {
  13850. // Do not add extra process if texture lod is supported.
  13851. if (onLoad) {
  13852. onLoad(texture);
  13853. }
  13854. return;
  13855. }
  13856. var mipSlices = 3;
  13857. var gl = _this._gl;
  13858. var width = loadData.width;
  13859. if (!width) {
  13860. return;
  13861. }
  13862. var textures = [];
  13863. for (var i = 0; i < mipSlices; i++) {
  13864. //compute LOD from even spacing in smoothness (matching shader calculation)
  13865. var smoothness = i / (mipSlices - 1);
  13866. var roughness = 1 - smoothness;
  13867. var minLODIndex = offset; // roughness = 0
  13868. var maxLODIndex = BABYLON.Scalar.Log2(width) * scale + offset; // roughness = 1
  13869. var lodIndex = minLODIndex + (maxLODIndex - minLODIndex) * roughness;
  13870. var mipmapIndex = Math.round(Math.min(Math.max(lodIndex, 0), maxLODIndex));
  13871. var glTextureFromLod = new BABYLON.InternalTexture(_this, BABYLON.InternalTexture.DATASOURCE_TEMP);
  13872. glTextureFromLod.isCube = true;
  13873. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, glTextureFromLod, true);
  13874. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  13875. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, gl.LINEAR);
  13876. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  13877. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  13878. if (loadData.isDDS) {
  13879. var info = loadData.info;
  13880. var data = loadData.data;
  13881. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, info.isCompressed ? 1 : 0);
  13882. BABYLON.DDSTools.UploadDDSLevels(_this, _this._gl, data, info, true, 6, mipmapIndex);
  13883. }
  13884. else {
  13885. BABYLON.Tools.Warn("DDS is the only prefiltered cube map supported so far.");
  13886. }
  13887. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  13888. // Wrap in a base texture for easy binding.
  13889. var lodTexture = new BABYLON.BaseTexture(scene);
  13890. lodTexture.isCube = true;
  13891. lodTexture._texture = glTextureFromLod;
  13892. glTextureFromLod.isReady = true;
  13893. textures.push(lodTexture);
  13894. }
  13895. texture._lodTextureHigh = textures[2];
  13896. texture._lodTextureMid = textures[1];
  13897. texture._lodTextureLow = textures[0];
  13898. if (onLoad) {
  13899. onLoad(texture);
  13900. }
  13901. };
  13902. return this.createCubeTexture(rootUrl, scene, null, false, callback, onError, format, forcedExtension);
  13903. };
  13904. Engine.prototype.createCubeTexture = function (rootUrl, scene, files, noMipmap, onLoad, onError, format, forcedExtension) {
  13905. var _this = this;
  13906. if (onLoad === void 0) { onLoad = null; }
  13907. if (onError === void 0) { onError = null; }
  13908. if (forcedExtension === void 0) { forcedExtension = null; }
  13909. var gl = this._gl;
  13910. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_CUBE);
  13911. texture.isCube = true;
  13912. texture.url = rootUrl;
  13913. texture.generateMipMaps = !noMipmap;
  13914. if (!this._doNotHandleContextLost) {
  13915. texture._extension = forcedExtension;
  13916. texture._files = files;
  13917. }
  13918. var isKTX = false;
  13919. var isDDS = false;
  13920. var lastDot = rootUrl.lastIndexOf('.');
  13921. var extension = forcedExtension ? forcedExtension : (lastDot > -1 ? rootUrl.substring(lastDot).toLowerCase() : "");
  13922. if (this._textureFormatInUse) {
  13923. extension = this._textureFormatInUse;
  13924. rootUrl = (lastDot > -1 ? rootUrl.substring(0, lastDot) : rootUrl) + this._textureFormatInUse;
  13925. isKTX = true;
  13926. }
  13927. else {
  13928. isDDS = (extension === ".dds");
  13929. }
  13930. var onerror = function (request, exception) {
  13931. if (onError && request) {
  13932. onError(request.status + " " + request.statusText, exception);
  13933. }
  13934. };
  13935. if (isKTX) {
  13936. this._loadFile(rootUrl, function (data) {
  13937. var ktx = new BABYLON.KhronosTextureContainer(data, 6);
  13938. var loadMipmap = ktx.numberOfMipmapLevels > 1 && !noMipmap;
  13939. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  13940. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 1);
  13941. ktx.uploadLevels(_this._gl, !noMipmap);
  13942. _this.setCubeMapTextureParams(gl, loadMipmap);
  13943. texture.width = ktx.pixelWidth;
  13944. texture.height = ktx.pixelHeight;
  13945. texture.isReady = true;
  13946. }, undefined, undefined, true, onerror);
  13947. }
  13948. else if (isDDS) {
  13949. if (files && files.length === 6) {
  13950. this._cascadeLoadFiles(scene, function (imgs) {
  13951. var info;
  13952. var loadMipmap = false;
  13953. var width = 0;
  13954. for (var index = 0; index < imgs.length; index++) {
  13955. var data = imgs[index];
  13956. info = BABYLON.DDSTools.GetDDSInfo(data);
  13957. loadMipmap = (info.isRGB || info.isLuminance || info.mipmapCount > 1) && !noMipmap;
  13958. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  13959. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, info.isCompressed ? 1 : 0);
  13960. BABYLON.DDSTools.UploadDDSLevels(_this, _this._gl, data, info, loadMipmap, 6, -1, index);
  13961. if (!noMipmap && !info.isFourCC && info.mipmapCount === 1) {
  13962. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  13963. }
  13964. texture.width = info.width;
  13965. texture.height = info.height;
  13966. texture.type = info.textureType;
  13967. width = info.width;
  13968. }
  13969. _this.setCubeMapTextureParams(gl, loadMipmap);
  13970. texture.isReady = true;
  13971. if (onLoad) {
  13972. onLoad({ isDDS: true, width: width, info: info, imgs: imgs, texture: texture });
  13973. }
  13974. }, files, onError);
  13975. }
  13976. else {
  13977. this._loadFile(rootUrl, function (data) {
  13978. var info = BABYLON.DDSTools.GetDDSInfo(data);
  13979. var loadMipmap = (info.isRGB || info.isLuminance || info.mipmapCount > 1) && !noMipmap;
  13980. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  13981. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, info.isCompressed ? 1 : 0);
  13982. BABYLON.DDSTools.UploadDDSLevels(_this, _this._gl, data, info, loadMipmap, 6);
  13983. if (!noMipmap && !info.isFourCC && info.mipmapCount === 1) {
  13984. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  13985. }
  13986. _this.setCubeMapTextureParams(gl, loadMipmap);
  13987. texture.width = info.width;
  13988. texture.height = info.height;
  13989. texture.isReady = true;
  13990. texture.type = info.textureType;
  13991. if (onLoad) {
  13992. onLoad({ isDDS: true, width: info.width, info: info, data: data, texture: texture });
  13993. }
  13994. }, undefined, undefined, true, onerror);
  13995. }
  13996. }
  13997. else {
  13998. if (!files) {
  13999. throw new Error("Cannot load cubemap because files were not defined");
  14000. }
  14001. cascadeLoadImgs(rootUrl, scene, function (imgs) {
  14002. var width = _this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(imgs[0].width, _this._caps.maxCubemapTextureSize) : imgs[0].width;
  14003. var height = width;
  14004. _this._prepareWorkingCanvas();
  14005. if (!_this._workingCanvas || !_this._workingContext) {
  14006. return;
  14007. }
  14008. _this._workingCanvas.width = width;
  14009. _this._workingCanvas.height = height;
  14010. var faces = [
  14011. gl.TEXTURE_CUBE_MAP_POSITIVE_X, gl.TEXTURE_CUBE_MAP_POSITIVE_Y, gl.TEXTURE_CUBE_MAP_POSITIVE_Z,
  14012. gl.TEXTURE_CUBE_MAP_NEGATIVE_X, gl.TEXTURE_CUBE_MAP_NEGATIVE_Y, gl.TEXTURE_CUBE_MAP_NEGATIVE_Z
  14013. ];
  14014. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  14015. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 0);
  14016. var internalFormat = format ? _this._getInternalFormat(format) : _this._gl.RGBA;
  14017. for (var index = 0; index < faces.length; index++) {
  14018. _this._workingContext.drawImage(imgs[index], 0, 0, imgs[index].width, imgs[index].height, 0, 0, width, height);
  14019. gl.texImage2D(faces[index], 0, internalFormat, internalFormat, gl.UNSIGNED_BYTE, _this._workingCanvas);
  14020. }
  14021. if (!noMipmap) {
  14022. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  14023. }
  14024. _this.setCubeMapTextureParams(gl, !noMipmap);
  14025. texture.width = width;
  14026. texture.height = height;
  14027. texture.isReady = true;
  14028. if (format) {
  14029. texture.format = format;
  14030. }
  14031. texture.onLoadedObservable.notifyObservers(texture);
  14032. texture.onLoadedObservable.clear();
  14033. if (onLoad) {
  14034. onLoad();
  14035. }
  14036. }, files, onError);
  14037. }
  14038. this._internalTexturesCache.push(texture);
  14039. return texture;
  14040. };
  14041. Engine.prototype.setCubeMapTextureParams = function (gl, loadMipmap) {
  14042. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  14043. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, loadMipmap ? gl.LINEAR_MIPMAP_LINEAR : gl.LINEAR);
  14044. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  14045. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  14046. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  14047. // this.resetTextureCache();
  14048. };
  14049. Engine.prototype.updateRawCubeTexture = function (texture, data, format, type, invertY, compression, level) {
  14050. if (compression === void 0) { compression = null; }
  14051. if (level === void 0) { level = 0; }
  14052. texture._bufferViewArray = data;
  14053. texture.format = format;
  14054. texture.type = type;
  14055. texture.invertY = invertY;
  14056. texture._compression = compression;
  14057. var gl = this._gl;
  14058. var textureType = this._getWebGLTextureType(type);
  14059. var internalFormat = this._getInternalFormat(format);
  14060. var internalSizedFomat = this._getRGBABufferInternalSizedFormat(type);
  14061. var needConversion = false;
  14062. if (internalFormat === gl.RGB) {
  14063. internalFormat = gl.RGBA;
  14064. needConversion = true;
  14065. }
  14066. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  14067. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, invertY === undefined ? 1 : (invertY ? 1 : 0));
  14068. if (texture.width % 4 !== 0) {
  14069. gl.pixelStorei(gl.UNPACK_ALIGNMENT, 1);
  14070. }
  14071. // Data are known to be in +X +Y +Z -X -Y -Z
  14072. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  14073. var faceData = data[faceIndex];
  14074. if (compression) {
  14075. gl.compressedTexImage2D(gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, level, (this.getCaps().s3tc)[compression], texture.width, texture.height, 0, faceData);
  14076. }
  14077. else {
  14078. if (needConversion) {
  14079. faceData = this._convertRGBtoRGBATextureData(faceData, texture.width, texture.height, type);
  14080. }
  14081. gl.texImage2D(gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, level, internalSizedFomat, texture.width, texture.height, 0, internalFormat, textureType, faceData);
  14082. }
  14083. }
  14084. var isPot = !this.needPOTTextures || (BABYLON.Tools.IsExponentOfTwo(texture.width) && BABYLON.Tools.IsExponentOfTwo(texture.height));
  14085. if (isPot && texture.generateMipMaps && level === 0) {
  14086. this._gl.generateMipmap(this._gl.TEXTURE_CUBE_MAP);
  14087. }
  14088. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  14089. // this.resetTextureCache();
  14090. texture.isReady = true;
  14091. };
  14092. Engine.prototype.createRawCubeTexture = function (data, size, format, type, generateMipMaps, invertY, samplingMode, compression) {
  14093. if (compression === void 0) { compression = null; }
  14094. var gl = this._gl;
  14095. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_CUBERAW);
  14096. texture.isCube = true;
  14097. texture.generateMipMaps = generateMipMaps;
  14098. texture.format = format;
  14099. texture.type = type;
  14100. if (!this._doNotHandleContextLost) {
  14101. texture._bufferViewArray = data;
  14102. }
  14103. var textureType = this._getWebGLTextureType(type);
  14104. var internalFormat = this._getInternalFormat(format);
  14105. if (internalFormat === gl.RGB) {
  14106. internalFormat = gl.RGBA;
  14107. }
  14108. var width = size;
  14109. var height = width;
  14110. texture.width = width;
  14111. texture.height = height;
  14112. // Double check on POT to generate Mips.
  14113. var isPot = !this.needPOTTextures || (BABYLON.Tools.IsExponentOfTwo(texture.width) && BABYLON.Tools.IsExponentOfTwo(texture.height));
  14114. if (!isPot) {
  14115. generateMipMaps = false;
  14116. }
  14117. // Upload data if needed. The texture won't be ready until then.
  14118. if (data) {
  14119. this.updateRawCubeTexture(texture, data, format, type, invertY, compression);
  14120. }
  14121. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, texture, true);
  14122. // Filters
  14123. if (data && generateMipMaps) {
  14124. this._gl.generateMipmap(this._gl.TEXTURE_CUBE_MAP);
  14125. }
  14126. if (textureType === gl.FLOAT && !this._caps.textureFloatLinearFiltering) {
  14127. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  14128. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  14129. }
  14130. else if (textureType === this._gl.HALF_FLOAT_OES && !this._caps.textureHalfFloatLinearFiltering) {
  14131. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  14132. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  14133. }
  14134. else {
  14135. var filters = getSamplingParameters(samplingMode, generateMipMaps, gl);
  14136. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, filters.mag);
  14137. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, filters.min);
  14138. }
  14139. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  14140. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  14141. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  14142. return texture;
  14143. };
  14144. Engine.prototype.createRawCubeTextureFromUrl = function (url, scene, size, format, type, noMipmap, callback, mipmmapGenerator, onLoad, onError, samplingMode, invertY) {
  14145. var _this = this;
  14146. if (onLoad === void 0) { onLoad = null; }
  14147. if (onError === void 0) { onError = null; }
  14148. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  14149. if (invertY === void 0) { invertY = false; }
  14150. var gl = this._gl;
  14151. var texture = this.createRawCubeTexture(null, size, format, type, !noMipmap, invertY, samplingMode);
  14152. scene._addPendingData(texture);
  14153. texture.url = url;
  14154. this._internalTexturesCache.push(texture);
  14155. var onerror = function (request, exception) {
  14156. scene._removePendingData(texture);
  14157. if (onError && request) {
  14158. onError(request.status + " " + request.statusText, exception);
  14159. }
  14160. };
  14161. var internalCallback = function (data) {
  14162. var width = texture.width;
  14163. var faceDataArrays = callback(data);
  14164. if (!faceDataArrays) {
  14165. return;
  14166. }
  14167. if (mipmmapGenerator) {
  14168. var textureType = _this._getWebGLTextureType(type);
  14169. var internalFormat = _this._getInternalFormat(format);
  14170. var internalSizedFomat = _this._getRGBABufferInternalSizedFormat(type);
  14171. var needConversion = false;
  14172. if (internalFormat === gl.RGB) {
  14173. internalFormat = gl.RGBA;
  14174. needConversion = true;
  14175. }
  14176. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  14177. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 0);
  14178. var mipData = mipmmapGenerator(faceDataArrays);
  14179. for (var level = 0; level < mipData.length; level++) {
  14180. var mipSize = width >> level;
  14181. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  14182. var mipFaceData = mipData[level][faceIndex];
  14183. if (needConversion) {
  14184. mipFaceData = _this._convertRGBtoRGBATextureData(mipFaceData, mipSize, mipSize, type);
  14185. }
  14186. gl.texImage2D(faceIndex, level, internalSizedFomat, mipSize, mipSize, 0, internalFormat, textureType, mipFaceData);
  14187. }
  14188. }
  14189. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  14190. }
  14191. else {
  14192. texture.generateMipMaps = !noMipmap;
  14193. _this.updateRawCubeTexture(texture, faceDataArrays, format, type, invertY);
  14194. }
  14195. texture.isReady = true;
  14196. // this.resetTextureCache();
  14197. scene._removePendingData(texture);
  14198. if (onLoad) {
  14199. onLoad();
  14200. }
  14201. };
  14202. this._loadFile(url, function (data) {
  14203. internalCallback(data);
  14204. }, undefined, scene.database, true, onerror);
  14205. return texture;
  14206. };
  14207. ;
  14208. Engine.prototype.updateRawTexture3D = function (texture, data, format, invertY, compression) {
  14209. if (compression === void 0) { compression = null; }
  14210. var internalFormat = this._getInternalFormat(format);
  14211. this._bindTextureDirectly(this._gl.TEXTURE_3D, texture, true);
  14212. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY === undefined ? 1 : (invertY ? 1 : 0));
  14213. if (!this._doNotHandleContextLost) {
  14214. texture._bufferView = data;
  14215. texture.format = format;
  14216. texture.invertY = invertY;
  14217. texture._compression = compression;
  14218. }
  14219. if (texture.width % 4 !== 0) {
  14220. this._gl.pixelStorei(this._gl.UNPACK_ALIGNMENT, 1);
  14221. }
  14222. if (compression && data) {
  14223. this._gl.compressedTexImage3D(this._gl.TEXTURE_3D, 0, this.getCaps().s3tc[compression], texture.width, texture.height, texture.depth, 0, data);
  14224. }
  14225. else {
  14226. this._gl.texImage3D(this._gl.TEXTURE_3D, 0, internalFormat, texture.width, texture.height, texture.depth, 0, internalFormat, this._gl.UNSIGNED_BYTE, data);
  14227. }
  14228. if (texture.generateMipMaps) {
  14229. this._gl.generateMipmap(this._gl.TEXTURE_3D);
  14230. }
  14231. this._bindTextureDirectly(this._gl.TEXTURE_3D, null);
  14232. // this.resetTextureCache();
  14233. texture.isReady = true;
  14234. };
  14235. Engine.prototype.createRawTexture3D = function (data, width, height, depth, format, generateMipMaps, invertY, samplingMode, compression) {
  14236. if (compression === void 0) { compression = null; }
  14237. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_RAW3D);
  14238. texture.baseWidth = width;
  14239. texture.baseHeight = height;
  14240. texture.baseDepth = depth;
  14241. texture.width = width;
  14242. texture.height = height;
  14243. texture.depth = depth;
  14244. texture.format = format;
  14245. texture.generateMipMaps = generateMipMaps;
  14246. texture.samplingMode = samplingMode;
  14247. texture.is3D = true;
  14248. if (!this._doNotHandleContextLost) {
  14249. texture._bufferView = data;
  14250. }
  14251. this.updateRawTexture3D(texture, data, format, invertY, compression);
  14252. this._bindTextureDirectly(this._gl.TEXTURE_3D, texture, true);
  14253. // Filters
  14254. var filters = getSamplingParameters(samplingMode, generateMipMaps, this._gl);
  14255. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  14256. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  14257. if (generateMipMaps) {
  14258. this._gl.generateMipmap(this._gl.TEXTURE_3D);
  14259. }
  14260. this._bindTextureDirectly(this._gl.TEXTURE_3D, null);
  14261. this._internalTexturesCache.push(texture);
  14262. return texture;
  14263. };
  14264. Engine.prototype._prepareWebGLTextureContinuation = function (texture, scene, noMipmap, isCompressed, samplingMode) {
  14265. var gl = this._gl;
  14266. if (!gl) {
  14267. return;
  14268. }
  14269. var filters = getSamplingParameters(samplingMode, !noMipmap, gl);
  14270. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  14271. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  14272. if (!noMipmap && !isCompressed) {
  14273. gl.generateMipmap(gl.TEXTURE_2D);
  14274. }
  14275. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  14276. // this.resetTextureCache();
  14277. if (scene) {
  14278. scene._removePendingData(texture);
  14279. }
  14280. texture.onLoadedObservable.notifyObservers(texture);
  14281. texture.onLoadedObservable.clear();
  14282. };
  14283. Engine.prototype._prepareWebGLTexture = function (texture, scene, width, height, invertY, noMipmap, isCompressed, processFunction, samplingMode) {
  14284. var _this = this;
  14285. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  14286. var potWidth = this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(width, this.getCaps().maxTextureSize) : width;
  14287. var potHeight = this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(height, this.getCaps().maxTextureSize) : height;
  14288. var gl = this._gl;
  14289. if (!gl) {
  14290. return;
  14291. }
  14292. if (!texture._webGLTexture) {
  14293. // this.resetTextureCache();
  14294. if (scene) {
  14295. scene._removePendingData(texture);
  14296. }
  14297. return;
  14298. }
  14299. this._bindTextureDirectly(gl.TEXTURE_2D, texture, true);
  14300. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, invertY === undefined ? 1 : (invertY ? 1 : 0));
  14301. texture.baseWidth = width;
  14302. texture.baseHeight = height;
  14303. texture.width = potWidth;
  14304. texture.height = potHeight;
  14305. texture.isReady = true;
  14306. if (processFunction(potWidth, potHeight, function () {
  14307. _this._prepareWebGLTextureContinuation(texture, scene, noMipmap, isCompressed, samplingMode);
  14308. })) {
  14309. // Returning as texture needs extra async steps
  14310. return;
  14311. }
  14312. this._prepareWebGLTextureContinuation(texture, scene, noMipmap, isCompressed, samplingMode);
  14313. };
  14314. Engine.prototype._convertRGBtoRGBATextureData = function (rgbData, width, height, textureType) {
  14315. // Create new RGBA data container.
  14316. var rgbaData;
  14317. if (textureType === Engine.TEXTURETYPE_FLOAT) {
  14318. rgbaData = new Float32Array(width * height * 4);
  14319. }
  14320. else {
  14321. rgbaData = new Uint32Array(width * height * 4);
  14322. }
  14323. // Convert each pixel.
  14324. for (var x = 0; x < width; x++) {
  14325. for (var y = 0; y < height; y++) {
  14326. var index = (y * width + x) * 3;
  14327. var newIndex = (y * width + x) * 4;
  14328. // Map Old Value to new value.
  14329. rgbaData[newIndex + 0] = rgbData[index + 0];
  14330. rgbaData[newIndex + 1] = rgbData[index + 1];
  14331. rgbaData[newIndex + 2] = rgbData[index + 2];
  14332. // Add fully opaque alpha channel.
  14333. rgbaData[newIndex + 3] = 1;
  14334. }
  14335. }
  14336. return rgbaData;
  14337. };
  14338. Engine.prototype._releaseFramebufferObjects = function (texture) {
  14339. var gl = this._gl;
  14340. if (texture._framebuffer) {
  14341. gl.deleteFramebuffer(texture._framebuffer);
  14342. texture._framebuffer = null;
  14343. }
  14344. if (texture._depthStencilBuffer) {
  14345. gl.deleteRenderbuffer(texture._depthStencilBuffer);
  14346. texture._depthStencilBuffer = null;
  14347. }
  14348. if (texture._MSAAFramebuffer) {
  14349. gl.deleteFramebuffer(texture._MSAAFramebuffer);
  14350. texture._MSAAFramebuffer = null;
  14351. }
  14352. if (texture._MSAARenderBuffer) {
  14353. gl.deleteRenderbuffer(texture._MSAARenderBuffer);
  14354. texture._MSAARenderBuffer = null;
  14355. }
  14356. };
  14357. Engine.prototype._releaseTexture = function (texture) {
  14358. var gl = this._gl;
  14359. this._releaseFramebufferObjects(texture);
  14360. gl.deleteTexture(texture._webGLTexture);
  14361. // Unbind channels
  14362. this.unbindAllTextures();
  14363. var index = this._internalTexturesCache.indexOf(texture);
  14364. if (index !== -1) {
  14365. this._internalTexturesCache.splice(index, 1);
  14366. }
  14367. // Integrated fixed lod samplers.
  14368. if (texture._lodTextureHigh) {
  14369. texture._lodTextureHigh.dispose();
  14370. }
  14371. if (texture._lodTextureMid) {
  14372. texture._lodTextureMid.dispose();
  14373. }
  14374. if (texture._lodTextureLow) {
  14375. texture._lodTextureLow.dispose();
  14376. }
  14377. };
  14378. Engine.prototype.setProgram = function (program) {
  14379. if (this._currentProgram !== program) {
  14380. this._gl.useProgram(program);
  14381. this._currentProgram = program;
  14382. }
  14383. };
  14384. Engine.prototype.bindSamplers = function (effect) {
  14385. this.setProgram(effect.getProgram());
  14386. var samplers = effect.getSamplers();
  14387. for (var index = 0; index < samplers.length; index++) {
  14388. var uniform = effect.getUniform(samplers[index]);
  14389. if (uniform) {
  14390. this._boundUniforms[index] = uniform;
  14391. }
  14392. }
  14393. this._currentEffect = null;
  14394. };
  14395. Engine.prototype._moveBoundTextureOnTop = function (internalTexture) {
  14396. if (this.disableTextureBindingOptimization || this._lastBoundInternalTextureTracker.previous === internalTexture) {
  14397. return;
  14398. }
  14399. // Remove
  14400. this._linkTrackers(internalTexture.previous, internalTexture.next);
  14401. // Bind last to it
  14402. this._linkTrackers(this._lastBoundInternalTextureTracker.previous, internalTexture);
  14403. // Bind to dummy
  14404. this._linkTrackers(internalTexture, this._lastBoundInternalTextureTracker);
  14405. };
  14406. Engine.prototype._getCorrectTextureChannel = function (channel, internalTexture) {
  14407. if (!internalTexture) {
  14408. return -1;
  14409. }
  14410. internalTexture._initialSlot = channel;
  14411. if (this.disableTextureBindingOptimization) {
  14412. if (channel !== internalTexture._designatedSlot) {
  14413. this._textureCollisions.addCount(1, false);
  14414. }
  14415. }
  14416. else {
  14417. if (channel !== internalTexture._designatedSlot) {
  14418. if (internalTexture._designatedSlot > -1) {
  14419. return internalTexture._designatedSlot;
  14420. }
  14421. else {
  14422. // No slot for this texture, let's pick a new one (if we find a free slot)
  14423. if (this._nextFreeTextureSlots.length) {
  14424. return this._nextFreeTextureSlots[0];
  14425. }
  14426. // We need to recycle the oldest bound texture, sorry.
  14427. this._textureCollisions.addCount(1, false);
  14428. return this._removeDesignatedSlot(this._firstBoundInternalTextureTracker.next);
  14429. }
  14430. }
  14431. }
  14432. return channel;
  14433. };
  14434. Engine.prototype._linkTrackers = function (previous, next) {
  14435. previous.next = next;
  14436. next.previous = previous;
  14437. };
  14438. Engine.prototype._removeDesignatedSlot = function (internalTexture) {
  14439. var currentSlot = internalTexture._designatedSlot;
  14440. if (currentSlot === -1) {
  14441. return -1;
  14442. }
  14443. internalTexture._designatedSlot = -1;
  14444. if (this.disableTextureBindingOptimization) {
  14445. return -1;
  14446. }
  14447. // Remove from bound list
  14448. this._linkTrackers(internalTexture.previous, internalTexture.next);
  14449. // Free the slot
  14450. this._boundTexturesCache[currentSlot] = null;
  14451. this._nextFreeTextureSlots.push(currentSlot);
  14452. return currentSlot;
  14453. };
  14454. Engine.prototype._activateCurrentTexture = function () {
  14455. if (this._currentTextureChannel !== this._activeChannel) {
  14456. this._gl.activeTexture(this._gl.TEXTURE0 + this._activeChannel);
  14457. this._currentTextureChannel = this._activeChannel;
  14458. }
  14459. };
  14460. Engine.prototype._bindTextureDirectly = function (target, texture, forTextureDataUpdate) {
  14461. if (forTextureDataUpdate === void 0) { forTextureDataUpdate = false; }
  14462. if (forTextureDataUpdate && texture && texture._designatedSlot > -1) {
  14463. this._activeChannel = texture._designatedSlot;
  14464. }
  14465. var currentTextureBound = this._boundTexturesCache[this._activeChannel];
  14466. var isTextureForRendering = texture && texture._initialSlot > -1;
  14467. if (currentTextureBound !== texture) {
  14468. if (currentTextureBound) {
  14469. this._removeDesignatedSlot(currentTextureBound);
  14470. }
  14471. this._activateCurrentTexture();
  14472. this._gl.bindTexture(target, texture ? texture._webGLTexture : null);
  14473. this._boundTexturesCache[this._activeChannel] = texture;
  14474. if (texture) {
  14475. if (!this.disableTextureBindingOptimization) {
  14476. var slotIndex = this._nextFreeTextureSlots.indexOf(this._activeChannel);
  14477. if (slotIndex > -1) {
  14478. this._nextFreeTextureSlots.splice(slotIndex, 1);
  14479. }
  14480. this._linkTrackers(this._lastBoundInternalTextureTracker.previous, texture);
  14481. this._linkTrackers(texture, this._lastBoundInternalTextureTracker);
  14482. }
  14483. texture._designatedSlot = this._activeChannel;
  14484. }
  14485. }
  14486. else if (forTextureDataUpdate) {
  14487. this._activateCurrentTexture();
  14488. }
  14489. if (isTextureForRendering && !forTextureDataUpdate) {
  14490. this._bindSamplerUniformToChannel(texture._initialSlot, this._activeChannel);
  14491. }
  14492. };
  14493. Engine.prototype._bindTexture = function (channel, texture) {
  14494. if (channel < 0) {
  14495. return;
  14496. }
  14497. if (texture) {
  14498. channel = this._getCorrectTextureChannel(channel, texture);
  14499. }
  14500. this._activeChannel = channel;
  14501. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture);
  14502. };
  14503. Engine.prototype.setTextureFromPostProcess = function (channel, postProcess) {
  14504. this._bindTexture(channel, postProcess ? postProcess._textures.data[postProcess._currentRenderTextureInd] : null);
  14505. };
  14506. Engine.prototype.unbindAllTextures = function () {
  14507. for (var channel = 0; channel < this._maxSimultaneousTextures; channel++) {
  14508. this._activeChannel = channel;
  14509. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  14510. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  14511. if (this.webGLVersion > 1) {
  14512. this._bindTextureDirectly(this._gl.TEXTURE_3D, null);
  14513. }
  14514. }
  14515. };
  14516. Engine.prototype.setTexture = function (channel, uniform, texture) {
  14517. if (channel < 0) {
  14518. return;
  14519. }
  14520. if (uniform) {
  14521. this._boundUniforms[channel] = uniform;
  14522. }
  14523. this._setTexture(channel, texture);
  14524. };
  14525. Engine.prototype._bindSamplerUniformToChannel = function (sourceSlot, destination) {
  14526. var uniform = this._boundUniforms[sourceSlot];
  14527. if (uniform._currentState === destination) {
  14528. return;
  14529. }
  14530. this._gl.uniform1i(uniform, destination);
  14531. uniform._currentState = destination;
  14532. };
  14533. Engine.prototype._setTexture = function (channel, texture, isPartOfTextureArray) {
  14534. if (isPartOfTextureArray === void 0) { isPartOfTextureArray = false; }
  14535. // Not ready?
  14536. if (!texture) {
  14537. if (this._boundTexturesCache[channel] != null) {
  14538. this._activeChannel = channel;
  14539. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  14540. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  14541. if (this.webGLVersion > 1) {
  14542. this._bindTextureDirectly(this._gl.TEXTURE_3D, null);
  14543. }
  14544. }
  14545. return false;
  14546. }
  14547. // Video
  14548. if (texture.video) {
  14549. this._activeChannel = channel;
  14550. texture.update();
  14551. }
  14552. else if (texture.delayLoadState === Engine.DELAYLOADSTATE_NOTLOADED) {
  14553. texture.delayLoad();
  14554. return false;
  14555. }
  14556. var internalTexture;
  14557. if (texture.isReady()) {
  14558. internalTexture = texture.getInternalTexture();
  14559. }
  14560. else if (texture.isCube) {
  14561. internalTexture = this.emptyCubeTexture;
  14562. }
  14563. else if (texture.is3D) {
  14564. internalTexture = this.emptyTexture3D;
  14565. }
  14566. else {
  14567. internalTexture = this.emptyTexture;
  14568. }
  14569. if (!isPartOfTextureArray) {
  14570. channel = this._getCorrectTextureChannel(channel, internalTexture);
  14571. }
  14572. if (this._boundTexturesCache[channel] === internalTexture) {
  14573. this._moveBoundTextureOnTop(internalTexture);
  14574. if (!isPartOfTextureArray) {
  14575. this._bindSamplerUniformToChannel(internalTexture._initialSlot, channel);
  14576. }
  14577. return false;
  14578. }
  14579. this._activeChannel = channel;
  14580. if (internalTexture && internalTexture.is3D) {
  14581. this._bindTextureDirectly(this._gl.TEXTURE_3D, internalTexture, isPartOfTextureArray);
  14582. if (internalTexture && internalTexture._cachedWrapU !== texture.wrapU) {
  14583. internalTexture._cachedWrapU = texture.wrapU;
  14584. switch (texture.wrapU) {
  14585. case BABYLON.Texture.WRAP_ADDRESSMODE:
  14586. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_S, this._gl.REPEAT);
  14587. break;
  14588. case BABYLON.Texture.CLAMP_ADDRESSMODE:
  14589. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_S, this._gl.CLAMP_TO_EDGE);
  14590. break;
  14591. case BABYLON.Texture.MIRROR_ADDRESSMODE:
  14592. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_S, this._gl.MIRRORED_REPEAT);
  14593. break;
  14594. }
  14595. }
  14596. if (internalTexture && internalTexture._cachedWrapV !== texture.wrapV) {
  14597. internalTexture._cachedWrapV = texture.wrapV;
  14598. switch (texture.wrapV) {
  14599. case BABYLON.Texture.WRAP_ADDRESSMODE:
  14600. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_T, this._gl.REPEAT);
  14601. break;
  14602. case BABYLON.Texture.CLAMP_ADDRESSMODE:
  14603. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_T, this._gl.CLAMP_TO_EDGE);
  14604. break;
  14605. case BABYLON.Texture.MIRROR_ADDRESSMODE:
  14606. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_T, this._gl.MIRRORED_REPEAT);
  14607. break;
  14608. }
  14609. }
  14610. if (internalTexture && internalTexture._cachedWrapR !== texture.wrapR) {
  14611. internalTexture._cachedWrapR = texture.wrapR;
  14612. switch (texture.wrapR) {
  14613. case BABYLON.Texture.WRAP_ADDRESSMODE:
  14614. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_R, this._gl.REPEAT);
  14615. break;
  14616. case BABYLON.Texture.CLAMP_ADDRESSMODE:
  14617. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_R, this._gl.CLAMP_TO_EDGE);
  14618. break;
  14619. case BABYLON.Texture.MIRROR_ADDRESSMODE:
  14620. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_R, this._gl.MIRRORED_REPEAT);
  14621. break;
  14622. }
  14623. }
  14624. this._setAnisotropicLevel(this._gl.TEXTURE_3D, texture);
  14625. }
  14626. else if (internalTexture && internalTexture.isCube) {
  14627. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, internalTexture, isPartOfTextureArray);
  14628. if (internalTexture._cachedCoordinatesMode !== texture.coordinatesMode) {
  14629. internalTexture._cachedCoordinatesMode = texture.coordinatesMode;
  14630. // CUBIC_MODE and SKYBOX_MODE both require CLAMP_TO_EDGE. All other modes use REPEAT.
  14631. var textureWrapMode = (texture.coordinatesMode !== BABYLON.Texture.CUBIC_MODE && texture.coordinatesMode !== BABYLON.Texture.SKYBOX_MODE) ? this._gl.REPEAT : this._gl.CLAMP_TO_EDGE;
  14632. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_WRAP_S, textureWrapMode);
  14633. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_WRAP_T, textureWrapMode);
  14634. }
  14635. this._setAnisotropicLevel(this._gl.TEXTURE_CUBE_MAP, texture);
  14636. }
  14637. else {
  14638. this._bindTextureDirectly(this._gl.TEXTURE_2D, internalTexture, isPartOfTextureArray);
  14639. if (internalTexture && internalTexture._cachedWrapU !== texture.wrapU) {
  14640. internalTexture._cachedWrapU = texture.wrapU;
  14641. switch (texture.wrapU) {
  14642. case BABYLON.Texture.WRAP_ADDRESSMODE:
  14643. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._gl.REPEAT);
  14644. break;
  14645. case BABYLON.Texture.CLAMP_ADDRESSMODE:
  14646. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._gl.CLAMP_TO_EDGE);
  14647. break;
  14648. case BABYLON.Texture.MIRROR_ADDRESSMODE:
  14649. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._gl.MIRRORED_REPEAT);
  14650. break;
  14651. }
  14652. }
  14653. if (internalTexture && internalTexture._cachedWrapV !== texture.wrapV) {
  14654. internalTexture._cachedWrapV = texture.wrapV;
  14655. switch (texture.wrapV) {
  14656. case BABYLON.Texture.WRAP_ADDRESSMODE:
  14657. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._gl.REPEAT);
  14658. break;
  14659. case BABYLON.Texture.CLAMP_ADDRESSMODE:
  14660. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._gl.CLAMP_TO_EDGE);
  14661. break;
  14662. case BABYLON.Texture.MIRROR_ADDRESSMODE:
  14663. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._gl.MIRRORED_REPEAT);
  14664. break;
  14665. }
  14666. }
  14667. this._setAnisotropicLevel(this._gl.TEXTURE_2D, texture);
  14668. }
  14669. return true;
  14670. };
  14671. Engine.prototype.setTextureArray = function (channel, uniform, textures) {
  14672. if (channel < 0 || !uniform) {
  14673. return;
  14674. }
  14675. if (!this._textureUnits || this._textureUnits.length !== textures.length) {
  14676. this._textureUnits = new Int32Array(textures.length);
  14677. }
  14678. for (var i = 0; i < textures.length; i++) {
  14679. this._textureUnits[i] = this._getCorrectTextureChannel(channel + i, textures[i].getInternalTexture());
  14680. }
  14681. this._gl.uniform1iv(uniform, this._textureUnits);
  14682. for (var index = 0; index < textures.length; index++) {
  14683. this._setTexture(this._textureUnits[index], textures[index], true);
  14684. }
  14685. };
  14686. Engine.prototype._setAnisotropicLevel = function (key, texture) {
  14687. var internalTexture = texture.getInternalTexture();
  14688. if (!internalTexture) {
  14689. return;
  14690. }
  14691. var anisotropicFilterExtension = this._caps.textureAnisotropicFilterExtension;
  14692. var value = texture.anisotropicFilteringLevel;
  14693. if (internalTexture.samplingMode !== BABYLON.Texture.LINEAR_LINEAR_MIPNEAREST
  14694. && internalTexture.samplingMode !== BABYLON.Texture.LINEAR_LINEAR_MIPLINEAR
  14695. && internalTexture.samplingMode !== BABYLON.Texture.LINEAR_LINEAR) {
  14696. value = 1; // Forcing the anisotropic to 1 because else webgl will force filters to linear
  14697. }
  14698. if (anisotropicFilterExtension && internalTexture._cachedAnisotropicFilteringLevel !== value) {
  14699. this._gl.texParameterf(key, anisotropicFilterExtension.TEXTURE_MAX_ANISOTROPY_EXT, Math.min(value, this._caps.maxAnisotropy));
  14700. internalTexture._cachedAnisotropicFilteringLevel = value;
  14701. }
  14702. };
  14703. Engine.prototype.readPixels = function (x, y, width, height) {
  14704. var data = new Uint8Array(height * width * 4);
  14705. this._gl.readPixels(x, y, width, height, this._gl.RGBA, this._gl.UNSIGNED_BYTE, data);
  14706. return data;
  14707. };
  14708. /**
  14709. * Add an externaly attached data from its key.
  14710. * This method call will fail and return false, if such key already exists.
  14711. * If you don't care and just want to get the data no matter what, use the more convenient getOrAddExternalDataWithFactory() method.
  14712. * @param key the unique key that identifies the data
  14713. * @param data the data object to associate to the key for this Engine instance
  14714. * @return true if no such key were already present and the data was added successfully, false otherwise
  14715. */
  14716. Engine.prototype.addExternalData = function (key, data) {
  14717. if (!this._externalData) {
  14718. this._externalData = new BABYLON.StringDictionary();
  14719. }
  14720. return this._externalData.add(key, data);
  14721. };
  14722. /**
  14723. * Get an externaly attached data from its key
  14724. * @param key the unique key that identifies the data
  14725. * @return the associated data, if present (can be null), or undefined if not present
  14726. */
  14727. Engine.prototype.getExternalData = function (key) {
  14728. if (!this._externalData) {
  14729. this._externalData = new BABYLON.StringDictionary();
  14730. }
  14731. return this._externalData.get(key);
  14732. };
  14733. /**
  14734. * Get an externaly attached data from its key, create it using a factory if it's not already present
  14735. * @param key the unique key that identifies the data
  14736. * @param factory the factory that will be called to create the instance if and only if it doesn't exists
  14737. * @return the associated data, can be null if the factory returned null.
  14738. */
  14739. Engine.prototype.getOrAddExternalDataWithFactory = function (key, factory) {
  14740. if (!this._externalData) {
  14741. this._externalData = new BABYLON.StringDictionary();
  14742. }
  14743. return this._externalData.getOrAddWithFactory(key, factory);
  14744. };
  14745. /**
  14746. * Remove an externaly attached data from the Engine instance
  14747. * @param key the unique key that identifies the data
  14748. * @return true if the data was successfully removed, false if it doesn't exist
  14749. */
  14750. Engine.prototype.removeExternalData = function (key) {
  14751. if (!this._externalData) {
  14752. this._externalData = new BABYLON.StringDictionary();
  14753. }
  14754. return this._externalData.remove(key);
  14755. };
  14756. Engine.prototype.unbindAllAttributes = function () {
  14757. if (this._mustWipeVertexAttributes) {
  14758. this._mustWipeVertexAttributes = false;
  14759. for (var i = 0; i < this._caps.maxVertexAttribs; i++) {
  14760. this._gl.disableVertexAttribArray(i);
  14761. this._vertexAttribArraysEnabled[i] = false;
  14762. this._currentBufferPointers[i].active = false;
  14763. }
  14764. return;
  14765. }
  14766. for (var i = 0, ul = this._vertexAttribArraysEnabled.length; i < ul; i++) {
  14767. if (i >= this._caps.maxVertexAttribs || !this._vertexAttribArraysEnabled[i]) {
  14768. continue;
  14769. }
  14770. this._gl.disableVertexAttribArray(i);
  14771. this._vertexAttribArraysEnabled[i] = false;
  14772. this._currentBufferPointers[i].active = false;
  14773. }
  14774. };
  14775. Engine.prototype.releaseEffects = function () {
  14776. for (var name in this._compiledEffects) {
  14777. this._deleteProgram(this._compiledEffects[name]._program);
  14778. }
  14779. this._compiledEffects = {};
  14780. };
  14781. // Dispose
  14782. Engine.prototype.dispose = function () {
  14783. this.hideLoadingUI();
  14784. this.stopRenderLoop();
  14785. // Release postProcesses
  14786. while (this.postProcesses.length) {
  14787. this.postProcesses[0].dispose();
  14788. }
  14789. // Empty texture
  14790. if (this._emptyTexture) {
  14791. this._releaseTexture(this._emptyTexture);
  14792. this._emptyTexture = null;
  14793. }
  14794. if (this._emptyCubeTexture) {
  14795. this._releaseTexture(this._emptyCubeTexture);
  14796. this._emptyCubeTexture = null;
  14797. }
  14798. // Rescale PP
  14799. if (this._rescalePostProcess) {
  14800. this._rescalePostProcess.dispose();
  14801. }
  14802. // Release scenes
  14803. while (this.scenes.length) {
  14804. this.scenes[0].dispose();
  14805. }
  14806. // Release audio engine
  14807. if (Engine.audioEngine) {
  14808. Engine.audioEngine.dispose();
  14809. }
  14810. // Release effects
  14811. this.releaseEffects();
  14812. // Unbind
  14813. this.unbindAllAttributes();
  14814. if (this._dummyFramebuffer) {
  14815. this._gl.deleteFramebuffer(this._dummyFramebuffer);
  14816. }
  14817. //WebVR
  14818. this.disableVR();
  14819. // Events
  14820. if (BABYLON.Tools.IsWindowObjectExist()) {
  14821. window.removeEventListener("blur", this._onBlur);
  14822. window.removeEventListener("focus", this._onFocus);
  14823. window.removeEventListener('vrdisplaypointerrestricted', this._onVRDisplayPointerRestricted);
  14824. window.removeEventListener('vrdisplaypointerunrestricted', this._onVRDisplayPointerUnrestricted);
  14825. if (this._renderingCanvas) {
  14826. this._renderingCanvas.removeEventListener("focus", this._onCanvasFocus);
  14827. this._renderingCanvas.removeEventListener("blur", this._onCanvasBlur);
  14828. this._renderingCanvas.removeEventListener("pointerout", this._onCanvasBlur);
  14829. if (!this._doNotHandleContextLost) {
  14830. this._renderingCanvas.removeEventListener("webglcontextlost", this._onContextLost);
  14831. this._renderingCanvas.removeEventListener("webglcontextrestored", this._onContextRestored);
  14832. }
  14833. }
  14834. document.removeEventListener("fullscreenchange", this._onFullscreenChange);
  14835. document.removeEventListener("mozfullscreenchange", this._onFullscreenChange);
  14836. document.removeEventListener("webkitfullscreenchange", this._onFullscreenChange);
  14837. document.removeEventListener("msfullscreenchange", this._onFullscreenChange);
  14838. document.removeEventListener("pointerlockchange", this._onPointerLockChange);
  14839. document.removeEventListener("mspointerlockchange", this._onPointerLockChange);
  14840. document.removeEventListener("mozpointerlockchange", this._onPointerLockChange);
  14841. document.removeEventListener("webkitpointerlockchange", this._onPointerLockChange);
  14842. if (this._onVrDisplayConnect) {
  14843. window.removeEventListener('vrdisplayconnect', this._onVrDisplayConnect);
  14844. if (this._onVrDisplayDisconnect) {
  14845. window.removeEventListener('vrdisplaydisconnect', this._onVrDisplayDisconnect);
  14846. }
  14847. if (this._onVrDisplayPresentChange) {
  14848. window.removeEventListener('vrdisplaypresentchange', this._onVrDisplayPresentChange);
  14849. }
  14850. this._onVrDisplayConnect = null;
  14851. this._onVrDisplayDisconnect = null;
  14852. }
  14853. }
  14854. // Remove from Instances
  14855. var index = Engine.Instances.indexOf(this);
  14856. if (index >= 0) {
  14857. Engine.Instances.splice(index, 1);
  14858. }
  14859. this._workingCanvas = null;
  14860. this._workingContext = null;
  14861. this._currentBufferPointers = [];
  14862. this._renderingCanvas = null;
  14863. this._currentProgram = null;
  14864. this.onResizeObservable.clear();
  14865. this.onCanvasBlurObservable.clear();
  14866. this.onCanvasFocusObservable.clear();
  14867. this.onCanvasPointerOutObservable.clear();
  14868. this.onBeginFrameObservable.clear();
  14869. this.onEndFrameObservable.clear();
  14870. BABYLON.Effect.ResetCache();
  14871. // Abort active requests
  14872. for (var _i = 0, _a = this._activeRequests; _i < _a.length; _i++) {
  14873. var request = _a[_i];
  14874. request.abort();
  14875. }
  14876. };
  14877. // Loading screen
  14878. Engine.prototype.displayLoadingUI = function () {
  14879. if (!BABYLON.Tools.IsWindowObjectExist()) {
  14880. return;
  14881. }
  14882. var loadingScreen = this.loadingScreen;
  14883. if (loadingScreen) {
  14884. loadingScreen.displayLoadingUI();
  14885. }
  14886. };
  14887. Engine.prototype.hideLoadingUI = function () {
  14888. if (!BABYLON.Tools.IsWindowObjectExist()) {
  14889. return;
  14890. }
  14891. var loadingScreen = this.loadingScreen;
  14892. if (loadingScreen) {
  14893. loadingScreen.hideLoadingUI();
  14894. }
  14895. };
  14896. Object.defineProperty(Engine.prototype, "loadingScreen", {
  14897. get: function () {
  14898. if (!this._loadingScreen && BABYLON.DefaultLoadingScreen && this._renderingCanvas)
  14899. this._loadingScreen = new BABYLON.DefaultLoadingScreen(this._renderingCanvas);
  14900. return this._loadingScreen;
  14901. },
  14902. set: function (loadingScreen) {
  14903. this._loadingScreen = loadingScreen;
  14904. },
  14905. enumerable: true,
  14906. configurable: true
  14907. });
  14908. Object.defineProperty(Engine.prototype, "loadingUIText", {
  14909. set: function (text) {
  14910. this.loadingScreen.loadingUIText = text;
  14911. },
  14912. enumerable: true,
  14913. configurable: true
  14914. });
  14915. Object.defineProperty(Engine.prototype, "loadingUIBackgroundColor", {
  14916. set: function (color) {
  14917. this.loadingScreen.loadingUIBackgroundColor = color;
  14918. },
  14919. enumerable: true,
  14920. configurable: true
  14921. });
  14922. Engine.prototype.attachContextLostEvent = function (callback) {
  14923. if (this._renderingCanvas) {
  14924. this._renderingCanvas.addEventListener("webglcontextlost", callback, false);
  14925. }
  14926. };
  14927. Engine.prototype.attachContextRestoredEvent = function (callback) {
  14928. if (this._renderingCanvas) {
  14929. this._renderingCanvas.addEventListener("webglcontextrestored", callback, false);
  14930. }
  14931. };
  14932. Engine.prototype.getVertexShaderSource = function (program) {
  14933. var shaders = this._gl.getAttachedShaders(program);
  14934. if (!shaders) {
  14935. return null;
  14936. }
  14937. return this._gl.getShaderSource(shaders[0]);
  14938. };
  14939. Engine.prototype.getFragmentShaderSource = function (program) {
  14940. var shaders = this._gl.getAttachedShaders(program);
  14941. if (!shaders) {
  14942. return null;
  14943. }
  14944. return this._gl.getShaderSource(shaders[1]);
  14945. };
  14946. Engine.prototype.getError = function () {
  14947. return this._gl.getError();
  14948. };
  14949. // FPS
  14950. Engine.prototype.getFps = function () {
  14951. return this._fps;
  14952. };
  14953. Engine.prototype.getDeltaTime = function () {
  14954. return this._deltaTime;
  14955. };
  14956. Engine.prototype._measureFps = function () {
  14957. this._performanceMonitor.sampleFrame();
  14958. this._fps = this._performanceMonitor.averageFPS;
  14959. this._deltaTime = this._performanceMonitor.instantaneousFrameTime || 0;
  14960. };
  14961. Engine.prototype._readTexturePixels = function (texture, width, height, faceIndex) {
  14962. if (faceIndex === void 0) { faceIndex = -1; }
  14963. var gl = this._gl;
  14964. if (!this._dummyFramebuffer) {
  14965. var dummy = gl.createFramebuffer();
  14966. if (!dummy) {
  14967. throw new Error("Unable to create dummy framebuffer");
  14968. }
  14969. this._dummyFramebuffer = dummy;
  14970. }
  14971. gl.bindFramebuffer(gl.FRAMEBUFFER, this._dummyFramebuffer);
  14972. if (faceIndex > -1) {
  14973. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, texture._webGLTexture, 0);
  14974. }
  14975. else {
  14976. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texture._webGLTexture, 0);
  14977. }
  14978. var readType = (texture.type !== undefined) ? this._getWebGLTextureType(texture.type) : gl.UNSIGNED_BYTE;
  14979. var buffer;
  14980. switch (readType) {
  14981. case gl.UNSIGNED_BYTE:
  14982. buffer = new Uint8Array(4 * width * height);
  14983. readType = gl.UNSIGNED_BYTE;
  14984. break;
  14985. default:
  14986. buffer = new Float32Array(4 * width * height);
  14987. readType = gl.FLOAT;
  14988. break;
  14989. }
  14990. gl.readPixels(0, 0, width, height, gl.RGBA, readType, buffer);
  14991. gl.bindFramebuffer(gl.FRAMEBUFFER, this._currentFramebuffer);
  14992. return buffer;
  14993. };
  14994. Engine.prototype._canRenderToFloatFramebuffer = function () {
  14995. if (this._webGLVersion > 1) {
  14996. return this._caps.colorBufferFloat;
  14997. }
  14998. return this._canRenderToFramebuffer(Engine.TEXTURETYPE_FLOAT);
  14999. };
  15000. Engine.prototype._canRenderToHalfFloatFramebuffer = function () {
  15001. if (this._webGLVersion > 1) {
  15002. return this._caps.colorBufferFloat;
  15003. }
  15004. return this._canRenderToFramebuffer(Engine.TEXTURETYPE_HALF_FLOAT);
  15005. };
  15006. // Thank you : http://stackoverflow.com/questions/28827511/webgl-ios-render-to-floating-point-texture
  15007. Engine.prototype._canRenderToFramebuffer = function (type) {
  15008. var gl = this._gl;
  15009. //clear existing errors
  15010. while (gl.getError() !== gl.NO_ERROR) { }
  15011. var successful = true;
  15012. var texture = gl.createTexture();
  15013. gl.bindTexture(gl.TEXTURE_2D, texture);
  15014. gl.texImage2D(gl.TEXTURE_2D, 0, this._getRGBABufferInternalSizedFormat(type), 1, 1, 0, gl.RGBA, this._getWebGLTextureType(type), null);
  15015. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  15016. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  15017. var fb = gl.createFramebuffer();
  15018. gl.bindFramebuffer(gl.FRAMEBUFFER, fb);
  15019. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texture, 0);
  15020. var status = gl.checkFramebufferStatus(gl.FRAMEBUFFER);
  15021. successful = successful && (status === gl.FRAMEBUFFER_COMPLETE);
  15022. successful = successful && (gl.getError() === gl.NO_ERROR);
  15023. //try render by clearing frame buffer's color buffer
  15024. if (successful) {
  15025. gl.clear(gl.COLOR_BUFFER_BIT);
  15026. successful = successful && (gl.getError() === gl.NO_ERROR);
  15027. }
  15028. //try reading from frame to ensure render occurs (just creating the FBO is not sufficient to determine if rendering is supported)
  15029. if (successful) {
  15030. //in practice it's sufficient to just read from the backbuffer rather than handle potentially issues reading from the texture
  15031. gl.bindFramebuffer(gl.FRAMEBUFFER, null);
  15032. var readFormat = gl.RGBA;
  15033. var readType = gl.UNSIGNED_BYTE;
  15034. var buffer = new Uint8Array(4);
  15035. gl.readPixels(0, 0, 1, 1, readFormat, readType, buffer);
  15036. successful = successful && (gl.getError() === gl.NO_ERROR);
  15037. }
  15038. //clean up
  15039. gl.deleteTexture(texture);
  15040. gl.deleteFramebuffer(fb);
  15041. gl.bindFramebuffer(gl.FRAMEBUFFER, null);
  15042. //clear accumulated errors
  15043. while (!successful && (gl.getError() !== gl.NO_ERROR)) { }
  15044. return successful;
  15045. };
  15046. Engine.prototype._getWebGLTextureType = function (type) {
  15047. if (type === Engine.TEXTURETYPE_FLOAT) {
  15048. return this._gl.FLOAT;
  15049. }
  15050. else if (type === Engine.TEXTURETYPE_HALF_FLOAT) {
  15051. // Add Half Float Constant.
  15052. return this._gl.HALF_FLOAT_OES;
  15053. }
  15054. return this._gl.UNSIGNED_BYTE;
  15055. };
  15056. ;
  15057. /** @ignore */
  15058. Engine.prototype._getRGBABufferInternalSizedFormat = function (type, format) {
  15059. if (this._webGLVersion === 1) {
  15060. return this._gl.RGBA;
  15061. }
  15062. if (type === Engine.TEXTURETYPE_FLOAT) {
  15063. if (format) {
  15064. switch (format) {
  15065. case Engine.TEXTUREFORMAT_R32F:
  15066. return this._gl.R32F;
  15067. case Engine.TEXTUREFORMAT_RG32F:
  15068. return this._gl.RG32F;
  15069. case Engine.TEXTUREFORMAT_RGB32F:
  15070. return this._gl.RGB32F;
  15071. }
  15072. }
  15073. return this._gl.RGBA32F;
  15074. }
  15075. else if (type === Engine.TEXTURETYPE_HALF_FLOAT) {
  15076. return this._gl.RGBA16F;
  15077. }
  15078. return this._gl.RGBA;
  15079. };
  15080. ;
  15081. Engine.prototype._getRGBAMultiSampleBufferFormat = function (type) {
  15082. if (type === Engine.TEXTURETYPE_FLOAT) {
  15083. return this._gl.RGBA32F;
  15084. }
  15085. else if (type === Engine.TEXTURETYPE_HALF_FLOAT) {
  15086. return this._gl.RGBA16F;
  15087. }
  15088. return this._gl.RGBA8;
  15089. };
  15090. ;
  15091. Engine.prototype.createQuery = function () {
  15092. return this._gl.createQuery();
  15093. };
  15094. Engine.prototype.deleteQuery = function (query) {
  15095. this._gl.deleteQuery(query);
  15096. return this;
  15097. };
  15098. Engine.prototype.isQueryResultAvailable = function (query) {
  15099. return this._gl.getQueryParameter(query, this._gl.QUERY_RESULT_AVAILABLE);
  15100. };
  15101. Engine.prototype.getQueryResult = function (query) {
  15102. return this._gl.getQueryParameter(query, this._gl.QUERY_RESULT);
  15103. };
  15104. Engine.prototype.beginOcclusionQuery = function (algorithmType, query) {
  15105. var glAlgorithm = this.getGlAlgorithmType(algorithmType);
  15106. this._gl.beginQuery(glAlgorithm, query);
  15107. return this;
  15108. };
  15109. Engine.prototype.endOcclusionQuery = function (algorithmType) {
  15110. var glAlgorithm = this.getGlAlgorithmType(algorithmType);
  15111. this._gl.endQuery(glAlgorithm);
  15112. return this;
  15113. };
  15114. /* Time queries */
  15115. Engine.prototype._createTimeQuery = function () {
  15116. var timerQuery = this._caps.timerQuery;
  15117. if (timerQuery.createQueryEXT) {
  15118. return timerQuery.createQueryEXT();
  15119. }
  15120. return this.createQuery();
  15121. };
  15122. Engine.prototype._deleteTimeQuery = function (query) {
  15123. var timerQuery = this._caps.timerQuery;
  15124. if (timerQuery.deleteQueryEXT) {
  15125. timerQuery.deleteQueryEXT(query);
  15126. return;
  15127. }
  15128. this.deleteQuery(query);
  15129. };
  15130. Engine.prototype._getTimeQueryResult = function (query) {
  15131. var timerQuery = this._caps.timerQuery;
  15132. if (timerQuery.getQueryObjectEXT) {
  15133. return timerQuery.getQueryObjectEXT(query, timerQuery.QUERY_RESULT_EXT);
  15134. }
  15135. return this.getQueryResult(query);
  15136. };
  15137. Engine.prototype._getTimeQueryAvailability = function (query) {
  15138. var timerQuery = this._caps.timerQuery;
  15139. if (timerQuery.getQueryObjectEXT) {
  15140. return timerQuery.getQueryObjectEXT(query, timerQuery.QUERY_RESULT_AVAILABLE_EXT);
  15141. }
  15142. return this.isQueryResultAvailable(query);
  15143. };
  15144. Engine.prototype.startTimeQuery = function () {
  15145. var timerQuery = this._caps.timerQuery;
  15146. if (!timerQuery) {
  15147. return null;
  15148. }
  15149. var token = new BABYLON._TimeToken();
  15150. this._gl.getParameter(timerQuery.GPU_DISJOINT_EXT);
  15151. if (this._caps.canUseTimestampForTimerQuery) {
  15152. token._startTimeQuery = this._createTimeQuery();
  15153. timerQuery.queryCounterEXT(token._startTimeQuery, timerQuery.TIMESTAMP_EXT);
  15154. }
  15155. else {
  15156. if (this._currentNonTimestampToken) {
  15157. return this._currentNonTimestampToken;
  15158. }
  15159. token._timeElapsedQuery = this._createTimeQuery();
  15160. if (timerQuery.beginQueryEXT) {
  15161. timerQuery.beginQueryEXT(timerQuery.TIME_ELAPSED_EXT, token._timeElapsedQuery);
  15162. }
  15163. else {
  15164. this._gl.beginQuery(timerQuery.TIME_ELAPSED_EXT, token._timeElapsedQuery);
  15165. }
  15166. this._currentNonTimestampToken = token;
  15167. }
  15168. return token;
  15169. };
  15170. Engine.prototype.endTimeQuery = function (token) {
  15171. var timerQuery = this._caps.timerQuery;
  15172. if (!timerQuery || !token) {
  15173. return -1;
  15174. }
  15175. if (this._caps.canUseTimestampForTimerQuery) {
  15176. if (!token._startTimeQuery) {
  15177. return -1;
  15178. }
  15179. if (!token._endTimeQuery) {
  15180. token._endTimeQuery = this._createTimeQuery();
  15181. timerQuery.queryCounterEXT(token._endTimeQuery, timerQuery.TIMESTAMP_EXT);
  15182. }
  15183. }
  15184. else if (!token._timeElapsedQueryEnded) {
  15185. if (!token._timeElapsedQuery) {
  15186. return -1;
  15187. }
  15188. if (timerQuery.endQueryEXT) {
  15189. timerQuery.endQueryEXT(timerQuery.TIME_ELAPSED_EXT);
  15190. }
  15191. else {
  15192. this._gl.endQuery(timerQuery.TIME_ELAPSED_EXT);
  15193. }
  15194. token._timeElapsedQueryEnded = true;
  15195. }
  15196. var disjoint = this._gl.getParameter(timerQuery.GPU_DISJOINT_EXT);
  15197. var available = false;
  15198. if (token._endTimeQuery) {
  15199. available = this._getTimeQueryAvailability(token._endTimeQuery);
  15200. }
  15201. else if (token._timeElapsedQuery) {
  15202. available = this._getTimeQueryAvailability(token._timeElapsedQuery);
  15203. }
  15204. if (available && !disjoint) {
  15205. var result = 0;
  15206. if (this._caps.canUseTimestampForTimerQuery) {
  15207. if (!token._startTimeQuery || !token._endTimeQuery) {
  15208. return -1;
  15209. }
  15210. var timeStart = this._getTimeQueryResult(token._startTimeQuery);
  15211. var timeEnd = this._getTimeQueryResult(token._endTimeQuery);
  15212. result = timeEnd - timeStart;
  15213. this._deleteTimeQuery(token._startTimeQuery);
  15214. this._deleteTimeQuery(token._endTimeQuery);
  15215. token._startTimeQuery = null;
  15216. token._endTimeQuery = null;
  15217. }
  15218. else {
  15219. if (!token._timeElapsedQuery) {
  15220. return -1;
  15221. }
  15222. result = this._getTimeQueryResult(token._timeElapsedQuery);
  15223. this._deleteTimeQuery(token._timeElapsedQuery);
  15224. token._timeElapsedQuery = null;
  15225. token._timeElapsedQueryEnded = false;
  15226. this._currentNonTimestampToken = null;
  15227. }
  15228. return result;
  15229. }
  15230. return -1;
  15231. };
  15232. Engine.prototype.getGlAlgorithmType = function (algorithmType) {
  15233. return algorithmType === BABYLON.AbstractMesh.OCCLUSION_ALGORITHM_TYPE_CONSERVATIVE ? this._gl.ANY_SAMPLES_PASSED_CONSERVATIVE : this._gl.ANY_SAMPLES_PASSED;
  15234. };
  15235. // Transform feedback
  15236. Engine.prototype.createTransformFeedback = function () {
  15237. return this._gl.createTransformFeedback();
  15238. };
  15239. Engine.prototype.deleteTransformFeedback = function (value) {
  15240. this._gl.deleteTransformFeedback(value);
  15241. };
  15242. Engine.prototype.bindTransformFeedback = function (value) {
  15243. this._gl.bindTransformFeedback(this._gl.TRANSFORM_FEEDBACK, value);
  15244. };
  15245. Engine.prototype.beginTransformFeedback = function (usePoints) {
  15246. if (usePoints === void 0) { usePoints = true; }
  15247. this._gl.beginTransformFeedback(usePoints ? this._gl.POINTS : this._gl.TRIANGLES);
  15248. };
  15249. Engine.prototype.endTransformFeedback = function () {
  15250. this._gl.endTransformFeedback();
  15251. };
  15252. Engine.prototype.setTranformFeedbackVaryings = function (program, value) {
  15253. this._gl.transformFeedbackVaryings(program, value, this._gl.INTERLEAVED_ATTRIBS);
  15254. };
  15255. Engine.prototype.bindTransformFeedbackBuffer = function (value) {
  15256. this._gl.bindBufferBase(this._gl.TRANSFORM_FEEDBACK_BUFFER, 0, value);
  15257. };
  15258. Engine.prototype._loadFile = function (url, onSuccess, onProgress, database, useArrayBuffer, onError) {
  15259. var _this = this;
  15260. var request = BABYLON.Tools.LoadFile(url, onSuccess, onProgress, database, useArrayBuffer, onError);
  15261. this._activeRequests.push(request);
  15262. request.onCompleteObservable.add(function (request) {
  15263. _this._activeRequests.splice(_this._activeRequests.indexOf(request), 1);
  15264. });
  15265. return request;
  15266. };
  15267. /** @ignore */
  15268. Engine.prototype._loadFileAsync = function (url, database, useArrayBuffer) {
  15269. var _this = this;
  15270. return new Promise(function (resolve, reject) {
  15271. _this._loadFile(url, function (data) {
  15272. resolve(data);
  15273. }, undefined, database, useArrayBuffer, function (request, exception) {
  15274. reject(exception);
  15275. });
  15276. });
  15277. };
  15278. Engine.prototype._partialLoadFile = function (url, index, loadedFiles, scene, onfinish, onErrorCallBack) {
  15279. if (onErrorCallBack === void 0) { onErrorCallBack = null; }
  15280. var onload = function (data) {
  15281. loadedFiles[index] = data;
  15282. loadedFiles._internalCount++;
  15283. if (loadedFiles._internalCount === 6) {
  15284. onfinish(loadedFiles);
  15285. }
  15286. };
  15287. var onerror = function (request, exception) {
  15288. if (onErrorCallBack && request) {
  15289. onErrorCallBack(request.status + " " + request.statusText, exception);
  15290. }
  15291. };
  15292. this._loadFile(url, onload, undefined, undefined, true, onerror);
  15293. };
  15294. Engine.prototype._cascadeLoadFiles = function (scene, onfinish, files, onError) {
  15295. if (onError === void 0) { onError = null; }
  15296. var loadedFiles = [];
  15297. loadedFiles._internalCount = 0;
  15298. for (var index = 0; index < 6; index++) {
  15299. this._partialLoadFile(files[index], index, loadedFiles, scene, onfinish, onError);
  15300. }
  15301. };
  15302. // Statics
  15303. Engine.isSupported = function () {
  15304. try {
  15305. var tempcanvas = document.createElement("canvas");
  15306. var gl = tempcanvas.getContext("webgl") || tempcanvas.getContext("experimental-webgl");
  15307. return gl != null && !!window.WebGLRenderingContext;
  15308. }
  15309. catch (e) {
  15310. return false;
  15311. }
  15312. };
  15313. /** Use this array to turn off some WebGL2 features on known buggy browsers version */
  15314. Engine.ExceptionList = [
  15315. { key: "Chrome/63.0", capture: "63\\.0\\.3239\\.(\\d+)", captureConstraint: 108, targets: ["uniformBuffer"] },
  15316. { key: "Firefox/58", capture: null, captureConstraint: null, targets: ["uniformBuffer"] },
  15317. { key: "Firefox/59", capture: null, captureConstraint: null, targets: ["uniformBuffer"] },
  15318. { key: "Macintosh", capture: null, captureConstraint: null, targets: ["textureBindingOptimization"] },
  15319. { key: "iPhone", capture: null, captureConstraint: null, targets: ["textureBindingOptimization"] },
  15320. { key: "iPad", capture: null, captureConstraint: null, targets: ["textureBindingOptimization"] }
  15321. ];
  15322. Engine.Instances = new Array();
  15323. // Const statics
  15324. Engine._ALPHA_DISABLE = 0;
  15325. Engine._ALPHA_ADD = 1;
  15326. Engine._ALPHA_COMBINE = 2;
  15327. Engine._ALPHA_SUBTRACT = 3;
  15328. Engine._ALPHA_MULTIPLY = 4;
  15329. Engine._ALPHA_MAXIMIZED = 5;
  15330. Engine._ALPHA_ONEONE = 6;
  15331. Engine._ALPHA_PREMULTIPLIED = 7;
  15332. Engine._ALPHA_PREMULTIPLIED_PORTERDUFF = 8;
  15333. Engine._ALPHA_INTERPOLATE = 9;
  15334. Engine._ALPHA_SCREENMODE = 10;
  15335. Engine._DELAYLOADSTATE_NONE = 0;
  15336. Engine._DELAYLOADSTATE_LOADED = 1;
  15337. Engine._DELAYLOADSTATE_LOADING = 2;
  15338. Engine._DELAYLOADSTATE_NOTLOADED = 4;
  15339. Engine._TEXTUREFORMAT_ALPHA = 0;
  15340. Engine._TEXTUREFORMAT_LUMINANCE = 1;
  15341. Engine._TEXTUREFORMAT_LUMINANCE_ALPHA = 2;
  15342. Engine._TEXTUREFORMAT_RGB = 4;
  15343. Engine._TEXTUREFORMAT_RGBA = 5;
  15344. Engine._TEXTUREFORMAT_R32F = 6;
  15345. Engine._TEXTUREFORMAT_RG32F = 7;
  15346. Engine._TEXTUREFORMAT_RGB32F = 8;
  15347. Engine._TEXTUREFORMAT_RGBA32F = 9;
  15348. Engine._TEXTURETYPE_UNSIGNED_INT = 0;
  15349. Engine._TEXTURETYPE_FLOAT = 1;
  15350. Engine._TEXTURETYPE_HALF_FLOAT = 2;
  15351. // Depht or Stencil test Constants.
  15352. Engine._NEVER = 0x0200; // Passed to depthFunction or stencilFunction to specify depth or stencil tests will never pass. i.e. Nothing will be drawn.
  15353. 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.
  15354. 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.
  15355. 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.
  15356. 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.
  15357. 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.
  15358. 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.
  15359. 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.
  15360. // Stencil Actions Constants.
  15361. Engine._KEEP = 0x1E00;
  15362. Engine._REPLACE = 0x1E01;
  15363. Engine._INCR = 0x1E02;
  15364. Engine._DECR = 0x1E03;
  15365. Engine._INVERT = 0x150A;
  15366. Engine._INCR_WRAP = 0x8507;
  15367. Engine._DECR_WRAP = 0x8508;
  15368. // Texture rescaling mode
  15369. Engine._SCALEMODE_FLOOR = 1;
  15370. Engine._SCALEMODE_NEAREST = 2;
  15371. Engine._SCALEMODE_CEILING = 3;
  15372. // Updatable statics so stick with vars here
  15373. Engine.CollisionsEpsilon = 0.001;
  15374. Engine.CodeRepository = "src/";
  15375. Engine.ShadersRepository = "src/Shaders/";
  15376. return Engine;
  15377. }());
  15378. BABYLON.Engine = Engine;
  15379. })(BABYLON || (BABYLON = {}));
  15380. //# sourceMappingURL=babylon.engine.js.map
  15381. var BABYLON;
  15382. (function (BABYLON) {
  15383. /**
  15384. * Node is the basic class for all scene objects (Mesh, Light Camera).
  15385. */
  15386. var Node = /** @class */ (function () {
  15387. /**
  15388. * Creates a new Node
  15389. * @param {string} name - the name and id to be given to this node
  15390. * @param {BABYLON.Scene} the scene this node will be added to
  15391. */
  15392. function Node(name, scene) {
  15393. if (scene === void 0) { scene = null; }
  15394. /**
  15395. * Gets or sets a string used to store user defined state for the node
  15396. */
  15397. this.state = "";
  15398. /**
  15399. * Gets or sets an object used to store user defined information for the node
  15400. */
  15401. this.metadata = null;
  15402. /**
  15403. * Gets or sets a boolean used to define if the node must be serialized
  15404. */
  15405. this.doNotSerialize = false;
  15406. /** @ignore */
  15407. this._isDisposed = false;
  15408. /**
  15409. * Gets a list of {BABYLON.Animation} associated with the node
  15410. */
  15411. this.animations = new Array();
  15412. this._ranges = {};
  15413. this._isEnabled = true;
  15414. this._isReady = true;
  15415. /** @ignore */
  15416. this._currentRenderId = -1;
  15417. this._parentRenderId = -1;
  15418. this._animationPropertiesOverride = null;
  15419. /**
  15420. * An event triggered when the mesh is disposed
  15421. * @type {BABYLON.Observable}
  15422. */
  15423. this.onDisposeObservable = new BABYLON.Observable();
  15424. // Behaviors
  15425. this._behaviors = new Array();
  15426. this.name = name;
  15427. this.id = name;
  15428. this._scene = (scene || BABYLON.Engine.LastCreatedScene);
  15429. this.uniqueId = this._scene.getUniqueId();
  15430. this._initCache();
  15431. }
  15432. /**
  15433. * Gets a boolean indicating if the node has been disposed
  15434. * @returns true if the node was disposed
  15435. */
  15436. Node.prototype.isDisposed = function () {
  15437. return this._isDisposed;
  15438. };
  15439. Object.defineProperty(Node.prototype, "parent", {
  15440. get: function () {
  15441. return this._parentNode;
  15442. },
  15443. /**
  15444. * Gets or sets the parent of the node
  15445. */
  15446. set: function (parent) {
  15447. if (this._parentNode === parent) {
  15448. return;
  15449. }
  15450. // Remove self from list of children of parent
  15451. if (this._parentNode && this._parentNode._children !== undefined && this._parentNode._children !== null) {
  15452. var index = this._parentNode._children.indexOf(this);
  15453. if (index !== -1) {
  15454. this._parentNode._children.splice(index, 1);
  15455. }
  15456. }
  15457. // Store new parent
  15458. this._parentNode = parent;
  15459. // Add as child to new parent
  15460. if (this._parentNode) {
  15461. if (this._parentNode._children === undefined || this._parentNode._children === null) {
  15462. this._parentNode._children = new Array();
  15463. }
  15464. this._parentNode._children.push(this);
  15465. }
  15466. },
  15467. enumerable: true,
  15468. configurable: true
  15469. });
  15470. Object.defineProperty(Node.prototype, "animationPropertiesOverride", {
  15471. /**
  15472. * Gets or sets the animation properties override
  15473. */
  15474. get: function () {
  15475. return this._animationPropertiesOverride;
  15476. },
  15477. set: function (value) {
  15478. this._animationPropertiesOverride = value;
  15479. },
  15480. enumerable: true,
  15481. configurable: true
  15482. });
  15483. /**
  15484. * Gets a string idenfifying the name of the class
  15485. * @returns "Node" string
  15486. */
  15487. Node.prototype.getClassName = function () {
  15488. return "Node";
  15489. };
  15490. Object.defineProperty(Node.prototype, "onDispose", {
  15491. /**
  15492. * Sets a callback that will be raised when the node will be disposed
  15493. */
  15494. set: function (callback) {
  15495. if (this._onDisposeObserver) {
  15496. this.onDisposeObservable.remove(this._onDisposeObserver);
  15497. }
  15498. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  15499. },
  15500. enumerable: true,
  15501. configurable: true
  15502. });
  15503. /**
  15504. * Gets the scene of the node
  15505. * @returns a {BABYLON.Scene}
  15506. */
  15507. Node.prototype.getScene = function () {
  15508. return this._scene;
  15509. };
  15510. /**
  15511. * Gets the engine of the node
  15512. * @returns a {BABYLON.Engine}
  15513. */
  15514. Node.prototype.getEngine = function () {
  15515. return this._scene.getEngine();
  15516. };
  15517. /**
  15518. * Attach a behavior to the node
  15519. * @see http://doc.babylonjs.com/features/behaviour
  15520. * @param behavior defines the behavior to attach
  15521. * @returns the current Node
  15522. */
  15523. Node.prototype.addBehavior = function (behavior) {
  15524. var _this = this;
  15525. var index = this._behaviors.indexOf(behavior);
  15526. if (index !== -1) {
  15527. return this;
  15528. }
  15529. behavior.init();
  15530. if (this._scene.isLoading) {
  15531. // We defer the attach when the scene will be loaded
  15532. var observer = this._scene.onDataLoadedObservable.add(function () {
  15533. behavior.attach(_this);
  15534. setTimeout(function () {
  15535. // Need to use a timeout to avoid removing an observer while iterating the list of observers
  15536. _this._scene.onDataLoadedObservable.remove(observer);
  15537. }, 0);
  15538. });
  15539. }
  15540. else {
  15541. behavior.attach(this);
  15542. }
  15543. this._behaviors.push(behavior);
  15544. return this;
  15545. };
  15546. /**
  15547. * Remove an attached behavior
  15548. * @see http://doc.babylonjs.com/features/behaviour
  15549. * @param behavior defines the behavior to attach
  15550. * @returns the current Node
  15551. */
  15552. Node.prototype.removeBehavior = function (behavior) {
  15553. var index = this._behaviors.indexOf(behavior);
  15554. if (index === -1) {
  15555. return this;
  15556. }
  15557. this._behaviors[index].detach();
  15558. this._behaviors.splice(index, 1);
  15559. return this;
  15560. };
  15561. Object.defineProperty(Node.prototype, "behaviors", {
  15562. /**
  15563. * Gets the list of attached behaviors
  15564. * @see http://doc.babylonjs.com/features/behaviour
  15565. */
  15566. get: function () {
  15567. return this._behaviors;
  15568. },
  15569. enumerable: true,
  15570. configurable: true
  15571. });
  15572. /**
  15573. * Gets an attached behavior by name
  15574. * @param name defines the name of the behavior to look for
  15575. * @see http://doc.babylonjs.com/features/behaviour
  15576. * @returns null if behavior was not found else the requested behavior
  15577. */
  15578. Node.prototype.getBehaviorByName = function (name) {
  15579. for (var _i = 0, _a = this._behaviors; _i < _a.length; _i++) {
  15580. var behavior = _a[_i];
  15581. if (behavior.name === name) {
  15582. return behavior;
  15583. }
  15584. }
  15585. return null;
  15586. };
  15587. /**
  15588. * Returns the world matrix of the node
  15589. * @returns a matrix containing the node's world matrix
  15590. */
  15591. Node.prototype.getWorldMatrix = function () {
  15592. return BABYLON.Matrix.Identity();
  15593. };
  15594. // override it in derived class if you add new variables to the cache
  15595. // and call the parent class method
  15596. /** @ignore */
  15597. Node.prototype._initCache = function () {
  15598. this._cache = {};
  15599. this._cache.parent = undefined;
  15600. };
  15601. /** @ignore */
  15602. Node.prototype.updateCache = function (force) {
  15603. if (!force && this.isSynchronized())
  15604. return;
  15605. this._cache.parent = this.parent;
  15606. this._updateCache();
  15607. };
  15608. // override it in derived class if you add new variables to the cache
  15609. // and call the parent class method if !ignoreParentClass
  15610. /** @ignore */
  15611. Node.prototype._updateCache = function (ignoreParentClass) {
  15612. };
  15613. // override it in derived class if you add new variables to the cache
  15614. /** @ignore */
  15615. Node.prototype._isSynchronized = function () {
  15616. return true;
  15617. };
  15618. /** @ignore */
  15619. Node.prototype._markSyncedWithParent = function () {
  15620. if (this.parent) {
  15621. this._parentRenderId = this.parent._currentRenderId;
  15622. }
  15623. };
  15624. /** @ignore */
  15625. Node.prototype.isSynchronizedWithParent = function () {
  15626. if (!this.parent) {
  15627. return true;
  15628. }
  15629. if (this._parentRenderId !== this.parent._currentRenderId) {
  15630. return false;
  15631. }
  15632. return this.parent.isSynchronized();
  15633. };
  15634. /** @ignore */
  15635. Node.prototype.isSynchronized = function (updateCache) {
  15636. var check = this.hasNewParent();
  15637. check = check || !this.isSynchronizedWithParent();
  15638. check = check || !this._isSynchronized();
  15639. if (updateCache)
  15640. this.updateCache(true);
  15641. return !check;
  15642. };
  15643. /** @ignore */
  15644. Node.prototype.hasNewParent = function (update) {
  15645. if (this._cache.parent === this.parent)
  15646. return false;
  15647. if (update)
  15648. this._cache.parent = this.parent;
  15649. return true;
  15650. };
  15651. /**
  15652. * Is this node ready to be used/rendered
  15653. * @param completeCheck defines if a complete check (including materials and lights) has to be done (false by default)
  15654. * @return true if the node is ready
  15655. */
  15656. Node.prototype.isReady = function (completeCheck) {
  15657. if (completeCheck === void 0) { completeCheck = false; }
  15658. return this._isReady;
  15659. };
  15660. /**
  15661. * Is this node enabled?
  15662. * 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
  15663. * @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
  15664. * @return whether this node (and its parent) is enabled
  15665. * @see setEnabled
  15666. */
  15667. Node.prototype.isEnabled = function (checkAncestors) {
  15668. if (checkAncestors === void 0) { checkAncestors = true; }
  15669. if (checkAncestors === false) {
  15670. return this._isEnabled;
  15671. }
  15672. if (this._isEnabled === false) {
  15673. return false;
  15674. }
  15675. if (this.parent !== undefined && this.parent !== null) {
  15676. return this.parent.isEnabled(checkAncestors);
  15677. }
  15678. return true;
  15679. };
  15680. /**
  15681. * Set the enabled state of this node
  15682. * @param value defines the new enabled state
  15683. * @see isEnabled
  15684. */
  15685. Node.prototype.setEnabled = function (value) {
  15686. this._isEnabled = value;
  15687. };
  15688. /**
  15689. * Is this node a descendant of the given node?
  15690. * The function will iterate up the hierarchy until the ancestor was found or no more parents defined
  15691. * @param ancestor defines the parent node to inspect
  15692. * @see parent
  15693. * @returns a boolean indicating if this node is a descendant of the given node
  15694. */
  15695. Node.prototype.isDescendantOf = function (ancestor) {
  15696. if (this.parent) {
  15697. if (this.parent === ancestor) {
  15698. return true;
  15699. }
  15700. return this.parent.isDescendantOf(ancestor);
  15701. }
  15702. return false;
  15703. };
  15704. /** @ignore */
  15705. Node.prototype._getDescendants = function (results, directDescendantsOnly, predicate) {
  15706. if (directDescendantsOnly === void 0) { directDescendantsOnly = false; }
  15707. if (!this._children) {
  15708. return;
  15709. }
  15710. for (var index = 0; index < this._children.length; index++) {
  15711. var item = this._children[index];
  15712. if (!predicate || predicate(item)) {
  15713. results.push(item);
  15714. }
  15715. if (!directDescendantsOnly) {
  15716. item._getDescendants(results, false, predicate);
  15717. }
  15718. }
  15719. };
  15720. /**
  15721. * Will return all nodes that have this node as ascendant
  15722. * @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
  15723. * @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
  15724. * @return all children nodes of all types
  15725. */
  15726. Node.prototype.getDescendants = function (directDescendantsOnly, predicate) {
  15727. var results = new Array();
  15728. this._getDescendants(results, directDescendantsOnly, predicate);
  15729. return results;
  15730. };
  15731. /**
  15732. * Get all child-meshes of this node
  15733. * @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
  15734. * @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
  15735. * @returns an array of {BABYLON.AbstractMesh}
  15736. */
  15737. Node.prototype.getChildMeshes = function (directDescendantsOnly, predicate) {
  15738. var results = [];
  15739. this._getDescendants(results, directDescendantsOnly, function (node) {
  15740. return ((!predicate || predicate(node)) && (node instanceof BABYLON.AbstractMesh));
  15741. });
  15742. return results;
  15743. };
  15744. /**
  15745. * Get all child-transformNodes of this node
  15746. * @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
  15747. * @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
  15748. * @returns an array of {BABYLON.TransformNode}
  15749. */
  15750. Node.prototype.getChildTransformNodes = function (directDescendantsOnly, predicate) {
  15751. var results = [];
  15752. this._getDescendants(results, directDescendantsOnly, function (node) {
  15753. return ((!predicate || predicate(node)) && (node instanceof BABYLON.TransformNode));
  15754. });
  15755. return results;
  15756. };
  15757. /**
  15758. * Get all direct children of this node
  15759. * @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
  15760. * @returns an array of {BABYLON.Node}
  15761. */
  15762. Node.prototype.getChildren = function (predicate) {
  15763. return this.getDescendants(true, predicate);
  15764. };
  15765. /** @ignore */
  15766. Node.prototype._setReady = function (state) {
  15767. if (state === this._isReady) {
  15768. return;
  15769. }
  15770. if (!state) {
  15771. this._isReady = false;
  15772. return;
  15773. }
  15774. this._isReady = true;
  15775. if (this.onReady) {
  15776. this.onReady(this);
  15777. }
  15778. };
  15779. /**
  15780. * Get an animation by name
  15781. * @param name defines the name of the animation to look for
  15782. * @returns null if not found else the requested animation
  15783. */
  15784. Node.prototype.getAnimationByName = function (name) {
  15785. for (var i = 0; i < this.animations.length; i++) {
  15786. var animation = this.animations[i];
  15787. if (animation.name === name) {
  15788. return animation;
  15789. }
  15790. }
  15791. return null;
  15792. };
  15793. /**
  15794. * Creates an animation range for this node
  15795. * @param name defines the name of the range
  15796. * @param from defines the starting key
  15797. * @param to defines the end key
  15798. */
  15799. Node.prototype.createAnimationRange = function (name, from, to) {
  15800. // check name not already in use
  15801. if (!this._ranges[name]) {
  15802. this._ranges[name] = new BABYLON.AnimationRange(name, from, to);
  15803. for (var i = 0, nAnimations = this.animations.length; i < nAnimations; i++) {
  15804. if (this.animations[i]) {
  15805. this.animations[i].createRange(name, from, to);
  15806. }
  15807. }
  15808. }
  15809. };
  15810. /**
  15811. * Delete a specific animation range
  15812. * @param name defines the name of the range to delete
  15813. * @param deleteFrames defines if animation frames from the range must be deleted as well
  15814. */
  15815. Node.prototype.deleteAnimationRange = function (name, deleteFrames) {
  15816. if (deleteFrames === void 0) { deleteFrames = true; }
  15817. for (var i = 0, nAnimations = this.animations.length; i < nAnimations; i++) {
  15818. if (this.animations[i]) {
  15819. this.animations[i].deleteRange(name, deleteFrames);
  15820. }
  15821. }
  15822. this._ranges[name] = null; // said much faster than 'delete this._range[name]'
  15823. };
  15824. /**
  15825. * Get an animation range by name
  15826. * @param name defines the name of the animation range to look for
  15827. * @returns null if not found else the requested animation range
  15828. */
  15829. Node.prototype.getAnimationRange = function (name) {
  15830. return this._ranges[name];
  15831. };
  15832. /**
  15833. * Will start the animation sequence
  15834. * @param name defines the range frames for animation sequence
  15835. * @param loop defines if the animation should loop (false by default)
  15836. * @param speedRatio defines the speed factor in which to run the animation (1 by default)
  15837. * @param onAnimationEnd defines a function to be executed when the animation ended (undefined by default)
  15838. * @returns the object created for this animation. If range does not exist, it will return null
  15839. */
  15840. Node.prototype.beginAnimation = function (name, loop, speedRatio, onAnimationEnd) {
  15841. var range = this.getAnimationRange(name);
  15842. if (!range) {
  15843. return null;
  15844. }
  15845. return this._scene.beginAnimation(this, range.from, range.to, loop, speedRatio, onAnimationEnd);
  15846. };
  15847. /**
  15848. * Serialize animation ranges into a JSON compatible object
  15849. * @returns serialization object
  15850. */
  15851. Node.prototype.serializeAnimationRanges = function () {
  15852. var serializationRanges = [];
  15853. for (var name in this._ranges) {
  15854. var localRange = this._ranges[name];
  15855. if (!localRange) {
  15856. continue;
  15857. }
  15858. var range = {};
  15859. range.name = name;
  15860. range.from = localRange.from;
  15861. range.to = localRange.to;
  15862. serializationRanges.push(range);
  15863. }
  15864. return serializationRanges;
  15865. };
  15866. /**
  15867. * Computes the world matrix of the node
  15868. * @param force defines if the cache version should be invalidated forcing the world matrix to be created from scratch
  15869. * @returns the world matrix
  15870. */
  15871. Node.prototype.computeWorldMatrix = function (force) {
  15872. return BABYLON.Matrix.Identity();
  15873. };
  15874. /**
  15875. * Releases resources associated with this node.
  15876. * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default)
  15877. * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default)
  15878. */
  15879. Node.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  15880. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  15881. if (!doNotRecurse) {
  15882. var nodes = this.getDescendants(true);
  15883. for (var _i = 0, nodes_1 = nodes; _i < nodes_1.length; _i++) {
  15884. var node = nodes_1[_i];
  15885. node.dispose(doNotRecurse, disposeMaterialAndTextures);
  15886. }
  15887. }
  15888. else {
  15889. var transformNodes = this.getChildTransformNodes(true);
  15890. for (var _a = 0, transformNodes_1 = transformNodes; _a < transformNodes_1.length; _a++) {
  15891. var transformNode = transformNodes_1[_a];
  15892. transformNode.parent = null;
  15893. transformNode.computeWorldMatrix(true);
  15894. }
  15895. }
  15896. this.parent = null;
  15897. // Callback
  15898. this.onDisposeObservable.notifyObservers(this);
  15899. this.onDisposeObservable.clear();
  15900. // Behaviors
  15901. for (var _b = 0, _c = this._behaviors; _b < _c.length; _b++) {
  15902. var behavior = _c[_b];
  15903. behavior.detach();
  15904. }
  15905. this._behaviors = [];
  15906. this._isDisposed = true;
  15907. };
  15908. /**
  15909. * Parse animation range data from a serialization object and store them into a given node
  15910. * @param node defines where to store the animation ranges
  15911. * @param parsedNode defines the serialization object to read data from
  15912. * @param scene defines the hosting scene
  15913. */
  15914. Node.ParseAnimationRanges = function (node, parsedNode, scene) {
  15915. if (parsedNode.ranges) {
  15916. for (var index = 0; index < parsedNode.ranges.length; index++) {
  15917. var data = parsedNode.ranges[index];
  15918. node.createAnimationRange(data.name, data.from, data.to);
  15919. }
  15920. }
  15921. };
  15922. __decorate([
  15923. BABYLON.serialize()
  15924. ], Node.prototype, "name", void 0);
  15925. __decorate([
  15926. BABYLON.serialize()
  15927. ], Node.prototype, "id", void 0);
  15928. __decorate([
  15929. BABYLON.serialize()
  15930. ], Node.prototype, "uniqueId", void 0);
  15931. __decorate([
  15932. BABYLON.serialize()
  15933. ], Node.prototype, "state", void 0);
  15934. __decorate([
  15935. BABYLON.serialize()
  15936. ], Node.prototype, "metadata", void 0);
  15937. return Node;
  15938. }());
  15939. BABYLON.Node = Node;
  15940. })(BABYLON || (BABYLON = {}));
  15941. //# sourceMappingURL=babylon.node.js.map
  15942. var BABYLON;
  15943. (function (BABYLON) {
  15944. var BoundingSphere = /** @class */ (function () {
  15945. function BoundingSphere(minimum, maximum) {
  15946. this.minimum = minimum;
  15947. this.maximum = maximum;
  15948. this._tempRadiusVector = BABYLON.Vector3.Zero();
  15949. var distance = BABYLON.Vector3.Distance(minimum, maximum);
  15950. this.center = BABYLON.Vector3.Lerp(minimum, maximum, 0.5);
  15951. this.radius = distance * 0.5;
  15952. this.centerWorld = BABYLON.Vector3.Zero();
  15953. this._update(BABYLON.Matrix.Identity());
  15954. }
  15955. // Methods
  15956. BoundingSphere.prototype._update = function (world) {
  15957. BABYLON.Vector3.TransformCoordinatesToRef(this.center, world, this.centerWorld);
  15958. BABYLON.Vector3.TransformNormalFromFloatsToRef(1.0, 1.0, 1.0, world, this._tempRadiusVector);
  15959. this.radiusWorld = Math.max(Math.abs(this._tempRadiusVector.x), Math.abs(this._tempRadiusVector.y), Math.abs(this._tempRadiusVector.z)) * this.radius;
  15960. };
  15961. BoundingSphere.prototype.isInFrustum = function (frustumPlanes) {
  15962. for (var i = 0; i < 6; i++) {
  15963. if (frustumPlanes[i].dotCoordinate(this.centerWorld) <= -this.radiusWorld)
  15964. return false;
  15965. }
  15966. return true;
  15967. };
  15968. BoundingSphere.prototype.intersectsPoint = function (point) {
  15969. var x = this.centerWorld.x - point.x;
  15970. var y = this.centerWorld.y - point.y;
  15971. var z = this.centerWorld.z - point.z;
  15972. var distance = Math.sqrt((x * x) + (y * y) + (z * z));
  15973. if (Math.abs(this.radiusWorld - distance) < BABYLON.Epsilon)
  15974. return false;
  15975. return true;
  15976. };
  15977. // Statics
  15978. BoundingSphere.Intersects = function (sphere0, sphere1) {
  15979. var x = sphere0.centerWorld.x - sphere1.centerWorld.x;
  15980. var y = sphere0.centerWorld.y - sphere1.centerWorld.y;
  15981. var z = sphere0.centerWorld.z - sphere1.centerWorld.z;
  15982. var distance = Math.sqrt((x * x) + (y * y) + (z * z));
  15983. if (sphere0.radiusWorld + sphere1.radiusWorld < distance)
  15984. return false;
  15985. return true;
  15986. };
  15987. return BoundingSphere;
  15988. }());
  15989. BABYLON.BoundingSphere = BoundingSphere;
  15990. })(BABYLON || (BABYLON = {}));
  15991. //# sourceMappingURL=babylon.boundingSphere.js.map
  15992. var BABYLON;
  15993. (function (BABYLON) {
  15994. var BoundingBox = /** @class */ (function () {
  15995. function BoundingBox(minimum, maximum) {
  15996. this.minimum = minimum;
  15997. this.maximum = maximum;
  15998. this.vectors = new Array();
  15999. this.vectorsWorld = new Array();
  16000. // Bounding vectors
  16001. this.vectors.push(this.minimum.clone());
  16002. this.vectors.push(this.maximum.clone());
  16003. this.vectors.push(this.minimum.clone());
  16004. this.vectors[2].x = this.maximum.x;
  16005. this.vectors.push(this.minimum.clone());
  16006. this.vectors[3].y = this.maximum.y;
  16007. this.vectors.push(this.minimum.clone());
  16008. this.vectors[4].z = this.maximum.z;
  16009. this.vectors.push(this.maximum.clone());
  16010. this.vectors[5].z = this.minimum.z;
  16011. this.vectors.push(this.maximum.clone());
  16012. this.vectors[6].x = this.minimum.x;
  16013. this.vectors.push(this.maximum.clone());
  16014. this.vectors[7].y = this.minimum.y;
  16015. // OBB
  16016. this.center = this.maximum.add(this.minimum).scale(0.5);
  16017. this.extendSize = this.maximum.subtract(this.minimum).scale(0.5);
  16018. this.directions = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  16019. // World
  16020. for (var index = 0; index < this.vectors.length; index++) {
  16021. this.vectorsWorld[index] = BABYLON.Vector3.Zero();
  16022. }
  16023. this.minimumWorld = BABYLON.Vector3.Zero();
  16024. this.maximumWorld = BABYLON.Vector3.Zero();
  16025. this.centerWorld = BABYLON.Vector3.Zero();
  16026. this.extendSizeWorld = BABYLON.Vector3.Zero();
  16027. this._update(BABYLON.Matrix.Identity());
  16028. }
  16029. // Methods
  16030. BoundingBox.prototype.getWorldMatrix = function () {
  16031. return this._worldMatrix;
  16032. };
  16033. BoundingBox.prototype.setWorldMatrix = function (matrix) {
  16034. this._worldMatrix.copyFrom(matrix);
  16035. return this;
  16036. };
  16037. BoundingBox.prototype._update = function (world) {
  16038. BABYLON.Vector3.FromFloatsToRef(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, this.minimumWorld);
  16039. BABYLON.Vector3.FromFloatsToRef(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE, this.maximumWorld);
  16040. for (var index = 0; index < this.vectors.length; index++) {
  16041. var v = this.vectorsWorld[index];
  16042. BABYLON.Vector3.TransformCoordinatesToRef(this.vectors[index], world, v);
  16043. if (v.x < this.minimumWorld.x)
  16044. this.minimumWorld.x = v.x;
  16045. if (v.y < this.minimumWorld.y)
  16046. this.minimumWorld.y = v.y;
  16047. if (v.z < this.minimumWorld.z)
  16048. this.minimumWorld.z = v.z;
  16049. if (v.x > this.maximumWorld.x)
  16050. this.maximumWorld.x = v.x;
  16051. if (v.y > this.maximumWorld.y)
  16052. this.maximumWorld.y = v.y;
  16053. if (v.z > this.maximumWorld.z)
  16054. this.maximumWorld.z = v.z;
  16055. }
  16056. // Extend
  16057. this.maximumWorld.subtractToRef(this.minimumWorld, this.extendSizeWorld);
  16058. this.extendSizeWorld.scaleInPlace(0.5);
  16059. // OBB
  16060. this.maximumWorld.addToRef(this.minimumWorld, this.centerWorld);
  16061. this.centerWorld.scaleInPlace(0.5);
  16062. BABYLON.Vector3.FromFloatArrayToRef(world.m, 0, this.directions[0]);
  16063. BABYLON.Vector3.FromFloatArrayToRef(world.m, 4, this.directions[1]);
  16064. BABYLON.Vector3.FromFloatArrayToRef(world.m, 8, this.directions[2]);
  16065. this._worldMatrix = world;
  16066. };
  16067. BoundingBox.prototype.isInFrustum = function (frustumPlanes) {
  16068. return BoundingBox.IsInFrustum(this.vectorsWorld, frustumPlanes);
  16069. };
  16070. BoundingBox.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  16071. return BoundingBox.IsCompletelyInFrustum(this.vectorsWorld, frustumPlanes);
  16072. };
  16073. BoundingBox.prototype.intersectsPoint = function (point) {
  16074. var delta = -BABYLON.Epsilon;
  16075. if (this.maximumWorld.x - point.x < delta || delta > point.x - this.minimumWorld.x)
  16076. return false;
  16077. if (this.maximumWorld.y - point.y < delta || delta > point.y - this.minimumWorld.y)
  16078. return false;
  16079. if (this.maximumWorld.z - point.z < delta || delta > point.z - this.minimumWorld.z)
  16080. return false;
  16081. return true;
  16082. };
  16083. BoundingBox.prototype.intersectsSphere = function (sphere) {
  16084. return BoundingBox.IntersectsSphere(this.minimumWorld, this.maximumWorld, sphere.centerWorld, sphere.radiusWorld);
  16085. };
  16086. BoundingBox.prototype.intersectsMinMax = function (min, max) {
  16087. if (this.maximumWorld.x < min.x || this.minimumWorld.x > max.x)
  16088. return false;
  16089. if (this.maximumWorld.y < min.y || this.minimumWorld.y > max.y)
  16090. return false;
  16091. if (this.maximumWorld.z < min.z || this.minimumWorld.z > max.z)
  16092. return false;
  16093. return true;
  16094. };
  16095. // Statics
  16096. BoundingBox.Intersects = function (box0, box1) {
  16097. if (box0.maximumWorld.x < box1.minimumWorld.x || box0.minimumWorld.x > box1.maximumWorld.x)
  16098. return false;
  16099. if (box0.maximumWorld.y < box1.minimumWorld.y || box0.minimumWorld.y > box1.maximumWorld.y)
  16100. return false;
  16101. if (box0.maximumWorld.z < box1.minimumWorld.z || box0.minimumWorld.z > box1.maximumWorld.z)
  16102. return false;
  16103. return true;
  16104. };
  16105. BoundingBox.IntersectsSphere = function (minPoint, maxPoint, sphereCenter, sphereRadius) {
  16106. var vector = BABYLON.Vector3.Clamp(sphereCenter, minPoint, maxPoint);
  16107. var num = BABYLON.Vector3.DistanceSquared(sphereCenter, vector);
  16108. return (num <= (sphereRadius * sphereRadius));
  16109. };
  16110. BoundingBox.IsCompletelyInFrustum = function (boundingVectors, frustumPlanes) {
  16111. for (var p = 0; p < 6; p++) {
  16112. for (var i = 0; i < 8; i++) {
  16113. if (frustumPlanes[p].dotCoordinate(boundingVectors[i]) < 0) {
  16114. return false;
  16115. }
  16116. }
  16117. }
  16118. return true;
  16119. };
  16120. BoundingBox.IsInFrustum = function (boundingVectors, frustumPlanes) {
  16121. for (var p = 0; p < 6; p++) {
  16122. var inCount = 8;
  16123. for (var i = 0; i < 8; i++) {
  16124. if (frustumPlanes[p].dotCoordinate(boundingVectors[i]) < 0) {
  16125. --inCount;
  16126. }
  16127. else {
  16128. break;
  16129. }
  16130. }
  16131. if (inCount === 0)
  16132. return false;
  16133. }
  16134. return true;
  16135. };
  16136. return BoundingBox;
  16137. }());
  16138. BABYLON.BoundingBox = BoundingBox;
  16139. })(BABYLON || (BABYLON = {}));
  16140. //# sourceMappingURL=babylon.boundingBox.js.map
  16141. var BABYLON;
  16142. (function (BABYLON) {
  16143. var computeBoxExtents = function (axis, box) {
  16144. var p = BABYLON.Vector3.Dot(box.centerWorld, axis);
  16145. var r0 = Math.abs(BABYLON.Vector3.Dot(box.directions[0], axis)) * box.extendSize.x;
  16146. var r1 = Math.abs(BABYLON.Vector3.Dot(box.directions[1], axis)) * box.extendSize.y;
  16147. var r2 = Math.abs(BABYLON.Vector3.Dot(box.directions[2], axis)) * box.extendSize.z;
  16148. var r = r0 + r1 + r2;
  16149. return {
  16150. min: p - r,
  16151. max: p + r
  16152. };
  16153. };
  16154. var extentsOverlap = function (min0, max0, min1, max1) { return !(min0 > max1 || min1 > max0); };
  16155. var axisOverlap = function (axis, box0, box1) {
  16156. var result0 = computeBoxExtents(axis, box0);
  16157. var result1 = computeBoxExtents(axis, box1);
  16158. return extentsOverlap(result0.min, result0.max, result1.min, result1.max);
  16159. };
  16160. var BoundingInfo = /** @class */ (function () {
  16161. function BoundingInfo(minimum, maximum) {
  16162. this.minimum = minimum;
  16163. this.maximum = maximum;
  16164. this._isLocked = false;
  16165. this.boundingBox = new BABYLON.BoundingBox(minimum, maximum);
  16166. this.boundingSphere = new BABYLON.BoundingSphere(minimum, maximum);
  16167. }
  16168. Object.defineProperty(BoundingInfo.prototype, "isLocked", {
  16169. get: function () {
  16170. return this._isLocked;
  16171. },
  16172. set: function (value) {
  16173. this._isLocked = value;
  16174. },
  16175. enumerable: true,
  16176. configurable: true
  16177. });
  16178. // Methods
  16179. BoundingInfo.prototype.update = function (world) {
  16180. if (this._isLocked) {
  16181. return;
  16182. }
  16183. this.boundingBox._update(world);
  16184. this.boundingSphere._update(world);
  16185. };
  16186. /**
  16187. * Recreate the bounding info to be centered around a specific point given a specific extend.
  16188. * @param center New center of the bounding info
  16189. * @param extend New extend of the bounding info
  16190. */
  16191. BoundingInfo.prototype.centerOn = function (center, extend) {
  16192. this.minimum = center.subtract(extend);
  16193. this.maximum = center.add(extend);
  16194. this.boundingBox = new BABYLON.BoundingBox(this.minimum, this.maximum);
  16195. this.boundingSphere = new BABYLON.BoundingSphere(this.minimum, this.maximum);
  16196. return this;
  16197. };
  16198. BoundingInfo.prototype.isInFrustum = function (frustumPlanes) {
  16199. if (!this.boundingSphere.isInFrustum(frustumPlanes))
  16200. return false;
  16201. return this.boundingBox.isInFrustum(frustumPlanes);
  16202. };
  16203. Object.defineProperty(BoundingInfo.prototype, "diagonalLength", {
  16204. /**
  16205. * Gets the world distance between the min and max points of the bounding box
  16206. */
  16207. get: function () {
  16208. var boundingBox = this.boundingBox;
  16209. var size = boundingBox.maximumWorld.subtract(boundingBox.minimumWorld);
  16210. return size.length();
  16211. },
  16212. enumerable: true,
  16213. configurable: true
  16214. });
  16215. BoundingInfo.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  16216. return this.boundingBox.isCompletelyInFrustum(frustumPlanes);
  16217. };
  16218. BoundingInfo.prototype._checkCollision = function (collider) {
  16219. return collider._canDoCollision(this.boundingSphere.centerWorld, this.boundingSphere.radiusWorld, this.boundingBox.minimumWorld, this.boundingBox.maximumWorld);
  16220. };
  16221. BoundingInfo.prototype.intersectsPoint = function (point) {
  16222. if (!this.boundingSphere.centerWorld) {
  16223. return false;
  16224. }
  16225. if (!this.boundingSphere.intersectsPoint(point)) {
  16226. return false;
  16227. }
  16228. if (!this.boundingBox.intersectsPoint(point)) {
  16229. return false;
  16230. }
  16231. return true;
  16232. };
  16233. BoundingInfo.prototype.intersects = function (boundingInfo, precise) {
  16234. if (!this.boundingSphere.centerWorld || !boundingInfo.boundingSphere.centerWorld) {
  16235. return false;
  16236. }
  16237. if (!BABYLON.BoundingSphere.Intersects(this.boundingSphere, boundingInfo.boundingSphere)) {
  16238. return false;
  16239. }
  16240. if (!BABYLON.BoundingBox.Intersects(this.boundingBox, boundingInfo.boundingBox)) {
  16241. return false;
  16242. }
  16243. if (!precise) {
  16244. return true;
  16245. }
  16246. var box0 = this.boundingBox;
  16247. var box1 = boundingInfo.boundingBox;
  16248. if (!axisOverlap(box0.directions[0], box0, box1))
  16249. return false;
  16250. if (!axisOverlap(box0.directions[1], box0, box1))
  16251. return false;
  16252. if (!axisOverlap(box0.directions[2], box0, box1))
  16253. return false;
  16254. if (!axisOverlap(box1.directions[0], box0, box1))
  16255. return false;
  16256. if (!axisOverlap(box1.directions[1], box0, box1))
  16257. return false;
  16258. if (!axisOverlap(box1.directions[2], box0, box1))
  16259. return false;
  16260. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[0]), box0, box1))
  16261. return false;
  16262. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[1]), box0, box1))
  16263. return false;
  16264. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[2]), box0, box1))
  16265. return false;
  16266. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[0]), box0, box1))
  16267. return false;
  16268. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[1]), box0, box1))
  16269. return false;
  16270. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[2]), box0, box1))
  16271. return false;
  16272. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[0]), box0, box1))
  16273. return false;
  16274. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[1]), box0, box1))
  16275. return false;
  16276. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[2]), box0, box1))
  16277. return false;
  16278. return true;
  16279. };
  16280. return BoundingInfo;
  16281. }());
  16282. BABYLON.BoundingInfo = BoundingInfo;
  16283. })(BABYLON || (BABYLON = {}));
  16284. //# sourceMappingURL=babylon.boundingInfo.js.map
  16285. var BABYLON;
  16286. (function (BABYLON) {
  16287. var TransformNode = /** @class */ (function (_super) {
  16288. __extends(TransformNode, _super);
  16289. function TransformNode(name, scene, isPure) {
  16290. if (scene === void 0) { scene = null; }
  16291. if (isPure === void 0) { isPure = true; }
  16292. var _this = _super.call(this, name, scene) || this;
  16293. // Properties
  16294. _this._rotation = BABYLON.Vector3.Zero();
  16295. _this._scaling = BABYLON.Vector3.One();
  16296. _this._isDirty = false;
  16297. _this.billboardMode = BABYLON.AbstractMesh.BILLBOARDMODE_NONE;
  16298. _this.scalingDeterminant = 1;
  16299. _this.infiniteDistance = false;
  16300. _this.position = BABYLON.Vector3.Zero();
  16301. _this._localWorld = BABYLON.Matrix.Zero();
  16302. _this._worldMatrix = BABYLON.Matrix.Zero();
  16303. _this._worldMatrixDeterminant = 0;
  16304. _this._absolutePosition = BABYLON.Vector3.Zero();
  16305. _this._pivotMatrix = BABYLON.Matrix.Identity();
  16306. _this._postMultiplyPivotMatrix = false;
  16307. _this._isWorldMatrixFrozen = false;
  16308. /**
  16309. * An event triggered after the world matrix is updated
  16310. * @type {BABYLON.Observable}
  16311. */
  16312. _this.onAfterWorldMatrixUpdateObservable = new BABYLON.Observable();
  16313. _this._nonUniformScaling = false;
  16314. if (isPure) {
  16315. _this.getScene().addTransformNode(_this);
  16316. }
  16317. return _this;
  16318. }
  16319. /**
  16320. * Gets a string idenfifying the name of the class
  16321. * @returns "TransformNode" string
  16322. */
  16323. TransformNode.prototype.getClassName = function () {
  16324. return "TransformNode";
  16325. };
  16326. Object.defineProperty(TransformNode.prototype, "rotation", {
  16327. /**
  16328. * Rotation property : a Vector3 depicting the rotation value in radians around each local axis X, Y, Z.
  16329. * If rotation quaternion is set, this Vector3 will (almost always) be the Zero vector!
  16330. * Default : (0.0, 0.0, 0.0)
  16331. */
  16332. get: function () {
  16333. return this._rotation;
  16334. },
  16335. set: function (newRotation) {
  16336. this._rotation = newRotation;
  16337. },
  16338. enumerable: true,
  16339. configurable: true
  16340. });
  16341. Object.defineProperty(TransformNode.prototype, "scaling", {
  16342. /**
  16343. * Scaling property : a Vector3 depicting the mesh scaling along each local axis X, Y, Z.
  16344. * Default : (1.0, 1.0, 1.0)
  16345. */
  16346. get: function () {
  16347. return this._scaling;
  16348. },
  16349. /**
  16350. * Scaling property : a Vector3 depicting the mesh scaling along each local axis X, Y, Z.
  16351. * Default : (1.0, 1.0, 1.0)
  16352. */
  16353. set: function (newScaling) {
  16354. this._scaling = newScaling;
  16355. },
  16356. enumerable: true,
  16357. configurable: true
  16358. });
  16359. Object.defineProperty(TransformNode.prototype, "rotationQuaternion", {
  16360. /**
  16361. * Rotation Quaternion property : this a Quaternion object depicting the mesh rotation by using a unit quaternion.
  16362. * It's null by default.
  16363. * 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)
  16364. */
  16365. get: function () {
  16366. return this._rotationQuaternion;
  16367. },
  16368. set: function (quaternion) {
  16369. this._rotationQuaternion = quaternion;
  16370. //reset the rotation vector.
  16371. if (quaternion && this.rotation.length()) {
  16372. this.rotation.copyFromFloats(0.0, 0.0, 0.0);
  16373. }
  16374. },
  16375. enumerable: true,
  16376. configurable: true
  16377. });
  16378. /**
  16379. * Returns the latest update of the World matrix
  16380. * Returns a Matrix.
  16381. */
  16382. TransformNode.prototype.getWorldMatrix = function () {
  16383. if (this._currentRenderId !== this.getScene().getRenderId()) {
  16384. this.computeWorldMatrix();
  16385. }
  16386. return this._worldMatrix;
  16387. };
  16388. /**
  16389. * Returns the latest update of the World matrix determinant.
  16390. */
  16391. TransformNode.prototype._getWorldMatrixDeterminant = function () {
  16392. return this._worldMatrixDeterminant;
  16393. };
  16394. Object.defineProperty(TransformNode.prototype, "worldMatrixFromCache", {
  16395. /**
  16396. * Returns directly the latest state of the mesh World matrix.
  16397. * A Matrix is returned.
  16398. */
  16399. get: function () {
  16400. return this._worldMatrix;
  16401. },
  16402. enumerable: true,
  16403. configurable: true
  16404. });
  16405. /**
  16406. * Copies the paramater passed Matrix into the mesh Pose matrix.
  16407. * Returns the AbstractMesh.
  16408. */
  16409. TransformNode.prototype.updatePoseMatrix = function (matrix) {
  16410. this._poseMatrix.copyFrom(matrix);
  16411. return this;
  16412. };
  16413. /**
  16414. * Returns the mesh Pose matrix.
  16415. * Returned object : Matrix
  16416. */
  16417. TransformNode.prototype.getPoseMatrix = function () {
  16418. return this._poseMatrix;
  16419. };
  16420. TransformNode.prototype._isSynchronized = function () {
  16421. if (this._isDirty) {
  16422. return false;
  16423. }
  16424. if (this.billboardMode !== this._cache.billboardMode || this.billboardMode !== BABYLON.AbstractMesh.BILLBOARDMODE_NONE)
  16425. return false;
  16426. if (this._cache.pivotMatrixUpdated) {
  16427. return false;
  16428. }
  16429. if (this.infiniteDistance) {
  16430. return false;
  16431. }
  16432. if (!this._cache.position.equals(this.position))
  16433. return false;
  16434. if (this.rotationQuaternion) {
  16435. if (!this._cache.rotationQuaternion.equals(this.rotationQuaternion))
  16436. return false;
  16437. }
  16438. if (!this._cache.rotation.equals(this.rotation))
  16439. return false;
  16440. if (!this._cache.scaling.equals(this.scaling))
  16441. return false;
  16442. return true;
  16443. };
  16444. TransformNode.prototype._initCache = function () {
  16445. _super.prototype._initCache.call(this);
  16446. this._cache.localMatrixUpdated = false;
  16447. this._cache.position = BABYLON.Vector3.Zero();
  16448. this._cache.scaling = BABYLON.Vector3.Zero();
  16449. this._cache.rotation = BABYLON.Vector3.Zero();
  16450. this._cache.rotationQuaternion = new BABYLON.Quaternion(0, 0, 0, 0);
  16451. this._cache.billboardMode = -1;
  16452. };
  16453. TransformNode.prototype.markAsDirty = function (property) {
  16454. if (property === "rotation") {
  16455. this.rotationQuaternion = null;
  16456. }
  16457. this._currentRenderId = Number.MAX_VALUE;
  16458. this._isDirty = true;
  16459. return this;
  16460. };
  16461. Object.defineProperty(TransformNode.prototype, "absolutePosition", {
  16462. /**
  16463. * Returns the current mesh absolute position.
  16464. * Retuns a Vector3.
  16465. */
  16466. get: function () {
  16467. return this._absolutePosition;
  16468. },
  16469. enumerable: true,
  16470. configurable: true
  16471. });
  16472. /**
  16473. * Sets a new matrix to apply before all other transformation
  16474. * @param matrix defines the transform matrix
  16475. * @returns the current TransformNode
  16476. */
  16477. TransformNode.prototype.setPreTransformMatrix = function (matrix) {
  16478. return this.setPivotMatrix(matrix, false);
  16479. };
  16480. /**
  16481. * Sets a new pivot matrix to the current node
  16482. * @param matrix defines the new pivot matrix to use
  16483. * @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
  16484. * @returns the current TransformNode
  16485. */
  16486. TransformNode.prototype.setPivotMatrix = function (matrix, postMultiplyPivotMatrix) {
  16487. if (postMultiplyPivotMatrix === void 0) { postMultiplyPivotMatrix = true; }
  16488. this._pivotMatrix = matrix.clone();
  16489. this._cache.pivotMatrixUpdated = true;
  16490. this._postMultiplyPivotMatrix = postMultiplyPivotMatrix;
  16491. if (this._postMultiplyPivotMatrix) {
  16492. if (!this._pivotMatrixInverse) {
  16493. this._pivotMatrixInverse = BABYLON.Matrix.Invert(this._pivotMatrix);
  16494. }
  16495. else {
  16496. this._pivotMatrix.invertToRef(this._pivotMatrixInverse);
  16497. }
  16498. }
  16499. return this;
  16500. };
  16501. /**
  16502. * Returns the mesh pivot matrix.
  16503. * Default : Identity.
  16504. * A Matrix is returned.
  16505. */
  16506. TransformNode.prototype.getPivotMatrix = function () {
  16507. return this._pivotMatrix;
  16508. };
  16509. /**
  16510. * Prevents the World matrix to be computed any longer.
  16511. * Returns the AbstractMesh.
  16512. */
  16513. TransformNode.prototype.freezeWorldMatrix = function () {
  16514. this._isWorldMatrixFrozen = false; // no guarantee world is not already frozen, switch off temporarily
  16515. this.computeWorldMatrix(true);
  16516. this._isWorldMatrixFrozen = true;
  16517. return this;
  16518. };
  16519. /**
  16520. * Allows back the World matrix computation.
  16521. * Returns the AbstractMesh.
  16522. */
  16523. TransformNode.prototype.unfreezeWorldMatrix = function () {
  16524. this._isWorldMatrixFrozen = false;
  16525. this.computeWorldMatrix(true);
  16526. return this;
  16527. };
  16528. Object.defineProperty(TransformNode.prototype, "isWorldMatrixFrozen", {
  16529. /**
  16530. * True if the World matrix has been frozen.
  16531. * Returns a boolean.
  16532. */
  16533. get: function () {
  16534. return this._isWorldMatrixFrozen;
  16535. },
  16536. enumerable: true,
  16537. configurable: true
  16538. });
  16539. /**
  16540. * Retuns the mesh absolute position in the World.
  16541. * Returns a Vector3.
  16542. */
  16543. TransformNode.prototype.getAbsolutePosition = function () {
  16544. this.computeWorldMatrix();
  16545. return this._absolutePosition;
  16546. };
  16547. /**
  16548. * Sets the mesh absolute position in the World from a Vector3 or an Array(3).
  16549. * Returns the AbstractMesh.
  16550. */
  16551. TransformNode.prototype.setAbsolutePosition = function (absolutePosition) {
  16552. if (!absolutePosition) {
  16553. return this;
  16554. }
  16555. var absolutePositionX;
  16556. var absolutePositionY;
  16557. var absolutePositionZ;
  16558. if (absolutePosition.x === undefined) {
  16559. if (arguments.length < 3) {
  16560. return this;
  16561. }
  16562. absolutePositionX = arguments[0];
  16563. absolutePositionY = arguments[1];
  16564. absolutePositionZ = arguments[2];
  16565. }
  16566. else {
  16567. absolutePositionX = absolutePosition.x;
  16568. absolutePositionY = absolutePosition.y;
  16569. absolutePositionZ = absolutePosition.z;
  16570. }
  16571. if (this.parent) {
  16572. var invertParentWorldMatrix = this.parent.getWorldMatrix().clone();
  16573. invertParentWorldMatrix.invert();
  16574. var worldPosition = new BABYLON.Vector3(absolutePositionX, absolutePositionY, absolutePositionZ);
  16575. this.position = BABYLON.Vector3.TransformCoordinates(worldPosition, invertParentWorldMatrix);
  16576. }
  16577. else {
  16578. this.position.x = absolutePositionX;
  16579. this.position.y = absolutePositionY;
  16580. this.position.z = absolutePositionZ;
  16581. }
  16582. return this;
  16583. };
  16584. /**
  16585. * Sets the mesh position in its local space.
  16586. * Returns the AbstractMesh.
  16587. */
  16588. TransformNode.prototype.setPositionWithLocalVector = function (vector3) {
  16589. this.computeWorldMatrix();
  16590. this.position = BABYLON.Vector3.TransformNormal(vector3, this._localWorld);
  16591. return this;
  16592. };
  16593. /**
  16594. * Returns the mesh position in the local space from the current World matrix values.
  16595. * Returns a new Vector3.
  16596. */
  16597. TransformNode.prototype.getPositionExpressedInLocalSpace = function () {
  16598. this.computeWorldMatrix();
  16599. var invLocalWorldMatrix = this._localWorld.clone();
  16600. invLocalWorldMatrix.invert();
  16601. return BABYLON.Vector3.TransformNormal(this.position, invLocalWorldMatrix);
  16602. };
  16603. /**
  16604. * Translates the mesh along the passed Vector3 in its local space.
  16605. * Returns the AbstractMesh.
  16606. */
  16607. TransformNode.prototype.locallyTranslate = function (vector3) {
  16608. this.computeWorldMatrix(true);
  16609. this.position = BABYLON.Vector3.TransformCoordinates(vector3, this._localWorld);
  16610. return this;
  16611. };
  16612. /**
  16613. * Orients a mesh towards a target point. Mesh must be drawn facing user.
  16614. * @param targetPoint the position (must be in same space as current mesh) to look at
  16615. * @param yawCor optional yaw (y-axis) correction in radians
  16616. * @param pitchCor optional pitch (x-axis) correction in radians
  16617. * @param rollCor optional roll (z-axis) correction in radians
  16618. * @param space the choosen space of the target
  16619. * @returns the TransformNode.
  16620. */
  16621. TransformNode.prototype.lookAt = function (targetPoint, yawCor, pitchCor, rollCor, space) {
  16622. if (yawCor === void 0) { yawCor = 0; }
  16623. if (pitchCor === void 0) { pitchCor = 0; }
  16624. if (rollCor === void 0) { rollCor = 0; }
  16625. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  16626. var dv = BABYLON.AbstractMesh._lookAtVectorCache;
  16627. var pos = space === BABYLON.Space.LOCAL ? this.position : this.getAbsolutePosition();
  16628. targetPoint.subtractToRef(pos, dv);
  16629. var yaw = -Math.atan2(dv.z, dv.x) - Math.PI / 2;
  16630. var len = Math.sqrt(dv.x * dv.x + dv.z * dv.z);
  16631. var pitch = Math.atan2(dv.y, len);
  16632. if (this.rotationQuaternion) {
  16633. BABYLON.Quaternion.RotationYawPitchRollToRef(yaw + yawCor, pitch + pitchCor, rollCor, this.rotationQuaternion);
  16634. }
  16635. else {
  16636. this.rotation.x = pitch + pitchCor;
  16637. this.rotation.y = yaw + yawCor;
  16638. this.rotation.z = rollCor;
  16639. }
  16640. return this;
  16641. };
  16642. /**
  16643. * Returns a new Vector3 what is the localAxis, expressed in the mesh local space, rotated like the mesh.
  16644. * This Vector3 is expressed in the World space.
  16645. */
  16646. TransformNode.prototype.getDirection = function (localAxis) {
  16647. var result = BABYLON.Vector3.Zero();
  16648. this.getDirectionToRef(localAxis, result);
  16649. return result;
  16650. };
  16651. /**
  16652. * Sets the Vector3 "result" as the rotated Vector3 "localAxis" in the same rotation than the mesh.
  16653. * localAxis is expressed in the mesh local space.
  16654. * result is computed in the Wordl space from the mesh World matrix.
  16655. * Returns the AbstractMesh.
  16656. */
  16657. TransformNode.prototype.getDirectionToRef = function (localAxis, result) {
  16658. BABYLON.Vector3.TransformNormalToRef(localAxis, this.getWorldMatrix(), result);
  16659. return this;
  16660. };
  16661. /**
  16662. * Sets a new pivot point to the current node
  16663. * @param point defines the new pivot point to use
  16664. * @param space defines if the point is in world or local space (local by default)
  16665. * @returns the current TransformNode
  16666. */
  16667. TransformNode.prototype.setPivotPoint = function (point, space) {
  16668. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  16669. if (this.getScene().getRenderId() == 0) {
  16670. this.computeWorldMatrix(true);
  16671. }
  16672. var wm = this.getWorldMatrix();
  16673. if (space == BABYLON.Space.WORLD) {
  16674. var tmat = BABYLON.Tmp.Matrix[0];
  16675. wm.invertToRef(tmat);
  16676. point = BABYLON.Vector3.TransformCoordinates(point, tmat);
  16677. }
  16678. return this.setPivotMatrix(BABYLON.Matrix.Translation(-point.x, -point.y, -point.z), true);
  16679. };
  16680. /**
  16681. * Returns a new Vector3 set with the mesh pivot point coordinates in the local space.
  16682. */
  16683. TransformNode.prototype.getPivotPoint = function () {
  16684. var point = BABYLON.Vector3.Zero();
  16685. this.getPivotPointToRef(point);
  16686. return point;
  16687. };
  16688. /**
  16689. * Sets the passed Vector3 "result" with the coordinates of the mesh pivot point in the local space.
  16690. * Returns the AbstractMesh.
  16691. */
  16692. TransformNode.prototype.getPivotPointToRef = function (result) {
  16693. result.x = -this._pivotMatrix.m[12];
  16694. result.y = -this._pivotMatrix.m[13];
  16695. result.z = -this._pivotMatrix.m[14];
  16696. return this;
  16697. };
  16698. /**
  16699. * Returns a new Vector3 set with the mesh pivot point World coordinates.
  16700. */
  16701. TransformNode.prototype.getAbsolutePivotPoint = function () {
  16702. var point = BABYLON.Vector3.Zero();
  16703. this.getAbsolutePivotPointToRef(point);
  16704. return point;
  16705. };
  16706. /**
  16707. * Sets the Vector3 "result" coordinates with the mesh pivot point World coordinates.
  16708. * Returns the AbstractMesh.
  16709. */
  16710. TransformNode.prototype.getAbsolutePivotPointToRef = function (result) {
  16711. result.x = this._pivotMatrix.m[12];
  16712. result.y = this._pivotMatrix.m[13];
  16713. result.z = this._pivotMatrix.m[14];
  16714. this.getPivotPointToRef(result);
  16715. BABYLON.Vector3.TransformCoordinatesToRef(result, this.getWorldMatrix(), result);
  16716. return this;
  16717. };
  16718. /**
  16719. * Defines the passed node as the parent of the current node.
  16720. * The node will remain exactly where it is and its position / rotation will be updated accordingly
  16721. * Returns the TransformNode.
  16722. */
  16723. TransformNode.prototype.setParent = function (node) {
  16724. if (node === null) {
  16725. var rotation = BABYLON.Tmp.Quaternion[0];
  16726. var position = BABYLON.Tmp.Vector3[0];
  16727. var scale = BABYLON.Tmp.Vector3[1];
  16728. if (this.parent && this.parent.computeWorldMatrix) {
  16729. this.parent.computeWorldMatrix(true);
  16730. }
  16731. this.computeWorldMatrix(true);
  16732. this.getWorldMatrix().decompose(scale, rotation, position);
  16733. if (this.rotationQuaternion) {
  16734. this.rotationQuaternion.copyFrom(rotation);
  16735. }
  16736. else {
  16737. rotation.toEulerAnglesToRef(this.rotation);
  16738. }
  16739. this.scaling.x = scale.x;
  16740. this.scaling.y = scale.y;
  16741. this.scaling.z = scale.z;
  16742. this.position.x = position.x;
  16743. this.position.y = position.y;
  16744. this.position.z = position.z;
  16745. }
  16746. else {
  16747. var rotation = BABYLON.Tmp.Quaternion[0];
  16748. var position = BABYLON.Tmp.Vector3[0];
  16749. var scale = BABYLON.Tmp.Vector3[1];
  16750. var diffMatrix = BABYLON.Tmp.Matrix[0];
  16751. var invParentMatrix = BABYLON.Tmp.Matrix[1];
  16752. this.computeWorldMatrix(true);
  16753. node.computeWorldMatrix(true);
  16754. node.getWorldMatrix().invertToRef(invParentMatrix);
  16755. this.getWorldMatrix().multiplyToRef(invParentMatrix, diffMatrix);
  16756. diffMatrix.decompose(scale, rotation, position);
  16757. if (this.rotationQuaternion) {
  16758. this.rotationQuaternion.copyFrom(rotation);
  16759. }
  16760. else {
  16761. rotation.toEulerAnglesToRef(this.rotation);
  16762. }
  16763. this.position.x = position.x;
  16764. this.position.y = position.y;
  16765. this.position.z = position.z;
  16766. this.scaling.x = scale.x;
  16767. this.scaling.y = scale.y;
  16768. this.scaling.z = scale.z;
  16769. }
  16770. this.parent = node;
  16771. return this;
  16772. };
  16773. Object.defineProperty(TransformNode.prototype, "nonUniformScaling", {
  16774. get: function () {
  16775. return this._nonUniformScaling;
  16776. },
  16777. enumerable: true,
  16778. configurable: true
  16779. });
  16780. TransformNode.prototype._updateNonUniformScalingState = function (value) {
  16781. if (this._nonUniformScaling === value) {
  16782. return false;
  16783. }
  16784. this._nonUniformScaling = true;
  16785. return true;
  16786. };
  16787. /**
  16788. * Attach the current TransformNode to another TransformNode associated with a bone
  16789. * @param bone Bone affecting the TransformNode
  16790. * @param affectedTransformNode TransformNode associated with the bone
  16791. */
  16792. TransformNode.prototype.attachToBone = function (bone, affectedTransformNode) {
  16793. this._transformToBoneReferal = affectedTransformNode;
  16794. this.parent = bone;
  16795. if (bone.getWorldMatrix().determinant() < 0) {
  16796. this.scalingDeterminant *= -1;
  16797. }
  16798. return this;
  16799. };
  16800. TransformNode.prototype.detachFromBone = function () {
  16801. if (!this.parent) {
  16802. return this;
  16803. }
  16804. if (this.parent.getWorldMatrix().determinant() < 0) {
  16805. this.scalingDeterminant *= -1;
  16806. }
  16807. this._transformToBoneReferal = null;
  16808. this.parent = null;
  16809. return this;
  16810. };
  16811. /**
  16812. * Rotates the mesh around the axis vector for the passed angle (amount) expressed in radians, in the given space.
  16813. * space (default LOCAL) can be either BABYLON.Space.LOCAL, either BABYLON.Space.WORLD.
  16814. * Note that the property `rotationQuaternion` is then automatically updated and the property `rotation` is set to (0,0,0) and no longer used.
  16815. * The passed axis is also normalized.
  16816. * Returns the AbstractMesh.
  16817. */
  16818. TransformNode.prototype.rotate = function (axis, amount, space) {
  16819. axis.normalize();
  16820. if (!this.rotationQuaternion) {
  16821. this.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z);
  16822. this.rotation = BABYLON.Vector3.Zero();
  16823. }
  16824. var rotationQuaternion;
  16825. if (!space || space === BABYLON.Space.LOCAL) {
  16826. rotationQuaternion = BABYLON.Quaternion.RotationAxisToRef(axis, amount, BABYLON.AbstractMesh._rotationAxisCache);
  16827. this.rotationQuaternion.multiplyToRef(rotationQuaternion, this.rotationQuaternion);
  16828. }
  16829. else {
  16830. if (this.parent) {
  16831. var invertParentWorldMatrix = this.parent.getWorldMatrix().clone();
  16832. invertParentWorldMatrix.invert();
  16833. axis = BABYLON.Vector3.TransformNormal(axis, invertParentWorldMatrix);
  16834. }
  16835. rotationQuaternion = BABYLON.Quaternion.RotationAxisToRef(axis, amount, BABYLON.AbstractMesh._rotationAxisCache);
  16836. rotationQuaternion.multiplyToRef(this.rotationQuaternion, this.rotationQuaternion);
  16837. }
  16838. return this;
  16839. };
  16840. /**
  16841. * Rotates the mesh around the axis vector for the passed angle (amount) expressed in radians, in world space.
  16842. * Note that the property `rotationQuaternion` is then automatically updated and the property `rotation` is set to (0,0,0) and no longer used.
  16843. * The passed axis is also normalized.
  16844. * Returns the AbstractMesh.
  16845. * Method is based on http://www.euclideanspace.com/maths/geometry/affine/aroundPoint/index.htm
  16846. */
  16847. TransformNode.prototype.rotateAround = function (point, axis, amount) {
  16848. axis.normalize();
  16849. if (!this.rotationQuaternion) {
  16850. this.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z);
  16851. this.rotation.copyFromFloats(0, 0, 0);
  16852. }
  16853. point.subtractToRef(this.position, BABYLON.Tmp.Vector3[0]);
  16854. BABYLON.Matrix.TranslationToRef(BABYLON.Tmp.Vector3[0].x, BABYLON.Tmp.Vector3[0].y, BABYLON.Tmp.Vector3[0].z, BABYLON.Tmp.Matrix[0]);
  16855. BABYLON.Tmp.Matrix[0].invertToRef(BABYLON.Tmp.Matrix[2]);
  16856. BABYLON.Matrix.RotationAxisToRef(axis, amount, BABYLON.Tmp.Matrix[1]);
  16857. BABYLON.Tmp.Matrix[2].multiplyToRef(BABYLON.Tmp.Matrix[1], BABYLON.Tmp.Matrix[2]);
  16858. BABYLON.Tmp.Matrix[2].multiplyToRef(BABYLON.Tmp.Matrix[0], BABYLON.Tmp.Matrix[2]);
  16859. BABYLON.Tmp.Matrix[2].decompose(BABYLON.Tmp.Vector3[0], BABYLON.Tmp.Quaternion[0], BABYLON.Tmp.Vector3[1]);
  16860. this.position.addInPlace(BABYLON.Tmp.Vector3[1]);
  16861. BABYLON.Tmp.Quaternion[0].multiplyToRef(this.rotationQuaternion, this.rotationQuaternion);
  16862. return this;
  16863. };
  16864. /**
  16865. * Translates the mesh along the axis vector for the passed distance in the given space.
  16866. * space (default LOCAL) can be either BABYLON.Space.LOCAL, either BABYLON.Space.WORLD.
  16867. * Returns the AbstractMesh.
  16868. */
  16869. TransformNode.prototype.translate = function (axis, distance, space) {
  16870. var displacementVector = axis.scale(distance);
  16871. if (!space || space === BABYLON.Space.LOCAL) {
  16872. var tempV3 = this.getPositionExpressedInLocalSpace().add(displacementVector);
  16873. this.setPositionWithLocalVector(tempV3);
  16874. }
  16875. else {
  16876. this.setAbsolutePosition(this.getAbsolutePosition().add(displacementVector));
  16877. }
  16878. return this;
  16879. };
  16880. /**
  16881. * Adds a rotation step to the mesh current rotation.
  16882. * x, y, z are Euler angles expressed in radians.
  16883. * This methods updates the current mesh rotation, either mesh.rotation, either mesh.rotationQuaternion if it's set.
  16884. * This means this rotation is made in the mesh local space only.
  16885. * It's useful to set a custom rotation order different from the BJS standard one YXZ.
  16886. * Example : this rotates the mesh first around its local X axis, then around its local Z axis, finally around its local Y axis.
  16887. * ```javascript
  16888. * mesh.addRotation(x1, 0, 0).addRotation(0, 0, z2).addRotation(0, 0, y3);
  16889. * ```
  16890. * Note that `addRotation()` accumulates the passed rotation values to the current ones and computes the .rotation or .rotationQuaternion updated values.
  16891. * 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.
  16892. * Returns the AbstractMesh.
  16893. */
  16894. TransformNode.prototype.addRotation = function (x, y, z) {
  16895. var rotationQuaternion;
  16896. if (this.rotationQuaternion) {
  16897. rotationQuaternion = this.rotationQuaternion;
  16898. }
  16899. else {
  16900. rotationQuaternion = BABYLON.Tmp.Quaternion[1];
  16901. BABYLON.Quaternion.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, rotationQuaternion);
  16902. }
  16903. var accumulation = BABYLON.Tmp.Quaternion[0];
  16904. BABYLON.Quaternion.RotationYawPitchRollToRef(y, x, z, accumulation);
  16905. rotationQuaternion.multiplyInPlace(accumulation);
  16906. if (!this.rotationQuaternion) {
  16907. rotationQuaternion.toEulerAnglesToRef(this.rotation);
  16908. }
  16909. return this;
  16910. };
  16911. /**
  16912. * Computes the mesh World matrix and returns it.
  16913. * If the mesh world matrix is frozen, this computation does nothing more than returning the last frozen values.
  16914. * If the parameter `force` is let to `false` (default), the current cached World matrix is returned.
  16915. * If the parameter `force`is set to `true`, the actual computation is done.
  16916. * Returns the mesh World Matrix.
  16917. */
  16918. TransformNode.prototype.computeWorldMatrix = function (force) {
  16919. if (this._isWorldMatrixFrozen) {
  16920. return this._worldMatrix;
  16921. }
  16922. if (!force && this.isSynchronized(true)) {
  16923. return this._worldMatrix;
  16924. }
  16925. this._cache.position.copyFrom(this.position);
  16926. this._cache.scaling.copyFrom(this.scaling);
  16927. this._cache.pivotMatrixUpdated = false;
  16928. this._cache.billboardMode = this.billboardMode;
  16929. this._currentRenderId = this.getScene().getRenderId();
  16930. this._isDirty = false;
  16931. // Scaling
  16932. BABYLON.Matrix.ScalingToRef(this.scaling.x * this.scalingDeterminant, this.scaling.y * this.scalingDeterminant, this.scaling.z * this.scalingDeterminant, BABYLON.Tmp.Matrix[1]);
  16933. // Rotation
  16934. //rotate, if quaternion is set and rotation was used
  16935. if (this.rotationQuaternion) {
  16936. var len = this.rotation.length();
  16937. if (len) {
  16938. this.rotationQuaternion.multiplyInPlace(BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z));
  16939. this.rotation.copyFromFloats(0, 0, 0);
  16940. }
  16941. }
  16942. if (this.rotationQuaternion) {
  16943. this.rotationQuaternion.toRotationMatrix(BABYLON.Tmp.Matrix[0]);
  16944. this._cache.rotationQuaternion.copyFrom(this.rotationQuaternion);
  16945. }
  16946. else {
  16947. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, BABYLON.Tmp.Matrix[0]);
  16948. this._cache.rotation.copyFrom(this.rotation);
  16949. }
  16950. // Translation
  16951. var camera = this.getScene().activeCamera;
  16952. if (this.infiniteDistance && !this.parent && camera) {
  16953. var cameraWorldMatrix = camera.getWorldMatrix();
  16954. var cameraGlobalPosition = new BABYLON.Vector3(cameraWorldMatrix.m[12], cameraWorldMatrix.m[13], cameraWorldMatrix.m[14]);
  16955. BABYLON.Matrix.TranslationToRef(this.position.x + cameraGlobalPosition.x, this.position.y + cameraGlobalPosition.y, this.position.z + cameraGlobalPosition.z, BABYLON.Tmp.Matrix[2]);
  16956. }
  16957. else {
  16958. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, BABYLON.Tmp.Matrix[2]);
  16959. }
  16960. // Composing transformations
  16961. this._pivotMatrix.multiplyToRef(BABYLON.Tmp.Matrix[1], BABYLON.Tmp.Matrix[4]);
  16962. BABYLON.Tmp.Matrix[4].multiplyToRef(BABYLON.Tmp.Matrix[0], BABYLON.Tmp.Matrix[5]);
  16963. // Billboarding (testing PG:http://www.babylonjs-playground.com/#UJEIL#13)
  16964. if (this.billboardMode !== BABYLON.AbstractMesh.BILLBOARDMODE_NONE && camera) {
  16965. if ((this.billboardMode & BABYLON.AbstractMesh.BILLBOARDMODE_ALL) !== BABYLON.AbstractMesh.BILLBOARDMODE_ALL) {
  16966. // Need to decompose each rotation here
  16967. var currentPosition = BABYLON.Tmp.Vector3[3];
  16968. if (this.parent && this.parent.getWorldMatrix) {
  16969. if (this._transformToBoneReferal) {
  16970. this.parent.getWorldMatrix().multiplyToRef(this._transformToBoneReferal.getWorldMatrix(), BABYLON.Tmp.Matrix[6]);
  16971. BABYLON.Vector3.TransformCoordinatesToRef(this.position, BABYLON.Tmp.Matrix[6], currentPosition);
  16972. }
  16973. else {
  16974. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this.parent.getWorldMatrix(), currentPosition);
  16975. }
  16976. }
  16977. else {
  16978. currentPosition.copyFrom(this.position);
  16979. }
  16980. currentPosition.subtractInPlace(camera.globalPosition);
  16981. var finalEuler = BABYLON.Tmp.Vector3[4].copyFromFloats(0, 0, 0);
  16982. if ((this.billboardMode & BABYLON.AbstractMesh.BILLBOARDMODE_X) === BABYLON.AbstractMesh.BILLBOARDMODE_X) {
  16983. finalEuler.x = Math.atan2(-currentPosition.y, currentPosition.z);
  16984. }
  16985. if ((this.billboardMode & BABYLON.AbstractMesh.BILLBOARDMODE_Y) === BABYLON.AbstractMesh.BILLBOARDMODE_Y) {
  16986. finalEuler.y = Math.atan2(currentPosition.x, currentPosition.z);
  16987. }
  16988. if ((this.billboardMode & BABYLON.AbstractMesh.BILLBOARDMODE_Z) === BABYLON.AbstractMesh.BILLBOARDMODE_Z) {
  16989. finalEuler.z = Math.atan2(currentPosition.y, currentPosition.x);
  16990. }
  16991. BABYLON.Matrix.RotationYawPitchRollToRef(finalEuler.y, finalEuler.x, finalEuler.z, BABYLON.Tmp.Matrix[0]);
  16992. }
  16993. else {
  16994. BABYLON.Tmp.Matrix[1].copyFrom(camera.getViewMatrix());
  16995. BABYLON.Tmp.Matrix[1].setTranslationFromFloats(0, 0, 0);
  16996. BABYLON.Tmp.Matrix[1].invertToRef(BABYLON.Tmp.Matrix[0]);
  16997. }
  16998. BABYLON.Tmp.Matrix[1].copyFrom(BABYLON.Tmp.Matrix[5]);
  16999. BABYLON.Tmp.Matrix[1].multiplyToRef(BABYLON.Tmp.Matrix[0], BABYLON.Tmp.Matrix[5]);
  17000. }
  17001. // Local world
  17002. BABYLON.Tmp.Matrix[5].multiplyToRef(BABYLON.Tmp.Matrix[2], this._localWorld);
  17003. // Parent
  17004. if (this.parent && this.parent.getWorldMatrix) {
  17005. if (this.billboardMode !== BABYLON.AbstractMesh.BILLBOARDMODE_NONE) {
  17006. if (this._transformToBoneReferal) {
  17007. this.parent.getWorldMatrix().multiplyToRef(this._transformToBoneReferal.getWorldMatrix(), BABYLON.Tmp.Matrix[6]);
  17008. BABYLON.Tmp.Matrix[5].copyFrom(BABYLON.Tmp.Matrix[6]);
  17009. }
  17010. else {
  17011. BABYLON.Tmp.Matrix[5].copyFrom(this.parent.getWorldMatrix());
  17012. }
  17013. this._localWorld.getTranslationToRef(BABYLON.Tmp.Vector3[5]);
  17014. BABYLON.Vector3.TransformCoordinatesToRef(BABYLON.Tmp.Vector3[5], BABYLON.Tmp.Matrix[5], BABYLON.Tmp.Vector3[5]);
  17015. this._worldMatrix.copyFrom(this._localWorld);
  17016. this._worldMatrix.setTranslation(BABYLON.Tmp.Vector3[5]);
  17017. }
  17018. else {
  17019. if (this._transformToBoneReferal) {
  17020. this._localWorld.multiplyToRef(this.parent.getWorldMatrix(), BABYLON.Tmp.Matrix[6]);
  17021. BABYLON.Tmp.Matrix[6].multiplyToRef(this._transformToBoneReferal.getWorldMatrix(), this._worldMatrix);
  17022. }
  17023. else {
  17024. this._localWorld.multiplyToRef(this.parent.getWorldMatrix(), this._worldMatrix);
  17025. }
  17026. }
  17027. this._markSyncedWithParent();
  17028. }
  17029. else {
  17030. this._worldMatrix.copyFrom(this._localWorld);
  17031. }
  17032. // Post multiply inverse of pivotMatrix
  17033. if (this._postMultiplyPivotMatrix) {
  17034. this._worldMatrix.multiplyToRef(this._pivotMatrixInverse, this._worldMatrix);
  17035. }
  17036. // Normal matrix
  17037. if (this.scaling.isNonUniform) {
  17038. this._updateNonUniformScalingState(true);
  17039. }
  17040. else if (this.parent && this.parent._nonUniformScaling) {
  17041. this._updateNonUniformScalingState(this.parent._nonUniformScaling);
  17042. }
  17043. else {
  17044. this._updateNonUniformScalingState(false);
  17045. }
  17046. this._afterComputeWorldMatrix();
  17047. // Absolute position
  17048. this._absolutePosition.copyFromFloats(this._worldMatrix.m[12], this._worldMatrix.m[13], this._worldMatrix.m[14]);
  17049. // Callbacks
  17050. this.onAfterWorldMatrixUpdateObservable.notifyObservers(this);
  17051. if (!this._poseMatrix) {
  17052. this._poseMatrix = BABYLON.Matrix.Invert(this._worldMatrix);
  17053. }
  17054. // Cache the determinant
  17055. this._worldMatrixDeterminant = this._worldMatrix.determinant();
  17056. return this._worldMatrix;
  17057. };
  17058. TransformNode.prototype._afterComputeWorldMatrix = function () {
  17059. };
  17060. /**
  17061. * If you'd like to be called back after the mesh position, rotation or scaling has been updated.
  17062. * @param func: callback function to add
  17063. *
  17064. * Returns the TransformNode.
  17065. */
  17066. TransformNode.prototype.registerAfterWorldMatrixUpdate = function (func) {
  17067. this.onAfterWorldMatrixUpdateObservable.add(func);
  17068. return this;
  17069. };
  17070. /**
  17071. * Removes a registered callback function.
  17072. * Returns the TransformNode.
  17073. */
  17074. TransformNode.prototype.unregisterAfterWorldMatrixUpdate = function (func) {
  17075. this.onAfterWorldMatrixUpdateObservable.removeCallback(func);
  17076. return this;
  17077. };
  17078. /**
  17079. * Clone the current transform node
  17080. * Returns the new transform node
  17081. * @param name Name of the new clone
  17082. * @param newParent New parent for the clone
  17083. * @param doNotCloneChildren Do not clone children hierarchy
  17084. */
  17085. TransformNode.prototype.clone = function (name, newParent, doNotCloneChildren) {
  17086. var _this = this;
  17087. var result = BABYLON.SerializationHelper.Clone(function () { return new TransformNode(name, _this.getScene()); }, this);
  17088. result.name = name;
  17089. result.id = name;
  17090. if (newParent) {
  17091. result.parent = newParent;
  17092. }
  17093. if (!doNotCloneChildren) {
  17094. // Children
  17095. var directDescendants = this.getDescendants(true);
  17096. for (var index = 0; index < directDescendants.length; index++) {
  17097. var child = directDescendants[index];
  17098. if (child.clone) {
  17099. child.clone(name + "." + child.name, result);
  17100. }
  17101. }
  17102. }
  17103. return result;
  17104. };
  17105. TransformNode.prototype.serialize = function (currentSerializationObject) {
  17106. var serializationObject = BABYLON.SerializationHelper.Serialize(this, currentSerializationObject);
  17107. serializationObject.type = this.getClassName();
  17108. // Parent
  17109. if (this.parent) {
  17110. serializationObject.parentId = this.parent.id;
  17111. }
  17112. if (BABYLON.Tags && BABYLON.Tags.HasTags(this)) {
  17113. serializationObject.tags = BABYLON.Tags.GetTags(this);
  17114. }
  17115. serializationObject.localMatrix = this.getPivotMatrix().asArray();
  17116. serializationObject.isEnabled = this.isEnabled();
  17117. // Parent
  17118. if (this.parent) {
  17119. serializationObject.parentId = this.parent.id;
  17120. }
  17121. return serializationObject;
  17122. };
  17123. // Statics
  17124. /**
  17125. * Returns a new TransformNode object parsed from the source provided.
  17126. * The parameter `parsedMesh` is the source.
  17127. * The parameter `rootUrl` is a string, it's the root URL to prefix the `delayLoadingFile` property with
  17128. */
  17129. TransformNode.Parse = function (parsedTransformNode, scene, rootUrl) {
  17130. var transformNode = BABYLON.SerializationHelper.Parse(function () { return new TransformNode(parsedTransformNode.name, scene); }, parsedTransformNode, scene, rootUrl);
  17131. if (BABYLON.Tags) {
  17132. BABYLON.Tags.AddTagsTo(transformNode, parsedTransformNode.tags);
  17133. }
  17134. if (parsedTransformNode.localMatrix) {
  17135. transformNode.setPreTransformMatrix(BABYLON.Matrix.FromArray(parsedTransformNode.localMatrix));
  17136. }
  17137. else if (parsedTransformNode.pivotMatrix) {
  17138. transformNode.setPivotMatrix(BABYLON.Matrix.FromArray(parsedTransformNode.pivotMatrix));
  17139. }
  17140. transformNode.setEnabled(parsedTransformNode.isEnabled);
  17141. // Parent
  17142. if (parsedTransformNode.parentId) {
  17143. transformNode._waitingParentId = parsedTransformNode.parentId;
  17144. }
  17145. return transformNode;
  17146. };
  17147. /**
  17148. * Releases resources associated with this transform node.
  17149. * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default)
  17150. * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default)
  17151. */
  17152. TransformNode.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  17153. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  17154. // Animations
  17155. this.getScene().stopAnimation(this);
  17156. // Remove from scene
  17157. this.getScene().removeTransformNode(this);
  17158. this.onAfterWorldMatrixUpdateObservable.clear();
  17159. _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
  17160. };
  17161. // Statics
  17162. TransformNode.BILLBOARDMODE_NONE = 0;
  17163. TransformNode.BILLBOARDMODE_X = 1;
  17164. TransformNode.BILLBOARDMODE_Y = 2;
  17165. TransformNode.BILLBOARDMODE_Z = 4;
  17166. TransformNode.BILLBOARDMODE_ALL = 7;
  17167. TransformNode._lookAtVectorCache = new BABYLON.Vector3(0, 0, 0);
  17168. TransformNode._rotationAxisCache = new BABYLON.Quaternion();
  17169. __decorate([
  17170. BABYLON.serializeAsVector3()
  17171. ], TransformNode.prototype, "_rotation", void 0);
  17172. __decorate([
  17173. BABYLON.serializeAsQuaternion()
  17174. ], TransformNode.prototype, "_rotationQuaternion", void 0);
  17175. __decorate([
  17176. BABYLON.serializeAsVector3()
  17177. ], TransformNode.prototype, "_scaling", void 0);
  17178. __decorate([
  17179. BABYLON.serialize()
  17180. ], TransformNode.prototype, "billboardMode", void 0);
  17181. __decorate([
  17182. BABYLON.serialize()
  17183. ], TransformNode.prototype, "scalingDeterminant", void 0);
  17184. __decorate([
  17185. BABYLON.serialize()
  17186. ], TransformNode.prototype, "infiniteDistance", void 0);
  17187. __decorate([
  17188. BABYLON.serializeAsVector3()
  17189. ], TransformNode.prototype, "position", void 0);
  17190. return TransformNode;
  17191. }(BABYLON.Node));
  17192. BABYLON.TransformNode = TransformNode;
  17193. })(BABYLON || (BABYLON = {}));
  17194. //# sourceMappingURL=babylon.transformNode.js.map
  17195. var BABYLON;
  17196. (function (BABYLON) {
  17197. var AbstractMesh = /** @class */ (function (_super) {
  17198. __extends(AbstractMesh, _super);
  17199. // Constructor
  17200. function AbstractMesh(name, scene) {
  17201. if (scene === void 0) { scene = null; }
  17202. var _this = _super.call(this, name, scene, false) || this;
  17203. _this._facetNb = 0; // facet number
  17204. _this._partitioningSubdivisions = 10; // number of subdivisions per axis in the partioning space
  17205. _this._partitioningBBoxRatio = 1.01; // the partioning array space is by default 1% bigger than the bounding box
  17206. _this._facetDataEnabled = false; // is the facet data feature enabled on this mesh ?
  17207. _this._facetParameters = {}; // keep a reference to the object parameters to avoid memory re-allocation
  17208. _this._bbSize = BABYLON.Vector3.Zero(); // bbox size approximated for facet data
  17209. _this._subDiv = {
  17210. max: 1,
  17211. X: 1,
  17212. Y: 1,
  17213. Z: 1
  17214. };
  17215. _this._facetDepthSort = false; // is the facet depth sort to be computed
  17216. _this._facetDepthSortEnabled = false; // is the facet depth sort initialized
  17217. // Events
  17218. /**
  17219. * An event triggered when this mesh collides with another one
  17220. * @type {BABYLON.Observable}
  17221. */
  17222. _this.onCollideObservable = new BABYLON.Observable();
  17223. /**
  17224. * An event triggered when the collision's position changes
  17225. * @type {BABYLON.Observable}
  17226. */
  17227. _this.onCollisionPositionChangeObservable = new BABYLON.Observable();
  17228. /**
  17229. * An event triggered when material is changed
  17230. * @type {BABYLON.Observable}
  17231. */
  17232. _this.onMaterialChangedObservable = new BABYLON.Observable();
  17233. // Properties
  17234. _this.definedFacingForward = true; // orientation for POV movement & rotation
  17235. /**
  17236. * This property determines the type of occlusion query algorithm to run in WebGl, you can use:
  17237. * AbstractMesh.OCCLUSION_ALGORITHM_TYPE_ACCURATE which is mapped to GL_ANY_SAMPLES_PASSED.
  17238. * or
  17239. * 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.
  17240. * for more info check WebGl documentations
  17241. */
  17242. _this.occlusionQueryAlgorithmType = AbstractMesh.OCCLUSION_ALGORITHM_TYPE_CONSERVATIVE;
  17243. /**
  17244. * 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:
  17245. * OCCLUSION_TYPE_NONE (Default Value): this option means no occlusion query whith the Mesh.
  17246. * OCCLUSION_TYPE_OPTIMISTIC: this option is means use occlusion query and if occlusionRetryCount is reached and the query is broken show the mesh.
  17247. * 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.
  17248. */
  17249. _this.occlusionType = AbstractMesh.OCCLUSION_TYPE_NONE;
  17250. /**
  17251. * 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.
  17252. * The default value is -1 which means don't break the query and wait till the result.
  17253. */
  17254. _this.occlusionRetryCount = -1;
  17255. _this._occlusionInternalRetryCounter = 0;
  17256. _this._isOccluded = false;
  17257. _this._isOcclusionQueryInProgress = false;
  17258. _this._visibility = 1.0;
  17259. _this.alphaIndex = Number.MAX_VALUE;
  17260. _this.isVisible = true;
  17261. _this.isPickable = true;
  17262. _this.showBoundingBox = false;
  17263. _this.showSubMeshesBoundingBox = false;
  17264. _this.isBlocker = false;
  17265. _this.enablePointerMoveEvents = false;
  17266. _this.renderingGroupId = 0;
  17267. _this._receiveShadows = false;
  17268. _this.renderOutline = false;
  17269. _this.outlineColor = BABYLON.Color3.Red();
  17270. _this.outlineWidth = 0.02;
  17271. _this.renderOverlay = false;
  17272. _this.overlayColor = BABYLON.Color3.Red();
  17273. _this.overlayAlpha = 0.5;
  17274. _this._hasVertexAlpha = false;
  17275. _this._useVertexColors = true;
  17276. _this._computeBonesUsingShaders = true;
  17277. _this._numBoneInfluencers = 4;
  17278. _this._applyFog = true;
  17279. _this.useOctreeForRenderingSelection = true;
  17280. _this.useOctreeForPicking = true;
  17281. _this.useOctreeForCollisions = true;
  17282. _this._layerMask = 0x0FFFFFFF;
  17283. /**
  17284. * True if the mesh must be rendered in any case.
  17285. */
  17286. _this.alwaysSelectAsActiveMesh = false;
  17287. /**
  17288. * This scene's action manager
  17289. * @type {BABYLON.ActionManager}
  17290. */
  17291. _this.actionManager = null;
  17292. // Physics
  17293. _this.physicsImpostor = null;
  17294. // Collisions
  17295. _this._checkCollisions = false;
  17296. _this._collisionMask = -1;
  17297. _this._collisionGroup = -1;
  17298. _this.ellipsoid = new BABYLON.Vector3(0.5, 1, 0.5);
  17299. _this.ellipsoidOffset = new BABYLON.Vector3(0, 0, 0);
  17300. _this._oldPositionForCollisions = new BABYLON.Vector3(0, 0, 0);
  17301. _this._diffPositionForCollisions = new BABYLON.Vector3(0, 0, 0);
  17302. // Edges
  17303. _this.edgesWidth = 1;
  17304. _this.edgesColor = new BABYLON.Color4(1, 0, 0, 1);
  17305. // Cache
  17306. _this._collisionsTransformMatrix = BABYLON.Matrix.Zero();
  17307. _this._collisionsScalingMatrix = BABYLON.Matrix.Zero();
  17308. _this._renderId = 0;
  17309. _this._intersectionsInProgress = new Array();
  17310. _this._unIndexed = false;
  17311. _this._lightSources = new Array();
  17312. _this._onCollisionPositionChange = function (collisionId, newPosition, collidedMesh) {
  17313. if (collidedMesh === void 0) { collidedMesh = null; }
  17314. //TODO move this to the collision coordinator!
  17315. if (_this.getScene().workerCollisions)
  17316. newPosition.multiplyInPlace(_this._collider._radius);
  17317. newPosition.subtractToRef(_this._oldPositionForCollisions, _this._diffPositionForCollisions);
  17318. if (_this._diffPositionForCollisions.length() > BABYLON.Engine.CollisionsEpsilon) {
  17319. _this.position.addInPlace(_this._diffPositionForCollisions);
  17320. }
  17321. if (collidedMesh) {
  17322. _this.onCollideObservable.notifyObservers(collidedMesh);
  17323. }
  17324. _this.onCollisionPositionChangeObservable.notifyObservers(_this.position);
  17325. };
  17326. _this.getScene().addMesh(_this);
  17327. _this._resyncLightSources();
  17328. return _this;
  17329. }
  17330. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_NONE", {
  17331. get: function () {
  17332. return BABYLON.TransformNode.BILLBOARDMODE_NONE;
  17333. },
  17334. enumerable: true,
  17335. configurable: true
  17336. });
  17337. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_X", {
  17338. get: function () {
  17339. return BABYLON.TransformNode.BILLBOARDMODE_X;
  17340. },
  17341. enumerable: true,
  17342. configurable: true
  17343. });
  17344. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_Y", {
  17345. get: function () {
  17346. return BABYLON.TransformNode.BILLBOARDMODE_Y;
  17347. },
  17348. enumerable: true,
  17349. configurable: true
  17350. });
  17351. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_Z", {
  17352. get: function () {
  17353. return BABYLON.TransformNode.BILLBOARDMODE_Z;
  17354. },
  17355. enumerable: true,
  17356. configurable: true
  17357. });
  17358. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_ALL", {
  17359. get: function () {
  17360. return BABYLON.TransformNode.BILLBOARDMODE_ALL;
  17361. },
  17362. enumerable: true,
  17363. configurable: true
  17364. });
  17365. Object.defineProperty(AbstractMesh.prototype, "facetNb", {
  17366. /**
  17367. * Read-only : the number of facets in the mesh
  17368. */
  17369. get: function () {
  17370. return this._facetNb;
  17371. },
  17372. enumerable: true,
  17373. configurable: true
  17374. });
  17375. Object.defineProperty(AbstractMesh.prototype, "partitioningSubdivisions", {
  17376. /**
  17377. * The number (integer) of subdivisions per axis in the partioning space
  17378. */
  17379. get: function () {
  17380. return this._partitioningSubdivisions;
  17381. },
  17382. set: function (nb) {
  17383. this._partitioningSubdivisions = nb;
  17384. },
  17385. enumerable: true,
  17386. configurable: true
  17387. });
  17388. Object.defineProperty(AbstractMesh.prototype, "partitioningBBoxRatio", {
  17389. /**
  17390. * The ratio (float) to apply to the bouding box size to set to the partioning space.
  17391. * Ex : 1.01 (default) the partioning space is 1% bigger than the bounding box.
  17392. */
  17393. get: function () {
  17394. return this._partitioningBBoxRatio;
  17395. },
  17396. set: function (ratio) {
  17397. this._partitioningBBoxRatio = ratio;
  17398. },
  17399. enumerable: true,
  17400. configurable: true
  17401. });
  17402. Object.defineProperty(AbstractMesh.prototype, "mustDepthSortFacets", {
  17403. /**
  17404. * Boolean : must the facet be depth sorted on next call to `updateFacetData()` ?
  17405. * Works only for updatable meshes.
  17406. * Doesn't work with multi-materials.
  17407. */
  17408. get: function () {
  17409. return this._facetDepthSort;
  17410. },
  17411. set: function (sort) {
  17412. this._facetDepthSort = sort;
  17413. },
  17414. enumerable: true,
  17415. configurable: true
  17416. });
  17417. Object.defineProperty(AbstractMesh.prototype, "facetDepthSortFrom", {
  17418. /**
  17419. * The location (Vector3) where the facet depth sort must be computed from.
  17420. * By default, the active camera position.
  17421. * Used only when facet depth sort is enabled.
  17422. */
  17423. get: function () {
  17424. return this._facetDepthSortFrom;
  17425. },
  17426. set: function (location) {
  17427. this._facetDepthSortFrom = location;
  17428. },
  17429. enumerable: true,
  17430. configurable: true
  17431. });
  17432. Object.defineProperty(AbstractMesh.prototype, "isFacetDataEnabled", {
  17433. /**
  17434. * Read-only boolean : is the feature facetData enabled ?
  17435. */
  17436. get: function () {
  17437. return this._facetDataEnabled;
  17438. },
  17439. enumerable: true,
  17440. configurable: true
  17441. });
  17442. AbstractMesh.prototype._updateNonUniformScalingState = function (value) {
  17443. if (!_super.prototype._updateNonUniformScalingState.call(this, value)) {
  17444. return false;
  17445. }
  17446. this._markSubMeshesAsMiscDirty();
  17447. return true;
  17448. };
  17449. Object.defineProperty(AbstractMesh.prototype, "onCollide", {
  17450. set: function (callback) {
  17451. if (this._onCollideObserver) {
  17452. this.onCollideObservable.remove(this._onCollideObserver);
  17453. }
  17454. this._onCollideObserver = this.onCollideObservable.add(callback);
  17455. },
  17456. enumerable: true,
  17457. configurable: true
  17458. });
  17459. Object.defineProperty(AbstractMesh.prototype, "onCollisionPositionChange", {
  17460. set: function (callback) {
  17461. if (this._onCollisionPositionChangeObserver) {
  17462. this.onCollisionPositionChangeObservable.remove(this._onCollisionPositionChangeObserver);
  17463. }
  17464. this._onCollisionPositionChangeObserver = this.onCollisionPositionChangeObservable.add(callback);
  17465. },
  17466. enumerable: true,
  17467. configurable: true
  17468. });
  17469. Object.defineProperty(AbstractMesh.prototype, "isOccluded", {
  17470. /**
  17471. * 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.
  17472. */
  17473. get: function () {
  17474. return this._isOccluded;
  17475. },
  17476. set: function (value) {
  17477. this._isOccluded = value;
  17478. },
  17479. enumerable: true,
  17480. configurable: true
  17481. });
  17482. Object.defineProperty(AbstractMesh.prototype, "isOcclusionQueryInProgress", {
  17483. /**
  17484. * Flag to check the progress status of the query
  17485. */
  17486. get: function () {
  17487. return this._isOcclusionQueryInProgress;
  17488. },
  17489. enumerable: true,
  17490. configurable: true
  17491. });
  17492. Object.defineProperty(AbstractMesh.prototype, "visibility", {
  17493. /**
  17494. * Gets or sets mesh visibility between 0 and 1 (defult is 1)
  17495. */
  17496. get: function () {
  17497. return this._visibility;
  17498. },
  17499. /**
  17500. * Gets or sets mesh visibility between 0 and 1 (defult is 1)
  17501. */
  17502. set: function (value) {
  17503. if (this._visibility === value) {
  17504. return;
  17505. }
  17506. this._visibility = value;
  17507. this._markSubMeshesAsMiscDirty();
  17508. },
  17509. enumerable: true,
  17510. configurable: true
  17511. });
  17512. Object.defineProperty(AbstractMesh.prototype, "material", {
  17513. get: function () {
  17514. return this._material;
  17515. },
  17516. set: function (value) {
  17517. if (this._material === value) {
  17518. return;
  17519. }
  17520. this._material = value;
  17521. if (this.onMaterialChangedObservable.hasObservers) {
  17522. this.onMaterialChangedObservable.notifyObservers(this);
  17523. }
  17524. if (!this.subMeshes) {
  17525. return;
  17526. }
  17527. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  17528. var subMesh = _a[_i];
  17529. subMesh.setEffect(null);
  17530. }
  17531. },
  17532. enumerable: true,
  17533. configurable: true
  17534. });
  17535. Object.defineProperty(AbstractMesh.prototype, "receiveShadows", {
  17536. get: function () {
  17537. return this._receiveShadows;
  17538. },
  17539. set: function (value) {
  17540. if (this._receiveShadows === value) {
  17541. return;
  17542. }
  17543. this._receiveShadows = value;
  17544. this._markSubMeshesAsLightDirty();
  17545. },
  17546. enumerable: true,
  17547. configurable: true
  17548. });
  17549. Object.defineProperty(AbstractMesh.prototype, "hasVertexAlpha", {
  17550. get: function () {
  17551. return this._hasVertexAlpha;
  17552. },
  17553. set: function (value) {
  17554. if (this._hasVertexAlpha === value) {
  17555. return;
  17556. }
  17557. this._hasVertexAlpha = value;
  17558. this._markSubMeshesAsAttributesDirty();
  17559. this._markSubMeshesAsMiscDirty();
  17560. },
  17561. enumerable: true,
  17562. configurable: true
  17563. });
  17564. Object.defineProperty(AbstractMesh.prototype, "useVertexColors", {
  17565. get: function () {
  17566. return this._useVertexColors;
  17567. },
  17568. set: function (value) {
  17569. if (this._useVertexColors === value) {
  17570. return;
  17571. }
  17572. this._useVertexColors = value;
  17573. this._markSubMeshesAsAttributesDirty();
  17574. },
  17575. enumerable: true,
  17576. configurable: true
  17577. });
  17578. Object.defineProperty(AbstractMesh.prototype, "computeBonesUsingShaders", {
  17579. get: function () {
  17580. return this._computeBonesUsingShaders;
  17581. },
  17582. set: function (value) {
  17583. if (this._computeBonesUsingShaders === value) {
  17584. return;
  17585. }
  17586. this._computeBonesUsingShaders = value;
  17587. this._markSubMeshesAsAttributesDirty();
  17588. },
  17589. enumerable: true,
  17590. configurable: true
  17591. });
  17592. Object.defineProperty(AbstractMesh.prototype, "numBoneInfluencers", {
  17593. get: function () {
  17594. return this._numBoneInfluencers;
  17595. },
  17596. set: function (value) {
  17597. if (this._numBoneInfluencers === value) {
  17598. return;
  17599. }
  17600. this._numBoneInfluencers = value;
  17601. this._markSubMeshesAsAttributesDirty();
  17602. },
  17603. enumerable: true,
  17604. configurable: true
  17605. });
  17606. Object.defineProperty(AbstractMesh.prototype, "applyFog", {
  17607. get: function () {
  17608. return this._applyFog;
  17609. },
  17610. set: function (value) {
  17611. if (this._applyFog === value) {
  17612. return;
  17613. }
  17614. this._applyFog = value;
  17615. this._markSubMeshesAsMiscDirty();
  17616. },
  17617. enumerable: true,
  17618. configurable: true
  17619. });
  17620. Object.defineProperty(AbstractMesh.prototype, "layerMask", {
  17621. get: function () {
  17622. return this._layerMask;
  17623. },
  17624. set: function (value) {
  17625. if (value === this._layerMask) {
  17626. return;
  17627. }
  17628. this._layerMask = value;
  17629. this._resyncLightSources();
  17630. },
  17631. enumerable: true,
  17632. configurable: true
  17633. });
  17634. Object.defineProperty(AbstractMesh.prototype, "collisionMask", {
  17635. get: function () {
  17636. return this._collisionMask;
  17637. },
  17638. set: function (mask) {
  17639. this._collisionMask = !isNaN(mask) ? mask : -1;
  17640. },
  17641. enumerable: true,
  17642. configurable: true
  17643. });
  17644. Object.defineProperty(AbstractMesh.prototype, "collisionGroup", {
  17645. get: function () {
  17646. return this._collisionGroup;
  17647. },
  17648. set: function (mask) {
  17649. this._collisionGroup = !isNaN(mask) ? mask : -1;
  17650. },
  17651. enumerable: true,
  17652. configurable: true
  17653. });
  17654. Object.defineProperty(AbstractMesh.prototype, "_positions", {
  17655. get: function () {
  17656. return null;
  17657. },
  17658. enumerable: true,
  17659. configurable: true
  17660. });
  17661. Object.defineProperty(AbstractMesh.prototype, "skeleton", {
  17662. get: function () {
  17663. return this._skeleton;
  17664. },
  17665. set: function (value) {
  17666. if (this._skeleton && this._skeleton.needInitialSkinMatrix) {
  17667. this._skeleton._unregisterMeshWithPoseMatrix(this);
  17668. }
  17669. if (value && value.needInitialSkinMatrix) {
  17670. value._registerMeshWithPoseMatrix(this);
  17671. }
  17672. this._skeleton = value;
  17673. if (!this._skeleton) {
  17674. this._bonesTransformMatrices = null;
  17675. }
  17676. this._markSubMeshesAsAttributesDirty();
  17677. },
  17678. enumerable: true,
  17679. configurable: true
  17680. });
  17681. /**
  17682. * Returns the string "AbstractMesh"
  17683. */
  17684. AbstractMesh.prototype.getClassName = function () {
  17685. return "AbstractMesh";
  17686. };
  17687. /**
  17688. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  17689. */
  17690. AbstractMesh.prototype.toString = function (fullDetails) {
  17691. var ret = "Name: " + this.name + ", isInstance: " + (this instanceof BABYLON.InstancedMesh ? "YES" : "NO");
  17692. ret += ", # of submeshes: " + (this.subMeshes ? this.subMeshes.length : 0);
  17693. if (this._skeleton) {
  17694. ret += ", skeleton: " + this._skeleton.name;
  17695. }
  17696. if (fullDetails) {
  17697. ret += ", billboard mode: " + (["NONE", "X", "Y", null, "Z", null, null, "ALL"])[this.billboardMode];
  17698. ret += ", freeze wrld mat: " + (this._isWorldMatrixFrozen || this._waitingFreezeWorldMatrix ? "YES" : "NO");
  17699. }
  17700. return ret;
  17701. };
  17702. AbstractMesh.prototype._rebuild = function () {
  17703. if (this._occlusionQuery) {
  17704. this._occlusionQuery = null;
  17705. }
  17706. if (this._edgesRenderer) {
  17707. this._edgesRenderer._rebuild();
  17708. }
  17709. if (!this.subMeshes) {
  17710. return;
  17711. }
  17712. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  17713. var subMesh = _a[_i];
  17714. subMesh._rebuild();
  17715. }
  17716. };
  17717. AbstractMesh.prototype._resyncLightSources = function () {
  17718. this._lightSources.length = 0;
  17719. for (var _i = 0, _a = this.getScene().lights; _i < _a.length; _i++) {
  17720. var light = _a[_i];
  17721. if (!light.isEnabled()) {
  17722. continue;
  17723. }
  17724. if (light.canAffectMesh(this)) {
  17725. this._lightSources.push(light);
  17726. }
  17727. }
  17728. this._markSubMeshesAsLightDirty();
  17729. };
  17730. AbstractMesh.prototype._resyncLighSource = function (light) {
  17731. var isIn = light.isEnabled() && light.canAffectMesh(this);
  17732. var index = this._lightSources.indexOf(light);
  17733. if (index === -1) {
  17734. if (!isIn) {
  17735. return;
  17736. }
  17737. this._lightSources.push(light);
  17738. }
  17739. else {
  17740. if (isIn) {
  17741. return;
  17742. }
  17743. this._lightSources.splice(index, 1);
  17744. }
  17745. this._markSubMeshesAsLightDirty();
  17746. };
  17747. AbstractMesh.prototype._removeLightSource = function (light) {
  17748. var index = this._lightSources.indexOf(light);
  17749. if (index === -1) {
  17750. return;
  17751. }
  17752. this._lightSources.splice(index, 1);
  17753. this._markSubMeshesAsLightDirty();
  17754. };
  17755. AbstractMesh.prototype._markSubMeshesAsDirty = function (func) {
  17756. if (!this.subMeshes) {
  17757. return;
  17758. }
  17759. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  17760. var subMesh = _a[_i];
  17761. if (subMesh._materialDefines) {
  17762. func(subMesh._materialDefines);
  17763. }
  17764. }
  17765. };
  17766. AbstractMesh.prototype._markSubMeshesAsLightDirty = function () {
  17767. this._markSubMeshesAsDirty(function (defines) { return defines.markAsLightDirty(); });
  17768. };
  17769. AbstractMesh.prototype._markSubMeshesAsAttributesDirty = function () {
  17770. this._markSubMeshesAsDirty(function (defines) { return defines.markAsAttributesDirty(); });
  17771. };
  17772. AbstractMesh.prototype._markSubMeshesAsMiscDirty = function () {
  17773. if (!this.subMeshes) {
  17774. return;
  17775. }
  17776. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  17777. var subMesh = _a[_i];
  17778. var material = subMesh.getMaterial();
  17779. if (material) {
  17780. material.markAsDirty(BABYLON.Material.MiscDirtyFlag);
  17781. }
  17782. }
  17783. };
  17784. Object.defineProperty(AbstractMesh.prototype, "scaling", {
  17785. /**
  17786. * Scaling property : a Vector3 depicting the mesh scaling along each local axis X, Y, Z.
  17787. * Default : (1.0, 1.0, 1.0)
  17788. */
  17789. get: function () {
  17790. return this._scaling;
  17791. },
  17792. /**
  17793. * Scaling property : a Vector3 depicting the mesh scaling along each local axis X, Y, Z.
  17794. * Default : (1.0, 1.0, 1.0)
  17795. */
  17796. set: function (newScaling) {
  17797. this._scaling = newScaling;
  17798. if (this.physicsImpostor) {
  17799. this.physicsImpostor.forceUpdate();
  17800. }
  17801. },
  17802. enumerable: true,
  17803. configurable: true
  17804. });
  17805. // Methods
  17806. /**
  17807. * Disables the mesh edger rendering mode.
  17808. * Returns the AbstractMesh.
  17809. */
  17810. AbstractMesh.prototype.disableEdgesRendering = function () {
  17811. if (this._edgesRenderer) {
  17812. this._edgesRenderer.dispose();
  17813. this._edgesRenderer = null;
  17814. }
  17815. return this;
  17816. };
  17817. /**
  17818. * Enables the edge rendering mode on the mesh.
  17819. * This mode makes the mesh edges visible.
  17820. * Returns the AbstractMesh.
  17821. */
  17822. AbstractMesh.prototype.enableEdgesRendering = function (epsilon, checkVerticesInsteadOfIndices) {
  17823. if (epsilon === void 0) { epsilon = 0.95; }
  17824. if (checkVerticesInsteadOfIndices === void 0) { checkVerticesInsteadOfIndices = false; }
  17825. this.disableEdgesRendering();
  17826. this._edgesRenderer = new BABYLON.EdgesRenderer(this, epsilon, checkVerticesInsteadOfIndices);
  17827. return this;
  17828. };
  17829. Object.defineProperty(AbstractMesh.prototype, "isBlocked", {
  17830. /**
  17831. * Returns true if the mesh is blocked. Used by the class Mesh.
  17832. * Returns the boolean `false` by default.
  17833. */
  17834. get: function () {
  17835. return false;
  17836. },
  17837. enumerable: true,
  17838. configurable: true
  17839. });
  17840. /**
  17841. * Returns the mesh itself by default, used by the class Mesh.
  17842. * Returned type : AbstractMesh
  17843. */
  17844. AbstractMesh.prototype.getLOD = function (camera) {
  17845. return this;
  17846. };
  17847. /**
  17848. * Returns 0 by default, used by the class Mesh.
  17849. * Returns an integer.
  17850. */
  17851. AbstractMesh.prototype.getTotalVertices = function () {
  17852. return 0;
  17853. };
  17854. /**
  17855. * Returns null by default, used by the class Mesh.
  17856. * Returned type : integer array
  17857. */
  17858. AbstractMesh.prototype.getIndices = function () {
  17859. return null;
  17860. };
  17861. /**
  17862. * Returns the array of the requested vertex data kind. Used by the class Mesh. Returns null here.
  17863. * Returned type : float array or Float32Array
  17864. */
  17865. AbstractMesh.prototype.getVerticesData = function (kind) {
  17866. return null;
  17867. };
  17868. /**
  17869. * Sets the vertex data of the mesh geometry for the requested `kind`.
  17870. * If the mesh has no geometry, a new Geometry object is set to the mesh and then passed this vertex data.
  17871. * The `data` are either a numeric array either a Float32Array.
  17872. * The parameter `updatable` is passed as is to the underlying Geometry object constructor (if initianilly none) or updater.
  17873. * 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).
  17874. * Note that a new underlying VertexBuffer object is created each call.
  17875. * If the `kind` is the `PositionKind`, the mesh BoundingInfo is renewed, so the bounding box and sphere, and the mesh World Matrix is recomputed.
  17876. *
  17877. * Possible `kind` values :
  17878. * - BABYLON.VertexBuffer.PositionKind
  17879. * - BABYLON.VertexBuffer.UVKind
  17880. * - BABYLON.VertexBuffer.UV2Kind
  17881. * - BABYLON.VertexBuffer.UV3Kind
  17882. * - BABYLON.VertexBuffer.UV4Kind
  17883. * - BABYLON.VertexBuffer.UV5Kind
  17884. * - BABYLON.VertexBuffer.UV6Kind
  17885. * - BABYLON.VertexBuffer.ColorKind
  17886. * - BABYLON.VertexBuffer.MatricesIndicesKind
  17887. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  17888. * - BABYLON.VertexBuffer.MatricesWeightsKind
  17889. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  17890. *
  17891. * Returns the Mesh.
  17892. */
  17893. AbstractMesh.prototype.setVerticesData = function (kind, data, updatable, stride) {
  17894. return this;
  17895. };
  17896. /**
  17897. * Updates the existing vertex data of the mesh geometry for the requested `kind`.
  17898. * If the mesh has no geometry, it is simply returned as it is.
  17899. * The `data` are either a numeric array either a Float32Array.
  17900. * No new underlying VertexBuffer object is created.
  17901. * 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.
  17902. * If the parameter `makeItUnique` is true, a new global geometry is created from this positions and is set to the mesh.
  17903. *
  17904. * Possible `kind` values :
  17905. * - BABYLON.VertexBuffer.PositionKind
  17906. * - BABYLON.VertexBuffer.UVKind
  17907. * - BABYLON.VertexBuffer.UV2Kind
  17908. * - BABYLON.VertexBuffer.UV3Kind
  17909. * - BABYLON.VertexBuffer.UV4Kind
  17910. * - BABYLON.VertexBuffer.UV5Kind
  17911. * - BABYLON.VertexBuffer.UV6Kind
  17912. * - BABYLON.VertexBuffer.ColorKind
  17913. * - BABYLON.VertexBuffer.MatricesIndicesKind
  17914. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  17915. * - BABYLON.VertexBuffer.MatricesWeightsKind
  17916. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  17917. *
  17918. * Returns the Mesh.
  17919. */
  17920. AbstractMesh.prototype.updateVerticesData = function (kind, data, updateExtends, makeItUnique) {
  17921. return this;
  17922. };
  17923. /**
  17924. * Sets the mesh indices.
  17925. * Expects an array populated with integers or a typed array (Int32Array, Uint32Array, Uint16Array).
  17926. * If the mesh has no geometry, a new Geometry object is created and set to the mesh.
  17927. * This method creates a new index buffer each call.
  17928. * Returns the Mesh.
  17929. */
  17930. AbstractMesh.prototype.setIndices = function (indices, totalVertices) {
  17931. return this;
  17932. };
  17933. /** Returns false by default, used by the class Mesh.
  17934. * Returns a boolean
  17935. */
  17936. AbstractMesh.prototype.isVerticesDataPresent = function (kind) {
  17937. return false;
  17938. };
  17939. /**
  17940. * Returns the mesh BoundingInfo object or creates a new one and returns it if undefined.
  17941. * Returns a BoundingInfo
  17942. */
  17943. AbstractMesh.prototype.getBoundingInfo = function () {
  17944. if (this._masterMesh) {
  17945. return this._masterMesh.getBoundingInfo();
  17946. }
  17947. if (!this._boundingInfo) {
  17948. // this._boundingInfo is being created here
  17949. this._updateBoundingInfo();
  17950. }
  17951. // cannot be null.
  17952. return this._boundingInfo;
  17953. };
  17954. /**
  17955. * Uniformly scales the mesh to fit inside of a unit cube (1 X 1 X 1 units).
  17956. * @param includeDescendants Take the hierarchy's bounding box instead of the mesh's bounding box.
  17957. */
  17958. AbstractMesh.prototype.normalizeToUnitCube = function (includeDescendants) {
  17959. if (includeDescendants === void 0) { includeDescendants = true; }
  17960. var boundingVectors = this.getHierarchyBoundingVectors(includeDescendants);
  17961. var sizeVec = boundingVectors.max.subtract(boundingVectors.min);
  17962. var maxDimension = Math.max(sizeVec.x, sizeVec.y, sizeVec.z);
  17963. if (maxDimension === 0) {
  17964. return this;
  17965. }
  17966. var scale = 1 / maxDimension;
  17967. this.scaling.scaleInPlace(scale);
  17968. return this;
  17969. };
  17970. /**
  17971. * Sets a mesh new object BoundingInfo.
  17972. * Returns the AbstractMesh.
  17973. */
  17974. AbstractMesh.prototype.setBoundingInfo = function (boundingInfo) {
  17975. this._boundingInfo = boundingInfo;
  17976. return this;
  17977. };
  17978. Object.defineProperty(AbstractMesh.prototype, "useBones", {
  17979. get: function () {
  17980. return (this.skeleton && this.getScene().skeletonsEnabled && this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind) && this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind));
  17981. },
  17982. enumerable: true,
  17983. configurable: true
  17984. });
  17985. AbstractMesh.prototype._preActivate = function () {
  17986. };
  17987. AbstractMesh.prototype._preActivateForIntermediateRendering = function (renderId) {
  17988. };
  17989. AbstractMesh.prototype._activate = function (renderId) {
  17990. this._renderId = renderId;
  17991. };
  17992. /**
  17993. * Returns the latest update of the World matrix
  17994. * Returns a Matrix.
  17995. */
  17996. AbstractMesh.prototype.getWorldMatrix = function () {
  17997. if (this._masterMesh) {
  17998. return this._masterMesh.getWorldMatrix();
  17999. }
  18000. return _super.prototype.getWorldMatrix.call(this);
  18001. };
  18002. /**
  18003. * Returns the latest update of the World matrix determinant.
  18004. */
  18005. AbstractMesh.prototype._getWorldMatrixDeterminant = function () {
  18006. if (this._masterMesh) {
  18007. return this._masterMesh._getWorldMatrixDeterminant();
  18008. }
  18009. return _super.prototype._getWorldMatrixDeterminant.call(this);
  18010. };
  18011. // ================================== Point of View Movement =================================
  18012. /**
  18013. * Perform relative position change from the point of view of behind the front of the mesh.
  18014. * This is performed taking into account the meshes current rotation, so you do not have to care.
  18015. * Supports definition of mesh facing forward or backward.
  18016. * @param {number} amountRight
  18017. * @param {number} amountUp
  18018. * @param {number} amountForward
  18019. *
  18020. * Returns the AbstractMesh.
  18021. */
  18022. AbstractMesh.prototype.movePOV = function (amountRight, amountUp, amountForward) {
  18023. this.position.addInPlace(this.calcMovePOV(amountRight, amountUp, amountForward));
  18024. return this;
  18025. };
  18026. /**
  18027. * Calculate relative position change from the point of view of behind the front of the mesh.
  18028. * This is performed taking into account the meshes current rotation, so you do not have to care.
  18029. * Supports definition of mesh facing forward or backward.
  18030. * @param {number} amountRight
  18031. * @param {number} amountUp
  18032. * @param {number} amountForward
  18033. *
  18034. * Returns a new Vector3.
  18035. */
  18036. AbstractMesh.prototype.calcMovePOV = function (amountRight, amountUp, amountForward) {
  18037. var rotMatrix = new BABYLON.Matrix();
  18038. var rotQuaternion = (this.rotationQuaternion) ? this.rotationQuaternion : BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z);
  18039. rotQuaternion.toRotationMatrix(rotMatrix);
  18040. var translationDelta = BABYLON.Vector3.Zero();
  18041. var defForwardMult = this.definedFacingForward ? -1 : 1;
  18042. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(amountRight * defForwardMult, amountUp, amountForward * defForwardMult, rotMatrix, translationDelta);
  18043. return translationDelta;
  18044. };
  18045. // ================================== Point of View Rotation =================================
  18046. /**
  18047. * Perform relative rotation change from the point of view of behind the front of the mesh.
  18048. * Supports definition of mesh facing forward or backward.
  18049. * @param {number} flipBack
  18050. * @param {number} twirlClockwise
  18051. * @param {number} tiltRight
  18052. *
  18053. * Returns the AbstractMesh.
  18054. */
  18055. AbstractMesh.prototype.rotatePOV = function (flipBack, twirlClockwise, tiltRight) {
  18056. this.rotation.addInPlace(this.calcRotatePOV(flipBack, twirlClockwise, tiltRight));
  18057. return this;
  18058. };
  18059. /**
  18060. * Calculate relative rotation change from the point of view of behind the front of the mesh.
  18061. * Supports definition of mesh facing forward or backward.
  18062. * @param {number} flipBack
  18063. * @param {number} twirlClockwise
  18064. * @param {number} tiltRight
  18065. *
  18066. * Returns a new Vector3.
  18067. */
  18068. AbstractMesh.prototype.calcRotatePOV = function (flipBack, twirlClockwise, tiltRight) {
  18069. var defForwardMult = this.definedFacingForward ? 1 : -1;
  18070. return new BABYLON.Vector3(flipBack * defForwardMult, twirlClockwise, tiltRight * defForwardMult);
  18071. };
  18072. /**
  18073. * Return the minimum and maximum world vectors of the entire hierarchy under current mesh
  18074. * @param includeDescendants Include bounding info from descendants as well (true by default).
  18075. */
  18076. AbstractMesh.prototype.getHierarchyBoundingVectors = function (includeDescendants) {
  18077. if (includeDescendants === void 0) { includeDescendants = true; }
  18078. this.computeWorldMatrix(true);
  18079. var min;
  18080. var max;
  18081. var boundingInfo = this.getBoundingInfo();
  18082. if (!this.subMeshes) {
  18083. min = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  18084. max = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  18085. }
  18086. else {
  18087. min = boundingInfo.boundingBox.minimumWorld;
  18088. max = boundingInfo.boundingBox.maximumWorld;
  18089. }
  18090. if (includeDescendants) {
  18091. var descendants = this.getDescendants(false);
  18092. for (var _i = 0, descendants_1 = descendants; _i < descendants_1.length; _i++) {
  18093. var descendant = descendants_1[_i];
  18094. var childMesh = descendant;
  18095. childMesh.computeWorldMatrix(true);
  18096. //make sure we have the needed params to get mix and max
  18097. if (!childMesh.getBoundingInfo || childMesh.getTotalVertices() === 0) {
  18098. continue;
  18099. }
  18100. var childBoundingInfo = childMesh.getBoundingInfo();
  18101. var boundingBox = childBoundingInfo.boundingBox;
  18102. var minBox = boundingBox.minimumWorld;
  18103. var maxBox = boundingBox.maximumWorld;
  18104. BABYLON.Tools.CheckExtends(minBox, min, max);
  18105. BABYLON.Tools.CheckExtends(maxBox, min, max);
  18106. }
  18107. }
  18108. return {
  18109. min: min,
  18110. max: max
  18111. };
  18112. };
  18113. /**
  18114. * Updates the mesh BoundingInfo object and all its children BoundingInfo objects also.
  18115. * Returns the AbstractMesh.
  18116. */
  18117. AbstractMesh.prototype._updateBoundingInfo = function () {
  18118. this._boundingInfo = this._boundingInfo || new BABYLON.BoundingInfo(this.absolutePosition, this.absolutePosition);
  18119. this._boundingInfo.update(this.worldMatrixFromCache);
  18120. this._updateSubMeshesBoundingInfo(this.worldMatrixFromCache);
  18121. return this;
  18122. };
  18123. /**
  18124. * Update a mesh's children BoundingInfo objects only.
  18125. * Returns the AbstractMesh.
  18126. */
  18127. AbstractMesh.prototype._updateSubMeshesBoundingInfo = function (matrix) {
  18128. if (!this.subMeshes) {
  18129. return this;
  18130. }
  18131. for (var subIndex = 0; subIndex < this.subMeshes.length; subIndex++) {
  18132. var subMesh = this.subMeshes[subIndex];
  18133. if (!subMesh.IsGlobal) {
  18134. subMesh.updateBoundingInfo(matrix);
  18135. }
  18136. }
  18137. return this;
  18138. };
  18139. AbstractMesh.prototype._afterComputeWorldMatrix = function () {
  18140. // Bounding info
  18141. this._updateBoundingInfo();
  18142. };
  18143. /**
  18144. * Returns `true` if the mesh is within the frustum defined by the passed array of planes.
  18145. * A mesh is in the frustum if its bounding box intersects the frustum.
  18146. * Boolean returned.
  18147. */
  18148. AbstractMesh.prototype.isInFrustum = function (frustumPlanes) {
  18149. return this._boundingInfo !== null && this._boundingInfo.isInFrustum(frustumPlanes);
  18150. };
  18151. /**
  18152. * Returns `true` if the mesh is completely in the frustum defined be the passed array of planes.
  18153. * A mesh is completely in the frustum if its bounding box it completely inside the frustum.
  18154. * Boolean returned.
  18155. */
  18156. AbstractMesh.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  18157. return this._boundingInfo !== null && this._boundingInfo.isCompletelyInFrustum(frustumPlanes);
  18158. ;
  18159. };
  18160. /**
  18161. * True if the mesh intersects another mesh or a SolidParticle object.
  18162. * 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)
  18163. * includeDescendants can be set to true to test if the mesh defined in parameters intersects with the current mesh or any child meshes
  18164. * Returns a boolean.
  18165. */
  18166. AbstractMesh.prototype.intersectsMesh = function (mesh, precise, includeDescendants) {
  18167. if (precise === void 0) { precise = false; }
  18168. if (!this._boundingInfo || !mesh._boundingInfo) {
  18169. return false;
  18170. }
  18171. if (this._boundingInfo.intersects(mesh._boundingInfo, precise)) {
  18172. return true;
  18173. }
  18174. if (includeDescendants) {
  18175. for (var _i = 0, _a = this.getChildMeshes(); _i < _a.length; _i++) {
  18176. var child = _a[_i];
  18177. if (child.intersectsMesh(mesh, precise, true)) {
  18178. return true;
  18179. }
  18180. }
  18181. }
  18182. return false;
  18183. };
  18184. /**
  18185. * Returns true if the passed point (Vector3) is inside the mesh bounding box.
  18186. * Returns a boolean.
  18187. */
  18188. AbstractMesh.prototype.intersectsPoint = function (point) {
  18189. if (!this._boundingInfo) {
  18190. return false;
  18191. }
  18192. return this._boundingInfo.intersectsPoint(point);
  18193. };
  18194. AbstractMesh.prototype.getPhysicsImpostor = function () {
  18195. return this.physicsImpostor;
  18196. };
  18197. AbstractMesh.prototype.getPositionInCameraSpace = function (camera) {
  18198. if (camera === void 0) { camera = null; }
  18199. if (!camera) {
  18200. camera = this.getScene().activeCamera;
  18201. }
  18202. return BABYLON.Vector3.TransformCoordinates(this.absolutePosition, camera.getViewMatrix());
  18203. };
  18204. /**
  18205. * Returns the distance from the mesh to the active camera.
  18206. * Returns a float.
  18207. */
  18208. AbstractMesh.prototype.getDistanceToCamera = function (camera) {
  18209. if (camera === void 0) { camera = null; }
  18210. if (!camera) {
  18211. camera = this.getScene().activeCamera;
  18212. }
  18213. return this.absolutePosition.subtract(camera.position).length();
  18214. };
  18215. AbstractMesh.prototype.applyImpulse = function (force, contactPoint) {
  18216. if (!this.physicsImpostor) {
  18217. return this;
  18218. }
  18219. this.physicsImpostor.applyImpulse(force, contactPoint);
  18220. return this;
  18221. };
  18222. AbstractMesh.prototype.setPhysicsLinkWith = function (otherMesh, pivot1, pivot2, options) {
  18223. if (!this.physicsImpostor || !otherMesh.physicsImpostor) {
  18224. return this;
  18225. }
  18226. this.physicsImpostor.createJoint(otherMesh.physicsImpostor, BABYLON.PhysicsJoint.HingeJoint, {
  18227. mainPivot: pivot1,
  18228. connectedPivot: pivot2,
  18229. nativeParams: options
  18230. });
  18231. return this;
  18232. };
  18233. Object.defineProperty(AbstractMesh.prototype, "checkCollisions", {
  18234. // Collisions
  18235. /**
  18236. * Property checkCollisions : Boolean, whether the camera should check the collisions against the mesh.
  18237. * Default `false`.
  18238. */
  18239. get: function () {
  18240. return this._checkCollisions;
  18241. },
  18242. set: function (collisionEnabled) {
  18243. this._checkCollisions = collisionEnabled;
  18244. if (this.getScene().workerCollisions) {
  18245. this.getScene().collisionCoordinator.onMeshUpdated(this);
  18246. }
  18247. },
  18248. enumerable: true,
  18249. configurable: true
  18250. });
  18251. Object.defineProperty(AbstractMesh.prototype, "collider", {
  18252. /**
  18253. * Gets Collider object used to compute collisions (not physics)
  18254. */
  18255. get: function () {
  18256. return this._collider;
  18257. },
  18258. enumerable: true,
  18259. configurable: true
  18260. });
  18261. AbstractMesh.prototype.moveWithCollisions = function (displacement) {
  18262. var globalPosition = this.getAbsolutePosition();
  18263. globalPosition.addToRef(this.ellipsoidOffset, this._oldPositionForCollisions);
  18264. if (!this._collider) {
  18265. this._collider = new BABYLON.Collider();
  18266. }
  18267. this._collider._radius = this.ellipsoid;
  18268. this.getScene().collisionCoordinator.getNewPosition(this._oldPositionForCollisions, displacement, this._collider, 3, this, this._onCollisionPositionChange, this.uniqueId);
  18269. return this;
  18270. };
  18271. // Submeshes octree
  18272. /**
  18273. * This function will create an octree to help to select the right submeshes for rendering, picking and collision computations.
  18274. * Please note that you must have a decent number of submeshes to get performance improvements when using an octree.
  18275. * Returns an Octree of submeshes.
  18276. */
  18277. AbstractMesh.prototype.createOrUpdateSubmeshesOctree = function (maxCapacity, maxDepth) {
  18278. if (maxCapacity === void 0) { maxCapacity = 64; }
  18279. if (maxDepth === void 0) { maxDepth = 2; }
  18280. if (!this._submeshesOctree) {
  18281. this._submeshesOctree = new BABYLON.Octree(BABYLON.Octree.CreationFuncForSubMeshes, maxCapacity, maxDepth);
  18282. }
  18283. this.computeWorldMatrix(true);
  18284. var boundingInfo = this.getBoundingInfo();
  18285. // Update octree
  18286. var bbox = boundingInfo.boundingBox;
  18287. this._submeshesOctree.update(bbox.minimumWorld, bbox.maximumWorld, this.subMeshes);
  18288. return this._submeshesOctree;
  18289. };
  18290. // Collisions
  18291. AbstractMesh.prototype._collideForSubMesh = function (subMesh, transformMatrix, collider) {
  18292. this._generatePointsArray();
  18293. if (!this._positions) {
  18294. return this;
  18295. }
  18296. // Transformation
  18297. if (!subMesh._lastColliderWorldVertices || !subMesh._lastColliderTransformMatrix.equals(transformMatrix)) {
  18298. subMesh._lastColliderTransformMatrix = transformMatrix.clone();
  18299. subMesh._lastColliderWorldVertices = [];
  18300. subMesh._trianglePlanes = [];
  18301. var start = subMesh.verticesStart;
  18302. var end = (subMesh.verticesStart + subMesh.verticesCount);
  18303. for (var i = start; i < end; i++) {
  18304. subMesh._lastColliderWorldVertices.push(BABYLON.Vector3.TransformCoordinates(this._positions[i], transformMatrix));
  18305. }
  18306. }
  18307. // Collide
  18308. collider._collide(subMesh._trianglePlanes, subMesh._lastColliderWorldVertices, this.getIndices(), subMesh.indexStart, subMesh.indexStart + subMesh.indexCount, subMesh.verticesStart, !!subMesh.getMaterial());
  18309. if (collider.collisionFound) {
  18310. collider.collidedMesh = this;
  18311. }
  18312. return this;
  18313. };
  18314. AbstractMesh.prototype._processCollisionsForSubMeshes = function (collider, transformMatrix) {
  18315. var subMeshes;
  18316. var len;
  18317. // Octrees
  18318. if (this._submeshesOctree && this.useOctreeForCollisions) {
  18319. var radius = collider._velocityWorldLength + Math.max(collider._radius.x, collider._radius.y, collider._radius.z);
  18320. var intersections = this._submeshesOctree.intersects(collider._basePointWorld, radius);
  18321. len = intersections.length;
  18322. subMeshes = intersections.data;
  18323. }
  18324. else {
  18325. subMeshes = this.subMeshes;
  18326. len = subMeshes.length;
  18327. }
  18328. for (var index = 0; index < len; index++) {
  18329. var subMesh = subMeshes[index];
  18330. // Bounding test
  18331. if (len > 1 && !subMesh._checkCollision(collider))
  18332. continue;
  18333. this._collideForSubMesh(subMesh, transformMatrix, collider);
  18334. }
  18335. return this;
  18336. };
  18337. AbstractMesh.prototype._checkCollision = function (collider) {
  18338. // Bounding box test
  18339. if (!this._boundingInfo || !this._boundingInfo._checkCollision(collider))
  18340. return this;
  18341. // Transformation matrix
  18342. BABYLON.Matrix.ScalingToRef(1.0 / collider._radius.x, 1.0 / collider._radius.y, 1.0 / collider._radius.z, this._collisionsScalingMatrix);
  18343. this.worldMatrixFromCache.multiplyToRef(this._collisionsScalingMatrix, this._collisionsTransformMatrix);
  18344. this._processCollisionsForSubMeshes(collider, this._collisionsTransformMatrix);
  18345. return this;
  18346. };
  18347. // Picking
  18348. AbstractMesh.prototype._generatePointsArray = function () {
  18349. return false;
  18350. };
  18351. /**
  18352. * Checks if the passed Ray intersects with the mesh.
  18353. * Returns an object PickingInfo.
  18354. */
  18355. AbstractMesh.prototype.intersects = function (ray, fastCheck) {
  18356. var pickingInfo = new BABYLON.PickingInfo();
  18357. if (!this.subMeshes || !this._boundingInfo || !ray.intersectsSphere(this._boundingInfo.boundingSphere) || !ray.intersectsBox(this._boundingInfo.boundingBox)) {
  18358. return pickingInfo;
  18359. }
  18360. if (!this._generatePointsArray()) {
  18361. return pickingInfo;
  18362. }
  18363. var intersectInfo = null;
  18364. // Octrees
  18365. var subMeshes;
  18366. var len;
  18367. if (this._submeshesOctree && this.useOctreeForPicking) {
  18368. var worldRay = BABYLON.Ray.Transform(ray, this.getWorldMatrix());
  18369. var intersections = this._submeshesOctree.intersectsRay(worldRay);
  18370. len = intersections.length;
  18371. subMeshes = intersections.data;
  18372. }
  18373. else {
  18374. subMeshes = this.subMeshes;
  18375. len = subMeshes.length;
  18376. }
  18377. for (var index = 0; index < len; index++) {
  18378. var subMesh = subMeshes[index];
  18379. // Bounding test
  18380. if (len > 1 && !subMesh.canIntersects(ray))
  18381. continue;
  18382. var currentIntersectInfo = subMesh.intersects(ray, this._positions, this.getIndices(), fastCheck);
  18383. if (currentIntersectInfo) {
  18384. if (fastCheck || !intersectInfo || currentIntersectInfo.distance < intersectInfo.distance) {
  18385. intersectInfo = currentIntersectInfo;
  18386. intersectInfo.subMeshId = index;
  18387. if (fastCheck) {
  18388. break;
  18389. }
  18390. }
  18391. }
  18392. }
  18393. if (intersectInfo) {
  18394. // Get picked point
  18395. var world = this.getWorldMatrix();
  18396. var worldOrigin = BABYLON.Vector3.TransformCoordinates(ray.origin, world);
  18397. var direction = ray.direction.clone();
  18398. direction = direction.scale(intersectInfo.distance);
  18399. var worldDirection = BABYLON.Vector3.TransformNormal(direction, world);
  18400. var pickedPoint = worldOrigin.add(worldDirection);
  18401. // Return result
  18402. pickingInfo.hit = true;
  18403. pickingInfo.distance = BABYLON.Vector3.Distance(worldOrigin, pickedPoint);
  18404. pickingInfo.pickedPoint = pickedPoint;
  18405. pickingInfo.pickedMesh = this;
  18406. pickingInfo.bu = intersectInfo.bu || 0;
  18407. pickingInfo.bv = intersectInfo.bv || 0;
  18408. pickingInfo.faceId = intersectInfo.faceId;
  18409. pickingInfo.subMeshId = intersectInfo.subMeshId;
  18410. return pickingInfo;
  18411. }
  18412. return pickingInfo;
  18413. };
  18414. /**
  18415. * Clones the mesh, used by the class Mesh.
  18416. * Just returns `null` for an AbstractMesh.
  18417. */
  18418. AbstractMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  18419. return null;
  18420. };
  18421. /**
  18422. * Disposes all the mesh submeshes.
  18423. * Returns the AbstractMesh.
  18424. */
  18425. AbstractMesh.prototype.releaseSubMeshes = function () {
  18426. if (this.subMeshes) {
  18427. while (this.subMeshes.length) {
  18428. this.subMeshes[0].dispose();
  18429. }
  18430. }
  18431. else {
  18432. this.subMeshes = new Array();
  18433. }
  18434. return this;
  18435. };
  18436. /**
  18437. * Releases resources associated with this abstract mesh.
  18438. * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default)
  18439. * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default)
  18440. */
  18441. AbstractMesh.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  18442. var _this = this;
  18443. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  18444. var index;
  18445. // Action manager
  18446. if (this.actionManager !== undefined && this.actionManager !== null) {
  18447. this.actionManager.dispose();
  18448. this.actionManager = null;
  18449. }
  18450. // Skeleton
  18451. this.skeleton = null;
  18452. // Physics
  18453. if (this.physicsImpostor) {
  18454. this.physicsImpostor.dispose();
  18455. }
  18456. // Intersections in progress
  18457. for (index = 0; index < this._intersectionsInProgress.length; index++) {
  18458. var other = this._intersectionsInProgress[index];
  18459. var pos = other._intersectionsInProgress.indexOf(this);
  18460. other._intersectionsInProgress.splice(pos, 1);
  18461. }
  18462. this._intersectionsInProgress = [];
  18463. // Lights
  18464. var lights = this.getScene().lights;
  18465. lights.forEach(function (light) {
  18466. var meshIndex = light.includedOnlyMeshes.indexOf(_this);
  18467. if (meshIndex !== -1) {
  18468. light.includedOnlyMeshes.splice(meshIndex, 1);
  18469. }
  18470. meshIndex = light.excludedMeshes.indexOf(_this);
  18471. if (meshIndex !== -1) {
  18472. light.excludedMeshes.splice(meshIndex, 1);
  18473. }
  18474. // Shadow generators
  18475. var generator = light.getShadowGenerator();
  18476. if (generator) {
  18477. var shadowMap = generator.getShadowMap();
  18478. if (shadowMap && shadowMap.renderList) {
  18479. meshIndex = shadowMap.renderList.indexOf(_this);
  18480. if (meshIndex !== -1) {
  18481. shadowMap.renderList.splice(meshIndex, 1);
  18482. }
  18483. }
  18484. }
  18485. });
  18486. // Edges
  18487. if (this._edgesRenderer) {
  18488. this._edgesRenderer.dispose();
  18489. this._edgesRenderer = null;
  18490. }
  18491. // SubMeshes
  18492. if (this.getClassName() !== "InstancedMesh") {
  18493. this.releaseSubMeshes();
  18494. }
  18495. // Octree
  18496. var sceneOctree = this.getScene().selectionOctree;
  18497. if (sceneOctree !== undefined && sceneOctree !== null) {
  18498. var index = sceneOctree.dynamicContent.indexOf(this);
  18499. if (index !== -1) {
  18500. sceneOctree.dynamicContent.splice(index, 1);
  18501. }
  18502. }
  18503. // Query
  18504. var engine = this.getScene().getEngine();
  18505. if (this._occlusionQuery) {
  18506. this._isOcclusionQueryInProgress = false;
  18507. engine.deleteQuery(this._occlusionQuery);
  18508. this._occlusionQuery = null;
  18509. }
  18510. // Engine
  18511. engine.wipeCaches();
  18512. // Remove from scene
  18513. this.getScene().removeMesh(this);
  18514. if (disposeMaterialAndTextures) {
  18515. if (this.material) {
  18516. this.material.dispose(false, true);
  18517. }
  18518. }
  18519. if (!doNotRecurse) {
  18520. // Particles
  18521. for (index = 0; index < this.getScene().particleSystems.length; index++) {
  18522. if (this.getScene().particleSystems[index].emitter === this) {
  18523. this.getScene().particleSystems[index].dispose();
  18524. index--;
  18525. }
  18526. }
  18527. }
  18528. // facet data
  18529. if (this._facetDataEnabled) {
  18530. this.disableFacetData();
  18531. }
  18532. this.onAfterWorldMatrixUpdateObservable.clear();
  18533. this.onCollideObservable.clear();
  18534. this.onCollisionPositionChangeObservable.clear();
  18535. _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
  18536. };
  18537. /**
  18538. * Adds the passed mesh as a child to the current mesh.
  18539. * Returns the AbstractMesh.
  18540. */
  18541. AbstractMesh.prototype.addChild = function (mesh) {
  18542. mesh.setParent(this);
  18543. return this;
  18544. };
  18545. /**
  18546. * Removes the passed mesh from the current mesh children list.
  18547. * Returns the AbstractMesh.
  18548. */
  18549. AbstractMesh.prototype.removeChild = function (mesh) {
  18550. mesh.setParent(null);
  18551. return this;
  18552. };
  18553. // Facet data
  18554. /**
  18555. * Initialize the facet data arrays : facetNormals, facetPositions and facetPartitioning.
  18556. * Returns the AbstractMesh.
  18557. */
  18558. AbstractMesh.prototype._initFacetData = function () {
  18559. if (!this._facetNormals) {
  18560. this._facetNormals = new Array();
  18561. }
  18562. if (!this._facetPositions) {
  18563. this._facetPositions = new Array();
  18564. }
  18565. if (!this._facetPartitioning) {
  18566. this._facetPartitioning = new Array();
  18567. }
  18568. this._facetNb = (this.getIndices().length / 3) | 0;
  18569. this._partitioningSubdivisions = (this._partitioningSubdivisions) ? this._partitioningSubdivisions : 10; // default nb of partitioning subdivisions = 10
  18570. this._partitioningBBoxRatio = (this._partitioningBBoxRatio) ? this._partitioningBBoxRatio : 1.01; // default ratio 1.01 = the partitioning is 1% bigger than the bounding box
  18571. for (var f = 0; f < this._facetNb; f++) {
  18572. this._facetNormals[f] = BABYLON.Vector3.Zero();
  18573. this._facetPositions[f] = BABYLON.Vector3.Zero();
  18574. }
  18575. this._facetDataEnabled = true;
  18576. return this;
  18577. };
  18578. /**
  18579. * Updates the mesh facetData arrays and the internal partitioning when the mesh is morphed or updated.
  18580. * This method can be called within the render loop.
  18581. * 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.
  18582. * Returns the AbstractMesh.
  18583. */
  18584. AbstractMesh.prototype.updateFacetData = function () {
  18585. if (!this._facetDataEnabled) {
  18586. this._initFacetData();
  18587. }
  18588. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  18589. var indices = this.getIndices();
  18590. var normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  18591. var bInfo = this.getBoundingInfo();
  18592. if (this._facetDepthSort && !this._facetDepthSortEnabled) {
  18593. // init arrays, matrix and sort function on first call
  18594. this._facetDepthSortEnabled = true;
  18595. if (indices instanceof Uint16Array) {
  18596. this._depthSortedIndices = new Uint16Array(indices);
  18597. }
  18598. else if (indices instanceof Uint32Array) {
  18599. this._depthSortedIndices = new Uint32Array(indices);
  18600. }
  18601. else {
  18602. var needs32bits = false;
  18603. for (var i = 0; i < indices.length; i++) {
  18604. if (indices[i] > 65535) {
  18605. needs32bits = true;
  18606. break;
  18607. }
  18608. }
  18609. if (needs32bits) {
  18610. this._depthSortedIndices = new Uint32Array(indices);
  18611. }
  18612. else {
  18613. this._depthSortedIndices = new Uint16Array(indices);
  18614. }
  18615. }
  18616. this._facetDepthSortFunction = function (f1, f2) {
  18617. return (f2.sqDistance - f1.sqDistance);
  18618. };
  18619. if (!this._facetDepthSortFrom) {
  18620. var camera = this.getScene().activeCamera;
  18621. this._facetDepthSortFrom = (camera) ? camera.position : BABYLON.Vector3.Zero();
  18622. }
  18623. this._depthSortedFacets = [];
  18624. for (var f = 0; f < this._facetNb; f++) {
  18625. var depthSortedFacet = { ind: f * 3, sqDistance: 0.0 };
  18626. this._depthSortedFacets.push(depthSortedFacet);
  18627. }
  18628. this._invertedMatrix = BABYLON.Matrix.Identity();
  18629. this._facetDepthSortOrigin = BABYLON.Vector3.Zero();
  18630. }
  18631. this._bbSize.x = (bInfo.maximum.x - bInfo.minimum.x > BABYLON.Epsilon) ? bInfo.maximum.x - bInfo.minimum.x : BABYLON.Epsilon;
  18632. this._bbSize.y = (bInfo.maximum.y - bInfo.minimum.y > BABYLON.Epsilon) ? bInfo.maximum.y - bInfo.minimum.y : BABYLON.Epsilon;
  18633. this._bbSize.z = (bInfo.maximum.z - bInfo.minimum.z > BABYLON.Epsilon) ? bInfo.maximum.z - bInfo.minimum.z : BABYLON.Epsilon;
  18634. var bbSizeMax = (this._bbSize.x > this._bbSize.y) ? this._bbSize.x : this._bbSize.y;
  18635. bbSizeMax = (bbSizeMax > this._bbSize.z) ? bbSizeMax : this._bbSize.z;
  18636. this._subDiv.max = this._partitioningSubdivisions;
  18637. this._subDiv.X = Math.floor(this._subDiv.max * this._bbSize.x / bbSizeMax); // adjust the number of subdivisions per axis
  18638. this._subDiv.Y = Math.floor(this._subDiv.max * this._bbSize.y / bbSizeMax); // according to each bbox size per axis
  18639. this._subDiv.Z = Math.floor(this._subDiv.max * this._bbSize.z / bbSizeMax);
  18640. this._subDiv.X = this._subDiv.X < 1 ? 1 : this._subDiv.X; // at least one subdivision
  18641. this._subDiv.Y = this._subDiv.Y < 1 ? 1 : this._subDiv.Y;
  18642. this._subDiv.Z = this._subDiv.Z < 1 ? 1 : this._subDiv.Z;
  18643. // set the parameters for ComputeNormals()
  18644. this._facetParameters.facetNormals = this.getFacetLocalNormals();
  18645. this._facetParameters.facetPositions = this.getFacetLocalPositions();
  18646. this._facetParameters.facetPartitioning = this.getFacetLocalPartitioning();
  18647. this._facetParameters.bInfo = bInfo;
  18648. this._facetParameters.bbSize = this._bbSize;
  18649. this._facetParameters.subDiv = this._subDiv;
  18650. this._facetParameters.ratio = this.partitioningBBoxRatio;
  18651. this._facetParameters.depthSort = this._facetDepthSort;
  18652. if (this._facetDepthSort && this._facetDepthSortEnabled) {
  18653. this.computeWorldMatrix(true);
  18654. this._worldMatrix.invertToRef(this._invertedMatrix);
  18655. BABYLON.Vector3.TransformCoordinatesToRef(this._facetDepthSortFrom, this._invertedMatrix, this._facetDepthSortOrigin);
  18656. this._facetParameters.distanceTo = this._facetDepthSortOrigin;
  18657. }
  18658. this._facetParameters.depthSortedFacets = this._depthSortedFacets;
  18659. BABYLON.VertexData.ComputeNormals(positions, indices, normals, this._facetParameters);
  18660. if (this._facetDepthSort && this._facetDepthSortEnabled) {
  18661. this._depthSortedFacets.sort(this._facetDepthSortFunction);
  18662. var l = (this._depthSortedIndices.length / 3) | 0;
  18663. for (var f = 0; f < l; f++) {
  18664. var sind = this._depthSortedFacets[f].ind;
  18665. this._depthSortedIndices[f * 3] = indices[sind];
  18666. this._depthSortedIndices[f * 3 + 1] = indices[sind + 1];
  18667. this._depthSortedIndices[f * 3 + 2] = indices[sind + 2];
  18668. }
  18669. this.updateIndices(this._depthSortedIndices);
  18670. }
  18671. return this;
  18672. };
  18673. /**
  18674. * Returns the facetLocalNormals array.
  18675. * The normals are expressed in the mesh local space.
  18676. */
  18677. AbstractMesh.prototype.getFacetLocalNormals = function () {
  18678. if (!this._facetNormals) {
  18679. this.updateFacetData();
  18680. }
  18681. return this._facetNormals;
  18682. };
  18683. /**
  18684. * Returns the facetLocalPositions array.
  18685. * The facet positions are expressed in the mesh local space.
  18686. */
  18687. AbstractMesh.prototype.getFacetLocalPositions = function () {
  18688. if (!this._facetPositions) {
  18689. this.updateFacetData();
  18690. }
  18691. return this._facetPositions;
  18692. };
  18693. /**
  18694. * Returns the facetLocalPartioning array.
  18695. */
  18696. AbstractMesh.prototype.getFacetLocalPartitioning = function () {
  18697. if (!this._facetPartitioning) {
  18698. this.updateFacetData();
  18699. }
  18700. return this._facetPartitioning;
  18701. };
  18702. /**
  18703. * Returns the i-th facet position in the world system.
  18704. * This method allocates a new Vector3 per call.
  18705. */
  18706. AbstractMesh.prototype.getFacetPosition = function (i) {
  18707. var pos = BABYLON.Vector3.Zero();
  18708. this.getFacetPositionToRef(i, pos);
  18709. return pos;
  18710. };
  18711. /**
  18712. * Sets the reference Vector3 with the i-th facet position in the world system.
  18713. * Returns the AbstractMesh.
  18714. */
  18715. AbstractMesh.prototype.getFacetPositionToRef = function (i, ref) {
  18716. var localPos = (this.getFacetLocalPositions())[i];
  18717. var world = this.getWorldMatrix();
  18718. BABYLON.Vector3.TransformCoordinatesToRef(localPos, world, ref);
  18719. return this;
  18720. };
  18721. /**
  18722. * Returns the i-th facet normal in the world system.
  18723. * This method allocates a new Vector3 per call.
  18724. */
  18725. AbstractMesh.prototype.getFacetNormal = function (i) {
  18726. var norm = BABYLON.Vector3.Zero();
  18727. this.getFacetNormalToRef(i, norm);
  18728. return norm;
  18729. };
  18730. /**
  18731. * Sets the reference Vector3 with the i-th facet normal in the world system.
  18732. * Returns the AbstractMesh.
  18733. */
  18734. AbstractMesh.prototype.getFacetNormalToRef = function (i, ref) {
  18735. var localNorm = (this.getFacetLocalNormals())[i];
  18736. BABYLON.Vector3.TransformNormalToRef(localNorm, this.getWorldMatrix(), ref);
  18737. return this;
  18738. };
  18739. /**
  18740. * 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).
  18741. */
  18742. AbstractMesh.prototype.getFacetsAtLocalCoordinates = function (x, y, z) {
  18743. var bInfo = this.getBoundingInfo();
  18744. var ox = Math.floor((x - bInfo.minimum.x * this._partitioningBBoxRatio) * this._subDiv.X * this._partitioningBBoxRatio / this._bbSize.x);
  18745. var oy = Math.floor((y - bInfo.minimum.y * this._partitioningBBoxRatio) * this._subDiv.Y * this._partitioningBBoxRatio / this._bbSize.y);
  18746. var oz = Math.floor((z - bInfo.minimum.z * this._partitioningBBoxRatio) * this._subDiv.Z * this._partitioningBBoxRatio / this._bbSize.z);
  18747. if (ox < 0 || ox > this._subDiv.max || oy < 0 || oy > this._subDiv.max || oz < 0 || oz > this._subDiv.max) {
  18748. return null;
  18749. }
  18750. return this._facetPartitioning[ox + this._subDiv.max * oy + this._subDiv.max * this._subDiv.max * oz];
  18751. };
  18752. /**
  18753. * Returns the closest mesh facet index at (x,y,z) World coordinates, null if not found.
  18754. * If the parameter projected (vector3) is passed, it is set as the (x,y,z) World projection on the facet.
  18755. * 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.
  18756. * If facing and checkFace are true, only the facet "facing" to (x, y, z) are returned : positive dot (x, y, z) * facet position.
  18757. * 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.
  18758. */
  18759. AbstractMesh.prototype.getClosestFacetAtCoordinates = function (x, y, z, projected, checkFace, facing) {
  18760. if (checkFace === void 0) { checkFace = false; }
  18761. if (facing === void 0) { facing = true; }
  18762. var world = this.getWorldMatrix();
  18763. var invMat = BABYLON.Tmp.Matrix[5];
  18764. world.invertToRef(invMat);
  18765. var invVect = BABYLON.Tmp.Vector3[8];
  18766. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, y, z, invMat, invVect); // transform (x,y,z) to coordinates in the mesh local space
  18767. var closest = this.getClosestFacetAtLocalCoordinates(invVect.x, invVect.y, invVect.z, projected, checkFace, facing);
  18768. if (projected) {
  18769. // tranform the local computed projected vector to world coordinates
  18770. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(projected.x, projected.y, projected.z, world, projected);
  18771. }
  18772. return closest;
  18773. };
  18774. /**
  18775. * Returns the closest mesh facet index at (x,y,z) local coordinates, null if not found.
  18776. * If the parameter projected (vector3) is passed, it is set as the (x,y,z) local projection on the facet.
  18777. * 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.
  18778. * If facing and checkFace are true, only the facet "facing" to (x, y, z) are returned : positive dot (x, y, z) * facet position.
  18779. * 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.
  18780. */
  18781. AbstractMesh.prototype.getClosestFacetAtLocalCoordinates = function (x, y, z, projected, checkFace, facing) {
  18782. if (checkFace === void 0) { checkFace = false; }
  18783. if (facing === void 0) { facing = true; }
  18784. var closest = null;
  18785. var tmpx = 0.0;
  18786. var tmpy = 0.0;
  18787. var tmpz = 0.0;
  18788. var d = 0.0; // tmp dot facet normal * facet position
  18789. var t0 = 0.0;
  18790. var projx = 0.0;
  18791. var projy = 0.0;
  18792. var projz = 0.0;
  18793. // Get all the facets in the same partitioning block than (x, y, z)
  18794. var facetPositions = this.getFacetLocalPositions();
  18795. var facetNormals = this.getFacetLocalNormals();
  18796. var facetsInBlock = this.getFacetsAtLocalCoordinates(x, y, z);
  18797. if (!facetsInBlock) {
  18798. return null;
  18799. }
  18800. // Get the closest facet to (x, y, z)
  18801. var shortest = Number.MAX_VALUE; // init distance vars
  18802. var tmpDistance = shortest;
  18803. var fib; // current facet in the block
  18804. var norm; // current facet normal
  18805. var p0; // current facet barycenter position
  18806. // loop on all the facets in the current partitioning block
  18807. for (var idx = 0; idx < facetsInBlock.length; idx++) {
  18808. fib = facetsInBlock[idx];
  18809. norm = facetNormals[fib];
  18810. p0 = facetPositions[fib];
  18811. d = (x - p0.x) * norm.x + (y - p0.y) * norm.y + (z - p0.z) * norm.z;
  18812. if (!checkFace || (checkFace && facing && d >= 0.0) || (checkFace && !facing && d <= 0.0)) {
  18813. // compute (x,y,z) projection on the facet = (projx, projy, projz)
  18814. d = norm.x * p0.x + norm.y * p0.y + norm.z * p0.z;
  18815. t0 = -(norm.x * x + norm.y * y + norm.z * z - d) / (norm.x * norm.x + norm.y * norm.y + norm.z * norm.z);
  18816. projx = x + norm.x * t0;
  18817. projy = y + norm.y * t0;
  18818. projz = z + norm.z * t0;
  18819. tmpx = projx - x;
  18820. tmpy = projy - y;
  18821. tmpz = projz - z;
  18822. tmpDistance = tmpx * tmpx + tmpy * tmpy + tmpz * tmpz; // compute length between (x, y, z) and its projection on the facet
  18823. if (tmpDistance < shortest) {
  18824. shortest = tmpDistance;
  18825. closest = fib;
  18826. if (projected) {
  18827. projected.x = projx;
  18828. projected.y = projy;
  18829. projected.z = projz;
  18830. }
  18831. }
  18832. }
  18833. }
  18834. return closest;
  18835. };
  18836. /**
  18837. * Returns the object "parameter" set with all the expected parameters for facetData computation by ComputeNormals()
  18838. */
  18839. AbstractMesh.prototype.getFacetDataParameters = function () {
  18840. return this._facetParameters;
  18841. };
  18842. /**
  18843. * Disables the feature FacetData and frees the related memory.
  18844. * Returns the AbstractMesh.
  18845. */
  18846. AbstractMesh.prototype.disableFacetData = function () {
  18847. if (this._facetDataEnabled) {
  18848. this._facetDataEnabled = false;
  18849. this._facetPositions = new Array();
  18850. this._facetNormals = new Array();
  18851. this._facetPartitioning = new Array();
  18852. this._facetParameters = null;
  18853. this._depthSortedIndices = new Uint32Array(0);
  18854. }
  18855. return this;
  18856. };
  18857. /**
  18858. * Updates the AbstractMesh indices array. Actually, used by the Mesh object.
  18859. * Returns the mesh.
  18860. */
  18861. AbstractMesh.prototype.updateIndices = function (indices) {
  18862. return this;
  18863. };
  18864. /**
  18865. * The mesh Geometry. Actually used by the Mesh object.
  18866. * Returns a blank geometry object.
  18867. */
  18868. /**
  18869. * Creates new normals data for the mesh.
  18870. * @param updatable.
  18871. */
  18872. AbstractMesh.prototype.createNormals = function (updatable) {
  18873. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  18874. var indices = this.getIndices();
  18875. var normals;
  18876. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  18877. normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  18878. }
  18879. else {
  18880. normals = [];
  18881. }
  18882. BABYLON.VertexData.ComputeNormals(positions, indices, normals, { useRightHandedSystem: this.getScene().useRightHandedSystem });
  18883. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals, updatable);
  18884. };
  18885. /**
  18886. * Align the mesh with a normal.
  18887. * Returns the mesh.
  18888. */
  18889. AbstractMesh.prototype.alignWithNormal = function (normal, upDirection) {
  18890. if (!upDirection) {
  18891. upDirection = BABYLON.Axis.Y;
  18892. }
  18893. var axisX = BABYLON.Tmp.Vector3[0];
  18894. var axisZ = BABYLON.Tmp.Vector3[1];
  18895. BABYLON.Vector3.CrossToRef(upDirection, normal, axisZ);
  18896. BABYLON.Vector3.CrossToRef(normal, axisZ, axisX);
  18897. if (this.rotationQuaternion) {
  18898. BABYLON.Quaternion.RotationQuaternionFromAxisToRef(axisX, normal, axisZ, this.rotationQuaternion);
  18899. }
  18900. else {
  18901. BABYLON.Vector3.RotationFromAxisToRef(axisX, normal, axisZ, this.rotation);
  18902. }
  18903. return this;
  18904. };
  18905. AbstractMesh.prototype.checkOcclusionQuery = function () {
  18906. var engine = this.getEngine();
  18907. if (engine.webGLVersion < 2 || this.occlusionType === AbstractMesh.OCCLUSION_TYPE_NONE) {
  18908. this._isOccluded = false;
  18909. return;
  18910. }
  18911. if (this.isOcclusionQueryInProgress && this._occlusionQuery) {
  18912. var isOcclusionQueryAvailable = engine.isQueryResultAvailable(this._occlusionQuery);
  18913. if (isOcclusionQueryAvailable) {
  18914. var occlusionQueryResult = engine.getQueryResult(this._occlusionQuery);
  18915. this._isOcclusionQueryInProgress = false;
  18916. this._occlusionInternalRetryCounter = 0;
  18917. this._isOccluded = occlusionQueryResult === 1 ? false : true;
  18918. }
  18919. else {
  18920. this._occlusionInternalRetryCounter++;
  18921. if (this.occlusionRetryCount !== -1 && this._occlusionInternalRetryCounter > this.occlusionRetryCount) {
  18922. this._isOcclusionQueryInProgress = false;
  18923. this._occlusionInternalRetryCounter = 0;
  18924. // if optimistic set isOccluded to false regardless of the status of isOccluded. (Render in the current render loop)
  18925. // if strict continue the last state of the object.
  18926. this._isOccluded = this.occlusionType === AbstractMesh.OCCLUSION_TYPE_OPTIMISTIC ? false : this._isOccluded;
  18927. }
  18928. else {
  18929. return;
  18930. }
  18931. }
  18932. }
  18933. var scene = this.getScene();
  18934. var occlusionBoundingBoxRenderer = scene.getBoundingBoxRenderer();
  18935. if (!this._occlusionQuery) {
  18936. this._occlusionQuery = engine.createQuery();
  18937. }
  18938. engine.beginOcclusionQuery(this.occlusionQueryAlgorithmType, this._occlusionQuery);
  18939. occlusionBoundingBoxRenderer.renderOcclusionBoundingBox(this);
  18940. engine.endOcclusionQuery(this.occlusionQueryAlgorithmType);
  18941. this._isOcclusionQueryInProgress = true;
  18942. };
  18943. AbstractMesh.OCCLUSION_TYPE_NONE = 0;
  18944. AbstractMesh.OCCLUSION_TYPE_OPTIMISTIC = 1;
  18945. AbstractMesh.OCCLUSION_TYPE_STRICT = 2;
  18946. AbstractMesh.OCCLUSION_ALGORITHM_TYPE_ACCURATE = 0;
  18947. AbstractMesh.OCCLUSION_ALGORITHM_TYPE_CONSERVATIVE = 1;
  18948. return AbstractMesh;
  18949. }(BABYLON.TransformNode));
  18950. BABYLON.AbstractMesh = AbstractMesh;
  18951. })(BABYLON || (BABYLON = {}));
  18952. //# sourceMappingURL=babylon.abstractMesh.js.map
  18953. var BABYLON;
  18954. (function (BABYLON) {
  18955. /**
  18956. * Base class of all the lights in Babylon. It groups all the generic information about lights.
  18957. * Lights are used, as you would expect, to affect how meshes are seen, in terms of both illumination and colour.
  18958. * 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.
  18959. */
  18960. var Light = /** @class */ (function (_super) {
  18961. __extends(Light, _super);
  18962. /**
  18963. * Creates a Light object in the scene.
  18964. * Documentation : http://doc.babylonjs.com/tutorials/lights
  18965. * @param name The firendly name of the light
  18966. * @param scene The scene the light belongs too
  18967. */
  18968. function Light(name, scene) {
  18969. var _this = _super.call(this, name, scene) || this;
  18970. /**
  18971. * Diffuse gives the basic color to an object.
  18972. */
  18973. _this.diffuse = new BABYLON.Color3(1.0, 1.0, 1.0);
  18974. /**
  18975. * Specular produces a highlight color on an object.
  18976. * Note: This is note affecting PBR materials.
  18977. */
  18978. _this.specular = new BABYLON.Color3(1.0, 1.0, 1.0);
  18979. /**
  18980. * Strength of the light.
  18981. * Note: By default it is define in the framework own unit.
  18982. * Note: In PBR materials the intensityMode can be use to chose what unit the intensity is defined in.
  18983. */
  18984. _this.intensity = 1.0;
  18985. /**
  18986. * Defines how far from the source the light is impacting in scene units.
  18987. * Note: Unused in PBR material as the distance light falloff is defined following the inverse squared falloff.
  18988. */
  18989. _this.range = Number.MAX_VALUE;
  18990. /**
  18991. * Cached photometric scale default to 1.0 as the automatic intensity mode defaults to 1.0 for every type
  18992. * of light.
  18993. */
  18994. _this._photometricScale = 1.0;
  18995. _this._intensityMode = Light.INTENSITYMODE_AUTOMATIC;
  18996. _this._radius = 0.00001;
  18997. /**
  18998. * Defines the rendering priority of the lights. It can help in case of fallback or number of lights
  18999. * exceeding the number allowed of the materials.
  19000. */
  19001. _this.renderPriority = 0;
  19002. /**
  19003. * Defines wether or not the shadows are enabled for this light. This can help turning off/on shadow without detaching
  19004. * the current shadow generator.
  19005. */
  19006. _this.shadowEnabled = true;
  19007. _this._excludeWithLayerMask = 0;
  19008. _this._includeOnlyWithLayerMask = 0;
  19009. _this._lightmapMode = 0;
  19010. /**
  19011. * @ignore Internal use only.
  19012. */
  19013. _this._excludedMeshesIds = new Array();
  19014. /**
  19015. * @ignore Internal use only.
  19016. */
  19017. _this._includedOnlyMeshesIds = new Array();
  19018. _this.getScene().addLight(_this);
  19019. _this._uniformBuffer = new BABYLON.UniformBuffer(_this.getScene().getEngine());
  19020. _this._buildUniformLayout();
  19021. _this.includedOnlyMeshes = new Array();
  19022. _this.excludedMeshes = new Array();
  19023. _this._resyncMeshes();
  19024. return _this;
  19025. }
  19026. Object.defineProperty(Light, "LIGHTMAP_DEFAULT", {
  19027. /**
  19028. * If every light affecting the material is in this lightmapMode,
  19029. * material.lightmapTexture adds or multiplies
  19030. * (depends on material.useLightmapAsShadowmap)
  19031. * after every other light calculations.
  19032. */
  19033. get: function () {
  19034. return Light._LIGHTMAP_DEFAULT;
  19035. },
  19036. enumerable: true,
  19037. configurable: true
  19038. });
  19039. Object.defineProperty(Light, "LIGHTMAP_SPECULAR", {
  19040. /**
  19041. * material.lightmapTexture as only diffuse lighting from this light
  19042. * adds only specular lighting from this light
  19043. * adds dynamic shadows
  19044. */
  19045. get: function () {
  19046. return Light._LIGHTMAP_SPECULAR;
  19047. },
  19048. enumerable: true,
  19049. configurable: true
  19050. });
  19051. Object.defineProperty(Light, "LIGHTMAP_SHADOWSONLY", {
  19052. /**
  19053. * material.lightmapTexture as only lighting
  19054. * no light calculation from this light
  19055. * only adds dynamic shadows from this light
  19056. */
  19057. get: function () {
  19058. return Light._LIGHTMAP_SHADOWSONLY;
  19059. },
  19060. enumerable: true,
  19061. configurable: true
  19062. });
  19063. Object.defineProperty(Light, "INTENSITYMODE_AUTOMATIC", {
  19064. /**
  19065. * Each light type uses the default quantity according to its type:
  19066. * point/spot lights use luminous intensity
  19067. * directional lights use illuminance
  19068. */
  19069. get: function () {
  19070. return Light._INTENSITYMODE_AUTOMATIC;
  19071. },
  19072. enumerable: true,
  19073. configurable: true
  19074. });
  19075. Object.defineProperty(Light, "INTENSITYMODE_LUMINOUSPOWER", {
  19076. /**
  19077. * lumen (lm)
  19078. */
  19079. get: function () {
  19080. return Light._INTENSITYMODE_LUMINOUSPOWER;
  19081. },
  19082. enumerable: true,
  19083. configurable: true
  19084. });
  19085. Object.defineProperty(Light, "INTENSITYMODE_LUMINOUSINTENSITY", {
  19086. /**
  19087. * candela (lm/sr)
  19088. */
  19089. get: function () {
  19090. return Light._INTENSITYMODE_LUMINOUSINTENSITY;
  19091. },
  19092. enumerable: true,
  19093. configurable: true
  19094. });
  19095. Object.defineProperty(Light, "INTENSITYMODE_ILLUMINANCE", {
  19096. /**
  19097. * lux (lm/m^2)
  19098. */
  19099. get: function () {
  19100. return Light._INTENSITYMODE_ILLUMINANCE;
  19101. },
  19102. enumerable: true,
  19103. configurable: true
  19104. });
  19105. Object.defineProperty(Light, "INTENSITYMODE_LUMINANCE", {
  19106. /**
  19107. * nit (cd/m^2)
  19108. */
  19109. get: function () {
  19110. return Light._INTENSITYMODE_LUMINANCE;
  19111. },
  19112. enumerable: true,
  19113. configurable: true
  19114. });
  19115. Object.defineProperty(Light, "LIGHTTYPEID_POINTLIGHT", {
  19116. /**
  19117. * Light type const id of the point light.
  19118. */
  19119. get: function () {
  19120. return Light._LIGHTTYPEID_POINTLIGHT;
  19121. },
  19122. enumerable: true,
  19123. configurable: true
  19124. });
  19125. Object.defineProperty(Light, "LIGHTTYPEID_DIRECTIONALLIGHT", {
  19126. /**
  19127. * Light type const id of the directional light.
  19128. */
  19129. get: function () {
  19130. return Light._LIGHTTYPEID_DIRECTIONALLIGHT;
  19131. },
  19132. enumerable: true,
  19133. configurable: true
  19134. });
  19135. Object.defineProperty(Light, "LIGHTTYPEID_SPOTLIGHT", {
  19136. /**
  19137. * Light type const id of the spot light.
  19138. */
  19139. get: function () {
  19140. return Light._LIGHTTYPEID_SPOTLIGHT;
  19141. },
  19142. enumerable: true,
  19143. configurable: true
  19144. });
  19145. Object.defineProperty(Light, "LIGHTTYPEID_HEMISPHERICLIGHT", {
  19146. /**
  19147. * Light type const id of the hemispheric light.
  19148. */
  19149. get: function () {
  19150. return Light._LIGHTTYPEID_HEMISPHERICLIGHT;
  19151. },
  19152. enumerable: true,
  19153. configurable: true
  19154. });
  19155. Object.defineProperty(Light.prototype, "intensityMode", {
  19156. /**
  19157. * Gets the photometric scale used to interpret the intensity.
  19158. * This is only relevant with PBR Materials where the light intensity can be defined in a physical way.
  19159. */
  19160. get: function () {
  19161. return this._intensityMode;
  19162. },
  19163. /**
  19164. * Sets the photometric scale used to interpret the intensity.
  19165. * This is only relevant with PBR Materials where the light intensity can be defined in a physical way.
  19166. */
  19167. set: function (value) {
  19168. this._intensityMode = value;
  19169. this._computePhotometricScale();
  19170. },
  19171. enumerable: true,
  19172. configurable: true
  19173. });
  19174. ;
  19175. ;
  19176. Object.defineProperty(Light.prototype, "radius", {
  19177. /**
  19178. * Gets the light radius used by PBR Materials to simulate soft area lights.
  19179. */
  19180. get: function () {
  19181. return this._radius;
  19182. },
  19183. /**
  19184. * sets the light radius used by PBR Materials to simulate soft area lights.
  19185. */
  19186. set: function (value) {
  19187. this._radius = value;
  19188. this._computePhotometricScale();
  19189. },
  19190. enumerable: true,
  19191. configurable: true
  19192. });
  19193. ;
  19194. ;
  19195. Object.defineProperty(Light.prototype, "includedOnlyMeshes", {
  19196. /**
  19197. * Gets the only meshes impacted by this light.
  19198. */
  19199. get: function () {
  19200. return this._includedOnlyMeshes;
  19201. },
  19202. /**
  19203. * Sets the only meshes impacted by this light.
  19204. */
  19205. set: function (value) {
  19206. this._includedOnlyMeshes = value;
  19207. this._hookArrayForIncludedOnly(value);
  19208. },
  19209. enumerable: true,
  19210. configurable: true
  19211. });
  19212. Object.defineProperty(Light.prototype, "excludedMeshes", {
  19213. /**
  19214. * Gets the meshes not impacted by this light.
  19215. */
  19216. get: function () {
  19217. return this._excludedMeshes;
  19218. },
  19219. /**
  19220. * Sets the meshes not impacted by this light.
  19221. */
  19222. set: function (value) {
  19223. this._excludedMeshes = value;
  19224. this._hookArrayForExcluded(value);
  19225. },
  19226. enumerable: true,
  19227. configurable: true
  19228. });
  19229. Object.defineProperty(Light.prototype, "excludeWithLayerMask", {
  19230. /**
  19231. * Gets the layer id use to find what meshes are not impacted by the light.
  19232. * Inactive if 0
  19233. */
  19234. get: function () {
  19235. return this._excludeWithLayerMask;
  19236. },
  19237. /**
  19238. * Sets the layer id use to find what meshes are not impacted by the light.
  19239. * Inactive if 0
  19240. */
  19241. set: function (value) {
  19242. this._excludeWithLayerMask = value;
  19243. this._resyncMeshes();
  19244. },
  19245. enumerable: true,
  19246. configurable: true
  19247. });
  19248. Object.defineProperty(Light.prototype, "includeOnlyWithLayerMask", {
  19249. /**
  19250. * Gets the layer id use to find what meshes are impacted by the light.
  19251. * Inactive if 0
  19252. */
  19253. get: function () {
  19254. return this._includeOnlyWithLayerMask;
  19255. },
  19256. /**
  19257. * Sets the layer id use to find what meshes are impacted by the light.
  19258. * Inactive if 0
  19259. */
  19260. set: function (value) {
  19261. this._includeOnlyWithLayerMask = value;
  19262. this._resyncMeshes();
  19263. },
  19264. enumerable: true,
  19265. configurable: true
  19266. });
  19267. Object.defineProperty(Light.prototype, "lightmapMode", {
  19268. /**
  19269. * Gets the lightmap mode of this light (should be one of the constants defined by Light.LIGHTMAP_x)
  19270. */
  19271. get: function () {
  19272. return this._lightmapMode;
  19273. },
  19274. /**
  19275. * Sets the lightmap mode of this light (should be one of the constants defined by Light.LIGHTMAP_x)
  19276. */
  19277. set: function (value) {
  19278. if (this._lightmapMode === value) {
  19279. return;
  19280. }
  19281. this._lightmapMode = value;
  19282. this._markMeshesAsLightDirty();
  19283. },
  19284. enumerable: true,
  19285. configurable: true
  19286. });
  19287. /**
  19288. * Returns the string "Light".
  19289. * @returns the class name
  19290. */
  19291. Light.prototype.getClassName = function () {
  19292. return "Light";
  19293. };
  19294. /**
  19295. * Converts the light information to a readable string for debug purpose.
  19296. * @param fullDetails Supports for multiple levels of logging within scene loading
  19297. * @returns the human readable light info
  19298. */
  19299. Light.prototype.toString = function (fullDetails) {
  19300. var ret = "Name: " + this.name;
  19301. ret += ", type: " + (["Point", "Directional", "Spot", "Hemispheric"])[this.getTypeID()];
  19302. if (this.animations) {
  19303. for (var i = 0; i < this.animations.length; i++) {
  19304. ret += ", animation[0]: " + this.animations[i].toString(fullDetails);
  19305. }
  19306. }
  19307. if (fullDetails) {
  19308. }
  19309. return ret;
  19310. };
  19311. /**
  19312. * Set the enabled state of this node.
  19313. * @param value - the new enabled state
  19314. * @see isEnabled
  19315. */
  19316. Light.prototype.setEnabled = function (value) {
  19317. _super.prototype.setEnabled.call(this, value);
  19318. this._resyncMeshes();
  19319. };
  19320. /**
  19321. * Returns the Light associated shadow generator if any.
  19322. * @return the associated shadow generator.
  19323. */
  19324. Light.prototype.getShadowGenerator = function () {
  19325. return this._shadowGenerator;
  19326. };
  19327. /**
  19328. * Returns a Vector3, the absolute light position in the World.
  19329. * @returns the world space position of the light
  19330. */
  19331. Light.prototype.getAbsolutePosition = function () {
  19332. return BABYLON.Vector3.Zero();
  19333. };
  19334. /**
  19335. * Specifies if the light will affect the passed mesh.
  19336. * @param mesh The mesh to test against the light
  19337. * @return true the mesh is affected otherwise, false.
  19338. */
  19339. Light.prototype.canAffectMesh = function (mesh) {
  19340. if (!mesh) {
  19341. return true;
  19342. }
  19343. if (this.includedOnlyMeshes && this.includedOnlyMeshes.length > 0 && this.includedOnlyMeshes.indexOf(mesh) === -1) {
  19344. return false;
  19345. }
  19346. if (this.excludedMeshes && this.excludedMeshes.length > 0 && this.excludedMeshes.indexOf(mesh) !== -1) {
  19347. return false;
  19348. }
  19349. if (this.includeOnlyWithLayerMask !== 0 && (this.includeOnlyWithLayerMask & mesh.layerMask) === 0) {
  19350. return false;
  19351. }
  19352. if (this.excludeWithLayerMask !== 0 && this.excludeWithLayerMask & mesh.layerMask) {
  19353. return false;
  19354. }
  19355. return true;
  19356. };
  19357. /**
  19358. * Computes and Returns the light World matrix.
  19359. * @returns the world matrix
  19360. */
  19361. Light.prototype.getWorldMatrix = function () {
  19362. this._currentRenderId = this.getScene().getRenderId();
  19363. var worldMatrix = this._getWorldMatrix();
  19364. if (this.parent && this.parent.getWorldMatrix) {
  19365. if (!this._parentedWorldMatrix) {
  19366. this._parentedWorldMatrix = BABYLON.Matrix.Identity();
  19367. }
  19368. worldMatrix.multiplyToRef(this.parent.getWorldMatrix(), this._parentedWorldMatrix);
  19369. this._markSyncedWithParent();
  19370. return this._parentedWorldMatrix;
  19371. }
  19372. return worldMatrix;
  19373. };
  19374. /**
  19375. * Sort function to order lights for rendering.
  19376. * @param a First Light object to compare to second.
  19377. * @param b Second Light object to compare first.
  19378. * @return -1 to reduce's a's index relative to be, 0 for no change, 1 to increase a's index relative to b.
  19379. */
  19380. Light.CompareLightsPriority = function (a, b) {
  19381. //shadow-casting lights have priority over non-shadow-casting lights
  19382. //the renderPrioirty is a secondary sort criterion
  19383. if (a.shadowEnabled !== b.shadowEnabled) {
  19384. return (b.shadowEnabled ? 1 : 0) - (a.shadowEnabled ? 1 : 0);
  19385. }
  19386. return b.renderPriority - a.renderPriority;
  19387. };
  19388. /**
  19389. * Releases resources associated with this node.
  19390. * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default)
  19391. * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default)
  19392. */
  19393. Light.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  19394. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  19395. if (this._shadowGenerator) {
  19396. this._shadowGenerator.dispose();
  19397. this._shadowGenerator = null;
  19398. }
  19399. // Animations
  19400. this.getScene().stopAnimation(this);
  19401. // Remove from meshes
  19402. for (var _i = 0, _a = this.getScene().meshes; _i < _a.length; _i++) {
  19403. var mesh = _a[_i];
  19404. mesh._removeLightSource(this);
  19405. }
  19406. this._uniformBuffer.dispose();
  19407. // Remove from scene
  19408. this.getScene().removeLight(this);
  19409. _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
  19410. };
  19411. /**
  19412. * Returns the light type ID (integer).
  19413. * @returns The light Type id as a constant defines in Light.LIGHTTYPEID_x
  19414. */
  19415. Light.prototype.getTypeID = function () {
  19416. return 0;
  19417. };
  19418. /**
  19419. * Returns the intensity scaled by the Photometric Scale according to the light type and intensity mode.
  19420. * @returns the scaled intensity in intensity mode unit
  19421. */
  19422. Light.prototype.getScaledIntensity = function () {
  19423. return this._photometricScale * this.intensity;
  19424. };
  19425. /**
  19426. * Returns a new Light object, named "name", from the current one.
  19427. * @param name The name of the cloned light
  19428. * @returns the new created light
  19429. */
  19430. Light.prototype.clone = function (name) {
  19431. var constructor = Light.GetConstructorFromName(this.getTypeID(), name, this.getScene());
  19432. if (!constructor) {
  19433. return null;
  19434. }
  19435. return BABYLON.SerializationHelper.Clone(constructor, this);
  19436. };
  19437. /**
  19438. * Serializes the current light into a Serialization object.
  19439. * @returns the serialized object.
  19440. */
  19441. Light.prototype.serialize = function () {
  19442. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  19443. // Type
  19444. serializationObject.type = this.getTypeID();
  19445. // Parent
  19446. if (this.parent) {
  19447. serializationObject.parentId = this.parent.id;
  19448. }
  19449. // Inclusion / exclusions
  19450. if (this.excludedMeshes.length > 0) {
  19451. serializationObject.excludedMeshesIds = [];
  19452. this.excludedMeshes.forEach(function (mesh) {
  19453. serializationObject.excludedMeshesIds.push(mesh.id);
  19454. });
  19455. }
  19456. if (this.includedOnlyMeshes.length > 0) {
  19457. serializationObject.includedOnlyMeshesIds = [];
  19458. this.includedOnlyMeshes.forEach(function (mesh) {
  19459. serializationObject.includedOnlyMeshesIds.push(mesh.id);
  19460. });
  19461. }
  19462. // Animations
  19463. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  19464. serializationObject.ranges = this.serializeAnimationRanges();
  19465. return serializationObject;
  19466. };
  19467. /**
  19468. * Creates a new typed light from the passed type (integer) : point light = 0, directional light = 1, spot light = 2, hemispheric light = 3.
  19469. * This new light is named "name" and added to the passed scene.
  19470. * @param type Type according to the types available in Light.LIGHTTYPEID_x
  19471. * @param name The friendly name of the light
  19472. * @param scene The scene the new light will belong to
  19473. * @returns the constructor function
  19474. */
  19475. Light.GetConstructorFromName = function (type, name, scene) {
  19476. switch (type) {
  19477. case 0:
  19478. return function () { return new BABYLON.PointLight(name, BABYLON.Vector3.Zero(), scene); };
  19479. case 1:
  19480. return function () { return new BABYLON.DirectionalLight(name, BABYLON.Vector3.Zero(), scene); };
  19481. case 2:
  19482. return function () { return new BABYLON.SpotLight(name, BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), 0, 0, scene); };
  19483. case 3:
  19484. return function () { return new BABYLON.HemisphericLight(name, BABYLON.Vector3.Zero(), scene); };
  19485. }
  19486. return null;
  19487. };
  19488. /**
  19489. * Parses the passed "parsedLight" and returns a new instanced Light from this parsing.
  19490. * @param parsedLight The JSON representation of the light
  19491. * @param scene The scene to create the parsed light in
  19492. * @returns the created light after parsing
  19493. */
  19494. Light.Parse = function (parsedLight, scene) {
  19495. var constructor = Light.GetConstructorFromName(parsedLight.type, parsedLight.name, scene);
  19496. if (!constructor) {
  19497. return null;
  19498. }
  19499. var light = BABYLON.SerializationHelper.Parse(constructor, parsedLight, scene);
  19500. // Inclusion / exclusions
  19501. if (parsedLight.excludedMeshesIds) {
  19502. light._excludedMeshesIds = parsedLight.excludedMeshesIds;
  19503. }
  19504. if (parsedLight.includedOnlyMeshesIds) {
  19505. light._includedOnlyMeshesIds = parsedLight.includedOnlyMeshesIds;
  19506. }
  19507. // Parent
  19508. if (parsedLight.parentId) {
  19509. light._waitingParentId = parsedLight.parentId;
  19510. }
  19511. // Animations
  19512. if (parsedLight.animations) {
  19513. for (var animationIndex = 0; animationIndex < parsedLight.animations.length; animationIndex++) {
  19514. var parsedAnimation = parsedLight.animations[animationIndex];
  19515. light.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  19516. }
  19517. BABYLON.Node.ParseAnimationRanges(light, parsedLight, scene);
  19518. }
  19519. if (parsedLight.autoAnimate) {
  19520. scene.beginAnimation(light, parsedLight.autoAnimateFrom, parsedLight.autoAnimateTo, parsedLight.autoAnimateLoop, parsedLight.autoAnimateSpeed || 1.0);
  19521. }
  19522. return light;
  19523. };
  19524. Light.prototype._hookArrayForExcluded = function (array) {
  19525. var _this = this;
  19526. var oldPush = array.push;
  19527. array.push = function () {
  19528. var items = [];
  19529. for (var _i = 0; _i < arguments.length; _i++) {
  19530. items[_i] = arguments[_i];
  19531. }
  19532. var result = oldPush.apply(array, items);
  19533. for (var _a = 0, items_1 = items; _a < items_1.length; _a++) {
  19534. var item = items_1[_a];
  19535. item._resyncLighSource(_this);
  19536. }
  19537. return result;
  19538. };
  19539. var oldSplice = array.splice;
  19540. array.splice = function (index, deleteCount) {
  19541. var deleted = oldSplice.apply(array, [index, deleteCount]);
  19542. for (var _i = 0, deleted_1 = deleted; _i < deleted_1.length; _i++) {
  19543. var item = deleted_1[_i];
  19544. item._resyncLighSource(_this);
  19545. }
  19546. return deleted;
  19547. };
  19548. for (var _i = 0, array_1 = array; _i < array_1.length; _i++) {
  19549. var item = array_1[_i];
  19550. item._resyncLighSource(this);
  19551. }
  19552. };
  19553. Light.prototype._hookArrayForIncludedOnly = function (array) {
  19554. var _this = this;
  19555. var oldPush = array.push;
  19556. array.push = function () {
  19557. var items = [];
  19558. for (var _i = 0; _i < arguments.length; _i++) {
  19559. items[_i] = arguments[_i];
  19560. }
  19561. var result = oldPush.apply(array, items);
  19562. _this._resyncMeshes();
  19563. return result;
  19564. };
  19565. var oldSplice = array.splice;
  19566. array.splice = function (index, deleteCount) {
  19567. var deleted = oldSplice.apply(array, [index, deleteCount]);
  19568. _this._resyncMeshes();
  19569. return deleted;
  19570. };
  19571. this._resyncMeshes();
  19572. };
  19573. Light.prototype._resyncMeshes = function () {
  19574. for (var _i = 0, _a = this.getScene().meshes; _i < _a.length; _i++) {
  19575. var mesh = _a[_i];
  19576. mesh._resyncLighSource(this);
  19577. }
  19578. };
  19579. /**
  19580. * Forces the meshes to update their light related information in their rendering used effects
  19581. * @ignore Internal Use Only
  19582. */
  19583. Light.prototype._markMeshesAsLightDirty = function () {
  19584. for (var _i = 0, _a = this.getScene().meshes; _i < _a.length; _i++) {
  19585. var mesh = _a[_i];
  19586. if (mesh._lightSources.indexOf(this) !== -1) {
  19587. mesh._markSubMeshesAsLightDirty();
  19588. }
  19589. }
  19590. };
  19591. /**
  19592. * Recomputes the cached photometric scale if needed.
  19593. */
  19594. Light.prototype._computePhotometricScale = function () {
  19595. this._photometricScale = this._getPhotometricScale();
  19596. this.getScene().resetCachedMaterial();
  19597. };
  19598. /**
  19599. * Returns the Photometric Scale according to the light type and intensity mode.
  19600. */
  19601. Light.prototype._getPhotometricScale = function () {
  19602. var photometricScale = 0.0;
  19603. var lightTypeID = this.getTypeID();
  19604. //get photometric mode
  19605. var photometricMode = this.intensityMode;
  19606. if (photometricMode === Light.INTENSITYMODE_AUTOMATIC) {
  19607. if (lightTypeID === Light.LIGHTTYPEID_DIRECTIONALLIGHT) {
  19608. photometricMode = Light.INTENSITYMODE_ILLUMINANCE;
  19609. }
  19610. else {
  19611. photometricMode = Light.INTENSITYMODE_LUMINOUSINTENSITY;
  19612. }
  19613. }
  19614. //compute photometric scale
  19615. switch (lightTypeID) {
  19616. case Light.LIGHTTYPEID_POINTLIGHT:
  19617. case Light.LIGHTTYPEID_SPOTLIGHT:
  19618. switch (photometricMode) {
  19619. case Light.INTENSITYMODE_LUMINOUSPOWER:
  19620. photometricScale = 1.0 / (4.0 * Math.PI);
  19621. break;
  19622. case Light.INTENSITYMODE_LUMINOUSINTENSITY:
  19623. photometricScale = 1.0;
  19624. break;
  19625. case Light.INTENSITYMODE_LUMINANCE:
  19626. photometricScale = this.radius * this.radius;
  19627. break;
  19628. }
  19629. break;
  19630. case Light.LIGHTTYPEID_DIRECTIONALLIGHT:
  19631. switch (photometricMode) {
  19632. case Light.INTENSITYMODE_ILLUMINANCE:
  19633. photometricScale = 1.0;
  19634. break;
  19635. case Light.INTENSITYMODE_LUMINANCE:
  19636. // When radius (and therefore solid angle) is non-zero a directional lights brightness can be specified via central (peak) luminance.
  19637. // For a directional light the 'radius' defines the angular radius (in radians) rather than world-space radius (e.g. in metres).
  19638. var apexAngleRadians = this.radius;
  19639. // Impose a minimum light angular size to avoid the light becoming an infinitely small angular light source (i.e. a dirac delta function).
  19640. apexAngleRadians = Math.max(apexAngleRadians, 0.001);
  19641. var solidAngle = 2.0 * Math.PI * (1.0 - Math.cos(apexAngleRadians));
  19642. photometricScale = solidAngle;
  19643. break;
  19644. }
  19645. break;
  19646. case Light.LIGHTTYPEID_HEMISPHERICLIGHT:
  19647. // No fall off in hemisperic light.
  19648. photometricScale = 1.0;
  19649. break;
  19650. }
  19651. return photometricScale;
  19652. };
  19653. /**
  19654. * Reorder the light in the scene according to their defined priority.
  19655. * @ignore Internal Use Only
  19656. */
  19657. Light.prototype._reorderLightsInScene = function () {
  19658. var scene = this.getScene();
  19659. if (this._renderPriority != 0) {
  19660. scene.requireLightSorting = true;
  19661. }
  19662. this.getScene().sortLightsByPriority();
  19663. };
  19664. //lightmapMode Consts
  19665. Light._LIGHTMAP_DEFAULT = 0;
  19666. Light._LIGHTMAP_SPECULAR = 1;
  19667. Light._LIGHTMAP_SHADOWSONLY = 2;
  19668. // Intensity Mode Consts
  19669. Light._INTENSITYMODE_AUTOMATIC = 0;
  19670. Light._INTENSITYMODE_LUMINOUSPOWER = 1;
  19671. Light._INTENSITYMODE_LUMINOUSINTENSITY = 2;
  19672. Light._INTENSITYMODE_ILLUMINANCE = 3;
  19673. Light._INTENSITYMODE_LUMINANCE = 4;
  19674. // Light types ids const.
  19675. Light._LIGHTTYPEID_POINTLIGHT = 0;
  19676. Light._LIGHTTYPEID_DIRECTIONALLIGHT = 1;
  19677. Light._LIGHTTYPEID_SPOTLIGHT = 2;
  19678. Light._LIGHTTYPEID_HEMISPHERICLIGHT = 3;
  19679. __decorate([
  19680. BABYLON.serializeAsColor3()
  19681. ], Light.prototype, "diffuse", void 0);
  19682. __decorate([
  19683. BABYLON.serializeAsColor3()
  19684. ], Light.prototype, "specular", void 0);
  19685. __decorate([
  19686. BABYLON.serialize()
  19687. ], Light.prototype, "intensity", void 0);
  19688. __decorate([
  19689. BABYLON.serialize()
  19690. ], Light.prototype, "range", void 0);
  19691. __decorate([
  19692. BABYLON.serialize()
  19693. ], Light.prototype, "intensityMode", null);
  19694. __decorate([
  19695. BABYLON.serialize()
  19696. ], Light.prototype, "radius", null);
  19697. __decorate([
  19698. BABYLON.serialize()
  19699. ], Light.prototype, "_renderPriority", void 0);
  19700. __decorate([
  19701. BABYLON.expandToProperty("_reorderLightsInScene")
  19702. ], Light.prototype, "renderPriority", void 0);
  19703. __decorate([
  19704. BABYLON.serialize()
  19705. ], Light.prototype, "shadowEnabled", void 0);
  19706. __decorate([
  19707. BABYLON.serialize("excludeWithLayerMask")
  19708. ], Light.prototype, "_excludeWithLayerMask", void 0);
  19709. __decorate([
  19710. BABYLON.serialize("includeOnlyWithLayerMask")
  19711. ], Light.prototype, "_includeOnlyWithLayerMask", void 0);
  19712. __decorate([
  19713. BABYLON.serialize("lightmapMode")
  19714. ], Light.prototype, "_lightmapMode", void 0);
  19715. return Light;
  19716. }(BABYLON.Node));
  19717. BABYLON.Light = Light;
  19718. })(BABYLON || (BABYLON = {}));
  19719. //# sourceMappingURL=babylon.light.js.map
  19720. var BABYLON;
  19721. (function (BABYLON) {
  19722. var Camera = /** @class */ (function (_super) {
  19723. __extends(Camera, _super);
  19724. function Camera(name, position, scene) {
  19725. var _this = _super.call(this, name, scene) || this;
  19726. /**
  19727. * The vector the camera should consider as up.
  19728. * (default is Vector3(0, 1, 0) aka Vector3.Up())
  19729. */
  19730. _this.upVector = BABYLON.Vector3.Up();
  19731. _this.orthoLeft = null;
  19732. _this.orthoRight = null;
  19733. _this.orthoBottom = null;
  19734. _this.orthoTop = null;
  19735. /**
  19736. * FOV is set in Radians. (default is 0.8)
  19737. */
  19738. _this.fov = 0.8;
  19739. _this.minZ = 1;
  19740. _this.maxZ = 10000.0;
  19741. _this.inertia = 0.9;
  19742. _this.mode = Camera.PERSPECTIVE_CAMERA;
  19743. _this.isIntermediate = false;
  19744. _this.viewport = new BABYLON.Viewport(0, 0, 1.0, 1.0);
  19745. /**
  19746. * Restricts the camera to viewing objects with the same layerMask.
  19747. * A camera with a layerMask of 1 will render mesh.layerMask & camera.layerMask!== 0
  19748. */
  19749. _this.layerMask = 0x0FFFFFFF;
  19750. /**
  19751. * fovMode sets the camera frustum bounds to the viewport bounds. (default is FOVMODE_VERTICAL_FIXED)
  19752. */
  19753. _this.fovMode = Camera.FOVMODE_VERTICAL_FIXED;
  19754. // Camera rig members
  19755. _this.cameraRigMode = Camera.RIG_MODE_NONE;
  19756. _this._rigCameras = new Array();
  19757. _this._webvrViewMatrix = BABYLON.Matrix.Identity();
  19758. _this._skipRendering = false;
  19759. _this.customRenderTargets = new Array();
  19760. // Observables
  19761. _this.onViewMatrixChangedObservable = new BABYLON.Observable();
  19762. _this.onProjectionMatrixChangedObservable = new BABYLON.Observable();
  19763. _this.onAfterCheckInputsObservable = new BABYLON.Observable();
  19764. _this.onRestoreStateObservable = new BABYLON.Observable();
  19765. // Cache
  19766. _this._computedViewMatrix = BABYLON.Matrix.Identity();
  19767. _this._projectionMatrix = new BABYLON.Matrix();
  19768. _this._doNotComputeProjectionMatrix = false;
  19769. _this._postProcesses = new Array();
  19770. _this._transformMatrix = BABYLON.Matrix.Zero();
  19771. _this._activeMeshes = new BABYLON.SmartArray(256);
  19772. _this._globalPosition = BABYLON.Vector3.Zero();
  19773. _this._refreshFrustumPlanes = true;
  19774. _this.getScene().addCamera(_this);
  19775. if (!_this.getScene().activeCamera) {
  19776. _this.getScene().activeCamera = _this;
  19777. }
  19778. _this.position = position;
  19779. return _this;
  19780. }
  19781. Object.defineProperty(Camera, "PERSPECTIVE_CAMERA", {
  19782. get: function () {
  19783. return Camera._PERSPECTIVE_CAMERA;
  19784. },
  19785. enumerable: true,
  19786. configurable: true
  19787. });
  19788. Object.defineProperty(Camera, "ORTHOGRAPHIC_CAMERA", {
  19789. get: function () {
  19790. return Camera._ORTHOGRAPHIC_CAMERA;
  19791. },
  19792. enumerable: true,
  19793. configurable: true
  19794. });
  19795. Object.defineProperty(Camera, "FOVMODE_VERTICAL_FIXED", {
  19796. /**
  19797. * This is the default FOV mode for perspective cameras.
  19798. * This setting aligns the upper and lower bounds of the viewport to the upper and lower bounds of the camera frustum.
  19799. *
  19800. */
  19801. get: function () {
  19802. return Camera._FOVMODE_VERTICAL_FIXED;
  19803. },
  19804. enumerable: true,
  19805. configurable: true
  19806. });
  19807. Object.defineProperty(Camera, "FOVMODE_HORIZONTAL_FIXED", {
  19808. /**
  19809. * This setting aligns the left and right bounds of the viewport to the left and right bounds of the camera frustum.
  19810. *
  19811. */
  19812. get: function () {
  19813. return Camera._FOVMODE_HORIZONTAL_FIXED;
  19814. },
  19815. enumerable: true,
  19816. configurable: true
  19817. });
  19818. Object.defineProperty(Camera, "RIG_MODE_NONE", {
  19819. get: function () {
  19820. return Camera._RIG_MODE_NONE;
  19821. },
  19822. enumerable: true,
  19823. configurable: true
  19824. });
  19825. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_ANAGLYPH", {
  19826. get: function () {
  19827. return Camera._RIG_MODE_STEREOSCOPIC_ANAGLYPH;
  19828. },
  19829. enumerable: true,
  19830. configurable: true
  19831. });
  19832. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL", {
  19833. get: function () {
  19834. return Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL;
  19835. },
  19836. enumerable: true,
  19837. configurable: true
  19838. });
  19839. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED", {
  19840. get: function () {
  19841. return Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED;
  19842. },
  19843. enumerable: true,
  19844. configurable: true
  19845. });
  19846. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_OVERUNDER", {
  19847. get: function () {
  19848. return Camera._RIG_MODE_STEREOSCOPIC_OVERUNDER;
  19849. },
  19850. enumerable: true,
  19851. configurable: true
  19852. });
  19853. Object.defineProperty(Camera, "RIG_MODE_VR", {
  19854. get: function () {
  19855. return Camera._RIG_MODE_VR;
  19856. },
  19857. enumerable: true,
  19858. configurable: true
  19859. });
  19860. Object.defineProperty(Camera, "RIG_MODE_WEBVR", {
  19861. get: function () {
  19862. return Camera._RIG_MODE_WEBVR;
  19863. },
  19864. enumerable: true,
  19865. configurable: true
  19866. });
  19867. /**
  19868. * Store current camera state (fov, position, etc..)
  19869. */
  19870. Camera.prototype.storeState = function () {
  19871. this._stateStored = true;
  19872. this._storedFov = this.fov;
  19873. return this;
  19874. };
  19875. /**
  19876. * Restores the camera state values if it has been stored. You must call storeState() first
  19877. */
  19878. Camera.prototype._restoreStateValues = function () {
  19879. if (!this._stateStored) {
  19880. return false;
  19881. }
  19882. this.fov = this._storedFov;
  19883. return true;
  19884. };
  19885. /**
  19886. * Restored camera state. You must call storeState() first
  19887. */
  19888. Camera.prototype.restoreState = function () {
  19889. if (this._restoreStateValues()) {
  19890. this.onRestoreStateObservable.notifyObservers(this);
  19891. return true;
  19892. }
  19893. return false;
  19894. };
  19895. Camera.prototype.getClassName = function () {
  19896. return "Camera";
  19897. };
  19898. /**
  19899. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  19900. */
  19901. Camera.prototype.toString = function (fullDetails) {
  19902. var ret = "Name: " + this.name;
  19903. ret += ", type: " + this.getClassName();
  19904. if (this.animations) {
  19905. for (var i = 0; i < this.animations.length; i++) {
  19906. ret += ", animation[0]: " + this.animations[i].toString(fullDetails);
  19907. }
  19908. }
  19909. if (fullDetails) {
  19910. }
  19911. return ret;
  19912. };
  19913. Object.defineProperty(Camera.prototype, "globalPosition", {
  19914. get: function () {
  19915. return this._globalPosition;
  19916. },
  19917. enumerable: true,
  19918. configurable: true
  19919. });
  19920. Camera.prototype.getActiveMeshes = function () {
  19921. return this._activeMeshes;
  19922. };
  19923. Camera.prototype.isActiveMesh = function (mesh) {
  19924. return (this._activeMeshes.indexOf(mesh) !== -1);
  19925. };
  19926. //Cache
  19927. Camera.prototype._initCache = function () {
  19928. _super.prototype._initCache.call(this);
  19929. this._cache.position = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  19930. this._cache.upVector = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  19931. this._cache.mode = undefined;
  19932. this._cache.minZ = undefined;
  19933. this._cache.maxZ = undefined;
  19934. this._cache.fov = undefined;
  19935. this._cache.fovMode = undefined;
  19936. this._cache.aspectRatio = undefined;
  19937. this._cache.orthoLeft = undefined;
  19938. this._cache.orthoRight = undefined;
  19939. this._cache.orthoBottom = undefined;
  19940. this._cache.orthoTop = undefined;
  19941. this._cache.renderWidth = undefined;
  19942. this._cache.renderHeight = undefined;
  19943. };
  19944. Camera.prototype._updateCache = function (ignoreParentClass) {
  19945. if (!ignoreParentClass) {
  19946. _super.prototype._updateCache.call(this);
  19947. }
  19948. this._cache.position.copyFrom(this.position);
  19949. this._cache.upVector.copyFrom(this.upVector);
  19950. };
  19951. // Synchronized
  19952. Camera.prototype._isSynchronized = function () {
  19953. return this._isSynchronizedViewMatrix() && this._isSynchronizedProjectionMatrix();
  19954. };
  19955. Camera.prototype._isSynchronizedViewMatrix = function () {
  19956. if (!_super.prototype._isSynchronized.call(this))
  19957. return false;
  19958. return this._cache.position.equals(this.position)
  19959. && this._cache.upVector.equals(this.upVector)
  19960. && this.isSynchronizedWithParent();
  19961. };
  19962. Camera.prototype._isSynchronizedProjectionMatrix = function () {
  19963. var check = this._cache.mode === this.mode
  19964. && this._cache.minZ === this.minZ
  19965. && this._cache.maxZ === this.maxZ;
  19966. if (!check) {
  19967. return false;
  19968. }
  19969. var engine = this.getEngine();
  19970. if (this.mode === Camera.PERSPECTIVE_CAMERA) {
  19971. check = this._cache.fov === this.fov
  19972. && this._cache.fovMode === this.fovMode
  19973. && this._cache.aspectRatio === engine.getAspectRatio(this);
  19974. }
  19975. else {
  19976. check = this._cache.orthoLeft === this.orthoLeft
  19977. && this._cache.orthoRight === this.orthoRight
  19978. && this._cache.orthoBottom === this.orthoBottom
  19979. && this._cache.orthoTop === this.orthoTop
  19980. && this._cache.renderWidth === engine.getRenderWidth()
  19981. && this._cache.renderHeight === engine.getRenderHeight();
  19982. }
  19983. return check;
  19984. };
  19985. // Controls
  19986. Camera.prototype.attachControl = function (element, noPreventDefault) {
  19987. };
  19988. Camera.prototype.detachControl = function (element) {
  19989. };
  19990. Camera.prototype.update = function () {
  19991. this._checkInputs();
  19992. if (this.cameraRigMode !== Camera.RIG_MODE_NONE) {
  19993. this._updateRigCameras();
  19994. }
  19995. };
  19996. Camera.prototype._checkInputs = function () {
  19997. this.onAfterCheckInputsObservable.notifyObservers(this);
  19998. };
  19999. Object.defineProperty(Camera.prototype, "rigCameras", {
  20000. get: function () {
  20001. return this._rigCameras;
  20002. },
  20003. enumerable: true,
  20004. configurable: true
  20005. });
  20006. Object.defineProperty(Camera.prototype, "rigPostProcess", {
  20007. get: function () {
  20008. return this._rigPostProcess;
  20009. },
  20010. enumerable: true,
  20011. configurable: true
  20012. });
  20013. Camera.prototype._cascadePostProcessesToRigCams = function () {
  20014. // invalidate framebuffer
  20015. if (this._postProcesses.length > 0) {
  20016. this._postProcesses[0].markTextureDirty();
  20017. }
  20018. // glue the rigPostProcess to the end of the user postprocesses & assign to each sub-camera
  20019. for (var i = 0, len = this._rigCameras.length; i < len; i++) {
  20020. var cam = this._rigCameras[i];
  20021. var rigPostProcess = cam._rigPostProcess;
  20022. // for VR rig, there does not have to be a post process
  20023. if (rigPostProcess) {
  20024. var isPass = rigPostProcess instanceof BABYLON.PassPostProcess;
  20025. if (isPass) {
  20026. // any rig which has a PassPostProcess for rig[0], cannot be isIntermediate when there are also user postProcesses
  20027. cam.isIntermediate = this._postProcesses.length === 0;
  20028. }
  20029. cam._postProcesses = this._postProcesses.slice(0).concat(rigPostProcess);
  20030. rigPostProcess.markTextureDirty();
  20031. }
  20032. else {
  20033. cam._postProcesses = this._postProcesses.slice(0);
  20034. }
  20035. }
  20036. };
  20037. Camera.prototype.attachPostProcess = function (postProcess, insertAt) {
  20038. if (insertAt === void 0) { insertAt = null; }
  20039. if (!postProcess.isReusable() && this._postProcesses.indexOf(postProcess) > -1) {
  20040. BABYLON.Tools.Error("You're trying to reuse a post process not defined as reusable.");
  20041. return 0;
  20042. }
  20043. if (insertAt == null || insertAt < 0) {
  20044. this._postProcesses.push(postProcess);
  20045. }
  20046. else {
  20047. this._postProcesses.splice(insertAt, 0, postProcess);
  20048. }
  20049. this._cascadePostProcessesToRigCams(); // also ensures framebuffer invalidated
  20050. return this._postProcesses.indexOf(postProcess);
  20051. };
  20052. Camera.prototype.detachPostProcess = function (postProcess) {
  20053. var idx = this._postProcesses.indexOf(postProcess);
  20054. if (idx !== -1) {
  20055. this._postProcesses.splice(idx, 1);
  20056. }
  20057. this._cascadePostProcessesToRigCams(); // also ensures framebuffer invalidated
  20058. };
  20059. Camera.prototype.getWorldMatrix = function () {
  20060. if (!this._worldMatrix) {
  20061. this._worldMatrix = BABYLON.Matrix.Identity();
  20062. }
  20063. var viewMatrix = this.getViewMatrix();
  20064. viewMatrix.invertToRef(this._worldMatrix);
  20065. return this._worldMatrix;
  20066. };
  20067. Camera.prototype._getViewMatrix = function () {
  20068. return BABYLON.Matrix.Identity();
  20069. };
  20070. Camera.prototype.getViewMatrix = function (force) {
  20071. if (!force && this._isSynchronizedViewMatrix()) {
  20072. return this._computedViewMatrix;
  20073. }
  20074. this.updateCache();
  20075. this._computedViewMatrix = this._getViewMatrix();
  20076. this._currentRenderId = this.getScene().getRenderId();
  20077. this._refreshFrustumPlanes = true;
  20078. if (!this.parent || !this.parent.getWorldMatrix) {
  20079. this._globalPosition.copyFrom(this.position);
  20080. }
  20081. else {
  20082. if (!this._worldMatrix) {
  20083. this._worldMatrix = BABYLON.Matrix.Identity();
  20084. }
  20085. this._computedViewMatrix.invertToRef(this._worldMatrix);
  20086. this._worldMatrix.multiplyToRef(this.parent.getWorldMatrix(), this._computedViewMatrix);
  20087. this._globalPosition.copyFromFloats(this._computedViewMatrix.m[12], this._computedViewMatrix.m[13], this._computedViewMatrix.m[14]);
  20088. this._computedViewMatrix.invert();
  20089. this._markSyncedWithParent();
  20090. }
  20091. if (this._cameraRigParams && this._cameraRigParams.vrPreViewMatrix) {
  20092. this._computedViewMatrix.multiplyToRef(this._cameraRigParams.vrPreViewMatrix, this._computedViewMatrix);
  20093. }
  20094. this.onViewMatrixChangedObservable.notifyObservers(this);
  20095. return this._computedViewMatrix;
  20096. };
  20097. Camera.prototype.freezeProjectionMatrix = function (projection) {
  20098. this._doNotComputeProjectionMatrix = true;
  20099. if (projection !== undefined) {
  20100. this._projectionMatrix = projection;
  20101. }
  20102. };
  20103. ;
  20104. Camera.prototype.unfreezeProjectionMatrix = function () {
  20105. this._doNotComputeProjectionMatrix = false;
  20106. };
  20107. ;
  20108. Camera.prototype.getProjectionMatrix = function (force) {
  20109. if (this._doNotComputeProjectionMatrix || (!force && this._isSynchronizedProjectionMatrix())) {
  20110. return this._projectionMatrix;
  20111. }
  20112. // Cache
  20113. this._cache.mode = this.mode;
  20114. this._cache.minZ = this.minZ;
  20115. this._cache.maxZ = this.maxZ;
  20116. // Matrix
  20117. this._refreshFrustumPlanes = true;
  20118. var engine = this.getEngine();
  20119. var scene = this.getScene();
  20120. if (this.mode === Camera.PERSPECTIVE_CAMERA) {
  20121. this._cache.fov = this.fov;
  20122. this._cache.fovMode = this.fovMode;
  20123. this._cache.aspectRatio = engine.getAspectRatio(this);
  20124. if (this.minZ <= 0) {
  20125. this.minZ = 0.1;
  20126. }
  20127. if (scene.useRightHandedSystem) {
  20128. BABYLON.Matrix.PerspectiveFovRHToRef(this.fov, engine.getAspectRatio(this), this.minZ, this.maxZ, this._projectionMatrix, this.fovMode === Camera.FOVMODE_VERTICAL_FIXED);
  20129. }
  20130. else {
  20131. BABYLON.Matrix.PerspectiveFovLHToRef(this.fov, engine.getAspectRatio(this), this.minZ, this.maxZ, this._projectionMatrix, this.fovMode === Camera.FOVMODE_VERTICAL_FIXED);
  20132. }
  20133. }
  20134. else {
  20135. var halfWidth = engine.getRenderWidth() / 2.0;
  20136. var halfHeight = engine.getRenderHeight() / 2.0;
  20137. if (scene.useRightHandedSystem) {
  20138. BABYLON.Matrix.OrthoOffCenterRHToRef(this.orthoLeft || -halfWidth, this.orthoRight || halfWidth, this.orthoBottom || -halfHeight, this.orthoTop || halfHeight, this.minZ, this.maxZ, this._projectionMatrix);
  20139. }
  20140. else {
  20141. BABYLON.Matrix.OrthoOffCenterLHToRef(this.orthoLeft || -halfWidth, this.orthoRight || halfWidth, this.orthoBottom || -halfHeight, this.orthoTop || halfHeight, this.minZ, this.maxZ, this._projectionMatrix);
  20142. }
  20143. this._cache.orthoLeft = this.orthoLeft;
  20144. this._cache.orthoRight = this.orthoRight;
  20145. this._cache.orthoBottom = this.orthoBottom;
  20146. this._cache.orthoTop = this.orthoTop;
  20147. this._cache.renderWidth = engine.getRenderWidth();
  20148. this._cache.renderHeight = engine.getRenderHeight();
  20149. }
  20150. this.onProjectionMatrixChangedObservable.notifyObservers(this);
  20151. return this._projectionMatrix;
  20152. };
  20153. Camera.prototype.getTranformationMatrix = function () {
  20154. this._computedViewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  20155. return this._transformMatrix;
  20156. };
  20157. Camera.prototype.updateFrustumPlanes = function () {
  20158. if (!this._refreshFrustumPlanes) {
  20159. return;
  20160. }
  20161. this.getTranformationMatrix();
  20162. if (!this._frustumPlanes) {
  20163. this._frustumPlanes = BABYLON.Frustum.GetPlanes(this._transformMatrix);
  20164. }
  20165. else {
  20166. BABYLON.Frustum.GetPlanesToRef(this._transformMatrix, this._frustumPlanes);
  20167. }
  20168. this._refreshFrustumPlanes = false;
  20169. };
  20170. Camera.prototype.isInFrustum = function (target) {
  20171. this.updateFrustumPlanes();
  20172. return target.isInFrustum(this._frustumPlanes);
  20173. };
  20174. Camera.prototype.isCompletelyInFrustum = function (target) {
  20175. this.updateFrustumPlanes();
  20176. return target.isCompletelyInFrustum(this._frustumPlanes);
  20177. };
  20178. Camera.prototype.getForwardRay = function (length, transform, origin) {
  20179. if (length === void 0) { length = 100; }
  20180. if (!transform) {
  20181. transform = this.getWorldMatrix();
  20182. }
  20183. if (!origin) {
  20184. origin = this.position;
  20185. }
  20186. var forward = new BABYLON.Vector3(0, 0, 1);
  20187. var forwardWorld = BABYLON.Vector3.TransformNormal(forward, transform);
  20188. var direction = BABYLON.Vector3.Normalize(forwardWorld);
  20189. return new BABYLON.Ray(origin, direction, length);
  20190. };
  20191. /**
  20192. * Releases resources associated with this node.
  20193. * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default)
  20194. * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default)
  20195. */
  20196. Camera.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  20197. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  20198. // Observables
  20199. this.onViewMatrixChangedObservable.clear();
  20200. this.onProjectionMatrixChangedObservable.clear();
  20201. this.onAfterCheckInputsObservable.clear();
  20202. this.onRestoreStateObservable.clear();
  20203. // Inputs
  20204. if (this.inputs) {
  20205. this.inputs.clear();
  20206. }
  20207. // Animations
  20208. this.getScene().stopAnimation(this);
  20209. // Remove from scene
  20210. this.getScene().removeCamera(this);
  20211. while (this._rigCameras.length > 0) {
  20212. var camera = this._rigCameras.pop();
  20213. if (camera) {
  20214. camera.dispose();
  20215. }
  20216. }
  20217. // Postprocesses
  20218. if (this._rigPostProcess) {
  20219. this._rigPostProcess.dispose(this);
  20220. this._rigPostProcess = null;
  20221. this._postProcesses = [];
  20222. }
  20223. else if (this.cameraRigMode !== Camera.RIG_MODE_NONE) {
  20224. this._rigPostProcess = null;
  20225. this._postProcesses = [];
  20226. }
  20227. else {
  20228. var i = this._postProcesses.length;
  20229. while (--i >= 0) {
  20230. this._postProcesses[i].dispose(this);
  20231. }
  20232. }
  20233. // Render targets
  20234. var i = this.customRenderTargets.length;
  20235. while (--i >= 0) {
  20236. this.customRenderTargets[i].dispose();
  20237. }
  20238. this.customRenderTargets = [];
  20239. // Active Meshes
  20240. this._activeMeshes.dispose();
  20241. _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
  20242. };
  20243. Object.defineProperty(Camera.prototype, "leftCamera", {
  20244. // ---- Camera rigs section ----
  20245. get: function () {
  20246. if (this._rigCameras.length < 1) {
  20247. return null;
  20248. }
  20249. return this._rigCameras[0];
  20250. },
  20251. enumerable: true,
  20252. configurable: true
  20253. });
  20254. Object.defineProperty(Camera.prototype, "rightCamera", {
  20255. get: function () {
  20256. if (this._rigCameras.length < 2) {
  20257. return null;
  20258. }
  20259. return this._rigCameras[1];
  20260. },
  20261. enumerable: true,
  20262. configurable: true
  20263. });
  20264. Camera.prototype.getLeftTarget = function () {
  20265. if (this._rigCameras.length < 1) {
  20266. return null;
  20267. }
  20268. return this._rigCameras[0].getTarget();
  20269. };
  20270. Camera.prototype.getRightTarget = function () {
  20271. if (this._rigCameras.length < 2) {
  20272. return null;
  20273. }
  20274. return this._rigCameras[1].getTarget();
  20275. };
  20276. Camera.prototype.setCameraRigMode = function (mode, rigParams) {
  20277. if (this.cameraRigMode === mode) {
  20278. return;
  20279. }
  20280. while (this._rigCameras.length > 0) {
  20281. var camera = this._rigCameras.pop();
  20282. if (camera) {
  20283. camera.dispose();
  20284. }
  20285. }
  20286. this.cameraRigMode = mode;
  20287. this._cameraRigParams = {};
  20288. //we have to implement stereo camera calcultating left and right viewpoints from interaxialDistance and target,
  20289. //not from a given angle as it is now, but until that complete code rewriting provisional stereoHalfAngle value is introduced
  20290. this._cameraRigParams.interaxialDistance = rigParams.interaxialDistance || 0.0637;
  20291. this._cameraRigParams.stereoHalfAngle = BABYLON.Tools.ToRadians(this._cameraRigParams.interaxialDistance / 0.0637);
  20292. // create the rig cameras, unless none
  20293. if (this.cameraRigMode !== Camera.RIG_MODE_NONE) {
  20294. var leftCamera = this.createRigCamera(this.name + "_L", 0);
  20295. var rightCamera = this.createRigCamera(this.name + "_R", 1);
  20296. if (leftCamera && rightCamera) {
  20297. this._rigCameras.push(leftCamera);
  20298. this._rigCameras.push(rightCamera);
  20299. }
  20300. }
  20301. switch (this.cameraRigMode) {
  20302. case Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  20303. this._rigCameras[0]._rigPostProcess = new BABYLON.PassPostProcess(this.name + "_passthru", 1.0, this._rigCameras[0]);
  20304. this._rigCameras[1]._rigPostProcess = new BABYLON.AnaglyphPostProcess(this.name + "_anaglyph", 1.0, this._rigCameras);
  20305. break;
  20306. case Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  20307. case Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  20308. case Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  20309. var isStereoscopicHoriz = this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL || this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED;
  20310. this._rigCameras[0]._rigPostProcess = new BABYLON.PassPostProcess(this.name + "_passthru", 1.0, this._rigCameras[0]);
  20311. this._rigCameras[1]._rigPostProcess = new BABYLON.StereoscopicInterlacePostProcess(this.name + "_stereoInterlace", this._rigCameras, isStereoscopicHoriz);
  20312. break;
  20313. case Camera.RIG_MODE_VR:
  20314. var metrics = rigParams.vrCameraMetrics || BABYLON.VRCameraMetrics.GetDefault();
  20315. this._rigCameras[0]._cameraRigParams.vrMetrics = metrics;
  20316. this._rigCameras[0].viewport = new BABYLON.Viewport(0, 0, 0.5, 1.0);
  20317. this._rigCameras[0]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  20318. this._rigCameras[0]._cameraRigParams.vrHMatrix = metrics.leftHMatrix;
  20319. this._rigCameras[0]._cameraRigParams.vrPreViewMatrix = metrics.leftPreViewMatrix;
  20320. this._rigCameras[0].getProjectionMatrix = this._rigCameras[0]._getVRProjectionMatrix;
  20321. this._rigCameras[1]._cameraRigParams.vrMetrics = metrics;
  20322. this._rigCameras[1].viewport = new BABYLON.Viewport(0.5, 0, 0.5, 1.0);
  20323. this._rigCameras[1]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  20324. this._rigCameras[1]._cameraRigParams.vrHMatrix = metrics.rightHMatrix;
  20325. this._rigCameras[1]._cameraRigParams.vrPreViewMatrix = metrics.rightPreViewMatrix;
  20326. this._rigCameras[1].getProjectionMatrix = this._rigCameras[1]._getVRProjectionMatrix;
  20327. if (metrics.compensateDistortion) {
  20328. this._rigCameras[0]._rigPostProcess = new BABYLON.VRDistortionCorrectionPostProcess("VR_Distort_Compensation_Left", this._rigCameras[0], false, metrics);
  20329. this._rigCameras[1]._rigPostProcess = new BABYLON.VRDistortionCorrectionPostProcess("VR_Distort_Compensation_Right", this._rigCameras[1], true, metrics);
  20330. }
  20331. break;
  20332. case Camera.RIG_MODE_WEBVR:
  20333. if (rigParams.vrDisplay) {
  20334. var leftEye = rigParams.vrDisplay.getEyeParameters('left');
  20335. var rightEye = rigParams.vrDisplay.getEyeParameters('right');
  20336. //Left eye
  20337. this._rigCameras[0].viewport = new BABYLON.Viewport(0, 0, 0.5, 1.0);
  20338. this._rigCameras[0].setCameraRigParameter("left", true);
  20339. //leaving this for future reference
  20340. this._rigCameras[0].setCameraRigParameter("specs", rigParams.specs);
  20341. this._rigCameras[0].setCameraRigParameter("eyeParameters", leftEye);
  20342. this._rigCameras[0].setCameraRigParameter("frameData", rigParams.frameData);
  20343. this._rigCameras[0].setCameraRigParameter("parentCamera", rigParams.parentCamera);
  20344. this._rigCameras[0]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  20345. this._rigCameras[0].getProjectionMatrix = this._getWebVRProjectionMatrix;
  20346. this._rigCameras[0].parent = this;
  20347. this._rigCameras[0]._getViewMatrix = this._getWebVRViewMatrix;
  20348. //Right eye
  20349. this._rigCameras[1].viewport = new BABYLON.Viewport(0.5, 0, 0.5, 1.0);
  20350. this._rigCameras[1].setCameraRigParameter('eyeParameters', rightEye);
  20351. this._rigCameras[1].setCameraRigParameter("specs", rigParams.specs);
  20352. this._rigCameras[1].setCameraRigParameter("frameData", rigParams.frameData);
  20353. this._rigCameras[1].setCameraRigParameter("parentCamera", rigParams.parentCamera);
  20354. this._rigCameras[1]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  20355. this._rigCameras[1].getProjectionMatrix = this._getWebVRProjectionMatrix;
  20356. this._rigCameras[1].parent = this;
  20357. this._rigCameras[1]._getViewMatrix = this._getWebVRViewMatrix;
  20358. if (Camera.UseAlternateWebVRRendering) {
  20359. this._rigCameras[1]._skipRendering = true;
  20360. this._rigCameras[0]._alternateCamera = this._rigCameras[1];
  20361. }
  20362. }
  20363. break;
  20364. }
  20365. this._cascadePostProcessesToRigCams();
  20366. this.update();
  20367. };
  20368. Camera.prototype._getVRProjectionMatrix = function () {
  20369. BABYLON.Matrix.PerspectiveFovLHToRef(this._cameraRigParams.vrMetrics.aspectRatioFov, this._cameraRigParams.vrMetrics.aspectRatio, this.minZ, this.maxZ, this._cameraRigParams.vrWorkMatrix);
  20370. this._cameraRigParams.vrWorkMatrix.multiplyToRef(this._cameraRigParams.vrHMatrix, this._projectionMatrix);
  20371. return this._projectionMatrix;
  20372. };
  20373. Camera.prototype._updateCameraRotationMatrix = function () {
  20374. //Here for WebVR
  20375. };
  20376. Camera.prototype._updateWebVRCameraRotationMatrix = function () {
  20377. //Here for WebVR
  20378. };
  20379. /**
  20380. * This function MUST be overwritten by the different WebVR cameras available.
  20381. * The context in which it is running is the RIG camera. So 'this' is the TargetCamera, left or right.
  20382. */
  20383. Camera.prototype._getWebVRProjectionMatrix = function () {
  20384. return BABYLON.Matrix.Identity();
  20385. };
  20386. /**
  20387. * This function MUST be overwritten by the different WebVR cameras available.
  20388. * The context in which it is running is the RIG camera. So 'this' is the TargetCamera, left or right.
  20389. */
  20390. Camera.prototype._getWebVRViewMatrix = function () {
  20391. return BABYLON.Matrix.Identity();
  20392. };
  20393. Camera.prototype.setCameraRigParameter = function (name, value) {
  20394. if (!this._cameraRigParams) {
  20395. this._cameraRigParams = {};
  20396. }
  20397. this._cameraRigParams[name] = value;
  20398. //provisionnally:
  20399. if (name === "interaxialDistance") {
  20400. this._cameraRigParams.stereoHalfAngle = BABYLON.Tools.ToRadians(value / 0.0637);
  20401. }
  20402. };
  20403. /**
  20404. * needs to be overridden by children so sub has required properties to be copied
  20405. */
  20406. Camera.prototype.createRigCamera = function (name, cameraIndex) {
  20407. return null;
  20408. };
  20409. /**
  20410. * May need to be overridden by children
  20411. */
  20412. Camera.prototype._updateRigCameras = function () {
  20413. for (var i = 0; i < this._rigCameras.length; i++) {
  20414. this._rigCameras[i].minZ = this.minZ;
  20415. this._rigCameras[i].maxZ = this.maxZ;
  20416. this._rigCameras[i].fov = this.fov;
  20417. }
  20418. // only update viewport when ANAGLYPH
  20419. if (this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH) {
  20420. this._rigCameras[0].viewport = this._rigCameras[1].viewport = this.viewport;
  20421. }
  20422. };
  20423. Camera.prototype._setupInputs = function () {
  20424. };
  20425. Camera.prototype.serialize = function () {
  20426. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  20427. // Type
  20428. serializationObject.type = this.getClassName();
  20429. // Parent
  20430. if (this.parent) {
  20431. serializationObject.parentId = this.parent.id;
  20432. }
  20433. if (this.inputs) {
  20434. this.inputs.serialize(serializationObject);
  20435. }
  20436. // Animations
  20437. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  20438. serializationObject.ranges = this.serializeAnimationRanges();
  20439. return serializationObject;
  20440. };
  20441. Camera.prototype.clone = function (name) {
  20442. return BABYLON.SerializationHelper.Clone(Camera.GetConstructorFromName(this.getClassName(), name, this.getScene(), this.interaxialDistance, this.isStereoscopicSideBySide), this);
  20443. };
  20444. Camera.prototype.getDirection = function (localAxis) {
  20445. var result = BABYLON.Vector3.Zero();
  20446. this.getDirectionToRef(localAxis, result);
  20447. return result;
  20448. };
  20449. Camera.prototype.getDirectionToRef = function (localAxis, result) {
  20450. BABYLON.Vector3.TransformNormalToRef(localAxis, this.getWorldMatrix(), result);
  20451. };
  20452. Camera.GetConstructorFromName = function (type, name, scene, interaxial_distance, isStereoscopicSideBySide) {
  20453. if (interaxial_distance === void 0) { interaxial_distance = 0; }
  20454. if (isStereoscopicSideBySide === void 0) { isStereoscopicSideBySide = true; }
  20455. switch (type) {
  20456. case "ArcRotateCamera":
  20457. return function () { return new BABYLON.ArcRotateCamera(name, 0, 0, 1.0, BABYLON.Vector3.Zero(), scene); };
  20458. case "DeviceOrientationCamera":
  20459. return function () { return new BABYLON.DeviceOrientationCamera(name, BABYLON.Vector3.Zero(), scene); };
  20460. case "FollowCamera":
  20461. return function () { return new BABYLON.FollowCamera(name, BABYLON.Vector3.Zero(), scene); };
  20462. case "ArcFollowCamera":
  20463. return function () { return new BABYLON.ArcFollowCamera(name, 0, 0, 1.0, null, scene); };
  20464. case "GamepadCamera":
  20465. return function () { return new BABYLON.GamepadCamera(name, BABYLON.Vector3.Zero(), scene); };
  20466. case "TouchCamera":
  20467. return function () { return new BABYLON.TouchCamera(name, BABYLON.Vector3.Zero(), scene); };
  20468. case "VirtualJoysticksCamera":
  20469. return function () { return new BABYLON.VirtualJoysticksCamera(name, BABYLON.Vector3.Zero(), scene); };
  20470. case "WebVRFreeCamera":
  20471. return function () { return new BABYLON.WebVRFreeCamera(name, BABYLON.Vector3.Zero(), scene); };
  20472. case "WebVRGamepadCamera":
  20473. return function () { return new BABYLON.WebVRFreeCamera(name, BABYLON.Vector3.Zero(), scene); };
  20474. case "VRDeviceOrientationFreeCamera":
  20475. return function () { return new BABYLON.VRDeviceOrientationFreeCamera(name, BABYLON.Vector3.Zero(), scene); };
  20476. case "VRDeviceOrientationGamepadCamera":
  20477. return function () { return new BABYLON.VRDeviceOrientationGamepadCamera(name, BABYLON.Vector3.Zero(), scene); };
  20478. case "AnaglyphArcRotateCamera":
  20479. return function () { return new BABYLON.AnaglyphArcRotateCamera(name, 0, 0, 1.0, BABYLON.Vector3.Zero(), interaxial_distance, scene); };
  20480. case "AnaglyphFreeCamera":
  20481. return function () { return new BABYLON.AnaglyphFreeCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, scene); };
  20482. case "AnaglyphGamepadCamera":
  20483. return function () { return new BABYLON.AnaglyphGamepadCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, scene); };
  20484. case "AnaglyphUniversalCamera":
  20485. return function () { return new BABYLON.AnaglyphUniversalCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, scene); };
  20486. case "StereoscopicArcRotateCamera":
  20487. return function () { return new BABYLON.StereoscopicArcRotateCamera(name, 0, 0, 1.0, BABYLON.Vector3.Zero(), interaxial_distance, isStereoscopicSideBySide, scene); };
  20488. case "StereoscopicFreeCamera":
  20489. return function () { return new BABYLON.StereoscopicFreeCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, isStereoscopicSideBySide, scene); };
  20490. case "StereoscopicGamepadCamera":
  20491. return function () { return new BABYLON.StereoscopicGamepadCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, isStereoscopicSideBySide, scene); };
  20492. case "StereoscopicUniversalCamera":
  20493. return function () { return new BABYLON.StereoscopicUniversalCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, isStereoscopicSideBySide, scene); };
  20494. case "FreeCamera":// Forcing Universal here
  20495. return function () { return new BABYLON.UniversalCamera(name, BABYLON.Vector3.Zero(), scene); };
  20496. default:// Universal Camera is the default value
  20497. return function () { return new BABYLON.UniversalCamera(name, BABYLON.Vector3.Zero(), scene); };
  20498. }
  20499. };
  20500. Camera.prototype.computeWorldMatrix = function () {
  20501. return this.getWorldMatrix();
  20502. };
  20503. Camera.Parse = function (parsedCamera, scene) {
  20504. var type = parsedCamera.type;
  20505. var construct = Camera.GetConstructorFromName(type, parsedCamera.name, scene, parsedCamera.interaxial_distance, parsedCamera.isStereoscopicSideBySide);
  20506. var camera = BABYLON.SerializationHelper.Parse(construct, parsedCamera, scene);
  20507. // Parent
  20508. if (parsedCamera.parentId) {
  20509. camera._waitingParentId = parsedCamera.parentId;
  20510. }
  20511. //If camera has an input manager, let it parse inputs settings
  20512. if (camera.inputs) {
  20513. camera.inputs.parse(parsedCamera);
  20514. camera._setupInputs();
  20515. }
  20516. if (camera.setPosition) {
  20517. camera.position.copyFromFloats(0, 0, 0);
  20518. camera.setPosition(BABYLON.Vector3.FromArray(parsedCamera.position));
  20519. }
  20520. // Target
  20521. if (parsedCamera.target) {
  20522. if (camera.setTarget) {
  20523. camera.setTarget(BABYLON.Vector3.FromArray(parsedCamera.target));
  20524. }
  20525. }
  20526. // Apply 3d rig, when found
  20527. if (parsedCamera.cameraRigMode) {
  20528. var rigParams = (parsedCamera.interaxial_distance) ? { interaxialDistance: parsedCamera.interaxial_distance } : {};
  20529. camera.setCameraRigMode(parsedCamera.cameraRigMode, rigParams);
  20530. }
  20531. // Animations
  20532. if (parsedCamera.animations) {
  20533. for (var animationIndex = 0; animationIndex < parsedCamera.animations.length; animationIndex++) {
  20534. var parsedAnimation = parsedCamera.animations[animationIndex];
  20535. camera.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  20536. }
  20537. BABYLON.Node.ParseAnimationRanges(camera, parsedCamera, scene);
  20538. }
  20539. if (parsedCamera.autoAnimate) {
  20540. scene.beginAnimation(camera, parsedCamera.autoAnimateFrom, parsedCamera.autoAnimateTo, parsedCamera.autoAnimateLoop, parsedCamera.autoAnimateSpeed || 1.0);
  20541. }
  20542. return camera;
  20543. };
  20544. // Statics
  20545. Camera._PERSPECTIVE_CAMERA = 0;
  20546. Camera._ORTHOGRAPHIC_CAMERA = 1;
  20547. Camera._FOVMODE_VERTICAL_FIXED = 0;
  20548. Camera._FOVMODE_HORIZONTAL_FIXED = 1;
  20549. Camera._RIG_MODE_NONE = 0;
  20550. Camera._RIG_MODE_STEREOSCOPIC_ANAGLYPH = 10;
  20551. Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL = 11;
  20552. Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED = 12;
  20553. Camera._RIG_MODE_STEREOSCOPIC_OVERUNDER = 13;
  20554. Camera._RIG_MODE_VR = 20;
  20555. Camera._RIG_MODE_WEBVR = 21;
  20556. Camera.ForceAttachControlToAlwaysPreventDefault = false;
  20557. Camera.UseAlternateWebVRRendering = false;
  20558. __decorate([
  20559. BABYLON.serializeAsVector3()
  20560. ], Camera.prototype, "position", void 0);
  20561. __decorate([
  20562. BABYLON.serializeAsVector3()
  20563. ], Camera.prototype, "upVector", void 0);
  20564. __decorate([
  20565. BABYLON.serialize()
  20566. ], Camera.prototype, "orthoLeft", void 0);
  20567. __decorate([
  20568. BABYLON.serialize()
  20569. ], Camera.prototype, "orthoRight", void 0);
  20570. __decorate([
  20571. BABYLON.serialize()
  20572. ], Camera.prototype, "orthoBottom", void 0);
  20573. __decorate([
  20574. BABYLON.serialize()
  20575. ], Camera.prototype, "orthoTop", void 0);
  20576. __decorate([
  20577. BABYLON.serialize()
  20578. ], Camera.prototype, "fov", void 0);
  20579. __decorate([
  20580. BABYLON.serialize()
  20581. ], Camera.prototype, "minZ", void 0);
  20582. __decorate([
  20583. BABYLON.serialize()
  20584. ], Camera.prototype, "maxZ", void 0);
  20585. __decorate([
  20586. BABYLON.serialize()
  20587. ], Camera.prototype, "inertia", void 0);
  20588. __decorate([
  20589. BABYLON.serialize()
  20590. ], Camera.prototype, "mode", void 0);
  20591. __decorate([
  20592. BABYLON.serialize()
  20593. ], Camera.prototype, "layerMask", void 0);
  20594. __decorate([
  20595. BABYLON.serialize()
  20596. ], Camera.prototype, "fovMode", void 0);
  20597. __decorate([
  20598. BABYLON.serialize()
  20599. ], Camera.prototype, "cameraRigMode", void 0);
  20600. __decorate([
  20601. BABYLON.serialize()
  20602. ], Camera.prototype, "interaxialDistance", void 0);
  20603. __decorate([
  20604. BABYLON.serialize()
  20605. ], Camera.prototype, "isStereoscopicSideBySide", void 0);
  20606. return Camera;
  20607. }(BABYLON.Node));
  20608. BABYLON.Camera = Camera;
  20609. })(BABYLON || (BABYLON = {}));
  20610. //# sourceMappingURL=babylon.camera.js.map
  20611. var BABYLON;
  20612. (function (BABYLON) {
  20613. var RenderingManager = /** @class */ (function () {
  20614. function RenderingManager(scene) {
  20615. this._renderingGroups = new Array();
  20616. this._autoClearDepthStencil = {};
  20617. this._customOpaqueSortCompareFn = {};
  20618. this._customAlphaTestSortCompareFn = {};
  20619. this._customTransparentSortCompareFn = {};
  20620. this._renderinGroupInfo = null;
  20621. this._scene = scene;
  20622. for (var i = RenderingManager.MIN_RENDERINGGROUPS; i < RenderingManager.MAX_RENDERINGGROUPS; i++) {
  20623. this._autoClearDepthStencil[i] = { autoClear: true, depth: true, stencil: true };
  20624. }
  20625. }
  20626. RenderingManager.prototype._clearDepthStencilBuffer = function (depth, stencil) {
  20627. if (depth === void 0) { depth = true; }
  20628. if (stencil === void 0) { stencil = true; }
  20629. if (this._depthStencilBufferAlreadyCleaned) {
  20630. return;
  20631. }
  20632. this._scene.getEngine().clear(null, false, depth, stencil);
  20633. this._depthStencilBufferAlreadyCleaned = true;
  20634. };
  20635. RenderingManager.prototype.render = function (customRenderFunction, activeMeshes, renderParticles, renderSprites) {
  20636. // Check if there's at least on observer on the onRenderingGroupObservable and initialize things to fire it
  20637. var observable = this._scene.onRenderingGroupObservable.hasObservers() ? this._scene.onRenderingGroupObservable : null;
  20638. var info = null;
  20639. if (observable) {
  20640. if (!this._renderinGroupInfo) {
  20641. this._renderinGroupInfo = new BABYLON.RenderingGroupInfo();
  20642. }
  20643. info = this._renderinGroupInfo;
  20644. info.scene = this._scene;
  20645. info.camera = this._scene.activeCamera;
  20646. }
  20647. // Dispatch sprites
  20648. if (renderSprites) {
  20649. for (var index = 0; index < this._scene.spriteManagers.length; index++) {
  20650. var manager = this._scene.spriteManagers[index];
  20651. this.dispatchSprites(manager);
  20652. }
  20653. }
  20654. // Render
  20655. for (var index = RenderingManager.MIN_RENDERINGGROUPS; index < RenderingManager.MAX_RENDERINGGROUPS; index++) {
  20656. this._depthStencilBufferAlreadyCleaned = index === RenderingManager.MIN_RENDERINGGROUPS;
  20657. var renderingGroup = this._renderingGroups[index];
  20658. if (!renderingGroup && !observable)
  20659. continue;
  20660. var renderingGroupMask = 0;
  20661. // Fire PRECLEAR stage
  20662. if (observable && info) {
  20663. renderingGroupMask = Math.pow(2, index);
  20664. info.renderStage = BABYLON.RenderingGroupInfo.STAGE_PRECLEAR;
  20665. info.renderingGroupId = index;
  20666. observable.notifyObservers(info, renderingGroupMask);
  20667. }
  20668. // Clear depth/stencil if needed
  20669. if (RenderingManager.AUTOCLEAR) {
  20670. var autoClear = this._autoClearDepthStencil[index];
  20671. if (autoClear && autoClear.autoClear) {
  20672. this._clearDepthStencilBuffer(autoClear.depth, autoClear.stencil);
  20673. }
  20674. }
  20675. if (observable && info) {
  20676. // Fire PREOPAQUE stage
  20677. info.renderStage = BABYLON.RenderingGroupInfo.STAGE_PREOPAQUE;
  20678. observable.notifyObservers(info, renderingGroupMask);
  20679. // Fire PRETRANSPARENT stage
  20680. info.renderStage = BABYLON.RenderingGroupInfo.STAGE_PRETRANSPARENT;
  20681. observable.notifyObservers(info, renderingGroupMask);
  20682. }
  20683. if (renderingGroup)
  20684. renderingGroup.render(customRenderFunction, renderSprites, renderParticles, activeMeshes);
  20685. // Fire POSTTRANSPARENT stage
  20686. if (observable && info) {
  20687. info.renderStage = BABYLON.RenderingGroupInfo.STAGE_POSTTRANSPARENT;
  20688. observable.notifyObservers(info, renderingGroupMask);
  20689. }
  20690. }
  20691. };
  20692. RenderingManager.prototype.reset = function () {
  20693. for (var index = RenderingManager.MIN_RENDERINGGROUPS; index < RenderingManager.MAX_RENDERINGGROUPS; index++) {
  20694. var renderingGroup = this._renderingGroups[index];
  20695. if (renderingGroup) {
  20696. renderingGroup.prepare();
  20697. }
  20698. }
  20699. };
  20700. RenderingManager.prototype.dispose = function () {
  20701. for (var index = RenderingManager.MIN_RENDERINGGROUPS; index < RenderingManager.MAX_RENDERINGGROUPS; index++) {
  20702. var renderingGroup = this._renderingGroups[index];
  20703. if (renderingGroup) {
  20704. renderingGroup.dispose();
  20705. }
  20706. }
  20707. this._renderingGroups.length = 0;
  20708. };
  20709. RenderingManager.prototype._prepareRenderingGroup = function (renderingGroupId) {
  20710. if (this._renderingGroups[renderingGroupId] === undefined) {
  20711. this._renderingGroups[renderingGroupId] = new BABYLON.RenderingGroup(renderingGroupId, this._scene, this._customOpaqueSortCompareFn[renderingGroupId], this._customAlphaTestSortCompareFn[renderingGroupId], this._customTransparentSortCompareFn[renderingGroupId]);
  20712. }
  20713. };
  20714. RenderingManager.prototype.dispatchSprites = function (spriteManager) {
  20715. var renderingGroupId = spriteManager.renderingGroupId || 0;
  20716. this._prepareRenderingGroup(renderingGroupId);
  20717. this._renderingGroups[renderingGroupId].dispatchSprites(spriteManager);
  20718. };
  20719. RenderingManager.prototype.dispatchParticles = function (particleSystem) {
  20720. var renderingGroupId = particleSystem.renderingGroupId || 0;
  20721. this._prepareRenderingGroup(renderingGroupId);
  20722. this._renderingGroups[renderingGroupId].dispatchParticles(particleSystem);
  20723. };
  20724. /**
  20725. * @param subMesh The submesh to dispatch
  20726. * @param [mesh] Optional reference to the submeshes's mesh. Provide if you have an exiting reference to improve performance.
  20727. * @param [material] Optional reference to the submeshes's material. Provide if you have an exiting reference to improve performance.
  20728. */
  20729. RenderingManager.prototype.dispatch = function (subMesh, mesh, material) {
  20730. if (mesh === undefined) {
  20731. mesh = subMesh.getMesh();
  20732. }
  20733. var renderingGroupId = mesh.renderingGroupId || 0;
  20734. this._prepareRenderingGroup(renderingGroupId);
  20735. this._renderingGroups[renderingGroupId].dispatch(subMesh, mesh, material);
  20736. };
  20737. /**
  20738. * Overrides the default sort function applied in the renderging group to prepare the meshes.
  20739. * This allowed control for front to back rendering or reversly depending of the special needs.
  20740. *
  20741. * @param renderingGroupId The rendering group id corresponding to its index
  20742. * @param opaqueSortCompareFn The opaque queue comparison function use to sort.
  20743. * @param alphaTestSortCompareFn The alpha test queue comparison function use to sort.
  20744. * @param transparentSortCompareFn The transparent queue comparison function use to sort.
  20745. */
  20746. RenderingManager.prototype.setRenderingOrder = function (renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  20747. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  20748. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  20749. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  20750. this._customOpaqueSortCompareFn[renderingGroupId] = opaqueSortCompareFn;
  20751. this._customAlphaTestSortCompareFn[renderingGroupId] = alphaTestSortCompareFn;
  20752. this._customTransparentSortCompareFn[renderingGroupId] = transparentSortCompareFn;
  20753. if (this._renderingGroups[renderingGroupId]) {
  20754. var group = this._renderingGroups[renderingGroupId];
  20755. group.opaqueSortCompareFn = this._customOpaqueSortCompareFn[renderingGroupId];
  20756. group.alphaTestSortCompareFn = this._customAlphaTestSortCompareFn[renderingGroupId];
  20757. group.transparentSortCompareFn = this._customTransparentSortCompareFn[renderingGroupId];
  20758. }
  20759. };
  20760. /**
  20761. * Specifies whether or not the stencil and depth buffer are cleared between two rendering groups.
  20762. *
  20763. * @param renderingGroupId The rendering group id corresponding to its index
  20764. * @param autoClearDepthStencil Automatically clears depth and stencil between groups if true.
  20765. * @param depth Automatically clears depth between groups if true and autoClear is true.
  20766. * @param stencil Automatically clears stencil between groups if true and autoClear is true.
  20767. */
  20768. RenderingManager.prototype.setRenderingAutoClearDepthStencil = function (renderingGroupId, autoClearDepthStencil, depth, stencil) {
  20769. if (depth === void 0) { depth = true; }
  20770. if (stencil === void 0) { stencil = true; }
  20771. this._autoClearDepthStencil[renderingGroupId] = {
  20772. autoClear: autoClearDepthStencil,
  20773. depth: depth,
  20774. stencil: stencil
  20775. };
  20776. };
  20777. /**
  20778. * The max id used for rendering groups (not included)
  20779. */
  20780. RenderingManager.MAX_RENDERINGGROUPS = 4;
  20781. /**
  20782. * The min id used for rendering groups (included)
  20783. */
  20784. RenderingManager.MIN_RENDERINGGROUPS = 0;
  20785. /**
  20786. * Used to globally prevent autoclearing scenes.
  20787. */
  20788. RenderingManager.AUTOCLEAR = true;
  20789. return RenderingManager;
  20790. }());
  20791. BABYLON.RenderingManager = RenderingManager;
  20792. })(BABYLON || (BABYLON = {}));
  20793. //# sourceMappingURL=babylon.renderingManager.js.map
  20794. var BABYLON;
  20795. (function (BABYLON) {
  20796. var RenderingGroup = /** @class */ (function () {
  20797. /**
  20798. * Creates a new rendering group.
  20799. * @param index The rendering group index
  20800. * @param opaqueSortCompareFn The opaque sort comparison function. If null no order is applied
  20801. * @param alphaTestSortCompareFn The alpha test sort comparison function. If null no order is applied
  20802. * @param transparentSortCompareFn The transparent sort comparison function. If null back to front + alpha index sort is applied
  20803. */
  20804. function RenderingGroup(index, scene, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  20805. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  20806. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  20807. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  20808. this.index = index;
  20809. this._opaqueSubMeshes = new BABYLON.SmartArray(256);
  20810. this._transparentSubMeshes = new BABYLON.SmartArray(256);
  20811. this._alphaTestSubMeshes = new BABYLON.SmartArray(256);
  20812. this._depthOnlySubMeshes = new BABYLON.SmartArray(256);
  20813. this._particleSystems = new BABYLON.SmartArray(256);
  20814. this._spriteManagers = new BABYLON.SmartArray(256);
  20815. this._edgesRenderers = new BABYLON.SmartArray(16);
  20816. this._scene = scene;
  20817. this.opaqueSortCompareFn = opaqueSortCompareFn;
  20818. this.alphaTestSortCompareFn = alphaTestSortCompareFn;
  20819. this.transparentSortCompareFn = transparentSortCompareFn;
  20820. }
  20821. Object.defineProperty(RenderingGroup.prototype, "opaqueSortCompareFn", {
  20822. /**
  20823. * Set the opaque sort comparison function.
  20824. * If null the sub meshes will be render in the order they were created
  20825. */
  20826. set: function (value) {
  20827. this._opaqueSortCompareFn = value;
  20828. if (value) {
  20829. this._renderOpaque = this.renderOpaqueSorted;
  20830. }
  20831. else {
  20832. this._renderOpaque = RenderingGroup.renderUnsorted;
  20833. }
  20834. },
  20835. enumerable: true,
  20836. configurable: true
  20837. });
  20838. Object.defineProperty(RenderingGroup.prototype, "alphaTestSortCompareFn", {
  20839. /**
  20840. * Set the alpha test sort comparison function.
  20841. * If null the sub meshes will be render in the order they were created
  20842. */
  20843. set: function (value) {
  20844. this._alphaTestSortCompareFn = value;
  20845. if (value) {
  20846. this._renderAlphaTest = this.renderAlphaTestSorted;
  20847. }
  20848. else {
  20849. this._renderAlphaTest = RenderingGroup.renderUnsorted;
  20850. }
  20851. },
  20852. enumerable: true,
  20853. configurable: true
  20854. });
  20855. Object.defineProperty(RenderingGroup.prototype, "transparentSortCompareFn", {
  20856. /**
  20857. * Set the transparent sort comparison function.
  20858. * If null the sub meshes will be render in the order they were created
  20859. */
  20860. set: function (value) {
  20861. if (value) {
  20862. this._transparentSortCompareFn = value;
  20863. }
  20864. else {
  20865. this._transparentSortCompareFn = RenderingGroup.defaultTransparentSortCompare;
  20866. }
  20867. this._renderTransparent = this.renderTransparentSorted;
  20868. },
  20869. enumerable: true,
  20870. configurable: true
  20871. });
  20872. /**
  20873. * Render all the sub meshes contained in the group.
  20874. * @param customRenderFunction Used to override the default render behaviour of the group.
  20875. * @returns true if rendered some submeshes.
  20876. */
  20877. RenderingGroup.prototype.render = function (customRenderFunction, renderSprites, renderParticles, activeMeshes) {
  20878. if (customRenderFunction) {
  20879. customRenderFunction(this._opaqueSubMeshes, this._alphaTestSubMeshes, this._transparentSubMeshes, this._depthOnlySubMeshes);
  20880. return;
  20881. }
  20882. var engine = this._scene.getEngine();
  20883. // Depth only
  20884. if (this._depthOnlySubMeshes.length !== 0) {
  20885. engine.setColorWrite(false);
  20886. this._renderAlphaTest(this._depthOnlySubMeshes);
  20887. engine.setColorWrite(true);
  20888. }
  20889. // Opaque
  20890. if (this._opaqueSubMeshes.length !== 0) {
  20891. this._renderOpaque(this._opaqueSubMeshes);
  20892. }
  20893. // Alpha test
  20894. if (this._alphaTestSubMeshes.length !== 0) {
  20895. this._renderAlphaTest(this._alphaTestSubMeshes);
  20896. }
  20897. var stencilState = engine.getStencilBuffer();
  20898. engine.setStencilBuffer(false);
  20899. // Sprites
  20900. if (renderSprites) {
  20901. this._renderSprites();
  20902. }
  20903. // Particles
  20904. if (renderParticles) {
  20905. this._renderParticles(activeMeshes);
  20906. }
  20907. if (this.onBeforeTransparentRendering) {
  20908. this.onBeforeTransparentRendering();
  20909. }
  20910. // Transparent
  20911. if (this._transparentSubMeshes.length !== 0) {
  20912. this._renderTransparent(this._transparentSubMeshes);
  20913. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  20914. }
  20915. // Set back stencil to false in case it changes before the edge renderer.
  20916. engine.setStencilBuffer(false);
  20917. // Edges
  20918. for (var edgesRendererIndex = 0; edgesRendererIndex < this._edgesRenderers.length; edgesRendererIndex++) {
  20919. this._edgesRenderers.data[edgesRendererIndex].render();
  20920. }
  20921. // Restore Stencil state.
  20922. engine.setStencilBuffer(stencilState);
  20923. };
  20924. /**
  20925. * Renders the opaque submeshes in the order from the opaqueSortCompareFn.
  20926. * @param subMeshes The submeshes to render
  20927. */
  20928. RenderingGroup.prototype.renderOpaqueSorted = function (subMeshes) {
  20929. return RenderingGroup.renderSorted(subMeshes, this._opaqueSortCompareFn, this._scene.activeCamera, false);
  20930. };
  20931. /**
  20932. * Renders the opaque submeshes in the order from the alphatestSortCompareFn.
  20933. * @param subMeshes The submeshes to render
  20934. */
  20935. RenderingGroup.prototype.renderAlphaTestSorted = function (subMeshes) {
  20936. return RenderingGroup.renderSorted(subMeshes, this._alphaTestSortCompareFn, this._scene.activeCamera, false);
  20937. };
  20938. /**
  20939. * Renders the opaque submeshes in the order from the transparentSortCompareFn.
  20940. * @param subMeshes The submeshes to render
  20941. */
  20942. RenderingGroup.prototype.renderTransparentSorted = function (subMeshes) {
  20943. return RenderingGroup.renderSorted(subMeshes, this._transparentSortCompareFn, this._scene.activeCamera, true);
  20944. };
  20945. /**
  20946. * Renders the submeshes in a specified order.
  20947. * @param subMeshes The submeshes to sort before render
  20948. * @param sortCompareFn The comparison function use to sort
  20949. * @param cameraPosition The camera position use to preprocess the submeshes to help sorting
  20950. * @param transparent Specifies to activate blending if true
  20951. */
  20952. RenderingGroup.renderSorted = function (subMeshes, sortCompareFn, camera, transparent) {
  20953. var subIndex = 0;
  20954. var subMesh;
  20955. var cameraPosition = camera ? camera.globalPosition : BABYLON.Vector3.Zero();
  20956. for (; subIndex < subMeshes.length; subIndex++) {
  20957. subMesh = subMeshes.data[subIndex];
  20958. subMesh._alphaIndex = subMesh.getMesh().alphaIndex;
  20959. subMesh._distanceToCamera = subMesh.getBoundingInfo().boundingSphere.centerWorld.subtract(cameraPosition).length();
  20960. }
  20961. var sortedArray = subMeshes.data.slice(0, subMeshes.length);
  20962. if (sortCompareFn) {
  20963. sortedArray.sort(sortCompareFn);
  20964. }
  20965. for (subIndex = 0; subIndex < sortedArray.length; subIndex++) {
  20966. subMesh = sortedArray[subIndex];
  20967. if (transparent) {
  20968. var material = subMesh.getMaterial();
  20969. if (material && material.needDepthPrePass) {
  20970. var engine = material.getScene().getEngine();
  20971. engine.setColorWrite(false);
  20972. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  20973. subMesh.render(false);
  20974. engine.setColorWrite(true);
  20975. }
  20976. }
  20977. subMesh.render(transparent);
  20978. }
  20979. };
  20980. /**
  20981. * Renders the submeshes in the order they were dispatched (no sort applied).
  20982. * @param subMeshes The submeshes to render
  20983. */
  20984. RenderingGroup.renderUnsorted = function (subMeshes) {
  20985. for (var subIndex = 0; subIndex < subMeshes.length; subIndex++) {
  20986. var submesh = subMeshes.data[subIndex];
  20987. submesh.render(false);
  20988. }
  20989. };
  20990. /**
  20991. * Build in function which can be applied to ensure meshes of a special queue (opaque, alpha test, transparent)
  20992. * are rendered back to front if in the same alpha index.
  20993. *
  20994. * @param a The first submesh
  20995. * @param b The second submesh
  20996. * @returns The result of the comparison
  20997. */
  20998. RenderingGroup.defaultTransparentSortCompare = function (a, b) {
  20999. // Alpha index first
  21000. if (a._alphaIndex > b._alphaIndex) {
  21001. return 1;
  21002. }
  21003. if (a._alphaIndex < b._alphaIndex) {
  21004. return -1;
  21005. }
  21006. // Then distance to camera
  21007. return RenderingGroup.backToFrontSortCompare(a, b);
  21008. };
  21009. /**
  21010. * Build in function which can be applied to ensure meshes of a special queue (opaque, alpha test, transparent)
  21011. * are rendered back to front.
  21012. *
  21013. * @param a The first submesh
  21014. * @param b The second submesh
  21015. * @returns The result of the comparison
  21016. */
  21017. RenderingGroup.backToFrontSortCompare = function (a, b) {
  21018. // Then distance to camera
  21019. if (a._distanceToCamera < b._distanceToCamera) {
  21020. return 1;
  21021. }
  21022. if (a._distanceToCamera > b._distanceToCamera) {
  21023. return -1;
  21024. }
  21025. return 0;
  21026. };
  21027. /**
  21028. * Build in function which can be applied to ensure meshes of a special queue (opaque, alpha test, transparent)
  21029. * are rendered front to back (prevent overdraw).
  21030. *
  21031. * @param a The first submesh
  21032. * @param b The second submesh
  21033. * @returns The result of the comparison
  21034. */
  21035. RenderingGroup.frontToBackSortCompare = function (a, b) {
  21036. // Then distance to camera
  21037. if (a._distanceToCamera < b._distanceToCamera) {
  21038. return -1;
  21039. }
  21040. if (a._distanceToCamera > b._distanceToCamera) {
  21041. return 1;
  21042. }
  21043. return 0;
  21044. };
  21045. /**
  21046. * Resets the different lists of submeshes to prepare a new frame.
  21047. */
  21048. RenderingGroup.prototype.prepare = function () {
  21049. this._opaqueSubMeshes.reset();
  21050. this._transparentSubMeshes.reset();
  21051. this._alphaTestSubMeshes.reset();
  21052. this._depthOnlySubMeshes.reset();
  21053. this._particleSystems.reset();
  21054. this._spriteManagers.reset();
  21055. this._edgesRenderers.reset();
  21056. };
  21057. RenderingGroup.prototype.dispose = function () {
  21058. this._opaqueSubMeshes.dispose();
  21059. this._transparentSubMeshes.dispose();
  21060. this._alphaTestSubMeshes.dispose();
  21061. this._depthOnlySubMeshes.dispose();
  21062. this._particleSystems.dispose();
  21063. this._spriteManagers.dispose();
  21064. this._edgesRenderers.dispose();
  21065. };
  21066. /**
  21067. * Inserts the submesh in its correct queue depending on its material.
  21068. * @param subMesh The submesh to dispatch
  21069. * @param [mesh] Optional reference to the submeshes's mesh. Provide if you have an exiting reference to improve performance.
  21070. * @param [material] Optional reference to the submeshes's material. Provide if you have an exiting reference to improve performance.
  21071. */
  21072. RenderingGroup.prototype.dispatch = function (subMesh, mesh, material) {
  21073. // Get mesh and materials if not provided
  21074. if (mesh === undefined) {
  21075. mesh = subMesh.getMesh();
  21076. }
  21077. if (material === undefined) {
  21078. material = subMesh.getMaterial();
  21079. }
  21080. if (material === null || material === undefined) {
  21081. return;
  21082. }
  21083. if (material.needAlphaBlendingForMesh(mesh)) {
  21084. this._transparentSubMeshes.push(subMesh);
  21085. }
  21086. else if (material.needAlphaTesting()) {
  21087. if (material.needDepthPrePass) {
  21088. this._depthOnlySubMeshes.push(subMesh);
  21089. }
  21090. this._alphaTestSubMeshes.push(subMesh);
  21091. }
  21092. else {
  21093. if (material.needDepthPrePass) {
  21094. this._depthOnlySubMeshes.push(subMesh);
  21095. }
  21096. this._opaqueSubMeshes.push(subMesh); // Opaque
  21097. }
  21098. if (mesh._edgesRenderer !== null && mesh._edgesRenderer !== undefined) {
  21099. this._edgesRenderers.push(mesh._edgesRenderer);
  21100. }
  21101. };
  21102. RenderingGroup.prototype.dispatchSprites = function (spriteManager) {
  21103. this._spriteManagers.push(spriteManager);
  21104. };
  21105. RenderingGroup.prototype.dispatchParticles = function (particleSystem) {
  21106. this._particleSystems.push(particleSystem);
  21107. };
  21108. RenderingGroup.prototype._renderParticles = function (activeMeshes) {
  21109. if (this._particleSystems.length === 0) {
  21110. return;
  21111. }
  21112. // Particles
  21113. var activeCamera = this._scene.activeCamera;
  21114. this._scene.onBeforeParticlesRenderingObservable.notifyObservers(this._scene);
  21115. for (var particleIndex = 0; particleIndex < this._particleSystems.length; particleIndex++) {
  21116. var particleSystem = this._particleSystems.data[particleIndex];
  21117. if ((activeCamera && activeCamera.layerMask & particleSystem.layerMask) === 0) {
  21118. continue;
  21119. }
  21120. var emitter = particleSystem.emitter;
  21121. if (!emitter.position || !activeMeshes || activeMeshes.indexOf(emitter) !== -1) {
  21122. this._scene._activeParticles.addCount(particleSystem.render(), false);
  21123. }
  21124. }
  21125. this._scene.onAfterParticlesRenderingObservable.notifyObservers(this._scene);
  21126. };
  21127. RenderingGroup.prototype._renderSprites = function () {
  21128. if (!this._scene.spritesEnabled || this._spriteManagers.length === 0) {
  21129. return;
  21130. }
  21131. // Sprites
  21132. var activeCamera = this._scene.activeCamera;
  21133. this._scene.onBeforeSpritesRenderingObservable.notifyObservers(this._scene);
  21134. for (var id = 0; id < this._spriteManagers.length; id++) {
  21135. var spriteManager = this._spriteManagers.data[id];
  21136. if (((activeCamera && activeCamera.layerMask & spriteManager.layerMask) !== 0)) {
  21137. spriteManager.render();
  21138. }
  21139. }
  21140. this._scene.onAfterSpritesRenderingObservable.notifyObservers(this._scene);
  21141. };
  21142. return RenderingGroup;
  21143. }());
  21144. BABYLON.RenderingGroup = RenderingGroup;
  21145. })(BABYLON || (BABYLON = {}));
  21146. //# sourceMappingURL=babylon.renderingGroup.js.map
  21147. var BABYLON;
  21148. (function (BABYLON) {
  21149. var ClickInfo = /** @class */ (function () {
  21150. function ClickInfo() {
  21151. this._singleClick = false;
  21152. this._doubleClick = false;
  21153. this._hasSwiped = false;
  21154. this._ignore = false;
  21155. }
  21156. Object.defineProperty(ClickInfo.prototype, "singleClick", {
  21157. get: function () {
  21158. return this._singleClick;
  21159. },
  21160. set: function (b) {
  21161. this._singleClick = b;
  21162. },
  21163. enumerable: true,
  21164. configurable: true
  21165. });
  21166. Object.defineProperty(ClickInfo.prototype, "doubleClick", {
  21167. get: function () {
  21168. return this._doubleClick;
  21169. },
  21170. set: function (b) {
  21171. this._doubleClick = b;
  21172. },
  21173. enumerable: true,
  21174. configurable: true
  21175. });
  21176. Object.defineProperty(ClickInfo.prototype, "hasSwiped", {
  21177. get: function () {
  21178. return this._hasSwiped;
  21179. },
  21180. set: function (b) {
  21181. this._hasSwiped = b;
  21182. },
  21183. enumerable: true,
  21184. configurable: true
  21185. });
  21186. Object.defineProperty(ClickInfo.prototype, "ignore", {
  21187. get: function () {
  21188. return this._ignore;
  21189. },
  21190. set: function (b) {
  21191. this._ignore = b;
  21192. },
  21193. enumerable: true,
  21194. configurable: true
  21195. });
  21196. return ClickInfo;
  21197. }());
  21198. /**
  21199. * This class is used by the onRenderingGroupObservable
  21200. */
  21201. var RenderingGroupInfo = /** @class */ (function () {
  21202. function RenderingGroupInfo() {
  21203. }
  21204. /**
  21205. * Stage corresponding to the very first hook in the renderingGroup phase: before the render buffer may be cleared
  21206. * This stage will be fired no matter what
  21207. */
  21208. RenderingGroupInfo.STAGE_PRECLEAR = 1;
  21209. /**
  21210. * Called before opaque object are rendered.
  21211. * This stage will be fired only if there's 3D Opaque content to render
  21212. */
  21213. RenderingGroupInfo.STAGE_PREOPAQUE = 2;
  21214. /**
  21215. * Called after the opaque objects are rendered and before the transparent ones
  21216. * This stage will be fired only if there's 3D transparent content to render
  21217. */
  21218. RenderingGroupInfo.STAGE_PRETRANSPARENT = 3;
  21219. /**
  21220. * Called after the transparent object are rendered, last hook of the renderingGroup phase
  21221. * This stage will be fired no matter what
  21222. */
  21223. RenderingGroupInfo.STAGE_POSTTRANSPARENT = 4;
  21224. return RenderingGroupInfo;
  21225. }());
  21226. BABYLON.RenderingGroupInfo = RenderingGroupInfo;
  21227. /**
  21228. * Represents a scene to be rendered by the engine.
  21229. * @see http://doc.babylonjs.com/page.php?p=21911
  21230. */
  21231. var Scene = /** @class */ (function () {
  21232. /**
  21233. * @constructor
  21234. * @param {BABYLON.Engine} engine - the engine to be used to render this scene.
  21235. */
  21236. function Scene(engine) {
  21237. // Members
  21238. this.autoClear = true;
  21239. this.autoClearDepthAndStencil = true;
  21240. this.clearColor = new BABYLON.Color4(0.2, 0.2, 0.3, 1.0);
  21241. this.ambientColor = new BABYLON.Color3(0, 0, 0);
  21242. this.forceWireframe = false;
  21243. this._forcePointsCloud = false;
  21244. this.forceShowBoundingBoxes = false;
  21245. this.animationsEnabled = true;
  21246. this.useConstantAnimationDeltaTime = false;
  21247. this.constantlyUpdateMeshUnderPointer = false;
  21248. this.hoverCursor = "pointer";
  21249. this.defaultCursor = "";
  21250. /**
  21251. * This is used to call preventDefault() on pointer down
  21252. * in order to block unwanted artifacts like system double clicks
  21253. */
  21254. this.preventDefaultOnPointerDown = true;
  21255. // Metadata
  21256. this.metadata = null;
  21257. /**
  21258. * An event triggered when the scene is disposed.
  21259. * @type {BABYLON.Observable}
  21260. */
  21261. this.onDisposeObservable = new BABYLON.Observable();
  21262. /**
  21263. * An event triggered before rendering the scene (right after animations and physics)
  21264. * @type {BABYLON.Observable}
  21265. */
  21266. this.onBeforeRenderObservable = new BABYLON.Observable();
  21267. /**
  21268. * An event triggered after rendering the scene
  21269. * @type {BABYLON.Observable}
  21270. */
  21271. this.onAfterRenderObservable = new BABYLON.Observable();
  21272. /**
  21273. * An event triggered before animating the scene
  21274. * @type {BABYLON.Observable}
  21275. */
  21276. this.onBeforeAnimationsObservable = new BABYLON.Observable();
  21277. /**
  21278. * An event triggered after animations processing
  21279. * @type {BABYLON.Observable}
  21280. */
  21281. this.onAfterAnimationsObservable = new BABYLON.Observable();
  21282. /**
  21283. * An event triggered before draw calls are ready to be sent
  21284. * @type {BABYLON.Observable}
  21285. */
  21286. this.onBeforeDrawPhaseObservable = new BABYLON.Observable();
  21287. /**
  21288. * An event triggered after draw calls have been sent
  21289. * @type {BABYLON.Observable}
  21290. */
  21291. this.onAfterDrawPhaseObservable = new BABYLON.Observable();
  21292. /**
  21293. * An event triggered when physic simulation is about to be run
  21294. * @type {BABYLON.Observable}
  21295. */
  21296. this.onBeforePhysicsObservable = new BABYLON.Observable();
  21297. /**
  21298. * An event triggered when physic simulation has been done
  21299. * @type {BABYLON.Observable}
  21300. */
  21301. this.onAfterPhysicsObservable = new BABYLON.Observable();
  21302. /**
  21303. * An event triggered when the scene is ready
  21304. * @type {BABYLON.Observable}
  21305. */
  21306. this.onReadyObservable = new BABYLON.Observable();
  21307. /**
  21308. * An event triggered before rendering a camera
  21309. * @type {BABYLON.Observable}
  21310. */
  21311. this.onBeforeCameraRenderObservable = new BABYLON.Observable();
  21312. /**
  21313. * An event triggered after rendering a camera
  21314. * @type {BABYLON.Observable}
  21315. */
  21316. this.onAfterCameraRenderObservable = new BABYLON.Observable();
  21317. /**
  21318. * An event triggered when active meshes evaluation is about to start
  21319. * @type {BABYLON.Observable}
  21320. */
  21321. this.onBeforeActiveMeshesEvaluationObservable = new BABYLON.Observable();
  21322. /**
  21323. * An event triggered when active meshes evaluation is done
  21324. * @type {BABYLON.Observable}
  21325. */
  21326. this.onAfterActiveMeshesEvaluationObservable = new BABYLON.Observable();
  21327. /**
  21328. * An event triggered when particles rendering is about to start
  21329. * Note: This event can be trigger more than once per frame (because particles can be rendered by render target textures as well)
  21330. * @type {BABYLON.Observable}
  21331. */
  21332. this.onBeforeParticlesRenderingObservable = new BABYLON.Observable();
  21333. /**
  21334. * An event triggered when particles rendering is done
  21335. * Note: This event can be trigger more than once per frame (because particles can be rendered by render target textures as well)
  21336. * @type {BABYLON.Observable}
  21337. */
  21338. this.onAfterParticlesRenderingObservable = new BABYLON.Observable();
  21339. /**
  21340. * An event triggered when sprites rendering is about to start
  21341. * Note: This event can be trigger more than once per frame (because sprites can be rendered by render target textures as well)
  21342. * @type {BABYLON.Observable}
  21343. */
  21344. this.onBeforeSpritesRenderingObservable = new BABYLON.Observable();
  21345. /**
  21346. * An event triggered when sprites rendering is done
  21347. * Note: This event can be trigger more than once per frame (because sprites can be rendered by render target textures as well)
  21348. * @type {BABYLON.Observable}
  21349. */
  21350. this.onAfterSpritesRenderingObservable = new BABYLON.Observable();
  21351. /**
  21352. * An event triggered when SceneLoader.Append or SceneLoader.Load or SceneLoader.ImportMesh were successfully executed
  21353. * @type {BABYLON.Observable}
  21354. */
  21355. this.onDataLoadedObservable = new BABYLON.Observable();
  21356. /**
  21357. * An event triggered when a camera is created
  21358. * @type {BABYLON.Observable}
  21359. */
  21360. this.onNewCameraAddedObservable = new BABYLON.Observable();
  21361. /**
  21362. * An event triggered when a camera is removed
  21363. * @type {BABYLON.Observable}
  21364. */
  21365. this.onCameraRemovedObservable = new BABYLON.Observable();
  21366. /**
  21367. * An event triggered when a light is created
  21368. * @type {BABYLON.Observable}
  21369. */
  21370. this.onNewLightAddedObservable = new BABYLON.Observable();
  21371. /**
  21372. * An event triggered when a light is removed
  21373. * @type {BABYLON.Observable}
  21374. */
  21375. this.onLightRemovedObservable = new BABYLON.Observable();
  21376. /**
  21377. * An event triggered when a geometry is created
  21378. * @type {BABYLON.Observable}
  21379. */
  21380. this.onNewGeometryAddedObservable = new BABYLON.Observable();
  21381. /**
  21382. * An event triggered when a geometry is removed
  21383. * @type {BABYLON.Observable}
  21384. */
  21385. this.onGeometryRemovedObservable = new BABYLON.Observable();
  21386. /**
  21387. * An event triggered when a transform node is created
  21388. * @type {BABYLON.Observable}
  21389. */
  21390. this.onNewTransformNodeAddedObservable = new BABYLON.Observable();
  21391. /**
  21392. * An event triggered when a transform node is removed
  21393. * @type {BABYLON.Observable}
  21394. */
  21395. this.onTransformNodeRemovedObservable = new BABYLON.Observable();
  21396. /**
  21397. * An event triggered when a mesh is created
  21398. * @type {BABYLON.Observable}
  21399. */
  21400. this.onNewMeshAddedObservable = new BABYLON.Observable();
  21401. /**
  21402. * An event triggered when a mesh is removed
  21403. * @type {BABYLON.Observable}
  21404. */
  21405. this.onMeshRemovedObservable = new BABYLON.Observable();
  21406. /**
  21407. * An event triggered when render targets are about to be rendered
  21408. * Can happen multiple times per frame.
  21409. * @type {BABYLON.Observable}
  21410. */
  21411. this.OnBeforeRenderTargetsRenderObservable = new BABYLON.Observable();
  21412. /**
  21413. * An event triggered when render targets were rendered.
  21414. * Can happen multiple times per frame.
  21415. * @type {BABYLON.Observable}
  21416. */
  21417. this.OnAfterRenderTargetsRenderObservable = new BABYLON.Observable();
  21418. /**
  21419. * An event triggered before calculating deterministic simulation step
  21420. * @type {BABYLON.Observable}
  21421. */
  21422. this.onBeforeStepObservable = new BABYLON.Observable();
  21423. /**
  21424. * An event triggered after calculating deterministic simulation step
  21425. * @type {BABYLON.Observable}
  21426. */
  21427. this.onAfterStepObservable = new BABYLON.Observable();
  21428. /**
  21429. * This Observable will be triggered for each stage of each renderingGroup of each rendered camera.
  21430. * The RenderinGroupInfo class contains all the information about the context in which the observable is called
  21431. * 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)
  21432. */
  21433. this.onRenderingGroupObservable = new BABYLON.Observable();
  21434. // Animations
  21435. this.animations = [];
  21436. /**
  21437. * 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).
  21438. * You have the possibility to skip the process and the call to onPointerObservable by setting PointerInfoPre.skipOnPointerObservable to true
  21439. */
  21440. this.onPrePointerObservable = new BABYLON.Observable();
  21441. /**
  21442. * Observable event triggered each time an input event is received from the rendering canvas
  21443. */
  21444. this.onPointerObservable = new BABYLON.Observable();
  21445. this._meshPickProceed = false;
  21446. this._currentPickResult = null;
  21447. this._previousPickResult = null;
  21448. this._totalPointersPressed = 0;
  21449. this._doubleClickOccured = false;
  21450. /** Define this parameter if you are using multiple cameras and you want to specify which one should be used for pointer position */
  21451. this.cameraToUseForPointers = null;
  21452. this._startingPointerPosition = new BABYLON.Vector2(0, 0);
  21453. this._previousStartingPointerPosition = new BABYLON.Vector2(0, 0);
  21454. this._startingPointerTime = 0;
  21455. this._previousStartingPointerTime = 0;
  21456. // Deterministic lockstep
  21457. this._timeAccumulator = 0;
  21458. this._currentStepId = 0;
  21459. this._currentInternalStep = 0;
  21460. // Keyboard
  21461. /**
  21462. * This observable event is triggered when any keyboard event si raised and registered during Scene.attachControl()
  21463. * You have the possibility to skip the process and the call to onKeyboardObservable by setting KeyboardInfoPre.skipOnPointerObservable to true
  21464. */
  21465. this.onPreKeyboardObservable = new BABYLON.Observable();
  21466. /**
  21467. * Observable event triggered each time an keyboard event is received from the hosting window
  21468. */
  21469. this.onKeyboardObservable = new BABYLON.Observable();
  21470. // Coordinate system
  21471. /**
  21472. * use right-handed coordinate system on this scene.
  21473. * @type {boolean}
  21474. */
  21475. this._useRightHandedSystem = false;
  21476. // Fog
  21477. this._fogEnabled = true;
  21478. this._fogMode = Scene.FOGMODE_NONE;
  21479. this.fogColor = new BABYLON.Color3(0.2, 0.2, 0.3);
  21480. this.fogDensity = 0.1;
  21481. this.fogStart = 0;
  21482. this.fogEnd = 1000.0;
  21483. // Lights
  21484. /**
  21485. * is shadow enabled on this scene.
  21486. * @type {boolean}
  21487. */
  21488. this._shadowsEnabled = true;
  21489. /**
  21490. * is light enabled on this scene.
  21491. * @type {boolean}
  21492. */
  21493. this._lightsEnabled = true;
  21494. /**
  21495. * All of the lights added to this scene.
  21496. * @see BABYLON.Light
  21497. * @type {BABYLON.Light[]}
  21498. */
  21499. this.lights = new Array();
  21500. // Cameras
  21501. /** All of the cameras added to this scene. */
  21502. this.cameras = new Array();
  21503. /** All of the active cameras added to this scene. */
  21504. this.activeCameras = new Array();
  21505. // Meshes
  21506. /**
  21507. * All of the tranform nodes added to this scene.
  21508. * @see BABYLON.TransformNode
  21509. * @type {BABYLON.TransformNode[]}
  21510. */
  21511. this.transformNodes = new Array();
  21512. /**
  21513. * All of the (abstract) meshes added to this scene.
  21514. * @see BABYLON.AbstractMesh
  21515. * @type {BABYLON.AbstractMesh[]}
  21516. */
  21517. this.meshes = new Array();
  21518. /**
  21519. * All of the animation groups added to this scene.
  21520. * @see BABYLON.AnimationGroup
  21521. * @type {BABYLON.AnimationGroup[]}
  21522. */
  21523. this.animationGroups = new Array();
  21524. // Geometries
  21525. this._geometries = new Array();
  21526. this.materials = new Array();
  21527. this.multiMaterials = new Array();
  21528. // Textures
  21529. this._texturesEnabled = true;
  21530. this.textures = new Array();
  21531. // Particles
  21532. this.particlesEnabled = true;
  21533. this.particleSystems = new Array();
  21534. // Sprites
  21535. this.spritesEnabled = true;
  21536. this.spriteManagers = new Array();
  21537. /**
  21538. * The list of layers (background and foreground) of the scene.
  21539. */
  21540. this.layers = new Array();
  21541. /**
  21542. * The list of effect layers (highlights/glow) contained in the scene.
  21543. */
  21544. this.effectLayers = new Array();
  21545. // Skeletons
  21546. this._skeletonsEnabled = true;
  21547. this.skeletons = new Array();
  21548. // Morph targets
  21549. this.morphTargetManagers = new Array();
  21550. // Lens flares
  21551. this.lensFlaresEnabled = true;
  21552. this.lensFlareSystems = new Array();
  21553. // Collisions
  21554. this.collisionsEnabled = true;
  21555. /** Defines the gravity applied to this scene */
  21556. this.gravity = new BABYLON.Vector3(0, -9.807, 0);
  21557. // Postprocesses
  21558. this.postProcesses = new Array();
  21559. this.postProcessesEnabled = true;
  21560. // Customs render targets
  21561. this.renderTargetsEnabled = true;
  21562. this.dumpNextRenderTargets = false;
  21563. this.customRenderTargets = new Array();
  21564. // Imported meshes
  21565. this.importedMeshesFiles = new Array();
  21566. // Probes
  21567. this.probesEnabled = true;
  21568. this.reflectionProbes = new Array();
  21569. this._actionManagers = new Array();
  21570. this._meshesForIntersections = new BABYLON.SmartArrayNoDuplicate(256);
  21571. // Procedural textures
  21572. this.proceduralTexturesEnabled = true;
  21573. this._proceduralTextures = new Array();
  21574. this.soundTracks = new Array();
  21575. this._audioEnabled = true;
  21576. this._headphone = false;
  21577. // Performance counters
  21578. this._totalVertices = new BABYLON.PerfCounter();
  21579. this._activeIndices = new BABYLON.PerfCounter();
  21580. this._activeParticles = new BABYLON.PerfCounter();
  21581. this._activeBones = new BABYLON.PerfCounter();
  21582. this._animationTime = 0;
  21583. this.animationTimeScale = 1;
  21584. this._renderId = 0;
  21585. this._executeWhenReadyTimeoutId = -1;
  21586. this._intermediateRendering = false;
  21587. this._viewUpdateFlag = -1;
  21588. this._projectionUpdateFlag = -1;
  21589. this._alternateViewUpdateFlag = -1;
  21590. this._alternateProjectionUpdateFlag = -1;
  21591. this._toBeDisposed = new BABYLON.SmartArray(256);
  21592. this._activeRequests = new Array();
  21593. this._pendingData = new Array();
  21594. this._isDisposed = false;
  21595. this.dispatchAllSubMeshesOfActiveMeshes = false;
  21596. this._activeMeshes = new BABYLON.SmartArray(256);
  21597. this._processedMaterials = new BABYLON.SmartArray(256);
  21598. this._renderTargets = new BABYLON.SmartArrayNoDuplicate(256);
  21599. this._activeParticleSystems = new BABYLON.SmartArray(256);
  21600. this._activeSkeletons = new BABYLON.SmartArrayNoDuplicate(32);
  21601. this._softwareSkinnedMeshes = new BABYLON.SmartArrayNoDuplicate(32);
  21602. this._activeAnimatables = new Array();
  21603. this._transformMatrix = BABYLON.Matrix.Zero();
  21604. this._useAlternateCameraConfiguration = false;
  21605. this._alternateRendering = false;
  21606. this.requireLightSorting = false;
  21607. this._depthRenderer = {};
  21608. this._activeMeshesFrozen = false;
  21609. this._tempPickingRay = BABYLON.Ray ? BABYLON.Ray.Zero() : null;
  21610. this._engine = engine || BABYLON.Engine.LastCreatedEngine;
  21611. this._engine.scenes.push(this);
  21612. this._uid = null;
  21613. this._renderingManager = new BABYLON.RenderingManager(this);
  21614. this.postProcessManager = new BABYLON.PostProcessManager(this);
  21615. if (BABYLON.OutlineRenderer) {
  21616. this._outlineRenderer = new BABYLON.OutlineRenderer(this);
  21617. }
  21618. if (BABYLON.Tools.IsWindowObjectExist()) {
  21619. this.attachControl();
  21620. }
  21621. //simplification queue
  21622. if (BABYLON.SimplificationQueue) {
  21623. this.simplificationQueue = new BABYLON.SimplificationQueue();
  21624. }
  21625. //collision coordinator initialization. For now legacy per default.
  21626. this.workerCollisions = false; //(!!Worker && (!!BABYLON.CollisionWorker || BABYLON.WorkerIncluded));
  21627. // Uniform Buffer
  21628. this._createUbo();
  21629. // Default Image processing definition.
  21630. this._imageProcessingConfiguration = new BABYLON.ImageProcessingConfiguration();
  21631. }
  21632. Object.defineProperty(Scene, "FOGMODE_NONE", {
  21633. /** The fog is deactivated */
  21634. get: function () {
  21635. return Scene._FOGMODE_NONE;
  21636. },
  21637. enumerable: true,
  21638. configurable: true
  21639. });
  21640. Object.defineProperty(Scene, "FOGMODE_EXP", {
  21641. /** The fog density is following an exponential function */
  21642. get: function () {
  21643. return Scene._FOGMODE_EXP;
  21644. },
  21645. enumerable: true,
  21646. configurable: true
  21647. });
  21648. Object.defineProperty(Scene, "FOGMODE_EXP2", {
  21649. /** The fog density is following an exponential function faster than FOGMODE_EXP */
  21650. get: function () {
  21651. return Scene._FOGMODE_EXP2;
  21652. },
  21653. enumerable: true,
  21654. configurable: true
  21655. });
  21656. Object.defineProperty(Scene, "FOGMODE_LINEAR", {
  21657. /** The fog density is following a linear function. */
  21658. get: function () {
  21659. return Scene._FOGMODE_LINEAR;
  21660. },
  21661. enumerable: true,
  21662. configurable: true
  21663. });
  21664. Object.defineProperty(Scene.prototype, "environmentTexture", {
  21665. /**
  21666. * Texture used in all pbr material as the reflection texture.
  21667. * As in the majority of the scene they are the same (exception for multi room and so on),
  21668. * this is easier to reference from here than from all the materials.
  21669. */
  21670. get: function () {
  21671. return this._environmentTexture;
  21672. },
  21673. /**
  21674. * Texture used in all pbr material as the reflection texture.
  21675. * As in the majority of the scene they are the same (exception for multi room and so on),
  21676. * this is easier to set here than in all the materials.
  21677. */
  21678. set: function (value) {
  21679. if (this._environmentTexture === value) {
  21680. return;
  21681. }
  21682. this._environmentTexture = value;
  21683. this.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  21684. },
  21685. enumerable: true,
  21686. configurable: true
  21687. });
  21688. Object.defineProperty(Scene.prototype, "imageProcessingConfiguration", {
  21689. /**
  21690. * Default image processing configuration used either in the rendering
  21691. * Forward main pass or through the imageProcessingPostProcess if present.
  21692. * As in the majority of the scene they are the same (exception for multi camera),
  21693. * this is easier to reference from here than from all the materials and post process.
  21694. *
  21695. * No setter as we it is a shared configuration, you can set the values instead.
  21696. */
  21697. get: function () {
  21698. return this._imageProcessingConfiguration;
  21699. },
  21700. enumerable: true,
  21701. configurable: true
  21702. });
  21703. Object.defineProperty(Scene.prototype, "forcePointsCloud", {
  21704. get: function () {
  21705. return this._forcePointsCloud;
  21706. },
  21707. set: function (value) {
  21708. if (this._forcePointsCloud === value) {
  21709. return;
  21710. }
  21711. this._forcePointsCloud = value;
  21712. this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
  21713. },
  21714. enumerable: true,
  21715. configurable: true
  21716. });
  21717. Object.defineProperty(Scene.prototype, "onDispose", {
  21718. /** A function to be executed when this scene is disposed. */
  21719. set: function (callback) {
  21720. if (this._onDisposeObserver) {
  21721. this.onDisposeObservable.remove(this._onDisposeObserver);
  21722. }
  21723. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  21724. },
  21725. enumerable: true,
  21726. configurable: true
  21727. });
  21728. Object.defineProperty(Scene.prototype, "beforeRender", {
  21729. /** A function to be executed before rendering this scene */
  21730. set: function (callback) {
  21731. if (this._onBeforeRenderObserver) {
  21732. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  21733. }
  21734. if (callback) {
  21735. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  21736. }
  21737. },
  21738. enumerable: true,
  21739. configurable: true
  21740. });
  21741. Object.defineProperty(Scene.prototype, "afterRender", {
  21742. /** A function to be executed after rendering this scene */
  21743. set: function (callback) {
  21744. if (this._onAfterRenderObserver) {
  21745. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  21746. }
  21747. if (callback) {
  21748. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  21749. }
  21750. },
  21751. enumerable: true,
  21752. configurable: true
  21753. });
  21754. Object.defineProperty(Scene.prototype, "beforeCameraRender", {
  21755. set: function (callback) {
  21756. if (this._onBeforeCameraRenderObserver) {
  21757. this.onBeforeCameraRenderObservable.remove(this._onBeforeCameraRenderObserver);
  21758. }
  21759. this._onBeforeCameraRenderObserver = this.onBeforeCameraRenderObservable.add(callback);
  21760. },
  21761. enumerable: true,
  21762. configurable: true
  21763. });
  21764. Object.defineProperty(Scene.prototype, "afterCameraRender", {
  21765. set: function (callback) {
  21766. if (this._onAfterCameraRenderObserver) {
  21767. this.onAfterCameraRenderObservable.remove(this._onAfterCameraRenderObserver);
  21768. }
  21769. this._onAfterCameraRenderObserver = this.onAfterCameraRenderObservable.add(callback);
  21770. },
  21771. enumerable: true,
  21772. configurable: true
  21773. });
  21774. Object.defineProperty(Scene.prototype, "gamepadManager", {
  21775. get: function () {
  21776. if (!this._gamepadManager) {
  21777. this._gamepadManager = new BABYLON.GamepadManager(this);
  21778. }
  21779. return this._gamepadManager;
  21780. },
  21781. enumerable: true,
  21782. configurable: true
  21783. });
  21784. Object.defineProperty(Scene.prototype, "unTranslatedPointer", {
  21785. get: function () {
  21786. return new BABYLON.Vector2(this._unTranslatedPointerX, this._unTranslatedPointerY);
  21787. },
  21788. enumerable: true,
  21789. configurable: true
  21790. });
  21791. Object.defineProperty(Scene.prototype, "useRightHandedSystem", {
  21792. get: function () {
  21793. return this._useRightHandedSystem;
  21794. },
  21795. set: function (value) {
  21796. if (this._useRightHandedSystem === value) {
  21797. return;
  21798. }
  21799. this._useRightHandedSystem = value;
  21800. this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
  21801. },
  21802. enumerable: true,
  21803. configurable: true
  21804. });
  21805. Scene.prototype.setStepId = function (newStepId) {
  21806. this._currentStepId = newStepId;
  21807. };
  21808. ;
  21809. Scene.prototype.getStepId = function () {
  21810. return this._currentStepId;
  21811. };
  21812. ;
  21813. Scene.prototype.getInternalStep = function () {
  21814. return this._currentInternalStep;
  21815. };
  21816. ;
  21817. Object.defineProperty(Scene.prototype, "fogEnabled", {
  21818. get: function () {
  21819. return this._fogEnabled;
  21820. },
  21821. /**
  21822. * is fog enabled on this scene.
  21823. */
  21824. set: function (value) {
  21825. if (this._fogEnabled === value) {
  21826. return;
  21827. }
  21828. this._fogEnabled = value;
  21829. this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
  21830. },
  21831. enumerable: true,
  21832. configurable: true
  21833. });
  21834. Object.defineProperty(Scene.prototype, "fogMode", {
  21835. get: function () {
  21836. return this._fogMode;
  21837. },
  21838. set: function (value) {
  21839. if (this._fogMode === value) {
  21840. return;
  21841. }
  21842. this._fogMode = value;
  21843. this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
  21844. },
  21845. enumerable: true,
  21846. configurable: true
  21847. });
  21848. Object.defineProperty(Scene.prototype, "shadowsEnabled", {
  21849. get: function () {
  21850. return this._shadowsEnabled;
  21851. },
  21852. set: function (value) {
  21853. if (this._shadowsEnabled === value) {
  21854. return;
  21855. }
  21856. this._shadowsEnabled = value;
  21857. this.markAllMaterialsAsDirty(BABYLON.Material.LightDirtyFlag);
  21858. },
  21859. enumerable: true,
  21860. configurable: true
  21861. });
  21862. Object.defineProperty(Scene.prototype, "lightsEnabled", {
  21863. get: function () {
  21864. return this._lightsEnabled;
  21865. },
  21866. set: function (value) {
  21867. if (this._lightsEnabled === value) {
  21868. return;
  21869. }
  21870. this._lightsEnabled = value;
  21871. this.markAllMaterialsAsDirty(BABYLON.Material.LightDirtyFlag);
  21872. },
  21873. enumerable: true,
  21874. configurable: true
  21875. });
  21876. Object.defineProperty(Scene.prototype, "defaultMaterial", {
  21877. /** The default material used on meshes when no material is affected */
  21878. get: function () {
  21879. if (!this._defaultMaterial) {
  21880. this._defaultMaterial = new BABYLON.StandardMaterial("default material", this);
  21881. }
  21882. return this._defaultMaterial;
  21883. },
  21884. /** The default material used on meshes when no material is affected */
  21885. set: function (value) {
  21886. this._defaultMaterial = value;
  21887. },
  21888. enumerable: true,
  21889. configurable: true
  21890. });
  21891. Object.defineProperty(Scene.prototype, "texturesEnabled", {
  21892. get: function () {
  21893. return this._texturesEnabled;
  21894. },
  21895. set: function (value) {
  21896. if (this._texturesEnabled === value) {
  21897. return;
  21898. }
  21899. this._texturesEnabled = value;
  21900. this.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  21901. },
  21902. enumerable: true,
  21903. configurable: true
  21904. });
  21905. Object.defineProperty(Scene.prototype, "skeletonsEnabled", {
  21906. get: function () {
  21907. return this._skeletonsEnabled;
  21908. },
  21909. set: function (value) {
  21910. if (this._skeletonsEnabled === value) {
  21911. return;
  21912. }
  21913. this._skeletonsEnabled = value;
  21914. this.markAllMaterialsAsDirty(BABYLON.Material.AttributesDirtyFlag);
  21915. },
  21916. enumerable: true,
  21917. configurable: true
  21918. });
  21919. Object.defineProperty(Scene.prototype, "postProcessRenderPipelineManager", {
  21920. get: function () {
  21921. if (!this._postProcessRenderPipelineManager) {
  21922. this._postProcessRenderPipelineManager = new BABYLON.PostProcessRenderPipelineManager();
  21923. }
  21924. return this._postProcessRenderPipelineManager;
  21925. },
  21926. enumerable: true,
  21927. configurable: true
  21928. });
  21929. Object.defineProperty(Scene.prototype, "mainSoundTrack", {
  21930. get: function () {
  21931. if (!this._mainSoundTrack) {
  21932. this._mainSoundTrack = new BABYLON.SoundTrack(this, { mainTrack: true });
  21933. }
  21934. return this._mainSoundTrack;
  21935. },
  21936. enumerable: true,
  21937. configurable: true
  21938. });
  21939. Object.defineProperty(Scene.prototype, "_isAlternateRenderingEnabled", {
  21940. get: function () {
  21941. return this._alternateRendering;
  21942. },
  21943. enumerable: true,
  21944. configurable: true
  21945. });
  21946. Object.defineProperty(Scene.prototype, "frustumPlanes", {
  21947. get: function () {
  21948. return this._frustumPlanes;
  21949. },
  21950. enumerable: true,
  21951. configurable: true
  21952. });
  21953. Object.defineProperty(Scene.prototype, "geometryBufferRenderer", {
  21954. /**
  21955. * Gets the current geometry buffer associated to the scene.
  21956. */
  21957. get: function () {
  21958. return this._geometryBufferRenderer;
  21959. },
  21960. /**
  21961. * Sets the current geometry buffer for the scene.
  21962. */
  21963. set: function (geometryBufferRenderer) {
  21964. if (geometryBufferRenderer && geometryBufferRenderer.isSupported) {
  21965. this._geometryBufferRenderer = geometryBufferRenderer;
  21966. }
  21967. },
  21968. enumerable: true,
  21969. configurable: true
  21970. });
  21971. Object.defineProperty(Scene.prototype, "debugLayer", {
  21972. // Properties
  21973. get: function () {
  21974. if (!this._debugLayer) {
  21975. this._debugLayer = new BABYLON.DebugLayer(this);
  21976. }
  21977. return this._debugLayer;
  21978. },
  21979. enumerable: true,
  21980. configurable: true
  21981. });
  21982. Object.defineProperty(Scene.prototype, "workerCollisions", {
  21983. get: function () {
  21984. return this._workerCollisions;
  21985. },
  21986. set: function (enabled) {
  21987. if (!BABYLON.CollisionCoordinatorLegacy) {
  21988. return;
  21989. }
  21990. enabled = (enabled && !!Worker && !!BABYLON.CollisionWorker);
  21991. this._workerCollisions = enabled;
  21992. if (this.collisionCoordinator) {
  21993. this.collisionCoordinator.destroy();
  21994. }
  21995. this.collisionCoordinator = enabled ? new BABYLON.CollisionCoordinatorWorker() : new BABYLON.CollisionCoordinatorLegacy();
  21996. this.collisionCoordinator.init(this);
  21997. },
  21998. enumerable: true,
  21999. configurable: true
  22000. });
  22001. Object.defineProperty(Scene.prototype, "selectionOctree", {
  22002. get: function () {
  22003. return this._selectionOctree;
  22004. },
  22005. enumerable: true,
  22006. configurable: true
  22007. });
  22008. Object.defineProperty(Scene.prototype, "meshUnderPointer", {
  22009. /**
  22010. * The mesh that is currently under the pointer.
  22011. * @return {BABYLON.AbstractMesh} mesh under the pointer/mouse cursor or null if none.
  22012. */
  22013. get: function () {
  22014. return this._pointerOverMesh;
  22015. },
  22016. enumerable: true,
  22017. configurable: true
  22018. });
  22019. Object.defineProperty(Scene.prototype, "pointerX", {
  22020. /**
  22021. * Current on-screen X position of the pointer
  22022. * @return {number} X position of the pointer
  22023. */
  22024. get: function () {
  22025. return this._pointerX;
  22026. },
  22027. enumerable: true,
  22028. configurable: true
  22029. });
  22030. Object.defineProperty(Scene.prototype, "pointerY", {
  22031. /**
  22032. * Current on-screen Y position of the pointer
  22033. * @return {number} Y position of the pointer
  22034. */
  22035. get: function () {
  22036. return this._pointerY;
  22037. },
  22038. enumerable: true,
  22039. configurable: true
  22040. });
  22041. Scene.prototype.getCachedMaterial = function () {
  22042. return this._cachedMaterial;
  22043. };
  22044. Scene.prototype.getCachedEffect = function () {
  22045. return this._cachedEffect;
  22046. };
  22047. Scene.prototype.getCachedVisibility = function () {
  22048. return this._cachedVisibility;
  22049. };
  22050. Scene.prototype.isCachedMaterialInvalid = function (material, effect, visibility) {
  22051. if (visibility === void 0) { visibility = 1; }
  22052. return this._cachedEffect !== effect || this._cachedMaterial !== material || this._cachedVisibility !== visibility;
  22053. };
  22054. Scene.prototype.getBoundingBoxRenderer = function () {
  22055. if (!this._boundingBoxRenderer) {
  22056. this._boundingBoxRenderer = new BABYLON.BoundingBoxRenderer(this);
  22057. }
  22058. return this._boundingBoxRenderer;
  22059. };
  22060. Scene.prototype.getOutlineRenderer = function () {
  22061. return this._outlineRenderer;
  22062. };
  22063. Scene.prototype.getEngine = function () {
  22064. return this._engine;
  22065. };
  22066. Scene.prototype.getTotalVertices = function () {
  22067. return this._totalVertices.current;
  22068. };
  22069. Object.defineProperty(Scene.prototype, "totalVerticesPerfCounter", {
  22070. get: function () {
  22071. return this._totalVertices;
  22072. },
  22073. enumerable: true,
  22074. configurable: true
  22075. });
  22076. Scene.prototype.getActiveIndices = function () {
  22077. return this._activeIndices.current;
  22078. };
  22079. Object.defineProperty(Scene.prototype, "totalActiveIndicesPerfCounter", {
  22080. get: function () {
  22081. return this._activeIndices;
  22082. },
  22083. enumerable: true,
  22084. configurable: true
  22085. });
  22086. Scene.prototype.getActiveParticles = function () {
  22087. return this._activeParticles.current;
  22088. };
  22089. Object.defineProperty(Scene.prototype, "activeParticlesPerfCounter", {
  22090. get: function () {
  22091. return this._activeParticles;
  22092. },
  22093. enumerable: true,
  22094. configurable: true
  22095. });
  22096. Scene.prototype.getActiveBones = function () {
  22097. return this._activeBones.current;
  22098. };
  22099. Object.defineProperty(Scene.prototype, "activeBonesPerfCounter", {
  22100. get: function () {
  22101. return this._activeBones;
  22102. },
  22103. enumerable: true,
  22104. configurable: true
  22105. });
  22106. // Stats
  22107. Scene.prototype.getInterFramePerfCounter = function () {
  22108. BABYLON.Tools.Warn("getInterFramePerfCounter is deprecated. Please use SceneInstrumentation class");
  22109. return 0;
  22110. };
  22111. Object.defineProperty(Scene.prototype, "interFramePerfCounter", {
  22112. get: function () {
  22113. BABYLON.Tools.Warn("interFramePerfCounter is deprecated. Please use SceneInstrumentation class");
  22114. return null;
  22115. },
  22116. enumerable: true,
  22117. configurable: true
  22118. });
  22119. Scene.prototype.getLastFrameDuration = function () {
  22120. BABYLON.Tools.Warn("getLastFrameDuration is deprecated. Please use SceneInstrumentation class");
  22121. return 0;
  22122. };
  22123. Object.defineProperty(Scene.prototype, "lastFramePerfCounter", {
  22124. get: function () {
  22125. BABYLON.Tools.Warn("lastFramePerfCounter is deprecated. Please use SceneInstrumentation class");
  22126. return null;
  22127. },
  22128. enumerable: true,
  22129. configurable: true
  22130. });
  22131. Scene.prototype.getEvaluateActiveMeshesDuration = function () {
  22132. BABYLON.Tools.Warn("getEvaluateActiveMeshesDuration is deprecated. Please use SceneInstrumentation class");
  22133. return 0;
  22134. };
  22135. Object.defineProperty(Scene.prototype, "evaluateActiveMeshesDurationPerfCounter", {
  22136. get: function () {
  22137. BABYLON.Tools.Warn("evaluateActiveMeshesDurationPerfCounter is deprecated. Please use SceneInstrumentation class");
  22138. return null;
  22139. },
  22140. enumerable: true,
  22141. configurable: true
  22142. });
  22143. Scene.prototype.getActiveMeshes = function () {
  22144. return this._activeMeshes;
  22145. };
  22146. Scene.prototype.getRenderTargetsDuration = function () {
  22147. BABYLON.Tools.Warn("getRenderTargetsDuration is deprecated. Please use SceneInstrumentation class");
  22148. return 0;
  22149. };
  22150. Scene.prototype.getRenderDuration = function () {
  22151. BABYLON.Tools.Warn("getRenderDuration is deprecated. Please use SceneInstrumentation class");
  22152. return 0;
  22153. };
  22154. Object.defineProperty(Scene.prototype, "renderDurationPerfCounter", {
  22155. get: function () {
  22156. BABYLON.Tools.Warn("renderDurationPerfCounter is deprecated. Please use SceneInstrumentation class");
  22157. return null;
  22158. },
  22159. enumerable: true,
  22160. configurable: true
  22161. });
  22162. Scene.prototype.getParticlesDuration = function () {
  22163. BABYLON.Tools.Warn("getParticlesDuration is deprecated. Please use SceneInstrumentation class");
  22164. return 0;
  22165. };
  22166. Object.defineProperty(Scene.prototype, "particlesDurationPerfCounter", {
  22167. get: function () {
  22168. BABYLON.Tools.Warn("particlesDurationPerfCounter is deprecated. Please use SceneInstrumentation class");
  22169. return null;
  22170. },
  22171. enumerable: true,
  22172. configurable: true
  22173. });
  22174. Scene.prototype.getSpritesDuration = function () {
  22175. BABYLON.Tools.Warn("getSpritesDuration is deprecated. Please use SceneInstrumentation class");
  22176. return 0;
  22177. };
  22178. Object.defineProperty(Scene.prototype, "spriteDuractionPerfCounter", {
  22179. get: function () {
  22180. BABYLON.Tools.Warn("spriteDuractionPerfCounter is deprecated. Please use SceneInstrumentation class");
  22181. return null;
  22182. },
  22183. enumerable: true,
  22184. configurable: true
  22185. });
  22186. Scene.prototype.getAnimationRatio = function () {
  22187. return this._animationRatio;
  22188. };
  22189. Scene.prototype.getRenderId = function () {
  22190. return this._renderId;
  22191. };
  22192. Scene.prototype.incrementRenderId = function () {
  22193. this._renderId++;
  22194. };
  22195. Scene.prototype._updatePointerPosition = function (evt) {
  22196. var canvasRect = this._engine.getRenderingCanvasClientRect();
  22197. if (!canvasRect) {
  22198. return;
  22199. }
  22200. this._pointerX = evt.clientX - canvasRect.left;
  22201. this._pointerY = evt.clientY - canvasRect.top;
  22202. this._unTranslatedPointerX = this._pointerX;
  22203. this._unTranslatedPointerY = this._pointerY;
  22204. };
  22205. Scene.prototype._createUbo = function () {
  22206. this._sceneUbo = new BABYLON.UniformBuffer(this._engine, undefined, true);
  22207. this._sceneUbo.addUniform("viewProjection", 16);
  22208. this._sceneUbo.addUniform("view", 16);
  22209. };
  22210. Scene.prototype._createAlternateUbo = function () {
  22211. this._alternateSceneUbo = new BABYLON.UniformBuffer(this._engine, undefined, true);
  22212. this._alternateSceneUbo.addUniform("viewProjection", 16);
  22213. this._alternateSceneUbo.addUniform("view", 16);
  22214. };
  22215. // Pointers handling
  22216. /**
  22217. * Use this method to simulate a pointer move on a mesh
  22218. * The pickResult parameter can be obtained from a scene.pick or scene.pickWithRay
  22219. * @param pickResult pickingInfo of the object wished to simulate pointer event on
  22220. * @param pointerEventInit pointer event state to be used when simulating the pointer event (eg. pointer id for multitouch)
  22221. */
  22222. Scene.prototype.simulatePointerMove = function (pickResult, pointerEventInit) {
  22223. var evt = new PointerEvent("pointermove", pointerEventInit);
  22224. return this._processPointerMove(pickResult, evt);
  22225. };
  22226. Scene.prototype._processPointerMove = function (pickResult, evt) {
  22227. var canvas = this._engine.getRenderingCanvas();
  22228. if (!canvas) {
  22229. return this;
  22230. }
  22231. if (pickResult && pickResult.hit && pickResult.pickedMesh) {
  22232. this.setPointerOverSprite(null);
  22233. this.setPointerOverMesh(pickResult.pickedMesh);
  22234. if (this._pointerOverMesh && this._pointerOverMesh.actionManager && this._pointerOverMesh.actionManager.hasPointerTriggers) {
  22235. if (this._pointerOverMesh.actionManager.hoverCursor) {
  22236. canvas.style.cursor = this._pointerOverMesh.actionManager.hoverCursor;
  22237. }
  22238. else {
  22239. canvas.style.cursor = this.hoverCursor;
  22240. }
  22241. }
  22242. else {
  22243. canvas.style.cursor = this.defaultCursor;
  22244. }
  22245. }
  22246. else {
  22247. this.setPointerOverMesh(null);
  22248. // Sprites
  22249. pickResult = this.pickSprite(this._unTranslatedPointerX, this._unTranslatedPointerY, this._spritePredicate, false, this.cameraToUseForPointers || undefined);
  22250. if (pickResult && pickResult.hit && pickResult.pickedSprite) {
  22251. this.setPointerOverSprite(pickResult.pickedSprite);
  22252. if (this._pointerOverSprite && this._pointerOverSprite.actionManager && this._pointerOverSprite.actionManager.hoverCursor) {
  22253. canvas.style.cursor = this._pointerOverSprite.actionManager.hoverCursor;
  22254. }
  22255. else {
  22256. canvas.style.cursor = this.hoverCursor;
  22257. }
  22258. }
  22259. else {
  22260. this.setPointerOverSprite(null);
  22261. // Restore pointer
  22262. canvas.style.cursor = this.defaultCursor;
  22263. }
  22264. }
  22265. if (pickResult) {
  22266. if (this.onPointerMove) {
  22267. this.onPointerMove(evt, pickResult);
  22268. }
  22269. if (this.onPointerObservable.hasObservers()) {
  22270. var type = evt.type === "mousewheel" || evt.type === "DOMMouseScroll" ? BABYLON.PointerEventTypes.POINTERWHEEL : BABYLON.PointerEventTypes.POINTERMOVE;
  22271. var pi = new BABYLON.PointerInfo(type, evt, pickResult);
  22272. this.onPointerObservable.notifyObservers(pi, type);
  22273. }
  22274. }
  22275. return this;
  22276. };
  22277. /**
  22278. * Use this method to simulate a pointer down on a mesh
  22279. * The pickResult parameter can be obtained from a scene.pick or scene.pickWithRay
  22280. * @param pickResult pickingInfo of the object wished to simulate pointer event on
  22281. * @param pointerEventInit pointer event state to be used when simulating the pointer event (eg. pointer id for multitouch)
  22282. */
  22283. Scene.prototype.simulatePointerDown = function (pickResult, pointerEventInit) {
  22284. var evt = new PointerEvent("pointerdown", pointerEventInit);
  22285. return this._processPointerDown(pickResult, evt);
  22286. };
  22287. Scene.prototype._processPointerDown = function (pickResult, evt) {
  22288. var _this = this;
  22289. if (pickResult && pickResult.hit && pickResult.pickedMesh) {
  22290. this._pickedDownMesh = pickResult.pickedMesh;
  22291. var actionManager = pickResult.pickedMesh.actionManager;
  22292. if (actionManager) {
  22293. if (actionManager.hasPickTriggers) {
  22294. actionManager.processTrigger(BABYLON.ActionManager.OnPickDownTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  22295. switch (evt.button) {
  22296. case 0:
  22297. actionManager.processTrigger(BABYLON.ActionManager.OnLeftPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  22298. break;
  22299. case 1:
  22300. actionManager.processTrigger(BABYLON.ActionManager.OnCenterPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  22301. break;
  22302. case 2:
  22303. actionManager.processTrigger(BABYLON.ActionManager.OnRightPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  22304. break;
  22305. }
  22306. }
  22307. if (actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnLongPressTrigger)) {
  22308. window.setTimeout(function () {
  22309. 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);
  22310. if (pickResult && pickResult.hit && pickResult.pickedMesh && actionManager) {
  22311. if (_this._totalPointersPressed !== 0 &&
  22312. ((new Date().getTime() - _this._startingPointerTime) > Scene.LongPressDelay) &&
  22313. (Math.abs(_this._startingPointerPosition.x - _this._pointerX) < Scene.DragMovementThreshold &&
  22314. Math.abs(_this._startingPointerPosition.y - _this._pointerY) < Scene.DragMovementThreshold)) {
  22315. _this._startingPointerTime = 0;
  22316. actionManager.processTrigger(BABYLON.ActionManager.OnLongPressTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  22317. }
  22318. }
  22319. }, Scene.LongPressDelay);
  22320. }
  22321. }
  22322. }
  22323. if (pickResult) {
  22324. if (this.onPointerDown) {
  22325. this.onPointerDown(evt, pickResult);
  22326. }
  22327. if (this.onPointerObservable.hasObservers()) {
  22328. var type = BABYLON.PointerEventTypes.POINTERDOWN;
  22329. var pi = new BABYLON.PointerInfo(type, evt, pickResult);
  22330. this.onPointerObservable.notifyObservers(pi, type);
  22331. }
  22332. }
  22333. return this;
  22334. };
  22335. /**
  22336. * Use this method to simulate a pointer up on a mesh
  22337. * The pickResult parameter can be obtained from a scene.pick or scene.pickWithRay
  22338. * @param pickResult pickingInfo of the object wished to simulate pointer event on
  22339. * @param pointerEventInit pointer event state to be used when simulating the pointer event (eg. pointer id for multitouch)
  22340. */
  22341. Scene.prototype.simulatePointerUp = function (pickResult, pointerEventInit) {
  22342. var evt = new PointerEvent("pointerup", pointerEventInit);
  22343. var clickInfo = new ClickInfo();
  22344. clickInfo.singleClick = true;
  22345. clickInfo.ignore = true;
  22346. return this._processPointerUp(pickResult, evt, clickInfo);
  22347. };
  22348. Scene.prototype._processPointerUp = function (pickResult, evt, clickInfo) {
  22349. if (pickResult && pickResult && pickResult.pickedMesh) {
  22350. this._pickedUpMesh = pickResult.pickedMesh;
  22351. if (this._pickedDownMesh === this._pickedUpMesh) {
  22352. if (this.onPointerPick) {
  22353. this.onPointerPick(evt, pickResult);
  22354. }
  22355. if (clickInfo.singleClick && !clickInfo.ignore && this.onPointerObservable.hasObservers()) {
  22356. var type = BABYLON.PointerEventTypes.POINTERPICK;
  22357. var pi = new BABYLON.PointerInfo(type, evt, pickResult);
  22358. this.onPointerObservable.notifyObservers(pi, type);
  22359. }
  22360. }
  22361. if (pickResult.pickedMesh.actionManager) {
  22362. if (clickInfo.ignore) {
  22363. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickUpTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  22364. }
  22365. if (!clickInfo.hasSwiped && !clickInfo.ignore && clickInfo.singleClick) {
  22366. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  22367. }
  22368. if (clickInfo.doubleClick && !clickInfo.ignore && pickResult.pickedMesh.actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger)) {
  22369. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnDoublePickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  22370. }
  22371. }
  22372. }
  22373. if (this._pickedDownMesh &&
  22374. this._pickedDownMesh.actionManager &&
  22375. this._pickedDownMesh.actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnPickOutTrigger) &&
  22376. this._pickedDownMesh !== this._pickedUpMesh) {
  22377. this._pickedDownMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickOutTrigger, BABYLON.ActionEvent.CreateNew(this._pickedDownMesh, evt));
  22378. }
  22379. if (this.onPointerUp) {
  22380. this.onPointerUp(evt, pickResult);
  22381. }
  22382. if (this.onPointerObservable.hasObservers()) {
  22383. if (!clickInfo.ignore) {
  22384. if (!clickInfo.hasSwiped) {
  22385. if (clickInfo.singleClick && this.onPointerObservable.hasSpecificMask(BABYLON.PointerEventTypes.POINTERTAP)) {
  22386. var type = BABYLON.PointerEventTypes.POINTERTAP;
  22387. var pi = new BABYLON.PointerInfo(type, evt, pickResult);
  22388. this.onPointerObservable.notifyObservers(pi, type);
  22389. }
  22390. if (clickInfo.doubleClick && this.onPointerObservable.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP)) {
  22391. var type = BABYLON.PointerEventTypes.POINTERDOUBLETAP;
  22392. var pi = new BABYLON.PointerInfo(type, evt, pickResult);
  22393. this.onPointerObservable.notifyObservers(pi, type);
  22394. }
  22395. }
  22396. }
  22397. else {
  22398. var type = BABYLON.PointerEventTypes.POINTERUP;
  22399. var pi = new BABYLON.PointerInfo(type, evt, pickResult);
  22400. this.onPointerObservable.notifyObservers(pi, type);
  22401. }
  22402. }
  22403. return this;
  22404. };
  22405. /**
  22406. * Attach events to the canvas (To handle actionManagers triggers and raise onPointerMove, onPointerDown and onPointerUp
  22407. * @param attachUp defines if you want to attach events to pointerup
  22408. * @param attachDown defines if you want to attach events to pointerdown
  22409. * @param attachMove defines if you want to attach events to pointermove
  22410. */
  22411. Scene.prototype.attachControl = function (attachUp, attachDown, attachMove) {
  22412. var _this = this;
  22413. if (attachUp === void 0) { attachUp = true; }
  22414. if (attachDown === void 0) { attachDown = true; }
  22415. if (attachMove === void 0) { attachMove = true; }
  22416. this._initActionManager = function (act, clickInfo) {
  22417. if (!_this._meshPickProceed) {
  22418. var pickResult = _this.pick(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this.pointerDownPredicate, false, _this.cameraToUseForPointers);
  22419. _this._currentPickResult = pickResult;
  22420. if (pickResult) {
  22421. act = (pickResult.hit && pickResult.pickedMesh) ? pickResult.pickedMesh.actionManager : null;
  22422. }
  22423. _this._meshPickProceed = true;
  22424. }
  22425. return act;
  22426. };
  22427. this._delayedSimpleClick = function (btn, clickInfo, cb) {
  22428. // double click delay is over and that no double click has been raised since, or the 2 consecutive keys pressed are different
  22429. if ((new Date().getTime() - _this._previousStartingPointerTime > Scene.DoubleClickDelay && !_this._doubleClickOccured) ||
  22430. btn !== _this._previousButtonPressed) {
  22431. _this._doubleClickOccured = false;
  22432. clickInfo.singleClick = true;
  22433. clickInfo.ignore = false;
  22434. cb(clickInfo, _this._currentPickResult);
  22435. }
  22436. };
  22437. this._initClickEvent = function (obs1, obs2, evt, cb) {
  22438. var clickInfo = new ClickInfo();
  22439. _this._currentPickResult = null;
  22440. var act = null;
  22441. var checkPicking = obs1.hasSpecificMask(BABYLON.PointerEventTypes.POINTERPICK) || obs2.hasSpecificMask(BABYLON.PointerEventTypes.POINTERPICK)
  22442. || obs1.hasSpecificMask(BABYLON.PointerEventTypes.POINTERTAP) || obs2.hasSpecificMask(BABYLON.PointerEventTypes.POINTERTAP)
  22443. || obs1.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP) || obs2.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP);
  22444. if (!checkPicking && BABYLON.ActionManager && BABYLON.ActionManager.HasPickTriggers) {
  22445. act = _this._initActionManager(act, clickInfo);
  22446. if (act)
  22447. checkPicking = act.hasPickTriggers;
  22448. }
  22449. if (checkPicking) {
  22450. var btn = evt.button;
  22451. clickInfo.hasSwiped = Math.abs(_this._startingPointerPosition.x - _this._pointerX) > Scene.DragMovementThreshold ||
  22452. Math.abs(_this._startingPointerPosition.y - _this._pointerY) > Scene.DragMovementThreshold;
  22453. if (!clickInfo.hasSwiped) {
  22454. var checkSingleClickImmediately = !Scene.ExclusiveDoubleClickMode;
  22455. if (!checkSingleClickImmediately) {
  22456. checkSingleClickImmediately = !obs1.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP) &&
  22457. !obs2.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP);
  22458. if (checkSingleClickImmediately && !BABYLON.ActionManager.HasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger)) {
  22459. act = _this._initActionManager(act, clickInfo);
  22460. if (act)
  22461. checkSingleClickImmediately = !act.hasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger);
  22462. }
  22463. }
  22464. if (checkSingleClickImmediately) {
  22465. // single click detected if double click delay is over or two different successive keys pressed without exclusive double click or no double click required
  22466. if (new Date().getTime() - _this._previousStartingPointerTime > Scene.DoubleClickDelay ||
  22467. btn !== _this._previousButtonPressed) {
  22468. clickInfo.singleClick = true;
  22469. cb(clickInfo, _this._currentPickResult);
  22470. }
  22471. }
  22472. else {
  22473. // wait that no double click has been raised during the double click delay
  22474. _this._previousDelayedSimpleClickTimeout = _this._delayedSimpleClickTimeout;
  22475. _this._delayedSimpleClickTimeout = window.setTimeout(_this._delayedSimpleClick.bind(_this, btn, clickInfo, cb), Scene.DoubleClickDelay);
  22476. }
  22477. var checkDoubleClick = obs1.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP) ||
  22478. obs2.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP);
  22479. if (!checkDoubleClick && BABYLON.ActionManager.HasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger)) {
  22480. act = _this._initActionManager(act, clickInfo);
  22481. if (act)
  22482. checkDoubleClick = act.hasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger);
  22483. }
  22484. if (checkDoubleClick) {
  22485. // two successive keys pressed are equal, double click delay is not over and double click has not just occurred
  22486. if (btn === _this._previousButtonPressed &&
  22487. new Date().getTime() - _this._previousStartingPointerTime < Scene.DoubleClickDelay &&
  22488. !_this._doubleClickOccured) {
  22489. // pointer has not moved for 2 clicks, it's a double click
  22490. if (!clickInfo.hasSwiped &&
  22491. Math.abs(_this._previousStartingPointerPosition.x - _this._startingPointerPosition.x) < Scene.DragMovementThreshold &&
  22492. Math.abs(_this._previousStartingPointerPosition.y - _this._startingPointerPosition.y) < Scene.DragMovementThreshold) {
  22493. _this._previousStartingPointerTime = 0;
  22494. _this._doubleClickOccured = true;
  22495. clickInfo.doubleClick = true;
  22496. clickInfo.ignore = false;
  22497. if (Scene.ExclusiveDoubleClickMode && _this._previousDelayedSimpleClickTimeout) {
  22498. clearTimeout(_this._previousDelayedSimpleClickTimeout);
  22499. }
  22500. _this._previousDelayedSimpleClickTimeout = _this._delayedSimpleClickTimeout;
  22501. cb(clickInfo, _this._currentPickResult);
  22502. }
  22503. else {
  22504. _this._doubleClickOccured = false;
  22505. _this._previousStartingPointerTime = _this._startingPointerTime;
  22506. _this._previousStartingPointerPosition.x = _this._startingPointerPosition.x;
  22507. _this._previousStartingPointerPosition.y = _this._startingPointerPosition.y;
  22508. _this._previousButtonPressed = btn;
  22509. if (Scene.ExclusiveDoubleClickMode) {
  22510. if (_this._previousDelayedSimpleClickTimeout) {
  22511. clearTimeout(_this._previousDelayedSimpleClickTimeout);
  22512. }
  22513. _this._previousDelayedSimpleClickTimeout = _this._delayedSimpleClickTimeout;
  22514. cb(clickInfo, _this._previousPickResult);
  22515. }
  22516. else {
  22517. cb(clickInfo, _this._currentPickResult);
  22518. }
  22519. }
  22520. }
  22521. else {
  22522. _this._doubleClickOccured = false;
  22523. _this._previousStartingPointerTime = _this._startingPointerTime;
  22524. _this._previousStartingPointerPosition.x = _this._startingPointerPosition.x;
  22525. _this._previousStartingPointerPosition.y = _this._startingPointerPosition.y;
  22526. _this._previousButtonPressed = btn;
  22527. }
  22528. }
  22529. }
  22530. }
  22531. clickInfo.ignore = true;
  22532. cb(clickInfo, _this._currentPickResult);
  22533. };
  22534. this._spritePredicate = function (sprite) {
  22535. return sprite.isPickable && sprite.actionManager && sprite.actionManager.hasPointerTriggers;
  22536. };
  22537. this._onPointerMove = function (evt) {
  22538. _this._updatePointerPosition(evt);
  22539. // PreObservable support
  22540. if (_this.onPrePointerObservable.hasObservers()) {
  22541. var type = evt.type === "mousewheel" || evt.type === "DOMMouseScroll" ? BABYLON.PointerEventTypes.POINTERWHEEL : BABYLON.PointerEventTypes.POINTERMOVE;
  22542. var pi = new BABYLON.PointerInfoPre(type, evt, _this._unTranslatedPointerX, _this._unTranslatedPointerY);
  22543. _this.onPrePointerObservable.notifyObservers(pi, type);
  22544. if (pi.skipOnPointerObservable) {
  22545. return;
  22546. }
  22547. }
  22548. if (!_this.cameraToUseForPointers && !_this.activeCamera) {
  22549. return;
  22550. }
  22551. if (!_this.pointerMovePredicate) {
  22552. _this.pointerMovePredicate = function (mesh) { return mesh.isPickable && mesh.isVisible && mesh.isReady() && mesh.isEnabled() && (mesh.enablePointerMoveEvents || _this.constantlyUpdateMeshUnderPointer || (mesh.actionManager !== null && mesh.actionManager !== undefined)); };
  22553. }
  22554. // Meshes
  22555. var pickResult = _this.pick(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this.pointerMovePredicate, false, _this.cameraToUseForPointers);
  22556. _this._processPointerMove(pickResult, evt);
  22557. };
  22558. this._onPointerDown = function (evt) {
  22559. _this._totalPointersPressed++;
  22560. _this._pickedDownMesh = null;
  22561. _this._meshPickProceed = false;
  22562. _this._updatePointerPosition(evt);
  22563. if (_this.preventDefaultOnPointerDown && canvas) {
  22564. evt.preventDefault();
  22565. canvas.focus();
  22566. }
  22567. // PreObservable support
  22568. if (_this.onPrePointerObservable.hasObservers()) {
  22569. var type = BABYLON.PointerEventTypes.POINTERDOWN;
  22570. var pi = new BABYLON.PointerInfoPre(type, evt, _this._unTranslatedPointerX, _this._unTranslatedPointerY);
  22571. _this.onPrePointerObservable.notifyObservers(pi, type);
  22572. if (pi.skipOnPointerObservable) {
  22573. return;
  22574. }
  22575. }
  22576. if (!_this.cameraToUseForPointers && !_this.activeCamera) {
  22577. return;
  22578. }
  22579. _this._startingPointerPosition.x = _this._pointerX;
  22580. _this._startingPointerPosition.y = _this._pointerY;
  22581. _this._startingPointerTime = new Date().getTime();
  22582. if (!_this.pointerDownPredicate) {
  22583. _this.pointerDownPredicate = function (mesh) {
  22584. return mesh.isPickable && mesh.isVisible && mesh.isReady() && mesh.isEnabled();
  22585. };
  22586. }
  22587. // Meshes
  22588. _this._pickedDownMesh = null;
  22589. var pickResult = _this.pick(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this.pointerDownPredicate, false, _this.cameraToUseForPointers);
  22590. _this._processPointerDown(pickResult, evt);
  22591. // Sprites
  22592. _this._pickedDownSprite = null;
  22593. if (_this.spriteManagers.length > 0) {
  22594. pickResult = _this.pickSprite(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this._spritePredicate, false, _this.cameraToUseForPointers || undefined);
  22595. if (pickResult && pickResult.hit && pickResult.pickedSprite) {
  22596. if (pickResult.pickedSprite.actionManager) {
  22597. _this._pickedDownSprite = pickResult.pickedSprite;
  22598. switch (evt.button) {
  22599. case 0:
  22600. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnLeftPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  22601. break;
  22602. case 1:
  22603. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnCenterPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  22604. break;
  22605. case 2:
  22606. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnRightPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  22607. break;
  22608. }
  22609. if (pickResult.pickedSprite.actionManager) {
  22610. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickDownTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  22611. }
  22612. }
  22613. }
  22614. }
  22615. };
  22616. this._onPointerUp = function (evt) {
  22617. if (_this._totalPointersPressed === 0) {
  22618. return; // So we need to test it the pointer down was pressed before.
  22619. }
  22620. _this._totalPointersPressed--;
  22621. _this._pickedUpMesh = null;
  22622. _this._meshPickProceed = false;
  22623. _this._updatePointerPosition(evt);
  22624. _this._initClickEvent(_this.onPrePointerObservable, _this.onPointerObservable, evt, function (clickInfo, pickResult) {
  22625. // PreObservable support
  22626. if (_this.onPrePointerObservable.hasObservers()) {
  22627. if (!clickInfo.ignore) {
  22628. if (!clickInfo.hasSwiped) {
  22629. if (clickInfo.singleClick && _this.onPrePointerObservable.hasSpecificMask(BABYLON.PointerEventTypes.POINTERTAP)) {
  22630. var type = BABYLON.PointerEventTypes.POINTERTAP;
  22631. var pi = new BABYLON.PointerInfoPre(type, evt, _this._unTranslatedPointerX, _this._unTranslatedPointerY);
  22632. _this.onPrePointerObservable.notifyObservers(pi, type);
  22633. if (pi.skipOnPointerObservable) {
  22634. return;
  22635. }
  22636. }
  22637. if (clickInfo.doubleClick && _this.onPrePointerObservable.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP)) {
  22638. var type = BABYLON.PointerEventTypes.POINTERDOUBLETAP;
  22639. var pi = new BABYLON.PointerInfoPre(type, evt, _this._unTranslatedPointerX, _this._unTranslatedPointerY);
  22640. _this.onPrePointerObservable.notifyObservers(pi, type);
  22641. if (pi.skipOnPointerObservable) {
  22642. return;
  22643. }
  22644. }
  22645. }
  22646. }
  22647. else {
  22648. var type = BABYLON.PointerEventTypes.POINTERUP;
  22649. var pi = new BABYLON.PointerInfoPre(type, evt, _this._unTranslatedPointerX, _this._unTranslatedPointerY);
  22650. _this.onPrePointerObservable.notifyObservers(pi, type);
  22651. if (pi.skipOnPointerObservable) {
  22652. return;
  22653. }
  22654. }
  22655. }
  22656. if (!_this.cameraToUseForPointers && !_this.activeCamera) {
  22657. return;
  22658. }
  22659. if (!_this.pointerUpPredicate) {
  22660. _this.pointerUpPredicate = function (mesh) {
  22661. return mesh.isPickable && mesh.isVisible && mesh.isReady() && mesh.isEnabled();
  22662. };
  22663. }
  22664. // Meshes
  22665. if (!_this._meshPickProceed && (BABYLON.ActionManager && BABYLON.ActionManager.HasTriggers || _this.onPointerObservable.hasObservers())) {
  22666. _this._initActionManager(null, clickInfo);
  22667. }
  22668. if (!pickResult) {
  22669. pickResult = _this._currentPickResult;
  22670. }
  22671. _this._processPointerUp(pickResult, evt, clickInfo);
  22672. // Sprites
  22673. if (_this.spriteManagers.length > 0) {
  22674. var spritePickResult = _this.pickSprite(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this._spritePredicate, false, _this.cameraToUseForPointers || undefined);
  22675. if (spritePickResult) {
  22676. if (spritePickResult.hit && spritePickResult.pickedSprite) {
  22677. if (spritePickResult.pickedSprite.actionManager) {
  22678. spritePickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickUpTrigger, BABYLON.ActionEvent.CreateNewFromSprite(spritePickResult.pickedSprite, _this, evt));
  22679. if (spritePickResult.pickedSprite.actionManager) {
  22680. if (Math.abs(_this._startingPointerPosition.x - _this._pointerX) < Scene.DragMovementThreshold && Math.abs(_this._startingPointerPosition.y - _this._pointerY) < Scene.DragMovementThreshold) {
  22681. spritePickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(spritePickResult.pickedSprite, _this, evt));
  22682. }
  22683. }
  22684. }
  22685. }
  22686. if (_this._pickedDownSprite && _this._pickedDownSprite.actionManager && _this._pickedDownSprite !== spritePickResult.pickedSprite) {
  22687. _this._pickedDownSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickOutTrigger, BABYLON.ActionEvent.CreateNewFromSprite(_this._pickedDownSprite, _this, evt));
  22688. }
  22689. }
  22690. }
  22691. _this._previousPickResult = _this._currentPickResult;
  22692. });
  22693. };
  22694. this._onKeyDown = function (evt) {
  22695. var type = BABYLON.KeyboardEventTypes.KEYDOWN;
  22696. if (_this.onPreKeyboardObservable.hasObservers()) {
  22697. var pi = new BABYLON.KeyboardInfoPre(type, evt);
  22698. _this.onPreKeyboardObservable.notifyObservers(pi, type);
  22699. if (pi.skipOnPointerObservable) {
  22700. return;
  22701. }
  22702. }
  22703. if (_this.onKeyboardObservable.hasObservers()) {
  22704. var pi = new BABYLON.KeyboardInfo(type, evt);
  22705. _this.onKeyboardObservable.notifyObservers(pi, type);
  22706. }
  22707. if (_this.actionManager) {
  22708. _this.actionManager.processTrigger(BABYLON.ActionManager.OnKeyDownTrigger, BABYLON.ActionEvent.CreateNewFromScene(_this, evt));
  22709. }
  22710. };
  22711. this._onKeyUp = function (evt) {
  22712. var type = BABYLON.KeyboardEventTypes.KEYUP;
  22713. if (_this.onPreKeyboardObservable.hasObservers()) {
  22714. var pi = new BABYLON.KeyboardInfoPre(type, evt);
  22715. _this.onPreKeyboardObservable.notifyObservers(pi, type);
  22716. if (pi.skipOnPointerObservable) {
  22717. return;
  22718. }
  22719. }
  22720. if (_this.onKeyboardObservable.hasObservers()) {
  22721. var pi = new BABYLON.KeyboardInfo(type, evt);
  22722. _this.onKeyboardObservable.notifyObservers(pi, type);
  22723. }
  22724. if (_this.actionManager) {
  22725. _this.actionManager.processTrigger(BABYLON.ActionManager.OnKeyUpTrigger, BABYLON.ActionEvent.CreateNewFromScene(_this, evt));
  22726. }
  22727. };
  22728. var engine = this.getEngine();
  22729. this._onCanvasFocusObserver = engine.onCanvasFocusObservable.add(function () {
  22730. if (!canvas) {
  22731. return;
  22732. }
  22733. canvas.addEventListener("keydown", _this._onKeyDown, false);
  22734. canvas.addEventListener("keyup", _this._onKeyUp, false);
  22735. });
  22736. this._onCanvasBlurObserver = engine.onCanvasBlurObservable.add(function () {
  22737. if (!canvas) {
  22738. return;
  22739. }
  22740. canvas.removeEventListener("keydown", _this._onKeyDown);
  22741. canvas.removeEventListener("keyup", _this._onKeyUp);
  22742. });
  22743. var eventPrefix = BABYLON.Tools.GetPointerPrefix();
  22744. var canvas = this._engine.getRenderingCanvas();
  22745. if (!canvas) {
  22746. return;
  22747. }
  22748. if (attachMove) {
  22749. canvas.addEventListener(eventPrefix + "move", this._onPointerMove, false);
  22750. // Wheel
  22751. canvas.addEventListener('mousewheel', this._onPointerMove, false);
  22752. canvas.addEventListener('DOMMouseScroll', this._onPointerMove, false);
  22753. }
  22754. if (attachDown) {
  22755. canvas.addEventListener(eventPrefix + "down", this._onPointerDown, false);
  22756. }
  22757. if (attachUp) {
  22758. window.addEventListener(eventPrefix + "up", this._onPointerUp, false);
  22759. }
  22760. canvas.tabIndex = 1;
  22761. };
  22762. Scene.prototype.detachControl = function () {
  22763. var engine = this.getEngine();
  22764. var eventPrefix = BABYLON.Tools.GetPointerPrefix();
  22765. var canvas = engine.getRenderingCanvas();
  22766. if (!canvas) {
  22767. return;
  22768. }
  22769. canvas.removeEventListener(eventPrefix + "move", this._onPointerMove);
  22770. canvas.removeEventListener(eventPrefix + "down", this._onPointerDown);
  22771. window.removeEventListener(eventPrefix + "up", this._onPointerUp);
  22772. if (this._onCanvasBlurObserver) {
  22773. engine.onCanvasBlurObservable.remove(this._onCanvasBlurObserver);
  22774. }
  22775. if (this._onCanvasFocusObserver) {
  22776. engine.onCanvasFocusObservable.remove(this._onCanvasFocusObserver);
  22777. }
  22778. // Wheel
  22779. canvas.removeEventListener('mousewheel', this._onPointerMove);
  22780. canvas.removeEventListener('DOMMouseScroll', this._onPointerMove);
  22781. // Keyboard
  22782. canvas.removeEventListener("keydown", this._onKeyDown);
  22783. canvas.removeEventListener("keyup", this._onKeyUp);
  22784. // Observables
  22785. this.onKeyboardObservable.clear();
  22786. this.onPreKeyboardObservable.clear();
  22787. this.onPointerObservable.clear();
  22788. this.onPrePointerObservable.clear();
  22789. };
  22790. /**
  22791. * This function will check if the scene can be rendered (textures are loaded, shaders are compiled)
  22792. * Delay loaded resources are not taking in account
  22793. * @return true if all required resources are ready
  22794. */
  22795. Scene.prototype.isReady = function () {
  22796. if (this._isDisposed) {
  22797. return false;
  22798. }
  22799. if (this._pendingData.length > 0) {
  22800. return false;
  22801. }
  22802. var index;
  22803. var engine = this.getEngine();
  22804. // Geometries
  22805. for (index = 0; index < this._geometries.length; index++) {
  22806. var geometry = this._geometries[index];
  22807. if (geometry.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  22808. return false;
  22809. }
  22810. }
  22811. // Meshes
  22812. for (index = 0; index < this.meshes.length; index++) {
  22813. var mesh = this.meshes[index];
  22814. if (!mesh.isEnabled()) {
  22815. continue;
  22816. }
  22817. if (!mesh.subMeshes || mesh.subMeshes.length === 0) {
  22818. continue;
  22819. }
  22820. if (!mesh.isReady(true)) {
  22821. return false;
  22822. }
  22823. // Effect layers
  22824. var hardwareInstancedRendering = mesh.getClassName() === "InstancedMesh" || engine.getCaps().instancedArrays && mesh.instances.length > 0;
  22825. for (var _i = 0, _a = this.effectLayers; _i < _a.length; _i++) {
  22826. var layer = _a[_i];
  22827. if (!layer.hasMesh(mesh)) {
  22828. continue;
  22829. }
  22830. for (var _b = 0, _c = mesh.subMeshes; _b < _c.length; _b++) {
  22831. var subMesh = _c[_b];
  22832. if (!layer.isReady(subMesh, hardwareInstancedRendering)) {
  22833. return false;
  22834. }
  22835. }
  22836. }
  22837. }
  22838. return true;
  22839. };
  22840. Scene.prototype.resetCachedMaterial = function () {
  22841. this._cachedMaterial = null;
  22842. this._cachedEffect = null;
  22843. this._cachedVisibility = null;
  22844. };
  22845. Scene.prototype.registerBeforeRender = function (func) {
  22846. this.onBeforeRenderObservable.add(func);
  22847. };
  22848. Scene.prototype.unregisterBeforeRender = function (func) {
  22849. this.onBeforeRenderObservable.removeCallback(func);
  22850. };
  22851. Scene.prototype.registerAfterRender = function (func) {
  22852. this.onAfterRenderObservable.add(func);
  22853. };
  22854. Scene.prototype.unregisterAfterRender = function (func) {
  22855. this.onAfterRenderObservable.removeCallback(func);
  22856. };
  22857. Scene.prototype._executeOnceBeforeRender = function (func) {
  22858. var _this = this;
  22859. var execFunc = function () {
  22860. func();
  22861. setTimeout(function () {
  22862. _this.unregisterBeforeRender(execFunc);
  22863. });
  22864. };
  22865. this.registerBeforeRender(execFunc);
  22866. };
  22867. /**
  22868. * The provided function will run before render once and will be disposed afterwards.
  22869. * A timeout delay can be provided so that the function will be executed in N ms.
  22870. * The timeout is using the browser's native setTimeout so time percision cannot be guaranteed.
  22871. * @param func The function to be executed.
  22872. * @param timeout optional delay in ms
  22873. */
  22874. Scene.prototype.executeOnceBeforeRender = function (func, timeout) {
  22875. var _this = this;
  22876. if (timeout !== undefined) {
  22877. setTimeout(function () {
  22878. _this._executeOnceBeforeRender(func);
  22879. }, timeout);
  22880. }
  22881. else {
  22882. this._executeOnceBeforeRender(func);
  22883. }
  22884. };
  22885. Scene.prototype._addPendingData = function (data) {
  22886. this._pendingData.push(data);
  22887. };
  22888. Scene.prototype._removePendingData = function (data) {
  22889. var wasLoading = this.isLoading;
  22890. var index = this._pendingData.indexOf(data);
  22891. if (index !== -1) {
  22892. this._pendingData.splice(index, 1);
  22893. }
  22894. if (wasLoading && !this.isLoading) {
  22895. this.onDataLoadedObservable.notifyObservers(this);
  22896. }
  22897. };
  22898. Scene.prototype.getWaitingItemsCount = function () {
  22899. return this._pendingData.length;
  22900. };
  22901. Object.defineProperty(Scene.prototype, "isLoading", {
  22902. get: function () {
  22903. return this._pendingData.length > 0;
  22904. },
  22905. enumerable: true,
  22906. configurable: true
  22907. });
  22908. /**
  22909. * Registers a function to be executed when the scene is ready.
  22910. * @param {Function} func - the function to be executed.
  22911. */
  22912. Scene.prototype.executeWhenReady = function (func) {
  22913. var _this = this;
  22914. this.onReadyObservable.add(func);
  22915. if (this._executeWhenReadyTimeoutId !== -1) {
  22916. return;
  22917. }
  22918. this._executeWhenReadyTimeoutId = setTimeout(function () {
  22919. _this._checkIsReady();
  22920. }, 150);
  22921. };
  22922. /**
  22923. * Returns a promise that resolves when the scene is ready.
  22924. * @returns A promise that resolves when the scene is ready.
  22925. */
  22926. Scene.prototype.whenReadyAsync = function () {
  22927. var _this = this;
  22928. return new Promise(function (resolve) {
  22929. _this.executeWhenReady(function () {
  22930. resolve();
  22931. });
  22932. });
  22933. };
  22934. Scene.prototype._checkIsReady = function () {
  22935. var _this = this;
  22936. if (this.isReady()) {
  22937. this.onReadyObservable.notifyObservers(this);
  22938. this.onReadyObservable.clear();
  22939. this._executeWhenReadyTimeoutId = -1;
  22940. return;
  22941. }
  22942. this._executeWhenReadyTimeoutId = setTimeout(function () {
  22943. _this._checkIsReady();
  22944. }, 150);
  22945. };
  22946. // Animations
  22947. /**
  22948. * Will start the animation sequence of a given target
  22949. * @param target - the target
  22950. * @param {number} from - from which frame should animation start
  22951. * @param {number} to - till which frame should animation run.
  22952. * @param {boolean} [loop] - should the animation loop
  22953. * @param {number} [speedRatio] - the speed in which to run the animation
  22954. * @param {Function} [onAnimationEnd] function to be executed when the animation ended.
  22955. * @param {BABYLON.Animatable} [animatable] an animatable object. If not provided a new one will be created from the given params.
  22956. * Returns {BABYLON.Animatable} the animatable object created for this animation
  22957. * See BABYLON.Animatable
  22958. */
  22959. Scene.prototype.beginAnimation = function (target, from, to, loop, speedRatio, onAnimationEnd, animatable) {
  22960. if (speedRatio === void 0) { speedRatio = 1.0; }
  22961. if (from > to && speedRatio > 0) {
  22962. speedRatio *= -1;
  22963. }
  22964. this.stopAnimation(target);
  22965. if (!animatable) {
  22966. animatable = new BABYLON.Animatable(this, target, from, to, loop, speedRatio, onAnimationEnd);
  22967. }
  22968. // Local animations
  22969. if (target.animations) {
  22970. animatable.appendAnimations(target, target.animations);
  22971. }
  22972. // Children animations
  22973. if (target.getAnimatables) {
  22974. var animatables = target.getAnimatables();
  22975. for (var index = 0; index < animatables.length; index++) {
  22976. this.beginAnimation(animatables[index], from, to, loop, speedRatio, onAnimationEnd, animatable);
  22977. }
  22978. }
  22979. animatable.reset();
  22980. return animatable;
  22981. };
  22982. /**
  22983. * Begin a new animation on a given node
  22984. * @param {BABYLON.Node} node defines the root node where the animation will take place
  22985. * @param {BABYLON.Animation[]} defines the list of animations to start
  22986. * @param {number} from defines the initial value
  22987. * @param {number} to defines the final value
  22988. * @param {boolean} loop defines if you want animation to loop (off by default)
  22989. * @param {number} speedRatio defines the speed ratio to apply to all animations
  22990. * @param onAnimationEnd defines the callback to call when an animation ends (will be called once per node)
  22991. * @returns the list of created animatables
  22992. */
  22993. Scene.prototype.beginDirectAnimation = function (target, animations, from, to, loop, speedRatio, onAnimationEnd) {
  22994. if (speedRatio === undefined) {
  22995. speedRatio = 1.0;
  22996. }
  22997. var animatable = new BABYLON.Animatable(this, target, from, to, loop, speedRatio, onAnimationEnd, animations);
  22998. return animatable;
  22999. };
  23000. /**
  23001. * Begin a new animation on a given node and its hierarchy
  23002. * @param {BABYLON.Node} node defines the root node where the animation will take place
  23003. * @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.
  23004. * @param {BABYLON.Animation[]} defines the list of animations to start
  23005. * @param {number} from defines the initial value
  23006. * @param {number} to defines the final value
  23007. * @param {boolean} loop defines if you want animation to loop (off by default)
  23008. * @param {number} speedRatio defines the speed ratio to apply to all animations
  23009. * @param onAnimationEnd defines the callback to call when an animation ends (will be called once per node)
  23010. * @returns the list of animatables created for all nodes
  23011. */
  23012. Scene.prototype.beginDirectHierarchyAnimation = function (target, directDescendantsOnly, animations, from, to, loop, speedRatio, onAnimationEnd) {
  23013. var children = target.getDescendants(directDescendantsOnly);
  23014. var result = [];
  23015. for (var _i = 0, children_1 = children; _i < children_1.length; _i++) {
  23016. var child = children_1[_i];
  23017. result.push(this.beginDirectAnimation(child, animations, from, to, loop, speedRatio, onAnimationEnd));
  23018. }
  23019. return result;
  23020. };
  23021. Scene.prototype.getAnimatableByTarget = function (target) {
  23022. for (var index = 0; index < this._activeAnimatables.length; index++) {
  23023. if (this._activeAnimatables[index].target === target) {
  23024. return this._activeAnimatables[index];
  23025. }
  23026. }
  23027. return null;
  23028. };
  23029. Object.defineProperty(Scene.prototype, "animatables", {
  23030. get: function () {
  23031. return this._activeAnimatables;
  23032. },
  23033. enumerable: true,
  23034. configurable: true
  23035. });
  23036. /**
  23037. * Will stop the animation of the given target
  23038. * @param target - the target
  23039. * @param animationName - the name of the animation to stop (all animations will be stopped is empty)
  23040. * @see beginAnimation
  23041. */
  23042. Scene.prototype.stopAnimation = function (target, animationName) {
  23043. var animatable = this.getAnimatableByTarget(target);
  23044. if (animatable) {
  23045. animatable.stop(animationName);
  23046. }
  23047. };
  23048. /**
  23049. * Stops and removes all animations that have been applied to the scene
  23050. */
  23051. Scene.prototype.stopAllAnimations = function () {
  23052. if (this._activeAnimatables) {
  23053. for (var i = 0; i < this._activeAnimatables.length; i++) {
  23054. this._activeAnimatables[i].stop();
  23055. }
  23056. this._activeAnimatables = [];
  23057. }
  23058. };
  23059. Scene.prototype._animate = function () {
  23060. if (!this.animationsEnabled || this._activeAnimatables.length === 0) {
  23061. return;
  23062. }
  23063. // Getting time
  23064. var now = BABYLON.Tools.Now;
  23065. if (!this._animationTimeLast) {
  23066. if (this._pendingData.length > 0) {
  23067. return;
  23068. }
  23069. this._animationTimeLast = now;
  23070. }
  23071. var deltaTime = this.useConstantAnimationDeltaTime ? 16.0 : (now - this._animationTimeLast) * this.animationTimeScale;
  23072. this._animationTime += deltaTime;
  23073. this._animationTimeLast = now;
  23074. for (var index = 0; index < this._activeAnimatables.length; index++) {
  23075. this._activeAnimatables[index]._animate(this._animationTime);
  23076. }
  23077. };
  23078. // Matrix
  23079. Scene.prototype._switchToAlternateCameraConfiguration = function (active) {
  23080. this._useAlternateCameraConfiguration = active;
  23081. };
  23082. Scene.prototype.getViewMatrix = function () {
  23083. return this._useAlternateCameraConfiguration ? this._alternateViewMatrix : this._viewMatrix;
  23084. };
  23085. Scene.prototype.getProjectionMatrix = function () {
  23086. return this._useAlternateCameraConfiguration ? this._alternateProjectionMatrix : this._projectionMatrix;
  23087. };
  23088. Scene.prototype.getTransformMatrix = function () {
  23089. return this._useAlternateCameraConfiguration ? this._alternateTransformMatrix : this._transformMatrix;
  23090. };
  23091. Scene.prototype.setTransformMatrix = function (view, projection) {
  23092. if (this._viewUpdateFlag === view.updateFlag && this._projectionUpdateFlag === projection.updateFlag) {
  23093. return;
  23094. }
  23095. this._viewUpdateFlag = view.updateFlag;
  23096. this._projectionUpdateFlag = projection.updateFlag;
  23097. this._viewMatrix = view;
  23098. this._projectionMatrix = projection;
  23099. this._viewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  23100. // Update frustum
  23101. if (!this._frustumPlanes) {
  23102. this._frustumPlanes = BABYLON.Frustum.GetPlanes(this._transformMatrix);
  23103. }
  23104. else {
  23105. BABYLON.Frustum.GetPlanesToRef(this._transformMatrix, this._frustumPlanes);
  23106. }
  23107. if (this.activeCamera && this.activeCamera._alternateCamera) {
  23108. var otherCamera = this.activeCamera._alternateCamera;
  23109. otherCamera.getViewMatrix().multiplyToRef(otherCamera.getProjectionMatrix(), BABYLON.Tmp.Matrix[0]);
  23110. BABYLON.Frustum.GetRightPlaneToRef(BABYLON.Tmp.Matrix[0], this._frustumPlanes[3]); // Replace right plane by second camera right plane
  23111. }
  23112. if (this._sceneUbo.useUbo) {
  23113. this._sceneUbo.updateMatrix("viewProjection", this._transformMatrix);
  23114. this._sceneUbo.updateMatrix("view", this._viewMatrix);
  23115. this._sceneUbo.update();
  23116. }
  23117. };
  23118. Scene.prototype._setAlternateTransformMatrix = function (view, projection) {
  23119. if (this._alternateViewUpdateFlag === view.updateFlag && this._alternateProjectionUpdateFlag === projection.updateFlag) {
  23120. return;
  23121. }
  23122. this._alternateViewUpdateFlag = view.updateFlag;
  23123. this._alternateProjectionUpdateFlag = projection.updateFlag;
  23124. this._alternateViewMatrix = view;
  23125. this._alternateProjectionMatrix = projection;
  23126. if (!this._alternateTransformMatrix) {
  23127. this._alternateTransformMatrix = BABYLON.Matrix.Zero();
  23128. }
  23129. this._alternateViewMatrix.multiplyToRef(this._alternateProjectionMatrix, this._alternateTransformMatrix);
  23130. if (!this._alternateSceneUbo) {
  23131. this._createAlternateUbo();
  23132. }
  23133. if (this._alternateSceneUbo.useUbo) {
  23134. this._alternateSceneUbo.updateMatrix("viewProjection", this._alternateTransformMatrix);
  23135. this._alternateSceneUbo.updateMatrix("view", this._alternateViewMatrix);
  23136. this._alternateSceneUbo.update();
  23137. }
  23138. };
  23139. Scene.prototype.getSceneUniformBuffer = function () {
  23140. return this._useAlternateCameraConfiguration ? this._alternateSceneUbo : this._sceneUbo;
  23141. };
  23142. // Methods
  23143. Scene.prototype.getUniqueId = function () {
  23144. var result = Scene._uniqueIdCounter;
  23145. Scene._uniqueIdCounter++;
  23146. return result;
  23147. };
  23148. Scene.prototype.addMesh = function (newMesh) {
  23149. this.meshes.push(newMesh);
  23150. //notify the collision coordinator
  23151. if (this.collisionCoordinator) {
  23152. this.collisionCoordinator.onMeshAdded(newMesh);
  23153. }
  23154. newMesh._resyncLightSources();
  23155. this.onNewMeshAddedObservable.notifyObservers(newMesh);
  23156. };
  23157. Scene.prototype.removeMesh = function (toRemove) {
  23158. var index = this.meshes.indexOf(toRemove);
  23159. if (index !== -1) {
  23160. // Remove from the scene if mesh found
  23161. this.meshes.splice(index, 1);
  23162. }
  23163. this.onMeshRemovedObservable.notifyObservers(toRemove);
  23164. return index;
  23165. };
  23166. Scene.prototype.addTransformNode = function (newTransformNode) {
  23167. this.transformNodes.push(newTransformNode);
  23168. this.onNewTransformNodeAddedObservable.notifyObservers(newTransformNode);
  23169. };
  23170. Scene.prototype.removeTransformNode = function (toRemove) {
  23171. var index = this.transformNodes.indexOf(toRemove);
  23172. if (index !== -1) {
  23173. // Remove from the scene if found
  23174. this.transformNodes.splice(index, 1);
  23175. }
  23176. this.onTransformNodeRemovedObservable.notifyObservers(toRemove);
  23177. return index;
  23178. };
  23179. Scene.prototype.removeSkeleton = function (toRemove) {
  23180. var index = this.skeletons.indexOf(toRemove);
  23181. if (index !== -1) {
  23182. // Remove from the scene if found
  23183. this.skeletons.splice(index, 1);
  23184. }
  23185. return index;
  23186. };
  23187. Scene.prototype.removeMorphTargetManager = function (toRemove) {
  23188. var index = this.morphTargetManagers.indexOf(toRemove);
  23189. if (index !== -1) {
  23190. // Remove from the scene if found
  23191. this.morphTargetManagers.splice(index, 1);
  23192. }
  23193. return index;
  23194. };
  23195. Scene.prototype.removeLight = function (toRemove) {
  23196. var index = this.lights.indexOf(toRemove);
  23197. if (index !== -1) {
  23198. // Remove from meshes
  23199. for (var _i = 0, _a = this.meshes; _i < _a.length; _i++) {
  23200. var mesh = _a[_i];
  23201. mesh._removeLightSource(toRemove);
  23202. }
  23203. // Remove from the scene if mesh found
  23204. this.lights.splice(index, 1);
  23205. this.sortLightsByPriority();
  23206. }
  23207. this.onLightRemovedObservable.notifyObservers(toRemove);
  23208. return index;
  23209. };
  23210. Scene.prototype.removeCamera = function (toRemove) {
  23211. var index = this.cameras.indexOf(toRemove);
  23212. if (index !== -1) {
  23213. // Remove from the scene if mesh found
  23214. this.cameras.splice(index, 1);
  23215. }
  23216. // Remove from activeCameras
  23217. var index2 = this.activeCameras.indexOf(toRemove);
  23218. if (index2 !== -1) {
  23219. // Remove from the scene if mesh found
  23220. this.activeCameras.splice(index2, 1);
  23221. }
  23222. // Reset the activeCamera
  23223. if (this.activeCamera === toRemove) {
  23224. if (this.cameras.length > 0) {
  23225. this.activeCamera = this.cameras[0];
  23226. }
  23227. else {
  23228. this.activeCamera = null;
  23229. }
  23230. }
  23231. this.onCameraRemovedObservable.notifyObservers(toRemove);
  23232. return index;
  23233. };
  23234. Scene.prototype.removeParticleSystem = function (toRemove) {
  23235. var index = this.particleSystems.indexOf(toRemove);
  23236. if (index !== -1) {
  23237. this.particleSystems.splice(index, 1);
  23238. }
  23239. return index;
  23240. };
  23241. ;
  23242. Scene.prototype.removeAnimation = function (toRemove) {
  23243. var index = this.animations.indexOf(toRemove);
  23244. if (index !== -1) {
  23245. this.animations.splice(index, 1);
  23246. }
  23247. return index;
  23248. };
  23249. ;
  23250. Scene.prototype.removeMultiMaterial = function (toRemove) {
  23251. var index = this.multiMaterials.indexOf(toRemove);
  23252. if (index !== -1) {
  23253. this.multiMaterials.splice(index, 1);
  23254. }
  23255. return index;
  23256. };
  23257. ;
  23258. Scene.prototype.removeMaterial = function (toRemove) {
  23259. var index = this.materials.indexOf(toRemove);
  23260. if (index !== -1) {
  23261. this.materials.splice(index, 1);
  23262. }
  23263. return index;
  23264. };
  23265. ;
  23266. Scene.prototype.removeLensFlareSystem = function (toRemove) {
  23267. var index = this.lensFlareSystems.indexOf(toRemove);
  23268. if (index !== -1) {
  23269. this.lensFlareSystems.splice(index, 1);
  23270. }
  23271. return index;
  23272. };
  23273. ;
  23274. Scene.prototype.removeActionManager = function (toRemove) {
  23275. var index = this._actionManagers.indexOf(toRemove);
  23276. if (index !== -1) {
  23277. this._actionManagers.splice(index, 1);
  23278. }
  23279. return index;
  23280. };
  23281. ;
  23282. Scene.prototype.addLight = function (newLight) {
  23283. this.lights.push(newLight);
  23284. this.sortLightsByPriority();
  23285. // Add light to all meshes (To support if the light is removed and then readded)
  23286. for (var _i = 0, _a = this.meshes; _i < _a.length; _i++) {
  23287. var mesh = _a[_i];
  23288. if (mesh._lightSources.indexOf(newLight) === -1) {
  23289. mesh._lightSources.push(newLight);
  23290. mesh._resyncLightSources();
  23291. }
  23292. }
  23293. this.onNewLightAddedObservable.notifyObservers(newLight);
  23294. };
  23295. Scene.prototype.sortLightsByPriority = function () {
  23296. if (this.requireLightSorting) {
  23297. this.lights.sort(BABYLON.Light.CompareLightsPriority);
  23298. }
  23299. };
  23300. Scene.prototype.addCamera = function (newCamera) {
  23301. this.cameras.push(newCamera);
  23302. this.onNewCameraAddedObservable.notifyObservers(newCamera);
  23303. };
  23304. Scene.prototype.addSkeleton = function (newSkeleton) {
  23305. this.skeletons.push(newSkeleton);
  23306. };
  23307. Scene.prototype.addParticleSystem = function (newParticleSystem) {
  23308. this.particleSystems.push(newParticleSystem);
  23309. };
  23310. Scene.prototype.addAnimation = function (newAnimation) {
  23311. this.animations.push(newAnimation);
  23312. };
  23313. Scene.prototype.addMultiMaterial = function (newMultiMaterial) {
  23314. this.multiMaterials.push(newMultiMaterial);
  23315. };
  23316. Scene.prototype.addMaterial = function (newMaterial) {
  23317. this.materials.push(newMaterial);
  23318. };
  23319. Scene.prototype.addMorphTargetManager = function (newMorphTargetManager) {
  23320. this.morphTargetManagers.push(newMorphTargetManager);
  23321. };
  23322. Scene.prototype.addGeometry = function (newGeometrie) {
  23323. this._geometries.push(newGeometrie);
  23324. };
  23325. Scene.prototype.addLensFlareSystem = function (newLensFlareSystem) {
  23326. this.lensFlareSystems.push(newLensFlareSystem);
  23327. };
  23328. Scene.prototype.addActionManager = function (newActionManager) {
  23329. this._actionManagers.push(newActionManager);
  23330. };
  23331. /**
  23332. * Switch active camera
  23333. * @param {Camera} newCamera - new active camera
  23334. * @param {boolean} attachControl - call attachControl for the new active camera (default: true)
  23335. */
  23336. Scene.prototype.switchActiveCamera = function (newCamera, attachControl) {
  23337. if (attachControl === void 0) { attachControl = true; }
  23338. var canvas = this._engine.getRenderingCanvas();
  23339. if (!canvas) {
  23340. return;
  23341. }
  23342. if (this.activeCamera) {
  23343. this.activeCamera.detachControl(canvas);
  23344. }
  23345. this.activeCamera = newCamera;
  23346. if (attachControl) {
  23347. newCamera.attachControl(canvas);
  23348. }
  23349. };
  23350. /**
  23351. * sets the active camera of the scene using its ID
  23352. * @param {string} id - the camera's ID
  23353. * @return {BABYLON.Camera|null} the new active camera or null if none found.
  23354. * @see activeCamera
  23355. */
  23356. Scene.prototype.setActiveCameraByID = function (id) {
  23357. var camera = this.getCameraByID(id);
  23358. if (camera) {
  23359. this.activeCamera = camera;
  23360. return camera;
  23361. }
  23362. return null;
  23363. };
  23364. /**
  23365. * sets the active camera of the scene using its name
  23366. * @param {string} name - the camera's name
  23367. * @return {BABYLON.Camera|null} the new active camera or null if none found.
  23368. * @see activeCamera
  23369. */
  23370. Scene.prototype.setActiveCameraByName = function (name) {
  23371. var camera = this.getCameraByName(name);
  23372. if (camera) {
  23373. this.activeCamera = camera;
  23374. return camera;
  23375. }
  23376. return null;
  23377. };
  23378. /**
  23379. * get an animation group using its name
  23380. * @param {string} the material's name
  23381. * @return {BABYLON.AnimationGroup|null} the animation group or null if none found.
  23382. */
  23383. Scene.prototype.getAnimationGroupByName = function (name) {
  23384. for (var index = 0; index < this.animationGroups.length; index++) {
  23385. if (this.animationGroups[index].name === name) {
  23386. return this.animationGroups[index];
  23387. }
  23388. }
  23389. return null;
  23390. };
  23391. /**
  23392. * get a material using its id
  23393. * @param {string} the material's ID
  23394. * @return {BABYLON.Material|null} the material or null if none found.
  23395. */
  23396. Scene.prototype.getMaterialByID = function (id) {
  23397. for (var index = 0; index < this.materials.length; index++) {
  23398. if (this.materials[index].id === id) {
  23399. return this.materials[index];
  23400. }
  23401. }
  23402. return null;
  23403. };
  23404. /**
  23405. * get a material using its name
  23406. * @param {string} the material's name
  23407. * @return {BABYLON.Material|null} the material or null if none found.
  23408. */
  23409. Scene.prototype.getMaterialByName = function (name) {
  23410. for (var index = 0; index < this.materials.length; index++) {
  23411. if (this.materials[index].name === name) {
  23412. return this.materials[index];
  23413. }
  23414. }
  23415. return null;
  23416. };
  23417. Scene.prototype.getLensFlareSystemByName = function (name) {
  23418. for (var index = 0; index < this.lensFlareSystems.length; index++) {
  23419. if (this.lensFlareSystems[index].name === name) {
  23420. return this.lensFlareSystems[index];
  23421. }
  23422. }
  23423. return null;
  23424. };
  23425. Scene.prototype.getLensFlareSystemByID = function (id) {
  23426. for (var index = 0; index < this.lensFlareSystems.length; index++) {
  23427. if (this.lensFlareSystems[index].id === id) {
  23428. return this.lensFlareSystems[index];
  23429. }
  23430. }
  23431. return null;
  23432. };
  23433. Scene.prototype.getCameraByID = function (id) {
  23434. for (var index = 0; index < this.cameras.length; index++) {
  23435. if (this.cameras[index].id === id) {
  23436. return this.cameras[index];
  23437. }
  23438. }
  23439. return null;
  23440. };
  23441. Scene.prototype.getCameraByUniqueID = function (uniqueId) {
  23442. for (var index = 0; index < this.cameras.length; index++) {
  23443. if (this.cameras[index].uniqueId === uniqueId) {
  23444. return this.cameras[index];
  23445. }
  23446. }
  23447. return null;
  23448. };
  23449. /**
  23450. * get a camera using its name
  23451. * @param {string} the camera's name
  23452. * @return {BABYLON.Camera|null} the camera or null if none found.
  23453. */
  23454. Scene.prototype.getCameraByName = function (name) {
  23455. for (var index = 0; index < this.cameras.length; index++) {
  23456. if (this.cameras[index].name === name) {
  23457. return this.cameras[index];
  23458. }
  23459. }
  23460. return null;
  23461. };
  23462. /**
  23463. * get a bone using its id
  23464. * @param {string} the bone's id
  23465. * @return {BABYLON.Bone|null} the bone or null if not found
  23466. */
  23467. Scene.prototype.getBoneByID = function (id) {
  23468. for (var skeletonIndex = 0; skeletonIndex < this.skeletons.length; skeletonIndex++) {
  23469. var skeleton = this.skeletons[skeletonIndex];
  23470. for (var boneIndex = 0; boneIndex < skeleton.bones.length; boneIndex++) {
  23471. if (skeleton.bones[boneIndex].id === id) {
  23472. return skeleton.bones[boneIndex];
  23473. }
  23474. }
  23475. }
  23476. return null;
  23477. };
  23478. /**
  23479. * get a bone using its id
  23480. * @param {string} the bone's name
  23481. * @return {BABYLON.Bone|null} the bone or null if not found
  23482. */
  23483. Scene.prototype.getBoneByName = function (name) {
  23484. for (var skeletonIndex = 0; skeletonIndex < this.skeletons.length; skeletonIndex++) {
  23485. var skeleton = this.skeletons[skeletonIndex];
  23486. for (var boneIndex = 0; boneIndex < skeleton.bones.length; boneIndex++) {
  23487. if (skeleton.bones[boneIndex].name === name) {
  23488. return skeleton.bones[boneIndex];
  23489. }
  23490. }
  23491. }
  23492. return null;
  23493. };
  23494. /**
  23495. * get a light node using its name
  23496. * @param {string} the light's name
  23497. * @return {BABYLON.Light|null} the light or null if none found.
  23498. */
  23499. Scene.prototype.getLightByName = function (name) {
  23500. for (var index = 0; index < this.lights.length; index++) {
  23501. if (this.lights[index].name === name) {
  23502. return this.lights[index];
  23503. }
  23504. }
  23505. return null;
  23506. };
  23507. /**
  23508. * get a light node using its ID
  23509. * @param {string} the light's id
  23510. * @return {BABYLON.Light|null} the light or null if none found.
  23511. */
  23512. Scene.prototype.getLightByID = function (id) {
  23513. for (var index = 0; index < this.lights.length; index++) {
  23514. if (this.lights[index].id === id) {
  23515. return this.lights[index];
  23516. }
  23517. }
  23518. return null;
  23519. };
  23520. /**
  23521. * get a light node using its scene-generated unique ID
  23522. * @param {number} the light's unique id
  23523. * @return {BABYLON.Light|null} the light or null if none found.
  23524. */
  23525. Scene.prototype.getLightByUniqueID = function (uniqueId) {
  23526. for (var index = 0; index < this.lights.length; index++) {
  23527. if (this.lights[index].uniqueId === uniqueId) {
  23528. return this.lights[index];
  23529. }
  23530. }
  23531. return null;
  23532. };
  23533. /**
  23534. * get a particle system by id
  23535. * @param id {number} the particle system id
  23536. * @return {BABYLON.IParticleSystem|null} the corresponding system or null if none found.
  23537. */
  23538. Scene.prototype.getParticleSystemByID = function (id) {
  23539. for (var index = 0; index < this.particleSystems.length; index++) {
  23540. if (this.particleSystems[index].id === id) {
  23541. return this.particleSystems[index];
  23542. }
  23543. }
  23544. return null;
  23545. };
  23546. /**
  23547. * get a geometry using its ID
  23548. * @param {string} the geometry's id
  23549. * @return {BABYLON.Geometry|null} the geometry or null if none found.
  23550. */
  23551. Scene.prototype.getGeometryByID = function (id) {
  23552. for (var index = 0; index < this._geometries.length; index++) {
  23553. if (this._geometries[index].id === id) {
  23554. return this._geometries[index];
  23555. }
  23556. }
  23557. return null;
  23558. };
  23559. /**
  23560. * add a new geometry to this scene.
  23561. * @param {BABYLON.Geometry} geometry - the geometry to be added to the scene.
  23562. * @param {boolean} [force] - force addition, even if a geometry with this ID already exists
  23563. * @return {boolean} was the geometry added or not
  23564. */
  23565. Scene.prototype.pushGeometry = function (geometry, force) {
  23566. if (!force && this.getGeometryByID(geometry.id)) {
  23567. return false;
  23568. }
  23569. this._geometries.push(geometry);
  23570. //notify the collision coordinator
  23571. if (this.collisionCoordinator) {
  23572. this.collisionCoordinator.onGeometryAdded(geometry);
  23573. }
  23574. this.onNewGeometryAddedObservable.notifyObservers(geometry);
  23575. return true;
  23576. };
  23577. /**
  23578. * Removes an existing geometry
  23579. * @param {BABYLON.Geometry} geometry - the geometry to be removed from the scene.
  23580. * @return {boolean} was the geometry removed or not
  23581. */
  23582. Scene.prototype.removeGeometry = function (geometry) {
  23583. var index = this._geometries.indexOf(geometry);
  23584. if (index > -1) {
  23585. this._geometries.splice(index, 1);
  23586. //notify the collision coordinator
  23587. if (this.collisionCoordinator) {
  23588. this.collisionCoordinator.onGeometryDeleted(geometry);
  23589. }
  23590. this.onGeometryRemovedObservable.notifyObservers(geometry);
  23591. return true;
  23592. }
  23593. return false;
  23594. };
  23595. Scene.prototype.getGeometries = function () {
  23596. return this._geometries;
  23597. };
  23598. /**
  23599. * Get the first added mesh found of a given ID
  23600. * @param {string} id - the id to search for
  23601. * @return {BABYLON.AbstractMesh|null} the mesh found or null if not found at all.
  23602. */
  23603. Scene.prototype.getMeshByID = function (id) {
  23604. for (var index = 0; index < this.meshes.length; index++) {
  23605. if (this.meshes[index].id === id) {
  23606. return this.meshes[index];
  23607. }
  23608. }
  23609. return null;
  23610. };
  23611. Scene.prototype.getMeshesByID = function (id) {
  23612. return this.meshes.filter(function (m) {
  23613. return m.id === id;
  23614. });
  23615. };
  23616. /**
  23617. * Get the first added transform node found of a given ID
  23618. * @param {string} id - the id to search for
  23619. * @return {BABYLON.TransformNode|null} the transform node found or null if not found at all.
  23620. */
  23621. Scene.prototype.getTransformNodeByID = function (id) {
  23622. for (var index = 0; index < this.transformNodes.length; index++) {
  23623. if (this.transformNodes[index].id === id) {
  23624. return this.transformNodes[index];
  23625. }
  23626. }
  23627. return null;
  23628. };
  23629. Scene.prototype.getTransformNodesByID = function (id) {
  23630. return this.transformNodes.filter(function (m) {
  23631. return m.id === id;
  23632. });
  23633. };
  23634. /**
  23635. * Get a mesh with its auto-generated unique id
  23636. * @param {number} uniqueId - the unique id to search for
  23637. * @return {BABYLON.AbstractMesh|null} the mesh found or null if not found at all.
  23638. */
  23639. Scene.prototype.getMeshByUniqueID = function (uniqueId) {
  23640. for (var index = 0; index < this.meshes.length; index++) {
  23641. if (this.meshes[index].uniqueId === uniqueId) {
  23642. return this.meshes[index];
  23643. }
  23644. }
  23645. return null;
  23646. };
  23647. /**
  23648. * Get a the last added mesh found of a given ID
  23649. * @param {string} id - the id to search for
  23650. * @return {BABYLON.AbstractMesh|null} the mesh found or null if not found at all.
  23651. */
  23652. Scene.prototype.getLastMeshByID = function (id) {
  23653. for (var index = this.meshes.length - 1; index >= 0; index--) {
  23654. if (this.meshes[index].id === id) {
  23655. return this.meshes[index];
  23656. }
  23657. }
  23658. return null;
  23659. };
  23660. /**
  23661. * Get a the last added node (Mesh, Camera, Light) found of a given ID
  23662. * @param {string} id - the id to search for
  23663. * @return {BABYLON.Node|null} the node found or null if not found at all.
  23664. */
  23665. Scene.prototype.getLastEntryByID = function (id) {
  23666. var index;
  23667. for (index = this.meshes.length - 1; index >= 0; index--) {
  23668. if (this.meshes[index].id === id) {
  23669. return this.meshes[index];
  23670. }
  23671. }
  23672. for (index = this.transformNodes.length - 1; index >= 0; index--) {
  23673. if (this.transformNodes[index].id === id) {
  23674. return this.transformNodes[index];
  23675. }
  23676. }
  23677. for (index = this.cameras.length - 1; index >= 0; index--) {
  23678. if (this.cameras[index].id === id) {
  23679. return this.cameras[index];
  23680. }
  23681. }
  23682. for (index = this.lights.length - 1; index >= 0; index--) {
  23683. if (this.lights[index].id === id) {
  23684. return this.lights[index];
  23685. }
  23686. }
  23687. return null;
  23688. };
  23689. Scene.prototype.getNodeByID = function (id) {
  23690. var mesh = this.getMeshByID(id);
  23691. if (mesh) {
  23692. return mesh;
  23693. }
  23694. var light = this.getLightByID(id);
  23695. if (light) {
  23696. return light;
  23697. }
  23698. var camera = this.getCameraByID(id);
  23699. if (camera) {
  23700. return camera;
  23701. }
  23702. var bone = this.getBoneByID(id);
  23703. return bone;
  23704. };
  23705. Scene.prototype.getNodeByName = function (name) {
  23706. var mesh = this.getMeshByName(name);
  23707. if (mesh) {
  23708. return mesh;
  23709. }
  23710. var light = this.getLightByName(name);
  23711. if (light) {
  23712. return light;
  23713. }
  23714. var camera = this.getCameraByName(name);
  23715. if (camera) {
  23716. return camera;
  23717. }
  23718. var bone = this.getBoneByName(name);
  23719. return bone;
  23720. };
  23721. Scene.prototype.getMeshByName = function (name) {
  23722. for (var index = 0; index < this.meshes.length; index++) {
  23723. if (this.meshes[index].name === name) {
  23724. return this.meshes[index];
  23725. }
  23726. }
  23727. return null;
  23728. };
  23729. Scene.prototype.getTransformNodeByName = function (name) {
  23730. for (var index = 0; index < this.transformNodes.length; index++) {
  23731. if (this.transformNodes[index].name === name) {
  23732. return this.transformNodes[index];
  23733. }
  23734. }
  23735. return null;
  23736. };
  23737. Scene.prototype.getSoundByName = function (name) {
  23738. var index;
  23739. if (BABYLON.AudioEngine) {
  23740. for (index = 0; index < this.mainSoundTrack.soundCollection.length; index++) {
  23741. if (this.mainSoundTrack.soundCollection[index].name === name) {
  23742. return this.mainSoundTrack.soundCollection[index];
  23743. }
  23744. }
  23745. for (var sdIndex = 0; sdIndex < this.soundTracks.length; sdIndex++) {
  23746. for (index = 0; index < this.soundTracks[sdIndex].soundCollection.length; index++) {
  23747. if (this.soundTracks[sdIndex].soundCollection[index].name === name) {
  23748. return this.soundTracks[sdIndex].soundCollection[index];
  23749. }
  23750. }
  23751. }
  23752. }
  23753. return null;
  23754. };
  23755. Scene.prototype.getLastSkeletonByID = function (id) {
  23756. for (var index = this.skeletons.length - 1; index >= 0; index--) {
  23757. if (this.skeletons[index].id === id) {
  23758. return this.skeletons[index];
  23759. }
  23760. }
  23761. return null;
  23762. };
  23763. Scene.prototype.getSkeletonById = function (id) {
  23764. for (var index = 0; index < this.skeletons.length; index++) {
  23765. if (this.skeletons[index].id === id) {
  23766. return this.skeletons[index];
  23767. }
  23768. }
  23769. return null;
  23770. };
  23771. Scene.prototype.getSkeletonByName = function (name) {
  23772. for (var index = 0; index < this.skeletons.length; index++) {
  23773. if (this.skeletons[index].name === name) {
  23774. return this.skeletons[index];
  23775. }
  23776. }
  23777. return null;
  23778. };
  23779. Scene.prototype.getMorphTargetManagerById = function (id) {
  23780. for (var index = 0; index < this.morphTargetManagers.length; index++) {
  23781. if (this.morphTargetManagers[index].uniqueId === id) {
  23782. return this.morphTargetManagers[index];
  23783. }
  23784. }
  23785. return null;
  23786. };
  23787. Scene.prototype.isActiveMesh = function (mesh) {
  23788. return (this._activeMeshes.indexOf(mesh) !== -1);
  23789. };
  23790. /**
  23791. * Return a the first highlight layer of the scene with a given name.
  23792. * @param name The name of the highlight layer to look for.
  23793. * @return The highlight layer if found otherwise null.
  23794. */
  23795. Scene.prototype.getHighlightLayerByName = function (name) {
  23796. for (var index = 0; index < this.effectLayers.length; index++) {
  23797. if (this.effectLayers[index].name === name && this.effectLayers[index].getEffectName() === BABYLON.HighlightLayer.EffectName) {
  23798. return this.effectLayers[index];
  23799. }
  23800. }
  23801. return null;
  23802. };
  23803. /**
  23804. * Return a the first highlight layer of the scene with a given name.
  23805. * @param name The name of the highlight layer to look for.
  23806. * @return The highlight layer if found otherwise null.
  23807. */
  23808. Scene.prototype.getGlowLayerByName = function (name) {
  23809. for (var index = 0; index < this.effectLayers.length; index++) {
  23810. if (this.effectLayers[index].name === name && this.effectLayers[index].getEffectName() === BABYLON.GlowLayer.EffectName) {
  23811. return this.effectLayers[index];
  23812. }
  23813. }
  23814. return null;
  23815. };
  23816. Object.defineProperty(Scene.prototype, "uid", {
  23817. /**
  23818. * Return a unique id as a string which can serve as an identifier for the scene
  23819. */
  23820. get: function () {
  23821. if (!this._uid) {
  23822. this._uid = BABYLON.Tools.RandomId();
  23823. }
  23824. return this._uid;
  23825. },
  23826. enumerable: true,
  23827. configurable: true
  23828. });
  23829. /**
  23830. * Add an externaly attached data from its key.
  23831. * This method call will fail and return false, if such key already exists.
  23832. * If you don't care and just want to get the data no matter what, use the more convenient getOrAddExternalDataWithFactory() method.
  23833. * @param key the unique key that identifies the data
  23834. * @param data the data object to associate to the key for this Engine instance
  23835. * @return true if no such key were already present and the data was added successfully, false otherwise
  23836. */
  23837. Scene.prototype.addExternalData = function (key, data) {
  23838. if (!this._externalData) {
  23839. this._externalData = new BABYLON.StringDictionary();
  23840. }
  23841. return this._externalData.add(key, data);
  23842. };
  23843. /**
  23844. * Get an externaly attached data from its key
  23845. * @param key the unique key that identifies the data
  23846. * @return the associated data, if present (can be null), or undefined if not present
  23847. */
  23848. Scene.prototype.getExternalData = function (key) {
  23849. if (!this._externalData) {
  23850. return null;
  23851. }
  23852. return this._externalData.get(key);
  23853. };
  23854. /**
  23855. * Get an externaly attached data from its key, create it using a factory if it's not already present
  23856. * @param key the unique key that identifies the data
  23857. * @param factory the factory that will be called to create the instance if and only if it doesn't exists
  23858. * @return the associated data, can be null if the factory returned null.
  23859. */
  23860. Scene.prototype.getOrAddExternalDataWithFactory = function (key, factory) {
  23861. if (!this._externalData) {
  23862. this._externalData = new BABYLON.StringDictionary();
  23863. }
  23864. return this._externalData.getOrAddWithFactory(key, factory);
  23865. };
  23866. /**
  23867. * Remove an externaly attached data from the Engine instance
  23868. * @param key the unique key that identifies the data
  23869. * @return true if the data was successfully removed, false if it doesn't exist
  23870. */
  23871. Scene.prototype.removeExternalData = function (key) {
  23872. return this._externalData.remove(key);
  23873. };
  23874. Scene.prototype._evaluateSubMesh = function (subMesh, mesh) {
  23875. if (this.dispatchAllSubMeshesOfActiveMeshes || mesh.alwaysSelectAsActiveMesh || mesh.subMeshes.length === 1 || subMesh.isInFrustum(this._frustumPlanes)) {
  23876. if (mesh.showSubMeshesBoundingBox) {
  23877. var boundingInfo = subMesh.getBoundingInfo();
  23878. if (boundingInfo !== null && boundingInfo !== undefined) {
  23879. this.getBoundingBoxRenderer().renderList.push(boundingInfo.boundingBox);
  23880. }
  23881. }
  23882. var material = subMesh.getMaterial();
  23883. if (material !== null && material !== undefined) {
  23884. // Render targets
  23885. if (material.getRenderTargetTextures !== undefined) {
  23886. if (this._processedMaterials.indexOf(material) === -1) {
  23887. this._processedMaterials.push(material);
  23888. this._renderTargets.concatWithNoDuplicate(material.getRenderTargetTextures());
  23889. }
  23890. }
  23891. // Dispatch
  23892. this._activeIndices.addCount(subMesh.indexCount, false);
  23893. this._renderingManager.dispatch(subMesh, mesh, material);
  23894. }
  23895. }
  23896. };
  23897. Scene.prototype._isInIntermediateRendering = function () {
  23898. return this._intermediateRendering;
  23899. };
  23900. Scene.prototype.setActiveMeshCandidateProvider = function (provider) {
  23901. this._activeMeshCandidateProvider = provider;
  23902. };
  23903. Scene.prototype.getActiveMeshCandidateProvider = function () {
  23904. return this._activeMeshCandidateProvider;
  23905. };
  23906. /**
  23907. * Use this function to stop evaluating active meshes. The current list will be keep alive between frames
  23908. */
  23909. Scene.prototype.freezeActiveMeshes = function () {
  23910. this._evaluateActiveMeshes();
  23911. this._activeMeshesFrozen = true;
  23912. return this;
  23913. };
  23914. /**
  23915. * Use this function to restart evaluating active meshes on every frame
  23916. */
  23917. Scene.prototype.unfreezeActiveMeshes = function () {
  23918. this._activeMeshesFrozen = false;
  23919. return this;
  23920. };
  23921. Scene.prototype._evaluateActiveMeshes = function () {
  23922. if (this._activeMeshesFrozen && this._activeMeshes.length) {
  23923. return;
  23924. }
  23925. if (!this.activeCamera) {
  23926. return;
  23927. }
  23928. this.onBeforeActiveMeshesEvaluationObservable.notifyObservers(this);
  23929. this.activeCamera._activeMeshes.reset();
  23930. this._activeMeshes.reset();
  23931. this._renderingManager.reset();
  23932. this._processedMaterials.reset();
  23933. this._activeParticleSystems.reset();
  23934. this._activeSkeletons.reset();
  23935. this._softwareSkinnedMeshes.reset();
  23936. if (this._boundingBoxRenderer) {
  23937. this._boundingBoxRenderer.reset();
  23938. }
  23939. // Meshes
  23940. var meshes;
  23941. var len;
  23942. var checkIsEnabled = true;
  23943. // Determine mesh candidates
  23944. if (this._activeMeshCandidateProvider !== undefined) {
  23945. // Use _activeMeshCandidateProvider
  23946. meshes = this._activeMeshCandidateProvider.getMeshes(this);
  23947. checkIsEnabled = this._activeMeshCandidateProvider.checksIsEnabled === false;
  23948. if (meshes !== undefined) {
  23949. len = meshes.length;
  23950. }
  23951. else {
  23952. len = 0;
  23953. }
  23954. }
  23955. else if (this._selectionOctree !== undefined) {
  23956. // Octree
  23957. var selection = this._selectionOctree.select(this._frustumPlanes);
  23958. meshes = selection.data;
  23959. len = selection.length;
  23960. }
  23961. else {
  23962. // Full scene traversal
  23963. len = this.meshes.length;
  23964. meshes = this.meshes;
  23965. }
  23966. // Check each mesh
  23967. for (var meshIndex = 0, mesh, meshLOD; meshIndex < len; meshIndex++) {
  23968. mesh = meshes[meshIndex];
  23969. if (mesh.isBlocked) {
  23970. continue;
  23971. }
  23972. this._totalVertices.addCount(mesh.getTotalVertices(), false);
  23973. if (!mesh.isReady() || (checkIsEnabled && !mesh.isEnabled())) {
  23974. continue;
  23975. }
  23976. mesh.computeWorldMatrix();
  23977. // Intersections
  23978. if (mesh.actionManager && mesh.actionManager.hasSpecificTriggers([BABYLON.ActionManager.OnIntersectionEnterTrigger, BABYLON.ActionManager.OnIntersectionExitTrigger])) {
  23979. this._meshesForIntersections.pushNoDuplicate(mesh);
  23980. }
  23981. // Switch to current LOD
  23982. meshLOD = mesh.getLOD(this.activeCamera);
  23983. if (meshLOD === undefined || meshLOD === null) {
  23984. continue;
  23985. }
  23986. mesh._preActivate();
  23987. if (mesh.alwaysSelectAsActiveMesh || mesh.isVisible && mesh.visibility > 0 && ((mesh.layerMask & this.activeCamera.layerMask) !== 0) && mesh.isInFrustum(this._frustumPlanes)) {
  23988. this._activeMeshes.push(mesh);
  23989. this.activeCamera._activeMeshes.push(mesh);
  23990. mesh._activate(this._renderId);
  23991. if (meshLOD !== mesh) {
  23992. meshLOD._activate(this._renderId);
  23993. }
  23994. this._activeMesh(mesh, meshLOD);
  23995. }
  23996. }
  23997. this.onAfterActiveMeshesEvaluationObservable.notifyObservers(this);
  23998. // Particle systems
  23999. if (this.particlesEnabled) {
  24000. this.onBeforeParticlesRenderingObservable.notifyObservers(this);
  24001. for (var particleIndex = 0; particleIndex < this.particleSystems.length; particleIndex++) {
  24002. var particleSystem = this.particleSystems[particleIndex];
  24003. if (!particleSystem.isStarted() || !particleSystem.emitter) {
  24004. continue;
  24005. }
  24006. var emitter = particleSystem.emitter;
  24007. if (!emitter.position || emitter.isEnabled()) {
  24008. this._activeParticleSystems.push(particleSystem);
  24009. particleSystem.animate();
  24010. this._renderingManager.dispatchParticles(particleSystem);
  24011. }
  24012. }
  24013. this.onAfterParticlesRenderingObservable.notifyObservers(this);
  24014. }
  24015. };
  24016. Scene.prototype._activeMesh = function (sourceMesh, mesh) {
  24017. if (this.skeletonsEnabled && mesh.skeleton !== null && mesh.skeleton !== undefined) {
  24018. if (this._activeSkeletons.pushNoDuplicate(mesh.skeleton)) {
  24019. mesh.skeleton.prepare();
  24020. }
  24021. if (!mesh.computeBonesUsingShaders) {
  24022. this._softwareSkinnedMeshes.pushNoDuplicate(mesh);
  24023. }
  24024. }
  24025. if (sourceMesh.showBoundingBox || this.forceShowBoundingBoxes) {
  24026. var boundingInfo = sourceMesh.getBoundingInfo();
  24027. this.getBoundingBoxRenderer().renderList.push(boundingInfo.boundingBox);
  24028. }
  24029. if (mesh !== undefined && mesh !== null
  24030. && mesh.subMeshes !== undefined && mesh.subMeshes !== null && mesh.subMeshes.length > 0) {
  24031. // Submeshes Octrees
  24032. var len;
  24033. var subMeshes;
  24034. if (mesh.useOctreeForRenderingSelection && mesh._submeshesOctree !== undefined && mesh._submeshesOctree !== null) {
  24035. var intersections = mesh._submeshesOctree.select(this._frustumPlanes);
  24036. len = intersections.length;
  24037. subMeshes = intersections.data;
  24038. }
  24039. else {
  24040. subMeshes = mesh.subMeshes;
  24041. len = subMeshes.length;
  24042. }
  24043. for (var subIndex = 0, subMesh; subIndex < len; subIndex++) {
  24044. subMesh = subMeshes[subIndex];
  24045. this._evaluateSubMesh(subMesh, mesh);
  24046. }
  24047. }
  24048. };
  24049. Scene.prototype.updateTransformMatrix = function (force) {
  24050. if (!this.activeCamera) {
  24051. return;
  24052. }
  24053. this.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix(force));
  24054. };
  24055. Scene.prototype.updateAlternateTransformMatrix = function (alternateCamera) {
  24056. this._setAlternateTransformMatrix(alternateCamera.getViewMatrix(), alternateCamera.getProjectionMatrix());
  24057. };
  24058. Scene.prototype._renderForCamera = function (camera, rigParent) {
  24059. if (camera && camera._skipRendering) {
  24060. return;
  24061. }
  24062. var engine = this._engine;
  24063. this.activeCamera = camera;
  24064. if (!this.activeCamera)
  24065. throw new Error("Active camera not set");
  24066. BABYLON.Tools.StartPerformanceCounter("Rendering camera " + this.activeCamera.name);
  24067. // Viewport
  24068. engine.setViewport(this.activeCamera.viewport);
  24069. // Camera
  24070. this.resetCachedMaterial();
  24071. this._renderId++;
  24072. this.updateTransformMatrix();
  24073. if (camera._alternateCamera) {
  24074. this.updateAlternateTransformMatrix(camera._alternateCamera);
  24075. this._alternateRendering = true;
  24076. }
  24077. this.onBeforeCameraRenderObservable.notifyObservers(this.activeCamera);
  24078. // Meshes
  24079. this._evaluateActiveMeshes();
  24080. // Software skinning
  24081. for (var softwareSkinnedMeshIndex = 0; softwareSkinnedMeshIndex < this._softwareSkinnedMeshes.length; softwareSkinnedMeshIndex++) {
  24082. var mesh = this._softwareSkinnedMeshes.data[softwareSkinnedMeshIndex];
  24083. mesh.applySkeleton(mesh.skeleton);
  24084. }
  24085. // Render targets
  24086. this.OnBeforeRenderTargetsRenderObservable.notifyObservers(this);
  24087. var needsRestoreFrameBuffer = false;
  24088. if (camera.customRenderTargets && camera.customRenderTargets.length > 0) {
  24089. this._renderTargets.concatWithNoDuplicate(camera.customRenderTargets);
  24090. }
  24091. if (rigParent && rigParent.customRenderTargets && rigParent.customRenderTargets.length > 0) {
  24092. this._renderTargets.concatWithNoDuplicate(rigParent.customRenderTargets);
  24093. }
  24094. if (this.renderTargetsEnabled && this._renderTargets.length > 0) {
  24095. this._intermediateRendering = true;
  24096. BABYLON.Tools.StartPerformanceCounter("Render targets", this._renderTargets.length > 0);
  24097. for (var renderIndex = 0; renderIndex < this._renderTargets.length; renderIndex++) {
  24098. var renderTarget = this._renderTargets.data[renderIndex];
  24099. if (renderTarget._shouldRender()) {
  24100. this._renderId++;
  24101. var hasSpecialRenderTargetCamera = renderTarget.activeCamera && renderTarget.activeCamera !== this.activeCamera;
  24102. renderTarget.render(hasSpecialRenderTargetCamera, this.dumpNextRenderTargets);
  24103. }
  24104. }
  24105. BABYLON.Tools.EndPerformanceCounter("Render targets", this._renderTargets.length > 0);
  24106. this._intermediateRendering = false;
  24107. this._renderId++;
  24108. needsRestoreFrameBuffer = true; // Restore back buffer
  24109. }
  24110. // Render EffecttLayer Texture
  24111. var stencilState = this._engine.getStencilBuffer();
  24112. var renderEffects = false;
  24113. var needStencil = false;
  24114. if (this.renderTargetsEnabled && this.effectLayers && this.effectLayers.length > 0) {
  24115. this._intermediateRendering = true;
  24116. for (var i = 0; i < this.effectLayers.length; i++) {
  24117. var effectLayer = this.effectLayers[i];
  24118. if (effectLayer.shouldRender() &&
  24119. (!effectLayer.camera ||
  24120. (effectLayer.camera.cameraRigMode === BABYLON.Camera.RIG_MODE_NONE && camera === effectLayer.camera) ||
  24121. (effectLayer.camera.cameraRigMode !== BABYLON.Camera.RIG_MODE_NONE && effectLayer.camera._rigCameras.indexOf(camera) > -1))) {
  24122. renderEffects = true;
  24123. needStencil = needStencil || effectLayer.needStencil();
  24124. var renderTarget = effectLayer._mainTexture;
  24125. if (renderTarget._shouldRender()) {
  24126. this._renderId++;
  24127. renderTarget.render(false, false);
  24128. needsRestoreFrameBuffer = true;
  24129. }
  24130. }
  24131. }
  24132. this._intermediateRendering = false;
  24133. this._renderId++;
  24134. }
  24135. if (needsRestoreFrameBuffer) {
  24136. engine.restoreDefaultFramebuffer(); // Restore back buffer
  24137. }
  24138. this.OnAfterRenderTargetsRenderObservable.notifyObservers(this);
  24139. // Prepare Frame
  24140. this.postProcessManager._prepareFrame();
  24141. // Backgrounds
  24142. var layerIndex;
  24143. var layer;
  24144. if (this.layers.length) {
  24145. engine.setDepthBuffer(false);
  24146. for (layerIndex = 0; layerIndex < this.layers.length; layerIndex++) {
  24147. layer = this.layers[layerIndex];
  24148. if (layer.isBackground && ((layer.layerMask & this.activeCamera.layerMask) !== 0)) {
  24149. layer.render();
  24150. }
  24151. }
  24152. engine.setDepthBuffer(true);
  24153. }
  24154. // Activate effect Layer stencil
  24155. if (needStencil) {
  24156. this._engine.setStencilBuffer(true);
  24157. }
  24158. // Render
  24159. this.onBeforeDrawPhaseObservable.notifyObservers(this);
  24160. this._renderingManager.render(null, null, true, true);
  24161. this.onAfterDrawPhaseObservable.notifyObservers(this);
  24162. // Restore effect Layer stencil
  24163. if (needStencil) {
  24164. this._engine.setStencilBuffer(stencilState);
  24165. }
  24166. // Bounding boxes
  24167. if (this._boundingBoxRenderer) {
  24168. this._boundingBoxRenderer.render();
  24169. }
  24170. // Lens flares
  24171. if (this.lensFlaresEnabled) {
  24172. BABYLON.Tools.StartPerformanceCounter("Lens flares", this.lensFlareSystems.length > 0);
  24173. for (var lensFlareSystemIndex = 0; lensFlareSystemIndex < this.lensFlareSystems.length; lensFlareSystemIndex++) {
  24174. var lensFlareSystem = this.lensFlareSystems[lensFlareSystemIndex];
  24175. if ((camera.layerMask & lensFlareSystem.layerMask) !== 0) {
  24176. lensFlareSystem.render();
  24177. }
  24178. }
  24179. BABYLON.Tools.EndPerformanceCounter("Lens flares", this.lensFlareSystems.length > 0);
  24180. }
  24181. // Foregrounds
  24182. if (this.layers.length) {
  24183. engine.setDepthBuffer(false);
  24184. for (layerIndex = 0; layerIndex < this.layers.length; layerIndex++) {
  24185. layer = this.layers[layerIndex];
  24186. if (!layer.isBackground && ((layer.layerMask & this.activeCamera.layerMask) !== 0)) {
  24187. layer.render();
  24188. }
  24189. }
  24190. engine.setDepthBuffer(true);
  24191. }
  24192. // Effect Layer
  24193. if (renderEffects) {
  24194. engine.setDepthBuffer(false);
  24195. for (var i = 0; i < this.effectLayers.length; i++) {
  24196. if (this.effectLayers[i].shouldRender()) {
  24197. this.effectLayers[i].render();
  24198. }
  24199. }
  24200. engine.setDepthBuffer(true);
  24201. }
  24202. // Finalize frame
  24203. this.postProcessManager._finalizeFrame(camera.isIntermediate);
  24204. // Reset some special arrays
  24205. this._renderTargets.reset();
  24206. this._alternateRendering = false;
  24207. this.onAfterCameraRenderObservable.notifyObservers(this.activeCamera);
  24208. BABYLON.Tools.EndPerformanceCounter("Rendering camera " + this.activeCamera.name);
  24209. };
  24210. Scene.prototype._processSubCameras = function (camera) {
  24211. if (camera.cameraRigMode === BABYLON.Camera.RIG_MODE_NONE) {
  24212. this._renderForCamera(camera);
  24213. return;
  24214. }
  24215. // rig cameras
  24216. for (var index = 0; index < camera._rigCameras.length; index++) {
  24217. this._renderForCamera(camera._rigCameras[index], camera);
  24218. }
  24219. this.activeCamera = camera;
  24220. this.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix());
  24221. };
  24222. Scene.prototype._checkIntersections = function () {
  24223. for (var index = 0; index < this._meshesForIntersections.length; index++) {
  24224. var sourceMesh = this._meshesForIntersections.data[index];
  24225. if (!sourceMesh.actionManager) {
  24226. continue;
  24227. }
  24228. for (var actionIndex = 0; actionIndex < sourceMesh.actionManager.actions.length; actionIndex++) {
  24229. var action = sourceMesh.actionManager.actions[actionIndex];
  24230. if (action.trigger === BABYLON.ActionManager.OnIntersectionEnterTrigger || action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  24231. var parameters = action.getTriggerParameter();
  24232. var otherMesh = parameters instanceof BABYLON.AbstractMesh ? parameters : parameters.mesh;
  24233. var areIntersecting = otherMesh.intersectsMesh(sourceMesh, parameters.usePreciseIntersection);
  24234. var currentIntersectionInProgress = sourceMesh._intersectionsInProgress.indexOf(otherMesh);
  24235. if (areIntersecting && currentIntersectionInProgress === -1) {
  24236. if (action.trigger === BABYLON.ActionManager.OnIntersectionEnterTrigger) {
  24237. action._executeCurrent(BABYLON.ActionEvent.CreateNew(sourceMesh, undefined, otherMesh));
  24238. sourceMesh._intersectionsInProgress.push(otherMesh);
  24239. }
  24240. else if (action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  24241. sourceMesh._intersectionsInProgress.push(otherMesh);
  24242. }
  24243. }
  24244. else if (!areIntersecting && currentIntersectionInProgress > -1) {
  24245. //They intersected, and now they don't.
  24246. //is this trigger an exit trigger? execute an event.
  24247. if (action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  24248. action._executeCurrent(BABYLON.ActionEvent.CreateNew(sourceMesh, undefined, otherMesh));
  24249. }
  24250. //if this is an exit trigger, or no exit trigger exists, remove the id from the intersection in progress array.
  24251. if (!sourceMesh.actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnIntersectionExitTrigger) || action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  24252. sourceMesh._intersectionsInProgress.splice(currentIntersectionInProgress, 1);
  24253. }
  24254. }
  24255. }
  24256. }
  24257. }
  24258. };
  24259. Scene.prototype.render = function () {
  24260. if (this.isDisposed) {
  24261. return;
  24262. }
  24263. this._activeParticles.fetchNewFrame();
  24264. this._totalVertices.fetchNewFrame();
  24265. this._activeIndices.fetchNewFrame();
  24266. this._activeBones.fetchNewFrame();
  24267. this._meshesForIntersections.reset();
  24268. this.resetCachedMaterial();
  24269. this.onBeforeAnimationsObservable.notifyObservers(this);
  24270. // Actions
  24271. if (this.actionManager) {
  24272. this.actionManager.processTrigger(BABYLON.ActionManager.OnEveryFrameTrigger);
  24273. }
  24274. //Simplification Queue
  24275. if (this.simplificationQueue && !this.simplificationQueue.running) {
  24276. this.simplificationQueue.executeNext();
  24277. }
  24278. if (this._engine.isDeterministicLockStep()) {
  24279. var deltaTime = Math.max(Scene.MinDeltaTime, Math.min(this._engine.getDeltaTime(), Scene.MaxDeltaTime)) + this._timeAccumulator;
  24280. var defaultFPS = (60.0 / 1000.0);
  24281. var defaultFrameTime = 1000 / 60; // frame time in MS
  24282. if (this._physicsEngine) {
  24283. defaultFrameTime = this._physicsEngine.getTimeStep() * 1000;
  24284. }
  24285. var stepsTaken = 0;
  24286. var maxSubSteps = this._engine.getLockstepMaxSteps();
  24287. var internalSteps = Math.floor(deltaTime / (1000 * defaultFPS));
  24288. internalSteps = Math.min(internalSteps, maxSubSteps);
  24289. do {
  24290. this.onBeforeStepObservable.notifyObservers(this);
  24291. // Animations
  24292. this._animationRatio = defaultFrameTime * defaultFPS;
  24293. this._animate();
  24294. this.onAfterAnimationsObservable.notifyObservers(this);
  24295. // Physics
  24296. if (this._physicsEngine) {
  24297. this.onBeforePhysicsObservable.notifyObservers(this);
  24298. this._physicsEngine._step(defaultFrameTime / 1000);
  24299. this.onAfterPhysicsObservable.notifyObservers(this);
  24300. }
  24301. this.onAfterStepObservable.notifyObservers(this);
  24302. this._currentStepId++;
  24303. stepsTaken++;
  24304. deltaTime -= defaultFrameTime;
  24305. } while (deltaTime > 0 && stepsTaken < internalSteps);
  24306. this._timeAccumulator = deltaTime < 0 ? 0 : deltaTime;
  24307. }
  24308. else {
  24309. // Animations
  24310. var deltaTime = this.useConstantAnimationDeltaTime ? 16 : Math.max(Scene.MinDeltaTime, Math.min(this._engine.getDeltaTime(), Scene.MaxDeltaTime));
  24311. this._animationRatio = deltaTime * (60.0 / 1000.0);
  24312. this._animate();
  24313. this.onAfterAnimationsObservable.notifyObservers(this);
  24314. // Physics
  24315. if (this._physicsEngine) {
  24316. this.onBeforePhysicsObservable.notifyObservers(this);
  24317. this._physicsEngine._step(deltaTime / 1000.0);
  24318. this.onAfterPhysicsObservable.notifyObservers(this);
  24319. }
  24320. }
  24321. // update gamepad manager
  24322. if (this._gamepadManager && this._gamepadManager._isMonitoring) {
  24323. this._gamepadManager._checkGamepadsStatus();
  24324. }
  24325. // Update Cameras
  24326. if (this.activeCameras.length > 0) {
  24327. for (var cameraIndex = 0; cameraIndex < this.activeCameras.length; cameraIndex++) {
  24328. var camera = this.activeCameras[cameraIndex];
  24329. camera.update();
  24330. if (camera.cameraRigMode !== BABYLON.Camera.RIG_MODE_NONE) {
  24331. // rig cameras
  24332. for (var index = 0; index < camera._rigCameras.length; index++) {
  24333. camera._rigCameras[index].update();
  24334. }
  24335. }
  24336. }
  24337. }
  24338. else if (this.activeCamera) {
  24339. this.activeCamera.update();
  24340. if (this.activeCamera.cameraRigMode !== BABYLON.Camera.RIG_MODE_NONE) {
  24341. // rig cameras
  24342. for (var index = 0; index < this.activeCamera._rigCameras.length; index++) {
  24343. this.activeCamera._rigCameras[index].update();
  24344. }
  24345. }
  24346. }
  24347. // Before render
  24348. this.onBeforeRenderObservable.notifyObservers(this);
  24349. // Customs render targets
  24350. this.OnBeforeRenderTargetsRenderObservable.notifyObservers(this);
  24351. var engine = this.getEngine();
  24352. var currentActiveCamera = this.activeCamera;
  24353. if (this.renderTargetsEnabled) {
  24354. BABYLON.Tools.StartPerformanceCounter("Custom render targets", this.customRenderTargets.length > 0);
  24355. this._intermediateRendering = true;
  24356. for (var customIndex = 0; customIndex < this.customRenderTargets.length; customIndex++) {
  24357. var renderTarget = this.customRenderTargets[customIndex];
  24358. if (renderTarget._shouldRender()) {
  24359. this._renderId++;
  24360. this.activeCamera = renderTarget.activeCamera || this.activeCamera;
  24361. if (!this.activeCamera)
  24362. throw new Error("Active camera not set");
  24363. // Viewport
  24364. engine.setViewport(this.activeCamera.viewport);
  24365. // Camera
  24366. this.updateTransformMatrix();
  24367. renderTarget.render(currentActiveCamera !== this.activeCamera, this.dumpNextRenderTargets);
  24368. }
  24369. }
  24370. BABYLON.Tools.EndPerformanceCounter("Custom render targets", this.customRenderTargets.length > 0);
  24371. this._intermediateRendering = false;
  24372. this._renderId++;
  24373. }
  24374. // Restore back buffer
  24375. if (this.customRenderTargets.length > 0) {
  24376. engine.restoreDefaultFramebuffer();
  24377. }
  24378. this.OnAfterRenderTargetsRenderObservable.notifyObservers(this);
  24379. this.activeCamera = currentActiveCamera;
  24380. // Procedural textures
  24381. if (this.proceduralTexturesEnabled) {
  24382. BABYLON.Tools.StartPerformanceCounter("Procedural textures", this._proceduralTextures.length > 0);
  24383. for (var proceduralIndex = 0; proceduralIndex < this._proceduralTextures.length; proceduralIndex++) {
  24384. var proceduralTexture = this._proceduralTextures[proceduralIndex];
  24385. if (proceduralTexture._shouldRender()) {
  24386. proceduralTexture.render();
  24387. }
  24388. }
  24389. BABYLON.Tools.EndPerformanceCounter("Procedural textures", this._proceduralTextures.length > 0);
  24390. }
  24391. // Clear
  24392. if (this.autoClearDepthAndStencil || this.autoClear) {
  24393. this._engine.clear(this.clearColor, this.autoClear || this.forceWireframe || this.forcePointsCloud, this.autoClearDepthAndStencil, this.autoClearDepthAndStencil);
  24394. }
  24395. // Shadows
  24396. if (this.shadowsEnabled) {
  24397. for (var lightIndex = 0; lightIndex < this.lights.length; lightIndex++) {
  24398. var light = this.lights[lightIndex];
  24399. var shadowGenerator = light.getShadowGenerator();
  24400. if (light.isEnabled() && light.shadowEnabled && shadowGenerator) {
  24401. var shadowMap = (shadowGenerator.getShadowMap());
  24402. if (this.textures.indexOf(shadowMap) !== -1) {
  24403. this._renderTargets.push(shadowMap);
  24404. }
  24405. }
  24406. }
  24407. }
  24408. // Depth renderer
  24409. for (var key in this._depthRenderer) {
  24410. this._renderTargets.push(this._depthRenderer[key].getDepthMap());
  24411. }
  24412. // Geometry renderer
  24413. if (this._geometryBufferRenderer) {
  24414. this._renderTargets.push(this._geometryBufferRenderer.getGBuffer());
  24415. }
  24416. // RenderPipeline
  24417. if (this._postProcessRenderPipelineManager) {
  24418. this._postProcessRenderPipelineManager.update();
  24419. }
  24420. // Multi-cameras?
  24421. if (this.activeCameras.length > 0) {
  24422. for (var cameraIndex = 0; cameraIndex < this.activeCameras.length; cameraIndex++) {
  24423. if (cameraIndex > 0) {
  24424. this._engine.clear(null, false, true, true);
  24425. }
  24426. this._processSubCameras(this.activeCameras[cameraIndex]);
  24427. }
  24428. }
  24429. else {
  24430. if (!this.activeCamera) {
  24431. throw new Error("No camera defined");
  24432. }
  24433. this._processSubCameras(this.activeCamera);
  24434. }
  24435. // Intersection checks
  24436. this._checkIntersections();
  24437. // Update the audio listener attached to the camera
  24438. if (BABYLON.AudioEngine) {
  24439. this._updateAudioParameters();
  24440. }
  24441. // After render
  24442. if (this.afterRender) {
  24443. this.afterRender();
  24444. }
  24445. this.onAfterRenderObservable.notifyObservers(this);
  24446. // Cleaning
  24447. for (var index = 0; index < this._toBeDisposed.length; index++) {
  24448. var data = this._toBeDisposed.data[index];
  24449. if (data) {
  24450. data.dispose();
  24451. }
  24452. this._toBeDisposed[index] = null;
  24453. }
  24454. this._toBeDisposed.reset();
  24455. if (this.dumpNextRenderTargets) {
  24456. this.dumpNextRenderTargets = false;
  24457. }
  24458. this._activeBones.addCount(0, true);
  24459. this._activeIndices.addCount(0, true);
  24460. this._activeParticles.addCount(0, true);
  24461. };
  24462. Scene.prototype._updateAudioParameters = function () {
  24463. if (!this.audioEnabled || !this._mainSoundTrack || (this._mainSoundTrack.soundCollection.length === 0 && this.soundTracks.length === 1)) {
  24464. return;
  24465. }
  24466. var listeningCamera;
  24467. var audioEngine = BABYLON.Engine.audioEngine;
  24468. if (this.activeCameras.length > 0) {
  24469. listeningCamera = this.activeCameras[0];
  24470. }
  24471. else {
  24472. listeningCamera = this.activeCamera;
  24473. }
  24474. if (listeningCamera && audioEngine.canUseWebAudio && audioEngine.audioContext) {
  24475. audioEngine.audioContext.listener.setPosition(listeningCamera.position.x, listeningCamera.position.y, listeningCamera.position.z);
  24476. // for VR cameras
  24477. if (listeningCamera.rigCameras && listeningCamera.rigCameras.length > 0) {
  24478. listeningCamera = listeningCamera.rigCameras[0];
  24479. }
  24480. var mat = BABYLON.Matrix.Invert(listeningCamera.getViewMatrix());
  24481. var cameraDirection = BABYLON.Vector3.TransformNormal(new BABYLON.Vector3(0, 0, -1), mat);
  24482. cameraDirection.normalize();
  24483. // To avoid some errors on GearVR
  24484. if (!isNaN(cameraDirection.x) && !isNaN(cameraDirection.y) && !isNaN(cameraDirection.z)) {
  24485. audioEngine.audioContext.listener.setOrientation(cameraDirection.x, cameraDirection.y, cameraDirection.z, 0, 1, 0);
  24486. }
  24487. var i;
  24488. for (i = 0; i < this.mainSoundTrack.soundCollection.length; i++) {
  24489. var sound = this.mainSoundTrack.soundCollection[i];
  24490. if (sound.useCustomAttenuation) {
  24491. sound.updateDistanceFromListener();
  24492. }
  24493. }
  24494. for (i = 0; i < this.soundTracks.length; i++) {
  24495. for (var j = 0; j < this.soundTracks[i].soundCollection.length; j++) {
  24496. sound = this.soundTracks[i].soundCollection[j];
  24497. if (sound.useCustomAttenuation) {
  24498. sound.updateDistanceFromListener();
  24499. }
  24500. }
  24501. }
  24502. }
  24503. };
  24504. Object.defineProperty(Scene.prototype, "audioEnabled", {
  24505. // Audio
  24506. get: function () {
  24507. return this._audioEnabled;
  24508. },
  24509. set: function (value) {
  24510. this._audioEnabled = value;
  24511. if (BABYLON.AudioEngine) {
  24512. if (this._audioEnabled) {
  24513. this._enableAudio();
  24514. }
  24515. else {
  24516. this._disableAudio();
  24517. }
  24518. }
  24519. },
  24520. enumerable: true,
  24521. configurable: true
  24522. });
  24523. Scene.prototype._disableAudio = function () {
  24524. var i;
  24525. for (i = 0; i < this.mainSoundTrack.soundCollection.length; i++) {
  24526. this.mainSoundTrack.soundCollection[i].pause();
  24527. }
  24528. for (i = 0; i < this.soundTracks.length; i++) {
  24529. for (var j = 0; j < this.soundTracks[i].soundCollection.length; j++) {
  24530. this.soundTracks[i].soundCollection[j].pause();
  24531. }
  24532. }
  24533. };
  24534. Scene.prototype._enableAudio = function () {
  24535. var i;
  24536. for (i = 0; i < this.mainSoundTrack.soundCollection.length; i++) {
  24537. if (this.mainSoundTrack.soundCollection[i].isPaused) {
  24538. this.mainSoundTrack.soundCollection[i].play();
  24539. }
  24540. }
  24541. for (i = 0; i < this.soundTracks.length; i++) {
  24542. for (var j = 0; j < this.soundTracks[i].soundCollection.length; j++) {
  24543. if (this.soundTracks[i].soundCollection[j].isPaused) {
  24544. this.soundTracks[i].soundCollection[j].play();
  24545. }
  24546. }
  24547. }
  24548. };
  24549. Object.defineProperty(Scene.prototype, "headphone", {
  24550. get: function () {
  24551. return this._headphone;
  24552. },
  24553. set: function (value) {
  24554. this._headphone = value;
  24555. if (BABYLON.AudioEngine) {
  24556. if (this._headphone) {
  24557. this._switchAudioModeForHeadphones();
  24558. }
  24559. else {
  24560. this._switchAudioModeForNormalSpeakers();
  24561. }
  24562. }
  24563. },
  24564. enumerable: true,
  24565. configurable: true
  24566. });
  24567. Scene.prototype._switchAudioModeForHeadphones = function () {
  24568. this.mainSoundTrack.switchPanningModelToHRTF();
  24569. for (var i = 0; i < this.soundTracks.length; i++) {
  24570. this.soundTracks[i].switchPanningModelToHRTF();
  24571. }
  24572. };
  24573. Scene.prototype._switchAudioModeForNormalSpeakers = function () {
  24574. this.mainSoundTrack.switchPanningModelToEqualPower();
  24575. for (var i = 0; i < this.soundTracks.length; i++) {
  24576. this.soundTracks[i].switchPanningModelToEqualPower();
  24577. }
  24578. };
  24579. /**
  24580. * Creates a depth renderer a given camera which contains a depth map which can be used for post processing.
  24581. * @param camera The camera to create the depth renderer on (default: scene's active camera)
  24582. * @returns the created depth renderer
  24583. */
  24584. Scene.prototype.enableDepthRenderer = function (camera) {
  24585. camera = camera || this.activeCamera;
  24586. if (!camera) {
  24587. throw "No camera available to enable depth renderer";
  24588. }
  24589. if (!this._depthRenderer[camera.id]) {
  24590. this._depthRenderer[camera.id] = new BABYLON.DepthRenderer(this, BABYLON.Engine.TEXTURETYPE_FLOAT, camera);
  24591. }
  24592. return this._depthRenderer[camera.id];
  24593. };
  24594. /**
  24595. * Disables a depth renderer for a given camera
  24596. * @param camera The camera to disable the depth renderer on (default: scene's active camera)
  24597. */
  24598. Scene.prototype.disableDepthRenderer = function (camera) {
  24599. camera = camera || this.activeCamera;
  24600. if (!camera || !this._depthRenderer[camera.id]) {
  24601. return;
  24602. }
  24603. this._depthRenderer[camera.id].dispose();
  24604. delete this._depthRenderer[camera.id];
  24605. };
  24606. Scene.prototype.enableGeometryBufferRenderer = function (ratio) {
  24607. if (ratio === void 0) { ratio = 1; }
  24608. if (this._geometryBufferRenderer) {
  24609. return this._geometryBufferRenderer;
  24610. }
  24611. this._geometryBufferRenderer = new BABYLON.GeometryBufferRenderer(this, ratio);
  24612. if (!this._geometryBufferRenderer.isSupported) {
  24613. this._geometryBufferRenderer = null;
  24614. }
  24615. return this._geometryBufferRenderer;
  24616. };
  24617. Scene.prototype.disableGeometryBufferRenderer = function () {
  24618. if (!this._geometryBufferRenderer) {
  24619. return;
  24620. }
  24621. this._geometryBufferRenderer.dispose();
  24622. this._geometryBufferRenderer = null;
  24623. };
  24624. Scene.prototype.freezeMaterials = function () {
  24625. for (var i = 0; i < this.materials.length; i++) {
  24626. this.materials[i].freeze();
  24627. }
  24628. };
  24629. Scene.prototype.unfreezeMaterials = function () {
  24630. for (var i = 0; i < this.materials.length; i++) {
  24631. this.materials[i].unfreeze();
  24632. }
  24633. };
  24634. Scene.prototype.dispose = function () {
  24635. this.beforeRender = null;
  24636. this.afterRender = null;
  24637. this.skeletons = [];
  24638. this.morphTargetManagers = [];
  24639. this.importedMeshesFiles = new Array();
  24640. this.stopAllAnimations();
  24641. this.resetCachedMaterial();
  24642. for (var key in this._depthRenderer) {
  24643. this._depthRenderer[key].dispose();
  24644. }
  24645. if (this._gamepadManager) {
  24646. this._gamepadManager.dispose();
  24647. this._gamepadManager = null;
  24648. }
  24649. // Smart arrays
  24650. if (this.activeCamera) {
  24651. this.activeCamera._activeMeshes.dispose();
  24652. this.activeCamera = null;
  24653. }
  24654. this._activeMeshes.dispose();
  24655. this._renderingManager.dispose();
  24656. this._processedMaterials.dispose();
  24657. this._activeParticleSystems.dispose();
  24658. this._activeSkeletons.dispose();
  24659. this._softwareSkinnedMeshes.dispose();
  24660. this._renderTargets.dispose();
  24661. if (this._boundingBoxRenderer) {
  24662. this._boundingBoxRenderer.dispose();
  24663. }
  24664. this._meshesForIntersections.dispose();
  24665. this._toBeDisposed.dispose();
  24666. // Abort active requests
  24667. for (var _i = 0, _a = this._activeRequests; _i < _a.length; _i++) {
  24668. var request = _a[_i];
  24669. request.abort();
  24670. }
  24671. // Debug layer
  24672. if (this._debugLayer) {
  24673. this._debugLayer.hide();
  24674. }
  24675. // Events
  24676. this.onDisposeObservable.notifyObservers(this);
  24677. this.onDisposeObservable.clear();
  24678. this.onBeforeRenderObservable.clear();
  24679. this.onAfterRenderObservable.clear();
  24680. this.OnBeforeRenderTargetsRenderObservable.clear();
  24681. this.OnAfterRenderTargetsRenderObservable.clear();
  24682. this.onAfterStepObservable.clear();
  24683. this.onBeforeStepObservable.clear();
  24684. this.onBeforeActiveMeshesEvaluationObservable.clear();
  24685. this.onAfterActiveMeshesEvaluationObservable.clear();
  24686. this.onBeforeParticlesRenderingObservable.clear();
  24687. this.onAfterParticlesRenderingObservable.clear();
  24688. this.onBeforeSpritesRenderingObservable.clear();
  24689. this.onAfterSpritesRenderingObservable.clear();
  24690. this.onBeforeDrawPhaseObservable.clear();
  24691. this.onAfterDrawPhaseObservable.clear();
  24692. this.onBeforePhysicsObservable.clear();
  24693. this.onAfterPhysicsObservable.clear();
  24694. this.onBeforeAnimationsObservable.clear();
  24695. this.onAfterAnimationsObservable.clear();
  24696. this.onDataLoadedObservable.clear();
  24697. this.detachControl();
  24698. // Release sounds & sounds tracks
  24699. if (BABYLON.AudioEngine) {
  24700. this.disposeSounds();
  24701. }
  24702. // VR Helper
  24703. if (this.VRHelper) {
  24704. this.VRHelper.dispose();
  24705. }
  24706. // Detach cameras
  24707. var canvas = this._engine.getRenderingCanvas();
  24708. if (canvas) {
  24709. var index;
  24710. for (index = 0; index < this.cameras.length; index++) {
  24711. this.cameras[index].detachControl(canvas);
  24712. }
  24713. }
  24714. // Release animation groups
  24715. while (this.animationGroups.length) {
  24716. this.animationGroups[0].dispose();
  24717. }
  24718. // Release lights
  24719. while (this.lights.length) {
  24720. this.lights[0].dispose();
  24721. }
  24722. // Release meshes
  24723. while (this.meshes.length) {
  24724. this.meshes[0].dispose(true);
  24725. }
  24726. while (this.transformNodes.length) {
  24727. this.removeTransformNode(this.transformNodes[0]);
  24728. }
  24729. // Release cameras
  24730. while (this.cameras.length) {
  24731. this.cameras[0].dispose();
  24732. }
  24733. // Release materials
  24734. if (this.defaultMaterial) {
  24735. this.defaultMaterial.dispose();
  24736. }
  24737. while (this.multiMaterials.length) {
  24738. this.multiMaterials[0].dispose();
  24739. }
  24740. while (this.materials.length) {
  24741. this.materials[0].dispose();
  24742. }
  24743. // Release particles
  24744. while (this.particleSystems.length) {
  24745. this.particleSystems[0].dispose();
  24746. }
  24747. // Release sprites
  24748. while (this.spriteManagers.length) {
  24749. this.spriteManagers[0].dispose();
  24750. }
  24751. // Release postProcesses
  24752. while (this.postProcesses.length) {
  24753. this.postProcesses[0].dispose();
  24754. }
  24755. // Release layers
  24756. while (this.layers.length) {
  24757. this.layers[0].dispose();
  24758. }
  24759. while (this.effectLayers.length) {
  24760. this.effectLayers[0].dispose();
  24761. }
  24762. // Release textures
  24763. while (this.textures.length) {
  24764. this.textures[0].dispose();
  24765. }
  24766. // Release UBO
  24767. this._sceneUbo.dispose();
  24768. if (this._alternateSceneUbo) {
  24769. this._alternateSceneUbo.dispose();
  24770. }
  24771. // Post-processes
  24772. this.postProcessManager.dispose();
  24773. if (this._postProcessRenderPipelineManager) {
  24774. this._postProcessRenderPipelineManager.dispose();
  24775. }
  24776. // Physics
  24777. if (this._physicsEngine) {
  24778. this.disablePhysicsEngine();
  24779. }
  24780. // Remove from engine
  24781. index = this._engine.scenes.indexOf(this);
  24782. if (index > -1) {
  24783. this._engine.scenes.splice(index, 1);
  24784. }
  24785. this._engine.wipeCaches(true);
  24786. this._isDisposed = true;
  24787. };
  24788. Object.defineProperty(Scene.prototype, "isDisposed", {
  24789. get: function () {
  24790. return this._isDisposed;
  24791. },
  24792. enumerable: true,
  24793. configurable: true
  24794. });
  24795. // Release sounds & sounds tracks
  24796. Scene.prototype.disposeSounds = function () {
  24797. if (!this._mainSoundTrack) {
  24798. return;
  24799. }
  24800. this.mainSoundTrack.dispose();
  24801. for (var scIndex = 0; scIndex < this.soundTracks.length; scIndex++) {
  24802. this.soundTracks[scIndex].dispose();
  24803. }
  24804. };
  24805. // Octrees
  24806. /**
  24807. * Get the world extend vectors with an optional filter
  24808. *
  24809. * @param filterPredicate the predicate - which meshes should be included when calculating the world size
  24810. * @returns {{ min: Vector3; max: Vector3 }} min and max vectors
  24811. */
  24812. Scene.prototype.getWorldExtends = function (filterPredicate) {
  24813. var min = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  24814. var max = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  24815. filterPredicate = filterPredicate || (function () { return true; });
  24816. this.meshes.filter(filterPredicate).forEach(function (mesh) {
  24817. mesh.computeWorldMatrix(true);
  24818. if (!mesh.subMeshes || mesh.subMeshes.length === 0 || mesh.infiniteDistance) {
  24819. return;
  24820. }
  24821. var boundingInfo = mesh.getBoundingInfo();
  24822. var minBox = boundingInfo.boundingBox.minimumWorld;
  24823. var maxBox = boundingInfo.boundingBox.maximumWorld;
  24824. BABYLON.Tools.CheckExtends(minBox, min, max);
  24825. BABYLON.Tools.CheckExtends(maxBox, min, max);
  24826. });
  24827. return {
  24828. min: min,
  24829. max: max
  24830. };
  24831. };
  24832. Scene.prototype.createOrUpdateSelectionOctree = function (maxCapacity, maxDepth) {
  24833. if (maxCapacity === void 0) { maxCapacity = 64; }
  24834. if (maxDepth === void 0) { maxDepth = 2; }
  24835. if (!this._selectionOctree) {
  24836. this._selectionOctree = new BABYLON.Octree(BABYLON.Octree.CreationFuncForMeshes, maxCapacity, maxDepth);
  24837. }
  24838. var worldExtends = this.getWorldExtends();
  24839. // Update octree
  24840. this._selectionOctree.update(worldExtends.min, worldExtends.max, this.meshes);
  24841. return this._selectionOctree;
  24842. };
  24843. // Picking
  24844. Scene.prototype.createPickingRay = function (x, y, world, camera, cameraViewSpace) {
  24845. if (cameraViewSpace === void 0) { cameraViewSpace = false; }
  24846. var result = BABYLON.Ray.Zero();
  24847. this.createPickingRayToRef(x, y, world, result, camera, cameraViewSpace);
  24848. return result;
  24849. };
  24850. Scene.prototype.createPickingRayToRef = function (x, y, world, result, camera, cameraViewSpace) {
  24851. if (cameraViewSpace === void 0) { cameraViewSpace = false; }
  24852. var engine = this._engine;
  24853. if (!camera) {
  24854. if (!this.activeCamera)
  24855. throw new Error("Active camera not set");
  24856. camera = this.activeCamera;
  24857. }
  24858. var cameraViewport = camera.viewport;
  24859. var viewport = cameraViewport.toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  24860. // Moving coordinates to local viewport world
  24861. x = x / this._engine.getHardwareScalingLevel() - viewport.x;
  24862. y = y / this._engine.getHardwareScalingLevel() - (this._engine.getRenderHeight() - viewport.y - viewport.height);
  24863. result.update(x, y, viewport.width, viewport.height, world ? world : BABYLON.Matrix.Identity(), cameraViewSpace ? BABYLON.Matrix.Identity() : camera.getViewMatrix(), camera.getProjectionMatrix());
  24864. return this;
  24865. };
  24866. Scene.prototype.createPickingRayInCameraSpace = function (x, y, camera) {
  24867. var result = BABYLON.Ray.Zero();
  24868. this.createPickingRayInCameraSpaceToRef(x, y, result, camera);
  24869. return result;
  24870. };
  24871. Scene.prototype.createPickingRayInCameraSpaceToRef = function (x, y, result, camera) {
  24872. if (!BABYLON.PickingInfo) {
  24873. return this;
  24874. }
  24875. var engine = this._engine;
  24876. if (!camera) {
  24877. if (!this.activeCamera)
  24878. throw new Error("Active camera not set");
  24879. camera = this.activeCamera;
  24880. }
  24881. var cameraViewport = camera.viewport;
  24882. var viewport = cameraViewport.toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  24883. var identity = BABYLON.Matrix.Identity();
  24884. // Moving coordinates to local viewport world
  24885. x = x / this._engine.getHardwareScalingLevel() - viewport.x;
  24886. y = y / this._engine.getHardwareScalingLevel() - (this._engine.getRenderHeight() - viewport.y - viewport.height);
  24887. result.update(x, y, viewport.width, viewport.height, identity, identity, camera.getProjectionMatrix());
  24888. return this;
  24889. };
  24890. Scene.prototype._internalPick = function (rayFunction, predicate, fastCheck) {
  24891. if (!BABYLON.PickingInfo) {
  24892. return null;
  24893. }
  24894. var pickingInfo = null;
  24895. for (var meshIndex = 0; meshIndex < this.meshes.length; meshIndex++) {
  24896. var mesh = this.meshes[meshIndex];
  24897. if (predicate) {
  24898. if (!predicate(mesh)) {
  24899. continue;
  24900. }
  24901. }
  24902. else if (!mesh.isEnabled() || !mesh.isVisible || !mesh.isPickable) {
  24903. continue;
  24904. }
  24905. var world = mesh.getWorldMatrix();
  24906. var ray = rayFunction(world);
  24907. var result = mesh.intersects(ray, fastCheck);
  24908. if (!result || !result.hit)
  24909. continue;
  24910. if (!fastCheck && pickingInfo != null && result.distance >= pickingInfo.distance)
  24911. continue;
  24912. pickingInfo = result;
  24913. if (fastCheck) {
  24914. break;
  24915. }
  24916. }
  24917. return pickingInfo || new BABYLON.PickingInfo();
  24918. };
  24919. Scene.prototype._internalMultiPick = function (rayFunction, predicate) {
  24920. if (!BABYLON.PickingInfo) {
  24921. return null;
  24922. }
  24923. var pickingInfos = new Array();
  24924. for (var meshIndex = 0; meshIndex < this.meshes.length; meshIndex++) {
  24925. var mesh = this.meshes[meshIndex];
  24926. if (predicate) {
  24927. if (!predicate(mesh)) {
  24928. continue;
  24929. }
  24930. }
  24931. else if (!mesh.isEnabled() || !mesh.isVisible || !mesh.isPickable) {
  24932. continue;
  24933. }
  24934. var world = mesh.getWorldMatrix();
  24935. var ray = rayFunction(world);
  24936. var result = mesh.intersects(ray, false);
  24937. if (!result || !result.hit)
  24938. continue;
  24939. pickingInfos.push(result);
  24940. }
  24941. return pickingInfos;
  24942. };
  24943. Scene.prototype._internalPickSprites = function (ray, predicate, fastCheck, camera) {
  24944. if (!BABYLON.PickingInfo) {
  24945. return null;
  24946. }
  24947. var pickingInfo = null;
  24948. if (!camera) {
  24949. if (!this.activeCamera) {
  24950. return null;
  24951. }
  24952. camera = this.activeCamera;
  24953. }
  24954. if (this.spriteManagers.length > 0) {
  24955. for (var spriteIndex = 0; spriteIndex < this.spriteManagers.length; spriteIndex++) {
  24956. var spriteManager = this.spriteManagers[spriteIndex];
  24957. if (!spriteManager.isPickable) {
  24958. continue;
  24959. }
  24960. var result = spriteManager.intersects(ray, camera, predicate, fastCheck);
  24961. if (!result || !result.hit)
  24962. continue;
  24963. if (!fastCheck && pickingInfo != null && result.distance >= pickingInfo.distance)
  24964. continue;
  24965. pickingInfo = result;
  24966. if (fastCheck) {
  24967. break;
  24968. }
  24969. }
  24970. }
  24971. return pickingInfo || new BABYLON.PickingInfo();
  24972. };
  24973. /** Launch a ray to try to pick a mesh in the scene
  24974. * @param x position on screen
  24975. * @param y position on screen
  24976. * @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
  24977. * @param fastCheck Launch a fast check only using the bounding boxes. Can be set to null.
  24978. * @param camera to use for computing the picking ray. Can be set to null. In this case, the scene.activeCamera will be used
  24979. */
  24980. Scene.prototype.pick = function (x, y, predicate, fastCheck, camera) {
  24981. var _this = this;
  24982. if (!BABYLON.PickingInfo) {
  24983. return null;
  24984. }
  24985. return this._internalPick(function (world) {
  24986. _this.createPickingRayToRef(x, y, world, _this._tempPickingRay, camera || null);
  24987. return _this._tempPickingRay;
  24988. }, predicate, fastCheck);
  24989. };
  24990. /** Launch a ray to try to pick a sprite in the scene
  24991. * @param x position on screen
  24992. * @param y position on screen
  24993. * @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
  24994. * @param fastCheck Launch a fast check only using the bounding boxes. Can be set to null.
  24995. * @param camera camera to use for computing the picking ray. Can be set to null. In this case, the scene.activeCamera will be used
  24996. */
  24997. Scene.prototype.pickSprite = function (x, y, predicate, fastCheck, camera) {
  24998. this.createPickingRayInCameraSpaceToRef(x, y, this._tempPickingRay, camera);
  24999. return this._internalPickSprites(this._tempPickingRay, predicate, fastCheck, camera);
  25000. };
  25001. /** Use the given ray to pick a mesh in the scene
  25002. * @param ray The ray to use to pick meshes
  25003. * @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
  25004. * @param fastCheck Launch a fast check only using the bounding boxes. Can be set to null.
  25005. */
  25006. Scene.prototype.pickWithRay = function (ray, predicate, fastCheck) {
  25007. var _this = this;
  25008. return this._internalPick(function (world) {
  25009. if (!_this._pickWithRayInverseMatrix) {
  25010. _this._pickWithRayInverseMatrix = BABYLON.Matrix.Identity();
  25011. }
  25012. world.invertToRef(_this._pickWithRayInverseMatrix);
  25013. if (!_this._cachedRayForTransform) {
  25014. _this._cachedRayForTransform = BABYLON.Ray.Zero();
  25015. }
  25016. BABYLON.Ray.TransformToRef(ray, _this._pickWithRayInverseMatrix, _this._cachedRayForTransform);
  25017. return _this._cachedRayForTransform;
  25018. }, predicate, fastCheck);
  25019. };
  25020. /**
  25021. * Launch a ray to try to pick a mesh in the scene
  25022. * @param x X position on screen
  25023. * @param y Y position on screen
  25024. * @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
  25025. * @param camera camera to use for computing the picking ray. Can be set to null. In this case, the scene.activeCamera will be used
  25026. */
  25027. Scene.prototype.multiPick = function (x, y, predicate, camera) {
  25028. var _this = this;
  25029. return this._internalMultiPick(function (world) { return _this.createPickingRay(x, y, world, camera || null); }, predicate);
  25030. };
  25031. /**
  25032. * Launch a ray to try to pick a mesh in the scene
  25033. * @param ray Ray to use
  25034. * @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
  25035. */
  25036. Scene.prototype.multiPickWithRay = function (ray, predicate) {
  25037. var _this = this;
  25038. return this._internalMultiPick(function (world) {
  25039. if (!_this._pickWithRayInverseMatrix) {
  25040. _this._pickWithRayInverseMatrix = BABYLON.Matrix.Identity();
  25041. }
  25042. world.invertToRef(_this._pickWithRayInverseMatrix);
  25043. if (!_this._cachedRayForTransform) {
  25044. _this._cachedRayForTransform = BABYLON.Ray.Zero();
  25045. }
  25046. BABYLON.Ray.TransformToRef(ray, _this._pickWithRayInverseMatrix, _this._cachedRayForTransform);
  25047. return _this._cachedRayForTransform;
  25048. }, predicate);
  25049. };
  25050. Scene.prototype.setPointerOverMesh = function (mesh) {
  25051. if (this._pointerOverMesh === mesh) {
  25052. return;
  25053. }
  25054. if (this._pointerOverMesh && this._pointerOverMesh.actionManager) {
  25055. this._pointerOverMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOutTrigger, BABYLON.ActionEvent.CreateNew(this._pointerOverMesh));
  25056. }
  25057. this._pointerOverMesh = mesh;
  25058. if (this._pointerOverMesh && this._pointerOverMesh.actionManager) {
  25059. this._pointerOverMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOverTrigger, BABYLON.ActionEvent.CreateNew(this._pointerOverMesh));
  25060. }
  25061. };
  25062. Scene.prototype.getPointerOverMesh = function () {
  25063. return this._pointerOverMesh;
  25064. };
  25065. Scene.prototype.setPointerOverSprite = function (sprite) {
  25066. if (this._pointerOverSprite === sprite) {
  25067. return;
  25068. }
  25069. if (this._pointerOverSprite && this._pointerOverSprite.actionManager) {
  25070. this._pointerOverSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOutTrigger, BABYLON.ActionEvent.CreateNewFromSprite(this._pointerOverSprite, this));
  25071. }
  25072. this._pointerOverSprite = sprite;
  25073. if (this._pointerOverSprite && this._pointerOverSprite.actionManager) {
  25074. this._pointerOverSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOverTrigger, BABYLON.ActionEvent.CreateNewFromSprite(this._pointerOverSprite, this));
  25075. }
  25076. };
  25077. Scene.prototype.getPointerOverSprite = function () {
  25078. return this._pointerOverSprite;
  25079. };
  25080. // Physics
  25081. Scene.prototype.getPhysicsEngine = function () {
  25082. return this._physicsEngine;
  25083. };
  25084. /**
  25085. * Enables physics to the current scene
  25086. * @param {BABYLON.Vector3} [gravity] - the scene's gravity for the physics engine
  25087. * @param {BABYLON.IPhysicsEnginePlugin} [plugin] - The physics engine to be used. defaults to OimoJS.
  25088. * @return {boolean} was the physics engine initialized
  25089. */
  25090. Scene.prototype.enablePhysics = function (gravity, plugin) {
  25091. if (gravity === void 0) { gravity = null; }
  25092. if (this._physicsEngine) {
  25093. return true;
  25094. }
  25095. try {
  25096. this._physicsEngine = new BABYLON.PhysicsEngine(gravity, plugin);
  25097. return true;
  25098. }
  25099. catch (e) {
  25100. BABYLON.Tools.Error(e.message);
  25101. return false;
  25102. }
  25103. };
  25104. Scene.prototype.disablePhysicsEngine = function () {
  25105. if (!this._physicsEngine) {
  25106. return;
  25107. }
  25108. this._physicsEngine.dispose();
  25109. this._physicsEngine = null;
  25110. };
  25111. Scene.prototype.isPhysicsEnabled = function () {
  25112. return this._physicsEngine !== undefined;
  25113. };
  25114. Scene.prototype.deleteCompoundImpostor = function (compound) {
  25115. var mesh = compound.parts[0].mesh;
  25116. if (mesh.physicsImpostor) {
  25117. mesh.physicsImpostor.dispose();
  25118. mesh.physicsImpostor = null;
  25119. }
  25120. };
  25121. // Misc.
  25122. Scene.prototype._rebuildGeometries = function () {
  25123. for (var _i = 0, _a = this._geometries; _i < _a.length; _i++) {
  25124. var geometry = _a[_i];
  25125. geometry._rebuild();
  25126. }
  25127. for (var _b = 0, _c = this.meshes; _b < _c.length; _b++) {
  25128. var mesh = _c[_b];
  25129. mesh._rebuild();
  25130. }
  25131. if (this.postProcessManager) {
  25132. this.postProcessManager._rebuild();
  25133. }
  25134. for (var _d = 0, _e = this.layers; _d < _e.length; _d++) {
  25135. var layer = _e[_d];
  25136. layer._rebuild();
  25137. }
  25138. for (var _f = 0, _g = this.effectLayers; _f < _g.length; _f++) {
  25139. var effectLayer = _g[_f];
  25140. effectLayer._rebuild();
  25141. }
  25142. if (this._boundingBoxRenderer) {
  25143. this._boundingBoxRenderer._rebuild();
  25144. }
  25145. for (var _h = 0, _j = this.particleSystems; _h < _j.length; _h++) {
  25146. var system = _j[_h];
  25147. system.rebuild();
  25148. }
  25149. if (this._postProcessRenderPipelineManager) {
  25150. this._postProcessRenderPipelineManager._rebuild();
  25151. }
  25152. };
  25153. Scene.prototype._rebuildTextures = function () {
  25154. for (var _i = 0, _a = this.textures; _i < _a.length; _i++) {
  25155. var texture = _a[_i];
  25156. texture._rebuild();
  25157. }
  25158. this.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  25159. };
  25160. /**
  25161. * Creates a default light for the scene.
  25162. * @param replace Whether to replace the existing lights in the scene.
  25163. */
  25164. Scene.prototype.createDefaultLight = function (replace) {
  25165. if (replace === void 0) { replace = false; }
  25166. // Dispose existing light in replace mode.
  25167. if (replace) {
  25168. if (this.lights) {
  25169. for (var i = 0; i < this.lights.length; i++) {
  25170. this.lights[i].dispose();
  25171. }
  25172. }
  25173. }
  25174. // Light
  25175. if (this.lights.length === 0) {
  25176. new BABYLON.HemisphericLight("default light", BABYLON.Vector3.Up(), this);
  25177. }
  25178. };
  25179. /**
  25180. * Creates a default camera for the scene.
  25181. * @param createArcRotateCamera Whether to create an arc rotate or a free camera.
  25182. * @param replace Whether to replace the existing active camera in the scene.
  25183. * @param attachCameraControls Whether to attach camera controls to the canvas.
  25184. */
  25185. Scene.prototype.createDefaultCamera = function (createArcRotateCamera, replace, attachCameraControls) {
  25186. if (createArcRotateCamera === void 0) { createArcRotateCamera = false; }
  25187. if (replace === void 0) { replace = false; }
  25188. if (attachCameraControls === void 0) { attachCameraControls = false; }
  25189. // Dispose existing camera in replace mode.
  25190. if (replace) {
  25191. if (this.activeCamera) {
  25192. this.activeCamera.dispose();
  25193. this.activeCamera = null;
  25194. }
  25195. }
  25196. // Camera
  25197. if (!this.activeCamera) {
  25198. var worldExtends = this.getWorldExtends();
  25199. var worldSize = worldExtends.max.subtract(worldExtends.min);
  25200. var worldCenter = worldExtends.min.add(worldSize.scale(0.5));
  25201. var camera;
  25202. var radius = worldSize.length() * 1.5;
  25203. // empty scene scenario!
  25204. if (!isFinite(radius)) {
  25205. radius = 1;
  25206. worldCenter.copyFromFloats(0, 0, 0);
  25207. }
  25208. if (createArcRotateCamera) {
  25209. var arcRotateCamera = new BABYLON.ArcRotateCamera("default camera", -(Math.PI / 2), Math.PI / 2, radius, worldCenter, this);
  25210. arcRotateCamera.lowerRadiusLimit = radius * 0.01;
  25211. arcRotateCamera.wheelPrecision = 100 / radius;
  25212. camera = arcRotateCamera;
  25213. }
  25214. else {
  25215. var freeCamera = new BABYLON.FreeCamera("default camera", new BABYLON.Vector3(worldCenter.x, worldCenter.y, -radius), this);
  25216. freeCamera.setTarget(worldCenter);
  25217. camera = freeCamera;
  25218. }
  25219. camera.minZ = radius * 0.01;
  25220. camera.maxZ = radius * 1000;
  25221. camera.speed = radius * 0.2;
  25222. this.activeCamera = camera;
  25223. var canvas = this.getEngine().getRenderingCanvas();
  25224. if (attachCameraControls && canvas) {
  25225. camera.attachControl(canvas);
  25226. }
  25227. }
  25228. };
  25229. Scene.prototype.createDefaultCameraOrLight = function (createArcRotateCamera, replace, attachCameraControls) {
  25230. if (createArcRotateCamera === void 0) { createArcRotateCamera = false; }
  25231. if (replace === void 0) { replace = false; }
  25232. if (attachCameraControls === void 0) { attachCameraControls = false; }
  25233. this.createDefaultLight(replace);
  25234. this.createDefaultCamera(createArcRotateCamera, replace, attachCameraControls);
  25235. };
  25236. Scene.prototype.createDefaultSkybox = function (environmentTexture, pbr, scale, blur) {
  25237. if (pbr === void 0) { pbr = false; }
  25238. if (scale === void 0) { scale = 1000; }
  25239. if (blur === void 0) { blur = 0; }
  25240. if (environmentTexture) {
  25241. this.environmentTexture = environmentTexture;
  25242. }
  25243. if (!this.environmentTexture) {
  25244. BABYLON.Tools.Warn("Can not create default skybox without environment texture.");
  25245. return null;
  25246. }
  25247. // Skybox
  25248. var hdrSkybox = BABYLON.Mesh.CreateBox("hdrSkyBox", scale, this);
  25249. if (pbr) {
  25250. var hdrSkyboxMaterial = new BABYLON.PBRMaterial("skyBox", this);
  25251. hdrSkyboxMaterial.backFaceCulling = false;
  25252. hdrSkyboxMaterial.reflectionTexture = this.environmentTexture.clone();
  25253. if (hdrSkyboxMaterial.reflectionTexture) {
  25254. hdrSkyboxMaterial.reflectionTexture.coordinatesMode = BABYLON.Texture.SKYBOX_MODE;
  25255. }
  25256. hdrSkyboxMaterial.microSurface = 1.0 - blur;
  25257. hdrSkyboxMaterial.disableLighting = true;
  25258. hdrSkyboxMaterial.twoSidedLighting = true;
  25259. hdrSkybox.infiniteDistance = true;
  25260. hdrSkybox.material = hdrSkyboxMaterial;
  25261. }
  25262. else {
  25263. var skyboxMaterial = new BABYLON.StandardMaterial("skyBox", this);
  25264. skyboxMaterial.backFaceCulling = false;
  25265. skyboxMaterial.reflectionTexture = this.environmentTexture.clone();
  25266. if (skyboxMaterial.reflectionTexture) {
  25267. skyboxMaterial.reflectionTexture.coordinatesMode = BABYLON.Texture.SKYBOX_MODE;
  25268. }
  25269. skyboxMaterial.disableLighting = true;
  25270. hdrSkybox.infiniteDistance = true;
  25271. hdrSkybox.material = skyboxMaterial;
  25272. }
  25273. return hdrSkybox;
  25274. };
  25275. Scene.prototype.createDefaultEnvironment = function (options) {
  25276. if (BABYLON.EnvironmentHelper) {
  25277. return new BABYLON.EnvironmentHelper(options, this);
  25278. }
  25279. return null;
  25280. };
  25281. Scene.prototype.createDefaultVRExperience = function (webVROptions) {
  25282. if (webVROptions === void 0) { webVROptions = {}; }
  25283. return new BABYLON.VRExperienceHelper(this, webVROptions);
  25284. };
  25285. // Tags
  25286. Scene.prototype._getByTags = function (list, tagsQuery, forEach) {
  25287. if (tagsQuery === undefined) {
  25288. // returns the complete list (could be done with BABYLON.Tags.MatchesQuery but no need to have a for-loop here)
  25289. return list;
  25290. }
  25291. var listByTags = [];
  25292. forEach = forEach || (function (item) { return; });
  25293. for (var i in list) {
  25294. var item = list[i];
  25295. if (BABYLON.Tags && BABYLON.Tags.MatchesQuery(item, tagsQuery)) {
  25296. listByTags.push(item);
  25297. forEach(item);
  25298. }
  25299. }
  25300. return listByTags;
  25301. };
  25302. Scene.prototype.getMeshesByTags = function (tagsQuery, forEach) {
  25303. return this._getByTags(this.meshes, tagsQuery, forEach);
  25304. };
  25305. Scene.prototype.getCamerasByTags = function (tagsQuery, forEach) {
  25306. return this._getByTags(this.cameras, tagsQuery, forEach);
  25307. };
  25308. Scene.prototype.getLightsByTags = function (tagsQuery, forEach) {
  25309. return this._getByTags(this.lights, tagsQuery, forEach);
  25310. };
  25311. Scene.prototype.getMaterialByTags = function (tagsQuery, forEach) {
  25312. return this._getByTags(this.materials, tagsQuery, forEach).concat(this._getByTags(this.multiMaterials, tagsQuery, forEach));
  25313. };
  25314. /**
  25315. * Overrides the default sort function applied in the renderging group to prepare the meshes.
  25316. * This allowed control for front to back rendering or reversly depending of the special needs.
  25317. *
  25318. * @param renderingGroupId The rendering group id corresponding to its index
  25319. * @param opaqueSortCompareFn The opaque queue comparison function use to sort.
  25320. * @param alphaTestSortCompareFn The alpha test queue comparison function use to sort.
  25321. * @param transparentSortCompareFn The transparent queue comparison function use to sort.
  25322. */
  25323. Scene.prototype.setRenderingOrder = function (renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  25324. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  25325. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  25326. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  25327. this._renderingManager.setRenderingOrder(renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn);
  25328. };
  25329. /**
  25330. * Specifies whether or not the stencil and depth buffer are cleared between two rendering groups.
  25331. *
  25332. * @param renderingGroupId The rendering group id corresponding to its index
  25333. * @param autoClearDepthStencil Automatically clears depth and stencil between groups if true.
  25334. * @param depth Automatically clears depth between groups if true and autoClear is true.
  25335. * @param stencil Automatically clears stencil between groups if true and autoClear is true.
  25336. */
  25337. Scene.prototype.setRenderingAutoClearDepthStencil = function (renderingGroupId, autoClearDepthStencil, depth, stencil) {
  25338. if (depth === void 0) { depth = true; }
  25339. if (stencil === void 0) { stencil = true; }
  25340. this._renderingManager.setRenderingAutoClearDepthStencil(renderingGroupId, autoClearDepthStencil, depth, stencil);
  25341. };
  25342. /**
  25343. * Will flag all materials as dirty to trigger new shader compilation
  25344. * @param predicate If not null, it will be used to specifiy if a material has to be marked as dirty
  25345. */
  25346. Scene.prototype.markAllMaterialsAsDirty = function (flag, predicate) {
  25347. for (var _i = 0, _a = this.materials; _i < _a.length; _i++) {
  25348. var material = _a[_i];
  25349. if (predicate && !predicate(material)) {
  25350. continue;
  25351. }
  25352. material.markAsDirty(flag);
  25353. }
  25354. };
  25355. Scene.prototype._loadFile = function (url, onSuccess, onProgress, useDatabase, useArrayBuffer, onError) {
  25356. var _this = this;
  25357. var request = BABYLON.Tools.LoadFile(url, onSuccess, onProgress, useDatabase ? this.database : undefined, useArrayBuffer, onError);
  25358. this._activeRequests.push(request);
  25359. request.onCompleteObservable.add(function (request) {
  25360. _this._activeRequests.splice(_this._activeRequests.indexOf(request), 1);
  25361. });
  25362. return request;
  25363. };
  25364. /** @ignore */
  25365. Scene.prototype._loadFileAsync = function (url, useDatabase, useArrayBuffer) {
  25366. var _this = this;
  25367. return new Promise(function (resolve, reject) {
  25368. _this._loadFile(url, function (data) {
  25369. resolve(data);
  25370. }, undefined, useDatabase, useArrayBuffer, function (request, exception) {
  25371. reject(exception);
  25372. });
  25373. });
  25374. };
  25375. // Statics
  25376. Scene._FOGMODE_NONE = 0;
  25377. Scene._FOGMODE_EXP = 1;
  25378. Scene._FOGMODE_EXP2 = 2;
  25379. Scene._FOGMODE_LINEAR = 3;
  25380. Scene._uniqueIdCounter = 0;
  25381. Scene.MinDeltaTime = 1.0;
  25382. Scene.MaxDeltaTime = 1000.0;
  25383. /** The distance in pixel that you have to move to prevent some events */
  25384. Scene.DragMovementThreshold = 10; // in pixels
  25385. /** Time in milliseconds to wait to raise long press events if button is still pressed */
  25386. Scene.LongPressDelay = 500; // in milliseconds
  25387. /** Time in milliseconds with two consecutive clicks will be considered as a double click */
  25388. Scene.DoubleClickDelay = 300; // in milliseconds
  25389. /** If you need to check double click without raising a single click at first click, enable this flag */
  25390. Scene.ExclusiveDoubleClickMode = false;
  25391. return Scene;
  25392. }());
  25393. BABYLON.Scene = Scene;
  25394. })(BABYLON || (BABYLON = {}));
  25395. //# sourceMappingURL=babylon.scene.js.map
  25396. var BABYLON;
  25397. (function (BABYLON) {
  25398. /**
  25399. * Set of assets to keep when moving a scene into an asset container.
  25400. */
  25401. var KeepAssets = /** @class */ (function () {
  25402. function KeepAssets() {
  25403. /**
  25404. * Cameras to keep.
  25405. */
  25406. this.cameras = new Array();
  25407. /**
  25408. * Lights to keep.
  25409. */
  25410. this.lights = new Array();
  25411. /**
  25412. * Meshes to keep.
  25413. */
  25414. this.meshes = new Array();
  25415. /**
  25416. * Skeletons to keep.
  25417. */
  25418. this.skeletons = new Array();
  25419. /**
  25420. * ParticleSystems to keep.
  25421. */
  25422. this.particleSystems = new Array();
  25423. /**
  25424. * Animations to keep.
  25425. */
  25426. this.animations = new Array();
  25427. /**
  25428. * MultiMaterials to keep.
  25429. */
  25430. this.multiMaterials = new Array();
  25431. /**
  25432. * Materials to keep.
  25433. */
  25434. this.materials = new Array();
  25435. /**
  25436. * MorphTargetManagers to keep.
  25437. */
  25438. this.morphTargetManagers = new Array();
  25439. /**
  25440. * Geometries to keep.
  25441. */
  25442. this.geometries = new Array();
  25443. /**
  25444. * TransformNodes to keep.
  25445. */
  25446. this.transformNodes = new Array();
  25447. /**
  25448. * LensFlareSystems to keep.
  25449. */
  25450. this.lensFlareSystems = new Array();
  25451. /**
  25452. * ShadowGenerators to keep.
  25453. */
  25454. this.shadowGenerators = new Array();
  25455. /**
  25456. * ActionManagers to keep.
  25457. */
  25458. this.actionManagers = new Array();
  25459. /**
  25460. * Sounds to keep.
  25461. */
  25462. this.sounds = new Array();
  25463. }
  25464. return KeepAssets;
  25465. }());
  25466. BABYLON.KeepAssets = KeepAssets;
  25467. /**
  25468. * Container with a set of assets that can be added or removed from a scene.
  25469. */
  25470. var AssetContainer = /** @class */ (function () {
  25471. /**
  25472. * Instantiates an AssetContainer.
  25473. * @param scene The scene the AssetContainer belongs to.
  25474. */
  25475. function AssetContainer(scene) {
  25476. // Objects
  25477. /**
  25478. * Cameras populated in the container.
  25479. */
  25480. this.cameras = new Array();
  25481. /**
  25482. * Lights populated in the container.
  25483. */
  25484. this.lights = new Array();
  25485. /**
  25486. * Meshes populated in the container.
  25487. */
  25488. this.meshes = new Array();
  25489. /**
  25490. * Skeletons populated in the container.
  25491. */
  25492. this.skeletons = new Array();
  25493. /**
  25494. * ParticleSystems populated in the container.
  25495. */
  25496. this.particleSystems = new Array();
  25497. /**
  25498. * Animations populated in the container.
  25499. */
  25500. this.animations = new Array();
  25501. /**
  25502. * MultiMaterials populated in the container.
  25503. */
  25504. this.multiMaterials = new Array();
  25505. /**
  25506. * Materials populated in the container.
  25507. */
  25508. this.materials = new Array();
  25509. /**
  25510. * MorphTargetManagers populated in the container.
  25511. */
  25512. this.morphTargetManagers = new Array();
  25513. /**
  25514. * Geometries populated in the container.
  25515. */
  25516. this.geometries = new Array();
  25517. /**
  25518. * TransformNodes populated in the container.
  25519. */
  25520. this.transformNodes = new Array();
  25521. /**
  25522. * LensFlareSystems populated in the container.
  25523. */
  25524. this.lensFlareSystems = new Array();
  25525. /**
  25526. * ShadowGenerators populated in the container.
  25527. */
  25528. this.shadowGenerators = new Array();
  25529. /**
  25530. * ActionManagers populated in the container.
  25531. */
  25532. this.actionManagers = new Array();
  25533. /**
  25534. * Sounds populated in the container.
  25535. */
  25536. this.sounds = new Array();
  25537. this.scene = scene;
  25538. }
  25539. /**
  25540. * Adds all the assets from the container to the scene.
  25541. */
  25542. AssetContainer.prototype.addAllToScene = function () {
  25543. var _this = this;
  25544. this.cameras.forEach(function (o) {
  25545. _this.scene.addCamera(o);
  25546. });
  25547. this.lights.forEach(function (o) {
  25548. _this.scene.addLight(o);
  25549. });
  25550. this.meshes.forEach(function (o) {
  25551. _this.scene.addMesh(o);
  25552. });
  25553. this.skeletons.forEach(function (o) {
  25554. _this.scene.addSkeleton(o);
  25555. });
  25556. this.particleSystems.forEach(function (o) {
  25557. _this.scene.addParticleSystem(o);
  25558. });
  25559. this.animations.forEach(function (o) {
  25560. _this.scene.addAnimation(o);
  25561. });
  25562. this.multiMaterials.forEach(function (o) {
  25563. _this.scene.addMultiMaterial(o);
  25564. });
  25565. this.materials.forEach(function (o) {
  25566. _this.scene.addMaterial(o);
  25567. });
  25568. this.morphTargetManagers.forEach(function (o) {
  25569. _this.scene.addMorphTargetManager(o);
  25570. });
  25571. this.geometries.forEach(function (o) {
  25572. _this.scene.addGeometry(o);
  25573. });
  25574. this.transformNodes.forEach(function (o) {
  25575. _this.scene.addTransformNode(o);
  25576. });
  25577. this.lensFlareSystems.forEach(function (o) {
  25578. _this.scene.addLensFlareSystem(o);
  25579. });
  25580. this.actionManagers.forEach(function (o) {
  25581. _this.scene.addActionManager(o);
  25582. });
  25583. this.sounds.forEach(function (o) {
  25584. o.play();
  25585. o.autoplay = true;
  25586. _this.scene.mainSoundTrack.AddSound(o);
  25587. });
  25588. };
  25589. /**
  25590. * Removes all the assets in the container from the scene
  25591. */
  25592. AssetContainer.prototype.removeAllFromScene = function () {
  25593. var _this = this;
  25594. this.cameras.forEach(function (o) {
  25595. _this.scene.removeCamera(o);
  25596. });
  25597. this.lights.forEach(function (o) {
  25598. _this.scene.removeLight(o);
  25599. });
  25600. this.meshes.forEach(function (o) {
  25601. _this.scene.removeMesh(o);
  25602. });
  25603. this.skeletons.forEach(function (o) {
  25604. _this.scene.removeSkeleton(o);
  25605. });
  25606. this.particleSystems.forEach(function (o) {
  25607. _this.scene.removeParticleSystem(o);
  25608. });
  25609. this.animations.forEach(function (o) {
  25610. _this.scene.removeAnimation(o);
  25611. });
  25612. this.multiMaterials.forEach(function (o) {
  25613. _this.scene.removeMultiMaterial(o);
  25614. });
  25615. this.materials.forEach(function (o) {
  25616. _this.scene.removeMaterial(o);
  25617. });
  25618. this.morphTargetManagers.forEach(function (o) {
  25619. _this.scene.removeMorphTargetManager(o);
  25620. });
  25621. this.geometries.forEach(function (o) {
  25622. _this.scene.removeGeometry(o);
  25623. });
  25624. this.transformNodes.forEach(function (o) {
  25625. _this.scene.removeTransformNode(o);
  25626. });
  25627. this.lensFlareSystems.forEach(function (o) {
  25628. _this.scene.removeLensFlareSystem(o);
  25629. });
  25630. this.actionManagers.forEach(function (o) {
  25631. _this.scene.removeActionManager(o);
  25632. });
  25633. this.sounds.forEach(function (o) {
  25634. o.stop();
  25635. o.autoplay = false;
  25636. _this.scene.mainSoundTrack.RemoveSound(o);
  25637. });
  25638. };
  25639. AssetContainer.prototype._moveAssets = function (sourceAssets, targetAssets, keepAssets) {
  25640. for (var _i = 0, sourceAssets_1 = sourceAssets; _i < sourceAssets_1.length; _i++) {
  25641. var asset = sourceAssets_1[_i];
  25642. var move = true;
  25643. for (var _a = 0, keepAssets_1 = keepAssets; _a < keepAssets_1.length; _a++) {
  25644. var keepAsset = keepAssets_1[_a];
  25645. if (asset === keepAsset) {
  25646. move = false;
  25647. break;
  25648. }
  25649. }
  25650. if (move) {
  25651. targetAssets.push(asset);
  25652. }
  25653. }
  25654. };
  25655. /**
  25656. * Removes all the assets contained in the scene and adds them to the container.
  25657. * @param keepAssets Set of assets to keep in the scene. (default: empty)
  25658. */
  25659. AssetContainer.prototype.moveAllFromScene = function (keepAssets) {
  25660. if (keepAssets === undefined) {
  25661. keepAssets = new KeepAssets();
  25662. }
  25663. this._moveAssets(this.scene.cameras, this.cameras, keepAssets.cameras);
  25664. this._moveAssets(this.scene.meshes, this.meshes, keepAssets.meshes);
  25665. this._moveAssets(this.scene.getGeometries(), this.geometries, keepAssets.geometries);
  25666. this._moveAssets(this.scene.materials, this.materials, keepAssets.materials);
  25667. this._moveAssets(this.scene._actionManagers, this.actionManagers, keepAssets.actionManagers);
  25668. this._moveAssets(this.scene.animations, this.animations, keepAssets.animations);
  25669. this._moveAssets(this.scene.lensFlareSystems, this.lensFlareSystems, keepAssets.lensFlareSystems);
  25670. this._moveAssets(this.scene.lights, this.lights, keepAssets.lights);
  25671. this._moveAssets(this.scene.morphTargetManagers, this.morphTargetManagers, keepAssets.morphTargetManagers);
  25672. this._moveAssets(this.scene.multiMaterials, this.multiMaterials, keepAssets.multiMaterials);
  25673. this._moveAssets(this.scene.skeletons, this.skeletons, keepAssets.skeletons);
  25674. this._moveAssets(this.scene.particleSystems, this.particleSystems, keepAssets.particleSystems);
  25675. this._moveAssets(this.scene.mainSoundTrack.soundCollection, this.sounds, keepAssets.sounds);
  25676. this._moveAssets(this.scene.transformNodes, this.transformNodes, keepAssets.transformNodes);
  25677. this.removeAllFromScene();
  25678. };
  25679. return AssetContainer;
  25680. }());
  25681. BABYLON.AssetContainer = AssetContainer;
  25682. })(BABYLON || (BABYLON = {}));
  25683. //# sourceMappingURL=babylon.assetContainer.js.map
  25684. var BABYLON;
  25685. (function (BABYLON) {
  25686. var Buffer = /** @class */ (function () {
  25687. function Buffer(engine, data, updatable, stride, postponeInternalCreation, instanced) {
  25688. if (instanced === void 0) { instanced = false; }
  25689. if (engine instanceof BABYLON.Mesh) {
  25690. this._engine = engine.getScene().getEngine();
  25691. }
  25692. else {
  25693. this._engine = engine;
  25694. }
  25695. this._updatable = updatable;
  25696. this._instanced = instanced;
  25697. this._data = data;
  25698. this._strideSize = stride;
  25699. if (!postponeInternalCreation) {
  25700. this.create();
  25701. }
  25702. }
  25703. /**
  25704. * Create a new {BABYLON.VertexBuffer} based on the current buffer
  25705. * @param kind defines the vertex buffer kind (position, normal, etc.)
  25706. * @param offset defines offset in the buffer (0 by default)
  25707. * @param size defines the size in floats of attributes (position is 3 for instance)
  25708. * @param stride defines the stride size in floats in the buffer (the offset to apply to reach next value when data is interleaved)
  25709. * @param instanced defines if the vertex buffer contains indexed data
  25710. * @returns the new vertex buffer
  25711. */
  25712. Buffer.prototype.createVertexBuffer = function (kind, offset, size, stride, instanced) {
  25713. // a lot of these parameters are ignored as they are overriden by the buffer
  25714. return new BABYLON.VertexBuffer(this._engine, this, kind, this._updatable, true, stride ? stride : this._strideSize, instanced === undefined ? this._instanced : instanced, offset, size);
  25715. };
  25716. // Properties
  25717. Buffer.prototype.isUpdatable = function () {
  25718. return this._updatable;
  25719. };
  25720. Buffer.prototype.getData = function () {
  25721. return this._data;
  25722. };
  25723. Buffer.prototype.getBuffer = function () {
  25724. return this._buffer;
  25725. };
  25726. Buffer.prototype.getStrideSize = function () {
  25727. return this._strideSize;
  25728. };
  25729. // public getIsInstanced(): boolean {
  25730. // return this._instanced;
  25731. // }
  25732. // public get instanceDivisor(): number {
  25733. // return this._instanceDivisor;
  25734. // }
  25735. // public set instanceDivisor(value: number) {
  25736. // this._instanceDivisor = value;
  25737. // if (value == 0) {
  25738. // this._instanced = false;
  25739. // } else {
  25740. // this._instanced = true;
  25741. // }
  25742. // }
  25743. // Methods
  25744. Buffer.prototype.create = function (data) {
  25745. if (data === void 0) { data = null; }
  25746. if (!data && this._buffer) {
  25747. return; // nothing to do
  25748. }
  25749. data = data || this._data;
  25750. if (!data) {
  25751. return;
  25752. }
  25753. if (!this._buffer) {
  25754. if (this._updatable) {
  25755. this._buffer = this._engine.createDynamicVertexBuffer(data);
  25756. this._data = data;
  25757. }
  25758. else {
  25759. this._buffer = this._engine.createVertexBuffer(data);
  25760. }
  25761. }
  25762. else if (this._updatable) {
  25763. this._engine.updateDynamicVertexBuffer(this._buffer, data);
  25764. this._data = data;
  25765. }
  25766. };
  25767. Buffer.prototype._rebuild = function () {
  25768. this._buffer = null;
  25769. this.create(this._data);
  25770. };
  25771. Buffer.prototype.update = function (data) {
  25772. this.create(data);
  25773. };
  25774. Buffer.prototype.updateDirectly = function (data, offset, vertexCount) {
  25775. if (!this._buffer) {
  25776. return;
  25777. }
  25778. if (this._updatable) {
  25779. this._engine.updateDynamicVertexBuffer(this._buffer, data, offset, (vertexCount ? vertexCount * this.getStrideSize() : undefined));
  25780. this._data = null;
  25781. }
  25782. };
  25783. Buffer.prototype.dispose = function () {
  25784. if (!this._buffer) {
  25785. return;
  25786. }
  25787. if (this._engine._releaseBuffer(this._buffer)) {
  25788. this._buffer = null;
  25789. }
  25790. };
  25791. return Buffer;
  25792. }());
  25793. BABYLON.Buffer = Buffer;
  25794. })(BABYLON || (BABYLON = {}));
  25795. //# sourceMappingURL=babylon.buffer.js.map
  25796. var BABYLON;
  25797. (function (BABYLON) {
  25798. var VertexBuffer = /** @class */ (function () {
  25799. function VertexBuffer(engine, data, kind, updatable, postponeInternalCreation, stride, instanced, offset, size) {
  25800. if (data instanceof BABYLON.Buffer) {
  25801. if (!stride) {
  25802. stride = data.getStrideSize();
  25803. }
  25804. this._buffer = data;
  25805. this._ownsBuffer = false;
  25806. }
  25807. else {
  25808. if (!stride) {
  25809. stride = VertexBuffer.DeduceStride(kind);
  25810. }
  25811. this._buffer = new BABYLON.Buffer(engine, data, updatable, stride, postponeInternalCreation, instanced);
  25812. this._ownsBuffer = true;
  25813. }
  25814. this._stride = stride;
  25815. this._instanced = instanced !== undefined ? instanced : false;
  25816. this._instanceDivisor = instanced ? 1 : 0;
  25817. this._offset = offset ? offset : 0;
  25818. this._size = size ? size : stride;
  25819. this._kind = kind;
  25820. }
  25821. Object.defineProperty(VertexBuffer.prototype, "instanceDivisor", {
  25822. /**
  25823. * Gets or sets the instance divisor when in instanced mode
  25824. */
  25825. get: function () {
  25826. return this._instanceDivisor;
  25827. },
  25828. set: function (value) {
  25829. this._instanceDivisor = value;
  25830. if (value == 0) {
  25831. this._instanced = false;
  25832. }
  25833. else {
  25834. this._instanced = true;
  25835. }
  25836. },
  25837. enumerable: true,
  25838. configurable: true
  25839. });
  25840. VertexBuffer.prototype._rebuild = function () {
  25841. if (!this._buffer) {
  25842. return;
  25843. }
  25844. this._buffer._rebuild();
  25845. };
  25846. /**
  25847. * Returns the kind of the VertexBuffer (string).
  25848. */
  25849. VertexBuffer.prototype.getKind = function () {
  25850. return this._kind;
  25851. };
  25852. // Properties
  25853. /**
  25854. * Boolean : is the VertexBuffer updatable ?
  25855. */
  25856. VertexBuffer.prototype.isUpdatable = function () {
  25857. return this._buffer.isUpdatable();
  25858. };
  25859. /**
  25860. * Returns an array of numbers or a Float32Array containing the VertexBuffer data.
  25861. */
  25862. VertexBuffer.prototype.getData = function () {
  25863. return this._buffer.getData();
  25864. };
  25865. /**
  25866. * Returns the WebGLBuffer associated to the VertexBuffer.
  25867. */
  25868. VertexBuffer.prototype.getBuffer = function () {
  25869. return this._buffer.getBuffer();
  25870. };
  25871. /**
  25872. * Returns the stride of the VertexBuffer (integer).
  25873. */
  25874. VertexBuffer.prototype.getStrideSize = function () {
  25875. return this._stride;
  25876. };
  25877. /**
  25878. * Returns the offset (integer).
  25879. */
  25880. VertexBuffer.prototype.getOffset = function () {
  25881. return this._offset;
  25882. };
  25883. /**
  25884. * Returns the VertexBuffer total size (integer).
  25885. */
  25886. VertexBuffer.prototype.getSize = function () {
  25887. return this._size;
  25888. };
  25889. /**
  25890. * Boolean : is the WebGLBuffer of the VertexBuffer instanced now ?
  25891. */
  25892. VertexBuffer.prototype.getIsInstanced = function () {
  25893. return this._instanced;
  25894. };
  25895. /**
  25896. * Returns the instancing divisor, zero for non-instanced (integer).
  25897. */
  25898. VertexBuffer.prototype.getInstanceDivisor = function () {
  25899. return this._instanceDivisor;
  25900. };
  25901. // Methods
  25902. /**
  25903. * Creates the underlying WebGLBuffer from the passed numeric array or Float32Array.
  25904. * Returns the created WebGLBuffer.
  25905. */
  25906. VertexBuffer.prototype.create = function (data) {
  25907. return this._buffer.create(data);
  25908. };
  25909. /**
  25910. * Updates the underlying WebGLBuffer according to the passed numeric array or Float32Array.
  25911. * This function will create a new buffer if the current one is not updatable
  25912. * Returns the updated WebGLBuffer.
  25913. */
  25914. VertexBuffer.prototype.update = function (data) {
  25915. return this._buffer.update(data);
  25916. };
  25917. /**
  25918. * Updates directly the underlying WebGLBuffer according to the passed numeric array or Float32Array.
  25919. * Returns the directly updated WebGLBuffer.
  25920. */
  25921. VertexBuffer.prototype.updateDirectly = function (data, offset) {
  25922. return this._buffer.updateDirectly(data, offset);
  25923. };
  25924. /**
  25925. * Disposes the VertexBuffer and the underlying WebGLBuffer.
  25926. */
  25927. VertexBuffer.prototype.dispose = function () {
  25928. if (this._ownsBuffer) {
  25929. this._buffer.dispose();
  25930. }
  25931. };
  25932. Object.defineProperty(VertexBuffer, "PositionKind", {
  25933. get: function () {
  25934. return VertexBuffer._PositionKind;
  25935. },
  25936. enumerable: true,
  25937. configurable: true
  25938. });
  25939. Object.defineProperty(VertexBuffer, "NormalKind", {
  25940. get: function () {
  25941. return VertexBuffer._NormalKind;
  25942. },
  25943. enumerable: true,
  25944. configurable: true
  25945. });
  25946. Object.defineProperty(VertexBuffer, "TangentKind", {
  25947. get: function () {
  25948. return VertexBuffer._TangentKind;
  25949. },
  25950. enumerable: true,
  25951. configurable: true
  25952. });
  25953. Object.defineProperty(VertexBuffer, "UVKind", {
  25954. get: function () {
  25955. return VertexBuffer._UVKind;
  25956. },
  25957. enumerable: true,
  25958. configurable: true
  25959. });
  25960. Object.defineProperty(VertexBuffer, "UV2Kind", {
  25961. get: function () {
  25962. return VertexBuffer._UV2Kind;
  25963. },
  25964. enumerable: true,
  25965. configurable: true
  25966. });
  25967. Object.defineProperty(VertexBuffer, "UV3Kind", {
  25968. get: function () {
  25969. return VertexBuffer._UV3Kind;
  25970. },
  25971. enumerable: true,
  25972. configurable: true
  25973. });
  25974. Object.defineProperty(VertexBuffer, "UV4Kind", {
  25975. get: function () {
  25976. return VertexBuffer._UV4Kind;
  25977. },
  25978. enumerable: true,
  25979. configurable: true
  25980. });
  25981. Object.defineProperty(VertexBuffer, "UV5Kind", {
  25982. get: function () {
  25983. return VertexBuffer._UV5Kind;
  25984. },
  25985. enumerable: true,
  25986. configurable: true
  25987. });
  25988. Object.defineProperty(VertexBuffer, "UV6Kind", {
  25989. get: function () {
  25990. return VertexBuffer._UV6Kind;
  25991. },
  25992. enumerable: true,
  25993. configurable: true
  25994. });
  25995. Object.defineProperty(VertexBuffer, "ColorKind", {
  25996. get: function () {
  25997. return VertexBuffer._ColorKind;
  25998. },
  25999. enumerable: true,
  26000. configurable: true
  26001. });
  26002. Object.defineProperty(VertexBuffer, "MatricesIndicesKind", {
  26003. get: function () {
  26004. return VertexBuffer._MatricesIndicesKind;
  26005. },
  26006. enumerable: true,
  26007. configurable: true
  26008. });
  26009. Object.defineProperty(VertexBuffer, "MatricesWeightsKind", {
  26010. get: function () {
  26011. return VertexBuffer._MatricesWeightsKind;
  26012. },
  26013. enumerable: true,
  26014. configurable: true
  26015. });
  26016. Object.defineProperty(VertexBuffer, "MatricesIndicesExtraKind", {
  26017. get: function () {
  26018. return VertexBuffer._MatricesIndicesExtraKind;
  26019. },
  26020. enumerable: true,
  26021. configurable: true
  26022. });
  26023. Object.defineProperty(VertexBuffer, "MatricesWeightsExtraKind", {
  26024. get: function () {
  26025. return VertexBuffer._MatricesWeightsExtraKind;
  26026. },
  26027. enumerable: true,
  26028. configurable: true
  26029. });
  26030. /**
  26031. * Deduces the stride given a kind.
  26032. * @param kind The kind string to deduce
  26033. * @returns The deduced stride
  26034. */
  26035. VertexBuffer.DeduceStride = function (kind) {
  26036. switch (kind) {
  26037. case VertexBuffer.UVKind:
  26038. case VertexBuffer.UV2Kind:
  26039. case VertexBuffer.UV3Kind:
  26040. case VertexBuffer.UV4Kind:
  26041. case VertexBuffer.UV5Kind:
  26042. case VertexBuffer.UV6Kind:
  26043. return 2;
  26044. case VertexBuffer.NormalKind:
  26045. case VertexBuffer.PositionKind:
  26046. return 3;
  26047. case VertexBuffer.ColorKind:
  26048. case VertexBuffer.MatricesIndicesKind:
  26049. case VertexBuffer.MatricesIndicesExtraKind:
  26050. case VertexBuffer.MatricesWeightsKind:
  26051. case VertexBuffer.MatricesWeightsExtraKind:
  26052. case VertexBuffer.TangentKind:
  26053. return 4;
  26054. default:
  26055. throw new Error("Invalid kind '" + kind + "'");
  26056. }
  26057. };
  26058. // Enums
  26059. VertexBuffer._PositionKind = "position";
  26060. VertexBuffer._NormalKind = "normal";
  26061. VertexBuffer._TangentKind = "tangent";
  26062. VertexBuffer._UVKind = "uv";
  26063. VertexBuffer._UV2Kind = "uv2";
  26064. VertexBuffer._UV3Kind = "uv3";
  26065. VertexBuffer._UV4Kind = "uv4";
  26066. VertexBuffer._UV5Kind = "uv5";
  26067. VertexBuffer._UV6Kind = "uv6";
  26068. VertexBuffer._ColorKind = "color";
  26069. VertexBuffer._MatricesIndicesKind = "matricesIndices";
  26070. VertexBuffer._MatricesWeightsKind = "matricesWeights";
  26071. VertexBuffer._MatricesIndicesExtraKind = "matricesIndicesExtra";
  26072. VertexBuffer._MatricesWeightsExtraKind = "matricesWeightsExtra";
  26073. return VertexBuffer;
  26074. }());
  26075. BABYLON.VertexBuffer = VertexBuffer;
  26076. })(BABYLON || (BABYLON = {}));
  26077. //# sourceMappingURL=babylon.vertexBuffer.js.map
  26078. var BABYLON;
  26079. (function (BABYLON) {
  26080. /**
  26081. * Internal class used by the engine to get list of {BABYLON.InternalTexture} already bound to the GL context
  26082. */
  26083. var DummyInternalTextureTracker = /** @class */ (function () {
  26084. function DummyInternalTextureTracker() {
  26085. /**
  26086. * Gets or set the previous tracker in the list
  26087. */
  26088. this.previous = null;
  26089. /**
  26090. * Gets or set the next tracker in the list
  26091. */
  26092. this.next = null;
  26093. }
  26094. return DummyInternalTextureTracker;
  26095. }());
  26096. BABYLON.DummyInternalTextureTracker = DummyInternalTextureTracker;
  26097. })(BABYLON || (BABYLON = {}));
  26098. //# sourceMappingURL=babylon.internalTextureTracker.js.map
  26099. var BABYLON;
  26100. (function (BABYLON) {
  26101. /**
  26102. * Class used to store data associated with WebGL texture data for the engine
  26103. * This class should not be used directly
  26104. */
  26105. var InternalTexture = /** @class */ (function () {
  26106. /**
  26107. * Creates a new InternalTexture
  26108. * @param engine defines the engine to use
  26109. * @param dataSource defines the type of data that will be used
  26110. */
  26111. function InternalTexture(engine, dataSource) {
  26112. /**
  26113. * Observable called when the texture is loaded
  26114. */
  26115. this.onLoadedObservable = new BABYLON.Observable();
  26116. /**
  26117. * Gets or set the previous tracker in the list
  26118. */
  26119. this.previous = null;
  26120. /**
  26121. * Gets or set the next tracker in the list
  26122. */
  26123. this.next = null;
  26124. // Private
  26125. /** @ignore */
  26126. this._initialSlot = -1;
  26127. /** @ignore */
  26128. this._designatedSlot = -1;
  26129. /** @ignore */
  26130. this._dataSource = InternalTexture.DATASOURCE_UNKNOWN;
  26131. /** @ignore */
  26132. this._comparisonFunction = 0;
  26133. /** @ignore */
  26134. this._references = 1;
  26135. this._engine = engine;
  26136. this._dataSource = dataSource;
  26137. this._webGLTexture = engine._createTexture();
  26138. }
  26139. Object.defineProperty(InternalTexture.prototype, "dataSource", {
  26140. /**
  26141. * Gets the data source type of the texture (can be one of the BABYLON.InternalTexture.DATASOURCE_XXXX)
  26142. */
  26143. get: function () {
  26144. return this._dataSource;
  26145. },
  26146. enumerable: true,
  26147. configurable: true
  26148. });
  26149. /**
  26150. * Increments the number of references (ie. the number of {BABYLON.Texture} that point to it)
  26151. */
  26152. InternalTexture.prototype.incrementReferences = function () {
  26153. this._references++;
  26154. };
  26155. /**
  26156. * Change the size of the texture (not the size of the content)
  26157. * @param width defines the new width
  26158. * @param height defines the new height
  26159. * @param depth defines the new depth (1 by default)
  26160. */
  26161. InternalTexture.prototype.updateSize = function (width, height, depth) {
  26162. if (depth === void 0) { depth = 1; }
  26163. this.width = width;
  26164. this.height = height;
  26165. this.depth = depth;
  26166. this.baseWidth = width;
  26167. this.baseHeight = height;
  26168. this.baseDepth = depth;
  26169. this._size = width * height * depth;
  26170. };
  26171. /** @ignore */
  26172. InternalTexture.prototype._rebuild = function () {
  26173. var _this = this;
  26174. var proxy;
  26175. this.isReady = false;
  26176. this._cachedCoordinatesMode = null;
  26177. this._cachedWrapU = null;
  26178. this._cachedWrapV = null;
  26179. this._cachedAnisotropicFilteringLevel = null;
  26180. switch (this._dataSource) {
  26181. case InternalTexture.DATASOURCE_TEMP:
  26182. return;
  26183. case InternalTexture.DATASOURCE_URL:
  26184. proxy = this._engine.createTexture(this.url, !this.generateMipMaps, this.invertY, null, this.samplingMode, function () {
  26185. _this.isReady = true;
  26186. }, null, this._buffer, undefined, this.format);
  26187. proxy._swapAndDie(this);
  26188. return;
  26189. case InternalTexture.DATASOURCE_RAW:
  26190. proxy = this._engine.createRawTexture(this._bufferView, this.baseWidth, this.baseHeight, this.format, this.generateMipMaps, this.invertY, this.samplingMode, this._compression);
  26191. proxy._swapAndDie(this);
  26192. this.isReady = true;
  26193. return;
  26194. case InternalTexture.DATASOURCE_RAW3D:
  26195. proxy = this._engine.createRawTexture3D(this._bufferView, this.baseWidth, this.baseHeight, this.baseDepth, this.format, this.generateMipMaps, this.invertY, this.samplingMode, this._compression);
  26196. proxy._swapAndDie(this);
  26197. this.isReady = true;
  26198. return;
  26199. case InternalTexture.DATASOURCE_DYNAMIC:
  26200. proxy = this._engine.createDynamicTexture(this.baseWidth, this.baseHeight, this.generateMipMaps, this.samplingMode);
  26201. proxy._swapAndDie(this);
  26202. // The engine will make sure to update content so no need to flag it as isReady = true
  26203. return;
  26204. case InternalTexture.DATASOURCE_RENDERTARGET:
  26205. var options = new BABYLON.RenderTargetCreationOptions();
  26206. options.generateDepthBuffer = this._generateDepthBuffer;
  26207. options.generateMipMaps = this.generateMipMaps;
  26208. options.generateStencilBuffer = this._generateStencilBuffer;
  26209. options.samplingMode = this.samplingMode;
  26210. options.type = this.type;
  26211. if (this.isCube) {
  26212. proxy = this._engine.createRenderTargetCubeTexture(this.width, options);
  26213. }
  26214. else {
  26215. var size = {
  26216. width: this.width,
  26217. height: this.height
  26218. };
  26219. proxy = this._engine.createRenderTargetTexture(size, options);
  26220. }
  26221. proxy._swapAndDie(this);
  26222. this.isReady = true;
  26223. return;
  26224. case InternalTexture.DATASOURCE_DEPTHTEXTURE:
  26225. var depthTextureOptions = {
  26226. bilinearFiltering: this.samplingMode !== BABYLON.Texture.BILINEAR_SAMPLINGMODE,
  26227. comparisonFunction: this._comparisonFunction,
  26228. generateStencil: this._generateStencilBuffer,
  26229. };
  26230. if (this.isCube) {
  26231. proxy = this._engine.createDepthStencilTexture({ width: this.width, height: this.height }, depthTextureOptions);
  26232. }
  26233. else {
  26234. proxy = this._engine.createDepthStencilCubeTexture(this.width, depthTextureOptions);
  26235. }
  26236. proxy._swapAndDie(this);
  26237. this.isReady = true;
  26238. return;
  26239. case InternalTexture.DATASOURCE_CUBE:
  26240. proxy = this._engine.createCubeTexture(this.url, null, this._files, !this.generateMipMaps, function () {
  26241. _this.isReady = true;
  26242. }, null, this.format, this._extension);
  26243. proxy._swapAndDie(this);
  26244. return;
  26245. case InternalTexture.DATASOURCE_CUBERAW:
  26246. proxy = this._engine.createRawCubeTexture(this._bufferViewArray, this.width, this.format, this.type, this.generateMipMaps, this.invertY, this.samplingMode, this._compression);
  26247. proxy._swapAndDie(this);
  26248. this.isReady = true;
  26249. return;
  26250. case InternalTexture.DATASOURCE_CUBEPREFILTERED:
  26251. proxy = this._engine.createPrefilteredCubeTexture(this.url, null, this._lodGenerationScale, this._lodGenerationOffset, function (proxy) {
  26252. if (proxy) {
  26253. proxy._swapAndDie(_this);
  26254. }
  26255. _this.isReady = true;
  26256. }, null, this.format, this._extension);
  26257. return;
  26258. }
  26259. };
  26260. InternalTexture.prototype._swapAndDie = function (target) {
  26261. target._webGLTexture = this._webGLTexture;
  26262. if (this._framebuffer) {
  26263. target._framebuffer = this._framebuffer;
  26264. }
  26265. if (this._depthStencilBuffer) {
  26266. target._depthStencilBuffer = this._depthStencilBuffer;
  26267. }
  26268. if (this._lodTextureHigh) {
  26269. if (target._lodTextureHigh) {
  26270. target._lodTextureHigh.dispose();
  26271. }
  26272. target._lodTextureHigh = this._lodTextureHigh;
  26273. }
  26274. if (this._lodTextureMid) {
  26275. if (target._lodTextureMid) {
  26276. target._lodTextureMid.dispose();
  26277. }
  26278. target._lodTextureMid = this._lodTextureMid;
  26279. }
  26280. if (this._lodTextureLow) {
  26281. if (target._lodTextureLow) {
  26282. target._lodTextureLow.dispose();
  26283. }
  26284. target._lodTextureLow = this._lodTextureLow;
  26285. }
  26286. var cache = this._engine.getLoadedTexturesCache();
  26287. var index = cache.indexOf(this);
  26288. if (index !== -1) {
  26289. cache.splice(index, 1);
  26290. }
  26291. };
  26292. /**
  26293. * Dispose the current allocated resources
  26294. */
  26295. InternalTexture.prototype.dispose = function () {
  26296. if (!this._webGLTexture) {
  26297. return;
  26298. }
  26299. this._references--;
  26300. if (this._references === 0) {
  26301. this._engine._releaseTexture(this);
  26302. this._webGLTexture = null;
  26303. this.previous = null;
  26304. this.next = null;
  26305. }
  26306. };
  26307. /**
  26308. * The source of the texture data is unknown
  26309. */
  26310. InternalTexture.DATASOURCE_UNKNOWN = 0;
  26311. /**
  26312. * Texture data comes from an URL
  26313. */
  26314. InternalTexture.DATASOURCE_URL = 1;
  26315. /**
  26316. * Texture data is only used for temporary storage
  26317. */
  26318. InternalTexture.DATASOURCE_TEMP = 2;
  26319. /**
  26320. * Texture data comes from raw data (ArrayBuffer)
  26321. */
  26322. InternalTexture.DATASOURCE_RAW = 3;
  26323. /**
  26324. * Texture content is dynamic (video or dynamic texture)
  26325. */
  26326. InternalTexture.DATASOURCE_DYNAMIC = 4;
  26327. /**
  26328. * Texture content is generated by rendering to it
  26329. */
  26330. InternalTexture.DATASOURCE_RENDERTARGET = 5;
  26331. /**
  26332. * Texture content is part of a multi render target process
  26333. */
  26334. InternalTexture.DATASOURCE_MULTIRENDERTARGET = 6;
  26335. /**
  26336. * Texture data comes from a cube data file
  26337. */
  26338. InternalTexture.DATASOURCE_CUBE = 7;
  26339. /**
  26340. * Texture data comes from a raw cube data
  26341. */
  26342. InternalTexture.DATASOURCE_CUBERAW = 8;
  26343. /**
  26344. * Texture data come from a prefiltered cube data file
  26345. */
  26346. InternalTexture.DATASOURCE_CUBEPREFILTERED = 9;
  26347. /**
  26348. * Texture content is raw 3D data
  26349. */
  26350. InternalTexture.DATASOURCE_RAW3D = 10;
  26351. /**
  26352. * Texture content is a depth texture
  26353. */
  26354. InternalTexture.DATASOURCE_DEPTHTEXTURE = 11;
  26355. return InternalTexture;
  26356. }());
  26357. BABYLON.InternalTexture = InternalTexture;
  26358. })(BABYLON || (BABYLON = {}));
  26359. //# sourceMappingURL=babylon.internalTexture.js.map
  26360. var BABYLON;
  26361. (function (BABYLON) {
  26362. var BaseTexture = /** @class */ (function () {
  26363. function BaseTexture(scene) {
  26364. this._hasAlpha = false;
  26365. this.getAlphaFromRGB = false;
  26366. this.level = 1;
  26367. this.coordinatesIndex = 0;
  26368. this._coordinatesMode = BABYLON.Texture.EXPLICIT_MODE;
  26369. /**
  26370. * | Value | Type | Description |
  26371. * | ----- | ------------------ | ----------- |
  26372. * | 0 | CLAMP_ADDRESSMODE | |
  26373. * | 1 | WRAP_ADDRESSMODE | |
  26374. * | 2 | MIRROR_ADDRESSMODE | |
  26375. */
  26376. this.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  26377. /**
  26378. * | Value | Type | Description |
  26379. * | ----- | ------------------ | ----------- |
  26380. * | 0 | CLAMP_ADDRESSMODE | |
  26381. * | 1 | WRAP_ADDRESSMODE | |
  26382. * | 2 | MIRROR_ADDRESSMODE | |
  26383. */
  26384. this.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  26385. /**
  26386. * | Value | Type | Description |
  26387. * | ----- | ------------------ | ----------- |
  26388. * | 0 | CLAMP_ADDRESSMODE | |
  26389. * | 1 | WRAP_ADDRESSMODE | |
  26390. * | 2 | MIRROR_ADDRESSMODE | |
  26391. */
  26392. this.wrapR = BABYLON.Texture.WRAP_ADDRESSMODE;
  26393. this.anisotropicFilteringLevel = BaseTexture.DEFAULT_ANISOTROPIC_FILTERING_LEVEL;
  26394. this.isCube = false;
  26395. this.is3D = false;
  26396. this.gammaSpace = true;
  26397. this.invertZ = false;
  26398. this.lodLevelInAlpha = false;
  26399. this.lodGenerationOffset = 0.0;
  26400. this.lodGenerationScale = 0.8;
  26401. this.isRenderTarget = false;
  26402. this.animations = new Array();
  26403. /**
  26404. * An event triggered when the texture is disposed.
  26405. * @type {BABYLON.Observable}
  26406. */
  26407. this.onDisposeObservable = new BABYLON.Observable();
  26408. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  26409. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  26410. if (this._scene) {
  26411. this._scene.textures.push(this);
  26412. }
  26413. this._uid = null;
  26414. }
  26415. Object.defineProperty(BaseTexture.prototype, "hasAlpha", {
  26416. get: function () {
  26417. return this._hasAlpha;
  26418. },
  26419. set: function (value) {
  26420. if (this._hasAlpha === value) {
  26421. return;
  26422. }
  26423. this._hasAlpha = value;
  26424. if (this._scene) {
  26425. this._scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag | BABYLON.Material.MiscDirtyFlag);
  26426. }
  26427. },
  26428. enumerable: true,
  26429. configurable: true
  26430. });
  26431. Object.defineProperty(BaseTexture.prototype, "coordinatesMode", {
  26432. get: function () {
  26433. return this._coordinatesMode;
  26434. },
  26435. /**
  26436. * How a texture is mapped.
  26437. *
  26438. * | Value | Type | Description |
  26439. * | ----- | ----------------------------------- | ----------- |
  26440. * | 0 | EXPLICIT_MODE | |
  26441. * | 1 | SPHERICAL_MODE | |
  26442. * | 2 | PLANAR_MODE | |
  26443. * | 3 | CUBIC_MODE | |
  26444. * | 4 | PROJECTION_MODE | |
  26445. * | 5 | SKYBOX_MODE | |
  26446. * | 6 | INVCUBIC_MODE | |
  26447. * | 7 | EQUIRECTANGULAR_MODE | |
  26448. * | 8 | FIXED_EQUIRECTANGULAR_MODE | |
  26449. * | 9 | FIXED_EQUIRECTANGULAR_MIRRORED_MODE | |
  26450. */
  26451. set: function (value) {
  26452. if (this._coordinatesMode === value) {
  26453. return;
  26454. }
  26455. this._coordinatesMode = value;
  26456. if (this._scene) {
  26457. this._scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  26458. }
  26459. },
  26460. enumerable: true,
  26461. configurable: true
  26462. });
  26463. Object.defineProperty(BaseTexture.prototype, "uid", {
  26464. get: function () {
  26465. if (!this._uid) {
  26466. this._uid = BABYLON.Tools.RandomId();
  26467. }
  26468. return this._uid;
  26469. },
  26470. enumerable: true,
  26471. configurable: true
  26472. });
  26473. BaseTexture.prototype.toString = function () {
  26474. return this.name;
  26475. };
  26476. BaseTexture.prototype.getClassName = function () {
  26477. return "BaseTexture";
  26478. };
  26479. Object.defineProperty(BaseTexture.prototype, "onDispose", {
  26480. set: function (callback) {
  26481. if (this._onDisposeObserver) {
  26482. this.onDisposeObservable.remove(this._onDisposeObserver);
  26483. }
  26484. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  26485. },
  26486. enumerable: true,
  26487. configurable: true
  26488. });
  26489. Object.defineProperty(BaseTexture.prototype, "isBlocking", {
  26490. get: function () {
  26491. return true;
  26492. },
  26493. enumerable: true,
  26494. configurable: true
  26495. });
  26496. BaseTexture.prototype.getScene = function () {
  26497. return this._scene;
  26498. };
  26499. BaseTexture.prototype.getTextureMatrix = function () {
  26500. return BABYLON.Matrix.IdentityReadOnly;
  26501. };
  26502. BaseTexture.prototype.getReflectionTextureMatrix = function () {
  26503. return BABYLON.Matrix.IdentityReadOnly;
  26504. };
  26505. BaseTexture.prototype.getInternalTexture = function () {
  26506. return this._texture;
  26507. };
  26508. BaseTexture.prototype.isReadyOrNotBlocking = function () {
  26509. return !this.isBlocking || this.isReady();
  26510. };
  26511. BaseTexture.prototype.isReady = function () {
  26512. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  26513. this.delayLoad();
  26514. return false;
  26515. }
  26516. if (this._texture) {
  26517. return this._texture.isReady;
  26518. }
  26519. return false;
  26520. };
  26521. BaseTexture.prototype.getSize = function () {
  26522. if (this._texture && this._texture.width) {
  26523. return new BABYLON.Size(this._texture.width, this._texture.height);
  26524. }
  26525. if (this._texture && this._texture._size) {
  26526. return new BABYLON.Size(this._texture._size, this._texture._size);
  26527. }
  26528. return BABYLON.Size.Zero();
  26529. };
  26530. BaseTexture.prototype.getBaseSize = function () {
  26531. if (!this.isReady() || !this._texture)
  26532. return BABYLON.Size.Zero();
  26533. if (this._texture._size) {
  26534. return new BABYLON.Size(this._texture._size, this._texture._size);
  26535. }
  26536. return new BABYLON.Size(this._texture.baseWidth, this._texture.baseHeight);
  26537. };
  26538. BaseTexture.prototype.scale = function (ratio) {
  26539. };
  26540. Object.defineProperty(BaseTexture.prototype, "canRescale", {
  26541. get: function () {
  26542. return false;
  26543. },
  26544. enumerable: true,
  26545. configurable: true
  26546. });
  26547. BaseTexture.prototype._getFromCache = function (url, noMipmap, sampling) {
  26548. if (!this._scene) {
  26549. return null;
  26550. }
  26551. var texturesCache = this._scene.getEngine().getLoadedTexturesCache();
  26552. for (var index = 0; index < texturesCache.length; index++) {
  26553. var texturesCacheEntry = texturesCache[index];
  26554. if (texturesCacheEntry.url === url && texturesCacheEntry.generateMipMaps === !noMipmap) {
  26555. if (!sampling || sampling === texturesCacheEntry.samplingMode) {
  26556. texturesCacheEntry.incrementReferences();
  26557. return texturesCacheEntry;
  26558. }
  26559. }
  26560. }
  26561. return null;
  26562. };
  26563. BaseTexture.prototype._rebuild = function () {
  26564. };
  26565. BaseTexture.prototype.delayLoad = function () {
  26566. };
  26567. BaseTexture.prototype.clone = function () {
  26568. return null;
  26569. };
  26570. Object.defineProperty(BaseTexture.prototype, "textureType", {
  26571. get: function () {
  26572. if (!this._texture) {
  26573. return BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  26574. }
  26575. return (this._texture.type !== undefined) ? this._texture.type : BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  26576. },
  26577. enumerable: true,
  26578. configurable: true
  26579. });
  26580. Object.defineProperty(BaseTexture.prototype, "textureFormat", {
  26581. get: function () {
  26582. if (!this._texture) {
  26583. return BABYLON.Engine.TEXTUREFORMAT_RGBA;
  26584. }
  26585. return (this._texture.format !== undefined) ? this._texture.format : BABYLON.Engine.TEXTUREFORMAT_RGBA;
  26586. },
  26587. enumerable: true,
  26588. configurable: true
  26589. });
  26590. BaseTexture.prototype.readPixels = function (faceIndex) {
  26591. if (faceIndex === void 0) { faceIndex = 0; }
  26592. if (!this._texture) {
  26593. return null;
  26594. }
  26595. var size = this.getSize();
  26596. var scene = this.getScene();
  26597. if (!scene) {
  26598. return null;
  26599. }
  26600. var engine = scene.getEngine();
  26601. if (this._texture.isCube) {
  26602. return engine._readTexturePixels(this._texture, size.width, size.height, faceIndex);
  26603. }
  26604. return engine._readTexturePixels(this._texture, size.width, size.height, -1);
  26605. };
  26606. BaseTexture.prototype.releaseInternalTexture = function () {
  26607. if (this._texture) {
  26608. this._texture.dispose();
  26609. this._texture = null;
  26610. }
  26611. };
  26612. Object.defineProperty(BaseTexture.prototype, "sphericalPolynomial", {
  26613. get: function () {
  26614. if (!this._texture || !BABYLON.CubeMapToSphericalPolynomialTools || !this.isReady()) {
  26615. return null;
  26616. }
  26617. if (!this._texture._sphericalPolynomial) {
  26618. this._texture._sphericalPolynomial =
  26619. BABYLON.CubeMapToSphericalPolynomialTools.ConvertCubeMapTextureToSphericalPolynomial(this);
  26620. }
  26621. return this._texture._sphericalPolynomial;
  26622. },
  26623. set: function (value) {
  26624. if (this._texture) {
  26625. this._texture._sphericalPolynomial = value;
  26626. }
  26627. },
  26628. enumerable: true,
  26629. configurable: true
  26630. });
  26631. Object.defineProperty(BaseTexture.prototype, "_lodTextureHigh", {
  26632. get: function () {
  26633. if (this._texture) {
  26634. return this._texture._lodTextureHigh;
  26635. }
  26636. return null;
  26637. },
  26638. enumerable: true,
  26639. configurable: true
  26640. });
  26641. Object.defineProperty(BaseTexture.prototype, "_lodTextureMid", {
  26642. get: function () {
  26643. if (this._texture) {
  26644. return this._texture._lodTextureMid;
  26645. }
  26646. return null;
  26647. },
  26648. enumerable: true,
  26649. configurable: true
  26650. });
  26651. Object.defineProperty(BaseTexture.prototype, "_lodTextureLow", {
  26652. get: function () {
  26653. if (this._texture) {
  26654. return this._texture._lodTextureLow;
  26655. }
  26656. return null;
  26657. },
  26658. enumerable: true,
  26659. configurable: true
  26660. });
  26661. BaseTexture.prototype.dispose = function () {
  26662. if (!this._scene) {
  26663. return;
  26664. }
  26665. // Animations
  26666. this._scene.stopAnimation(this);
  26667. // Remove from scene
  26668. this._scene._removePendingData(this);
  26669. var index = this._scene.textures.indexOf(this);
  26670. if (index >= 0) {
  26671. this._scene.textures.splice(index, 1);
  26672. }
  26673. if (this._texture === undefined) {
  26674. return;
  26675. }
  26676. // Release
  26677. this.releaseInternalTexture();
  26678. // Callback
  26679. this.onDisposeObservable.notifyObservers(this);
  26680. this.onDisposeObservable.clear();
  26681. };
  26682. BaseTexture.prototype.serialize = function () {
  26683. if (!this.name) {
  26684. return null;
  26685. }
  26686. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  26687. // Animations
  26688. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  26689. return serializationObject;
  26690. };
  26691. BaseTexture.WhenAllReady = function (textures, callback) {
  26692. var numRemaining = textures.length;
  26693. if (numRemaining === 0) {
  26694. callback();
  26695. return;
  26696. }
  26697. var _loop_1 = function () {
  26698. texture = textures[i];
  26699. if (texture.isReady()) {
  26700. if (--numRemaining === 0) {
  26701. callback();
  26702. }
  26703. }
  26704. else {
  26705. onLoadObservable = texture.onLoadObservable;
  26706. var onLoadCallback_1 = function () {
  26707. onLoadObservable.removeCallback(onLoadCallback_1);
  26708. if (--numRemaining === 0) {
  26709. callback();
  26710. }
  26711. };
  26712. onLoadObservable.add(onLoadCallback_1);
  26713. }
  26714. };
  26715. var texture, onLoadObservable;
  26716. for (var i = 0; i < textures.length; i++) {
  26717. _loop_1();
  26718. }
  26719. };
  26720. BaseTexture.DEFAULT_ANISOTROPIC_FILTERING_LEVEL = 4;
  26721. __decorate([
  26722. BABYLON.serialize()
  26723. ], BaseTexture.prototype, "name", void 0);
  26724. __decorate([
  26725. BABYLON.serialize("hasAlpha")
  26726. ], BaseTexture.prototype, "_hasAlpha", void 0);
  26727. __decorate([
  26728. BABYLON.serialize()
  26729. ], BaseTexture.prototype, "getAlphaFromRGB", void 0);
  26730. __decorate([
  26731. BABYLON.serialize()
  26732. ], BaseTexture.prototype, "level", void 0);
  26733. __decorate([
  26734. BABYLON.serialize()
  26735. ], BaseTexture.prototype, "coordinatesIndex", void 0);
  26736. __decorate([
  26737. BABYLON.serialize("coordinatesMode")
  26738. ], BaseTexture.prototype, "_coordinatesMode", void 0);
  26739. __decorate([
  26740. BABYLON.serialize()
  26741. ], BaseTexture.prototype, "wrapU", void 0);
  26742. __decorate([
  26743. BABYLON.serialize()
  26744. ], BaseTexture.prototype, "wrapV", void 0);
  26745. __decorate([
  26746. BABYLON.serialize()
  26747. ], BaseTexture.prototype, "wrapR", void 0);
  26748. __decorate([
  26749. BABYLON.serialize()
  26750. ], BaseTexture.prototype, "anisotropicFilteringLevel", void 0);
  26751. __decorate([
  26752. BABYLON.serialize()
  26753. ], BaseTexture.prototype, "isCube", void 0);
  26754. __decorate([
  26755. BABYLON.serialize()
  26756. ], BaseTexture.prototype, "is3D", void 0);
  26757. __decorate([
  26758. BABYLON.serialize()
  26759. ], BaseTexture.prototype, "gammaSpace", void 0);
  26760. __decorate([
  26761. BABYLON.serialize()
  26762. ], BaseTexture.prototype, "invertZ", void 0);
  26763. __decorate([
  26764. BABYLON.serialize()
  26765. ], BaseTexture.prototype, "lodLevelInAlpha", void 0);
  26766. __decorate([
  26767. BABYLON.serialize()
  26768. ], BaseTexture.prototype, "lodGenerationOffset", void 0);
  26769. __decorate([
  26770. BABYLON.serialize()
  26771. ], BaseTexture.prototype, "lodGenerationScale", void 0);
  26772. __decorate([
  26773. BABYLON.serialize()
  26774. ], BaseTexture.prototype, "isRenderTarget", void 0);
  26775. return BaseTexture;
  26776. }());
  26777. BABYLON.BaseTexture = BaseTexture;
  26778. })(BABYLON || (BABYLON = {}));
  26779. //# sourceMappingURL=babylon.baseTexture.js.map
  26780. var BABYLON;
  26781. (function (BABYLON) {
  26782. var Texture = /** @class */ (function (_super) {
  26783. __extends(Texture, _super);
  26784. function Texture(url, scene, noMipmap, invertY, samplingMode, onLoad, onError, buffer, deleteBuffer, format) {
  26785. if (noMipmap === void 0) { noMipmap = false; }
  26786. if (invertY === void 0) { invertY = true; }
  26787. if (samplingMode === void 0) { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; }
  26788. if (onLoad === void 0) { onLoad = null; }
  26789. if (onError === void 0) { onError = null; }
  26790. if (buffer === void 0) { buffer = null; }
  26791. if (deleteBuffer === void 0) { deleteBuffer = false; }
  26792. var _this = _super.call(this, scene) || this;
  26793. _this.uOffset = 0;
  26794. _this.vOffset = 0;
  26795. _this.uScale = 1.0;
  26796. _this.vScale = 1.0;
  26797. _this.uAng = 0;
  26798. _this.vAng = 0;
  26799. _this.wAng = 0;
  26800. _this._isBlocking = true;
  26801. _this.name = url || "";
  26802. _this.url = url;
  26803. _this._noMipmap = noMipmap;
  26804. _this._invertY = invertY;
  26805. _this._samplingMode = samplingMode;
  26806. _this._buffer = buffer;
  26807. _this._deleteBuffer = deleteBuffer;
  26808. if (format) {
  26809. _this._format = format;
  26810. }
  26811. scene = _this.getScene();
  26812. if (!scene) {
  26813. return _this;
  26814. }
  26815. scene.getEngine().onBeforeTextureInitObservable.notifyObservers(_this);
  26816. var load = function () {
  26817. if (_this._onLoadObservable && _this._onLoadObservable.hasObservers()) {
  26818. _this.onLoadObservable.notifyObservers(_this);
  26819. }
  26820. if (onLoad) {
  26821. onLoad();
  26822. }
  26823. if (!_this.isBlocking && scene) {
  26824. scene.resetCachedMaterial();
  26825. }
  26826. };
  26827. if (!_this.url) {
  26828. _this._delayedOnLoad = load;
  26829. _this._delayedOnError = onError;
  26830. return _this;
  26831. }
  26832. _this._texture = _this._getFromCache(_this.url, noMipmap, samplingMode);
  26833. if (!_this._texture) {
  26834. if (!scene.useDelayedTextureLoading) {
  26835. _this._texture = scene.getEngine().createTexture(_this.url, noMipmap, invertY, scene, _this._samplingMode, load, onError, _this._buffer, undefined, _this._format);
  26836. if (deleteBuffer) {
  26837. delete _this._buffer;
  26838. }
  26839. }
  26840. else {
  26841. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  26842. _this._delayedOnLoad = load;
  26843. _this._delayedOnError = onError;
  26844. }
  26845. }
  26846. else {
  26847. if (_this._texture.isReady) {
  26848. BABYLON.Tools.SetImmediate(function () { return load(); });
  26849. }
  26850. else {
  26851. _this._texture.onLoadedObservable.add(load);
  26852. }
  26853. }
  26854. return _this;
  26855. }
  26856. Object.defineProperty(Texture.prototype, "noMipmap", {
  26857. get: function () {
  26858. return this._noMipmap;
  26859. },
  26860. enumerable: true,
  26861. configurable: true
  26862. });
  26863. Object.defineProperty(Texture.prototype, "isBlocking", {
  26864. get: function () {
  26865. return this._isBlocking;
  26866. },
  26867. set: function (value) {
  26868. this._isBlocking = value;
  26869. },
  26870. enumerable: true,
  26871. configurable: true
  26872. });
  26873. Object.defineProperty(Texture.prototype, "samplingMode", {
  26874. get: function () {
  26875. return this._samplingMode;
  26876. },
  26877. enumerable: true,
  26878. configurable: true
  26879. });
  26880. Texture.prototype.updateURL = function (url) {
  26881. this.url = url;
  26882. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  26883. this.delayLoad();
  26884. };
  26885. Texture.prototype.delayLoad = function () {
  26886. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  26887. return;
  26888. }
  26889. var scene = this.getScene();
  26890. if (!scene) {
  26891. return;
  26892. }
  26893. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  26894. this._texture = this._getFromCache(this.url, this._noMipmap, this._samplingMode);
  26895. if (!this._texture) {
  26896. this._texture = scene.getEngine().createTexture(this.url, this._noMipmap, this._invertY, scene, this._samplingMode, this._delayedOnLoad, this._delayedOnError, this._buffer, null, this._format);
  26897. if (this._deleteBuffer) {
  26898. delete this._buffer;
  26899. }
  26900. }
  26901. else {
  26902. if (this._delayedOnLoad) {
  26903. if (this._texture.isReady) {
  26904. BABYLON.Tools.SetImmediate(this._delayedOnLoad);
  26905. }
  26906. else {
  26907. this._texture.onLoadedObservable.add(this._delayedOnLoad);
  26908. }
  26909. }
  26910. }
  26911. this._delayedOnLoad = null;
  26912. this._delayedOnError = null;
  26913. };
  26914. Texture.prototype.updateSamplingMode = function (samplingMode) {
  26915. if (!this._texture) {
  26916. return;
  26917. }
  26918. var scene = this.getScene();
  26919. if (!scene) {
  26920. return;
  26921. }
  26922. this._samplingMode = samplingMode;
  26923. scene.getEngine().updateTextureSamplingMode(samplingMode, this._texture);
  26924. };
  26925. Texture.prototype._prepareRowForTextureGeneration = function (x, y, z, t) {
  26926. x *= this.uScale;
  26927. y *= this.vScale;
  26928. x -= 0.5 * this.uScale;
  26929. y -= 0.5 * this.vScale;
  26930. z -= 0.5;
  26931. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, y, z, this._rowGenerationMatrix, t);
  26932. t.x += 0.5 * this.uScale + this.uOffset;
  26933. t.y += 0.5 * this.vScale + this.vOffset;
  26934. t.z += 0.5;
  26935. };
  26936. Texture.prototype.getTextureMatrix = function () {
  26937. var _this = this;
  26938. if (this.uOffset === this._cachedUOffset &&
  26939. this.vOffset === this._cachedVOffset &&
  26940. this.uScale === this._cachedUScale &&
  26941. this.vScale === this._cachedVScale &&
  26942. this.uAng === this._cachedUAng &&
  26943. this.vAng === this._cachedVAng &&
  26944. this.wAng === this._cachedWAng) {
  26945. return this._cachedTextureMatrix;
  26946. }
  26947. this._cachedUOffset = this.uOffset;
  26948. this._cachedVOffset = this.vOffset;
  26949. this._cachedUScale = this.uScale;
  26950. this._cachedVScale = this.vScale;
  26951. this._cachedUAng = this.uAng;
  26952. this._cachedVAng = this.vAng;
  26953. this._cachedWAng = this.wAng;
  26954. if (!this._cachedTextureMatrix) {
  26955. this._cachedTextureMatrix = BABYLON.Matrix.Zero();
  26956. this._rowGenerationMatrix = new BABYLON.Matrix();
  26957. this._t0 = BABYLON.Vector3.Zero();
  26958. this._t1 = BABYLON.Vector3.Zero();
  26959. this._t2 = BABYLON.Vector3.Zero();
  26960. }
  26961. BABYLON.Matrix.RotationYawPitchRollToRef(this.vAng, this.uAng, this.wAng, this._rowGenerationMatrix);
  26962. this._prepareRowForTextureGeneration(0, 0, 0, this._t0);
  26963. this._prepareRowForTextureGeneration(1.0, 0, 0, this._t1);
  26964. this._prepareRowForTextureGeneration(0, 1.0, 0, this._t2);
  26965. this._t1.subtractInPlace(this._t0);
  26966. this._t2.subtractInPlace(this._t0);
  26967. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  26968. this._cachedTextureMatrix.m[0] = this._t1.x;
  26969. this._cachedTextureMatrix.m[1] = this._t1.y;
  26970. this._cachedTextureMatrix.m[2] = this._t1.z;
  26971. this._cachedTextureMatrix.m[4] = this._t2.x;
  26972. this._cachedTextureMatrix.m[5] = this._t2.y;
  26973. this._cachedTextureMatrix.m[6] = this._t2.z;
  26974. this._cachedTextureMatrix.m[8] = this._t0.x;
  26975. this._cachedTextureMatrix.m[9] = this._t0.y;
  26976. this._cachedTextureMatrix.m[10] = this._t0.z;
  26977. var scene = this.getScene();
  26978. if (!scene) {
  26979. return this._cachedTextureMatrix;
  26980. }
  26981. scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag, function (mat) {
  26982. return mat.hasTexture(_this);
  26983. });
  26984. return this._cachedTextureMatrix;
  26985. };
  26986. Texture.prototype.getReflectionTextureMatrix = function () {
  26987. var _this = this;
  26988. var scene = this.getScene();
  26989. if (!scene) {
  26990. return this._cachedTextureMatrix;
  26991. }
  26992. if (this.uOffset === this._cachedUOffset &&
  26993. this.vOffset === this._cachedVOffset &&
  26994. this.uScale === this._cachedUScale &&
  26995. this.vScale === this._cachedVScale &&
  26996. this.coordinatesMode === this._cachedCoordinatesMode) {
  26997. if (this.coordinatesMode === Texture.PROJECTION_MODE) {
  26998. if (this._cachedProjectionMatrixId === scene.getProjectionMatrix().updateFlag) {
  26999. return this._cachedTextureMatrix;
  27000. }
  27001. }
  27002. else {
  27003. return this._cachedTextureMatrix;
  27004. }
  27005. }
  27006. if (!this._cachedTextureMatrix) {
  27007. this._cachedTextureMatrix = BABYLON.Matrix.Zero();
  27008. }
  27009. if (!this._projectionModeMatrix) {
  27010. this._projectionModeMatrix = BABYLON.Matrix.Zero();
  27011. }
  27012. this._cachedUOffset = this.uOffset;
  27013. this._cachedVOffset = this.vOffset;
  27014. this._cachedUScale = this.uScale;
  27015. this._cachedVScale = this.vScale;
  27016. this._cachedCoordinatesMode = this.coordinatesMode;
  27017. switch (this.coordinatesMode) {
  27018. case Texture.PLANAR_MODE:
  27019. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  27020. this._cachedTextureMatrix[0] = this.uScale;
  27021. this._cachedTextureMatrix[5] = this.vScale;
  27022. this._cachedTextureMatrix[12] = this.uOffset;
  27023. this._cachedTextureMatrix[13] = this.vOffset;
  27024. break;
  27025. case Texture.PROJECTION_MODE:
  27026. BABYLON.Matrix.IdentityToRef(this._projectionModeMatrix);
  27027. this._projectionModeMatrix.m[0] = 0.5;
  27028. this._projectionModeMatrix.m[5] = -0.5;
  27029. this._projectionModeMatrix.m[10] = 0.0;
  27030. this._projectionModeMatrix.m[12] = 0.5;
  27031. this._projectionModeMatrix.m[13] = 0.5;
  27032. this._projectionModeMatrix.m[14] = 1.0;
  27033. this._projectionModeMatrix.m[15] = 1.0;
  27034. var projectionMatrix = scene.getProjectionMatrix();
  27035. this._cachedProjectionMatrixId = projectionMatrix.updateFlag;
  27036. projectionMatrix.multiplyToRef(this._projectionModeMatrix, this._cachedTextureMatrix);
  27037. break;
  27038. default:
  27039. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  27040. break;
  27041. }
  27042. scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag, function (mat) {
  27043. return (mat.getActiveTextures().indexOf(_this) !== -1);
  27044. });
  27045. return this._cachedTextureMatrix;
  27046. };
  27047. Texture.prototype.clone = function () {
  27048. var _this = this;
  27049. return BABYLON.SerializationHelper.Clone(function () {
  27050. return new Texture(_this._texture ? _this._texture.url : null, _this.getScene(), _this._noMipmap, _this._invertY, _this._samplingMode);
  27051. }, this);
  27052. };
  27053. Object.defineProperty(Texture.prototype, "onLoadObservable", {
  27054. get: function () {
  27055. if (!this._onLoadObservable) {
  27056. this._onLoadObservable = new BABYLON.Observable();
  27057. }
  27058. return this._onLoadObservable;
  27059. },
  27060. enumerable: true,
  27061. configurable: true
  27062. });
  27063. Texture.prototype.serialize = function () {
  27064. var serializationObject = _super.prototype.serialize.call(this);
  27065. if (typeof this._buffer === "string" && this._buffer.substr(0, 5) === "data:") {
  27066. serializationObject.base64String = this._buffer;
  27067. serializationObject.name = serializationObject.name.replace("data:", "");
  27068. }
  27069. return serializationObject;
  27070. };
  27071. Texture.prototype.getClassName = function () {
  27072. return "Texture";
  27073. };
  27074. Texture.prototype.dispose = function () {
  27075. _super.prototype.dispose.call(this);
  27076. if (this.onLoadObservable) {
  27077. this.onLoadObservable.clear();
  27078. this._onLoadObservable = null;
  27079. }
  27080. this._delayedOnLoad = null;
  27081. this._delayedOnError = null;
  27082. };
  27083. // Statics
  27084. Texture.CreateFromBase64String = function (data, name, scene, noMipmap, invertY, samplingMode, onLoad, onError, format) {
  27085. if (samplingMode === void 0) { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; }
  27086. if (onLoad === void 0) { onLoad = null; }
  27087. if (onError === void 0) { onError = null; }
  27088. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  27089. return new Texture("data:" + name, scene, noMipmap, invertY, samplingMode, onLoad, onError, data, false, format);
  27090. };
  27091. Texture.Parse = function (parsedTexture, scene, rootUrl) {
  27092. if (parsedTexture.customType) {
  27093. var customTexture = BABYLON.Tools.Instantiate(parsedTexture.customType);
  27094. // Update Sampling Mode
  27095. var parsedCustomTexture = customTexture.Parse(parsedTexture, scene, rootUrl);
  27096. if (parsedTexture.samplingMode && parsedCustomTexture.updateSamplingMode && parsedCustomTexture._samplingMode) {
  27097. if (parsedCustomTexture._samplingMode !== parsedTexture.samplingMode) {
  27098. parsedCustomTexture.updateSamplingMode(parsedTexture.samplingMode);
  27099. }
  27100. }
  27101. return parsedCustomTexture;
  27102. }
  27103. if (parsedTexture.isCube) {
  27104. return BABYLON.CubeTexture.Parse(parsedTexture, scene, rootUrl);
  27105. }
  27106. if (!parsedTexture.name && !parsedTexture.isRenderTarget) {
  27107. return null;
  27108. }
  27109. var texture = BABYLON.SerializationHelper.Parse(function () {
  27110. var generateMipMaps = true;
  27111. if (parsedTexture.noMipmap) {
  27112. generateMipMaps = false;
  27113. }
  27114. if (parsedTexture.mirrorPlane) {
  27115. var mirrorTexture = new BABYLON.MirrorTexture(parsedTexture.name, parsedTexture.renderTargetSize, scene, generateMipMaps);
  27116. mirrorTexture._waitingRenderList = parsedTexture.renderList;
  27117. mirrorTexture.mirrorPlane = BABYLON.Plane.FromArray(parsedTexture.mirrorPlane);
  27118. return mirrorTexture;
  27119. }
  27120. else if (parsedTexture.isRenderTarget) {
  27121. var renderTargetTexture = new BABYLON.RenderTargetTexture(parsedTexture.name, parsedTexture.renderTargetSize, scene, generateMipMaps);
  27122. renderTargetTexture._waitingRenderList = parsedTexture.renderList;
  27123. return renderTargetTexture;
  27124. }
  27125. else {
  27126. var texture;
  27127. if (parsedTexture.base64String) {
  27128. texture = Texture.CreateFromBase64String(parsedTexture.base64String, parsedTexture.name, scene, !generateMipMaps);
  27129. }
  27130. else {
  27131. var url = rootUrl + parsedTexture.name;
  27132. if (Texture.UseSerializedUrlIfAny && parsedTexture.url) {
  27133. url = parsedTexture.url;
  27134. }
  27135. texture = new Texture(url, scene, !generateMipMaps);
  27136. }
  27137. return texture;
  27138. }
  27139. }, parsedTexture, scene);
  27140. // Update Sampling Mode
  27141. if (parsedTexture.samplingMode) {
  27142. var sampling = parsedTexture.samplingMode;
  27143. if (texture._samplingMode !== sampling) {
  27144. texture.updateSamplingMode(sampling);
  27145. }
  27146. }
  27147. // Animations
  27148. if (parsedTexture.animations) {
  27149. for (var animationIndex = 0; animationIndex < parsedTexture.animations.length; animationIndex++) {
  27150. var parsedAnimation = parsedTexture.animations[animationIndex];
  27151. texture.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  27152. }
  27153. }
  27154. return texture;
  27155. };
  27156. Texture.LoadFromDataString = function (name, buffer, scene, deleteBuffer, noMipmap, invertY, samplingMode, onLoad, onError, format) {
  27157. if (deleteBuffer === void 0) { deleteBuffer = false; }
  27158. if (noMipmap === void 0) { noMipmap = false; }
  27159. if (invertY === void 0) { invertY = true; }
  27160. if (samplingMode === void 0) { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; }
  27161. if (onLoad === void 0) { onLoad = null; }
  27162. if (onError === void 0) { onError = null; }
  27163. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  27164. if (name.substr(0, 5) !== "data:") {
  27165. name = "data:" + name;
  27166. }
  27167. return new Texture(name, scene, noMipmap, invertY, samplingMode, onLoad, onError, buffer, deleteBuffer, format);
  27168. };
  27169. // Constants
  27170. Texture.NEAREST_SAMPLINGMODE = 1;
  27171. Texture.NEAREST_NEAREST_MIPLINEAR = 1; // nearest is mag = nearest and min = nearest and mip = linear
  27172. Texture.BILINEAR_SAMPLINGMODE = 2;
  27173. Texture.LINEAR_LINEAR_MIPNEAREST = 2; // Bilinear is mag = linear and min = linear and mip = nearest
  27174. Texture.TRILINEAR_SAMPLINGMODE = 3;
  27175. Texture.LINEAR_LINEAR_MIPLINEAR = 3; // Trilinear is mag = linear and min = linear and mip = linear
  27176. Texture.NEAREST_NEAREST_MIPNEAREST = 4;
  27177. Texture.NEAREST_LINEAR_MIPNEAREST = 5;
  27178. Texture.NEAREST_LINEAR_MIPLINEAR = 6;
  27179. Texture.NEAREST_LINEAR = 7;
  27180. Texture.NEAREST_NEAREST = 8;
  27181. Texture.LINEAR_NEAREST_MIPNEAREST = 9;
  27182. Texture.LINEAR_NEAREST_MIPLINEAR = 10;
  27183. Texture.LINEAR_LINEAR = 11;
  27184. Texture.LINEAR_NEAREST = 12;
  27185. Texture.EXPLICIT_MODE = 0;
  27186. Texture.SPHERICAL_MODE = 1;
  27187. Texture.PLANAR_MODE = 2;
  27188. Texture.CUBIC_MODE = 3;
  27189. Texture.PROJECTION_MODE = 4;
  27190. Texture.SKYBOX_MODE = 5;
  27191. Texture.INVCUBIC_MODE = 6;
  27192. Texture.EQUIRECTANGULAR_MODE = 7;
  27193. Texture.FIXED_EQUIRECTANGULAR_MODE = 8;
  27194. Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE = 9;
  27195. Texture.CLAMP_ADDRESSMODE = 0;
  27196. Texture.WRAP_ADDRESSMODE = 1;
  27197. Texture.MIRROR_ADDRESSMODE = 2;
  27198. /**
  27199. * 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
  27200. */
  27201. Texture.UseSerializedUrlIfAny = false;
  27202. __decorate([
  27203. BABYLON.serialize()
  27204. ], Texture.prototype, "url", void 0);
  27205. __decorate([
  27206. BABYLON.serialize()
  27207. ], Texture.prototype, "uOffset", void 0);
  27208. __decorate([
  27209. BABYLON.serialize()
  27210. ], Texture.prototype, "vOffset", void 0);
  27211. __decorate([
  27212. BABYLON.serialize()
  27213. ], Texture.prototype, "uScale", void 0);
  27214. __decorate([
  27215. BABYLON.serialize()
  27216. ], Texture.prototype, "vScale", void 0);
  27217. __decorate([
  27218. BABYLON.serialize()
  27219. ], Texture.prototype, "uAng", void 0);
  27220. __decorate([
  27221. BABYLON.serialize()
  27222. ], Texture.prototype, "vAng", void 0);
  27223. __decorate([
  27224. BABYLON.serialize()
  27225. ], Texture.prototype, "wAng", void 0);
  27226. __decorate([
  27227. BABYLON.serialize()
  27228. ], Texture.prototype, "isBlocking", null);
  27229. return Texture;
  27230. }(BABYLON.BaseTexture));
  27231. BABYLON.Texture = Texture;
  27232. })(BABYLON || (BABYLON = {}));
  27233. //# sourceMappingURL=babylon.texture.js.map
  27234. var BABYLON;
  27235. (function (BABYLON) {
  27236. var _InstancesBatch = /** @class */ (function () {
  27237. function _InstancesBatch() {
  27238. this.mustReturn = false;
  27239. this.visibleInstances = new Array();
  27240. this.renderSelf = new Array();
  27241. }
  27242. return _InstancesBatch;
  27243. }());
  27244. BABYLON._InstancesBatch = _InstancesBatch;
  27245. var Mesh = /** @class */ (function (_super) {
  27246. __extends(Mesh, _super);
  27247. /**
  27248. * @constructor
  27249. * @param {string} name The value used by scene.getMeshByName() to do a lookup.
  27250. * @param {Scene} scene The scene to add this mesh to.
  27251. * @param {Node} parent The parent of this mesh, if it has one
  27252. * @param {Mesh} source An optional Mesh from which geometry is shared, cloned.
  27253. * @param {boolean} doNotCloneChildren When cloning, skip cloning child meshes of source, default False.
  27254. * When false, achieved by calling a clone(), also passing False.
  27255. * This will make creation of children, recursive.
  27256. * @param {boolean} clonePhysicsImpostor When cloning, include cloning mesh physics impostor, default True.
  27257. */
  27258. function Mesh(name, scene, parent, source, doNotCloneChildren, clonePhysicsImpostor) {
  27259. if (scene === void 0) { scene = null; }
  27260. if (parent === void 0) { parent = null; }
  27261. if (source === void 0) { source = null; }
  27262. if (clonePhysicsImpostor === void 0) { clonePhysicsImpostor = true; }
  27263. var _this = _super.call(this, name, scene) || this;
  27264. // Events
  27265. /**
  27266. * An event triggered before rendering the mesh
  27267. * @type {BABYLON.Observable}
  27268. */
  27269. _this.onBeforeRenderObservable = new BABYLON.Observable();
  27270. /**
  27271. * An event triggered after rendering the mesh
  27272. * @type {BABYLON.Observable}
  27273. */
  27274. _this.onAfterRenderObservable = new BABYLON.Observable();
  27275. /**
  27276. * An event triggered before drawing the mesh
  27277. * @type {BABYLON.Observable}
  27278. */
  27279. _this.onBeforeDrawObservable = new BABYLON.Observable();
  27280. // Members
  27281. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  27282. _this.instances = new Array();
  27283. _this._LODLevels = new Array();
  27284. _this._visibleInstances = {};
  27285. _this._renderIdForInstances = new Array();
  27286. _this._batchCache = new _InstancesBatch();
  27287. _this._instancesBufferSize = 32 * 16 * 4; // let's start with a maximum of 32 instances
  27288. // Use by builder only to know what orientation were the mesh build in.
  27289. _this._originalBuilderSideOrientation = Mesh._DEFAULTSIDE;
  27290. _this.overrideMaterialSideOrientation = null;
  27291. _this._areNormalsFrozen = false; // Will be used by ribbons mainly
  27292. // Will be used to save a source mesh reference, If any
  27293. _this._source = null;
  27294. scene = _this.getScene();
  27295. if (source) {
  27296. // Source mesh
  27297. _this._source = source;
  27298. // Geometry
  27299. if (source._geometry) {
  27300. source._geometry.applyToMesh(_this);
  27301. }
  27302. // Deep copy
  27303. BABYLON.Tools.DeepCopy(source, _this, ["name", "material", "skeleton", "instances", "parent", "uniqueId", "source", "metadata"], ["_poseMatrix", "_source"]);
  27304. // Metadata
  27305. if (source.metadata && source.metadata.clone) {
  27306. _this.metadata = source.metadata.clone();
  27307. }
  27308. else {
  27309. _this.metadata = source.metadata;
  27310. }
  27311. // Tags
  27312. if (BABYLON.Tags && BABYLON.Tags.HasTags(source)) {
  27313. BABYLON.Tags.AddTagsTo(_this, BABYLON.Tags.GetTags(source, true));
  27314. }
  27315. // Parent
  27316. _this.parent = source.parent;
  27317. // Pivot
  27318. _this.setPivotMatrix(source.getPivotMatrix());
  27319. _this.id = name + "." + source.id;
  27320. // Material
  27321. _this.material = source.material;
  27322. var index;
  27323. if (!doNotCloneChildren) {
  27324. // Children
  27325. var directDescendants = source.getDescendants(true);
  27326. for (var index_1 = 0; index_1 < directDescendants.length; index_1++) {
  27327. var child = directDescendants[index_1];
  27328. if (child.clone) {
  27329. child.clone(name + "." + child.name, _this);
  27330. }
  27331. }
  27332. }
  27333. // Physics clone
  27334. var physicsEngine = _this.getScene().getPhysicsEngine();
  27335. if (clonePhysicsImpostor && physicsEngine) {
  27336. var impostor = physicsEngine.getImpostorForPhysicsObject(source);
  27337. if (impostor) {
  27338. _this.physicsImpostor = impostor.clone(_this);
  27339. }
  27340. }
  27341. // Particles
  27342. for (index = 0; index < scene.particleSystems.length; index++) {
  27343. var system = scene.particleSystems[index];
  27344. if (system.emitter === source) {
  27345. system.clone(system.name, _this);
  27346. }
  27347. }
  27348. _this.computeWorldMatrix(true);
  27349. }
  27350. // Parent
  27351. if (parent !== null) {
  27352. _this.parent = parent;
  27353. }
  27354. return _this;
  27355. }
  27356. Object.defineProperty(Mesh, "FRONTSIDE", {
  27357. /**
  27358. * Mesh side orientation : usually the external or front surface
  27359. */
  27360. get: function () {
  27361. return Mesh._FRONTSIDE;
  27362. },
  27363. enumerable: true,
  27364. configurable: true
  27365. });
  27366. Object.defineProperty(Mesh, "BACKSIDE", {
  27367. /**
  27368. * Mesh side orientation : usually the internal or back surface
  27369. */
  27370. get: function () {
  27371. return Mesh._BACKSIDE;
  27372. },
  27373. enumerable: true,
  27374. configurable: true
  27375. });
  27376. Object.defineProperty(Mesh, "DOUBLESIDE", {
  27377. /**
  27378. * Mesh side orientation : both internal and external or front and back surfaces
  27379. */
  27380. get: function () {
  27381. return Mesh._DOUBLESIDE;
  27382. },
  27383. enumerable: true,
  27384. configurable: true
  27385. });
  27386. Object.defineProperty(Mesh, "DEFAULTSIDE", {
  27387. /**
  27388. * Mesh side orientation : by default, `FRONTSIDE`
  27389. */
  27390. get: function () {
  27391. return Mesh._DEFAULTSIDE;
  27392. },
  27393. enumerable: true,
  27394. configurable: true
  27395. });
  27396. Object.defineProperty(Mesh, "NO_CAP", {
  27397. /**
  27398. * Mesh cap setting : no cap
  27399. */
  27400. get: function () {
  27401. return Mesh._NO_CAP;
  27402. },
  27403. enumerable: true,
  27404. configurable: true
  27405. });
  27406. Object.defineProperty(Mesh, "CAP_START", {
  27407. /**
  27408. * Mesh cap setting : one cap at the beginning of the mesh
  27409. */
  27410. get: function () {
  27411. return Mesh._CAP_START;
  27412. },
  27413. enumerable: true,
  27414. configurable: true
  27415. });
  27416. Object.defineProperty(Mesh, "CAP_END", {
  27417. /**
  27418. * Mesh cap setting : one cap at the end of the mesh
  27419. */
  27420. get: function () {
  27421. return Mesh._CAP_END;
  27422. },
  27423. enumerable: true,
  27424. configurable: true
  27425. });
  27426. Object.defineProperty(Mesh, "CAP_ALL", {
  27427. /**
  27428. * Mesh cap setting : two caps, one at the beginning and one at the end of the mesh
  27429. */
  27430. get: function () {
  27431. return Mesh._CAP_ALL;
  27432. },
  27433. enumerable: true,
  27434. configurable: true
  27435. });
  27436. Object.defineProperty(Mesh.prototype, "onBeforeDraw", {
  27437. set: function (callback) {
  27438. if (this._onBeforeDrawObserver) {
  27439. this.onBeforeDrawObservable.remove(this._onBeforeDrawObserver);
  27440. }
  27441. this._onBeforeDrawObserver = this.onBeforeDrawObservable.add(callback);
  27442. },
  27443. enumerable: true,
  27444. configurable: true
  27445. });
  27446. Object.defineProperty(Mesh.prototype, "morphTargetManager", {
  27447. get: function () {
  27448. return this._morphTargetManager;
  27449. },
  27450. set: function (value) {
  27451. if (this._morphTargetManager === value) {
  27452. return;
  27453. }
  27454. this._morphTargetManager = value;
  27455. this._syncGeometryWithMorphTargetManager();
  27456. },
  27457. enumerable: true,
  27458. configurable: true
  27459. });
  27460. Object.defineProperty(Mesh.prototype, "source", {
  27461. get: function () {
  27462. return this._source;
  27463. },
  27464. enumerable: true,
  27465. configurable: true
  27466. });
  27467. Object.defineProperty(Mesh.prototype, "isUnIndexed", {
  27468. get: function () {
  27469. return this._unIndexed;
  27470. },
  27471. set: function (value) {
  27472. if (this._unIndexed !== value) {
  27473. this._unIndexed = value;
  27474. this._markSubMeshesAsAttributesDirty();
  27475. }
  27476. },
  27477. enumerable: true,
  27478. configurable: true
  27479. });
  27480. // Methods
  27481. /**
  27482. * Returns the string "Mesh".
  27483. */
  27484. Mesh.prototype.getClassName = function () {
  27485. return "Mesh";
  27486. };
  27487. /**
  27488. * Returns a string.
  27489. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  27490. */
  27491. Mesh.prototype.toString = function (fullDetails) {
  27492. var ret = _super.prototype.toString.call(this, fullDetails);
  27493. ret += ", n vertices: " + this.getTotalVertices();
  27494. ret += ", parent: " + (this._waitingParentId ? this._waitingParentId : (this.parent ? this.parent.name : "NONE"));
  27495. if (this.animations) {
  27496. for (var i = 0; i < this.animations.length; i++) {
  27497. ret += ", animation[0]: " + this.animations[i].toString(fullDetails);
  27498. }
  27499. }
  27500. if (fullDetails) {
  27501. if (this._geometry) {
  27502. var ib = this.getIndices();
  27503. var vb = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  27504. if (vb && ib) {
  27505. ret += ", flat shading: " + (vb.length / 3 === ib.length ? "YES" : "NO");
  27506. }
  27507. }
  27508. else {
  27509. ret += ", flat shading: UNKNOWN";
  27510. }
  27511. }
  27512. return ret;
  27513. };
  27514. Object.defineProperty(Mesh.prototype, "hasLODLevels", {
  27515. /**
  27516. * True if the mesh has some Levels Of Details (LOD).
  27517. * Returns a boolean.
  27518. */
  27519. get: function () {
  27520. return this._LODLevels.length > 0;
  27521. },
  27522. enumerable: true,
  27523. configurable: true
  27524. });
  27525. /**
  27526. * Gets the list of {BABYLON.MeshLODLevel} associated with the current mesh
  27527. * @returns an array of {BABYLON.MeshLODLevel}
  27528. */
  27529. Mesh.prototype.getLODLevels = function () {
  27530. return this._LODLevels;
  27531. };
  27532. Mesh.prototype._sortLODLevels = function () {
  27533. this._LODLevels.sort(function (a, b) {
  27534. if (a.distance < b.distance) {
  27535. return 1;
  27536. }
  27537. if (a.distance > b.distance) {
  27538. return -1;
  27539. }
  27540. return 0;
  27541. });
  27542. };
  27543. /**
  27544. * Add a mesh as LOD level triggered at the given distance.
  27545. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_LOD
  27546. * @param {number} distance The distance from the center of the object to show this level
  27547. * @param {Mesh} mesh The mesh to be added as LOD level
  27548. * @return {Mesh} This mesh (for chaining)
  27549. */
  27550. Mesh.prototype.addLODLevel = function (distance, mesh) {
  27551. if (mesh && mesh._masterMesh) {
  27552. BABYLON.Tools.Warn("You cannot use a mesh as LOD level twice");
  27553. return this;
  27554. }
  27555. var level = new BABYLON.MeshLODLevel(distance, mesh);
  27556. this._LODLevels.push(level);
  27557. if (mesh) {
  27558. mesh._masterMesh = this;
  27559. }
  27560. this._sortLODLevels();
  27561. return this;
  27562. };
  27563. /**
  27564. * Returns the LOD level mesh at the passed distance or null if not found.
  27565. * It is related to the method `addLODLevel(distance, mesh)`.
  27566. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_LOD
  27567. * Returns an object Mesh or `null`.
  27568. */
  27569. Mesh.prototype.getLODLevelAtDistance = function (distance) {
  27570. for (var index = 0; index < this._LODLevels.length; index++) {
  27571. var level = this._LODLevels[index];
  27572. if (level.distance === distance) {
  27573. return level.mesh;
  27574. }
  27575. }
  27576. return null;
  27577. };
  27578. /**
  27579. * Remove a mesh from the LOD array
  27580. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_LOD
  27581. * @param {Mesh} mesh The mesh to be removed.
  27582. * @return {Mesh} This mesh (for chaining)
  27583. */
  27584. Mesh.prototype.removeLODLevel = function (mesh) {
  27585. for (var index = 0; index < this._LODLevels.length; index++) {
  27586. if (this._LODLevels[index].mesh === mesh) {
  27587. this._LODLevels.splice(index, 1);
  27588. if (mesh) {
  27589. mesh._masterMesh = null;
  27590. }
  27591. }
  27592. }
  27593. this._sortLODLevels();
  27594. return this;
  27595. };
  27596. /**
  27597. * Returns the registered LOD mesh distant from the parameter `camera` position if any, else returns the current mesh.
  27598. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_LOD
  27599. */
  27600. Mesh.prototype.getLOD = function (camera, boundingSphere) {
  27601. if (!this._LODLevels || this._LODLevels.length === 0) {
  27602. return this;
  27603. }
  27604. var bSphere;
  27605. if (boundingSphere) {
  27606. bSphere = boundingSphere;
  27607. }
  27608. else {
  27609. var boundingInfo = this.getBoundingInfo();
  27610. bSphere = boundingInfo.boundingSphere;
  27611. }
  27612. var distanceToCamera = bSphere.centerWorld.subtract(camera.globalPosition).length();
  27613. if (this._LODLevels[this._LODLevels.length - 1].distance > distanceToCamera) {
  27614. if (this.onLODLevelSelection) {
  27615. this.onLODLevelSelection(distanceToCamera, this, this._LODLevels[this._LODLevels.length - 1].mesh);
  27616. }
  27617. return this;
  27618. }
  27619. for (var index = 0; index < this._LODLevels.length; index++) {
  27620. var level = this._LODLevels[index];
  27621. if (level.distance < distanceToCamera) {
  27622. if (level.mesh) {
  27623. level.mesh._preActivate();
  27624. level.mesh._updateSubMeshesBoundingInfo(this.worldMatrixFromCache);
  27625. }
  27626. if (this.onLODLevelSelection) {
  27627. this.onLODLevelSelection(distanceToCamera, this, level.mesh);
  27628. }
  27629. return level.mesh;
  27630. }
  27631. }
  27632. if (this.onLODLevelSelection) {
  27633. this.onLODLevelSelection(distanceToCamera, this, this);
  27634. }
  27635. return this;
  27636. };
  27637. Object.defineProperty(Mesh.prototype, "geometry", {
  27638. /**
  27639. * Returns the mesh internal Geometry object.
  27640. */
  27641. get: function () {
  27642. return this._geometry;
  27643. },
  27644. enumerable: true,
  27645. configurable: true
  27646. });
  27647. /**
  27648. * Returns a positive integer : the total number of vertices within the mesh geometry or zero if the mesh has no geometry.
  27649. */
  27650. Mesh.prototype.getTotalVertices = function () {
  27651. if (this._geometry === null || this._geometry === undefined) {
  27652. return 0;
  27653. }
  27654. return this._geometry.getTotalVertices();
  27655. };
  27656. /**
  27657. * Returns an array of integers or floats, or a Float32Array, depending on the requested `kind` (positions, indices, normals, etc).
  27658. * 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.
  27659. * You can force the copy with forceCopy === true
  27660. * Returns null if the mesh has no geometry or no vertex buffer.
  27661. * Possible `kind` values :
  27662. * - BABYLON.VertexBuffer.PositionKind
  27663. * - BABYLON.VertexBuffer.UVKind
  27664. * - BABYLON.VertexBuffer.UV2Kind
  27665. * - BABYLON.VertexBuffer.UV3Kind
  27666. * - BABYLON.VertexBuffer.UV4Kind
  27667. * - BABYLON.VertexBuffer.UV5Kind
  27668. * - BABYLON.VertexBuffer.UV6Kind
  27669. * - BABYLON.VertexBuffer.ColorKind
  27670. * - BABYLON.VertexBuffer.MatricesIndicesKind
  27671. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  27672. * - BABYLON.VertexBuffer.MatricesWeightsKind
  27673. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  27674. */
  27675. Mesh.prototype.getVerticesData = function (kind, copyWhenShared, forceCopy) {
  27676. if (!this._geometry) {
  27677. return null;
  27678. }
  27679. return this._geometry.getVerticesData(kind, copyWhenShared, forceCopy);
  27680. };
  27681. /**
  27682. * Returns the mesh VertexBuffer object from the requested `kind` : positions, indices, normals, etc.
  27683. * Returns `null` if the mesh has no geometry.
  27684. * Possible `kind` values :
  27685. * - BABYLON.VertexBuffer.PositionKind
  27686. * - BABYLON.VertexBuffer.UVKind
  27687. * - BABYLON.VertexBuffer.UV2Kind
  27688. * - BABYLON.VertexBuffer.UV3Kind
  27689. * - BABYLON.VertexBuffer.UV4Kind
  27690. * - BABYLON.VertexBuffer.UV5Kind
  27691. * - BABYLON.VertexBuffer.UV6Kind
  27692. * - BABYLON.VertexBuffer.ColorKind
  27693. * - BABYLON.VertexBuffer.MatricesIndicesKind
  27694. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  27695. * - BABYLON.VertexBuffer.MatricesWeightsKind
  27696. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  27697. */
  27698. Mesh.prototype.getVertexBuffer = function (kind) {
  27699. if (!this._geometry) {
  27700. return null;
  27701. }
  27702. return this._geometry.getVertexBuffer(kind);
  27703. };
  27704. /**
  27705. * Returns a boolean depending on the existence of the Vertex Data for the requested `kind`.
  27706. * Possible `kind` values :
  27707. * - BABYLON.VertexBuffer.PositionKind
  27708. * - BABYLON.VertexBuffer.UVKind
  27709. * - BABYLON.VertexBuffer.UV2Kind
  27710. * - BABYLON.VertexBuffer.UV3Kind
  27711. * - BABYLON.VertexBuffer.UV4Kind
  27712. * - BABYLON.VertexBuffer.UV5Kind
  27713. * - BABYLON.VertexBuffer.UV6Kind
  27714. * - BABYLON.VertexBuffer.ColorKind
  27715. * - BABYLON.VertexBuffer.MatricesIndicesKind
  27716. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  27717. * - BABYLON.VertexBuffer.MatricesWeightsKind
  27718. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  27719. */
  27720. Mesh.prototype.isVerticesDataPresent = function (kind) {
  27721. if (!this._geometry) {
  27722. if (this._delayInfo) {
  27723. return this._delayInfo.indexOf(kind) !== -1;
  27724. }
  27725. return false;
  27726. }
  27727. return this._geometry.isVerticesDataPresent(kind);
  27728. };
  27729. /**
  27730. * Returns a boolean defining if the vertex data for the requested `kind` is updatable.
  27731. * Possible `kind` values :
  27732. * - BABYLON.VertexBuffer.PositionKind
  27733. * - BABYLON.VertexBuffer.UVKind
  27734. * - BABYLON.VertexBuffer.UV2Kind
  27735. * - BABYLON.VertexBuffer.UV3Kind
  27736. * - BABYLON.VertexBuffer.UV4Kind
  27737. * - BABYLON.VertexBuffer.UV5Kind
  27738. * - BABYLON.VertexBuffer.UV6Kind
  27739. * - BABYLON.VertexBuffer.ColorKind
  27740. * - BABYLON.VertexBuffer.MatricesIndicesKind
  27741. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  27742. * - BABYLON.VertexBuffer.MatricesWeightsKind
  27743. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  27744. */
  27745. Mesh.prototype.isVertexBufferUpdatable = function (kind) {
  27746. if (!this._geometry) {
  27747. if (this._delayInfo) {
  27748. return this._delayInfo.indexOf(kind) !== -1;
  27749. }
  27750. return false;
  27751. }
  27752. return this._geometry.isVertexBufferUpdatable(kind);
  27753. };
  27754. /**
  27755. * Returns a string : the list of existing `kinds` of Vertex Data for this mesh.
  27756. * Possible `kind` values :
  27757. * - BABYLON.VertexBuffer.PositionKind
  27758. * - BABYLON.VertexBuffer.UVKind
  27759. * - BABYLON.VertexBuffer.UV2Kind
  27760. * - BABYLON.VertexBuffer.UV3Kind
  27761. * - BABYLON.VertexBuffer.UV4Kind
  27762. * - BABYLON.VertexBuffer.UV5Kind
  27763. * - BABYLON.VertexBuffer.UV6Kind
  27764. * - BABYLON.VertexBuffer.ColorKind
  27765. * - BABYLON.VertexBuffer.MatricesIndicesKind
  27766. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  27767. * - BABYLON.VertexBuffer.MatricesWeightsKind
  27768. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  27769. */
  27770. Mesh.prototype.getVerticesDataKinds = function () {
  27771. if (!this._geometry) {
  27772. var result = new Array();
  27773. if (this._delayInfo) {
  27774. this._delayInfo.forEach(function (kind, index, array) {
  27775. result.push(kind);
  27776. });
  27777. }
  27778. return result;
  27779. }
  27780. return this._geometry.getVerticesDataKinds();
  27781. };
  27782. /**
  27783. * Returns a positive integer : the total number of indices in this mesh geometry.
  27784. * Returns zero if the mesh has no geometry.
  27785. */
  27786. Mesh.prototype.getTotalIndices = function () {
  27787. if (!this._geometry) {
  27788. return 0;
  27789. }
  27790. return this._geometry.getTotalIndices();
  27791. };
  27792. /**
  27793. * Returns an array of integers or a typed array (Int32Array, Uint32Array, Uint16Array) populated with the mesh indices.
  27794. * 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.
  27795. * Returns an empty array if the mesh has no geometry.
  27796. */
  27797. Mesh.prototype.getIndices = function (copyWhenShared) {
  27798. if (!this._geometry) {
  27799. return [];
  27800. }
  27801. return this._geometry.getIndices(copyWhenShared);
  27802. };
  27803. Object.defineProperty(Mesh.prototype, "isBlocked", {
  27804. get: function () {
  27805. return this._masterMesh !== null && this._masterMesh !== undefined;
  27806. },
  27807. enumerable: true,
  27808. configurable: true
  27809. });
  27810. /**
  27811. * Determine if the current mesh is ready to be rendered
  27812. * @param completeCheck defines if a complete check (including materials and lights) has to be done (false by default)
  27813. * @param forceInstanceSupport will check if the mesh will be ready when used with instances (false by default)
  27814. * @returns true if all associated assets are ready (material, textures, shaders)
  27815. */
  27816. Mesh.prototype.isReady = function (completeCheck, forceInstanceSupport) {
  27817. if (completeCheck === void 0) { completeCheck = false; }
  27818. if (forceInstanceSupport === void 0) { forceInstanceSupport = false; }
  27819. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  27820. return false;
  27821. }
  27822. if (!_super.prototype.isReady.call(this, completeCheck)) {
  27823. return false;
  27824. }
  27825. if (!this.subMeshes || this.subMeshes.length === 0) {
  27826. return true;
  27827. }
  27828. if (!completeCheck) {
  27829. return true;
  27830. }
  27831. var engine = this.getEngine();
  27832. var scene = this.getScene();
  27833. var hardwareInstancedRendering = forceInstanceSupport || engine.getCaps().instancedArrays && this.instances.length > 0;
  27834. this.computeWorldMatrix();
  27835. var mat = this.material || scene.defaultMaterial;
  27836. if (mat) {
  27837. if (mat.storeEffectOnSubMeshes) {
  27838. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  27839. var subMesh = _a[_i];
  27840. var effectiveMaterial = subMesh.getMaterial();
  27841. if (effectiveMaterial) {
  27842. if (!effectiveMaterial.isReadyForSubMesh(this, subMesh, hardwareInstancedRendering)) {
  27843. return false;
  27844. }
  27845. }
  27846. }
  27847. }
  27848. else {
  27849. if (!mat.isReady(this, hardwareInstancedRendering)) {
  27850. return false;
  27851. }
  27852. }
  27853. }
  27854. // Shadows
  27855. for (var _b = 0, _c = this._lightSources; _b < _c.length; _b++) {
  27856. var light = _c[_b];
  27857. var generator = light.getShadowGenerator();
  27858. if (generator) {
  27859. for (var _d = 0, _e = this.subMeshes; _d < _e.length; _d++) {
  27860. var subMesh = _e[_d];
  27861. if (!generator.isReady(subMesh, hardwareInstancedRendering)) {
  27862. return false;
  27863. }
  27864. }
  27865. }
  27866. }
  27867. // LOD
  27868. for (var _f = 0, _g = this._LODLevels; _f < _g.length; _f++) {
  27869. var lod = _g[_f];
  27870. if (lod.mesh && !lod.mesh.isReady(hardwareInstancedRendering)) {
  27871. return false;
  27872. }
  27873. }
  27874. return true;
  27875. };
  27876. Object.defineProperty(Mesh.prototype, "areNormalsFrozen", {
  27877. /**
  27878. * Boolean : true if the normals aren't to be recomputed on next mesh `positions` array update.
  27879. * This property is pertinent only for updatable parametric shapes.
  27880. */
  27881. get: function () {
  27882. return this._areNormalsFrozen;
  27883. },
  27884. enumerable: true,
  27885. configurable: true
  27886. });
  27887. /**
  27888. * This function affects parametric shapes on vertex position update only : ribbons, tubes, etc.
  27889. * It has no effect at all on other shapes.
  27890. * It prevents the mesh normals from being recomputed on next `positions` array update.
  27891. * Returns the Mesh.
  27892. */
  27893. Mesh.prototype.freezeNormals = function () {
  27894. this._areNormalsFrozen = true;
  27895. return this;
  27896. };
  27897. /**
  27898. * This function affects parametric shapes on vertex position update only : ribbons, tubes, etc.
  27899. * It has no effect at all on other shapes.
  27900. * It reactivates the mesh normals computation if it was previously frozen.
  27901. * Returns the Mesh.
  27902. */
  27903. Mesh.prototype.unfreezeNormals = function () {
  27904. this._areNormalsFrozen = false;
  27905. return this;
  27906. };
  27907. Object.defineProperty(Mesh.prototype, "overridenInstanceCount", {
  27908. /**
  27909. * Overrides instance count. Only applicable when custom instanced InterleavedVertexBuffer are used rather than InstancedMeshs
  27910. */
  27911. set: function (count) {
  27912. this._overridenInstanceCount = count;
  27913. },
  27914. enumerable: true,
  27915. configurable: true
  27916. });
  27917. // Methods
  27918. Mesh.prototype._preActivate = function () {
  27919. var sceneRenderId = this.getScene().getRenderId();
  27920. if (this._preActivateId === sceneRenderId) {
  27921. return this;
  27922. }
  27923. this._preActivateId = sceneRenderId;
  27924. this._visibleInstances = null;
  27925. return this;
  27926. };
  27927. Mesh.prototype._preActivateForIntermediateRendering = function (renderId) {
  27928. if (this._visibleInstances) {
  27929. this._visibleInstances.intermediateDefaultRenderId = renderId;
  27930. }
  27931. return this;
  27932. };
  27933. Mesh.prototype._registerInstanceForRenderId = function (instance, renderId) {
  27934. if (!this._visibleInstances) {
  27935. this._visibleInstances = {};
  27936. this._visibleInstances.defaultRenderId = renderId;
  27937. this._visibleInstances.selfDefaultRenderId = this._renderId;
  27938. }
  27939. if (!this._visibleInstances[renderId]) {
  27940. this._visibleInstances[renderId] = new Array();
  27941. }
  27942. this._visibleInstances[renderId].push(instance);
  27943. return this;
  27944. };
  27945. /**
  27946. * This method recomputes and sets a new BoundingInfo to the mesh unless it is locked.
  27947. * This means the mesh underlying bounding box and sphere are recomputed.
  27948. * Returns the Mesh.
  27949. */
  27950. Mesh.prototype.refreshBoundingInfo = function () {
  27951. return this._refreshBoundingInfo(false);
  27952. };
  27953. Mesh.prototype._refreshBoundingInfo = function (applySkeleton) {
  27954. if (this._boundingInfo && this._boundingInfo.isLocked) {
  27955. return this;
  27956. }
  27957. var data = this._getPositionData(applySkeleton);
  27958. if (data) {
  27959. var extend = BABYLON.Tools.ExtractMinAndMax(data, 0, this.getTotalVertices());
  27960. this._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  27961. }
  27962. if (this.subMeshes) {
  27963. for (var index = 0; index < this.subMeshes.length; index++) {
  27964. this.subMeshes[index].refreshBoundingInfo();
  27965. }
  27966. }
  27967. this._updateBoundingInfo();
  27968. return this;
  27969. };
  27970. Mesh.prototype._getPositionData = function (applySkeleton) {
  27971. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  27972. if (data && applySkeleton && this.skeleton) {
  27973. data = BABYLON.Tools.Slice(data);
  27974. var matricesIndicesData = this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind);
  27975. var matricesWeightsData = this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind);
  27976. if (matricesWeightsData && matricesIndicesData) {
  27977. var needExtras = this.numBoneInfluencers > 4;
  27978. var matricesIndicesExtraData = needExtras ? this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind) : null;
  27979. var matricesWeightsExtraData = needExtras ? this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind) : null;
  27980. var skeletonMatrices = this.skeleton.getTransformMatrices(this);
  27981. var tempVector = BABYLON.Tmp.Vector3[0];
  27982. var finalMatrix = BABYLON.Tmp.Matrix[0];
  27983. var tempMatrix = BABYLON.Tmp.Matrix[1];
  27984. var matWeightIdx = 0;
  27985. for (var index = 0; index < data.length; index += 3, matWeightIdx += 4) {
  27986. finalMatrix.reset();
  27987. var inf;
  27988. var weight;
  27989. for (inf = 0; inf < 4; inf++) {
  27990. weight = matricesWeightsData[matWeightIdx + inf];
  27991. if (weight <= 0)
  27992. break;
  27993. BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, Math.floor(matricesIndicesData[matWeightIdx + inf] * 16), weight, tempMatrix);
  27994. finalMatrix.addToSelf(tempMatrix);
  27995. }
  27996. if (needExtras) {
  27997. for (inf = 0; inf < 4; inf++) {
  27998. weight = matricesWeightsExtraData[matWeightIdx + inf];
  27999. if (weight <= 0)
  28000. break;
  28001. BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, Math.floor(matricesIndicesExtraData[matWeightIdx + inf] * 16), weight, tempMatrix);
  28002. finalMatrix.addToSelf(tempMatrix);
  28003. }
  28004. }
  28005. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(data[index], data[index + 1], data[index + 2], finalMatrix, tempVector);
  28006. tempVector.toArray(data, index);
  28007. }
  28008. }
  28009. }
  28010. return data;
  28011. };
  28012. Mesh.prototype._createGlobalSubMesh = function (force) {
  28013. var totalVertices = this.getTotalVertices();
  28014. if (!totalVertices || !this.getIndices()) {
  28015. return null;
  28016. }
  28017. // Check if we need to recreate the submeshes
  28018. if (this.subMeshes && this.subMeshes.length > 0) {
  28019. var ib = this.getIndices();
  28020. if (!ib) {
  28021. return null;
  28022. }
  28023. var totalIndices = ib.length;
  28024. var needToRecreate = false;
  28025. if (force) {
  28026. needToRecreate = true;
  28027. }
  28028. else {
  28029. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  28030. var submesh = _a[_i];
  28031. if (submesh.indexStart + submesh.indexCount >= totalIndices) {
  28032. needToRecreate = true;
  28033. break;
  28034. }
  28035. if (submesh.verticesStart + submesh.verticesCount >= totalVertices) {
  28036. needToRecreate = true;
  28037. break;
  28038. }
  28039. }
  28040. }
  28041. if (!needToRecreate) {
  28042. return this.subMeshes[0];
  28043. }
  28044. }
  28045. this.releaseSubMeshes();
  28046. return new BABYLON.SubMesh(0, 0, totalVertices, 0, this.getTotalIndices(), this);
  28047. };
  28048. Mesh.prototype.subdivide = function (count) {
  28049. if (count < 1) {
  28050. return;
  28051. }
  28052. var totalIndices = this.getTotalIndices();
  28053. var subdivisionSize = (totalIndices / count) | 0;
  28054. var offset = 0;
  28055. // Ensure that subdivisionSize is a multiple of 3
  28056. while (subdivisionSize % 3 !== 0) {
  28057. subdivisionSize++;
  28058. }
  28059. this.releaseSubMeshes();
  28060. for (var index = 0; index < count; index++) {
  28061. if (offset >= totalIndices) {
  28062. break;
  28063. }
  28064. BABYLON.SubMesh.CreateFromIndices(0, offset, Math.min(subdivisionSize, totalIndices - offset), this);
  28065. offset += subdivisionSize;
  28066. }
  28067. this.synchronizeInstances();
  28068. };
  28069. /**
  28070. * Sets the vertex data of the mesh geometry for the requested `kind`.
  28071. * If the mesh has no geometry, a new Geometry object is set to the mesh and then passed this vertex data.
  28072. * The `data` are either a numeric array either a Float32Array.
  28073. * The parameter `updatable` is passed as is to the underlying Geometry object constructor (if initianilly none) or updater.
  28074. * 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).
  28075. * Note that a new underlying VertexBuffer object is created each call.
  28076. * If the `kind` is the `PositionKind`, the mesh BoundingInfo is renewed, so the bounding box and sphere, and the mesh World Matrix is recomputed.
  28077. *
  28078. * Possible `kind` values :
  28079. * - BABYLON.VertexBuffer.PositionKind
  28080. * - BABYLON.VertexBuffer.UVKind
  28081. * - BABYLON.VertexBuffer.UV2Kind
  28082. * - BABYLON.VertexBuffer.UV3Kind
  28083. * - BABYLON.VertexBuffer.UV4Kind
  28084. * - BABYLON.VertexBuffer.UV5Kind
  28085. * - BABYLON.VertexBuffer.UV6Kind
  28086. * - BABYLON.VertexBuffer.ColorKind
  28087. * - BABYLON.VertexBuffer.MatricesIndicesKind
  28088. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  28089. * - BABYLON.VertexBuffer.MatricesWeightsKind
  28090. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  28091. *
  28092. * Returns the Mesh.
  28093. */
  28094. Mesh.prototype.setVerticesData = function (kind, data, updatable, stride) {
  28095. if (updatable === void 0) { updatable = false; }
  28096. if (!this._geometry) {
  28097. var vertexData = new BABYLON.VertexData();
  28098. vertexData.set(data, kind);
  28099. var scene = this.getScene();
  28100. new BABYLON.Geometry(BABYLON.Geometry.RandomId(), scene, vertexData, updatable, this);
  28101. }
  28102. else {
  28103. this._geometry.setVerticesData(kind, data, updatable, stride);
  28104. }
  28105. return this;
  28106. };
  28107. Mesh.prototype.markVerticesDataAsUpdatable = function (kind, updatable) {
  28108. if (updatable === void 0) { updatable = true; }
  28109. var vb = this.getVertexBuffer(kind);
  28110. if (!vb || vb.isUpdatable() === updatable) {
  28111. return;
  28112. }
  28113. this.setVerticesData(kind, this.getVerticesData(kind), updatable);
  28114. };
  28115. /**
  28116. * Sets the mesh VertexBuffer.
  28117. * Returns the Mesh.
  28118. */
  28119. Mesh.prototype.setVerticesBuffer = function (buffer) {
  28120. if (!this._geometry) {
  28121. this._geometry = BABYLON.Geometry.CreateGeometryForMesh(this);
  28122. }
  28123. this._geometry.setVerticesBuffer(buffer);
  28124. return this;
  28125. };
  28126. /**
  28127. * Updates the existing vertex data of the mesh geometry for the requested `kind`.
  28128. * If the mesh has no geometry, it is simply returned as it is.
  28129. * The `data` are either a numeric array either a Float32Array.
  28130. * No new underlying VertexBuffer object is created.
  28131. * 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.
  28132. * If the parameter `makeItUnique` is true, a new global geometry is created from this positions and is set to the mesh.
  28133. *
  28134. * Possible `kind` values :
  28135. * - BABYLON.VertexBuffer.PositionKind
  28136. * - BABYLON.VertexBuffer.UVKind
  28137. * - BABYLON.VertexBuffer.UV2Kind
  28138. * - BABYLON.VertexBuffer.UV3Kind
  28139. * - BABYLON.VertexBuffer.UV4Kind
  28140. * - BABYLON.VertexBuffer.UV5Kind
  28141. * - BABYLON.VertexBuffer.UV6Kind
  28142. * - BABYLON.VertexBuffer.ColorKind
  28143. * - BABYLON.VertexBuffer.MatricesIndicesKind
  28144. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  28145. * - BABYLON.VertexBuffer.MatricesWeightsKind
  28146. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  28147. *
  28148. * Returns the Mesh.
  28149. */
  28150. Mesh.prototype.updateVerticesData = function (kind, data, updateExtends, makeItUnique) {
  28151. if (!this._geometry) {
  28152. return this;
  28153. }
  28154. if (!makeItUnique) {
  28155. this._geometry.updateVerticesData(kind, data, updateExtends);
  28156. }
  28157. else {
  28158. this.makeGeometryUnique();
  28159. this.updateVerticesData(kind, data, updateExtends, false);
  28160. }
  28161. return this;
  28162. };
  28163. /**
  28164. * This method updates the vertex positions of an updatable mesh according to the `positionFunction` returned values.
  28165. * tuto : http://doc.babylonjs.com/tutorials/How_to_dynamically_morph_a_mesh#other-shapes-updatemeshpositions
  28166. * The parameter `positionFunction` is a simple JS function what is passed the mesh `positions` array. It doesn't need to return anything.
  28167. * The parameter `computeNormals` is a boolean (default true) to enable/disable the mesh normal recomputation after the vertex position update.
  28168. * Returns the Mesh.
  28169. */
  28170. Mesh.prototype.updateMeshPositions = function (positionFunction, computeNormals) {
  28171. if (computeNormals === void 0) { computeNormals = true; }
  28172. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  28173. if (!positions) {
  28174. return this;
  28175. }
  28176. positionFunction(positions);
  28177. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions, false, false);
  28178. if (computeNormals) {
  28179. var indices = this.getIndices();
  28180. var normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  28181. if (!normals) {
  28182. return this;
  28183. }
  28184. BABYLON.VertexData.ComputeNormals(positions, indices, normals);
  28185. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals, false, false);
  28186. }
  28187. return this;
  28188. };
  28189. /**
  28190. * Creates a un-shared specific occurence of the geometry for the mesh.
  28191. * Returns the Mesh.
  28192. */
  28193. Mesh.prototype.makeGeometryUnique = function () {
  28194. if (!this._geometry) {
  28195. return this;
  28196. }
  28197. var oldGeometry = this._geometry;
  28198. var geometry = this._geometry.copy(BABYLON.Geometry.RandomId());
  28199. oldGeometry.releaseForMesh(this, true);
  28200. geometry.applyToMesh(this);
  28201. return this;
  28202. };
  28203. /**
  28204. * Sets the mesh indices.
  28205. * Expects an array populated with integers or a typed array (Int32Array, Uint32Array, Uint16Array).
  28206. * Type is Uint16Array by default unless the mesh has more than 65536 vertices.
  28207. * If the mesh has no geometry, a new Geometry object is created and set to the mesh.
  28208. * This method creates a new index buffer each call.
  28209. * Returns the Mesh.
  28210. */
  28211. Mesh.prototype.setIndices = function (indices, totalVertices, updatable) {
  28212. if (totalVertices === void 0) { totalVertices = null; }
  28213. if (updatable === void 0) { updatable = false; }
  28214. if (!this._geometry) {
  28215. var vertexData = new BABYLON.VertexData();
  28216. vertexData.indices = indices;
  28217. var scene = this.getScene();
  28218. new BABYLON.Geometry(BABYLON.Geometry.RandomId(), scene, vertexData, updatable, this);
  28219. }
  28220. else {
  28221. this._geometry.setIndices(indices, totalVertices, updatable);
  28222. }
  28223. return this;
  28224. };
  28225. /**
  28226. * Update the current index buffer
  28227. * Expects an array populated with integers or a typed array (Int32Array, Uint32Array, Uint16Array)
  28228. * Returns the Mesh.
  28229. */
  28230. Mesh.prototype.updateIndices = function (indices, offset) {
  28231. if (!this._geometry) {
  28232. return this;
  28233. }
  28234. this._geometry.updateIndices(indices, offset);
  28235. return this;
  28236. };
  28237. /**
  28238. * Invert the geometry to move from a right handed system to a left handed one.
  28239. * Returns the Mesh.
  28240. */
  28241. Mesh.prototype.toLeftHanded = function () {
  28242. if (!this._geometry) {
  28243. return this;
  28244. }
  28245. this._geometry.toLeftHanded();
  28246. return this;
  28247. };
  28248. Mesh.prototype._bind = function (subMesh, effect, fillMode) {
  28249. if (!this._geometry) {
  28250. return this;
  28251. }
  28252. var engine = this.getScene().getEngine();
  28253. // Wireframe
  28254. var indexToBind;
  28255. if (this._unIndexed) {
  28256. indexToBind = null;
  28257. }
  28258. else {
  28259. switch (fillMode) {
  28260. case BABYLON.Material.PointFillMode:
  28261. indexToBind = null;
  28262. break;
  28263. case BABYLON.Material.WireFrameFillMode:
  28264. indexToBind = subMesh.getLinesIndexBuffer(this.getIndices(), engine);
  28265. break;
  28266. default:
  28267. case BABYLON.Material.TriangleFillMode:
  28268. indexToBind = this._unIndexed ? null : this._geometry.getIndexBuffer();
  28269. break;
  28270. }
  28271. }
  28272. // VBOs
  28273. this._geometry._bind(effect, indexToBind);
  28274. return this;
  28275. };
  28276. Mesh.prototype._draw = function (subMesh, fillMode, instancesCount, alternate) {
  28277. if (alternate === void 0) { alternate = false; }
  28278. if (!this._geometry || !this._geometry.getVertexBuffers() || !this._geometry.getIndexBuffer()) {
  28279. return this;
  28280. }
  28281. this.onBeforeDrawObservable.notifyObservers(this);
  28282. var scene = this.getScene();
  28283. var engine = scene.getEngine();
  28284. if (this._unIndexed || fillMode == BABYLON.Material.PointFillMode) {
  28285. // or triangles as points
  28286. engine.drawArraysType(fillMode, subMesh.verticesStart, subMesh.verticesCount, instancesCount);
  28287. }
  28288. else if (fillMode == BABYLON.Material.WireFrameFillMode) {
  28289. // Triangles as wireframe
  28290. engine.drawElementsType(fillMode, 0, subMesh.linesIndexCount, instancesCount);
  28291. }
  28292. else {
  28293. engine.drawElementsType(fillMode, subMesh.indexStart, subMesh.indexCount, instancesCount);
  28294. }
  28295. if (scene._isAlternateRenderingEnabled && !alternate) {
  28296. var effect = subMesh.effect || this._effectiveMaterial.getEffect();
  28297. if (!effect || !scene.activeCamera) {
  28298. return this;
  28299. }
  28300. scene._switchToAlternateCameraConfiguration(true);
  28301. this._effectiveMaterial.bindView(effect);
  28302. this._effectiveMaterial.bindViewProjection(effect);
  28303. engine.setViewport(scene.activeCamera._alternateCamera.viewport);
  28304. this._draw(subMesh, fillMode, instancesCount, true);
  28305. engine.setViewport(scene.activeCamera.viewport);
  28306. scene._switchToAlternateCameraConfiguration(false);
  28307. this._effectiveMaterial.bindView(effect);
  28308. this._effectiveMaterial.bindViewProjection(effect);
  28309. }
  28310. return this;
  28311. };
  28312. /**
  28313. * Registers for this mesh a javascript function called just before the rendering process.
  28314. * This function is passed the current mesh.
  28315. * Return the Mesh.
  28316. */
  28317. Mesh.prototype.registerBeforeRender = function (func) {
  28318. this.onBeforeRenderObservable.add(func);
  28319. return this;
  28320. };
  28321. /**
  28322. * Disposes a previously registered javascript function called before the rendering.
  28323. * This function is passed the current mesh.
  28324. * Returns the Mesh.
  28325. */
  28326. Mesh.prototype.unregisterBeforeRender = function (func) {
  28327. this.onBeforeRenderObservable.removeCallback(func);
  28328. return this;
  28329. };
  28330. /**
  28331. * Registers for this mesh a javascript function called just after the rendering is complete.
  28332. * This function is passed the current mesh.
  28333. * Returns the Mesh.
  28334. */
  28335. Mesh.prototype.registerAfterRender = function (func) {
  28336. this.onAfterRenderObservable.add(func);
  28337. return this;
  28338. };
  28339. /**
  28340. * Disposes a previously registered javascript function called after the rendering.
  28341. * This function is passed the current mesh.
  28342. * Return the Mesh.
  28343. */
  28344. Mesh.prototype.unregisterAfterRender = function (func) {
  28345. this.onAfterRenderObservable.removeCallback(func);
  28346. return this;
  28347. };
  28348. Mesh.prototype._getInstancesRenderList = function (subMeshId) {
  28349. var scene = this.getScene();
  28350. this._batchCache.mustReturn = false;
  28351. this._batchCache.renderSelf[subMeshId] = this.isEnabled() && this.isVisible;
  28352. this._batchCache.visibleInstances[subMeshId] = null;
  28353. if (this._visibleInstances) {
  28354. var currentRenderId = scene.getRenderId();
  28355. var defaultRenderId = (scene._isInIntermediateRendering() ? this._visibleInstances.intermediateDefaultRenderId : this._visibleInstances.defaultRenderId);
  28356. this._batchCache.visibleInstances[subMeshId] = this._visibleInstances[currentRenderId];
  28357. var selfRenderId = this._renderId;
  28358. if (!this._batchCache.visibleInstances[subMeshId] && defaultRenderId) {
  28359. this._batchCache.visibleInstances[subMeshId] = this._visibleInstances[defaultRenderId];
  28360. currentRenderId = Math.max(defaultRenderId, currentRenderId);
  28361. selfRenderId = Math.max(this._visibleInstances.selfDefaultRenderId, currentRenderId);
  28362. }
  28363. var visibleInstancesForSubMesh = this._batchCache.visibleInstances[subMeshId];
  28364. if (visibleInstancesForSubMesh && visibleInstancesForSubMesh.length) {
  28365. if (this._renderIdForInstances[subMeshId] === currentRenderId) {
  28366. this._batchCache.mustReturn = true;
  28367. return this._batchCache;
  28368. }
  28369. if (currentRenderId !== selfRenderId) {
  28370. this._batchCache.renderSelf[subMeshId] = false;
  28371. }
  28372. }
  28373. this._renderIdForInstances[subMeshId] = currentRenderId;
  28374. }
  28375. return this._batchCache;
  28376. };
  28377. Mesh.prototype._renderWithInstances = function (subMesh, fillMode, batch, effect, engine) {
  28378. var visibleInstances = batch.visibleInstances[subMesh._id];
  28379. if (!visibleInstances) {
  28380. return this;
  28381. }
  28382. var matricesCount = visibleInstances.length + 1;
  28383. var bufferSize = matricesCount * 16 * 4;
  28384. var currentInstancesBufferSize = this._instancesBufferSize;
  28385. var instancesBuffer = this._instancesBuffer;
  28386. while (this._instancesBufferSize < bufferSize) {
  28387. this._instancesBufferSize *= 2;
  28388. }
  28389. if (!this._instancesData || currentInstancesBufferSize != this._instancesBufferSize) {
  28390. this._instancesData = new Float32Array(this._instancesBufferSize / 4);
  28391. }
  28392. var offset = 0;
  28393. var instancesCount = 0;
  28394. var world = this.getWorldMatrix();
  28395. if (batch.renderSelf[subMesh._id]) {
  28396. world.copyToArray(this._instancesData, offset);
  28397. offset += 16;
  28398. instancesCount++;
  28399. }
  28400. if (visibleInstances) {
  28401. for (var instanceIndex = 0; instanceIndex < visibleInstances.length; instanceIndex++) {
  28402. var instance = visibleInstances[instanceIndex];
  28403. instance.getWorldMatrix().copyToArray(this._instancesData, offset);
  28404. offset += 16;
  28405. instancesCount++;
  28406. }
  28407. }
  28408. if (!instancesBuffer || currentInstancesBufferSize != this._instancesBufferSize) {
  28409. if (instancesBuffer) {
  28410. instancesBuffer.dispose();
  28411. }
  28412. instancesBuffer = new BABYLON.Buffer(engine, this._instancesData, true, 16, false, true);
  28413. this._instancesBuffer = instancesBuffer;
  28414. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world0", 0, 4));
  28415. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world1", 4, 4));
  28416. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world2", 8, 4));
  28417. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world3", 12, 4));
  28418. }
  28419. else {
  28420. instancesBuffer.updateDirectly(this._instancesData, 0, instancesCount);
  28421. }
  28422. this._bind(subMesh, effect, fillMode);
  28423. this._draw(subMesh, fillMode, instancesCount);
  28424. engine.unbindInstanceAttributes();
  28425. return this;
  28426. };
  28427. Mesh.prototype._processRendering = function (subMesh, effect, fillMode, batch, hardwareInstancedRendering, onBeforeDraw, effectiveMaterial) {
  28428. var scene = this.getScene();
  28429. var engine = scene.getEngine();
  28430. if (hardwareInstancedRendering) {
  28431. this._renderWithInstances(subMesh, fillMode, batch, effect, engine);
  28432. }
  28433. else {
  28434. if (batch.renderSelf[subMesh._id]) {
  28435. // Draw
  28436. if (onBeforeDraw) {
  28437. onBeforeDraw(false, this.getWorldMatrix(), effectiveMaterial);
  28438. }
  28439. this._draw(subMesh, fillMode, this._overridenInstanceCount);
  28440. }
  28441. var visibleInstancesForSubMesh = batch.visibleInstances[subMesh._id];
  28442. if (visibleInstancesForSubMesh) {
  28443. for (var instanceIndex = 0; instanceIndex < visibleInstancesForSubMesh.length; instanceIndex++) {
  28444. var instance = visibleInstancesForSubMesh[instanceIndex];
  28445. // World
  28446. var world = instance.getWorldMatrix();
  28447. if (onBeforeDraw) {
  28448. onBeforeDraw(true, world, effectiveMaterial);
  28449. }
  28450. // Draw
  28451. this._draw(subMesh, fillMode);
  28452. }
  28453. }
  28454. }
  28455. return this;
  28456. };
  28457. /**
  28458. * Triggers the draw call for the mesh.
  28459. * Usually, you don't need to call this method by your own because the mesh rendering is handled by the scene rendering manager.
  28460. * Returns the Mesh.
  28461. */
  28462. Mesh.prototype.render = function (subMesh, enableAlphaMode) {
  28463. this.checkOcclusionQuery();
  28464. if (this._isOccluded) {
  28465. return this;
  28466. }
  28467. var scene = this.getScene();
  28468. // Managing instances
  28469. var batch = this._getInstancesRenderList(subMesh._id);
  28470. if (batch.mustReturn) {
  28471. return this;
  28472. }
  28473. // Checking geometry state
  28474. if (!this._geometry || !this._geometry.getVertexBuffers() || !this._geometry.getIndexBuffer()) {
  28475. return this;
  28476. }
  28477. this.onBeforeRenderObservable.notifyObservers(this);
  28478. var engine = scene.getEngine();
  28479. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  28480. // Material
  28481. var material = subMesh.getMaterial();
  28482. if (!material) {
  28483. return this;
  28484. }
  28485. this._effectiveMaterial = material;
  28486. if (this._effectiveMaterial.storeEffectOnSubMeshes) {
  28487. if (!this._effectiveMaterial.isReadyForSubMesh(this, subMesh, hardwareInstancedRendering)) {
  28488. return this;
  28489. }
  28490. }
  28491. else if (!this._effectiveMaterial.isReady(this, hardwareInstancedRendering)) {
  28492. return this;
  28493. }
  28494. // Alpha mode
  28495. if (enableAlphaMode) {
  28496. engine.setAlphaMode(this._effectiveMaterial.alphaMode);
  28497. }
  28498. // Outline - step 1
  28499. var savedDepthWrite = engine.getDepthWrite();
  28500. if (this.renderOutline) {
  28501. engine.setDepthWrite(false);
  28502. scene.getOutlineRenderer().render(subMesh, batch);
  28503. engine.setDepthWrite(savedDepthWrite);
  28504. }
  28505. var effect;
  28506. if (this._effectiveMaterial.storeEffectOnSubMeshes) {
  28507. effect = subMesh.effect;
  28508. }
  28509. else {
  28510. effect = this._effectiveMaterial.getEffect();
  28511. }
  28512. if (!effect) {
  28513. return this;
  28514. }
  28515. var sideOrientation = this.overrideMaterialSideOrientation;
  28516. if (sideOrientation == null) {
  28517. sideOrientation = this._effectiveMaterial.sideOrientation;
  28518. if (this._getWorldMatrixDeterminant() < 0) {
  28519. sideOrientation = (sideOrientation === BABYLON.Material.ClockWiseSideOrientation ? BABYLON.Material.CounterClockWiseSideOrientation : BABYLON.Material.ClockWiseSideOrientation);
  28520. }
  28521. }
  28522. var reverse = this._effectiveMaterial._preBind(effect, sideOrientation);
  28523. if (this._effectiveMaterial.forceDepthWrite) {
  28524. engine.setDepthWrite(true);
  28525. }
  28526. // Bind
  28527. var fillMode = scene.forcePointsCloud ? BABYLON.Material.PointFillMode : (scene.forceWireframe ? BABYLON.Material.WireFrameFillMode : this._effectiveMaterial.fillMode);
  28528. if (!hardwareInstancedRendering) {
  28529. this._bind(subMesh, effect, fillMode);
  28530. }
  28531. var world = this.getWorldMatrix();
  28532. if (this._effectiveMaterial.storeEffectOnSubMeshes) {
  28533. this._effectiveMaterial.bindForSubMesh(world, this, subMesh);
  28534. }
  28535. else {
  28536. this._effectiveMaterial.bind(world, this);
  28537. }
  28538. if (!this._effectiveMaterial.backFaceCulling && this._effectiveMaterial.separateCullingPass) {
  28539. engine.setState(true, this._effectiveMaterial.zOffset, false, !reverse);
  28540. this._processRendering(subMesh, effect, fillMode, batch, hardwareInstancedRendering, this._onBeforeDraw, this._effectiveMaterial);
  28541. engine.setState(true, this._effectiveMaterial.zOffset, false, reverse);
  28542. }
  28543. // Draw
  28544. this._processRendering(subMesh, effect, fillMode, batch, hardwareInstancedRendering, this._onBeforeDraw, this._effectiveMaterial);
  28545. // Unbind
  28546. this._effectiveMaterial.unbind();
  28547. // Outline - step 2
  28548. if (this.renderOutline && savedDepthWrite) {
  28549. engine.setDepthWrite(true);
  28550. engine.setColorWrite(false);
  28551. scene.getOutlineRenderer().render(subMesh, batch);
  28552. engine.setColorWrite(true);
  28553. }
  28554. // Overlay
  28555. if (this.renderOverlay) {
  28556. var currentMode = engine.getAlphaMode();
  28557. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  28558. scene.getOutlineRenderer().render(subMesh, batch, true);
  28559. engine.setAlphaMode(currentMode);
  28560. }
  28561. this.onAfterRenderObservable.notifyObservers(this);
  28562. return this;
  28563. };
  28564. Mesh.prototype._onBeforeDraw = function (isInstance, world, effectiveMaterial) {
  28565. if (isInstance && effectiveMaterial) {
  28566. effectiveMaterial.bindOnlyWorldMatrix(world);
  28567. }
  28568. };
  28569. /**
  28570. * Returns an array populated with ParticleSystem objects whose the mesh is the emitter.
  28571. */
  28572. Mesh.prototype.getEmittedParticleSystems = function () {
  28573. var results = new Array();
  28574. for (var index = 0; index < this.getScene().particleSystems.length; index++) {
  28575. var particleSystem = this.getScene().particleSystems[index];
  28576. if (particleSystem.emitter === this) {
  28577. results.push(particleSystem);
  28578. }
  28579. }
  28580. return results;
  28581. };
  28582. /**
  28583. * Returns an array populated with ParticleSystem objects whose the mesh or its children are the emitter.
  28584. */
  28585. Mesh.prototype.getHierarchyEmittedParticleSystems = function () {
  28586. var results = new Array();
  28587. var descendants = this.getDescendants();
  28588. descendants.push(this);
  28589. for (var index = 0; index < this.getScene().particleSystems.length; index++) {
  28590. var particleSystem = this.getScene().particleSystems[index];
  28591. var emitter = particleSystem.emitter;
  28592. if (emitter.position && descendants.indexOf(emitter) !== -1) {
  28593. results.push(particleSystem);
  28594. }
  28595. }
  28596. return results;
  28597. };
  28598. Mesh.prototype._checkDelayState = function () {
  28599. var scene = this.getScene();
  28600. if (this._geometry) {
  28601. this._geometry.load(scene);
  28602. }
  28603. else if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  28604. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADING;
  28605. this._queueLoad(scene);
  28606. }
  28607. return this;
  28608. };
  28609. Mesh.prototype._queueLoad = function (scene) {
  28610. var _this = this;
  28611. scene._addPendingData(this);
  28612. var getBinaryData = (this.delayLoadingFile.indexOf(".babylonbinarymeshdata") !== -1);
  28613. BABYLON.Tools.LoadFile(this.delayLoadingFile, function (data) {
  28614. if (data instanceof ArrayBuffer) {
  28615. _this._delayLoadingFunction(data, _this);
  28616. }
  28617. else {
  28618. _this._delayLoadingFunction(JSON.parse(data), _this);
  28619. }
  28620. _this.instances.forEach(function (instance) {
  28621. instance._syncSubMeshes();
  28622. });
  28623. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  28624. scene._removePendingData(_this);
  28625. }, function () { }, scene.database, getBinaryData);
  28626. return this;
  28627. };
  28628. /**
  28629. * Boolean, true is the mesh in the frustum defined by the Plane objects from the `frustumPlanes` array parameter.
  28630. */
  28631. Mesh.prototype.isInFrustum = function (frustumPlanes) {
  28632. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  28633. return false;
  28634. }
  28635. if (!_super.prototype.isInFrustum.call(this, frustumPlanes)) {
  28636. return false;
  28637. }
  28638. this._checkDelayState();
  28639. return true;
  28640. };
  28641. /**
  28642. * Sets the mesh material by the material or multiMaterial `id` property.
  28643. * The material `id` is a string identifying the material or the multiMaterial.
  28644. * This method returns the Mesh.
  28645. */
  28646. Mesh.prototype.setMaterialByID = function (id) {
  28647. var materials = this.getScene().materials;
  28648. var index;
  28649. for (index = materials.length - 1; index > -1; index--) {
  28650. if (materials[index].id === id) {
  28651. this.material = materials[index];
  28652. return this;
  28653. }
  28654. }
  28655. // Multi
  28656. var multiMaterials = this.getScene().multiMaterials;
  28657. for (index = multiMaterials.length - 1; index > -1; index--) {
  28658. if (multiMaterials[index].id === id) {
  28659. this.material = multiMaterials[index];
  28660. return this;
  28661. }
  28662. }
  28663. return this;
  28664. };
  28665. /**
  28666. * Returns as a new array populated with the mesh material and/or skeleton, if any.
  28667. */
  28668. Mesh.prototype.getAnimatables = function () {
  28669. var results = new Array();
  28670. if (this.material) {
  28671. results.push(this.material);
  28672. }
  28673. if (this.skeleton) {
  28674. results.push(this.skeleton);
  28675. }
  28676. return results;
  28677. };
  28678. /**
  28679. * Modifies the mesh geometry according to the passed transformation matrix.
  28680. * This method returns nothing but it really modifies the mesh even if it's originally not set as updatable.
  28681. * The mesh normals are modified accordingly the same transformation.
  28682. * tuto : http://doc.babylonjs.com/tutorials/How_Rotations_and_Translations_Work#baking-transform
  28683. * Note that, under the hood, this method sets a new VertexBuffer each call.
  28684. * Returns the Mesh.
  28685. */
  28686. Mesh.prototype.bakeTransformIntoVertices = function (transform) {
  28687. // Position
  28688. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  28689. return this;
  28690. }
  28691. var submeshes = this.subMeshes.splice(0);
  28692. this._resetPointsArrayCache();
  28693. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  28694. var temp = new Array();
  28695. var index;
  28696. for (index = 0; index < data.length; index += 3) {
  28697. BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.FromArray(data, index), transform).toArray(temp, index);
  28698. }
  28699. this.setVerticesData(BABYLON.VertexBuffer.PositionKind, temp, this.getVertexBuffer(BABYLON.VertexBuffer.PositionKind).isUpdatable());
  28700. // Normals
  28701. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  28702. return this;
  28703. }
  28704. data = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  28705. temp = [];
  28706. for (index = 0; index < data.length; index += 3) {
  28707. BABYLON.Vector3.TransformNormal(BABYLON.Vector3.FromArray(data, index), transform).normalize().toArray(temp, index);
  28708. }
  28709. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, temp, this.getVertexBuffer(BABYLON.VertexBuffer.NormalKind).isUpdatable());
  28710. // flip faces?
  28711. if (transform.m[0] * transform.m[5] * transform.m[10] < 0) {
  28712. this.flipFaces();
  28713. }
  28714. // Restore submeshes
  28715. this.releaseSubMeshes();
  28716. this.subMeshes = submeshes;
  28717. return this;
  28718. };
  28719. /**
  28720. * Modifies the mesh geometry according to its own current World Matrix.
  28721. * The mesh World Matrix is then reset.
  28722. * This method returns nothing but really modifies the mesh even if it's originally not set as updatable.
  28723. * tuto : tuto : http://doc.babylonjs.com/resources/baking_transformations
  28724. * Note that, under the hood, this method sets a new VertexBuffer each call.
  28725. * Returns the Mesh.
  28726. */
  28727. Mesh.prototype.bakeCurrentTransformIntoVertices = function () {
  28728. this.bakeTransformIntoVertices(this.computeWorldMatrix(true));
  28729. this.scaling.copyFromFloats(1, 1, 1);
  28730. this.position.copyFromFloats(0, 0, 0);
  28731. this.rotation.copyFromFloats(0, 0, 0);
  28732. //only if quaternion is already set
  28733. if (this.rotationQuaternion) {
  28734. this.rotationQuaternion = BABYLON.Quaternion.Identity();
  28735. }
  28736. this._worldMatrix = BABYLON.Matrix.Identity();
  28737. return this;
  28738. };
  28739. Object.defineProperty(Mesh.prototype, "_positions", {
  28740. // Cache
  28741. get: function () {
  28742. if (this._geometry) {
  28743. return this._geometry._positions;
  28744. }
  28745. return null;
  28746. },
  28747. enumerable: true,
  28748. configurable: true
  28749. });
  28750. Mesh.prototype._resetPointsArrayCache = function () {
  28751. if (this._geometry) {
  28752. this._geometry._resetPointsArrayCache();
  28753. }
  28754. return this;
  28755. };
  28756. Mesh.prototype._generatePointsArray = function () {
  28757. if (this._geometry) {
  28758. return this._geometry._generatePointsArray();
  28759. }
  28760. return false;
  28761. };
  28762. /**
  28763. * Returns a new Mesh object generated from the current mesh properties.
  28764. * This method must not get confused with createInstance().
  28765. * The parameter `name` is a string, the name given to the new mesh.
  28766. * The optional parameter `newParent` can be any Node object (default `null`).
  28767. * The optional parameter `doNotCloneChildren` (default `false`) allows/denies the recursive cloning of the original mesh children if any.
  28768. * 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.
  28769. */
  28770. Mesh.prototype.clone = function (name, newParent, doNotCloneChildren, clonePhysicsImpostor) {
  28771. if (clonePhysicsImpostor === void 0) { clonePhysicsImpostor = true; }
  28772. return new Mesh(name, this.getScene(), newParent, this, doNotCloneChildren, clonePhysicsImpostor);
  28773. };
  28774. /**
  28775. * Releases resources associated with this mesh.
  28776. * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default)
  28777. * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default)
  28778. */
  28779. Mesh.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  28780. var _this = this;
  28781. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  28782. this.morphTargetManager = null;
  28783. if (this._geometry) {
  28784. this._geometry.releaseForMesh(this, true);
  28785. }
  28786. // Sources
  28787. var meshes = this.getScene().meshes;
  28788. meshes.forEach(function (abstractMesh) {
  28789. var mesh = abstractMesh;
  28790. if (mesh._source && mesh._source === _this) {
  28791. mesh._source = null;
  28792. }
  28793. });
  28794. this._source = null;
  28795. // Instances
  28796. if (this._instancesBuffer) {
  28797. this._instancesBuffer.dispose();
  28798. this._instancesBuffer = null;
  28799. }
  28800. while (this.instances.length) {
  28801. this.instances[0].dispose();
  28802. }
  28803. // Effect layers.
  28804. var effectLayers = this.getScene().effectLayers;
  28805. for (var i = 0; i < effectLayers.length; i++) {
  28806. var effectLayer = effectLayers[i];
  28807. if (effectLayer) {
  28808. effectLayer._disposeMesh(this);
  28809. }
  28810. }
  28811. _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
  28812. };
  28813. /**
  28814. * Modifies the mesh geometry according to a displacement map.
  28815. * 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.
  28816. * The mesh must be set as updatable. Its internal geometry is directly modified, no new buffer are allocated.
  28817. * This method returns nothing.
  28818. * The parameter `url` is a string, the URL from the image file is to be downloaded.
  28819. * The parameters `minHeight` and `maxHeight` are the lower and upper limits of the displacement.
  28820. * 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.
  28821. * The parameter `uvOffset` is an optional vector2 used to offset UV.
  28822. * The parameter `uvScale` is an optional vector2 used to scale UV.
  28823. *
  28824. * Returns the Mesh.
  28825. */
  28826. Mesh.prototype.applyDisplacementMap = function (url, minHeight, maxHeight, onSuccess, uvOffset, uvScale) {
  28827. var _this = this;
  28828. var scene = this.getScene();
  28829. var onload = function (img) {
  28830. // Getting height map data
  28831. var canvas = document.createElement("canvas");
  28832. var context = canvas.getContext("2d");
  28833. var heightMapWidth = img.width;
  28834. var heightMapHeight = img.height;
  28835. canvas.width = heightMapWidth;
  28836. canvas.height = heightMapHeight;
  28837. context.drawImage(img, 0, 0);
  28838. // Create VertexData from map data
  28839. //Cast is due to wrong definition in lib.d.ts from ts 1.3 - https://github.com/Microsoft/TypeScript/issues/949
  28840. var buffer = context.getImageData(0, 0, heightMapWidth, heightMapHeight).data;
  28841. _this.applyDisplacementMapFromBuffer(buffer, heightMapWidth, heightMapHeight, minHeight, maxHeight, uvOffset, uvScale);
  28842. //execute success callback, if set
  28843. if (onSuccess) {
  28844. onSuccess(_this);
  28845. }
  28846. };
  28847. BABYLON.Tools.LoadImage(url, onload, function () { }, scene.database);
  28848. return this;
  28849. };
  28850. /**
  28851. * Modifies the mesh geometry according to a displacementMap buffer.
  28852. * 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.
  28853. * The mesh must be set as updatable. Its internal geometry is directly modified, no new buffer are allocated.
  28854. * This method returns nothing.
  28855. * 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.
  28856. * The parameters `heightMapWidth` and `heightMapHeight` are positive integers to set the width and height of the buffer image.
  28857. * The parameters `minHeight` and `maxHeight` are the lower and upper limits of the displacement.
  28858. * The parameter `uvOffset` is an optional vector2 used to offset UV.
  28859. * The parameter `uvScale` is an optional vector2 used to scale UV.
  28860. *
  28861. * Returns the Mesh.
  28862. */
  28863. Mesh.prototype.applyDisplacementMapFromBuffer = function (buffer, heightMapWidth, heightMapHeight, minHeight, maxHeight, uvOffset, uvScale) {
  28864. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)
  28865. || !this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)
  28866. || !this.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  28867. BABYLON.Tools.Warn("Cannot call applyDisplacementMap: Given mesh is not complete. Position, Normal or UV are missing");
  28868. return this;
  28869. }
  28870. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  28871. var normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  28872. var uvs = this.getVerticesData(BABYLON.VertexBuffer.UVKind);
  28873. var position = BABYLON.Vector3.Zero();
  28874. var normal = BABYLON.Vector3.Zero();
  28875. var uv = BABYLON.Vector2.Zero();
  28876. uvOffset = uvOffset || BABYLON.Vector2.Zero();
  28877. uvScale = uvScale || new BABYLON.Vector2(1, 1);
  28878. for (var index = 0; index < positions.length; index += 3) {
  28879. BABYLON.Vector3.FromArrayToRef(positions, index, position);
  28880. BABYLON.Vector3.FromArrayToRef(normals, index, normal);
  28881. BABYLON.Vector2.FromArrayToRef(uvs, (index / 3) * 2, uv);
  28882. // Compute height
  28883. var u = ((Math.abs(uv.x * uvScale.x + uvOffset.x) * heightMapWidth) % heightMapWidth) | 0;
  28884. var v = ((Math.abs(uv.y * uvScale.y + uvOffset.y) * heightMapHeight) % heightMapHeight) | 0;
  28885. var pos = (u + v * heightMapWidth) * 4;
  28886. var r = buffer[pos] / 255.0;
  28887. var g = buffer[pos + 1] / 255.0;
  28888. var b = buffer[pos + 2] / 255.0;
  28889. var gradient = r * 0.3 + g * 0.59 + b * 0.11;
  28890. normal.normalize();
  28891. normal.scaleInPlace(minHeight + (maxHeight - minHeight) * gradient);
  28892. position = position.add(normal);
  28893. position.toArray(positions, index);
  28894. }
  28895. BABYLON.VertexData.ComputeNormals(positions, this.getIndices(), normals);
  28896. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions);
  28897. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals);
  28898. return this;
  28899. };
  28900. /**
  28901. * Modify the mesh to get a flat shading rendering.
  28902. * This means each mesh facet will then have its own normals. Usually new vertices are added in the mesh geometry to get this result.
  28903. * This method returns the Mesh.
  28904. * Warning : the mesh is really modified even if not set originally as updatable and, under the hood, a new VertexBuffer is allocated.
  28905. */
  28906. Mesh.prototype.convertToFlatShadedMesh = function () {
  28907. /// <summary>Update normals and vertices to get a flat shading rendering.</summary>
  28908. /// <summary>Warning: This may imply adding vertices to the mesh in order to get exactly 3 vertices per face</summary>
  28909. var kinds = this.getVerticesDataKinds();
  28910. var vbs = {};
  28911. var data = {};
  28912. var newdata = {};
  28913. var updatableNormals = false;
  28914. var kindIndex;
  28915. var kind;
  28916. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  28917. kind = kinds[kindIndex];
  28918. var vertexBuffer = this.getVertexBuffer(kind);
  28919. if (kind === BABYLON.VertexBuffer.NormalKind) {
  28920. updatableNormals = vertexBuffer.isUpdatable();
  28921. kinds.splice(kindIndex, 1);
  28922. kindIndex--;
  28923. continue;
  28924. }
  28925. vbs[kind] = vertexBuffer;
  28926. data[kind] = vbs[kind].getData();
  28927. newdata[kind] = [];
  28928. }
  28929. // Save previous submeshes
  28930. var previousSubmeshes = this.subMeshes.slice(0);
  28931. var indices = this.getIndices();
  28932. var totalIndices = this.getTotalIndices();
  28933. // Generating unique vertices per face
  28934. var index;
  28935. for (index = 0; index < totalIndices; index++) {
  28936. var vertexIndex = indices[index];
  28937. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  28938. kind = kinds[kindIndex];
  28939. var stride = vbs[kind].getStrideSize();
  28940. for (var offset = 0; offset < stride; offset++) {
  28941. newdata[kind].push(data[kind][vertexIndex * stride + offset]);
  28942. }
  28943. }
  28944. }
  28945. // Updating faces & normal
  28946. var normals = [];
  28947. var positions = newdata[BABYLON.VertexBuffer.PositionKind];
  28948. for (index = 0; index < totalIndices; index += 3) {
  28949. indices[index] = index;
  28950. indices[index + 1] = index + 1;
  28951. indices[index + 2] = index + 2;
  28952. var p1 = BABYLON.Vector3.FromArray(positions, index * 3);
  28953. var p2 = BABYLON.Vector3.FromArray(positions, (index + 1) * 3);
  28954. var p3 = BABYLON.Vector3.FromArray(positions, (index + 2) * 3);
  28955. var p1p2 = p1.subtract(p2);
  28956. var p3p2 = p3.subtract(p2);
  28957. var normal = BABYLON.Vector3.Normalize(BABYLON.Vector3.Cross(p1p2, p3p2));
  28958. // Store same normals for every vertex
  28959. for (var localIndex = 0; localIndex < 3; localIndex++) {
  28960. normals.push(normal.x);
  28961. normals.push(normal.y);
  28962. normals.push(normal.z);
  28963. }
  28964. }
  28965. this.setIndices(indices);
  28966. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals, updatableNormals);
  28967. // Updating vertex buffers
  28968. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  28969. kind = kinds[kindIndex];
  28970. this.setVerticesData(kind, newdata[kind], vbs[kind].isUpdatable());
  28971. }
  28972. // Updating submeshes
  28973. this.releaseSubMeshes();
  28974. for (var submeshIndex = 0; submeshIndex < previousSubmeshes.length; submeshIndex++) {
  28975. var previousOne = previousSubmeshes[submeshIndex];
  28976. BABYLON.SubMesh.AddToMesh(previousOne.materialIndex, previousOne.indexStart, previousOne.indexCount, previousOne.indexStart, previousOne.indexCount, this);
  28977. }
  28978. this.synchronizeInstances();
  28979. return this;
  28980. };
  28981. /**
  28982. * This method removes all the mesh indices and add new vertices (duplication) in order to unfold facets into buffers.
  28983. * In other words, more vertices, no more indices and a single bigger VBO.
  28984. * The mesh is really modified even if not set originally as updatable. Under the hood, a new VertexBuffer is allocated.
  28985. * Returns the Mesh.
  28986. */
  28987. Mesh.prototype.convertToUnIndexedMesh = function () {
  28988. /// <summary>Remove indices by unfolding faces into buffers</summary>
  28989. /// <summary>Warning: This implies adding vertices to the mesh in order to get exactly 3 vertices per face</summary>
  28990. var kinds = this.getVerticesDataKinds();
  28991. var vbs = {};
  28992. var data = {};
  28993. var newdata = {};
  28994. var kindIndex;
  28995. var kind;
  28996. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  28997. kind = kinds[kindIndex];
  28998. var vertexBuffer = this.getVertexBuffer(kind);
  28999. vbs[kind] = vertexBuffer;
  29000. data[kind] = vbs[kind].getData();
  29001. newdata[kind] = [];
  29002. }
  29003. // Save previous submeshes
  29004. var previousSubmeshes = this.subMeshes.slice(0);
  29005. var indices = this.getIndices();
  29006. var totalIndices = this.getTotalIndices();
  29007. // Generating unique vertices per face
  29008. var index;
  29009. for (index = 0; index < totalIndices; index++) {
  29010. var vertexIndex = indices[index];
  29011. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  29012. kind = kinds[kindIndex];
  29013. var stride = vbs[kind].getStrideSize();
  29014. for (var offset = 0; offset < stride; offset++) {
  29015. newdata[kind].push(data[kind][vertexIndex * stride + offset]);
  29016. }
  29017. }
  29018. }
  29019. // Updating indices
  29020. for (index = 0; index < totalIndices; index += 3) {
  29021. indices[index] = index;
  29022. indices[index + 1] = index + 1;
  29023. indices[index + 2] = index + 2;
  29024. }
  29025. this.setIndices(indices);
  29026. // Updating vertex buffers
  29027. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  29028. kind = kinds[kindIndex];
  29029. this.setVerticesData(kind, newdata[kind], vbs[kind].isUpdatable());
  29030. }
  29031. // Updating submeshes
  29032. this.releaseSubMeshes();
  29033. for (var submeshIndex = 0; submeshIndex < previousSubmeshes.length; submeshIndex++) {
  29034. var previousOne = previousSubmeshes[submeshIndex];
  29035. BABYLON.SubMesh.AddToMesh(previousOne.materialIndex, previousOne.indexStart, previousOne.indexCount, previousOne.indexStart, previousOne.indexCount, this);
  29036. }
  29037. this._unIndexed = true;
  29038. this.synchronizeInstances();
  29039. return this;
  29040. };
  29041. /**
  29042. * Inverses facet orientations and inverts also the normals with `flipNormals` (default `false`) if true.
  29043. * This method returns the Mesh.
  29044. * Warning : the mesh is really modified even if not set originally as updatable. A new VertexBuffer is created under the hood each call.
  29045. */
  29046. Mesh.prototype.flipFaces = function (flipNormals) {
  29047. if (flipNormals === void 0) { flipNormals = false; }
  29048. var vertex_data = BABYLON.VertexData.ExtractFromMesh(this);
  29049. var i;
  29050. if (flipNormals && this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind) && vertex_data.normals) {
  29051. for (i = 0; i < vertex_data.normals.length; i++) {
  29052. vertex_data.normals[i] *= -1;
  29053. }
  29054. }
  29055. if (vertex_data.indices) {
  29056. var temp;
  29057. for (i = 0; i < vertex_data.indices.length; i += 3) {
  29058. // reassign indices
  29059. temp = vertex_data.indices[i + 1];
  29060. vertex_data.indices[i + 1] = vertex_data.indices[i + 2];
  29061. vertex_data.indices[i + 2] = temp;
  29062. }
  29063. }
  29064. vertex_data.applyToMesh(this);
  29065. return this;
  29066. };
  29067. // Instances
  29068. /**
  29069. * Creates a new InstancedMesh object from the mesh model.
  29070. * An instance shares the same properties and the same material than its model.
  29071. * Only these properties of each instance can then be set individually :
  29072. * - position
  29073. * - rotation
  29074. * - rotationQuaternion
  29075. * - setPivotMatrix
  29076. * - scaling
  29077. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_Instances
  29078. * Warning : this method is not supported for Line mesh and LineSystem
  29079. */
  29080. Mesh.prototype.createInstance = function (name) {
  29081. return new BABYLON.InstancedMesh(name, this);
  29082. };
  29083. /**
  29084. * Synchronises all the mesh instance submeshes to the current mesh submeshes, if any.
  29085. * After this call, all the mesh instances have the same submeshes than the current mesh.
  29086. * This method returns the Mesh.
  29087. */
  29088. Mesh.prototype.synchronizeInstances = function () {
  29089. for (var instanceIndex = 0; instanceIndex < this.instances.length; instanceIndex++) {
  29090. var instance = this.instances[instanceIndex];
  29091. instance._syncSubMeshes();
  29092. }
  29093. return this;
  29094. };
  29095. /**
  29096. * Simplify the mesh according to the given array of settings.
  29097. * Function will return immediately and will simplify async. It returns the Mesh.
  29098. * @param settings a collection of simplification settings.
  29099. * @param parallelProcessing should all levels calculate parallel or one after the other.
  29100. * @param type the type of simplification to run.
  29101. * @param successCallback optional success callback to be called after the simplification finished processing all settings.
  29102. */
  29103. Mesh.prototype.simplify = function (settings, parallelProcessing, simplificationType, successCallback) {
  29104. if (parallelProcessing === void 0) { parallelProcessing = true; }
  29105. if (simplificationType === void 0) { simplificationType = BABYLON.SimplificationType.QUADRATIC; }
  29106. this.getScene().simplificationQueue.addTask({
  29107. settings: settings,
  29108. parallelProcessing: parallelProcessing,
  29109. mesh: this,
  29110. simplificationType: simplificationType,
  29111. successCallback: successCallback
  29112. });
  29113. return this;
  29114. };
  29115. /**
  29116. * Optimization of the mesh's indices, in case a mesh has duplicated vertices.
  29117. * The function will only reorder the indices and will not remove unused vertices to avoid problems with submeshes.
  29118. * This should be used together with the simplification to avoid disappearing triangles.
  29119. * Returns the Mesh.
  29120. * @param successCallback an optional success callback to be called after the optimization finished.
  29121. */
  29122. Mesh.prototype.optimizeIndices = function (successCallback) {
  29123. var _this = this;
  29124. var indices = this.getIndices();
  29125. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  29126. if (!positions || !indices) {
  29127. return this;
  29128. }
  29129. var vectorPositions = new Array();
  29130. for (var pos = 0; pos < positions.length; pos = pos + 3) {
  29131. vectorPositions.push(BABYLON.Vector3.FromArray(positions, pos));
  29132. }
  29133. var dupes = new Array();
  29134. BABYLON.AsyncLoop.SyncAsyncForLoop(vectorPositions.length, 40, function (iteration) {
  29135. var realPos = vectorPositions.length - 1 - iteration;
  29136. var testedPosition = vectorPositions[realPos];
  29137. for (var j = 0; j < realPos; ++j) {
  29138. var againstPosition = vectorPositions[j];
  29139. if (testedPosition.equals(againstPosition)) {
  29140. dupes[realPos] = j;
  29141. break;
  29142. }
  29143. }
  29144. }, function () {
  29145. for (var i = 0; i < indices.length; ++i) {
  29146. indices[i] = dupes[indices[i]] || indices[i];
  29147. }
  29148. //indices are now reordered
  29149. var originalSubMeshes = _this.subMeshes.slice(0);
  29150. _this.setIndices(indices);
  29151. _this.subMeshes = originalSubMeshes;
  29152. if (successCallback) {
  29153. successCallback(_this);
  29154. }
  29155. });
  29156. return this;
  29157. };
  29158. Mesh.prototype.serialize = function (serializationObject) {
  29159. serializationObject.name = this.name;
  29160. serializationObject.id = this.id;
  29161. serializationObject.type = this.getClassName();
  29162. if (BABYLON.Tags && BABYLON.Tags.HasTags(this)) {
  29163. serializationObject.tags = BABYLON.Tags.GetTags(this);
  29164. }
  29165. serializationObject.position = this.position.asArray();
  29166. if (this.rotationQuaternion) {
  29167. serializationObject.rotationQuaternion = this.rotationQuaternion.asArray();
  29168. }
  29169. else if (this.rotation) {
  29170. serializationObject.rotation = this.rotation.asArray();
  29171. }
  29172. serializationObject.scaling = this.scaling.asArray();
  29173. serializationObject.localMatrix = this.getPivotMatrix().asArray();
  29174. serializationObject.isEnabled = this.isEnabled(false);
  29175. serializationObject.isVisible = this.isVisible;
  29176. serializationObject.infiniteDistance = this.infiniteDistance;
  29177. serializationObject.pickable = this.isPickable;
  29178. serializationObject.receiveShadows = this.receiveShadows;
  29179. serializationObject.billboardMode = this.billboardMode;
  29180. serializationObject.visibility = this.visibility;
  29181. serializationObject.checkCollisions = this.checkCollisions;
  29182. serializationObject.isBlocker = this.isBlocker;
  29183. // Parent
  29184. if (this.parent) {
  29185. serializationObject.parentId = this.parent.id;
  29186. }
  29187. // Geometry
  29188. serializationObject.isUnIndexed = this.isUnIndexed;
  29189. var geometry = this._geometry;
  29190. if (geometry) {
  29191. var geometryId = geometry.id;
  29192. serializationObject.geometryId = geometryId;
  29193. // SubMeshes
  29194. serializationObject.subMeshes = [];
  29195. for (var subIndex = 0; subIndex < this.subMeshes.length; subIndex++) {
  29196. var subMesh = this.subMeshes[subIndex];
  29197. serializationObject.subMeshes.push({
  29198. materialIndex: subMesh.materialIndex,
  29199. verticesStart: subMesh.verticesStart,
  29200. verticesCount: subMesh.verticesCount,
  29201. indexStart: subMesh.indexStart,
  29202. indexCount: subMesh.indexCount
  29203. });
  29204. }
  29205. }
  29206. // Material
  29207. if (this.material) {
  29208. serializationObject.materialId = this.material.id;
  29209. }
  29210. else {
  29211. this.material = null;
  29212. }
  29213. // Morph targets
  29214. if (this.morphTargetManager) {
  29215. serializationObject.morphTargetManagerId = this.morphTargetManager.uniqueId;
  29216. }
  29217. // Skeleton
  29218. if (this.skeleton) {
  29219. serializationObject.skeletonId = this.skeleton.id;
  29220. }
  29221. // Physics
  29222. //TODO implement correct serialization for physics impostors.
  29223. var impostor = this.getPhysicsImpostor();
  29224. if (impostor) {
  29225. serializationObject.physicsMass = impostor.getParam("mass");
  29226. serializationObject.physicsFriction = impostor.getParam("friction");
  29227. serializationObject.physicsRestitution = impostor.getParam("mass");
  29228. serializationObject.physicsImpostor = impostor.type;
  29229. }
  29230. // Metadata
  29231. if (this.metadata) {
  29232. serializationObject.metadata = this.metadata;
  29233. }
  29234. // Instances
  29235. serializationObject.instances = [];
  29236. for (var index = 0; index < this.instances.length; index++) {
  29237. var instance = this.instances[index];
  29238. var serializationInstance = {
  29239. name: instance.name,
  29240. id: instance.id,
  29241. position: instance.position.asArray(),
  29242. scaling: instance.scaling.asArray()
  29243. };
  29244. if (instance.rotationQuaternion) {
  29245. serializationInstance.rotationQuaternion = instance.rotationQuaternion.asArray();
  29246. }
  29247. else if (instance.rotation) {
  29248. serializationInstance.rotation = instance.rotation.asArray();
  29249. }
  29250. serializationObject.instances.push(serializationInstance);
  29251. // Animations
  29252. BABYLON.Animation.AppendSerializedAnimations(instance, serializationInstance);
  29253. serializationInstance.ranges = instance.serializeAnimationRanges();
  29254. }
  29255. //
  29256. // Animations
  29257. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  29258. serializationObject.ranges = this.serializeAnimationRanges();
  29259. // Layer mask
  29260. serializationObject.layerMask = this.layerMask;
  29261. // Alpha
  29262. serializationObject.alphaIndex = this.alphaIndex;
  29263. serializationObject.hasVertexAlpha = this.hasVertexAlpha;
  29264. // Overlay
  29265. serializationObject.overlayAlpha = this.overlayAlpha;
  29266. serializationObject.overlayColor = this.overlayColor.asArray();
  29267. serializationObject.renderOverlay = this.renderOverlay;
  29268. // Fog
  29269. serializationObject.applyFog = this.applyFog;
  29270. // Action Manager
  29271. if (this.actionManager) {
  29272. serializationObject.actions = this.actionManager.serialize(this.name);
  29273. }
  29274. };
  29275. Mesh.prototype._syncGeometryWithMorphTargetManager = function () {
  29276. if (!this.geometry) {
  29277. return;
  29278. }
  29279. this._markSubMeshesAsAttributesDirty();
  29280. var morphTargetManager = this._morphTargetManager;
  29281. if (morphTargetManager && morphTargetManager.vertexCount) {
  29282. if (morphTargetManager.vertexCount !== this.getTotalVertices()) {
  29283. BABYLON.Tools.Error("Mesh is incompatible with morph targets. Targets and mesh must all have the same vertices count.");
  29284. this.morphTargetManager = null;
  29285. return;
  29286. }
  29287. for (var index = 0; index < morphTargetManager.numInfluencers; index++) {
  29288. var morphTarget = morphTargetManager.getActiveTarget(index);
  29289. var positions = morphTarget.getPositions();
  29290. if (!positions) {
  29291. BABYLON.Tools.Error("Invalid morph target. Target must have positions.");
  29292. return;
  29293. }
  29294. this.geometry.setVerticesData(BABYLON.VertexBuffer.PositionKind + index, positions, false, 3);
  29295. var normals = morphTarget.getNormals();
  29296. if (normals) {
  29297. this.geometry.setVerticesData(BABYLON.VertexBuffer.NormalKind + index, normals, false, 3);
  29298. }
  29299. var tangents = morphTarget.getTangents();
  29300. if (tangents) {
  29301. this.geometry.setVerticesData(BABYLON.VertexBuffer.TangentKind + index, tangents, false, 3);
  29302. }
  29303. }
  29304. }
  29305. else {
  29306. var index = 0;
  29307. // Positions
  29308. while (this.geometry.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind + index)) {
  29309. this.geometry.removeVerticesData(BABYLON.VertexBuffer.PositionKind + index);
  29310. if (this.geometry.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind + index)) {
  29311. this.geometry.removeVerticesData(BABYLON.VertexBuffer.NormalKind + index);
  29312. }
  29313. if (this.geometry.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind + index)) {
  29314. this.geometry.removeVerticesData(BABYLON.VertexBuffer.TangentKind + index);
  29315. }
  29316. index++;
  29317. }
  29318. }
  29319. };
  29320. // Statics
  29321. /**
  29322. * Returns a new Mesh object parsed from the source provided.
  29323. * The parameter `parsedMesh` is the source.
  29324. * The parameter `rootUrl` is a string, it's the root URL to prefix the `delayLoadingFile` property with
  29325. */
  29326. Mesh.Parse = function (parsedMesh, scene, rootUrl) {
  29327. var mesh;
  29328. if (parsedMesh.type && parsedMesh.type === "GroundMesh") {
  29329. mesh = BABYLON.GroundMesh.Parse(parsedMesh, scene);
  29330. }
  29331. else {
  29332. mesh = new Mesh(parsedMesh.name, scene);
  29333. }
  29334. mesh.id = parsedMesh.id;
  29335. if (BABYLON.Tags) {
  29336. BABYLON.Tags.AddTagsTo(mesh, parsedMesh.tags);
  29337. }
  29338. mesh.position = BABYLON.Vector3.FromArray(parsedMesh.position);
  29339. if (parsedMesh.metadata !== undefined) {
  29340. mesh.metadata = parsedMesh.metadata;
  29341. }
  29342. if (parsedMesh.rotationQuaternion) {
  29343. mesh.rotationQuaternion = BABYLON.Quaternion.FromArray(parsedMesh.rotationQuaternion);
  29344. }
  29345. else if (parsedMesh.rotation) {
  29346. mesh.rotation = BABYLON.Vector3.FromArray(parsedMesh.rotation);
  29347. }
  29348. mesh.scaling = BABYLON.Vector3.FromArray(parsedMesh.scaling);
  29349. if (parsedMesh.localMatrix) {
  29350. mesh.setPreTransformMatrix(BABYLON.Matrix.FromArray(parsedMesh.localMatrix));
  29351. }
  29352. else if (parsedMesh.pivotMatrix) {
  29353. mesh.setPivotMatrix(BABYLON.Matrix.FromArray(parsedMesh.pivotMatrix));
  29354. }
  29355. mesh.setEnabled(parsedMesh.isEnabled);
  29356. mesh.isVisible = parsedMesh.isVisible;
  29357. mesh.infiniteDistance = parsedMesh.infiniteDistance;
  29358. mesh.showBoundingBox = parsedMesh.showBoundingBox;
  29359. mesh.showSubMeshesBoundingBox = parsedMesh.showSubMeshesBoundingBox;
  29360. if (parsedMesh.applyFog !== undefined) {
  29361. mesh.applyFog = parsedMesh.applyFog;
  29362. }
  29363. if (parsedMesh.pickable !== undefined) {
  29364. mesh.isPickable = parsedMesh.pickable;
  29365. }
  29366. if (parsedMesh.alphaIndex !== undefined) {
  29367. mesh.alphaIndex = parsedMesh.alphaIndex;
  29368. }
  29369. mesh.receiveShadows = parsedMesh.receiveShadows;
  29370. mesh.billboardMode = parsedMesh.billboardMode;
  29371. if (parsedMesh.visibility !== undefined) {
  29372. mesh.visibility = parsedMesh.visibility;
  29373. }
  29374. mesh.checkCollisions = parsedMesh.checkCollisions;
  29375. if (parsedMesh.isBlocker !== undefined) {
  29376. mesh.isBlocker = parsedMesh.isBlocker;
  29377. }
  29378. mesh._shouldGenerateFlatShading = parsedMesh.useFlatShading;
  29379. // freezeWorldMatrix
  29380. if (parsedMesh.freezeWorldMatrix) {
  29381. mesh._waitingFreezeWorldMatrix = parsedMesh.freezeWorldMatrix;
  29382. }
  29383. // Parent
  29384. if (parsedMesh.parentId) {
  29385. mesh._waitingParentId = parsedMesh.parentId;
  29386. }
  29387. // Actions
  29388. if (parsedMesh.actions !== undefined) {
  29389. mesh._waitingActions = parsedMesh.actions;
  29390. }
  29391. // Overlay
  29392. if (parsedMesh.overlayAlpha !== undefined) {
  29393. mesh.overlayAlpha = parsedMesh.overlayAlpha;
  29394. }
  29395. if (parsedMesh.overlayColor !== undefined) {
  29396. mesh.overlayColor = BABYLON.Color3.FromArray(parsedMesh.overlayColor);
  29397. }
  29398. if (parsedMesh.renderOverlay !== undefined) {
  29399. mesh.renderOverlay = parsedMesh.renderOverlay;
  29400. }
  29401. // Geometry
  29402. mesh.isUnIndexed = !!parsedMesh.isUnIndexed;
  29403. mesh.hasVertexAlpha = parsedMesh.hasVertexAlpha;
  29404. if (parsedMesh.delayLoadingFile) {
  29405. mesh.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  29406. mesh.delayLoadingFile = rootUrl + parsedMesh.delayLoadingFile;
  29407. mesh._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Vector3.FromArray(parsedMesh.boundingBoxMinimum), BABYLON.Vector3.FromArray(parsedMesh.boundingBoxMaximum));
  29408. if (parsedMesh._binaryInfo) {
  29409. mesh._binaryInfo = parsedMesh._binaryInfo;
  29410. }
  29411. mesh._delayInfo = [];
  29412. if (parsedMesh.hasUVs) {
  29413. mesh._delayInfo.push(BABYLON.VertexBuffer.UVKind);
  29414. }
  29415. if (parsedMesh.hasUVs2) {
  29416. mesh._delayInfo.push(BABYLON.VertexBuffer.UV2Kind);
  29417. }
  29418. if (parsedMesh.hasUVs3) {
  29419. mesh._delayInfo.push(BABYLON.VertexBuffer.UV3Kind);
  29420. }
  29421. if (parsedMesh.hasUVs4) {
  29422. mesh._delayInfo.push(BABYLON.VertexBuffer.UV4Kind);
  29423. }
  29424. if (parsedMesh.hasUVs5) {
  29425. mesh._delayInfo.push(BABYLON.VertexBuffer.UV5Kind);
  29426. }
  29427. if (parsedMesh.hasUVs6) {
  29428. mesh._delayInfo.push(BABYLON.VertexBuffer.UV6Kind);
  29429. }
  29430. if (parsedMesh.hasColors) {
  29431. mesh._delayInfo.push(BABYLON.VertexBuffer.ColorKind);
  29432. }
  29433. if (parsedMesh.hasMatricesIndices) {
  29434. mesh._delayInfo.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  29435. }
  29436. if (parsedMesh.hasMatricesWeights) {
  29437. mesh._delayInfo.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  29438. }
  29439. mesh._delayLoadingFunction = BABYLON.Geometry._ImportGeometry;
  29440. if (BABYLON.SceneLoader.ForceFullSceneLoadingForIncremental) {
  29441. mesh._checkDelayState();
  29442. }
  29443. }
  29444. else {
  29445. BABYLON.Geometry._ImportGeometry(parsedMesh, mesh);
  29446. }
  29447. // Material
  29448. if (parsedMesh.materialId) {
  29449. mesh.setMaterialByID(parsedMesh.materialId);
  29450. }
  29451. else {
  29452. mesh.material = null;
  29453. }
  29454. // Morph targets
  29455. if (parsedMesh.morphTargetManagerId > -1) {
  29456. mesh.morphTargetManager = scene.getMorphTargetManagerById(parsedMesh.morphTargetManagerId);
  29457. }
  29458. // Skeleton
  29459. if (parsedMesh.skeletonId > -1) {
  29460. mesh.skeleton = scene.getLastSkeletonByID(parsedMesh.skeletonId);
  29461. if (parsedMesh.numBoneInfluencers) {
  29462. mesh.numBoneInfluencers = parsedMesh.numBoneInfluencers;
  29463. }
  29464. }
  29465. // Animations
  29466. if (parsedMesh.animations) {
  29467. for (var animationIndex = 0; animationIndex < parsedMesh.animations.length; animationIndex++) {
  29468. var parsedAnimation = parsedMesh.animations[animationIndex];
  29469. mesh.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  29470. }
  29471. BABYLON.Node.ParseAnimationRanges(mesh, parsedMesh, scene);
  29472. }
  29473. if (parsedMesh.autoAnimate) {
  29474. scene.beginAnimation(mesh, parsedMesh.autoAnimateFrom, parsedMesh.autoAnimateTo, parsedMesh.autoAnimateLoop, parsedMesh.autoAnimateSpeed || 1.0);
  29475. }
  29476. // Layer Mask
  29477. if (parsedMesh.layerMask && (!isNaN(parsedMesh.layerMask))) {
  29478. mesh.layerMask = Math.abs(parseInt(parsedMesh.layerMask));
  29479. }
  29480. else {
  29481. mesh.layerMask = 0x0FFFFFFF;
  29482. }
  29483. // Physics
  29484. if (parsedMesh.physicsImpostor) {
  29485. mesh.physicsImpostor = new BABYLON.PhysicsImpostor(mesh, parsedMesh.physicsImpostor, {
  29486. mass: parsedMesh.physicsMass,
  29487. friction: parsedMesh.physicsFriction,
  29488. restitution: parsedMesh.physicsRestitution
  29489. }, scene);
  29490. }
  29491. // Instances
  29492. if (parsedMesh.instances) {
  29493. for (var index = 0; index < parsedMesh.instances.length; index++) {
  29494. var parsedInstance = parsedMesh.instances[index];
  29495. var instance = mesh.createInstance(parsedInstance.name);
  29496. if (parsedInstance.id) {
  29497. instance.id = parsedInstance.id;
  29498. }
  29499. if (BABYLON.Tags) {
  29500. BABYLON.Tags.AddTagsTo(instance, parsedInstance.tags);
  29501. }
  29502. instance.position = BABYLON.Vector3.FromArray(parsedInstance.position);
  29503. if (parsedInstance.parentId) {
  29504. instance._waitingParentId = parsedInstance.parentId;
  29505. }
  29506. if (parsedInstance.rotationQuaternion) {
  29507. instance.rotationQuaternion = BABYLON.Quaternion.FromArray(parsedInstance.rotationQuaternion);
  29508. }
  29509. else if (parsedInstance.rotation) {
  29510. instance.rotation = BABYLON.Vector3.FromArray(parsedInstance.rotation);
  29511. }
  29512. instance.scaling = BABYLON.Vector3.FromArray(parsedInstance.scaling);
  29513. instance.checkCollisions = mesh.checkCollisions;
  29514. if (parsedMesh.animations) {
  29515. for (animationIndex = 0; animationIndex < parsedMesh.animations.length; animationIndex++) {
  29516. parsedAnimation = parsedMesh.animations[animationIndex];
  29517. instance.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  29518. }
  29519. BABYLON.Node.ParseAnimationRanges(instance, parsedMesh, scene);
  29520. }
  29521. }
  29522. }
  29523. return mesh;
  29524. };
  29525. /**
  29526. * Creates a ribbon mesh.
  29527. * Please consider using the same method from the MeshBuilder class instead.
  29528. * 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.
  29529. *
  29530. * Please read this full tutorial to understand how to design a ribbon : http://doc.babylonjs.com/tutorials/Ribbon_Tutorial
  29531. * The parameter `pathArray` is a required array of paths, what are each an array of successive Vector3. The pathArray parameter depicts the ribbon geometry.
  29532. * The parameter `closeArray` (boolean, default false) creates a seam between the first and the last paths of the path array.
  29533. * The parameter `closePath` (boolean, default false) creates a seam between the first and the last points of each path of the path array.
  29534. * 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.
  29535. * 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.
  29536. * 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
  29537. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  29538. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  29539. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  29540. */
  29541. Mesh.CreateRibbon = function (name, pathArray, closeArray, closePath, offset, scene, updatable, sideOrientation, instance) {
  29542. if (closeArray === void 0) { closeArray = false; }
  29543. if (updatable === void 0) { updatable = false; }
  29544. return BABYLON.MeshBuilder.CreateRibbon(name, {
  29545. pathArray: pathArray,
  29546. closeArray: closeArray,
  29547. closePath: closePath,
  29548. offset: offset,
  29549. updatable: updatable,
  29550. sideOrientation: sideOrientation,
  29551. instance: instance
  29552. }, scene);
  29553. };
  29554. /**
  29555. * Creates a plane polygonal mesh. By default, this is a disc.
  29556. * Please consider using the same method from the MeshBuilder class instead.
  29557. * The parameter `radius` sets the radius size (float) of the polygon (default 0.5).
  29558. * 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.
  29559. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  29560. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  29561. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  29562. */
  29563. Mesh.CreateDisc = function (name, radius, tessellation, scene, updatable, sideOrientation) {
  29564. if (scene === void 0) { scene = null; }
  29565. var options = {
  29566. radius: radius,
  29567. tessellation: tessellation,
  29568. sideOrientation: sideOrientation,
  29569. updatable: updatable
  29570. };
  29571. return BABYLON.MeshBuilder.CreateDisc(name, options, scene);
  29572. };
  29573. /**
  29574. * Creates a box mesh.
  29575. * Please consider using the same method from the MeshBuilder class instead.
  29576. * The parameter `size` sets the size (float) of each box side (default 1).
  29577. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  29578. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  29579. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  29580. */
  29581. Mesh.CreateBox = function (name, size, scene, updatable, sideOrientation) {
  29582. if (scene === void 0) { scene = null; }
  29583. var options = {
  29584. size: size,
  29585. sideOrientation: sideOrientation,
  29586. updatable: updatable
  29587. };
  29588. return BABYLON.MeshBuilder.CreateBox(name, options, scene);
  29589. };
  29590. /**
  29591. * Creates a sphere mesh.
  29592. * Please consider using the same method from the MeshBuilder class instead.
  29593. * The parameter `diameter` sets the diameter size (float) of the sphere (default 1).
  29594. * The parameter `segments` sets the sphere number of horizontal stripes (positive integer, default 32).
  29595. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  29596. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  29597. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  29598. */
  29599. Mesh.CreateSphere = function (name, segments, diameter, scene, updatable, sideOrientation) {
  29600. var options = {
  29601. segments: segments,
  29602. diameterX: diameter,
  29603. diameterY: diameter,
  29604. diameterZ: diameter,
  29605. sideOrientation: sideOrientation,
  29606. updatable: updatable
  29607. };
  29608. return BABYLON.MeshBuilder.CreateSphere(name, options, scene);
  29609. };
  29610. /**
  29611. * Creates a cylinder or a cone mesh.
  29612. * Please consider using the same method from the MeshBuilder class instead.
  29613. * The parameter `height` sets the height size (float) of the cylinder/cone (float, default 2).
  29614. * The parameter `diameter` sets the diameter of the top and bottom cap at once (float, default 1).
  29615. * 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.
  29616. * The parameter `tessellation` sets the number of cylinder sides (positive integer, default 24). Set it to 3 to get a prism for instance.
  29617. * The parameter `subdivisions` sets the number of rings along the cylinder height (positive integer, default 1).
  29618. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  29619. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  29620. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  29621. */
  29622. Mesh.CreateCylinder = function (name, height, diameterTop, diameterBottom, tessellation, subdivisions, scene, updatable, sideOrientation) {
  29623. if (scene === undefined || !(scene instanceof BABYLON.Scene)) {
  29624. if (scene !== undefined) {
  29625. sideOrientation = updatable || Mesh.DEFAULTSIDE;
  29626. updatable = scene;
  29627. }
  29628. scene = subdivisions;
  29629. subdivisions = 1;
  29630. }
  29631. var options = {
  29632. height: height,
  29633. diameterTop: diameterTop,
  29634. diameterBottom: diameterBottom,
  29635. tessellation: tessellation,
  29636. subdivisions: subdivisions,
  29637. sideOrientation: sideOrientation,
  29638. updatable: updatable
  29639. };
  29640. return BABYLON.MeshBuilder.CreateCylinder(name, options, scene);
  29641. };
  29642. // Torus (Code from SharpDX.org)
  29643. /**
  29644. * Creates a torus mesh.
  29645. * Please consider using the same method from the MeshBuilder class instead.
  29646. * The parameter `diameter` sets the diameter size (float) of the torus (default 1).
  29647. * The parameter `thickness` sets the diameter size of the tube of the torus (float, default 0.5).
  29648. * The parameter `tessellation` sets the number of torus sides (postive integer, default 16).
  29649. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  29650. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  29651. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  29652. */
  29653. Mesh.CreateTorus = function (name, diameter, thickness, tessellation, scene, updatable, sideOrientation) {
  29654. var options = {
  29655. diameter: diameter,
  29656. thickness: thickness,
  29657. tessellation: tessellation,
  29658. sideOrientation: sideOrientation,
  29659. updatable: updatable
  29660. };
  29661. return BABYLON.MeshBuilder.CreateTorus(name, options, scene);
  29662. };
  29663. /**
  29664. * Creates a torus knot mesh.
  29665. * Please consider using the same method from the MeshBuilder class instead.
  29666. * The parameter `radius` sets the global radius size (float) of the torus knot (default 2).
  29667. * The parameter `radialSegments` sets the number of sides on each tube segments (positive integer, default 32).
  29668. * The parameter `tubularSegments` sets the number of tubes to decompose the knot into (positive integer, default 32).
  29669. * The parameters `p` and `q` are the number of windings on each axis (positive integers, default 2 and 3).
  29670. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  29671. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  29672. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  29673. */
  29674. Mesh.CreateTorusKnot = function (name, radius, tube, radialSegments, tubularSegments, p, q, scene, updatable, sideOrientation) {
  29675. var options = {
  29676. radius: radius,
  29677. tube: tube,
  29678. radialSegments: radialSegments,
  29679. tubularSegments: tubularSegments,
  29680. p: p,
  29681. q: q,
  29682. sideOrientation: sideOrientation,
  29683. updatable: updatable
  29684. };
  29685. return BABYLON.MeshBuilder.CreateTorusKnot(name, options, scene);
  29686. };
  29687. /**
  29688. * Creates a line mesh.
  29689. * Please consider using the same method from the MeshBuilder class instead.
  29690. * 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.
  29691. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function.
  29692. * The parameter `points` is an array successive Vector3.
  29693. * 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
  29694. * When updating an instance, remember that only point positions can change, not the number of points.
  29695. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  29696. */
  29697. Mesh.CreateLines = function (name, points, scene, updatable, instance) {
  29698. if (scene === void 0) { scene = null; }
  29699. if (updatable === void 0) { updatable = false; }
  29700. if (instance === void 0) { instance = null; }
  29701. var options = {
  29702. points: points,
  29703. updatable: updatable,
  29704. instance: instance
  29705. };
  29706. return BABYLON.MeshBuilder.CreateLines(name, options, scene);
  29707. };
  29708. /**
  29709. * Creates a dashed line mesh.
  29710. * Please consider using the same method from the MeshBuilder class instead.
  29711. * 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.
  29712. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function.
  29713. * The parameter `points` is an array successive Vector3.
  29714. * The parameter `dashNb` is the intended total number of dashes (positive integer, default 200).
  29715. * The parameter `dashSize` is the size of the dashes relatively the dash number (positive float, default 3).
  29716. * The parameter `gapSize` is the size of the gap between two successive dashes relatively the dash number (positive float, default 1).
  29717. * 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
  29718. * When updating an instance, remember that only point positions can change, not the number of points.
  29719. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  29720. */
  29721. Mesh.CreateDashedLines = function (name, points, dashSize, gapSize, dashNb, scene, updatable, instance) {
  29722. if (scene === void 0) { scene = null; }
  29723. var options = {
  29724. points: points,
  29725. dashSize: dashSize,
  29726. gapSize: gapSize,
  29727. dashNb: dashNb,
  29728. updatable: updatable,
  29729. instance: instance
  29730. };
  29731. return BABYLON.MeshBuilder.CreateDashedLines(name, options, scene);
  29732. };
  29733. /**
  29734. * Creates a polygon mesh.
  29735. * Please consider using the same method from the MeshBuilder class instead.
  29736. * The polygon's shape will depend on the input parameters and is constructed parallel to a ground mesh.
  29737. * 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.
  29738. * You can set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  29739. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  29740. * Remember you can only change the shape positions, not their number when updating a polygon.
  29741. */
  29742. Mesh.CreatePolygon = function (name, shape, scene, holes, updatable, sideOrientation) {
  29743. var options = {
  29744. shape: shape,
  29745. holes: holes,
  29746. updatable: updatable,
  29747. sideOrientation: sideOrientation
  29748. };
  29749. return BABYLON.MeshBuilder.CreatePolygon(name, options, scene);
  29750. };
  29751. /**
  29752. * Creates an extruded polygon mesh, with depth in the Y direction.
  29753. * Please consider using the same method from the MeshBuilder class instead.
  29754. */
  29755. Mesh.ExtrudePolygon = function (name, shape, depth, scene, holes, updatable, sideOrientation) {
  29756. var options = {
  29757. shape: shape,
  29758. holes: holes,
  29759. depth: depth,
  29760. updatable: updatable,
  29761. sideOrientation: sideOrientation
  29762. };
  29763. return BABYLON.MeshBuilder.ExtrudePolygon(name, options, scene);
  29764. };
  29765. /**
  29766. * Creates an extruded shape mesh.
  29767. * 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.
  29768. * Please consider using the same method from the MeshBuilder class instead.
  29769. *
  29770. * Please read this full tutorial to understand how to design an extruded shape : http://doc.babylonjs.com/tutorials/Parametric_Shapes#extrusion
  29771. * 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
  29772. * extruded along the Z axis.
  29773. * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  29774. * 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.
  29775. * The parameter `scale` (float, default 1) is the value to scale the shape.
  29776. * 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
  29777. * 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
  29778. * Remember you can only change the shape or path point positions, not their number when updating an extruded shape.
  29779. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  29780. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  29781. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  29782. */
  29783. Mesh.ExtrudeShape = function (name, shape, path, scale, rotation, cap, scene, updatable, sideOrientation, instance) {
  29784. if (scene === void 0) { scene = null; }
  29785. var options = {
  29786. shape: shape,
  29787. path: path,
  29788. scale: scale,
  29789. rotation: rotation,
  29790. cap: (cap === 0) ? 0 : cap || Mesh.NO_CAP,
  29791. sideOrientation: sideOrientation,
  29792. instance: instance,
  29793. updatable: updatable
  29794. };
  29795. return BABYLON.MeshBuilder.ExtrudeShape(name, options, scene);
  29796. };
  29797. /**
  29798. * Creates an custom extruded shape mesh.
  29799. * 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.
  29800. * Please consider using the same method from the MeshBuilder class instead.
  29801. *
  29802. * Please read this full tutorial to understand how to design a custom extruded shape : http://doc.babylonjs.com/tutorials/Parametric_Shapes#extrusion
  29803. * 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
  29804. * extruded along the Z axis.
  29805. * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  29806. * 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
  29807. * and the distance of this point from the begining of the path :
  29808. * ```javascript
  29809. * var rotationFunction = function(i, distance) {
  29810. * // do things
  29811. * return rotationValue; }
  29812. * ```
  29813. * It must returns a float value that will be the rotation in radians applied to the shape on each path point.
  29814. * 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
  29815. * and the distance of this point from the begining of the path :
  29816. * ```javascript
  29817. * var scaleFunction = function(i, distance) {
  29818. * // do things
  29819. * return scaleValue;}
  29820. * ```
  29821. * It must returns a float value that will be the scale value applied to the shape on each path point.
  29822. * The parameter `ribbonClosePath` (boolean, default false) forces the extrusion underlying ribbon to close all the paths in its `pathArray`.
  29823. * The parameter `ribbonCloseArray` (boolean, default false) forces the extrusion underlying ribbon to close its `pathArray`.
  29824. * 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
  29825. * 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
  29826. * Remember you can only change the shape or path point positions, not their number when updating an extruded shape.
  29827. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  29828. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  29829. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  29830. */
  29831. Mesh.ExtrudeShapeCustom = function (name, shape, path, scaleFunction, rotationFunction, ribbonCloseArray, ribbonClosePath, cap, scene, updatable, sideOrientation, instance) {
  29832. var options = {
  29833. shape: shape,
  29834. path: path,
  29835. scaleFunction: scaleFunction,
  29836. rotationFunction: rotationFunction,
  29837. ribbonCloseArray: ribbonCloseArray,
  29838. ribbonClosePath: ribbonClosePath,
  29839. cap: (cap === 0) ? 0 : cap || Mesh.NO_CAP,
  29840. sideOrientation: sideOrientation,
  29841. instance: instance,
  29842. updatable: updatable
  29843. };
  29844. return BABYLON.MeshBuilder.ExtrudeShapeCustom(name, options, scene);
  29845. };
  29846. /**
  29847. * Creates lathe mesh.
  29848. * The lathe is a shape with a symetry axis : a 2D model shape is rotated around this axis to design the lathe.
  29849. * Please consider using the same method from the MeshBuilder class instead.
  29850. * 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
  29851. * rotated around the Y axis. It's usually a 2D shape, so the Vector3 z coordinates are often set to zero.
  29852. * The parameter `radius` (positive float, default 1) is the radius value of the lathe.
  29853. * The parameter `tessellation` (positive integer, default 64) is the side number of the lathe.
  29854. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  29855. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  29856. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  29857. */
  29858. Mesh.CreateLathe = function (name, shape, radius, tessellation, scene, updatable, sideOrientation) {
  29859. var options = {
  29860. shape: shape,
  29861. radius: radius,
  29862. tessellation: tessellation,
  29863. sideOrientation: sideOrientation,
  29864. updatable: updatable
  29865. };
  29866. return BABYLON.MeshBuilder.CreateLathe(name, options, scene);
  29867. };
  29868. /**
  29869. * Creates a plane mesh.
  29870. * Please consider using the same method from the MeshBuilder class instead.
  29871. * The parameter `size` sets the size (float) of both sides of the plane at once (default 1).
  29872. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  29873. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  29874. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  29875. */
  29876. Mesh.CreatePlane = function (name, size, scene, updatable, sideOrientation) {
  29877. var options = {
  29878. size: size,
  29879. width: size,
  29880. height: size,
  29881. sideOrientation: sideOrientation,
  29882. updatable: updatable
  29883. };
  29884. return BABYLON.MeshBuilder.CreatePlane(name, options, scene);
  29885. };
  29886. /**
  29887. * Creates a ground mesh.
  29888. * Please consider using the same method from the MeshBuilder class instead.
  29889. * The parameters `width` and `height` (floats, default 1) set the width and height sizes of the ground.
  29890. * The parameter `subdivisions` (positive integer) sets the number of subdivisions per side.
  29891. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  29892. */
  29893. Mesh.CreateGround = function (name, width, height, subdivisions, scene, updatable) {
  29894. var options = {
  29895. width: width,
  29896. height: height,
  29897. subdivisions: subdivisions,
  29898. updatable: updatable
  29899. };
  29900. return BABYLON.MeshBuilder.CreateGround(name, options, scene);
  29901. };
  29902. /**
  29903. * Creates a tiled ground mesh.
  29904. * Please consider using the same method from the MeshBuilder class instead.
  29905. * The parameters `xmin` and `xmax` (floats, default -1 and 1) set the ground minimum and maximum X coordinates.
  29906. * The parameters `zmin` and `zmax` (floats, default -1 and 1) set the ground minimum and maximum Z coordinates.
  29907. * The parameter `subdivisions` is a javascript object `{w: positive integer, h: positive integer}` (default `{w: 6, h: 6}`). `w` and `h` are the
  29908. * numbers of subdivisions on the ground width and height. Each subdivision is called a tile.
  29909. * The parameter `precision` is a javascript object `{w: positive integer, h: positive integer}` (default `{w: 2, h: 2}`). `w` and `h` are the
  29910. * numbers of subdivisions on the ground width and height of each tile.
  29911. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  29912. */
  29913. Mesh.CreateTiledGround = function (name, xmin, zmin, xmax, zmax, subdivisions, precision, scene, updatable) {
  29914. var options = {
  29915. xmin: xmin,
  29916. zmin: zmin,
  29917. xmax: xmax,
  29918. zmax: zmax,
  29919. subdivisions: subdivisions,
  29920. precision: precision,
  29921. updatable: updatable
  29922. };
  29923. return BABYLON.MeshBuilder.CreateTiledGround(name, options, scene);
  29924. };
  29925. /**
  29926. * Creates a ground mesh from a height map.
  29927. * tuto : http://doc.babylonjs.com/tutorials/14._Height_Map
  29928. * Please consider using the same method from the MeshBuilder class instead.
  29929. * The parameter `url` sets the URL of the height map image resource.
  29930. * The parameters `width` and `height` (positive floats, default 10) set the ground width and height sizes.
  29931. * The parameter `subdivisions` (positive integer, default 1) sets the number of subdivision per side.
  29932. * The parameter `minHeight` (float, default 0) is the minimum altitude on the ground.
  29933. * The parameter `maxHeight` (float, default 1) is the maximum altitude on the ground.
  29934. * 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).
  29935. * This function is passed the newly built mesh :
  29936. * ```javascript
  29937. * function(mesh) { // do things
  29938. * return; }
  29939. * ```
  29940. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  29941. */
  29942. Mesh.CreateGroundFromHeightMap = function (name, url, width, height, subdivisions, minHeight, maxHeight, scene, updatable, onReady) {
  29943. var options = {
  29944. width: width,
  29945. height: height,
  29946. subdivisions: subdivisions,
  29947. minHeight: minHeight,
  29948. maxHeight: maxHeight,
  29949. updatable: updatable,
  29950. onReady: onReady
  29951. };
  29952. return BABYLON.MeshBuilder.CreateGroundFromHeightMap(name, url, options, scene);
  29953. };
  29954. /**
  29955. * Creates a tube mesh.
  29956. * 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.
  29957. * Please consider using the same method from the MeshBuilder class instead.
  29958. * The parameter `path` is a required array of successive Vector3. It is the curve used as the axis of the tube.
  29959. * The parameter `radius` (positive float, default 1) sets the tube radius size.
  29960. * The parameter `tessellation` (positive float, default 64) is the number of sides on the tubular surface.
  29961. * The parameter `radiusFunction` (javascript function, default null) is a vanilla javascript function. If it is not null, it overwrittes the parameter `radius`.
  29962. * 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.
  29963. * It must return a radius value (positive float) :
  29964. * ```javascript
  29965. * var radiusFunction = function(i, distance) {
  29966. * // do things
  29967. * return radius; }
  29968. * ```
  29969. * 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
  29970. * 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
  29971. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  29972. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  29973. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  29974. */
  29975. Mesh.CreateTube = function (name, path, radius, tessellation, radiusFunction, cap, scene, updatable, sideOrientation, instance) {
  29976. var options = {
  29977. path: path,
  29978. radius: radius,
  29979. tessellation: tessellation,
  29980. radiusFunction: radiusFunction,
  29981. arc: 1,
  29982. cap: cap,
  29983. updatable: updatable,
  29984. sideOrientation: sideOrientation,
  29985. instance: instance
  29986. };
  29987. return BABYLON.MeshBuilder.CreateTube(name, options, scene);
  29988. };
  29989. /**
  29990. * Creates a polyhedron mesh.
  29991. * Please consider using the same method from the MeshBuilder class instead.
  29992. * 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
  29993. * to choose the wanted type.
  29994. * The parameter `size` (positive float, default 1) sets the polygon size.
  29995. * You can overwrite the `size` on each dimension bu using the parameters `sizeX`, `sizeY` or `sizeZ` (positive floats, default to `size` value).
  29996. * 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`.
  29997. * 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
  29998. * 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)`).
  29999. * 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
  30000. * 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.
  30001. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  30002. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  30003. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  30004. */
  30005. Mesh.CreatePolyhedron = function (name, options, scene) {
  30006. return BABYLON.MeshBuilder.CreatePolyhedron(name, options, scene);
  30007. };
  30008. /**
  30009. * Creates a sphere based upon an icosahedron with 20 triangular faces which can be subdivided.
  30010. * Please consider using the same method from the MeshBuilder class instead.
  30011. * The parameter `radius` sets the radius size (float) of the icosphere (default 1).
  30012. * 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`).
  30013. * The parameter `subdivisions` sets the number of subdivisions (postive integer, default 4). The more subdivisions, the more faces on the icosphere whatever its size.
  30014. * 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.
  30015. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  30016. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  30017. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  30018. */
  30019. Mesh.CreateIcoSphere = function (name, options, scene) {
  30020. return BABYLON.MeshBuilder.CreateIcoSphere(name, options, scene);
  30021. };
  30022. /**
  30023. * Creates a decal mesh.
  30024. * Please consider using the same method from the MeshBuilder class instead.
  30025. * 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.
  30026. * The parameter `position` (Vector3, default `(0, 0, 0)`) sets the position of the decal in World coordinates.
  30027. * The parameter `normal` (Vector3, default Vector3.Up) sets the normal of the mesh where the decal is applied onto in World coordinates.
  30028. * The parameter `size` (Vector3, default `(1, 1, 1)`) sets the decal scaling.
  30029. * The parameter `angle` (float in radian, default 0) sets the angle to rotate the decal.
  30030. */
  30031. Mesh.CreateDecal = function (name, sourceMesh, position, normal, size, angle) {
  30032. var options = {
  30033. position: position,
  30034. normal: normal,
  30035. size: size,
  30036. angle: angle
  30037. };
  30038. return BABYLON.MeshBuilder.CreateDecal(name, sourceMesh, options);
  30039. };
  30040. // Skeletons
  30041. /**
  30042. * @returns original positions used for CPU skinning. Useful for integrating Morphing with skeletons in same mesh.
  30043. */
  30044. Mesh.prototype.setPositionsForCPUSkinning = function () {
  30045. if (!this._sourcePositions) {
  30046. var source = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  30047. if (!source) {
  30048. return this._sourcePositions;
  30049. }
  30050. this._sourcePositions = new Float32Array(source);
  30051. if (!this.isVertexBufferUpdatable(BABYLON.VertexBuffer.PositionKind)) {
  30052. this.setVerticesData(BABYLON.VertexBuffer.PositionKind, source, true);
  30053. }
  30054. }
  30055. return this._sourcePositions;
  30056. };
  30057. /**
  30058. * @returns original normals used for CPU skinning. Useful for integrating Morphing with skeletons in same mesh.
  30059. */
  30060. Mesh.prototype.setNormalsForCPUSkinning = function () {
  30061. if (!this._sourceNormals) {
  30062. var source = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  30063. if (!source) {
  30064. return this._sourceNormals;
  30065. }
  30066. this._sourceNormals = new Float32Array(source);
  30067. if (!this.isVertexBufferUpdatable(BABYLON.VertexBuffer.NormalKind)) {
  30068. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, source, true);
  30069. }
  30070. }
  30071. return this._sourceNormals;
  30072. };
  30073. /**
  30074. * Updates the vertex buffer by applying transformation from the bones.
  30075. * Returns the Mesh.
  30076. *
  30077. * @param {skeleton} skeleton to apply
  30078. */
  30079. Mesh.prototype.applySkeleton = function (skeleton) {
  30080. if (!this.geometry) {
  30081. return this;
  30082. }
  30083. if (this.geometry._softwareSkinningRenderId == this.getScene().getRenderId()) {
  30084. return this;
  30085. }
  30086. this.geometry._softwareSkinningRenderId = this.getScene().getRenderId();
  30087. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  30088. return this;
  30089. }
  30090. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  30091. return this;
  30092. }
  30093. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  30094. return this;
  30095. }
  30096. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  30097. return this;
  30098. }
  30099. if (!this._sourcePositions) {
  30100. var submeshes = this.subMeshes.slice();
  30101. this.setPositionsForCPUSkinning();
  30102. this.subMeshes = submeshes;
  30103. }
  30104. if (!this._sourceNormals) {
  30105. this.setNormalsForCPUSkinning();
  30106. }
  30107. // positionsData checks for not being Float32Array will only pass at most once
  30108. var positionsData = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  30109. if (!positionsData) {
  30110. return this;
  30111. }
  30112. if (!(positionsData instanceof Float32Array)) {
  30113. positionsData = new Float32Array(positionsData);
  30114. }
  30115. // normalsData checks for not being Float32Array will only pass at most once
  30116. var normalsData = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  30117. if (!normalsData) {
  30118. return this;
  30119. }
  30120. if (!(normalsData instanceof Float32Array)) {
  30121. normalsData = new Float32Array(normalsData);
  30122. }
  30123. var matricesIndicesData = this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind);
  30124. var matricesWeightsData = this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind);
  30125. if (!matricesWeightsData || !matricesIndicesData) {
  30126. return this;
  30127. }
  30128. var needExtras = this.numBoneInfluencers > 4;
  30129. var matricesIndicesExtraData = needExtras ? this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind) : null;
  30130. var matricesWeightsExtraData = needExtras ? this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind) : null;
  30131. var skeletonMatrices = skeleton.getTransformMatrices(this);
  30132. var tempVector3 = BABYLON.Vector3.Zero();
  30133. var finalMatrix = new BABYLON.Matrix();
  30134. var tempMatrix = new BABYLON.Matrix();
  30135. var matWeightIdx = 0;
  30136. var inf;
  30137. for (var index = 0; index < positionsData.length; index += 3, matWeightIdx += 4) {
  30138. var weight;
  30139. for (inf = 0; inf < 4; inf++) {
  30140. weight = matricesWeightsData[matWeightIdx + inf];
  30141. if (weight > 0) {
  30142. BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, Math.floor(matricesIndicesData[matWeightIdx + inf] * 16), weight, tempMatrix);
  30143. finalMatrix.addToSelf(tempMatrix);
  30144. }
  30145. else
  30146. break;
  30147. }
  30148. if (needExtras) {
  30149. for (inf = 0; inf < 4; inf++) {
  30150. weight = matricesWeightsExtraData[matWeightIdx + inf];
  30151. if (weight > 0) {
  30152. BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, Math.floor(matricesIndicesExtraData[matWeightIdx + inf] * 16), weight, tempMatrix);
  30153. finalMatrix.addToSelf(tempMatrix);
  30154. }
  30155. else
  30156. break;
  30157. }
  30158. }
  30159. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(this._sourcePositions[index], this._sourcePositions[index + 1], this._sourcePositions[index + 2], finalMatrix, tempVector3);
  30160. tempVector3.toArray(positionsData, index);
  30161. BABYLON.Vector3.TransformNormalFromFloatsToRef(this._sourceNormals[index], this._sourceNormals[index + 1], this._sourceNormals[index + 2], finalMatrix, tempVector3);
  30162. tempVector3.toArray(normalsData, index);
  30163. finalMatrix.reset();
  30164. }
  30165. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positionsData);
  30166. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normalsData);
  30167. return this;
  30168. };
  30169. // Tools
  30170. /**
  30171. * Returns an object `{min:` Vector3`, max:` Vector3`}`
  30172. * This min and max Vector3 are the minimum and maximum vectors of each mesh bounding box from the passed array, in the World system
  30173. */
  30174. Mesh.MinMax = function (meshes) {
  30175. var minVector = null;
  30176. var maxVector = null;
  30177. meshes.forEach(function (mesh, index, array) {
  30178. var boundingInfo = mesh.getBoundingInfo();
  30179. var boundingBox = boundingInfo.boundingBox;
  30180. if (!minVector || !maxVector) {
  30181. minVector = boundingBox.minimumWorld;
  30182. maxVector = boundingBox.maximumWorld;
  30183. }
  30184. else {
  30185. minVector.minimizeInPlace(boundingBox.minimumWorld);
  30186. maxVector.maximizeInPlace(boundingBox.maximumWorld);
  30187. }
  30188. });
  30189. if (!minVector || !maxVector) {
  30190. return {
  30191. min: BABYLON.Vector3.Zero(),
  30192. max: BABYLON.Vector3.Zero()
  30193. };
  30194. }
  30195. return {
  30196. min: minVector,
  30197. max: maxVector
  30198. };
  30199. };
  30200. /**
  30201. * Returns a Vector3, the center of the `{min:` Vector3`, max:` Vector3`}` or the center of MinMax vector3 computed from a mesh array.
  30202. */
  30203. Mesh.Center = function (meshesOrMinMaxVector) {
  30204. var minMaxVector = (meshesOrMinMaxVector instanceof Array) ? Mesh.MinMax(meshesOrMinMaxVector) : meshesOrMinMaxVector;
  30205. return BABYLON.Vector3.Center(minMaxVector.min, minMaxVector.max);
  30206. };
  30207. /**
  30208. * Merge the array of meshes into a single mesh for performance reasons.
  30209. * @param {Array<Mesh>} meshes - The vertices source. They should all be of the same material. Entries can empty
  30210. * @param {boolean} disposeSource - When true (default), dispose of the vertices from the source meshes
  30211. * @param {boolean} allow32BitsIndices - When the sum of the vertices > 64k, this must be set to true.
  30212. * @param {Mesh} meshSubclass - When set, vertices inserted into this Mesh. Meshes can then be merged into a Mesh sub-class.
  30213. * @param {boolean} subdivideWithSubMeshes - When true (false default), subdivide mesh to his subMesh array with meshes source.
  30214. */
  30215. Mesh.MergeMeshes = function (meshes, disposeSource, allow32BitsIndices, meshSubclass, subdivideWithSubMeshes) {
  30216. if (disposeSource === void 0) { disposeSource = true; }
  30217. var index;
  30218. if (!allow32BitsIndices) {
  30219. var totalVertices = 0;
  30220. // Counting vertices
  30221. for (index = 0; index < meshes.length; index++) {
  30222. if (meshes[index]) {
  30223. totalVertices += meshes[index].getTotalVertices();
  30224. if (totalVertices > 65536) {
  30225. BABYLON.Tools.Warn("Cannot merge meshes because resulting mesh will have more than 65536 vertices. Please use allow32BitsIndices = true to use 32 bits indices");
  30226. return null;
  30227. }
  30228. }
  30229. }
  30230. }
  30231. // Merge
  30232. var vertexData = null;
  30233. var otherVertexData;
  30234. var indiceArray = new Array();
  30235. var source = null;
  30236. for (index = 0; index < meshes.length; index++) {
  30237. if (meshes[index]) {
  30238. meshes[index].computeWorldMatrix(true);
  30239. otherVertexData = BABYLON.VertexData.ExtractFromMesh(meshes[index], true);
  30240. otherVertexData.transform(meshes[index].getWorldMatrix());
  30241. if (vertexData) {
  30242. vertexData.merge(otherVertexData);
  30243. }
  30244. else {
  30245. vertexData = otherVertexData;
  30246. source = meshes[index];
  30247. }
  30248. if (subdivideWithSubMeshes) {
  30249. indiceArray.push(meshes[index].getTotalIndices());
  30250. }
  30251. }
  30252. }
  30253. source = source;
  30254. if (!meshSubclass) {
  30255. meshSubclass = new Mesh(source.name + "_merged", source.getScene());
  30256. }
  30257. vertexData.applyToMesh(meshSubclass);
  30258. // Setting properties
  30259. meshSubclass.material = source.material;
  30260. meshSubclass.checkCollisions = source.checkCollisions;
  30261. // Cleaning
  30262. if (disposeSource) {
  30263. for (index = 0; index < meshes.length; index++) {
  30264. if (meshes[index]) {
  30265. meshes[index].dispose();
  30266. }
  30267. }
  30268. }
  30269. // Subdivide
  30270. if (subdivideWithSubMeshes) {
  30271. //-- Suppresions du submesh global
  30272. meshSubclass.releaseSubMeshes();
  30273. index = 0;
  30274. var offset = 0;
  30275. //-- aplique la subdivision en fonction du tableau d'indices
  30276. while (index < indiceArray.length) {
  30277. BABYLON.SubMesh.CreateFromIndices(0, offset, indiceArray[index], meshSubclass);
  30278. offset += indiceArray[index];
  30279. index++;
  30280. }
  30281. }
  30282. return meshSubclass;
  30283. };
  30284. // Consts
  30285. Mesh._FRONTSIDE = 0;
  30286. Mesh._BACKSIDE = 1;
  30287. Mesh._DOUBLESIDE = 2;
  30288. Mesh._DEFAULTSIDE = 0;
  30289. Mesh._NO_CAP = 0;
  30290. Mesh._CAP_START = 1;
  30291. Mesh._CAP_END = 2;
  30292. Mesh._CAP_ALL = 3;
  30293. return Mesh;
  30294. }(BABYLON.AbstractMesh));
  30295. BABYLON.Mesh = Mesh;
  30296. })(BABYLON || (BABYLON = {}));
  30297. //# sourceMappingURL=babylon.mesh.js.map
  30298. var BABYLON;
  30299. (function (BABYLON) {
  30300. var BaseSubMesh = /** @class */ (function () {
  30301. function BaseSubMesh() {
  30302. }
  30303. Object.defineProperty(BaseSubMesh.prototype, "effect", {
  30304. get: function () {
  30305. return this._materialEffect;
  30306. },
  30307. enumerable: true,
  30308. configurable: true
  30309. });
  30310. BaseSubMesh.prototype.setEffect = function (effect, defines) {
  30311. if (defines === void 0) { defines = null; }
  30312. if (this._materialEffect === effect) {
  30313. if (!effect) {
  30314. this._materialDefines = null;
  30315. }
  30316. return;
  30317. }
  30318. this._materialDefines = defines;
  30319. this._materialEffect = effect;
  30320. };
  30321. return BaseSubMesh;
  30322. }());
  30323. BABYLON.BaseSubMesh = BaseSubMesh;
  30324. var SubMesh = /** @class */ (function (_super) {
  30325. __extends(SubMesh, _super);
  30326. function SubMesh(materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh, renderingMesh, createBoundingBox) {
  30327. if (createBoundingBox === void 0) { createBoundingBox = true; }
  30328. var _this = _super.call(this) || this;
  30329. _this.materialIndex = materialIndex;
  30330. _this.verticesStart = verticesStart;
  30331. _this.verticesCount = verticesCount;
  30332. _this.indexStart = indexStart;
  30333. _this.indexCount = indexCount;
  30334. _this._renderId = 0;
  30335. _this._mesh = mesh;
  30336. _this._renderingMesh = renderingMesh || mesh;
  30337. mesh.subMeshes.push(_this);
  30338. _this._trianglePlanes = [];
  30339. _this._id = mesh.subMeshes.length - 1;
  30340. if (createBoundingBox) {
  30341. _this.refreshBoundingInfo();
  30342. mesh.computeWorldMatrix(true);
  30343. }
  30344. return _this;
  30345. }
  30346. SubMesh.AddToMesh = function (materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh, renderingMesh, createBoundingBox) {
  30347. if (createBoundingBox === void 0) { createBoundingBox = true; }
  30348. return new SubMesh(materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh, renderingMesh, createBoundingBox);
  30349. };
  30350. Object.defineProperty(SubMesh.prototype, "IsGlobal", {
  30351. get: function () {
  30352. return (this.verticesStart === 0 && this.verticesCount == this._mesh.getTotalVertices());
  30353. },
  30354. enumerable: true,
  30355. configurable: true
  30356. });
  30357. /**
  30358. * Returns the submesh BoudingInfo object.
  30359. */
  30360. SubMesh.prototype.getBoundingInfo = function () {
  30361. if (this.IsGlobal) {
  30362. return this._mesh.getBoundingInfo();
  30363. }
  30364. return this._boundingInfo;
  30365. };
  30366. /**
  30367. * Sets the submesh BoundingInfo.
  30368. * Return the SubMesh.
  30369. */
  30370. SubMesh.prototype.setBoundingInfo = function (boundingInfo) {
  30371. this._boundingInfo = boundingInfo;
  30372. return this;
  30373. };
  30374. /**
  30375. * Returns the mesh of the current submesh.
  30376. */
  30377. SubMesh.prototype.getMesh = function () {
  30378. return this._mesh;
  30379. };
  30380. /**
  30381. * Returns the rendering mesh of the submesh.
  30382. */
  30383. SubMesh.prototype.getRenderingMesh = function () {
  30384. return this._renderingMesh;
  30385. };
  30386. /**
  30387. * Returns the submesh material.
  30388. */
  30389. SubMesh.prototype.getMaterial = function () {
  30390. var rootMaterial = this._renderingMesh.material;
  30391. if (rootMaterial === null || rootMaterial === undefined) {
  30392. return this._mesh.getScene().defaultMaterial;
  30393. }
  30394. else if (rootMaterial.getSubMaterial) {
  30395. var multiMaterial = rootMaterial;
  30396. var effectiveMaterial = multiMaterial.getSubMaterial(this.materialIndex);
  30397. if (this._currentMaterial !== effectiveMaterial) {
  30398. this._currentMaterial = effectiveMaterial;
  30399. this._materialDefines = null;
  30400. }
  30401. return effectiveMaterial;
  30402. }
  30403. return rootMaterial;
  30404. };
  30405. // Methods
  30406. /**
  30407. * Sets a new updated BoundingInfo object to the submesh.
  30408. * Returns the SubMesh.
  30409. */
  30410. SubMesh.prototype.refreshBoundingInfo = function () {
  30411. this._lastColliderWorldVertices = null;
  30412. if (this.IsGlobal || !this._renderingMesh || !this._renderingMesh.geometry) {
  30413. return this;
  30414. }
  30415. var data = this._renderingMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  30416. if (!data) {
  30417. this._boundingInfo = this._mesh.getBoundingInfo();
  30418. return this;
  30419. }
  30420. var indices = this._renderingMesh.getIndices();
  30421. var extend;
  30422. //is this the only submesh?
  30423. if (this.indexStart === 0 && this.indexCount === indices.length) {
  30424. var boundingInfo = this._renderingMesh.getBoundingInfo();
  30425. //the rendering mesh's bounding info can be used, it is the standard submesh for all indices.
  30426. extend = { minimum: boundingInfo.minimum.clone(), maximum: boundingInfo.maximum.clone() };
  30427. }
  30428. else {
  30429. extend = BABYLON.Tools.ExtractMinAndMaxIndexed(data, indices, this.indexStart, this.indexCount, this._renderingMesh.geometry.boundingBias);
  30430. }
  30431. this._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  30432. return this;
  30433. };
  30434. SubMesh.prototype._checkCollision = function (collider) {
  30435. var boundingInfo = this._renderingMesh.getBoundingInfo();
  30436. return boundingInfo._checkCollision(collider);
  30437. };
  30438. /**
  30439. * Updates the submesh BoundingInfo.
  30440. * Returns the Submesh.
  30441. */
  30442. SubMesh.prototype.updateBoundingInfo = function (world) {
  30443. var boundingInfo = this.getBoundingInfo();
  30444. if (!boundingInfo) {
  30445. this.refreshBoundingInfo();
  30446. boundingInfo = this.getBoundingInfo();
  30447. }
  30448. boundingInfo.update(world);
  30449. return this;
  30450. };
  30451. /**
  30452. * True is the submesh bounding box intersects the frustum defined by the passed array of planes.
  30453. * Boolean returned.
  30454. */
  30455. SubMesh.prototype.isInFrustum = function (frustumPlanes) {
  30456. var boundingInfo = this.getBoundingInfo();
  30457. if (!boundingInfo) {
  30458. return false;
  30459. }
  30460. return boundingInfo.isInFrustum(frustumPlanes);
  30461. };
  30462. /**
  30463. * True is the submesh bounding box is completely inside the frustum defined by the passed array of planes.
  30464. * Boolean returned.
  30465. */
  30466. SubMesh.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  30467. var boundingInfo = this.getBoundingInfo();
  30468. if (!boundingInfo) {
  30469. return false;
  30470. }
  30471. return boundingInfo.isCompletelyInFrustum(frustumPlanes);
  30472. };
  30473. /**
  30474. * Renders the submesh.
  30475. * Returns it.
  30476. */
  30477. SubMesh.prototype.render = function (enableAlphaMode) {
  30478. this._renderingMesh.render(this, enableAlphaMode);
  30479. return this;
  30480. };
  30481. /**
  30482. * Returns a new Index Buffer.
  30483. * Type returned : WebGLBuffer.
  30484. */
  30485. SubMesh.prototype.getLinesIndexBuffer = function (indices, engine) {
  30486. if (!this._linesIndexBuffer) {
  30487. var linesIndices = [];
  30488. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 3) {
  30489. linesIndices.push(indices[index], indices[index + 1], indices[index + 1], indices[index + 2], indices[index + 2], indices[index]);
  30490. }
  30491. this._linesIndexBuffer = engine.createIndexBuffer(linesIndices);
  30492. this.linesIndexCount = linesIndices.length;
  30493. }
  30494. return this._linesIndexBuffer;
  30495. };
  30496. /**
  30497. * True is the passed Ray intersects the submesh bounding box.
  30498. * Boolean returned.
  30499. */
  30500. SubMesh.prototype.canIntersects = function (ray) {
  30501. var boundingInfo = this.getBoundingInfo();
  30502. if (!boundingInfo) {
  30503. return false;
  30504. }
  30505. return ray.intersectsBox(boundingInfo.boundingBox);
  30506. };
  30507. /**
  30508. * Returns an object IntersectionInfo.
  30509. */
  30510. SubMesh.prototype.intersects = function (ray, positions, indices, fastCheck) {
  30511. var intersectInfo = null;
  30512. // LineMesh first as it's also a Mesh...
  30513. if (BABYLON.LinesMesh && this._mesh instanceof BABYLON.LinesMesh) {
  30514. var lineMesh = this._mesh;
  30515. // Line test
  30516. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 2) {
  30517. var p0 = positions[indices[index]];
  30518. var p1 = positions[indices[index + 1]];
  30519. var length = ray.intersectionSegment(p0, p1, lineMesh.intersectionThreshold);
  30520. if (length < 0) {
  30521. continue;
  30522. }
  30523. if (fastCheck || !intersectInfo || length < intersectInfo.distance) {
  30524. intersectInfo = new BABYLON.IntersectionInfo(null, null, length);
  30525. if (fastCheck) {
  30526. break;
  30527. }
  30528. }
  30529. }
  30530. }
  30531. else {
  30532. // Triangles test
  30533. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 3) {
  30534. var p0 = positions[indices[index]];
  30535. var p1 = positions[indices[index + 1]];
  30536. var p2 = positions[indices[index + 2]];
  30537. var currentIntersectInfo = ray.intersectsTriangle(p0, p1, p2);
  30538. if (currentIntersectInfo) {
  30539. if (currentIntersectInfo.distance < 0) {
  30540. continue;
  30541. }
  30542. if (fastCheck || !intersectInfo || currentIntersectInfo.distance < intersectInfo.distance) {
  30543. intersectInfo = currentIntersectInfo;
  30544. intersectInfo.faceId = index / 3;
  30545. if (fastCheck) {
  30546. break;
  30547. }
  30548. }
  30549. }
  30550. }
  30551. }
  30552. return intersectInfo;
  30553. };
  30554. SubMesh.prototype._rebuild = function () {
  30555. if (this._linesIndexBuffer) {
  30556. this._linesIndexBuffer = null;
  30557. }
  30558. };
  30559. // Clone
  30560. /**
  30561. * Creates a new Submesh from the passed Mesh.
  30562. */
  30563. SubMesh.prototype.clone = function (newMesh, newRenderingMesh) {
  30564. var result = new SubMesh(this.materialIndex, this.verticesStart, this.verticesCount, this.indexStart, this.indexCount, newMesh, newRenderingMesh, false);
  30565. if (!this.IsGlobal) {
  30566. var boundingInfo = this.getBoundingInfo();
  30567. if (!boundingInfo) {
  30568. return result;
  30569. }
  30570. result._boundingInfo = new BABYLON.BoundingInfo(boundingInfo.minimum, boundingInfo.maximum);
  30571. }
  30572. return result;
  30573. };
  30574. // Dispose
  30575. /**
  30576. * Disposes the Submesh.
  30577. * Returns nothing.
  30578. */
  30579. SubMesh.prototype.dispose = function () {
  30580. if (this._linesIndexBuffer) {
  30581. this._mesh.getScene().getEngine()._releaseBuffer(this._linesIndexBuffer);
  30582. this._linesIndexBuffer = null;
  30583. }
  30584. // Remove from mesh
  30585. var index = this._mesh.subMeshes.indexOf(this);
  30586. this._mesh.subMeshes.splice(index, 1);
  30587. };
  30588. // Statics
  30589. /**
  30590. * Creates a new Submesh from the passed parameters :
  30591. * - materialIndex (integer) : the index of the main mesh material.
  30592. * - startIndex (integer) : the index where to start the copy in the mesh indices array.
  30593. * - indexCount (integer) : the number of indices to copy then from the startIndex.
  30594. * - mesh (Mesh) : the main mesh to create the submesh from.
  30595. * - renderingMesh (optional Mesh) : rendering mesh.
  30596. */
  30597. SubMesh.CreateFromIndices = function (materialIndex, startIndex, indexCount, mesh, renderingMesh) {
  30598. var minVertexIndex = Number.MAX_VALUE;
  30599. var maxVertexIndex = -Number.MAX_VALUE;
  30600. renderingMesh = (renderingMesh || mesh);
  30601. var indices = renderingMesh.getIndices();
  30602. for (var index = startIndex; index < startIndex + indexCount; index++) {
  30603. var vertexIndex = indices[index];
  30604. if (vertexIndex < minVertexIndex)
  30605. minVertexIndex = vertexIndex;
  30606. if (vertexIndex > maxVertexIndex)
  30607. maxVertexIndex = vertexIndex;
  30608. }
  30609. return new SubMesh(materialIndex, minVertexIndex, maxVertexIndex - minVertexIndex + 1, startIndex, indexCount, mesh, renderingMesh);
  30610. };
  30611. return SubMesh;
  30612. }(BaseSubMesh));
  30613. BABYLON.SubMesh = SubMesh;
  30614. })(BABYLON || (BABYLON = {}));
  30615. //# sourceMappingURL=babylon.subMesh.js.map
  30616. var __assign = (this && this.__assign) || Object.assign || function(t) {
  30617. for (var s, i = 1, n = arguments.length; i < n; i++) {
  30618. s = arguments[i];
  30619. for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
  30620. t[p] = s[p];
  30621. }
  30622. return t;
  30623. };
  30624. var BABYLON;
  30625. (function (BABYLON) {
  30626. /**
  30627. * Manages the defines for the Material.
  30628. */
  30629. var MaterialDefines = /** @class */ (function () {
  30630. function MaterialDefines() {
  30631. this._isDirty = true;
  30632. this._areLightsDirty = true;
  30633. this._areAttributesDirty = true;
  30634. this._areTexturesDirty = true;
  30635. this._areFresnelDirty = true;
  30636. this._areMiscDirty = true;
  30637. this._areImageProcessingDirty = true;
  30638. this._normals = false;
  30639. this._uvs = false;
  30640. this._needNormals = false;
  30641. this._needUVs = false;
  30642. }
  30643. Object.defineProperty(MaterialDefines.prototype, "isDirty", {
  30644. /**
  30645. * Specifies if the material needs to be re-calculated.
  30646. */
  30647. get: function () {
  30648. return this._isDirty;
  30649. },
  30650. enumerable: true,
  30651. configurable: true
  30652. });
  30653. /**
  30654. * Marks the material to indicate that it has been re-calculated.
  30655. */
  30656. MaterialDefines.prototype.markAsProcessed = function () {
  30657. this._isDirty = false;
  30658. this._areAttributesDirty = false;
  30659. this._areTexturesDirty = false;
  30660. this._areFresnelDirty = false;
  30661. this._areLightsDirty = false;
  30662. this._areMiscDirty = false;
  30663. this._areImageProcessingDirty = false;
  30664. };
  30665. /**
  30666. * Marks the material to indicate that it needs to be re-calculated.
  30667. */
  30668. MaterialDefines.prototype.markAsUnprocessed = function () {
  30669. this._isDirty = true;
  30670. };
  30671. /**
  30672. * Marks the material to indicate all of its defines need to be re-calculated.
  30673. */
  30674. MaterialDefines.prototype.markAllAsDirty = function () {
  30675. this._areTexturesDirty = true;
  30676. this._areAttributesDirty = true;
  30677. this._areLightsDirty = true;
  30678. this._areFresnelDirty = true;
  30679. this._areMiscDirty = true;
  30680. this._areImageProcessingDirty = true;
  30681. this._isDirty = true;
  30682. };
  30683. /**
  30684. * Marks the material to indicate that image processing needs to be re-calculated.
  30685. */
  30686. MaterialDefines.prototype.markAsImageProcessingDirty = function () {
  30687. this._areImageProcessingDirty = true;
  30688. this._isDirty = true;
  30689. };
  30690. /**
  30691. * Marks the material to indicate the lights need to be re-calculated.
  30692. */
  30693. MaterialDefines.prototype.markAsLightDirty = function () {
  30694. this._areLightsDirty = true;
  30695. this._isDirty = true;
  30696. };
  30697. /**
  30698. * Marks the attribute state as changed.
  30699. */
  30700. MaterialDefines.prototype.markAsAttributesDirty = function () {
  30701. this._areAttributesDirty = true;
  30702. this._isDirty = true;
  30703. };
  30704. /**
  30705. * Marks the texture state as changed.
  30706. */
  30707. MaterialDefines.prototype.markAsTexturesDirty = function () {
  30708. this._areTexturesDirty = true;
  30709. this._isDirty = true;
  30710. };
  30711. /**
  30712. * Marks the fresnel state as changed.
  30713. */
  30714. MaterialDefines.prototype.markAsFresnelDirty = function () {
  30715. this._areFresnelDirty = true;
  30716. this._isDirty = true;
  30717. };
  30718. /**
  30719. * Marks the misc state as changed.
  30720. */
  30721. MaterialDefines.prototype.markAsMiscDirty = function () {
  30722. this._areMiscDirty = true;
  30723. this._isDirty = true;
  30724. };
  30725. /**
  30726. * Rebuilds the material defines.
  30727. */
  30728. MaterialDefines.prototype.rebuild = function () {
  30729. if (this._keys) {
  30730. delete this._keys;
  30731. }
  30732. this._keys = [];
  30733. for (var _i = 0, _a = Object.keys(this); _i < _a.length; _i++) {
  30734. var key = _a[_i];
  30735. if (key[0] === "_") {
  30736. continue;
  30737. }
  30738. this._keys.push(key);
  30739. }
  30740. };
  30741. /**
  30742. * Specifies if two material defines are equal.
  30743. * @param other - A material define instance to compare to.
  30744. * @returns - Boolean indicating if the material defines are equal (true) or not (false).
  30745. */
  30746. MaterialDefines.prototype.isEqual = function (other) {
  30747. if (this._keys.length !== other._keys.length) {
  30748. return false;
  30749. }
  30750. for (var index = 0; index < this._keys.length; index++) {
  30751. var prop = this._keys[index];
  30752. if (this[prop] !== other[prop]) {
  30753. return false;
  30754. }
  30755. }
  30756. return true;
  30757. };
  30758. /**
  30759. * Clones this instance's defines to another instance.
  30760. * @param other - material defines to clone values to.
  30761. */
  30762. MaterialDefines.prototype.cloneTo = function (other) {
  30763. if (this._keys.length !== other._keys.length) {
  30764. other._keys = this._keys.slice(0);
  30765. }
  30766. for (var index = 0; index < this._keys.length; index++) {
  30767. var prop = this._keys[index];
  30768. other[prop] = this[prop];
  30769. }
  30770. };
  30771. /**
  30772. * Resets the material define values.
  30773. */
  30774. MaterialDefines.prototype.reset = function () {
  30775. for (var index = 0; index < this._keys.length; index++) {
  30776. var prop = this._keys[index];
  30777. if (typeof (this[prop]) === "number") {
  30778. this[prop] = 0;
  30779. }
  30780. else {
  30781. this[prop] = false;
  30782. }
  30783. }
  30784. };
  30785. /**
  30786. * Converts the material define values to a string.
  30787. * @returns - String of material define information.
  30788. */
  30789. MaterialDefines.prototype.toString = function () {
  30790. var result = "";
  30791. for (var index = 0; index < this._keys.length; index++) {
  30792. var prop = this._keys[index];
  30793. var value = this[prop];
  30794. if (typeof (value) === "number") {
  30795. result += "#define " + prop + " " + this[prop] + "\n";
  30796. }
  30797. else if (value) {
  30798. result += "#define " + prop + "\n";
  30799. }
  30800. }
  30801. return result;
  30802. };
  30803. return MaterialDefines;
  30804. }());
  30805. BABYLON.MaterialDefines = MaterialDefines;
  30806. /**
  30807. * This offers the main features of a material in BJS.
  30808. */
  30809. var Material = /** @class */ (function () {
  30810. /**
  30811. * Creates a material instance.
  30812. * @param name - The name of the material.
  30813. * @param scene - The BJS scene to reference.
  30814. * @param doNotAdd - Specifies if the material should be added to the scene.
  30815. */
  30816. function Material(name, scene, doNotAdd) {
  30817. /**
  30818. * Specifies if the ready state should be checked on each call.
  30819. */
  30820. this.checkReadyOnEveryCall = false;
  30821. /**
  30822. * Specifies if the ready state should be checked once.
  30823. */
  30824. this.checkReadyOnlyOnce = false;
  30825. /**
  30826. * The state of the material.
  30827. */
  30828. this.state = "";
  30829. /**
  30830. * The alpha value of the material.
  30831. */
  30832. this._alpha = 1.0;
  30833. /**
  30834. * Specifies if back face culling is enabled.
  30835. */
  30836. this._backFaceCulling = true;
  30837. /**
  30838. * Specifies if the material should be serialized.
  30839. */
  30840. this.doNotSerialize = false;
  30841. /**
  30842. * Specifies if the effect should be stored on sub meshes.
  30843. */
  30844. this.storeEffectOnSubMeshes = false;
  30845. /**
  30846. * An event triggered when the material is disposed.
  30847. * @type {BABYLON.Observable}
  30848. */
  30849. this.onDisposeObservable = new BABYLON.Observable();
  30850. /**
  30851. * An event triggered when the material is bound.
  30852. * @type {BABYLON.Observable}
  30853. */
  30854. this.onBindObservable = new BABYLON.Observable();
  30855. /**
  30856. * An event triggered when the material is unbound.
  30857. * @type {BABYLON.Observable}
  30858. */
  30859. this.onUnBindObservable = new BABYLON.Observable();
  30860. /**
  30861. * Stores the value of the alpha mode.
  30862. */
  30863. this._alphaMode = BABYLON.Engine.ALPHA_COMBINE;
  30864. /**
  30865. * Stores the state of the need depth pre-pass value.
  30866. */
  30867. this._needDepthPrePass = false;
  30868. /**
  30869. * Specifies if depth writing should be disabled.
  30870. */
  30871. this.disableDepthWrite = false;
  30872. /**
  30873. * Specifies if depth writing should be forced.
  30874. */
  30875. this.forceDepthWrite = false;
  30876. /**
  30877. * Specifies if there should be a separate pass for culling.
  30878. */
  30879. this.separateCullingPass = false;
  30880. /**
  30881. * Stores the state specifing if fog should be enabled.
  30882. */
  30883. this._fogEnabled = true;
  30884. /**
  30885. * Stores the size of points.
  30886. */
  30887. this.pointSize = 1.0;
  30888. /**
  30889. * Stores the z offset value.
  30890. */
  30891. this.zOffset = 0;
  30892. /**
  30893. * Specifies if the material was previously ready.
  30894. */
  30895. this._wasPreviouslyReady = false;
  30896. /**
  30897. * Stores the fill mode state.
  30898. */
  30899. this._fillMode = Material.TriangleFillMode;
  30900. this.name = name;
  30901. this.id = name || BABYLON.Tools.RandomId();
  30902. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  30903. if (this._scene.useRightHandedSystem) {
  30904. this.sideOrientation = Material.ClockWiseSideOrientation;
  30905. }
  30906. else {
  30907. this.sideOrientation = Material.CounterClockWiseSideOrientation;
  30908. }
  30909. this._uniformBuffer = new BABYLON.UniformBuffer(this._scene.getEngine());
  30910. this._useUBO = this.getScene().getEngine().supportsUniformBuffers;
  30911. if (!doNotAdd) {
  30912. this._scene.materials.push(this);
  30913. }
  30914. }
  30915. Object.defineProperty(Material, "TriangleFillMode", {
  30916. /**
  30917. * Returns the triangle fill mode.
  30918. */
  30919. get: function () {
  30920. return Material._TriangleFillMode;
  30921. },
  30922. enumerable: true,
  30923. configurable: true
  30924. });
  30925. Object.defineProperty(Material, "WireFrameFillMode", {
  30926. /**
  30927. * Returns the wireframe mode.
  30928. */
  30929. get: function () {
  30930. return Material._WireFrameFillMode;
  30931. },
  30932. enumerable: true,
  30933. configurable: true
  30934. });
  30935. Object.defineProperty(Material, "PointFillMode", {
  30936. /**
  30937. * Returns the point fill mode.
  30938. */
  30939. get: function () {
  30940. return Material._PointFillMode;
  30941. },
  30942. enumerable: true,
  30943. configurable: true
  30944. });
  30945. Object.defineProperty(Material, "PointListDrawMode", {
  30946. /**
  30947. * Returns the point list draw mode.
  30948. */
  30949. get: function () {
  30950. return Material._PointListDrawMode;
  30951. },
  30952. enumerable: true,
  30953. configurable: true
  30954. });
  30955. Object.defineProperty(Material, "LineListDrawMode", {
  30956. /**
  30957. * Returns the line list draw mode.
  30958. */
  30959. get: function () {
  30960. return Material._LineListDrawMode;
  30961. },
  30962. enumerable: true,
  30963. configurable: true
  30964. });
  30965. Object.defineProperty(Material, "LineLoopDrawMode", {
  30966. /**
  30967. * Returns the line loop draw mode.
  30968. */
  30969. get: function () {
  30970. return Material._LineLoopDrawMode;
  30971. },
  30972. enumerable: true,
  30973. configurable: true
  30974. });
  30975. Object.defineProperty(Material, "LineStripDrawMode", {
  30976. /**
  30977. * Returns the line strip draw mode.
  30978. */
  30979. get: function () {
  30980. return Material._LineStripDrawMode;
  30981. },
  30982. enumerable: true,
  30983. configurable: true
  30984. });
  30985. Object.defineProperty(Material, "TriangleStripDrawMode", {
  30986. /**
  30987. * Returns the triangle strip draw mode.
  30988. */
  30989. get: function () {
  30990. return Material._TriangleStripDrawMode;
  30991. },
  30992. enumerable: true,
  30993. configurable: true
  30994. });
  30995. Object.defineProperty(Material, "TriangleFanDrawMode", {
  30996. /**
  30997. * Returns the triangle fan draw mode.
  30998. */
  30999. get: function () {
  31000. return Material._TriangleFanDrawMode;
  31001. },
  31002. enumerable: true,
  31003. configurable: true
  31004. });
  31005. Object.defineProperty(Material, "ClockWiseSideOrientation", {
  31006. /**
  31007. * Returns the clock-wise side orientation.
  31008. */
  31009. get: function () {
  31010. return Material._ClockWiseSideOrientation;
  31011. },
  31012. enumerable: true,
  31013. configurable: true
  31014. });
  31015. Object.defineProperty(Material, "CounterClockWiseSideOrientation", {
  31016. /**
  31017. * Returns the counter clock-wise side orientation.
  31018. */
  31019. get: function () {
  31020. return Material._CounterClockWiseSideOrientation;
  31021. },
  31022. enumerable: true,
  31023. configurable: true
  31024. });
  31025. Object.defineProperty(Material, "TextureDirtyFlag", {
  31026. /**
  31027. * Returns the dirty texture flag value.
  31028. */
  31029. get: function () {
  31030. return Material._TextureDirtyFlag;
  31031. },
  31032. enumerable: true,
  31033. configurable: true
  31034. });
  31035. Object.defineProperty(Material, "LightDirtyFlag", {
  31036. /**
  31037. * Returns the dirty light flag value.
  31038. */
  31039. get: function () {
  31040. return Material._LightDirtyFlag;
  31041. },
  31042. enumerable: true,
  31043. configurable: true
  31044. });
  31045. Object.defineProperty(Material, "FresnelDirtyFlag", {
  31046. /**
  31047. * Returns the dirty fresnel flag value.
  31048. */
  31049. get: function () {
  31050. return Material._FresnelDirtyFlag;
  31051. },
  31052. enumerable: true,
  31053. configurable: true
  31054. });
  31055. Object.defineProperty(Material, "AttributesDirtyFlag", {
  31056. /**
  31057. * Returns the dirty attributes flag value.
  31058. */
  31059. get: function () {
  31060. return Material._AttributesDirtyFlag;
  31061. },
  31062. enumerable: true,
  31063. configurable: true
  31064. });
  31065. Object.defineProperty(Material, "MiscDirtyFlag", {
  31066. /**
  31067. * Returns the dirty misc flag value.
  31068. */
  31069. get: function () {
  31070. return Material._MiscDirtyFlag;
  31071. },
  31072. enumerable: true,
  31073. configurable: true
  31074. });
  31075. Object.defineProperty(Material.prototype, "alpha", {
  31076. /**
  31077. * Gets the alpha value of the material.
  31078. */
  31079. get: function () {
  31080. return this._alpha;
  31081. },
  31082. /**
  31083. * Sets the alpha value of the material.
  31084. */
  31085. set: function (value) {
  31086. if (this._alpha === value) {
  31087. return;
  31088. }
  31089. this._alpha = value;
  31090. this.markAsDirty(Material.MiscDirtyFlag);
  31091. },
  31092. enumerable: true,
  31093. configurable: true
  31094. });
  31095. Object.defineProperty(Material.prototype, "backFaceCulling", {
  31096. /**
  31097. * Gets the back-face culling state.
  31098. */
  31099. get: function () {
  31100. return this._backFaceCulling;
  31101. },
  31102. /**
  31103. * Sets the back-face culling state.
  31104. */
  31105. set: function (value) {
  31106. if (this._backFaceCulling === value) {
  31107. return;
  31108. }
  31109. this._backFaceCulling = value;
  31110. this.markAsDirty(Material.TextureDirtyFlag);
  31111. },
  31112. enumerable: true,
  31113. configurable: true
  31114. });
  31115. Object.defineProperty(Material.prototype, "onDispose", {
  31116. /**
  31117. * Called during a dispose event.
  31118. */
  31119. set: function (callback) {
  31120. if (this._onDisposeObserver) {
  31121. this.onDisposeObservable.remove(this._onDisposeObserver);
  31122. }
  31123. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  31124. },
  31125. enumerable: true,
  31126. configurable: true
  31127. });
  31128. Object.defineProperty(Material.prototype, "onBind", {
  31129. /**
  31130. * Called during a bind event.
  31131. */
  31132. set: function (callback) {
  31133. if (this._onBindObserver) {
  31134. this.onBindObservable.remove(this._onBindObserver);
  31135. }
  31136. this._onBindObserver = this.onBindObservable.add(callback);
  31137. },
  31138. enumerable: true,
  31139. configurable: true
  31140. });
  31141. Object.defineProperty(Material.prototype, "alphaMode", {
  31142. /**
  31143. * Gets the value of the alpha mode.
  31144. */
  31145. get: function () {
  31146. return this._alphaMode;
  31147. },
  31148. /**
  31149. * Sets the value of the alpha mode.
  31150. */
  31151. set: function (value) {
  31152. if (this._alphaMode === value) {
  31153. return;
  31154. }
  31155. this._alphaMode = value;
  31156. this.markAsDirty(Material.TextureDirtyFlag);
  31157. },
  31158. enumerable: true,
  31159. configurable: true
  31160. });
  31161. Object.defineProperty(Material.prototype, "needDepthPrePass", {
  31162. /**
  31163. * Gets the depth pre-pass value.
  31164. */
  31165. get: function () {
  31166. return this._needDepthPrePass;
  31167. },
  31168. /**
  31169. * Sets the need depth pre-pass value.
  31170. */
  31171. set: function (value) {
  31172. if (this._needDepthPrePass === value) {
  31173. return;
  31174. }
  31175. this._needDepthPrePass = value;
  31176. if (this._needDepthPrePass) {
  31177. this.checkReadyOnEveryCall = true;
  31178. }
  31179. },
  31180. enumerable: true,
  31181. configurable: true
  31182. });
  31183. Object.defineProperty(Material.prototype, "fogEnabled", {
  31184. /**
  31185. * Gets the value of the fog enabled state.
  31186. */
  31187. get: function () {
  31188. return this._fogEnabled;
  31189. },
  31190. /**
  31191. * Sets the state for enabling fog.
  31192. */
  31193. set: function (value) {
  31194. if (this._fogEnabled === value) {
  31195. return;
  31196. }
  31197. this._fogEnabled = value;
  31198. this.markAsDirty(Material.MiscDirtyFlag);
  31199. },
  31200. enumerable: true,
  31201. configurable: true
  31202. });
  31203. Object.defineProperty(Material.prototype, "wireframe", {
  31204. /**
  31205. * Gets a value specifying if wireframe mode is enabled.
  31206. */
  31207. get: function () {
  31208. return this._fillMode === Material.WireFrameFillMode;
  31209. },
  31210. /**
  31211. * Sets the state of wireframe mode.
  31212. */
  31213. set: function (value) {
  31214. this._fillMode = (value ? Material.WireFrameFillMode : Material.TriangleFillMode);
  31215. },
  31216. enumerable: true,
  31217. configurable: true
  31218. });
  31219. Object.defineProperty(Material.prototype, "pointsCloud", {
  31220. /**
  31221. * Gets the value specifying if point clouds are enabled.
  31222. */
  31223. get: function () {
  31224. return this._fillMode === Material.PointFillMode;
  31225. },
  31226. /**
  31227. * Sets the state of point cloud mode.
  31228. */
  31229. set: function (value) {
  31230. this._fillMode = (value ? Material.PointFillMode : Material.TriangleFillMode);
  31231. },
  31232. enumerable: true,
  31233. configurable: true
  31234. });
  31235. Object.defineProperty(Material.prototype, "fillMode", {
  31236. /**
  31237. * Gets the material fill mode.
  31238. */
  31239. get: function () {
  31240. return this._fillMode;
  31241. },
  31242. /**
  31243. * Sets the material fill mode.
  31244. */
  31245. set: function (value) {
  31246. if (this._fillMode === value) {
  31247. return;
  31248. }
  31249. this._fillMode = value;
  31250. this.markAsDirty(Material.MiscDirtyFlag);
  31251. },
  31252. enumerable: true,
  31253. configurable: true
  31254. });
  31255. /**
  31256. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  31257. * subclasses should override adding information pertainent to themselves.
  31258. * @returns - String with material information.
  31259. */
  31260. Material.prototype.toString = function (fullDetails) {
  31261. var ret = "Name: " + this.name;
  31262. if (fullDetails) {
  31263. }
  31264. return ret;
  31265. };
  31266. /**
  31267. * Gets the class name of the material.
  31268. * @returns - String with the class name of the material.
  31269. */
  31270. Material.prototype.getClassName = function () {
  31271. return "Material";
  31272. };
  31273. Object.defineProperty(Material.prototype, "isFrozen", {
  31274. /**
  31275. * Specifies if updates for the material been locked.
  31276. */
  31277. get: function () {
  31278. return this.checkReadyOnlyOnce;
  31279. },
  31280. enumerable: true,
  31281. configurable: true
  31282. });
  31283. /**
  31284. * Locks updates for the material.
  31285. */
  31286. Material.prototype.freeze = function () {
  31287. this.checkReadyOnlyOnce = true;
  31288. };
  31289. /**
  31290. * Unlocks updates for the material.
  31291. */
  31292. Material.prototype.unfreeze = function () {
  31293. this.checkReadyOnlyOnce = false;
  31294. };
  31295. /**
  31296. * Specifies if the material is ready to be used.
  31297. * @param mesh - BJS mesh.
  31298. * @param useInstances - Specifies if instances should be used.
  31299. * @returns - Boolean indicating if the material is ready to be used.
  31300. */
  31301. Material.prototype.isReady = function (mesh, useInstances) {
  31302. return true;
  31303. };
  31304. /**
  31305. * Specifies that the submesh is ready to be used.
  31306. * @param mesh - BJS mesh.
  31307. * @param subMesh - A submesh of the BJS mesh. Used to check if it is ready.
  31308. * @param useInstances - Specifies that instances should be used.
  31309. * @returns - boolean indicating that the submesh is ready or not.
  31310. */
  31311. Material.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  31312. return false;
  31313. };
  31314. /**
  31315. * Returns the material effect.
  31316. * @returns - Nullable material effect.
  31317. */
  31318. Material.prototype.getEffect = function () {
  31319. return this._effect;
  31320. };
  31321. /**
  31322. * Returns the BJS scene.
  31323. * @returns - BJS Scene.
  31324. */
  31325. Material.prototype.getScene = function () {
  31326. return this._scene;
  31327. };
  31328. /**
  31329. * Specifies if the material will require alpha blending
  31330. * @returns - Boolean specifying if alpha blending is needed.
  31331. */
  31332. Material.prototype.needAlphaBlending = function () {
  31333. return (this.alpha < 1.0);
  31334. };
  31335. /**
  31336. * Specifies if the mesh will require alpha blending.
  31337. * @param mesh - BJS mesh.
  31338. * @returns - Boolean specifying if alpha blending is needed for the mesh.
  31339. */
  31340. Material.prototype.needAlphaBlendingForMesh = function (mesh) {
  31341. return this.needAlphaBlending() || (mesh.visibility < 1.0) || mesh.hasVertexAlpha;
  31342. };
  31343. /**
  31344. * Specifies if this material should be rendered in alpha test mode.
  31345. * @returns - Boolean specifying if an alpha test is needed.
  31346. */
  31347. Material.prototype.needAlphaTesting = function () {
  31348. return false;
  31349. };
  31350. /**
  31351. * Gets the texture used for the alpha test.
  31352. * @returns - Nullable alpha test texture.
  31353. */
  31354. Material.prototype.getAlphaTestTexture = function () {
  31355. return null;
  31356. };
  31357. /**
  31358. * Marks the material to indicate that it needs to be re-calculated.
  31359. */
  31360. Material.prototype.markDirty = function () {
  31361. this._wasPreviouslyReady = false;
  31362. };
  31363. Material.prototype._preBind = function (effect, overrideOrientation) {
  31364. if (overrideOrientation === void 0) { overrideOrientation = null; }
  31365. var engine = this._scene.getEngine();
  31366. var orientation = (overrideOrientation == null) ? this.sideOrientation : overrideOrientation;
  31367. var reverse = orientation === Material.ClockWiseSideOrientation;
  31368. engine.enableEffect(effect ? effect : this._effect);
  31369. engine.setState(this.backFaceCulling, this.zOffset, false, reverse);
  31370. return reverse;
  31371. };
  31372. /**
  31373. * Binds the material to the mesh.
  31374. * @param world - World transformation matrix.
  31375. * @param mesh - Mesh to bind the material to.
  31376. */
  31377. Material.prototype.bind = function (world, mesh) {
  31378. };
  31379. /**
  31380. * Binds the submesh to the material.
  31381. * @param world - World transformation matrix.
  31382. * @param mesh - Mesh containing the submesh.
  31383. * @param subMesh - Submesh to bind the material to.
  31384. */
  31385. Material.prototype.bindForSubMesh = function (world, mesh, subMesh) {
  31386. };
  31387. /**
  31388. * Binds the world matrix to the material.
  31389. * @param world - World transformation matrix.
  31390. */
  31391. Material.prototype.bindOnlyWorldMatrix = function (world) {
  31392. };
  31393. /**
  31394. * Binds the scene's uniform buffer to the effect.
  31395. * @param effect - Effect to bind to the scene uniform buffer.
  31396. * @param sceneUbo - Scene uniform buffer.
  31397. */
  31398. Material.prototype.bindSceneUniformBuffer = function (effect, sceneUbo) {
  31399. sceneUbo.bindToEffect(effect, "Scene");
  31400. };
  31401. /**
  31402. * Binds the view matrix to the effect.
  31403. * @param effect - Effect to bind the view matrix to.
  31404. */
  31405. Material.prototype.bindView = function (effect) {
  31406. if (!this._useUBO) {
  31407. effect.setMatrix("view", this.getScene().getViewMatrix());
  31408. }
  31409. else {
  31410. this.bindSceneUniformBuffer(effect, this.getScene().getSceneUniformBuffer());
  31411. }
  31412. };
  31413. /**
  31414. * Binds the view projection matrix to the effect.
  31415. * @param effect - Effect to bind the view projection matrix to.
  31416. */
  31417. Material.prototype.bindViewProjection = function (effect) {
  31418. if (!this._useUBO) {
  31419. effect.setMatrix("viewProjection", this.getScene().getTransformMatrix());
  31420. }
  31421. else {
  31422. this.bindSceneUniformBuffer(effect, this.getScene().getSceneUniformBuffer());
  31423. }
  31424. };
  31425. /**
  31426. * Specifies if material alpha testing should be turned on for the mesh.
  31427. * @param mesh - BJS mesh.
  31428. */
  31429. Material.prototype._shouldTurnAlphaTestOn = function (mesh) {
  31430. return (!this.needAlphaBlendingForMesh(mesh) && this.needAlphaTesting());
  31431. };
  31432. /**
  31433. * Processes to execute after binding the material to a mesh.
  31434. * @param mesh - BJS mesh.
  31435. */
  31436. Material.prototype._afterBind = function (mesh) {
  31437. this._scene._cachedMaterial = this;
  31438. if (mesh) {
  31439. this._scene._cachedVisibility = mesh.visibility;
  31440. }
  31441. else {
  31442. this._scene._cachedVisibility = 1;
  31443. }
  31444. if (mesh) {
  31445. this.onBindObservable.notifyObservers(mesh);
  31446. }
  31447. if (this.disableDepthWrite) {
  31448. var engine = this._scene.getEngine();
  31449. this._cachedDepthWriteState = engine.getDepthWrite();
  31450. engine.setDepthWrite(false);
  31451. }
  31452. };
  31453. /**
  31454. * Unbinds the material from the mesh.
  31455. */
  31456. Material.prototype.unbind = function () {
  31457. this.onUnBindObservable.notifyObservers(this);
  31458. if (this.disableDepthWrite) {
  31459. var engine = this._scene.getEngine();
  31460. engine.setDepthWrite(this._cachedDepthWriteState);
  31461. }
  31462. };
  31463. /**
  31464. * Gets the active textures from the material.
  31465. * @returns - Array of textures.
  31466. */
  31467. Material.prototype.getActiveTextures = function () {
  31468. return [];
  31469. };
  31470. /**
  31471. * Specifies if the material uses a texture.
  31472. * @param texture - Texture to check against the material.
  31473. * @returns - Boolean specifying if the material uses the texture.
  31474. */
  31475. Material.prototype.hasTexture = function (texture) {
  31476. return false;
  31477. };
  31478. /**
  31479. * Makes a duplicate of the material, and gives it a new name.
  31480. * @param name - Name to call the duplicated material.
  31481. * @returns - Nullable cloned material
  31482. */
  31483. Material.prototype.clone = function (name) {
  31484. return null;
  31485. };
  31486. /**
  31487. * Gets the meshes bound to the material.
  31488. * @returns - Array of meshes bound to the material.
  31489. */
  31490. Material.prototype.getBindedMeshes = function () {
  31491. var result = new Array();
  31492. for (var index = 0; index < this._scene.meshes.length; index++) {
  31493. var mesh = this._scene.meshes[index];
  31494. if (mesh.material === this) {
  31495. result.push(mesh);
  31496. }
  31497. }
  31498. return result;
  31499. };
  31500. /**
  31501. * Force shader compilation
  31502. * @param mesh - BJS mesh.
  31503. * @param onCompiled - function to execute once the material is compiled.
  31504. * @param options - options to pass to this function.
  31505. */
  31506. Material.prototype.forceCompilation = function (mesh, onCompiled, options) {
  31507. var _this = this;
  31508. var localOptions = __assign({ clipPlane: false }, options);
  31509. var subMesh = new BABYLON.BaseSubMesh();
  31510. var scene = this.getScene();
  31511. var checkReady = function () {
  31512. if (!_this._scene || !_this._scene.getEngine()) {
  31513. return;
  31514. }
  31515. if (subMesh._materialDefines) {
  31516. subMesh._materialDefines._renderId = -1;
  31517. }
  31518. var clipPlaneState = scene.clipPlane;
  31519. if (localOptions.clipPlane) {
  31520. scene.clipPlane = new BABYLON.Plane(0, 0, 0, 1);
  31521. }
  31522. if (_this.storeEffectOnSubMeshes) {
  31523. if (_this.isReadyForSubMesh(mesh, subMesh)) {
  31524. if (onCompiled) {
  31525. onCompiled(_this);
  31526. }
  31527. }
  31528. else {
  31529. setTimeout(checkReady, 16);
  31530. }
  31531. }
  31532. else {
  31533. if (_this.isReady(mesh)) {
  31534. if (onCompiled) {
  31535. onCompiled(_this);
  31536. }
  31537. }
  31538. else {
  31539. setTimeout(checkReady, 16);
  31540. }
  31541. }
  31542. if (localOptions.clipPlane) {
  31543. scene.clipPlane = clipPlaneState;
  31544. }
  31545. };
  31546. checkReady();
  31547. };
  31548. /**
  31549. * Force shader compilation.
  31550. * @param mesh The mesh that will use this material
  31551. * @param options Additional options for compiling the shaders
  31552. * @returns A promise that resolves when the compilation completes
  31553. */
  31554. Material.prototype.forceCompilationAsync = function (mesh, options) {
  31555. var _this = this;
  31556. return new Promise(function (resolve) {
  31557. _this.forceCompilation(mesh, function () {
  31558. resolve();
  31559. }, options);
  31560. });
  31561. };
  31562. /**
  31563. * Marks a define in the material to indicate that it needs to be re-computed.
  31564. * @param flag - Material define flag.
  31565. */
  31566. Material.prototype.markAsDirty = function (flag) {
  31567. if (flag & Material.TextureDirtyFlag) {
  31568. this._markAllSubMeshesAsTexturesDirty();
  31569. }
  31570. if (flag & Material.LightDirtyFlag) {
  31571. this._markAllSubMeshesAsLightsDirty();
  31572. }
  31573. if (flag & Material.FresnelDirtyFlag) {
  31574. this._markAllSubMeshesAsFresnelDirty();
  31575. }
  31576. if (flag & Material.AttributesDirtyFlag) {
  31577. this._markAllSubMeshesAsAttributesDirty();
  31578. }
  31579. if (flag & Material.MiscDirtyFlag) {
  31580. this._markAllSubMeshesAsMiscDirty();
  31581. }
  31582. this.getScene().resetCachedMaterial();
  31583. };
  31584. /**
  31585. * Marks all submeshes of a material to indicate that their material defines need to be re-calculated.
  31586. * @param func - function which checks material defines against the submeshes.
  31587. */
  31588. Material.prototype._markAllSubMeshesAsDirty = function (func) {
  31589. for (var _i = 0, _a = this.getScene().meshes; _i < _a.length; _i++) {
  31590. var mesh = _a[_i];
  31591. if (!mesh.subMeshes) {
  31592. continue;
  31593. }
  31594. for (var _b = 0, _c = mesh.subMeshes; _b < _c.length; _b++) {
  31595. var subMesh = _c[_b];
  31596. if (subMesh.getMaterial() !== this) {
  31597. continue;
  31598. }
  31599. if (!subMesh._materialDefines) {
  31600. continue;
  31601. }
  31602. func(subMesh._materialDefines);
  31603. }
  31604. }
  31605. };
  31606. /**
  31607. * Indicates that image processing needs to be re-calculated for all submeshes.
  31608. */
  31609. Material.prototype._markAllSubMeshesAsImageProcessingDirty = function () {
  31610. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsImageProcessingDirty(); });
  31611. };
  31612. /**
  31613. * Indicates that textures need to be re-calculated for all submeshes.
  31614. */
  31615. Material.prototype._markAllSubMeshesAsTexturesDirty = function () {
  31616. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsTexturesDirty(); });
  31617. };
  31618. /**
  31619. * Indicates that fresnel needs to be re-calculated for all submeshes.
  31620. */
  31621. Material.prototype._markAllSubMeshesAsFresnelDirty = function () {
  31622. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsFresnelDirty(); });
  31623. };
  31624. /**
  31625. * Indicates that fresnel and misc need to be re-calculated for all submeshes.
  31626. */
  31627. Material.prototype._markAllSubMeshesAsFresnelAndMiscDirty = function () {
  31628. this._markAllSubMeshesAsDirty(function (defines) {
  31629. defines.markAsFresnelDirty();
  31630. defines.markAsMiscDirty();
  31631. });
  31632. };
  31633. /**
  31634. * Indicates that lights need to be re-calculated for all submeshes.
  31635. */
  31636. Material.prototype._markAllSubMeshesAsLightsDirty = function () {
  31637. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsLightDirty(); });
  31638. };
  31639. /**
  31640. * Indicates that attributes need to be re-calculated for all submeshes.
  31641. */
  31642. Material.prototype._markAllSubMeshesAsAttributesDirty = function () {
  31643. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsAttributesDirty(); });
  31644. };
  31645. /**
  31646. * Indicates that misc needs to be re-calculated for all submeshes.
  31647. */
  31648. Material.prototype._markAllSubMeshesAsMiscDirty = function () {
  31649. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsMiscDirty(); });
  31650. };
  31651. /**
  31652. * Indicates that textures and misc need to be re-calculated for all submeshes.
  31653. */
  31654. Material.prototype._markAllSubMeshesAsTexturesAndMiscDirty = function () {
  31655. this._markAllSubMeshesAsDirty(function (defines) {
  31656. defines.markAsTexturesDirty();
  31657. defines.markAsMiscDirty();
  31658. });
  31659. };
  31660. /**
  31661. * Disposes the material.
  31662. * @param forceDisposeEffect - Specifies if effects should be force disposed.
  31663. * @param forceDisposeTextures - Specifies if textures should be force disposed.
  31664. */
  31665. Material.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  31666. // Animations
  31667. this.getScene().stopAnimation(this);
  31668. // Remove from scene
  31669. var index = this._scene.materials.indexOf(this);
  31670. if (index >= 0) {
  31671. this._scene.materials.splice(index, 1);
  31672. }
  31673. // Remove from meshes
  31674. for (index = 0; index < this._scene.meshes.length; index++) {
  31675. var mesh = this._scene.meshes[index];
  31676. if (mesh.material === this) {
  31677. mesh.material = null;
  31678. if (mesh.geometry) {
  31679. var geometry = (mesh.geometry);
  31680. if (this.storeEffectOnSubMeshes) {
  31681. for (var _i = 0, _a = mesh.subMeshes; _i < _a.length; _i++) {
  31682. var subMesh = _a[_i];
  31683. geometry._releaseVertexArrayObject(subMesh._materialEffect);
  31684. if (forceDisposeEffect && subMesh._materialEffect) {
  31685. this._scene.getEngine()._releaseEffect(subMesh._materialEffect);
  31686. }
  31687. }
  31688. }
  31689. else {
  31690. geometry._releaseVertexArrayObject(this._effect);
  31691. }
  31692. }
  31693. }
  31694. }
  31695. this._uniformBuffer.dispose();
  31696. // Shader are kept in cache for further use but we can get rid of this by using forceDisposeEffect
  31697. if (forceDisposeEffect && this._effect) {
  31698. if (!this.storeEffectOnSubMeshes) {
  31699. this._scene.getEngine()._releaseEffect(this._effect);
  31700. }
  31701. this._effect = null;
  31702. }
  31703. // Callback
  31704. this.onDisposeObservable.notifyObservers(this);
  31705. this.onDisposeObservable.clear();
  31706. this.onBindObservable.clear();
  31707. this.onUnBindObservable.clear();
  31708. };
  31709. /**
  31710. * Serializes this material.
  31711. * @returns - serialized material object.
  31712. */
  31713. Material.prototype.serialize = function () {
  31714. return BABYLON.SerializationHelper.Serialize(this);
  31715. };
  31716. /**
  31717. * Creates a MultiMaterial from parse MultiMaterial data.
  31718. * @param parsedMultiMaterial - Parsed MultiMaterial data.
  31719. * @param scene - BJS scene.
  31720. * @returns - MultiMaterial.
  31721. */
  31722. Material.ParseMultiMaterial = function (parsedMultiMaterial, scene) {
  31723. var multiMaterial = new BABYLON.MultiMaterial(parsedMultiMaterial.name, scene);
  31724. multiMaterial.id = parsedMultiMaterial.id;
  31725. if (BABYLON.Tags) {
  31726. BABYLON.Tags.AddTagsTo(multiMaterial, parsedMultiMaterial.tags);
  31727. }
  31728. for (var matIndex = 0; matIndex < parsedMultiMaterial.materials.length; matIndex++) {
  31729. var subMatId = parsedMultiMaterial.materials[matIndex];
  31730. if (subMatId) {
  31731. multiMaterial.subMaterials.push(scene.getMaterialByID(subMatId));
  31732. }
  31733. else {
  31734. multiMaterial.subMaterials.push(null);
  31735. }
  31736. }
  31737. return multiMaterial;
  31738. };
  31739. /**
  31740. * Creates a material from parsed material data.
  31741. * @param parsedMaterial - Parsed material data.
  31742. * @param scene - BJS scene.
  31743. * @param rootUrl - Root URL containing the material information.
  31744. * @returns - Parsed material.
  31745. */
  31746. Material.Parse = function (parsedMaterial, scene, rootUrl) {
  31747. if (!parsedMaterial.customType) {
  31748. return BABYLON.StandardMaterial.Parse(parsedMaterial, scene, rootUrl);
  31749. }
  31750. if (parsedMaterial.customType === "BABYLON.PBRMaterial" && parsedMaterial.overloadedAlbedo) {
  31751. parsedMaterial.customType = "BABYLON.LegacyPBRMaterial";
  31752. if (!BABYLON.LegacyPBRMaterial) {
  31753. BABYLON.Tools.Error("Your scene is trying to load a legacy version of the PBRMaterial, please, include it from the materials library.");
  31754. return;
  31755. }
  31756. }
  31757. var materialType = BABYLON.Tools.Instantiate(parsedMaterial.customType);
  31758. return materialType.Parse(parsedMaterial, scene, rootUrl);
  31759. ;
  31760. };
  31761. // Triangle views
  31762. Material._TriangleFillMode = 0;
  31763. Material._WireFrameFillMode = 1;
  31764. Material._PointFillMode = 2;
  31765. // Draw modes
  31766. Material._PointListDrawMode = 3;
  31767. Material._LineListDrawMode = 4;
  31768. Material._LineLoopDrawMode = 5;
  31769. Material._LineStripDrawMode = 6;
  31770. Material._TriangleStripDrawMode = 7;
  31771. Material._TriangleFanDrawMode = 8;
  31772. /**
  31773. * Stores the clock-wise side orientation.
  31774. */
  31775. Material._ClockWiseSideOrientation = 0;
  31776. /**
  31777. * Stores the counter clock-wise side orientation.
  31778. */
  31779. Material._CounterClockWiseSideOrientation = 1;
  31780. /**
  31781. * The dirty texture flag value.
  31782. */
  31783. Material._TextureDirtyFlag = 1;
  31784. /**
  31785. * The dirty light flag value.
  31786. */
  31787. Material._LightDirtyFlag = 2;
  31788. /**
  31789. * The dirty fresnel flag value.
  31790. */
  31791. Material._FresnelDirtyFlag = 4;
  31792. /**
  31793. * The dirty attribute flag value.
  31794. */
  31795. Material._AttributesDirtyFlag = 8;
  31796. /**
  31797. * The dirty misc flag value.
  31798. */
  31799. Material._MiscDirtyFlag = 16;
  31800. __decorate([
  31801. BABYLON.serialize()
  31802. ], Material.prototype, "id", void 0);
  31803. __decorate([
  31804. BABYLON.serialize()
  31805. ], Material.prototype, "name", void 0);
  31806. __decorate([
  31807. BABYLON.serialize()
  31808. ], Material.prototype, "checkReadyOnEveryCall", void 0);
  31809. __decorate([
  31810. BABYLON.serialize()
  31811. ], Material.prototype, "checkReadyOnlyOnce", void 0);
  31812. __decorate([
  31813. BABYLON.serialize()
  31814. ], Material.prototype, "state", void 0);
  31815. __decorate([
  31816. BABYLON.serialize("alpha")
  31817. ], Material.prototype, "_alpha", void 0);
  31818. __decorate([
  31819. BABYLON.serialize("backFaceCulling")
  31820. ], Material.prototype, "_backFaceCulling", void 0);
  31821. __decorate([
  31822. BABYLON.serialize()
  31823. ], Material.prototype, "sideOrientation", void 0);
  31824. __decorate([
  31825. BABYLON.serialize("alphaMode")
  31826. ], Material.prototype, "_alphaMode", void 0);
  31827. __decorate([
  31828. BABYLON.serialize()
  31829. ], Material.prototype, "_needDepthPrePass", void 0);
  31830. __decorate([
  31831. BABYLON.serialize()
  31832. ], Material.prototype, "disableDepthWrite", void 0);
  31833. __decorate([
  31834. BABYLON.serialize()
  31835. ], Material.prototype, "forceDepthWrite", void 0);
  31836. __decorate([
  31837. BABYLON.serialize()
  31838. ], Material.prototype, "separateCullingPass", void 0);
  31839. __decorate([
  31840. BABYLON.serialize("fogEnabled")
  31841. ], Material.prototype, "_fogEnabled", void 0);
  31842. __decorate([
  31843. BABYLON.serialize()
  31844. ], Material.prototype, "pointSize", void 0);
  31845. __decorate([
  31846. BABYLON.serialize()
  31847. ], Material.prototype, "zOffset", void 0);
  31848. __decorate([
  31849. BABYLON.serialize()
  31850. ], Material.prototype, "wireframe", null);
  31851. __decorate([
  31852. BABYLON.serialize()
  31853. ], Material.prototype, "pointsCloud", null);
  31854. __decorate([
  31855. BABYLON.serialize()
  31856. ], Material.prototype, "fillMode", null);
  31857. return Material;
  31858. }());
  31859. BABYLON.Material = Material;
  31860. })(BABYLON || (BABYLON = {}));
  31861. //# sourceMappingURL=babylon.material.js.map
  31862. var BABYLON;
  31863. (function (BABYLON) {
  31864. var UniformBuffer = /** @class */ (function () {
  31865. /**
  31866. * Uniform buffer objects.
  31867. *
  31868. * Handles blocks of uniform on the GPU.
  31869. *
  31870. * If WebGL 2 is not available, this class falls back on traditionnal setUniformXXX calls.
  31871. *
  31872. * For more information, please refer to :
  31873. * https://www.khronos.org/opengl/wiki/Uniform_Buffer_Object
  31874. */
  31875. function UniformBuffer(engine, data, dynamic) {
  31876. this._engine = engine;
  31877. this._noUBO = !engine.supportsUniformBuffers;
  31878. this._dynamic = dynamic;
  31879. this._data = data || [];
  31880. this._uniformLocations = {};
  31881. this._uniformSizes = {};
  31882. this._uniformLocationPointer = 0;
  31883. this._needSync = false;
  31884. if (this._noUBO) {
  31885. this.updateMatrix3x3 = this._updateMatrix3x3ForEffect;
  31886. this.updateMatrix2x2 = this._updateMatrix2x2ForEffect;
  31887. this.updateFloat = this._updateFloatForEffect;
  31888. this.updateFloat2 = this._updateFloat2ForEffect;
  31889. this.updateFloat3 = this._updateFloat3ForEffect;
  31890. this.updateFloat4 = this._updateFloat4ForEffect;
  31891. this.updateMatrix = this._updateMatrixForEffect;
  31892. this.updateVector3 = this._updateVector3ForEffect;
  31893. this.updateVector4 = this._updateVector4ForEffect;
  31894. this.updateColor3 = this._updateColor3ForEffect;
  31895. this.updateColor4 = this._updateColor4ForEffect;
  31896. }
  31897. else {
  31898. this._engine._uniformBuffers.push(this);
  31899. this.updateMatrix3x3 = this._updateMatrix3x3ForUniform;
  31900. this.updateMatrix2x2 = this._updateMatrix2x2ForUniform;
  31901. this.updateFloat = this._updateFloatForUniform;
  31902. this.updateFloat2 = this._updateFloat2ForUniform;
  31903. this.updateFloat3 = this._updateFloat3ForUniform;
  31904. this.updateFloat4 = this._updateFloat4ForUniform;
  31905. this.updateMatrix = this._updateMatrixForUniform;
  31906. this.updateVector3 = this._updateVector3ForUniform;
  31907. this.updateVector4 = this._updateVector4ForUniform;
  31908. this.updateColor3 = this._updateColor3ForUniform;
  31909. this.updateColor4 = this._updateColor4ForUniform;
  31910. }
  31911. }
  31912. Object.defineProperty(UniformBuffer.prototype, "useUbo", {
  31913. // Properties
  31914. /**
  31915. * Indicates if the buffer is using the WebGL2 UBO implementation,
  31916. * or just falling back on setUniformXXX calls.
  31917. */
  31918. get: function () {
  31919. return !this._noUBO;
  31920. },
  31921. enumerable: true,
  31922. configurable: true
  31923. });
  31924. Object.defineProperty(UniformBuffer.prototype, "isSync", {
  31925. /**
  31926. * Indicates if the WebGL underlying uniform buffer is in sync
  31927. * with the javascript cache data.
  31928. */
  31929. get: function () {
  31930. return !this._needSync;
  31931. },
  31932. enumerable: true,
  31933. configurable: true
  31934. });
  31935. /**
  31936. * Indicates if the WebGL underlying uniform buffer is dynamic.
  31937. * Also, a dynamic UniformBuffer will disable cache verification and always
  31938. * update the underlying WebGL uniform buffer to the GPU.
  31939. */
  31940. UniformBuffer.prototype.isDynamic = function () {
  31941. return this._dynamic !== undefined;
  31942. };
  31943. /**
  31944. * The data cache on JS side.
  31945. */
  31946. UniformBuffer.prototype.getData = function () {
  31947. return this._bufferData;
  31948. };
  31949. /**
  31950. * The underlying WebGL Uniform buffer.
  31951. */
  31952. UniformBuffer.prototype.getBuffer = function () {
  31953. return this._buffer;
  31954. };
  31955. /**
  31956. * std140 layout specifies how to align data within an UBO structure.
  31957. * See https://khronos.org/registry/OpenGL/specs/gl/glspec45.core.pdf#page=159
  31958. * for specs.
  31959. */
  31960. UniformBuffer.prototype._fillAlignment = function (size) {
  31961. // This code has been simplified because we only use floats, vectors of 1, 2, 3, 4 components
  31962. // and 4x4 matrices
  31963. // TODO : change if other types are used
  31964. var alignment;
  31965. if (size <= 2) {
  31966. alignment = size;
  31967. }
  31968. else {
  31969. alignment = 4;
  31970. }
  31971. if ((this._uniformLocationPointer % alignment) !== 0) {
  31972. var oldPointer = this._uniformLocationPointer;
  31973. this._uniformLocationPointer += alignment - (this._uniformLocationPointer % alignment);
  31974. var diff = this._uniformLocationPointer - oldPointer;
  31975. for (var i = 0; i < diff; i++) {
  31976. this._data.push(0);
  31977. }
  31978. }
  31979. };
  31980. /**
  31981. * Adds an uniform in the buffer.
  31982. * Warning : the subsequents calls of this function must be in the same order as declared in the shader
  31983. * for the layout to be correct !
  31984. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  31985. * @param {number|number[]} size Data size, or data directly.
  31986. */
  31987. UniformBuffer.prototype.addUniform = function (name, size) {
  31988. if (this._noUBO) {
  31989. return;
  31990. }
  31991. if (this._uniformLocations[name] !== undefined) {
  31992. // Already existing uniform
  31993. return;
  31994. }
  31995. // This function must be called in the order of the shader layout !
  31996. // size can be the size of the uniform, or data directly
  31997. var data;
  31998. if (size instanceof Array) {
  31999. data = size;
  32000. size = data.length;
  32001. }
  32002. else {
  32003. size = size;
  32004. data = [];
  32005. // Fill with zeros
  32006. for (var i = 0; i < size; i++) {
  32007. data.push(0);
  32008. }
  32009. }
  32010. this._fillAlignment(size);
  32011. this._uniformSizes[name] = size;
  32012. this._uniformLocations[name] = this._uniformLocationPointer;
  32013. this._uniformLocationPointer += size;
  32014. for (var i = 0; i < size; i++) {
  32015. this._data.push(data[i]);
  32016. }
  32017. this._needSync = true;
  32018. };
  32019. /**
  32020. * Wrapper for addUniform.
  32021. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  32022. * @param {Matrix} mat A 4x4 matrix.
  32023. */
  32024. UniformBuffer.prototype.addMatrix = function (name, mat) {
  32025. this.addUniform(name, Array.prototype.slice.call(mat.toArray()));
  32026. };
  32027. /**
  32028. * Wrapper for addUniform.
  32029. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  32030. * @param {number} x
  32031. * @param {number} y
  32032. */
  32033. UniformBuffer.prototype.addFloat2 = function (name, x, y) {
  32034. var temp = [x, y];
  32035. this.addUniform(name, temp);
  32036. };
  32037. /**
  32038. * Wrapper for addUniform.
  32039. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  32040. * @param {number} x
  32041. * @param {number} y
  32042. * @param {number} z
  32043. */
  32044. UniformBuffer.prototype.addFloat3 = function (name, x, y, z) {
  32045. var temp = [x, y, z];
  32046. this.addUniform(name, temp);
  32047. };
  32048. /**
  32049. * Wrapper for addUniform.
  32050. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  32051. * @param {Color3} color
  32052. */
  32053. UniformBuffer.prototype.addColor3 = function (name, color) {
  32054. var temp = new Array();
  32055. color.toArray(temp);
  32056. this.addUniform(name, temp);
  32057. };
  32058. /**
  32059. * Wrapper for addUniform.
  32060. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  32061. * @param {Color3} color
  32062. * @param {number} alpha
  32063. */
  32064. UniformBuffer.prototype.addColor4 = function (name, color, alpha) {
  32065. var temp = new Array();
  32066. color.toArray(temp);
  32067. temp.push(alpha);
  32068. this.addUniform(name, temp);
  32069. };
  32070. /**
  32071. * Wrapper for addUniform.
  32072. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  32073. * @param {Vector3} vector
  32074. */
  32075. UniformBuffer.prototype.addVector3 = function (name, vector) {
  32076. var temp = new Array();
  32077. vector.toArray(temp);
  32078. this.addUniform(name, temp);
  32079. };
  32080. /**
  32081. * Wrapper for addUniform.
  32082. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  32083. */
  32084. UniformBuffer.prototype.addMatrix3x3 = function (name) {
  32085. this.addUniform(name, 12);
  32086. };
  32087. /**
  32088. * Wrapper for addUniform.
  32089. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  32090. */
  32091. UniformBuffer.prototype.addMatrix2x2 = function (name) {
  32092. this.addUniform(name, 8);
  32093. };
  32094. /**
  32095. * Effectively creates the WebGL Uniform Buffer, once layout is completed with `addUniform`.
  32096. */
  32097. UniformBuffer.prototype.create = function () {
  32098. if (this._noUBO) {
  32099. return;
  32100. }
  32101. if (this._buffer) {
  32102. return; // nothing to do
  32103. }
  32104. // See spec, alignment must be filled as a vec4
  32105. this._fillAlignment(4);
  32106. this._bufferData = new Float32Array(this._data);
  32107. this._rebuild();
  32108. this._needSync = true;
  32109. };
  32110. UniformBuffer.prototype._rebuild = function () {
  32111. if (this._noUBO) {
  32112. return;
  32113. }
  32114. if (this._dynamic) {
  32115. this._buffer = this._engine.createDynamicUniformBuffer(this._bufferData);
  32116. }
  32117. else {
  32118. this._buffer = this._engine.createUniformBuffer(this._bufferData);
  32119. }
  32120. };
  32121. /**
  32122. * Updates the WebGL Uniform Buffer on the GPU.
  32123. * If the `dynamic` flag is set to true, no cache comparison is done.
  32124. * Otherwise, the buffer will be updated only if the cache differs.
  32125. */
  32126. UniformBuffer.prototype.update = function () {
  32127. if (!this._buffer) {
  32128. this.create();
  32129. return;
  32130. }
  32131. if (!this._dynamic && !this._needSync) {
  32132. return;
  32133. }
  32134. this._engine.updateUniformBuffer(this._buffer, this._bufferData);
  32135. this._needSync = false;
  32136. };
  32137. /**
  32138. * Updates the value of an uniform. The `update` method must be called afterwards to make it effective in the GPU.
  32139. * @param {string} uniformName Name of the uniform, as used in the uniform block in the shader.
  32140. * @param {number[]|Float32Array} data Flattened data
  32141. * @param {number} size Size of the data.
  32142. */
  32143. UniformBuffer.prototype.updateUniform = function (uniformName, data, size) {
  32144. var location = this._uniformLocations[uniformName];
  32145. if (location === undefined) {
  32146. if (this._buffer) {
  32147. // Cannot add an uniform if the buffer is already created
  32148. BABYLON.Tools.Error("Cannot add an uniform after UBO has been created.");
  32149. return;
  32150. }
  32151. this.addUniform(uniformName, size);
  32152. location = this._uniformLocations[uniformName];
  32153. }
  32154. if (!this._buffer) {
  32155. this.create();
  32156. }
  32157. if (!this._dynamic) {
  32158. // Cache for static uniform buffers
  32159. var changed = false;
  32160. for (var i = 0; i < size; i++) {
  32161. if (this._bufferData[location + i] !== data[i]) {
  32162. changed = true;
  32163. this._bufferData[location + i] = data[i];
  32164. }
  32165. }
  32166. this._needSync = this._needSync || changed;
  32167. }
  32168. else {
  32169. // No cache for dynamic
  32170. for (var i = 0; i < size; i++) {
  32171. this._bufferData[location + i] = data[i];
  32172. }
  32173. }
  32174. };
  32175. // Update methods
  32176. UniformBuffer.prototype._updateMatrix3x3ForUniform = function (name, matrix) {
  32177. // To match std140, matrix must be realigned
  32178. for (var i = 0; i < 3; i++) {
  32179. UniformBuffer._tempBuffer[i * 4] = matrix[i * 3];
  32180. UniformBuffer._tempBuffer[i * 4 + 1] = matrix[i * 3 + 1];
  32181. UniformBuffer._tempBuffer[i * 4 + 2] = matrix[i * 3 + 2];
  32182. UniformBuffer._tempBuffer[i * 4 + 3] = 0.0;
  32183. }
  32184. this.updateUniform(name, UniformBuffer._tempBuffer, 12);
  32185. };
  32186. UniformBuffer.prototype._updateMatrix3x3ForEffect = function (name, matrix) {
  32187. this._currentEffect.setMatrix3x3(name, matrix);
  32188. };
  32189. UniformBuffer.prototype._updateMatrix2x2ForEffect = function (name, matrix) {
  32190. this._currentEffect.setMatrix2x2(name, matrix);
  32191. };
  32192. UniformBuffer.prototype._updateMatrix2x2ForUniform = function (name, matrix) {
  32193. // To match std140, matrix must be realigned
  32194. for (var i = 0; i < 2; i++) {
  32195. UniformBuffer._tempBuffer[i * 4] = matrix[i * 2];
  32196. UniformBuffer._tempBuffer[i * 4 + 1] = matrix[i * 2 + 1];
  32197. UniformBuffer._tempBuffer[i * 4 + 2] = 0.0;
  32198. UniformBuffer._tempBuffer[i * 4 + 3] = 0.0;
  32199. }
  32200. this.updateUniform(name, UniformBuffer._tempBuffer, 8);
  32201. };
  32202. UniformBuffer.prototype._updateFloatForEffect = function (name, x) {
  32203. this._currentEffect.setFloat(name, x);
  32204. };
  32205. UniformBuffer.prototype._updateFloatForUniform = function (name, x) {
  32206. UniformBuffer._tempBuffer[0] = x;
  32207. this.updateUniform(name, UniformBuffer._tempBuffer, 1);
  32208. };
  32209. UniformBuffer.prototype._updateFloat2ForEffect = function (name, x, y, suffix) {
  32210. if (suffix === void 0) { suffix = ""; }
  32211. this._currentEffect.setFloat2(name + suffix, x, y);
  32212. };
  32213. UniformBuffer.prototype._updateFloat2ForUniform = function (name, x, y, suffix) {
  32214. if (suffix === void 0) { suffix = ""; }
  32215. UniformBuffer._tempBuffer[0] = x;
  32216. UniformBuffer._tempBuffer[1] = y;
  32217. this.updateUniform(name, UniformBuffer._tempBuffer, 2);
  32218. };
  32219. UniformBuffer.prototype._updateFloat3ForEffect = function (name, x, y, z, suffix) {
  32220. if (suffix === void 0) { suffix = ""; }
  32221. this._currentEffect.setFloat3(name + suffix, x, y, z);
  32222. };
  32223. UniformBuffer.prototype._updateFloat3ForUniform = function (name, x, y, z, suffix) {
  32224. if (suffix === void 0) { suffix = ""; }
  32225. UniformBuffer._tempBuffer[0] = x;
  32226. UniformBuffer._tempBuffer[1] = y;
  32227. UniformBuffer._tempBuffer[2] = z;
  32228. this.updateUniform(name, UniformBuffer._tempBuffer, 3);
  32229. };
  32230. UniformBuffer.prototype._updateFloat4ForEffect = function (name, x, y, z, w, suffix) {
  32231. if (suffix === void 0) { suffix = ""; }
  32232. this._currentEffect.setFloat4(name + suffix, x, y, z, w);
  32233. };
  32234. UniformBuffer.prototype._updateFloat4ForUniform = function (name, x, y, z, w, suffix) {
  32235. if (suffix === void 0) { suffix = ""; }
  32236. UniformBuffer._tempBuffer[0] = x;
  32237. UniformBuffer._tempBuffer[1] = y;
  32238. UniformBuffer._tempBuffer[2] = z;
  32239. UniformBuffer._tempBuffer[3] = w;
  32240. this.updateUniform(name, UniformBuffer._tempBuffer, 4);
  32241. };
  32242. UniformBuffer.prototype._updateMatrixForEffect = function (name, mat) {
  32243. this._currentEffect.setMatrix(name, mat);
  32244. };
  32245. UniformBuffer.prototype._updateMatrixForUniform = function (name, mat) {
  32246. this.updateUniform(name, mat.toArray(), 16);
  32247. };
  32248. UniformBuffer.prototype._updateVector3ForEffect = function (name, vector) {
  32249. this._currentEffect.setVector3(name, vector);
  32250. };
  32251. UniformBuffer.prototype._updateVector3ForUniform = function (name, vector) {
  32252. vector.toArray(UniformBuffer._tempBuffer);
  32253. this.updateUniform(name, UniformBuffer._tempBuffer, 3);
  32254. };
  32255. UniformBuffer.prototype._updateVector4ForEffect = function (name, vector) {
  32256. this._currentEffect.setVector4(name, vector);
  32257. };
  32258. UniformBuffer.prototype._updateVector4ForUniform = function (name, vector) {
  32259. vector.toArray(UniformBuffer._tempBuffer);
  32260. this.updateUniform(name, UniformBuffer._tempBuffer, 4);
  32261. };
  32262. UniformBuffer.prototype._updateColor3ForEffect = function (name, color, suffix) {
  32263. if (suffix === void 0) { suffix = ""; }
  32264. this._currentEffect.setColor3(name + suffix, color);
  32265. };
  32266. UniformBuffer.prototype._updateColor3ForUniform = function (name, color, suffix) {
  32267. if (suffix === void 0) { suffix = ""; }
  32268. color.toArray(UniformBuffer._tempBuffer);
  32269. this.updateUniform(name, UniformBuffer._tempBuffer, 3);
  32270. };
  32271. UniformBuffer.prototype._updateColor4ForEffect = function (name, color, alpha, suffix) {
  32272. if (suffix === void 0) { suffix = ""; }
  32273. this._currentEffect.setColor4(name + suffix, color, alpha);
  32274. };
  32275. UniformBuffer.prototype._updateColor4ForUniform = function (name, color, alpha, suffix) {
  32276. if (suffix === void 0) { suffix = ""; }
  32277. color.toArray(UniformBuffer._tempBuffer);
  32278. UniformBuffer._tempBuffer[3] = alpha;
  32279. this.updateUniform(name, UniformBuffer._tempBuffer, 4);
  32280. };
  32281. /**
  32282. * Sets a sampler uniform on the effect.
  32283. * @param {string} name Name of the sampler.
  32284. * @param {Texture} texture
  32285. */
  32286. UniformBuffer.prototype.setTexture = function (name, texture) {
  32287. this._currentEffect.setTexture(name, texture);
  32288. };
  32289. /**
  32290. * Directly updates the value of the uniform in the cache AND on the GPU.
  32291. * @param {string} uniformName Name of the uniform, as used in the uniform block in the shader.
  32292. * @param {number[]|Float32Array} data Flattened data
  32293. */
  32294. UniformBuffer.prototype.updateUniformDirectly = function (uniformName, data) {
  32295. this.updateUniform(uniformName, data, data.length);
  32296. this.update();
  32297. };
  32298. /**
  32299. * Binds this uniform buffer to an effect.
  32300. * @param {Effect} effect
  32301. * @param {string} name Name of the uniform block in the shader.
  32302. */
  32303. UniformBuffer.prototype.bindToEffect = function (effect, name) {
  32304. this._currentEffect = effect;
  32305. if (this._noUBO || !this._buffer) {
  32306. return;
  32307. }
  32308. effect.bindUniformBuffer(this._buffer, name);
  32309. };
  32310. /**
  32311. * Disposes the uniform buffer.
  32312. */
  32313. UniformBuffer.prototype.dispose = function () {
  32314. if (this._noUBO) {
  32315. return;
  32316. }
  32317. var index = this._engine._uniformBuffers.indexOf(this);
  32318. if (index !== -1) {
  32319. this._engine._uniformBuffers.splice(index, 1);
  32320. }
  32321. if (!this._buffer) {
  32322. return;
  32323. }
  32324. if (this._engine._releaseBuffer(this._buffer)) {
  32325. this._buffer = null;
  32326. }
  32327. };
  32328. // Pool for avoiding memory leaks
  32329. UniformBuffer._MAX_UNIFORM_SIZE = 256;
  32330. UniformBuffer._tempBuffer = new Float32Array(UniformBuffer._MAX_UNIFORM_SIZE);
  32331. return UniformBuffer;
  32332. }());
  32333. BABYLON.UniformBuffer = UniformBuffer;
  32334. })(BABYLON || (BABYLON = {}));
  32335. //# sourceMappingURL=babylon.uniformBuffer.js.map
  32336. var BABYLON;
  32337. (function (BABYLON) {
  32338. var VertexData = /** @class */ (function () {
  32339. function VertexData() {
  32340. }
  32341. VertexData.prototype.set = function (data, kind) {
  32342. switch (kind) {
  32343. case BABYLON.VertexBuffer.PositionKind:
  32344. this.positions = data;
  32345. break;
  32346. case BABYLON.VertexBuffer.NormalKind:
  32347. this.normals = data;
  32348. break;
  32349. case BABYLON.VertexBuffer.TangentKind:
  32350. this.tangents = data;
  32351. break;
  32352. case BABYLON.VertexBuffer.UVKind:
  32353. this.uvs = data;
  32354. break;
  32355. case BABYLON.VertexBuffer.UV2Kind:
  32356. this.uvs2 = data;
  32357. break;
  32358. case BABYLON.VertexBuffer.UV3Kind:
  32359. this.uvs3 = data;
  32360. break;
  32361. case BABYLON.VertexBuffer.UV4Kind:
  32362. this.uvs4 = data;
  32363. break;
  32364. case BABYLON.VertexBuffer.UV5Kind:
  32365. this.uvs5 = data;
  32366. break;
  32367. case BABYLON.VertexBuffer.UV6Kind:
  32368. this.uvs6 = data;
  32369. break;
  32370. case BABYLON.VertexBuffer.ColorKind:
  32371. this.colors = data;
  32372. break;
  32373. case BABYLON.VertexBuffer.MatricesIndicesKind:
  32374. this.matricesIndices = data;
  32375. break;
  32376. case BABYLON.VertexBuffer.MatricesWeightsKind:
  32377. this.matricesWeights = data;
  32378. break;
  32379. case BABYLON.VertexBuffer.MatricesIndicesExtraKind:
  32380. this.matricesIndicesExtra = data;
  32381. break;
  32382. case BABYLON.VertexBuffer.MatricesWeightsExtraKind:
  32383. this.matricesWeightsExtra = data;
  32384. break;
  32385. }
  32386. };
  32387. /**
  32388. * Associates the vertexData to the passed Mesh.
  32389. * Sets it as updatable or not (default `false`).
  32390. * Returns the VertexData.
  32391. */
  32392. VertexData.prototype.applyToMesh = function (mesh, updatable) {
  32393. this._applyTo(mesh, updatable);
  32394. return this;
  32395. };
  32396. /**
  32397. * Associates the vertexData to the passed Geometry.
  32398. * Sets it as updatable or not (default `false`).
  32399. * Returns the VertexData.
  32400. */
  32401. VertexData.prototype.applyToGeometry = function (geometry, updatable) {
  32402. this._applyTo(geometry, updatable);
  32403. return this;
  32404. };
  32405. /**
  32406. * Updates the associated mesh.
  32407. * Returns the VertexData.
  32408. */
  32409. VertexData.prototype.updateMesh = function (mesh, updateExtends, makeItUnique) {
  32410. this._update(mesh);
  32411. return this;
  32412. };
  32413. /**
  32414. * Updates the associated geometry.
  32415. * Returns the VertexData.
  32416. */
  32417. VertexData.prototype.updateGeometry = function (geometry, updateExtends, makeItUnique) {
  32418. this._update(geometry);
  32419. return this;
  32420. };
  32421. VertexData.prototype._applyTo = function (meshOrGeometry, updatable) {
  32422. if (updatable === void 0) { updatable = false; }
  32423. if (this.positions) {
  32424. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.PositionKind, this.positions, updatable);
  32425. }
  32426. if (this.normals) {
  32427. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.NormalKind, this.normals, updatable);
  32428. }
  32429. if (this.tangents) {
  32430. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.TangentKind, this.tangents, updatable);
  32431. }
  32432. if (this.uvs) {
  32433. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UVKind, this.uvs, updatable);
  32434. }
  32435. if (this.uvs2) {
  32436. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV2Kind, this.uvs2, updatable);
  32437. }
  32438. if (this.uvs3) {
  32439. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV3Kind, this.uvs3, updatable);
  32440. }
  32441. if (this.uvs4) {
  32442. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV4Kind, this.uvs4, updatable);
  32443. }
  32444. if (this.uvs5) {
  32445. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV5Kind, this.uvs5, updatable);
  32446. }
  32447. if (this.uvs6) {
  32448. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV6Kind, this.uvs6, updatable);
  32449. }
  32450. if (this.colors) {
  32451. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.ColorKind, this.colors, updatable);
  32452. }
  32453. if (this.matricesIndices) {
  32454. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, this.matricesIndices, updatable);
  32455. }
  32456. if (this.matricesWeights) {
  32457. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, this.matricesWeights, updatable);
  32458. }
  32459. if (this.matricesIndicesExtra) {
  32460. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, this.matricesIndicesExtra, updatable);
  32461. }
  32462. if (this.matricesWeightsExtra) {
  32463. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, this.matricesWeightsExtra, updatable);
  32464. }
  32465. if (this.indices) {
  32466. meshOrGeometry.setIndices(this.indices, null, updatable);
  32467. }
  32468. return this;
  32469. };
  32470. VertexData.prototype._update = function (meshOrGeometry, updateExtends, makeItUnique) {
  32471. if (this.positions) {
  32472. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.PositionKind, this.positions, updateExtends, makeItUnique);
  32473. }
  32474. if (this.normals) {
  32475. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.NormalKind, this.normals, updateExtends, makeItUnique);
  32476. }
  32477. if (this.tangents) {
  32478. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.TangentKind, this.tangents, updateExtends, makeItUnique);
  32479. }
  32480. if (this.uvs) {
  32481. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UVKind, this.uvs, updateExtends, makeItUnique);
  32482. }
  32483. if (this.uvs2) {
  32484. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV2Kind, this.uvs2, updateExtends, makeItUnique);
  32485. }
  32486. if (this.uvs3) {
  32487. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV3Kind, this.uvs3, updateExtends, makeItUnique);
  32488. }
  32489. if (this.uvs4) {
  32490. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV4Kind, this.uvs4, updateExtends, makeItUnique);
  32491. }
  32492. if (this.uvs5) {
  32493. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV5Kind, this.uvs5, updateExtends, makeItUnique);
  32494. }
  32495. if (this.uvs6) {
  32496. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV6Kind, this.uvs6, updateExtends, makeItUnique);
  32497. }
  32498. if (this.colors) {
  32499. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.ColorKind, this.colors, updateExtends, makeItUnique);
  32500. }
  32501. if (this.matricesIndices) {
  32502. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, this.matricesIndices, updateExtends, makeItUnique);
  32503. }
  32504. if (this.matricesWeights) {
  32505. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, this.matricesWeights, updateExtends, makeItUnique);
  32506. }
  32507. if (this.matricesIndicesExtra) {
  32508. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, this.matricesIndicesExtra, updateExtends, makeItUnique);
  32509. }
  32510. if (this.matricesWeightsExtra) {
  32511. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, this.matricesWeightsExtra, updateExtends, makeItUnique);
  32512. }
  32513. if (this.indices) {
  32514. meshOrGeometry.setIndices(this.indices, null);
  32515. }
  32516. return this;
  32517. };
  32518. /**
  32519. * Transforms each position and each normal of the vertexData according to the passed Matrix.
  32520. * Returns the VertexData.
  32521. */
  32522. VertexData.prototype.transform = function (matrix) {
  32523. var transformed = BABYLON.Vector3.Zero();
  32524. var index;
  32525. if (this.positions) {
  32526. var position = BABYLON.Vector3.Zero();
  32527. for (index = 0; index < this.positions.length; index += 3) {
  32528. BABYLON.Vector3.FromArrayToRef(this.positions, index, position);
  32529. BABYLON.Vector3.TransformCoordinatesToRef(position, matrix, transformed);
  32530. this.positions[index] = transformed.x;
  32531. this.positions[index + 1] = transformed.y;
  32532. this.positions[index + 2] = transformed.z;
  32533. }
  32534. }
  32535. if (this.normals) {
  32536. var normal = BABYLON.Vector3.Zero();
  32537. for (index = 0; index < this.normals.length; index += 3) {
  32538. BABYLON.Vector3.FromArrayToRef(this.normals, index, normal);
  32539. BABYLON.Vector3.TransformNormalToRef(normal, matrix, transformed);
  32540. this.normals[index] = transformed.x;
  32541. this.normals[index + 1] = transformed.y;
  32542. this.normals[index + 2] = transformed.z;
  32543. }
  32544. }
  32545. if (this.tangents) {
  32546. var tangent = BABYLON.Vector4.Zero();
  32547. var tangentTransformed = BABYLON.Vector4.Zero();
  32548. for (index = 0; index < this.tangents.length; index += 4) {
  32549. BABYLON.Vector4.FromArrayToRef(this.tangents, index, tangent);
  32550. BABYLON.Vector4.TransformNormalToRef(tangent, matrix, tangentTransformed);
  32551. this.tangents[index] = tangentTransformed.x;
  32552. this.tangents[index + 1] = tangentTransformed.y;
  32553. this.tangents[index + 2] = tangentTransformed.z;
  32554. this.tangents[index + 3] = tangentTransformed.w;
  32555. }
  32556. }
  32557. return this;
  32558. };
  32559. /**
  32560. * Merges the passed VertexData into the current one.
  32561. * Returns the modified VertexData.
  32562. */
  32563. VertexData.prototype.merge = function (other) {
  32564. this._validate();
  32565. other._validate();
  32566. if (!this.normals !== !other.normals ||
  32567. !this.tangents !== !other.tangents ||
  32568. !this.uvs !== !other.uvs ||
  32569. !this.uvs2 !== !other.uvs2 ||
  32570. !this.uvs3 !== !other.uvs3 ||
  32571. !this.uvs4 !== !other.uvs4 ||
  32572. !this.uvs5 !== !other.uvs5 ||
  32573. !this.uvs6 !== !other.uvs6 ||
  32574. !this.colors !== !other.colors ||
  32575. !this.matricesIndices !== !other.matricesIndices ||
  32576. !this.matricesWeights !== !other.matricesWeights ||
  32577. !this.matricesIndicesExtra !== !other.matricesIndicesExtra ||
  32578. !this.matricesWeightsExtra !== !other.matricesWeightsExtra) {
  32579. throw new Error("Cannot merge vertex data that do not have the same set of attributes");
  32580. }
  32581. if (other.indices) {
  32582. if (!this.indices) {
  32583. this.indices = [];
  32584. }
  32585. var offset = this.positions ? this.positions.length / 3 : 0;
  32586. for (var index = 0; index < other.indices.length; index++) {
  32587. //TODO check type - if Int32Array | Uint32Array | Uint16Array!
  32588. this.indices.push(other.indices[index] + offset);
  32589. }
  32590. }
  32591. this.positions = this._mergeElement(this.positions, other.positions);
  32592. this.normals = this._mergeElement(this.normals, other.normals);
  32593. this.tangents = this._mergeElement(this.tangents, other.tangents);
  32594. this.uvs = this._mergeElement(this.uvs, other.uvs);
  32595. this.uvs2 = this._mergeElement(this.uvs2, other.uvs2);
  32596. this.uvs3 = this._mergeElement(this.uvs3, other.uvs3);
  32597. this.uvs4 = this._mergeElement(this.uvs4, other.uvs4);
  32598. this.uvs5 = this._mergeElement(this.uvs5, other.uvs5);
  32599. this.uvs6 = this._mergeElement(this.uvs6, other.uvs6);
  32600. this.colors = this._mergeElement(this.colors, other.colors);
  32601. this.matricesIndices = this._mergeElement(this.matricesIndices, other.matricesIndices);
  32602. this.matricesWeights = this._mergeElement(this.matricesWeights, other.matricesWeights);
  32603. this.matricesIndicesExtra = this._mergeElement(this.matricesIndicesExtra, other.matricesIndicesExtra);
  32604. this.matricesWeightsExtra = this._mergeElement(this.matricesWeightsExtra, other.matricesWeightsExtra);
  32605. return this;
  32606. };
  32607. VertexData.prototype._mergeElement = function (source, other) {
  32608. if (!source) {
  32609. return other;
  32610. }
  32611. if (!other) {
  32612. return source;
  32613. }
  32614. var len = other.length + source.length;
  32615. var isSrcTypedArray = source instanceof Float32Array;
  32616. var isOthTypedArray = other instanceof Float32Array;
  32617. // use non-loop method when the source is Float32Array
  32618. if (isSrcTypedArray) {
  32619. var ret32 = new Float32Array(len);
  32620. ret32.set(source);
  32621. ret32.set(other, source.length);
  32622. return ret32;
  32623. // source is number[], when other is also use concat
  32624. }
  32625. else if (!isOthTypedArray) {
  32626. return source.concat(other);
  32627. // source is a number[], but other is a Float32Array, loop required
  32628. }
  32629. else {
  32630. var ret = source.slice(0); // copy source to a separate array
  32631. for (var i = 0, len = other.length; i < len; i++) {
  32632. ret.push(other[i]);
  32633. }
  32634. return ret;
  32635. }
  32636. };
  32637. VertexData.prototype._validate = function () {
  32638. if (!this.positions) {
  32639. throw new Error("Positions are required");
  32640. }
  32641. var getElementCount = function (kind, values) {
  32642. var stride = BABYLON.VertexBuffer.DeduceStride(kind);
  32643. if ((values.length % stride) !== 0) {
  32644. throw new Error("The " + kind + "s array count must be a multiple of " + stride);
  32645. }
  32646. return values.length / stride;
  32647. };
  32648. var positionsElementCount = getElementCount(BABYLON.VertexBuffer.PositionKind, this.positions);
  32649. var validateElementCount = function (kind, values) {
  32650. var elementCount = getElementCount(kind, values);
  32651. if (elementCount !== positionsElementCount) {
  32652. throw new Error("The " + kind + "s element count (" + elementCount + ") does not match the positions count (" + positionsElementCount + ")");
  32653. }
  32654. };
  32655. if (this.normals)
  32656. validateElementCount(BABYLON.VertexBuffer.NormalKind, this.normals);
  32657. if (this.tangents)
  32658. validateElementCount(BABYLON.VertexBuffer.TangentKind, this.tangents);
  32659. if (this.uvs)
  32660. validateElementCount(BABYLON.VertexBuffer.UVKind, this.uvs);
  32661. if (this.uvs2)
  32662. validateElementCount(BABYLON.VertexBuffer.UV2Kind, this.uvs2);
  32663. if (this.uvs3)
  32664. validateElementCount(BABYLON.VertexBuffer.UV3Kind, this.uvs3);
  32665. if (this.uvs4)
  32666. validateElementCount(BABYLON.VertexBuffer.UV4Kind, this.uvs4);
  32667. if (this.uvs5)
  32668. validateElementCount(BABYLON.VertexBuffer.UV5Kind, this.uvs5);
  32669. if (this.uvs6)
  32670. validateElementCount(BABYLON.VertexBuffer.UV6Kind, this.uvs6);
  32671. if (this.colors)
  32672. validateElementCount(BABYLON.VertexBuffer.ColorKind, this.colors);
  32673. if (this.matricesIndices)
  32674. validateElementCount(BABYLON.VertexBuffer.MatricesIndicesKind, this.matricesIndices);
  32675. if (this.matricesWeights)
  32676. validateElementCount(BABYLON.VertexBuffer.MatricesWeightsKind, this.matricesWeights);
  32677. if (this.matricesIndicesExtra)
  32678. validateElementCount(BABYLON.VertexBuffer.MatricesIndicesExtraKind, this.matricesIndicesExtra);
  32679. if (this.matricesWeightsExtra)
  32680. validateElementCount(BABYLON.VertexBuffer.MatricesWeightsExtraKind, this.matricesWeightsExtra);
  32681. };
  32682. /**
  32683. * Serializes the VertexData.
  32684. * Returns a serialized object.
  32685. */
  32686. VertexData.prototype.serialize = function () {
  32687. var serializationObject = this.serialize();
  32688. if (this.positions) {
  32689. serializationObject.positions = this.positions;
  32690. }
  32691. if (this.normals) {
  32692. serializationObject.normals = this.normals;
  32693. }
  32694. if (this.tangents) {
  32695. serializationObject.tangents = this.tangents;
  32696. }
  32697. if (this.uvs) {
  32698. serializationObject.uvs = this.uvs;
  32699. }
  32700. if (this.uvs2) {
  32701. serializationObject.uvs2 = this.uvs2;
  32702. }
  32703. if (this.uvs3) {
  32704. serializationObject.uvs3 = this.uvs3;
  32705. }
  32706. if (this.uvs4) {
  32707. serializationObject.uvs4 = this.uvs4;
  32708. }
  32709. if (this.uvs5) {
  32710. serializationObject.uvs5 = this.uvs5;
  32711. }
  32712. if (this.uvs6) {
  32713. serializationObject.uvs6 = this.uvs6;
  32714. }
  32715. if (this.colors) {
  32716. serializationObject.colors = this.colors;
  32717. }
  32718. if (this.matricesIndices) {
  32719. serializationObject.matricesIndices = this.matricesIndices;
  32720. serializationObject.matricesIndices._isExpanded = true;
  32721. }
  32722. if (this.matricesWeights) {
  32723. serializationObject.matricesWeights = this.matricesWeights;
  32724. }
  32725. if (this.matricesIndicesExtra) {
  32726. serializationObject.matricesIndicesExtra = this.matricesIndicesExtra;
  32727. serializationObject.matricesIndicesExtra._isExpanded = true;
  32728. }
  32729. if (this.matricesWeightsExtra) {
  32730. serializationObject.matricesWeightsExtra = this.matricesWeightsExtra;
  32731. }
  32732. serializationObject.indices = this.indices;
  32733. return serializationObject;
  32734. };
  32735. // Statics
  32736. /**
  32737. * Returns the object VertexData associated to the passed mesh.
  32738. */
  32739. VertexData.ExtractFromMesh = function (mesh, copyWhenShared, forceCopy) {
  32740. return VertexData._ExtractFrom(mesh, copyWhenShared, forceCopy);
  32741. };
  32742. /**
  32743. * Returns the object VertexData associated to the passed geometry.
  32744. */
  32745. VertexData.ExtractFromGeometry = function (geometry, copyWhenShared, forceCopy) {
  32746. return VertexData._ExtractFrom(geometry, copyWhenShared, forceCopy);
  32747. };
  32748. VertexData._ExtractFrom = function (meshOrGeometry, copyWhenShared, forceCopy) {
  32749. var result = new VertexData();
  32750. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  32751. result.positions = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.PositionKind, copyWhenShared, forceCopy);
  32752. }
  32753. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  32754. result.normals = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.NormalKind, copyWhenShared, forceCopy);
  32755. }
  32756. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind)) {
  32757. result.tangents = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.TangentKind, copyWhenShared, forceCopy);
  32758. }
  32759. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  32760. result.uvs = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UVKind, copyWhenShared, forceCopy);
  32761. }
  32762. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  32763. result.uvs2 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV2Kind, copyWhenShared, forceCopy);
  32764. }
  32765. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV3Kind)) {
  32766. result.uvs3 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV3Kind, copyWhenShared, forceCopy);
  32767. }
  32768. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV4Kind)) {
  32769. result.uvs4 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV4Kind, copyWhenShared, forceCopy);
  32770. }
  32771. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV5Kind)) {
  32772. result.uvs5 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV5Kind, copyWhenShared, forceCopy);
  32773. }
  32774. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV6Kind)) {
  32775. result.uvs6 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV6Kind, copyWhenShared, forceCopy);
  32776. }
  32777. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  32778. result.colors = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.ColorKind, copyWhenShared, forceCopy);
  32779. }
  32780. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  32781. result.matricesIndices = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, copyWhenShared, forceCopy);
  32782. }
  32783. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  32784. result.matricesWeights = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, copyWhenShared, forceCopy);
  32785. }
  32786. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesExtraKind)) {
  32787. result.matricesIndicesExtra = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, copyWhenShared, forceCopy);
  32788. }
  32789. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsExtraKind)) {
  32790. result.matricesWeightsExtra = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, copyWhenShared, forceCopy);
  32791. }
  32792. result.indices = meshOrGeometry.getIndices(copyWhenShared);
  32793. return result;
  32794. };
  32795. /**
  32796. * Creates the vertexData of the Ribbon.
  32797. */
  32798. VertexData.CreateRibbon = function (options) {
  32799. var pathArray = options.pathArray;
  32800. var closeArray = options.closeArray || false;
  32801. var closePath = options.closePath || false;
  32802. var invertUV = options.invertUV || false;
  32803. var defaultOffset = Math.floor(pathArray[0].length / 2);
  32804. var offset = options.offset || defaultOffset;
  32805. offset = offset > defaultOffset ? defaultOffset : Math.floor(offset); // offset max allowed : defaultOffset
  32806. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  32807. var customUV = options.uvs;
  32808. var customColors = options.colors;
  32809. var positions = [];
  32810. var indices = [];
  32811. var normals = [];
  32812. var uvs = [];
  32813. var us = []; // us[path_id] = [uDist1, uDist2, uDist3 ... ] distances between points on path path_id
  32814. var vs = []; // vs[i] = [vDist1, vDist2, vDist3, ... ] distances between points i of consecutives paths from pathArray
  32815. var uTotalDistance = []; // uTotalDistance[p] : total distance of path p
  32816. var vTotalDistance = []; // vTotalDistance[i] : total distance between points i of first and last path from pathArray
  32817. var minlg; // minimal length among all paths from pathArray
  32818. var lg = []; // array of path lengths : nb of vertex per path
  32819. var idx = []; // array of path indexes : index of each path (first vertex) in the total vertex number
  32820. var p; // path iterator
  32821. var i; // point iterator
  32822. var j; // point iterator
  32823. // if single path in pathArray
  32824. if (pathArray.length < 2) {
  32825. var ar1 = [];
  32826. var ar2 = [];
  32827. for (i = 0; i < pathArray[0].length - offset; i++) {
  32828. ar1.push(pathArray[0][i]);
  32829. ar2.push(pathArray[0][i + offset]);
  32830. }
  32831. pathArray = [ar1, ar2];
  32832. }
  32833. // positions and horizontal distances (u)
  32834. var idc = 0;
  32835. var closePathCorr = (closePath) ? 1 : 0; // the final index will be +1 if closePath
  32836. var path;
  32837. var l;
  32838. minlg = pathArray[0].length;
  32839. var vectlg;
  32840. var dist;
  32841. for (p = 0; p < pathArray.length; p++) {
  32842. uTotalDistance[p] = 0;
  32843. us[p] = [0];
  32844. path = pathArray[p];
  32845. l = path.length;
  32846. minlg = (minlg < l) ? minlg : l;
  32847. j = 0;
  32848. while (j < l) {
  32849. positions.push(path[j].x, path[j].y, path[j].z);
  32850. if (j > 0) {
  32851. vectlg = path[j].subtract(path[j - 1]).length();
  32852. dist = vectlg + uTotalDistance[p];
  32853. us[p].push(dist);
  32854. uTotalDistance[p] = dist;
  32855. }
  32856. j++;
  32857. }
  32858. if (closePath) {
  32859. j--;
  32860. positions.push(path[0].x, path[0].y, path[0].z);
  32861. vectlg = path[j].subtract(path[0]).length();
  32862. dist = vectlg + uTotalDistance[p];
  32863. us[p].push(dist);
  32864. uTotalDistance[p] = dist;
  32865. }
  32866. lg[p] = l + closePathCorr;
  32867. idx[p] = idc;
  32868. idc += (l + closePathCorr);
  32869. }
  32870. // vertical distances (v)
  32871. var path1;
  32872. var path2;
  32873. var vertex1 = null;
  32874. var vertex2 = null;
  32875. for (i = 0; i < minlg + closePathCorr; i++) {
  32876. vTotalDistance[i] = 0;
  32877. vs[i] = [0];
  32878. for (p = 0; p < pathArray.length - 1; p++) {
  32879. path1 = pathArray[p];
  32880. path2 = pathArray[p + 1];
  32881. if (i === minlg) {
  32882. vertex1 = path1[0];
  32883. vertex2 = path2[0];
  32884. }
  32885. else {
  32886. vertex1 = path1[i];
  32887. vertex2 = path2[i];
  32888. }
  32889. vectlg = vertex2.subtract(vertex1).length();
  32890. dist = vectlg + vTotalDistance[i];
  32891. vs[i].push(dist);
  32892. vTotalDistance[i] = dist;
  32893. }
  32894. if (closeArray && vertex2 && vertex1) {
  32895. path1 = pathArray[p];
  32896. path2 = pathArray[0];
  32897. if (i === minlg) {
  32898. vertex2 = path2[0];
  32899. }
  32900. vectlg = vertex2.subtract(vertex1).length();
  32901. dist = vectlg + vTotalDistance[i];
  32902. vTotalDistance[i] = dist;
  32903. }
  32904. }
  32905. // uvs
  32906. var u;
  32907. var v;
  32908. if (customUV) {
  32909. for (p = 0; p < customUV.length; p++) {
  32910. uvs.push(customUV[p].x, customUV[p].y);
  32911. }
  32912. }
  32913. else {
  32914. for (p = 0; p < pathArray.length; p++) {
  32915. for (i = 0; i < minlg + closePathCorr; i++) {
  32916. u = (uTotalDistance[p] != 0.0) ? us[p][i] / uTotalDistance[p] : 0.0;
  32917. v = (vTotalDistance[i] != 0.0) ? vs[i][p] / vTotalDistance[i] : 0.0;
  32918. if (invertUV) {
  32919. uvs.push(v, u);
  32920. }
  32921. else {
  32922. uvs.push(u, v);
  32923. }
  32924. }
  32925. }
  32926. }
  32927. // indices
  32928. p = 0; // path index
  32929. var pi = 0; // positions array index
  32930. var l1 = lg[p] - 1; // path1 length
  32931. var l2 = lg[p + 1] - 1; // path2 length
  32932. var min = (l1 < l2) ? l1 : l2; // current path stop index
  32933. var shft = idx[1] - idx[0]; // shift
  32934. var path1nb = closeArray ? lg.length : lg.length - 1; // number of path1 to iterate on
  32935. while (pi <= min && p < path1nb) {
  32936. // 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
  32937. indices.push(pi, pi + shft, pi + 1);
  32938. indices.push(pi + shft + 1, pi + 1, pi + shft);
  32939. pi += 1;
  32940. if (pi === min) {
  32941. p++;
  32942. if (p === lg.length - 1) {
  32943. shft = idx[0] - idx[p];
  32944. l1 = lg[p] - 1;
  32945. l2 = lg[0] - 1;
  32946. }
  32947. else {
  32948. shft = idx[p + 1] - idx[p];
  32949. l1 = lg[p] - 1;
  32950. l2 = lg[p + 1] - 1;
  32951. }
  32952. pi = idx[p];
  32953. min = (l1 < l2) ? l1 + pi : l2 + pi;
  32954. }
  32955. }
  32956. // normals
  32957. VertexData.ComputeNormals(positions, indices, normals);
  32958. if (closePath) {
  32959. var indexFirst = 0;
  32960. var indexLast = 0;
  32961. for (p = 0; p < pathArray.length; p++) {
  32962. indexFirst = idx[p] * 3;
  32963. if (p + 1 < pathArray.length) {
  32964. indexLast = (idx[p + 1] - 1) * 3;
  32965. }
  32966. else {
  32967. indexLast = normals.length - 3;
  32968. }
  32969. normals[indexFirst] = (normals[indexFirst] + normals[indexLast]) * 0.5;
  32970. normals[indexFirst + 1] = (normals[indexFirst + 1] + normals[indexLast + 1]) * 0.5;
  32971. normals[indexFirst + 2] = (normals[indexFirst + 2] + normals[indexLast + 2]) * 0.5;
  32972. normals[indexLast] = normals[indexFirst];
  32973. normals[indexLast + 1] = normals[indexFirst + 1];
  32974. normals[indexLast + 2] = normals[indexFirst + 2];
  32975. }
  32976. }
  32977. // sides
  32978. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  32979. // Colors
  32980. var colors = null;
  32981. if (customColors) {
  32982. colors = new Float32Array(customColors.length * 4);
  32983. for (var c = 0; c < customColors.length; c++) {
  32984. colors[c * 4] = customColors[c].r;
  32985. colors[c * 4 + 1] = customColors[c].g;
  32986. colors[c * 4 + 2] = customColors[c].b;
  32987. colors[c * 4 + 3] = customColors[c].a;
  32988. }
  32989. }
  32990. // Result
  32991. var vertexData = new VertexData();
  32992. var positions32 = new Float32Array(positions);
  32993. var normals32 = new Float32Array(normals);
  32994. var uvs32 = new Float32Array(uvs);
  32995. vertexData.indices = indices;
  32996. vertexData.positions = positions32;
  32997. vertexData.normals = normals32;
  32998. vertexData.uvs = uvs32;
  32999. if (colors) {
  33000. vertexData.set(colors, BABYLON.VertexBuffer.ColorKind);
  33001. }
  33002. if (closePath) {
  33003. vertexData._idx = idx;
  33004. }
  33005. return vertexData;
  33006. };
  33007. /**
  33008. * Creates the VertexData of the Box.
  33009. */
  33010. VertexData.CreateBox = function (options) {
  33011. var normalsSource = [
  33012. new BABYLON.Vector3(0, 0, 1),
  33013. new BABYLON.Vector3(0, 0, -1),
  33014. new BABYLON.Vector3(1, 0, 0),
  33015. new BABYLON.Vector3(-1, 0, 0),
  33016. new BABYLON.Vector3(0, 1, 0),
  33017. new BABYLON.Vector3(0, -1, 0)
  33018. ];
  33019. var indices = [];
  33020. var positions = [];
  33021. var normals = [];
  33022. var uvs = [];
  33023. var width = options.width || options.size || 1;
  33024. var height = options.height || options.size || 1;
  33025. var depth = options.depth || options.size || 1;
  33026. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  33027. var faceUV = options.faceUV || new Array(6);
  33028. var faceColors = options.faceColors;
  33029. var colors = [];
  33030. // default face colors and UV if undefined
  33031. for (var f = 0; f < 6; f++) {
  33032. if (faceUV[f] === undefined) {
  33033. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  33034. }
  33035. if (faceColors && faceColors[f] === undefined) {
  33036. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  33037. }
  33038. }
  33039. var scaleVector = new BABYLON.Vector3(width / 2, height / 2, depth / 2);
  33040. // Create each face in turn.
  33041. for (var index = 0; index < normalsSource.length; index++) {
  33042. var normal = normalsSource[index];
  33043. // Get two vectors perpendicular to the face normal and to each other.
  33044. var side1 = new BABYLON.Vector3(normal.y, normal.z, normal.x);
  33045. var side2 = BABYLON.Vector3.Cross(normal, side1);
  33046. // Six indices (two triangles) per face.
  33047. var verticesLength = positions.length / 3;
  33048. indices.push(verticesLength);
  33049. indices.push(verticesLength + 1);
  33050. indices.push(verticesLength + 2);
  33051. indices.push(verticesLength);
  33052. indices.push(verticesLength + 2);
  33053. indices.push(verticesLength + 3);
  33054. // Four vertices per face.
  33055. var vertex = normal.subtract(side1).subtract(side2).multiply(scaleVector);
  33056. positions.push(vertex.x, vertex.y, vertex.z);
  33057. normals.push(normal.x, normal.y, normal.z);
  33058. uvs.push(faceUV[index].z, faceUV[index].w);
  33059. if (faceColors) {
  33060. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  33061. }
  33062. vertex = normal.subtract(side1).add(side2).multiply(scaleVector);
  33063. positions.push(vertex.x, vertex.y, vertex.z);
  33064. normals.push(normal.x, normal.y, normal.z);
  33065. uvs.push(faceUV[index].x, faceUV[index].w);
  33066. if (faceColors) {
  33067. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  33068. }
  33069. vertex = normal.add(side1).add(side2).multiply(scaleVector);
  33070. positions.push(vertex.x, vertex.y, vertex.z);
  33071. normals.push(normal.x, normal.y, normal.z);
  33072. uvs.push(faceUV[index].x, faceUV[index].y);
  33073. if (faceColors) {
  33074. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  33075. }
  33076. vertex = normal.add(side1).subtract(side2).multiply(scaleVector);
  33077. positions.push(vertex.x, vertex.y, vertex.z);
  33078. normals.push(normal.x, normal.y, normal.z);
  33079. uvs.push(faceUV[index].z, faceUV[index].y);
  33080. if (faceColors) {
  33081. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  33082. }
  33083. }
  33084. // sides
  33085. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  33086. // Result
  33087. var vertexData = new VertexData();
  33088. vertexData.indices = indices;
  33089. vertexData.positions = positions;
  33090. vertexData.normals = normals;
  33091. vertexData.uvs = uvs;
  33092. if (faceColors) {
  33093. var totalColors = (sideOrientation === BABYLON.Mesh.DOUBLESIDE) ? colors.concat(colors) : colors;
  33094. vertexData.colors = totalColors;
  33095. }
  33096. return vertexData;
  33097. };
  33098. /**
  33099. * Creates the VertexData of the Sphere.
  33100. */
  33101. VertexData.CreateSphere = function (options) {
  33102. var segments = options.segments || 32;
  33103. var diameterX = options.diameterX || options.diameter || 1;
  33104. var diameterY = options.diameterY || options.diameter || 1;
  33105. var diameterZ = options.diameterZ || options.diameter || 1;
  33106. var arc = options.arc && (options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc || 1.0;
  33107. var slice = options.slice && (options.slice <= 0) ? 1.0 : options.slice || 1.0;
  33108. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  33109. var radius = new BABYLON.Vector3(diameterX / 2, diameterY / 2, diameterZ / 2);
  33110. var totalZRotationSteps = 2 + segments;
  33111. var totalYRotationSteps = 2 * totalZRotationSteps;
  33112. var indices = [];
  33113. var positions = [];
  33114. var normals = [];
  33115. var uvs = [];
  33116. for (var zRotationStep = 0; zRotationStep <= totalZRotationSteps; zRotationStep++) {
  33117. var normalizedZ = zRotationStep / totalZRotationSteps;
  33118. var angleZ = normalizedZ * Math.PI * slice;
  33119. for (var yRotationStep = 0; yRotationStep <= totalYRotationSteps; yRotationStep++) {
  33120. var normalizedY = yRotationStep / totalYRotationSteps;
  33121. var angleY = normalizedY * Math.PI * 2 * arc;
  33122. var rotationZ = BABYLON.Matrix.RotationZ(-angleZ);
  33123. var rotationY = BABYLON.Matrix.RotationY(angleY);
  33124. var afterRotZ = BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.Up(), rotationZ);
  33125. var complete = BABYLON.Vector3.TransformCoordinates(afterRotZ, rotationY);
  33126. var vertex = complete.multiply(radius);
  33127. var normal = complete.divide(radius).normalize();
  33128. positions.push(vertex.x, vertex.y, vertex.z);
  33129. normals.push(normal.x, normal.y, normal.z);
  33130. uvs.push(normalizedY, normalizedZ);
  33131. }
  33132. if (zRotationStep > 0) {
  33133. var verticesCount = positions.length / 3;
  33134. for (var firstIndex = verticesCount - 2 * (totalYRotationSteps + 1); (firstIndex + totalYRotationSteps + 2) < verticesCount; firstIndex++) {
  33135. indices.push((firstIndex));
  33136. indices.push((firstIndex + 1));
  33137. indices.push(firstIndex + totalYRotationSteps + 1);
  33138. indices.push((firstIndex + totalYRotationSteps + 1));
  33139. indices.push((firstIndex + 1));
  33140. indices.push((firstIndex + totalYRotationSteps + 2));
  33141. }
  33142. }
  33143. }
  33144. // Sides
  33145. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  33146. // Result
  33147. var vertexData = new VertexData();
  33148. vertexData.indices = indices;
  33149. vertexData.positions = positions;
  33150. vertexData.normals = normals;
  33151. vertexData.uvs = uvs;
  33152. return vertexData;
  33153. };
  33154. /**
  33155. * Creates the VertexData of the Cylinder or Cone.
  33156. */
  33157. VertexData.CreateCylinder = function (options) {
  33158. var height = options.height || 2;
  33159. var diameterTop = (options.diameterTop === 0) ? 0 : options.diameterTop || options.diameter || 1;
  33160. var diameterBottom = (options.diameterBottom === 0) ? 0 : options.diameterBottom || options.diameter || 1;
  33161. var tessellation = options.tessellation || 24;
  33162. var subdivisions = options.subdivisions || 1;
  33163. var hasRings = options.hasRings ? true : false;
  33164. var enclose = options.enclose ? true : false;
  33165. var arc = options.arc && (options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc || 1.0;
  33166. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  33167. var faceUV = options.faceUV || new Array(3);
  33168. var faceColors = options.faceColors;
  33169. // default face colors and UV if undefined
  33170. var quadNb = (arc !== 1 && enclose) ? 2 : 0;
  33171. var ringNb = (hasRings) ? subdivisions : 1;
  33172. var surfaceNb = 2 + (1 + quadNb) * ringNb;
  33173. var f;
  33174. for (f = 0; f < surfaceNb; f++) {
  33175. if (faceColors && faceColors[f] === undefined) {
  33176. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  33177. }
  33178. }
  33179. for (f = 0; f < surfaceNb; f++) {
  33180. if (faceUV && faceUV[f] === undefined) {
  33181. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  33182. }
  33183. }
  33184. var indices = new Array();
  33185. var positions = new Array();
  33186. var normals = new Array();
  33187. var uvs = new Array();
  33188. var colors = new Array();
  33189. var angle_step = Math.PI * 2 * arc / tessellation;
  33190. var angle;
  33191. var h;
  33192. var radius;
  33193. var tan = (diameterBottom - diameterTop) / 2 / height;
  33194. var ringVertex = BABYLON.Vector3.Zero();
  33195. var ringNormal = BABYLON.Vector3.Zero();
  33196. var ringFirstVertex = BABYLON.Vector3.Zero();
  33197. var ringFirstNormal = BABYLON.Vector3.Zero();
  33198. var quadNormal = BABYLON.Vector3.Zero();
  33199. var Y = BABYLON.Axis.Y;
  33200. // positions, normals, uvs
  33201. var i;
  33202. var j;
  33203. var r;
  33204. var ringIdx = 1;
  33205. var s = 1; // surface index
  33206. var cs = 0;
  33207. var v = 0;
  33208. for (i = 0; i <= subdivisions; i++) {
  33209. h = i / subdivisions;
  33210. radius = (h * (diameterTop - diameterBottom) + diameterBottom) / 2;
  33211. ringIdx = (hasRings && i !== 0 && i !== subdivisions) ? 2 : 1;
  33212. for (r = 0; r < ringIdx; r++) {
  33213. if (hasRings) {
  33214. s += r;
  33215. }
  33216. if (enclose) {
  33217. s += 2 * r;
  33218. }
  33219. for (j = 0; j <= tessellation; j++) {
  33220. angle = j * angle_step;
  33221. // position
  33222. ringVertex.x = Math.cos(-angle) * radius;
  33223. ringVertex.y = -height / 2 + h * height;
  33224. ringVertex.z = Math.sin(-angle) * radius;
  33225. // normal
  33226. if (diameterTop === 0 && i === subdivisions) {
  33227. // if no top cap, reuse former normals
  33228. ringNormal.x = normals[normals.length - (tessellation + 1) * 3];
  33229. ringNormal.y = normals[normals.length - (tessellation + 1) * 3 + 1];
  33230. ringNormal.z = normals[normals.length - (tessellation + 1) * 3 + 2];
  33231. }
  33232. else {
  33233. ringNormal.x = ringVertex.x;
  33234. ringNormal.z = ringVertex.z;
  33235. ringNormal.y = Math.sqrt(ringNormal.x * ringNormal.x + ringNormal.z * ringNormal.z) * tan;
  33236. ringNormal.normalize();
  33237. }
  33238. // keep first ring vertex values for enclose
  33239. if (j === 0) {
  33240. ringFirstVertex.copyFrom(ringVertex);
  33241. ringFirstNormal.copyFrom(ringNormal);
  33242. }
  33243. positions.push(ringVertex.x, ringVertex.y, ringVertex.z);
  33244. normals.push(ringNormal.x, ringNormal.y, ringNormal.z);
  33245. if (hasRings) {
  33246. v = (cs !== s) ? faceUV[s].y : faceUV[s].w;
  33247. }
  33248. else {
  33249. v = faceUV[s].y + (faceUV[s].w - faceUV[s].y) * h;
  33250. }
  33251. uvs.push(faceUV[s].x + (faceUV[s].z - faceUV[s].x) * j / tessellation, v);
  33252. if (faceColors) {
  33253. colors.push(faceColors[s].r, faceColors[s].g, faceColors[s].b, faceColors[s].a);
  33254. }
  33255. }
  33256. // if enclose, add four vertices and their dedicated normals
  33257. if (arc !== 1 && enclose) {
  33258. positions.push(ringVertex.x, ringVertex.y, ringVertex.z);
  33259. positions.push(0, ringVertex.y, 0);
  33260. positions.push(0, ringVertex.y, 0);
  33261. positions.push(ringFirstVertex.x, ringFirstVertex.y, ringFirstVertex.z);
  33262. BABYLON.Vector3.CrossToRef(Y, ringNormal, quadNormal);
  33263. quadNormal.normalize();
  33264. normals.push(quadNormal.x, quadNormal.y, quadNormal.z, quadNormal.x, quadNormal.y, quadNormal.z);
  33265. BABYLON.Vector3.CrossToRef(ringFirstNormal, Y, quadNormal);
  33266. quadNormal.normalize();
  33267. normals.push(quadNormal.x, quadNormal.y, quadNormal.z, quadNormal.x, quadNormal.y, quadNormal.z);
  33268. if (hasRings) {
  33269. v = (cs !== s) ? faceUV[s + 1].y : faceUV[s + 1].w;
  33270. }
  33271. else {
  33272. v = faceUV[s + 1].y + (faceUV[s + 1].w - faceUV[s + 1].y) * h;
  33273. }
  33274. uvs.push(faceUV[s + 1].x, v);
  33275. uvs.push(faceUV[s + 1].z, v);
  33276. if (hasRings) {
  33277. v = (cs !== s) ? faceUV[s + 2].y : faceUV[s + 2].w;
  33278. }
  33279. else {
  33280. v = faceUV[s + 2].y + (faceUV[s + 2].w - faceUV[s + 2].y) * h;
  33281. }
  33282. uvs.push(faceUV[s + 2].x, v);
  33283. uvs.push(faceUV[s + 2].z, v);
  33284. if (faceColors) {
  33285. colors.push(faceColors[s + 1].r, faceColors[s + 1].g, faceColors[s + 1].b, faceColors[s + 1].a);
  33286. colors.push(faceColors[s + 1].r, faceColors[s + 1].g, faceColors[s + 1].b, faceColors[s + 1].a);
  33287. colors.push(faceColors[s + 2].r, faceColors[s + 2].g, faceColors[s + 2].b, faceColors[s + 2].a);
  33288. colors.push(faceColors[s + 2].r, faceColors[s + 2].g, faceColors[s + 2].b, faceColors[s + 2].a);
  33289. }
  33290. }
  33291. if (cs !== s) {
  33292. cs = s;
  33293. }
  33294. }
  33295. }
  33296. // indices
  33297. var e = (arc !== 1 && enclose) ? tessellation + 4 : tessellation; // correction of number of iteration if enclose
  33298. var s;
  33299. i = 0;
  33300. for (s = 0; s < subdivisions; s++) {
  33301. var i0 = 0;
  33302. var i1 = 0;
  33303. var i2 = 0;
  33304. var i3 = 0;
  33305. for (j = 0; j < tessellation; j++) {
  33306. i0 = i * (e + 1) + j;
  33307. i1 = (i + 1) * (e + 1) + j;
  33308. i2 = i * (e + 1) + (j + 1);
  33309. i3 = (i + 1) * (e + 1) + (j + 1);
  33310. indices.push(i0, i1, i2);
  33311. indices.push(i3, i2, i1);
  33312. }
  33313. if (arc !== 1 && enclose) {
  33314. indices.push(i0 + 2, i1 + 2, i2 + 2);
  33315. indices.push(i3 + 2, i2 + 2, i1 + 2);
  33316. indices.push(i0 + 4, i1 + 4, i2 + 4);
  33317. indices.push(i3 + 4, i2 + 4, i1 + 4);
  33318. }
  33319. i = (hasRings) ? (i + 2) : (i + 1);
  33320. }
  33321. // Caps
  33322. var createCylinderCap = function (isTop) {
  33323. var radius = isTop ? diameterTop / 2 : diameterBottom / 2;
  33324. if (radius === 0) {
  33325. return;
  33326. }
  33327. // Cap positions, normals & uvs
  33328. var angle;
  33329. var circleVector;
  33330. var i;
  33331. var u = (isTop) ? faceUV[surfaceNb - 1] : faceUV[0];
  33332. var c = null;
  33333. if (faceColors) {
  33334. c = (isTop) ? faceColors[surfaceNb - 1] : faceColors[0];
  33335. }
  33336. // cap center
  33337. var vbase = positions.length / 3;
  33338. var offset = isTop ? height / 2 : -height / 2;
  33339. var center = new BABYLON.Vector3(0, offset, 0);
  33340. positions.push(center.x, center.y, center.z);
  33341. normals.push(0, isTop ? 1 : -1, 0);
  33342. uvs.push(u.x + (u.z - u.x) * 0.5, u.y + (u.w - u.y) * 0.5);
  33343. if (c) {
  33344. colors.push(c.r, c.g, c.b, c.a);
  33345. }
  33346. var textureScale = new BABYLON.Vector2(0.5, 0.5);
  33347. for (i = 0; i <= tessellation; i++) {
  33348. angle = Math.PI * 2 * i * arc / tessellation;
  33349. var cos = Math.cos(-angle);
  33350. var sin = Math.sin(-angle);
  33351. circleVector = new BABYLON.Vector3(cos * radius, offset, sin * radius);
  33352. var textureCoordinate = new BABYLON.Vector2(cos * textureScale.x + 0.5, sin * textureScale.y + 0.5);
  33353. positions.push(circleVector.x, circleVector.y, circleVector.z);
  33354. normals.push(0, isTop ? 1 : -1, 0);
  33355. uvs.push(u.x + (u.z - u.x) * textureCoordinate.x, u.y + (u.w - u.y) * textureCoordinate.y);
  33356. if (c) {
  33357. colors.push(c.r, c.g, c.b, c.a);
  33358. }
  33359. }
  33360. // Cap indices
  33361. for (i = 0; i < tessellation; i++) {
  33362. if (!isTop) {
  33363. indices.push(vbase);
  33364. indices.push(vbase + (i + 1));
  33365. indices.push(vbase + (i + 2));
  33366. }
  33367. else {
  33368. indices.push(vbase);
  33369. indices.push(vbase + (i + 2));
  33370. indices.push(vbase + (i + 1));
  33371. }
  33372. }
  33373. };
  33374. // add caps to geometry
  33375. createCylinderCap(false);
  33376. createCylinderCap(true);
  33377. // Sides
  33378. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  33379. var vertexData = new VertexData();
  33380. vertexData.indices = indices;
  33381. vertexData.positions = positions;
  33382. vertexData.normals = normals;
  33383. vertexData.uvs = uvs;
  33384. if (faceColors) {
  33385. vertexData.colors = colors;
  33386. }
  33387. return vertexData;
  33388. };
  33389. /**
  33390. * Creates the VertexData of the Torus.
  33391. */
  33392. VertexData.CreateTorus = function (options) {
  33393. var indices = [];
  33394. var positions = [];
  33395. var normals = [];
  33396. var uvs = [];
  33397. var diameter = options.diameter || 1;
  33398. var thickness = options.thickness || 0.5;
  33399. var tessellation = options.tessellation || 16;
  33400. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  33401. var stride = tessellation + 1;
  33402. for (var i = 0; i <= tessellation; i++) {
  33403. var u = i / tessellation;
  33404. var outerAngle = i * Math.PI * 2.0 / tessellation - Math.PI / 2.0;
  33405. var transform = BABYLON.Matrix.Translation(diameter / 2.0, 0, 0).multiply(BABYLON.Matrix.RotationY(outerAngle));
  33406. for (var j = 0; j <= tessellation; j++) {
  33407. var v = 1 - j / tessellation;
  33408. var innerAngle = j * Math.PI * 2.0 / tessellation + Math.PI;
  33409. var dx = Math.cos(innerAngle);
  33410. var dy = Math.sin(innerAngle);
  33411. // Create a vertex.
  33412. var normal = new BABYLON.Vector3(dx, dy, 0);
  33413. var position = normal.scale(thickness / 2);
  33414. var textureCoordinate = new BABYLON.Vector2(u, v);
  33415. position = BABYLON.Vector3.TransformCoordinates(position, transform);
  33416. normal = BABYLON.Vector3.TransformNormal(normal, transform);
  33417. positions.push(position.x, position.y, position.z);
  33418. normals.push(normal.x, normal.y, normal.z);
  33419. uvs.push(textureCoordinate.x, textureCoordinate.y);
  33420. // And create indices for two triangles.
  33421. var nextI = (i + 1) % stride;
  33422. var nextJ = (j + 1) % stride;
  33423. indices.push(i * stride + j);
  33424. indices.push(i * stride + nextJ);
  33425. indices.push(nextI * stride + j);
  33426. indices.push(i * stride + nextJ);
  33427. indices.push(nextI * stride + nextJ);
  33428. indices.push(nextI * stride + j);
  33429. }
  33430. }
  33431. // Sides
  33432. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  33433. // Result
  33434. var vertexData = new VertexData();
  33435. vertexData.indices = indices;
  33436. vertexData.positions = positions;
  33437. vertexData.normals = normals;
  33438. vertexData.uvs = uvs;
  33439. return vertexData;
  33440. };
  33441. /**
  33442. * Creates the VertexData of the LineSystem.
  33443. */
  33444. VertexData.CreateLineSystem = function (options) {
  33445. var indices = [];
  33446. var positions = [];
  33447. var lines = options.lines;
  33448. var colors = options.colors;
  33449. var vertexColors = [];
  33450. var idx = 0;
  33451. for (var l = 0; l < lines.length; l++) {
  33452. var points = lines[l];
  33453. for (var index = 0; index < points.length; index++) {
  33454. positions.push(points[index].x, points[index].y, points[index].z);
  33455. if (colors) {
  33456. var color = colors[l];
  33457. vertexColors.push(color[index].r, color[index].g, color[index].b, color[index].a);
  33458. }
  33459. if (index > 0) {
  33460. indices.push(idx - 1);
  33461. indices.push(idx);
  33462. }
  33463. idx++;
  33464. }
  33465. }
  33466. var vertexData = new VertexData();
  33467. vertexData.indices = indices;
  33468. vertexData.positions = positions;
  33469. if (colors) {
  33470. vertexData.colors = vertexColors;
  33471. }
  33472. return vertexData;
  33473. };
  33474. /**
  33475. * Create the VertexData of the DashedLines.
  33476. */
  33477. VertexData.CreateDashedLines = function (options) {
  33478. var dashSize = options.dashSize || 3;
  33479. var gapSize = options.gapSize || 1;
  33480. var dashNb = options.dashNb || 200;
  33481. var points = options.points;
  33482. var positions = new Array();
  33483. var indices = new Array();
  33484. var curvect = BABYLON.Vector3.Zero();
  33485. var lg = 0;
  33486. var nb = 0;
  33487. var shft = 0;
  33488. var dashshft = 0;
  33489. var curshft = 0;
  33490. var idx = 0;
  33491. var i = 0;
  33492. for (i = 0; i < points.length - 1; i++) {
  33493. points[i + 1].subtractToRef(points[i], curvect);
  33494. lg += curvect.length();
  33495. }
  33496. shft = lg / dashNb;
  33497. dashshft = dashSize * shft / (dashSize + gapSize);
  33498. for (i = 0; i < points.length - 1; i++) {
  33499. points[i + 1].subtractToRef(points[i], curvect);
  33500. nb = Math.floor(curvect.length() / shft);
  33501. curvect.normalize();
  33502. for (var j = 0; j < nb; j++) {
  33503. curshft = shft * j;
  33504. positions.push(points[i].x + curshft * curvect.x, points[i].y + curshft * curvect.y, points[i].z + curshft * curvect.z);
  33505. positions.push(points[i].x + (curshft + dashshft) * curvect.x, points[i].y + (curshft + dashshft) * curvect.y, points[i].z + (curshft + dashshft) * curvect.z);
  33506. indices.push(idx, idx + 1);
  33507. idx += 2;
  33508. }
  33509. }
  33510. // Result
  33511. var vertexData = new VertexData();
  33512. vertexData.positions = positions;
  33513. vertexData.indices = indices;
  33514. return vertexData;
  33515. };
  33516. /**
  33517. * Creates the VertexData of the Ground.
  33518. */
  33519. VertexData.CreateGround = function (options) {
  33520. var indices = [];
  33521. var positions = [];
  33522. var normals = [];
  33523. var uvs = [];
  33524. var row, col;
  33525. var width = options.width || 1;
  33526. var height = options.height || 1;
  33527. var subdivisionsX = options.subdivisionsX || options.subdivisions || 1;
  33528. var subdivisionsY = options.subdivisionsY || options.subdivisions || 1;
  33529. for (row = 0; row <= subdivisionsY; row++) {
  33530. for (col = 0; col <= subdivisionsX; col++) {
  33531. var position = new BABYLON.Vector3((col * width) / subdivisionsX - (width / 2.0), 0, ((subdivisionsY - row) * height) / subdivisionsY - (height / 2.0));
  33532. var normal = new BABYLON.Vector3(0, 1.0, 0);
  33533. positions.push(position.x, position.y, position.z);
  33534. normals.push(normal.x, normal.y, normal.z);
  33535. uvs.push(col / subdivisionsX, 1.0 - row / subdivisionsY);
  33536. }
  33537. }
  33538. for (row = 0; row < subdivisionsY; row++) {
  33539. for (col = 0; col < subdivisionsX; col++) {
  33540. indices.push(col + 1 + (row + 1) * (subdivisionsX + 1));
  33541. indices.push(col + 1 + row * (subdivisionsX + 1));
  33542. indices.push(col + row * (subdivisionsX + 1));
  33543. indices.push(col + (row + 1) * (subdivisionsX + 1));
  33544. indices.push(col + 1 + (row + 1) * (subdivisionsX + 1));
  33545. indices.push(col + row * (subdivisionsX + 1));
  33546. }
  33547. }
  33548. // Result
  33549. var vertexData = new VertexData();
  33550. vertexData.indices = indices;
  33551. vertexData.positions = positions;
  33552. vertexData.normals = normals;
  33553. vertexData.uvs = uvs;
  33554. return vertexData;
  33555. };
  33556. /**
  33557. * Creates the VertexData of the TiledGround.
  33558. */
  33559. VertexData.CreateTiledGround = function (options) {
  33560. var xmin = (options.xmin !== undefined && options.xmin !== null) ? options.xmin : -1.0;
  33561. var zmin = (options.zmin !== undefined && options.zmin !== null) ? options.zmin : -1.0;
  33562. var xmax = (options.xmax !== undefined && options.xmax !== null) ? options.xmax : 1.0;
  33563. var zmax = (options.zmax !== undefined && options.zmax !== null) ? options.zmax : 1.0;
  33564. var subdivisions = options.subdivisions || { w: 1, h: 1 };
  33565. var precision = options.precision || { w: 1, h: 1 };
  33566. var indices = new Array();
  33567. var positions = new Array();
  33568. var normals = new Array();
  33569. var uvs = new Array();
  33570. var row, col, tileRow, tileCol;
  33571. subdivisions.h = (subdivisions.h < 1) ? 1 : subdivisions.h;
  33572. subdivisions.w = (subdivisions.w < 1) ? 1 : subdivisions.w;
  33573. precision.w = (precision.w < 1) ? 1 : precision.w;
  33574. precision.h = (precision.h < 1) ? 1 : precision.h;
  33575. var tileSize = {
  33576. 'w': (xmax - xmin) / subdivisions.w,
  33577. 'h': (zmax - zmin) / subdivisions.h
  33578. };
  33579. function applyTile(xTileMin, zTileMin, xTileMax, zTileMax) {
  33580. // Indices
  33581. var base = positions.length / 3;
  33582. var rowLength = precision.w + 1;
  33583. for (row = 0; row < precision.h; row++) {
  33584. for (col = 0; col < precision.w; col++) {
  33585. var square = [
  33586. base + col + row * rowLength,
  33587. base + (col + 1) + row * rowLength,
  33588. base + (col + 1) + (row + 1) * rowLength,
  33589. base + col + (row + 1) * rowLength
  33590. ];
  33591. indices.push(square[1]);
  33592. indices.push(square[2]);
  33593. indices.push(square[3]);
  33594. indices.push(square[0]);
  33595. indices.push(square[1]);
  33596. indices.push(square[3]);
  33597. }
  33598. }
  33599. // Position, normals and uvs
  33600. var position = BABYLON.Vector3.Zero();
  33601. var normal = new BABYLON.Vector3(0, 1.0, 0);
  33602. for (row = 0; row <= precision.h; row++) {
  33603. position.z = (row * (zTileMax - zTileMin)) / precision.h + zTileMin;
  33604. for (col = 0; col <= precision.w; col++) {
  33605. position.x = (col * (xTileMax - xTileMin)) / precision.w + xTileMin;
  33606. position.y = 0;
  33607. positions.push(position.x, position.y, position.z);
  33608. normals.push(normal.x, normal.y, normal.z);
  33609. uvs.push(col / precision.w, row / precision.h);
  33610. }
  33611. }
  33612. }
  33613. for (tileRow = 0; tileRow < subdivisions.h; tileRow++) {
  33614. for (tileCol = 0; tileCol < subdivisions.w; tileCol++) {
  33615. applyTile(xmin + tileCol * tileSize.w, zmin + tileRow * tileSize.h, xmin + (tileCol + 1) * tileSize.w, zmin + (tileRow + 1) * tileSize.h);
  33616. }
  33617. }
  33618. // Result
  33619. var vertexData = new VertexData();
  33620. vertexData.indices = indices;
  33621. vertexData.positions = positions;
  33622. vertexData.normals = normals;
  33623. vertexData.uvs = uvs;
  33624. return vertexData;
  33625. };
  33626. /**
  33627. * Creates the VertexData of the Ground designed from a heightmap.
  33628. */
  33629. VertexData.CreateGroundFromHeightMap = function (options) {
  33630. var indices = [];
  33631. var positions = [];
  33632. var normals = [];
  33633. var uvs = [];
  33634. var row, col;
  33635. var filter = options.colorFilter || new BABYLON.Color3(0.3, 0.59, 0.11);
  33636. // Vertices
  33637. for (row = 0; row <= options.subdivisions; row++) {
  33638. for (col = 0; col <= options.subdivisions; col++) {
  33639. 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));
  33640. // Compute height
  33641. var heightMapX = (((position.x + options.width / 2) / options.width) * (options.bufferWidth - 1)) | 0;
  33642. var heightMapY = ((1.0 - (position.z + options.height / 2) / options.height) * (options.bufferHeight - 1)) | 0;
  33643. var pos = (heightMapX + heightMapY * options.bufferWidth) * 4;
  33644. var r = options.buffer[pos] / 255.0;
  33645. var g = options.buffer[pos + 1] / 255.0;
  33646. var b = options.buffer[pos + 2] / 255.0;
  33647. var gradient = r * filter.r + g * filter.g + b * filter.b;
  33648. position.y = options.minHeight + (options.maxHeight - options.minHeight) * gradient;
  33649. // Add vertex
  33650. positions.push(position.x, position.y, position.z);
  33651. normals.push(0, 0, 0);
  33652. uvs.push(col / options.subdivisions, 1.0 - row / options.subdivisions);
  33653. }
  33654. }
  33655. // Indices
  33656. for (row = 0; row < options.subdivisions; row++) {
  33657. for (col = 0; col < options.subdivisions; col++) {
  33658. indices.push(col + 1 + (row + 1) * (options.subdivisions + 1));
  33659. indices.push(col + 1 + row * (options.subdivisions + 1));
  33660. indices.push(col + row * (options.subdivisions + 1));
  33661. indices.push(col + (row + 1) * (options.subdivisions + 1));
  33662. indices.push(col + 1 + (row + 1) * (options.subdivisions + 1));
  33663. indices.push(col + row * (options.subdivisions + 1));
  33664. }
  33665. }
  33666. // Normals
  33667. VertexData.ComputeNormals(positions, indices, normals);
  33668. // Result
  33669. var vertexData = new VertexData();
  33670. vertexData.indices = indices;
  33671. vertexData.positions = positions;
  33672. vertexData.normals = normals;
  33673. vertexData.uvs = uvs;
  33674. return vertexData;
  33675. };
  33676. /**
  33677. * Creates the VertexData of the Plane.
  33678. */
  33679. VertexData.CreatePlane = function (options) {
  33680. var indices = [];
  33681. var positions = [];
  33682. var normals = [];
  33683. var uvs = [];
  33684. var width = options.width || options.size || 1;
  33685. var height = options.height || options.size || 1;
  33686. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  33687. // Vertices
  33688. var halfWidth = width / 2.0;
  33689. var halfHeight = height / 2.0;
  33690. positions.push(-halfWidth, -halfHeight, 0);
  33691. normals.push(0, 0, -1.0);
  33692. uvs.push(0.0, 0.0);
  33693. positions.push(halfWidth, -halfHeight, 0);
  33694. normals.push(0, 0, -1.0);
  33695. uvs.push(1.0, 0.0);
  33696. positions.push(halfWidth, halfHeight, 0);
  33697. normals.push(0, 0, -1.0);
  33698. uvs.push(1.0, 1.0);
  33699. positions.push(-halfWidth, halfHeight, 0);
  33700. normals.push(0, 0, -1.0);
  33701. uvs.push(0.0, 1.0);
  33702. // Indices
  33703. indices.push(0);
  33704. indices.push(1);
  33705. indices.push(2);
  33706. indices.push(0);
  33707. indices.push(2);
  33708. indices.push(3);
  33709. // Sides
  33710. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  33711. // Result
  33712. var vertexData = new VertexData();
  33713. vertexData.indices = indices;
  33714. vertexData.positions = positions;
  33715. vertexData.normals = normals;
  33716. vertexData.uvs = uvs;
  33717. return vertexData;
  33718. };
  33719. /**
  33720. * Creates the VertexData of the Disc or regular Polygon.
  33721. */
  33722. VertexData.CreateDisc = function (options) {
  33723. var positions = new Array();
  33724. var indices = new Array();
  33725. var normals = new Array();
  33726. var uvs = new Array();
  33727. var radius = options.radius || 0.5;
  33728. var tessellation = options.tessellation || 64;
  33729. var arc = options.arc && (options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc || 1.0;
  33730. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  33731. // positions and uvs
  33732. positions.push(0, 0, 0); // disc center first
  33733. uvs.push(0.5, 0.5);
  33734. var theta = Math.PI * 2 * arc;
  33735. var step = theta / tessellation;
  33736. for (var a = 0; a < theta; a += step) {
  33737. var x = Math.cos(a);
  33738. var y = Math.sin(a);
  33739. var u = (x + 1) / 2;
  33740. var v = (1 - y) / 2;
  33741. positions.push(radius * x, radius * y, 0);
  33742. uvs.push(u, v);
  33743. }
  33744. if (arc === 1) {
  33745. positions.push(positions[3], positions[4], positions[5]); // close the circle
  33746. uvs.push(uvs[2], uvs[3]);
  33747. }
  33748. //indices
  33749. var vertexNb = positions.length / 3;
  33750. for (var i = 1; i < vertexNb - 1; i++) {
  33751. indices.push(i + 1, 0, i);
  33752. }
  33753. // result
  33754. VertexData.ComputeNormals(positions, indices, normals);
  33755. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  33756. var vertexData = new VertexData();
  33757. vertexData.indices = indices;
  33758. vertexData.positions = positions;
  33759. vertexData.normals = normals;
  33760. vertexData.uvs = uvs;
  33761. return vertexData;
  33762. };
  33763. /**
  33764. * Re-creates the VertexData of the Polygon for sideOrientation.
  33765. */
  33766. VertexData.CreatePolygon = function (polygon, sideOrientation, fUV, fColors, frontUVs, backUVs) {
  33767. var faceUV = fUV || new Array(3);
  33768. var faceColors = fColors;
  33769. var colors = [];
  33770. // default face colors and UV if undefined
  33771. for (var f = 0; f < 3; f++) {
  33772. if (faceUV[f] === undefined) {
  33773. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  33774. }
  33775. if (faceColors && faceColors[f] === undefined) {
  33776. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  33777. }
  33778. }
  33779. var positions = polygon.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  33780. var normals = polygon.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  33781. var uvs = polygon.getVerticesData(BABYLON.VertexBuffer.UVKind);
  33782. var indices = polygon.getIndices();
  33783. // set face colours and textures
  33784. var idx = 0;
  33785. var face = 0;
  33786. for (var index = 0; index < normals.length; index += 3) {
  33787. //Edge Face no. 1
  33788. if (Math.abs(normals[index + 1]) < 0.001) {
  33789. face = 1;
  33790. }
  33791. //Top Face no. 0
  33792. if (Math.abs(normals[index + 1] - 1) < 0.001) {
  33793. face = 0;
  33794. }
  33795. //Bottom Face no. 2
  33796. if (Math.abs(normals[index + 1] + 1) < 0.001) {
  33797. face = 2;
  33798. }
  33799. idx = index / 3;
  33800. uvs[2 * idx] = (1 - uvs[2 * idx]) * faceUV[face].x + uvs[2 * idx] * faceUV[face].z;
  33801. uvs[2 * idx + 1] = (1 - uvs[2 * idx + 1]) * faceUV[face].y + uvs[2 * idx + 1] * faceUV[face].w;
  33802. if (faceColors) {
  33803. colors.push(faceColors[face].r, faceColors[face].g, faceColors[face].b, faceColors[face].a);
  33804. }
  33805. }
  33806. // sides
  33807. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, frontUVs, backUVs);
  33808. // Result
  33809. var vertexData = new VertexData();
  33810. vertexData.indices = indices;
  33811. vertexData.positions = positions;
  33812. vertexData.normals = normals;
  33813. vertexData.uvs = uvs;
  33814. if (faceColors) {
  33815. var totalColors = (sideOrientation === BABYLON.Mesh.DOUBLESIDE) ? colors.concat(colors) : colors;
  33816. vertexData.colors = totalColors;
  33817. }
  33818. return vertexData;
  33819. };
  33820. /**
  33821. * Creates the VertexData of the IcoSphere.
  33822. */
  33823. VertexData.CreateIcoSphere = function (options) {
  33824. var sideOrientation = options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  33825. var radius = options.radius || 1;
  33826. var flat = (options.flat === undefined) ? true : options.flat;
  33827. var subdivisions = options.subdivisions || 4;
  33828. var radiusX = options.radiusX || radius;
  33829. var radiusY = options.radiusY || radius;
  33830. var radiusZ = options.radiusZ || radius;
  33831. var t = (1 + Math.sqrt(5)) / 2;
  33832. // 12 vertex x,y,z
  33833. var ico_vertices = [
  33834. -1, t, -0, 1, t, 0, -1, -t, 0, 1, -t, 0,
  33835. 0, -1, -t, 0, 1, -t, 0, -1, t, 0, 1, t,
  33836. t, 0, 1, t, 0, -1, -t, 0, 1, -t, 0, -1 // v8-11
  33837. ];
  33838. // index of 3 vertex makes a face of icopshere
  33839. var ico_indices = [
  33840. 0, 11, 5, 0, 5, 1, 0, 1, 7, 0, 7, 10, 12, 22, 23,
  33841. 1, 5, 20, 5, 11, 4, 23, 22, 13, 22, 18, 6, 7, 1, 8,
  33842. 14, 21, 4, 14, 4, 2, 16, 13, 6, 15, 6, 19, 3, 8, 9,
  33843. 4, 21, 5, 13, 17, 23, 6, 13, 22, 19, 6, 18, 9, 8, 1
  33844. ];
  33845. // vertex for uv have aliased position, not for UV
  33846. var vertices_unalias_id = [
  33847. 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11,
  33848. // vertex alias
  33849. 0,
  33850. 2,
  33851. 3,
  33852. 3,
  33853. 3,
  33854. 4,
  33855. 7,
  33856. 8,
  33857. 9,
  33858. 9,
  33859. 10,
  33860. 11 // 23: B + 12
  33861. ];
  33862. // uv as integer step (not pixels !)
  33863. var ico_vertexuv = [
  33864. 5, 1, 3, 1, 6, 4, 0, 0,
  33865. 5, 3, 4, 2, 2, 2, 4, 0,
  33866. 2, 0, 1, 1, 6, 0, 6, 2,
  33867. // vertex alias (for same vertex on different faces)
  33868. 0, 4,
  33869. 3, 3,
  33870. 4, 4,
  33871. 3, 1,
  33872. 4, 2,
  33873. 4, 4,
  33874. 0, 2,
  33875. 1, 1,
  33876. 2, 2,
  33877. 3, 3,
  33878. 1, 3,
  33879. 2, 4 // 23: B + 12
  33880. ];
  33881. // Vertices[0, 1, ...9, A, B] : position on UV plane
  33882. // '+' indicate duplicate position to be fixed (3,9:0,2,3,4,7,8,A,B)
  33883. // First island of uv mapping
  33884. // v = 4h 3+ 2
  33885. // v = 3h 9+ 4
  33886. // v = 2h 9+ 5 B
  33887. // v = 1h 9 1 0
  33888. // v = 0h 3 8 7 A
  33889. // u = 0 1 2 3 4 5 6 *a
  33890. // Second island of uv mapping
  33891. // v = 4h 0+ B+ 4+
  33892. // v = 3h A+ 2+
  33893. // v = 2h 7+ 6 3+
  33894. // v = 1h 8+ 3+
  33895. // v = 0h
  33896. // u = 0 1 2 3 4 5 6 *a
  33897. // Face layout on texture UV mapping
  33898. // ============
  33899. // \ 4 /\ 16 / ======
  33900. // \ / \ / /\ 11 /
  33901. // \/ 7 \/ / \ /
  33902. // ======= / 10 \/
  33903. // /\ 17 /\ =======
  33904. // / \ / \ \ 15 /\
  33905. // / 8 \/ 12 \ \ / \
  33906. // ============ \/ 6 \
  33907. // \ 18 /\ ============
  33908. // \ / \ \ 5 /\ 0 /
  33909. // \/ 13 \ \ / \ /
  33910. // ======= \/ 1 \/
  33911. // =============
  33912. // /\ 19 /\ 2 /\
  33913. // / \ / \ / \
  33914. // / 14 \/ 9 \/ 3 \
  33915. // ===================
  33916. // uv step is u:1 or 0.5, v:cos(30)=sqrt(3)/2, ratio approx is 84/97
  33917. var ustep = 138 / 1024;
  33918. var vstep = 239 / 1024;
  33919. var uoffset = 60 / 1024;
  33920. var voffset = 26 / 1024;
  33921. // Second island should have margin, not to touch the first island
  33922. // avoid any borderline artefact in pixel rounding
  33923. var island_u_offset = -40 / 1024;
  33924. var island_v_offset = +20 / 1024;
  33925. // face is either island 0 or 1 :
  33926. // second island is for faces : [4, 7, 8, 12, 13, 16, 17, 18]
  33927. var island = [
  33928. 0, 0, 0, 0, 1,
  33929. 0, 0, 1, 1, 0,
  33930. 0, 0, 1, 1, 0,
  33931. 0, 1, 1, 1, 0 // 15 - 19
  33932. ];
  33933. var indices = new Array();
  33934. var positions = new Array();
  33935. var normals = new Array();
  33936. var uvs = new Array();
  33937. var current_indice = 0;
  33938. // prepare array of 3 vector (empty) (to be worked in place, shared for each face)
  33939. var face_vertex_pos = new Array(3);
  33940. var face_vertex_uv = new Array(3);
  33941. var v012;
  33942. for (v012 = 0; v012 < 3; v012++) {
  33943. face_vertex_pos[v012] = BABYLON.Vector3.Zero();
  33944. face_vertex_uv[v012] = BABYLON.Vector2.Zero();
  33945. }
  33946. // create all with normals
  33947. for (var face = 0; face < 20; face++) {
  33948. // 3 vertex per face
  33949. for (v012 = 0; v012 < 3; v012++) {
  33950. // look up vertex 0,1,2 to its index in 0 to 11 (or 23 including alias)
  33951. var v_id = ico_indices[3 * face + v012];
  33952. // vertex have 3D position (x,y,z)
  33953. 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]);
  33954. // Normalize to get normal, then scale to radius
  33955. face_vertex_pos[v012].normalize().scaleInPlace(radius);
  33956. // uv Coordinates from vertex ID
  33957. 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);
  33958. }
  33959. // Subdivide the face (interpolate pos, norm, uv)
  33960. // - pos is linear interpolation, then projected to sphere (converge polyhedron to sphere)
  33961. // - norm is linear interpolation of vertex corner normal
  33962. // (to be checked if better to re-calc from face vertex, or if approximation is OK ??? )
  33963. // - uv is linear interpolation
  33964. //
  33965. // Topology is as below for sub-divide by 2
  33966. // vertex shown as v0,v1,v2
  33967. // interp index is i1 to progress in range [v0,v1[
  33968. // interp index is i2 to progress in range [v0,v2[
  33969. // face index as (i1,i2) for /\ : (i1,i2),(i1+1,i2),(i1,i2+1)
  33970. // and (i1,i2)' for \/ : (i1+1,i2),(i1+1,i2+1),(i1,i2+1)
  33971. //
  33972. //
  33973. // i2 v2
  33974. // ^ ^
  33975. // / / \
  33976. // / / \
  33977. // / / \
  33978. // / / (0,1) \
  33979. // / #---------\
  33980. // / / \ (0,0)'/ \
  33981. // / / \ / \
  33982. // / / \ / \
  33983. // / / (0,0) \ / (1,0) \
  33984. // / #---------#---------\
  33985. // v0 v1
  33986. //
  33987. // --------------------> i1
  33988. //
  33989. // interp of (i1,i2):
  33990. // along i2 : x0=lerp(v0,v2, i2/S) <---> x1=lerp(v1,v2, i2/S)
  33991. // along i1 : lerp(x0,x1, i1/(S-i2))
  33992. //
  33993. // centroid of triangle is needed to get help normal computation
  33994. // (c1,c2) are used for centroid location
  33995. var interp_vertex = function (i1, i2, c1, c2) {
  33996. // vertex is interpolated from
  33997. // - face_vertex_pos[0..2]
  33998. // - face_vertex_uv[0..2]
  33999. var pos_x0 = BABYLON.Vector3.Lerp(face_vertex_pos[0], face_vertex_pos[2], i2 / subdivisions);
  34000. var pos_x1 = BABYLON.Vector3.Lerp(face_vertex_pos[1], face_vertex_pos[2], i2 / subdivisions);
  34001. var pos_interp = (subdivisions === i2) ? face_vertex_pos[2] : BABYLON.Vector3.Lerp(pos_x0, pos_x1, i1 / (subdivisions - i2));
  34002. pos_interp.normalize();
  34003. var vertex_normal;
  34004. if (flat) {
  34005. // in flat mode, recalculate normal as face centroid normal
  34006. var centroid_x0 = BABYLON.Vector3.Lerp(face_vertex_pos[0], face_vertex_pos[2], c2 / subdivisions);
  34007. var centroid_x1 = BABYLON.Vector3.Lerp(face_vertex_pos[1], face_vertex_pos[2], c2 / subdivisions);
  34008. vertex_normal = BABYLON.Vector3.Lerp(centroid_x0, centroid_x1, c1 / (subdivisions - c2));
  34009. }
  34010. else {
  34011. // in smooth mode, recalculate normal from each single vertex position
  34012. vertex_normal = new BABYLON.Vector3(pos_interp.x, pos_interp.y, pos_interp.z);
  34013. }
  34014. // Vertex normal need correction due to X,Y,Z radius scaling
  34015. vertex_normal.x /= radiusX;
  34016. vertex_normal.y /= radiusY;
  34017. vertex_normal.z /= radiusZ;
  34018. vertex_normal.normalize();
  34019. var uv_x0 = BABYLON.Vector2.Lerp(face_vertex_uv[0], face_vertex_uv[2], i2 / subdivisions);
  34020. var uv_x1 = BABYLON.Vector2.Lerp(face_vertex_uv[1], face_vertex_uv[2], i2 / subdivisions);
  34021. var uv_interp = (subdivisions === i2) ? face_vertex_uv[2] : BABYLON.Vector2.Lerp(uv_x0, uv_x1, i1 / (subdivisions - i2));
  34022. positions.push(pos_interp.x * radiusX, pos_interp.y * radiusY, pos_interp.z * radiusZ);
  34023. normals.push(vertex_normal.x, vertex_normal.y, vertex_normal.z);
  34024. uvs.push(uv_interp.x, uv_interp.y);
  34025. // push each vertex has member of a face
  34026. // Same vertex can bleong to multiple face, it is pushed multiple time (duplicate vertex are present)
  34027. indices.push(current_indice);
  34028. current_indice++;
  34029. };
  34030. for (var i2 = 0; i2 < subdivisions; i2++) {
  34031. for (var i1 = 0; i1 + i2 < subdivisions; i1++) {
  34032. // face : (i1,i2) for /\ :
  34033. // interp for : (i1,i2),(i1+1,i2),(i1,i2+1)
  34034. interp_vertex(i1, i2, i1 + 1.0 / 3, i2 + 1.0 / 3);
  34035. interp_vertex(i1 + 1, i2, i1 + 1.0 / 3, i2 + 1.0 / 3);
  34036. interp_vertex(i1, i2 + 1, i1 + 1.0 / 3, i2 + 1.0 / 3);
  34037. if (i1 + i2 + 1 < subdivisions) {
  34038. // face : (i1,i2)' for \/ :
  34039. // interp for (i1+1,i2),(i1+1,i2+1),(i1,i2+1)
  34040. interp_vertex(i1 + 1, i2, i1 + 2.0 / 3, i2 + 2.0 / 3);
  34041. interp_vertex(i1 + 1, i2 + 1, i1 + 2.0 / 3, i2 + 2.0 / 3);
  34042. interp_vertex(i1, i2 + 1, i1 + 2.0 / 3, i2 + 2.0 / 3);
  34043. }
  34044. }
  34045. }
  34046. }
  34047. // Sides
  34048. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  34049. // Result
  34050. var vertexData = new VertexData();
  34051. vertexData.indices = indices;
  34052. vertexData.positions = positions;
  34053. vertexData.normals = normals;
  34054. vertexData.uvs = uvs;
  34055. return vertexData;
  34056. };
  34057. // inspired from // http://stemkoski.github.io/Three.js/Polyhedra.html
  34058. /**
  34059. * Creates the VertexData of the Polyhedron.
  34060. */
  34061. VertexData.CreatePolyhedron = function (options) {
  34062. // provided polyhedron types :
  34063. // 0 : Tetrahedron, 1 : Octahedron, 2 : Dodecahedron, 3 : Icosahedron, 4 : Rhombicuboctahedron, 5 : Triangular Prism, 6 : Pentagonal Prism, 7 : Hexagonal Prism, 8 : Square Pyramid (J1)
  34064. // 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)
  34065. var polyhedra = [];
  34066. 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]] };
  34067. 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]] };
  34068. polyhedra[2] = {
  34069. 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]],
  34070. 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]]
  34071. };
  34072. polyhedra[3] = {
  34073. 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]],
  34074. 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]]
  34075. };
  34076. polyhedra[4] = {
  34077. 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]],
  34078. 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]]
  34079. };
  34080. 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]] };
  34081. 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]] };
  34082. 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]] };
  34083. 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]] };
  34084. 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]] };
  34085. 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]] };
  34086. 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]] };
  34087. 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]] };
  34088. 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]] };
  34089. polyhedra[14] = {
  34090. 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]],
  34091. 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]]
  34092. };
  34093. var type = options.type && (options.type < 0 || options.type >= polyhedra.length) ? 0 : options.type || 0;
  34094. var size = options.size;
  34095. var sizeX = options.sizeX || size || 1;
  34096. var sizeY = options.sizeY || size || 1;
  34097. var sizeZ = options.sizeZ || size || 1;
  34098. var data = options.custom || polyhedra[type];
  34099. var nbfaces = data.face.length;
  34100. var faceUV = options.faceUV || new Array(nbfaces);
  34101. var faceColors = options.faceColors;
  34102. var flat = (options.flat === undefined) ? true : options.flat;
  34103. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  34104. var positions = new Array();
  34105. var indices = new Array();
  34106. var normals = new Array();
  34107. var uvs = new Array();
  34108. var colors = new Array();
  34109. var index = 0;
  34110. var faceIdx = 0; // face cursor in the array "indexes"
  34111. var indexes = new Array();
  34112. var i = 0;
  34113. var f = 0;
  34114. var u, v, ang, x, y, tmp;
  34115. // default face colors and UV if undefined
  34116. if (flat) {
  34117. for (f = 0; f < nbfaces; f++) {
  34118. if (faceColors && faceColors[f] === undefined) {
  34119. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  34120. }
  34121. if (faceUV && faceUV[f] === undefined) {
  34122. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  34123. }
  34124. }
  34125. }
  34126. if (!flat) {
  34127. for (i = 0; i < data.vertex.length; i++) {
  34128. positions.push(data.vertex[i][0] * sizeX, data.vertex[i][1] * sizeY, data.vertex[i][2] * sizeZ);
  34129. uvs.push(0, 0);
  34130. }
  34131. for (f = 0; f < nbfaces; f++) {
  34132. for (i = 0; i < data.face[f].length - 2; i++) {
  34133. indices.push(data.face[f][0], data.face[f][i + 2], data.face[f][i + 1]);
  34134. }
  34135. }
  34136. }
  34137. else {
  34138. for (f = 0; f < nbfaces; f++) {
  34139. var fl = data.face[f].length; // number of vertices of the current face
  34140. ang = 2 * Math.PI / fl;
  34141. x = 0.5 * Math.tan(ang / 2);
  34142. y = 0.5;
  34143. // positions, uvs, colors
  34144. for (i = 0; i < fl; i++) {
  34145. // positions
  34146. 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);
  34147. indexes.push(index);
  34148. index++;
  34149. // uvs
  34150. u = faceUV[f].x + (faceUV[f].z - faceUV[f].x) * (0.5 + x);
  34151. v = faceUV[f].y + (faceUV[f].w - faceUV[f].y) * (y - 0.5);
  34152. uvs.push(u, v);
  34153. tmp = x * Math.cos(ang) - y * Math.sin(ang);
  34154. y = x * Math.sin(ang) + y * Math.cos(ang);
  34155. x = tmp;
  34156. // colors
  34157. if (faceColors) {
  34158. colors.push(faceColors[f].r, faceColors[f].g, faceColors[f].b, faceColors[f].a);
  34159. }
  34160. }
  34161. // indices from indexes
  34162. for (i = 0; i < fl - 2; i++) {
  34163. indices.push(indexes[0 + faceIdx], indexes[i + 2 + faceIdx], indexes[i + 1 + faceIdx]);
  34164. }
  34165. faceIdx += fl;
  34166. }
  34167. }
  34168. VertexData.ComputeNormals(positions, indices, normals);
  34169. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  34170. var vertexData = new VertexData();
  34171. vertexData.positions = positions;
  34172. vertexData.indices = indices;
  34173. vertexData.normals = normals;
  34174. vertexData.uvs = uvs;
  34175. if (faceColors && flat) {
  34176. vertexData.colors = colors;
  34177. }
  34178. return vertexData;
  34179. };
  34180. // based on http://code.google.com/p/away3d/source/browse/trunk/fp10/Away3D/src/away3d/primitives/TorusKnot.as?spec=svn2473&r=2473
  34181. /**
  34182. * Creates the VertexData of the Torus Knot.
  34183. */
  34184. VertexData.CreateTorusKnot = function (options) {
  34185. var indices = new Array();
  34186. var positions = new Array();
  34187. var normals = new Array();
  34188. var uvs = new Array();
  34189. var radius = options.radius || 2;
  34190. var tube = options.tube || 0.5;
  34191. var radialSegments = options.radialSegments || 32;
  34192. var tubularSegments = options.tubularSegments || 32;
  34193. var p = options.p || 2;
  34194. var q = options.q || 3;
  34195. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  34196. // Helper
  34197. var getPos = function (angle) {
  34198. var cu = Math.cos(angle);
  34199. var su = Math.sin(angle);
  34200. var quOverP = q / p * angle;
  34201. var cs = Math.cos(quOverP);
  34202. var tx = radius * (2 + cs) * 0.5 * cu;
  34203. var ty = radius * (2 + cs) * su * 0.5;
  34204. var tz = radius * Math.sin(quOverP) * 0.5;
  34205. return new BABYLON.Vector3(tx, ty, tz);
  34206. };
  34207. // Vertices
  34208. var i;
  34209. var j;
  34210. for (i = 0; i <= radialSegments; i++) {
  34211. var modI = i % radialSegments;
  34212. var u = modI / radialSegments * 2 * p * Math.PI;
  34213. var p1 = getPos(u);
  34214. var p2 = getPos(u + 0.01);
  34215. var tang = p2.subtract(p1);
  34216. var n = p2.add(p1);
  34217. var bitan = BABYLON.Vector3.Cross(tang, n);
  34218. n = BABYLON.Vector3.Cross(bitan, tang);
  34219. bitan.normalize();
  34220. n.normalize();
  34221. for (j = 0; j < tubularSegments; j++) {
  34222. var modJ = j % tubularSegments;
  34223. var v = modJ / tubularSegments * 2 * Math.PI;
  34224. var cx = -tube * Math.cos(v);
  34225. var cy = tube * Math.sin(v);
  34226. positions.push(p1.x + cx * n.x + cy * bitan.x);
  34227. positions.push(p1.y + cx * n.y + cy * bitan.y);
  34228. positions.push(p1.z + cx * n.z + cy * bitan.z);
  34229. uvs.push(i / radialSegments);
  34230. uvs.push(j / tubularSegments);
  34231. }
  34232. }
  34233. for (i = 0; i < radialSegments; i++) {
  34234. for (j = 0; j < tubularSegments; j++) {
  34235. var jNext = (j + 1) % tubularSegments;
  34236. var a = i * tubularSegments + j;
  34237. var b = (i + 1) * tubularSegments + j;
  34238. var c = (i + 1) * tubularSegments + jNext;
  34239. var d = i * tubularSegments + jNext;
  34240. indices.push(d);
  34241. indices.push(b);
  34242. indices.push(a);
  34243. indices.push(d);
  34244. indices.push(c);
  34245. indices.push(b);
  34246. }
  34247. }
  34248. // Normals
  34249. VertexData.ComputeNormals(positions, indices, normals);
  34250. // Sides
  34251. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  34252. // Result
  34253. var vertexData = new VertexData();
  34254. vertexData.indices = indices;
  34255. vertexData.positions = positions;
  34256. vertexData.normals = normals;
  34257. vertexData.uvs = uvs;
  34258. return vertexData;
  34259. };
  34260. // Tools
  34261. /**
  34262. * @param {any} - positions (number[] or Float32Array)
  34263. * @param {any} - indices (number[] or Uint16Array)
  34264. * @param {any} - normals (number[] or Float32Array)
  34265. * options (optional) :
  34266. * facetPositions : optional array of facet positions (vector3)
  34267. * facetNormals : optional array of facet normals (vector3)
  34268. * facetPartitioning : optional partitioning array. facetPositions is required for facetPartitioning computation
  34269. * subDiv : optional partitioning data about subdivsions on each axis (int), required for facetPartitioning computation
  34270. * ratio : optional partitioning ratio / bounding box, required for facetPartitioning computation
  34271. * bbSize : optional bounding box size data, required for facetPartitioning computation
  34272. * bInfo : optional bounding info, required for facetPartitioning computation
  34273. * useRightHandedSystem: optional boolean to for right handed system computation
  34274. * depthSort : optional boolean to enable the facet depth sort computation
  34275. * distanceTo : optional Vector3 to compute the facet depth from this location
  34276. * depthSortedFacets : optional array of depthSortedFacets to store the facet distances from the reference location
  34277. */
  34278. VertexData.ComputeNormals = function (positions, indices, normals, options) {
  34279. // temporary scalar variables
  34280. var index = 0; // facet index
  34281. var p1p2x = 0.0; // p1p2 vector x coordinate
  34282. var p1p2y = 0.0; // p1p2 vector y coordinate
  34283. var p1p2z = 0.0; // p1p2 vector z coordinate
  34284. var p3p2x = 0.0; // p3p2 vector x coordinate
  34285. var p3p2y = 0.0; // p3p2 vector y coordinate
  34286. var p3p2z = 0.0; // p3p2 vector z coordinate
  34287. var faceNormalx = 0.0; // facet normal x coordinate
  34288. var faceNormaly = 0.0; // facet normal y coordinate
  34289. var faceNormalz = 0.0; // facet normal z coordinate
  34290. var length = 0.0; // facet normal length before normalization
  34291. var v1x = 0; // vector1 x index in the positions array
  34292. var v1y = 0; // vector1 y index in the positions array
  34293. var v1z = 0; // vector1 z index in the positions array
  34294. var v2x = 0; // vector2 x index in the positions array
  34295. var v2y = 0; // vector2 y index in the positions array
  34296. var v2z = 0; // vector2 z index in the positions array
  34297. var v3x = 0; // vector3 x index in the positions array
  34298. var v3y = 0; // vector3 y index in the positions array
  34299. var v3z = 0; // vector3 z index in the positions array
  34300. var computeFacetNormals = false;
  34301. var computeFacetPositions = false;
  34302. var computeFacetPartitioning = false;
  34303. var computeDepthSort = false;
  34304. var faceNormalSign = 1;
  34305. var ratio = 0;
  34306. var distanceTo = null;
  34307. if (options) {
  34308. computeFacetNormals = (options.facetNormals) ? true : false;
  34309. computeFacetPositions = (options.facetPositions) ? true : false;
  34310. computeFacetPartitioning = (options.facetPartitioning) ? true : false;
  34311. faceNormalSign = (options.useRightHandedSystem === true) ? -1 : 1;
  34312. ratio = options.ratio || 0;
  34313. computeDepthSort = (options.depthSort) ? true : false;
  34314. distanceTo = (options.distanceTo);
  34315. if (computeDepthSort) {
  34316. if (distanceTo === undefined) {
  34317. distanceTo = BABYLON.Vector3.Zero();
  34318. }
  34319. var depthSortedFacets = options.depthSortedFacets;
  34320. }
  34321. }
  34322. // facetPartitioning reinit if needed
  34323. var xSubRatio = 0;
  34324. var ySubRatio = 0;
  34325. var zSubRatio = 0;
  34326. var subSq = 0;
  34327. if (computeFacetPartitioning && options && options.bbSize) {
  34328. var ox = 0; // X partitioning index for facet position
  34329. var oy = 0; // Y partinioning index for facet position
  34330. var oz = 0; // Z partinioning index for facet position
  34331. var b1x = 0; // X partitioning index for facet v1 vertex
  34332. var b1y = 0; // Y partitioning index for facet v1 vertex
  34333. var b1z = 0; // z partitioning index for facet v1 vertex
  34334. var b2x = 0; // X partitioning index for facet v2 vertex
  34335. var b2y = 0; // Y partitioning index for facet v2 vertex
  34336. var b2z = 0; // Z partitioning index for facet v2 vertex
  34337. var b3x = 0; // X partitioning index for facet v3 vertex
  34338. var b3y = 0; // Y partitioning index for facet v3 vertex
  34339. var b3z = 0; // Z partitioning index for facet v3 vertex
  34340. var block_idx_o = 0; // facet barycenter block index
  34341. var block_idx_v1 = 0; // v1 vertex block index
  34342. var block_idx_v2 = 0; // v2 vertex block index
  34343. var block_idx_v3 = 0; // v3 vertex block index
  34344. var bbSizeMax = (options.bbSize.x > options.bbSize.y) ? options.bbSize.x : options.bbSize.y;
  34345. bbSizeMax = (bbSizeMax > options.bbSize.z) ? bbSizeMax : options.bbSize.z;
  34346. xSubRatio = options.subDiv.X * ratio / options.bbSize.x;
  34347. ySubRatio = options.subDiv.Y * ratio / options.bbSize.y;
  34348. zSubRatio = options.subDiv.Z * ratio / options.bbSize.z;
  34349. subSq = options.subDiv.max * options.subDiv.max;
  34350. options.facetPartitioning.length = 0;
  34351. }
  34352. // reset the normals
  34353. for (index = 0; index < positions.length; index++) {
  34354. normals[index] = 0.0;
  34355. }
  34356. // Loop : 1 indice triplet = 1 facet
  34357. var nbFaces = (indices.length / 3) | 0;
  34358. for (index = 0; index < nbFaces; index++) {
  34359. // get the indexes of the coordinates of each vertex of the facet
  34360. v1x = indices[index * 3] * 3;
  34361. v1y = v1x + 1;
  34362. v1z = v1x + 2;
  34363. v2x = indices[index * 3 + 1] * 3;
  34364. v2y = v2x + 1;
  34365. v2z = v2x + 2;
  34366. v3x = indices[index * 3 + 2] * 3;
  34367. v3y = v3x + 1;
  34368. v3z = v3x + 2;
  34369. p1p2x = positions[v1x] - positions[v2x]; // compute two vectors per facet : p1p2 and p3p2
  34370. p1p2y = positions[v1y] - positions[v2y];
  34371. p1p2z = positions[v1z] - positions[v2z];
  34372. p3p2x = positions[v3x] - positions[v2x];
  34373. p3p2y = positions[v3y] - positions[v2y];
  34374. p3p2z = positions[v3z] - positions[v2z];
  34375. // compute the face normal with the cross product
  34376. faceNormalx = faceNormalSign * (p1p2y * p3p2z - p1p2z * p3p2y);
  34377. faceNormaly = faceNormalSign * (p1p2z * p3p2x - p1p2x * p3p2z);
  34378. faceNormalz = faceNormalSign * (p1p2x * p3p2y - p1p2y * p3p2x);
  34379. // normalize this normal and store it in the array facetData
  34380. length = Math.sqrt(faceNormalx * faceNormalx + faceNormaly * faceNormaly + faceNormalz * faceNormalz);
  34381. length = (length === 0) ? 1.0 : length;
  34382. faceNormalx /= length;
  34383. faceNormaly /= length;
  34384. faceNormalz /= length;
  34385. if (computeFacetNormals && options) {
  34386. options.facetNormals[index].x = faceNormalx;
  34387. options.facetNormals[index].y = faceNormaly;
  34388. options.facetNormals[index].z = faceNormalz;
  34389. }
  34390. if (computeFacetPositions && options) {
  34391. // compute and the facet barycenter coordinates in the array facetPositions
  34392. options.facetPositions[index].x = (positions[v1x] + positions[v2x] + positions[v3x]) / 3.0;
  34393. options.facetPositions[index].y = (positions[v1y] + positions[v2y] + positions[v3y]) / 3.0;
  34394. options.facetPositions[index].z = (positions[v1z] + positions[v2z] + positions[v3z]) / 3.0;
  34395. }
  34396. if (computeFacetPartitioning && options) {
  34397. // store the facet indexes in arrays in the main facetPartitioning array :
  34398. // compute each facet vertex (+ facet barycenter) index in the partiniong array
  34399. ox = Math.floor((options.facetPositions[index].x - options.bInfo.minimum.x * ratio) * xSubRatio);
  34400. oy = Math.floor((options.facetPositions[index].y - options.bInfo.minimum.y * ratio) * ySubRatio);
  34401. oz = Math.floor((options.facetPositions[index].z - options.bInfo.minimum.z * ratio) * zSubRatio);
  34402. b1x = Math.floor((positions[v1x] - options.bInfo.minimum.x * ratio) * xSubRatio);
  34403. b1y = Math.floor((positions[v1y] - options.bInfo.minimum.y * ratio) * ySubRatio);
  34404. b1z = Math.floor((positions[v1z] - options.bInfo.minimum.z * ratio) * zSubRatio);
  34405. b2x = Math.floor((positions[v2x] - options.bInfo.minimum.x * ratio) * xSubRatio);
  34406. b2y = Math.floor((positions[v2y] - options.bInfo.minimum.y * ratio) * ySubRatio);
  34407. b2z = Math.floor((positions[v2z] - options.bInfo.minimum.z * ratio) * zSubRatio);
  34408. b3x = Math.floor((positions[v3x] - options.bInfo.minimum.x * ratio) * xSubRatio);
  34409. b3y = Math.floor((positions[v3y] - options.bInfo.minimum.y * ratio) * ySubRatio);
  34410. b3z = Math.floor((positions[v3z] - options.bInfo.minimum.z * ratio) * zSubRatio);
  34411. block_idx_v1 = b1x + options.subDiv.max * b1y + subSq * b1z;
  34412. block_idx_v2 = b2x + options.subDiv.max * b2y + subSq * b2z;
  34413. block_idx_v3 = b3x + options.subDiv.max * b3y + subSq * b3z;
  34414. block_idx_o = ox + options.subDiv.max * oy + subSq * oz;
  34415. options.facetPartitioning[block_idx_o] = options.facetPartitioning[block_idx_o] ? options.facetPartitioning[block_idx_o] : new Array();
  34416. options.facetPartitioning[block_idx_v1] = options.facetPartitioning[block_idx_v1] ? options.facetPartitioning[block_idx_v1] : new Array();
  34417. options.facetPartitioning[block_idx_v2] = options.facetPartitioning[block_idx_v2] ? options.facetPartitioning[block_idx_v2] : new Array();
  34418. options.facetPartitioning[block_idx_v3] = options.facetPartitioning[block_idx_v3] ? options.facetPartitioning[block_idx_v3] : new Array();
  34419. // push each facet index in each block containing the vertex
  34420. options.facetPartitioning[block_idx_v1].push(index);
  34421. if (block_idx_v2 != block_idx_v1) {
  34422. options.facetPartitioning[block_idx_v2].push(index);
  34423. }
  34424. if (!(block_idx_v3 == block_idx_v2 || block_idx_v3 == block_idx_v1)) {
  34425. options.facetPartitioning[block_idx_v3].push(index);
  34426. }
  34427. if (!(block_idx_o == block_idx_v1 || block_idx_o == block_idx_v2 || block_idx_o == block_idx_v3)) {
  34428. options.facetPartitioning[block_idx_o].push(index);
  34429. }
  34430. }
  34431. if (computeDepthSort && options && options.facetPositions) {
  34432. var dsf = depthSortedFacets[index];
  34433. dsf.ind = index * 3;
  34434. dsf.sqDistance = BABYLON.Vector3.DistanceSquared(options.facetPositions[index], distanceTo);
  34435. }
  34436. // compute the normals anyway
  34437. normals[v1x] += faceNormalx; // accumulate all the normals per face
  34438. normals[v1y] += faceNormaly;
  34439. normals[v1z] += faceNormalz;
  34440. normals[v2x] += faceNormalx;
  34441. normals[v2y] += faceNormaly;
  34442. normals[v2z] += faceNormalz;
  34443. normals[v3x] += faceNormalx;
  34444. normals[v3y] += faceNormaly;
  34445. normals[v3z] += faceNormalz;
  34446. }
  34447. // last normalization of each normal
  34448. for (index = 0; index < normals.length / 3; index++) {
  34449. faceNormalx = normals[index * 3];
  34450. faceNormaly = normals[index * 3 + 1];
  34451. faceNormalz = normals[index * 3 + 2];
  34452. length = Math.sqrt(faceNormalx * faceNormalx + faceNormaly * faceNormaly + faceNormalz * faceNormalz);
  34453. length = (length === 0) ? 1.0 : length;
  34454. faceNormalx /= length;
  34455. faceNormaly /= length;
  34456. faceNormalz /= length;
  34457. normals[index * 3] = faceNormalx;
  34458. normals[index * 3 + 1] = faceNormaly;
  34459. normals[index * 3 + 2] = faceNormalz;
  34460. }
  34461. };
  34462. VertexData._ComputeSides = function (sideOrientation, positions, indices, normals, uvs, frontUVs, backUVs) {
  34463. var li = indices.length;
  34464. var ln = normals.length;
  34465. var i;
  34466. var n;
  34467. sideOrientation = sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  34468. switch (sideOrientation) {
  34469. case BABYLON.Mesh.FRONTSIDE:
  34470. // nothing changed
  34471. break;
  34472. case BABYLON.Mesh.BACKSIDE:
  34473. var tmp;
  34474. // indices
  34475. for (i = 0; i < li; i += 3) {
  34476. tmp = indices[i];
  34477. indices[i] = indices[i + 2];
  34478. indices[i + 2] = tmp;
  34479. }
  34480. // normals
  34481. for (n = 0; n < ln; n++) {
  34482. normals[n] = -normals[n];
  34483. }
  34484. break;
  34485. case BABYLON.Mesh.DOUBLESIDE:
  34486. // positions
  34487. var lp = positions.length;
  34488. var l = lp / 3;
  34489. for (var p = 0; p < lp; p++) {
  34490. positions[lp + p] = positions[p];
  34491. }
  34492. // indices
  34493. for (i = 0; i < li; i += 3) {
  34494. indices[i + li] = indices[i + 2] + l;
  34495. indices[i + 1 + li] = indices[i + 1] + l;
  34496. indices[i + 2 + li] = indices[i] + l;
  34497. }
  34498. // normals
  34499. for (n = 0; n < ln; n++) {
  34500. normals[ln + n] = -normals[n];
  34501. }
  34502. // uvs
  34503. var lu = uvs.length;
  34504. var u = 0;
  34505. for (u = 0; u < lu; u++) {
  34506. uvs[u + lu] = uvs[u];
  34507. }
  34508. frontUVs = frontUVs ? frontUVs : new BABYLON.Vector4(0.0, 0.0, 1.0, 1.0);
  34509. backUVs = backUVs ? backUVs : new BABYLON.Vector4(0.0, 0.0, 1.0, 1.0);
  34510. u = 0;
  34511. for (i = 0; i < lu / 2; i++) {
  34512. uvs[u] = frontUVs.x + (frontUVs.z - frontUVs.x) * uvs[u];
  34513. uvs[u + 1] = frontUVs.y + (frontUVs.w - frontUVs.y) * uvs[u + 1];
  34514. uvs[u + lu] = backUVs.x + (backUVs.z - backUVs.x) * uvs[u + lu];
  34515. uvs[u + lu + 1] = backUVs.y + (backUVs.w - backUVs.y) * uvs[u + lu + 1];
  34516. u += 2;
  34517. }
  34518. break;
  34519. }
  34520. };
  34521. /**
  34522. * Creates a new VertexData from the imported parameters.
  34523. */
  34524. VertexData.ImportVertexData = function (parsedVertexData, geometry) {
  34525. var vertexData = new VertexData();
  34526. // positions
  34527. var positions = parsedVertexData.positions;
  34528. if (positions) {
  34529. vertexData.set(positions, BABYLON.VertexBuffer.PositionKind);
  34530. }
  34531. // normals
  34532. var normals = parsedVertexData.normals;
  34533. if (normals) {
  34534. vertexData.set(normals, BABYLON.VertexBuffer.NormalKind);
  34535. }
  34536. // tangents
  34537. var tangents = parsedVertexData.tangents;
  34538. if (tangents) {
  34539. vertexData.set(tangents, BABYLON.VertexBuffer.TangentKind);
  34540. }
  34541. // uvs
  34542. var uvs = parsedVertexData.uvs;
  34543. if (uvs) {
  34544. vertexData.set(uvs, BABYLON.VertexBuffer.UVKind);
  34545. }
  34546. // uv2s
  34547. var uv2s = parsedVertexData.uv2s;
  34548. if (uv2s) {
  34549. vertexData.set(uv2s, BABYLON.VertexBuffer.UV2Kind);
  34550. }
  34551. // uv3s
  34552. var uv3s = parsedVertexData.uv3s;
  34553. if (uv3s) {
  34554. vertexData.set(uv3s, BABYLON.VertexBuffer.UV3Kind);
  34555. }
  34556. // uv4s
  34557. var uv4s = parsedVertexData.uv4s;
  34558. if (uv4s) {
  34559. vertexData.set(uv4s, BABYLON.VertexBuffer.UV4Kind);
  34560. }
  34561. // uv5s
  34562. var uv5s = parsedVertexData.uv5s;
  34563. if (uv5s) {
  34564. vertexData.set(uv5s, BABYLON.VertexBuffer.UV5Kind);
  34565. }
  34566. // uv6s
  34567. var uv6s = parsedVertexData.uv6s;
  34568. if (uv6s) {
  34569. vertexData.set(uv6s, BABYLON.VertexBuffer.UV6Kind);
  34570. }
  34571. // colors
  34572. var colors = parsedVertexData.colors;
  34573. if (colors) {
  34574. vertexData.set(BABYLON.Color4.CheckColors4(colors, positions.length / 3), BABYLON.VertexBuffer.ColorKind);
  34575. }
  34576. // matricesIndices
  34577. var matricesIndices = parsedVertexData.matricesIndices;
  34578. if (matricesIndices) {
  34579. vertexData.set(matricesIndices, BABYLON.VertexBuffer.MatricesIndicesKind);
  34580. }
  34581. // matricesWeights
  34582. var matricesWeights = parsedVertexData.matricesWeights;
  34583. if (matricesWeights) {
  34584. vertexData.set(matricesWeights, BABYLON.VertexBuffer.MatricesWeightsKind);
  34585. }
  34586. // indices
  34587. var indices = parsedVertexData.indices;
  34588. if (indices) {
  34589. vertexData.indices = indices;
  34590. }
  34591. geometry.setAllVerticesData(vertexData, parsedVertexData.updatable);
  34592. };
  34593. return VertexData;
  34594. }());
  34595. BABYLON.VertexData = VertexData;
  34596. })(BABYLON || (BABYLON = {}));
  34597. //# sourceMappingURL=babylon.mesh.vertexData.js.map
  34598. var BABYLON;
  34599. (function (BABYLON) {
  34600. /**
  34601. * Class used to store geometry data (vertex buffers + index buffer)
  34602. */
  34603. var Geometry = /** @class */ (function () {
  34604. /**
  34605. * Creates a new geometry
  34606. * @param id defines the unique ID
  34607. * @param scene defines the hosting scene
  34608. * @param vertexData defines the {BABYLON.VertexData} used to get geometry data
  34609. * @param updatable defines if geometry must be updatable (false by default)
  34610. * @param mesh defines the mesh that will be associated with the geometry
  34611. */
  34612. function Geometry(id, scene, vertexData, updatable, mesh) {
  34613. if (updatable === void 0) { updatable = false; }
  34614. if (mesh === void 0) { mesh = null; }
  34615. /**
  34616. * Gets the delay loading state of the geometry (none by default which means not delayed)
  34617. */
  34618. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  34619. this._totalVertices = 0;
  34620. this._isDisposed = false;
  34621. this._indexBufferIsUpdatable = false;
  34622. this.id = id;
  34623. this._engine = scene.getEngine();
  34624. this._meshes = [];
  34625. this._scene = scene;
  34626. //Init vertex buffer cache
  34627. this._vertexBuffers = {};
  34628. this._indices = [];
  34629. this._updatable = updatable;
  34630. // vertexData
  34631. if (vertexData) {
  34632. this.setAllVerticesData(vertexData, updatable);
  34633. }
  34634. else {
  34635. this._totalVertices = 0;
  34636. this._indices = [];
  34637. }
  34638. if (this._engine.getCaps().vertexArrayObject) {
  34639. this._vertexArrayObjects = {};
  34640. }
  34641. // applyToMesh
  34642. if (mesh) {
  34643. if (mesh.getClassName() === "LinesMesh") {
  34644. this.boundingBias = new BABYLON.Vector2(0, mesh.intersectionThreshold);
  34645. this.updateExtend();
  34646. }
  34647. this.applyToMesh(mesh);
  34648. mesh.computeWorldMatrix(true);
  34649. }
  34650. }
  34651. Object.defineProperty(Geometry.prototype, "boundingBias", {
  34652. /**
  34653. * 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
  34654. */
  34655. get: function () {
  34656. return this._boundingBias;
  34657. },
  34658. /**
  34659. * 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
  34660. */
  34661. set: function (value) {
  34662. if (this._boundingBias && this._boundingBias.equals(value)) {
  34663. return;
  34664. }
  34665. this._boundingBias = value.clone();
  34666. this.updateBoundingInfo(true, null);
  34667. },
  34668. enumerable: true,
  34669. configurable: true
  34670. });
  34671. /**
  34672. * Static function used to attach a new empty geometry to a mesh
  34673. * @param mesh defines the mesh to attach the geometry to
  34674. * @returns the new {BABYLON.Geometry}
  34675. */
  34676. Geometry.CreateGeometryForMesh = function (mesh) {
  34677. var geometry = new Geometry(Geometry.RandomId(), mesh.getScene());
  34678. geometry.applyToMesh(mesh);
  34679. return geometry;
  34680. };
  34681. Object.defineProperty(Geometry.prototype, "extend", {
  34682. /**
  34683. * Gets the current extend of the geometry
  34684. */
  34685. get: function () {
  34686. return this._extend;
  34687. },
  34688. enumerable: true,
  34689. configurable: true
  34690. });
  34691. /**
  34692. * Gets the hosting scene
  34693. * @returns the hosting {BABYLON.Scene}
  34694. */
  34695. Geometry.prototype.getScene = function () {
  34696. return this._scene;
  34697. };
  34698. /**
  34699. * Gets the hosting engine
  34700. * @returns the hosting {BABYLON.Engine}
  34701. */
  34702. Geometry.prototype.getEngine = function () {
  34703. return this._engine;
  34704. };
  34705. /**
  34706. * Defines if the geometry is ready to use
  34707. * @returns true if the geometry is ready to be used
  34708. */
  34709. Geometry.prototype.isReady = function () {
  34710. return this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE;
  34711. };
  34712. Object.defineProperty(Geometry.prototype, "doNotSerialize", {
  34713. /**
  34714. * Gets a value indicating that the geometry should not be serialized
  34715. */
  34716. get: function () {
  34717. for (var index = 0; index < this._meshes.length; index++) {
  34718. if (!this._meshes[index].doNotSerialize) {
  34719. return false;
  34720. }
  34721. }
  34722. return true;
  34723. },
  34724. enumerable: true,
  34725. configurable: true
  34726. });
  34727. /** @ignore */
  34728. Geometry.prototype._rebuild = function () {
  34729. if (this._vertexArrayObjects) {
  34730. this._vertexArrayObjects = {};
  34731. }
  34732. // Index buffer
  34733. if (this._meshes.length !== 0 && this._indices) {
  34734. this._indexBuffer = this._engine.createIndexBuffer(this._indices);
  34735. }
  34736. // Vertex buffers
  34737. for (var key in this._vertexBuffers) {
  34738. var vertexBuffer = this._vertexBuffers[key];
  34739. vertexBuffer._rebuild();
  34740. }
  34741. };
  34742. /**
  34743. * Affects all gemetry data in one call
  34744. * @param vertexData defines the geometry data
  34745. * @param updatable defines if the geometry must be flagged as updatable (false as default)
  34746. */
  34747. Geometry.prototype.setAllVerticesData = function (vertexData, updatable) {
  34748. vertexData.applyToGeometry(this, updatable);
  34749. this.notifyUpdate();
  34750. };
  34751. /**
  34752. * Set specific vertex data
  34753. * @param kind defines the data kind (Position, normal, etc...)
  34754. * @param data defines the vertex data to use
  34755. * @param updatable defines if the vertex must be flagged as updatable (false as default)
  34756. * @param stride defines the stride to use (0 by default). This value is deduced from the kind value if not specified
  34757. */
  34758. Geometry.prototype.setVerticesData = function (kind, data, updatable, stride) {
  34759. if (updatable === void 0) { updatable = false; }
  34760. var buffer = new BABYLON.VertexBuffer(this._engine, data, kind, updatable, this._meshes.length === 0, stride);
  34761. this.setVerticesBuffer(buffer);
  34762. };
  34763. /**
  34764. * Removes a specific vertex data
  34765. * @param kind defines the data kind (Position, normal, etc...)
  34766. */
  34767. Geometry.prototype.removeVerticesData = function (kind) {
  34768. if (this._vertexBuffers[kind]) {
  34769. this._vertexBuffers[kind].dispose();
  34770. delete this._vertexBuffers[kind];
  34771. }
  34772. };
  34773. /**
  34774. * Affect a vertex buffer to the geometry. the vertexBuffer.getKind() function is used to determine where to store the data
  34775. * @param buffer defines the vertex buffer to use
  34776. */
  34777. Geometry.prototype.setVerticesBuffer = function (buffer) {
  34778. var kind = buffer.getKind();
  34779. if (this._vertexBuffers[kind]) {
  34780. this._vertexBuffers[kind].dispose();
  34781. }
  34782. this._vertexBuffers[kind] = buffer;
  34783. if (kind === BABYLON.VertexBuffer.PositionKind) {
  34784. var data = buffer.getData();
  34785. var stride = buffer.getStrideSize();
  34786. this._totalVertices = data.length / stride;
  34787. this.updateExtend(data, stride);
  34788. this._resetPointsArrayCache();
  34789. var meshes = this._meshes;
  34790. var numOfMeshes = meshes.length;
  34791. for (var index = 0; index < numOfMeshes; index++) {
  34792. var mesh = meshes[index];
  34793. mesh._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  34794. mesh._createGlobalSubMesh(false);
  34795. mesh.computeWorldMatrix(true);
  34796. }
  34797. }
  34798. this.notifyUpdate(kind);
  34799. if (this._vertexArrayObjects) {
  34800. this._disposeVertexArrayObjects();
  34801. this._vertexArrayObjects = {}; // Will trigger a rebuild of the VAO if supported
  34802. }
  34803. };
  34804. /**
  34805. * Update a specific vertex buffer
  34806. * This function will directly update the underlying WebGLBuffer according to the passed numeric array or Float32Array
  34807. * It will do nothing if the buffer is not updatable
  34808. * @param kind defines the data kind (Position, normal, etc...)
  34809. * @param data defines the data to use
  34810. * @param offset defines the offset in the target buffer where to store the data
  34811. */
  34812. Geometry.prototype.updateVerticesDataDirectly = function (kind, data, offset) {
  34813. var vertexBuffer = this.getVertexBuffer(kind);
  34814. if (!vertexBuffer) {
  34815. return;
  34816. }
  34817. vertexBuffer.updateDirectly(data, offset);
  34818. this.notifyUpdate(kind);
  34819. };
  34820. /**
  34821. * Update a specific vertex buffer
  34822. * This function will create a new buffer if the current one is not updatable
  34823. * @param kind defines the data kind (Position, normal, etc...)
  34824. * @param data defines the data to use
  34825. * @param updateExtends defines if the geometry extends must be recomputed (false by default)
  34826. */
  34827. Geometry.prototype.updateVerticesData = function (kind, data, updateExtends) {
  34828. if (updateExtends === void 0) { updateExtends = false; }
  34829. var vertexBuffer = this.getVertexBuffer(kind);
  34830. if (!vertexBuffer) {
  34831. return;
  34832. }
  34833. vertexBuffer.update(data);
  34834. if (kind === BABYLON.VertexBuffer.PositionKind) {
  34835. var stride = vertexBuffer.getStrideSize();
  34836. this._totalVertices = data.length / stride;
  34837. this.updateBoundingInfo(updateExtends, data);
  34838. }
  34839. this.notifyUpdate(kind);
  34840. };
  34841. Geometry.prototype.updateBoundingInfo = function (updateExtends, data) {
  34842. if (updateExtends) {
  34843. this.updateExtend(data);
  34844. }
  34845. var meshes = this._meshes;
  34846. var numOfMeshes = meshes.length;
  34847. this._resetPointsArrayCache();
  34848. for (var index = 0; index < numOfMeshes; index++) {
  34849. var mesh = meshes[index];
  34850. if (updateExtends) {
  34851. mesh._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  34852. for (var subIndex = 0; subIndex < mesh.subMeshes.length; subIndex++) {
  34853. var subMesh = mesh.subMeshes[subIndex];
  34854. subMesh.refreshBoundingInfo();
  34855. }
  34856. }
  34857. }
  34858. };
  34859. /** @ignore */
  34860. Geometry.prototype._bind = function (effect, indexToBind) {
  34861. if (!effect) {
  34862. return;
  34863. }
  34864. if (indexToBind === undefined) {
  34865. indexToBind = this._indexBuffer;
  34866. }
  34867. var vbs = this.getVertexBuffers();
  34868. if (!vbs) {
  34869. return;
  34870. }
  34871. if (indexToBind != this._indexBuffer || !this._vertexArrayObjects) {
  34872. this._engine.bindBuffers(vbs, indexToBind, effect);
  34873. return;
  34874. }
  34875. // Using VAO
  34876. if (!this._vertexArrayObjects[effect.key]) {
  34877. this._vertexArrayObjects[effect.key] = this._engine.recordVertexArrayObject(vbs, indexToBind, effect);
  34878. }
  34879. this._engine.bindVertexArrayObject(this._vertexArrayObjects[effect.key], indexToBind);
  34880. };
  34881. /**
  34882. * Gets total number of vertices
  34883. * @returns the total number of vertices
  34884. */
  34885. Geometry.prototype.getTotalVertices = function () {
  34886. if (!this.isReady()) {
  34887. return 0;
  34888. }
  34889. return this._totalVertices;
  34890. };
  34891. /**
  34892. * Gets a specific vertex data attached to this geometry
  34893. * @param kind defines the data kind (Position, normal, etc...)
  34894. * @param copyWhenShared defines if the returned array must be cloned upon returning it if the current geometry is shared between multiple meshes
  34895. * @param forceCopy defines a boolean indicating that the returned array must be cloned upon returning it
  34896. * @returns a float array containing vertex data
  34897. */
  34898. Geometry.prototype.getVerticesData = function (kind, copyWhenShared, forceCopy) {
  34899. var vertexBuffer = this.getVertexBuffer(kind);
  34900. if (!vertexBuffer) {
  34901. return null;
  34902. }
  34903. var orig = vertexBuffer.getData();
  34904. if (!forceCopy && (!copyWhenShared || this._meshes.length === 1)) {
  34905. return orig;
  34906. }
  34907. else {
  34908. var len = orig.length;
  34909. var copy = [];
  34910. for (var i = 0; i < len; i++) {
  34911. copy.push(orig[i]);
  34912. }
  34913. return copy;
  34914. }
  34915. };
  34916. /**
  34917. * Returns a boolean defining if the vertex data for the requested `kind` is updatable
  34918. * @param kind defines the data kind (Position, normal, etc...)
  34919. * @returns true if the vertex buffer with the specified kind is updatable
  34920. */
  34921. Geometry.prototype.isVertexBufferUpdatable = function (kind) {
  34922. var vb = this._vertexBuffers[kind];
  34923. if (!vb) {
  34924. return false;
  34925. }
  34926. return vb.isUpdatable();
  34927. };
  34928. /**
  34929. * Gets a specific vertex buffer
  34930. * @param kind defines the data kind (Position, normal, etc...)
  34931. * @returns a {BABYLON.VertexBuffer}
  34932. */
  34933. Geometry.prototype.getVertexBuffer = function (kind) {
  34934. if (!this.isReady()) {
  34935. return null;
  34936. }
  34937. return this._vertexBuffers[kind];
  34938. };
  34939. /**
  34940. * Returns all vertex buffers
  34941. * @return an object holding all vertex buffers indexed by kind
  34942. */
  34943. Geometry.prototype.getVertexBuffers = function () {
  34944. if (!this.isReady()) {
  34945. return null;
  34946. }
  34947. return this._vertexBuffers;
  34948. };
  34949. /**
  34950. * Gets a boolean indicating if specific vertex buffer is present
  34951. * @param kind defines the data kind (Position, normal, etc...)
  34952. * @returns true if data is present
  34953. */
  34954. Geometry.prototype.isVerticesDataPresent = function (kind) {
  34955. if (!this._vertexBuffers) {
  34956. if (this._delayInfo) {
  34957. return this._delayInfo.indexOf(kind) !== -1;
  34958. }
  34959. return false;
  34960. }
  34961. return this._vertexBuffers[kind] !== undefined;
  34962. };
  34963. /**
  34964. * Gets a list of all attached data kinds (Position, normal, etc...)
  34965. * @returns a list of string containing all kinds
  34966. */
  34967. Geometry.prototype.getVerticesDataKinds = function () {
  34968. var result = [];
  34969. var kind;
  34970. if (!this._vertexBuffers && this._delayInfo) {
  34971. for (kind in this._delayInfo) {
  34972. result.push(kind);
  34973. }
  34974. }
  34975. else {
  34976. for (kind in this._vertexBuffers) {
  34977. result.push(kind);
  34978. }
  34979. }
  34980. return result;
  34981. };
  34982. /**
  34983. * Update index buffer
  34984. * @param indices defines the indices to store in the index buffer
  34985. * @param offset defines the offset in the target buffer where to store the data
  34986. */
  34987. Geometry.prototype.updateIndices = function (indices, offset) {
  34988. if (!this._indexBuffer) {
  34989. return;
  34990. }
  34991. if (!this._indexBufferIsUpdatable) {
  34992. this.setIndices(indices, null, true);
  34993. }
  34994. else {
  34995. this._engine.updateDynamicIndexBuffer(this._indexBuffer, indices, offset);
  34996. }
  34997. };
  34998. /**
  34999. * Creates a new index buffer
  35000. * @param indices defines the indices to store in the index buffer
  35001. * @param totalVertices defines the total number of vertices (could be null)
  35002. * @param updatable defines if the index buffer must be flagged as updatable (false by default)
  35003. */
  35004. Geometry.prototype.setIndices = function (indices, totalVertices, updatable) {
  35005. if (totalVertices === void 0) { totalVertices = null; }
  35006. if (updatable === void 0) { updatable = false; }
  35007. if (this._indexBuffer) {
  35008. this._engine._releaseBuffer(this._indexBuffer);
  35009. }
  35010. this._disposeVertexArrayObjects();
  35011. this._indices = indices;
  35012. this._indexBufferIsUpdatable = updatable;
  35013. if (this._meshes.length !== 0 && this._indices) {
  35014. this._indexBuffer = this._engine.createIndexBuffer(this._indices, updatable);
  35015. }
  35016. if (totalVertices != undefined) {
  35017. this._totalVertices = totalVertices;
  35018. }
  35019. var meshes = this._meshes;
  35020. var numOfMeshes = meshes.length;
  35021. for (var index = 0; index < numOfMeshes; index++) {
  35022. meshes[index]._createGlobalSubMesh(true);
  35023. }
  35024. this.notifyUpdate();
  35025. };
  35026. /**
  35027. * Return the total number of indices
  35028. * @returns the total number of indices
  35029. */
  35030. Geometry.prototype.getTotalIndices = function () {
  35031. if (!this.isReady()) {
  35032. return 0;
  35033. }
  35034. return this._indices.length;
  35035. };
  35036. /**
  35037. * Gets the index buffer array
  35038. * @param copyWhenShared defines if the returned array must be cloned upon returning it if the current geometry is shared between multiple meshes
  35039. * @returns the index buffer array
  35040. */
  35041. Geometry.prototype.getIndices = function (copyWhenShared) {
  35042. if (!this.isReady()) {
  35043. return null;
  35044. }
  35045. var orig = this._indices;
  35046. if (!copyWhenShared || this._meshes.length === 1) {
  35047. return orig;
  35048. }
  35049. else {
  35050. var len = orig.length;
  35051. var copy = [];
  35052. for (var i = 0; i < len; i++) {
  35053. copy.push(orig[i]);
  35054. }
  35055. return copy;
  35056. }
  35057. };
  35058. /**
  35059. * Gets the index buffer
  35060. * @return the index buffer
  35061. */
  35062. Geometry.prototype.getIndexBuffer = function () {
  35063. if (!this.isReady()) {
  35064. return null;
  35065. }
  35066. return this._indexBuffer;
  35067. };
  35068. /** @ignore */
  35069. Geometry.prototype._releaseVertexArrayObject = function (effect) {
  35070. if (effect === void 0) { effect = null; }
  35071. if (!effect || !this._vertexArrayObjects) {
  35072. return;
  35073. }
  35074. if (this._vertexArrayObjects[effect.key]) {
  35075. this._engine.releaseVertexArrayObject(this._vertexArrayObjects[effect.key]);
  35076. delete this._vertexArrayObjects[effect.key];
  35077. }
  35078. };
  35079. /**
  35080. * Release the associated resources for a specific mesh
  35081. * @param mesh defines the source mesh
  35082. * @param shouldDispose defines if the geometry must be disposed if there is no more mesh pointing to it
  35083. */
  35084. Geometry.prototype.releaseForMesh = function (mesh, shouldDispose) {
  35085. var meshes = this._meshes;
  35086. var index = meshes.indexOf(mesh);
  35087. if (index === -1) {
  35088. return;
  35089. }
  35090. meshes.splice(index, 1);
  35091. mesh._geometry = null;
  35092. if (meshes.length === 0 && shouldDispose) {
  35093. this.dispose();
  35094. }
  35095. };
  35096. /**
  35097. * Apply current geometry to a given mesh
  35098. * @param mesh defines the mesh to apply geometry to
  35099. */
  35100. Geometry.prototype.applyToMesh = function (mesh) {
  35101. if (mesh._geometry === this) {
  35102. return;
  35103. }
  35104. var previousGeometry = mesh._geometry;
  35105. if (previousGeometry) {
  35106. previousGeometry.releaseForMesh(mesh);
  35107. }
  35108. var meshes = this._meshes;
  35109. // must be done before setting vertexBuffers because of mesh._createGlobalSubMesh()
  35110. mesh._geometry = this;
  35111. this._scene.pushGeometry(this);
  35112. meshes.push(mesh);
  35113. if (this.isReady()) {
  35114. this._applyToMesh(mesh);
  35115. }
  35116. else {
  35117. mesh._boundingInfo = this._boundingInfo;
  35118. }
  35119. };
  35120. Geometry.prototype.updateExtend = function (data, stride) {
  35121. if (data === void 0) { data = null; }
  35122. if (!data) {
  35123. data = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind].getData();
  35124. }
  35125. this._extend = BABYLON.Tools.ExtractMinAndMax(data, 0, this._totalVertices, this.boundingBias, stride);
  35126. };
  35127. Geometry.prototype._applyToMesh = function (mesh) {
  35128. var numOfMeshes = this._meshes.length;
  35129. // vertexBuffers
  35130. for (var kind in this._vertexBuffers) {
  35131. if (numOfMeshes === 1) {
  35132. this._vertexBuffers[kind].create();
  35133. }
  35134. var buffer = this._vertexBuffers[kind].getBuffer();
  35135. if (buffer)
  35136. buffer.references = numOfMeshes;
  35137. if (kind === BABYLON.VertexBuffer.PositionKind) {
  35138. if (!this._extend) {
  35139. this.updateExtend(this._vertexBuffers[kind].getData());
  35140. }
  35141. mesh._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  35142. mesh._createGlobalSubMesh(false);
  35143. //bounding info was just created again, world matrix should be applied again.
  35144. mesh._updateBoundingInfo();
  35145. }
  35146. }
  35147. // indexBuffer
  35148. if (numOfMeshes === 1 && this._indices && this._indices.length > 0) {
  35149. this._indexBuffer = this._engine.createIndexBuffer(this._indices);
  35150. }
  35151. if (this._indexBuffer) {
  35152. this._indexBuffer.references = numOfMeshes;
  35153. }
  35154. };
  35155. Geometry.prototype.notifyUpdate = function (kind) {
  35156. if (this.onGeometryUpdated) {
  35157. this.onGeometryUpdated(this, kind);
  35158. }
  35159. for (var _i = 0, _a = this._meshes; _i < _a.length; _i++) {
  35160. var mesh = _a[_i];
  35161. mesh._markSubMeshesAsAttributesDirty();
  35162. }
  35163. };
  35164. /**
  35165. * Load the geometry if it was flagged as delay loaded
  35166. * @param scene defines the hosting scene
  35167. * @param onLoaded defines a callback called when the geometry is loaded
  35168. */
  35169. Geometry.prototype.load = function (scene, onLoaded) {
  35170. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  35171. return;
  35172. }
  35173. if (this.isReady()) {
  35174. if (onLoaded) {
  35175. onLoaded();
  35176. }
  35177. return;
  35178. }
  35179. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADING;
  35180. this._queueLoad(scene, onLoaded);
  35181. };
  35182. Geometry.prototype._queueLoad = function (scene, onLoaded) {
  35183. var _this = this;
  35184. if (!this.delayLoadingFile) {
  35185. return;
  35186. }
  35187. scene._addPendingData(this);
  35188. scene._loadFile(this.delayLoadingFile, function (data) {
  35189. if (!_this._delayLoadingFunction) {
  35190. return;
  35191. }
  35192. _this._delayLoadingFunction(JSON.parse(data), _this);
  35193. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  35194. _this._delayInfo = [];
  35195. scene._removePendingData(_this);
  35196. var meshes = _this._meshes;
  35197. var numOfMeshes = meshes.length;
  35198. for (var index = 0; index < numOfMeshes; index++) {
  35199. _this._applyToMesh(meshes[index]);
  35200. }
  35201. if (onLoaded) {
  35202. onLoaded();
  35203. }
  35204. }, undefined, true);
  35205. };
  35206. /**
  35207. * Invert the geometry to move from a right handed system to a left handed one.
  35208. */
  35209. Geometry.prototype.toLeftHanded = function () {
  35210. // Flip faces
  35211. var tIndices = this.getIndices(false);
  35212. if (tIndices != null && tIndices.length > 0) {
  35213. for (var i = 0; i < tIndices.length; i += 3) {
  35214. var tTemp = tIndices[i + 0];
  35215. tIndices[i + 0] = tIndices[i + 2];
  35216. tIndices[i + 2] = tTemp;
  35217. }
  35218. this.setIndices(tIndices);
  35219. }
  35220. // Negate position.z
  35221. var tPositions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind, false);
  35222. if (tPositions != null && tPositions.length > 0) {
  35223. for (var i = 0; i < tPositions.length; i += 3) {
  35224. tPositions[i + 2] = -tPositions[i + 2];
  35225. }
  35226. this.setVerticesData(BABYLON.VertexBuffer.PositionKind, tPositions, false);
  35227. }
  35228. // Negate normal.z
  35229. var tNormals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind, false);
  35230. if (tNormals != null && tNormals.length > 0) {
  35231. for (var i = 0; i < tNormals.length; i += 3) {
  35232. tNormals[i + 2] = -tNormals[i + 2];
  35233. }
  35234. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, tNormals, false);
  35235. }
  35236. };
  35237. // Cache
  35238. /** @ignore */
  35239. Geometry.prototype._resetPointsArrayCache = function () {
  35240. this._positions = null;
  35241. };
  35242. /** @ignore */
  35243. Geometry.prototype._generatePointsArray = function () {
  35244. if (this._positions)
  35245. return true;
  35246. this._positions = [];
  35247. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  35248. if (!data) {
  35249. return false;
  35250. }
  35251. for (var index = 0; index < data.length; index += 3) {
  35252. this._positions.push(BABYLON.Vector3.FromArray(data, index));
  35253. }
  35254. return true;
  35255. };
  35256. /**
  35257. * Gets a value indicating if the geometry is disposed
  35258. * @returns true if the geometry was disposed
  35259. */
  35260. Geometry.prototype.isDisposed = function () {
  35261. return this._isDisposed;
  35262. };
  35263. Geometry.prototype._disposeVertexArrayObjects = function () {
  35264. if (this._vertexArrayObjects) {
  35265. for (var kind in this._vertexArrayObjects) {
  35266. this._engine.releaseVertexArrayObject(this._vertexArrayObjects[kind]);
  35267. }
  35268. this._vertexArrayObjects = {};
  35269. }
  35270. };
  35271. /**
  35272. * Free all associated resources
  35273. */
  35274. Geometry.prototype.dispose = function () {
  35275. var meshes = this._meshes;
  35276. var numOfMeshes = meshes.length;
  35277. var index;
  35278. for (index = 0; index < numOfMeshes; index++) {
  35279. this.releaseForMesh(meshes[index]);
  35280. }
  35281. this._meshes = [];
  35282. this._disposeVertexArrayObjects();
  35283. for (var kind in this._vertexBuffers) {
  35284. this._vertexBuffers[kind].dispose();
  35285. }
  35286. this._vertexBuffers = {};
  35287. this._totalVertices = 0;
  35288. if (this._indexBuffer) {
  35289. this._engine._releaseBuffer(this._indexBuffer);
  35290. }
  35291. this._indexBuffer = null;
  35292. this._indices = [];
  35293. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  35294. this.delayLoadingFile = null;
  35295. this._delayLoadingFunction = null;
  35296. this._delayInfo = [];
  35297. this._boundingInfo = null;
  35298. this._scene.removeGeometry(this);
  35299. this._isDisposed = true;
  35300. };
  35301. /**
  35302. * Clone the current geometry into a new geometry
  35303. * @param id defines the unique ID of the new geometry
  35304. * @returns a new geometry object
  35305. */
  35306. Geometry.prototype.copy = function (id) {
  35307. var vertexData = new BABYLON.VertexData();
  35308. vertexData.indices = [];
  35309. var indices = this.getIndices();
  35310. if (indices) {
  35311. for (var index = 0; index < indices.length; index++) {
  35312. vertexData.indices.push(indices[index]);
  35313. }
  35314. }
  35315. var updatable = false;
  35316. var stopChecking = false;
  35317. var kind;
  35318. for (kind in this._vertexBuffers) {
  35319. // using slice() to make a copy of the array and not just reference it
  35320. var data = this.getVerticesData(kind);
  35321. if (data instanceof Float32Array) {
  35322. vertexData.set(new Float32Array(data), kind);
  35323. }
  35324. else {
  35325. vertexData.set(data.slice(0), kind);
  35326. }
  35327. if (!stopChecking) {
  35328. var vb = this.getVertexBuffer(kind);
  35329. if (vb) {
  35330. updatable = vb.isUpdatable();
  35331. stopChecking = !updatable;
  35332. }
  35333. }
  35334. }
  35335. var geometry = new Geometry(id, this._scene, vertexData, updatable);
  35336. geometry.delayLoadState = this.delayLoadState;
  35337. geometry.delayLoadingFile = this.delayLoadingFile;
  35338. geometry._delayLoadingFunction = this._delayLoadingFunction;
  35339. for (kind in this._delayInfo) {
  35340. geometry._delayInfo = geometry._delayInfo || [];
  35341. geometry._delayInfo.push(kind);
  35342. }
  35343. // Bounding info
  35344. geometry._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  35345. return geometry;
  35346. };
  35347. /**
  35348. * Serialize the current geometry info (and not the vertices data) into a JSON object
  35349. * @return a JSON representation of the current geometry data (without the vertices data)
  35350. */
  35351. Geometry.prototype.serialize = function () {
  35352. var serializationObject = {};
  35353. serializationObject.id = this.id;
  35354. serializationObject.updatable = this._updatable;
  35355. if (BABYLON.Tags && BABYLON.Tags.HasTags(this)) {
  35356. serializationObject.tags = BABYLON.Tags.GetTags(this);
  35357. }
  35358. return serializationObject;
  35359. };
  35360. Geometry.prototype.toNumberArray = function (origin) {
  35361. if (Array.isArray(origin)) {
  35362. return origin;
  35363. }
  35364. else {
  35365. return Array.prototype.slice.call(origin);
  35366. }
  35367. };
  35368. /**
  35369. * Serialize all vertices data into a JSON oject
  35370. * @returns a JSON representation of the current geometry data
  35371. */
  35372. Geometry.prototype.serializeVerticeData = function () {
  35373. var serializationObject = this.serialize();
  35374. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  35375. serializationObject.positions = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.PositionKind));
  35376. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.PositionKind)) {
  35377. serializationObject.positions._updatable = true;
  35378. }
  35379. }
  35380. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  35381. serializationObject.normals = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.NormalKind));
  35382. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.NormalKind)) {
  35383. serializationObject.normals._updatable = true;
  35384. }
  35385. }
  35386. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind)) {
  35387. serializationObject.tangets = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.TangentKind));
  35388. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.TangentKind)) {
  35389. serializationObject.tangets._updatable = true;
  35390. }
  35391. }
  35392. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  35393. serializationObject.uvs = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UVKind));
  35394. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UVKind)) {
  35395. serializationObject.uvs._updatable = true;
  35396. }
  35397. }
  35398. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  35399. serializationObject.uv2s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV2Kind));
  35400. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UV2Kind)) {
  35401. serializationObject.uv2s._updatable = true;
  35402. }
  35403. }
  35404. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV3Kind)) {
  35405. serializationObject.uv3s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV3Kind));
  35406. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UV3Kind)) {
  35407. serializationObject.uv3s._updatable = true;
  35408. }
  35409. }
  35410. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV4Kind)) {
  35411. serializationObject.uv4s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV4Kind));
  35412. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UV4Kind)) {
  35413. serializationObject.uv4s._updatable = true;
  35414. }
  35415. }
  35416. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV5Kind)) {
  35417. serializationObject.uv5s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV5Kind));
  35418. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UV5Kind)) {
  35419. serializationObject.uv5s._updatable = true;
  35420. }
  35421. }
  35422. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV6Kind)) {
  35423. serializationObject.uv6s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV6Kind));
  35424. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UV6Kind)) {
  35425. serializationObject.uv6s._updatable = true;
  35426. }
  35427. }
  35428. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  35429. serializationObject.colors = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.ColorKind));
  35430. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.ColorKind)) {
  35431. serializationObject.colors._updatable = true;
  35432. }
  35433. }
  35434. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  35435. serializationObject.matricesIndices = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind));
  35436. serializationObject.matricesIndices._isExpanded = true;
  35437. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  35438. serializationObject.matricesIndices._updatable = true;
  35439. }
  35440. }
  35441. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  35442. serializationObject.matricesWeights = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind));
  35443. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  35444. serializationObject.matricesWeights._updatable = true;
  35445. }
  35446. }
  35447. serializationObject.indices = this.toNumberArray(this.getIndices());
  35448. return serializationObject;
  35449. };
  35450. // Statics
  35451. /**
  35452. * Extracts a clone of a mesh geometry
  35453. * @param mesh defines the source mesh
  35454. * @param id defines the unique ID of the new geometry object
  35455. * @returns the new geometry object
  35456. */
  35457. Geometry.ExtractFromMesh = function (mesh, id) {
  35458. var geometry = mesh._geometry;
  35459. if (!geometry) {
  35460. return null;
  35461. }
  35462. return geometry.copy(id);
  35463. };
  35464. /**
  35465. * You should now use Tools.RandomId(), this method is still here for legacy reasons.
  35466. * Implementation from http://stackoverflow.com/questions/105034/how-to-create-a-guid-uuid-in-javascript/2117523#answer-2117523
  35467. * Be aware Math.random() could cause collisions, but:
  35468. * "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"
  35469. * @returns a string containing a new GUID
  35470. */
  35471. Geometry.RandomId = function () {
  35472. return BABYLON.Tools.RandomId();
  35473. };
  35474. /** @ignore */
  35475. Geometry._ImportGeometry = function (parsedGeometry, mesh) {
  35476. var scene = mesh.getScene();
  35477. // Geometry
  35478. var geometryId = parsedGeometry.geometryId;
  35479. if (geometryId) {
  35480. var geometry = scene.getGeometryByID(geometryId);
  35481. if (geometry) {
  35482. geometry.applyToMesh(mesh);
  35483. }
  35484. }
  35485. else if (parsedGeometry instanceof ArrayBuffer) {
  35486. var binaryInfo = mesh._binaryInfo;
  35487. if (binaryInfo.positionsAttrDesc && binaryInfo.positionsAttrDesc.count > 0) {
  35488. var positionsData = new Float32Array(parsedGeometry, binaryInfo.positionsAttrDesc.offset, binaryInfo.positionsAttrDesc.count);
  35489. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, positionsData, false);
  35490. }
  35491. if (binaryInfo.normalsAttrDesc && binaryInfo.normalsAttrDesc.count > 0) {
  35492. var normalsData = new Float32Array(parsedGeometry, binaryInfo.normalsAttrDesc.offset, binaryInfo.normalsAttrDesc.count);
  35493. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, normalsData, false);
  35494. }
  35495. if (binaryInfo.tangetsAttrDesc && binaryInfo.tangetsAttrDesc.count > 0) {
  35496. var tangentsData = new Float32Array(parsedGeometry, binaryInfo.tangetsAttrDesc.offset, binaryInfo.tangetsAttrDesc.count);
  35497. mesh.setVerticesData(BABYLON.VertexBuffer.TangentKind, tangentsData, false);
  35498. }
  35499. if (binaryInfo.uvsAttrDesc && binaryInfo.uvsAttrDesc.count > 0) {
  35500. var uvsData = new Float32Array(parsedGeometry, binaryInfo.uvsAttrDesc.offset, binaryInfo.uvsAttrDesc.count);
  35501. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, uvsData, false);
  35502. }
  35503. if (binaryInfo.uvs2AttrDesc && binaryInfo.uvs2AttrDesc.count > 0) {
  35504. var uvs2Data = new Float32Array(parsedGeometry, binaryInfo.uvs2AttrDesc.offset, binaryInfo.uvs2AttrDesc.count);
  35505. mesh.setVerticesData(BABYLON.VertexBuffer.UV2Kind, uvs2Data, false);
  35506. }
  35507. if (binaryInfo.uvs3AttrDesc && binaryInfo.uvs3AttrDesc.count > 0) {
  35508. var uvs3Data = new Float32Array(parsedGeometry, binaryInfo.uvs3AttrDesc.offset, binaryInfo.uvs3AttrDesc.count);
  35509. mesh.setVerticesData(BABYLON.VertexBuffer.UV3Kind, uvs3Data, false);
  35510. }
  35511. if (binaryInfo.uvs4AttrDesc && binaryInfo.uvs4AttrDesc.count > 0) {
  35512. var uvs4Data = new Float32Array(parsedGeometry, binaryInfo.uvs4AttrDesc.offset, binaryInfo.uvs4AttrDesc.count);
  35513. mesh.setVerticesData(BABYLON.VertexBuffer.UV4Kind, uvs4Data, false);
  35514. }
  35515. if (binaryInfo.uvs5AttrDesc && binaryInfo.uvs5AttrDesc.count > 0) {
  35516. var uvs5Data = new Float32Array(parsedGeometry, binaryInfo.uvs5AttrDesc.offset, binaryInfo.uvs5AttrDesc.count);
  35517. mesh.setVerticesData(BABYLON.VertexBuffer.UV5Kind, uvs5Data, false);
  35518. }
  35519. if (binaryInfo.uvs6AttrDesc && binaryInfo.uvs6AttrDesc.count > 0) {
  35520. var uvs6Data = new Float32Array(parsedGeometry, binaryInfo.uvs6AttrDesc.offset, binaryInfo.uvs6AttrDesc.count);
  35521. mesh.setVerticesData(BABYLON.VertexBuffer.UV6Kind, uvs6Data, false);
  35522. }
  35523. if (binaryInfo.colorsAttrDesc && binaryInfo.colorsAttrDesc.count > 0) {
  35524. var colorsData = new Float32Array(parsedGeometry, binaryInfo.colorsAttrDesc.offset, binaryInfo.colorsAttrDesc.count);
  35525. mesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, colorsData, false, binaryInfo.colorsAttrDesc.stride);
  35526. }
  35527. if (binaryInfo.matricesIndicesAttrDesc && binaryInfo.matricesIndicesAttrDesc.count > 0) {
  35528. var matricesIndicesData = new Int32Array(parsedGeometry, binaryInfo.matricesIndicesAttrDesc.offset, binaryInfo.matricesIndicesAttrDesc.count);
  35529. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, matricesIndicesData, false);
  35530. }
  35531. if (binaryInfo.matricesWeightsAttrDesc && binaryInfo.matricesWeightsAttrDesc.count > 0) {
  35532. var matricesWeightsData = new Float32Array(parsedGeometry, binaryInfo.matricesWeightsAttrDesc.offset, binaryInfo.matricesWeightsAttrDesc.count);
  35533. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, matricesWeightsData, false);
  35534. }
  35535. if (binaryInfo.indicesAttrDesc && binaryInfo.indicesAttrDesc.count > 0) {
  35536. var indicesData = new Int32Array(parsedGeometry, binaryInfo.indicesAttrDesc.offset, binaryInfo.indicesAttrDesc.count);
  35537. mesh.setIndices(indicesData, null);
  35538. }
  35539. if (binaryInfo.subMeshesAttrDesc && binaryInfo.subMeshesAttrDesc.count > 0) {
  35540. var subMeshesData = new Int32Array(parsedGeometry, binaryInfo.subMeshesAttrDesc.offset, binaryInfo.subMeshesAttrDesc.count * 5);
  35541. mesh.subMeshes = [];
  35542. for (var i = 0; i < binaryInfo.subMeshesAttrDesc.count; i++) {
  35543. var materialIndex = subMeshesData[(i * 5) + 0];
  35544. var verticesStart = subMeshesData[(i * 5) + 1];
  35545. var verticesCount = subMeshesData[(i * 5) + 2];
  35546. var indexStart = subMeshesData[(i * 5) + 3];
  35547. var indexCount = subMeshesData[(i * 5) + 4];
  35548. BABYLON.SubMesh.AddToMesh(materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh);
  35549. }
  35550. }
  35551. }
  35552. else if (parsedGeometry.positions && parsedGeometry.normals && parsedGeometry.indices) {
  35553. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, parsedGeometry.positions, parsedGeometry.positions._updatable);
  35554. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, parsedGeometry.normals, parsedGeometry.normals._updatable);
  35555. if (parsedGeometry.tangents) {
  35556. mesh.setVerticesData(BABYLON.VertexBuffer.TangentKind, parsedGeometry.tangents, parsedGeometry.tangents._updatable);
  35557. }
  35558. if (parsedGeometry.uvs) {
  35559. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, parsedGeometry.uvs, parsedGeometry.uvs._updatable);
  35560. }
  35561. if (parsedGeometry.uvs2) {
  35562. mesh.setVerticesData(BABYLON.VertexBuffer.UV2Kind, parsedGeometry.uvs2, parsedGeometry.uvs2._updatable);
  35563. }
  35564. if (parsedGeometry.uvs3) {
  35565. mesh.setVerticesData(BABYLON.VertexBuffer.UV3Kind, parsedGeometry.uvs3, parsedGeometry.uvs3._updatable);
  35566. }
  35567. if (parsedGeometry.uvs4) {
  35568. mesh.setVerticesData(BABYLON.VertexBuffer.UV4Kind, parsedGeometry.uvs4, parsedGeometry.uvs4._updatable);
  35569. }
  35570. if (parsedGeometry.uvs5) {
  35571. mesh.setVerticesData(BABYLON.VertexBuffer.UV5Kind, parsedGeometry.uvs5, parsedGeometry.uvs5._updatable);
  35572. }
  35573. if (parsedGeometry.uvs6) {
  35574. mesh.setVerticesData(BABYLON.VertexBuffer.UV6Kind, parsedGeometry.uvs6, parsedGeometry.uvs6._updatable);
  35575. }
  35576. if (parsedGeometry.colors) {
  35577. mesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, BABYLON.Color4.CheckColors4(parsedGeometry.colors, parsedGeometry.positions.length / 3), parsedGeometry.colors._updatable);
  35578. }
  35579. if (parsedGeometry.matricesIndices) {
  35580. if (!parsedGeometry.matricesIndices._isExpanded) {
  35581. var floatIndices = [];
  35582. for (var i = 0; i < parsedGeometry.matricesIndices.length; i++) {
  35583. var matricesIndex = parsedGeometry.matricesIndices[i];
  35584. floatIndices.push(matricesIndex & 0x000000FF);
  35585. floatIndices.push((matricesIndex & 0x0000FF00) >> 8);
  35586. floatIndices.push((matricesIndex & 0x00FF0000) >> 16);
  35587. floatIndices.push(matricesIndex >> 24);
  35588. }
  35589. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, floatIndices, parsedGeometry.matricesIndices._updatable);
  35590. }
  35591. else {
  35592. delete parsedGeometry.matricesIndices._isExpanded;
  35593. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, parsedGeometry.matricesIndices, parsedGeometry.matricesIndices._updatable);
  35594. }
  35595. }
  35596. if (parsedGeometry.matricesIndicesExtra) {
  35597. if (!parsedGeometry.matricesIndicesExtra._isExpanded) {
  35598. var floatIndices = [];
  35599. for (var i = 0; i < parsedGeometry.matricesIndicesExtra.length; i++) {
  35600. var matricesIndex = parsedGeometry.matricesIndicesExtra[i];
  35601. floatIndices.push(matricesIndex & 0x000000FF);
  35602. floatIndices.push((matricesIndex & 0x0000FF00) >> 8);
  35603. floatIndices.push((matricesIndex & 0x00FF0000) >> 16);
  35604. floatIndices.push(matricesIndex >> 24);
  35605. }
  35606. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, floatIndices, parsedGeometry.matricesIndicesExtra._updatable);
  35607. }
  35608. else {
  35609. delete parsedGeometry.matricesIndices._isExpanded;
  35610. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, parsedGeometry.matricesIndicesExtra, parsedGeometry.matricesIndicesExtra._updatable);
  35611. }
  35612. }
  35613. if (parsedGeometry.matricesWeights) {
  35614. Geometry._CleanMatricesWeights(parsedGeometry, mesh);
  35615. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, parsedGeometry.matricesWeights, parsedGeometry.matricesWeights._updatable);
  35616. }
  35617. if (parsedGeometry.matricesWeightsExtra) {
  35618. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, parsedGeometry.matricesWeightsExtra, parsedGeometry.matricesWeights._updatable);
  35619. }
  35620. mesh.setIndices(parsedGeometry.indices, null);
  35621. }
  35622. // SubMeshes
  35623. if (parsedGeometry.subMeshes) {
  35624. mesh.subMeshes = [];
  35625. for (var subIndex = 0; subIndex < parsedGeometry.subMeshes.length; subIndex++) {
  35626. var parsedSubMesh = parsedGeometry.subMeshes[subIndex];
  35627. BABYLON.SubMesh.AddToMesh(parsedSubMesh.materialIndex, parsedSubMesh.verticesStart, parsedSubMesh.verticesCount, parsedSubMesh.indexStart, parsedSubMesh.indexCount, mesh);
  35628. }
  35629. }
  35630. // Flat shading
  35631. if (mesh._shouldGenerateFlatShading) {
  35632. mesh.convertToFlatShadedMesh();
  35633. delete mesh._shouldGenerateFlatShading;
  35634. }
  35635. // Update
  35636. mesh.computeWorldMatrix(true);
  35637. // Octree
  35638. var sceneOctree = scene.selectionOctree;
  35639. if (sceneOctree !== undefined && sceneOctree !== null) {
  35640. sceneOctree.addMesh(mesh);
  35641. }
  35642. };
  35643. Geometry._CleanMatricesWeights = function (parsedGeometry, mesh) {
  35644. var epsilon = 1e-3;
  35645. if (!BABYLON.SceneLoader.CleanBoneMatrixWeights) {
  35646. return;
  35647. }
  35648. var noInfluenceBoneIndex = 0.0;
  35649. if (parsedGeometry.skeletonId > -1) {
  35650. var skeleton = mesh.getScene().getLastSkeletonByID(parsedGeometry.skeletonId);
  35651. if (!skeleton) {
  35652. return;
  35653. }
  35654. noInfluenceBoneIndex = skeleton.bones.length;
  35655. }
  35656. else {
  35657. return;
  35658. }
  35659. var matricesIndices = mesh.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind);
  35660. var matricesIndicesExtra = mesh.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  35661. var matricesWeights = parsedGeometry.matricesWeights;
  35662. var matricesWeightsExtra = parsedGeometry.matricesWeightsExtra;
  35663. var influencers = parsedGeometry.numBoneInfluencer;
  35664. var size = matricesWeights.length;
  35665. for (var i = 0; i < size; i += 4) {
  35666. var weight = 0.0;
  35667. var firstZeroWeight = -1;
  35668. for (var j = 0; j < 4; j++) {
  35669. var w = matricesWeights[i + j];
  35670. weight += w;
  35671. if (w < epsilon && firstZeroWeight < 0) {
  35672. firstZeroWeight = j;
  35673. }
  35674. }
  35675. if (matricesWeightsExtra) {
  35676. for (var j = 0; j < 4; j++) {
  35677. var w = matricesWeightsExtra[i + j];
  35678. weight += w;
  35679. if (w < epsilon && firstZeroWeight < 0) {
  35680. firstZeroWeight = j + 4;
  35681. }
  35682. }
  35683. }
  35684. if (firstZeroWeight < 0 || firstZeroWeight > (influencers - 1)) {
  35685. firstZeroWeight = influencers - 1;
  35686. }
  35687. if (weight > epsilon) {
  35688. var mweight = 1.0 / weight;
  35689. for (var j = 0; j < 4; j++) {
  35690. matricesWeights[i + j] *= mweight;
  35691. }
  35692. if (matricesWeightsExtra) {
  35693. for (var j = 0; j < 4; j++) {
  35694. matricesWeightsExtra[i + j] *= mweight;
  35695. }
  35696. }
  35697. }
  35698. else {
  35699. if (firstZeroWeight >= 4) {
  35700. matricesWeightsExtra[i + firstZeroWeight - 4] = 1.0 - weight;
  35701. matricesIndicesExtra[i + firstZeroWeight - 4] = noInfluenceBoneIndex;
  35702. }
  35703. else {
  35704. matricesWeights[i + firstZeroWeight] = 1.0 - weight;
  35705. matricesIndices[i + firstZeroWeight] = noInfluenceBoneIndex;
  35706. }
  35707. }
  35708. }
  35709. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, matricesIndices);
  35710. if (parsedGeometry.matricesWeightsExtra) {
  35711. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, matricesIndicesExtra);
  35712. }
  35713. };
  35714. /**
  35715. * Create a new geometry from persisted data (Using .babylon file format)
  35716. * @param parsedVertexData defines the persisted data
  35717. * @param scene defines the hosting scene
  35718. * @param rootUrl defines the root url to use to load assets (like delayed data)
  35719. * @returns the new geometry object
  35720. */
  35721. Geometry.Parse = function (parsedVertexData, scene, rootUrl) {
  35722. if (scene.getGeometryByID(parsedVertexData.id)) {
  35723. return null; // null since geometry could be something else than a box...
  35724. }
  35725. var geometry = new Geometry(parsedVertexData.id, scene, undefined, parsedVertexData.updatable);
  35726. if (BABYLON.Tags) {
  35727. BABYLON.Tags.AddTagsTo(geometry, parsedVertexData.tags);
  35728. }
  35729. if (parsedVertexData.delayLoadingFile) {
  35730. geometry.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  35731. geometry.delayLoadingFile = rootUrl + parsedVertexData.delayLoadingFile;
  35732. geometry._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Vector3.FromArray(parsedVertexData.boundingBoxMinimum), BABYLON.Vector3.FromArray(parsedVertexData.boundingBoxMaximum));
  35733. geometry._delayInfo = [];
  35734. if (parsedVertexData.hasUVs) {
  35735. geometry._delayInfo.push(BABYLON.VertexBuffer.UVKind);
  35736. }
  35737. if (parsedVertexData.hasUVs2) {
  35738. geometry._delayInfo.push(BABYLON.VertexBuffer.UV2Kind);
  35739. }
  35740. if (parsedVertexData.hasUVs3) {
  35741. geometry._delayInfo.push(BABYLON.VertexBuffer.UV3Kind);
  35742. }
  35743. if (parsedVertexData.hasUVs4) {
  35744. geometry._delayInfo.push(BABYLON.VertexBuffer.UV4Kind);
  35745. }
  35746. if (parsedVertexData.hasUVs5) {
  35747. geometry._delayInfo.push(BABYLON.VertexBuffer.UV5Kind);
  35748. }
  35749. if (parsedVertexData.hasUVs6) {
  35750. geometry._delayInfo.push(BABYLON.VertexBuffer.UV6Kind);
  35751. }
  35752. if (parsedVertexData.hasColors) {
  35753. geometry._delayInfo.push(BABYLON.VertexBuffer.ColorKind);
  35754. }
  35755. if (parsedVertexData.hasMatricesIndices) {
  35756. geometry._delayInfo.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  35757. }
  35758. if (parsedVertexData.hasMatricesWeights) {
  35759. geometry._delayInfo.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  35760. }
  35761. geometry._delayLoadingFunction = BABYLON.VertexData.ImportVertexData;
  35762. }
  35763. else {
  35764. BABYLON.VertexData.ImportVertexData(parsedVertexData, geometry);
  35765. }
  35766. scene.pushGeometry(geometry, true);
  35767. return geometry;
  35768. };
  35769. return Geometry;
  35770. }());
  35771. BABYLON.Geometry = Geometry;
  35772. // Primitives
  35773. /// Abstract class
  35774. /**
  35775. * Abstract class used to provide common services for all typed geometries
  35776. */
  35777. var _PrimitiveGeometry = /** @class */ (function (_super) {
  35778. __extends(_PrimitiveGeometry, _super);
  35779. /**
  35780. * Creates a new typed geometry
  35781. * @param id defines the unique ID of the geometry
  35782. * @param scene defines the hosting scene
  35783. * @param _canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  35784. * @param mesh defines the hosting mesh (can be null)
  35785. */
  35786. function _PrimitiveGeometry(id, scene, _canBeRegenerated, mesh) {
  35787. if (_canBeRegenerated === void 0) { _canBeRegenerated = false; }
  35788. if (mesh === void 0) { mesh = null; }
  35789. var _this = _super.call(this, id, scene, undefined, false, mesh) || this;
  35790. _this._canBeRegenerated = _canBeRegenerated;
  35791. _this._beingRegenerated = true;
  35792. _this.regenerate();
  35793. _this._beingRegenerated = false;
  35794. return _this;
  35795. }
  35796. /**
  35797. * Gets a value indicating if the geometry supports being regenerated with new parameters (false by default)
  35798. * @returns true if the geometry can be regenerated
  35799. */
  35800. _PrimitiveGeometry.prototype.canBeRegenerated = function () {
  35801. return this._canBeRegenerated;
  35802. };
  35803. /**
  35804. * If the geometry supports regeneration, the function will recreates the geometry with updated parameter values
  35805. */
  35806. _PrimitiveGeometry.prototype.regenerate = function () {
  35807. if (!this._canBeRegenerated) {
  35808. return;
  35809. }
  35810. this._beingRegenerated = true;
  35811. this.setAllVerticesData(this._regenerateVertexData(), false);
  35812. this._beingRegenerated = false;
  35813. };
  35814. /**
  35815. * Clone the geometry
  35816. * @param id defines the unique ID of the new geometry
  35817. * @returns the new geometry
  35818. */
  35819. _PrimitiveGeometry.prototype.asNewGeometry = function (id) {
  35820. return _super.prototype.copy.call(this, id);
  35821. };
  35822. // overrides
  35823. _PrimitiveGeometry.prototype.setAllVerticesData = function (vertexData, updatable) {
  35824. if (!this._beingRegenerated) {
  35825. return;
  35826. }
  35827. _super.prototype.setAllVerticesData.call(this, vertexData, false);
  35828. };
  35829. _PrimitiveGeometry.prototype.setVerticesData = function (kind, data, updatable) {
  35830. if (!this._beingRegenerated) {
  35831. return;
  35832. }
  35833. _super.prototype.setVerticesData.call(this, kind, data, false);
  35834. };
  35835. // to override
  35836. /** @ignore */
  35837. _PrimitiveGeometry.prototype._regenerateVertexData = function () {
  35838. throw new Error("Abstract method");
  35839. };
  35840. _PrimitiveGeometry.prototype.copy = function (id) {
  35841. throw new Error("Must be overriden in sub-classes.");
  35842. };
  35843. _PrimitiveGeometry.prototype.serialize = function () {
  35844. var serializationObject = _super.prototype.serialize.call(this);
  35845. serializationObject.canBeRegenerated = this.canBeRegenerated();
  35846. return serializationObject;
  35847. };
  35848. return _PrimitiveGeometry;
  35849. }(Geometry));
  35850. BABYLON._PrimitiveGeometry = _PrimitiveGeometry;
  35851. /**
  35852. * Creates a ribbon geometry
  35853. * @description See http://doc.babylonjs.com/how_to/ribbon_tutorial, http://doc.babylonjs.com/resources/maths_make_ribbons
  35854. */
  35855. var RibbonGeometry = /** @class */ (function (_super) {
  35856. __extends(RibbonGeometry, _super);
  35857. /**
  35858. * Creates a ribbon geometry
  35859. * @param id defines the unique ID of the geometry
  35860. * @param scene defines the hosting scene
  35861. * @param pathArray defines the array of paths to use
  35862. * @param closeArray defines if the last path and the first path must be joined
  35863. * @param closePath defines if the last and first points of each path in your pathArray must be joined
  35864. * @param offset defines the offset between points
  35865. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  35866. * @param mesh defines the hosting mesh (can be null)
  35867. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  35868. */
  35869. function RibbonGeometry(id, scene,
  35870. /**
  35871. * Defines the array of paths to use
  35872. */
  35873. pathArray,
  35874. /**
  35875. * Defines if the last and first points of each path in your pathArray must be joined
  35876. */
  35877. closeArray,
  35878. /**
  35879. * Defines if the last and first points of each path in your pathArray must be joined
  35880. */
  35881. closePath,
  35882. /**
  35883. * Defines the offset between points
  35884. */
  35885. offset, canBeRegenerated, mesh,
  35886. /**
  35887. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  35888. */
  35889. side) {
  35890. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  35891. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  35892. _this.pathArray = pathArray;
  35893. _this.closeArray = closeArray;
  35894. _this.closePath = closePath;
  35895. _this.offset = offset;
  35896. _this.side = side;
  35897. return _this;
  35898. }
  35899. /** @ignore */
  35900. RibbonGeometry.prototype._regenerateVertexData = function () {
  35901. return BABYLON.VertexData.CreateRibbon({ pathArray: this.pathArray, closeArray: this.closeArray, closePath: this.closePath, offset: this.offset, sideOrientation: this.side });
  35902. };
  35903. RibbonGeometry.prototype.copy = function (id) {
  35904. return new RibbonGeometry(id, this.getScene(), this.pathArray, this.closeArray, this.closePath, this.offset, this.canBeRegenerated(), undefined, this.side);
  35905. };
  35906. return RibbonGeometry;
  35907. }(_PrimitiveGeometry));
  35908. BABYLON.RibbonGeometry = RibbonGeometry;
  35909. /**
  35910. * Creates a box geometry
  35911. * @description see http://doc.babylonjs.com/how_to/set_shapes#box
  35912. */
  35913. var BoxGeometry = /** @class */ (function (_super) {
  35914. __extends(BoxGeometry, _super);
  35915. /**
  35916. * Creates a box geometry
  35917. * @param id defines the unique ID of the geometry
  35918. * @param scene defines the hosting scene
  35919. * @param size defines the zise of the box (width, height and depth are the same)
  35920. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  35921. * @param mesh defines the hosting mesh (can be null)
  35922. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  35923. */
  35924. function BoxGeometry(id, scene,
  35925. /**
  35926. * Defines the zise of the box (width, height and depth are the same)
  35927. */
  35928. size, canBeRegenerated, mesh,
  35929. /**
  35930. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  35931. */
  35932. side) {
  35933. if (mesh === void 0) { mesh = null; }
  35934. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  35935. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  35936. _this.size = size;
  35937. _this.side = side;
  35938. return _this;
  35939. }
  35940. BoxGeometry.prototype._regenerateVertexData = function () {
  35941. return BABYLON.VertexData.CreateBox({ size: this.size, sideOrientation: this.side });
  35942. };
  35943. BoxGeometry.prototype.copy = function (id) {
  35944. return new BoxGeometry(id, this.getScene(), this.size, this.canBeRegenerated(), undefined, this.side);
  35945. };
  35946. BoxGeometry.prototype.serialize = function () {
  35947. var serializationObject = _super.prototype.serialize.call(this);
  35948. serializationObject.size = this.size;
  35949. return serializationObject;
  35950. };
  35951. BoxGeometry.Parse = function (parsedBox, scene) {
  35952. if (scene.getGeometryByID(parsedBox.id)) {
  35953. return null; // null since geometry could be something else than a box...
  35954. }
  35955. var box = new BoxGeometry(parsedBox.id, scene, parsedBox.size, parsedBox.canBeRegenerated, null);
  35956. if (BABYLON.Tags) {
  35957. BABYLON.Tags.AddTagsTo(box, parsedBox.tags);
  35958. }
  35959. scene.pushGeometry(box, true);
  35960. return box;
  35961. };
  35962. return BoxGeometry;
  35963. }(_PrimitiveGeometry));
  35964. BABYLON.BoxGeometry = BoxGeometry;
  35965. /**
  35966. * Creates a sphere geometry
  35967. * @description see http://doc.babylonjs.com/how_to/set_shapes#sphere
  35968. */
  35969. var SphereGeometry = /** @class */ (function (_super) {
  35970. __extends(SphereGeometry, _super);
  35971. /**
  35972. * Create a new sphere geometry
  35973. * @param id defines the unique ID of the geometry
  35974. * @param scene defines the hosting scene
  35975. * @param segments defines the number of segments to use to create the sphere
  35976. * @param diameter defines the diameter of the sphere
  35977. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  35978. * @param mesh defines the hosting mesh (can be null)
  35979. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  35980. */
  35981. function SphereGeometry(id, scene,
  35982. /**
  35983. * Defines the number of segments to use to create the sphere
  35984. */
  35985. segments,
  35986. /**
  35987. * Defines the diameter of the sphere
  35988. */
  35989. diameter, canBeRegenerated, mesh,
  35990. /**
  35991. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  35992. */
  35993. side) {
  35994. if (mesh === void 0) { mesh = null; }
  35995. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  35996. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  35997. _this.segments = segments;
  35998. _this.diameter = diameter;
  35999. _this.side = side;
  36000. return _this;
  36001. }
  36002. SphereGeometry.prototype._regenerateVertexData = function () {
  36003. return BABYLON.VertexData.CreateSphere({ segments: this.segments, diameter: this.diameter, sideOrientation: this.side });
  36004. };
  36005. SphereGeometry.prototype.copy = function (id) {
  36006. return new SphereGeometry(id, this.getScene(), this.segments, this.diameter, this.canBeRegenerated(), null, this.side);
  36007. };
  36008. SphereGeometry.prototype.serialize = function () {
  36009. var serializationObject = _super.prototype.serialize.call(this);
  36010. serializationObject.segments = this.segments;
  36011. serializationObject.diameter = this.diameter;
  36012. return serializationObject;
  36013. };
  36014. SphereGeometry.Parse = function (parsedSphere, scene) {
  36015. if (scene.getGeometryByID(parsedSphere.id)) {
  36016. return null; // null since geometry could be something else than a sphere...
  36017. }
  36018. var sphere = new SphereGeometry(parsedSphere.id, scene, parsedSphere.segments, parsedSphere.diameter, parsedSphere.canBeRegenerated, null);
  36019. if (BABYLON.Tags) {
  36020. BABYLON.Tags.AddTagsTo(sphere, parsedSphere.tags);
  36021. }
  36022. scene.pushGeometry(sphere, true);
  36023. return sphere;
  36024. };
  36025. return SphereGeometry;
  36026. }(_PrimitiveGeometry));
  36027. BABYLON.SphereGeometry = SphereGeometry;
  36028. /**
  36029. * Creates a disc geometry
  36030. * @description see http://doc.babylonjs.com/how_to/set_shapes#disc-or-regular-polygon
  36031. */
  36032. var DiscGeometry = /** @class */ (function (_super) {
  36033. __extends(DiscGeometry, _super);
  36034. /**
  36035. * Creates a new disc geometry
  36036. * @param id defines the unique ID of the geometry
  36037. * @param scene defines the hosting scene
  36038. * @param radius defines the radius of the disc
  36039. * @param tessellation defines the tesselation factor to apply to the disc
  36040. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  36041. * @param mesh defines the hosting mesh (can be null)
  36042. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  36043. */
  36044. function DiscGeometry(id, scene,
  36045. /**
  36046. * Defines the radius of the disc
  36047. */
  36048. radius,
  36049. /**
  36050. * Defines the tesselation factor to apply to the disc
  36051. */
  36052. tessellation, canBeRegenerated, mesh,
  36053. /**
  36054. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  36055. */
  36056. side) {
  36057. if (mesh === void 0) { mesh = null; }
  36058. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  36059. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  36060. _this.radius = radius;
  36061. _this.tessellation = tessellation;
  36062. _this.side = side;
  36063. return _this;
  36064. }
  36065. DiscGeometry.prototype._regenerateVertexData = function () {
  36066. return BABYLON.VertexData.CreateDisc({ radius: this.radius, tessellation: this.tessellation, sideOrientation: this.side });
  36067. };
  36068. DiscGeometry.prototype.copy = function (id) {
  36069. return new DiscGeometry(id, this.getScene(), this.radius, this.tessellation, this.canBeRegenerated(), null, this.side);
  36070. };
  36071. return DiscGeometry;
  36072. }(_PrimitiveGeometry));
  36073. BABYLON.DiscGeometry = DiscGeometry;
  36074. /**
  36075. * Creates a new cylinder geometry
  36076. * @description see http://doc.babylonjs.com/how_to/set_shapes#cylinder-or-cone
  36077. */
  36078. var CylinderGeometry = /** @class */ (function (_super) {
  36079. __extends(CylinderGeometry, _super);
  36080. /**
  36081. * Creates a new cylinder geometry
  36082. * @param id defines the unique ID of the geometry
  36083. * @param scene defines the hosting scene
  36084. * @param height defines the height of the cylinder
  36085. * @param diameterTop defines the diameter of the cylinder's top cap
  36086. * @param diameterBottom defines the diameter of the cylinder's bottom cap
  36087. * @param tessellation defines the tessellation factor to apply to the cylinder (number of radial sides)
  36088. * @param subdivisions defines the number of subdivisions to apply to the cylinder (number of rings) (1 by default)
  36089. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  36090. * @param mesh defines the hosting mesh (can be null)
  36091. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  36092. */
  36093. function CylinderGeometry(id, scene,
  36094. /**
  36095. * Defines the height of the cylinder
  36096. */
  36097. height,
  36098. /**
  36099. * Defines the diameter of the cylinder's top cap
  36100. */
  36101. diameterTop,
  36102. /**
  36103. * Defines the diameter of the cylinder's bottom cap
  36104. */
  36105. diameterBottom,
  36106. /**
  36107. * Defines the tessellation factor to apply to the cylinder
  36108. */
  36109. tessellation,
  36110. /**
  36111. * Defines the number of subdivisions to apply to the cylinder (1 by default)
  36112. */
  36113. subdivisions, canBeRegenerated, mesh,
  36114. /**
  36115. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  36116. */
  36117. side) {
  36118. if (subdivisions === void 0) { subdivisions = 1; }
  36119. if (mesh === void 0) { mesh = null; }
  36120. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  36121. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  36122. _this.height = height;
  36123. _this.diameterTop = diameterTop;
  36124. _this.diameterBottom = diameterBottom;
  36125. _this.tessellation = tessellation;
  36126. _this.subdivisions = subdivisions;
  36127. _this.side = side;
  36128. return _this;
  36129. }
  36130. CylinderGeometry.prototype._regenerateVertexData = function () {
  36131. return BABYLON.VertexData.CreateCylinder({ height: this.height, diameterTop: this.diameterTop, diameterBottom: this.diameterBottom, tessellation: this.tessellation, subdivisions: this.subdivisions, sideOrientation: this.side });
  36132. };
  36133. CylinderGeometry.prototype.copy = function (id) {
  36134. return new CylinderGeometry(id, this.getScene(), this.height, this.diameterTop, this.diameterBottom, this.tessellation, this.subdivisions, this.canBeRegenerated(), null, this.side);
  36135. };
  36136. CylinderGeometry.prototype.serialize = function () {
  36137. var serializationObject = _super.prototype.serialize.call(this);
  36138. serializationObject.height = this.height;
  36139. serializationObject.diameterTop = this.diameterTop;
  36140. serializationObject.diameterBottom = this.diameterBottom;
  36141. serializationObject.tessellation = this.tessellation;
  36142. return serializationObject;
  36143. };
  36144. CylinderGeometry.Parse = function (parsedCylinder, scene) {
  36145. if (scene.getGeometryByID(parsedCylinder.id)) {
  36146. return null; // null since geometry could be something else than a cylinder...
  36147. }
  36148. var cylinder = new CylinderGeometry(parsedCylinder.id, scene, parsedCylinder.height, parsedCylinder.diameterTop, parsedCylinder.diameterBottom, parsedCylinder.tessellation, parsedCylinder.subdivisions, parsedCylinder.canBeRegenerated, null);
  36149. if (BABYLON.Tags) {
  36150. BABYLON.Tags.AddTagsTo(cylinder, parsedCylinder.tags);
  36151. }
  36152. scene.pushGeometry(cylinder, true);
  36153. return cylinder;
  36154. };
  36155. return CylinderGeometry;
  36156. }(_PrimitiveGeometry));
  36157. BABYLON.CylinderGeometry = CylinderGeometry;
  36158. /**
  36159. * Creates a new torus geometry
  36160. * @description see http://doc.babylonjs.com/how_to/set_shapes#torus
  36161. */
  36162. var TorusGeometry = /** @class */ (function (_super) {
  36163. __extends(TorusGeometry, _super);
  36164. /**
  36165. * Creates a new torus geometry
  36166. * @param id defines the unique ID of the geometry
  36167. * @param scene defines the hosting scene
  36168. * @param diameter defines the diameter of the torus
  36169. * @param thickness defines the thickness of the torus (ie. internal diameter)
  36170. * @param tessellation defines the tesselation factor to apply to the torus (number of segments along the circle)
  36171. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  36172. * @param mesh defines the hosting mesh (can be null)
  36173. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  36174. */
  36175. function TorusGeometry(id, scene,
  36176. /**
  36177. * Defines the diameter of the torus
  36178. */
  36179. diameter,
  36180. /**
  36181. * Defines the thickness of the torus (ie. internal diameter)
  36182. */
  36183. thickness,
  36184. /**
  36185. * Defines the tesselation factor to apply to the torus
  36186. */
  36187. tessellation, canBeRegenerated, mesh,
  36188. /**
  36189. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  36190. */
  36191. side) {
  36192. if (mesh === void 0) { mesh = null; }
  36193. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  36194. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  36195. _this.diameter = diameter;
  36196. _this.thickness = thickness;
  36197. _this.tessellation = tessellation;
  36198. _this.side = side;
  36199. return _this;
  36200. }
  36201. TorusGeometry.prototype._regenerateVertexData = function () {
  36202. return BABYLON.VertexData.CreateTorus({ diameter: this.diameter, thickness: this.thickness, tessellation: this.tessellation, sideOrientation: this.side });
  36203. };
  36204. TorusGeometry.prototype.copy = function (id) {
  36205. return new TorusGeometry(id, this.getScene(), this.diameter, this.thickness, this.tessellation, this.canBeRegenerated(), null, this.side);
  36206. };
  36207. TorusGeometry.prototype.serialize = function () {
  36208. var serializationObject = _super.prototype.serialize.call(this);
  36209. serializationObject.diameter = this.diameter;
  36210. serializationObject.thickness = this.thickness;
  36211. serializationObject.tessellation = this.tessellation;
  36212. return serializationObject;
  36213. };
  36214. TorusGeometry.Parse = function (parsedTorus, scene) {
  36215. if (scene.getGeometryByID(parsedTorus.id)) {
  36216. return null; // null since geometry could be something else than a torus...
  36217. }
  36218. var torus = new TorusGeometry(parsedTorus.id, scene, parsedTorus.diameter, parsedTorus.thickness, parsedTorus.tessellation, parsedTorus.canBeRegenerated, null);
  36219. if (BABYLON.Tags) {
  36220. BABYLON.Tags.AddTagsTo(torus, parsedTorus.tags);
  36221. }
  36222. scene.pushGeometry(torus, true);
  36223. return torus;
  36224. };
  36225. return TorusGeometry;
  36226. }(_PrimitiveGeometry));
  36227. BABYLON.TorusGeometry = TorusGeometry;
  36228. /**
  36229. * Creates a new ground geometry
  36230. * @description see http://doc.babylonjs.com/how_to/set_shapes#ground
  36231. */
  36232. var GroundGeometry = /** @class */ (function (_super) {
  36233. __extends(GroundGeometry, _super);
  36234. /**
  36235. * Creates a new ground geometry
  36236. * @param id defines the unique ID of the geometry
  36237. * @param scene defines the hosting scene
  36238. * @param width defines the width of the ground
  36239. * @param height defines the height of the ground
  36240. * @param subdivisions defines the subdivisions to apply to the ground
  36241. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  36242. * @param mesh defines the hosting mesh (can be null)
  36243. */
  36244. function GroundGeometry(id, scene,
  36245. /**
  36246. * Defines the width of the ground
  36247. */
  36248. width,
  36249. /**
  36250. * Defines the height of the ground
  36251. */
  36252. height,
  36253. /**
  36254. * Defines the subdivisions to apply to the ground
  36255. */
  36256. subdivisions, canBeRegenerated, mesh) {
  36257. if (mesh === void 0) { mesh = null; }
  36258. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  36259. _this.width = width;
  36260. _this.height = height;
  36261. _this.subdivisions = subdivisions;
  36262. return _this;
  36263. }
  36264. GroundGeometry.prototype._regenerateVertexData = function () {
  36265. return BABYLON.VertexData.CreateGround({ width: this.width, height: this.height, subdivisions: this.subdivisions });
  36266. };
  36267. GroundGeometry.prototype.copy = function (id) {
  36268. return new GroundGeometry(id, this.getScene(), this.width, this.height, this.subdivisions, this.canBeRegenerated(), null);
  36269. };
  36270. GroundGeometry.prototype.serialize = function () {
  36271. var serializationObject = _super.prototype.serialize.call(this);
  36272. serializationObject.width = this.width;
  36273. serializationObject.height = this.height;
  36274. serializationObject.subdivisions = this.subdivisions;
  36275. return serializationObject;
  36276. };
  36277. GroundGeometry.Parse = function (parsedGround, scene) {
  36278. if (scene.getGeometryByID(parsedGround.id)) {
  36279. return null; // null since geometry could be something else than a ground...
  36280. }
  36281. var ground = new GroundGeometry(parsedGround.id, scene, parsedGround.width, parsedGround.height, parsedGround.subdivisions, parsedGround.canBeRegenerated, null);
  36282. if (BABYLON.Tags) {
  36283. BABYLON.Tags.AddTagsTo(ground, parsedGround.tags);
  36284. }
  36285. scene.pushGeometry(ground, true);
  36286. return ground;
  36287. };
  36288. return GroundGeometry;
  36289. }(_PrimitiveGeometry));
  36290. BABYLON.GroundGeometry = GroundGeometry;
  36291. /**
  36292. * Creates a tiled ground geometry
  36293. * @description see http://doc.babylonjs.com/how_to/set_shapes#tiled-ground
  36294. */
  36295. var TiledGroundGeometry = /** @class */ (function (_super) {
  36296. __extends(TiledGroundGeometry, _super);
  36297. /**
  36298. * Creates a tiled ground geometry
  36299. * @param id defines the unique ID of the geometry
  36300. * @param scene defines the hosting scene
  36301. * @param xmin defines the minimum value on X axis
  36302. * @param zmin defines the minimum value on Z axis
  36303. * @param xmax defines the maximum value on X axis
  36304. * @param zmax defines the maximum value on Z axis
  36305. * @param subdivisions defines the subdivisions to apply to the ground (number of subdivisions (tiles) on the height and the width of the map)
  36306. * @param precision defines the precision to use when computing the tiles
  36307. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  36308. * @param mesh defines the hosting mesh (can be null)
  36309. */
  36310. function TiledGroundGeometry(id, scene,
  36311. /**
  36312. * Defines the minimum value on X axis
  36313. */
  36314. xmin,
  36315. /**
  36316. * Defines the minimum value on Z axis
  36317. */
  36318. zmin,
  36319. /**
  36320. * Defines the maximum value on X axis
  36321. */
  36322. xmax,
  36323. /**
  36324. * Defines the maximum value on Z axis
  36325. */
  36326. zmax,
  36327. /**
  36328. * Defines the subdivisions to apply to the ground
  36329. */
  36330. subdivisions,
  36331. /**
  36332. * Defines the precision to use when computing the tiles
  36333. */
  36334. precision, canBeRegenerated, mesh) {
  36335. if (mesh === void 0) { mesh = null; }
  36336. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  36337. _this.xmin = xmin;
  36338. _this.zmin = zmin;
  36339. _this.xmax = xmax;
  36340. _this.zmax = zmax;
  36341. _this.subdivisions = subdivisions;
  36342. _this.precision = precision;
  36343. return _this;
  36344. }
  36345. TiledGroundGeometry.prototype._regenerateVertexData = function () {
  36346. return BABYLON.VertexData.CreateTiledGround({ xmin: this.xmin, zmin: this.zmin, xmax: this.xmax, zmax: this.zmax, subdivisions: this.subdivisions, precision: this.precision });
  36347. };
  36348. TiledGroundGeometry.prototype.copy = function (id) {
  36349. return new TiledGroundGeometry(id, this.getScene(), this.xmin, this.zmin, this.xmax, this.zmax, this.subdivisions, this.precision, this.canBeRegenerated(), null);
  36350. };
  36351. return TiledGroundGeometry;
  36352. }(_PrimitiveGeometry));
  36353. BABYLON.TiledGroundGeometry = TiledGroundGeometry;
  36354. /**
  36355. * Creates a plane geometry
  36356. * @description see http://doc.babylonjs.com/how_to/set_shapes#plane
  36357. */
  36358. var PlaneGeometry = /** @class */ (function (_super) {
  36359. __extends(PlaneGeometry, _super);
  36360. /**
  36361. * Creates a plane geometry
  36362. * @param id defines the unique ID of the geometry
  36363. * @param scene defines the hosting scene
  36364. * @param size defines the size of the plane (width === height)
  36365. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  36366. * @param mesh defines the hosting mesh (can be null)
  36367. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  36368. */
  36369. function PlaneGeometry(id, scene,
  36370. /**
  36371. * Defines the size of the plane (width === height)
  36372. */
  36373. size, canBeRegenerated, mesh,
  36374. /**
  36375. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  36376. */
  36377. side) {
  36378. if (mesh === void 0) { mesh = null; }
  36379. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  36380. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  36381. _this.size = size;
  36382. _this.side = side;
  36383. return _this;
  36384. }
  36385. PlaneGeometry.prototype._regenerateVertexData = function () {
  36386. return BABYLON.VertexData.CreatePlane({ size: this.size, sideOrientation: this.side });
  36387. };
  36388. PlaneGeometry.prototype.copy = function (id) {
  36389. return new PlaneGeometry(id, this.getScene(), this.size, this.canBeRegenerated(), null, this.side);
  36390. };
  36391. PlaneGeometry.prototype.serialize = function () {
  36392. var serializationObject = _super.prototype.serialize.call(this);
  36393. serializationObject.size = this.size;
  36394. return serializationObject;
  36395. };
  36396. PlaneGeometry.Parse = function (parsedPlane, scene) {
  36397. if (scene.getGeometryByID(parsedPlane.id)) {
  36398. return null; // null since geometry could be something else than a ground...
  36399. }
  36400. var plane = new PlaneGeometry(parsedPlane.id, scene, parsedPlane.size, parsedPlane.canBeRegenerated, null);
  36401. if (BABYLON.Tags) {
  36402. BABYLON.Tags.AddTagsTo(plane, parsedPlane.tags);
  36403. }
  36404. scene.pushGeometry(plane, true);
  36405. return plane;
  36406. };
  36407. return PlaneGeometry;
  36408. }(_PrimitiveGeometry));
  36409. BABYLON.PlaneGeometry = PlaneGeometry;
  36410. /**
  36411. * Creates a torus knot geometry
  36412. * @description see http://doc.babylonjs.com/how_to/set_shapes#torus-knot
  36413. */
  36414. var TorusKnotGeometry = /** @class */ (function (_super) {
  36415. __extends(TorusKnotGeometry, _super);
  36416. /**
  36417. * Creates a torus knot geometry
  36418. * @param id defines the unique ID of the geometry
  36419. * @param scene defines the hosting scene
  36420. * @param radius defines the radius of the torus knot
  36421. * @param tube defines the thickness of the torus knot tube
  36422. * @param radialSegments defines the number of radial segments
  36423. * @param tubularSegments defines the number of tubular segments
  36424. * @param p defines the first number of windings
  36425. * @param q defines the second number of windings
  36426. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  36427. * @param mesh defines the hosting mesh (can be null)
  36428. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  36429. */
  36430. function TorusKnotGeometry(id, scene,
  36431. /**
  36432. * Defines the radius of the torus knot
  36433. */
  36434. radius,
  36435. /**
  36436. * Defines the thickness of the torus knot tube
  36437. */
  36438. tube,
  36439. /**
  36440. * Defines the number of radial segments
  36441. */
  36442. radialSegments,
  36443. /**
  36444. * Defines the number of tubular segments
  36445. */
  36446. tubularSegments,
  36447. /**
  36448. * Defines the first number of windings
  36449. */
  36450. p,
  36451. /**
  36452. * Defines the second number of windings
  36453. */
  36454. q, canBeRegenerated, mesh,
  36455. /**
  36456. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  36457. */
  36458. side) {
  36459. if (mesh === void 0) { mesh = null; }
  36460. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  36461. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  36462. _this.radius = radius;
  36463. _this.tube = tube;
  36464. _this.radialSegments = radialSegments;
  36465. _this.tubularSegments = tubularSegments;
  36466. _this.p = p;
  36467. _this.q = q;
  36468. _this.side = side;
  36469. return _this;
  36470. }
  36471. TorusKnotGeometry.prototype._regenerateVertexData = function () {
  36472. 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 });
  36473. };
  36474. TorusKnotGeometry.prototype.copy = function (id) {
  36475. return new TorusKnotGeometry(id, this.getScene(), this.radius, this.tube, this.radialSegments, this.tubularSegments, this.p, this.q, this.canBeRegenerated(), null, this.side);
  36476. };
  36477. TorusKnotGeometry.prototype.serialize = function () {
  36478. var serializationObject = _super.prototype.serialize.call(this);
  36479. serializationObject.radius = this.radius;
  36480. serializationObject.tube = this.tube;
  36481. serializationObject.radialSegments = this.radialSegments;
  36482. serializationObject.tubularSegments = this.tubularSegments;
  36483. serializationObject.p = this.p;
  36484. serializationObject.q = this.q;
  36485. return serializationObject;
  36486. };
  36487. ;
  36488. TorusKnotGeometry.Parse = function (parsedTorusKnot, scene) {
  36489. if (scene.getGeometryByID(parsedTorusKnot.id)) {
  36490. return null; // null since geometry could be something else than a ground...
  36491. }
  36492. var torusKnot = new TorusKnotGeometry(parsedTorusKnot.id, scene, parsedTorusKnot.radius, parsedTorusKnot.tube, parsedTorusKnot.radialSegments, parsedTorusKnot.tubularSegments, parsedTorusKnot.p, parsedTorusKnot.q, parsedTorusKnot.canBeRegenerated, null);
  36493. if (BABYLON.Tags) {
  36494. BABYLON.Tags.AddTagsTo(torusKnot, parsedTorusKnot.tags);
  36495. }
  36496. scene.pushGeometry(torusKnot, true);
  36497. return torusKnot;
  36498. };
  36499. return TorusKnotGeometry;
  36500. }(_PrimitiveGeometry));
  36501. BABYLON.TorusKnotGeometry = TorusKnotGeometry;
  36502. //}
  36503. })(BABYLON || (BABYLON = {}));
  36504. //# sourceMappingURL=babylon.geometry.js.map
  36505. var BABYLON;
  36506. (function (BABYLON) {
  36507. /**
  36508. * PostProcessManager is used to manage one or more post processes or post process pipelines
  36509. * See https://doc.babylonjs.com/how_to/how_to_use_postprocesses
  36510. */
  36511. var PostProcessManager = /** @class */ (function () {
  36512. /**
  36513. * Creates a new instance of @see PostProcess
  36514. * @param scene The scene that the post process is associated with.
  36515. */
  36516. function PostProcessManager(scene) {
  36517. this._vertexBuffers = {};
  36518. this._scene = scene;
  36519. }
  36520. PostProcessManager.prototype._prepareBuffers = function () {
  36521. if (this._vertexBuffers[BABYLON.VertexBuffer.PositionKind]) {
  36522. return;
  36523. }
  36524. // VBO
  36525. var vertices = [];
  36526. vertices.push(1, 1);
  36527. vertices.push(-1, 1);
  36528. vertices.push(-1, -1);
  36529. vertices.push(1, -1);
  36530. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(this._scene.getEngine(), vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  36531. this._buildIndexBuffer();
  36532. };
  36533. PostProcessManager.prototype._buildIndexBuffer = function () {
  36534. // Indices
  36535. var indices = [];
  36536. indices.push(0);
  36537. indices.push(1);
  36538. indices.push(2);
  36539. indices.push(0);
  36540. indices.push(2);
  36541. indices.push(3);
  36542. this._indexBuffer = this._scene.getEngine().createIndexBuffer(indices);
  36543. };
  36544. /**
  36545. * Rebuilds the vertex buffers of the manager.
  36546. */
  36547. PostProcessManager.prototype._rebuild = function () {
  36548. var vb = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  36549. if (!vb) {
  36550. return;
  36551. }
  36552. vb._rebuild();
  36553. this._buildIndexBuffer();
  36554. };
  36555. // Methods
  36556. /**
  36557. * Prepares a frame to be run through a post process.
  36558. * @param sourceTexture The input texture to the post procesess. (default: null)
  36559. * @param postProcesses An array of post processes to be run. (default: null)
  36560. * @returns True if the post processes were able to be run.
  36561. */
  36562. PostProcessManager.prototype._prepareFrame = function (sourceTexture, postProcesses) {
  36563. if (sourceTexture === void 0) { sourceTexture = null; }
  36564. if (postProcesses === void 0) { postProcesses = null; }
  36565. var camera = this._scene.activeCamera;
  36566. if (!camera) {
  36567. return false;
  36568. }
  36569. var postProcesses = postProcesses || camera._postProcesses;
  36570. if (!postProcesses || postProcesses.length === 0 || !this._scene.postProcessesEnabled) {
  36571. return false;
  36572. }
  36573. postProcesses[0].activate(camera, sourceTexture, postProcesses !== null && postProcesses !== undefined);
  36574. return true;
  36575. };
  36576. /**
  36577. * Manually render a set of post processes to a texture.
  36578. * @param postProcesses An array of post processes to be run.
  36579. * @param targetTexture The target texture to render to.
  36580. * @param forceFullscreenViewport force gl.viewport to be full screen eg. 0,0,textureWidth,textureHeight
  36581. */
  36582. PostProcessManager.prototype.directRender = function (postProcesses, targetTexture, forceFullscreenViewport) {
  36583. if (targetTexture === void 0) { targetTexture = null; }
  36584. if (forceFullscreenViewport === void 0) { forceFullscreenViewport = false; }
  36585. var engine = this._scene.getEngine();
  36586. for (var index = 0; index < postProcesses.length; index++) {
  36587. if (index < postProcesses.length - 1) {
  36588. postProcesses[index + 1].activate(this._scene.activeCamera, targetTexture);
  36589. }
  36590. else {
  36591. if (targetTexture) {
  36592. engine.bindFramebuffer(targetTexture, 0, undefined, undefined, forceFullscreenViewport);
  36593. }
  36594. else {
  36595. engine.restoreDefaultFramebuffer();
  36596. }
  36597. }
  36598. var pp = postProcesses[index];
  36599. var effect = pp.apply();
  36600. if (effect) {
  36601. pp.onBeforeRenderObservable.notifyObservers(effect);
  36602. // VBOs
  36603. this._prepareBuffers();
  36604. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  36605. // Draw order
  36606. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  36607. pp.onAfterRenderObservable.notifyObservers(effect);
  36608. }
  36609. }
  36610. // Restore depth buffer
  36611. engine.setDepthBuffer(true);
  36612. engine.setDepthWrite(true);
  36613. };
  36614. /**
  36615. * Finalize the result of the output of the postprocesses.
  36616. * @param doNotPresent If true the result will not be displayed to the screen.
  36617. * @param targetTexture The target texture to render to.
  36618. * @param faceIndex The index of the face to bind the target texture to.
  36619. * @param postProcesses The array of post processes to render.
  36620. * @param forceFullscreenViewport force gl.viewport to be full screen eg. 0,0,textureWidth,textureHeight (default: false)
  36621. */
  36622. PostProcessManager.prototype._finalizeFrame = function (doNotPresent, targetTexture, faceIndex, postProcesses, forceFullscreenViewport) {
  36623. if (forceFullscreenViewport === void 0) { forceFullscreenViewport = false; }
  36624. var camera = this._scene.activeCamera;
  36625. if (!camera) {
  36626. return;
  36627. }
  36628. postProcesses = postProcesses || camera._postProcesses;
  36629. if (postProcesses.length === 0 || !this._scene.postProcessesEnabled) {
  36630. return;
  36631. }
  36632. var engine = this._scene.getEngine();
  36633. for (var index = 0, len = postProcesses.length; index < len; index++) {
  36634. if (index < len - 1) {
  36635. postProcesses[index + 1].activate(camera, targetTexture);
  36636. }
  36637. else {
  36638. if (targetTexture) {
  36639. engine.bindFramebuffer(targetTexture, faceIndex, undefined, undefined, forceFullscreenViewport);
  36640. }
  36641. else {
  36642. engine.restoreDefaultFramebuffer();
  36643. }
  36644. }
  36645. if (doNotPresent) {
  36646. break;
  36647. }
  36648. var pp = postProcesses[index];
  36649. var effect = pp.apply();
  36650. if (effect) {
  36651. pp.onBeforeRenderObservable.notifyObservers(effect);
  36652. // VBOs
  36653. this._prepareBuffers();
  36654. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  36655. // Draw order
  36656. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  36657. pp.onAfterRenderObservable.notifyObservers(effect);
  36658. }
  36659. }
  36660. // Restore states
  36661. engine.setDepthBuffer(true);
  36662. engine.setDepthWrite(true);
  36663. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  36664. };
  36665. /**
  36666. * Disposes of the post process manager.
  36667. */
  36668. PostProcessManager.prototype.dispose = function () {
  36669. var buffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  36670. if (buffer) {
  36671. buffer.dispose();
  36672. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  36673. }
  36674. if (this._indexBuffer) {
  36675. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  36676. this._indexBuffer = null;
  36677. }
  36678. };
  36679. return PostProcessManager;
  36680. }());
  36681. BABYLON.PostProcessManager = PostProcessManager;
  36682. })(BABYLON || (BABYLON = {}));
  36683. //# sourceMappingURL=babylon.postProcessManager.js.map
  36684. var BABYLON;
  36685. (function (BABYLON) {
  36686. /**
  36687. * Performance monitor tracks rolling average frame-time and frame-time variance over a user defined sliding-window
  36688. */
  36689. var PerformanceMonitor = /** @class */ (function () {
  36690. /**
  36691. * constructor
  36692. * @param frameSampleSize The number of samples required to saturate the sliding window
  36693. */
  36694. function PerformanceMonitor(frameSampleSize) {
  36695. if (frameSampleSize === void 0) { frameSampleSize = 30; }
  36696. this._enabled = true;
  36697. this._rollingFrameTime = new RollingAverage(frameSampleSize);
  36698. }
  36699. /**
  36700. * Samples current frame
  36701. * @param timeMs A timestamp in milliseconds of the current frame to compare with other frames
  36702. */
  36703. PerformanceMonitor.prototype.sampleFrame = function (timeMs) {
  36704. if (timeMs === void 0) { timeMs = BABYLON.Tools.Now; }
  36705. if (!this._enabled)
  36706. return;
  36707. if (this._lastFrameTimeMs != null) {
  36708. var dt = timeMs - this._lastFrameTimeMs;
  36709. this._rollingFrameTime.add(dt);
  36710. }
  36711. this._lastFrameTimeMs = timeMs;
  36712. };
  36713. Object.defineProperty(PerformanceMonitor.prototype, "averageFrameTime", {
  36714. /**
  36715. * Returns the average frame time in milliseconds over the sliding window (or the subset of frames sampled so far)
  36716. * @return Average frame time in milliseconds
  36717. */
  36718. get: function () {
  36719. return this._rollingFrameTime.average;
  36720. },
  36721. enumerable: true,
  36722. configurable: true
  36723. });
  36724. Object.defineProperty(PerformanceMonitor.prototype, "averageFrameTimeVariance", {
  36725. /**
  36726. * Returns the variance frame time in milliseconds over the sliding window (or the subset of frames sampled so far)
  36727. * @return Frame time variance in milliseconds squared
  36728. */
  36729. get: function () {
  36730. return this._rollingFrameTime.variance;
  36731. },
  36732. enumerable: true,
  36733. configurable: true
  36734. });
  36735. Object.defineProperty(PerformanceMonitor.prototype, "instantaneousFrameTime", {
  36736. /**
  36737. * Returns the frame time of the most recent frame
  36738. * @return Frame time in milliseconds
  36739. */
  36740. get: function () {
  36741. return this._rollingFrameTime.history(0);
  36742. },
  36743. enumerable: true,
  36744. configurable: true
  36745. });
  36746. Object.defineProperty(PerformanceMonitor.prototype, "averageFPS", {
  36747. /**
  36748. * Returns the average framerate in frames per second over the sliding window (or the subset of frames sampled so far)
  36749. * @return Framerate in frames per second
  36750. */
  36751. get: function () {
  36752. return 1000.0 / this._rollingFrameTime.average;
  36753. },
  36754. enumerable: true,
  36755. configurable: true
  36756. });
  36757. Object.defineProperty(PerformanceMonitor.prototype, "instantaneousFPS", {
  36758. /**
  36759. * Returns the average framerate in frames per second using the most recent frame time
  36760. * @return Framerate in frames per second
  36761. */
  36762. get: function () {
  36763. var history = this._rollingFrameTime.history(0);
  36764. if (history === 0) {
  36765. return 0;
  36766. }
  36767. return 1000.0 / history;
  36768. },
  36769. enumerable: true,
  36770. configurable: true
  36771. });
  36772. Object.defineProperty(PerformanceMonitor.prototype, "isSaturated", {
  36773. /**
  36774. * Returns true if enough samples have been taken to completely fill the sliding window
  36775. * @return true if saturated
  36776. */
  36777. get: function () {
  36778. return this._rollingFrameTime.isSaturated();
  36779. },
  36780. enumerable: true,
  36781. configurable: true
  36782. });
  36783. /**
  36784. * Enables contributions to the sliding window sample set
  36785. */
  36786. PerformanceMonitor.prototype.enable = function () {
  36787. this._enabled = true;
  36788. };
  36789. /**
  36790. * Disables contributions to the sliding window sample set
  36791. * Samples will not be interpolated over the disabled period
  36792. */
  36793. PerformanceMonitor.prototype.disable = function () {
  36794. this._enabled = false;
  36795. //clear last sample to avoid interpolating over the disabled period when next enabled
  36796. this._lastFrameTimeMs = null;
  36797. };
  36798. Object.defineProperty(PerformanceMonitor.prototype, "isEnabled", {
  36799. /**
  36800. * Returns true if sampling is enabled
  36801. * @return true if enabled
  36802. */
  36803. get: function () {
  36804. return this._enabled;
  36805. },
  36806. enumerable: true,
  36807. configurable: true
  36808. });
  36809. /**
  36810. * Resets performance monitor
  36811. */
  36812. PerformanceMonitor.prototype.reset = function () {
  36813. //clear last sample to avoid interpolating over the disabled period when next enabled
  36814. this._lastFrameTimeMs = null;
  36815. //wipe record
  36816. this._rollingFrameTime.reset();
  36817. };
  36818. return PerformanceMonitor;
  36819. }());
  36820. BABYLON.PerformanceMonitor = PerformanceMonitor;
  36821. /**
  36822. * RollingAverage
  36823. *
  36824. * Utility to efficiently compute the rolling average and variance over a sliding window of samples
  36825. */
  36826. var RollingAverage = /** @class */ (function () {
  36827. /**
  36828. * constructor
  36829. * @param length The number of samples required to saturate the sliding window
  36830. */
  36831. function RollingAverage(length) {
  36832. this._samples = new Array(length);
  36833. this.reset();
  36834. }
  36835. /**
  36836. * Adds a sample to the sample set
  36837. * @param v The sample value
  36838. */
  36839. RollingAverage.prototype.add = function (v) {
  36840. //http://en.wikipedia.org/wiki/Algorithms_for_calculating_variance
  36841. var delta;
  36842. //we need to check if we've already wrapped round
  36843. if (this.isSaturated()) {
  36844. //remove bottom of stack from mean
  36845. var bottomValue = this._samples[this._pos];
  36846. delta = bottomValue - this.average;
  36847. this.average -= delta / (this._sampleCount - 1);
  36848. this._m2 -= delta * (bottomValue - this.average);
  36849. }
  36850. else {
  36851. this._sampleCount++;
  36852. }
  36853. //add new value to mean
  36854. delta = v - this.average;
  36855. this.average += delta / (this._sampleCount);
  36856. this._m2 += delta * (v - this.average);
  36857. //set the new variance
  36858. this.variance = this._m2 / (this._sampleCount - 1);
  36859. this._samples[this._pos] = v;
  36860. this._pos++;
  36861. this._pos %= this._samples.length; //positive wrap around
  36862. };
  36863. /**
  36864. * Returns previously added values or null if outside of history or outside the sliding window domain
  36865. * @param i Index in history. For example, pass 0 for the most recent value and 1 for the value before that
  36866. * @return Value previously recorded with add() or null if outside of range
  36867. */
  36868. RollingAverage.prototype.history = function (i) {
  36869. if ((i >= this._sampleCount) || (i >= this._samples.length)) {
  36870. return 0;
  36871. }
  36872. var i0 = this._wrapPosition(this._pos - 1.0);
  36873. return this._samples[this._wrapPosition(i0 - i)];
  36874. };
  36875. /**
  36876. * Returns true if enough samples have been taken to completely fill the sliding window
  36877. * @return true if sample-set saturated
  36878. */
  36879. RollingAverage.prototype.isSaturated = function () {
  36880. return this._sampleCount >= this._samples.length;
  36881. };
  36882. /**
  36883. * Resets the rolling average (equivalent to 0 samples taken so far)
  36884. */
  36885. RollingAverage.prototype.reset = function () {
  36886. this.average = 0;
  36887. this.variance = 0;
  36888. this._sampleCount = 0;
  36889. this._pos = 0;
  36890. this._m2 = 0;
  36891. };
  36892. /**
  36893. * Wraps a value around the sample range boundaries
  36894. * @param i Position in sample range, for example if the sample length is 5, and i is -3, then 2 will be returned.
  36895. * @return Wrapped position in sample range
  36896. */
  36897. RollingAverage.prototype._wrapPosition = function (i) {
  36898. var max = this._samples.length;
  36899. return ((i % max) + max) % max;
  36900. };
  36901. return RollingAverage;
  36902. }());
  36903. BABYLON.RollingAverage = RollingAverage;
  36904. })(BABYLON || (BABYLON = {}));
  36905. //# sourceMappingURL=babylon.performanceMonitor.js.map
  36906. var BABYLON;
  36907. (function (BABYLON) {
  36908. /**
  36909. * This groups together the common properties used for image processing either in direct forward pass
  36910. * or through post processing effect depending on the use of the image processing pipeline in your scene
  36911. * or not.
  36912. */
  36913. var ImageProcessingConfiguration = /** @class */ (function () {
  36914. function ImageProcessingConfiguration() {
  36915. /**
  36916. * Color curves setup used in the effect if colorCurvesEnabled is set to true
  36917. */
  36918. this.colorCurves = new BABYLON.ColorCurves();
  36919. this._colorCurvesEnabled = false;
  36920. this._colorGradingEnabled = false;
  36921. this._colorGradingWithGreenDepth = true;
  36922. this._colorGradingBGR = true;
  36923. this._exposure = 1.0;
  36924. this._toneMappingEnabled = false;
  36925. this._contrast = 1.0;
  36926. /**
  36927. * Vignette stretch size.
  36928. */
  36929. this.vignetteStretch = 0;
  36930. /**
  36931. * Vignette centre X Offset.
  36932. */
  36933. this.vignetteCentreX = 0;
  36934. /**
  36935. * Vignette centre Y Offset.
  36936. */
  36937. this.vignetteCentreY = 0;
  36938. /**
  36939. * Vignette weight or intensity of the vignette effect.
  36940. */
  36941. this.vignetteWeight = 1.5;
  36942. /**
  36943. * Color of the vignette applied on the screen through the chosen blend mode (vignetteBlendMode)
  36944. * if vignetteEnabled is set to true.
  36945. */
  36946. this.vignetteColor = new BABYLON.Color4(0, 0, 0, 0);
  36947. /**
  36948. * Camera field of view used by the Vignette effect.
  36949. */
  36950. this.vignetteCameraFov = 0.5;
  36951. this._grainEnabled = false;
  36952. this._grainIntensity = 30;
  36953. this._grainAnimated = false;
  36954. this._vignetteBlendMode = ImageProcessingConfiguration.VIGNETTEMODE_MULTIPLY;
  36955. this._vignetteEnabled = false;
  36956. this._applyByPostProcess = false;
  36957. this._isEnabled = true;
  36958. /**
  36959. * An event triggered when the configuration changes and requires Shader to Update some parameters.
  36960. * @type {BABYLON.Observable}
  36961. */
  36962. this.onUpdateParameters = new BABYLON.Observable();
  36963. }
  36964. Object.defineProperty(ImageProcessingConfiguration.prototype, "colorCurvesEnabled", {
  36965. /**
  36966. * Gets wether the color curves effect is enabled.
  36967. */
  36968. get: function () {
  36969. return this._colorCurvesEnabled;
  36970. },
  36971. /**
  36972. * Sets wether the color curves effect is enabled.
  36973. */
  36974. set: function (value) {
  36975. if (this._colorCurvesEnabled === value) {
  36976. return;
  36977. }
  36978. this._colorCurvesEnabled = value;
  36979. this._updateParameters();
  36980. },
  36981. enumerable: true,
  36982. configurable: true
  36983. });
  36984. Object.defineProperty(ImageProcessingConfiguration.prototype, "colorGradingEnabled", {
  36985. /**
  36986. * Gets wether the color grading effect is enabled.
  36987. */
  36988. get: function () {
  36989. return this._colorGradingEnabled;
  36990. },
  36991. /**
  36992. * Sets wether the color grading effect is enabled.
  36993. */
  36994. set: function (value) {
  36995. if (this._colorGradingEnabled === value) {
  36996. return;
  36997. }
  36998. this._colorGradingEnabled = value;
  36999. this._updateParameters();
  37000. },
  37001. enumerable: true,
  37002. configurable: true
  37003. });
  37004. Object.defineProperty(ImageProcessingConfiguration.prototype, "colorGradingWithGreenDepth", {
  37005. /**
  37006. * Gets wether the color grading effect is using a green depth for the 3d Texture.
  37007. */
  37008. get: function () {
  37009. return this._colorGradingWithGreenDepth;
  37010. },
  37011. /**
  37012. * Sets wether the color grading effect is using a green depth for the 3d Texture.
  37013. */
  37014. set: function (value) {
  37015. if (this._colorGradingWithGreenDepth === value) {
  37016. return;
  37017. }
  37018. this._colorGradingWithGreenDepth = value;
  37019. this._updateParameters();
  37020. },
  37021. enumerable: true,
  37022. configurable: true
  37023. });
  37024. Object.defineProperty(ImageProcessingConfiguration.prototype, "colorGradingBGR", {
  37025. /**
  37026. * Gets wether the color grading texture contains BGR values.
  37027. */
  37028. get: function () {
  37029. return this._colorGradingBGR;
  37030. },
  37031. /**
  37032. * Sets wether the color grading texture contains BGR values.
  37033. */
  37034. set: function (value) {
  37035. if (this._colorGradingBGR === value) {
  37036. return;
  37037. }
  37038. this._colorGradingBGR = value;
  37039. this._updateParameters();
  37040. },
  37041. enumerable: true,
  37042. configurable: true
  37043. });
  37044. Object.defineProperty(ImageProcessingConfiguration.prototype, "exposure", {
  37045. /**
  37046. * Gets the Exposure used in the effect.
  37047. */
  37048. get: function () {
  37049. return this._exposure;
  37050. },
  37051. /**
  37052. * Sets the Exposure used in the effect.
  37053. */
  37054. set: function (value) {
  37055. if (this._exposure === value) {
  37056. return;
  37057. }
  37058. this._exposure = value;
  37059. this._updateParameters();
  37060. },
  37061. enumerable: true,
  37062. configurable: true
  37063. });
  37064. Object.defineProperty(ImageProcessingConfiguration.prototype, "toneMappingEnabled", {
  37065. /**
  37066. * Gets wether the tone mapping effect is enabled.
  37067. */
  37068. get: function () {
  37069. return this._toneMappingEnabled;
  37070. },
  37071. /**
  37072. * Sets wether the tone mapping effect is enabled.
  37073. */
  37074. set: function (value) {
  37075. if (this._toneMappingEnabled === value) {
  37076. return;
  37077. }
  37078. this._toneMappingEnabled = value;
  37079. this._updateParameters();
  37080. },
  37081. enumerable: true,
  37082. configurable: true
  37083. });
  37084. Object.defineProperty(ImageProcessingConfiguration.prototype, "contrast", {
  37085. /**
  37086. * Gets the contrast used in the effect.
  37087. */
  37088. get: function () {
  37089. return this._contrast;
  37090. },
  37091. /**
  37092. * Sets the contrast used in the effect.
  37093. */
  37094. set: function (value) {
  37095. if (this._contrast === value) {
  37096. return;
  37097. }
  37098. this._contrast = value;
  37099. this._updateParameters();
  37100. },
  37101. enumerable: true,
  37102. configurable: true
  37103. });
  37104. Object.defineProperty(ImageProcessingConfiguration.prototype, "grainEnabled", {
  37105. /**
  37106. * If the grain effect should be enabled.
  37107. */
  37108. get: function () {
  37109. return this._grainEnabled;
  37110. },
  37111. set: function (value) {
  37112. if (this._grainEnabled === value) {
  37113. return;
  37114. }
  37115. this._grainEnabled = value;
  37116. this._updateParameters();
  37117. },
  37118. enumerable: true,
  37119. configurable: true
  37120. });
  37121. Object.defineProperty(ImageProcessingConfiguration.prototype, "grainIntensity", {
  37122. /**
  37123. * Amount of grain to be applied by the grain effect.
  37124. */
  37125. get: function () {
  37126. return this._grainIntensity;
  37127. },
  37128. set: function (value) {
  37129. if (this._grainIntensity === value) {
  37130. return;
  37131. }
  37132. this._grainIntensity = value;
  37133. },
  37134. enumerable: true,
  37135. configurable: true
  37136. });
  37137. Object.defineProperty(ImageProcessingConfiguration.prototype, "grainAnimated", {
  37138. /**
  37139. * If the grain effect should be animated.
  37140. */
  37141. get: function () {
  37142. return this._grainAnimated;
  37143. },
  37144. set: function (value) {
  37145. if (this._grainAnimated === value) {
  37146. return;
  37147. }
  37148. this._grainAnimated = value;
  37149. this._updateParameters();
  37150. },
  37151. enumerable: true,
  37152. configurable: true
  37153. });
  37154. Object.defineProperty(ImageProcessingConfiguration.prototype, "vignetteBlendMode", {
  37155. /**
  37156. * Gets the vignette blend mode allowing different kind of effect.
  37157. */
  37158. get: function () {
  37159. return this._vignetteBlendMode;
  37160. },
  37161. /**
  37162. * Sets the vignette blend mode allowing different kind of effect.
  37163. */
  37164. set: function (value) {
  37165. if (this._vignetteBlendMode === value) {
  37166. return;
  37167. }
  37168. this._vignetteBlendMode = value;
  37169. this._updateParameters();
  37170. },
  37171. enumerable: true,
  37172. configurable: true
  37173. });
  37174. Object.defineProperty(ImageProcessingConfiguration.prototype, "vignetteEnabled", {
  37175. /**
  37176. * Gets wether the vignette effect is enabled.
  37177. */
  37178. get: function () {
  37179. return this._vignetteEnabled;
  37180. },
  37181. /**
  37182. * Sets wether the vignette effect is enabled.
  37183. */
  37184. set: function (value) {
  37185. if (this._vignetteEnabled === value) {
  37186. return;
  37187. }
  37188. this._vignetteEnabled = value;
  37189. this._updateParameters();
  37190. },
  37191. enumerable: true,
  37192. configurable: true
  37193. });
  37194. Object.defineProperty(ImageProcessingConfiguration.prototype, "applyByPostProcess", {
  37195. /**
  37196. * Gets wether the image processing is applied through a post process or not.
  37197. */
  37198. get: function () {
  37199. return this._applyByPostProcess;
  37200. },
  37201. /**
  37202. * Sets wether the image processing is applied through a post process or not.
  37203. */
  37204. set: function (value) {
  37205. if (this._applyByPostProcess === value) {
  37206. return;
  37207. }
  37208. this._applyByPostProcess = value;
  37209. this._updateParameters();
  37210. },
  37211. enumerable: true,
  37212. configurable: true
  37213. });
  37214. Object.defineProperty(ImageProcessingConfiguration.prototype, "isEnabled", {
  37215. /**
  37216. * Gets wether the image processing is enabled or not.
  37217. */
  37218. get: function () {
  37219. return this._isEnabled;
  37220. },
  37221. /**
  37222. * Sets wether the image processing is enabled or not.
  37223. */
  37224. set: function (value) {
  37225. if (this._isEnabled === value) {
  37226. return;
  37227. }
  37228. this._isEnabled = value;
  37229. this._updateParameters();
  37230. },
  37231. enumerable: true,
  37232. configurable: true
  37233. });
  37234. /**
  37235. * Method called each time the image processing information changes requires to recompile the effect.
  37236. */
  37237. ImageProcessingConfiguration.prototype._updateParameters = function () {
  37238. this.onUpdateParameters.notifyObservers(this);
  37239. };
  37240. ImageProcessingConfiguration.prototype.getClassName = function () {
  37241. return "ImageProcessingConfiguration";
  37242. };
  37243. /**
  37244. * Prepare the list of uniforms associated with the Image Processing effects.
  37245. * @param uniformsList The list of uniforms used in the effect
  37246. * @param defines the list of defines currently in use
  37247. */
  37248. ImageProcessingConfiguration.PrepareUniforms = function (uniforms, defines) {
  37249. if (defines.EXPOSURE) {
  37250. uniforms.push("exposureLinear");
  37251. }
  37252. if (defines.CONTRAST) {
  37253. uniforms.push("contrast");
  37254. }
  37255. if (defines.COLORGRADING) {
  37256. uniforms.push("colorTransformSettings");
  37257. }
  37258. if (defines.VIGNETTE) {
  37259. uniforms.push("vInverseScreenSize");
  37260. uniforms.push("vignetteSettings1");
  37261. uniforms.push("vignetteSettings2");
  37262. }
  37263. if (defines.COLORCURVES) {
  37264. BABYLON.ColorCurves.PrepareUniforms(uniforms);
  37265. }
  37266. if (defines.GRAIN) {
  37267. uniforms.push("grainVarianceAmount");
  37268. uniforms.push("grainAnimatedSeed");
  37269. }
  37270. };
  37271. /**
  37272. * Prepare the list of samplers associated with the Image Processing effects.
  37273. * @param uniformsList The list of uniforms used in the effect
  37274. * @param defines the list of defines currently in use
  37275. */
  37276. ImageProcessingConfiguration.PrepareSamplers = function (samplersList, defines) {
  37277. if (defines.COLORGRADING) {
  37278. samplersList.push("txColorTransform");
  37279. }
  37280. };
  37281. /**
  37282. * Prepare the list of defines associated to the shader.
  37283. * @param defines the list of defines to complete
  37284. */
  37285. ImageProcessingConfiguration.prototype.prepareDefines = function (defines, forPostProcess) {
  37286. if (forPostProcess === void 0) { forPostProcess = false; }
  37287. if (forPostProcess !== this.applyByPostProcess || !this._isEnabled) {
  37288. defines.VIGNETTE = false;
  37289. defines.TONEMAPPING = false;
  37290. defines.CONTRAST = false;
  37291. defines.EXPOSURE = false;
  37292. defines.COLORCURVES = false;
  37293. defines.COLORGRADING = false;
  37294. defines.COLORGRADING3D = false;
  37295. defines.IMAGEPROCESSING = false;
  37296. defines.IMAGEPROCESSINGPOSTPROCESS = this.applyByPostProcess && this._isEnabled;
  37297. return;
  37298. }
  37299. defines.VIGNETTE = this.vignetteEnabled;
  37300. defines.VIGNETTEBLENDMODEMULTIPLY = (this.vignetteBlendMode === ImageProcessingConfiguration._VIGNETTEMODE_MULTIPLY);
  37301. defines.VIGNETTEBLENDMODEOPAQUE = !defines.VIGNETTEBLENDMODEMULTIPLY;
  37302. defines.TONEMAPPING = this.toneMappingEnabled;
  37303. defines.CONTRAST = (this.contrast !== 1.0);
  37304. defines.EXPOSURE = (this.exposure !== 1.0);
  37305. defines.COLORCURVES = (this.colorCurvesEnabled && !!this.colorCurves);
  37306. defines.COLORGRADING = (this.colorGradingEnabled && !!this.colorGradingTexture);
  37307. if (defines.COLORGRADING) {
  37308. defines.COLORGRADING3D = this.colorGradingTexture.is3D;
  37309. }
  37310. else {
  37311. defines.COLORGRADING3D = false;
  37312. }
  37313. defines.SAMPLER3DGREENDEPTH = this.colorGradingWithGreenDepth;
  37314. defines.SAMPLER3DBGRMAP = this.colorGradingBGR;
  37315. defines.IMAGEPROCESSINGPOSTPROCESS = this.applyByPostProcess;
  37316. defines.GRAIN = this.grainEnabled;
  37317. defines.IMAGEPROCESSING = defines.VIGNETTE || defines.TONEMAPPING || defines.CONTRAST || defines.EXPOSURE || defines.COLORCURVES || defines.COLORGRADING || defines.GRAIN;
  37318. };
  37319. /**
  37320. * Returns true if all the image processing information are ready.
  37321. */
  37322. ImageProcessingConfiguration.prototype.isReady = function () {
  37323. // Color Grading texure can not be none blocking.
  37324. return !this.colorGradingEnabled || !this.colorGradingTexture || this.colorGradingTexture.isReady();
  37325. };
  37326. /**
  37327. * Binds the image processing to the shader.
  37328. * @param effect The effect to bind to
  37329. */
  37330. ImageProcessingConfiguration.prototype.bind = function (effect, aspectRatio) {
  37331. if (aspectRatio === void 0) { aspectRatio = 1; }
  37332. // Color Curves
  37333. if (this._colorCurvesEnabled && this.colorCurves) {
  37334. BABYLON.ColorCurves.Bind(this.colorCurves, effect);
  37335. }
  37336. // Vignette
  37337. if (this._vignetteEnabled) {
  37338. var inverseWidth = 1 / effect.getEngine().getRenderWidth();
  37339. var inverseHeight = 1 / effect.getEngine().getRenderHeight();
  37340. effect.setFloat2("vInverseScreenSize", inverseWidth, inverseHeight);
  37341. var vignetteScaleY = Math.tan(this.vignetteCameraFov * 0.5);
  37342. var vignetteScaleX = vignetteScaleY * aspectRatio;
  37343. var vignetteScaleGeometricMean = Math.sqrt(vignetteScaleX * vignetteScaleY);
  37344. vignetteScaleX = BABYLON.Tools.Mix(vignetteScaleX, vignetteScaleGeometricMean, this.vignetteStretch);
  37345. vignetteScaleY = BABYLON.Tools.Mix(vignetteScaleY, vignetteScaleGeometricMean, this.vignetteStretch);
  37346. effect.setFloat4("vignetteSettings1", vignetteScaleX, vignetteScaleY, -vignetteScaleX * this.vignetteCentreX, -vignetteScaleY * this.vignetteCentreY);
  37347. var vignettePower = -2.0 * this.vignetteWeight;
  37348. effect.setFloat4("vignetteSettings2", this.vignetteColor.r, this.vignetteColor.g, this.vignetteColor.b, vignettePower);
  37349. }
  37350. // Exposure
  37351. effect.setFloat("exposureLinear", this.exposure);
  37352. // Contrast
  37353. effect.setFloat("contrast", this.contrast);
  37354. // Color transform settings
  37355. if (this.colorGradingTexture) {
  37356. effect.setTexture("txColorTransform", this.colorGradingTexture);
  37357. var textureSize = this.colorGradingTexture.getSize().height;
  37358. effect.setFloat4("colorTransformSettings", (textureSize - 1) / textureSize, // textureScale
  37359. 0.5 / textureSize, // textureOffset
  37360. textureSize, // textureSize
  37361. this.colorGradingTexture.level // weight
  37362. );
  37363. }
  37364. effect.setFloat("grainVarianceAmount", this.grainIntensity);
  37365. effect.setFloat("grainAnimatedSeed", this.grainAnimated ? Math.random() + 1 : 1);
  37366. };
  37367. /**
  37368. * Clones the current image processing instance.
  37369. * @return The cloned image processing
  37370. */
  37371. ImageProcessingConfiguration.prototype.clone = function () {
  37372. return BABYLON.SerializationHelper.Clone(function () { return new ImageProcessingConfiguration(); }, this);
  37373. };
  37374. /**
  37375. * Serializes the current image processing instance to a json representation.
  37376. * @return a JSON representation
  37377. */
  37378. ImageProcessingConfiguration.prototype.serialize = function () {
  37379. return BABYLON.SerializationHelper.Serialize(this);
  37380. };
  37381. /**
  37382. * Parses the image processing from a json representation.
  37383. * @param source the JSON source to parse
  37384. * @return The parsed image processing
  37385. */
  37386. ImageProcessingConfiguration.Parse = function (source) {
  37387. return BABYLON.SerializationHelper.Parse(function () { return new ImageProcessingConfiguration(); }, source, null, null);
  37388. };
  37389. Object.defineProperty(ImageProcessingConfiguration, "VIGNETTEMODE_MULTIPLY", {
  37390. /**
  37391. * Used to apply the vignette as a mix with the pixel color.
  37392. */
  37393. get: function () {
  37394. return this._VIGNETTEMODE_MULTIPLY;
  37395. },
  37396. enumerable: true,
  37397. configurable: true
  37398. });
  37399. Object.defineProperty(ImageProcessingConfiguration, "VIGNETTEMODE_OPAQUE", {
  37400. /**
  37401. * Used to apply the vignette as a replacement of the pixel color.
  37402. */
  37403. get: function () {
  37404. return this._VIGNETTEMODE_OPAQUE;
  37405. },
  37406. enumerable: true,
  37407. configurable: true
  37408. });
  37409. // Static constants associated to the image processing.
  37410. ImageProcessingConfiguration._VIGNETTEMODE_MULTIPLY = 0;
  37411. ImageProcessingConfiguration._VIGNETTEMODE_OPAQUE = 1;
  37412. __decorate([
  37413. BABYLON.serializeAsColorCurves()
  37414. ], ImageProcessingConfiguration.prototype, "colorCurves", void 0);
  37415. __decorate([
  37416. BABYLON.serialize()
  37417. ], ImageProcessingConfiguration.prototype, "_colorCurvesEnabled", void 0);
  37418. __decorate([
  37419. BABYLON.serializeAsTexture()
  37420. ], ImageProcessingConfiguration.prototype, "colorGradingTexture", void 0);
  37421. __decorate([
  37422. BABYLON.serialize()
  37423. ], ImageProcessingConfiguration.prototype, "_colorGradingEnabled", void 0);
  37424. __decorate([
  37425. BABYLON.serialize()
  37426. ], ImageProcessingConfiguration.prototype, "_colorGradingWithGreenDepth", void 0);
  37427. __decorate([
  37428. BABYLON.serialize()
  37429. ], ImageProcessingConfiguration.prototype, "_colorGradingBGR", void 0);
  37430. __decorate([
  37431. BABYLON.serialize()
  37432. ], ImageProcessingConfiguration.prototype, "_exposure", void 0);
  37433. __decorate([
  37434. BABYLON.serialize()
  37435. ], ImageProcessingConfiguration.prototype, "_toneMappingEnabled", void 0);
  37436. __decorate([
  37437. BABYLON.serialize()
  37438. ], ImageProcessingConfiguration.prototype, "_contrast", void 0);
  37439. __decorate([
  37440. BABYLON.serialize()
  37441. ], ImageProcessingConfiguration.prototype, "vignetteStretch", void 0);
  37442. __decorate([
  37443. BABYLON.serialize()
  37444. ], ImageProcessingConfiguration.prototype, "vignetteCentreX", void 0);
  37445. __decorate([
  37446. BABYLON.serialize()
  37447. ], ImageProcessingConfiguration.prototype, "vignetteCentreY", void 0);
  37448. __decorate([
  37449. BABYLON.serialize()
  37450. ], ImageProcessingConfiguration.prototype, "vignetteWeight", void 0);
  37451. __decorate([
  37452. BABYLON.serializeAsColor4()
  37453. ], ImageProcessingConfiguration.prototype, "vignetteColor", void 0);
  37454. __decorate([
  37455. BABYLON.serialize()
  37456. ], ImageProcessingConfiguration.prototype, "vignetteCameraFov", void 0);
  37457. __decorate([
  37458. BABYLON.serialize()
  37459. ], ImageProcessingConfiguration.prototype, "_grainEnabled", void 0);
  37460. __decorate([
  37461. BABYLON.serialize()
  37462. ], ImageProcessingConfiguration.prototype, "_grainIntensity", void 0);
  37463. __decorate([
  37464. BABYLON.serialize()
  37465. ], ImageProcessingConfiguration.prototype, "_grainAnimated", void 0);
  37466. __decorate([
  37467. BABYLON.serialize()
  37468. ], ImageProcessingConfiguration.prototype, "_vignetteBlendMode", void 0);
  37469. __decorate([
  37470. BABYLON.serialize()
  37471. ], ImageProcessingConfiguration.prototype, "_vignetteEnabled", void 0);
  37472. __decorate([
  37473. BABYLON.serialize()
  37474. ], ImageProcessingConfiguration.prototype, "_applyByPostProcess", void 0);
  37475. __decorate([
  37476. BABYLON.serialize()
  37477. ], ImageProcessingConfiguration.prototype, "_isEnabled", void 0);
  37478. return ImageProcessingConfiguration;
  37479. }());
  37480. BABYLON.ImageProcessingConfiguration = ImageProcessingConfiguration;
  37481. })(BABYLON || (BABYLON = {}));
  37482. //# sourceMappingURL=babylon.imageProcessingConfiguration.js.map
  37483. var BABYLON;
  37484. (function (BABYLON) {
  37485. /**
  37486. * This represents a color grading texture. This acts as a lookup table LUT, useful during post process
  37487. * It can help converting any input color in a desired output one. This can then be used to create effects
  37488. * from sepia, black and white to sixties or futuristic rendering...
  37489. *
  37490. * The only supported format is currently 3dl.
  37491. * More information on LUT: https://en.wikipedia.org/wiki/3D_lookup_table/
  37492. */
  37493. var ColorGradingTexture = /** @class */ (function (_super) {
  37494. __extends(ColorGradingTexture, _super);
  37495. /**
  37496. * Instantiates a ColorGradingTexture from the following parameters.
  37497. *
  37498. * @param url The location of the color gradind data (currently only supporting 3dl)
  37499. * @param scene The scene the texture will be used in
  37500. */
  37501. function ColorGradingTexture(url, scene) {
  37502. var _this = _super.call(this, scene) || this;
  37503. if (!url) {
  37504. return _this;
  37505. }
  37506. _this._engine = scene.getEngine();
  37507. _this._textureMatrix = BABYLON.Matrix.Identity();
  37508. _this.name = url;
  37509. _this.url = url;
  37510. _this.hasAlpha = false;
  37511. _this.isCube = false;
  37512. _this.is3D = _this._engine.webGLVersion > 1;
  37513. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  37514. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  37515. _this.wrapR = BABYLON.Texture.CLAMP_ADDRESSMODE;
  37516. _this.anisotropicFilteringLevel = 1;
  37517. _this._texture = _this._getFromCache(url, true);
  37518. if (!_this._texture) {
  37519. if (!scene.useDelayedTextureLoading) {
  37520. _this.loadTexture();
  37521. }
  37522. else {
  37523. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  37524. }
  37525. }
  37526. return _this;
  37527. }
  37528. /**
  37529. * Returns the texture matrix used in most of the material.
  37530. * This is not used in color grading but keep for troubleshooting purpose (easily swap diffuse by colorgrading to look in).
  37531. */
  37532. ColorGradingTexture.prototype.getTextureMatrix = function () {
  37533. return this._textureMatrix;
  37534. };
  37535. /**
  37536. * Occurs when the file being loaded is a .3dl LUT file.
  37537. */
  37538. ColorGradingTexture.prototype.load3dlTexture = function () {
  37539. var engine = this._engine;
  37540. var texture;
  37541. if (engine.webGLVersion === 1) {
  37542. texture = engine.createRawTexture(null, 1, 1, BABYLON.Engine.TEXTUREFORMAT_RGBA, false, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  37543. }
  37544. else {
  37545. texture = engine.createRawTexture3D(null, 1, 1, 1, BABYLON.Engine.TEXTUREFORMAT_RGBA, false, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  37546. }
  37547. this._texture = texture;
  37548. var callback = function (text) {
  37549. if (typeof text !== "string") {
  37550. return;
  37551. }
  37552. var data = null;
  37553. var tempData = null;
  37554. var line;
  37555. var lines = text.split('\n');
  37556. var size = 0, pixelIndexW = 0, pixelIndexH = 0, pixelIndexSlice = 0;
  37557. var maxColor = 0;
  37558. for (var i = 0; i < lines.length; i++) {
  37559. line = lines[i];
  37560. if (!ColorGradingTexture._noneEmptyLineRegex.test(line))
  37561. continue;
  37562. if (line.indexOf('#') === 0)
  37563. continue;
  37564. var words = line.split(" ");
  37565. if (size === 0) {
  37566. // Number of space + one
  37567. size = words.length;
  37568. data = new Uint8Array(size * size * size * 4); // volume texture of side size and rgb 8
  37569. tempData = new Float32Array(size * size * size * 4);
  37570. continue;
  37571. }
  37572. if (size != 0) {
  37573. var r = Math.max(parseInt(words[0]), 0);
  37574. var g = Math.max(parseInt(words[1]), 0);
  37575. var b = Math.max(parseInt(words[2]), 0);
  37576. maxColor = Math.max(r, maxColor);
  37577. maxColor = Math.max(g, maxColor);
  37578. maxColor = Math.max(b, maxColor);
  37579. var pixelStorageIndex = (pixelIndexW + pixelIndexSlice * size + pixelIndexH * size * size) * 4;
  37580. if (tempData) {
  37581. tempData[pixelStorageIndex + 0] = r;
  37582. tempData[pixelStorageIndex + 1] = g;
  37583. tempData[pixelStorageIndex + 2] = b;
  37584. }
  37585. pixelIndexSlice++;
  37586. if (pixelIndexSlice % size == 0) {
  37587. pixelIndexH++;
  37588. pixelIndexSlice = 0;
  37589. if (pixelIndexH % size == 0) {
  37590. pixelIndexW++;
  37591. pixelIndexH = 0;
  37592. }
  37593. }
  37594. }
  37595. }
  37596. if (tempData && data) {
  37597. for (var i = 0; i < tempData.length; i++) {
  37598. if (i > 0 && (i + 1) % 4 === 0) {
  37599. data[i] = 255;
  37600. }
  37601. else {
  37602. var value = tempData[i];
  37603. data[i] = (value / maxColor * 255);
  37604. }
  37605. }
  37606. }
  37607. if (texture.is3D) {
  37608. texture.updateSize(size, size, size);
  37609. engine.updateRawTexture3D(texture, data, BABYLON.Engine.TEXTUREFORMAT_RGBA, false);
  37610. }
  37611. else {
  37612. texture.updateSize(size * size, size);
  37613. engine.updateRawTexture(texture, data, BABYLON.Engine.TEXTUREFORMAT_RGBA, false);
  37614. }
  37615. };
  37616. var scene = this.getScene();
  37617. if (scene) {
  37618. scene._loadFile(this.url, callback);
  37619. }
  37620. else {
  37621. this._engine._loadFile(this.url, callback);
  37622. }
  37623. return this._texture;
  37624. };
  37625. /**
  37626. * Starts the loading process of the texture.
  37627. */
  37628. ColorGradingTexture.prototype.loadTexture = function () {
  37629. if (this.url && this.url.toLocaleLowerCase().indexOf(".3dl") == (this.url.length - 4)) {
  37630. this.load3dlTexture();
  37631. }
  37632. };
  37633. /**
  37634. * Clones the color gradind texture.
  37635. */
  37636. ColorGradingTexture.prototype.clone = function () {
  37637. var newTexture = new ColorGradingTexture(this.url, this.getScene());
  37638. // Base texture
  37639. newTexture.level = this.level;
  37640. return newTexture;
  37641. };
  37642. /**
  37643. * Called during delayed load for textures.
  37644. */
  37645. ColorGradingTexture.prototype.delayLoad = function () {
  37646. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  37647. return;
  37648. }
  37649. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  37650. this._texture = this._getFromCache(this.url, true);
  37651. if (!this._texture) {
  37652. this.loadTexture();
  37653. }
  37654. };
  37655. /**
  37656. * Parses a color grading texture serialized by Babylon.
  37657. * @param parsedTexture The texture information being parsedTexture
  37658. * @param scene The scene to load the texture in
  37659. * @param rootUrl The root url of the data assets to load
  37660. * @return A color gradind texture
  37661. */
  37662. ColorGradingTexture.Parse = function (parsedTexture, scene, rootUrl) {
  37663. var texture = null;
  37664. if (parsedTexture.name && !parsedTexture.isRenderTarget) {
  37665. texture = new ColorGradingTexture(parsedTexture.name, scene);
  37666. texture.name = parsedTexture.name;
  37667. texture.level = parsedTexture.level;
  37668. }
  37669. return texture;
  37670. };
  37671. /**
  37672. * Serializes the LUT texture to json format.
  37673. */
  37674. ColorGradingTexture.prototype.serialize = function () {
  37675. if (!this.name) {
  37676. return null;
  37677. }
  37678. var serializationObject = {};
  37679. serializationObject.name = this.name;
  37680. serializationObject.level = this.level;
  37681. serializationObject.customType = "BABYLON.ColorGradingTexture";
  37682. return serializationObject;
  37683. };
  37684. /**
  37685. * Empty line regex stored for GC.
  37686. */
  37687. ColorGradingTexture._noneEmptyLineRegex = /\S+/;
  37688. return ColorGradingTexture;
  37689. }(BABYLON.BaseTexture));
  37690. BABYLON.ColorGradingTexture = ColorGradingTexture;
  37691. })(BABYLON || (BABYLON = {}));
  37692. //# sourceMappingURL=babylon.colorGradingTexture.js.map
  37693. var BABYLON;
  37694. (function (BABYLON) {
  37695. /**
  37696. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  37697. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  37698. * 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;
  37699. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  37700. */
  37701. var ColorCurves = /** @class */ (function () {
  37702. function ColorCurves() {
  37703. this._dirty = true;
  37704. this._tempColor = new BABYLON.Color4(0, 0, 0, 0);
  37705. this._globalCurve = new BABYLON.Color4(0, 0, 0, 0);
  37706. this._highlightsCurve = new BABYLON.Color4(0, 0, 0, 0);
  37707. this._midtonesCurve = new BABYLON.Color4(0, 0, 0, 0);
  37708. this._shadowsCurve = new BABYLON.Color4(0, 0, 0, 0);
  37709. this._positiveCurve = new BABYLON.Color4(0, 0, 0, 0);
  37710. this._negativeCurve = new BABYLON.Color4(0, 0, 0, 0);
  37711. this._globalHue = 30;
  37712. this._globalDensity = 0;
  37713. this._globalSaturation = 0;
  37714. this._globalExposure = 0;
  37715. this._highlightsHue = 30;
  37716. this._highlightsDensity = 0;
  37717. this._highlightsSaturation = 0;
  37718. this._highlightsExposure = 0;
  37719. this._midtonesHue = 30;
  37720. this._midtonesDensity = 0;
  37721. this._midtonesSaturation = 0;
  37722. this._midtonesExposure = 0;
  37723. this._shadowsHue = 30;
  37724. this._shadowsDensity = 0;
  37725. this._shadowsSaturation = 0;
  37726. this._shadowsExposure = 0;
  37727. }
  37728. Object.defineProperty(ColorCurves.prototype, "globalHue", {
  37729. /**
  37730. * Gets the global Hue value.
  37731. * 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).
  37732. */
  37733. get: function () {
  37734. return this._globalHue;
  37735. },
  37736. /**
  37737. * Sets the global Hue value.
  37738. * 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).
  37739. */
  37740. set: function (value) {
  37741. this._globalHue = value;
  37742. this._dirty = true;
  37743. },
  37744. enumerable: true,
  37745. configurable: true
  37746. });
  37747. Object.defineProperty(ColorCurves.prototype, "globalDensity", {
  37748. /**
  37749. * Gets the global Density value.
  37750. * 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.
  37751. * Values less than zero provide a filter of opposite hue.
  37752. */
  37753. get: function () {
  37754. return this._globalDensity;
  37755. },
  37756. /**
  37757. * Sets the global Density value.
  37758. * 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.
  37759. * Values less than zero provide a filter of opposite hue.
  37760. */
  37761. set: function (value) {
  37762. this._globalDensity = value;
  37763. this._dirty = true;
  37764. },
  37765. enumerable: true,
  37766. configurable: true
  37767. });
  37768. Object.defineProperty(ColorCurves.prototype, "globalSaturation", {
  37769. /**
  37770. * Gets the global Saturation value.
  37771. * 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.
  37772. */
  37773. get: function () {
  37774. return this._globalSaturation;
  37775. },
  37776. /**
  37777. * Sets the global Saturation value.
  37778. * 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.
  37779. */
  37780. set: function (value) {
  37781. this._globalSaturation = value;
  37782. this._dirty = true;
  37783. },
  37784. enumerable: true,
  37785. configurable: true
  37786. });
  37787. Object.defineProperty(ColorCurves.prototype, "highlightsHue", {
  37788. /**
  37789. * Gets the highlights Hue value.
  37790. * 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).
  37791. */
  37792. get: function () {
  37793. return this._highlightsHue;
  37794. },
  37795. /**
  37796. * Sets the highlights Hue value.
  37797. * 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).
  37798. */
  37799. set: function (value) {
  37800. this._highlightsHue = value;
  37801. this._dirty = true;
  37802. },
  37803. enumerable: true,
  37804. configurable: true
  37805. });
  37806. Object.defineProperty(ColorCurves.prototype, "highlightsDensity", {
  37807. /**
  37808. * Gets the highlights Density value.
  37809. * 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.
  37810. * Values less than zero provide a filter of opposite hue.
  37811. */
  37812. get: function () {
  37813. return this._highlightsDensity;
  37814. },
  37815. /**
  37816. * Sets the highlights Density value.
  37817. * 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.
  37818. * Values less than zero provide a filter of opposite hue.
  37819. */
  37820. set: function (value) {
  37821. this._highlightsDensity = value;
  37822. this._dirty = true;
  37823. },
  37824. enumerable: true,
  37825. configurable: true
  37826. });
  37827. Object.defineProperty(ColorCurves.prototype, "highlightsSaturation", {
  37828. /**
  37829. * Gets the highlights Saturation value.
  37830. * 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.
  37831. */
  37832. get: function () {
  37833. return this._highlightsSaturation;
  37834. },
  37835. /**
  37836. * Sets the highlights Saturation value.
  37837. * 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.
  37838. */
  37839. set: function (value) {
  37840. this._highlightsSaturation = value;
  37841. this._dirty = true;
  37842. },
  37843. enumerable: true,
  37844. configurable: true
  37845. });
  37846. Object.defineProperty(ColorCurves.prototype, "highlightsExposure", {
  37847. /**
  37848. * Gets the highlights Exposure value.
  37849. * 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.
  37850. */
  37851. get: function () {
  37852. return this._highlightsExposure;
  37853. },
  37854. /**
  37855. * Sets the highlights Exposure value.
  37856. * 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.
  37857. */
  37858. set: function (value) {
  37859. this._highlightsExposure = value;
  37860. this._dirty = true;
  37861. },
  37862. enumerable: true,
  37863. configurable: true
  37864. });
  37865. Object.defineProperty(ColorCurves.prototype, "midtonesHue", {
  37866. /**
  37867. * Gets the midtones Hue value.
  37868. * 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).
  37869. */
  37870. get: function () {
  37871. return this._midtonesHue;
  37872. },
  37873. /**
  37874. * Sets the midtones Hue value.
  37875. * 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).
  37876. */
  37877. set: function (value) {
  37878. this._midtonesHue = value;
  37879. this._dirty = true;
  37880. },
  37881. enumerable: true,
  37882. configurable: true
  37883. });
  37884. Object.defineProperty(ColorCurves.prototype, "midtonesDensity", {
  37885. /**
  37886. * Gets the midtones Density value.
  37887. * 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.
  37888. * Values less than zero provide a filter of opposite hue.
  37889. */
  37890. get: function () {
  37891. return this._midtonesDensity;
  37892. },
  37893. /**
  37894. * Sets the midtones Density value.
  37895. * 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.
  37896. * Values less than zero provide a filter of opposite hue.
  37897. */
  37898. set: function (value) {
  37899. this._midtonesDensity = value;
  37900. this._dirty = true;
  37901. },
  37902. enumerable: true,
  37903. configurable: true
  37904. });
  37905. Object.defineProperty(ColorCurves.prototype, "midtonesSaturation", {
  37906. /**
  37907. * Gets the midtones Saturation value.
  37908. * 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.
  37909. */
  37910. get: function () {
  37911. return this._midtonesSaturation;
  37912. },
  37913. /**
  37914. * Sets the midtones Saturation value.
  37915. * 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.
  37916. */
  37917. set: function (value) {
  37918. this._midtonesSaturation = value;
  37919. this._dirty = true;
  37920. },
  37921. enumerable: true,
  37922. configurable: true
  37923. });
  37924. Object.defineProperty(ColorCurves.prototype, "midtonesExposure", {
  37925. /**
  37926. * Gets the midtones Exposure value.
  37927. * 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.
  37928. */
  37929. get: function () {
  37930. return this._midtonesExposure;
  37931. },
  37932. /**
  37933. * Sets the midtones Exposure value.
  37934. * 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.
  37935. */
  37936. set: function (value) {
  37937. this._midtonesExposure = value;
  37938. this._dirty = true;
  37939. },
  37940. enumerable: true,
  37941. configurable: true
  37942. });
  37943. Object.defineProperty(ColorCurves.prototype, "shadowsHue", {
  37944. /**
  37945. * Gets the shadows Hue value.
  37946. * 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).
  37947. */
  37948. get: function () {
  37949. return this._shadowsHue;
  37950. },
  37951. /**
  37952. * Sets the shadows Hue value.
  37953. * 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).
  37954. */
  37955. set: function (value) {
  37956. this._shadowsHue = value;
  37957. this._dirty = true;
  37958. },
  37959. enumerable: true,
  37960. configurable: true
  37961. });
  37962. Object.defineProperty(ColorCurves.prototype, "shadowsDensity", {
  37963. /**
  37964. * Gets the shadows Density value.
  37965. * 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.
  37966. * Values less than zero provide a filter of opposite hue.
  37967. */
  37968. get: function () {
  37969. return this._shadowsDensity;
  37970. },
  37971. /**
  37972. * Sets the shadows Density value.
  37973. * 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.
  37974. * Values less than zero provide a filter of opposite hue.
  37975. */
  37976. set: function (value) {
  37977. this._shadowsDensity = value;
  37978. this._dirty = true;
  37979. },
  37980. enumerable: true,
  37981. configurable: true
  37982. });
  37983. Object.defineProperty(ColorCurves.prototype, "shadowsSaturation", {
  37984. /**
  37985. * Gets the shadows Saturation value.
  37986. * 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.
  37987. */
  37988. get: function () {
  37989. return this._shadowsSaturation;
  37990. },
  37991. /**
  37992. * Sets the shadows Saturation value.
  37993. * 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.
  37994. */
  37995. set: function (value) {
  37996. this._shadowsSaturation = value;
  37997. this._dirty = true;
  37998. },
  37999. enumerable: true,
  38000. configurable: true
  38001. });
  38002. Object.defineProperty(ColorCurves.prototype, "shadowsExposure", {
  38003. /**
  38004. * Gets the shadows Exposure value.
  38005. * 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.
  38006. */
  38007. get: function () {
  38008. return this._shadowsExposure;
  38009. },
  38010. /**
  38011. * Sets the shadows Exposure value.
  38012. * 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.
  38013. */
  38014. set: function (value) {
  38015. this._shadowsExposure = value;
  38016. this._dirty = true;
  38017. },
  38018. enumerable: true,
  38019. configurable: true
  38020. });
  38021. ColorCurves.prototype.getClassName = function () {
  38022. return "ColorCurves";
  38023. };
  38024. /**
  38025. * Binds the color curves to the shader.
  38026. * @param colorCurves The color curve to bind
  38027. * @param effect The effect to bind to
  38028. */
  38029. ColorCurves.Bind = function (colorCurves, effect, positiveUniform, neutralUniform, negativeUniform) {
  38030. if (positiveUniform === void 0) { positiveUniform = "vCameraColorCurvePositive"; }
  38031. if (neutralUniform === void 0) { neutralUniform = "vCameraColorCurveNeutral"; }
  38032. if (negativeUniform === void 0) { negativeUniform = "vCameraColorCurveNegative"; }
  38033. if (colorCurves._dirty) {
  38034. colorCurves._dirty = false;
  38035. // Fill in global info.
  38036. colorCurves.getColorGradingDataToRef(colorCurves._globalHue, colorCurves._globalDensity, colorCurves._globalSaturation, colorCurves._globalExposure, colorCurves._globalCurve);
  38037. // Compute highlights info.
  38038. colorCurves.getColorGradingDataToRef(colorCurves._highlightsHue, colorCurves._highlightsDensity, colorCurves._highlightsSaturation, colorCurves._highlightsExposure, colorCurves._tempColor);
  38039. colorCurves._tempColor.multiplyToRef(colorCurves._globalCurve, colorCurves._highlightsCurve);
  38040. // Compute midtones info.
  38041. colorCurves.getColorGradingDataToRef(colorCurves._midtonesHue, colorCurves._midtonesDensity, colorCurves._midtonesSaturation, colorCurves._midtonesExposure, colorCurves._tempColor);
  38042. colorCurves._tempColor.multiplyToRef(colorCurves._globalCurve, colorCurves._midtonesCurve);
  38043. // Compute shadows info.
  38044. colorCurves.getColorGradingDataToRef(colorCurves._shadowsHue, colorCurves._shadowsDensity, colorCurves._shadowsSaturation, colorCurves._shadowsExposure, colorCurves._tempColor);
  38045. colorCurves._tempColor.multiplyToRef(colorCurves._globalCurve, colorCurves._shadowsCurve);
  38046. // Compute deltas (neutral is midtones).
  38047. colorCurves._highlightsCurve.subtractToRef(colorCurves._midtonesCurve, colorCurves._positiveCurve);
  38048. colorCurves._midtonesCurve.subtractToRef(colorCurves._shadowsCurve, colorCurves._negativeCurve);
  38049. }
  38050. if (effect) {
  38051. effect.setFloat4(positiveUniform, colorCurves._positiveCurve.r, colorCurves._positiveCurve.g, colorCurves._positiveCurve.b, colorCurves._positiveCurve.a);
  38052. effect.setFloat4(neutralUniform, colorCurves._midtonesCurve.r, colorCurves._midtonesCurve.g, colorCurves._midtonesCurve.b, colorCurves._midtonesCurve.a);
  38053. effect.setFloat4(negativeUniform, colorCurves._negativeCurve.r, colorCurves._negativeCurve.g, colorCurves._negativeCurve.b, colorCurves._negativeCurve.a);
  38054. }
  38055. };
  38056. /**
  38057. * Prepare the list of uniforms associated with the ColorCurves effects.
  38058. * @param uniformsList The list of uniforms used in the effect
  38059. */
  38060. ColorCurves.PrepareUniforms = function (uniformsList) {
  38061. uniformsList.push("vCameraColorCurveNeutral", "vCameraColorCurvePositive", "vCameraColorCurveNegative");
  38062. };
  38063. /**
  38064. * Returns color grading data based on a hue, density, saturation and exposure value.
  38065. * @param filterHue The hue of the color filter.
  38066. * @param filterDensity The density of the color filter.
  38067. * @param saturation The saturation.
  38068. * @param exposure The exposure.
  38069. * @param result The result data container.
  38070. */
  38071. ColorCurves.prototype.getColorGradingDataToRef = function (hue, density, saturation, exposure, result) {
  38072. if (hue == null) {
  38073. return;
  38074. }
  38075. hue = ColorCurves.clamp(hue, 0, 360);
  38076. density = ColorCurves.clamp(density, -100, 100);
  38077. saturation = ColorCurves.clamp(saturation, -100, 100);
  38078. exposure = ColorCurves.clamp(exposure, -100, 100);
  38079. // Remap the slider/config filter density with non-linear mapping and also scale by half
  38080. // so that the maximum filter density is only 50% control. This provides fine control
  38081. // for small values and reasonable range.
  38082. density = ColorCurves.applyColorGradingSliderNonlinear(density);
  38083. density *= 0.5;
  38084. exposure = ColorCurves.applyColorGradingSliderNonlinear(exposure);
  38085. if (density < 0) {
  38086. density *= -1;
  38087. hue = (hue + 180) % 360;
  38088. }
  38089. ColorCurves.fromHSBToRef(hue, density, 50 + 0.25 * exposure, result);
  38090. result.scaleToRef(2, result);
  38091. result.a = 1 + 0.01 * saturation;
  38092. };
  38093. /**
  38094. * Takes an input slider value and returns an adjusted value that provides extra control near the centre.
  38095. * @param value The input slider value in range [-100,100].
  38096. * @returns Adjusted value.
  38097. */
  38098. ColorCurves.applyColorGradingSliderNonlinear = function (value) {
  38099. value /= 100;
  38100. var x = Math.abs(value);
  38101. x = Math.pow(x, 2);
  38102. if (value < 0) {
  38103. x *= -1;
  38104. }
  38105. x *= 100;
  38106. return x;
  38107. };
  38108. /**
  38109. * Returns an RGBA Color4 based on Hue, Saturation and Brightness (also referred to as value, HSV).
  38110. * @param hue The hue (H) input.
  38111. * @param saturation The saturation (S) input.
  38112. * @param brightness The brightness (B) input.
  38113. * @result An RGBA color represented as Vector4.
  38114. */
  38115. ColorCurves.fromHSBToRef = function (hue, saturation, brightness, result) {
  38116. var h = ColorCurves.clamp(hue, 0, 360);
  38117. var s = ColorCurves.clamp(saturation / 100, 0, 1);
  38118. var v = ColorCurves.clamp(brightness / 100, 0, 1);
  38119. if (s === 0) {
  38120. result.r = v;
  38121. result.g = v;
  38122. result.b = v;
  38123. }
  38124. else {
  38125. // sector 0 to 5
  38126. h /= 60;
  38127. var i = Math.floor(h);
  38128. // fractional part of h
  38129. var f = h - i;
  38130. var p = v * (1 - s);
  38131. var q = v * (1 - s * f);
  38132. var t = v * (1 - s * (1 - f));
  38133. switch (i) {
  38134. case 0:
  38135. result.r = v;
  38136. result.g = t;
  38137. result.b = p;
  38138. break;
  38139. case 1:
  38140. result.r = q;
  38141. result.g = v;
  38142. result.b = p;
  38143. break;
  38144. case 2:
  38145. result.r = p;
  38146. result.g = v;
  38147. result.b = t;
  38148. break;
  38149. case 3:
  38150. result.r = p;
  38151. result.g = q;
  38152. result.b = v;
  38153. break;
  38154. case 4:
  38155. result.r = t;
  38156. result.g = p;
  38157. result.b = v;
  38158. break;
  38159. default:// case 5:
  38160. result.r = v;
  38161. result.g = p;
  38162. result.b = q;
  38163. break;
  38164. }
  38165. }
  38166. result.a = 1;
  38167. };
  38168. /**
  38169. * Returns a value clamped between min and max
  38170. * @param value The value to clamp
  38171. * @param min The minimum of value
  38172. * @param max The maximum of value
  38173. * @returns The clamped value.
  38174. */
  38175. ColorCurves.clamp = function (value, min, max) {
  38176. return Math.min(Math.max(value, min), max);
  38177. };
  38178. /**
  38179. * Clones the current color curve instance.
  38180. * @return The cloned curves
  38181. */
  38182. ColorCurves.prototype.clone = function () {
  38183. return BABYLON.SerializationHelper.Clone(function () { return new ColorCurves(); }, this);
  38184. };
  38185. /**
  38186. * Serializes the current color curve instance to a json representation.
  38187. * @return a JSON representation
  38188. */
  38189. ColorCurves.prototype.serialize = function () {
  38190. return BABYLON.SerializationHelper.Serialize(this);
  38191. };
  38192. /**
  38193. * Parses the color curve from a json representation.
  38194. * @param source the JSON source to parse
  38195. * @return The parsed curves
  38196. */
  38197. ColorCurves.Parse = function (source) {
  38198. return BABYLON.SerializationHelper.Parse(function () { return new ColorCurves(); }, source, null, null);
  38199. };
  38200. __decorate([
  38201. BABYLON.serialize()
  38202. ], ColorCurves.prototype, "_globalHue", void 0);
  38203. __decorate([
  38204. BABYLON.serialize()
  38205. ], ColorCurves.prototype, "_globalDensity", void 0);
  38206. __decorate([
  38207. BABYLON.serialize()
  38208. ], ColorCurves.prototype, "_globalSaturation", void 0);
  38209. __decorate([
  38210. BABYLON.serialize()
  38211. ], ColorCurves.prototype, "_globalExposure", void 0);
  38212. __decorate([
  38213. BABYLON.serialize()
  38214. ], ColorCurves.prototype, "_highlightsHue", void 0);
  38215. __decorate([
  38216. BABYLON.serialize()
  38217. ], ColorCurves.prototype, "_highlightsDensity", void 0);
  38218. __decorate([
  38219. BABYLON.serialize()
  38220. ], ColorCurves.prototype, "_highlightsSaturation", void 0);
  38221. __decorate([
  38222. BABYLON.serialize()
  38223. ], ColorCurves.prototype, "_highlightsExposure", void 0);
  38224. __decorate([
  38225. BABYLON.serialize()
  38226. ], ColorCurves.prototype, "_midtonesHue", void 0);
  38227. __decorate([
  38228. BABYLON.serialize()
  38229. ], ColorCurves.prototype, "_midtonesDensity", void 0);
  38230. __decorate([
  38231. BABYLON.serialize()
  38232. ], ColorCurves.prototype, "_midtonesSaturation", void 0);
  38233. __decorate([
  38234. BABYLON.serialize()
  38235. ], ColorCurves.prototype, "_midtonesExposure", void 0);
  38236. return ColorCurves;
  38237. }());
  38238. BABYLON.ColorCurves = ColorCurves;
  38239. })(BABYLON || (BABYLON = {}));
  38240. //# sourceMappingURL=babylon.colorCurves.js.map
  38241. //# sourceMappingURL=babylon.behavior.js.map
  38242. var BABYLON;
  38243. (function (BABYLON) {
  38244. /**
  38245. * "Static Class" containing the most commonly used helper while dealing with material for
  38246. * rendering purpose.
  38247. *
  38248. * It contains the basic tools to help defining defines, binding uniform for the common part of the materials.
  38249. *
  38250. * This works by convention in BabylonJS but is meant to be use only with shader following the in place naming rules and conventions.
  38251. */
  38252. var MaterialHelper = /** @class */ (function () {
  38253. function MaterialHelper() {
  38254. }
  38255. /**
  38256. * Bind the current view position to an effect.
  38257. * @param effect The effect to be bound
  38258. * @param scene The scene the eyes position is used from
  38259. */
  38260. MaterialHelper.BindEyePosition = function (effect, scene) {
  38261. if (scene._forcedViewPosition) {
  38262. effect.setVector3("vEyePosition", scene._forcedViewPosition);
  38263. return;
  38264. }
  38265. effect.setVector3("vEyePosition", scene._mirroredCameraPosition ? scene._mirroredCameraPosition : scene.activeCamera.globalPosition);
  38266. };
  38267. /**
  38268. * Helps preparing the defines values about the UVs in used in the effect.
  38269. * UVs are shared as much as we can accross chanels in the shaders.
  38270. * @param texture The texture we are preparing the UVs for
  38271. * @param defines The defines to update
  38272. * @param key The chanel key "diffuse", "specular"... used in the shader
  38273. */
  38274. MaterialHelper.PrepareDefinesForMergedUV = function (texture, defines, key) {
  38275. defines._needUVs = true;
  38276. defines[key] = true;
  38277. if (texture.getTextureMatrix().isIdentity(true)) {
  38278. defines[key + "DIRECTUV"] = texture.coordinatesIndex + 1;
  38279. if (texture.coordinatesIndex === 0) {
  38280. defines["MAINUV1"] = true;
  38281. }
  38282. else {
  38283. defines["MAINUV2"] = true;
  38284. }
  38285. }
  38286. else {
  38287. defines[key + "DIRECTUV"] = 0;
  38288. }
  38289. };
  38290. /**
  38291. * Binds a texture matrix value to its corrsponding uniform
  38292. * @param texture The texture to bind the matrix for
  38293. * @param uniformBuffer The uniform buffer receivin the data
  38294. * @param key The chanel key "diffuse", "specular"... used in the shader
  38295. */
  38296. MaterialHelper.BindTextureMatrix = function (texture, uniformBuffer, key) {
  38297. var matrix = texture.getTextureMatrix();
  38298. if (!matrix.isIdentity(true)) {
  38299. uniformBuffer.updateMatrix(key + "Matrix", matrix);
  38300. }
  38301. };
  38302. /**
  38303. * Helper used to prepare the list of defines associated with misc. values for shader compilation
  38304. * @param mesh defines the current mesh
  38305. * @param scene defines the current scene
  38306. * @param useLogarithmicDepth defines if logarithmic depth has to be turned on
  38307. * @param pointsCloud defines if point cloud rendering has to be turned on
  38308. * @param fogEnabled defines if fog has to be turned on
  38309. * @param alphaTest defines if alpha testing has to be turned on
  38310. * @param defines defines the current list of defines
  38311. */
  38312. MaterialHelper.PrepareDefinesForMisc = function (mesh, scene, useLogarithmicDepth, pointsCloud, fogEnabled, alphaTest, defines) {
  38313. if (defines._areMiscDirty) {
  38314. defines["LOGARITHMICDEPTH"] = useLogarithmicDepth;
  38315. defines["POINTSIZE"] = (pointsCloud || scene.forcePointsCloud);
  38316. defines["FOG"] = (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && fogEnabled);
  38317. defines["NONUNIFORMSCALING"] = mesh.nonUniformScaling;
  38318. defines["ALPHATEST"] = alphaTest;
  38319. }
  38320. };
  38321. /**
  38322. * Helper used to prepare the list of defines associated with frame values for shader compilation
  38323. * @param scene defines the current scene
  38324. * @param engine defines the current engine
  38325. * @param defines specifies the list of active defines
  38326. * @param useInstances defines if instances have to be turned on
  38327. * @param useClipPlane defines if clip plane have to be turned on
  38328. */
  38329. MaterialHelper.PrepareDefinesForFrameBoundValues = function (scene, engine, defines, useInstances, useClipPlane) {
  38330. if (useClipPlane === void 0) { useClipPlane = null; }
  38331. var changed = false;
  38332. if (useClipPlane == null) {
  38333. useClipPlane = (scene.clipPlane !== undefined && scene.clipPlane !== null);
  38334. }
  38335. if (defines["CLIPPLANE"] !== useClipPlane) {
  38336. defines["CLIPPLANE"] = useClipPlane;
  38337. changed = true;
  38338. }
  38339. if (defines["DEPTHPREPASS"] !== !engine.getColorWrite()) {
  38340. defines["DEPTHPREPASS"] = !defines["DEPTHPREPASS"];
  38341. changed = true;
  38342. }
  38343. if (defines["INSTANCES"] !== useInstances) {
  38344. defines["INSTANCES"] = useInstances;
  38345. changed = true;
  38346. }
  38347. if (changed) {
  38348. defines.markAsUnprocessed();
  38349. }
  38350. };
  38351. /**
  38352. * Prepares the defines used in the shader depending on the attributes data available in the mesh
  38353. * @param mesh The mesh containing the geometry data we will draw
  38354. * @param defines The defines to update
  38355. * @param useVertexColor Precise whether vertex colors should be used or not (override mesh info)
  38356. * @param useBones Precise whether bones should be used or not (override mesh info)
  38357. * @param useMorphTargets Precise whether morph targets should be used or not (override mesh info)
  38358. * @param useVertexAlpha Precise whether vertex alpha should be used or not (override mesh info)
  38359. * @returns false if defines are considered not dirty and have not been checked
  38360. */
  38361. MaterialHelper.PrepareDefinesForAttributes = function (mesh, defines, useVertexColor, useBones, useMorphTargets, useVertexAlpha) {
  38362. if (useMorphTargets === void 0) { useMorphTargets = false; }
  38363. if (useVertexAlpha === void 0) { useVertexAlpha = true; }
  38364. if (!defines._areAttributesDirty && defines._needNormals === defines._normals && defines._needUVs === defines._uvs) {
  38365. return false;
  38366. }
  38367. defines._normals = defines._needNormals;
  38368. defines._uvs = defines._needUVs;
  38369. defines["NORMAL"] = (defines._needNormals && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind));
  38370. if (defines._needNormals && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind)) {
  38371. defines["TANGENT"] = true;
  38372. }
  38373. if (defines._needUVs) {
  38374. defines["UV1"] = mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind);
  38375. defines["UV2"] = mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind);
  38376. }
  38377. else {
  38378. defines["UV1"] = false;
  38379. defines["UV2"] = false;
  38380. }
  38381. if (useVertexColor) {
  38382. var hasVertexColors = mesh.useVertexColors && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind);
  38383. defines["VERTEXCOLOR"] = hasVertexColors;
  38384. defines["VERTEXALPHA"] = mesh.hasVertexAlpha && hasVertexColors && useVertexAlpha;
  38385. }
  38386. if (useBones) {
  38387. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  38388. defines["NUM_BONE_INFLUENCERS"] = mesh.numBoneInfluencers;
  38389. defines["BonesPerMesh"] = (mesh.skeleton.bones.length + 1);
  38390. }
  38391. else {
  38392. defines["NUM_BONE_INFLUENCERS"] = 0;
  38393. defines["BonesPerMesh"] = 0;
  38394. }
  38395. }
  38396. if (useMorphTargets) {
  38397. var manager = mesh.morphTargetManager;
  38398. if (manager) {
  38399. defines["MORPHTARGETS_TANGENT"] = manager.supportsTangents && defines["TANGENT"];
  38400. defines["MORPHTARGETS_NORMAL"] = manager.supportsNormals && defines["NORMAL"];
  38401. defines["MORPHTARGETS"] = (manager.numInfluencers > 0);
  38402. defines["NUM_MORPH_INFLUENCERS"] = manager.numInfluencers;
  38403. }
  38404. else {
  38405. defines["MORPHTARGETS_TANGENT"] = false;
  38406. defines["MORPHTARGETS_NORMAL"] = false;
  38407. defines["MORPHTARGETS"] = false;
  38408. defines["NUM_MORPH_INFLUENCERS"] = 0;
  38409. }
  38410. }
  38411. return true;
  38412. };
  38413. /**
  38414. * Prepares the defines related to the light information passed in parameter
  38415. * @param scene The scene we are intending to draw
  38416. * @param mesh The mesh the effect is compiling for
  38417. * @param defines The defines to update
  38418. * @param specularSupported Specifies whether specular is supported or not (override lights data)
  38419. * @param maxSimultaneousLights Specfies how manuy lights can be added to the effect at max
  38420. * @param disableLighting Specifies whether the lighting is disabled (override scene and light)
  38421. * @returns true if normals will be required for the rest of the effect
  38422. */
  38423. MaterialHelper.PrepareDefinesForLights = function (scene, mesh, defines, specularSupported, maxSimultaneousLights, disableLighting) {
  38424. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  38425. if (disableLighting === void 0) { disableLighting = false; }
  38426. if (!defines._areLightsDirty) {
  38427. return defines._needNormals;
  38428. }
  38429. var lightIndex = 0;
  38430. var needNormals = false;
  38431. var needRebuild = false;
  38432. var lightmapMode = false;
  38433. var shadowEnabled = false;
  38434. var specularEnabled = false;
  38435. if (scene.lightsEnabled && !disableLighting) {
  38436. for (var _i = 0, _a = mesh._lightSources; _i < _a.length; _i++) {
  38437. var light = _a[_i];
  38438. needNormals = true;
  38439. if (defines["LIGHT" + lightIndex] === undefined) {
  38440. needRebuild = true;
  38441. }
  38442. defines["LIGHT" + lightIndex] = true;
  38443. defines["SPOTLIGHT" + lightIndex] = false;
  38444. defines["HEMILIGHT" + lightIndex] = false;
  38445. defines["POINTLIGHT" + lightIndex] = false;
  38446. defines["DIRLIGHT" + lightIndex] = false;
  38447. var type;
  38448. if (light.getTypeID() === BABYLON.Light.LIGHTTYPEID_SPOTLIGHT) {
  38449. type = "SPOTLIGHT" + lightIndex;
  38450. var spotLight = light;
  38451. defines["PROJECTEDLIGHTTEXTURE" + lightIndex] = spotLight.projectionTexture ? spotLight.projectionTexture.isReady() : false;
  38452. }
  38453. else if (light.getTypeID() === BABYLON.Light.LIGHTTYPEID_HEMISPHERICLIGHT) {
  38454. type = "HEMILIGHT" + lightIndex;
  38455. }
  38456. else if (light.getTypeID() === BABYLON.Light.LIGHTTYPEID_POINTLIGHT) {
  38457. type = "POINTLIGHT" + lightIndex;
  38458. }
  38459. else {
  38460. type = "DIRLIGHT" + lightIndex;
  38461. }
  38462. defines[type] = true;
  38463. // Specular
  38464. if (specularSupported && !light.specular.equalsFloats(0, 0, 0)) {
  38465. specularEnabled = true;
  38466. }
  38467. // Shadows
  38468. defines["SHADOW" + lightIndex] = false;
  38469. defines["SHADOWPCF" + lightIndex] = false;
  38470. defines["SHADOWESM" + lightIndex] = false;
  38471. defines["SHADOWCUBE" + lightIndex] = false;
  38472. if (mesh && mesh.receiveShadows && scene.shadowsEnabled && light.shadowEnabled) {
  38473. var shadowGenerator = light.getShadowGenerator();
  38474. if (shadowGenerator) {
  38475. shadowEnabled = true;
  38476. shadowGenerator.prepareDefines(defines, lightIndex);
  38477. }
  38478. }
  38479. if (light.lightmapMode != BABYLON.Light.LIGHTMAP_DEFAULT) {
  38480. lightmapMode = true;
  38481. defines["LIGHTMAPEXCLUDED" + lightIndex] = true;
  38482. defines["LIGHTMAPNOSPECULAR" + lightIndex] = (light.lightmapMode == BABYLON.Light.LIGHTMAP_SHADOWSONLY);
  38483. }
  38484. else {
  38485. defines["LIGHTMAPEXCLUDED" + lightIndex] = false;
  38486. defines["LIGHTMAPNOSPECULAR" + lightIndex] = false;
  38487. }
  38488. lightIndex++;
  38489. if (lightIndex === maxSimultaneousLights)
  38490. break;
  38491. }
  38492. }
  38493. defines["SPECULARTERM"] = specularEnabled;
  38494. defines["SHADOWS"] = shadowEnabled;
  38495. // Resetting all other lights if any
  38496. for (var index = lightIndex; index < maxSimultaneousLights; index++) {
  38497. if (defines["LIGHT" + index] !== undefined) {
  38498. defines["LIGHT" + index] = false;
  38499. defines["HEMILIGHT" + lightIndex] = false;
  38500. defines["POINTLIGHT" + lightIndex] = false;
  38501. defines["DIRLIGHT" + lightIndex] = false;
  38502. defines["SPOTLIGHT" + lightIndex] = false;
  38503. defines["SHADOW" + lightIndex] = false;
  38504. }
  38505. }
  38506. var caps = scene.getEngine().getCaps();
  38507. if (defines["SHADOWFLOAT"] === undefined) {
  38508. needRebuild = true;
  38509. }
  38510. defines["SHADOWFLOAT"] = shadowEnabled &&
  38511. ((caps.textureFloatRender && caps.textureFloatLinearFiltering) ||
  38512. (caps.textureHalfFloatRender && caps.textureHalfFloatLinearFiltering));
  38513. defines["LIGHTMAPEXCLUDED"] = lightmapMode;
  38514. if (needRebuild) {
  38515. defines.rebuild();
  38516. }
  38517. return needNormals;
  38518. };
  38519. /**
  38520. * Prepares the uniforms and samplers list to be used in the effect. This can automatically remove from the list uniforms
  38521. * that won t be acctive due to defines being turned off.
  38522. * @param uniformsListOrOptions The uniform names to prepare or an EffectCreationOptions containing the liist and extra information
  38523. * @param samplersList The samplers list
  38524. * @param defines The defines helping in the list generation
  38525. * @param maxSimultaneousLights The maximum number of simultanous light allowed in the effect
  38526. */
  38527. MaterialHelper.PrepareUniformsAndSamplersList = function (uniformsListOrOptions, samplersList, defines, maxSimultaneousLights) {
  38528. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  38529. var uniformsList;
  38530. var uniformBuffersList = null;
  38531. if (uniformsListOrOptions.uniformsNames) {
  38532. var options = uniformsListOrOptions;
  38533. uniformsList = options.uniformsNames;
  38534. uniformBuffersList = options.uniformBuffersNames;
  38535. samplersList = options.samplers;
  38536. defines = options.defines;
  38537. maxSimultaneousLights = options.maxSimultaneousLights;
  38538. }
  38539. else {
  38540. uniformsList = uniformsListOrOptions;
  38541. if (!samplersList) {
  38542. samplersList = [];
  38543. }
  38544. }
  38545. for (var lightIndex = 0; lightIndex < maxSimultaneousLights; lightIndex++) {
  38546. if (!defines["LIGHT" + lightIndex]) {
  38547. break;
  38548. }
  38549. uniformsList.push("vLightData" + lightIndex, "vLightDiffuse" + lightIndex, "vLightSpecular" + lightIndex, "vLightDirection" + lightIndex, "vLightGround" + lightIndex, "lightMatrix" + lightIndex, "shadowsInfo" + lightIndex, "depthValues" + lightIndex);
  38550. if (uniformBuffersList) {
  38551. uniformBuffersList.push("Light" + lightIndex);
  38552. }
  38553. samplersList.push("shadowSampler" + lightIndex);
  38554. if (defines["PROJECTEDLIGHTTEXTURE" + lightIndex]) {
  38555. samplersList.push("projectionLightSampler" + lightIndex);
  38556. uniformsList.push("textureProjectionMatrix" + lightIndex);
  38557. }
  38558. }
  38559. if (defines["NUM_MORPH_INFLUENCERS"]) {
  38560. uniformsList.push("morphTargetInfluences");
  38561. }
  38562. };
  38563. /**
  38564. * This helps decreasing rank by rank the shadow quality (0 being the highest rank and quality)
  38565. * @param defines The defines to update while falling back
  38566. * @param fallbacks The authorized effect fallbacks
  38567. * @param maxSimultaneousLights The maximum number of lights allowed
  38568. * @param rank the current rank of the Effect
  38569. * @returns The newly affected rank
  38570. */
  38571. MaterialHelper.HandleFallbacksForShadows = function (defines, fallbacks, maxSimultaneousLights, rank) {
  38572. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  38573. if (rank === void 0) { rank = 0; }
  38574. var lightFallbackRank = 0;
  38575. for (var lightIndex = 0; lightIndex < maxSimultaneousLights; lightIndex++) {
  38576. if (!defines["LIGHT" + lightIndex]) {
  38577. break;
  38578. }
  38579. if (lightIndex > 0) {
  38580. lightFallbackRank = rank + lightIndex;
  38581. fallbacks.addFallback(lightFallbackRank, "LIGHT" + lightIndex);
  38582. }
  38583. if (!defines["SHADOWS"]) {
  38584. if (defines["SHADOW" + lightIndex]) {
  38585. fallbacks.addFallback(rank, "SHADOW" + lightIndex);
  38586. }
  38587. if (defines["SHADOWPCF" + lightIndex]) {
  38588. fallbacks.addFallback(rank, "SHADOWPCF" + lightIndex);
  38589. }
  38590. if (defines["SHADOWESM" + lightIndex]) {
  38591. fallbacks.addFallback(rank, "SHADOWESM" + lightIndex);
  38592. }
  38593. }
  38594. }
  38595. return lightFallbackRank++;
  38596. };
  38597. /**
  38598. * Prepares the list of attributes required for morph targets according to the effect defines.
  38599. * @param attribs The current list of supported attribs
  38600. * @param mesh The mesh to prepare the morph targets attributes for
  38601. * @param defines The current Defines of the effect
  38602. */
  38603. MaterialHelper.PrepareAttributesForMorphTargets = function (attribs, mesh, defines) {
  38604. var influencers = defines["NUM_MORPH_INFLUENCERS"];
  38605. if (influencers > 0 && BABYLON.Engine.LastCreatedEngine) {
  38606. var maxAttributesCount = BABYLON.Engine.LastCreatedEngine.getCaps().maxVertexAttribs;
  38607. var manager = mesh.morphTargetManager;
  38608. var normal = manager && manager.supportsNormals && defines["NORMAL"];
  38609. var tangent = manager && manager.supportsTangents && defines["TANGENT"];
  38610. for (var index = 0; index < influencers; index++) {
  38611. attribs.push(BABYLON.VertexBuffer.PositionKind + index);
  38612. if (normal) {
  38613. attribs.push(BABYLON.VertexBuffer.NormalKind + index);
  38614. }
  38615. if (tangent) {
  38616. attribs.push(BABYLON.VertexBuffer.TangentKind + index);
  38617. }
  38618. if (attribs.length > maxAttributesCount) {
  38619. BABYLON.Tools.Error("Cannot add more vertex attributes for mesh " + mesh.name);
  38620. }
  38621. }
  38622. }
  38623. };
  38624. /**
  38625. * Prepares the list of attributes required for bones according to the effect defines.
  38626. * @param attribs The current list of supported attribs
  38627. * @param mesh The mesh to prepare the bones attributes for
  38628. * @param defines The current Defines of the effect
  38629. * @param fallbacks The current efffect fallback strategy
  38630. */
  38631. MaterialHelper.PrepareAttributesForBones = function (attribs, mesh, defines, fallbacks) {
  38632. if (defines["NUM_BONE_INFLUENCERS"] > 0) {
  38633. fallbacks.addCPUSkinningFallback(0, mesh);
  38634. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  38635. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  38636. if (defines["NUM_BONE_INFLUENCERS"] > 4) {
  38637. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  38638. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  38639. }
  38640. }
  38641. };
  38642. /**
  38643. * Prepares the list of attributes required for instances according to the effect defines.
  38644. * @param attribs The current list of supported attribs
  38645. * @param defines The current Defines of the effect
  38646. */
  38647. MaterialHelper.PrepareAttributesForInstances = function (attribs, defines) {
  38648. if (defines["INSTANCES"]) {
  38649. attribs.push("world0");
  38650. attribs.push("world1");
  38651. attribs.push("world2");
  38652. attribs.push("world3");
  38653. }
  38654. };
  38655. /**
  38656. * Binds the light shadow information to the effect for the given mesh.
  38657. * @param light The light containing the generator
  38658. * @param scene The scene the lights belongs to
  38659. * @param mesh The mesh we are binding the information to render
  38660. * @param lightIndex The light index in the effect used to render the mesh
  38661. * @param effect The effect we are binding the data to
  38662. */
  38663. MaterialHelper.BindLightShadow = function (light, scene, mesh, lightIndex, effect) {
  38664. if (light.shadowEnabled && mesh.receiveShadows) {
  38665. var shadowGenerator = light.getShadowGenerator();
  38666. if (shadowGenerator) {
  38667. shadowGenerator.bindShadowLight(lightIndex, effect);
  38668. }
  38669. }
  38670. };
  38671. /**
  38672. * Binds the light information to the effect.
  38673. * @param light The light containing the generator
  38674. * @param effect The effect we are binding the data to
  38675. * @param lightIndex The light index in the effect used to render
  38676. */
  38677. MaterialHelper.BindLightProperties = function (light, effect, lightIndex) {
  38678. light.transferToEffect(effect, lightIndex + "");
  38679. };
  38680. /**
  38681. * Binds the lights information from the scene to the effect for the given mesh.
  38682. * @param scene The scene the lights belongs to
  38683. * @param mesh The mesh we are binding the information to render
  38684. * @param effect The effect we are binding the data to
  38685. * @param defines The generated defines for the effect
  38686. * @param maxSimultaneousLights The maximum number of light that can be bound to the effect
  38687. * @param usePhysicalLightFalloff Specifies whether the light falloff is defined physically or not
  38688. */
  38689. MaterialHelper.BindLights = function (scene, mesh, effect, defines, maxSimultaneousLights, usePhysicalLightFalloff) {
  38690. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  38691. if (usePhysicalLightFalloff === void 0) { usePhysicalLightFalloff = false; }
  38692. var len = Math.min(mesh._lightSources.length, maxSimultaneousLights);
  38693. for (var i = 0; i < len; i++) {
  38694. var light = mesh._lightSources[i];
  38695. var iAsString = i.toString();
  38696. var scaledIntensity = light.getScaledIntensity();
  38697. light._uniformBuffer.bindToEffect(effect, "Light" + i);
  38698. MaterialHelper.BindLightProperties(light, effect, i);
  38699. light.diffuse.scaleToRef(scaledIntensity, BABYLON.Tmp.Color3[0]);
  38700. light._uniformBuffer.updateColor4("vLightDiffuse", BABYLON.Tmp.Color3[0], usePhysicalLightFalloff ? light.radius : light.range, iAsString);
  38701. if (defines["SPECULARTERM"]) {
  38702. light.specular.scaleToRef(scaledIntensity, BABYLON.Tmp.Color3[1]);
  38703. light._uniformBuffer.updateColor3("vLightSpecular", BABYLON.Tmp.Color3[1], iAsString);
  38704. }
  38705. // Shadows
  38706. if (scene.shadowsEnabled) {
  38707. this.BindLightShadow(light, scene, mesh, iAsString, effect);
  38708. }
  38709. light._uniformBuffer.update();
  38710. }
  38711. };
  38712. /**
  38713. * Binds the fog information from the scene to the effect for the given mesh.
  38714. * @param scene The scene the lights belongs to
  38715. * @param mesh The mesh we are binding the information to render
  38716. * @param effect The effect we are binding the data to
  38717. */
  38718. MaterialHelper.BindFogParameters = function (scene, mesh, effect) {
  38719. if (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE) {
  38720. effect.setFloat4("vFogInfos", scene.fogMode, scene.fogStart, scene.fogEnd, scene.fogDensity);
  38721. effect.setColor3("vFogColor", scene.fogColor);
  38722. }
  38723. };
  38724. /**
  38725. * Binds the bones information from the mesh to the effect.
  38726. * @param mesh The mesh we are binding the information to render
  38727. * @param effect The effect we are binding the data to
  38728. */
  38729. MaterialHelper.BindBonesParameters = function (mesh, effect) {
  38730. if (mesh && mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  38731. var matrices = mesh.skeleton.getTransformMatrices(mesh);
  38732. if (matrices && effect) {
  38733. effect.setMatrices("mBones", matrices);
  38734. }
  38735. }
  38736. };
  38737. /**
  38738. * Binds the morph targets information from the mesh to the effect.
  38739. * @param abstractMesh The mesh we are binding the information to render
  38740. * @param effect The effect we are binding the data to
  38741. */
  38742. MaterialHelper.BindMorphTargetParameters = function (abstractMesh, effect) {
  38743. var manager = abstractMesh.morphTargetManager;
  38744. if (!abstractMesh || !manager) {
  38745. return;
  38746. }
  38747. effect.setFloatArray("morphTargetInfluences", manager.influences);
  38748. };
  38749. /**
  38750. * Binds the logarithmic depth information from the scene to the effect for the given defines.
  38751. * @param defines The generated defines used in the effect
  38752. * @param effect The effect we are binding the data to
  38753. * @param scene The scene we are willing to render with logarithmic scale for
  38754. */
  38755. MaterialHelper.BindLogDepth = function (defines, effect, scene) {
  38756. if (defines["LOGARITHMICDEPTH"]) {
  38757. effect.setFloat("logarithmicDepthConstant", 2.0 / (Math.log(scene.activeCamera.maxZ + 1.0) / Math.LN2));
  38758. }
  38759. };
  38760. /**
  38761. * Binds the clip plane information from the scene to the effect.
  38762. * @param scene The scene the clip plane information are extracted from
  38763. * @param effect The effect we are binding the data to
  38764. */
  38765. MaterialHelper.BindClipPlane = function (effect, scene) {
  38766. if (scene.clipPlane) {
  38767. var clipPlane = scene.clipPlane;
  38768. effect.setFloat4("vClipPlane", clipPlane.normal.x, clipPlane.normal.y, clipPlane.normal.z, clipPlane.d);
  38769. }
  38770. };
  38771. return MaterialHelper;
  38772. }());
  38773. BABYLON.MaterialHelper = MaterialHelper;
  38774. })(BABYLON || (BABYLON = {}));
  38775. //# sourceMappingURL=babylon.materialHelper.js.map
  38776. var BABYLON;
  38777. (function (BABYLON) {
  38778. var PushMaterial = /** @class */ (function (_super) {
  38779. __extends(PushMaterial, _super);
  38780. function PushMaterial(name, scene) {
  38781. var _this = _super.call(this, name, scene) || this;
  38782. _this._normalMatrix = new BABYLON.Matrix();
  38783. _this.storeEffectOnSubMeshes = true;
  38784. return _this;
  38785. }
  38786. PushMaterial.prototype.getEffect = function () {
  38787. return this._activeEffect;
  38788. };
  38789. PushMaterial.prototype.isReady = function (mesh, useInstances) {
  38790. if (!mesh) {
  38791. return false;
  38792. }
  38793. if (!mesh.subMeshes || mesh.subMeshes.length === 0) {
  38794. return true;
  38795. }
  38796. return this.isReadyForSubMesh(mesh, mesh.subMeshes[0], useInstances);
  38797. };
  38798. /**
  38799. * Binds the given world matrix to the active effect
  38800. *
  38801. * @param world the matrix to bind
  38802. */
  38803. PushMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  38804. this._activeEffect.setMatrix("world", world);
  38805. };
  38806. /**
  38807. * Binds the given normal matrix to the active effect
  38808. *
  38809. * @param normalMatrix the matrix to bind
  38810. */
  38811. PushMaterial.prototype.bindOnlyNormalMatrix = function (normalMatrix) {
  38812. this._activeEffect.setMatrix("normalMatrix", normalMatrix);
  38813. };
  38814. PushMaterial.prototype.bind = function (world, mesh) {
  38815. if (!mesh) {
  38816. return;
  38817. }
  38818. this.bindForSubMesh(world, mesh, mesh.subMeshes[0]);
  38819. };
  38820. PushMaterial.prototype._afterBind = function (mesh, effect) {
  38821. if (effect === void 0) { effect = null; }
  38822. _super.prototype._afterBind.call(this, mesh);
  38823. this.getScene()._cachedEffect = effect;
  38824. };
  38825. PushMaterial.prototype._mustRebind = function (scene, effect, visibility) {
  38826. if (visibility === void 0) { visibility = 1; }
  38827. return scene.isCachedMaterialInvalid(this, effect, visibility);
  38828. };
  38829. return PushMaterial;
  38830. }(BABYLON.Material));
  38831. BABYLON.PushMaterial = PushMaterial;
  38832. })(BABYLON || (BABYLON = {}));
  38833. //# sourceMappingURL=babylon.pushMaterial.js.map
  38834. var BABYLON;
  38835. (function (BABYLON) {
  38836. /** @ignore */
  38837. var StandardMaterialDefines = /** @class */ (function (_super) {
  38838. __extends(StandardMaterialDefines, _super);
  38839. function StandardMaterialDefines() {
  38840. var _this = _super.call(this) || this;
  38841. _this.MAINUV1 = false;
  38842. _this.MAINUV2 = false;
  38843. _this.DIFFUSE = false;
  38844. _this.DIFFUSEDIRECTUV = 0;
  38845. _this.AMBIENT = false;
  38846. _this.AMBIENTDIRECTUV = 0;
  38847. _this.OPACITY = false;
  38848. _this.OPACITYDIRECTUV = 0;
  38849. _this.OPACITYRGB = false;
  38850. _this.REFLECTION = false;
  38851. _this.EMISSIVE = false;
  38852. _this.EMISSIVEDIRECTUV = 0;
  38853. _this.SPECULAR = false;
  38854. _this.SPECULARDIRECTUV = 0;
  38855. _this.BUMP = false;
  38856. _this.BUMPDIRECTUV = 0;
  38857. _this.PARALLAX = false;
  38858. _this.PARALLAXOCCLUSION = false;
  38859. _this.SPECULAROVERALPHA = false;
  38860. _this.CLIPPLANE = false;
  38861. _this.ALPHATEST = false;
  38862. _this.DEPTHPREPASS = false;
  38863. _this.ALPHAFROMDIFFUSE = false;
  38864. _this.POINTSIZE = false;
  38865. _this.FOG = false;
  38866. _this.SPECULARTERM = false;
  38867. _this.DIFFUSEFRESNEL = false;
  38868. _this.OPACITYFRESNEL = false;
  38869. _this.REFLECTIONFRESNEL = false;
  38870. _this.REFRACTIONFRESNEL = false;
  38871. _this.EMISSIVEFRESNEL = false;
  38872. _this.FRESNEL = false;
  38873. _this.NORMAL = false;
  38874. _this.UV1 = false;
  38875. _this.UV2 = false;
  38876. _this.VERTEXCOLOR = false;
  38877. _this.VERTEXALPHA = false;
  38878. _this.NUM_BONE_INFLUENCERS = 0;
  38879. _this.BonesPerMesh = 0;
  38880. _this.INSTANCES = false;
  38881. _this.GLOSSINESS = false;
  38882. _this.ROUGHNESS = false;
  38883. _this.EMISSIVEASILLUMINATION = false;
  38884. _this.LINKEMISSIVEWITHDIFFUSE = false;
  38885. _this.REFLECTIONFRESNELFROMSPECULAR = false;
  38886. _this.LIGHTMAP = false;
  38887. _this.LIGHTMAPDIRECTUV = 0;
  38888. _this.OBJECTSPACE_NORMALMAP = false;
  38889. _this.USELIGHTMAPASSHADOWMAP = false;
  38890. _this.REFLECTIONMAP_3D = false;
  38891. _this.REFLECTIONMAP_SPHERICAL = false;
  38892. _this.REFLECTIONMAP_PLANAR = false;
  38893. _this.REFLECTIONMAP_CUBIC = false;
  38894. _this.USE_LOCAL_REFLECTIONMAP_CUBIC = false;
  38895. _this.REFLECTIONMAP_PROJECTION = false;
  38896. _this.REFLECTIONMAP_SKYBOX = false;
  38897. _this.REFLECTIONMAP_EXPLICIT = false;
  38898. _this.REFLECTIONMAP_EQUIRECTANGULAR = false;
  38899. _this.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  38900. _this.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  38901. _this.INVERTCUBICMAP = false;
  38902. _this.LOGARITHMICDEPTH = false;
  38903. _this.REFRACTION = false;
  38904. _this.REFRACTIONMAP_3D = false;
  38905. _this.REFLECTIONOVERALPHA = false;
  38906. _this.TWOSIDEDLIGHTING = false;
  38907. _this.SHADOWFLOAT = false;
  38908. _this.MORPHTARGETS = false;
  38909. _this.MORPHTARGETS_NORMAL = false;
  38910. _this.MORPHTARGETS_TANGENT = false;
  38911. _this.NUM_MORPH_INFLUENCERS = 0;
  38912. _this.NONUNIFORMSCALING = false; // https://playground.babylonjs.com#V6DWIH
  38913. _this.PREMULTIPLYALPHA = false; // https://playground.babylonjs.com#LNVJJ7
  38914. _this.IMAGEPROCESSING = false;
  38915. _this.VIGNETTE = false;
  38916. _this.VIGNETTEBLENDMODEMULTIPLY = false;
  38917. _this.VIGNETTEBLENDMODEOPAQUE = false;
  38918. _this.TONEMAPPING = false;
  38919. _this.CONTRAST = false;
  38920. _this.COLORCURVES = false;
  38921. _this.COLORGRADING = false;
  38922. _this.COLORGRADING3D = false;
  38923. _this.SAMPLER3DGREENDEPTH = false;
  38924. _this.SAMPLER3DBGRMAP = false;
  38925. _this.IMAGEPROCESSINGPOSTPROCESS = false;
  38926. _this.EXPOSURE = false;
  38927. _this.GRAIN = false;
  38928. _this.rebuild();
  38929. return _this;
  38930. }
  38931. StandardMaterialDefines.prototype.setReflectionMode = function (modeToEnable) {
  38932. var modes = [
  38933. "REFLECTIONMAP_CUBIC", "REFLECTIONMAP_EXPLICIT", "REFLECTIONMAP_PLANAR",
  38934. "REFLECTIONMAP_PROJECTION", "REFLECTIONMAP_PROJECTION", "REFLECTIONMAP_SKYBOX",
  38935. "REFLECTIONMAP_SPHERICAL", "REFLECTIONMAP_EQUIRECTANGULAR", "REFLECTIONMAP_EQUIRECTANGULAR_FIXED",
  38936. "REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED"
  38937. ];
  38938. for (var _i = 0, modes_1 = modes; _i < modes_1.length; _i++) {
  38939. var mode = modes_1[_i];
  38940. this[mode] = (mode === modeToEnable);
  38941. }
  38942. };
  38943. return StandardMaterialDefines;
  38944. }(BABYLON.MaterialDefines));
  38945. BABYLON.StandardMaterialDefines = StandardMaterialDefines;
  38946. var StandardMaterial = /** @class */ (function (_super) {
  38947. __extends(StandardMaterial, _super);
  38948. function StandardMaterial(name, scene) {
  38949. var _this = _super.call(this, name, scene) || this;
  38950. _this.ambientColor = new BABYLON.Color3(0, 0, 0);
  38951. _this.diffuseColor = new BABYLON.Color3(1, 1, 1);
  38952. _this.specularColor = new BABYLON.Color3(1, 1, 1);
  38953. _this.emissiveColor = new BABYLON.Color3(0, 0, 0);
  38954. _this.specularPower = 64;
  38955. _this._useAlphaFromDiffuseTexture = false;
  38956. _this._useEmissiveAsIllumination = false;
  38957. _this._linkEmissiveWithDiffuse = false;
  38958. _this._useSpecularOverAlpha = false;
  38959. _this._useReflectionOverAlpha = false;
  38960. _this._disableLighting = false;
  38961. _this._useObjectSpaceNormalMap = false;
  38962. _this._useParallax = false;
  38963. _this._useParallaxOcclusion = false;
  38964. _this.parallaxScaleBias = 0.05;
  38965. _this._roughness = 0;
  38966. _this.indexOfRefraction = 0.98;
  38967. _this.invertRefractionY = true;
  38968. _this._useLightmapAsShadowmap = false;
  38969. _this._useReflectionFresnelFromSpecular = false;
  38970. _this._useGlossinessFromSpecularMapAlpha = false;
  38971. _this._maxSimultaneousLights = 4;
  38972. /**
  38973. * If sets to true, x component of normal map value will invert (x = 1.0 - x).
  38974. */
  38975. _this._invertNormalMapX = false;
  38976. /**
  38977. * If sets to true, y component of normal map value will invert (y = 1.0 - y).
  38978. */
  38979. _this._invertNormalMapY = false;
  38980. /**
  38981. * If sets to true and backfaceCulling is false, normals will be flipped on the backside.
  38982. */
  38983. _this._twoSidedLighting = false;
  38984. _this._renderTargets = new BABYLON.SmartArray(16);
  38985. _this._worldViewProjectionMatrix = BABYLON.Matrix.Zero();
  38986. _this._globalAmbientColor = new BABYLON.Color3(0, 0, 0);
  38987. // Setup the default processing configuration to the scene.
  38988. _this._attachImageProcessingConfiguration(null);
  38989. _this.getRenderTargetTextures = function () {
  38990. _this._renderTargets.reset();
  38991. if (StandardMaterial.ReflectionTextureEnabled && _this._reflectionTexture && _this._reflectionTexture.isRenderTarget) {
  38992. _this._renderTargets.push(_this._reflectionTexture);
  38993. }
  38994. if (StandardMaterial.RefractionTextureEnabled && _this._refractionTexture && _this._refractionTexture.isRenderTarget) {
  38995. _this._renderTargets.push(_this._refractionTexture);
  38996. }
  38997. return _this._renderTargets;
  38998. };
  38999. return _this;
  39000. }
  39001. ;
  39002. ;
  39003. ;
  39004. ;
  39005. ;
  39006. ;
  39007. ;
  39008. ;
  39009. ;
  39010. ;
  39011. ;
  39012. ;
  39013. ;
  39014. ;
  39015. ;
  39016. ;
  39017. ;
  39018. Object.defineProperty(StandardMaterial.prototype, "imageProcessingConfiguration", {
  39019. /**
  39020. * Gets the image processing configuration used either in this material.
  39021. */
  39022. get: function () {
  39023. return this._imageProcessingConfiguration;
  39024. },
  39025. /**
  39026. * Sets the Default image processing configuration used either in the this material.
  39027. *
  39028. * If sets to null, the scene one is in use.
  39029. */
  39030. set: function (value) {
  39031. this._attachImageProcessingConfiguration(value);
  39032. // Ensure the effect will be rebuilt.
  39033. this._markAllSubMeshesAsTexturesDirty();
  39034. },
  39035. enumerable: true,
  39036. configurable: true
  39037. });
  39038. /**
  39039. * Attaches a new image processing configuration to the Standard Material.
  39040. * @param configuration
  39041. */
  39042. StandardMaterial.prototype._attachImageProcessingConfiguration = function (configuration) {
  39043. var _this = this;
  39044. if (configuration === this._imageProcessingConfiguration) {
  39045. return;
  39046. }
  39047. // Detaches observer.
  39048. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  39049. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  39050. }
  39051. // Pick the scene configuration if needed.
  39052. if (!configuration) {
  39053. this._imageProcessingConfiguration = this.getScene().imageProcessingConfiguration;
  39054. }
  39055. else {
  39056. this._imageProcessingConfiguration = configuration;
  39057. }
  39058. // Attaches observer.
  39059. this._imageProcessingObserver = this._imageProcessingConfiguration.onUpdateParameters.add(function (conf) {
  39060. _this._markAllSubMeshesAsImageProcessingDirty();
  39061. });
  39062. };
  39063. Object.defineProperty(StandardMaterial.prototype, "cameraColorCurvesEnabled", {
  39064. /**
  39065. * Gets wether the color curves effect is enabled.
  39066. */
  39067. get: function () {
  39068. return this.imageProcessingConfiguration.colorCurvesEnabled;
  39069. },
  39070. /**
  39071. * Sets wether the color curves effect is enabled.
  39072. */
  39073. set: function (value) {
  39074. this.imageProcessingConfiguration.colorCurvesEnabled = value;
  39075. },
  39076. enumerable: true,
  39077. configurable: true
  39078. });
  39079. Object.defineProperty(StandardMaterial.prototype, "cameraColorGradingEnabled", {
  39080. /**
  39081. * Gets wether the color grading effect is enabled.
  39082. */
  39083. get: function () {
  39084. return this.imageProcessingConfiguration.colorGradingEnabled;
  39085. },
  39086. /**
  39087. * Gets wether the color grading effect is enabled.
  39088. */
  39089. set: function (value) {
  39090. this.imageProcessingConfiguration.colorGradingEnabled = value;
  39091. },
  39092. enumerable: true,
  39093. configurable: true
  39094. });
  39095. Object.defineProperty(StandardMaterial.prototype, "cameraToneMappingEnabled", {
  39096. /**
  39097. * Gets wether tonemapping is enabled or not.
  39098. */
  39099. get: function () {
  39100. return this._imageProcessingConfiguration.toneMappingEnabled;
  39101. },
  39102. /**
  39103. * Sets wether tonemapping is enabled or not
  39104. */
  39105. set: function (value) {
  39106. this._imageProcessingConfiguration.toneMappingEnabled = value;
  39107. },
  39108. enumerable: true,
  39109. configurable: true
  39110. });
  39111. ;
  39112. ;
  39113. Object.defineProperty(StandardMaterial.prototype, "cameraExposure", {
  39114. /**
  39115. * The camera exposure used on this material.
  39116. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  39117. * This corresponds to a photographic exposure.
  39118. */
  39119. get: function () {
  39120. return this._imageProcessingConfiguration.exposure;
  39121. },
  39122. /**
  39123. * The camera exposure used on this material.
  39124. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  39125. * This corresponds to a photographic exposure.
  39126. */
  39127. set: function (value) {
  39128. this._imageProcessingConfiguration.exposure = value;
  39129. },
  39130. enumerable: true,
  39131. configurable: true
  39132. });
  39133. ;
  39134. ;
  39135. Object.defineProperty(StandardMaterial.prototype, "cameraContrast", {
  39136. /**
  39137. * Gets The camera contrast used on this material.
  39138. */
  39139. get: function () {
  39140. return this._imageProcessingConfiguration.contrast;
  39141. },
  39142. /**
  39143. * Sets The camera contrast used on this material.
  39144. */
  39145. set: function (value) {
  39146. this._imageProcessingConfiguration.contrast = value;
  39147. },
  39148. enumerable: true,
  39149. configurable: true
  39150. });
  39151. Object.defineProperty(StandardMaterial.prototype, "cameraColorGradingTexture", {
  39152. /**
  39153. * Gets the Color Grading 2D Lookup Texture.
  39154. */
  39155. get: function () {
  39156. return this._imageProcessingConfiguration.colorGradingTexture;
  39157. },
  39158. /**
  39159. * Sets the Color Grading 2D Lookup Texture.
  39160. */
  39161. set: function (value) {
  39162. this._imageProcessingConfiguration.colorGradingTexture = value;
  39163. },
  39164. enumerable: true,
  39165. configurable: true
  39166. });
  39167. Object.defineProperty(StandardMaterial.prototype, "cameraColorCurves", {
  39168. /**
  39169. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  39170. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  39171. * 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;
  39172. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  39173. */
  39174. get: function () {
  39175. return this._imageProcessingConfiguration.colorCurves;
  39176. },
  39177. /**
  39178. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  39179. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  39180. * 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;
  39181. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  39182. */
  39183. set: function (value) {
  39184. this._imageProcessingConfiguration.colorCurves = value;
  39185. },
  39186. enumerable: true,
  39187. configurable: true
  39188. });
  39189. StandardMaterial.prototype.getClassName = function () {
  39190. return "StandardMaterial";
  39191. };
  39192. Object.defineProperty(StandardMaterial.prototype, "useLogarithmicDepth", {
  39193. get: function () {
  39194. return this._useLogarithmicDepth;
  39195. },
  39196. set: function (value) {
  39197. this._useLogarithmicDepth = value && this.getScene().getEngine().getCaps().fragmentDepthSupported;
  39198. this._markAllSubMeshesAsMiscDirty();
  39199. },
  39200. enumerable: true,
  39201. configurable: true
  39202. });
  39203. StandardMaterial.prototype.needAlphaBlending = function () {
  39204. return (this.alpha < 1.0) || (this._opacityTexture != null) || this._shouldUseAlphaFromDiffuseTexture() || this._opacityFresnelParameters && this._opacityFresnelParameters.isEnabled;
  39205. };
  39206. StandardMaterial.prototype.needAlphaTesting = function () {
  39207. return this._diffuseTexture != null && this._diffuseTexture.hasAlpha;
  39208. };
  39209. StandardMaterial.prototype._shouldUseAlphaFromDiffuseTexture = function () {
  39210. return this._diffuseTexture != null && this._diffuseTexture.hasAlpha && this._useAlphaFromDiffuseTexture;
  39211. };
  39212. StandardMaterial.prototype.getAlphaTestTexture = function () {
  39213. return this._diffuseTexture;
  39214. };
  39215. /**
  39216. * Child classes can use it to update shaders
  39217. */
  39218. StandardMaterial.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  39219. if (useInstances === void 0) { useInstances = false; }
  39220. if (subMesh.effect && this.isFrozen) {
  39221. if (this._wasPreviouslyReady && subMesh.effect) {
  39222. return true;
  39223. }
  39224. }
  39225. if (!subMesh._materialDefines) {
  39226. subMesh._materialDefines = new StandardMaterialDefines();
  39227. }
  39228. var scene = this.getScene();
  39229. var defines = subMesh._materialDefines;
  39230. if (!this.checkReadyOnEveryCall && subMesh.effect) {
  39231. if (defines._renderId === scene.getRenderId()) {
  39232. return true;
  39233. }
  39234. }
  39235. var engine = scene.getEngine();
  39236. // Lights
  39237. defines._needNormals = BABYLON.MaterialHelper.PrepareDefinesForLights(scene, mesh, defines, true, this._maxSimultaneousLights, this._disableLighting);
  39238. // Textures
  39239. if (defines._areTexturesDirty) {
  39240. defines._needUVs = false;
  39241. defines.MAINUV1 = false;
  39242. defines.MAINUV2 = false;
  39243. if (scene.texturesEnabled) {
  39244. if (this._diffuseTexture && StandardMaterial.DiffuseTextureEnabled) {
  39245. if (!this._diffuseTexture.isReadyOrNotBlocking()) {
  39246. return false;
  39247. }
  39248. else {
  39249. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._diffuseTexture, defines, "DIFFUSE");
  39250. }
  39251. }
  39252. else {
  39253. defines.DIFFUSE = false;
  39254. }
  39255. if (this._ambientTexture && StandardMaterial.AmbientTextureEnabled) {
  39256. if (!this._ambientTexture.isReadyOrNotBlocking()) {
  39257. return false;
  39258. }
  39259. else {
  39260. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._ambientTexture, defines, "AMBIENT");
  39261. }
  39262. }
  39263. else {
  39264. defines.AMBIENT = false;
  39265. }
  39266. if (this._opacityTexture && StandardMaterial.OpacityTextureEnabled) {
  39267. if (!this._opacityTexture.isReadyOrNotBlocking()) {
  39268. return false;
  39269. }
  39270. else {
  39271. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._opacityTexture, defines, "OPACITY");
  39272. defines.OPACITYRGB = this._opacityTexture.getAlphaFromRGB;
  39273. }
  39274. }
  39275. else {
  39276. defines.OPACITY = false;
  39277. }
  39278. if (this._reflectionTexture && StandardMaterial.ReflectionTextureEnabled) {
  39279. if (!this._reflectionTexture.isReadyOrNotBlocking()) {
  39280. return false;
  39281. }
  39282. else {
  39283. defines._needNormals = true;
  39284. defines.REFLECTION = true;
  39285. defines.ROUGHNESS = (this._roughness > 0);
  39286. defines.REFLECTIONOVERALPHA = this._useReflectionOverAlpha;
  39287. defines.INVERTCUBICMAP = (this._reflectionTexture.coordinatesMode === BABYLON.Texture.INVCUBIC_MODE);
  39288. defines.REFLECTIONMAP_3D = this._reflectionTexture.isCube;
  39289. switch (this._reflectionTexture.coordinatesMode) {
  39290. case BABYLON.Texture.CUBIC_MODE:
  39291. case BABYLON.Texture.INVCUBIC_MODE:
  39292. defines.setReflectionMode("REFLECTIONMAP_CUBIC");
  39293. break;
  39294. case BABYLON.Texture.EXPLICIT_MODE:
  39295. defines.setReflectionMode("REFLECTIONMAP_EXPLICIT");
  39296. break;
  39297. case BABYLON.Texture.PLANAR_MODE:
  39298. defines.setReflectionMode("REFLECTIONMAP_PLANAR");
  39299. break;
  39300. case BABYLON.Texture.PROJECTION_MODE:
  39301. defines.setReflectionMode("REFLECTIONMAP_PROJECTION");
  39302. break;
  39303. case BABYLON.Texture.SKYBOX_MODE:
  39304. defines.setReflectionMode("REFLECTIONMAP_SKYBOX");
  39305. break;
  39306. case BABYLON.Texture.SPHERICAL_MODE:
  39307. defines.setReflectionMode("REFLECTIONMAP_SPHERICAL");
  39308. break;
  39309. case BABYLON.Texture.EQUIRECTANGULAR_MODE:
  39310. defines.setReflectionMode("REFLECTIONMAP_EQUIRECTANGULAR");
  39311. break;
  39312. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MODE:
  39313. defines.setReflectionMode("REFLECTIONMAP_EQUIRECTANGULAR_FIXED");
  39314. break;
  39315. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE:
  39316. defines.setReflectionMode("REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED");
  39317. break;
  39318. }
  39319. defines.USE_LOCAL_REFLECTIONMAP_CUBIC = this._reflectionTexture.boundingBoxSize ? true : false;
  39320. }
  39321. }
  39322. else {
  39323. defines.REFLECTION = false;
  39324. }
  39325. if (this._emissiveTexture && StandardMaterial.EmissiveTextureEnabled) {
  39326. if (!this._emissiveTexture.isReadyOrNotBlocking()) {
  39327. return false;
  39328. }
  39329. else {
  39330. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._emissiveTexture, defines, "EMISSIVE");
  39331. }
  39332. }
  39333. else {
  39334. defines.EMISSIVE = false;
  39335. }
  39336. if (this._lightmapTexture && StandardMaterial.LightmapTextureEnabled) {
  39337. if (!this._lightmapTexture.isReadyOrNotBlocking()) {
  39338. return false;
  39339. }
  39340. else {
  39341. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._lightmapTexture, defines, "LIGHTMAP");
  39342. defines.USELIGHTMAPASSHADOWMAP = this._useLightmapAsShadowmap;
  39343. }
  39344. }
  39345. else {
  39346. defines.LIGHTMAP = false;
  39347. }
  39348. if (this._specularTexture && StandardMaterial.SpecularTextureEnabled) {
  39349. if (!this._specularTexture.isReadyOrNotBlocking()) {
  39350. return false;
  39351. }
  39352. else {
  39353. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._specularTexture, defines, "SPECULAR");
  39354. defines.GLOSSINESS = this._useGlossinessFromSpecularMapAlpha;
  39355. }
  39356. }
  39357. else {
  39358. defines.SPECULAR = false;
  39359. }
  39360. if (scene.getEngine().getCaps().standardDerivatives && this._bumpTexture && StandardMaterial.BumpTextureEnabled) {
  39361. // Bump texure can not be not blocking.
  39362. if (!this._bumpTexture.isReady()) {
  39363. return false;
  39364. }
  39365. else {
  39366. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._bumpTexture, defines, "BUMP");
  39367. defines.PARALLAX = this._useParallax;
  39368. defines.PARALLAXOCCLUSION = this._useParallaxOcclusion;
  39369. }
  39370. defines.OBJECTSPACE_NORMALMAP = this._useObjectSpaceNormalMap;
  39371. }
  39372. else {
  39373. defines.BUMP = false;
  39374. }
  39375. if (this._refractionTexture && StandardMaterial.RefractionTextureEnabled) {
  39376. if (!this._refractionTexture.isReadyOrNotBlocking()) {
  39377. return false;
  39378. }
  39379. else {
  39380. defines._needUVs = true;
  39381. defines.REFRACTION = true;
  39382. defines.REFRACTIONMAP_3D = this._refractionTexture.isCube;
  39383. }
  39384. }
  39385. else {
  39386. defines.REFRACTION = false;
  39387. }
  39388. defines.TWOSIDEDLIGHTING = !this._backFaceCulling && this._twoSidedLighting;
  39389. }
  39390. else {
  39391. defines.DIFFUSE = false;
  39392. defines.AMBIENT = false;
  39393. defines.OPACITY = false;
  39394. defines.REFLECTION = false;
  39395. defines.EMISSIVE = false;
  39396. defines.LIGHTMAP = false;
  39397. defines.BUMP = false;
  39398. defines.REFRACTION = false;
  39399. }
  39400. defines.ALPHAFROMDIFFUSE = this._shouldUseAlphaFromDiffuseTexture();
  39401. defines.EMISSIVEASILLUMINATION = this._useEmissiveAsIllumination;
  39402. defines.LINKEMISSIVEWITHDIFFUSE = this._linkEmissiveWithDiffuse;
  39403. defines.SPECULAROVERALPHA = this._useSpecularOverAlpha;
  39404. defines.PREMULTIPLYALPHA = (this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED || this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED_PORTERDUFF);
  39405. }
  39406. if (defines._areImageProcessingDirty) {
  39407. if (!this._imageProcessingConfiguration.isReady()) {
  39408. return false;
  39409. }
  39410. this._imageProcessingConfiguration.prepareDefines(defines);
  39411. }
  39412. if (defines._areFresnelDirty) {
  39413. if (StandardMaterial.FresnelEnabled) {
  39414. // Fresnel
  39415. if (this._diffuseFresnelParameters || this._opacityFresnelParameters ||
  39416. this._emissiveFresnelParameters || this._refractionFresnelParameters ||
  39417. this._reflectionFresnelParameters) {
  39418. defines.DIFFUSEFRESNEL = (this._diffuseFresnelParameters && this._diffuseFresnelParameters.isEnabled);
  39419. defines.OPACITYFRESNEL = (this._opacityFresnelParameters && this._opacityFresnelParameters.isEnabled);
  39420. defines.REFLECTIONFRESNEL = (this._reflectionFresnelParameters && this._reflectionFresnelParameters.isEnabled);
  39421. defines.REFLECTIONFRESNELFROMSPECULAR = this._useReflectionFresnelFromSpecular;
  39422. defines.REFRACTIONFRESNEL = (this._refractionFresnelParameters && this._refractionFresnelParameters.isEnabled);
  39423. defines.EMISSIVEFRESNEL = (this._emissiveFresnelParameters && this._emissiveFresnelParameters.isEnabled);
  39424. defines._needNormals = true;
  39425. defines.FRESNEL = true;
  39426. }
  39427. }
  39428. else {
  39429. defines.FRESNEL = false;
  39430. }
  39431. }
  39432. // Misc.
  39433. BABYLON.MaterialHelper.PrepareDefinesForMisc(mesh, scene, this._useLogarithmicDepth, this.pointsCloud, this.fogEnabled, this._shouldTurnAlphaTestOn(mesh), defines);
  39434. // Attribs
  39435. BABYLON.MaterialHelper.PrepareDefinesForAttributes(mesh, defines, true, true, true);
  39436. // Values that need to be evaluated on every frame
  39437. BABYLON.MaterialHelper.PrepareDefinesForFrameBoundValues(scene, engine, defines, useInstances);
  39438. // Get correct effect
  39439. if (defines.isDirty) {
  39440. defines.markAsProcessed();
  39441. scene.resetCachedMaterial();
  39442. // Fallbacks
  39443. var fallbacks = new BABYLON.EffectFallbacks();
  39444. if (defines.REFLECTION) {
  39445. fallbacks.addFallback(0, "REFLECTION");
  39446. }
  39447. if (defines.SPECULAR) {
  39448. fallbacks.addFallback(0, "SPECULAR");
  39449. }
  39450. if (defines.BUMP) {
  39451. fallbacks.addFallback(0, "BUMP");
  39452. }
  39453. if (defines.PARALLAX) {
  39454. fallbacks.addFallback(1, "PARALLAX");
  39455. }
  39456. if (defines.PARALLAXOCCLUSION) {
  39457. fallbacks.addFallback(0, "PARALLAXOCCLUSION");
  39458. }
  39459. if (defines.SPECULAROVERALPHA) {
  39460. fallbacks.addFallback(0, "SPECULAROVERALPHA");
  39461. }
  39462. if (defines.FOG) {
  39463. fallbacks.addFallback(1, "FOG");
  39464. }
  39465. if (defines.POINTSIZE) {
  39466. fallbacks.addFallback(0, "POINTSIZE");
  39467. }
  39468. if (defines.LOGARITHMICDEPTH) {
  39469. fallbacks.addFallback(0, "LOGARITHMICDEPTH");
  39470. }
  39471. BABYLON.MaterialHelper.HandleFallbacksForShadows(defines, fallbacks, this._maxSimultaneousLights);
  39472. if (defines.SPECULARTERM) {
  39473. fallbacks.addFallback(0, "SPECULARTERM");
  39474. }
  39475. if (defines.DIFFUSEFRESNEL) {
  39476. fallbacks.addFallback(1, "DIFFUSEFRESNEL");
  39477. }
  39478. if (defines.OPACITYFRESNEL) {
  39479. fallbacks.addFallback(2, "OPACITYFRESNEL");
  39480. }
  39481. if (defines.REFLECTIONFRESNEL) {
  39482. fallbacks.addFallback(3, "REFLECTIONFRESNEL");
  39483. }
  39484. if (defines.EMISSIVEFRESNEL) {
  39485. fallbacks.addFallback(4, "EMISSIVEFRESNEL");
  39486. }
  39487. if (defines.FRESNEL) {
  39488. fallbacks.addFallback(4, "FRESNEL");
  39489. }
  39490. //Attributes
  39491. var attribs = [BABYLON.VertexBuffer.PositionKind];
  39492. if (defines.NORMAL) {
  39493. attribs.push(BABYLON.VertexBuffer.NormalKind);
  39494. }
  39495. if (defines.UV1) {
  39496. attribs.push(BABYLON.VertexBuffer.UVKind);
  39497. }
  39498. if (defines.UV2) {
  39499. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  39500. }
  39501. if (defines.VERTEXCOLOR) {
  39502. attribs.push(BABYLON.VertexBuffer.ColorKind);
  39503. }
  39504. BABYLON.MaterialHelper.PrepareAttributesForBones(attribs, mesh, defines, fallbacks);
  39505. BABYLON.MaterialHelper.PrepareAttributesForInstances(attribs, defines);
  39506. BABYLON.MaterialHelper.PrepareAttributesForMorphTargets(attribs, mesh, defines);
  39507. var shaderName = "default";
  39508. var uniforms = ["world", "view", "viewProjection", "vEyePosition", "vLightsType", "vAmbientColor", "vDiffuseColor", "vSpecularColor", "vEmissiveColor",
  39509. "vFogInfos", "vFogColor", "pointSize",
  39510. "vDiffuseInfos", "vAmbientInfos", "vOpacityInfos", "vReflectionInfos", "vEmissiveInfos", "vSpecularInfos", "vBumpInfos", "vLightmapInfos", "vRefractionInfos",
  39511. "mBones",
  39512. "vClipPlane", "diffuseMatrix", "ambientMatrix", "opacityMatrix", "reflectionMatrix", "emissiveMatrix", "specularMatrix", "bumpMatrix", "normalMatrix", "lightmapMatrix", "refractionMatrix",
  39513. "diffuseLeftColor", "diffuseRightColor", "opacityParts", "reflectionLeftColor", "reflectionRightColor", "emissiveLeftColor", "emissiveRightColor", "refractionLeftColor", "refractionRightColor",
  39514. "vReflectionPosition", "vReflectionSize",
  39515. "logarithmicDepthConstant", "vTangentSpaceParams"
  39516. ];
  39517. var samplers = ["diffuseSampler", "ambientSampler", "opacitySampler", "reflectionCubeSampler", "reflection2DSampler", "emissiveSampler", "specularSampler", "bumpSampler", "lightmapSampler", "refractionCubeSampler", "refraction2DSampler"];
  39518. var uniformBuffers = ["Material", "Scene"];
  39519. BABYLON.ImageProcessingConfiguration.PrepareUniforms(uniforms, defines);
  39520. BABYLON.ImageProcessingConfiguration.PrepareSamplers(samplers, defines);
  39521. BABYLON.MaterialHelper.PrepareUniformsAndSamplersList({
  39522. uniformsNames: uniforms,
  39523. uniformBuffersNames: uniformBuffers,
  39524. samplers: samplers,
  39525. defines: defines,
  39526. maxSimultaneousLights: this._maxSimultaneousLights
  39527. });
  39528. if (this.customShaderNameResolve) {
  39529. shaderName = this.customShaderNameResolve(shaderName, uniforms, uniformBuffers, samplers, defines);
  39530. }
  39531. var join = defines.toString();
  39532. subMesh.setEffect(scene.getEngine().createEffect(shaderName, {
  39533. attributes: attribs,
  39534. uniformsNames: uniforms,
  39535. uniformBuffersNames: uniformBuffers,
  39536. samplers: samplers,
  39537. defines: join,
  39538. fallbacks: fallbacks,
  39539. onCompiled: this.onCompiled,
  39540. onError: this.onError,
  39541. indexParameters: { maxSimultaneousLights: this._maxSimultaneousLights, maxSimultaneousMorphTargets: defines.NUM_MORPH_INFLUENCERS }
  39542. }, engine), defines);
  39543. this.buildUniformLayout();
  39544. }
  39545. if (!subMesh.effect || !subMesh.effect.isReady()) {
  39546. return false;
  39547. }
  39548. defines._renderId = scene.getRenderId();
  39549. this._wasPreviouslyReady = true;
  39550. return true;
  39551. };
  39552. StandardMaterial.prototype.buildUniformLayout = function () {
  39553. // Order is important !
  39554. this._uniformBuffer.addUniform("diffuseLeftColor", 4);
  39555. this._uniformBuffer.addUniform("diffuseRightColor", 4);
  39556. this._uniformBuffer.addUniform("opacityParts", 4);
  39557. this._uniformBuffer.addUniform("reflectionLeftColor", 4);
  39558. this._uniformBuffer.addUniform("reflectionRightColor", 4);
  39559. this._uniformBuffer.addUniform("refractionLeftColor", 4);
  39560. this._uniformBuffer.addUniform("refractionRightColor", 4);
  39561. this._uniformBuffer.addUniform("emissiveLeftColor", 4);
  39562. this._uniformBuffer.addUniform("emissiveRightColor", 4);
  39563. this._uniformBuffer.addUniform("vDiffuseInfos", 2);
  39564. this._uniformBuffer.addUniform("vAmbientInfos", 2);
  39565. this._uniformBuffer.addUniform("vOpacityInfos", 2);
  39566. this._uniformBuffer.addUniform("vReflectionInfos", 2);
  39567. this._uniformBuffer.addUniform("vReflectionPosition", 3);
  39568. this._uniformBuffer.addUniform("vReflectionSize", 3);
  39569. this._uniformBuffer.addUniform("vEmissiveInfos", 2);
  39570. this._uniformBuffer.addUniform("vLightmapInfos", 2);
  39571. this._uniformBuffer.addUniform("vSpecularInfos", 2);
  39572. this._uniformBuffer.addUniform("vBumpInfos", 3);
  39573. this._uniformBuffer.addUniform("diffuseMatrix", 16);
  39574. this._uniformBuffer.addUniform("ambientMatrix", 16);
  39575. this._uniformBuffer.addUniform("opacityMatrix", 16);
  39576. this._uniformBuffer.addUniform("reflectionMatrix", 16);
  39577. this._uniformBuffer.addUniform("emissiveMatrix", 16);
  39578. this._uniformBuffer.addUniform("lightmapMatrix", 16);
  39579. this._uniformBuffer.addUniform("specularMatrix", 16);
  39580. this._uniformBuffer.addUniform("bumpMatrix", 16);
  39581. this._uniformBuffer.addUniform("vTangentSpaceParams", 2);
  39582. this._uniformBuffer.addUniform("refractionMatrix", 16);
  39583. this._uniformBuffer.addUniform("vRefractionInfos", 4);
  39584. this._uniformBuffer.addUniform("vSpecularColor", 4);
  39585. this._uniformBuffer.addUniform("vEmissiveColor", 3);
  39586. this._uniformBuffer.addUniform("vDiffuseColor", 4);
  39587. this._uniformBuffer.addUniform("pointSize", 1);
  39588. this._uniformBuffer.create();
  39589. };
  39590. StandardMaterial.prototype.unbind = function () {
  39591. if (this._activeEffect) {
  39592. if (this._reflectionTexture && this._reflectionTexture.isRenderTarget) {
  39593. this._activeEffect.setTexture("reflection2DSampler", null);
  39594. }
  39595. if (this._refractionTexture && this._refractionTexture.isRenderTarget) {
  39596. this._activeEffect.setTexture("refraction2DSampler", null);
  39597. }
  39598. }
  39599. _super.prototype.unbind.call(this);
  39600. };
  39601. StandardMaterial.prototype.bindForSubMesh = function (world, mesh, subMesh) {
  39602. var scene = this.getScene();
  39603. var defines = subMesh._materialDefines;
  39604. if (!defines) {
  39605. return;
  39606. }
  39607. var effect = subMesh.effect;
  39608. if (!effect) {
  39609. return;
  39610. }
  39611. this._activeEffect = effect;
  39612. // Matrices
  39613. this.bindOnlyWorldMatrix(world);
  39614. // Normal Matrix
  39615. if (defines.OBJECTSPACE_NORMALMAP) {
  39616. world.toNormalMatrix(this._normalMatrix);
  39617. this.bindOnlyNormalMatrix(this._normalMatrix);
  39618. }
  39619. var mustRebind = this._mustRebind(scene, effect, mesh.visibility);
  39620. // Bones
  39621. BABYLON.MaterialHelper.BindBonesParameters(mesh, effect);
  39622. if (mustRebind) {
  39623. this._uniformBuffer.bindToEffect(effect, "Material");
  39624. this.bindViewProjection(effect);
  39625. if (!this._uniformBuffer.useUbo || !this.isFrozen || !this._uniformBuffer.isSync) {
  39626. if (StandardMaterial.FresnelEnabled && defines.FRESNEL) {
  39627. // Fresnel
  39628. if (this.diffuseFresnelParameters && this.diffuseFresnelParameters.isEnabled) {
  39629. this._uniformBuffer.updateColor4("diffuseLeftColor", this.diffuseFresnelParameters.leftColor, this.diffuseFresnelParameters.power);
  39630. this._uniformBuffer.updateColor4("diffuseRightColor", this.diffuseFresnelParameters.rightColor, this.diffuseFresnelParameters.bias);
  39631. }
  39632. if (this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled) {
  39633. this._uniformBuffer.updateColor4("opacityParts", new BABYLON.Color3(this.opacityFresnelParameters.leftColor.toLuminance(), this.opacityFresnelParameters.rightColor.toLuminance(), this.opacityFresnelParameters.bias), this.opacityFresnelParameters.power);
  39634. }
  39635. if (this.reflectionFresnelParameters && this.reflectionFresnelParameters.isEnabled) {
  39636. this._uniformBuffer.updateColor4("reflectionLeftColor", this.reflectionFresnelParameters.leftColor, this.reflectionFresnelParameters.power);
  39637. this._uniformBuffer.updateColor4("reflectionRightColor", this.reflectionFresnelParameters.rightColor, this.reflectionFresnelParameters.bias);
  39638. }
  39639. if (this.refractionFresnelParameters && this.refractionFresnelParameters.isEnabled) {
  39640. this._uniformBuffer.updateColor4("refractionLeftColor", this.refractionFresnelParameters.leftColor, this.refractionFresnelParameters.power);
  39641. this._uniformBuffer.updateColor4("refractionRightColor", this.refractionFresnelParameters.rightColor, this.refractionFresnelParameters.bias);
  39642. }
  39643. if (this.emissiveFresnelParameters && this.emissiveFresnelParameters.isEnabled) {
  39644. this._uniformBuffer.updateColor4("emissiveLeftColor", this.emissiveFresnelParameters.leftColor, this.emissiveFresnelParameters.power);
  39645. this._uniformBuffer.updateColor4("emissiveRightColor", this.emissiveFresnelParameters.rightColor, this.emissiveFresnelParameters.bias);
  39646. }
  39647. }
  39648. // Textures
  39649. if (scene.texturesEnabled) {
  39650. if (this._diffuseTexture && StandardMaterial.DiffuseTextureEnabled) {
  39651. this._uniformBuffer.updateFloat2("vDiffuseInfos", this._diffuseTexture.coordinatesIndex, this._diffuseTexture.level);
  39652. BABYLON.MaterialHelper.BindTextureMatrix(this._diffuseTexture, this._uniformBuffer, "diffuse");
  39653. }
  39654. if (this._ambientTexture && StandardMaterial.AmbientTextureEnabled) {
  39655. this._uniformBuffer.updateFloat2("vAmbientInfos", this._ambientTexture.coordinatesIndex, this._ambientTexture.level);
  39656. BABYLON.MaterialHelper.BindTextureMatrix(this._ambientTexture, this._uniformBuffer, "ambient");
  39657. }
  39658. if (this._opacityTexture && StandardMaterial.OpacityTextureEnabled) {
  39659. this._uniformBuffer.updateFloat2("vOpacityInfos", this._opacityTexture.coordinatesIndex, this._opacityTexture.level);
  39660. BABYLON.MaterialHelper.BindTextureMatrix(this._opacityTexture, this._uniformBuffer, "opacity");
  39661. }
  39662. if (this._reflectionTexture && StandardMaterial.ReflectionTextureEnabled) {
  39663. this._uniformBuffer.updateFloat2("vReflectionInfos", this._reflectionTexture.level, this.roughness);
  39664. this._uniformBuffer.updateMatrix("reflectionMatrix", this._reflectionTexture.getReflectionTextureMatrix());
  39665. if (this._reflectionTexture.boundingBoxSize) {
  39666. var cubeTexture = this._reflectionTexture;
  39667. this._uniformBuffer.updateVector3("vReflectionPosition", cubeTexture.boundingBoxPosition);
  39668. this._uniformBuffer.updateVector3("vReflectionSize", cubeTexture.boundingBoxSize);
  39669. }
  39670. }
  39671. if (this._emissiveTexture && StandardMaterial.EmissiveTextureEnabled) {
  39672. this._uniformBuffer.updateFloat2("vEmissiveInfos", this._emissiveTexture.coordinatesIndex, this._emissiveTexture.level);
  39673. BABYLON.MaterialHelper.BindTextureMatrix(this._emissiveTexture, this._uniformBuffer, "emissive");
  39674. }
  39675. if (this._lightmapTexture && StandardMaterial.LightmapTextureEnabled) {
  39676. this._uniformBuffer.updateFloat2("vLightmapInfos", this._lightmapTexture.coordinatesIndex, this._lightmapTexture.level);
  39677. BABYLON.MaterialHelper.BindTextureMatrix(this._lightmapTexture, this._uniformBuffer, "lightmap");
  39678. }
  39679. if (this._specularTexture && StandardMaterial.SpecularTextureEnabled) {
  39680. this._uniformBuffer.updateFloat2("vSpecularInfos", this._specularTexture.coordinatesIndex, this._specularTexture.level);
  39681. BABYLON.MaterialHelper.BindTextureMatrix(this._specularTexture, this._uniformBuffer, "specular");
  39682. }
  39683. if (this._bumpTexture && scene.getEngine().getCaps().standardDerivatives && StandardMaterial.BumpTextureEnabled) {
  39684. this._uniformBuffer.updateFloat3("vBumpInfos", this._bumpTexture.coordinatesIndex, 1.0 / this._bumpTexture.level, this.parallaxScaleBias);
  39685. BABYLON.MaterialHelper.BindTextureMatrix(this._bumpTexture, this._uniformBuffer, "bump");
  39686. if (scene._mirroredCameraPosition) {
  39687. this._uniformBuffer.updateFloat2("vTangentSpaceParams", this._invertNormalMapX ? 1.0 : -1.0, this._invertNormalMapY ? 1.0 : -1.0);
  39688. }
  39689. else {
  39690. this._uniformBuffer.updateFloat2("vTangentSpaceParams", this._invertNormalMapX ? -1.0 : 1.0, this._invertNormalMapY ? -1.0 : 1.0);
  39691. }
  39692. }
  39693. if (this._refractionTexture && StandardMaterial.RefractionTextureEnabled) {
  39694. var depth = 1.0;
  39695. if (!this._refractionTexture.isCube) {
  39696. this._uniformBuffer.updateMatrix("refractionMatrix", this._refractionTexture.getReflectionTextureMatrix());
  39697. if (this._refractionTexture.depth) {
  39698. depth = this._refractionTexture.depth;
  39699. }
  39700. }
  39701. this._uniformBuffer.updateFloat4("vRefractionInfos", this._refractionTexture.level, this.indexOfRefraction, depth, this.invertRefractionY ? -1 : 1);
  39702. }
  39703. }
  39704. // Point size
  39705. if (this.pointsCloud) {
  39706. this._uniformBuffer.updateFloat("pointSize", this.pointSize);
  39707. }
  39708. if (defines.SPECULARTERM) {
  39709. this._uniformBuffer.updateColor4("vSpecularColor", this.specularColor, this.specularPower);
  39710. }
  39711. this._uniformBuffer.updateColor3("vEmissiveColor", this.emissiveColor);
  39712. // Diffuse
  39713. this._uniformBuffer.updateColor4("vDiffuseColor", this.diffuseColor, this.alpha * mesh.visibility);
  39714. }
  39715. // Textures
  39716. if (scene.texturesEnabled) {
  39717. if (this._diffuseTexture && StandardMaterial.DiffuseTextureEnabled) {
  39718. effect.setTexture("diffuseSampler", this._diffuseTexture);
  39719. }
  39720. if (this._ambientTexture && StandardMaterial.AmbientTextureEnabled) {
  39721. effect.setTexture("ambientSampler", this._ambientTexture);
  39722. }
  39723. if (this._opacityTexture && StandardMaterial.OpacityTextureEnabled) {
  39724. effect.setTexture("opacitySampler", this._opacityTexture);
  39725. }
  39726. if (this._reflectionTexture && StandardMaterial.ReflectionTextureEnabled) {
  39727. if (this._reflectionTexture.isCube) {
  39728. effect.setTexture("reflectionCubeSampler", this._reflectionTexture);
  39729. }
  39730. else {
  39731. effect.setTexture("reflection2DSampler", this._reflectionTexture);
  39732. }
  39733. }
  39734. if (this._emissiveTexture && StandardMaterial.EmissiveTextureEnabled) {
  39735. effect.setTexture("emissiveSampler", this._emissiveTexture);
  39736. }
  39737. if (this._lightmapTexture && StandardMaterial.LightmapTextureEnabled) {
  39738. effect.setTexture("lightmapSampler", this._lightmapTexture);
  39739. }
  39740. if (this._specularTexture && StandardMaterial.SpecularTextureEnabled) {
  39741. effect.setTexture("specularSampler", this._specularTexture);
  39742. }
  39743. if (this._bumpTexture && scene.getEngine().getCaps().standardDerivatives && StandardMaterial.BumpTextureEnabled) {
  39744. effect.setTexture("bumpSampler", this._bumpTexture);
  39745. }
  39746. if (this._refractionTexture && StandardMaterial.RefractionTextureEnabled) {
  39747. var depth = 1.0;
  39748. if (this._refractionTexture.isCube) {
  39749. effect.setTexture("refractionCubeSampler", this._refractionTexture);
  39750. }
  39751. else {
  39752. effect.setTexture("refraction2DSampler", this._refractionTexture);
  39753. }
  39754. }
  39755. }
  39756. // Clip plane
  39757. BABYLON.MaterialHelper.BindClipPlane(effect, scene);
  39758. // Colors
  39759. scene.ambientColor.multiplyToRef(this.ambientColor, this._globalAmbientColor);
  39760. BABYLON.MaterialHelper.BindEyePosition(effect, scene);
  39761. effect.setColor3("vAmbientColor", this._globalAmbientColor);
  39762. }
  39763. if (mustRebind || !this.isFrozen) {
  39764. // Lights
  39765. if (scene.lightsEnabled && !this._disableLighting) {
  39766. BABYLON.MaterialHelper.BindLights(scene, mesh, effect, defines, this._maxSimultaneousLights);
  39767. }
  39768. // View
  39769. if (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE || this._reflectionTexture || this._refractionTexture) {
  39770. this.bindView(effect);
  39771. }
  39772. // Fog
  39773. BABYLON.MaterialHelper.BindFogParameters(scene, mesh, effect);
  39774. // Morph targets
  39775. if (defines.NUM_MORPH_INFLUENCERS) {
  39776. BABYLON.MaterialHelper.BindMorphTargetParameters(mesh, effect);
  39777. }
  39778. // Log. depth
  39779. BABYLON.MaterialHelper.BindLogDepth(defines, effect, scene);
  39780. // image processing
  39781. if (!this._imageProcessingConfiguration.applyByPostProcess) {
  39782. this._imageProcessingConfiguration.bind(this._activeEffect);
  39783. }
  39784. }
  39785. this._uniformBuffer.update();
  39786. this._afterBind(mesh, this._activeEffect);
  39787. };
  39788. StandardMaterial.prototype.getAnimatables = function () {
  39789. var results = [];
  39790. if (this._diffuseTexture && this._diffuseTexture.animations && this._diffuseTexture.animations.length > 0) {
  39791. results.push(this._diffuseTexture);
  39792. }
  39793. if (this._ambientTexture && this._ambientTexture.animations && this._ambientTexture.animations.length > 0) {
  39794. results.push(this._ambientTexture);
  39795. }
  39796. if (this._opacityTexture && this._opacityTexture.animations && this._opacityTexture.animations.length > 0) {
  39797. results.push(this._opacityTexture);
  39798. }
  39799. if (this._reflectionTexture && this._reflectionTexture.animations && this._reflectionTexture.animations.length > 0) {
  39800. results.push(this._reflectionTexture);
  39801. }
  39802. if (this._emissiveTexture && this._emissiveTexture.animations && this._emissiveTexture.animations.length > 0) {
  39803. results.push(this._emissiveTexture);
  39804. }
  39805. if (this._specularTexture && this._specularTexture.animations && this._specularTexture.animations.length > 0) {
  39806. results.push(this._specularTexture);
  39807. }
  39808. if (this._bumpTexture && this._bumpTexture.animations && this._bumpTexture.animations.length > 0) {
  39809. results.push(this._bumpTexture);
  39810. }
  39811. if (this._lightmapTexture && this._lightmapTexture.animations && this._lightmapTexture.animations.length > 0) {
  39812. results.push(this._lightmapTexture);
  39813. }
  39814. if (this._refractionTexture && this._refractionTexture.animations && this._refractionTexture.animations.length > 0) {
  39815. results.push(this._refractionTexture);
  39816. }
  39817. return results;
  39818. };
  39819. StandardMaterial.prototype.getActiveTextures = function () {
  39820. var activeTextures = _super.prototype.getActiveTextures.call(this);
  39821. if (this._diffuseTexture) {
  39822. activeTextures.push(this._diffuseTexture);
  39823. }
  39824. if (this._ambientTexture) {
  39825. activeTextures.push(this._ambientTexture);
  39826. }
  39827. if (this._opacityTexture) {
  39828. activeTextures.push(this._opacityTexture);
  39829. }
  39830. if (this._reflectionTexture) {
  39831. activeTextures.push(this._reflectionTexture);
  39832. }
  39833. if (this._emissiveTexture) {
  39834. activeTextures.push(this._emissiveTexture);
  39835. }
  39836. if (this._specularTexture) {
  39837. activeTextures.push(this._specularTexture);
  39838. }
  39839. if (this._bumpTexture) {
  39840. activeTextures.push(this._bumpTexture);
  39841. }
  39842. if (this._lightmapTexture) {
  39843. activeTextures.push(this._lightmapTexture);
  39844. }
  39845. if (this._refractionTexture) {
  39846. activeTextures.push(this._refractionTexture);
  39847. }
  39848. return activeTextures;
  39849. };
  39850. StandardMaterial.prototype.hasTexture = function (texture) {
  39851. if (_super.prototype.hasTexture.call(this, texture)) {
  39852. return true;
  39853. }
  39854. if (this._diffuseTexture === texture) {
  39855. return true;
  39856. }
  39857. if (this._ambientTexture === texture) {
  39858. return true;
  39859. }
  39860. if (this._opacityTexture === texture) {
  39861. return true;
  39862. }
  39863. if (this._reflectionTexture === texture) {
  39864. return true;
  39865. }
  39866. if (this._emissiveTexture === texture) {
  39867. return true;
  39868. }
  39869. if (this._specularTexture === texture) {
  39870. return true;
  39871. }
  39872. if (this._bumpTexture === texture) {
  39873. return true;
  39874. }
  39875. if (this._lightmapTexture === texture) {
  39876. return true;
  39877. }
  39878. if (this._refractionTexture === texture) {
  39879. return true;
  39880. }
  39881. return false;
  39882. };
  39883. StandardMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  39884. if (forceDisposeTextures) {
  39885. if (this._diffuseTexture) {
  39886. this._diffuseTexture.dispose();
  39887. }
  39888. if (this._ambientTexture) {
  39889. this._ambientTexture.dispose();
  39890. }
  39891. if (this._opacityTexture) {
  39892. this._opacityTexture.dispose();
  39893. }
  39894. if (this._reflectionTexture) {
  39895. this._reflectionTexture.dispose();
  39896. }
  39897. if (this._emissiveTexture) {
  39898. this._emissiveTexture.dispose();
  39899. }
  39900. if (this._specularTexture) {
  39901. this._specularTexture.dispose();
  39902. }
  39903. if (this._bumpTexture) {
  39904. this._bumpTexture.dispose();
  39905. }
  39906. if (this._lightmapTexture) {
  39907. this._lightmapTexture.dispose();
  39908. }
  39909. if (this._refractionTexture) {
  39910. this._refractionTexture.dispose();
  39911. }
  39912. }
  39913. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  39914. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  39915. }
  39916. _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);
  39917. };
  39918. StandardMaterial.prototype.clone = function (name) {
  39919. var _this = this;
  39920. var result = BABYLON.SerializationHelper.Clone(function () { return new StandardMaterial(name, _this.getScene()); }, this);
  39921. result.name = name;
  39922. result.id = name;
  39923. return result;
  39924. };
  39925. StandardMaterial.prototype.serialize = function () {
  39926. return BABYLON.SerializationHelper.Serialize(this);
  39927. };
  39928. // Statics
  39929. StandardMaterial.Parse = function (source, scene, rootUrl) {
  39930. return BABYLON.SerializationHelper.Parse(function () { return new StandardMaterial(source.name, scene); }, source, scene, rootUrl);
  39931. };
  39932. Object.defineProperty(StandardMaterial, "DiffuseTextureEnabled", {
  39933. get: function () {
  39934. return StandardMaterial._DiffuseTextureEnabled;
  39935. },
  39936. set: function (value) {
  39937. if (StandardMaterial._DiffuseTextureEnabled === value) {
  39938. return;
  39939. }
  39940. StandardMaterial._DiffuseTextureEnabled = value;
  39941. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  39942. },
  39943. enumerable: true,
  39944. configurable: true
  39945. });
  39946. Object.defineProperty(StandardMaterial, "AmbientTextureEnabled", {
  39947. get: function () {
  39948. return StandardMaterial._AmbientTextureEnabled;
  39949. },
  39950. set: function (value) {
  39951. if (StandardMaterial._AmbientTextureEnabled === value) {
  39952. return;
  39953. }
  39954. StandardMaterial._AmbientTextureEnabled = value;
  39955. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  39956. },
  39957. enumerable: true,
  39958. configurable: true
  39959. });
  39960. Object.defineProperty(StandardMaterial, "OpacityTextureEnabled", {
  39961. get: function () {
  39962. return StandardMaterial._OpacityTextureEnabled;
  39963. },
  39964. set: function (value) {
  39965. if (StandardMaterial._OpacityTextureEnabled === value) {
  39966. return;
  39967. }
  39968. StandardMaterial._OpacityTextureEnabled = value;
  39969. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  39970. },
  39971. enumerable: true,
  39972. configurable: true
  39973. });
  39974. Object.defineProperty(StandardMaterial, "ReflectionTextureEnabled", {
  39975. get: function () {
  39976. return StandardMaterial._ReflectionTextureEnabled;
  39977. },
  39978. set: function (value) {
  39979. if (StandardMaterial._ReflectionTextureEnabled === value) {
  39980. return;
  39981. }
  39982. StandardMaterial._ReflectionTextureEnabled = value;
  39983. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  39984. },
  39985. enumerable: true,
  39986. configurable: true
  39987. });
  39988. Object.defineProperty(StandardMaterial, "EmissiveTextureEnabled", {
  39989. get: function () {
  39990. return StandardMaterial._EmissiveTextureEnabled;
  39991. },
  39992. set: function (value) {
  39993. if (StandardMaterial._EmissiveTextureEnabled === value) {
  39994. return;
  39995. }
  39996. StandardMaterial._EmissiveTextureEnabled = value;
  39997. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  39998. },
  39999. enumerable: true,
  40000. configurable: true
  40001. });
  40002. Object.defineProperty(StandardMaterial, "SpecularTextureEnabled", {
  40003. get: function () {
  40004. return StandardMaterial._SpecularTextureEnabled;
  40005. },
  40006. set: function (value) {
  40007. if (StandardMaterial._SpecularTextureEnabled === value) {
  40008. return;
  40009. }
  40010. StandardMaterial._SpecularTextureEnabled = value;
  40011. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  40012. },
  40013. enumerable: true,
  40014. configurable: true
  40015. });
  40016. Object.defineProperty(StandardMaterial, "BumpTextureEnabled", {
  40017. get: function () {
  40018. return StandardMaterial._BumpTextureEnabled;
  40019. },
  40020. set: function (value) {
  40021. if (StandardMaterial._BumpTextureEnabled === value) {
  40022. return;
  40023. }
  40024. StandardMaterial._BumpTextureEnabled = value;
  40025. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  40026. },
  40027. enumerable: true,
  40028. configurable: true
  40029. });
  40030. Object.defineProperty(StandardMaterial, "LightmapTextureEnabled", {
  40031. get: function () {
  40032. return StandardMaterial._LightmapTextureEnabled;
  40033. },
  40034. set: function (value) {
  40035. if (StandardMaterial._LightmapTextureEnabled === value) {
  40036. return;
  40037. }
  40038. StandardMaterial._LightmapTextureEnabled = value;
  40039. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  40040. },
  40041. enumerable: true,
  40042. configurable: true
  40043. });
  40044. Object.defineProperty(StandardMaterial, "RefractionTextureEnabled", {
  40045. get: function () {
  40046. return StandardMaterial._RefractionTextureEnabled;
  40047. },
  40048. set: function (value) {
  40049. if (StandardMaterial._RefractionTextureEnabled === value) {
  40050. return;
  40051. }
  40052. StandardMaterial._RefractionTextureEnabled = value;
  40053. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  40054. },
  40055. enumerable: true,
  40056. configurable: true
  40057. });
  40058. Object.defineProperty(StandardMaterial, "ColorGradingTextureEnabled", {
  40059. get: function () {
  40060. return StandardMaterial._ColorGradingTextureEnabled;
  40061. },
  40062. set: function (value) {
  40063. if (StandardMaterial._ColorGradingTextureEnabled === value) {
  40064. return;
  40065. }
  40066. StandardMaterial._ColorGradingTextureEnabled = value;
  40067. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  40068. },
  40069. enumerable: true,
  40070. configurable: true
  40071. });
  40072. Object.defineProperty(StandardMaterial, "FresnelEnabled", {
  40073. get: function () {
  40074. return StandardMaterial._FresnelEnabled;
  40075. },
  40076. set: function (value) {
  40077. if (StandardMaterial._FresnelEnabled === value) {
  40078. return;
  40079. }
  40080. StandardMaterial._FresnelEnabled = value;
  40081. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.FresnelDirtyFlag);
  40082. },
  40083. enumerable: true,
  40084. configurable: true
  40085. });
  40086. // Flags used to enable or disable a type of texture for all Standard Materials
  40087. StandardMaterial._DiffuseTextureEnabled = true;
  40088. StandardMaterial._AmbientTextureEnabled = true;
  40089. StandardMaterial._OpacityTextureEnabled = true;
  40090. StandardMaterial._ReflectionTextureEnabled = true;
  40091. StandardMaterial._EmissiveTextureEnabled = true;
  40092. StandardMaterial._SpecularTextureEnabled = true;
  40093. StandardMaterial._BumpTextureEnabled = true;
  40094. StandardMaterial._LightmapTextureEnabled = true;
  40095. StandardMaterial._RefractionTextureEnabled = true;
  40096. StandardMaterial._ColorGradingTextureEnabled = true;
  40097. StandardMaterial._FresnelEnabled = true;
  40098. __decorate([
  40099. BABYLON.serializeAsTexture("diffuseTexture")
  40100. ], StandardMaterial.prototype, "_diffuseTexture", void 0);
  40101. __decorate([
  40102. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesAndMiscDirty")
  40103. ], StandardMaterial.prototype, "diffuseTexture", void 0);
  40104. __decorate([
  40105. BABYLON.serializeAsTexture("ambientTexture")
  40106. ], StandardMaterial.prototype, "_ambientTexture", void 0);
  40107. __decorate([
  40108. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  40109. ], StandardMaterial.prototype, "ambientTexture", void 0);
  40110. __decorate([
  40111. BABYLON.serializeAsTexture("opacityTexture")
  40112. ], StandardMaterial.prototype, "_opacityTexture", void 0);
  40113. __decorate([
  40114. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesAndMiscDirty")
  40115. ], StandardMaterial.prototype, "opacityTexture", void 0);
  40116. __decorate([
  40117. BABYLON.serializeAsTexture("reflectionTexture")
  40118. ], StandardMaterial.prototype, "_reflectionTexture", void 0);
  40119. __decorate([
  40120. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  40121. ], StandardMaterial.prototype, "reflectionTexture", void 0);
  40122. __decorate([
  40123. BABYLON.serializeAsTexture("emissiveTexture")
  40124. ], StandardMaterial.prototype, "_emissiveTexture", void 0);
  40125. __decorate([
  40126. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  40127. ], StandardMaterial.prototype, "emissiveTexture", void 0);
  40128. __decorate([
  40129. BABYLON.serializeAsTexture("specularTexture")
  40130. ], StandardMaterial.prototype, "_specularTexture", void 0);
  40131. __decorate([
  40132. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  40133. ], StandardMaterial.prototype, "specularTexture", void 0);
  40134. __decorate([
  40135. BABYLON.serializeAsTexture("bumpTexture")
  40136. ], StandardMaterial.prototype, "_bumpTexture", void 0);
  40137. __decorate([
  40138. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  40139. ], StandardMaterial.prototype, "bumpTexture", void 0);
  40140. __decorate([
  40141. BABYLON.serializeAsTexture("lightmapTexture")
  40142. ], StandardMaterial.prototype, "_lightmapTexture", void 0);
  40143. __decorate([
  40144. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  40145. ], StandardMaterial.prototype, "lightmapTexture", void 0);
  40146. __decorate([
  40147. BABYLON.serializeAsTexture("refractionTexture")
  40148. ], StandardMaterial.prototype, "_refractionTexture", void 0);
  40149. __decorate([
  40150. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  40151. ], StandardMaterial.prototype, "refractionTexture", void 0);
  40152. __decorate([
  40153. BABYLON.serializeAsColor3("ambient")
  40154. ], StandardMaterial.prototype, "ambientColor", void 0);
  40155. __decorate([
  40156. BABYLON.serializeAsColor3("diffuse")
  40157. ], StandardMaterial.prototype, "diffuseColor", void 0);
  40158. __decorate([
  40159. BABYLON.serializeAsColor3("specular")
  40160. ], StandardMaterial.prototype, "specularColor", void 0);
  40161. __decorate([
  40162. BABYLON.serializeAsColor3("emissive")
  40163. ], StandardMaterial.prototype, "emissiveColor", void 0);
  40164. __decorate([
  40165. BABYLON.serialize()
  40166. ], StandardMaterial.prototype, "specularPower", void 0);
  40167. __decorate([
  40168. BABYLON.serialize("useAlphaFromDiffuseTexture")
  40169. ], StandardMaterial.prototype, "_useAlphaFromDiffuseTexture", void 0);
  40170. __decorate([
  40171. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  40172. ], StandardMaterial.prototype, "useAlphaFromDiffuseTexture", void 0);
  40173. __decorate([
  40174. BABYLON.serialize("useEmissiveAsIllumination")
  40175. ], StandardMaterial.prototype, "_useEmissiveAsIllumination", void 0);
  40176. __decorate([
  40177. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  40178. ], StandardMaterial.prototype, "useEmissiveAsIllumination", void 0);
  40179. __decorate([
  40180. BABYLON.serialize("linkEmissiveWithDiffuse")
  40181. ], StandardMaterial.prototype, "_linkEmissiveWithDiffuse", void 0);
  40182. __decorate([
  40183. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  40184. ], StandardMaterial.prototype, "linkEmissiveWithDiffuse", void 0);
  40185. __decorate([
  40186. BABYLON.serialize("useSpecularOverAlpha")
  40187. ], StandardMaterial.prototype, "_useSpecularOverAlpha", void 0);
  40188. __decorate([
  40189. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  40190. ], StandardMaterial.prototype, "useSpecularOverAlpha", void 0);
  40191. __decorate([
  40192. BABYLON.serialize("useReflectionOverAlpha")
  40193. ], StandardMaterial.prototype, "_useReflectionOverAlpha", void 0);
  40194. __decorate([
  40195. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  40196. ], StandardMaterial.prototype, "useReflectionOverAlpha", void 0);
  40197. __decorate([
  40198. BABYLON.serialize("disableLighting")
  40199. ], StandardMaterial.prototype, "_disableLighting", void 0);
  40200. __decorate([
  40201. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  40202. ], StandardMaterial.prototype, "disableLighting", void 0);
  40203. __decorate([
  40204. BABYLON.serialize("useObjectSpaceNormalMap")
  40205. ], StandardMaterial.prototype, "_useObjectSpaceNormalMap", void 0);
  40206. __decorate([
  40207. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  40208. ], StandardMaterial.prototype, "useObjectSpaceNormalMap", void 0);
  40209. __decorate([
  40210. BABYLON.serialize("useParallax")
  40211. ], StandardMaterial.prototype, "_useParallax", void 0);
  40212. __decorate([
  40213. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  40214. ], StandardMaterial.prototype, "useParallax", void 0);
  40215. __decorate([
  40216. BABYLON.serialize("useParallaxOcclusion")
  40217. ], StandardMaterial.prototype, "_useParallaxOcclusion", void 0);
  40218. __decorate([
  40219. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  40220. ], StandardMaterial.prototype, "useParallaxOcclusion", void 0);
  40221. __decorate([
  40222. BABYLON.serialize()
  40223. ], StandardMaterial.prototype, "parallaxScaleBias", void 0);
  40224. __decorate([
  40225. BABYLON.serialize("roughness")
  40226. ], StandardMaterial.prototype, "_roughness", void 0);
  40227. __decorate([
  40228. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  40229. ], StandardMaterial.prototype, "roughness", void 0);
  40230. __decorate([
  40231. BABYLON.serialize()
  40232. ], StandardMaterial.prototype, "indexOfRefraction", void 0);
  40233. __decorate([
  40234. BABYLON.serialize()
  40235. ], StandardMaterial.prototype, "invertRefractionY", void 0);
  40236. __decorate([
  40237. BABYLON.serialize("useLightmapAsShadowmap")
  40238. ], StandardMaterial.prototype, "_useLightmapAsShadowmap", void 0);
  40239. __decorate([
  40240. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  40241. ], StandardMaterial.prototype, "useLightmapAsShadowmap", void 0);
  40242. __decorate([
  40243. BABYLON.serializeAsFresnelParameters("diffuseFresnelParameters")
  40244. ], StandardMaterial.prototype, "_diffuseFresnelParameters", void 0);
  40245. __decorate([
  40246. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  40247. ], StandardMaterial.prototype, "diffuseFresnelParameters", void 0);
  40248. __decorate([
  40249. BABYLON.serializeAsFresnelParameters("opacityFresnelParameters")
  40250. ], StandardMaterial.prototype, "_opacityFresnelParameters", void 0);
  40251. __decorate([
  40252. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelAndMiscDirty")
  40253. ], StandardMaterial.prototype, "opacityFresnelParameters", void 0);
  40254. __decorate([
  40255. BABYLON.serializeAsFresnelParameters("reflectionFresnelParameters")
  40256. ], StandardMaterial.prototype, "_reflectionFresnelParameters", void 0);
  40257. __decorate([
  40258. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  40259. ], StandardMaterial.prototype, "reflectionFresnelParameters", void 0);
  40260. __decorate([
  40261. BABYLON.serializeAsFresnelParameters("refractionFresnelParameters")
  40262. ], StandardMaterial.prototype, "_refractionFresnelParameters", void 0);
  40263. __decorate([
  40264. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  40265. ], StandardMaterial.prototype, "refractionFresnelParameters", void 0);
  40266. __decorate([
  40267. BABYLON.serializeAsFresnelParameters("emissiveFresnelParameters")
  40268. ], StandardMaterial.prototype, "_emissiveFresnelParameters", void 0);
  40269. __decorate([
  40270. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  40271. ], StandardMaterial.prototype, "emissiveFresnelParameters", void 0);
  40272. __decorate([
  40273. BABYLON.serialize("useReflectionFresnelFromSpecular")
  40274. ], StandardMaterial.prototype, "_useReflectionFresnelFromSpecular", void 0);
  40275. __decorate([
  40276. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  40277. ], StandardMaterial.prototype, "useReflectionFresnelFromSpecular", void 0);
  40278. __decorate([
  40279. BABYLON.serialize("useGlossinessFromSpecularMapAlpha")
  40280. ], StandardMaterial.prototype, "_useGlossinessFromSpecularMapAlpha", void 0);
  40281. __decorate([
  40282. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  40283. ], StandardMaterial.prototype, "useGlossinessFromSpecularMapAlpha", void 0);
  40284. __decorate([
  40285. BABYLON.serialize("maxSimultaneousLights")
  40286. ], StandardMaterial.prototype, "_maxSimultaneousLights", void 0);
  40287. __decorate([
  40288. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  40289. ], StandardMaterial.prototype, "maxSimultaneousLights", void 0);
  40290. __decorate([
  40291. BABYLON.serialize("invertNormalMapX")
  40292. ], StandardMaterial.prototype, "_invertNormalMapX", void 0);
  40293. __decorate([
  40294. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  40295. ], StandardMaterial.prototype, "invertNormalMapX", void 0);
  40296. __decorate([
  40297. BABYLON.serialize("invertNormalMapY")
  40298. ], StandardMaterial.prototype, "_invertNormalMapY", void 0);
  40299. __decorate([
  40300. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  40301. ], StandardMaterial.prototype, "invertNormalMapY", void 0);
  40302. __decorate([
  40303. BABYLON.serialize("twoSidedLighting")
  40304. ], StandardMaterial.prototype, "_twoSidedLighting", void 0);
  40305. __decorate([
  40306. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  40307. ], StandardMaterial.prototype, "twoSidedLighting", void 0);
  40308. __decorate([
  40309. BABYLON.serialize()
  40310. ], StandardMaterial.prototype, "useLogarithmicDepth", null);
  40311. return StandardMaterial;
  40312. }(BABYLON.PushMaterial));
  40313. BABYLON.StandardMaterial = StandardMaterial;
  40314. })(BABYLON || (BABYLON = {}));
  40315. //# sourceMappingURL=babylon.standardMaterial.js.map
  40316. var BABYLON;
  40317. (function (BABYLON) {
  40318. /**
  40319. * Manages the defines for the PBR Material.
  40320. */
  40321. var PBRMaterialDefines = /** @class */ (function (_super) {
  40322. __extends(PBRMaterialDefines, _super);
  40323. /**
  40324. * Initializes the PBR Material defines.
  40325. */
  40326. function PBRMaterialDefines() {
  40327. var _this = _super.call(this) || this;
  40328. _this.PBR = true;
  40329. _this.MAINUV1 = false;
  40330. _this.MAINUV2 = false;
  40331. _this.UV1 = false;
  40332. _this.UV2 = false;
  40333. _this.ALBEDO = false;
  40334. _this.ALBEDODIRECTUV = 0;
  40335. _this.VERTEXCOLOR = false;
  40336. _this.AMBIENT = false;
  40337. _this.AMBIENTDIRECTUV = 0;
  40338. _this.AMBIENTINGRAYSCALE = false;
  40339. _this.OPACITY = false;
  40340. _this.VERTEXALPHA = false;
  40341. _this.OPACITYDIRECTUV = 0;
  40342. _this.OPACITYRGB = false;
  40343. _this.ALPHATEST = false;
  40344. _this.DEPTHPREPASS = false;
  40345. _this.ALPHABLEND = false;
  40346. _this.ALPHAFROMALBEDO = false;
  40347. _this.ALPHATESTVALUE = 0.5;
  40348. _this.SPECULAROVERALPHA = false;
  40349. _this.RADIANCEOVERALPHA = false;
  40350. _this.ALPHAFRESNEL = false;
  40351. _this.LINEARALPHAFRESNEL = false;
  40352. _this.PREMULTIPLYALPHA = false;
  40353. _this.EMISSIVE = false;
  40354. _this.EMISSIVEDIRECTUV = 0;
  40355. _this.REFLECTIVITY = false;
  40356. _this.REFLECTIVITYDIRECTUV = 0;
  40357. _this.SPECULARTERM = false;
  40358. _this.MICROSURFACEFROMREFLECTIVITYMAP = false;
  40359. _this.MICROSURFACEAUTOMATIC = false;
  40360. _this.LODBASEDMICROSFURACE = false;
  40361. _this.MICROSURFACEMAP = false;
  40362. _this.MICROSURFACEMAPDIRECTUV = 0;
  40363. _this.METALLICWORKFLOW = false;
  40364. _this.ROUGHNESSSTOREINMETALMAPALPHA = false;
  40365. _this.ROUGHNESSSTOREINMETALMAPGREEN = false;
  40366. _this.METALLNESSSTOREINMETALMAPBLUE = false;
  40367. _this.AOSTOREINMETALMAPRED = false;
  40368. _this.ENVIRONMENTBRDF = false;
  40369. _this.NORMAL = false;
  40370. _this.TANGENT = false;
  40371. _this.BUMP = false;
  40372. _this.BUMPDIRECTUV = 0;
  40373. _this.OBJECTSPACE_NORMALMAP = false;
  40374. _this.PARALLAX = false;
  40375. _this.PARALLAXOCCLUSION = false;
  40376. _this.NORMALXYSCALE = true;
  40377. _this.LIGHTMAP = false;
  40378. _this.LIGHTMAPDIRECTUV = 0;
  40379. _this.USELIGHTMAPASSHADOWMAP = false;
  40380. _this.REFLECTION = false;
  40381. _this.REFLECTIONMAP_3D = false;
  40382. _this.REFLECTIONMAP_SPHERICAL = false;
  40383. _this.REFLECTIONMAP_PLANAR = false;
  40384. _this.REFLECTIONMAP_CUBIC = false;
  40385. _this.USE_LOCAL_REFLECTIONMAP_CUBIC = false;
  40386. _this.REFLECTIONMAP_PROJECTION = false;
  40387. _this.REFLECTIONMAP_SKYBOX = false;
  40388. _this.REFLECTIONMAP_EXPLICIT = false;
  40389. _this.REFLECTIONMAP_EQUIRECTANGULAR = false;
  40390. _this.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  40391. _this.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  40392. _this.INVERTCUBICMAP = false;
  40393. _this.USESPHERICALFROMREFLECTIONMAP = false;
  40394. _this.USESPHERICALINVERTEX = false;
  40395. _this.REFLECTIONMAP_OPPOSITEZ = false;
  40396. _this.LODINREFLECTIONALPHA = false;
  40397. _this.GAMMAREFLECTION = false;
  40398. _this.RADIANCEOCCLUSION = false;
  40399. _this.HORIZONOCCLUSION = false;
  40400. _this.REFRACTION = false;
  40401. _this.REFRACTIONMAP_3D = false;
  40402. _this.REFRACTIONMAP_OPPOSITEZ = false;
  40403. _this.LODINREFRACTIONALPHA = false;
  40404. _this.GAMMAREFRACTION = false;
  40405. _this.LINKREFRACTIONTOTRANSPARENCY = false;
  40406. _this.INSTANCES = false;
  40407. _this.NUM_BONE_INFLUENCERS = 0;
  40408. _this.BonesPerMesh = 0;
  40409. _this.NONUNIFORMSCALING = false;
  40410. _this.MORPHTARGETS = false;
  40411. _this.MORPHTARGETS_NORMAL = false;
  40412. _this.MORPHTARGETS_TANGENT = false;
  40413. _this.NUM_MORPH_INFLUENCERS = 0;
  40414. _this.IMAGEPROCESSING = false;
  40415. _this.VIGNETTE = false;
  40416. _this.VIGNETTEBLENDMODEMULTIPLY = false;
  40417. _this.VIGNETTEBLENDMODEOPAQUE = false;
  40418. _this.TONEMAPPING = false;
  40419. _this.CONTRAST = false;
  40420. _this.COLORCURVES = false;
  40421. _this.COLORGRADING = false;
  40422. _this.COLORGRADING3D = false;
  40423. _this.SAMPLER3DGREENDEPTH = false;
  40424. _this.SAMPLER3DBGRMAP = false;
  40425. _this.IMAGEPROCESSINGPOSTPROCESS = false;
  40426. _this.EXPOSURE = false;
  40427. _this.GRAIN = false;
  40428. _this.USEPHYSICALLIGHTFALLOFF = false;
  40429. _this.TWOSIDEDLIGHTING = false;
  40430. _this.SHADOWFLOAT = false;
  40431. _this.CLIPPLANE = false;
  40432. _this.POINTSIZE = false;
  40433. _this.FOG = false;
  40434. _this.LOGARITHMICDEPTH = false;
  40435. _this.FORCENORMALFORWARD = false;
  40436. _this.rebuild();
  40437. return _this;
  40438. }
  40439. /**
  40440. * Resets the PBR Material defines.
  40441. */
  40442. PBRMaterialDefines.prototype.reset = function () {
  40443. _super.prototype.reset.call(this);
  40444. this.ALPHATESTVALUE = 0.5;
  40445. this.PBR = true;
  40446. };
  40447. return PBRMaterialDefines;
  40448. }(BABYLON.MaterialDefines));
  40449. /**
  40450. * The Physically based material base class of BJS.
  40451. *
  40452. * This offers the main features of a standard PBR material.
  40453. * For more information, please refer to the documentation :
  40454. * http://doc.babylonjs.com/extensions/Physically_Based_Rendering
  40455. */
  40456. var PBRBaseMaterial = /** @class */ (function (_super) {
  40457. __extends(PBRBaseMaterial, _super);
  40458. /**
  40459. * Instantiates a new PBRMaterial instance.
  40460. *
  40461. * @param name The material name
  40462. * @param scene The scene the material will be use in.
  40463. */
  40464. function PBRBaseMaterial(name, scene) {
  40465. var _this = _super.call(this, name, scene) || this;
  40466. /**
  40467. * Intensity of the direct lights e.g. the four lights available in your scene.
  40468. * This impacts both the direct diffuse and specular highlights.
  40469. */
  40470. _this._directIntensity = 1.0;
  40471. /**
  40472. * Intensity of the emissive part of the material.
  40473. * This helps controlling the emissive effect without modifying the emissive color.
  40474. */
  40475. _this._emissiveIntensity = 1.0;
  40476. /**
  40477. * Intensity of the environment e.g. how much the environment will light the object
  40478. * either through harmonics for rough material or through the refelction for shiny ones.
  40479. */
  40480. _this._environmentIntensity = 1.0;
  40481. /**
  40482. * This is a special control allowing the reduction of the specular highlights coming from the
  40483. * four lights of the scene. Those highlights may not be needed in full environment lighting.
  40484. */
  40485. _this._specularIntensity = 1.0;
  40486. /**
  40487. * This stores the direct, emissive, environment, and specular light intensities into a Vector4.
  40488. */
  40489. _this._lightingInfos = new BABYLON.Vector4(_this._directIntensity, _this._emissiveIntensity, _this._environmentIntensity, _this._specularIntensity);
  40490. /**
  40491. * Debug Control allowing disabling the bump map on this material.
  40492. */
  40493. _this._disableBumpMap = false;
  40494. /**
  40495. * AKA Occlusion Texture Intensity in other nomenclature.
  40496. */
  40497. _this._ambientTextureStrength = 1.0;
  40498. /**
  40499. * The color of a material in ambient lighting.
  40500. */
  40501. _this._ambientColor = new BABYLON.Color3(0, 0, 0);
  40502. /**
  40503. * AKA Diffuse Color in other nomenclature.
  40504. */
  40505. _this._albedoColor = new BABYLON.Color3(1, 1, 1);
  40506. /**
  40507. * AKA Specular Color in other nomenclature.
  40508. */
  40509. _this._reflectivityColor = new BABYLON.Color3(1, 1, 1);
  40510. /**
  40511. * The color applied when light is reflected from a material.
  40512. */
  40513. _this._reflectionColor = new BABYLON.Color3(1, 1, 1);
  40514. /**
  40515. * The color applied when light is emitted from a material.
  40516. */
  40517. _this._emissiveColor = new BABYLON.Color3(0, 0, 0);
  40518. /**
  40519. * AKA Glossiness in other nomenclature.
  40520. */
  40521. _this._microSurface = 0.9;
  40522. /**
  40523. * source material index of refraction (IOR)' / 'destination material IOR.
  40524. */
  40525. _this._indexOfRefraction = 0.66;
  40526. /**
  40527. * Controls if refraction needs to be inverted on Y. This could be usefull for procedural texture.
  40528. */
  40529. _this._invertRefractionY = false;
  40530. /**
  40531. * This parameters will make the material used its opacity to control how much it is refracting aginst not.
  40532. * Materials half opaque for instance using refraction could benefit from this control.
  40533. */
  40534. _this._linkRefractionWithTransparency = false;
  40535. /**
  40536. * Specifies that the material will use the light map as a show map.
  40537. */
  40538. _this._useLightmapAsShadowmap = false;
  40539. /**
  40540. * This parameters will enable/disable Horizon occlusion to prevent normal maps to look shiny when the normal
  40541. * makes the reflect vector face the model (under horizon).
  40542. */
  40543. _this._useHorizonOcclusion = true;
  40544. /**
  40545. * This parameters will enable/disable radiance occlusion by preventing the radiance to lit
  40546. * too much the area relying on ambient texture to define their ambient occlusion.
  40547. */
  40548. _this._useRadianceOcclusion = true;
  40549. /**
  40550. * Specifies that the alpha is coming form the albedo channel alpha channel for alpha blending.
  40551. */
  40552. _this._useAlphaFromAlbedoTexture = false;
  40553. /**
  40554. * Specifies that the material will keeps the specular highlights over a transparent surface (only the most limunous ones).
  40555. * A car glass is a good exemple of that. When sun reflects on it you can not see what is behind.
  40556. */
  40557. _this._useSpecularOverAlpha = true;
  40558. /**
  40559. * Specifies if the reflectivity texture contains the glossiness information in its alpha channel.
  40560. */
  40561. _this._useMicroSurfaceFromReflectivityMapAlpha = false;
  40562. /**
  40563. * Specifies if the metallic texture contains the roughness information in its alpha channel.
  40564. */
  40565. _this._useRoughnessFromMetallicTextureAlpha = true;
  40566. /**
  40567. * Specifies if the metallic texture contains the roughness information in its green channel.
  40568. */
  40569. _this._useRoughnessFromMetallicTextureGreen = false;
  40570. /**
  40571. * Specifies if the metallic texture contains the metallness information in its blue channel.
  40572. */
  40573. _this._useMetallnessFromMetallicTextureBlue = false;
  40574. /**
  40575. * Specifies if the metallic texture contains the ambient occlusion information in its red channel.
  40576. */
  40577. _this._useAmbientOcclusionFromMetallicTextureRed = false;
  40578. /**
  40579. * Specifies if the ambient texture contains the ambient occlusion information in its red channel only.
  40580. */
  40581. _this._useAmbientInGrayScale = false;
  40582. /**
  40583. * In case the reflectivity map does not contain the microsurface information in its alpha channel,
  40584. * The material will try to infer what glossiness each pixel should be.
  40585. */
  40586. _this._useAutoMicroSurfaceFromReflectivityMap = false;
  40587. /**
  40588. * BJS is using an harcoded light falloff based on a manually sets up range.
  40589. * In PBR, one way to represents the fallof is to use the inverse squared root algorythm.
  40590. * This parameter can help you switch back to the BJS mode in order to create scenes using both materials.
  40591. */
  40592. _this._usePhysicalLightFalloff = true;
  40593. /**
  40594. * Specifies that the material will keeps the reflection highlights over a transparent surface (only the most limunous ones).
  40595. * A car glass is a good exemple of that. When the street lights reflects on it you can not see what is behind.
  40596. */
  40597. _this._useRadianceOverAlpha = true;
  40598. /**
  40599. * Allows using an object space normal map (instead of tangent space).
  40600. */
  40601. _this._useObjectSpaceNormalMap = false;
  40602. /**
  40603. * Allows using the bump map in parallax mode.
  40604. */
  40605. _this._useParallax = false;
  40606. /**
  40607. * Allows using the bump map in parallax occlusion mode.
  40608. */
  40609. _this._useParallaxOcclusion = false;
  40610. /**
  40611. * Controls the scale bias of the parallax mode.
  40612. */
  40613. _this._parallaxScaleBias = 0.05;
  40614. /**
  40615. * If sets to true, disables all the lights affecting the material.
  40616. */
  40617. _this._disableLighting = false;
  40618. /**
  40619. * Number of Simultaneous lights allowed on the material.
  40620. */
  40621. _this._maxSimultaneousLights = 4;
  40622. /**
  40623. * If sets to true, x component of normal map value will be inverted (x = 1.0 - x).
  40624. */
  40625. _this._invertNormalMapX = false;
  40626. /**
  40627. * If sets to true, y component of normal map value will be inverted (y = 1.0 - y).
  40628. */
  40629. _this._invertNormalMapY = false;
  40630. /**
  40631. * If sets to true and backfaceCulling is false, normals will be flipped on the backside.
  40632. */
  40633. _this._twoSidedLighting = false;
  40634. /**
  40635. * Defines the alpha limits in alpha test mode.
  40636. */
  40637. _this._alphaCutOff = 0.4;
  40638. /**
  40639. * Enforces alpha test in opaque or blend mode in order to improve the performances of some situations.
  40640. */
  40641. _this._forceAlphaTest = false;
  40642. /**
  40643. * A fresnel is applied to the alpha of the model to ensure grazing angles edges are not alpha tested.
  40644. * And/Or occlude the blended part. (alpha is converted to gamma to compute the fresnel)
  40645. */
  40646. _this._useAlphaFresnel = false;
  40647. /**
  40648. * A fresnel is applied to the alpha of the model to ensure grazing angles edges are not alpha tested.
  40649. * And/Or occlude the blended part. (alpha stays linear to compute the fresnel)
  40650. */
  40651. _this._useLinearAlphaFresnel = false;
  40652. /**
  40653. * The transparency mode of the material.
  40654. */
  40655. _this._transparencyMode = null;
  40656. /**
  40657. * Specifies the environment BRDF texture used to comput the scale and offset roughness values
  40658. * from cos thetav and roughness:
  40659. * http://blog.selfshadow.com/publications/s2013-shading-course/karis/s2013_pbs_epic_notes_v2.pdf
  40660. */
  40661. _this._environmentBRDFTexture = null;
  40662. /**
  40663. * Force the shader to compute irradiance in the fragment shader in order to take bump in account.
  40664. */
  40665. _this._forceIrradianceInFragment = false;
  40666. /**
  40667. * Force normal to face away from face.
  40668. */
  40669. _this._forceNormalForward = false;
  40670. /**
  40671. * Stores the available render targets.
  40672. */
  40673. _this._renderTargets = new BABYLON.SmartArray(16);
  40674. /**
  40675. * Sets the global ambient color for the material used in lighting calculations.
  40676. */
  40677. _this._globalAmbientColor = new BABYLON.Color3(0, 0, 0);
  40678. // Setup the default processing configuration to the scene.
  40679. _this._attachImageProcessingConfiguration(null);
  40680. _this.getRenderTargetTextures = function () {
  40681. _this._renderTargets.reset();
  40682. if (BABYLON.StandardMaterial.ReflectionTextureEnabled && _this._reflectionTexture && _this._reflectionTexture.isRenderTarget) {
  40683. _this._renderTargets.push(_this._reflectionTexture);
  40684. }
  40685. if (BABYLON.StandardMaterial.RefractionTextureEnabled && _this._refractionTexture && _this._refractionTexture.isRenderTarget) {
  40686. _this._renderTargets.push(_this._refractionTexture);
  40687. }
  40688. return _this._renderTargets;
  40689. };
  40690. _this._environmentBRDFTexture = BABYLON.TextureTools.GetEnvironmentBRDFTexture(scene);
  40691. return _this;
  40692. }
  40693. /**
  40694. * Attaches a new image processing configuration to the PBR Material.
  40695. * @param configuration
  40696. */
  40697. PBRBaseMaterial.prototype._attachImageProcessingConfiguration = function (configuration) {
  40698. var _this = this;
  40699. if (configuration === this._imageProcessingConfiguration) {
  40700. return;
  40701. }
  40702. // Detaches observer.
  40703. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  40704. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  40705. }
  40706. // Pick the scene configuration if needed.
  40707. if (!configuration) {
  40708. this._imageProcessingConfiguration = this.getScene().imageProcessingConfiguration;
  40709. }
  40710. else {
  40711. this._imageProcessingConfiguration = configuration;
  40712. }
  40713. // Attaches observer.
  40714. this._imageProcessingObserver = this._imageProcessingConfiguration.onUpdateParameters.add(function (conf) {
  40715. _this._markAllSubMeshesAsImageProcessingDirty();
  40716. });
  40717. };
  40718. /**
  40719. * Gets the name of the material class.
  40720. */
  40721. PBRBaseMaterial.prototype.getClassName = function () {
  40722. return "PBRBaseMaterial";
  40723. };
  40724. Object.defineProperty(PBRBaseMaterial.prototype, "useLogarithmicDepth", {
  40725. /**
  40726. * Enabled the use of logarithmic depth buffers, which is good for wide depth buffers.
  40727. */
  40728. get: function () {
  40729. return this._useLogarithmicDepth;
  40730. },
  40731. /**
  40732. * Enabled the use of logarithmic depth buffers, which is good for wide depth buffers.
  40733. */
  40734. set: function (value) {
  40735. this._useLogarithmicDepth = value && this.getScene().getEngine().getCaps().fragmentDepthSupported;
  40736. },
  40737. enumerable: true,
  40738. configurable: true
  40739. });
  40740. Object.defineProperty(PBRBaseMaterial.prototype, "transparencyMode", {
  40741. /**
  40742. * Gets the current transparency mode.
  40743. */
  40744. get: function () {
  40745. return this._transparencyMode;
  40746. },
  40747. /**
  40748. * Sets the transparency mode of the material.
  40749. */
  40750. set: function (value) {
  40751. if (this._transparencyMode === value) {
  40752. return;
  40753. }
  40754. this._transparencyMode = value;
  40755. this._forceAlphaTest = (value === BABYLON.PBRMaterial.PBRMATERIAL_ALPHATESTANDBLEND);
  40756. this._markAllSubMeshesAsTexturesAndMiscDirty();
  40757. },
  40758. enumerable: true,
  40759. configurable: true
  40760. });
  40761. Object.defineProperty(PBRBaseMaterial.prototype, "_disableAlphaBlending", {
  40762. /**
  40763. * Returns true if alpha blending should be disabled.
  40764. */
  40765. get: function () {
  40766. return (this._linkRefractionWithTransparency ||
  40767. this._transparencyMode === BABYLON.PBRMaterial.PBRMATERIAL_OPAQUE ||
  40768. this._transparencyMode === BABYLON.PBRMaterial.PBRMATERIAL_ALPHATEST);
  40769. },
  40770. enumerable: true,
  40771. configurable: true
  40772. });
  40773. /**
  40774. * Specifies whether or not this material should be rendered in alpha blend mode.
  40775. */
  40776. PBRBaseMaterial.prototype.needAlphaBlending = function () {
  40777. if (this._disableAlphaBlending) {
  40778. return false;
  40779. }
  40780. return (this.alpha < 1.0) || (this._opacityTexture != null) || this._shouldUseAlphaFromAlbedoTexture();
  40781. };
  40782. /**
  40783. * Specifies if the mesh will require alpha blending.
  40784. * @param mesh - BJS mesh.
  40785. */
  40786. PBRBaseMaterial.prototype.needAlphaBlendingForMesh = function (mesh) {
  40787. if (this._disableAlphaBlending) {
  40788. return false;
  40789. }
  40790. return _super.prototype.needAlphaBlendingForMesh.call(this, mesh);
  40791. };
  40792. /**
  40793. * Specifies whether or not this material should be rendered in alpha test mode.
  40794. */
  40795. PBRBaseMaterial.prototype.needAlphaTesting = function () {
  40796. if (this._forceAlphaTest) {
  40797. return true;
  40798. }
  40799. if (this._linkRefractionWithTransparency) {
  40800. return false;
  40801. }
  40802. return this._albedoTexture != null && this._albedoTexture.hasAlpha && (this._transparencyMode == null || this._transparencyMode === BABYLON.PBRMaterial.PBRMATERIAL_ALPHATEST);
  40803. };
  40804. /**
  40805. * Specifies whether or not the alpha value of the albedo texture should be used for alpha blending.
  40806. */
  40807. PBRBaseMaterial.prototype._shouldUseAlphaFromAlbedoTexture = function () {
  40808. return this._albedoTexture != null && this._albedoTexture.hasAlpha && this._useAlphaFromAlbedoTexture && this._transparencyMode !== BABYLON.PBRMaterial.PBRMATERIAL_OPAQUE;
  40809. };
  40810. /**
  40811. * Gets the texture used for the alpha test.
  40812. */
  40813. PBRBaseMaterial.prototype.getAlphaTestTexture = function () {
  40814. return this._albedoTexture;
  40815. };
  40816. /**
  40817. * Specifies that the submesh is ready to be used.
  40818. * @param mesh - BJS mesh.
  40819. * @param subMesh - A submesh of the BJS mesh. Used to check if it is ready.
  40820. * @param useInstances - Specifies that instances should be used.
  40821. * @returns - boolean indicating that the submesh is ready or not.
  40822. */
  40823. PBRBaseMaterial.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  40824. if (subMesh.effect && this.isFrozen) {
  40825. if (this._wasPreviouslyReady) {
  40826. return true;
  40827. }
  40828. }
  40829. if (!subMesh._materialDefines) {
  40830. subMesh._materialDefines = new PBRMaterialDefines();
  40831. }
  40832. var defines = subMesh._materialDefines;
  40833. if (!this.checkReadyOnEveryCall && subMesh.effect) {
  40834. if (defines._renderId === this.getScene().getRenderId()) {
  40835. return true;
  40836. }
  40837. }
  40838. var scene = this.getScene();
  40839. var engine = scene.getEngine();
  40840. if (defines._areTexturesDirty) {
  40841. if (scene.texturesEnabled) {
  40842. if (this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  40843. if (!this._albedoTexture.isReadyOrNotBlocking()) {
  40844. return false;
  40845. }
  40846. }
  40847. if (this._ambientTexture && BABYLON.StandardMaterial.AmbientTextureEnabled) {
  40848. if (!this._ambientTexture.isReadyOrNotBlocking()) {
  40849. return false;
  40850. }
  40851. }
  40852. if (this._opacityTexture && BABYLON.StandardMaterial.OpacityTextureEnabled) {
  40853. if (!this._opacityTexture.isReadyOrNotBlocking()) {
  40854. return false;
  40855. }
  40856. }
  40857. var reflectionTexture = this._getReflectionTexture();
  40858. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  40859. if (!reflectionTexture.isReadyOrNotBlocking()) {
  40860. return false;
  40861. }
  40862. }
  40863. if (this._lightmapTexture && BABYLON.StandardMaterial.LightmapTextureEnabled) {
  40864. if (!this._lightmapTexture.isReadyOrNotBlocking()) {
  40865. return false;
  40866. }
  40867. }
  40868. if (this._emissiveTexture && BABYLON.StandardMaterial.EmissiveTextureEnabled) {
  40869. if (!this._emissiveTexture.isReadyOrNotBlocking()) {
  40870. return false;
  40871. }
  40872. }
  40873. if (BABYLON.StandardMaterial.SpecularTextureEnabled) {
  40874. if (this._metallicTexture) {
  40875. if (!this._metallicTexture.isReadyOrNotBlocking()) {
  40876. return false;
  40877. }
  40878. }
  40879. else if (this._reflectivityTexture) {
  40880. if (!this._reflectivityTexture.isReadyOrNotBlocking()) {
  40881. return false;
  40882. }
  40883. }
  40884. if (this._microSurfaceTexture) {
  40885. if (!this._microSurfaceTexture.isReadyOrNotBlocking()) {
  40886. return false;
  40887. }
  40888. }
  40889. }
  40890. if (engine.getCaps().standardDerivatives && this._bumpTexture && BABYLON.StandardMaterial.BumpTextureEnabled && !this._disableBumpMap) {
  40891. // Bump texture cannot be not blocking.
  40892. if (!this._bumpTexture.isReady()) {
  40893. return false;
  40894. }
  40895. }
  40896. var refractionTexture = this._getRefractionTexture();
  40897. if (refractionTexture && BABYLON.StandardMaterial.RefractionTextureEnabled) {
  40898. if (!refractionTexture.isReadyOrNotBlocking()) {
  40899. return false;
  40900. }
  40901. }
  40902. if (this._environmentBRDFTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  40903. // This is blocking.
  40904. if (!this._environmentBRDFTexture.isReady()) {
  40905. return false;
  40906. }
  40907. }
  40908. }
  40909. }
  40910. if (defines._areImageProcessingDirty) {
  40911. if (!this._imageProcessingConfiguration.isReady()) {
  40912. return false;
  40913. }
  40914. }
  40915. if (!engine.getCaps().standardDerivatives) {
  40916. var bufferMesh = null;
  40917. if (mesh.getClassName() === "InstancedMesh") {
  40918. bufferMesh = mesh.sourceMesh;
  40919. }
  40920. else if (mesh.getClassName() === "Mesh") {
  40921. bufferMesh = mesh;
  40922. }
  40923. if (bufferMesh && bufferMesh.geometry && bufferMesh.geometry.isReady() && !bufferMesh.geometry.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  40924. bufferMesh.createNormals(true);
  40925. BABYLON.Tools.Warn("PBRMaterial: Normals have been created for the mesh: " + bufferMesh.name);
  40926. }
  40927. }
  40928. var effect = this._prepareEffect(mesh, defines, this.onCompiled, this.onError, useInstances);
  40929. if (effect) {
  40930. scene.resetCachedMaterial();
  40931. subMesh.setEffect(effect, defines);
  40932. this.buildUniformLayout();
  40933. }
  40934. if (!subMesh.effect || !subMesh.effect.isReady()) {
  40935. return false;
  40936. }
  40937. defines._renderId = scene.getRenderId();
  40938. this._wasPreviouslyReady = true;
  40939. return true;
  40940. };
  40941. /**
  40942. * Specifies if the material uses metallic roughness workflow.
  40943. * @returns boolean specifiying if the material uses metallic roughness workflow.
  40944. */
  40945. PBRBaseMaterial.prototype.isMetallicWorkflow = function () {
  40946. if (this._metallic != null || this._roughness != null || this._metallicTexture) {
  40947. return true;
  40948. }
  40949. return false;
  40950. };
  40951. PBRBaseMaterial.prototype._prepareEffect = function (mesh, defines, onCompiled, onError, useInstances, useClipPlane) {
  40952. if (onCompiled === void 0) { onCompiled = null; }
  40953. if (onError === void 0) { onError = null; }
  40954. if (useInstances === void 0) { useInstances = null; }
  40955. if (useClipPlane === void 0) { useClipPlane = null; }
  40956. this._prepareDefines(mesh, defines, useInstances, useClipPlane);
  40957. if (!defines.isDirty) {
  40958. return null;
  40959. }
  40960. defines.markAsProcessed();
  40961. var scene = this.getScene();
  40962. var engine = scene.getEngine();
  40963. // Fallbacks
  40964. var fallbacks = new BABYLON.EffectFallbacks();
  40965. var fallbackRank = 0;
  40966. if (defines.USESPHERICALINVERTEX) {
  40967. fallbacks.addFallback(fallbackRank++, "USESPHERICALINVERTEX");
  40968. }
  40969. if (defines.FOG) {
  40970. fallbacks.addFallback(fallbackRank, "FOG");
  40971. }
  40972. if (defines.POINTSIZE) {
  40973. fallbacks.addFallback(fallbackRank, "POINTSIZE");
  40974. }
  40975. if (defines.LOGARITHMICDEPTH) {
  40976. fallbacks.addFallback(fallbackRank, "LOGARITHMICDEPTH");
  40977. }
  40978. if (defines.PARALLAX) {
  40979. fallbacks.addFallback(fallbackRank, "PARALLAX");
  40980. }
  40981. if (defines.PARALLAXOCCLUSION) {
  40982. fallbacks.addFallback(fallbackRank++, "PARALLAXOCCLUSION");
  40983. }
  40984. if (defines.ENVIRONMENTBRDF) {
  40985. fallbacks.addFallback(fallbackRank++, "ENVIRONMENTBRDF");
  40986. }
  40987. if (defines.TANGENT) {
  40988. fallbacks.addFallback(fallbackRank++, "TANGENT");
  40989. }
  40990. if (defines.BUMP) {
  40991. fallbacks.addFallback(fallbackRank++, "BUMP");
  40992. }
  40993. fallbackRank = BABYLON.MaterialHelper.HandleFallbacksForShadows(defines, fallbacks, this._maxSimultaneousLights, fallbackRank++);
  40994. if (defines.SPECULARTERM) {
  40995. fallbacks.addFallback(fallbackRank++, "SPECULARTERM");
  40996. }
  40997. if (defines.USESPHERICALFROMREFLECTIONMAP) {
  40998. fallbacks.addFallback(fallbackRank++, "USESPHERICALFROMREFLECTIONMAP");
  40999. }
  41000. if (defines.LIGHTMAP) {
  41001. fallbacks.addFallback(fallbackRank++, "LIGHTMAP");
  41002. }
  41003. if (defines.NORMAL) {
  41004. fallbacks.addFallback(fallbackRank++, "NORMAL");
  41005. }
  41006. if (defines.AMBIENT) {
  41007. fallbacks.addFallback(fallbackRank++, "AMBIENT");
  41008. }
  41009. if (defines.EMISSIVE) {
  41010. fallbacks.addFallback(fallbackRank++, "EMISSIVE");
  41011. }
  41012. if (defines.VERTEXCOLOR) {
  41013. fallbacks.addFallback(fallbackRank++, "VERTEXCOLOR");
  41014. }
  41015. if (defines.NUM_BONE_INFLUENCERS > 0) {
  41016. fallbacks.addCPUSkinningFallback(fallbackRank++, mesh);
  41017. }
  41018. if (defines.MORPHTARGETS) {
  41019. fallbacks.addFallback(fallbackRank++, "MORPHTARGETS");
  41020. }
  41021. //Attributes
  41022. var attribs = [BABYLON.VertexBuffer.PositionKind];
  41023. if (defines.NORMAL) {
  41024. attribs.push(BABYLON.VertexBuffer.NormalKind);
  41025. }
  41026. if (defines.TANGENT) {
  41027. attribs.push(BABYLON.VertexBuffer.TangentKind);
  41028. }
  41029. if (defines.UV1) {
  41030. attribs.push(BABYLON.VertexBuffer.UVKind);
  41031. }
  41032. if (defines.UV2) {
  41033. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  41034. }
  41035. if (defines.VERTEXCOLOR) {
  41036. attribs.push(BABYLON.VertexBuffer.ColorKind);
  41037. }
  41038. BABYLON.MaterialHelper.PrepareAttributesForBones(attribs, mesh, defines, fallbacks);
  41039. BABYLON.MaterialHelper.PrepareAttributesForInstances(attribs, defines);
  41040. BABYLON.MaterialHelper.PrepareAttributesForMorphTargets(attribs, mesh, defines);
  41041. var uniforms = ["world", "view", "viewProjection", "vEyePosition", "vLightsType", "vAmbientColor", "vAlbedoColor", "vReflectivityColor", "vEmissiveColor", "vReflectionColor",
  41042. "vFogInfos", "vFogColor", "pointSize",
  41043. "vAlbedoInfos", "vAmbientInfos", "vOpacityInfos", "vReflectionInfos", "vReflectionPosition", "vReflectionSize", "vEmissiveInfos", "vReflectivityInfos",
  41044. "vMicroSurfaceSamplerInfos", "vBumpInfos", "vLightmapInfos", "vRefractionInfos",
  41045. "mBones",
  41046. "vClipPlane", "albedoMatrix", "ambientMatrix", "opacityMatrix", "reflectionMatrix", "emissiveMatrix", "reflectivityMatrix", "normalMatrix", "microSurfaceSamplerMatrix", "bumpMatrix", "lightmapMatrix", "refractionMatrix",
  41047. "vLightingIntensity",
  41048. "logarithmicDepthConstant",
  41049. "vSphericalX", "vSphericalY", "vSphericalZ",
  41050. "vSphericalXX", "vSphericalYY", "vSphericalZZ",
  41051. "vSphericalXY", "vSphericalYZ", "vSphericalZX",
  41052. "vReflectionMicrosurfaceInfos", "vRefractionMicrosurfaceInfos",
  41053. "vTangentSpaceParams"
  41054. ];
  41055. var samplers = ["albedoSampler", "reflectivitySampler", "ambientSampler", "emissiveSampler",
  41056. "bumpSampler", "lightmapSampler", "opacitySampler",
  41057. "refractionSampler", "refractionSamplerLow", "refractionSamplerHigh",
  41058. "reflectionSampler", "reflectionSamplerLow", "reflectionSamplerHigh",
  41059. "microSurfaceSampler", "environmentBrdfSampler"];
  41060. var uniformBuffers = ["Material", "Scene"];
  41061. BABYLON.ImageProcessingConfiguration.PrepareUniforms(uniforms, defines);
  41062. BABYLON.ImageProcessingConfiguration.PrepareSamplers(samplers, defines);
  41063. BABYLON.MaterialHelper.PrepareUniformsAndSamplersList({
  41064. uniformsNames: uniforms,
  41065. uniformBuffersNames: uniformBuffers,
  41066. samplers: samplers,
  41067. defines: defines,
  41068. maxSimultaneousLights: this._maxSimultaneousLights
  41069. });
  41070. var join = defines.toString();
  41071. return engine.createEffect("pbr", {
  41072. attributes: attribs,
  41073. uniformsNames: uniforms,
  41074. uniformBuffersNames: uniformBuffers,
  41075. samplers: samplers,
  41076. defines: join,
  41077. fallbacks: fallbacks,
  41078. onCompiled: onCompiled,
  41079. onError: onError,
  41080. indexParameters: { maxSimultaneousLights: this._maxSimultaneousLights, maxSimultaneousMorphTargets: defines.NUM_MORPH_INFLUENCERS }
  41081. }, engine);
  41082. };
  41083. PBRBaseMaterial.prototype._prepareDefines = function (mesh, defines, useInstances, useClipPlane) {
  41084. if (useInstances === void 0) { useInstances = null; }
  41085. if (useClipPlane === void 0) { useClipPlane = null; }
  41086. var scene = this.getScene();
  41087. var engine = scene.getEngine();
  41088. // Lights
  41089. BABYLON.MaterialHelper.PrepareDefinesForLights(scene, mesh, defines, true, this._maxSimultaneousLights, this._disableLighting);
  41090. defines._needNormals = true;
  41091. // Textures
  41092. defines.METALLICWORKFLOW = this.isMetallicWorkflow();
  41093. if (defines._areTexturesDirty) {
  41094. defines._needUVs = false;
  41095. if (scene.texturesEnabled) {
  41096. if (scene.getEngine().getCaps().textureLOD) {
  41097. defines.LODBASEDMICROSFURACE = true;
  41098. }
  41099. if (this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  41100. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._albedoTexture, defines, "ALBEDO");
  41101. }
  41102. else {
  41103. defines.ALBEDO = false;
  41104. }
  41105. if (this._ambientTexture && BABYLON.StandardMaterial.AmbientTextureEnabled) {
  41106. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._ambientTexture, defines, "AMBIENT");
  41107. defines.AMBIENTINGRAYSCALE = this._useAmbientInGrayScale;
  41108. }
  41109. else {
  41110. defines.AMBIENT = false;
  41111. }
  41112. if (this._opacityTexture && BABYLON.StandardMaterial.OpacityTextureEnabled) {
  41113. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._opacityTexture, defines, "OPACITY");
  41114. defines.OPACITYRGB = this._opacityTexture.getAlphaFromRGB;
  41115. }
  41116. else {
  41117. defines.OPACITY = false;
  41118. }
  41119. var reflectionTexture = this._getReflectionTexture();
  41120. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  41121. defines.REFLECTION = true;
  41122. defines.GAMMAREFLECTION = reflectionTexture.gammaSpace;
  41123. defines.REFLECTIONMAP_OPPOSITEZ = this.getScene().useRightHandedSystem ? !reflectionTexture.invertZ : reflectionTexture.invertZ;
  41124. defines.LODINREFLECTIONALPHA = reflectionTexture.lodLevelInAlpha;
  41125. if (reflectionTexture.coordinatesMode === BABYLON.Texture.INVCUBIC_MODE) {
  41126. defines.INVERTCUBICMAP = true;
  41127. }
  41128. defines.REFLECTIONMAP_3D = reflectionTexture.isCube;
  41129. switch (reflectionTexture.coordinatesMode) {
  41130. case BABYLON.Texture.CUBIC_MODE:
  41131. case BABYLON.Texture.INVCUBIC_MODE:
  41132. defines.REFLECTIONMAP_CUBIC = true;
  41133. defines.USE_LOCAL_REFLECTIONMAP_CUBIC = reflectionTexture.boundingBoxSize ? true : false;
  41134. break;
  41135. case BABYLON.Texture.EXPLICIT_MODE:
  41136. defines.REFLECTIONMAP_EXPLICIT = true;
  41137. break;
  41138. case BABYLON.Texture.PLANAR_MODE:
  41139. defines.REFLECTIONMAP_PLANAR = true;
  41140. break;
  41141. case BABYLON.Texture.PROJECTION_MODE:
  41142. defines.REFLECTIONMAP_PROJECTION = true;
  41143. break;
  41144. case BABYLON.Texture.SKYBOX_MODE:
  41145. defines.REFLECTIONMAP_SKYBOX = true;
  41146. break;
  41147. case BABYLON.Texture.SPHERICAL_MODE:
  41148. defines.REFLECTIONMAP_SPHERICAL = true;
  41149. break;
  41150. case BABYLON.Texture.EQUIRECTANGULAR_MODE:
  41151. defines.REFLECTIONMAP_EQUIRECTANGULAR = true;
  41152. break;
  41153. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MODE:
  41154. defines.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = true;
  41155. break;
  41156. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE:
  41157. defines.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = true;
  41158. break;
  41159. }
  41160. if (reflectionTexture.coordinatesMode !== BABYLON.Texture.SKYBOX_MODE) {
  41161. if (reflectionTexture.sphericalPolynomial) {
  41162. defines.USESPHERICALFROMREFLECTIONMAP = true;
  41163. if (this._forceIrradianceInFragment || scene.getEngine().getCaps().maxVaryingVectors <= 8) {
  41164. defines.USESPHERICALINVERTEX = false;
  41165. }
  41166. else {
  41167. defines.USESPHERICALINVERTEX = true;
  41168. }
  41169. }
  41170. }
  41171. }
  41172. else {
  41173. defines.REFLECTION = false;
  41174. defines.REFLECTIONMAP_3D = false;
  41175. defines.REFLECTIONMAP_SPHERICAL = false;
  41176. defines.REFLECTIONMAP_PLANAR = false;
  41177. defines.REFLECTIONMAP_CUBIC = false;
  41178. defines.USE_LOCAL_REFLECTIONMAP_CUBIC = false;
  41179. defines.REFLECTIONMAP_PROJECTION = false;
  41180. defines.REFLECTIONMAP_SKYBOX = false;
  41181. defines.REFLECTIONMAP_EXPLICIT = false;
  41182. defines.REFLECTIONMAP_EQUIRECTANGULAR = false;
  41183. defines.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  41184. defines.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  41185. defines.INVERTCUBICMAP = false;
  41186. defines.USESPHERICALFROMREFLECTIONMAP = false;
  41187. defines.USESPHERICALINVERTEX = false;
  41188. defines.REFLECTIONMAP_OPPOSITEZ = false;
  41189. defines.LODINREFLECTIONALPHA = false;
  41190. defines.GAMMAREFLECTION = false;
  41191. }
  41192. if (this._lightmapTexture && BABYLON.StandardMaterial.LightmapTextureEnabled) {
  41193. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._lightmapTexture, defines, "LIGHTMAP");
  41194. defines.USELIGHTMAPASSHADOWMAP = this._useLightmapAsShadowmap;
  41195. }
  41196. else {
  41197. defines.LIGHTMAP = false;
  41198. }
  41199. if (this._emissiveTexture && BABYLON.StandardMaterial.EmissiveTextureEnabled) {
  41200. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._emissiveTexture, defines, "EMISSIVE");
  41201. }
  41202. else {
  41203. defines.EMISSIVE = false;
  41204. }
  41205. if (BABYLON.StandardMaterial.SpecularTextureEnabled) {
  41206. if (this._metallicTexture) {
  41207. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._metallicTexture, defines, "REFLECTIVITY");
  41208. defines.ROUGHNESSSTOREINMETALMAPALPHA = this._useRoughnessFromMetallicTextureAlpha;
  41209. defines.ROUGHNESSSTOREINMETALMAPGREEN = !this._useRoughnessFromMetallicTextureAlpha && this._useRoughnessFromMetallicTextureGreen;
  41210. defines.METALLNESSSTOREINMETALMAPBLUE = this._useMetallnessFromMetallicTextureBlue;
  41211. defines.AOSTOREINMETALMAPRED = this._useAmbientOcclusionFromMetallicTextureRed;
  41212. }
  41213. else if (this._reflectivityTexture) {
  41214. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._reflectivityTexture, defines, "REFLECTIVITY");
  41215. defines.MICROSURFACEFROMREFLECTIVITYMAP = this._useMicroSurfaceFromReflectivityMapAlpha;
  41216. defines.MICROSURFACEAUTOMATIC = this._useAutoMicroSurfaceFromReflectivityMap;
  41217. }
  41218. else {
  41219. defines.REFLECTIVITY = false;
  41220. }
  41221. if (this._microSurfaceTexture) {
  41222. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._microSurfaceTexture, defines, "MICROSURFACEMAP");
  41223. }
  41224. else {
  41225. defines.MICROSURFACEMAP = false;
  41226. }
  41227. }
  41228. else {
  41229. defines.REFLECTIVITY = false;
  41230. defines.MICROSURFACEMAP = false;
  41231. }
  41232. if (scene.getEngine().getCaps().standardDerivatives && this._bumpTexture && BABYLON.StandardMaterial.BumpTextureEnabled && !this._disableBumpMap) {
  41233. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._bumpTexture, defines, "BUMP");
  41234. if (this._useParallax && this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  41235. defines.PARALLAX = true;
  41236. defines.PARALLAXOCCLUSION = !!this._useParallaxOcclusion;
  41237. }
  41238. else {
  41239. defines.PARALLAX = false;
  41240. }
  41241. defines.OBJECTSPACE_NORMALMAP = this._useObjectSpaceNormalMap;
  41242. }
  41243. else {
  41244. defines.BUMP = false;
  41245. }
  41246. var refractionTexture = this._getRefractionTexture();
  41247. if (refractionTexture && BABYLON.StandardMaterial.RefractionTextureEnabled) {
  41248. defines.REFRACTION = true;
  41249. defines.REFRACTIONMAP_3D = refractionTexture.isCube;
  41250. defines.GAMMAREFRACTION = refractionTexture.gammaSpace;
  41251. defines.REFRACTIONMAP_OPPOSITEZ = refractionTexture.invertZ;
  41252. defines.LODINREFRACTIONALPHA = refractionTexture.lodLevelInAlpha;
  41253. if (this._linkRefractionWithTransparency) {
  41254. defines.LINKREFRACTIONTOTRANSPARENCY = true;
  41255. }
  41256. }
  41257. else {
  41258. defines.REFRACTION = false;
  41259. }
  41260. if (this._environmentBRDFTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  41261. defines.ENVIRONMENTBRDF = true;
  41262. }
  41263. else {
  41264. defines.ENVIRONMENTBRDF = false;
  41265. }
  41266. if (this._shouldUseAlphaFromAlbedoTexture()) {
  41267. defines.ALPHAFROMALBEDO = true;
  41268. }
  41269. else {
  41270. defines.ALPHAFROMALBEDO = false;
  41271. }
  41272. }
  41273. defines.SPECULAROVERALPHA = this._useSpecularOverAlpha;
  41274. defines.USEPHYSICALLIGHTFALLOFF = this._usePhysicalLightFalloff;
  41275. defines.RADIANCEOVERALPHA = this._useRadianceOverAlpha;
  41276. if (!this.backFaceCulling && this._twoSidedLighting) {
  41277. defines.TWOSIDEDLIGHTING = true;
  41278. }
  41279. else {
  41280. defines.TWOSIDEDLIGHTING = false;
  41281. }
  41282. defines.ALPHATESTVALUE = this._alphaCutOff;
  41283. defines.PREMULTIPLYALPHA = (this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED || this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED_PORTERDUFF);
  41284. defines.ALPHABLEND = this.needAlphaBlendingForMesh(mesh);
  41285. defines.ALPHAFRESNEL = this._useAlphaFresnel || this._useLinearAlphaFresnel;
  41286. defines.LINEARALPHAFRESNEL = this._useLinearAlphaFresnel;
  41287. }
  41288. if (defines._areImageProcessingDirty) {
  41289. this._imageProcessingConfiguration.prepareDefines(defines);
  41290. }
  41291. defines.FORCENORMALFORWARD = this._forceNormalForward;
  41292. defines.RADIANCEOCCLUSION = this._useRadianceOcclusion;
  41293. defines.HORIZONOCCLUSION = this._useHorizonOcclusion;
  41294. // Misc.
  41295. BABYLON.MaterialHelper.PrepareDefinesForMisc(mesh, scene, this._useLogarithmicDepth, this.pointsCloud, this.fogEnabled, this._shouldTurnAlphaTestOn(mesh) || this._forceAlphaTest, defines);
  41296. // Values that need to be evaluated on every frame
  41297. BABYLON.MaterialHelper.PrepareDefinesForFrameBoundValues(scene, engine, defines, useInstances ? true : false, useClipPlane);
  41298. // Attribs
  41299. BABYLON.MaterialHelper.PrepareDefinesForAttributes(mesh, defines, true, true, true, this._transparencyMode !== BABYLON.PBRMaterial.PBRMATERIAL_OPAQUE);
  41300. };
  41301. /**
  41302. * Force shader compilation
  41303. */
  41304. PBRBaseMaterial.prototype.forceCompilation = function (mesh, onCompiled, options) {
  41305. var _this = this;
  41306. var localOptions = __assign({ clipPlane: false }, options);
  41307. var defines = new PBRMaterialDefines();
  41308. var effect = this._prepareEffect(mesh, defines, undefined, undefined, undefined, localOptions.clipPlane);
  41309. if (effect.isReady()) {
  41310. if (onCompiled) {
  41311. onCompiled(this);
  41312. }
  41313. }
  41314. else {
  41315. effect.onCompileObservable.add(function () {
  41316. if (onCompiled) {
  41317. onCompiled(_this);
  41318. }
  41319. });
  41320. }
  41321. };
  41322. /**
  41323. * Initializes the uniform buffer layout for the shader.
  41324. */
  41325. PBRBaseMaterial.prototype.buildUniformLayout = function () {
  41326. // Order is important !
  41327. this._uniformBuffer.addUniform("vAlbedoInfos", 2);
  41328. this._uniformBuffer.addUniform("vAmbientInfos", 3);
  41329. this._uniformBuffer.addUniform("vOpacityInfos", 2);
  41330. this._uniformBuffer.addUniform("vEmissiveInfos", 2);
  41331. this._uniformBuffer.addUniform("vLightmapInfos", 2);
  41332. this._uniformBuffer.addUniform("vReflectivityInfos", 3);
  41333. this._uniformBuffer.addUniform("vMicroSurfaceSamplerInfos", 2);
  41334. this._uniformBuffer.addUniform("vRefractionInfos", 4);
  41335. this._uniformBuffer.addUniform("vReflectionInfos", 2);
  41336. this._uniformBuffer.addUniform("vReflectionPosition", 3);
  41337. this._uniformBuffer.addUniform("vReflectionSize", 3);
  41338. this._uniformBuffer.addUniform("vBumpInfos", 3);
  41339. this._uniformBuffer.addUniform("albedoMatrix", 16);
  41340. this._uniformBuffer.addUniform("ambientMatrix", 16);
  41341. this._uniformBuffer.addUniform("opacityMatrix", 16);
  41342. this._uniformBuffer.addUniform("emissiveMatrix", 16);
  41343. this._uniformBuffer.addUniform("lightmapMatrix", 16);
  41344. this._uniformBuffer.addUniform("reflectivityMatrix", 16);
  41345. this._uniformBuffer.addUniform("microSurfaceSamplerMatrix", 16);
  41346. this._uniformBuffer.addUniform("bumpMatrix", 16);
  41347. this._uniformBuffer.addUniform("vTangentSpaceParams", 2);
  41348. this._uniformBuffer.addUniform("refractionMatrix", 16);
  41349. this._uniformBuffer.addUniform("reflectionMatrix", 16);
  41350. this._uniformBuffer.addUniform("vReflectionColor", 3);
  41351. this._uniformBuffer.addUniform("vAlbedoColor", 4);
  41352. this._uniformBuffer.addUniform("vLightingIntensity", 4);
  41353. this._uniformBuffer.addUniform("vRefractionMicrosurfaceInfos", 3);
  41354. this._uniformBuffer.addUniform("vReflectionMicrosurfaceInfos", 3);
  41355. this._uniformBuffer.addUniform("vReflectivityColor", 4);
  41356. this._uniformBuffer.addUniform("vEmissiveColor", 3);
  41357. this._uniformBuffer.addUniform("pointSize", 1);
  41358. this._uniformBuffer.create();
  41359. };
  41360. /**
  41361. * Unbinds the textures.
  41362. */
  41363. PBRBaseMaterial.prototype.unbind = function () {
  41364. if (this._reflectionTexture && this._reflectionTexture.isRenderTarget) {
  41365. this._uniformBuffer.setTexture("reflectionSampler", null);
  41366. }
  41367. if (this._refractionTexture && this._refractionTexture.isRenderTarget) {
  41368. this._uniformBuffer.setTexture("refractionSampler", null);
  41369. }
  41370. _super.prototype.unbind.call(this);
  41371. };
  41372. /**
  41373. * Binds the submesh data.
  41374. * @param world - The world matrix.
  41375. * @param mesh - The BJS mesh.
  41376. * @param subMesh - A submesh of the BJS mesh.
  41377. */
  41378. PBRBaseMaterial.prototype.bindForSubMesh = function (world, mesh, subMesh) {
  41379. var scene = this.getScene();
  41380. var defines = subMesh._materialDefines;
  41381. if (!defines) {
  41382. return;
  41383. }
  41384. var effect = subMesh.effect;
  41385. if (!effect) {
  41386. return;
  41387. }
  41388. this._activeEffect = effect;
  41389. // Matrices
  41390. this.bindOnlyWorldMatrix(world);
  41391. // Normal Matrix
  41392. if (defines.OBJECTSPACE_NORMALMAP) {
  41393. world.toNormalMatrix(this._normalMatrix);
  41394. this.bindOnlyNormalMatrix(this._normalMatrix);
  41395. }
  41396. var mustRebind = this._mustRebind(scene, effect, mesh.visibility);
  41397. // Bones
  41398. BABYLON.MaterialHelper.BindBonesParameters(mesh, this._activeEffect);
  41399. var reflectionTexture = null;
  41400. if (mustRebind) {
  41401. this._uniformBuffer.bindToEffect(effect, "Material");
  41402. this.bindViewProjection(effect);
  41403. reflectionTexture = this._getReflectionTexture();
  41404. var refractionTexture = this._getRefractionTexture();
  41405. if (!this._uniformBuffer.useUbo || !this.isFrozen || !this._uniformBuffer.isSync) {
  41406. // Texture uniforms
  41407. if (scene.texturesEnabled) {
  41408. if (this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  41409. this._uniformBuffer.updateFloat2("vAlbedoInfos", this._albedoTexture.coordinatesIndex, this._albedoTexture.level);
  41410. BABYLON.MaterialHelper.BindTextureMatrix(this._albedoTexture, this._uniformBuffer, "albedo");
  41411. }
  41412. if (this._ambientTexture && BABYLON.StandardMaterial.AmbientTextureEnabled) {
  41413. this._uniformBuffer.updateFloat3("vAmbientInfos", this._ambientTexture.coordinatesIndex, this._ambientTexture.level, this._ambientTextureStrength);
  41414. BABYLON.MaterialHelper.BindTextureMatrix(this._ambientTexture, this._uniformBuffer, "ambient");
  41415. }
  41416. if (this._opacityTexture && BABYLON.StandardMaterial.OpacityTextureEnabled) {
  41417. this._uniformBuffer.updateFloat2("vOpacityInfos", this._opacityTexture.coordinatesIndex, this._opacityTexture.level);
  41418. BABYLON.MaterialHelper.BindTextureMatrix(this._opacityTexture, this._uniformBuffer, "opacity");
  41419. }
  41420. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  41421. this._uniformBuffer.updateMatrix("reflectionMatrix", reflectionTexture.getReflectionTextureMatrix());
  41422. this._uniformBuffer.updateFloat2("vReflectionInfos", reflectionTexture.level, 0);
  41423. if (reflectionTexture.boundingBoxSize) {
  41424. var cubeTexture = reflectionTexture;
  41425. this._uniformBuffer.updateVector3("vReflectionPosition", cubeTexture.boundingBoxPosition);
  41426. this._uniformBuffer.updateVector3("vReflectionSize", cubeTexture.boundingBoxSize);
  41427. }
  41428. var polynomials = reflectionTexture.sphericalPolynomial;
  41429. if (defines.USESPHERICALFROMREFLECTIONMAP && polynomials) {
  41430. this._activeEffect.setFloat3("vSphericalX", polynomials.x.x, polynomials.x.y, polynomials.x.z);
  41431. this._activeEffect.setFloat3("vSphericalY", polynomials.y.x, polynomials.y.y, polynomials.y.z);
  41432. this._activeEffect.setFloat3("vSphericalZ", polynomials.z.x, polynomials.z.y, polynomials.z.z);
  41433. this._activeEffect.setFloat3("vSphericalXX_ZZ", polynomials.xx.x - polynomials.zz.x, polynomials.xx.y - polynomials.zz.y, polynomials.xx.z - polynomials.zz.z);
  41434. this._activeEffect.setFloat3("vSphericalYY_ZZ", polynomials.yy.x - polynomials.zz.x, polynomials.yy.y - polynomials.zz.y, polynomials.yy.z - polynomials.zz.z);
  41435. this._activeEffect.setFloat3("vSphericalZZ", polynomials.zz.x, polynomials.zz.y, polynomials.zz.z);
  41436. this._activeEffect.setFloat3("vSphericalXY", polynomials.xy.x, polynomials.xy.y, polynomials.xy.z);
  41437. this._activeEffect.setFloat3("vSphericalYZ", polynomials.yz.x, polynomials.yz.y, polynomials.yz.z);
  41438. this._activeEffect.setFloat3("vSphericalZX", polynomials.zx.x, polynomials.zx.y, polynomials.zx.z);
  41439. }
  41440. this._uniformBuffer.updateFloat3("vReflectionMicrosurfaceInfos", reflectionTexture.getSize().width, reflectionTexture.lodGenerationScale, reflectionTexture.lodGenerationOffset);
  41441. }
  41442. if (this._emissiveTexture && BABYLON.StandardMaterial.EmissiveTextureEnabled) {
  41443. this._uniformBuffer.updateFloat2("vEmissiveInfos", this._emissiveTexture.coordinatesIndex, this._emissiveTexture.level);
  41444. BABYLON.MaterialHelper.BindTextureMatrix(this._emissiveTexture, this._uniformBuffer, "emissive");
  41445. }
  41446. if (this._lightmapTexture && BABYLON.StandardMaterial.LightmapTextureEnabled) {
  41447. this._uniformBuffer.updateFloat2("vLightmapInfos", this._lightmapTexture.coordinatesIndex, this._lightmapTexture.level);
  41448. BABYLON.MaterialHelper.BindTextureMatrix(this._lightmapTexture, this._uniformBuffer, "lightmap");
  41449. }
  41450. if (BABYLON.StandardMaterial.SpecularTextureEnabled) {
  41451. if (this._metallicTexture) {
  41452. this._uniformBuffer.updateFloat3("vReflectivityInfos", this._metallicTexture.coordinatesIndex, this._metallicTexture.level, this._ambientTextureStrength);
  41453. BABYLON.MaterialHelper.BindTextureMatrix(this._metallicTexture, this._uniformBuffer, "reflectivity");
  41454. }
  41455. else if (this._reflectivityTexture) {
  41456. this._uniformBuffer.updateFloat3("vReflectivityInfos", this._reflectivityTexture.coordinatesIndex, this._reflectivityTexture.level, 1.0);
  41457. BABYLON.MaterialHelper.BindTextureMatrix(this._reflectivityTexture, this._uniformBuffer, "reflectivity");
  41458. }
  41459. if (this._microSurfaceTexture) {
  41460. this._uniformBuffer.updateFloat2("vMicroSurfaceSamplerInfos", this._microSurfaceTexture.coordinatesIndex, this._microSurfaceTexture.level);
  41461. BABYLON.MaterialHelper.BindTextureMatrix(this._microSurfaceTexture, this._uniformBuffer, "microSurfaceSampler");
  41462. }
  41463. }
  41464. if (this._bumpTexture && scene.getEngine().getCaps().standardDerivatives && BABYLON.StandardMaterial.BumpTextureEnabled && !this._disableBumpMap) {
  41465. this._uniformBuffer.updateFloat3("vBumpInfos", this._bumpTexture.coordinatesIndex, this._bumpTexture.level, this._parallaxScaleBias);
  41466. BABYLON.MaterialHelper.BindTextureMatrix(this._bumpTexture, this._uniformBuffer, "bump");
  41467. if (scene._mirroredCameraPosition) {
  41468. this._uniformBuffer.updateFloat2("vTangentSpaceParams", this._invertNormalMapX ? 1.0 : -1.0, this._invertNormalMapY ? 1.0 : -1.0);
  41469. }
  41470. else {
  41471. this._uniformBuffer.updateFloat2("vTangentSpaceParams", this._invertNormalMapX ? -1.0 : 1.0, this._invertNormalMapY ? -1.0 : 1.0);
  41472. }
  41473. }
  41474. if (refractionTexture && BABYLON.StandardMaterial.RefractionTextureEnabled) {
  41475. this._uniformBuffer.updateMatrix("refractionMatrix", refractionTexture.getReflectionTextureMatrix());
  41476. var depth = 1.0;
  41477. if (!refractionTexture.isCube) {
  41478. if (refractionTexture.depth) {
  41479. depth = refractionTexture.depth;
  41480. }
  41481. }
  41482. this._uniformBuffer.updateFloat4("vRefractionInfos", refractionTexture.level, this._indexOfRefraction, depth, this._invertRefractionY ? -1 : 1);
  41483. this._uniformBuffer.updateFloat3("vRefractionMicrosurfaceInfos", refractionTexture.getSize().width, refractionTexture.lodGenerationScale, refractionTexture.lodGenerationOffset);
  41484. }
  41485. }
  41486. // Point size
  41487. if (this.pointsCloud) {
  41488. this._uniformBuffer.updateFloat("pointSize", this.pointSize);
  41489. }
  41490. // Colors
  41491. if (defines.METALLICWORKFLOW) {
  41492. BABYLON.PBRMaterial._scaledReflectivity.r = (this._metallic === undefined || this._metallic === null) ? 1 : this._metallic;
  41493. BABYLON.PBRMaterial._scaledReflectivity.g = (this._roughness === undefined || this._roughness === null) ? 1 : this._roughness;
  41494. this._uniformBuffer.updateColor4("vReflectivityColor", BABYLON.PBRMaterial._scaledReflectivity, 0);
  41495. }
  41496. else {
  41497. this._uniformBuffer.updateColor4("vReflectivityColor", this._reflectivityColor, this._microSurface);
  41498. }
  41499. this._uniformBuffer.updateColor3("vEmissiveColor", this._emissiveColor);
  41500. this._uniformBuffer.updateColor3("vReflectionColor", this._reflectionColor);
  41501. this._uniformBuffer.updateColor4("vAlbedoColor", this._albedoColor, this.alpha * mesh.visibility);
  41502. // Misc
  41503. this._lightingInfos.x = this._directIntensity;
  41504. this._lightingInfos.y = this._emissiveIntensity;
  41505. this._lightingInfos.z = this._environmentIntensity;
  41506. this._lightingInfos.w = this._specularIntensity;
  41507. this._uniformBuffer.updateVector4("vLightingIntensity", this._lightingInfos);
  41508. }
  41509. // Textures
  41510. if (scene.texturesEnabled) {
  41511. if (this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  41512. this._uniformBuffer.setTexture("albedoSampler", this._albedoTexture);
  41513. }
  41514. if (this._ambientTexture && BABYLON.StandardMaterial.AmbientTextureEnabled) {
  41515. this._uniformBuffer.setTexture("ambientSampler", this._ambientTexture);
  41516. }
  41517. if (this._opacityTexture && BABYLON.StandardMaterial.OpacityTextureEnabled) {
  41518. this._uniformBuffer.setTexture("opacitySampler", this._opacityTexture);
  41519. }
  41520. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  41521. if (defines.LODBASEDMICROSFURACE) {
  41522. this._uniformBuffer.setTexture("reflectionSampler", reflectionTexture);
  41523. }
  41524. else {
  41525. this._uniformBuffer.setTexture("reflectionSampler", reflectionTexture._lodTextureMid || reflectionTexture);
  41526. this._uniformBuffer.setTexture("reflectionSamplerLow", reflectionTexture._lodTextureLow || reflectionTexture);
  41527. this._uniformBuffer.setTexture("reflectionSamplerHigh", reflectionTexture._lodTextureHigh || reflectionTexture);
  41528. }
  41529. }
  41530. if (defines.ENVIRONMENTBRDF) {
  41531. this._uniformBuffer.setTexture("environmentBrdfSampler", this._environmentBRDFTexture);
  41532. }
  41533. if (refractionTexture && BABYLON.StandardMaterial.RefractionTextureEnabled) {
  41534. if (defines.LODBASEDMICROSFURACE) {
  41535. this._uniformBuffer.setTexture("refractionSampler", refractionTexture);
  41536. }
  41537. else {
  41538. this._uniformBuffer.setTexture("refractionSampler", refractionTexture._lodTextureMid || refractionTexture);
  41539. this._uniformBuffer.setTexture("refractionSamplerLow", refractionTexture._lodTextureLow || refractionTexture);
  41540. this._uniformBuffer.setTexture("refractionSamplerHigh", refractionTexture._lodTextureHigh || refractionTexture);
  41541. }
  41542. }
  41543. if (this._emissiveTexture && BABYLON.StandardMaterial.EmissiveTextureEnabled) {
  41544. this._uniformBuffer.setTexture("emissiveSampler", this._emissiveTexture);
  41545. }
  41546. if (this._lightmapTexture && BABYLON.StandardMaterial.LightmapTextureEnabled) {
  41547. this._uniformBuffer.setTexture("lightmapSampler", this._lightmapTexture);
  41548. }
  41549. if (BABYLON.StandardMaterial.SpecularTextureEnabled) {
  41550. if (this._metallicTexture) {
  41551. this._uniformBuffer.setTexture("reflectivitySampler", this._metallicTexture);
  41552. }
  41553. else if (this._reflectivityTexture) {
  41554. this._uniformBuffer.setTexture("reflectivitySampler", this._reflectivityTexture);
  41555. }
  41556. if (this._microSurfaceTexture) {
  41557. this._uniformBuffer.setTexture("microSurfaceSampler", this._microSurfaceTexture);
  41558. }
  41559. }
  41560. if (this._bumpTexture && scene.getEngine().getCaps().standardDerivatives && BABYLON.StandardMaterial.BumpTextureEnabled && !this._disableBumpMap) {
  41561. this._uniformBuffer.setTexture("bumpSampler", this._bumpTexture);
  41562. }
  41563. }
  41564. // Clip plane
  41565. BABYLON.MaterialHelper.BindClipPlane(this._activeEffect, scene);
  41566. // Colors
  41567. scene.ambientColor.multiplyToRef(this._ambientColor, this._globalAmbientColor);
  41568. var eyePosition = scene._forcedViewPosition ? scene._forcedViewPosition : (scene._mirroredCameraPosition ? scene._mirroredCameraPosition : scene.activeCamera.globalPosition);
  41569. var invertNormal = (scene.useRightHandedSystem === (scene._mirroredCameraPosition != null));
  41570. effect.setFloat4("vEyePosition", eyePosition.x, eyePosition.y, eyePosition.z, invertNormal ? -1 : 1);
  41571. effect.setColor3("vAmbientColor", this._globalAmbientColor);
  41572. }
  41573. if (mustRebind || !this.isFrozen) {
  41574. // Lights
  41575. if (scene.lightsEnabled && !this._disableLighting) {
  41576. BABYLON.MaterialHelper.BindLights(scene, mesh, this._activeEffect, defines, this._maxSimultaneousLights, this._usePhysicalLightFalloff);
  41577. }
  41578. // View
  41579. if (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE || reflectionTexture) {
  41580. this.bindView(effect);
  41581. }
  41582. // Fog
  41583. BABYLON.MaterialHelper.BindFogParameters(scene, mesh, this._activeEffect);
  41584. // Morph targets
  41585. if (defines.NUM_MORPH_INFLUENCERS) {
  41586. BABYLON.MaterialHelper.BindMorphTargetParameters(mesh, this._activeEffect);
  41587. }
  41588. // image processing
  41589. this._imageProcessingConfiguration.bind(this._activeEffect);
  41590. // Log. depth
  41591. BABYLON.MaterialHelper.BindLogDepth(defines, this._activeEffect, scene);
  41592. }
  41593. this._uniformBuffer.update();
  41594. this._afterBind(mesh);
  41595. };
  41596. /**
  41597. * Returns the animatable textures.
  41598. * @returns - Array of animatable textures.
  41599. */
  41600. PBRBaseMaterial.prototype.getAnimatables = function () {
  41601. var results = [];
  41602. if (this._albedoTexture && this._albedoTexture.animations && this._albedoTexture.animations.length > 0) {
  41603. results.push(this._albedoTexture);
  41604. }
  41605. if (this._ambientTexture && this._ambientTexture.animations && this._ambientTexture.animations.length > 0) {
  41606. results.push(this._ambientTexture);
  41607. }
  41608. if (this._opacityTexture && this._opacityTexture.animations && this._opacityTexture.animations.length > 0) {
  41609. results.push(this._opacityTexture);
  41610. }
  41611. if (this._reflectionTexture && this._reflectionTexture.animations && this._reflectionTexture.animations.length > 0) {
  41612. results.push(this._reflectionTexture);
  41613. }
  41614. if (this._emissiveTexture && this._emissiveTexture.animations && this._emissiveTexture.animations.length > 0) {
  41615. results.push(this._emissiveTexture);
  41616. }
  41617. if (this._metallicTexture && this._metallicTexture.animations && this._metallicTexture.animations.length > 0) {
  41618. results.push(this._metallicTexture);
  41619. }
  41620. else if (this._reflectivityTexture && this._reflectivityTexture.animations && this._reflectivityTexture.animations.length > 0) {
  41621. results.push(this._reflectivityTexture);
  41622. }
  41623. if (this._bumpTexture && this._bumpTexture.animations && this._bumpTexture.animations.length > 0) {
  41624. results.push(this._bumpTexture);
  41625. }
  41626. if (this._lightmapTexture && this._lightmapTexture.animations && this._lightmapTexture.animations.length > 0) {
  41627. results.push(this._lightmapTexture);
  41628. }
  41629. if (this._refractionTexture && this._refractionTexture.animations && this._refractionTexture.animations.length > 0) {
  41630. results.push(this._refractionTexture);
  41631. }
  41632. return results;
  41633. };
  41634. /**
  41635. * Returns the texture used for reflections.
  41636. * @returns - Reflection texture if present. Otherwise, returns the environment texture.
  41637. */
  41638. PBRBaseMaterial.prototype._getReflectionTexture = function () {
  41639. if (this._reflectionTexture) {
  41640. return this._reflectionTexture;
  41641. }
  41642. return this.getScene().environmentTexture;
  41643. };
  41644. /**
  41645. * Returns the texture used for refraction or null if none is used.
  41646. * @returns - Refection texture if present. If no refraction texture and refraction
  41647. * is linked with transparency, returns environment texture. Otherwise, returns null.
  41648. */
  41649. PBRBaseMaterial.prototype._getRefractionTexture = function () {
  41650. if (this._refractionTexture) {
  41651. return this._refractionTexture;
  41652. }
  41653. if (this._linkRefractionWithTransparency) {
  41654. return this.getScene().environmentTexture;
  41655. }
  41656. return null;
  41657. };
  41658. /**
  41659. * Disposes the resources of the material.
  41660. * @param forceDisposeEffect - Forces the disposal of effects.
  41661. * @param forceDisposeTextures - Forces the disposal of all textures.
  41662. */
  41663. PBRBaseMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  41664. if (forceDisposeTextures) {
  41665. if (this._albedoTexture) {
  41666. this._albedoTexture.dispose();
  41667. }
  41668. if (this._ambientTexture) {
  41669. this._ambientTexture.dispose();
  41670. }
  41671. if (this._opacityTexture) {
  41672. this._opacityTexture.dispose();
  41673. }
  41674. if (this._reflectionTexture) {
  41675. this._reflectionTexture.dispose();
  41676. }
  41677. if (this._environmentBRDFTexture && this.getScene()._environmentBRDFTexture !== this._environmentBRDFTexture) {
  41678. this._environmentBRDFTexture.dispose();
  41679. }
  41680. if (this._emissiveTexture) {
  41681. this._emissiveTexture.dispose();
  41682. }
  41683. if (this._metallicTexture) {
  41684. this._metallicTexture.dispose();
  41685. }
  41686. if (this._reflectivityTexture) {
  41687. this._reflectivityTexture.dispose();
  41688. }
  41689. if (this._bumpTexture) {
  41690. this._bumpTexture.dispose();
  41691. }
  41692. if (this._lightmapTexture) {
  41693. this._lightmapTexture.dispose();
  41694. }
  41695. if (this._refractionTexture) {
  41696. this._refractionTexture.dispose();
  41697. }
  41698. }
  41699. this._renderTargets.dispose();
  41700. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  41701. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  41702. }
  41703. _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);
  41704. };
  41705. /**
  41706. * Stores the reflectivity values based on metallic roughness workflow.
  41707. */
  41708. PBRBaseMaterial._scaledReflectivity = new BABYLON.Color3();
  41709. __decorate([
  41710. BABYLON.serializeAsImageProcessingConfiguration()
  41711. ], PBRBaseMaterial.prototype, "_imageProcessingConfiguration", void 0);
  41712. __decorate([
  41713. BABYLON.serialize()
  41714. ], PBRBaseMaterial.prototype, "useLogarithmicDepth", null);
  41715. __decorate([
  41716. BABYLON.serialize()
  41717. ], PBRBaseMaterial.prototype, "transparencyMode", null);
  41718. return PBRBaseMaterial;
  41719. }(BABYLON.PushMaterial));
  41720. BABYLON.PBRBaseMaterial = PBRBaseMaterial;
  41721. })(BABYLON || (BABYLON = {}));
  41722. //# sourceMappingURL=babylon.pbrBaseMaterial.js.map
  41723. var BABYLON;
  41724. (function (BABYLON) {
  41725. /**
  41726. * The Physically based simple base material of BJS.
  41727. *
  41728. * This enables better naming and convention enforcements on top of the pbrMaterial.
  41729. * It is used as the base class for both the specGloss and metalRough conventions.
  41730. */
  41731. var PBRBaseSimpleMaterial = /** @class */ (function (_super) {
  41732. __extends(PBRBaseSimpleMaterial, _super);
  41733. /**
  41734. * Instantiates a new PBRMaterial instance.
  41735. *
  41736. * @param name The material name
  41737. * @param scene The scene the material will be use in.
  41738. */
  41739. function PBRBaseSimpleMaterial(name, scene) {
  41740. var _this = _super.call(this, name, scene) || this;
  41741. /**
  41742. * Number of Simultaneous lights allowed on the material.
  41743. */
  41744. _this.maxSimultaneousLights = 4;
  41745. /**
  41746. * If sets to true, disables all the lights affecting the material.
  41747. */
  41748. _this.disableLighting = false;
  41749. /**
  41750. * If sets to true, x component of normal map value will invert (x = 1.0 - x).
  41751. */
  41752. _this.invertNormalMapX = false;
  41753. /**
  41754. * If sets to true, y component of normal map value will invert (y = 1.0 - y).
  41755. */
  41756. _this.invertNormalMapY = false;
  41757. /**
  41758. * Emissivie color used to self-illuminate the model.
  41759. */
  41760. _this.emissiveColor = new BABYLON.Color3(0, 0, 0);
  41761. /**
  41762. * Occlusion Channel Strenght.
  41763. */
  41764. _this.occlusionStrength = 1.0;
  41765. _this.useLightmapAsShadowmap = false;
  41766. _this._useAlphaFromAlbedoTexture = true;
  41767. _this._useAmbientInGrayScale = true;
  41768. return _this;
  41769. }
  41770. Object.defineProperty(PBRBaseSimpleMaterial.prototype, "doubleSided", {
  41771. /**
  41772. * Gets the current double sided mode.
  41773. */
  41774. get: function () {
  41775. return this._twoSidedLighting;
  41776. },
  41777. /**
  41778. * If sets to true and backfaceCulling is false, normals will be flipped on the backside.
  41779. */
  41780. set: function (value) {
  41781. if (this._twoSidedLighting === value) {
  41782. return;
  41783. }
  41784. this._twoSidedLighting = value;
  41785. this.backFaceCulling = !value;
  41786. this._markAllSubMeshesAsTexturesDirty();
  41787. },
  41788. enumerable: true,
  41789. configurable: true
  41790. });
  41791. /**
  41792. * Return the active textures of the material.
  41793. */
  41794. PBRBaseSimpleMaterial.prototype.getActiveTextures = function () {
  41795. var activeTextures = _super.prototype.getActiveTextures.call(this);
  41796. if (this.environmentTexture) {
  41797. activeTextures.push(this.environmentTexture);
  41798. }
  41799. if (this.normalTexture) {
  41800. activeTextures.push(this.normalTexture);
  41801. }
  41802. if (this.emissiveTexture) {
  41803. activeTextures.push(this.emissiveTexture);
  41804. }
  41805. if (this.occlusionTexture) {
  41806. activeTextures.push(this.occlusionTexture);
  41807. }
  41808. if (this.lightmapTexture) {
  41809. activeTextures.push(this.lightmapTexture);
  41810. }
  41811. return activeTextures;
  41812. };
  41813. PBRBaseSimpleMaterial.prototype.hasTexture = function (texture) {
  41814. if (_super.prototype.hasTexture.call(this, texture)) {
  41815. return true;
  41816. }
  41817. if (this.lightmapTexture === texture) {
  41818. return true;
  41819. }
  41820. return false;
  41821. };
  41822. PBRBaseSimpleMaterial.prototype.getClassName = function () {
  41823. return "PBRBaseSimpleMaterial";
  41824. };
  41825. __decorate([
  41826. BABYLON.serialize(),
  41827. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  41828. ], PBRBaseSimpleMaterial.prototype, "maxSimultaneousLights", void 0);
  41829. __decorate([
  41830. BABYLON.serialize(),
  41831. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  41832. ], PBRBaseSimpleMaterial.prototype, "disableLighting", void 0);
  41833. __decorate([
  41834. BABYLON.serializeAsTexture(),
  41835. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_reflectionTexture")
  41836. ], PBRBaseSimpleMaterial.prototype, "environmentTexture", void 0);
  41837. __decorate([
  41838. BABYLON.serialize(),
  41839. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  41840. ], PBRBaseSimpleMaterial.prototype, "invertNormalMapX", void 0);
  41841. __decorate([
  41842. BABYLON.serialize(),
  41843. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  41844. ], PBRBaseSimpleMaterial.prototype, "invertNormalMapY", void 0);
  41845. __decorate([
  41846. BABYLON.serializeAsTexture(),
  41847. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_bumpTexture")
  41848. ], PBRBaseSimpleMaterial.prototype, "normalTexture", void 0);
  41849. __decorate([
  41850. BABYLON.serializeAsColor3("emissive"),
  41851. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  41852. ], PBRBaseSimpleMaterial.prototype, "emissiveColor", void 0);
  41853. __decorate([
  41854. BABYLON.serializeAsTexture(),
  41855. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  41856. ], PBRBaseSimpleMaterial.prototype, "emissiveTexture", void 0);
  41857. __decorate([
  41858. BABYLON.serialize(),
  41859. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_ambientTextureStrength")
  41860. ], PBRBaseSimpleMaterial.prototype, "occlusionStrength", void 0);
  41861. __decorate([
  41862. BABYLON.serializeAsTexture(),
  41863. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_ambientTexture")
  41864. ], PBRBaseSimpleMaterial.prototype, "occlusionTexture", void 0);
  41865. __decorate([
  41866. BABYLON.serialize(),
  41867. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_alphaCutOff")
  41868. ], PBRBaseSimpleMaterial.prototype, "alphaCutOff", void 0);
  41869. __decorate([
  41870. BABYLON.serialize()
  41871. ], PBRBaseSimpleMaterial.prototype, "doubleSided", null);
  41872. __decorate([
  41873. BABYLON.serializeAsTexture(),
  41874. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", null)
  41875. ], PBRBaseSimpleMaterial.prototype, "lightmapTexture", void 0);
  41876. __decorate([
  41877. BABYLON.serialize(),
  41878. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  41879. ], PBRBaseSimpleMaterial.prototype, "useLightmapAsShadowmap", void 0);
  41880. return PBRBaseSimpleMaterial;
  41881. }(BABYLON.PBRBaseMaterial));
  41882. BABYLON.PBRBaseSimpleMaterial = PBRBaseSimpleMaterial;
  41883. })(BABYLON || (BABYLON = {}));
  41884. //# sourceMappingURL=babylon.pbrBaseSimpleMaterial.js.map
  41885. var BABYLON;
  41886. (function (BABYLON) {
  41887. /**
  41888. * The Physically based material of BJS.
  41889. *
  41890. * This offers the main features of a standard PBR material.
  41891. * For more information, please refer to the documentation :
  41892. * http://doc.babylonjs.com/extensions/Physically_Based_Rendering
  41893. */
  41894. var PBRMaterial = /** @class */ (function (_super) {
  41895. __extends(PBRMaterial, _super);
  41896. /**
  41897. * Instantiates a new PBRMaterial instance.
  41898. *
  41899. * @param name The material name
  41900. * @param scene The scene the material will be use in.
  41901. */
  41902. function PBRMaterial(name, scene) {
  41903. var _this = _super.call(this, name, scene) || this;
  41904. /**
  41905. * Intensity of the direct lights e.g. the four lights available in your scene.
  41906. * This impacts both the direct diffuse and specular highlights.
  41907. */
  41908. _this.directIntensity = 1.0;
  41909. /**
  41910. * Intensity of the emissive part of the material.
  41911. * This helps controlling the emissive effect without modifying the emissive color.
  41912. */
  41913. _this.emissiveIntensity = 1.0;
  41914. /**
  41915. * Intensity of the environment e.g. how much the environment will light the object
  41916. * either through harmonics for rough material or through the refelction for shiny ones.
  41917. */
  41918. _this.environmentIntensity = 1.0;
  41919. /**
  41920. * This is a special control allowing the reduction of the specular highlights coming from the
  41921. * four lights of the scene. Those highlights may not be needed in full environment lighting.
  41922. */
  41923. _this.specularIntensity = 1.0;
  41924. /**
  41925. * Debug Control allowing disabling the bump map on this material.
  41926. */
  41927. _this.disableBumpMap = false;
  41928. /**
  41929. * AKA Occlusion Texture Intensity in other nomenclature.
  41930. */
  41931. _this.ambientTextureStrength = 1.0;
  41932. /**
  41933. * The color of a material in ambient lighting.
  41934. */
  41935. _this.ambientColor = new BABYLON.Color3(0, 0, 0);
  41936. /**
  41937. * AKA Diffuse Color in other nomenclature.
  41938. */
  41939. _this.albedoColor = new BABYLON.Color3(1, 1, 1);
  41940. /**
  41941. * AKA Specular Color in other nomenclature.
  41942. */
  41943. _this.reflectivityColor = new BABYLON.Color3(1, 1, 1);
  41944. /**
  41945. * The color reflected from the material.
  41946. */
  41947. _this.reflectionColor = new BABYLON.Color3(1.0, 1.0, 1.0);
  41948. /**
  41949. * The color emitted from the material.
  41950. */
  41951. _this.emissiveColor = new BABYLON.Color3(0, 0, 0);
  41952. /**
  41953. * AKA Glossiness in other nomenclature.
  41954. */
  41955. _this.microSurface = 1.0;
  41956. /**
  41957. * source material index of refraction (IOR)' / 'destination material IOR.
  41958. */
  41959. _this.indexOfRefraction = 0.66;
  41960. /**
  41961. * Controls if refraction needs to be inverted on Y. This could be usefull for procedural texture.
  41962. */
  41963. _this.invertRefractionY = false;
  41964. /**
  41965. * This parameters will make the material used its opacity to control how much it is refracting aginst not.
  41966. * Materials half opaque for instance using refraction could benefit from this control.
  41967. */
  41968. _this.linkRefractionWithTransparency = false;
  41969. _this.useLightmapAsShadowmap = false;
  41970. /**
  41971. * Specifies that the alpha is coming form the albedo channel alpha channel for alpha blending.
  41972. */
  41973. _this.useAlphaFromAlbedoTexture = false;
  41974. /**
  41975. * Enforces alpha test in opaque or blend mode in order to improve the performances of some situations.
  41976. */
  41977. _this.forceAlphaTest = false;
  41978. /**
  41979. * Defines the alpha limits in alpha test mode.
  41980. */
  41981. _this.alphaCutOff = 0.4;
  41982. /**
  41983. * Specifies that the material will keeps the specular highlights over a transparent surface (only the most limunous ones).
  41984. * A car glass is a good exemple of that. When sun reflects on it you can not see what is behind.
  41985. */
  41986. _this.useSpecularOverAlpha = true;
  41987. /**
  41988. * Specifies if the reflectivity texture contains the glossiness information in its alpha channel.
  41989. */
  41990. _this.useMicroSurfaceFromReflectivityMapAlpha = false;
  41991. /**
  41992. * Specifies if the metallic texture contains the roughness information in its alpha channel.
  41993. */
  41994. _this.useRoughnessFromMetallicTextureAlpha = true;
  41995. /**
  41996. * Specifies if the metallic texture contains the roughness information in its green channel.
  41997. */
  41998. _this.useRoughnessFromMetallicTextureGreen = false;
  41999. /**
  42000. * Specifies if the metallic texture contains the metallness information in its blue channel.
  42001. */
  42002. _this.useMetallnessFromMetallicTextureBlue = false;
  42003. /**
  42004. * Specifies if the metallic texture contains the ambient occlusion information in its red channel.
  42005. */
  42006. _this.useAmbientOcclusionFromMetallicTextureRed = false;
  42007. /**
  42008. * Specifies if the ambient texture contains the ambient occlusion information in its red channel only.
  42009. */
  42010. _this.useAmbientInGrayScale = false;
  42011. /**
  42012. * In case the reflectivity map does not contain the microsurface information in its alpha channel,
  42013. * The material will try to infer what glossiness each pixel should be.
  42014. */
  42015. _this.useAutoMicroSurfaceFromReflectivityMap = false;
  42016. /**
  42017. * BJS is using an harcoded light falloff based on a manually sets up range.
  42018. * In PBR, one way to represents the fallof is to use the inverse squared root algorythm.
  42019. * This parameter can help you switch back to the BJS mode in order to create scenes using both materials.
  42020. */
  42021. _this.usePhysicalLightFalloff = true;
  42022. /**
  42023. * Specifies that the material will keeps the reflection highlights over a transparent surface (only the most limunous ones).
  42024. * A car glass is a good exemple of that. When the street lights reflects on it you can not see what is behind.
  42025. */
  42026. _this.useRadianceOverAlpha = true;
  42027. /**
  42028. * Allows using an object space normal map (instead of tangent space).
  42029. */
  42030. _this.useObjectSpaceNormalMap = false;
  42031. /**
  42032. * Allows using the bump map in parallax mode.
  42033. */
  42034. _this.useParallax = false;
  42035. /**
  42036. * Allows using the bump map in parallax occlusion mode.
  42037. */
  42038. _this.useParallaxOcclusion = false;
  42039. /**
  42040. * Controls the scale bias of the parallax mode.
  42041. */
  42042. _this.parallaxScaleBias = 0.05;
  42043. /**
  42044. * If sets to true, disables all the lights affecting the material.
  42045. */
  42046. _this.disableLighting = false;
  42047. /**
  42048. * Force the shader to compute irradiance in the fragment shader in order to take bump in account.
  42049. */
  42050. _this.forceIrradianceInFragment = false;
  42051. /**
  42052. * Number of Simultaneous lights allowed on the material.
  42053. */
  42054. _this.maxSimultaneousLights = 4;
  42055. /**
  42056. * If sets to true, x component of normal map value will invert (x = 1.0 - x).
  42057. */
  42058. _this.invertNormalMapX = false;
  42059. /**
  42060. * If sets to true, y component of normal map value will invert (y = 1.0 - y).
  42061. */
  42062. _this.invertNormalMapY = false;
  42063. /**
  42064. * If sets to true and backfaceCulling is false, normals will be flipped on the backside.
  42065. */
  42066. _this.twoSidedLighting = false;
  42067. /**
  42068. * A fresnel is applied to the alpha of the model to ensure grazing angles edges are not alpha tested.
  42069. * And/Or occlude the blended part. (alpha is converted to gamma to compute the fresnel)
  42070. */
  42071. _this.useAlphaFresnel = false;
  42072. /**
  42073. * A fresnel is applied to the alpha of the model to ensure grazing angles edges are not alpha tested.
  42074. * And/Or occlude the blended part. (alpha stays linear to compute the fresnel)
  42075. */
  42076. _this.useLinearAlphaFresnel = false;
  42077. /**
  42078. * A fresnel is applied to the alpha of the model to ensure grazing angles edges are not alpha tested.
  42079. * And/Or occlude the blended part.
  42080. */
  42081. _this.environmentBRDFTexture = null;
  42082. /**
  42083. * Force normal to face away from face.
  42084. */
  42085. _this.forceNormalForward = false;
  42086. /**
  42087. * This parameters will enable/disable Horizon occlusion to prevent normal maps to look shiny when the normal
  42088. * makes the reflect vector face the model (under horizon).
  42089. */
  42090. _this.useHorizonOcclusion = true;
  42091. /**
  42092. * This parameters will enable/disable radiance occlusion by preventing the radiance to lit
  42093. * too much the area relying on ambient texture to define their ambient occlusion.
  42094. */
  42095. _this.useRadianceOcclusion = true;
  42096. _this._environmentBRDFTexture = BABYLON.TextureTools.GetEnvironmentBRDFTexture(scene);
  42097. return _this;
  42098. }
  42099. Object.defineProperty(PBRMaterial, "PBRMATERIAL_OPAQUE", {
  42100. /**
  42101. * PBRMaterialTransparencyMode: No transparency mode, Alpha channel is not use.
  42102. */
  42103. get: function () {
  42104. return this._PBRMATERIAL_OPAQUE;
  42105. },
  42106. enumerable: true,
  42107. configurable: true
  42108. });
  42109. Object.defineProperty(PBRMaterial, "PBRMATERIAL_ALPHATEST", {
  42110. /**
  42111. * PBRMaterialTransparencyMode: Alpha Test mode, pixel are discarded below a certain threshold defined by the alpha cutoff value.
  42112. */
  42113. get: function () {
  42114. return this._PBRMATERIAL_ALPHATEST;
  42115. },
  42116. enumerable: true,
  42117. configurable: true
  42118. });
  42119. Object.defineProperty(PBRMaterial, "PBRMATERIAL_ALPHABLEND", {
  42120. /**
  42121. * PBRMaterialTransparencyMode: Pixels are blended (according to the alpha mode) with the already drawn pixels in the current frame buffer.
  42122. */
  42123. get: function () {
  42124. return this._PBRMATERIAL_ALPHABLEND;
  42125. },
  42126. enumerable: true,
  42127. configurable: true
  42128. });
  42129. Object.defineProperty(PBRMaterial, "PBRMATERIAL_ALPHATESTANDBLEND", {
  42130. /**
  42131. * PBRMaterialTransparencyMode: Pixels are blended (according to the alpha mode) with the already drawn pixels in the current frame buffer.
  42132. * They are also discarded below the alpha cutoff threshold to improve performances.
  42133. */
  42134. get: function () {
  42135. return this._PBRMATERIAL_ALPHATESTANDBLEND;
  42136. },
  42137. enumerable: true,
  42138. configurable: true
  42139. });
  42140. Object.defineProperty(PBRMaterial.prototype, "imageProcessingConfiguration", {
  42141. /**
  42142. * Gets the image processing configuration used either in this material.
  42143. */
  42144. get: function () {
  42145. return this._imageProcessingConfiguration;
  42146. },
  42147. /**
  42148. * Sets the Default image processing configuration used either in the this material.
  42149. *
  42150. * If sets to null, the scene one is in use.
  42151. */
  42152. set: function (value) {
  42153. this._attachImageProcessingConfiguration(value);
  42154. // Ensure the effect will be rebuilt.
  42155. this._markAllSubMeshesAsTexturesDirty();
  42156. },
  42157. enumerable: true,
  42158. configurable: true
  42159. });
  42160. Object.defineProperty(PBRMaterial.prototype, "cameraColorCurvesEnabled", {
  42161. /**
  42162. * Gets wether the color curves effect is enabled.
  42163. */
  42164. get: function () {
  42165. return this.imageProcessingConfiguration.colorCurvesEnabled;
  42166. },
  42167. /**
  42168. * Sets wether the color curves effect is enabled.
  42169. */
  42170. set: function (value) {
  42171. this.imageProcessingConfiguration.colorCurvesEnabled = value;
  42172. },
  42173. enumerable: true,
  42174. configurable: true
  42175. });
  42176. Object.defineProperty(PBRMaterial.prototype, "cameraColorGradingEnabled", {
  42177. /**
  42178. * Gets wether the color grading effect is enabled.
  42179. */
  42180. get: function () {
  42181. return this.imageProcessingConfiguration.colorGradingEnabled;
  42182. },
  42183. /**
  42184. * Gets wether the color grading effect is enabled.
  42185. */
  42186. set: function (value) {
  42187. this.imageProcessingConfiguration.colorGradingEnabled = value;
  42188. },
  42189. enumerable: true,
  42190. configurable: true
  42191. });
  42192. Object.defineProperty(PBRMaterial.prototype, "cameraToneMappingEnabled", {
  42193. /**
  42194. * Gets wether tonemapping is enabled or not.
  42195. */
  42196. get: function () {
  42197. return this._imageProcessingConfiguration.toneMappingEnabled;
  42198. },
  42199. /**
  42200. * Sets wether tonemapping is enabled or not
  42201. */
  42202. set: function (value) {
  42203. this._imageProcessingConfiguration.toneMappingEnabled = value;
  42204. },
  42205. enumerable: true,
  42206. configurable: true
  42207. });
  42208. ;
  42209. ;
  42210. Object.defineProperty(PBRMaterial.prototype, "cameraExposure", {
  42211. /**
  42212. * The camera exposure used on this material.
  42213. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  42214. * This corresponds to a photographic exposure.
  42215. */
  42216. get: function () {
  42217. return this._imageProcessingConfiguration.exposure;
  42218. },
  42219. /**
  42220. * The camera exposure used on this material.
  42221. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  42222. * This corresponds to a photographic exposure.
  42223. */
  42224. set: function (value) {
  42225. this._imageProcessingConfiguration.exposure = value;
  42226. },
  42227. enumerable: true,
  42228. configurable: true
  42229. });
  42230. ;
  42231. ;
  42232. Object.defineProperty(PBRMaterial.prototype, "cameraContrast", {
  42233. /**
  42234. * Gets The camera contrast used on this material.
  42235. */
  42236. get: function () {
  42237. return this._imageProcessingConfiguration.contrast;
  42238. },
  42239. /**
  42240. * Sets The camera contrast used on this material.
  42241. */
  42242. set: function (value) {
  42243. this._imageProcessingConfiguration.contrast = value;
  42244. },
  42245. enumerable: true,
  42246. configurable: true
  42247. });
  42248. Object.defineProperty(PBRMaterial.prototype, "cameraColorGradingTexture", {
  42249. /**
  42250. * Gets the Color Grading 2D Lookup Texture.
  42251. */
  42252. get: function () {
  42253. return this._imageProcessingConfiguration.colorGradingTexture;
  42254. },
  42255. /**
  42256. * Sets the Color Grading 2D Lookup Texture.
  42257. */
  42258. set: function (value) {
  42259. this._imageProcessingConfiguration.colorGradingTexture = value;
  42260. },
  42261. enumerable: true,
  42262. configurable: true
  42263. });
  42264. Object.defineProperty(PBRMaterial.prototype, "cameraColorCurves", {
  42265. /**
  42266. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  42267. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  42268. * 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;
  42269. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  42270. */
  42271. get: function () {
  42272. return this._imageProcessingConfiguration.colorCurves;
  42273. },
  42274. /**
  42275. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  42276. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  42277. * 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;
  42278. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  42279. */
  42280. set: function (value) {
  42281. this._imageProcessingConfiguration.colorCurves = value;
  42282. },
  42283. enumerable: true,
  42284. configurable: true
  42285. });
  42286. /**
  42287. * Returns the name of this material class.
  42288. */
  42289. PBRMaterial.prototype.getClassName = function () {
  42290. return "PBRMaterial";
  42291. };
  42292. /**
  42293. * Returns an array of the actively used textures.
  42294. * @returns - Array of BaseTextures
  42295. */
  42296. PBRMaterial.prototype.getActiveTextures = function () {
  42297. var activeTextures = _super.prototype.getActiveTextures.call(this);
  42298. if (this._albedoTexture) {
  42299. activeTextures.push(this._albedoTexture);
  42300. }
  42301. if (this._ambientTexture) {
  42302. activeTextures.push(this._ambientTexture);
  42303. }
  42304. if (this._opacityTexture) {
  42305. activeTextures.push(this._opacityTexture);
  42306. }
  42307. if (this._reflectionTexture) {
  42308. activeTextures.push(this._reflectionTexture);
  42309. }
  42310. if (this._emissiveTexture) {
  42311. activeTextures.push(this._emissiveTexture);
  42312. }
  42313. if (this._reflectivityTexture) {
  42314. activeTextures.push(this._reflectivityTexture);
  42315. }
  42316. if (this._metallicTexture) {
  42317. activeTextures.push(this._metallicTexture);
  42318. }
  42319. if (this._microSurfaceTexture) {
  42320. activeTextures.push(this._microSurfaceTexture);
  42321. }
  42322. if (this._bumpTexture) {
  42323. activeTextures.push(this._bumpTexture);
  42324. }
  42325. if (this._lightmapTexture) {
  42326. activeTextures.push(this._lightmapTexture);
  42327. }
  42328. if (this._refractionTexture) {
  42329. activeTextures.push(this._refractionTexture);
  42330. }
  42331. return activeTextures;
  42332. };
  42333. /**
  42334. * Checks to see if a texture is used in the material.
  42335. * @param texture - Base texture to use.
  42336. * @returns - Boolean specifying if a texture is used in the material.
  42337. */
  42338. PBRMaterial.prototype.hasTexture = function (texture) {
  42339. if (_super.prototype.hasTexture.call(this, texture)) {
  42340. return true;
  42341. }
  42342. if (this._albedoTexture === texture) {
  42343. return true;
  42344. }
  42345. if (this._ambientTexture === texture) {
  42346. return true;
  42347. }
  42348. if (this._opacityTexture === texture) {
  42349. return true;
  42350. }
  42351. if (this._reflectionTexture === texture) {
  42352. return true;
  42353. }
  42354. if (this._reflectivityTexture === texture) {
  42355. return true;
  42356. }
  42357. if (this._metallicTexture === texture) {
  42358. return true;
  42359. }
  42360. if (this._microSurfaceTexture === texture) {
  42361. return true;
  42362. }
  42363. if (this._bumpTexture === texture) {
  42364. return true;
  42365. }
  42366. if (this._lightmapTexture === texture) {
  42367. return true;
  42368. }
  42369. if (this._refractionTexture === texture) {
  42370. return true;
  42371. }
  42372. return false;
  42373. };
  42374. /**
  42375. * Makes a duplicate of the current material.
  42376. * @param name - name to use for the new material.
  42377. */
  42378. PBRMaterial.prototype.clone = function (name) {
  42379. var _this = this;
  42380. var clone = BABYLON.SerializationHelper.Clone(function () { return new PBRMaterial(name, _this.getScene()); }, this);
  42381. clone.id = name;
  42382. clone.name = name;
  42383. return clone;
  42384. };
  42385. /**
  42386. * Serializes this PBR Material.
  42387. * @returns - An object with the serialized material.
  42388. */
  42389. PBRMaterial.prototype.serialize = function () {
  42390. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  42391. serializationObject.customType = "BABYLON.PBRMaterial";
  42392. return serializationObject;
  42393. };
  42394. // Statics
  42395. /**
  42396. * Parses a PBR Material from a serialized object.
  42397. * @param source - Serialized object.
  42398. * @param scene - BJS scene instance.
  42399. * @param rootUrl - url for the scene object
  42400. * @returns - PBRMaterial
  42401. */
  42402. PBRMaterial.Parse = function (source, scene, rootUrl) {
  42403. return BABYLON.SerializationHelper.Parse(function () { return new PBRMaterial(source.name, scene); }, source, scene, rootUrl);
  42404. };
  42405. PBRMaterial._PBRMATERIAL_OPAQUE = 0;
  42406. /**
  42407. * Alpha Test mode, pixel are discarded below a certain threshold defined by the alpha cutoff value.
  42408. */
  42409. PBRMaterial._PBRMATERIAL_ALPHATEST = 1;
  42410. /**
  42411. * Represents the value for Alpha Blend. Pixels are blended (according to the alpha mode) with the already drawn pixels in the current frame buffer.
  42412. */
  42413. PBRMaterial._PBRMATERIAL_ALPHABLEND = 2;
  42414. /**
  42415. * 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.
  42416. * They are also discarded below the alpha cutoff threshold to improve performances.
  42417. */
  42418. PBRMaterial._PBRMATERIAL_ALPHATESTANDBLEND = 3;
  42419. __decorate([
  42420. BABYLON.serialize(),
  42421. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42422. ], PBRMaterial.prototype, "directIntensity", void 0);
  42423. __decorate([
  42424. BABYLON.serialize(),
  42425. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42426. ], PBRMaterial.prototype, "emissiveIntensity", void 0);
  42427. __decorate([
  42428. BABYLON.serialize(),
  42429. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42430. ], PBRMaterial.prototype, "environmentIntensity", void 0);
  42431. __decorate([
  42432. BABYLON.serialize(),
  42433. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42434. ], PBRMaterial.prototype, "specularIntensity", void 0);
  42435. __decorate([
  42436. BABYLON.serialize(),
  42437. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42438. ], PBRMaterial.prototype, "disableBumpMap", void 0);
  42439. __decorate([
  42440. BABYLON.serializeAsTexture(),
  42441. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42442. ], PBRMaterial.prototype, "albedoTexture", void 0);
  42443. __decorate([
  42444. BABYLON.serializeAsTexture(),
  42445. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42446. ], PBRMaterial.prototype, "ambientTexture", void 0);
  42447. __decorate([
  42448. BABYLON.serialize(),
  42449. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42450. ], PBRMaterial.prototype, "ambientTextureStrength", void 0);
  42451. __decorate([
  42452. BABYLON.serializeAsTexture(),
  42453. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesAndMiscDirty")
  42454. ], PBRMaterial.prototype, "opacityTexture", void 0);
  42455. __decorate([
  42456. BABYLON.serializeAsTexture(),
  42457. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42458. ], PBRMaterial.prototype, "reflectionTexture", void 0);
  42459. __decorate([
  42460. BABYLON.serializeAsTexture(),
  42461. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42462. ], PBRMaterial.prototype, "emissiveTexture", void 0);
  42463. __decorate([
  42464. BABYLON.serializeAsTexture(),
  42465. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42466. ], PBRMaterial.prototype, "reflectivityTexture", void 0);
  42467. __decorate([
  42468. BABYLON.serializeAsTexture(),
  42469. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42470. ], PBRMaterial.prototype, "metallicTexture", void 0);
  42471. __decorate([
  42472. BABYLON.serialize(),
  42473. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42474. ], PBRMaterial.prototype, "metallic", void 0);
  42475. __decorate([
  42476. BABYLON.serialize(),
  42477. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42478. ], PBRMaterial.prototype, "roughness", void 0);
  42479. __decorate([
  42480. BABYLON.serializeAsTexture(),
  42481. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42482. ], PBRMaterial.prototype, "microSurfaceTexture", void 0);
  42483. __decorate([
  42484. BABYLON.serializeAsTexture(),
  42485. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42486. ], PBRMaterial.prototype, "bumpTexture", void 0);
  42487. __decorate([
  42488. BABYLON.serializeAsTexture(),
  42489. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", null)
  42490. ], PBRMaterial.prototype, "lightmapTexture", void 0);
  42491. __decorate([
  42492. BABYLON.serializeAsTexture(),
  42493. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42494. ], PBRMaterial.prototype, "refractionTexture", void 0);
  42495. __decorate([
  42496. BABYLON.serializeAsColor3("ambient"),
  42497. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42498. ], PBRMaterial.prototype, "ambientColor", void 0);
  42499. __decorate([
  42500. BABYLON.serializeAsColor3("albedo"),
  42501. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42502. ], PBRMaterial.prototype, "albedoColor", void 0);
  42503. __decorate([
  42504. BABYLON.serializeAsColor3("reflectivity"),
  42505. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42506. ], PBRMaterial.prototype, "reflectivityColor", void 0);
  42507. __decorate([
  42508. BABYLON.serializeAsColor3("reflection"),
  42509. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42510. ], PBRMaterial.prototype, "reflectionColor", void 0);
  42511. __decorate([
  42512. BABYLON.serializeAsColor3("emissive"),
  42513. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42514. ], PBRMaterial.prototype, "emissiveColor", void 0);
  42515. __decorate([
  42516. BABYLON.serialize(),
  42517. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42518. ], PBRMaterial.prototype, "microSurface", void 0);
  42519. __decorate([
  42520. BABYLON.serialize(),
  42521. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42522. ], PBRMaterial.prototype, "indexOfRefraction", void 0);
  42523. __decorate([
  42524. BABYLON.serialize(),
  42525. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42526. ], PBRMaterial.prototype, "invertRefractionY", void 0);
  42527. __decorate([
  42528. BABYLON.serialize(),
  42529. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42530. ], PBRMaterial.prototype, "linkRefractionWithTransparency", void 0);
  42531. __decorate([
  42532. BABYLON.serialize(),
  42533. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42534. ], PBRMaterial.prototype, "useLightmapAsShadowmap", void 0);
  42535. __decorate([
  42536. BABYLON.serialize(),
  42537. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesAndMiscDirty")
  42538. ], PBRMaterial.prototype, "useAlphaFromAlbedoTexture", void 0);
  42539. __decorate([
  42540. BABYLON.serialize(),
  42541. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesAndMiscDirty")
  42542. ], PBRMaterial.prototype, "forceAlphaTest", void 0);
  42543. __decorate([
  42544. BABYLON.serialize(),
  42545. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesAndMiscDirty")
  42546. ], PBRMaterial.prototype, "alphaCutOff", void 0);
  42547. __decorate([
  42548. BABYLON.serialize(),
  42549. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42550. ], PBRMaterial.prototype, "useSpecularOverAlpha", void 0);
  42551. __decorate([
  42552. BABYLON.serialize(),
  42553. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42554. ], PBRMaterial.prototype, "useMicroSurfaceFromReflectivityMapAlpha", void 0);
  42555. __decorate([
  42556. BABYLON.serialize(),
  42557. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42558. ], PBRMaterial.prototype, "useRoughnessFromMetallicTextureAlpha", void 0);
  42559. __decorate([
  42560. BABYLON.serialize(),
  42561. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42562. ], PBRMaterial.prototype, "useRoughnessFromMetallicTextureGreen", void 0);
  42563. __decorate([
  42564. BABYLON.serialize(),
  42565. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42566. ], PBRMaterial.prototype, "useMetallnessFromMetallicTextureBlue", void 0);
  42567. __decorate([
  42568. BABYLON.serialize(),
  42569. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42570. ], PBRMaterial.prototype, "useAmbientOcclusionFromMetallicTextureRed", void 0);
  42571. __decorate([
  42572. BABYLON.serialize(),
  42573. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42574. ], PBRMaterial.prototype, "useAmbientInGrayScale", void 0);
  42575. __decorate([
  42576. BABYLON.serialize(),
  42577. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42578. ], PBRMaterial.prototype, "useAutoMicroSurfaceFromReflectivityMap", void 0);
  42579. __decorate([
  42580. BABYLON.serialize(),
  42581. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42582. ], PBRMaterial.prototype, "usePhysicalLightFalloff", void 0);
  42583. __decorate([
  42584. BABYLON.serialize(),
  42585. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42586. ], PBRMaterial.prototype, "useRadianceOverAlpha", void 0);
  42587. __decorate([
  42588. BABYLON.serialize(),
  42589. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42590. ], PBRMaterial.prototype, "useObjectSpaceNormalMap", void 0);
  42591. __decorate([
  42592. BABYLON.serialize(),
  42593. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42594. ], PBRMaterial.prototype, "useParallax", void 0);
  42595. __decorate([
  42596. BABYLON.serialize(),
  42597. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42598. ], PBRMaterial.prototype, "useParallaxOcclusion", void 0);
  42599. __decorate([
  42600. BABYLON.serialize(),
  42601. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42602. ], PBRMaterial.prototype, "parallaxScaleBias", void 0);
  42603. __decorate([
  42604. BABYLON.serialize(),
  42605. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  42606. ], PBRMaterial.prototype, "disableLighting", void 0);
  42607. __decorate([
  42608. BABYLON.serialize(),
  42609. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42610. ], PBRMaterial.prototype, "forceIrradianceInFragment", void 0);
  42611. __decorate([
  42612. BABYLON.serialize(),
  42613. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  42614. ], PBRMaterial.prototype, "maxSimultaneousLights", void 0);
  42615. __decorate([
  42616. BABYLON.serialize(),
  42617. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42618. ], PBRMaterial.prototype, "invertNormalMapX", void 0);
  42619. __decorate([
  42620. BABYLON.serialize(),
  42621. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42622. ], PBRMaterial.prototype, "invertNormalMapY", void 0);
  42623. __decorate([
  42624. BABYLON.serialize(),
  42625. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42626. ], PBRMaterial.prototype, "twoSidedLighting", void 0);
  42627. __decorate([
  42628. BABYLON.serialize(),
  42629. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42630. ], PBRMaterial.prototype, "useAlphaFresnel", void 0);
  42631. __decorate([
  42632. BABYLON.serialize(),
  42633. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42634. ], PBRMaterial.prototype, "useLinearAlphaFresnel", void 0);
  42635. __decorate([
  42636. BABYLON.serializeAsTexture(),
  42637. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42638. ], PBRMaterial.prototype, "environmentBRDFTexture", void 0);
  42639. __decorate([
  42640. BABYLON.serialize(),
  42641. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42642. ], PBRMaterial.prototype, "forceNormalForward", void 0);
  42643. __decorate([
  42644. BABYLON.serialize(),
  42645. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42646. ], PBRMaterial.prototype, "useHorizonOcclusion", void 0);
  42647. __decorate([
  42648. BABYLON.serialize(),
  42649. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42650. ], PBRMaterial.prototype, "useRadianceOcclusion", void 0);
  42651. return PBRMaterial;
  42652. }(BABYLON.PBRBaseMaterial));
  42653. BABYLON.PBRMaterial = PBRMaterial;
  42654. })(BABYLON || (BABYLON = {}));
  42655. //# sourceMappingURL=babylon.pbrMaterial.js.map
  42656. var BABYLON;
  42657. (function (BABYLON) {
  42658. /**
  42659. * The PBR material of BJS following the metal roughness convention.
  42660. *
  42661. * This fits to the PBR convention in the GLTF definition:
  42662. * https://github.com/KhronosGroup/glTF/tree/2.0/specification/2.0
  42663. */
  42664. var PBRMetallicRoughnessMaterial = /** @class */ (function (_super) {
  42665. __extends(PBRMetallicRoughnessMaterial, _super);
  42666. /**
  42667. * Instantiates a new PBRMetalRoughnessMaterial instance.
  42668. *
  42669. * @param name The material name
  42670. * @param scene The scene the material will be use in.
  42671. */
  42672. function PBRMetallicRoughnessMaterial(name, scene) {
  42673. var _this = _super.call(this, name, scene) || this;
  42674. _this._useRoughnessFromMetallicTextureAlpha = false;
  42675. _this._useRoughnessFromMetallicTextureGreen = true;
  42676. _this._useMetallnessFromMetallicTextureBlue = true;
  42677. _this.metallic = 1.0;
  42678. _this.roughness = 1.0;
  42679. return _this;
  42680. }
  42681. /**
  42682. * Return the currrent class name of the material.
  42683. */
  42684. PBRMetallicRoughnessMaterial.prototype.getClassName = function () {
  42685. return "PBRMetallicRoughnessMaterial";
  42686. };
  42687. /**
  42688. * Return the active textures of the material.
  42689. */
  42690. PBRMetallicRoughnessMaterial.prototype.getActiveTextures = function () {
  42691. var activeTextures = _super.prototype.getActiveTextures.call(this);
  42692. if (this.baseTexture) {
  42693. activeTextures.push(this.baseTexture);
  42694. }
  42695. if (this.metallicRoughnessTexture) {
  42696. activeTextures.push(this.metallicRoughnessTexture);
  42697. }
  42698. return activeTextures;
  42699. };
  42700. /**
  42701. * Checks to see if a texture is used in the material.
  42702. * @param texture - Base texture to use.
  42703. * @returns - Boolean specifying if a texture is used in the material.
  42704. */
  42705. PBRMetallicRoughnessMaterial.prototype.hasTexture = function (texture) {
  42706. if (_super.prototype.hasTexture.call(this, texture)) {
  42707. return true;
  42708. }
  42709. if (this.baseTexture === texture) {
  42710. return true;
  42711. }
  42712. if (this.metallicRoughnessTexture === texture) {
  42713. return true;
  42714. }
  42715. return false;
  42716. };
  42717. /**
  42718. * Makes a duplicate of the current material.
  42719. * @param name - name to use for the new material.
  42720. */
  42721. PBRMetallicRoughnessMaterial.prototype.clone = function (name) {
  42722. var _this = this;
  42723. var clone = BABYLON.SerializationHelper.Clone(function () { return new PBRMetallicRoughnessMaterial(name, _this.getScene()); }, this);
  42724. clone.id = name;
  42725. clone.name = name;
  42726. return clone;
  42727. };
  42728. /**
  42729. * Serialize the material to a parsable JSON object.
  42730. */
  42731. PBRMetallicRoughnessMaterial.prototype.serialize = function () {
  42732. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  42733. serializationObject.customType = "BABYLON.PBRMetallicRoughnessMaterial";
  42734. return serializationObject;
  42735. };
  42736. /**
  42737. * Parses a JSON object correponding to the serialize function.
  42738. */
  42739. PBRMetallicRoughnessMaterial.Parse = function (source, scene, rootUrl) {
  42740. return BABYLON.SerializationHelper.Parse(function () { return new PBRMetallicRoughnessMaterial(source.name, scene); }, source, scene, rootUrl);
  42741. };
  42742. __decorate([
  42743. BABYLON.serializeAsColor3(),
  42744. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_albedoColor")
  42745. ], PBRMetallicRoughnessMaterial.prototype, "baseColor", void 0);
  42746. __decorate([
  42747. BABYLON.serializeAsTexture(),
  42748. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_albedoTexture")
  42749. ], PBRMetallicRoughnessMaterial.prototype, "baseTexture", void 0);
  42750. __decorate([
  42751. BABYLON.serialize(),
  42752. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42753. ], PBRMetallicRoughnessMaterial.prototype, "metallic", void 0);
  42754. __decorate([
  42755. BABYLON.serialize(),
  42756. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42757. ], PBRMetallicRoughnessMaterial.prototype, "roughness", void 0);
  42758. __decorate([
  42759. BABYLON.serializeAsTexture(),
  42760. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_metallicTexture")
  42761. ], PBRMetallicRoughnessMaterial.prototype, "metallicRoughnessTexture", void 0);
  42762. return PBRMetallicRoughnessMaterial;
  42763. }(BABYLON.PBRBaseSimpleMaterial));
  42764. BABYLON.PBRMetallicRoughnessMaterial = PBRMetallicRoughnessMaterial;
  42765. })(BABYLON || (BABYLON = {}));
  42766. //# sourceMappingURL=babylon.pbrMetallicRoughnessMaterial.js.map
  42767. var BABYLON;
  42768. (function (BABYLON) {
  42769. /**
  42770. * The PBR material of BJS following the specular glossiness convention.
  42771. *
  42772. * This fits to the PBR convention in the GLTF definition:
  42773. * https://github.com/KhronosGroup/glTF/tree/2.0/extensions/Khronos/KHR_materials_pbrSpecularGlossiness
  42774. */
  42775. var PBRSpecularGlossinessMaterial = /** @class */ (function (_super) {
  42776. __extends(PBRSpecularGlossinessMaterial, _super);
  42777. /**
  42778. * Instantiates a new PBRSpecularGlossinessMaterial instance.
  42779. *
  42780. * @param name The material name
  42781. * @param scene The scene the material will be use in.
  42782. */
  42783. function PBRSpecularGlossinessMaterial(name, scene) {
  42784. var _this = _super.call(this, name, scene) || this;
  42785. _this._useMicroSurfaceFromReflectivityMapAlpha = true;
  42786. return _this;
  42787. }
  42788. /**
  42789. * Return the currrent class name of the material.
  42790. */
  42791. PBRSpecularGlossinessMaterial.prototype.getClassName = function () {
  42792. return "PBRSpecularGlossinessMaterial";
  42793. };
  42794. /**
  42795. * Return the active textures of the material.
  42796. */
  42797. PBRSpecularGlossinessMaterial.prototype.getActiveTextures = function () {
  42798. var activeTextures = _super.prototype.getActiveTextures.call(this);
  42799. if (this.diffuseTexture) {
  42800. activeTextures.push(this.diffuseTexture);
  42801. }
  42802. if (this.specularGlossinessTexture) {
  42803. activeTextures.push(this.specularGlossinessTexture);
  42804. }
  42805. return activeTextures;
  42806. };
  42807. /**
  42808. * Checks to see if a texture is used in the material.
  42809. * @param texture - Base texture to use.
  42810. * @returns - Boolean specifying if a texture is used in the material.
  42811. */
  42812. PBRSpecularGlossinessMaterial.prototype.hasTexture = function (texture) {
  42813. if (_super.prototype.hasTexture.call(this, texture)) {
  42814. return true;
  42815. }
  42816. if (this.diffuseTexture === texture) {
  42817. return true;
  42818. }
  42819. if (this.specularGlossinessTexture === texture) {
  42820. return true;
  42821. }
  42822. return false;
  42823. };
  42824. /**
  42825. * Makes a duplicate of the current material.
  42826. * @param name - name to use for the new material.
  42827. */
  42828. PBRSpecularGlossinessMaterial.prototype.clone = function (name) {
  42829. var _this = this;
  42830. var clone = BABYLON.SerializationHelper.Clone(function () { return new PBRSpecularGlossinessMaterial(name, _this.getScene()); }, this);
  42831. clone.id = name;
  42832. clone.name = name;
  42833. return clone;
  42834. };
  42835. /**
  42836. * Serialize the material to a parsable JSON object.
  42837. */
  42838. PBRSpecularGlossinessMaterial.prototype.serialize = function () {
  42839. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  42840. serializationObject.customType = "BABYLON.PBRSpecularGlossinessMaterial";
  42841. return serializationObject;
  42842. };
  42843. /**
  42844. * Parses a JSON object correponding to the serialize function.
  42845. */
  42846. PBRSpecularGlossinessMaterial.Parse = function (source, scene, rootUrl) {
  42847. return BABYLON.SerializationHelper.Parse(function () { return new PBRSpecularGlossinessMaterial(source.name, scene); }, source, scene, rootUrl);
  42848. };
  42849. __decorate([
  42850. BABYLON.serializeAsColor3("diffuse"),
  42851. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_albedoColor")
  42852. ], PBRSpecularGlossinessMaterial.prototype, "diffuseColor", void 0);
  42853. __decorate([
  42854. BABYLON.serializeAsTexture(),
  42855. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_albedoTexture")
  42856. ], PBRSpecularGlossinessMaterial.prototype, "diffuseTexture", void 0);
  42857. __decorate([
  42858. BABYLON.serializeAsColor3("specular"),
  42859. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_reflectivityColor")
  42860. ], PBRSpecularGlossinessMaterial.prototype, "specularColor", void 0);
  42861. __decorate([
  42862. BABYLON.serialize(),
  42863. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_microSurface")
  42864. ], PBRSpecularGlossinessMaterial.prototype, "glossiness", void 0);
  42865. __decorate([
  42866. BABYLON.serializeAsTexture(),
  42867. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_reflectivityTexture")
  42868. ], PBRSpecularGlossinessMaterial.prototype, "specularGlossinessTexture", void 0);
  42869. return PBRSpecularGlossinessMaterial;
  42870. }(BABYLON.PBRBaseSimpleMaterial));
  42871. BABYLON.PBRSpecularGlossinessMaterial = PBRSpecularGlossinessMaterial;
  42872. })(BABYLON || (BABYLON = {}));
  42873. //# sourceMappingURL=babylon.pbrSpecularGlossinessMaterial.js.map
  42874. var BABYLON;
  42875. (function (BABYLON) {
  42876. BABYLON.CameraInputTypes = {};
  42877. var CameraInputsManager = /** @class */ (function () {
  42878. function CameraInputsManager(camera) {
  42879. this.attached = {};
  42880. this.camera = camera;
  42881. this.checkInputs = function () { };
  42882. }
  42883. /**
  42884. * Add an input method to a camera.
  42885. * builtin inputs example: camera.inputs.addGamepad();
  42886. * custom inputs example: camera.inputs.add(new BABYLON.FreeCameraGamepadInput());
  42887. * @param input camera input method
  42888. */
  42889. CameraInputsManager.prototype.add = function (input) {
  42890. var type = input.getSimpleName();
  42891. if (this.attached[type]) {
  42892. BABYLON.Tools.Warn("camera input of type " + type + " already exists on camera");
  42893. return;
  42894. }
  42895. this.attached[type] = input;
  42896. input.camera = this.camera;
  42897. //for checkInputs, we are dynamically creating a function
  42898. //the goal is to avoid the performance penalty of looping for inputs in the render loop
  42899. if (input.checkInputs) {
  42900. this.checkInputs = this._addCheckInputs(input.checkInputs.bind(input));
  42901. }
  42902. if (this.attachedElement) {
  42903. input.attachControl(this.attachedElement);
  42904. }
  42905. };
  42906. /**
  42907. * Remove a specific input method from a camera
  42908. * example: camera.inputs.remove(camera.inputs.attached.mouse);
  42909. * @param inputToRemove camera input method
  42910. */
  42911. CameraInputsManager.prototype.remove = function (inputToRemove) {
  42912. for (var cam in this.attached) {
  42913. var input = this.attached[cam];
  42914. if (input === inputToRemove) {
  42915. input.detachControl(this.attachedElement);
  42916. input.camera = null;
  42917. delete this.attached[cam];
  42918. this.rebuildInputCheck();
  42919. }
  42920. }
  42921. };
  42922. CameraInputsManager.prototype.removeByType = function (inputType) {
  42923. for (var cam in this.attached) {
  42924. var input = this.attached[cam];
  42925. if (input.getClassName() === inputType) {
  42926. input.detachControl(this.attachedElement);
  42927. input.camera = null;
  42928. delete this.attached[cam];
  42929. this.rebuildInputCheck();
  42930. }
  42931. }
  42932. };
  42933. CameraInputsManager.prototype._addCheckInputs = function (fn) {
  42934. var current = this.checkInputs;
  42935. return function () {
  42936. current();
  42937. fn();
  42938. };
  42939. };
  42940. CameraInputsManager.prototype.attachInput = function (input) {
  42941. if (this.attachedElement) {
  42942. input.attachControl(this.attachedElement, this.noPreventDefault);
  42943. }
  42944. };
  42945. CameraInputsManager.prototype.attachElement = function (element, noPreventDefault) {
  42946. if (noPreventDefault === void 0) { noPreventDefault = false; }
  42947. if (this.attachedElement) {
  42948. return;
  42949. }
  42950. noPreventDefault = BABYLON.Camera.ForceAttachControlToAlwaysPreventDefault ? false : noPreventDefault;
  42951. this.attachedElement = element;
  42952. this.noPreventDefault = noPreventDefault;
  42953. for (var cam in this.attached) {
  42954. this.attached[cam].attachControl(element, noPreventDefault);
  42955. }
  42956. };
  42957. CameraInputsManager.prototype.detachElement = function (element, disconnect) {
  42958. if (disconnect === void 0) { disconnect = false; }
  42959. if (this.attachedElement !== element) {
  42960. return;
  42961. }
  42962. for (var cam in this.attached) {
  42963. this.attached[cam].detachControl(element);
  42964. if (disconnect) {
  42965. this.attached[cam].camera = null;
  42966. }
  42967. }
  42968. this.attachedElement = null;
  42969. };
  42970. CameraInputsManager.prototype.rebuildInputCheck = function () {
  42971. this.checkInputs = function () { };
  42972. for (var cam in this.attached) {
  42973. var input = this.attached[cam];
  42974. if (input.checkInputs) {
  42975. this.checkInputs = this._addCheckInputs(input.checkInputs.bind(input));
  42976. }
  42977. }
  42978. };
  42979. /**
  42980. * Remove all attached input methods from a camera
  42981. */
  42982. CameraInputsManager.prototype.clear = function () {
  42983. if (this.attachedElement) {
  42984. this.detachElement(this.attachedElement, true);
  42985. }
  42986. this.attached = {};
  42987. this.attachedElement = null;
  42988. this.checkInputs = function () { };
  42989. };
  42990. CameraInputsManager.prototype.serialize = function (serializedCamera) {
  42991. var inputs = {};
  42992. for (var cam in this.attached) {
  42993. var input = this.attached[cam];
  42994. var res = BABYLON.SerializationHelper.Serialize(input);
  42995. inputs[input.getClassName()] = res;
  42996. }
  42997. serializedCamera.inputsmgr = inputs;
  42998. };
  42999. CameraInputsManager.prototype.parse = function (parsedCamera) {
  43000. var parsedInputs = parsedCamera.inputsmgr;
  43001. if (parsedInputs) {
  43002. this.clear();
  43003. for (var n in parsedInputs) {
  43004. var construct = BABYLON.CameraInputTypes[n];
  43005. if (construct) {
  43006. var parsedinput = parsedInputs[n];
  43007. var input = BABYLON.SerializationHelper.Parse(function () { return new construct(); }, parsedinput, null);
  43008. this.add(input);
  43009. }
  43010. }
  43011. }
  43012. else {
  43013. //2016-03-08 this part is for managing backward compatibility
  43014. for (var n in this.attached) {
  43015. var construct = BABYLON.CameraInputTypes[this.attached[n].getClassName()];
  43016. if (construct) {
  43017. var input = BABYLON.SerializationHelper.Parse(function () { return new construct(); }, parsedCamera, null);
  43018. this.remove(this.attached[n]);
  43019. this.add(input);
  43020. }
  43021. }
  43022. }
  43023. };
  43024. return CameraInputsManager;
  43025. }());
  43026. BABYLON.CameraInputsManager = CameraInputsManager;
  43027. })(BABYLON || (BABYLON = {}));
  43028. //# sourceMappingURL=babylon.cameraInputsManager.js.map
  43029. var BABYLON;
  43030. (function (BABYLON) {
  43031. var TargetCamera = /** @class */ (function (_super) {
  43032. __extends(TargetCamera, _super);
  43033. function TargetCamera(name, position, scene) {
  43034. var _this = _super.call(this, name, position, scene) || this;
  43035. _this.cameraDirection = new BABYLON.Vector3(0, 0, 0);
  43036. _this.cameraRotation = new BABYLON.Vector2(0, 0);
  43037. _this.rotation = new BABYLON.Vector3(0, 0, 0);
  43038. _this.speed = 2.0;
  43039. _this.noRotationConstraint = false;
  43040. _this.lockedTarget = null;
  43041. _this._currentTarget = BABYLON.Vector3.Zero();
  43042. _this._viewMatrix = BABYLON.Matrix.Zero();
  43043. _this._camMatrix = BABYLON.Matrix.Zero();
  43044. _this._cameraTransformMatrix = BABYLON.Matrix.Zero();
  43045. _this._cameraRotationMatrix = BABYLON.Matrix.Zero();
  43046. _this._referencePoint = new BABYLON.Vector3(0, 0, 1);
  43047. _this._currentUpVector = new BABYLON.Vector3(0, 1, 0);
  43048. _this._transformedReferencePoint = BABYLON.Vector3.Zero();
  43049. _this._lookAtTemp = BABYLON.Matrix.Zero();
  43050. _this._tempMatrix = BABYLON.Matrix.Zero();
  43051. return _this;
  43052. }
  43053. TargetCamera.prototype.getFrontPosition = function (distance) {
  43054. this.getWorldMatrix();
  43055. var direction = this.getTarget().subtract(this.position);
  43056. direction.normalize();
  43057. direction.scaleInPlace(distance);
  43058. return this.globalPosition.add(direction);
  43059. };
  43060. TargetCamera.prototype._getLockedTargetPosition = function () {
  43061. if (!this.lockedTarget) {
  43062. return null;
  43063. }
  43064. if (this.lockedTarget.absolutePosition) {
  43065. this.lockedTarget.computeWorldMatrix();
  43066. }
  43067. return this.lockedTarget.absolutePosition || this.lockedTarget;
  43068. };
  43069. TargetCamera.prototype.storeState = function () {
  43070. this._storedPosition = this.position.clone();
  43071. this._storedRotation = this.rotation.clone();
  43072. if (this.rotationQuaternion) {
  43073. this._storedRotationQuaternion = this.rotationQuaternion.clone();
  43074. }
  43075. return _super.prototype.storeState.call(this);
  43076. };
  43077. /**
  43078. * Restored camera state. You must call storeState() first
  43079. */
  43080. TargetCamera.prototype._restoreStateValues = function () {
  43081. if (!_super.prototype._restoreStateValues.call(this)) {
  43082. return false;
  43083. }
  43084. this.position = this._storedPosition.clone();
  43085. this.rotation = this._storedRotation.clone();
  43086. if (this.rotationQuaternion) {
  43087. this.rotationQuaternion = this._storedRotationQuaternion.clone();
  43088. }
  43089. this.cameraDirection.copyFromFloats(0, 0, 0);
  43090. this.cameraRotation.copyFromFloats(0, 0);
  43091. return true;
  43092. };
  43093. // Cache
  43094. TargetCamera.prototype._initCache = function () {
  43095. _super.prototype._initCache.call(this);
  43096. this._cache.lockedTarget = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  43097. this._cache.rotation = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  43098. this._cache.rotationQuaternion = new BABYLON.Quaternion(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  43099. };
  43100. TargetCamera.prototype._updateCache = function (ignoreParentClass) {
  43101. if (!ignoreParentClass) {
  43102. _super.prototype._updateCache.call(this);
  43103. }
  43104. var lockedTargetPosition = this._getLockedTargetPosition();
  43105. if (!lockedTargetPosition) {
  43106. this._cache.lockedTarget = null;
  43107. }
  43108. else {
  43109. if (!this._cache.lockedTarget) {
  43110. this._cache.lockedTarget = lockedTargetPosition.clone();
  43111. }
  43112. else {
  43113. this._cache.lockedTarget.copyFrom(lockedTargetPosition);
  43114. }
  43115. }
  43116. this._cache.rotation.copyFrom(this.rotation);
  43117. if (this.rotationQuaternion)
  43118. this._cache.rotationQuaternion.copyFrom(this.rotationQuaternion);
  43119. };
  43120. // Synchronized
  43121. TargetCamera.prototype._isSynchronizedViewMatrix = function () {
  43122. if (!_super.prototype._isSynchronizedViewMatrix.call(this)) {
  43123. return false;
  43124. }
  43125. var lockedTargetPosition = this._getLockedTargetPosition();
  43126. return (this._cache.lockedTarget ? this._cache.lockedTarget.equals(lockedTargetPosition) : !lockedTargetPosition)
  43127. && (this.rotationQuaternion ? this.rotationQuaternion.equals(this._cache.rotationQuaternion) : this._cache.rotation.equals(this.rotation));
  43128. };
  43129. // Methods
  43130. TargetCamera.prototype._computeLocalCameraSpeed = function () {
  43131. var engine = this.getEngine();
  43132. return this.speed * Math.sqrt((engine.getDeltaTime() / (engine.getFps() * 100.0)));
  43133. };
  43134. // Target
  43135. TargetCamera.prototype.setTarget = function (target) {
  43136. this.upVector.normalize();
  43137. BABYLON.Matrix.LookAtLHToRef(this.position, target, this.upVector, this._camMatrix);
  43138. this._camMatrix.invert();
  43139. this.rotation.x = Math.atan(this._camMatrix.m[6] / this._camMatrix.m[10]);
  43140. var vDir = target.subtract(this.position);
  43141. if (vDir.x >= 0.0) {
  43142. this.rotation.y = (-Math.atan(vDir.z / vDir.x) + Math.PI / 2.0);
  43143. }
  43144. else {
  43145. this.rotation.y = (-Math.atan(vDir.z / vDir.x) - Math.PI / 2.0);
  43146. }
  43147. this.rotation.z = 0;
  43148. if (isNaN(this.rotation.x)) {
  43149. this.rotation.x = 0;
  43150. }
  43151. if (isNaN(this.rotation.y)) {
  43152. this.rotation.y = 0;
  43153. }
  43154. if (isNaN(this.rotation.z)) {
  43155. this.rotation.z = 0;
  43156. }
  43157. if (this.rotationQuaternion) {
  43158. BABYLON.Quaternion.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this.rotationQuaternion);
  43159. }
  43160. };
  43161. /**
  43162. * Return the current target position of the camera. This value is expressed in local space.
  43163. */
  43164. TargetCamera.prototype.getTarget = function () {
  43165. return this._currentTarget;
  43166. };
  43167. TargetCamera.prototype._decideIfNeedsToMove = function () {
  43168. return Math.abs(this.cameraDirection.x) > 0 || Math.abs(this.cameraDirection.y) > 0 || Math.abs(this.cameraDirection.z) > 0;
  43169. };
  43170. TargetCamera.prototype._updatePosition = function () {
  43171. if (this.parent) {
  43172. this.parent.getWorldMatrix().invertToRef(BABYLON.Tmp.Matrix[0]);
  43173. BABYLON.Vector3.TransformNormalToRef(this.cameraDirection, BABYLON.Tmp.Matrix[0], BABYLON.Tmp.Vector3[0]);
  43174. this.position.addInPlace(BABYLON.Tmp.Vector3[0]);
  43175. return;
  43176. }
  43177. this.position.addInPlace(this.cameraDirection);
  43178. };
  43179. TargetCamera.prototype._checkInputs = function () {
  43180. var needToMove = this._decideIfNeedsToMove();
  43181. var needToRotate = Math.abs(this.cameraRotation.x) > 0 || Math.abs(this.cameraRotation.y) > 0;
  43182. // Move
  43183. if (needToMove) {
  43184. this._updatePosition();
  43185. }
  43186. // Rotate
  43187. if (needToRotate) {
  43188. this.rotation.x += this.cameraRotation.x;
  43189. this.rotation.y += this.cameraRotation.y;
  43190. //rotate, if quaternion is set and rotation was used
  43191. if (this.rotationQuaternion) {
  43192. var len = this.rotation.lengthSquared();
  43193. if (len) {
  43194. BABYLON.Quaternion.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this.rotationQuaternion);
  43195. }
  43196. }
  43197. if (!this.noRotationConstraint) {
  43198. var limit = (Math.PI / 2) * 0.95;
  43199. if (this.rotation.x > limit)
  43200. this.rotation.x = limit;
  43201. if (this.rotation.x < -limit)
  43202. this.rotation.x = -limit;
  43203. }
  43204. }
  43205. // Inertia
  43206. if (needToMove) {
  43207. if (Math.abs(this.cameraDirection.x) < this.speed * BABYLON.Epsilon) {
  43208. this.cameraDirection.x = 0;
  43209. }
  43210. if (Math.abs(this.cameraDirection.y) < this.speed * BABYLON.Epsilon) {
  43211. this.cameraDirection.y = 0;
  43212. }
  43213. if (Math.abs(this.cameraDirection.z) < this.speed * BABYLON.Epsilon) {
  43214. this.cameraDirection.z = 0;
  43215. }
  43216. this.cameraDirection.scaleInPlace(this.inertia);
  43217. }
  43218. if (needToRotate) {
  43219. if (Math.abs(this.cameraRotation.x) < this.speed * BABYLON.Epsilon) {
  43220. this.cameraRotation.x = 0;
  43221. }
  43222. if (Math.abs(this.cameraRotation.y) < this.speed * BABYLON.Epsilon) {
  43223. this.cameraRotation.y = 0;
  43224. }
  43225. this.cameraRotation.scaleInPlace(this.inertia);
  43226. }
  43227. _super.prototype._checkInputs.call(this);
  43228. };
  43229. TargetCamera.prototype._updateCameraRotationMatrix = function () {
  43230. if (this.rotationQuaternion) {
  43231. this.rotationQuaternion.toRotationMatrix(this._cameraRotationMatrix);
  43232. }
  43233. else {
  43234. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this._cameraRotationMatrix);
  43235. }
  43236. //update the up vector!
  43237. BABYLON.Vector3.TransformNormalToRef(this.upVector, this._cameraRotationMatrix, this._currentUpVector);
  43238. };
  43239. TargetCamera.prototype._getViewMatrix = function () {
  43240. if (this.lockedTarget) {
  43241. this.setTarget(this._getLockedTargetPosition());
  43242. }
  43243. // Compute
  43244. this._updateCameraRotationMatrix();
  43245. BABYLON.Vector3.TransformCoordinatesToRef(this._referencePoint, this._cameraRotationMatrix, this._transformedReferencePoint);
  43246. // Computing target and final matrix
  43247. this.position.addToRef(this._transformedReferencePoint, this._currentTarget);
  43248. if (this.getScene().useRightHandedSystem) {
  43249. BABYLON.Matrix.LookAtRHToRef(this.position, this._currentTarget, this._currentUpVector, this._viewMatrix);
  43250. }
  43251. else {
  43252. BABYLON.Matrix.LookAtLHToRef(this.position, this._currentTarget, this._currentUpVector, this._viewMatrix);
  43253. }
  43254. return this._viewMatrix;
  43255. };
  43256. /**
  43257. * @override
  43258. * Override Camera.createRigCamera
  43259. */
  43260. TargetCamera.prototype.createRigCamera = function (name, cameraIndex) {
  43261. if (this.cameraRigMode !== BABYLON.Camera.RIG_MODE_NONE) {
  43262. var rigCamera = new TargetCamera(name, this.position.clone(), this.getScene());
  43263. if (this.cameraRigMode === BABYLON.Camera.RIG_MODE_VR || this.cameraRigMode === BABYLON.Camera.RIG_MODE_WEBVR) {
  43264. if (!this.rotationQuaternion) {
  43265. this.rotationQuaternion = new BABYLON.Quaternion();
  43266. }
  43267. rigCamera._cameraRigParams = {};
  43268. rigCamera.rotationQuaternion = new BABYLON.Quaternion();
  43269. }
  43270. return rigCamera;
  43271. }
  43272. return null;
  43273. };
  43274. /**
  43275. * @override
  43276. * Override Camera._updateRigCameras
  43277. */
  43278. TargetCamera.prototype._updateRigCameras = function () {
  43279. var camLeft = this._rigCameras[0];
  43280. var camRight = this._rigCameras[1];
  43281. switch (this.cameraRigMode) {
  43282. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  43283. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  43284. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  43285. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  43286. //provisionnaly using _cameraRigParams.stereoHalfAngle instead of calculations based on _cameraRigParams.interaxialDistance:
  43287. var leftSign = (this.cameraRigMode === BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED) ? 1 : -1;
  43288. var rightSign = (this.cameraRigMode === BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED) ? -1 : 1;
  43289. this._getRigCamPosition(this._cameraRigParams.stereoHalfAngle * leftSign, camLeft.position);
  43290. this._getRigCamPosition(this._cameraRigParams.stereoHalfAngle * rightSign, camRight.position);
  43291. camLeft.setTarget(this.getTarget());
  43292. camRight.setTarget(this.getTarget());
  43293. break;
  43294. case BABYLON.Camera.RIG_MODE_VR:
  43295. if (camLeft.rotationQuaternion) {
  43296. camLeft.rotationQuaternion.copyFrom(this.rotationQuaternion);
  43297. camRight.rotationQuaternion.copyFrom(this.rotationQuaternion);
  43298. }
  43299. else {
  43300. camLeft.rotation.copyFrom(this.rotation);
  43301. camRight.rotation.copyFrom(this.rotation);
  43302. }
  43303. camLeft.position.copyFrom(this.position);
  43304. camRight.position.copyFrom(this.position);
  43305. break;
  43306. }
  43307. _super.prototype._updateRigCameras.call(this);
  43308. };
  43309. TargetCamera.prototype._getRigCamPosition = function (halfSpace, result) {
  43310. if (!this._rigCamTransformMatrix) {
  43311. this._rigCamTransformMatrix = new BABYLON.Matrix();
  43312. }
  43313. var target = this.getTarget();
  43314. BABYLON.Matrix.Translation(-target.x, -target.y, -target.z).multiplyToRef(BABYLON.Matrix.RotationY(halfSpace), this._rigCamTransformMatrix);
  43315. this._rigCamTransformMatrix = this._rigCamTransformMatrix.multiply(BABYLON.Matrix.Translation(target.x, target.y, target.z));
  43316. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this._rigCamTransformMatrix, result);
  43317. };
  43318. TargetCamera.prototype.getClassName = function () {
  43319. return "TargetCamera";
  43320. };
  43321. __decorate([
  43322. BABYLON.serializeAsVector3()
  43323. ], TargetCamera.prototype, "rotation", void 0);
  43324. __decorate([
  43325. BABYLON.serialize()
  43326. ], TargetCamera.prototype, "speed", void 0);
  43327. __decorate([
  43328. BABYLON.serializeAsMeshReference("lockedTargetId")
  43329. ], TargetCamera.prototype, "lockedTarget", void 0);
  43330. return TargetCamera;
  43331. }(BABYLON.Camera));
  43332. BABYLON.TargetCamera = TargetCamera;
  43333. })(BABYLON || (BABYLON = {}));
  43334. //# sourceMappingURL=babylon.targetCamera.js.map
  43335. var BABYLON;
  43336. (function (BABYLON) {
  43337. var FreeCameraMouseInput = /** @class */ (function () {
  43338. function FreeCameraMouseInput(touchEnabled) {
  43339. if (touchEnabled === void 0) { touchEnabled = true; }
  43340. this.touchEnabled = touchEnabled;
  43341. this.buttons = [0, 1, 2];
  43342. this.angularSensibility = 2000.0;
  43343. this.previousPosition = null;
  43344. }
  43345. FreeCameraMouseInput.prototype.attachControl = function (element, noPreventDefault) {
  43346. var _this = this;
  43347. var engine = this.camera.getEngine();
  43348. if (!this._pointerInput) {
  43349. this._pointerInput = function (p, s) {
  43350. var evt = p.event;
  43351. if (engine.isInVRExclusivePointerMode) {
  43352. return;
  43353. }
  43354. if (!_this.touchEnabled && evt.pointerType === "touch") {
  43355. return;
  43356. }
  43357. if (p.type !== BABYLON.PointerEventTypes.POINTERMOVE && _this.buttons.indexOf(evt.button) === -1) {
  43358. return;
  43359. }
  43360. var srcElement = (evt.srcElement || evt.target);
  43361. if (p.type === BABYLON.PointerEventTypes.POINTERDOWN && srcElement) {
  43362. try {
  43363. srcElement.setPointerCapture(evt.pointerId);
  43364. }
  43365. catch (e) {
  43366. //Nothing to do with the error. Execution will continue.
  43367. }
  43368. _this.previousPosition = {
  43369. x: evt.clientX,
  43370. y: evt.clientY
  43371. };
  43372. if (!noPreventDefault) {
  43373. evt.preventDefault();
  43374. element.focus();
  43375. }
  43376. }
  43377. else if (p.type === BABYLON.PointerEventTypes.POINTERUP && srcElement) {
  43378. try {
  43379. srcElement.releasePointerCapture(evt.pointerId);
  43380. }
  43381. catch (e) {
  43382. //Nothing to do with the error.
  43383. }
  43384. _this.previousPosition = null;
  43385. if (!noPreventDefault) {
  43386. evt.preventDefault();
  43387. }
  43388. }
  43389. else if (p.type === BABYLON.PointerEventTypes.POINTERMOVE) {
  43390. if (!_this.previousPosition || engine.isPointerLock) {
  43391. return;
  43392. }
  43393. var offsetX = evt.clientX - _this.previousPosition.x;
  43394. var offsetY = evt.clientY - _this.previousPosition.y;
  43395. if (_this.camera.getScene().useRightHandedSystem) {
  43396. _this.camera.cameraRotation.y -= offsetX / _this.angularSensibility;
  43397. }
  43398. else {
  43399. _this.camera.cameraRotation.y += offsetX / _this.angularSensibility;
  43400. }
  43401. _this.camera.cameraRotation.x += offsetY / _this.angularSensibility;
  43402. _this.previousPosition = {
  43403. x: evt.clientX,
  43404. y: evt.clientY
  43405. };
  43406. if (!noPreventDefault) {
  43407. evt.preventDefault();
  43408. }
  43409. }
  43410. };
  43411. }
  43412. this._onMouseMove = function (evt) {
  43413. if (!engine.isPointerLock) {
  43414. return;
  43415. }
  43416. if (engine.isInVRExclusivePointerMode) {
  43417. return;
  43418. }
  43419. var offsetX = evt.movementX || evt.mozMovementX || evt.webkitMovementX || evt.msMovementX || 0;
  43420. var offsetY = evt.movementY || evt.mozMovementY || evt.webkitMovementY || evt.msMovementY || 0;
  43421. if (_this.camera.getScene().useRightHandedSystem) {
  43422. _this.camera.cameraRotation.y -= offsetX / _this.angularSensibility;
  43423. }
  43424. else {
  43425. _this.camera.cameraRotation.y += offsetX / _this.angularSensibility;
  43426. }
  43427. _this.camera.cameraRotation.x += offsetY / _this.angularSensibility;
  43428. _this.previousPosition = null;
  43429. if (!noPreventDefault) {
  43430. evt.preventDefault();
  43431. }
  43432. };
  43433. this._observer = this.camera.getScene().onPointerObservable.add(this._pointerInput, BABYLON.PointerEventTypes.POINTERDOWN | BABYLON.PointerEventTypes.POINTERUP | BABYLON.PointerEventTypes.POINTERMOVE);
  43434. element.addEventListener("mousemove", this._onMouseMove, false);
  43435. };
  43436. FreeCameraMouseInput.prototype.detachControl = function (element) {
  43437. if (this._observer && element) {
  43438. this.camera.getScene().onPointerObservable.remove(this._observer);
  43439. if (this._onMouseMove) {
  43440. element.removeEventListener("mousemove", this._onMouseMove);
  43441. }
  43442. this._observer = null;
  43443. this._onMouseMove = null;
  43444. this.previousPosition = null;
  43445. }
  43446. };
  43447. FreeCameraMouseInput.prototype.getClassName = function () {
  43448. return "FreeCameraMouseInput";
  43449. };
  43450. FreeCameraMouseInput.prototype.getSimpleName = function () {
  43451. return "mouse";
  43452. };
  43453. __decorate([
  43454. BABYLON.serialize()
  43455. ], FreeCameraMouseInput.prototype, "buttons", void 0);
  43456. __decorate([
  43457. BABYLON.serialize()
  43458. ], FreeCameraMouseInput.prototype, "angularSensibility", void 0);
  43459. return FreeCameraMouseInput;
  43460. }());
  43461. BABYLON.FreeCameraMouseInput = FreeCameraMouseInput;
  43462. BABYLON.CameraInputTypes["FreeCameraMouseInput"] = FreeCameraMouseInput;
  43463. })(BABYLON || (BABYLON = {}));
  43464. //# sourceMappingURL=babylon.freeCameraMouseInput.js.map
  43465. var BABYLON;
  43466. (function (BABYLON) {
  43467. var FreeCameraKeyboardMoveInput = /** @class */ (function () {
  43468. function FreeCameraKeyboardMoveInput() {
  43469. this._keys = new Array();
  43470. this.keysUp = [38];
  43471. this.keysDown = [40];
  43472. this.keysLeft = [37];
  43473. this.keysRight = [39];
  43474. }
  43475. FreeCameraKeyboardMoveInput.prototype.attachControl = function (element, noPreventDefault) {
  43476. var _this = this;
  43477. if (this._onCanvasBlurObserver) {
  43478. return;
  43479. }
  43480. this._scene = this.camera.getScene();
  43481. this._engine = this._scene.getEngine();
  43482. this._onCanvasBlurObserver = this._engine.onCanvasBlurObservable.add(function () {
  43483. _this._keys = [];
  43484. });
  43485. this._onKeyboardObserver = this._scene.onKeyboardObservable.add(function (info) {
  43486. var evt = info.event;
  43487. if (info.type === BABYLON.KeyboardEventTypes.KEYDOWN) {
  43488. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  43489. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  43490. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  43491. _this.keysRight.indexOf(evt.keyCode) !== -1) {
  43492. var index = _this._keys.indexOf(evt.keyCode);
  43493. if (index === -1) {
  43494. _this._keys.push(evt.keyCode);
  43495. }
  43496. if (!noPreventDefault) {
  43497. evt.preventDefault();
  43498. }
  43499. }
  43500. }
  43501. else {
  43502. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  43503. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  43504. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  43505. _this.keysRight.indexOf(evt.keyCode) !== -1) {
  43506. var index = _this._keys.indexOf(evt.keyCode);
  43507. if (index >= 0) {
  43508. _this._keys.splice(index, 1);
  43509. }
  43510. if (!noPreventDefault) {
  43511. evt.preventDefault();
  43512. }
  43513. }
  43514. }
  43515. });
  43516. };
  43517. FreeCameraKeyboardMoveInput.prototype.detachControl = function (element) {
  43518. if (this._scene) {
  43519. if (this._onKeyboardObserver) {
  43520. this._scene.onKeyboardObservable.remove(this._onKeyboardObserver);
  43521. }
  43522. if (this._onCanvasBlurObserver) {
  43523. this._engine.onCanvasBlurObservable.remove(this._onCanvasBlurObserver);
  43524. }
  43525. this._onKeyboardObserver = null;
  43526. this._onCanvasBlurObserver = null;
  43527. }
  43528. this._keys = [];
  43529. };
  43530. FreeCameraKeyboardMoveInput.prototype.checkInputs = function () {
  43531. if (this._onKeyboardObserver) {
  43532. var camera = this.camera;
  43533. // Keyboard
  43534. for (var index = 0; index < this._keys.length; index++) {
  43535. var keyCode = this._keys[index];
  43536. var speed = camera._computeLocalCameraSpeed();
  43537. if (this.keysLeft.indexOf(keyCode) !== -1) {
  43538. camera._localDirection.copyFromFloats(-speed, 0, 0);
  43539. }
  43540. else if (this.keysUp.indexOf(keyCode) !== -1) {
  43541. camera._localDirection.copyFromFloats(0, 0, speed);
  43542. }
  43543. else if (this.keysRight.indexOf(keyCode) !== -1) {
  43544. camera._localDirection.copyFromFloats(speed, 0, 0);
  43545. }
  43546. else if (this.keysDown.indexOf(keyCode) !== -1) {
  43547. camera._localDirection.copyFromFloats(0, 0, -speed);
  43548. }
  43549. if (camera.getScene().useRightHandedSystem) {
  43550. camera._localDirection.z *= -1;
  43551. }
  43552. camera.getViewMatrix().invertToRef(camera._cameraTransformMatrix);
  43553. BABYLON.Vector3.TransformNormalToRef(camera._localDirection, camera._cameraTransformMatrix, camera._transformedDirection);
  43554. camera.cameraDirection.addInPlace(camera._transformedDirection);
  43555. }
  43556. }
  43557. };
  43558. FreeCameraKeyboardMoveInput.prototype.getClassName = function () {
  43559. return "FreeCameraKeyboardMoveInput";
  43560. };
  43561. FreeCameraKeyboardMoveInput.prototype._onLostFocus = function (e) {
  43562. this._keys = [];
  43563. };
  43564. FreeCameraKeyboardMoveInput.prototype.getSimpleName = function () {
  43565. return "keyboard";
  43566. };
  43567. __decorate([
  43568. BABYLON.serialize()
  43569. ], FreeCameraKeyboardMoveInput.prototype, "keysUp", void 0);
  43570. __decorate([
  43571. BABYLON.serialize()
  43572. ], FreeCameraKeyboardMoveInput.prototype, "keysDown", void 0);
  43573. __decorate([
  43574. BABYLON.serialize()
  43575. ], FreeCameraKeyboardMoveInput.prototype, "keysLeft", void 0);
  43576. __decorate([
  43577. BABYLON.serialize()
  43578. ], FreeCameraKeyboardMoveInput.prototype, "keysRight", void 0);
  43579. return FreeCameraKeyboardMoveInput;
  43580. }());
  43581. BABYLON.FreeCameraKeyboardMoveInput = FreeCameraKeyboardMoveInput;
  43582. BABYLON.CameraInputTypes["FreeCameraKeyboardMoveInput"] = FreeCameraKeyboardMoveInput;
  43583. })(BABYLON || (BABYLON = {}));
  43584. //# sourceMappingURL=babylon.freeCameraKeyboardMoveInput.js.map
  43585. var BABYLON;
  43586. (function (BABYLON) {
  43587. var FreeCameraInputsManager = /** @class */ (function (_super) {
  43588. __extends(FreeCameraInputsManager, _super);
  43589. function FreeCameraInputsManager(camera) {
  43590. return _super.call(this, camera) || this;
  43591. }
  43592. FreeCameraInputsManager.prototype.addKeyboard = function () {
  43593. this.add(new BABYLON.FreeCameraKeyboardMoveInput());
  43594. return this;
  43595. };
  43596. FreeCameraInputsManager.prototype.addMouse = function (touchEnabled) {
  43597. if (touchEnabled === void 0) { touchEnabled = true; }
  43598. this.add(new BABYLON.FreeCameraMouseInput(touchEnabled));
  43599. return this;
  43600. };
  43601. FreeCameraInputsManager.prototype.addGamepad = function () {
  43602. this.add(new BABYLON.FreeCameraGamepadInput());
  43603. return this;
  43604. };
  43605. FreeCameraInputsManager.prototype.addDeviceOrientation = function () {
  43606. this.add(new BABYLON.FreeCameraDeviceOrientationInput());
  43607. return this;
  43608. };
  43609. FreeCameraInputsManager.prototype.addTouch = function () {
  43610. this.add(new BABYLON.FreeCameraTouchInput());
  43611. return this;
  43612. };
  43613. FreeCameraInputsManager.prototype.addVirtualJoystick = function () {
  43614. this.add(new BABYLON.FreeCameraVirtualJoystickInput());
  43615. return this;
  43616. };
  43617. return FreeCameraInputsManager;
  43618. }(BABYLON.CameraInputsManager));
  43619. BABYLON.FreeCameraInputsManager = FreeCameraInputsManager;
  43620. })(BABYLON || (BABYLON = {}));
  43621. //# sourceMappingURL=babylon.freeCameraInputsManager.js.map
  43622. var BABYLON;
  43623. (function (BABYLON) {
  43624. var FreeCamera = /** @class */ (function (_super) {
  43625. __extends(FreeCamera, _super);
  43626. function FreeCamera(name, position, scene) {
  43627. var _this = _super.call(this, name, position, scene) || this;
  43628. _this.ellipsoid = new BABYLON.Vector3(0.5, 1, 0.5);
  43629. _this.ellipsoidOffset = new BABYLON.Vector3(0, 0, 0);
  43630. _this.checkCollisions = false;
  43631. _this.applyGravity = false;
  43632. _this._needMoveForGravity = false;
  43633. _this._oldPosition = BABYLON.Vector3.Zero();
  43634. _this._diffPosition = BABYLON.Vector3.Zero();
  43635. _this._newPosition = BABYLON.Vector3.Zero();
  43636. // Collisions
  43637. _this._collisionMask = -1;
  43638. _this._onCollisionPositionChange = function (collisionId, newPosition, collidedMesh) {
  43639. if (collidedMesh === void 0) { collidedMesh = null; }
  43640. //TODO move this to the collision coordinator!
  43641. if (_this.getScene().workerCollisions)
  43642. newPosition.multiplyInPlace(_this._collider._radius);
  43643. var updatePosition = function (newPos) {
  43644. _this._newPosition.copyFrom(newPos);
  43645. _this._newPosition.subtractToRef(_this._oldPosition, _this._diffPosition);
  43646. if (_this._diffPosition.length() > BABYLON.Engine.CollisionsEpsilon) {
  43647. _this.position.addInPlace(_this._diffPosition);
  43648. if (_this.onCollide && collidedMesh) {
  43649. _this.onCollide(collidedMesh);
  43650. }
  43651. }
  43652. };
  43653. updatePosition(newPosition);
  43654. };
  43655. _this.inputs = new BABYLON.FreeCameraInputsManager(_this);
  43656. _this.inputs.addKeyboard().addMouse();
  43657. return _this;
  43658. }
  43659. Object.defineProperty(FreeCamera.prototype, "angularSensibility", {
  43660. //-- begin properties for backward compatibility for inputs
  43661. /**
  43662. * Gets the input sensibility for a mouse input. (default is 2000.0)
  43663. * Higher values reduce sensitivity.
  43664. */
  43665. get: function () {
  43666. var mouse = this.inputs.attached["mouse"];
  43667. if (mouse)
  43668. return mouse.angularSensibility;
  43669. return 0;
  43670. },
  43671. /**
  43672. * Sets the input sensibility for a mouse input. (default is 2000.0)
  43673. * Higher values reduce sensitivity.
  43674. */
  43675. set: function (value) {
  43676. var mouse = this.inputs.attached["mouse"];
  43677. if (mouse)
  43678. mouse.angularSensibility = value;
  43679. },
  43680. enumerable: true,
  43681. configurable: true
  43682. });
  43683. Object.defineProperty(FreeCamera.prototype, "keysUp", {
  43684. get: function () {
  43685. var keyboard = this.inputs.attached["keyboard"];
  43686. if (keyboard)
  43687. return keyboard.keysUp;
  43688. return [];
  43689. },
  43690. set: function (value) {
  43691. var keyboard = this.inputs.attached["keyboard"];
  43692. if (keyboard)
  43693. keyboard.keysUp = value;
  43694. },
  43695. enumerable: true,
  43696. configurable: true
  43697. });
  43698. Object.defineProperty(FreeCamera.prototype, "keysDown", {
  43699. get: function () {
  43700. var keyboard = this.inputs.attached["keyboard"];
  43701. if (keyboard)
  43702. return keyboard.keysDown;
  43703. return [];
  43704. },
  43705. set: function (value) {
  43706. var keyboard = this.inputs.attached["keyboard"];
  43707. if (keyboard)
  43708. keyboard.keysDown = value;
  43709. },
  43710. enumerable: true,
  43711. configurable: true
  43712. });
  43713. Object.defineProperty(FreeCamera.prototype, "keysLeft", {
  43714. get: function () {
  43715. var keyboard = this.inputs.attached["keyboard"];
  43716. if (keyboard)
  43717. return keyboard.keysLeft;
  43718. return [];
  43719. },
  43720. set: function (value) {
  43721. var keyboard = this.inputs.attached["keyboard"];
  43722. if (keyboard)
  43723. keyboard.keysLeft = value;
  43724. },
  43725. enumerable: true,
  43726. configurable: true
  43727. });
  43728. Object.defineProperty(FreeCamera.prototype, "keysRight", {
  43729. get: function () {
  43730. var keyboard = this.inputs.attached["keyboard"];
  43731. if (keyboard)
  43732. return keyboard.keysRight;
  43733. return [];
  43734. },
  43735. set: function (value) {
  43736. var keyboard = this.inputs.attached["keyboard"];
  43737. if (keyboard)
  43738. keyboard.keysRight = value;
  43739. },
  43740. enumerable: true,
  43741. configurable: true
  43742. });
  43743. // Controls
  43744. FreeCamera.prototype.attachControl = function (element, noPreventDefault) {
  43745. this.inputs.attachElement(element, noPreventDefault);
  43746. };
  43747. FreeCamera.prototype.detachControl = function (element) {
  43748. this.inputs.detachElement(element);
  43749. this.cameraDirection = new BABYLON.Vector3(0, 0, 0);
  43750. this.cameraRotation = new BABYLON.Vector2(0, 0);
  43751. };
  43752. Object.defineProperty(FreeCamera.prototype, "collisionMask", {
  43753. get: function () {
  43754. return this._collisionMask;
  43755. },
  43756. set: function (mask) {
  43757. this._collisionMask = !isNaN(mask) ? mask : -1;
  43758. },
  43759. enumerable: true,
  43760. configurable: true
  43761. });
  43762. FreeCamera.prototype._collideWithWorld = function (displacement) {
  43763. var globalPosition;
  43764. if (this.parent) {
  43765. globalPosition = BABYLON.Vector3.TransformCoordinates(this.position, this.parent.getWorldMatrix());
  43766. }
  43767. else {
  43768. globalPosition = this.position;
  43769. }
  43770. globalPosition.subtractFromFloatsToRef(0, this.ellipsoid.y, 0, this._oldPosition);
  43771. this._oldPosition.addInPlace(this.ellipsoidOffset);
  43772. if (!this._collider) {
  43773. this._collider = new BABYLON.Collider();
  43774. }
  43775. this._collider._radius = this.ellipsoid;
  43776. this._collider.collisionMask = this._collisionMask;
  43777. //no need for clone, as long as gravity is not on.
  43778. var actualDisplacement = displacement;
  43779. //add gravity to the direction to prevent the dual-collision checking
  43780. if (this.applyGravity) {
  43781. //this prevents mending with cameraDirection, a global variable of the free camera class.
  43782. actualDisplacement = displacement.add(this.getScene().gravity);
  43783. }
  43784. this.getScene().collisionCoordinator.getNewPosition(this._oldPosition, actualDisplacement, this._collider, 3, null, this._onCollisionPositionChange, this.uniqueId);
  43785. };
  43786. FreeCamera.prototype._checkInputs = function () {
  43787. if (!this._localDirection) {
  43788. this._localDirection = BABYLON.Vector3.Zero();
  43789. this._transformedDirection = BABYLON.Vector3.Zero();
  43790. }
  43791. this.inputs.checkInputs();
  43792. _super.prototype._checkInputs.call(this);
  43793. };
  43794. FreeCamera.prototype._decideIfNeedsToMove = function () {
  43795. return this._needMoveForGravity || Math.abs(this.cameraDirection.x) > 0 || Math.abs(this.cameraDirection.y) > 0 || Math.abs(this.cameraDirection.z) > 0;
  43796. };
  43797. FreeCamera.prototype._updatePosition = function () {
  43798. if (this.checkCollisions && this.getScene().collisionsEnabled) {
  43799. this._collideWithWorld(this.cameraDirection);
  43800. }
  43801. else {
  43802. _super.prototype._updatePosition.call(this);
  43803. }
  43804. };
  43805. FreeCamera.prototype.dispose = function () {
  43806. this.inputs.clear();
  43807. _super.prototype.dispose.call(this);
  43808. };
  43809. FreeCamera.prototype.getClassName = function () {
  43810. return "FreeCamera";
  43811. };
  43812. __decorate([
  43813. BABYLON.serializeAsVector3()
  43814. ], FreeCamera.prototype, "ellipsoid", void 0);
  43815. __decorate([
  43816. BABYLON.serializeAsVector3()
  43817. ], FreeCamera.prototype, "ellipsoidOffset", void 0);
  43818. __decorate([
  43819. BABYLON.serialize()
  43820. ], FreeCamera.prototype, "checkCollisions", void 0);
  43821. __decorate([
  43822. BABYLON.serialize()
  43823. ], FreeCamera.prototype, "applyGravity", void 0);
  43824. return FreeCamera;
  43825. }(BABYLON.TargetCamera));
  43826. BABYLON.FreeCamera = FreeCamera;
  43827. })(BABYLON || (BABYLON = {}));
  43828. //# sourceMappingURL=babylon.freeCamera.js.map
  43829. var BABYLON;
  43830. (function (BABYLON) {
  43831. var ArcRotateCameraKeyboardMoveInput = /** @class */ (function () {
  43832. function ArcRotateCameraKeyboardMoveInput() {
  43833. this._keys = new Array();
  43834. this.keysUp = [38];
  43835. this.keysDown = [40];
  43836. this.keysLeft = [37];
  43837. this.keysRight = [39];
  43838. this.keysReset = [220];
  43839. this.panningSensibility = 50.0;
  43840. this.zoomingSensibility = 25.0;
  43841. this.useAltToZoom = true;
  43842. }
  43843. ArcRotateCameraKeyboardMoveInput.prototype.attachControl = function (element, noPreventDefault) {
  43844. var _this = this;
  43845. if (this._onCanvasBlurObserver) {
  43846. return;
  43847. }
  43848. this._scene = this.camera.getScene();
  43849. this._engine = this._scene.getEngine();
  43850. this._onCanvasBlurObserver = this._engine.onCanvasBlurObservable.add(function () {
  43851. _this._keys = [];
  43852. });
  43853. this._onKeyboardObserver = this._scene.onKeyboardObservable.add(function (info) {
  43854. var evt = info.event;
  43855. if (info.type === BABYLON.KeyboardEventTypes.KEYDOWN) {
  43856. _this._ctrlPressed = evt.ctrlKey;
  43857. _this._altPressed = evt.altKey;
  43858. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  43859. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  43860. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  43861. _this.keysRight.indexOf(evt.keyCode) !== -1 ||
  43862. _this.keysReset.indexOf(evt.keyCode) !== -1) {
  43863. var index = _this._keys.indexOf(evt.keyCode);
  43864. if (index === -1) {
  43865. _this._keys.push(evt.keyCode);
  43866. }
  43867. if (evt.preventDefault) {
  43868. if (!noPreventDefault) {
  43869. evt.preventDefault();
  43870. }
  43871. }
  43872. }
  43873. }
  43874. else {
  43875. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  43876. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  43877. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  43878. _this.keysRight.indexOf(evt.keyCode) !== -1 ||
  43879. _this.keysReset.indexOf(evt.keyCode) !== -1) {
  43880. var index = _this._keys.indexOf(evt.keyCode);
  43881. if (index >= 0) {
  43882. _this._keys.splice(index, 1);
  43883. }
  43884. if (evt.preventDefault) {
  43885. if (!noPreventDefault) {
  43886. evt.preventDefault();
  43887. }
  43888. }
  43889. }
  43890. }
  43891. });
  43892. };
  43893. ArcRotateCameraKeyboardMoveInput.prototype.detachControl = function (element) {
  43894. if (this._scene) {
  43895. if (this._onKeyboardObserver) {
  43896. this._scene.onKeyboardObservable.remove(this._onKeyboardObserver);
  43897. }
  43898. if (this._onCanvasBlurObserver) {
  43899. this._engine.onCanvasBlurObservable.remove(this._onCanvasBlurObserver);
  43900. }
  43901. this._onKeyboardObserver = null;
  43902. this._onCanvasBlurObserver = null;
  43903. }
  43904. this._keys = [];
  43905. };
  43906. ArcRotateCameraKeyboardMoveInput.prototype.checkInputs = function () {
  43907. if (this._onKeyboardObserver) {
  43908. var camera = this.camera;
  43909. for (var index = 0; index < this._keys.length; index++) {
  43910. var keyCode = this._keys[index];
  43911. if (this.keysLeft.indexOf(keyCode) !== -1) {
  43912. if (this._ctrlPressed && this.camera._useCtrlForPanning) {
  43913. camera.inertialPanningX -= 1 / this.panningSensibility;
  43914. }
  43915. else {
  43916. camera.inertialAlphaOffset -= 0.01;
  43917. }
  43918. }
  43919. else if (this.keysUp.indexOf(keyCode) !== -1) {
  43920. if (this._ctrlPressed && this.camera._useCtrlForPanning) {
  43921. camera.inertialPanningY += 1 / this.panningSensibility;
  43922. }
  43923. else if (this._altPressed && this.useAltToZoom) {
  43924. camera.inertialRadiusOffset += 1 / this.zoomingSensibility;
  43925. }
  43926. else {
  43927. camera.inertialBetaOffset -= 0.01;
  43928. }
  43929. }
  43930. else if (this.keysRight.indexOf(keyCode) !== -1) {
  43931. if (this._ctrlPressed && this.camera._useCtrlForPanning) {
  43932. camera.inertialPanningX += 1 / this.panningSensibility;
  43933. }
  43934. else {
  43935. camera.inertialAlphaOffset += 0.01;
  43936. }
  43937. }
  43938. else if (this.keysDown.indexOf(keyCode) !== -1) {
  43939. if (this._ctrlPressed && this.camera._useCtrlForPanning) {
  43940. camera.inertialPanningY -= 1 / this.panningSensibility;
  43941. }
  43942. else if (this._altPressed && this.useAltToZoom) {
  43943. camera.inertialRadiusOffset -= 1 / this.zoomingSensibility;
  43944. }
  43945. else {
  43946. camera.inertialBetaOffset += 0.01;
  43947. }
  43948. }
  43949. else if (this.keysReset.indexOf(keyCode) !== -1) {
  43950. camera.restoreState();
  43951. }
  43952. }
  43953. }
  43954. };
  43955. ArcRotateCameraKeyboardMoveInput.prototype.getClassName = function () {
  43956. return "ArcRotateCameraKeyboardMoveInput";
  43957. };
  43958. ArcRotateCameraKeyboardMoveInput.prototype.getSimpleName = function () {
  43959. return "keyboard";
  43960. };
  43961. __decorate([
  43962. BABYLON.serialize()
  43963. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysUp", void 0);
  43964. __decorate([
  43965. BABYLON.serialize()
  43966. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysDown", void 0);
  43967. __decorate([
  43968. BABYLON.serialize()
  43969. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysLeft", void 0);
  43970. __decorate([
  43971. BABYLON.serialize()
  43972. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysRight", void 0);
  43973. __decorate([
  43974. BABYLON.serialize()
  43975. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysReset", void 0);
  43976. __decorate([
  43977. BABYLON.serialize()
  43978. ], ArcRotateCameraKeyboardMoveInput.prototype, "panningSensibility", void 0);
  43979. __decorate([
  43980. BABYLON.serialize()
  43981. ], ArcRotateCameraKeyboardMoveInput.prototype, "zoomingSensibility", void 0);
  43982. __decorate([
  43983. BABYLON.serialize()
  43984. ], ArcRotateCameraKeyboardMoveInput.prototype, "useAltToZoom", void 0);
  43985. return ArcRotateCameraKeyboardMoveInput;
  43986. }());
  43987. BABYLON.ArcRotateCameraKeyboardMoveInput = ArcRotateCameraKeyboardMoveInput;
  43988. BABYLON.CameraInputTypes["ArcRotateCameraKeyboardMoveInput"] = ArcRotateCameraKeyboardMoveInput;
  43989. })(BABYLON || (BABYLON = {}));
  43990. //# sourceMappingURL=babylon.arcRotateCameraKeyboardMoveInput.js.map
  43991. var BABYLON;
  43992. (function (BABYLON) {
  43993. var ArcRotateCameraMouseWheelInput = /** @class */ (function () {
  43994. function ArcRotateCameraMouseWheelInput() {
  43995. this.wheelPrecision = 3.0;
  43996. /**
  43997. * wheelDeltaPercentage will be used instead of wheelPrecision if different from 0.
  43998. * It defines the percentage of current camera.radius to use as delta when wheel is used.
  43999. */
  44000. this.wheelDeltaPercentage = 0;
  44001. }
  44002. ArcRotateCameraMouseWheelInput.prototype.attachControl = function (element, noPreventDefault) {
  44003. var _this = this;
  44004. this._wheel = function (p, s) {
  44005. //sanity check - this should be a PointerWheel event.
  44006. if (p.type !== BABYLON.PointerEventTypes.POINTERWHEEL)
  44007. return;
  44008. var event = p.event;
  44009. var delta = 0;
  44010. if (event.wheelDelta) {
  44011. delta = _this.wheelDeltaPercentage ? (event.wheelDelta * 0.01) * _this.camera.radius * _this.wheelDeltaPercentage : event.wheelDelta / (_this.wheelPrecision * 40);
  44012. }
  44013. else if (event.detail) {
  44014. delta = -event.detail / _this.wheelPrecision;
  44015. }
  44016. if (delta)
  44017. _this.camera.inertialRadiusOffset += delta;
  44018. if (event.preventDefault) {
  44019. if (!noPreventDefault) {
  44020. event.preventDefault();
  44021. }
  44022. }
  44023. };
  44024. this._observer = this.camera.getScene().onPointerObservable.add(this._wheel, BABYLON.PointerEventTypes.POINTERWHEEL);
  44025. };
  44026. ArcRotateCameraMouseWheelInput.prototype.detachControl = function (element) {
  44027. if (this._observer && element) {
  44028. this.camera.getScene().onPointerObservable.remove(this._observer);
  44029. this._observer = null;
  44030. this._wheel = null;
  44031. }
  44032. };
  44033. ArcRotateCameraMouseWheelInput.prototype.getClassName = function () {
  44034. return "ArcRotateCameraMouseWheelInput";
  44035. };
  44036. ArcRotateCameraMouseWheelInput.prototype.getSimpleName = function () {
  44037. return "mousewheel";
  44038. };
  44039. __decorate([
  44040. BABYLON.serialize()
  44041. ], ArcRotateCameraMouseWheelInput.prototype, "wheelPrecision", void 0);
  44042. __decorate([
  44043. BABYLON.serialize()
  44044. ], ArcRotateCameraMouseWheelInput.prototype, "wheelDeltaPercentage", void 0);
  44045. return ArcRotateCameraMouseWheelInput;
  44046. }());
  44047. BABYLON.ArcRotateCameraMouseWheelInput = ArcRotateCameraMouseWheelInput;
  44048. BABYLON.CameraInputTypes["ArcRotateCameraMouseWheelInput"] = ArcRotateCameraMouseWheelInput;
  44049. })(BABYLON || (BABYLON = {}));
  44050. //# sourceMappingURL=babylon.arcRotateCameraMouseWheelInput.js.map
  44051. var BABYLON;
  44052. (function (BABYLON) {
  44053. var ArcRotateCameraPointersInput = /** @class */ (function () {
  44054. function ArcRotateCameraPointersInput() {
  44055. this.buttons = [0, 1, 2];
  44056. this.angularSensibilityX = 1000.0;
  44057. this.angularSensibilityY = 1000.0;
  44058. this.pinchPrecision = 12.0;
  44059. /**
  44060. * pinchDeltaPercentage will be used instead of pinchPrecision if different from 0.
  44061. * It defines the percentage of current camera.radius to use as delta when pinch zoom is used.
  44062. */
  44063. this.pinchDeltaPercentage = 0;
  44064. this.panningSensibility = 1000.0;
  44065. this.multiTouchPanning = true;
  44066. this.multiTouchPanAndZoom = true;
  44067. this._isPanClick = false;
  44068. this.pinchInwards = true;
  44069. }
  44070. ArcRotateCameraPointersInput.prototype.attachControl = function (element, noPreventDefault) {
  44071. var _this = this;
  44072. var engine = this.camera.getEngine();
  44073. var cacheSoloPointer; // cache pointer object for better perf on camera rotation
  44074. var pointA = null;
  44075. var pointB = null;
  44076. var previousPinchSquaredDistance = 0;
  44077. var initialDistance = 0;
  44078. var twoFingerActivityCount = 0;
  44079. var previousMultiTouchPanPosition = { x: 0, y: 0, isPaning: false, isPinching: false };
  44080. this._pointerInput = function (p, s) {
  44081. var evt = p.event;
  44082. var isTouch = p.event.pointerType === "touch";
  44083. if (engine.isInVRExclusivePointerMode) {
  44084. return;
  44085. }
  44086. if (p.type !== BABYLON.PointerEventTypes.POINTERMOVE && _this.buttons.indexOf(evt.button) === -1) {
  44087. return;
  44088. }
  44089. var srcElement = (evt.srcElement || evt.target);
  44090. if (p.type === BABYLON.PointerEventTypes.POINTERDOWN && srcElement) {
  44091. try {
  44092. srcElement.setPointerCapture(evt.pointerId);
  44093. }
  44094. catch (e) {
  44095. //Nothing to do with the error. Execution will continue.
  44096. }
  44097. // Manage panning with pan button click
  44098. _this._isPanClick = evt.button === _this.camera._panningMouseButton;
  44099. // manage pointers
  44100. cacheSoloPointer = { x: evt.clientX, y: evt.clientY, pointerId: evt.pointerId, type: evt.pointerType };
  44101. if (pointA === null) {
  44102. pointA = cacheSoloPointer;
  44103. }
  44104. else if (pointB === null) {
  44105. pointB = cacheSoloPointer;
  44106. }
  44107. if (!noPreventDefault) {
  44108. evt.preventDefault();
  44109. element.focus();
  44110. }
  44111. }
  44112. else if (p.type === BABYLON.PointerEventTypes.POINTERDOUBLETAP) {
  44113. _this.camera.restoreState();
  44114. }
  44115. else if (p.type === BABYLON.PointerEventTypes.POINTERUP && srcElement) {
  44116. try {
  44117. srcElement.releasePointerCapture(evt.pointerId);
  44118. }
  44119. catch (e) {
  44120. //Nothing to do with the error.
  44121. }
  44122. cacheSoloPointer = null;
  44123. previousPinchSquaredDistance = 0;
  44124. previousMultiTouchPanPosition.isPaning = false;
  44125. previousMultiTouchPanPosition.isPinching = false;
  44126. twoFingerActivityCount = 0;
  44127. initialDistance = 0;
  44128. if (!isTouch) {
  44129. pointB = null; // Mouse and pen are mono pointer
  44130. }
  44131. //would be better to use pointers.remove(evt.pointerId) for multitouch gestures,
  44132. //but emptying completly pointers collection is required to fix a bug on iPhone :
  44133. //when changing orientation while pinching camera, one pointer stay pressed forever if we don't release all pointers
  44134. //will be ok to put back pointers.remove(evt.pointerId); when iPhone bug corrected
  44135. if (engine.badOS) {
  44136. pointA = pointB = null;
  44137. }
  44138. else {
  44139. //only remove the impacted pointer in case of multitouch allowing on most
  44140. //platforms switching from rotate to zoom and pan seamlessly.
  44141. if (pointB && pointA && pointA.pointerId == evt.pointerId) {
  44142. pointA = pointB;
  44143. pointB = null;
  44144. cacheSoloPointer = { x: pointA.x, y: pointA.y, pointerId: pointA.pointerId, type: evt.pointerType };
  44145. }
  44146. else if (pointA && pointB && pointB.pointerId == evt.pointerId) {
  44147. pointB = null;
  44148. cacheSoloPointer = { x: pointA.x, y: pointA.y, pointerId: pointA.pointerId, type: evt.pointerType };
  44149. }
  44150. else {
  44151. pointA = pointB = null;
  44152. }
  44153. }
  44154. if (!noPreventDefault) {
  44155. evt.preventDefault();
  44156. }
  44157. }
  44158. else if (p.type === BABYLON.PointerEventTypes.POINTERMOVE) {
  44159. if (!noPreventDefault) {
  44160. evt.preventDefault();
  44161. }
  44162. // One button down
  44163. if (pointA && pointB === null && cacheSoloPointer) {
  44164. if (_this.panningSensibility !== 0 &&
  44165. ((evt.ctrlKey && _this.camera._useCtrlForPanning) || _this._isPanClick)) {
  44166. _this.camera.inertialPanningX += -(evt.clientX - cacheSoloPointer.x) / _this.panningSensibility;
  44167. _this.camera.inertialPanningY += (evt.clientY - cacheSoloPointer.y) / _this.panningSensibility;
  44168. }
  44169. else {
  44170. var offsetX = evt.clientX - cacheSoloPointer.x;
  44171. var offsetY = evt.clientY - cacheSoloPointer.y;
  44172. _this.camera.inertialAlphaOffset -= offsetX / _this.angularSensibilityX;
  44173. _this.camera.inertialBetaOffset -= offsetY / _this.angularSensibilityY;
  44174. }
  44175. cacheSoloPointer.x = evt.clientX;
  44176. cacheSoloPointer.y = evt.clientY;
  44177. }
  44178. else if (pointA && pointB) {
  44179. //if (noPreventDefault) { evt.preventDefault(); } //if pinch gesture, could be useful to force preventDefault to avoid html page scroll/zoom in some mobile browsers
  44180. var ed = (pointA.pointerId === evt.pointerId) ? pointA : pointB;
  44181. ed.x = evt.clientX;
  44182. ed.y = evt.clientY;
  44183. var direction = _this.pinchInwards ? 1 : -1;
  44184. var distX = pointA.x - pointB.x;
  44185. var distY = pointA.y - pointB.y;
  44186. var pinchSquaredDistance = (distX * distX) + (distY * distY);
  44187. var pinchDistance = Math.sqrt(pinchSquaredDistance);
  44188. if (previousPinchSquaredDistance === 0) {
  44189. initialDistance = pinchDistance;
  44190. previousPinchSquaredDistance = pinchSquaredDistance;
  44191. previousMultiTouchPanPosition.x = (pointA.x + pointB.x) / 2;
  44192. previousMultiTouchPanPosition.y = (pointA.y + pointB.y) / 2;
  44193. return;
  44194. }
  44195. if (_this.multiTouchPanAndZoom) {
  44196. if (_this.pinchDeltaPercentage) {
  44197. _this.camera.inertialRadiusOffset += ((pinchSquaredDistance - previousPinchSquaredDistance) * 0.001) * _this.camera.radius * _this.pinchDeltaPercentage;
  44198. }
  44199. else {
  44200. _this.camera.inertialRadiusOffset += (pinchSquaredDistance - previousPinchSquaredDistance) /
  44201. (_this.pinchPrecision *
  44202. ((_this.angularSensibilityX + _this.angularSensibilityY) / 2) *
  44203. direction);
  44204. }
  44205. if (_this.panningSensibility !== 0) {
  44206. var pointersCenterX = (pointA.x + pointB.x) / 2;
  44207. var pointersCenterY = (pointA.y + pointB.y) / 2;
  44208. var pointersCenterDistX = pointersCenterX - previousMultiTouchPanPosition.x;
  44209. var pointersCenterDistY = pointersCenterY - previousMultiTouchPanPosition.y;
  44210. previousMultiTouchPanPosition.x = pointersCenterX;
  44211. previousMultiTouchPanPosition.y = pointersCenterY;
  44212. _this.camera.inertialPanningX += -(pointersCenterDistX) / (_this.panningSensibility);
  44213. _this.camera.inertialPanningY += (pointersCenterDistY) / (_this.panningSensibility);
  44214. }
  44215. }
  44216. else {
  44217. twoFingerActivityCount++;
  44218. if (previousMultiTouchPanPosition.isPinching || (twoFingerActivityCount < 20 && Math.abs(pinchDistance - initialDistance) > _this.camera.pinchToPanMaxDistance)) {
  44219. if (_this.pinchDeltaPercentage) {
  44220. _this.camera.inertialRadiusOffset += ((pinchSquaredDistance - previousPinchSquaredDistance) * 0.001) * _this.camera.radius * _this.pinchDeltaPercentage;
  44221. }
  44222. else {
  44223. _this.camera.inertialRadiusOffset += (pinchSquaredDistance - previousPinchSquaredDistance) /
  44224. (_this.pinchPrecision *
  44225. ((_this.angularSensibilityX + _this.angularSensibilityY) / 2) *
  44226. direction);
  44227. }
  44228. previousMultiTouchPanPosition.isPaning = false;
  44229. previousMultiTouchPanPosition.isPinching = true;
  44230. }
  44231. else {
  44232. if (cacheSoloPointer && cacheSoloPointer.pointerId === ed.pointerId && _this.panningSensibility !== 0 && _this.multiTouchPanning) {
  44233. if (!previousMultiTouchPanPosition.isPaning) {
  44234. previousMultiTouchPanPosition.isPaning = true;
  44235. previousMultiTouchPanPosition.isPinching = false;
  44236. previousMultiTouchPanPosition.x = ed.x;
  44237. previousMultiTouchPanPosition.y = ed.y;
  44238. return;
  44239. }
  44240. _this.camera.inertialPanningX += -(ed.x - previousMultiTouchPanPosition.x) / (_this.panningSensibility);
  44241. _this.camera.inertialPanningY += (ed.y - previousMultiTouchPanPosition.y) / (_this.panningSensibility);
  44242. }
  44243. }
  44244. if (cacheSoloPointer && cacheSoloPointer.pointerId === evt.pointerId) {
  44245. previousMultiTouchPanPosition.x = ed.x;
  44246. previousMultiTouchPanPosition.y = ed.y;
  44247. }
  44248. }
  44249. previousPinchSquaredDistance = pinchSquaredDistance;
  44250. }
  44251. }
  44252. };
  44253. this._observer = this.camera.getScene().onPointerObservable.add(this._pointerInput, BABYLON.PointerEventTypes.POINTERDOWN | BABYLON.PointerEventTypes.POINTERUP | BABYLON.PointerEventTypes.POINTERMOVE | BABYLON.PointerEventTypes._POINTERDOUBLETAP);
  44254. this._onContextMenu = function (evt) {
  44255. evt.preventDefault();
  44256. };
  44257. if (!this.camera._useCtrlForPanning) {
  44258. element.addEventListener("contextmenu", this._onContextMenu, false);
  44259. }
  44260. this._onLostFocus = function () {
  44261. //this._keys = [];
  44262. pointA = pointB = null;
  44263. previousPinchSquaredDistance = 0;
  44264. previousMultiTouchPanPosition.isPaning = false;
  44265. previousMultiTouchPanPosition.isPinching = false;
  44266. twoFingerActivityCount = 0;
  44267. cacheSoloPointer = null;
  44268. initialDistance = 0;
  44269. };
  44270. this._onMouseMove = function (evt) {
  44271. if (!engine.isPointerLock) {
  44272. return;
  44273. }
  44274. var offsetX = evt.movementX || evt.mozMovementX || evt.webkitMovementX || evt.msMovementX || 0;
  44275. var offsetY = evt.movementY || evt.mozMovementY || evt.webkitMovementY || evt.msMovementY || 0;
  44276. _this.camera.inertialAlphaOffset -= offsetX / _this.angularSensibilityX;
  44277. _this.camera.inertialBetaOffset -= offsetY / _this.angularSensibilityY;
  44278. if (!noPreventDefault) {
  44279. evt.preventDefault();
  44280. }
  44281. };
  44282. this._onGestureStart = function (e) {
  44283. if (window.MSGesture === undefined) {
  44284. return;
  44285. }
  44286. if (!_this._MSGestureHandler) {
  44287. _this._MSGestureHandler = new MSGesture();
  44288. _this._MSGestureHandler.target = element;
  44289. }
  44290. _this._MSGestureHandler.addPointer(e.pointerId);
  44291. };
  44292. this._onGesture = function (e) {
  44293. _this.camera.radius *= e.scale;
  44294. if (e.preventDefault) {
  44295. if (!noPreventDefault) {
  44296. e.stopPropagation();
  44297. e.preventDefault();
  44298. }
  44299. }
  44300. };
  44301. element.addEventListener("mousemove", this._onMouseMove, false);
  44302. element.addEventListener("MSPointerDown", this._onGestureStart, false);
  44303. element.addEventListener("MSGestureChange", this._onGesture, false);
  44304. BABYLON.Tools.RegisterTopRootEvents([
  44305. { name: "blur", handler: this._onLostFocus }
  44306. ]);
  44307. };
  44308. ArcRotateCameraPointersInput.prototype.detachControl = function (element) {
  44309. if (this._onLostFocus) {
  44310. BABYLON.Tools.UnregisterTopRootEvents([
  44311. { name: "blur", handler: this._onLostFocus }
  44312. ]);
  44313. }
  44314. if (element && this._observer) {
  44315. this.camera.getScene().onPointerObservable.remove(this._observer);
  44316. this._observer = null;
  44317. if (this._onContextMenu) {
  44318. element.removeEventListener("contextmenu", this._onContextMenu);
  44319. }
  44320. if (this._onMouseMove) {
  44321. element.removeEventListener("mousemove", this._onMouseMove);
  44322. }
  44323. if (this._onGestureStart) {
  44324. element.removeEventListener("MSPointerDown", this._onGestureStart);
  44325. }
  44326. if (this._onGesture) {
  44327. element.removeEventListener("MSGestureChange", this._onGesture);
  44328. }
  44329. this._isPanClick = false;
  44330. this.pinchInwards = true;
  44331. this._onMouseMove = null;
  44332. this._onGestureStart = null;
  44333. this._onGesture = null;
  44334. this._MSGestureHandler = null;
  44335. this._onLostFocus = null;
  44336. this._onContextMenu = null;
  44337. }
  44338. };
  44339. ArcRotateCameraPointersInput.prototype.getClassName = function () {
  44340. return "ArcRotateCameraPointersInput";
  44341. };
  44342. ArcRotateCameraPointersInput.prototype.getSimpleName = function () {
  44343. return "pointers";
  44344. };
  44345. __decorate([
  44346. BABYLON.serialize()
  44347. ], ArcRotateCameraPointersInput.prototype, "buttons", void 0);
  44348. __decorate([
  44349. BABYLON.serialize()
  44350. ], ArcRotateCameraPointersInput.prototype, "angularSensibilityX", void 0);
  44351. __decorate([
  44352. BABYLON.serialize()
  44353. ], ArcRotateCameraPointersInput.prototype, "angularSensibilityY", void 0);
  44354. __decorate([
  44355. BABYLON.serialize()
  44356. ], ArcRotateCameraPointersInput.prototype, "pinchPrecision", void 0);
  44357. __decorate([
  44358. BABYLON.serialize()
  44359. ], ArcRotateCameraPointersInput.prototype, "pinchDeltaPercentage", void 0);
  44360. __decorate([
  44361. BABYLON.serialize()
  44362. ], ArcRotateCameraPointersInput.prototype, "panningSensibility", void 0);
  44363. __decorate([
  44364. BABYLON.serialize()
  44365. ], ArcRotateCameraPointersInput.prototype, "multiTouchPanning", void 0);
  44366. __decorate([
  44367. BABYLON.serialize()
  44368. ], ArcRotateCameraPointersInput.prototype, "multiTouchPanAndZoom", void 0);
  44369. return ArcRotateCameraPointersInput;
  44370. }());
  44371. BABYLON.ArcRotateCameraPointersInput = ArcRotateCameraPointersInput;
  44372. BABYLON.CameraInputTypes["ArcRotateCameraPointersInput"] = ArcRotateCameraPointersInput;
  44373. })(BABYLON || (BABYLON = {}));
  44374. //# sourceMappingURL=babylon.arcRotateCameraPointersInput.js.map
  44375. var BABYLON;
  44376. (function (BABYLON) {
  44377. var ArcRotateCameraInputsManager = /** @class */ (function (_super) {
  44378. __extends(ArcRotateCameraInputsManager, _super);
  44379. function ArcRotateCameraInputsManager(camera) {
  44380. return _super.call(this, camera) || this;
  44381. }
  44382. ArcRotateCameraInputsManager.prototype.addMouseWheel = function () {
  44383. this.add(new BABYLON.ArcRotateCameraMouseWheelInput());
  44384. return this;
  44385. };
  44386. ArcRotateCameraInputsManager.prototype.addPointers = function () {
  44387. this.add(new BABYLON.ArcRotateCameraPointersInput());
  44388. return this;
  44389. };
  44390. ArcRotateCameraInputsManager.prototype.addKeyboard = function () {
  44391. this.add(new BABYLON.ArcRotateCameraKeyboardMoveInput());
  44392. return this;
  44393. };
  44394. ArcRotateCameraInputsManager.prototype.addGamepad = function () {
  44395. this.add(new BABYLON.ArcRotateCameraGamepadInput());
  44396. return this;
  44397. };
  44398. ArcRotateCameraInputsManager.prototype.addVRDeviceOrientation = function () {
  44399. this.add(new BABYLON.ArcRotateCameraVRDeviceOrientationInput());
  44400. return this;
  44401. };
  44402. return ArcRotateCameraInputsManager;
  44403. }(BABYLON.CameraInputsManager));
  44404. BABYLON.ArcRotateCameraInputsManager = ArcRotateCameraInputsManager;
  44405. })(BABYLON || (BABYLON = {}));
  44406. //# sourceMappingURL=babylon.arcRotateCameraInputsManager.js.map
  44407. var BABYLON;
  44408. (function (BABYLON) {
  44409. var ArcRotateCamera = /** @class */ (function (_super) {
  44410. __extends(ArcRotateCamera, _super);
  44411. function ArcRotateCamera(name, alpha, beta, radius, target, scene) {
  44412. var _this = _super.call(this, name, BABYLON.Vector3.Zero(), scene) || this;
  44413. _this.inertialAlphaOffset = 0;
  44414. _this.inertialBetaOffset = 0;
  44415. _this.inertialRadiusOffset = 0;
  44416. _this.lowerAlphaLimit = null;
  44417. _this.upperAlphaLimit = null;
  44418. _this.lowerBetaLimit = 0.01;
  44419. _this.upperBetaLimit = Math.PI;
  44420. _this.lowerRadiusLimit = null;
  44421. _this.upperRadiusLimit = null;
  44422. _this.inertialPanningX = 0;
  44423. _this.inertialPanningY = 0;
  44424. _this.pinchToPanMaxDistance = 20;
  44425. _this.panningDistanceLimit = null;
  44426. _this.panningOriginTarget = BABYLON.Vector3.Zero();
  44427. _this.panningInertia = 0.9;
  44428. //-- end properties for backward compatibility for inputs
  44429. _this.zoomOnFactor = 1;
  44430. _this.targetScreenOffset = BABYLON.Vector2.Zero();
  44431. _this.allowUpsideDown = true;
  44432. _this._viewMatrix = new BABYLON.Matrix();
  44433. // Panning
  44434. _this.panningAxis = new BABYLON.Vector3(1, 1, 0);
  44435. _this.onMeshTargetChangedObservable = new BABYLON.Observable();
  44436. _this.checkCollisions = false;
  44437. _this.collisionRadius = new BABYLON.Vector3(0.5, 0.5, 0.5);
  44438. _this._previousPosition = BABYLON.Vector3.Zero();
  44439. _this._collisionVelocity = BABYLON.Vector3.Zero();
  44440. _this._newPosition = BABYLON.Vector3.Zero();
  44441. _this._computationVector = BABYLON.Vector3.Zero();
  44442. _this._onCollisionPositionChange = function (collisionId, newPosition, collidedMesh) {
  44443. if (collidedMesh === void 0) { collidedMesh = null; }
  44444. if (_this.getScene().workerCollisions && _this.checkCollisions) {
  44445. newPosition.multiplyInPlace(_this._collider._radius);
  44446. }
  44447. if (!collidedMesh) {
  44448. _this._previousPosition.copyFrom(_this.position);
  44449. }
  44450. else {
  44451. _this.setPosition(newPosition);
  44452. if (_this.onCollide) {
  44453. _this.onCollide(collidedMesh);
  44454. }
  44455. }
  44456. // Recompute because of constraints
  44457. var cosa = Math.cos(_this.alpha);
  44458. var sina = Math.sin(_this.alpha);
  44459. var cosb = Math.cos(_this.beta);
  44460. var sinb = Math.sin(_this.beta);
  44461. if (sinb === 0) {
  44462. sinb = 0.0001;
  44463. }
  44464. var target = _this._getTargetPosition();
  44465. _this._computationVector.copyFromFloats(_this.radius * cosa * sinb, _this.radius * cosb, _this.radius * sina * sinb);
  44466. target.addToRef(_this._computationVector, _this._newPosition);
  44467. _this.position.copyFrom(_this._newPosition);
  44468. var up = _this.upVector;
  44469. if (_this.allowUpsideDown && _this.beta < 0) {
  44470. up = up.clone();
  44471. up = up.negate();
  44472. }
  44473. BABYLON.Matrix.LookAtLHToRef(_this.position, target, up, _this._viewMatrix);
  44474. _this._viewMatrix.m[12] += _this.targetScreenOffset.x;
  44475. _this._viewMatrix.m[13] += _this.targetScreenOffset.y;
  44476. _this._collisionTriggered = false;
  44477. };
  44478. _this._target = BABYLON.Vector3.Zero();
  44479. if (target) {
  44480. _this.setTarget(target);
  44481. }
  44482. _this.alpha = alpha;
  44483. _this.beta = beta;
  44484. _this.radius = radius;
  44485. _this.getViewMatrix();
  44486. _this.inputs = new BABYLON.ArcRotateCameraInputsManager(_this);
  44487. _this.inputs.addKeyboard().addMouseWheel().addPointers();
  44488. return _this;
  44489. }
  44490. Object.defineProperty(ArcRotateCamera.prototype, "target", {
  44491. get: function () {
  44492. return this._target;
  44493. },
  44494. set: function (value) {
  44495. this.setTarget(value);
  44496. },
  44497. enumerable: true,
  44498. configurable: true
  44499. });
  44500. Object.defineProperty(ArcRotateCamera.prototype, "angularSensibilityX", {
  44501. //-- begin properties for backward compatibility for inputs
  44502. get: function () {
  44503. var pointers = this.inputs.attached["pointers"];
  44504. if (pointers)
  44505. return pointers.angularSensibilityX;
  44506. return 0;
  44507. },
  44508. set: function (value) {
  44509. var pointers = this.inputs.attached["pointers"];
  44510. if (pointers) {
  44511. pointers.angularSensibilityX = value;
  44512. }
  44513. },
  44514. enumerable: true,
  44515. configurable: true
  44516. });
  44517. Object.defineProperty(ArcRotateCamera.prototype, "angularSensibilityY", {
  44518. get: function () {
  44519. var pointers = this.inputs.attached["pointers"];
  44520. if (pointers)
  44521. return pointers.angularSensibilityY;
  44522. return 0;
  44523. },
  44524. set: function (value) {
  44525. var pointers = this.inputs.attached["pointers"];
  44526. if (pointers) {
  44527. pointers.angularSensibilityY = value;
  44528. }
  44529. },
  44530. enumerable: true,
  44531. configurable: true
  44532. });
  44533. Object.defineProperty(ArcRotateCamera.prototype, "pinchPrecision", {
  44534. get: function () {
  44535. var pointers = this.inputs.attached["pointers"];
  44536. if (pointers)
  44537. return pointers.pinchPrecision;
  44538. return 0;
  44539. },
  44540. set: function (value) {
  44541. var pointers = this.inputs.attached["pointers"];
  44542. if (pointers) {
  44543. pointers.pinchPrecision = value;
  44544. }
  44545. },
  44546. enumerable: true,
  44547. configurable: true
  44548. });
  44549. Object.defineProperty(ArcRotateCamera.prototype, "pinchDeltaPercentage", {
  44550. get: function () {
  44551. var pointers = this.inputs.attached["pointers"];
  44552. if (pointers)
  44553. return pointers.pinchDeltaPercentage;
  44554. return 0;
  44555. },
  44556. set: function (value) {
  44557. var pointers = this.inputs.attached["pointers"];
  44558. if (pointers) {
  44559. pointers.pinchDeltaPercentage = value;
  44560. }
  44561. },
  44562. enumerable: true,
  44563. configurable: true
  44564. });
  44565. Object.defineProperty(ArcRotateCamera.prototype, "panningSensibility", {
  44566. get: function () {
  44567. var pointers = this.inputs.attached["pointers"];
  44568. if (pointers)
  44569. return pointers.panningSensibility;
  44570. return 0;
  44571. },
  44572. set: function (value) {
  44573. var pointers = this.inputs.attached["pointers"];
  44574. if (pointers) {
  44575. pointers.panningSensibility = value;
  44576. }
  44577. },
  44578. enumerable: true,
  44579. configurable: true
  44580. });
  44581. Object.defineProperty(ArcRotateCamera.prototype, "keysUp", {
  44582. get: function () {
  44583. var keyboard = this.inputs.attached["keyboard"];
  44584. if (keyboard)
  44585. return keyboard.keysUp;
  44586. return [];
  44587. },
  44588. set: function (value) {
  44589. var keyboard = this.inputs.attached["keyboard"];
  44590. if (keyboard)
  44591. keyboard.keysUp = value;
  44592. },
  44593. enumerable: true,
  44594. configurable: true
  44595. });
  44596. Object.defineProperty(ArcRotateCamera.prototype, "keysDown", {
  44597. get: function () {
  44598. var keyboard = this.inputs.attached["keyboard"];
  44599. if (keyboard)
  44600. return keyboard.keysDown;
  44601. return [];
  44602. },
  44603. set: function (value) {
  44604. var keyboard = this.inputs.attached["keyboard"];
  44605. if (keyboard)
  44606. keyboard.keysDown = value;
  44607. },
  44608. enumerable: true,
  44609. configurable: true
  44610. });
  44611. Object.defineProperty(ArcRotateCamera.prototype, "keysLeft", {
  44612. get: function () {
  44613. var keyboard = this.inputs.attached["keyboard"];
  44614. if (keyboard)
  44615. return keyboard.keysLeft;
  44616. return [];
  44617. },
  44618. set: function (value) {
  44619. var keyboard = this.inputs.attached["keyboard"];
  44620. if (keyboard)
  44621. keyboard.keysLeft = value;
  44622. },
  44623. enumerable: true,
  44624. configurable: true
  44625. });
  44626. Object.defineProperty(ArcRotateCamera.prototype, "keysRight", {
  44627. get: function () {
  44628. var keyboard = this.inputs.attached["keyboard"];
  44629. if (keyboard)
  44630. return keyboard.keysRight;
  44631. return [];
  44632. },
  44633. set: function (value) {
  44634. var keyboard = this.inputs.attached["keyboard"];
  44635. if (keyboard)
  44636. keyboard.keysRight = value;
  44637. },
  44638. enumerable: true,
  44639. configurable: true
  44640. });
  44641. Object.defineProperty(ArcRotateCamera.prototype, "wheelPrecision", {
  44642. get: function () {
  44643. var mousewheel = this.inputs.attached["mousewheel"];
  44644. if (mousewheel)
  44645. return mousewheel.wheelPrecision;
  44646. return 0;
  44647. },
  44648. set: function (value) {
  44649. var mousewheel = this.inputs.attached["mousewheel"];
  44650. if (mousewheel)
  44651. mousewheel.wheelPrecision = value;
  44652. },
  44653. enumerable: true,
  44654. configurable: true
  44655. });
  44656. Object.defineProperty(ArcRotateCamera.prototype, "wheelDeltaPercentage", {
  44657. get: function () {
  44658. var mousewheel = this.inputs.attached["mousewheel"];
  44659. if (mousewheel)
  44660. return mousewheel.wheelDeltaPercentage;
  44661. return 0;
  44662. },
  44663. set: function (value) {
  44664. var mousewheel = this.inputs.attached["mousewheel"];
  44665. if (mousewheel)
  44666. mousewheel.wheelDeltaPercentage = value;
  44667. },
  44668. enumerable: true,
  44669. configurable: true
  44670. });
  44671. Object.defineProperty(ArcRotateCamera.prototype, "bouncingBehavior", {
  44672. get: function () {
  44673. return this._bouncingBehavior;
  44674. },
  44675. enumerable: true,
  44676. configurable: true
  44677. });
  44678. Object.defineProperty(ArcRotateCamera.prototype, "useBouncingBehavior", {
  44679. get: function () {
  44680. return this._bouncingBehavior != null;
  44681. },
  44682. set: function (value) {
  44683. if (value === this.useBouncingBehavior) {
  44684. return;
  44685. }
  44686. if (value) {
  44687. this._bouncingBehavior = new BABYLON.BouncingBehavior();
  44688. this.addBehavior(this._bouncingBehavior);
  44689. }
  44690. else if (this._bouncingBehavior) {
  44691. this.removeBehavior(this._bouncingBehavior);
  44692. this._bouncingBehavior = null;
  44693. }
  44694. },
  44695. enumerable: true,
  44696. configurable: true
  44697. });
  44698. Object.defineProperty(ArcRotateCamera.prototype, "framingBehavior", {
  44699. get: function () {
  44700. return this._framingBehavior;
  44701. },
  44702. enumerable: true,
  44703. configurable: true
  44704. });
  44705. Object.defineProperty(ArcRotateCamera.prototype, "useFramingBehavior", {
  44706. get: function () {
  44707. return this._framingBehavior != null;
  44708. },
  44709. set: function (value) {
  44710. if (value === this.useFramingBehavior) {
  44711. return;
  44712. }
  44713. if (value) {
  44714. this._framingBehavior = new BABYLON.FramingBehavior();
  44715. this.addBehavior(this._framingBehavior);
  44716. }
  44717. else if (this._framingBehavior) {
  44718. this.removeBehavior(this._framingBehavior);
  44719. this._framingBehavior = null;
  44720. }
  44721. },
  44722. enumerable: true,
  44723. configurable: true
  44724. });
  44725. Object.defineProperty(ArcRotateCamera.prototype, "autoRotationBehavior", {
  44726. get: function () {
  44727. return this._autoRotationBehavior;
  44728. },
  44729. enumerable: true,
  44730. configurable: true
  44731. });
  44732. Object.defineProperty(ArcRotateCamera.prototype, "useAutoRotationBehavior", {
  44733. get: function () {
  44734. return this._autoRotationBehavior != null;
  44735. },
  44736. set: function (value) {
  44737. if (value === this.useAutoRotationBehavior) {
  44738. return;
  44739. }
  44740. if (value) {
  44741. this._autoRotationBehavior = new BABYLON.AutoRotationBehavior();
  44742. this.addBehavior(this._autoRotationBehavior);
  44743. }
  44744. else if (this._autoRotationBehavior) {
  44745. this.removeBehavior(this._autoRotationBehavior);
  44746. this._autoRotationBehavior = null;
  44747. }
  44748. },
  44749. enumerable: true,
  44750. configurable: true
  44751. });
  44752. // Cache
  44753. ArcRotateCamera.prototype._initCache = function () {
  44754. _super.prototype._initCache.call(this);
  44755. this._cache._target = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  44756. this._cache.alpha = undefined;
  44757. this._cache.beta = undefined;
  44758. this._cache.radius = undefined;
  44759. this._cache.targetScreenOffset = BABYLON.Vector2.Zero();
  44760. };
  44761. ArcRotateCamera.prototype._updateCache = function (ignoreParentClass) {
  44762. if (!ignoreParentClass) {
  44763. _super.prototype._updateCache.call(this);
  44764. }
  44765. this._cache._target.copyFrom(this._getTargetPosition());
  44766. this._cache.alpha = this.alpha;
  44767. this._cache.beta = this.beta;
  44768. this._cache.radius = this.radius;
  44769. this._cache.targetScreenOffset.copyFrom(this.targetScreenOffset);
  44770. };
  44771. ArcRotateCamera.prototype._getTargetPosition = function () {
  44772. if (this._targetHost && this._targetHost.getAbsolutePosition) {
  44773. var pos = this._targetHost.getAbsolutePosition();
  44774. if (this._targetBoundingCenter) {
  44775. pos.addToRef(this._targetBoundingCenter, this._target);
  44776. }
  44777. else {
  44778. this._target.copyFrom(pos);
  44779. }
  44780. }
  44781. var lockedTargetPosition = this._getLockedTargetPosition();
  44782. if (lockedTargetPosition) {
  44783. return lockedTargetPosition;
  44784. }
  44785. return this._target;
  44786. };
  44787. ArcRotateCamera.prototype.storeState = function () {
  44788. this._storedAlpha = this.alpha;
  44789. this._storedBeta = this.beta;
  44790. this._storedRadius = this.radius;
  44791. this._storedTarget = this._getTargetPosition().clone();
  44792. return _super.prototype.storeState.call(this);
  44793. };
  44794. /**
  44795. * Restored camera state. You must call storeState() first
  44796. */
  44797. ArcRotateCamera.prototype._restoreStateValues = function () {
  44798. if (!_super.prototype._restoreStateValues.call(this)) {
  44799. return false;
  44800. }
  44801. this.alpha = this._storedAlpha;
  44802. this.beta = this._storedBeta;
  44803. this.radius = this._storedRadius;
  44804. this.setTarget(this._storedTarget.clone());
  44805. this.inertialAlphaOffset = 0;
  44806. this.inertialBetaOffset = 0;
  44807. this.inertialRadiusOffset = 0;
  44808. this.inertialPanningX = 0;
  44809. this.inertialPanningY = 0;
  44810. return true;
  44811. };
  44812. // Synchronized
  44813. ArcRotateCamera.prototype._isSynchronizedViewMatrix = function () {
  44814. if (!_super.prototype._isSynchronizedViewMatrix.call(this))
  44815. return false;
  44816. return this._cache._target.equals(this._getTargetPosition())
  44817. && this._cache.alpha === this.alpha
  44818. && this._cache.beta === this.beta
  44819. && this._cache.radius === this.radius
  44820. && this._cache.targetScreenOffset.equals(this.targetScreenOffset);
  44821. };
  44822. // Methods
  44823. ArcRotateCamera.prototype.attachControl = function (element, noPreventDefault, useCtrlForPanning, panningMouseButton) {
  44824. var _this = this;
  44825. if (useCtrlForPanning === void 0) { useCtrlForPanning = true; }
  44826. if (panningMouseButton === void 0) { panningMouseButton = 2; }
  44827. this._useCtrlForPanning = useCtrlForPanning;
  44828. this._panningMouseButton = panningMouseButton;
  44829. this.inputs.attachElement(element, noPreventDefault);
  44830. this._reset = function () {
  44831. _this.inertialAlphaOffset = 0;
  44832. _this.inertialBetaOffset = 0;
  44833. _this.inertialRadiusOffset = 0;
  44834. _this.inertialPanningX = 0;
  44835. _this.inertialPanningY = 0;
  44836. };
  44837. };
  44838. ArcRotateCamera.prototype.detachControl = function (element) {
  44839. this.inputs.detachElement(element);
  44840. if (this._reset) {
  44841. this._reset();
  44842. }
  44843. };
  44844. ArcRotateCamera.prototype._checkInputs = function () {
  44845. //if (async) collision inspection was triggered, don't update the camera's position - until the collision callback was called.
  44846. if (this._collisionTriggered) {
  44847. return;
  44848. }
  44849. this.inputs.checkInputs();
  44850. // Inertia
  44851. if (this.inertialAlphaOffset !== 0 || this.inertialBetaOffset !== 0 || this.inertialRadiusOffset !== 0) {
  44852. if (this.getScene().useRightHandedSystem) {
  44853. this.alpha -= this.beta <= 0 ? -this.inertialAlphaOffset : this.inertialAlphaOffset;
  44854. }
  44855. else {
  44856. this.alpha += this.beta <= 0 ? -this.inertialAlphaOffset : this.inertialAlphaOffset;
  44857. }
  44858. this.beta += this.inertialBetaOffset;
  44859. this.radius -= this.inertialRadiusOffset;
  44860. this.inertialAlphaOffset *= this.inertia;
  44861. this.inertialBetaOffset *= this.inertia;
  44862. this.inertialRadiusOffset *= this.inertia;
  44863. if (Math.abs(this.inertialAlphaOffset) < BABYLON.Epsilon)
  44864. this.inertialAlphaOffset = 0;
  44865. if (Math.abs(this.inertialBetaOffset) < BABYLON.Epsilon)
  44866. this.inertialBetaOffset = 0;
  44867. if (Math.abs(this.inertialRadiusOffset) < this.speed * BABYLON.Epsilon)
  44868. this.inertialRadiusOffset = 0;
  44869. }
  44870. // Panning inertia
  44871. if (this.inertialPanningX !== 0 || this.inertialPanningY !== 0) {
  44872. if (!this._localDirection) {
  44873. this._localDirection = BABYLON.Vector3.Zero();
  44874. this._transformedDirection = BABYLON.Vector3.Zero();
  44875. }
  44876. this._localDirection.copyFromFloats(this.inertialPanningX, this.inertialPanningY, this.inertialPanningY);
  44877. this._localDirection.multiplyInPlace(this.panningAxis);
  44878. this._viewMatrix.invertToRef(this._cameraTransformMatrix);
  44879. BABYLON.Vector3.TransformNormalToRef(this._localDirection, this._cameraTransformMatrix, this._transformedDirection);
  44880. //Eliminate y if map panning is enabled (panningAxis == 1,0,1)
  44881. if (!this.panningAxis.y) {
  44882. this._transformedDirection.y = 0;
  44883. }
  44884. if (!this._targetHost) {
  44885. if (this.panningDistanceLimit) {
  44886. this._transformedDirection.addInPlace(this._target);
  44887. var distanceSquared = BABYLON.Vector3.DistanceSquared(this._transformedDirection, this.panningOriginTarget);
  44888. if (distanceSquared <= (this.panningDistanceLimit * this.panningDistanceLimit)) {
  44889. this._target.copyFrom(this._transformedDirection);
  44890. }
  44891. }
  44892. else {
  44893. this._target.addInPlace(this._transformedDirection);
  44894. }
  44895. }
  44896. this.inertialPanningX *= this.panningInertia;
  44897. this.inertialPanningY *= this.panningInertia;
  44898. if (Math.abs(this.inertialPanningX) < this.speed * BABYLON.Epsilon)
  44899. this.inertialPanningX = 0;
  44900. if (Math.abs(this.inertialPanningY) < this.speed * BABYLON.Epsilon)
  44901. this.inertialPanningY = 0;
  44902. }
  44903. // Limits
  44904. this._checkLimits();
  44905. _super.prototype._checkInputs.call(this);
  44906. };
  44907. ArcRotateCamera.prototype._checkLimits = function () {
  44908. if (this.lowerBetaLimit === null || this.lowerBetaLimit === undefined) {
  44909. if (this.allowUpsideDown && this.beta > Math.PI) {
  44910. this.beta = this.beta - (2 * Math.PI);
  44911. }
  44912. }
  44913. else {
  44914. if (this.beta < this.lowerBetaLimit) {
  44915. this.beta = this.lowerBetaLimit;
  44916. }
  44917. }
  44918. if (this.upperBetaLimit === null || this.upperBetaLimit === undefined) {
  44919. if (this.allowUpsideDown && this.beta < -Math.PI) {
  44920. this.beta = this.beta + (2 * Math.PI);
  44921. }
  44922. }
  44923. else {
  44924. if (this.beta > this.upperBetaLimit) {
  44925. this.beta = this.upperBetaLimit;
  44926. }
  44927. }
  44928. if (this.lowerAlphaLimit && this.alpha < this.lowerAlphaLimit) {
  44929. this.alpha = this.lowerAlphaLimit;
  44930. }
  44931. if (this.upperAlphaLimit && this.alpha > this.upperAlphaLimit) {
  44932. this.alpha = this.upperAlphaLimit;
  44933. }
  44934. if (this.lowerRadiusLimit && this.radius < this.lowerRadiusLimit) {
  44935. this.radius = this.lowerRadiusLimit;
  44936. }
  44937. if (this.upperRadiusLimit && this.radius > this.upperRadiusLimit) {
  44938. this.radius = this.upperRadiusLimit;
  44939. }
  44940. };
  44941. ArcRotateCamera.prototype.rebuildAnglesAndRadius = function () {
  44942. this.position.subtractToRef(this._getTargetPosition(), this._computationVector);
  44943. this.radius = this._computationVector.length();
  44944. if (this.radius === 0) {
  44945. this.radius = 0.0001; // Just to avoid division by zero
  44946. }
  44947. // Alpha
  44948. this.alpha = Math.acos(this._computationVector.x / Math.sqrt(Math.pow(this._computationVector.x, 2) + Math.pow(this._computationVector.z, 2)));
  44949. if (this._computationVector.z < 0) {
  44950. this.alpha = 2 * Math.PI - this.alpha;
  44951. }
  44952. // Beta
  44953. this.beta = Math.acos(this._computationVector.y / this.radius);
  44954. this._checkLimits();
  44955. };
  44956. ArcRotateCamera.prototype.setPosition = function (position) {
  44957. if (this.position.equals(position)) {
  44958. return;
  44959. }
  44960. this.position.copyFrom(position);
  44961. this.rebuildAnglesAndRadius();
  44962. };
  44963. ArcRotateCamera.prototype.setTarget = function (target, toBoundingCenter, allowSamePosition) {
  44964. if (toBoundingCenter === void 0) { toBoundingCenter = false; }
  44965. if (allowSamePosition === void 0) { allowSamePosition = false; }
  44966. if (target.getBoundingInfo) {
  44967. if (toBoundingCenter) {
  44968. this._targetBoundingCenter = target.getBoundingInfo().boundingBox.centerWorld.clone();
  44969. }
  44970. else {
  44971. this._targetBoundingCenter = null;
  44972. }
  44973. this._targetHost = target;
  44974. this._target = this._getTargetPosition();
  44975. this.onMeshTargetChangedObservable.notifyObservers(this._targetHost);
  44976. }
  44977. else {
  44978. var newTarget = target;
  44979. var currentTarget = this._getTargetPosition();
  44980. if (currentTarget && !allowSamePosition && currentTarget.equals(newTarget)) {
  44981. return;
  44982. }
  44983. this._targetHost = null;
  44984. this._target = newTarget;
  44985. this._targetBoundingCenter = null;
  44986. this.onMeshTargetChangedObservable.notifyObservers(null);
  44987. }
  44988. this.rebuildAnglesAndRadius();
  44989. };
  44990. ArcRotateCamera.prototype._getViewMatrix = function () {
  44991. // Compute
  44992. var cosa = Math.cos(this.alpha);
  44993. var sina = Math.sin(this.alpha);
  44994. var cosb = Math.cos(this.beta);
  44995. var sinb = Math.sin(this.beta);
  44996. if (sinb === 0) {
  44997. sinb = 0.0001;
  44998. }
  44999. var target = this._getTargetPosition();
  45000. this._computationVector.copyFromFloats(this.radius * cosa * sinb, this.radius * cosb, this.radius * sina * sinb);
  45001. target.addToRef(this._computationVector, this._newPosition);
  45002. if (this.getScene().collisionsEnabled && this.checkCollisions) {
  45003. if (!this._collider) {
  45004. this._collider = new BABYLON.Collider();
  45005. }
  45006. this._collider._radius = this.collisionRadius;
  45007. this._newPosition.subtractToRef(this.position, this._collisionVelocity);
  45008. this._collisionTriggered = true;
  45009. this.getScene().collisionCoordinator.getNewPosition(this.position, this._collisionVelocity, this._collider, 3, null, this._onCollisionPositionChange, this.uniqueId);
  45010. }
  45011. else {
  45012. this.position.copyFrom(this._newPosition);
  45013. var up = this.upVector;
  45014. if (this.allowUpsideDown && sinb < 0) {
  45015. up = up.clone();
  45016. up = up.negate();
  45017. }
  45018. if (this.getScene().useRightHandedSystem) {
  45019. BABYLON.Matrix.LookAtRHToRef(this.position, target, up, this._viewMatrix);
  45020. }
  45021. else {
  45022. BABYLON.Matrix.LookAtLHToRef(this.position, target, up, this._viewMatrix);
  45023. }
  45024. this._viewMatrix.m[12] += this.targetScreenOffset.x;
  45025. this._viewMatrix.m[13] += this.targetScreenOffset.y;
  45026. }
  45027. this._currentTarget = target;
  45028. return this._viewMatrix;
  45029. };
  45030. ArcRotateCamera.prototype.zoomOn = function (meshes, doNotUpdateMaxZ) {
  45031. if (doNotUpdateMaxZ === void 0) { doNotUpdateMaxZ = false; }
  45032. meshes = meshes || this.getScene().meshes;
  45033. var minMaxVector = BABYLON.Mesh.MinMax(meshes);
  45034. var distance = BABYLON.Vector3.Distance(minMaxVector.min, minMaxVector.max);
  45035. this.radius = distance * this.zoomOnFactor;
  45036. this.focusOn({ min: minMaxVector.min, max: minMaxVector.max, distance: distance }, doNotUpdateMaxZ);
  45037. };
  45038. ArcRotateCamera.prototype.focusOn = function (meshesOrMinMaxVectorAndDistance, doNotUpdateMaxZ) {
  45039. if (doNotUpdateMaxZ === void 0) { doNotUpdateMaxZ = false; }
  45040. var meshesOrMinMaxVector;
  45041. var distance;
  45042. if (meshesOrMinMaxVectorAndDistance.min === undefined) {
  45043. var meshes = meshesOrMinMaxVectorAndDistance || this.getScene().meshes;
  45044. meshesOrMinMaxVector = BABYLON.Mesh.MinMax(meshes);
  45045. distance = BABYLON.Vector3.Distance(meshesOrMinMaxVector.min, meshesOrMinMaxVector.max);
  45046. }
  45047. else {
  45048. var minMaxVectorAndDistance = meshesOrMinMaxVectorAndDistance;
  45049. meshesOrMinMaxVector = minMaxVectorAndDistance;
  45050. distance = minMaxVectorAndDistance.distance;
  45051. }
  45052. this._target = BABYLON.Mesh.Center(meshesOrMinMaxVector);
  45053. if (!doNotUpdateMaxZ) {
  45054. this.maxZ = distance * 2;
  45055. }
  45056. };
  45057. /**
  45058. * @override
  45059. * Override Camera.createRigCamera
  45060. */
  45061. ArcRotateCamera.prototype.createRigCamera = function (name, cameraIndex) {
  45062. var alphaShift = 0;
  45063. switch (this.cameraRigMode) {
  45064. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  45065. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  45066. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  45067. case BABYLON.Camera.RIG_MODE_VR:
  45068. alphaShift = this._cameraRigParams.stereoHalfAngle * (cameraIndex === 0 ? 1 : -1);
  45069. break;
  45070. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  45071. alphaShift = this._cameraRigParams.stereoHalfAngle * (cameraIndex === 0 ? -1 : 1);
  45072. break;
  45073. }
  45074. var rigCam = new ArcRotateCamera(name, this.alpha + alphaShift, this.beta, this.radius, this._target, this.getScene());
  45075. rigCam._cameraRigParams = {};
  45076. return rigCam;
  45077. };
  45078. /**
  45079. * @override
  45080. * Override Camera._updateRigCameras
  45081. */
  45082. ArcRotateCamera.prototype._updateRigCameras = function () {
  45083. var camLeft = this._rigCameras[0];
  45084. var camRight = this._rigCameras[1];
  45085. camLeft.beta = camRight.beta = this.beta;
  45086. camLeft.radius = camRight.radius = this.radius;
  45087. switch (this.cameraRigMode) {
  45088. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  45089. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  45090. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  45091. case BABYLON.Camera.RIG_MODE_VR:
  45092. camLeft.alpha = this.alpha - this._cameraRigParams.stereoHalfAngle;
  45093. camRight.alpha = this.alpha + this._cameraRigParams.stereoHalfAngle;
  45094. break;
  45095. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  45096. camLeft.alpha = this.alpha + this._cameraRigParams.stereoHalfAngle;
  45097. camRight.alpha = this.alpha - this._cameraRigParams.stereoHalfAngle;
  45098. break;
  45099. }
  45100. _super.prototype._updateRigCameras.call(this);
  45101. };
  45102. ArcRotateCamera.prototype.dispose = function () {
  45103. this.inputs.clear();
  45104. _super.prototype.dispose.call(this);
  45105. };
  45106. ArcRotateCamera.prototype.getClassName = function () {
  45107. return "ArcRotateCamera";
  45108. };
  45109. __decorate([
  45110. BABYLON.serialize()
  45111. ], ArcRotateCamera.prototype, "alpha", void 0);
  45112. __decorate([
  45113. BABYLON.serialize()
  45114. ], ArcRotateCamera.prototype, "beta", void 0);
  45115. __decorate([
  45116. BABYLON.serialize()
  45117. ], ArcRotateCamera.prototype, "radius", void 0);
  45118. __decorate([
  45119. BABYLON.serializeAsVector3("target")
  45120. ], ArcRotateCamera.prototype, "_target", void 0);
  45121. __decorate([
  45122. BABYLON.serialize()
  45123. ], ArcRotateCamera.prototype, "inertialAlphaOffset", void 0);
  45124. __decorate([
  45125. BABYLON.serialize()
  45126. ], ArcRotateCamera.prototype, "inertialBetaOffset", void 0);
  45127. __decorate([
  45128. BABYLON.serialize()
  45129. ], ArcRotateCamera.prototype, "inertialRadiusOffset", void 0);
  45130. __decorate([
  45131. BABYLON.serialize()
  45132. ], ArcRotateCamera.prototype, "lowerAlphaLimit", void 0);
  45133. __decorate([
  45134. BABYLON.serialize()
  45135. ], ArcRotateCamera.prototype, "upperAlphaLimit", void 0);
  45136. __decorate([
  45137. BABYLON.serialize()
  45138. ], ArcRotateCamera.prototype, "lowerBetaLimit", void 0);
  45139. __decorate([
  45140. BABYLON.serialize()
  45141. ], ArcRotateCamera.prototype, "upperBetaLimit", void 0);
  45142. __decorate([
  45143. BABYLON.serialize()
  45144. ], ArcRotateCamera.prototype, "lowerRadiusLimit", void 0);
  45145. __decorate([
  45146. BABYLON.serialize()
  45147. ], ArcRotateCamera.prototype, "upperRadiusLimit", void 0);
  45148. __decorate([
  45149. BABYLON.serialize()
  45150. ], ArcRotateCamera.prototype, "inertialPanningX", void 0);
  45151. __decorate([
  45152. BABYLON.serialize()
  45153. ], ArcRotateCamera.prototype, "inertialPanningY", void 0);
  45154. __decorate([
  45155. BABYLON.serialize()
  45156. ], ArcRotateCamera.prototype, "pinchToPanMaxDistance", void 0);
  45157. __decorate([
  45158. BABYLON.serialize()
  45159. ], ArcRotateCamera.prototype, "panningDistanceLimit", void 0);
  45160. __decorate([
  45161. BABYLON.serializeAsVector3()
  45162. ], ArcRotateCamera.prototype, "panningOriginTarget", void 0);
  45163. __decorate([
  45164. BABYLON.serialize()
  45165. ], ArcRotateCamera.prototype, "panningInertia", void 0);
  45166. __decorate([
  45167. BABYLON.serialize()
  45168. ], ArcRotateCamera.prototype, "zoomOnFactor", void 0);
  45169. __decorate([
  45170. BABYLON.serialize()
  45171. ], ArcRotateCamera.prototype, "allowUpsideDown", void 0);
  45172. return ArcRotateCamera;
  45173. }(BABYLON.TargetCamera));
  45174. BABYLON.ArcRotateCamera = ArcRotateCamera;
  45175. })(BABYLON || (BABYLON = {}));
  45176. //# sourceMappingURL=babylon.arcRotateCamera.js.map
  45177. var BABYLON;
  45178. (function (BABYLON) {
  45179. /**
  45180. * The HemisphericLight simulates the ambient environment light,
  45181. * so the passed direction is the light reflection direction, not the incoming direction.
  45182. */
  45183. var HemisphericLight = /** @class */ (function (_super) {
  45184. __extends(HemisphericLight, _super);
  45185. /**
  45186. * Creates a HemisphericLight object in the scene according to the passed direction (Vector3).
  45187. * The HemisphericLight simulates the ambient environment light, so the passed direction is the light reflection direction, not the incoming direction.
  45188. * The HemisphericLight can't cast shadows.
  45189. * Documentation : http://doc.babylonjs.com/tutorials/lights
  45190. * @param name The friendly name of the light
  45191. * @param direction The direction of the light reflection
  45192. * @param scene The scene the light belongs to
  45193. */
  45194. function HemisphericLight(name, direction, scene) {
  45195. var _this = _super.call(this, name, scene) || this;
  45196. /**
  45197. * The groundColor is the light in the opposite direction to the one specified during creation.
  45198. * 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.
  45199. */
  45200. _this.groundColor = new BABYLON.Color3(0.0, 0.0, 0.0);
  45201. _this.direction = direction || BABYLON.Vector3.Up();
  45202. return _this;
  45203. }
  45204. HemisphericLight.prototype._buildUniformLayout = function () {
  45205. this._uniformBuffer.addUniform("vLightData", 4);
  45206. this._uniformBuffer.addUniform("vLightDiffuse", 4);
  45207. this._uniformBuffer.addUniform("vLightSpecular", 3);
  45208. this._uniformBuffer.addUniform("vLightGround", 3);
  45209. this._uniformBuffer.addUniform("shadowsInfo", 3);
  45210. this._uniformBuffer.addUniform("depthValues", 2);
  45211. this._uniformBuffer.create();
  45212. };
  45213. /**
  45214. * Returns the string "HemisphericLight".
  45215. * @return The class name
  45216. */
  45217. HemisphericLight.prototype.getClassName = function () {
  45218. return "HemisphericLight";
  45219. };
  45220. /**
  45221. * Sets the HemisphericLight direction towards the passed target (Vector3).
  45222. * Returns the updated direction.
  45223. * @param target The target the direction should point to
  45224. * @return The computed direction
  45225. */
  45226. HemisphericLight.prototype.setDirectionToTarget = function (target) {
  45227. this.direction = BABYLON.Vector3.Normalize(target.subtract(BABYLON.Vector3.Zero()));
  45228. return this.direction;
  45229. };
  45230. /**
  45231. * Returns the shadow generator associated to the light.
  45232. * @returns Always null for hemispheric lights because it does not support shadows.
  45233. */
  45234. HemisphericLight.prototype.getShadowGenerator = function () {
  45235. return null;
  45236. };
  45237. /**
  45238. * Sets the passed Effect object with the HemisphericLight normalized direction and color and the passed name (string).
  45239. * @param effect The effect to update
  45240. * @param lightIndex The index of the light in the effect to update
  45241. * @returns The hemispheric light
  45242. */
  45243. HemisphericLight.prototype.transferToEffect = function (effect, lightIndex) {
  45244. var normalizeDirection = BABYLON.Vector3.Normalize(this.direction);
  45245. this._uniformBuffer.updateFloat4("vLightData", normalizeDirection.x, normalizeDirection.y, normalizeDirection.z, 0.0, lightIndex);
  45246. this._uniformBuffer.updateColor3("vLightGround", this.groundColor.scale(this.intensity), lightIndex);
  45247. return this;
  45248. };
  45249. /**
  45250. * @ignore internal use only.
  45251. */
  45252. HemisphericLight.prototype._getWorldMatrix = function () {
  45253. if (!this._worldMatrix) {
  45254. this._worldMatrix = BABYLON.Matrix.Identity();
  45255. }
  45256. return this._worldMatrix;
  45257. };
  45258. /**
  45259. * Returns the integer 3.
  45260. * @return The light Type id as a constant defines in Light.LIGHTTYPEID_x
  45261. */
  45262. HemisphericLight.prototype.getTypeID = function () {
  45263. return BABYLON.Light.LIGHTTYPEID_HEMISPHERICLIGHT;
  45264. };
  45265. __decorate([
  45266. BABYLON.serializeAsColor3()
  45267. ], HemisphericLight.prototype, "groundColor", void 0);
  45268. __decorate([
  45269. BABYLON.serializeAsVector3()
  45270. ], HemisphericLight.prototype, "direction", void 0);
  45271. return HemisphericLight;
  45272. }(BABYLON.Light));
  45273. BABYLON.HemisphericLight = HemisphericLight;
  45274. })(BABYLON || (BABYLON = {}));
  45275. //# sourceMappingURL=babylon.hemisphericLight.js.map
  45276. var BABYLON;
  45277. (function (BABYLON) {
  45278. /**
  45279. * Base implementation of @see IShadowLight
  45280. * It groups all the common behaviour in order to reduce dupplication and better follow the DRY pattern.
  45281. */
  45282. var ShadowLight = /** @class */ (function (_super) {
  45283. __extends(ShadowLight, _super);
  45284. function ShadowLight() {
  45285. var _this = _super !== null && _super.apply(this, arguments) || this;
  45286. _this._needProjectionMatrixCompute = true;
  45287. return _this;
  45288. }
  45289. ShadowLight.prototype._setPosition = function (value) {
  45290. this._position = value;
  45291. };
  45292. Object.defineProperty(ShadowLight.prototype, "position", {
  45293. /**
  45294. * Sets the position the shadow will be casted from. Also use as the light position for both
  45295. * point and spot lights.
  45296. */
  45297. get: function () {
  45298. return this._position;
  45299. },
  45300. /**
  45301. * Sets the position the shadow will be casted from. Also use as the light position for both
  45302. * point and spot lights.
  45303. */
  45304. set: function (value) {
  45305. this._setPosition(value);
  45306. },
  45307. enumerable: true,
  45308. configurable: true
  45309. });
  45310. ShadowLight.prototype._setDirection = function (value) {
  45311. this._direction = value;
  45312. };
  45313. Object.defineProperty(ShadowLight.prototype, "direction", {
  45314. /**
  45315. * In 2d mode (needCube being false), gets the direction used to cast the shadow.
  45316. * Also use as the light direction on spot and directional lights.
  45317. */
  45318. get: function () {
  45319. return this._direction;
  45320. },
  45321. /**
  45322. * In 2d mode (needCube being false), sets the direction used to cast the shadow.
  45323. * Also use as the light direction on spot and directional lights.
  45324. */
  45325. set: function (value) {
  45326. this._setDirection(value);
  45327. },
  45328. enumerable: true,
  45329. configurable: true
  45330. });
  45331. Object.defineProperty(ShadowLight.prototype, "shadowMinZ", {
  45332. /**
  45333. * Gets the shadow projection clipping minimum z value.
  45334. */
  45335. get: function () {
  45336. return this._shadowMinZ;
  45337. },
  45338. /**
  45339. * Sets the shadow projection clipping minimum z value.
  45340. */
  45341. set: function (value) {
  45342. this._shadowMinZ = value;
  45343. this.forceProjectionMatrixCompute();
  45344. },
  45345. enumerable: true,
  45346. configurable: true
  45347. });
  45348. Object.defineProperty(ShadowLight.prototype, "shadowMaxZ", {
  45349. /**
  45350. * Sets the shadow projection clipping maximum z value.
  45351. */
  45352. get: function () {
  45353. return this._shadowMaxZ;
  45354. },
  45355. /**
  45356. * Gets the shadow projection clipping maximum z value.
  45357. */
  45358. set: function (value) {
  45359. this._shadowMaxZ = value;
  45360. this.forceProjectionMatrixCompute();
  45361. },
  45362. enumerable: true,
  45363. configurable: true
  45364. });
  45365. /**
  45366. * Computes the transformed information (transformedPosition and transformedDirection in World space) of the current light
  45367. * @returns true if the information has been computed, false if it does not need to (no parenting)
  45368. */
  45369. ShadowLight.prototype.computeTransformedInformation = function () {
  45370. if (this.parent && this.parent.getWorldMatrix) {
  45371. if (!this.transformedPosition) {
  45372. this.transformedPosition = BABYLON.Vector3.Zero();
  45373. }
  45374. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this.parent.getWorldMatrix(), this.transformedPosition);
  45375. // In case the direction is present.
  45376. if (this.direction) {
  45377. if (!this.transformedDirection) {
  45378. this.transformedDirection = BABYLON.Vector3.Zero();
  45379. }
  45380. BABYLON.Vector3.TransformNormalToRef(this.direction, this.parent.getWorldMatrix(), this.transformedDirection);
  45381. }
  45382. return true;
  45383. }
  45384. return false;
  45385. };
  45386. /**
  45387. * Return the depth scale used for the shadow map.
  45388. * @returns the depth scale.
  45389. */
  45390. ShadowLight.prototype.getDepthScale = function () {
  45391. return 50.0;
  45392. };
  45393. /**
  45394. * Get the direction to use to render the shadow map. In case of cube texture, the face index can be passed.
  45395. * @param faceIndex The index of the face we are computed the direction to generate shadow
  45396. * @returns The set direction in 2d mode otherwise the direction to the cubemap face if needCube() is true
  45397. */
  45398. ShadowLight.prototype.getShadowDirection = function (faceIndex) {
  45399. return this.transformedDirection ? this.transformedDirection : this.direction;
  45400. };
  45401. /**
  45402. * Returns the ShadowLight absolute position in the World.
  45403. * @returns the position vector in world space
  45404. */
  45405. ShadowLight.prototype.getAbsolutePosition = function () {
  45406. return this.transformedPosition ? this.transformedPosition : this.position;
  45407. };
  45408. /**
  45409. * Sets the ShadowLight direction toward the passed target.
  45410. * @param target The point tot target in local space
  45411. * @returns the updated ShadowLight direction
  45412. */
  45413. ShadowLight.prototype.setDirectionToTarget = function (target) {
  45414. this.direction = BABYLON.Vector3.Normalize(target.subtract(this.position));
  45415. return this.direction;
  45416. };
  45417. /**
  45418. * Returns the light rotation in euler definition.
  45419. * @returns the x y z rotation in local space.
  45420. */
  45421. ShadowLight.prototype.getRotation = function () {
  45422. this.direction.normalize();
  45423. var xaxis = BABYLON.Vector3.Cross(this.direction, BABYLON.Axis.Y);
  45424. var yaxis = BABYLON.Vector3.Cross(xaxis, this.direction);
  45425. return BABYLON.Vector3.RotationFromAxis(xaxis, yaxis, this.direction);
  45426. };
  45427. /**
  45428. * Returns whether or not the shadow generation require a cube texture or a 2d texture.
  45429. * @returns true if a cube texture needs to be use
  45430. */
  45431. ShadowLight.prototype.needCube = function () {
  45432. return false;
  45433. };
  45434. /**
  45435. * Detects if the projection matrix requires to be recomputed this frame.
  45436. * @returns true if it requires to be recomputed otherwise, false.
  45437. */
  45438. ShadowLight.prototype.needProjectionMatrixCompute = function () {
  45439. return this._needProjectionMatrixCompute;
  45440. };
  45441. /**
  45442. * Forces the shadow generator to recompute the projection matrix even if position and direction did not changed.
  45443. */
  45444. ShadowLight.prototype.forceProjectionMatrixCompute = function () {
  45445. this._needProjectionMatrixCompute = true;
  45446. };
  45447. /**
  45448. * Get the world matrix of the sahdow lights.
  45449. * @ignore Internal Use Only
  45450. */
  45451. ShadowLight.prototype._getWorldMatrix = function () {
  45452. if (!this._worldMatrix) {
  45453. this._worldMatrix = BABYLON.Matrix.Identity();
  45454. }
  45455. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, this._worldMatrix);
  45456. return this._worldMatrix;
  45457. };
  45458. /**
  45459. * Gets the minZ used for shadow according to both the scene and the light.
  45460. * @param activeCamera The camera we are returning the min for
  45461. * @returns the depth min z
  45462. */
  45463. ShadowLight.prototype.getDepthMinZ = function (activeCamera) {
  45464. return this.shadowMinZ !== undefined ? this.shadowMinZ : activeCamera.minZ;
  45465. };
  45466. /**
  45467. * Gets the maxZ used for shadow according to both the scene and the light.
  45468. * @param activeCamera The camera we are returning the max for
  45469. * @returns the depth max z
  45470. */
  45471. ShadowLight.prototype.getDepthMaxZ = function (activeCamera) {
  45472. return this.shadowMaxZ !== undefined ? this.shadowMaxZ : activeCamera.maxZ;
  45473. };
  45474. /**
  45475. * Sets the shadow projection matrix in parameter to the generated projection matrix.
  45476. * @param matrix The materix to updated with the projection information
  45477. * @param viewMatrix The transform matrix of the light
  45478. * @param renderList The list of mesh to render in the map
  45479. * @returns The current light
  45480. */
  45481. ShadowLight.prototype.setShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  45482. if (this.customProjectionMatrixBuilder) {
  45483. this.customProjectionMatrixBuilder(viewMatrix, renderList, matrix);
  45484. }
  45485. else {
  45486. this._setDefaultShadowProjectionMatrix(matrix, viewMatrix, renderList);
  45487. }
  45488. return this;
  45489. };
  45490. __decorate([
  45491. BABYLON.serializeAsVector3()
  45492. ], ShadowLight.prototype, "position", null);
  45493. __decorate([
  45494. BABYLON.serializeAsVector3()
  45495. ], ShadowLight.prototype, "direction", null);
  45496. __decorate([
  45497. BABYLON.serialize()
  45498. ], ShadowLight.prototype, "shadowMinZ", null);
  45499. __decorate([
  45500. BABYLON.serialize()
  45501. ], ShadowLight.prototype, "shadowMaxZ", null);
  45502. return ShadowLight;
  45503. }(BABYLON.Light));
  45504. BABYLON.ShadowLight = ShadowLight;
  45505. })(BABYLON || (BABYLON = {}));
  45506. //# sourceMappingURL=babylon.shadowLight.js.map
  45507. var BABYLON;
  45508. (function (BABYLON) {
  45509. /**
  45510. * A point light is a light defined by an unique point in world space.
  45511. * The light is emitted in every direction from this point.
  45512. * A good example of a point light is a standard light bulb.
  45513. * Documentation: https://doc.babylonjs.com/babylon101/lights
  45514. */
  45515. var PointLight = /** @class */ (function (_super) {
  45516. __extends(PointLight, _super);
  45517. /**
  45518. * Creates a PointLight object from the passed name and position (Vector3) and adds it in the scene.
  45519. * A PointLight emits the light in every direction.
  45520. * It can cast shadows.
  45521. * If the scene camera is already defined and you want to set your PointLight at the camera position, just set it :
  45522. * ```javascript
  45523. * var pointLight = new BABYLON.PointLight("pl", camera.position, scene);
  45524. * ```
  45525. * Documentation : http://doc.babylonjs.com/tutorials/lights
  45526. * @param name The light friendly name
  45527. * @param position The position of the point light in the scene
  45528. * @param scene The scene the lights belongs to
  45529. */
  45530. function PointLight(name, position, scene) {
  45531. var _this = _super.call(this, name, scene) || this;
  45532. _this._shadowAngle = Math.PI / 2;
  45533. _this.position = position;
  45534. return _this;
  45535. }
  45536. Object.defineProperty(PointLight.prototype, "shadowAngle", {
  45537. /**
  45538. * Getter: In case of direction provided, the shadow will not use a cube texture but simulate a spot shadow as a fallback
  45539. * This specifies what angle the shadow will use to be created.
  45540. *
  45541. * It default to 90 degrees to work nicely with the cube texture generation for point lights shadow maps.
  45542. */
  45543. get: function () {
  45544. return this._shadowAngle;
  45545. },
  45546. /**
  45547. * Setter: In case of direction provided, the shadow will not use a cube texture but simulate a spot shadow as a fallback
  45548. * This specifies what angle the shadow will use to be created.
  45549. *
  45550. * It default to 90 degrees to work nicely with the cube texture generation for point lights shadow maps.
  45551. */
  45552. set: function (value) {
  45553. this._shadowAngle = value;
  45554. this.forceProjectionMatrixCompute();
  45555. },
  45556. enumerable: true,
  45557. configurable: true
  45558. });
  45559. Object.defineProperty(PointLight.prototype, "direction", {
  45560. /**
  45561. * Gets the direction if it has been set.
  45562. * In case of direction provided, the shadow will not use a cube texture but simulate a spot shadow as a fallback
  45563. */
  45564. get: function () {
  45565. return this._direction;
  45566. },
  45567. /**
  45568. * In case of direction provided, the shadow will not use a cube texture but simulate a spot shadow as a fallback
  45569. */
  45570. set: function (value) {
  45571. var previousNeedCube = this.needCube();
  45572. this._direction = value;
  45573. if (this.needCube() !== previousNeedCube && this._shadowGenerator) {
  45574. this._shadowGenerator.recreateShadowMap();
  45575. }
  45576. },
  45577. enumerable: true,
  45578. configurable: true
  45579. });
  45580. /**
  45581. * Returns the string "PointLight"
  45582. * @returns the class name
  45583. */
  45584. PointLight.prototype.getClassName = function () {
  45585. return "PointLight";
  45586. };
  45587. /**
  45588. * Returns the integer 0.
  45589. * @returns The light Type id as a constant defines in Light.LIGHTTYPEID_x
  45590. */
  45591. PointLight.prototype.getTypeID = function () {
  45592. return BABYLON.Light.LIGHTTYPEID_POINTLIGHT;
  45593. };
  45594. /**
  45595. * Specifies wether or not the shadowmap should be a cube texture.
  45596. * @returns true if the shadowmap needs to be a cube texture.
  45597. */
  45598. PointLight.prototype.needCube = function () {
  45599. return !this.direction;
  45600. };
  45601. /**
  45602. * Returns a new Vector3 aligned with the PointLight cube system according to the passed cube face index (integer).
  45603. * @param faceIndex The index of the face we are computed the direction to generate shadow
  45604. * @returns The set direction in 2d mode otherwise the direction to the cubemap face if needCube() is true
  45605. */
  45606. PointLight.prototype.getShadowDirection = function (faceIndex) {
  45607. if (this.direction) {
  45608. return _super.prototype.getShadowDirection.call(this, faceIndex);
  45609. }
  45610. else {
  45611. switch (faceIndex) {
  45612. case 0:
  45613. return new BABYLON.Vector3(1.0, 0.0, 0.0);
  45614. case 1:
  45615. return new BABYLON.Vector3(-1.0, 0.0, 0.0);
  45616. case 2:
  45617. return new BABYLON.Vector3(0.0, -1.0, 0.0);
  45618. case 3:
  45619. return new BABYLON.Vector3(0.0, 1.0, 0.0);
  45620. case 4:
  45621. return new BABYLON.Vector3(0.0, 0.0, 1.0);
  45622. case 5:
  45623. return new BABYLON.Vector3(0.0, 0.0, -1.0);
  45624. }
  45625. }
  45626. return BABYLON.Vector3.Zero();
  45627. };
  45628. /**
  45629. * Sets the passed matrix "matrix" as a left-handed perspective projection matrix with the following settings :
  45630. * - fov = PI / 2
  45631. * - aspect ratio : 1.0
  45632. * - z-near and far equal to the active camera minZ and maxZ.
  45633. * Returns the PointLight.
  45634. */
  45635. PointLight.prototype._setDefaultShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  45636. var activeCamera = this.getScene().activeCamera;
  45637. if (!activeCamera) {
  45638. return;
  45639. }
  45640. BABYLON.Matrix.PerspectiveFovLHToRef(this.shadowAngle, 1.0, this.getDepthMinZ(activeCamera), this.getDepthMaxZ(activeCamera), matrix);
  45641. };
  45642. PointLight.prototype._buildUniformLayout = function () {
  45643. this._uniformBuffer.addUniform("vLightData", 4);
  45644. this._uniformBuffer.addUniform("vLightDiffuse", 4);
  45645. this._uniformBuffer.addUniform("vLightSpecular", 3);
  45646. this._uniformBuffer.addUniform("shadowsInfo", 3);
  45647. this._uniformBuffer.addUniform("depthValues", 2);
  45648. this._uniformBuffer.create();
  45649. };
  45650. /**
  45651. * Sets the passed Effect "effect" with the PointLight transformed position (or position, if none) and passed name (string).
  45652. * @param effect The effect to update
  45653. * @param lightIndex The index of the light in the effect to update
  45654. * @returns The point light
  45655. */
  45656. PointLight.prototype.transferToEffect = function (effect, lightIndex) {
  45657. if (this.computeTransformedInformation()) {
  45658. this._uniformBuffer.updateFloat4("vLightData", this.transformedPosition.x, this.transformedPosition.y, this.transformedPosition.z, 0.0, lightIndex);
  45659. return this;
  45660. }
  45661. this._uniformBuffer.updateFloat4("vLightData", this.position.x, this.position.y, this.position.z, 0, lightIndex);
  45662. return this;
  45663. };
  45664. __decorate([
  45665. BABYLON.serialize()
  45666. ], PointLight.prototype, "shadowAngle", null);
  45667. return PointLight;
  45668. }(BABYLON.ShadowLight));
  45669. BABYLON.PointLight = PointLight;
  45670. })(BABYLON || (BABYLON = {}));
  45671. //# sourceMappingURL=babylon.pointLight.js.map
  45672. var BABYLON;
  45673. (function (BABYLON) {
  45674. /**
  45675. * A directional light is defined by a direction (what a surprise!).
  45676. * The light is emitted from everywhere in the specified direction, and has an infinite range.
  45677. * 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.
  45678. * Documentation: https://doc.babylonjs.com/babylon101/lights
  45679. */
  45680. var DirectionalLight = /** @class */ (function (_super) {
  45681. __extends(DirectionalLight, _super);
  45682. /**
  45683. * Creates a DirectionalLight object in the scene, oriented towards the passed direction (Vector3).
  45684. * The directional light is emitted from everywhere in the given direction.
  45685. * It can cast shawdows.
  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
  45689. * @param scene The scene the light belongs to
  45690. */
  45691. function DirectionalLight(name, direction, scene) {
  45692. var _this = _super.call(this, name, scene) || this;
  45693. _this._shadowFrustumSize = 0;
  45694. _this._shadowOrthoScale = 0.5;
  45695. /**
  45696. * Automatically compute the projection matrix to best fit (including all the casters)
  45697. * on each frame.
  45698. */
  45699. _this.autoUpdateExtends = true;
  45700. // Cache
  45701. _this._orthoLeft = Number.MAX_VALUE;
  45702. _this._orthoRight = Number.MIN_VALUE;
  45703. _this._orthoTop = Number.MIN_VALUE;
  45704. _this._orthoBottom = Number.MAX_VALUE;
  45705. _this.position = direction.scale(-1.0);
  45706. _this.direction = direction;
  45707. return _this;
  45708. }
  45709. Object.defineProperty(DirectionalLight.prototype, "shadowFrustumSize", {
  45710. /**
  45711. * Fix frustum size for the shadow generation. This is disabled if the value is 0.
  45712. */
  45713. get: function () {
  45714. return this._shadowFrustumSize;
  45715. },
  45716. /**
  45717. * Specifies a fix frustum size for the shadow generation.
  45718. */
  45719. set: function (value) {
  45720. this._shadowFrustumSize = value;
  45721. this.forceProjectionMatrixCompute();
  45722. },
  45723. enumerable: true,
  45724. configurable: true
  45725. });
  45726. Object.defineProperty(DirectionalLight.prototype, "shadowOrthoScale", {
  45727. /**
  45728. * Gets the shadow projection scale against the optimal computed one.
  45729. * 0.1 by default which means that the projection window is increase by 10% from the optimal size.
  45730. * This does not impact in fixed frustum size (shadowFrustumSize being set)
  45731. */
  45732. get: function () {
  45733. return this._shadowOrthoScale;
  45734. },
  45735. /**
  45736. * Sets the shadow projection scale against the optimal computed one.
  45737. * 0.1 by default which means that the projection window is increase by 10% from the optimal size.
  45738. * This does not impact in fixed frustum size (shadowFrustumSize being set)
  45739. */
  45740. set: function (value) {
  45741. this._shadowOrthoScale = value;
  45742. this.forceProjectionMatrixCompute();
  45743. },
  45744. enumerable: true,
  45745. configurable: true
  45746. });
  45747. /**
  45748. * Returns the string "DirectionalLight".
  45749. * @return The class name
  45750. */
  45751. DirectionalLight.prototype.getClassName = function () {
  45752. return "DirectionalLight";
  45753. };
  45754. /**
  45755. * Returns the integer 1.
  45756. * @return The light Type id as a constant defines in Light.LIGHTTYPEID_x
  45757. */
  45758. DirectionalLight.prototype.getTypeID = function () {
  45759. return BABYLON.Light.LIGHTTYPEID_DIRECTIONALLIGHT;
  45760. };
  45761. /**
  45762. * Sets the passed matrix "matrix" as projection matrix for the shadows cast by the light according to the passed view matrix.
  45763. * Returns the DirectionalLight Shadow projection matrix.
  45764. */
  45765. DirectionalLight.prototype._setDefaultShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  45766. if (this.shadowFrustumSize > 0) {
  45767. this._setDefaultFixedFrustumShadowProjectionMatrix(matrix, viewMatrix);
  45768. }
  45769. else {
  45770. this._setDefaultAutoExtendShadowProjectionMatrix(matrix, viewMatrix, renderList);
  45771. }
  45772. };
  45773. /**
  45774. * Sets the passed matrix "matrix" as fixed frustum projection matrix for the shadows cast by the light according to the passed view matrix.
  45775. * Returns the DirectionalLight Shadow projection matrix.
  45776. */
  45777. DirectionalLight.prototype._setDefaultFixedFrustumShadowProjectionMatrix = function (matrix, viewMatrix) {
  45778. var activeCamera = this.getScene().activeCamera;
  45779. if (!activeCamera) {
  45780. return;
  45781. }
  45782. BABYLON.Matrix.OrthoLHToRef(this.shadowFrustumSize, this.shadowFrustumSize, this.shadowMinZ !== undefined ? this.shadowMinZ : activeCamera.minZ, this.shadowMaxZ !== undefined ? this.shadowMaxZ : activeCamera.maxZ, matrix);
  45783. };
  45784. /**
  45785. * Sets the passed matrix "matrix" as auto extend projection matrix for the shadows cast by the light according to the passed view matrix.
  45786. * Returns the DirectionalLight Shadow projection matrix.
  45787. */
  45788. DirectionalLight.prototype._setDefaultAutoExtendShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  45789. var activeCamera = this.getScene().activeCamera;
  45790. if (!activeCamera) {
  45791. return;
  45792. }
  45793. // Check extends
  45794. if (this.autoUpdateExtends || this._orthoLeft === Number.MAX_VALUE) {
  45795. var tempVector3 = BABYLON.Vector3.Zero();
  45796. this._orthoLeft = Number.MAX_VALUE;
  45797. this._orthoRight = Number.MIN_VALUE;
  45798. this._orthoTop = Number.MIN_VALUE;
  45799. this._orthoBottom = Number.MAX_VALUE;
  45800. for (var meshIndex = 0; meshIndex < renderList.length; meshIndex++) {
  45801. var mesh = renderList[meshIndex];
  45802. if (!mesh) {
  45803. continue;
  45804. }
  45805. var boundingInfo = mesh.getBoundingInfo();
  45806. var boundingBox = boundingInfo.boundingBox;
  45807. for (var index = 0; index < boundingBox.vectorsWorld.length; index++) {
  45808. BABYLON.Vector3.TransformCoordinatesToRef(boundingBox.vectorsWorld[index], viewMatrix, tempVector3);
  45809. if (tempVector3.x < this._orthoLeft)
  45810. this._orthoLeft = tempVector3.x;
  45811. if (tempVector3.y < this._orthoBottom)
  45812. this._orthoBottom = tempVector3.y;
  45813. if (tempVector3.x > this._orthoRight)
  45814. this._orthoRight = tempVector3.x;
  45815. if (tempVector3.y > this._orthoTop)
  45816. this._orthoTop = tempVector3.y;
  45817. }
  45818. }
  45819. }
  45820. var xOffset = this._orthoRight - this._orthoLeft;
  45821. var yOffset = this._orthoTop - this._orthoBottom;
  45822. 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);
  45823. };
  45824. DirectionalLight.prototype._buildUniformLayout = function () {
  45825. this._uniformBuffer.addUniform("vLightData", 4);
  45826. this._uniformBuffer.addUniform("vLightDiffuse", 4);
  45827. this._uniformBuffer.addUniform("vLightSpecular", 3);
  45828. this._uniformBuffer.addUniform("shadowsInfo", 3);
  45829. this._uniformBuffer.addUniform("depthValues", 2);
  45830. this._uniformBuffer.create();
  45831. };
  45832. /**
  45833. * Sets the passed Effect object with the DirectionalLight transformed position (or position if not parented) and the passed name.
  45834. * @param effect The effect to update
  45835. * @param lightIndex The index of the light in the effect to update
  45836. * @returns The directional light
  45837. */
  45838. DirectionalLight.prototype.transferToEffect = function (effect, lightIndex) {
  45839. if (this.computeTransformedInformation()) {
  45840. this._uniformBuffer.updateFloat4("vLightData", this.transformedDirection.x, this.transformedDirection.y, this.transformedDirection.z, 1, lightIndex);
  45841. return this;
  45842. }
  45843. this._uniformBuffer.updateFloat4("vLightData", this.direction.x, this.direction.y, this.direction.z, 1, lightIndex);
  45844. return this;
  45845. };
  45846. /**
  45847. * Gets the minZ used for shadow according to both the scene and the light.
  45848. *
  45849. * Values are fixed on directional lights as it relies on an ortho projection hence the need to convert being
  45850. * -1 and 1 to 0 and 1 doing (depth + min) / (min + max) -> (depth + 1) / (1 + 1) -> (depth * 0.5) + 0.5.
  45851. * @param activeCamera The camera we are returning the min for
  45852. * @returns the depth min z
  45853. */
  45854. DirectionalLight.prototype.getDepthMinZ = function (activeCamera) {
  45855. return 1;
  45856. };
  45857. /**
  45858. * Gets the maxZ used for shadow according to both the scene and the light.
  45859. *
  45860. * Values are fixed on directional lights as it relies on an ortho projection hence the need to convert being
  45861. * -1 and 1 to 0 and 1 doing (depth + min) / (min + max) -> (depth + 1) / (1 + 1) -> (depth * 0.5) + 0.5.
  45862. * @param activeCamera The camera we are returning the max for
  45863. * @returns the depth max z
  45864. */
  45865. DirectionalLight.prototype.getDepthMaxZ = function (activeCamera) {
  45866. return 1;
  45867. };
  45868. __decorate([
  45869. BABYLON.serialize()
  45870. ], DirectionalLight.prototype, "shadowFrustumSize", null);
  45871. __decorate([
  45872. BABYLON.serialize()
  45873. ], DirectionalLight.prototype, "shadowOrthoScale", null);
  45874. __decorate([
  45875. BABYLON.serialize()
  45876. ], DirectionalLight.prototype, "autoUpdateExtends", void 0);
  45877. return DirectionalLight;
  45878. }(BABYLON.ShadowLight));
  45879. BABYLON.DirectionalLight = DirectionalLight;
  45880. })(BABYLON || (BABYLON = {}));
  45881. //# sourceMappingURL=babylon.directionalLight.js.map
  45882. var BABYLON;
  45883. (function (BABYLON) {
  45884. /**
  45885. * A spot light is defined by a position, a direction, an angle, and an exponent.
  45886. * These values define a cone of light starting from the position, emitting toward the direction.
  45887. * The angle, in radians, defines the size (field of illumination) of the spotlight's conical beam,
  45888. * and the exponent defines the speed of the decay of the light with distance (reach).
  45889. * Documentation: https://doc.babylonjs.com/babylon101/lights
  45890. */
  45891. var SpotLight = /** @class */ (function (_super) {
  45892. __extends(SpotLight, _super);
  45893. /**
  45894. * Creates a SpotLight object in the scene. A spot light is a simply light oriented cone.
  45895. * It can cast shadows.
  45896. * Documentation : http://doc.babylonjs.com/tutorials/lights
  45897. * @param name The light friendly name
  45898. * @param position The position of the spot light in the scene
  45899. * @param direction The direction of the light in the scene
  45900. * @param angle The cone angle of the light in Radians
  45901. * @param exponent The light decay speed with the distance from the emission spot
  45902. * @param scene The scene the lights belongs to
  45903. */
  45904. function SpotLight(name, position, direction, angle, exponent, scene) {
  45905. var _this = _super.call(this, name, scene) || this;
  45906. _this._projectionTextureMatrix = BABYLON.Matrix.Zero();
  45907. _this._projectionTextureLightNear = 1e-6;
  45908. _this._projectionTextureLightFar = 1000.0;
  45909. _this._projectionTextureUpDirection = BABYLON.Vector3.Up();
  45910. _this._projectionTextureViewLightDirty = true;
  45911. _this._projectionTextureProjectionLightDirty = true;
  45912. _this._projectionTextureDirty = true;
  45913. _this._projectionTextureViewTargetVector = BABYLON.Vector3.Zero();
  45914. _this._projectionTextureViewLightMatrix = BABYLON.Matrix.Zero();
  45915. _this._projectionTextureProjectionLightMatrix = BABYLON.Matrix.Zero();
  45916. _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);
  45917. _this.position = position;
  45918. _this.direction = direction;
  45919. _this.angle = angle;
  45920. _this.exponent = exponent;
  45921. return _this;
  45922. }
  45923. Object.defineProperty(SpotLight.prototype, "angle", {
  45924. /**
  45925. * Gets the cone angle of the spot light in Radians.
  45926. */
  45927. get: function () {
  45928. return this._angle;
  45929. },
  45930. /**
  45931. * Sets the cone angle of the spot light in Radians.
  45932. */
  45933. set: function (value) {
  45934. this._angle = value;
  45935. this._projectionTextureProjectionLightDirty = true;
  45936. this.forceProjectionMatrixCompute();
  45937. },
  45938. enumerable: true,
  45939. configurable: true
  45940. });
  45941. Object.defineProperty(SpotLight.prototype, "shadowAngleScale", {
  45942. /**
  45943. * Allows scaling the angle of the light for shadow generation only.
  45944. */
  45945. get: function () {
  45946. return this._shadowAngleScale;
  45947. },
  45948. /**
  45949. * Allows scaling the angle of the light for shadow generation only.
  45950. */
  45951. set: function (value) {
  45952. this._shadowAngleScale = value;
  45953. this.forceProjectionMatrixCompute();
  45954. },
  45955. enumerable: true,
  45956. configurable: true
  45957. });
  45958. Object.defineProperty(SpotLight.prototype, "projectionTextureMatrix", {
  45959. /**
  45960. * Allows reading the projecton texture
  45961. */
  45962. get: function () {
  45963. return this._projectionTextureMatrix;
  45964. },
  45965. enumerable: true,
  45966. configurable: true
  45967. });
  45968. ;
  45969. Object.defineProperty(SpotLight.prototype, "projectionTextureLightNear", {
  45970. /**
  45971. * Gets the near clip of the Spotlight for texture projection.
  45972. */
  45973. get: function () {
  45974. return this._projectionTextureLightNear;
  45975. },
  45976. /**
  45977. * Sets the near clip of the Spotlight for texture projection.
  45978. */
  45979. set: function (value) {
  45980. this._projectionTextureLightNear = value;
  45981. this._projectionTextureProjectionLightDirty = true;
  45982. },
  45983. enumerable: true,
  45984. configurable: true
  45985. });
  45986. Object.defineProperty(SpotLight.prototype, "projectionTextureLightFar", {
  45987. /**
  45988. * Gets the far clip of the Spotlight for texture projection.
  45989. */
  45990. get: function () {
  45991. return this._projectionTextureLightFar;
  45992. },
  45993. /**
  45994. * Sets the far clip of the Spotlight for texture projection.
  45995. */
  45996. set: function (value) {
  45997. this._projectionTextureLightFar = value;
  45998. this._projectionTextureProjectionLightDirty = true;
  45999. },
  46000. enumerable: true,
  46001. configurable: true
  46002. });
  46003. Object.defineProperty(SpotLight.prototype, "projectionTextureUpDirection", {
  46004. /**
  46005. * Gets the Up vector of the Spotlight for texture projection.
  46006. */
  46007. get: function () {
  46008. return this._projectionTextureUpDirection;
  46009. },
  46010. /**
  46011. * Sets the Up vector of the Spotlight for texture projection.
  46012. */
  46013. set: function (value) {
  46014. this._projectionTextureUpDirection = value;
  46015. this._projectionTextureProjectionLightDirty = true;
  46016. },
  46017. enumerable: true,
  46018. configurable: true
  46019. });
  46020. ;
  46021. Object.defineProperty(SpotLight.prototype, "projectionTexture", {
  46022. /**
  46023. * Gets the projection texture of the light.
  46024. */
  46025. get: function () {
  46026. return this._projectionTexture;
  46027. },
  46028. /**
  46029. * Sets the projection texture of the light.
  46030. */
  46031. set: function (value) {
  46032. this._projectionTexture = value;
  46033. this._projectionTextureDirty = true;
  46034. },
  46035. enumerable: true,
  46036. configurable: true
  46037. });
  46038. /**
  46039. * Returns the string "SpotLight".
  46040. * @returns the class name
  46041. */
  46042. SpotLight.prototype.getClassName = function () {
  46043. return "SpotLight";
  46044. };
  46045. /**
  46046. * Returns the integer 2.
  46047. * @returns The light Type id as a constant defines in Light.LIGHTTYPEID_x
  46048. */
  46049. SpotLight.prototype.getTypeID = function () {
  46050. return BABYLON.Light.LIGHTTYPEID_SPOTLIGHT;
  46051. };
  46052. /**
  46053. * Overrides the direction setter to recompute the projection texture view light Matrix.
  46054. */
  46055. SpotLight.prototype._setDirection = function (value) {
  46056. _super.prototype._setDirection.call(this, value);
  46057. this._projectionTextureViewLightDirty = true;
  46058. };
  46059. /**
  46060. * Overrides the position setter to recompute the projection texture view light Matrix.
  46061. */
  46062. SpotLight.prototype._setPosition = function (value) {
  46063. _super.prototype._setPosition.call(this, value);
  46064. this._projectionTextureViewLightDirty = true;
  46065. };
  46066. /**
  46067. * 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.
  46068. * Returns the SpotLight.
  46069. */
  46070. SpotLight.prototype._setDefaultShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  46071. var activeCamera = this.getScene().activeCamera;
  46072. if (!activeCamera) {
  46073. return;
  46074. }
  46075. this._shadowAngleScale = this._shadowAngleScale || 1;
  46076. var angle = this._shadowAngleScale * this._angle;
  46077. BABYLON.Matrix.PerspectiveFovLHToRef(angle, 1.0, this.getDepthMinZ(activeCamera), this.getDepthMaxZ(activeCamera), matrix);
  46078. };
  46079. SpotLight.prototype._computeProjectionTextureViewLightMatrix = function () {
  46080. this._projectionTextureViewLightDirty = false;
  46081. this._projectionTextureDirty = true;
  46082. this.position.addToRef(this.direction, this._projectionTextureViewTargetVector);
  46083. BABYLON.Matrix.LookAtLHToRef(this.position, this._projectionTextureViewTargetVector, this._projectionTextureUpDirection, this._projectionTextureViewLightMatrix);
  46084. };
  46085. SpotLight.prototype._computeProjectionTextureProjectionLightMatrix = function () {
  46086. this._projectionTextureProjectionLightDirty = false;
  46087. this._projectionTextureDirty = true;
  46088. var light_far = this.projectionTextureLightFar;
  46089. var light_near = this.projectionTextureLightNear;
  46090. var P = light_far / (light_far - light_near);
  46091. var Q = -P * light_near;
  46092. var S = 1.0 / Math.tan(this._angle / 2.0);
  46093. var A = 1.0;
  46094. 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);
  46095. };
  46096. /**
  46097. * Main function for light texture projection matrix computing.
  46098. */
  46099. SpotLight.prototype._computeProjectionTextureMatrix = function () {
  46100. this._projectionTextureDirty = false;
  46101. this._projectionTextureViewLightMatrix.multiplyToRef(this._projectionTextureProjectionLightMatrix, this._projectionTextureMatrix);
  46102. this._projectionTextureMatrix.multiplyToRef(this._projectionTextureScalingMatrix, this._projectionTextureMatrix);
  46103. };
  46104. SpotLight.prototype._buildUniformLayout = function () {
  46105. this._uniformBuffer.addUniform("vLightData", 4);
  46106. this._uniformBuffer.addUniform("vLightDiffuse", 4);
  46107. this._uniformBuffer.addUniform("vLightSpecular", 3);
  46108. this._uniformBuffer.addUniform("vLightDirection", 3);
  46109. this._uniformBuffer.addUniform("shadowsInfo", 3);
  46110. this._uniformBuffer.addUniform("depthValues", 2);
  46111. this._uniformBuffer.create();
  46112. };
  46113. /**
  46114. * Sets the passed Effect object with the SpotLight transfomed position (or position if not parented) and normalized direction.
  46115. * @param effect The effect to update
  46116. * @param lightIndex The index of the light in the effect to update
  46117. * @returns The spot light
  46118. */
  46119. SpotLight.prototype.transferToEffect = function (effect, lightIndex) {
  46120. var normalizeDirection;
  46121. if (this.computeTransformedInformation()) {
  46122. this._uniformBuffer.updateFloat4("vLightData", this.transformedPosition.x, this.transformedPosition.y, this.transformedPosition.z, this.exponent, lightIndex);
  46123. normalizeDirection = BABYLON.Vector3.Normalize(this.transformedDirection);
  46124. }
  46125. else {
  46126. this._uniformBuffer.updateFloat4("vLightData", this.position.x, this.position.y, this.position.z, this.exponent, lightIndex);
  46127. normalizeDirection = BABYLON.Vector3.Normalize(this.direction);
  46128. }
  46129. this._uniformBuffer.updateFloat4("vLightDirection", normalizeDirection.x, normalizeDirection.y, normalizeDirection.z, Math.cos(this.angle * 0.5), lightIndex);
  46130. if (this.projectionTexture && this.projectionTexture.isReady()) {
  46131. if (this._projectionTextureViewLightDirty) {
  46132. this._computeProjectionTextureViewLightMatrix();
  46133. }
  46134. if (this._projectionTextureProjectionLightDirty) {
  46135. this._computeProjectionTextureProjectionLightMatrix();
  46136. }
  46137. if (this._projectionTextureDirty) {
  46138. this._computeProjectionTextureMatrix();
  46139. }
  46140. effect.setMatrix("textureProjectionMatrix" + lightIndex, this._projectionTextureMatrix);
  46141. effect.setTexture("projectionLightSampler" + lightIndex, this.projectionTexture);
  46142. }
  46143. return this;
  46144. };
  46145. /**
  46146. * Disposes the light and the associated resources.
  46147. */
  46148. SpotLight.prototype.dispose = function () {
  46149. _super.prototype.dispose.call(this);
  46150. if (this._projectionTexture) {
  46151. this._projectionTexture.dispose();
  46152. }
  46153. };
  46154. __decorate([
  46155. BABYLON.serialize()
  46156. ], SpotLight.prototype, "angle", null);
  46157. __decorate([
  46158. BABYLON.serialize()
  46159. ], SpotLight.prototype, "shadowAngleScale", null);
  46160. __decorate([
  46161. BABYLON.serialize()
  46162. ], SpotLight.prototype, "exponent", void 0);
  46163. __decorate([
  46164. BABYLON.serialize()
  46165. ], SpotLight.prototype, "projectionTextureLightNear", null);
  46166. __decorate([
  46167. BABYLON.serialize()
  46168. ], SpotLight.prototype, "projectionTextureLightFar", null);
  46169. __decorate([
  46170. BABYLON.serialize()
  46171. ], SpotLight.prototype, "projectionTextureUpDirection", null);
  46172. __decorate([
  46173. BABYLON.serializeAsTexture("projectedLightTexture")
  46174. ], SpotLight.prototype, "_projectionTexture", void 0);
  46175. return SpotLight;
  46176. }(BABYLON.ShadowLight));
  46177. BABYLON.SpotLight = SpotLight;
  46178. })(BABYLON || (BABYLON = {}));
  46179. //# sourceMappingURL=babylon.spotLight.js.map
  46180. var BABYLON;
  46181. (function (BABYLON) {
  46182. /**
  46183. * Class used to override all child animations of a given target
  46184. */
  46185. var AnimationPropertiesOverride = /** @class */ (function () {
  46186. function AnimationPropertiesOverride() {
  46187. /**
  46188. * Gets or sets a value indicating if animation blending must be used
  46189. */
  46190. this.enableBlending = false;
  46191. /**
  46192. * Gets or sets the blending speed to use when enableBlending is true
  46193. */
  46194. this.blendingSpeed = 0.01;
  46195. /**
  46196. * Gets or sets the default loop mode to use
  46197. */
  46198. this.loopMode = BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE;
  46199. }
  46200. return AnimationPropertiesOverride;
  46201. }());
  46202. BABYLON.AnimationPropertiesOverride = AnimationPropertiesOverride;
  46203. })(BABYLON || (BABYLON = {}));
  46204. //# sourceMappingURL=babylon.animationPropertiesOverride.js.map
  46205. var BABYLON;
  46206. (function (BABYLON) {
  46207. var AnimationRange = /** @class */ (function () {
  46208. function AnimationRange(name, from, to) {
  46209. this.name = name;
  46210. this.from = from;
  46211. this.to = to;
  46212. }
  46213. AnimationRange.prototype.clone = function () {
  46214. return new AnimationRange(this.name, this.from, this.to);
  46215. };
  46216. return AnimationRange;
  46217. }());
  46218. BABYLON.AnimationRange = AnimationRange;
  46219. /**
  46220. * Composed of a frame, and an action function
  46221. */
  46222. var AnimationEvent = /** @class */ (function () {
  46223. function AnimationEvent(frame, action, onlyOnce) {
  46224. this.frame = frame;
  46225. this.action = action;
  46226. this.onlyOnce = onlyOnce;
  46227. this.isDone = false;
  46228. }
  46229. return AnimationEvent;
  46230. }());
  46231. BABYLON.AnimationEvent = AnimationEvent;
  46232. var PathCursor = /** @class */ (function () {
  46233. function PathCursor(path) {
  46234. this.path = path;
  46235. this._onchange = new Array();
  46236. this.value = 0;
  46237. this.animations = new Array();
  46238. }
  46239. PathCursor.prototype.getPoint = function () {
  46240. var point = this.path.getPointAtLengthPosition(this.value);
  46241. return new BABYLON.Vector3(point.x, 0, point.y);
  46242. };
  46243. PathCursor.prototype.moveAhead = function (step) {
  46244. if (step === void 0) { step = 0.002; }
  46245. this.move(step);
  46246. return this;
  46247. };
  46248. PathCursor.prototype.moveBack = function (step) {
  46249. if (step === void 0) { step = 0.002; }
  46250. this.move(-step);
  46251. return this;
  46252. };
  46253. PathCursor.prototype.move = function (step) {
  46254. if (Math.abs(step) > 1) {
  46255. throw "step size should be less than 1.";
  46256. }
  46257. this.value += step;
  46258. this.ensureLimits();
  46259. this.raiseOnChange();
  46260. return this;
  46261. };
  46262. PathCursor.prototype.ensureLimits = function () {
  46263. while (this.value > 1) {
  46264. this.value -= 1;
  46265. }
  46266. while (this.value < 0) {
  46267. this.value += 1;
  46268. }
  46269. return this;
  46270. };
  46271. // used by animation engine
  46272. PathCursor.prototype.raiseOnChange = function () {
  46273. var _this = this;
  46274. this._onchange.forEach(function (f) { return f(_this); });
  46275. return this;
  46276. };
  46277. PathCursor.prototype.onchange = function (f) {
  46278. this._onchange.push(f);
  46279. return this;
  46280. };
  46281. return PathCursor;
  46282. }());
  46283. BABYLON.PathCursor = PathCursor;
  46284. var AnimationKeyInterpolation;
  46285. (function (AnimationKeyInterpolation) {
  46286. /**
  46287. * Do not interpolate between keys and use the start key value only. Tangents are ignored.
  46288. */
  46289. AnimationKeyInterpolation[AnimationKeyInterpolation["STEP"] = 1] = "STEP";
  46290. })(AnimationKeyInterpolation = BABYLON.AnimationKeyInterpolation || (BABYLON.AnimationKeyInterpolation = {}));
  46291. var Animation = /** @class */ (function () {
  46292. function Animation(name, targetProperty, framePerSecond, dataType, loopMode, enableBlending) {
  46293. this.name = name;
  46294. this.targetProperty = targetProperty;
  46295. this.framePerSecond = framePerSecond;
  46296. this.dataType = dataType;
  46297. this.loopMode = loopMode;
  46298. this.enableBlending = enableBlending;
  46299. this._runtimeAnimations = new Array();
  46300. // The set of event that will be linked to this animation
  46301. this._events = new Array();
  46302. this.blendingSpeed = 0.01;
  46303. this._ranges = {};
  46304. this.targetPropertyPath = targetProperty.split(".");
  46305. this.dataType = dataType;
  46306. this.loopMode = loopMode === undefined ? Animation.ANIMATIONLOOPMODE_CYCLE : loopMode;
  46307. }
  46308. Animation._PrepareAnimation = function (name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction) {
  46309. var dataType = undefined;
  46310. if (!isNaN(parseFloat(from)) && isFinite(from)) {
  46311. dataType = Animation.ANIMATIONTYPE_FLOAT;
  46312. }
  46313. else if (from instanceof BABYLON.Quaternion) {
  46314. dataType = Animation.ANIMATIONTYPE_QUATERNION;
  46315. }
  46316. else if (from instanceof BABYLON.Vector3) {
  46317. dataType = Animation.ANIMATIONTYPE_VECTOR3;
  46318. }
  46319. else if (from instanceof BABYLON.Vector2) {
  46320. dataType = Animation.ANIMATIONTYPE_VECTOR2;
  46321. }
  46322. else if (from instanceof BABYLON.Color3) {
  46323. dataType = Animation.ANIMATIONTYPE_COLOR3;
  46324. }
  46325. else if (from instanceof BABYLON.Size) {
  46326. dataType = Animation.ANIMATIONTYPE_SIZE;
  46327. }
  46328. if (dataType == undefined) {
  46329. return null;
  46330. }
  46331. var animation = new Animation(name, targetProperty, framePerSecond, dataType, loopMode);
  46332. var keys = [{ frame: 0, value: from }, { frame: totalFrame, value: to }];
  46333. animation.setKeys(keys);
  46334. if (easingFunction !== undefined) {
  46335. animation.setEasingFunction(easingFunction);
  46336. }
  46337. return animation;
  46338. };
  46339. /**
  46340. * Sets up an animation.
  46341. * @param property the property to animate
  46342. * @param animationType the animation type to apply
  46343. * @param easingFunction the easing function used in the animation
  46344. * @returns The created animation
  46345. */
  46346. Animation.CreateAnimation = function (property, animationType, framePerSecond, easingFunction) {
  46347. var animation = new Animation(property + "Animation", property, framePerSecond, animationType, Animation.ANIMATIONLOOPMODE_CONSTANT);
  46348. animation.setEasingFunction(easingFunction);
  46349. return animation;
  46350. };
  46351. /**
  46352. * Create and start an animation on a node
  46353. * @param {string} name defines the name of the global animation that will be run on all nodes
  46354. * @param {BABYLON.Node} node defines the root node where the animation will take place
  46355. * @param {string} targetProperty defines property to animate
  46356. * @param {number} framePerSecond defines the number of frame per second yo use
  46357. * @param {number} totalFrame defines the number of frames in total
  46358. * @param {any} from defines the initial value
  46359. * @param {any} to defines the final value
  46360. * @param {number} loopMode defines which loop mode you want to use (off by default)
  46361. * @param {BABYLON.EasingFunction} easingFunction defines the easing function to use (linear by default)
  46362. * @param onAnimationEnd defines the callback to call when animation end
  46363. * @returns the animatable created for this animation
  46364. */
  46365. Animation.CreateAndStartAnimation = function (name, node, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction, onAnimationEnd) {
  46366. var animation = Animation._PrepareAnimation(name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction);
  46367. if (!animation) {
  46368. return null;
  46369. }
  46370. return node.getScene().beginDirectAnimation(node, [animation], 0, totalFrame, (animation.loopMode === 1), 1.0, onAnimationEnd);
  46371. };
  46372. /**
  46373. * Create and start an animation on a node and its descendants
  46374. * @param {string} name defines the name of the global animation that will be run on all nodes
  46375. * @param {BABYLON.Node} node defines the root node where the animation will take place
  46376. * @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.
  46377. * @param {string} targetProperty defines property to animate
  46378. * @param {number} framePerSecond defines the number of frame per second yo use
  46379. * @param {number} totalFrame defines the number of frames in total
  46380. * @param {any} from defines the initial value
  46381. * @param {any} to defines the final value
  46382. * @param {number} loopMode defines which loop mode you want to use (off by default)
  46383. * @param {BABYLON.EasingFunction} easingFunction defines the easing function to use (linear by default)
  46384. * @param onAnimationEnd defines the callback to call when an animation ends (will be called once per node)
  46385. * @returns the list of animatables created for all nodes
  46386. * @example https://www.babylonjs-playground.com/#MH0VLI
  46387. */
  46388. Animation.CreateAndStartHierarchyAnimation = function (name, node, directDescendantsOnly, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction, onAnimationEnd) {
  46389. var animation = Animation._PrepareAnimation(name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction);
  46390. if (!animation) {
  46391. return null;
  46392. }
  46393. var scene = node.getScene();
  46394. return scene.beginDirectHierarchyAnimation(node, directDescendantsOnly, [animation], 0, totalFrame, (animation.loopMode === 1), 1.0, onAnimationEnd);
  46395. };
  46396. Animation.CreateMergeAndStartAnimation = function (name, node, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction, onAnimationEnd) {
  46397. var animation = Animation._PrepareAnimation(name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction);
  46398. if (!animation) {
  46399. return null;
  46400. }
  46401. node.animations.push(animation);
  46402. return node.getScene().beginAnimation(node, 0, totalFrame, (animation.loopMode === 1), 1.0, onAnimationEnd);
  46403. };
  46404. /**
  46405. * Transition property of the Camera to the target Value.
  46406. * @param property The property to transition
  46407. * @param targetValue The target Value of the property
  46408. * @param host The object where the property to animate belongs
  46409. * @param scene Scene used to run the animation
  46410. * @param frameRate Framerate (in frame/s) to use
  46411. * @param transition The transition type we want to use
  46412. * @param duration The duration of the animation, in milliseconds
  46413. * @param onAnimationEnd Call back trigger at the end of the animation.
  46414. */
  46415. Animation.TransitionTo = function (property, targetValue, host, scene, frameRate, transition, duration, onAnimationEnd) {
  46416. if (onAnimationEnd === void 0) { onAnimationEnd = null; }
  46417. if (duration <= 0) {
  46418. host[property] = targetValue;
  46419. if (onAnimationEnd) {
  46420. onAnimationEnd();
  46421. }
  46422. return null;
  46423. }
  46424. var endFrame = frameRate * (duration / 1000);
  46425. transition.setKeys([{
  46426. frame: 0,
  46427. value: host[property].clone ? host[property].clone() : host[property]
  46428. },
  46429. {
  46430. frame: endFrame,
  46431. value: targetValue
  46432. }]);
  46433. if (!host.animations) {
  46434. host.animations = [];
  46435. }
  46436. host.animations.push(transition);
  46437. var animation = scene.beginAnimation(host, 0, endFrame, false);
  46438. animation.onAnimationEnd = onAnimationEnd;
  46439. return animation;
  46440. };
  46441. Object.defineProperty(Animation.prototype, "runtimeAnimations", {
  46442. /**
  46443. * Return the array of runtime animations currently using this animation
  46444. */
  46445. get: function () {
  46446. return this._runtimeAnimations;
  46447. },
  46448. enumerable: true,
  46449. configurable: true
  46450. });
  46451. Object.defineProperty(Animation.prototype, "hasRunningRuntimeAnimations", {
  46452. get: function () {
  46453. for (var _i = 0, _a = this._runtimeAnimations; _i < _a.length; _i++) {
  46454. var runtimeAnimation = _a[_i];
  46455. if (!runtimeAnimation.isStopped) {
  46456. return true;
  46457. }
  46458. }
  46459. return false;
  46460. },
  46461. enumerable: true,
  46462. configurable: true
  46463. });
  46464. // Methods
  46465. /**
  46466. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  46467. */
  46468. Animation.prototype.toString = function (fullDetails) {
  46469. var ret = "Name: " + this.name + ", property: " + this.targetProperty;
  46470. ret += ", datatype: " + (["Float", "Vector3", "Quaternion", "Matrix", "Color3", "Vector2"])[this.dataType];
  46471. ret += ", nKeys: " + (this._keys ? this._keys.length : "none");
  46472. ret += ", nRanges: " + (this._ranges ? Object.keys(this._ranges).length : "none");
  46473. if (fullDetails) {
  46474. ret += ", Ranges: {";
  46475. var first = true;
  46476. for (var name in this._ranges) {
  46477. if (first) {
  46478. ret += ", ";
  46479. first = false;
  46480. }
  46481. ret += name;
  46482. }
  46483. ret += "}";
  46484. }
  46485. return ret;
  46486. };
  46487. /**
  46488. * Add an event to this animation.
  46489. */
  46490. Animation.prototype.addEvent = function (event) {
  46491. this._events.push(event);
  46492. };
  46493. /**
  46494. * Remove all events found at the given frame
  46495. * @param frame
  46496. */
  46497. Animation.prototype.removeEvents = function (frame) {
  46498. for (var index = 0; index < this._events.length; index++) {
  46499. if (this._events[index].frame === frame) {
  46500. this._events.splice(index, 1);
  46501. index--;
  46502. }
  46503. }
  46504. };
  46505. Animation.prototype.getEvents = function () {
  46506. return this._events;
  46507. };
  46508. Animation.prototype.createRange = function (name, from, to) {
  46509. // check name not already in use; could happen for bones after serialized
  46510. if (!this._ranges[name]) {
  46511. this._ranges[name] = new AnimationRange(name, from, to);
  46512. }
  46513. };
  46514. Animation.prototype.deleteRange = function (name, deleteFrames) {
  46515. if (deleteFrames === void 0) { deleteFrames = true; }
  46516. var range = this._ranges[name];
  46517. if (!range) {
  46518. return;
  46519. }
  46520. if (deleteFrames) {
  46521. var from = range.from;
  46522. var to = range.to;
  46523. // this loop MUST go high to low for multiple splices to work
  46524. for (var key = this._keys.length - 1; key >= 0; key--) {
  46525. if (this._keys[key].frame >= from && this._keys[key].frame <= to) {
  46526. this._keys.splice(key, 1);
  46527. }
  46528. }
  46529. }
  46530. this._ranges[name] = null; // said much faster than 'delete this._range[name]'
  46531. };
  46532. Animation.prototype.getRange = function (name) {
  46533. return this._ranges[name];
  46534. };
  46535. Animation.prototype.getKeys = function () {
  46536. return this._keys;
  46537. };
  46538. Animation.prototype.getHighestFrame = function () {
  46539. var ret = 0;
  46540. for (var key = 0, nKeys = this._keys.length; key < nKeys; key++) {
  46541. if (ret < this._keys[key].frame) {
  46542. ret = this._keys[key].frame;
  46543. }
  46544. }
  46545. return ret;
  46546. };
  46547. Animation.prototype.getEasingFunction = function () {
  46548. return this._easingFunction;
  46549. };
  46550. Animation.prototype.setEasingFunction = function (easingFunction) {
  46551. this._easingFunction = easingFunction;
  46552. };
  46553. Animation.prototype.floatInterpolateFunction = function (startValue, endValue, gradient) {
  46554. return BABYLON.Scalar.Lerp(startValue, endValue, gradient);
  46555. };
  46556. Animation.prototype.floatInterpolateFunctionWithTangents = function (startValue, outTangent, endValue, inTangent, gradient) {
  46557. return BABYLON.Scalar.Hermite(startValue, outTangent, endValue, inTangent, gradient);
  46558. };
  46559. Animation.prototype.quaternionInterpolateFunction = function (startValue, endValue, gradient) {
  46560. return BABYLON.Quaternion.Slerp(startValue, endValue, gradient);
  46561. };
  46562. Animation.prototype.quaternionInterpolateFunctionWithTangents = function (startValue, outTangent, endValue, inTangent, gradient) {
  46563. return BABYLON.Quaternion.Hermite(startValue, outTangent, endValue, inTangent, gradient).normalize();
  46564. };
  46565. Animation.prototype.vector3InterpolateFunction = function (startValue, endValue, gradient) {
  46566. return BABYLON.Vector3.Lerp(startValue, endValue, gradient);
  46567. };
  46568. Animation.prototype.vector3InterpolateFunctionWithTangents = function (startValue, outTangent, endValue, inTangent, gradient) {
  46569. return BABYLON.Vector3.Hermite(startValue, outTangent, endValue, inTangent, gradient);
  46570. };
  46571. Animation.prototype.vector2InterpolateFunction = function (startValue, endValue, gradient) {
  46572. return BABYLON.Vector2.Lerp(startValue, endValue, gradient);
  46573. };
  46574. Animation.prototype.vector2InterpolateFunctionWithTangents = function (startValue, outTangent, endValue, inTangent, gradient) {
  46575. return BABYLON.Vector2.Hermite(startValue, outTangent, endValue, inTangent, gradient);
  46576. };
  46577. Animation.prototype.sizeInterpolateFunction = function (startValue, endValue, gradient) {
  46578. return BABYLON.Size.Lerp(startValue, endValue, gradient);
  46579. };
  46580. Animation.prototype.color3InterpolateFunction = function (startValue, endValue, gradient) {
  46581. return BABYLON.Color3.Lerp(startValue, endValue, gradient);
  46582. };
  46583. Animation.prototype.matrixInterpolateFunction = function (startValue, endValue, gradient) {
  46584. return BABYLON.Matrix.Lerp(startValue, endValue, gradient);
  46585. };
  46586. Animation.prototype.clone = function () {
  46587. var clone = new Animation(this.name, this.targetPropertyPath.join("."), this.framePerSecond, this.dataType, this.loopMode);
  46588. clone.enableBlending = this.enableBlending;
  46589. clone.blendingSpeed = this.blendingSpeed;
  46590. if (this._keys) {
  46591. clone.setKeys(this._keys);
  46592. }
  46593. if (this._ranges) {
  46594. clone._ranges = {};
  46595. for (var name in this._ranges) {
  46596. var range = this._ranges[name];
  46597. if (!range) {
  46598. continue;
  46599. }
  46600. clone._ranges[name] = range.clone();
  46601. }
  46602. }
  46603. return clone;
  46604. };
  46605. Animation.prototype.setKeys = function (values) {
  46606. this._keys = values.slice(0);
  46607. };
  46608. Animation.prototype.serialize = function () {
  46609. var serializationObject = {};
  46610. serializationObject.name = this.name;
  46611. serializationObject.property = this.targetProperty;
  46612. serializationObject.framePerSecond = this.framePerSecond;
  46613. serializationObject.dataType = this.dataType;
  46614. serializationObject.loopBehavior = this.loopMode;
  46615. serializationObject.enableBlending = this.enableBlending;
  46616. serializationObject.blendingSpeed = this.blendingSpeed;
  46617. var dataType = this.dataType;
  46618. serializationObject.keys = [];
  46619. var keys = this.getKeys();
  46620. for (var index = 0; index < keys.length; index++) {
  46621. var animationKey = keys[index];
  46622. var key = {};
  46623. key.frame = animationKey.frame;
  46624. switch (dataType) {
  46625. case Animation.ANIMATIONTYPE_FLOAT:
  46626. key.values = [animationKey.value];
  46627. break;
  46628. case Animation.ANIMATIONTYPE_QUATERNION:
  46629. case Animation.ANIMATIONTYPE_MATRIX:
  46630. case Animation.ANIMATIONTYPE_VECTOR3:
  46631. case Animation.ANIMATIONTYPE_COLOR3:
  46632. key.values = animationKey.value.asArray();
  46633. break;
  46634. }
  46635. serializationObject.keys.push(key);
  46636. }
  46637. serializationObject.ranges = [];
  46638. for (var name in this._ranges) {
  46639. var source = this._ranges[name];
  46640. if (!source) {
  46641. continue;
  46642. }
  46643. var range = {};
  46644. range.name = name;
  46645. range.from = source.from;
  46646. range.to = source.to;
  46647. serializationObject.ranges.push(range);
  46648. }
  46649. return serializationObject;
  46650. };
  46651. Object.defineProperty(Animation, "ANIMATIONTYPE_FLOAT", {
  46652. get: function () {
  46653. return Animation._ANIMATIONTYPE_FLOAT;
  46654. },
  46655. enumerable: true,
  46656. configurable: true
  46657. });
  46658. Object.defineProperty(Animation, "ANIMATIONTYPE_VECTOR3", {
  46659. get: function () {
  46660. return Animation._ANIMATIONTYPE_VECTOR3;
  46661. },
  46662. enumerable: true,
  46663. configurable: true
  46664. });
  46665. Object.defineProperty(Animation, "ANIMATIONTYPE_VECTOR2", {
  46666. get: function () {
  46667. return Animation._ANIMATIONTYPE_VECTOR2;
  46668. },
  46669. enumerable: true,
  46670. configurable: true
  46671. });
  46672. Object.defineProperty(Animation, "ANIMATIONTYPE_SIZE", {
  46673. get: function () {
  46674. return Animation._ANIMATIONTYPE_SIZE;
  46675. },
  46676. enumerable: true,
  46677. configurable: true
  46678. });
  46679. Object.defineProperty(Animation, "ANIMATIONTYPE_QUATERNION", {
  46680. get: function () {
  46681. return Animation._ANIMATIONTYPE_QUATERNION;
  46682. },
  46683. enumerable: true,
  46684. configurable: true
  46685. });
  46686. Object.defineProperty(Animation, "ANIMATIONTYPE_MATRIX", {
  46687. get: function () {
  46688. return Animation._ANIMATIONTYPE_MATRIX;
  46689. },
  46690. enumerable: true,
  46691. configurable: true
  46692. });
  46693. Object.defineProperty(Animation, "ANIMATIONTYPE_COLOR3", {
  46694. get: function () {
  46695. return Animation._ANIMATIONTYPE_COLOR3;
  46696. },
  46697. enumerable: true,
  46698. configurable: true
  46699. });
  46700. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_RELATIVE", {
  46701. get: function () {
  46702. return Animation._ANIMATIONLOOPMODE_RELATIVE;
  46703. },
  46704. enumerable: true,
  46705. configurable: true
  46706. });
  46707. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_CYCLE", {
  46708. get: function () {
  46709. return Animation._ANIMATIONLOOPMODE_CYCLE;
  46710. },
  46711. enumerable: true,
  46712. configurable: true
  46713. });
  46714. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_CONSTANT", {
  46715. get: function () {
  46716. return Animation._ANIMATIONLOOPMODE_CONSTANT;
  46717. },
  46718. enumerable: true,
  46719. configurable: true
  46720. });
  46721. Animation.Parse = function (parsedAnimation) {
  46722. var animation = new Animation(parsedAnimation.name, parsedAnimation.property, parsedAnimation.framePerSecond, parsedAnimation.dataType, parsedAnimation.loopBehavior);
  46723. var dataType = parsedAnimation.dataType;
  46724. var keys = [];
  46725. var data;
  46726. var index;
  46727. if (parsedAnimation.enableBlending) {
  46728. animation.enableBlending = parsedAnimation.enableBlending;
  46729. }
  46730. if (parsedAnimation.blendingSpeed) {
  46731. animation.blendingSpeed = parsedAnimation.blendingSpeed;
  46732. }
  46733. for (index = 0; index < parsedAnimation.keys.length; index++) {
  46734. var key = parsedAnimation.keys[index];
  46735. var inTangent;
  46736. var outTangent;
  46737. switch (dataType) {
  46738. case Animation.ANIMATIONTYPE_FLOAT:
  46739. data = key.values[0];
  46740. if (key.values.length >= 1) {
  46741. inTangent = key.values[1];
  46742. }
  46743. if (key.values.length >= 2) {
  46744. outTangent = key.values[2];
  46745. }
  46746. break;
  46747. case Animation.ANIMATIONTYPE_QUATERNION:
  46748. data = BABYLON.Quaternion.FromArray(key.values);
  46749. if (key.values.length >= 8) {
  46750. var _inTangent = BABYLON.Quaternion.FromArray(key.values.slice(4, 8));
  46751. if (!_inTangent.equals(BABYLON.Quaternion.Zero())) {
  46752. inTangent = _inTangent;
  46753. }
  46754. }
  46755. if (key.values.length >= 12) {
  46756. var _outTangent = BABYLON.Quaternion.FromArray(key.values.slice(8, 12));
  46757. if (!_outTangent.equals(BABYLON.Quaternion.Zero())) {
  46758. outTangent = _outTangent;
  46759. }
  46760. }
  46761. break;
  46762. case Animation.ANIMATIONTYPE_MATRIX:
  46763. data = BABYLON.Matrix.FromArray(key.values);
  46764. break;
  46765. case Animation.ANIMATIONTYPE_COLOR3:
  46766. data = BABYLON.Color3.FromArray(key.values);
  46767. break;
  46768. case Animation.ANIMATIONTYPE_VECTOR3:
  46769. default:
  46770. data = BABYLON.Vector3.FromArray(key.values);
  46771. break;
  46772. }
  46773. var keyData = {};
  46774. keyData.frame = key.frame;
  46775. keyData.value = data;
  46776. if (inTangent != undefined) {
  46777. keyData.inTangent = inTangent;
  46778. }
  46779. if (outTangent != undefined) {
  46780. keyData.outTangent = outTangent;
  46781. }
  46782. keys.push(keyData);
  46783. }
  46784. animation.setKeys(keys);
  46785. if (parsedAnimation.ranges) {
  46786. for (index = 0; index < parsedAnimation.ranges.length; index++) {
  46787. data = parsedAnimation.ranges[index];
  46788. animation.createRange(data.name, data.from, data.to);
  46789. }
  46790. }
  46791. return animation;
  46792. };
  46793. Animation.AppendSerializedAnimations = function (source, destination) {
  46794. if (source.animations) {
  46795. destination.animations = [];
  46796. for (var animationIndex = 0; animationIndex < source.animations.length; animationIndex++) {
  46797. var animation = source.animations[animationIndex];
  46798. destination.animations.push(animation.serialize());
  46799. }
  46800. }
  46801. };
  46802. Animation.AllowMatricesInterpolation = false;
  46803. // Statics
  46804. Animation._ANIMATIONTYPE_FLOAT = 0;
  46805. Animation._ANIMATIONTYPE_VECTOR3 = 1;
  46806. Animation._ANIMATIONTYPE_QUATERNION = 2;
  46807. Animation._ANIMATIONTYPE_MATRIX = 3;
  46808. Animation._ANIMATIONTYPE_COLOR3 = 4;
  46809. Animation._ANIMATIONTYPE_VECTOR2 = 5;
  46810. Animation._ANIMATIONTYPE_SIZE = 6;
  46811. Animation._ANIMATIONLOOPMODE_RELATIVE = 0;
  46812. Animation._ANIMATIONLOOPMODE_CYCLE = 1;
  46813. Animation._ANIMATIONLOOPMODE_CONSTANT = 2;
  46814. return Animation;
  46815. }());
  46816. BABYLON.Animation = Animation;
  46817. })(BABYLON || (BABYLON = {}));
  46818. //# sourceMappingURL=babylon.animation.js.map
  46819. var BABYLON;
  46820. (function (BABYLON) {
  46821. /**
  46822. * This class defines the direct association between an animation and a target
  46823. */
  46824. var TargetedAnimation = /** @class */ (function () {
  46825. function TargetedAnimation() {
  46826. }
  46827. return TargetedAnimation;
  46828. }());
  46829. BABYLON.TargetedAnimation = TargetedAnimation;
  46830. /**
  46831. * Use this class to create coordinated animations on multiple targets
  46832. */
  46833. var AnimationGroup = /** @class */ (function () {
  46834. function AnimationGroup(name, scene) {
  46835. if (scene === void 0) { scene = null; }
  46836. this.name = name;
  46837. this._targetedAnimations = new Array();
  46838. this._animatables = new Array();
  46839. this._from = Number.MAX_VALUE;
  46840. this._to = -Number.MAX_VALUE;
  46841. this._speedRatio = 1;
  46842. this.onAnimationEndObservable = new BABYLON.Observable();
  46843. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  46844. this._scene.animationGroups.push(this);
  46845. }
  46846. Object.defineProperty(AnimationGroup.prototype, "isStarted", {
  46847. /**
  46848. * Define if the animations are started
  46849. */
  46850. get: function () {
  46851. return this._isStarted;
  46852. },
  46853. enumerable: true,
  46854. configurable: true
  46855. });
  46856. Object.defineProperty(AnimationGroup.prototype, "speedRatio", {
  46857. /**
  46858. * Gets or sets the speed ratio to use for all animations
  46859. */
  46860. get: function () {
  46861. return this._speedRatio;
  46862. },
  46863. /**
  46864. * Gets or sets the speed ratio to use for all animations
  46865. */
  46866. set: function (value) {
  46867. if (this._speedRatio === value) {
  46868. return;
  46869. }
  46870. this._speedRatio = value;
  46871. for (var index = 0; index < this._animatables.length; index++) {
  46872. var animatable = this._animatables[index];
  46873. animatable.speedRatio = this._speedRatio;
  46874. }
  46875. },
  46876. enumerable: true,
  46877. configurable: true
  46878. });
  46879. Object.defineProperty(AnimationGroup.prototype, "targetedAnimations", {
  46880. /**
  46881. * Gets the targeted animations for this animation group
  46882. */
  46883. get: function () {
  46884. return this._targetedAnimations;
  46885. },
  46886. enumerable: true,
  46887. configurable: true
  46888. });
  46889. Object.defineProperty(AnimationGroup.prototype, "animatables", {
  46890. /**
  46891. * returning the list of animatables controlled by this animation group.
  46892. */
  46893. get: function () {
  46894. return this._animatables;
  46895. },
  46896. enumerable: true,
  46897. configurable: true
  46898. });
  46899. /**
  46900. * Add an animation (with its target) in the group
  46901. * @param animation defines the animation we want to add
  46902. * @param target defines the target of the animation
  46903. * @returns the {BABYLON.TargetedAnimation} object
  46904. */
  46905. AnimationGroup.prototype.addTargetedAnimation = function (animation, target) {
  46906. var targetedAnimation = {
  46907. animation: animation,
  46908. target: target
  46909. };
  46910. var keys = animation.getKeys();
  46911. if (this._from > keys[0].frame) {
  46912. this._from = keys[0].frame;
  46913. }
  46914. if (this._to < keys[keys.length - 1].frame) {
  46915. this._to = keys[keys.length - 1].frame;
  46916. }
  46917. this._targetedAnimations.push(targetedAnimation);
  46918. return targetedAnimation;
  46919. };
  46920. /**
  46921. * This function will normalize every animation in the group to make sure they all go from beginFrame to endFrame
  46922. * It can add constant keys at begin or end
  46923. * @param beginFrame defines the new begin frame for all animations. It can't be bigger than the smallest begin frame of all animations
  46924. * @param endFrame defines the new end frame for all animations. It can't be smaller than the largest end frame of all animations
  46925. */
  46926. AnimationGroup.prototype.normalize = function (beginFrame, endFrame) {
  46927. if (beginFrame === void 0) { beginFrame = -Number.MAX_VALUE; }
  46928. if (endFrame === void 0) { endFrame = Number.MAX_VALUE; }
  46929. beginFrame = Math.max(beginFrame, this._from);
  46930. endFrame = Math.min(endFrame, this._to);
  46931. for (var index = 0; index < this._targetedAnimations.length; index++) {
  46932. var targetedAnimation = this._targetedAnimations[index];
  46933. var keys = targetedAnimation.animation.getKeys();
  46934. var startKey = keys[0];
  46935. var endKey = keys[keys.length - 1];
  46936. if (startKey.frame > beginFrame) {
  46937. var newKey = {
  46938. frame: beginFrame,
  46939. value: startKey.value,
  46940. inTangent: startKey.inTangent,
  46941. outTangent: startKey.outTangent,
  46942. interpolation: startKey.interpolation
  46943. };
  46944. keys.splice(0, 0, newKey);
  46945. }
  46946. if (endKey.frame < endFrame) {
  46947. var newKey = {
  46948. frame: endFrame,
  46949. value: endKey.value,
  46950. inTangent: endKey.outTangent,
  46951. outTangent: endKey.outTangent,
  46952. interpolation: endKey.interpolation
  46953. };
  46954. keys.push(newKey);
  46955. }
  46956. }
  46957. return this;
  46958. };
  46959. /**
  46960. * Start all animations on given targets
  46961. * @param loop defines if animations must loop
  46962. * @param speedRatio defines the ratio to apply to animation speed (1 by default)
  46963. */
  46964. AnimationGroup.prototype.start = function (loop, speedRatio) {
  46965. var _this = this;
  46966. if (loop === void 0) { loop = false; }
  46967. if (speedRatio === void 0) { speedRatio = 1; }
  46968. if (this._isStarted || this._targetedAnimations.length === 0) {
  46969. return this;
  46970. }
  46971. var _loop_1 = function () {
  46972. var targetedAnimation = this_1._targetedAnimations[index];
  46973. this_1._animatables.push(this_1._scene.beginDirectAnimation(targetedAnimation.target, [targetedAnimation.animation], this_1._from, this_1._to, loop, speedRatio, function () {
  46974. _this.onAnimationEndObservable.notifyObservers(targetedAnimation);
  46975. }));
  46976. };
  46977. var this_1 = this;
  46978. for (var index = 0; index < this._targetedAnimations.length; index++) {
  46979. _loop_1();
  46980. }
  46981. this._speedRatio = speedRatio;
  46982. this._isStarted = true;
  46983. return this;
  46984. };
  46985. /**
  46986. * Pause all animations
  46987. */
  46988. AnimationGroup.prototype.pause = function () {
  46989. if (!this._isStarted) {
  46990. return this;
  46991. }
  46992. for (var index = 0; index < this._animatables.length; index++) {
  46993. var animatable = this._animatables[index];
  46994. animatable.pause();
  46995. }
  46996. return this;
  46997. };
  46998. /**
  46999. * Play all animations to initial state
  47000. * This function will start() the animations if they were not started or will restart() them if they were paused
  47001. * @param loop defines if animations must loop
  47002. */
  47003. AnimationGroup.prototype.play = function (loop) {
  47004. if (this.isStarted) {
  47005. if (loop !== undefined) {
  47006. for (var index = 0; index < this._animatables.length; index++) {
  47007. var animatable = this._animatables[index];
  47008. animatable.loopAnimation = loop;
  47009. }
  47010. }
  47011. this.restart();
  47012. }
  47013. else {
  47014. this.start(loop, this._speedRatio);
  47015. }
  47016. return this;
  47017. };
  47018. /**
  47019. * Reset all animations to initial state
  47020. */
  47021. AnimationGroup.prototype.reset = function () {
  47022. if (!this._isStarted) {
  47023. return this;
  47024. }
  47025. for (var index = 0; index < this._animatables.length; index++) {
  47026. var animatable = this._animatables[index];
  47027. animatable.reset();
  47028. }
  47029. return this;
  47030. };
  47031. /**
  47032. * Restart animations from key 0
  47033. */
  47034. AnimationGroup.prototype.restart = function () {
  47035. if (!this._isStarted) {
  47036. return this;
  47037. }
  47038. for (var index = 0; index < this._animatables.length; index++) {
  47039. var animatable = this._animatables[index];
  47040. animatable.restart();
  47041. }
  47042. return this;
  47043. };
  47044. /**
  47045. * Stop all animations
  47046. */
  47047. AnimationGroup.prototype.stop = function () {
  47048. if (!this._isStarted) {
  47049. return this;
  47050. }
  47051. for (var index = 0; index < this._animatables.length; index++) {
  47052. var animatable = this._animatables[index];
  47053. animatable.stop();
  47054. }
  47055. this._isStarted = false;
  47056. return this;
  47057. };
  47058. /**
  47059. * Goes to a specific frame in this animation group
  47060. *
  47061. * @param frame the frame number to go to
  47062. * @return the animationGroup
  47063. */
  47064. AnimationGroup.prototype.goToFrame = function (frame) {
  47065. if (!this._isStarted) {
  47066. return this;
  47067. }
  47068. for (var index = 0; index < this._animatables.length; index++) {
  47069. var animatable = this._animatables[index];
  47070. animatable.goToFrame(frame);
  47071. }
  47072. return this;
  47073. };
  47074. /**
  47075. * Dispose all associated resources
  47076. */
  47077. AnimationGroup.prototype.dispose = function () {
  47078. this._targetedAnimations = [];
  47079. this._animatables = [];
  47080. var index = this._scene.animationGroups.indexOf(this);
  47081. if (index > -1) {
  47082. this._scene.animationGroups.splice(index, 1);
  47083. }
  47084. };
  47085. return AnimationGroup;
  47086. }());
  47087. BABYLON.AnimationGroup = AnimationGroup;
  47088. })(BABYLON || (BABYLON = {}));
  47089. //# sourceMappingURL=babylon.animationGroup.js.map
  47090. var BABYLON;
  47091. (function (BABYLON) {
  47092. var RuntimeAnimation = /** @class */ (function () {
  47093. function RuntimeAnimation(target, animation) {
  47094. this._offsetsCache = {};
  47095. this._highLimitsCache = {};
  47096. this._stopped = false;
  47097. this._blendingFactor = 0;
  47098. this._ratioOffset = 0;
  47099. this._animation = animation;
  47100. this._target = target;
  47101. animation._runtimeAnimations.push(this);
  47102. }
  47103. Object.defineProperty(RuntimeAnimation.prototype, "animation", {
  47104. get: function () {
  47105. return this._animation;
  47106. },
  47107. enumerable: true,
  47108. configurable: true
  47109. });
  47110. RuntimeAnimation.prototype.reset = function () {
  47111. this._offsetsCache = {};
  47112. this._highLimitsCache = {};
  47113. this.currentFrame = 0;
  47114. this._blendingFactor = 0;
  47115. this._originalBlendValue = null;
  47116. };
  47117. RuntimeAnimation.prototype.isStopped = function () {
  47118. return this._stopped;
  47119. };
  47120. RuntimeAnimation.prototype.dispose = function () {
  47121. var index = this._animation.runtimeAnimations.indexOf(this);
  47122. if (index > -1) {
  47123. this._animation.runtimeAnimations.splice(index, 1);
  47124. }
  47125. };
  47126. RuntimeAnimation.prototype._getKeyValue = function (value) {
  47127. if (typeof value === "function") {
  47128. return value();
  47129. }
  47130. return value;
  47131. };
  47132. RuntimeAnimation.prototype._interpolate = function (currentFrame, repeatCount, loopMode, offsetValue, highLimitValue) {
  47133. if (loopMode === BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT && repeatCount > 0) {
  47134. return highLimitValue.clone ? highLimitValue.clone() : highLimitValue;
  47135. }
  47136. this.currentFrame = currentFrame;
  47137. var keys = this._animation.getKeys();
  47138. // Try to get a hash to find the right key
  47139. 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));
  47140. if (keys[startKeyIndex].frame >= currentFrame) {
  47141. while (startKeyIndex - 1 >= 0 && keys[startKeyIndex].frame >= currentFrame) {
  47142. startKeyIndex--;
  47143. }
  47144. }
  47145. for (var key = startKeyIndex; key < keys.length; key++) {
  47146. var endKey = keys[key + 1];
  47147. if (endKey.frame >= currentFrame) {
  47148. var startKey = keys[key];
  47149. var startValue = this._getKeyValue(startKey.value);
  47150. if (startKey.interpolation === BABYLON.AnimationKeyInterpolation.STEP) {
  47151. return startValue;
  47152. }
  47153. var endValue = this._getKeyValue(endKey.value);
  47154. var useTangent = startKey.outTangent !== undefined && endKey.inTangent !== undefined;
  47155. var frameDelta = endKey.frame - startKey.frame;
  47156. // gradient : percent of currentFrame between the frame inf and the frame sup
  47157. var gradient = (currentFrame - startKey.frame) / frameDelta;
  47158. // check for easingFunction and correction of gradient
  47159. var easingFunction = this._animation.getEasingFunction();
  47160. if (easingFunction != null) {
  47161. gradient = easingFunction.ease(gradient);
  47162. }
  47163. switch (this._animation.dataType) {
  47164. // Float
  47165. case BABYLON.Animation.ANIMATIONTYPE_FLOAT:
  47166. var floatValue = useTangent ? this._animation.floatInterpolateFunctionWithTangents(startValue, startKey.outTangent * frameDelta, endValue, endKey.inTangent * frameDelta, gradient) : this._animation.floatInterpolateFunction(startValue, endValue, gradient);
  47167. switch (loopMode) {
  47168. case BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE:
  47169. case BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT:
  47170. return floatValue;
  47171. case BABYLON.Animation.ANIMATIONLOOPMODE_RELATIVE:
  47172. return offsetValue * repeatCount + floatValue;
  47173. }
  47174. break;
  47175. // Quaternion
  47176. case BABYLON.Animation.ANIMATIONTYPE_QUATERNION:
  47177. var quatValue = useTangent ? this._animation.quaternionInterpolateFunctionWithTangents(startValue, startKey.outTangent.scale(frameDelta), endValue, endKey.inTangent.scale(frameDelta), gradient) : this._animation.quaternionInterpolateFunction(startValue, endValue, gradient);
  47178. switch (loopMode) {
  47179. case BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE:
  47180. case BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT:
  47181. return quatValue;
  47182. case BABYLON.Animation.ANIMATIONLOOPMODE_RELATIVE:
  47183. return quatValue.add(offsetValue.scale(repeatCount));
  47184. }
  47185. return quatValue;
  47186. // Vector3
  47187. case BABYLON.Animation.ANIMATIONTYPE_VECTOR3:
  47188. var vec3Value = useTangent ? this._animation.vector3InterpolateFunctionWithTangents(startValue, startKey.outTangent.scale(frameDelta), endValue, endKey.inTangent.scale(frameDelta), gradient) : this._animation.vector3InterpolateFunction(startValue, endValue, gradient);
  47189. switch (loopMode) {
  47190. case BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE:
  47191. case BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT:
  47192. return vec3Value;
  47193. case BABYLON.Animation.ANIMATIONLOOPMODE_RELATIVE:
  47194. return vec3Value.add(offsetValue.scale(repeatCount));
  47195. }
  47196. // Vector2
  47197. case BABYLON.Animation.ANIMATIONTYPE_VECTOR2:
  47198. var vec2Value = useTangent ? this._animation.vector2InterpolateFunctionWithTangents(startValue, startKey.outTangent.scale(frameDelta), endValue, endKey.inTangent.scale(frameDelta), gradient) : this._animation.vector2InterpolateFunction(startValue, endValue, gradient);
  47199. switch (loopMode) {
  47200. case BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE:
  47201. case BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT:
  47202. return vec2Value;
  47203. case BABYLON.Animation.ANIMATIONLOOPMODE_RELATIVE:
  47204. return vec2Value.add(offsetValue.scale(repeatCount));
  47205. }
  47206. // Size
  47207. case BABYLON.Animation.ANIMATIONTYPE_SIZE:
  47208. switch (loopMode) {
  47209. case BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE:
  47210. case BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT:
  47211. return this._animation.sizeInterpolateFunction(startValue, endValue, gradient);
  47212. case BABYLON.Animation.ANIMATIONLOOPMODE_RELATIVE:
  47213. return this._animation.sizeInterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  47214. }
  47215. // Color3
  47216. case BABYLON.Animation.ANIMATIONTYPE_COLOR3:
  47217. switch (loopMode) {
  47218. case BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE:
  47219. case BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT:
  47220. return this._animation.color3InterpolateFunction(startValue, endValue, gradient);
  47221. case BABYLON.Animation.ANIMATIONLOOPMODE_RELATIVE:
  47222. return this._animation.color3InterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  47223. }
  47224. // Matrix
  47225. case BABYLON.Animation.ANIMATIONTYPE_MATRIX:
  47226. switch (loopMode) {
  47227. case BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE:
  47228. case BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT:
  47229. if (BABYLON.Animation.AllowMatricesInterpolation) {
  47230. return this._animation.matrixInterpolateFunction(startValue, endValue, gradient);
  47231. }
  47232. case BABYLON.Animation.ANIMATIONLOOPMODE_RELATIVE:
  47233. return startValue;
  47234. }
  47235. default:
  47236. break;
  47237. }
  47238. break;
  47239. }
  47240. }
  47241. return this._getKeyValue(keys[keys.length - 1].value);
  47242. };
  47243. RuntimeAnimation.prototype.setValue = function (currentValue, blend) {
  47244. if (blend === void 0) { blend = false; }
  47245. // Set value
  47246. var path;
  47247. var destination;
  47248. var targetPropertyPath = this._animation.targetPropertyPath;
  47249. if (targetPropertyPath.length > 1) {
  47250. var property = this._target[targetPropertyPath[0]];
  47251. for (var index = 1; index < targetPropertyPath.length - 1; index++) {
  47252. property = property[targetPropertyPath[index]];
  47253. }
  47254. path = targetPropertyPath[targetPropertyPath.length - 1];
  47255. destination = property;
  47256. }
  47257. else {
  47258. path = targetPropertyPath[0];
  47259. destination = this._target;
  47260. }
  47261. // Blending
  47262. var enableBlending = this._target && this._target.animationPropertiesOverride ? this._target.animationPropertiesOverride.enableBlending : this._animation.enableBlending;
  47263. var blendingSpeed = this._target && this._target.animationPropertiesOverride ? this._target.animationPropertiesOverride.blendingSpeed : this._animation.blendingSpeed;
  47264. if (enableBlending && this._blendingFactor <= 1.0) {
  47265. if (!this._originalBlendValue) {
  47266. if (destination[path].clone) {
  47267. this._originalBlendValue = destination[path].clone();
  47268. }
  47269. else {
  47270. this._originalBlendValue = destination[path];
  47271. }
  47272. }
  47273. if (this._originalBlendValue.prototype) {
  47274. if (this._originalBlendValue.prototype.Lerp) {
  47275. destination[path] = this._originalBlendValue.construtor.prototype.Lerp(currentValue, this._originalBlendValue, this._blendingFactor);
  47276. }
  47277. else {
  47278. destination[path] = currentValue;
  47279. }
  47280. }
  47281. else if (this._originalBlendValue.m) {
  47282. destination[path] = BABYLON.Matrix.Lerp(this._originalBlendValue, currentValue, this._blendingFactor);
  47283. }
  47284. else {
  47285. destination[path] = this._originalBlendValue * (1.0 - this._blendingFactor) + this._blendingFactor * currentValue;
  47286. }
  47287. this._blendingFactor += blendingSpeed;
  47288. }
  47289. else {
  47290. destination[path] = currentValue;
  47291. }
  47292. if (this._target.markAsDirty) {
  47293. this._target.markAsDirty(this._animation.targetProperty);
  47294. }
  47295. };
  47296. RuntimeAnimation.prototype._getCorrectLoopMode = function () {
  47297. if (this._target && this._target.animationPropertiesOverride) {
  47298. return this._target.animationPropertiesOverride.loopMode;
  47299. }
  47300. return this._animation.loopMode;
  47301. };
  47302. RuntimeAnimation.prototype.goToFrame = function (frame) {
  47303. var keys = this._animation.getKeys();
  47304. if (frame < keys[0].frame) {
  47305. frame = keys[0].frame;
  47306. }
  47307. else if (frame > keys[keys.length - 1].frame) {
  47308. frame = keys[keys.length - 1].frame;
  47309. }
  47310. var currentValue = this._interpolate(frame, 0, this._getCorrectLoopMode());
  47311. this.setValue(currentValue);
  47312. };
  47313. RuntimeAnimation.prototype._prepareForSpeedRatioChange = function (newSpeedRatio) {
  47314. var newRatio = this._previousDelay * (this._animation.framePerSecond * newSpeedRatio) / 1000.0;
  47315. this._ratioOffset = this._previousRatio - newRatio;
  47316. };
  47317. RuntimeAnimation.prototype.animate = function (delay, from, to, loop, speedRatio, blend) {
  47318. if (blend === void 0) { blend = false; }
  47319. var targetPropertyPath = this._animation.targetPropertyPath;
  47320. if (!targetPropertyPath || targetPropertyPath.length < 1) {
  47321. this._stopped = true;
  47322. return false;
  47323. }
  47324. var returnValue = true;
  47325. var keys = this._animation.getKeys();
  47326. // Adding a start key at frame 0 if missing
  47327. if (keys[0].frame !== 0) {
  47328. var newKey = { frame: 0, value: keys[0].value };
  47329. keys.splice(0, 0, newKey);
  47330. }
  47331. // Check limits
  47332. if (from < keys[0].frame || from > keys[keys.length - 1].frame) {
  47333. from = keys[0].frame;
  47334. }
  47335. if (to < keys[0].frame || to > keys[keys.length - 1].frame) {
  47336. to = keys[keys.length - 1].frame;
  47337. }
  47338. //to and from cannot be the same key
  47339. if (from === to) {
  47340. if (from > keys[0].frame) {
  47341. from--;
  47342. }
  47343. else if (to < keys[keys.length - 1].frame) {
  47344. to++;
  47345. }
  47346. }
  47347. // Compute ratio
  47348. var range = to - from;
  47349. var offsetValue;
  47350. // ratio represents the frame delta between from and to
  47351. var ratio = (delay * (this._animation.framePerSecond * speedRatio) / 1000.0) + this._ratioOffset;
  47352. var highLimitValue = 0;
  47353. this._previousDelay = delay;
  47354. this._previousRatio = ratio;
  47355. if (((to > from && ratio > range) || (from > to && ratio < range)) && !loop) {
  47356. returnValue = false;
  47357. highLimitValue = this._getKeyValue(keys[keys.length - 1].value);
  47358. }
  47359. else {
  47360. // Get max value if required
  47361. if (this._getCorrectLoopMode() !== BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE) {
  47362. var keyOffset = to.toString() + from.toString();
  47363. if (!this._offsetsCache[keyOffset]) {
  47364. var fromValue = this._interpolate(from, 0, BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE);
  47365. var toValue = this._interpolate(to, 0, BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE);
  47366. switch (this._animation.dataType) {
  47367. // Float
  47368. case BABYLON.Animation.ANIMATIONTYPE_FLOAT:
  47369. this._offsetsCache[keyOffset] = toValue - fromValue;
  47370. break;
  47371. // Quaternion
  47372. case BABYLON.Animation.ANIMATIONTYPE_QUATERNION:
  47373. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  47374. break;
  47375. // Vector3
  47376. case BABYLON.Animation.ANIMATIONTYPE_VECTOR3:
  47377. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  47378. // Vector2
  47379. case BABYLON.Animation.ANIMATIONTYPE_VECTOR2:
  47380. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  47381. // Size
  47382. case BABYLON.Animation.ANIMATIONTYPE_SIZE:
  47383. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  47384. // Color3
  47385. case BABYLON.Animation.ANIMATIONTYPE_COLOR3:
  47386. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  47387. default:
  47388. break;
  47389. }
  47390. this._highLimitsCache[keyOffset] = toValue;
  47391. }
  47392. highLimitValue = this._highLimitsCache[keyOffset];
  47393. offsetValue = this._offsetsCache[keyOffset];
  47394. }
  47395. }
  47396. if (offsetValue === undefined) {
  47397. switch (this._animation.dataType) {
  47398. // Float
  47399. case BABYLON.Animation.ANIMATIONTYPE_FLOAT:
  47400. offsetValue = 0;
  47401. break;
  47402. // Quaternion
  47403. case BABYLON.Animation.ANIMATIONTYPE_QUATERNION:
  47404. offsetValue = new BABYLON.Quaternion(0, 0, 0, 0);
  47405. break;
  47406. // Vector3
  47407. case BABYLON.Animation.ANIMATIONTYPE_VECTOR3:
  47408. offsetValue = BABYLON.Vector3.Zero();
  47409. break;
  47410. // Vector2
  47411. case BABYLON.Animation.ANIMATIONTYPE_VECTOR2:
  47412. offsetValue = BABYLON.Vector2.Zero();
  47413. break;
  47414. // Size
  47415. case BABYLON.Animation.ANIMATIONTYPE_SIZE:
  47416. offsetValue = BABYLON.Size.Zero();
  47417. break;
  47418. // Color3
  47419. case BABYLON.Animation.ANIMATIONTYPE_COLOR3:
  47420. offsetValue = BABYLON.Color3.Black();
  47421. }
  47422. }
  47423. // Compute value
  47424. var repeatCount = (ratio / range) >> 0;
  47425. var currentFrame = returnValue ? from + ratio % range : to;
  47426. var currentValue = this._interpolate(currentFrame, repeatCount, this._getCorrectLoopMode(), offsetValue, highLimitValue);
  47427. // Set value
  47428. this.setValue(currentValue);
  47429. // Check events
  47430. var events = this._animation.getEvents();
  47431. for (var index = 0; index < events.length; index++) {
  47432. // Make sure current frame has passed event frame and that event frame is within the current range
  47433. // Also, handle both forward and reverse animations
  47434. if ((range > 0 && currentFrame >= events[index].frame && events[index].frame >= from) ||
  47435. (range < 0 && currentFrame <= events[index].frame && events[index].frame <= from)) {
  47436. var event = events[index];
  47437. if (!event.isDone) {
  47438. // If event should be done only once, remove it.
  47439. if (event.onlyOnce) {
  47440. events.splice(index, 1);
  47441. index--;
  47442. }
  47443. event.isDone = true;
  47444. event.action();
  47445. } // Don't do anything if the event has already be done.
  47446. }
  47447. else if (events[index].isDone && !events[index].onlyOnce) {
  47448. // reset event, the animation is looping
  47449. events[index].isDone = false;
  47450. }
  47451. }
  47452. if (!returnValue) {
  47453. this._stopped = true;
  47454. }
  47455. return returnValue;
  47456. };
  47457. return RuntimeAnimation;
  47458. }());
  47459. BABYLON.RuntimeAnimation = RuntimeAnimation;
  47460. })(BABYLON || (BABYLON = {}));
  47461. //# sourceMappingURL=babylon.runtimeAnimation.js.map
  47462. var BABYLON;
  47463. (function (BABYLON) {
  47464. var Animatable = /** @class */ (function () {
  47465. function Animatable(scene, target, fromFrame, toFrame, loopAnimation, speedRatio, onAnimationEnd, animations) {
  47466. if (fromFrame === void 0) { fromFrame = 0; }
  47467. if (toFrame === void 0) { toFrame = 100; }
  47468. if (loopAnimation === void 0) { loopAnimation = false; }
  47469. if (speedRatio === void 0) { speedRatio = 1.0; }
  47470. this.target = target;
  47471. this.fromFrame = fromFrame;
  47472. this.toFrame = toFrame;
  47473. this.loopAnimation = loopAnimation;
  47474. this.onAnimationEnd = onAnimationEnd;
  47475. this._localDelayOffset = null;
  47476. this._pausedDelay = null;
  47477. this._runtimeAnimations = new Array();
  47478. this._paused = false;
  47479. this._speedRatio = 1;
  47480. this.animationStarted = false;
  47481. if (animations) {
  47482. this.appendAnimations(target, animations);
  47483. }
  47484. this._speedRatio = speedRatio;
  47485. this._scene = scene;
  47486. scene._activeAnimatables.push(this);
  47487. }
  47488. Object.defineProperty(Animatable.prototype, "speedRatio", {
  47489. get: function () {
  47490. return this._speedRatio;
  47491. },
  47492. set: function (value) {
  47493. for (var index = 0; index < this._runtimeAnimations.length; index++) {
  47494. var animation = this._runtimeAnimations[index];
  47495. animation._prepareForSpeedRatioChange(value);
  47496. }
  47497. this._speedRatio = value;
  47498. },
  47499. enumerable: true,
  47500. configurable: true
  47501. });
  47502. // Methods
  47503. Animatable.prototype.getAnimations = function () {
  47504. return this._runtimeAnimations;
  47505. };
  47506. Animatable.prototype.appendAnimations = function (target, animations) {
  47507. for (var index = 0; index < animations.length; index++) {
  47508. var animation = animations[index];
  47509. this._runtimeAnimations.push(new BABYLON.RuntimeAnimation(target, animation));
  47510. }
  47511. };
  47512. Animatable.prototype.getAnimationByTargetProperty = function (property) {
  47513. var runtimeAnimations = this._runtimeAnimations;
  47514. for (var index = 0; index < runtimeAnimations.length; index++) {
  47515. if (runtimeAnimations[index].animation.targetProperty === property) {
  47516. return runtimeAnimations[index].animation;
  47517. }
  47518. }
  47519. return null;
  47520. };
  47521. Animatable.prototype.getRuntimeAnimationByTargetProperty = function (property) {
  47522. var runtimeAnimations = this._runtimeAnimations;
  47523. for (var index = 0; index < runtimeAnimations.length; index++) {
  47524. if (runtimeAnimations[index].animation.targetProperty === property) {
  47525. return runtimeAnimations[index];
  47526. }
  47527. }
  47528. return null;
  47529. };
  47530. Animatable.prototype.reset = function () {
  47531. var runtimeAnimations = this._runtimeAnimations;
  47532. for (var index = 0; index < runtimeAnimations.length; index++) {
  47533. runtimeAnimations[index].reset();
  47534. }
  47535. // Reset to original value
  47536. for (index = 0; index < runtimeAnimations.length; index++) {
  47537. var animation = runtimeAnimations[index];
  47538. animation.animate(0, this.fromFrame, this.toFrame, false, this._speedRatio);
  47539. }
  47540. this._localDelayOffset = null;
  47541. this._pausedDelay = null;
  47542. };
  47543. Animatable.prototype.enableBlending = function (blendingSpeed) {
  47544. var runtimeAnimations = this._runtimeAnimations;
  47545. for (var index = 0; index < runtimeAnimations.length; index++) {
  47546. runtimeAnimations[index].animation.enableBlending = true;
  47547. runtimeAnimations[index].animation.blendingSpeed = blendingSpeed;
  47548. }
  47549. };
  47550. Animatable.prototype.disableBlending = function () {
  47551. var runtimeAnimations = this._runtimeAnimations;
  47552. for (var index = 0; index < runtimeAnimations.length; index++) {
  47553. runtimeAnimations[index].animation.enableBlending = false;
  47554. }
  47555. };
  47556. Animatable.prototype.goToFrame = function (frame) {
  47557. var runtimeAnimations = this._runtimeAnimations;
  47558. if (runtimeAnimations[0]) {
  47559. var fps = runtimeAnimations[0].animation.framePerSecond;
  47560. var currentFrame = runtimeAnimations[0].currentFrame;
  47561. var adjustTime = frame - currentFrame;
  47562. var delay = adjustTime * 1000 / (fps * this.speedRatio);
  47563. if (this._localDelayOffset === null) {
  47564. this._localDelayOffset = 0;
  47565. }
  47566. this._localDelayOffset -= delay;
  47567. }
  47568. for (var index = 0; index < runtimeAnimations.length; index++) {
  47569. runtimeAnimations[index].goToFrame(frame);
  47570. }
  47571. };
  47572. Animatable.prototype.pause = function () {
  47573. if (this._paused) {
  47574. return;
  47575. }
  47576. this._paused = true;
  47577. };
  47578. Animatable.prototype.restart = function () {
  47579. this._paused = false;
  47580. };
  47581. Animatable.prototype.stop = function (animationName) {
  47582. if (animationName) {
  47583. var idx = this._scene._activeAnimatables.indexOf(this);
  47584. if (idx > -1) {
  47585. var runtimeAnimations = this._runtimeAnimations;
  47586. for (var index = runtimeAnimations.length - 1; index >= 0; index--) {
  47587. if (typeof animationName === "string" && runtimeAnimations[index].animation.name != animationName) {
  47588. continue;
  47589. }
  47590. runtimeAnimations[index].dispose();
  47591. runtimeAnimations.splice(index, 1);
  47592. }
  47593. if (runtimeAnimations.length == 0) {
  47594. this._scene._activeAnimatables.splice(idx, 1);
  47595. if (this.onAnimationEnd) {
  47596. this.onAnimationEnd();
  47597. }
  47598. }
  47599. }
  47600. }
  47601. else {
  47602. var index = this._scene._activeAnimatables.indexOf(this);
  47603. if (index > -1) {
  47604. this._scene._activeAnimatables.splice(index, 1);
  47605. var runtimeAnimations = this._runtimeAnimations;
  47606. for (var index = 0; index < runtimeAnimations.length; index++) {
  47607. runtimeAnimations[index].dispose();
  47608. }
  47609. if (this.onAnimationEnd) {
  47610. this.onAnimationEnd();
  47611. }
  47612. }
  47613. }
  47614. };
  47615. Animatable.prototype._animate = function (delay) {
  47616. if (this._paused) {
  47617. this.animationStarted = false;
  47618. if (this._pausedDelay === null) {
  47619. this._pausedDelay = delay;
  47620. }
  47621. return true;
  47622. }
  47623. if (this._localDelayOffset === null) {
  47624. this._localDelayOffset = delay;
  47625. this._pausedDelay = null;
  47626. }
  47627. else if (this._pausedDelay !== null) {
  47628. this._localDelayOffset += delay - this._pausedDelay;
  47629. this._pausedDelay = null;
  47630. }
  47631. // Animating
  47632. var running = false;
  47633. var runtimeAnimations = this._runtimeAnimations;
  47634. var index;
  47635. for (index = 0; index < runtimeAnimations.length; index++) {
  47636. var animation = runtimeAnimations[index];
  47637. var isRunning = animation.animate(delay - this._localDelayOffset, this.fromFrame, this.toFrame, this.loopAnimation, this._speedRatio);
  47638. running = running || isRunning;
  47639. }
  47640. this.animationStarted = running;
  47641. if (!running) {
  47642. // Remove from active animatables
  47643. index = this._scene._activeAnimatables.indexOf(this);
  47644. this._scene._activeAnimatables.splice(index, 1);
  47645. // Dispose all runtime animations
  47646. for (index = 0; index < runtimeAnimations.length; index++) {
  47647. runtimeAnimations[index].dispose();
  47648. }
  47649. }
  47650. if (!running && this.onAnimationEnd) {
  47651. this.onAnimationEnd();
  47652. this.onAnimationEnd = null;
  47653. }
  47654. return running;
  47655. };
  47656. return Animatable;
  47657. }());
  47658. BABYLON.Animatable = Animatable;
  47659. })(BABYLON || (BABYLON = {}));
  47660. //# sourceMappingURL=babylon.animatable.js.map
  47661. var BABYLON;
  47662. (function (BABYLON) {
  47663. var EasingFunction = /** @class */ (function () {
  47664. function EasingFunction() {
  47665. // Properties
  47666. this._easingMode = EasingFunction.EASINGMODE_EASEIN;
  47667. }
  47668. Object.defineProperty(EasingFunction, "EASINGMODE_EASEIN", {
  47669. get: function () {
  47670. return EasingFunction._EASINGMODE_EASEIN;
  47671. },
  47672. enumerable: true,
  47673. configurable: true
  47674. });
  47675. Object.defineProperty(EasingFunction, "EASINGMODE_EASEOUT", {
  47676. get: function () {
  47677. return EasingFunction._EASINGMODE_EASEOUT;
  47678. },
  47679. enumerable: true,
  47680. configurable: true
  47681. });
  47682. Object.defineProperty(EasingFunction, "EASINGMODE_EASEINOUT", {
  47683. get: function () {
  47684. return EasingFunction._EASINGMODE_EASEINOUT;
  47685. },
  47686. enumerable: true,
  47687. configurable: true
  47688. });
  47689. EasingFunction.prototype.setEasingMode = function (easingMode) {
  47690. var n = Math.min(Math.max(easingMode, 0), 2);
  47691. this._easingMode = n;
  47692. };
  47693. EasingFunction.prototype.getEasingMode = function () {
  47694. return this._easingMode;
  47695. };
  47696. EasingFunction.prototype.easeInCore = function (gradient) {
  47697. throw new Error('You must implement this method');
  47698. };
  47699. EasingFunction.prototype.ease = function (gradient) {
  47700. switch (this._easingMode) {
  47701. case EasingFunction.EASINGMODE_EASEIN:
  47702. return this.easeInCore(gradient);
  47703. case EasingFunction.EASINGMODE_EASEOUT:
  47704. return (1 - this.easeInCore(1 - gradient));
  47705. }
  47706. if (gradient >= 0.5) {
  47707. return (((1 - this.easeInCore((1 - gradient) * 2)) * 0.5) + 0.5);
  47708. }
  47709. return (this.easeInCore(gradient * 2) * 0.5);
  47710. };
  47711. //Statics
  47712. EasingFunction._EASINGMODE_EASEIN = 0;
  47713. EasingFunction._EASINGMODE_EASEOUT = 1;
  47714. EasingFunction._EASINGMODE_EASEINOUT = 2;
  47715. return EasingFunction;
  47716. }());
  47717. BABYLON.EasingFunction = EasingFunction;
  47718. var CircleEase = /** @class */ (function (_super) {
  47719. __extends(CircleEase, _super);
  47720. function CircleEase() {
  47721. return _super !== null && _super.apply(this, arguments) || this;
  47722. }
  47723. CircleEase.prototype.easeInCore = function (gradient) {
  47724. gradient = Math.max(0, Math.min(1, gradient));
  47725. return (1.0 - Math.sqrt(1.0 - (gradient * gradient)));
  47726. };
  47727. return CircleEase;
  47728. }(EasingFunction));
  47729. BABYLON.CircleEase = CircleEase;
  47730. var BackEase = /** @class */ (function (_super) {
  47731. __extends(BackEase, _super);
  47732. function BackEase(amplitude) {
  47733. if (amplitude === void 0) { amplitude = 1; }
  47734. var _this = _super.call(this) || this;
  47735. _this.amplitude = amplitude;
  47736. return _this;
  47737. }
  47738. BackEase.prototype.easeInCore = function (gradient) {
  47739. var num = Math.max(0, this.amplitude);
  47740. return (Math.pow(gradient, 3.0) - ((gradient * num) * Math.sin(3.1415926535897931 * gradient)));
  47741. };
  47742. return BackEase;
  47743. }(EasingFunction));
  47744. BABYLON.BackEase = BackEase;
  47745. var BounceEase = /** @class */ (function (_super) {
  47746. __extends(BounceEase, _super);
  47747. function BounceEase(bounces, bounciness) {
  47748. if (bounces === void 0) { bounces = 3; }
  47749. if (bounciness === void 0) { bounciness = 2; }
  47750. var _this = _super.call(this) || this;
  47751. _this.bounces = bounces;
  47752. _this.bounciness = bounciness;
  47753. return _this;
  47754. }
  47755. BounceEase.prototype.easeInCore = function (gradient) {
  47756. var y = Math.max(0.0, this.bounces);
  47757. var bounciness = this.bounciness;
  47758. if (bounciness <= 1.0) {
  47759. bounciness = 1.001;
  47760. }
  47761. var num9 = Math.pow(bounciness, y);
  47762. var num5 = 1.0 - bounciness;
  47763. var num4 = ((1.0 - num9) / num5) + (num9 * 0.5);
  47764. var num15 = gradient * num4;
  47765. var num65 = Math.log((-num15 * (1.0 - bounciness)) + 1.0) / Math.log(bounciness);
  47766. var num3 = Math.floor(num65);
  47767. var num13 = num3 + 1.0;
  47768. var num8 = (1.0 - Math.pow(bounciness, num3)) / (num5 * num4);
  47769. var num12 = (1.0 - Math.pow(bounciness, num13)) / (num5 * num4);
  47770. var num7 = (num8 + num12) * 0.5;
  47771. var num6 = gradient - num7;
  47772. var num2 = num7 - num8;
  47773. return (((-Math.pow(1.0 / bounciness, y - num3) / (num2 * num2)) * (num6 - num2)) * (num6 + num2));
  47774. };
  47775. return BounceEase;
  47776. }(EasingFunction));
  47777. BABYLON.BounceEase = BounceEase;
  47778. var CubicEase = /** @class */ (function (_super) {
  47779. __extends(CubicEase, _super);
  47780. function CubicEase() {
  47781. return _super !== null && _super.apply(this, arguments) || this;
  47782. }
  47783. CubicEase.prototype.easeInCore = function (gradient) {
  47784. return (gradient * gradient * gradient);
  47785. };
  47786. return CubicEase;
  47787. }(EasingFunction));
  47788. BABYLON.CubicEase = CubicEase;
  47789. var ElasticEase = /** @class */ (function (_super) {
  47790. __extends(ElasticEase, _super);
  47791. function ElasticEase(oscillations, springiness) {
  47792. if (oscillations === void 0) { oscillations = 3; }
  47793. if (springiness === void 0) { springiness = 3; }
  47794. var _this = _super.call(this) || this;
  47795. _this.oscillations = oscillations;
  47796. _this.springiness = springiness;
  47797. return _this;
  47798. }
  47799. ElasticEase.prototype.easeInCore = function (gradient) {
  47800. var num2;
  47801. var num3 = Math.max(0.0, this.oscillations);
  47802. var num = Math.max(0.0, this.springiness);
  47803. if (num == 0) {
  47804. num2 = gradient;
  47805. }
  47806. else {
  47807. num2 = (Math.exp(num * gradient) - 1.0) / (Math.exp(num) - 1.0);
  47808. }
  47809. return (num2 * Math.sin(((6.2831853071795862 * num3) + 1.5707963267948966) * gradient));
  47810. };
  47811. return ElasticEase;
  47812. }(EasingFunction));
  47813. BABYLON.ElasticEase = ElasticEase;
  47814. var ExponentialEase = /** @class */ (function (_super) {
  47815. __extends(ExponentialEase, _super);
  47816. function ExponentialEase(exponent) {
  47817. if (exponent === void 0) { exponent = 2; }
  47818. var _this = _super.call(this) || this;
  47819. _this.exponent = exponent;
  47820. return _this;
  47821. }
  47822. ExponentialEase.prototype.easeInCore = function (gradient) {
  47823. if (this.exponent <= 0) {
  47824. return gradient;
  47825. }
  47826. return ((Math.exp(this.exponent * gradient) - 1.0) / (Math.exp(this.exponent) - 1.0));
  47827. };
  47828. return ExponentialEase;
  47829. }(EasingFunction));
  47830. BABYLON.ExponentialEase = ExponentialEase;
  47831. var PowerEase = /** @class */ (function (_super) {
  47832. __extends(PowerEase, _super);
  47833. function PowerEase(power) {
  47834. if (power === void 0) { power = 2; }
  47835. var _this = _super.call(this) || this;
  47836. _this.power = power;
  47837. return _this;
  47838. }
  47839. PowerEase.prototype.easeInCore = function (gradient) {
  47840. var y = Math.max(0.0, this.power);
  47841. return Math.pow(gradient, y);
  47842. };
  47843. return PowerEase;
  47844. }(EasingFunction));
  47845. BABYLON.PowerEase = PowerEase;
  47846. var QuadraticEase = /** @class */ (function (_super) {
  47847. __extends(QuadraticEase, _super);
  47848. function QuadraticEase() {
  47849. return _super !== null && _super.apply(this, arguments) || this;
  47850. }
  47851. QuadraticEase.prototype.easeInCore = function (gradient) {
  47852. return (gradient * gradient);
  47853. };
  47854. return QuadraticEase;
  47855. }(EasingFunction));
  47856. BABYLON.QuadraticEase = QuadraticEase;
  47857. var QuarticEase = /** @class */ (function (_super) {
  47858. __extends(QuarticEase, _super);
  47859. function QuarticEase() {
  47860. return _super !== null && _super.apply(this, arguments) || this;
  47861. }
  47862. QuarticEase.prototype.easeInCore = function (gradient) {
  47863. return (gradient * gradient * gradient * gradient);
  47864. };
  47865. return QuarticEase;
  47866. }(EasingFunction));
  47867. BABYLON.QuarticEase = QuarticEase;
  47868. var QuinticEase = /** @class */ (function (_super) {
  47869. __extends(QuinticEase, _super);
  47870. function QuinticEase() {
  47871. return _super !== null && _super.apply(this, arguments) || this;
  47872. }
  47873. QuinticEase.prototype.easeInCore = function (gradient) {
  47874. return (gradient * gradient * gradient * gradient * gradient);
  47875. };
  47876. return QuinticEase;
  47877. }(EasingFunction));
  47878. BABYLON.QuinticEase = QuinticEase;
  47879. var SineEase = /** @class */ (function (_super) {
  47880. __extends(SineEase, _super);
  47881. function SineEase() {
  47882. return _super !== null && _super.apply(this, arguments) || this;
  47883. }
  47884. SineEase.prototype.easeInCore = function (gradient) {
  47885. return (1.0 - Math.sin(1.5707963267948966 * (1.0 - gradient)));
  47886. };
  47887. return SineEase;
  47888. }(EasingFunction));
  47889. BABYLON.SineEase = SineEase;
  47890. var BezierCurveEase = /** @class */ (function (_super) {
  47891. __extends(BezierCurveEase, _super);
  47892. function BezierCurveEase(x1, y1, x2, y2) {
  47893. if (x1 === void 0) { x1 = 0; }
  47894. if (y1 === void 0) { y1 = 0; }
  47895. if (x2 === void 0) { x2 = 1; }
  47896. if (y2 === void 0) { y2 = 1; }
  47897. var _this = _super.call(this) || this;
  47898. _this.x1 = x1;
  47899. _this.y1 = y1;
  47900. _this.x2 = x2;
  47901. _this.y2 = y2;
  47902. return _this;
  47903. }
  47904. BezierCurveEase.prototype.easeInCore = function (gradient) {
  47905. return BABYLON.BezierCurve.interpolate(gradient, this.x1, this.y1, this.x2, this.y2);
  47906. };
  47907. return BezierCurveEase;
  47908. }(EasingFunction));
  47909. BABYLON.BezierCurveEase = BezierCurveEase;
  47910. })(BABYLON || (BABYLON = {}));
  47911. //# sourceMappingURL=babylon.easing.js.map
  47912. var BABYLON;
  47913. (function (BABYLON) {
  47914. var Condition = /** @class */ (function () {
  47915. function Condition(actionManager) {
  47916. this._actionManager = actionManager;
  47917. }
  47918. Condition.prototype.isValid = function () {
  47919. return true;
  47920. };
  47921. Condition.prototype._getProperty = function (propertyPath) {
  47922. return this._actionManager._getProperty(propertyPath);
  47923. };
  47924. Condition.prototype._getEffectiveTarget = function (target, propertyPath) {
  47925. return this._actionManager._getEffectiveTarget(target, propertyPath);
  47926. };
  47927. Condition.prototype.serialize = function () {
  47928. };
  47929. Condition.prototype._serialize = function (serializedCondition) {
  47930. return {
  47931. type: 2,
  47932. children: [],
  47933. name: serializedCondition.name,
  47934. properties: serializedCondition.properties
  47935. };
  47936. };
  47937. return Condition;
  47938. }());
  47939. BABYLON.Condition = Condition;
  47940. var ValueCondition = /** @class */ (function (_super) {
  47941. __extends(ValueCondition, _super);
  47942. function ValueCondition(actionManager, target, propertyPath, value, operator) {
  47943. if (operator === void 0) { operator = ValueCondition.IsEqual; }
  47944. var _this = _super.call(this, actionManager) || this;
  47945. _this.propertyPath = propertyPath;
  47946. _this.value = value;
  47947. _this.operator = operator;
  47948. _this._target = target;
  47949. _this._effectiveTarget = _this._getEffectiveTarget(target, _this.propertyPath);
  47950. _this._property = _this._getProperty(_this.propertyPath);
  47951. return _this;
  47952. }
  47953. Object.defineProperty(ValueCondition, "IsEqual", {
  47954. get: function () {
  47955. return ValueCondition._IsEqual;
  47956. },
  47957. enumerable: true,
  47958. configurable: true
  47959. });
  47960. Object.defineProperty(ValueCondition, "IsDifferent", {
  47961. get: function () {
  47962. return ValueCondition._IsDifferent;
  47963. },
  47964. enumerable: true,
  47965. configurable: true
  47966. });
  47967. Object.defineProperty(ValueCondition, "IsGreater", {
  47968. get: function () {
  47969. return ValueCondition._IsGreater;
  47970. },
  47971. enumerable: true,
  47972. configurable: true
  47973. });
  47974. Object.defineProperty(ValueCondition, "IsLesser", {
  47975. get: function () {
  47976. return ValueCondition._IsLesser;
  47977. },
  47978. enumerable: true,
  47979. configurable: true
  47980. });
  47981. // Methods
  47982. ValueCondition.prototype.isValid = function () {
  47983. switch (this.operator) {
  47984. case ValueCondition.IsGreater:
  47985. return this._effectiveTarget[this._property] > this.value;
  47986. case ValueCondition.IsLesser:
  47987. return this._effectiveTarget[this._property] < this.value;
  47988. case ValueCondition.IsEqual:
  47989. case ValueCondition.IsDifferent:
  47990. var check;
  47991. if (this.value.equals) {
  47992. check = this.value.equals(this._effectiveTarget[this._property]);
  47993. }
  47994. else {
  47995. check = this.value === this._effectiveTarget[this._property];
  47996. }
  47997. return this.operator === ValueCondition.IsEqual ? check : !check;
  47998. }
  47999. return false;
  48000. };
  48001. ValueCondition.prototype.serialize = function () {
  48002. return this._serialize({
  48003. name: "ValueCondition",
  48004. properties: [
  48005. BABYLON.Action._GetTargetProperty(this._target),
  48006. { name: "propertyPath", value: this.propertyPath },
  48007. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) },
  48008. { name: "operator", value: ValueCondition.GetOperatorName(this.operator) }
  48009. ]
  48010. });
  48011. };
  48012. ValueCondition.GetOperatorName = function (operator) {
  48013. switch (operator) {
  48014. case ValueCondition._IsEqual: return "IsEqual";
  48015. case ValueCondition._IsDifferent: return "IsDifferent";
  48016. case ValueCondition._IsGreater: return "IsGreater";
  48017. case ValueCondition._IsLesser: return "IsLesser";
  48018. default: return "";
  48019. }
  48020. };
  48021. // Statics
  48022. ValueCondition._IsEqual = 0;
  48023. ValueCondition._IsDifferent = 1;
  48024. ValueCondition._IsGreater = 2;
  48025. ValueCondition._IsLesser = 3;
  48026. return ValueCondition;
  48027. }(Condition));
  48028. BABYLON.ValueCondition = ValueCondition;
  48029. var PredicateCondition = /** @class */ (function (_super) {
  48030. __extends(PredicateCondition, _super);
  48031. function PredicateCondition(actionManager, predicate) {
  48032. var _this = _super.call(this, actionManager) || this;
  48033. _this.predicate = predicate;
  48034. return _this;
  48035. }
  48036. PredicateCondition.prototype.isValid = function () {
  48037. return this.predicate();
  48038. };
  48039. return PredicateCondition;
  48040. }(Condition));
  48041. BABYLON.PredicateCondition = PredicateCondition;
  48042. var StateCondition = /** @class */ (function (_super) {
  48043. __extends(StateCondition, _super);
  48044. function StateCondition(actionManager, target, value) {
  48045. var _this = _super.call(this, actionManager) || this;
  48046. _this.value = value;
  48047. _this._target = target;
  48048. return _this;
  48049. }
  48050. // Methods
  48051. StateCondition.prototype.isValid = function () {
  48052. return this._target.state === this.value;
  48053. };
  48054. StateCondition.prototype.serialize = function () {
  48055. return this._serialize({
  48056. name: "StateCondition",
  48057. properties: [
  48058. BABYLON.Action._GetTargetProperty(this._target),
  48059. { name: "value", value: this.value }
  48060. ]
  48061. });
  48062. };
  48063. return StateCondition;
  48064. }(Condition));
  48065. BABYLON.StateCondition = StateCondition;
  48066. })(BABYLON || (BABYLON = {}));
  48067. //# sourceMappingURL=babylon.condition.js.map
  48068. var BABYLON;
  48069. (function (BABYLON) {
  48070. var Action = /** @class */ (function () {
  48071. function Action(triggerOptions, condition) {
  48072. this.triggerOptions = triggerOptions;
  48073. this.onBeforeExecuteObservable = new BABYLON.Observable();
  48074. if (triggerOptions.parameter) {
  48075. this.trigger = triggerOptions.trigger;
  48076. this._triggerParameter = triggerOptions.parameter;
  48077. }
  48078. else {
  48079. this.trigger = triggerOptions;
  48080. }
  48081. this._nextActiveAction = this;
  48082. this._condition = condition;
  48083. }
  48084. // Methods
  48085. Action.prototype._prepare = function () {
  48086. };
  48087. Action.prototype.getTriggerParameter = function () {
  48088. return this._triggerParameter;
  48089. };
  48090. Action.prototype._executeCurrent = function (evt) {
  48091. if (this._nextActiveAction._condition) {
  48092. var condition = this._nextActiveAction._condition;
  48093. var currentRenderId = this._actionManager.getScene().getRenderId();
  48094. // We cache the current evaluation for the current frame
  48095. if (condition._evaluationId === currentRenderId) {
  48096. if (!condition._currentResult) {
  48097. return;
  48098. }
  48099. }
  48100. else {
  48101. condition._evaluationId = currentRenderId;
  48102. if (!condition.isValid()) {
  48103. condition._currentResult = false;
  48104. return;
  48105. }
  48106. condition._currentResult = true;
  48107. }
  48108. }
  48109. this.onBeforeExecuteObservable.notifyObservers(this);
  48110. this._nextActiveAction.execute(evt);
  48111. this.skipToNextActiveAction();
  48112. };
  48113. Action.prototype.execute = function (evt) {
  48114. };
  48115. Action.prototype.skipToNextActiveAction = function () {
  48116. if (this._nextActiveAction._child) {
  48117. if (!this._nextActiveAction._child._actionManager) {
  48118. this._nextActiveAction._child._actionManager = this._actionManager;
  48119. }
  48120. this._nextActiveAction = this._nextActiveAction._child;
  48121. }
  48122. else {
  48123. this._nextActiveAction = this;
  48124. }
  48125. };
  48126. Action.prototype.then = function (action) {
  48127. this._child = action;
  48128. action._actionManager = this._actionManager;
  48129. action._prepare();
  48130. return action;
  48131. };
  48132. Action.prototype._getProperty = function (propertyPath) {
  48133. return this._actionManager._getProperty(propertyPath);
  48134. };
  48135. Action.prototype._getEffectiveTarget = function (target, propertyPath) {
  48136. return this._actionManager._getEffectiveTarget(target, propertyPath);
  48137. };
  48138. Action.prototype.serialize = function (parent) {
  48139. };
  48140. // Called by BABYLON.Action objects in serialize(...). Internal use
  48141. Action.prototype._serialize = function (serializedAction, parent) {
  48142. var serializationObject = {
  48143. type: 1,
  48144. children: [],
  48145. name: serializedAction.name,
  48146. properties: serializedAction.properties || []
  48147. };
  48148. // Serialize child
  48149. if (this._child) {
  48150. this._child.serialize(serializationObject);
  48151. }
  48152. // Check if "this" has a condition
  48153. if (this._condition) {
  48154. var serializedCondition = this._condition.serialize();
  48155. serializedCondition.children.push(serializationObject);
  48156. if (parent) {
  48157. parent.children.push(serializedCondition);
  48158. }
  48159. return serializedCondition;
  48160. }
  48161. if (parent) {
  48162. parent.children.push(serializationObject);
  48163. }
  48164. return serializationObject;
  48165. };
  48166. Action._SerializeValueAsString = function (value) {
  48167. if (typeof value === "number") {
  48168. return value.toString();
  48169. }
  48170. if (typeof value === "boolean") {
  48171. return value ? "true" : "false";
  48172. }
  48173. if (value instanceof BABYLON.Vector2) {
  48174. return value.x + ", " + value.y;
  48175. }
  48176. if (value instanceof BABYLON.Vector3) {
  48177. return value.x + ", " + value.y + ", " + value.z;
  48178. }
  48179. if (value instanceof BABYLON.Color3) {
  48180. return value.r + ", " + value.g + ", " + value.b;
  48181. }
  48182. if (value instanceof BABYLON.Color4) {
  48183. return value.r + ", " + value.g + ", " + value.b + ", " + value.a;
  48184. }
  48185. return value; // string
  48186. };
  48187. Action._GetTargetProperty = function (target) {
  48188. return {
  48189. name: "target",
  48190. targetType: target instanceof BABYLON.Mesh ? "MeshProperties"
  48191. : target instanceof BABYLON.Light ? "LightProperties"
  48192. : target instanceof BABYLON.Camera ? "CameraProperties"
  48193. : "SceneProperties",
  48194. value: target instanceof BABYLON.Scene ? "Scene" : target.name
  48195. };
  48196. };
  48197. return Action;
  48198. }());
  48199. BABYLON.Action = Action;
  48200. })(BABYLON || (BABYLON = {}));
  48201. //# sourceMappingURL=babylon.action.js.map
  48202. var BABYLON;
  48203. (function (BABYLON) {
  48204. /**
  48205. * ActionEvent is the event beint sent when an action is triggered.
  48206. */
  48207. var ActionEvent = /** @class */ (function () {
  48208. /**
  48209. * @param source The mesh or sprite that triggered the action.
  48210. * @param pointerX The X mouse cursor position at the time of the event
  48211. * @param pointerY The Y mouse cursor position at the time of the event
  48212. * @param meshUnderPointer The mesh that is currently pointed at (can be null)
  48213. * @param sourceEvent the original (browser) event that triggered the ActionEvent
  48214. */
  48215. function ActionEvent(source, pointerX, pointerY, meshUnderPointer, sourceEvent, additionalData) {
  48216. this.source = source;
  48217. this.pointerX = pointerX;
  48218. this.pointerY = pointerY;
  48219. this.meshUnderPointer = meshUnderPointer;
  48220. this.sourceEvent = sourceEvent;
  48221. this.additionalData = additionalData;
  48222. }
  48223. /**
  48224. * Helper function to auto-create an ActionEvent from a source mesh.
  48225. * @param source The source mesh that triggered the event
  48226. * @param evt {Event} The original (browser) event
  48227. */
  48228. ActionEvent.CreateNew = function (source, evt, additionalData) {
  48229. var scene = source.getScene();
  48230. return new ActionEvent(source, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt, additionalData);
  48231. };
  48232. /**
  48233. * Helper function to auto-create an ActionEvent from a source mesh.
  48234. * @param source The source sprite that triggered the event
  48235. * @param scene Scene associated with the sprite
  48236. * @param evt {Event} The original (browser) event
  48237. */
  48238. ActionEvent.CreateNewFromSprite = function (source, scene, evt, additionalData) {
  48239. return new ActionEvent(source, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt, additionalData);
  48240. };
  48241. /**
  48242. * Helper function to auto-create an ActionEvent from a scene. If triggered by a mesh use ActionEvent.CreateNew
  48243. * @param scene the scene where the event occurred
  48244. * @param evt {Event} The original (browser) event
  48245. */
  48246. ActionEvent.CreateNewFromScene = function (scene, evt) {
  48247. return new ActionEvent(null, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt);
  48248. };
  48249. ActionEvent.CreateNewFromPrimitive = function (prim, pointerPos, evt, additionalData) {
  48250. return new ActionEvent(prim, pointerPos.x, pointerPos.y, null, evt, additionalData);
  48251. };
  48252. return ActionEvent;
  48253. }());
  48254. BABYLON.ActionEvent = ActionEvent;
  48255. /**
  48256. * Action Manager manages all events to be triggered on a given mesh or the global scene.
  48257. * A single scene can have many Action Managers to handle predefined actions on specific meshes.
  48258. */
  48259. var ActionManager = /** @class */ (function () {
  48260. function ActionManager(scene) {
  48261. // Members
  48262. this.actions = new Array();
  48263. this.hoverCursor = '';
  48264. this._scene = scene;
  48265. scene._actionManagers.push(this);
  48266. }
  48267. Object.defineProperty(ActionManager, "NothingTrigger", {
  48268. get: function () {
  48269. return ActionManager._NothingTrigger;
  48270. },
  48271. enumerable: true,
  48272. configurable: true
  48273. });
  48274. Object.defineProperty(ActionManager, "OnPickTrigger", {
  48275. get: function () {
  48276. return ActionManager._OnPickTrigger;
  48277. },
  48278. enumerable: true,
  48279. configurable: true
  48280. });
  48281. Object.defineProperty(ActionManager, "OnLeftPickTrigger", {
  48282. get: function () {
  48283. return ActionManager._OnLeftPickTrigger;
  48284. },
  48285. enumerable: true,
  48286. configurable: true
  48287. });
  48288. Object.defineProperty(ActionManager, "OnRightPickTrigger", {
  48289. get: function () {
  48290. return ActionManager._OnRightPickTrigger;
  48291. },
  48292. enumerable: true,
  48293. configurable: true
  48294. });
  48295. Object.defineProperty(ActionManager, "OnCenterPickTrigger", {
  48296. get: function () {
  48297. return ActionManager._OnCenterPickTrigger;
  48298. },
  48299. enumerable: true,
  48300. configurable: true
  48301. });
  48302. Object.defineProperty(ActionManager, "OnPickDownTrigger", {
  48303. get: function () {
  48304. return ActionManager._OnPickDownTrigger;
  48305. },
  48306. enumerable: true,
  48307. configurable: true
  48308. });
  48309. Object.defineProperty(ActionManager, "OnDoublePickTrigger", {
  48310. get: function () {
  48311. return ActionManager._OnDoublePickTrigger;
  48312. },
  48313. enumerable: true,
  48314. configurable: true
  48315. });
  48316. Object.defineProperty(ActionManager, "OnPickUpTrigger", {
  48317. get: function () {
  48318. return ActionManager._OnPickUpTrigger;
  48319. },
  48320. enumerable: true,
  48321. configurable: true
  48322. });
  48323. Object.defineProperty(ActionManager, "OnPickOutTrigger", {
  48324. /// This trigger will only be raised if you also declared a OnPickDown
  48325. get: function () {
  48326. return ActionManager._OnPickOutTrigger;
  48327. },
  48328. enumerable: true,
  48329. configurable: true
  48330. });
  48331. Object.defineProperty(ActionManager, "OnLongPressTrigger", {
  48332. get: function () {
  48333. return ActionManager._OnLongPressTrigger;
  48334. },
  48335. enumerable: true,
  48336. configurable: true
  48337. });
  48338. Object.defineProperty(ActionManager, "OnPointerOverTrigger", {
  48339. get: function () {
  48340. return ActionManager._OnPointerOverTrigger;
  48341. },
  48342. enumerable: true,
  48343. configurable: true
  48344. });
  48345. Object.defineProperty(ActionManager, "OnPointerOutTrigger", {
  48346. get: function () {
  48347. return ActionManager._OnPointerOutTrigger;
  48348. },
  48349. enumerable: true,
  48350. configurable: true
  48351. });
  48352. Object.defineProperty(ActionManager, "OnEveryFrameTrigger", {
  48353. get: function () {
  48354. return ActionManager._OnEveryFrameTrigger;
  48355. },
  48356. enumerable: true,
  48357. configurable: true
  48358. });
  48359. Object.defineProperty(ActionManager, "OnIntersectionEnterTrigger", {
  48360. get: function () {
  48361. return ActionManager._OnIntersectionEnterTrigger;
  48362. },
  48363. enumerable: true,
  48364. configurable: true
  48365. });
  48366. Object.defineProperty(ActionManager, "OnIntersectionExitTrigger", {
  48367. get: function () {
  48368. return ActionManager._OnIntersectionExitTrigger;
  48369. },
  48370. enumerable: true,
  48371. configurable: true
  48372. });
  48373. Object.defineProperty(ActionManager, "OnKeyDownTrigger", {
  48374. get: function () {
  48375. return ActionManager._OnKeyDownTrigger;
  48376. },
  48377. enumerable: true,
  48378. configurable: true
  48379. });
  48380. Object.defineProperty(ActionManager, "OnKeyUpTrigger", {
  48381. get: function () {
  48382. return ActionManager._OnKeyUpTrigger;
  48383. },
  48384. enumerable: true,
  48385. configurable: true
  48386. });
  48387. // Methods
  48388. ActionManager.prototype.dispose = function () {
  48389. var index = this._scene._actionManagers.indexOf(this);
  48390. for (var i = 0; i < this.actions.length; i++) {
  48391. var action = this.actions[i];
  48392. ActionManager.Triggers[action.trigger]--;
  48393. if (ActionManager.Triggers[action.trigger] === 0) {
  48394. delete ActionManager.Triggers[action.trigger];
  48395. }
  48396. }
  48397. if (index > -1) {
  48398. this._scene._actionManagers.splice(index, 1);
  48399. }
  48400. };
  48401. ActionManager.prototype.getScene = function () {
  48402. return this._scene;
  48403. };
  48404. /**
  48405. * Does this action manager handles actions of any of the given triggers
  48406. * @param {number[]} triggers - the triggers to be tested
  48407. * @return {boolean} whether one (or more) of the triggers is handeled
  48408. */
  48409. ActionManager.prototype.hasSpecificTriggers = function (triggers) {
  48410. for (var index = 0; index < this.actions.length; index++) {
  48411. var action = this.actions[index];
  48412. if (triggers.indexOf(action.trigger) > -1) {
  48413. return true;
  48414. }
  48415. }
  48416. return false;
  48417. };
  48418. /**
  48419. * Does this action manager handles actions of a given trigger
  48420. * @param {number} trigger - the trigger to be tested
  48421. * @return {boolean} whether the trigger is handeled
  48422. */
  48423. ActionManager.prototype.hasSpecificTrigger = function (trigger) {
  48424. for (var index = 0; index < this.actions.length; index++) {
  48425. var action = this.actions[index];
  48426. if (action.trigger === trigger) {
  48427. return true;
  48428. }
  48429. }
  48430. return false;
  48431. };
  48432. Object.defineProperty(ActionManager.prototype, "hasPointerTriggers", {
  48433. /**
  48434. * Does this action manager has pointer triggers
  48435. * @return {boolean} whether or not it has pointer triggers
  48436. */
  48437. get: function () {
  48438. for (var index = 0; index < this.actions.length; index++) {
  48439. var action = this.actions[index];
  48440. if (action.trigger >= ActionManager._OnPickTrigger && action.trigger <= ActionManager._OnPointerOutTrigger) {
  48441. return true;
  48442. }
  48443. }
  48444. return false;
  48445. },
  48446. enumerable: true,
  48447. configurable: true
  48448. });
  48449. Object.defineProperty(ActionManager.prototype, "hasPickTriggers", {
  48450. /**
  48451. * Does this action manager has pick triggers
  48452. * @return {boolean} whether or not it has pick triggers
  48453. */
  48454. get: function () {
  48455. for (var index = 0; index < this.actions.length; index++) {
  48456. var action = this.actions[index];
  48457. if (action.trigger >= ActionManager._OnPickTrigger && action.trigger <= ActionManager._OnPickUpTrigger) {
  48458. return true;
  48459. }
  48460. }
  48461. return false;
  48462. },
  48463. enumerable: true,
  48464. configurable: true
  48465. });
  48466. Object.defineProperty(ActionManager, "HasTriggers", {
  48467. /**
  48468. * Does exist one action manager with at least one trigger
  48469. * @return {boolean} whether or not it exists one action manager with one trigger
  48470. **/
  48471. get: function () {
  48472. for (var t in ActionManager.Triggers) {
  48473. if (ActionManager.Triggers.hasOwnProperty(t)) {
  48474. return true;
  48475. }
  48476. }
  48477. return false;
  48478. },
  48479. enumerable: true,
  48480. configurable: true
  48481. });
  48482. Object.defineProperty(ActionManager, "HasPickTriggers", {
  48483. /**
  48484. * Does exist one action manager with at least one pick trigger
  48485. * @return {boolean} whether or not it exists one action manager with one pick trigger
  48486. **/
  48487. get: function () {
  48488. for (var t in ActionManager.Triggers) {
  48489. if (ActionManager.Triggers.hasOwnProperty(t)) {
  48490. var t_int = parseInt(t);
  48491. if (t_int >= ActionManager._OnPickTrigger && t_int <= ActionManager._OnPickUpTrigger) {
  48492. return true;
  48493. }
  48494. }
  48495. }
  48496. return false;
  48497. },
  48498. enumerable: true,
  48499. configurable: true
  48500. });
  48501. /**
  48502. * Does exist one action manager that handles actions of a given trigger
  48503. * @param {number} trigger - the trigger to be tested
  48504. * @return {boolean} whether the trigger is handeled by at least one action manager
  48505. **/
  48506. ActionManager.HasSpecificTrigger = function (trigger) {
  48507. for (var t in ActionManager.Triggers) {
  48508. if (ActionManager.Triggers.hasOwnProperty(t)) {
  48509. var t_int = parseInt(t);
  48510. if (t_int === trigger) {
  48511. return true;
  48512. }
  48513. }
  48514. }
  48515. return false;
  48516. };
  48517. /**
  48518. * Registers an action to this action manager
  48519. * @param {BABYLON.Action} action - the action to be registered
  48520. * @return {BABYLON.Action} the action amended (prepared) after registration
  48521. */
  48522. ActionManager.prototype.registerAction = function (action) {
  48523. if (action.trigger === ActionManager.OnEveryFrameTrigger) {
  48524. if (this.getScene().actionManager !== this) {
  48525. BABYLON.Tools.Warn("OnEveryFrameTrigger can only be used with scene.actionManager");
  48526. return null;
  48527. }
  48528. }
  48529. this.actions.push(action);
  48530. if (ActionManager.Triggers[action.trigger]) {
  48531. ActionManager.Triggers[action.trigger]++;
  48532. }
  48533. else {
  48534. ActionManager.Triggers[action.trigger] = 1;
  48535. }
  48536. action._actionManager = this;
  48537. action._prepare();
  48538. return action;
  48539. };
  48540. /**
  48541. * Unregisters an action to this action manager
  48542. * @param action The action to be unregistered
  48543. * @return whether the action has been unregistered
  48544. */
  48545. ActionManager.prototype.unregisterAction = function (action) {
  48546. var index = this.actions.indexOf(action);
  48547. if (index !== -1) {
  48548. this.actions.splice(index, 1);
  48549. ActionManager.Triggers[action.trigger] -= 1;
  48550. if (ActionManager.Triggers[action.trigger] === 0) {
  48551. delete ActionManager.Triggers[action.trigger];
  48552. }
  48553. delete action._actionManager;
  48554. return true;
  48555. }
  48556. return false;
  48557. };
  48558. /**
  48559. * Process a specific trigger
  48560. * @param {number} trigger - the trigger to process
  48561. * @param evt {BABYLON.ActionEvent} the event details to be processed
  48562. */
  48563. ActionManager.prototype.processTrigger = function (trigger, evt) {
  48564. for (var index = 0; index < this.actions.length; index++) {
  48565. var action = this.actions[index];
  48566. if (action.trigger === trigger) {
  48567. if (evt) {
  48568. if (trigger === ActionManager.OnKeyUpTrigger
  48569. || trigger === ActionManager.OnKeyDownTrigger) {
  48570. var parameter = action.getTriggerParameter();
  48571. if (parameter && parameter !== evt.sourceEvent.keyCode) {
  48572. if (!parameter.toLowerCase) {
  48573. continue;
  48574. }
  48575. var lowerCase = parameter.toLowerCase();
  48576. if (lowerCase !== evt.sourceEvent.key) {
  48577. var unicode = evt.sourceEvent.charCode ? evt.sourceEvent.charCode : evt.sourceEvent.keyCode;
  48578. var actualkey = String.fromCharCode(unicode).toLowerCase();
  48579. if (actualkey !== lowerCase) {
  48580. continue;
  48581. }
  48582. }
  48583. }
  48584. }
  48585. }
  48586. action._executeCurrent(evt);
  48587. }
  48588. }
  48589. };
  48590. ActionManager.prototype._getEffectiveTarget = function (target, propertyPath) {
  48591. var properties = propertyPath.split(".");
  48592. for (var index = 0; index < properties.length - 1; index++) {
  48593. target = target[properties[index]];
  48594. }
  48595. return target;
  48596. };
  48597. ActionManager.prototype._getProperty = function (propertyPath) {
  48598. var properties = propertyPath.split(".");
  48599. return properties[properties.length - 1];
  48600. };
  48601. ActionManager.prototype.serialize = function (name) {
  48602. var root = {
  48603. children: new Array(),
  48604. name: name,
  48605. type: 3,
  48606. properties: new Array() // Empty for root but required
  48607. };
  48608. for (var i = 0; i < this.actions.length; i++) {
  48609. var triggerObject = {
  48610. type: 0,
  48611. children: new Array(),
  48612. name: ActionManager.GetTriggerName(this.actions[i].trigger),
  48613. properties: new Array()
  48614. };
  48615. var triggerOptions = this.actions[i].triggerOptions;
  48616. if (triggerOptions && typeof triggerOptions !== "number") {
  48617. if (triggerOptions.parameter instanceof BABYLON.Node) {
  48618. triggerObject.properties.push(BABYLON.Action._GetTargetProperty(triggerOptions.parameter));
  48619. }
  48620. else {
  48621. var parameter = {};
  48622. BABYLON.Tools.DeepCopy(triggerOptions.parameter, parameter, ["mesh"]);
  48623. if (triggerOptions.parameter.mesh) {
  48624. parameter._meshId = triggerOptions.parameter.mesh.id;
  48625. }
  48626. triggerObject.properties.push({ name: "parameter", targetType: null, value: parameter });
  48627. }
  48628. }
  48629. // Serialize child action, recursively
  48630. this.actions[i].serialize(triggerObject);
  48631. // Add serialized trigger
  48632. root.children.push(triggerObject);
  48633. }
  48634. return root;
  48635. };
  48636. ActionManager.Parse = function (parsedActions, object, scene) {
  48637. var actionManager = new ActionManager(scene);
  48638. if (object === null)
  48639. scene.actionManager = actionManager;
  48640. else
  48641. object.actionManager = actionManager;
  48642. // instanciate a new object
  48643. var instanciate = function (name, params) {
  48644. // TODO: We will need to find a solution for the next line when using commonjs / es6 .
  48645. var newInstance = Object.create(BABYLON.Tools.Instantiate("BABYLON." + name).prototype);
  48646. newInstance.constructor.apply(newInstance, params);
  48647. return newInstance;
  48648. };
  48649. var parseParameter = function (name, value, target, propertyPath) {
  48650. if (propertyPath === null) {
  48651. // String, boolean or float
  48652. var floatValue = parseFloat(value);
  48653. if (value === "true" || value === "false")
  48654. return value === "true";
  48655. else
  48656. return isNaN(floatValue) ? value : floatValue;
  48657. }
  48658. var effectiveTarget = propertyPath.split(".");
  48659. var values = value.split(",");
  48660. // Get effective Target
  48661. for (var i = 0; i < effectiveTarget.length; i++) {
  48662. target = target[effectiveTarget[i]];
  48663. }
  48664. // Return appropriate value with its type
  48665. if (typeof (target) === "boolean")
  48666. return values[0] === "true";
  48667. if (typeof (target) === "string")
  48668. return values[0];
  48669. // Parameters with multiple values such as Vector3 etc.
  48670. var split = new Array();
  48671. for (var i = 0; i < values.length; i++)
  48672. split.push(parseFloat(values[i]));
  48673. if (target instanceof BABYLON.Vector3)
  48674. return BABYLON.Vector3.FromArray(split);
  48675. if (target instanceof BABYLON.Vector4)
  48676. return BABYLON.Vector4.FromArray(split);
  48677. if (target instanceof BABYLON.Color3)
  48678. return BABYLON.Color3.FromArray(split);
  48679. if (target instanceof BABYLON.Color4)
  48680. return BABYLON.Color4.FromArray(split);
  48681. return parseFloat(values[0]);
  48682. };
  48683. // traverse graph per trigger
  48684. var traverse = function (parsedAction, trigger, condition, action, combineArray) {
  48685. if (combineArray === void 0) { combineArray = null; }
  48686. if (parsedAction.detached)
  48687. return;
  48688. var parameters = new Array();
  48689. var target = null;
  48690. var propertyPath = null;
  48691. var combine = parsedAction.combine && parsedAction.combine.length > 0;
  48692. // Parameters
  48693. if (parsedAction.type === 2)
  48694. parameters.push(actionManager);
  48695. else
  48696. parameters.push(trigger);
  48697. if (combine) {
  48698. var actions = new Array();
  48699. for (var j = 0; j < parsedAction.combine.length; j++) {
  48700. traverse(parsedAction.combine[j], ActionManager.NothingTrigger, condition, action, actions);
  48701. }
  48702. parameters.push(actions);
  48703. }
  48704. else {
  48705. for (var i = 0; i < parsedAction.properties.length; i++) {
  48706. var value = parsedAction.properties[i].value;
  48707. var name = parsedAction.properties[i].name;
  48708. var targetType = parsedAction.properties[i].targetType;
  48709. if (name === "target")
  48710. if (targetType !== null && targetType === "SceneProperties")
  48711. value = target = scene;
  48712. else
  48713. value = target = scene.getNodeByName(value);
  48714. else if (name === "parent")
  48715. value = scene.getNodeByName(value);
  48716. else if (name === "sound")
  48717. value = scene.getSoundByName(value);
  48718. else if (name !== "propertyPath") {
  48719. if (parsedAction.type === 2 && name === "operator")
  48720. value = BABYLON.ValueCondition[value];
  48721. else
  48722. value = parseParameter(name, value, target, name === "value" ? propertyPath : null);
  48723. }
  48724. else {
  48725. propertyPath = value;
  48726. }
  48727. parameters.push(value);
  48728. }
  48729. }
  48730. if (combineArray === null) {
  48731. parameters.push(condition);
  48732. }
  48733. else {
  48734. parameters.push(null);
  48735. }
  48736. // If interpolate value action
  48737. if (parsedAction.name === "InterpolateValueAction") {
  48738. var param = parameters[parameters.length - 2];
  48739. parameters[parameters.length - 1] = param;
  48740. parameters[parameters.length - 2] = condition;
  48741. }
  48742. // Action or condition(s) and not CombineAction
  48743. var newAction = instanciate(parsedAction.name, parameters);
  48744. if (newAction instanceof BABYLON.Condition && condition !== null) {
  48745. var nothing = new BABYLON.DoNothingAction(trigger, condition);
  48746. if (action)
  48747. action.then(nothing);
  48748. else
  48749. actionManager.registerAction(nothing);
  48750. action = nothing;
  48751. }
  48752. if (combineArray === null) {
  48753. if (newAction instanceof BABYLON.Condition) {
  48754. condition = newAction;
  48755. newAction = action;
  48756. }
  48757. else {
  48758. condition = null;
  48759. if (action)
  48760. action.then(newAction);
  48761. else
  48762. actionManager.registerAction(newAction);
  48763. }
  48764. }
  48765. else {
  48766. combineArray.push(newAction);
  48767. }
  48768. for (var i = 0; i < parsedAction.children.length; i++)
  48769. traverse(parsedAction.children[i], trigger, condition, newAction, null);
  48770. };
  48771. // triggers
  48772. for (var i = 0; i < parsedActions.children.length; i++) {
  48773. var triggerParams;
  48774. var trigger = parsedActions.children[i];
  48775. if (trigger.properties.length > 0) {
  48776. var param = trigger.properties[0].value;
  48777. var value = trigger.properties[0].targetType === null ? param : scene.getMeshByName(param);
  48778. if (value._meshId) {
  48779. value.mesh = scene.getMeshByID(value._meshId);
  48780. }
  48781. triggerParams = { trigger: ActionManager[trigger.name], parameter: value };
  48782. }
  48783. else
  48784. triggerParams = ActionManager[trigger.name];
  48785. for (var j = 0; j < trigger.children.length; j++) {
  48786. if (!trigger.detached)
  48787. traverse(trigger.children[j], triggerParams, null, null);
  48788. }
  48789. }
  48790. };
  48791. ActionManager.GetTriggerName = function (trigger) {
  48792. switch (trigger) {
  48793. case 0: return "NothingTrigger";
  48794. case 1: return "OnPickTrigger";
  48795. case 2: return "OnLeftPickTrigger";
  48796. case 3: return "OnRightPickTrigger";
  48797. case 4: return "OnCenterPickTrigger";
  48798. case 5: return "OnPickDownTrigger";
  48799. case 6: return "OnPickUpTrigger";
  48800. case 7: return "OnLongPressTrigger";
  48801. case 8: return "OnPointerOverTrigger";
  48802. case 9: return "OnPointerOutTrigger";
  48803. case 10: return "OnEveryFrameTrigger";
  48804. case 11: return "OnIntersectionEnterTrigger";
  48805. case 12: return "OnIntersectionExitTrigger";
  48806. case 13: return "OnKeyDownTrigger";
  48807. case 14: return "OnKeyUpTrigger";
  48808. case 15: return "OnPickOutTrigger";
  48809. default: return "";
  48810. }
  48811. };
  48812. // Statics
  48813. ActionManager._NothingTrigger = 0;
  48814. ActionManager._OnPickTrigger = 1;
  48815. ActionManager._OnLeftPickTrigger = 2;
  48816. ActionManager._OnRightPickTrigger = 3;
  48817. ActionManager._OnCenterPickTrigger = 4;
  48818. ActionManager._OnPickDownTrigger = 5;
  48819. ActionManager._OnDoublePickTrigger = 6;
  48820. ActionManager._OnPickUpTrigger = 7;
  48821. ActionManager._OnLongPressTrigger = 8;
  48822. ActionManager._OnPointerOverTrigger = 9;
  48823. ActionManager._OnPointerOutTrigger = 10;
  48824. ActionManager._OnEveryFrameTrigger = 11;
  48825. ActionManager._OnIntersectionEnterTrigger = 12;
  48826. ActionManager._OnIntersectionExitTrigger = 13;
  48827. ActionManager._OnKeyDownTrigger = 14;
  48828. ActionManager._OnKeyUpTrigger = 15;
  48829. ActionManager._OnPickOutTrigger = 16;
  48830. ActionManager.Triggers = {};
  48831. return ActionManager;
  48832. }());
  48833. BABYLON.ActionManager = ActionManager;
  48834. })(BABYLON || (BABYLON = {}));
  48835. //# sourceMappingURL=babylon.actionManager.js.map
  48836. var BABYLON;
  48837. (function (BABYLON) {
  48838. var InterpolateValueAction = /** @class */ (function (_super) {
  48839. __extends(InterpolateValueAction, _super);
  48840. function InterpolateValueAction(triggerOptions, target, propertyPath, value, duration, condition, stopOtherAnimations, onInterpolationDone) {
  48841. if (duration === void 0) { duration = 1000; }
  48842. var _this = _super.call(this, triggerOptions, condition) || this;
  48843. _this.propertyPath = propertyPath;
  48844. _this.value = value;
  48845. _this.duration = duration;
  48846. _this.stopOtherAnimations = stopOtherAnimations;
  48847. _this.onInterpolationDone = onInterpolationDone;
  48848. _this.onInterpolationDoneObservable = new BABYLON.Observable();
  48849. _this._target = _this._effectiveTarget = target;
  48850. return _this;
  48851. }
  48852. InterpolateValueAction.prototype._prepare = function () {
  48853. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  48854. this._property = this._getProperty(this.propertyPath);
  48855. };
  48856. InterpolateValueAction.prototype.execute = function () {
  48857. var _this = this;
  48858. var scene = this._actionManager.getScene();
  48859. var keys = [
  48860. {
  48861. frame: 0,
  48862. value: this._effectiveTarget[this._property]
  48863. }, {
  48864. frame: 100,
  48865. value: this.value
  48866. }
  48867. ];
  48868. var dataType;
  48869. if (typeof this.value === "number") {
  48870. dataType = BABYLON.Animation.ANIMATIONTYPE_FLOAT;
  48871. }
  48872. else if (this.value instanceof BABYLON.Color3) {
  48873. dataType = BABYLON.Animation.ANIMATIONTYPE_COLOR3;
  48874. }
  48875. else if (this.value instanceof BABYLON.Vector3) {
  48876. dataType = BABYLON.Animation.ANIMATIONTYPE_VECTOR3;
  48877. }
  48878. else if (this.value instanceof BABYLON.Matrix) {
  48879. dataType = BABYLON.Animation.ANIMATIONTYPE_MATRIX;
  48880. }
  48881. else if (this.value instanceof BABYLON.Quaternion) {
  48882. dataType = BABYLON.Animation.ANIMATIONTYPE_QUATERNION;
  48883. }
  48884. else {
  48885. BABYLON.Tools.Warn("InterpolateValueAction: Unsupported type (" + typeof this.value + ")");
  48886. return;
  48887. }
  48888. var animation = new BABYLON.Animation("InterpolateValueAction", this._property, 100 * (1000.0 / this.duration), dataType, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  48889. animation.setKeys(keys);
  48890. if (this.stopOtherAnimations) {
  48891. scene.stopAnimation(this._effectiveTarget);
  48892. }
  48893. var wrapper = function () {
  48894. _this.onInterpolationDoneObservable.notifyObservers(_this);
  48895. if (_this.onInterpolationDone) {
  48896. _this.onInterpolationDone();
  48897. }
  48898. };
  48899. scene.beginDirectAnimation(this._effectiveTarget, [animation], 0, 100, false, 1, wrapper);
  48900. };
  48901. InterpolateValueAction.prototype.serialize = function (parent) {
  48902. return _super.prototype._serialize.call(this, {
  48903. name: "InterpolateValueAction",
  48904. properties: [
  48905. BABYLON.Action._GetTargetProperty(this._target),
  48906. { name: "propertyPath", value: this.propertyPath },
  48907. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) },
  48908. { name: "duration", value: BABYLON.Action._SerializeValueAsString(this.duration) },
  48909. { name: "stopOtherAnimations", value: BABYLON.Action._SerializeValueAsString(this.stopOtherAnimations) || false }
  48910. ]
  48911. }, parent);
  48912. };
  48913. return InterpolateValueAction;
  48914. }(BABYLON.Action));
  48915. BABYLON.InterpolateValueAction = InterpolateValueAction;
  48916. })(BABYLON || (BABYLON = {}));
  48917. //# sourceMappingURL=babylon.interpolateValueAction.js.map
  48918. var BABYLON;
  48919. (function (BABYLON) {
  48920. var SwitchBooleanAction = /** @class */ (function (_super) {
  48921. __extends(SwitchBooleanAction, _super);
  48922. function SwitchBooleanAction(triggerOptions, target, propertyPath, condition) {
  48923. var _this = _super.call(this, triggerOptions, condition) || this;
  48924. _this.propertyPath = propertyPath;
  48925. _this._target = _this._effectiveTarget = target;
  48926. return _this;
  48927. }
  48928. SwitchBooleanAction.prototype._prepare = function () {
  48929. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  48930. this._property = this._getProperty(this.propertyPath);
  48931. };
  48932. SwitchBooleanAction.prototype.execute = function () {
  48933. this._effectiveTarget[this._property] = !this._effectiveTarget[this._property];
  48934. };
  48935. SwitchBooleanAction.prototype.serialize = function (parent) {
  48936. return _super.prototype._serialize.call(this, {
  48937. name: "SwitchBooleanAction",
  48938. properties: [
  48939. BABYLON.Action._GetTargetProperty(this._target),
  48940. { name: "propertyPath", value: this.propertyPath }
  48941. ]
  48942. }, parent);
  48943. };
  48944. return SwitchBooleanAction;
  48945. }(BABYLON.Action));
  48946. BABYLON.SwitchBooleanAction = SwitchBooleanAction;
  48947. var SetStateAction = /** @class */ (function (_super) {
  48948. __extends(SetStateAction, _super);
  48949. function SetStateAction(triggerOptions, target, value, condition) {
  48950. var _this = _super.call(this, triggerOptions, condition) || this;
  48951. _this.value = value;
  48952. _this._target = target;
  48953. return _this;
  48954. }
  48955. SetStateAction.prototype.execute = function () {
  48956. this._target.state = this.value;
  48957. };
  48958. SetStateAction.prototype.serialize = function (parent) {
  48959. return _super.prototype._serialize.call(this, {
  48960. name: "SetStateAction",
  48961. properties: [
  48962. BABYLON.Action._GetTargetProperty(this._target),
  48963. { name: "value", value: this.value }
  48964. ]
  48965. }, parent);
  48966. };
  48967. return SetStateAction;
  48968. }(BABYLON.Action));
  48969. BABYLON.SetStateAction = SetStateAction;
  48970. var SetValueAction = /** @class */ (function (_super) {
  48971. __extends(SetValueAction, _super);
  48972. function SetValueAction(triggerOptions, target, propertyPath, value, condition) {
  48973. var _this = _super.call(this, triggerOptions, condition) || this;
  48974. _this.propertyPath = propertyPath;
  48975. _this.value = value;
  48976. _this._target = _this._effectiveTarget = target;
  48977. return _this;
  48978. }
  48979. SetValueAction.prototype._prepare = function () {
  48980. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  48981. this._property = this._getProperty(this.propertyPath);
  48982. };
  48983. SetValueAction.prototype.execute = function () {
  48984. this._effectiveTarget[this._property] = this.value;
  48985. if (this._target.markAsDirty) {
  48986. this._target.markAsDirty(this._property);
  48987. }
  48988. };
  48989. SetValueAction.prototype.serialize = function (parent) {
  48990. return _super.prototype._serialize.call(this, {
  48991. name: "SetValueAction",
  48992. properties: [
  48993. BABYLON.Action._GetTargetProperty(this._target),
  48994. { name: "propertyPath", value: this.propertyPath },
  48995. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) }
  48996. ]
  48997. }, parent);
  48998. };
  48999. return SetValueAction;
  49000. }(BABYLON.Action));
  49001. BABYLON.SetValueAction = SetValueAction;
  49002. var IncrementValueAction = /** @class */ (function (_super) {
  49003. __extends(IncrementValueAction, _super);
  49004. function IncrementValueAction(triggerOptions, target, propertyPath, value, condition) {
  49005. var _this = _super.call(this, triggerOptions, condition) || this;
  49006. _this.propertyPath = propertyPath;
  49007. _this.value = value;
  49008. _this._target = _this._effectiveTarget = target;
  49009. return _this;
  49010. }
  49011. IncrementValueAction.prototype._prepare = function () {
  49012. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  49013. this._property = this._getProperty(this.propertyPath);
  49014. if (typeof this._effectiveTarget[this._property] !== "number") {
  49015. BABYLON.Tools.Warn("Warning: IncrementValueAction can only be used with number values");
  49016. }
  49017. };
  49018. IncrementValueAction.prototype.execute = function () {
  49019. this._effectiveTarget[this._property] += this.value;
  49020. if (this._target.markAsDirty) {
  49021. this._target.markAsDirty(this._property);
  49022. }
  49023. };
  49024. IncrementValueAction.prototype.serialize = function (parent) {
  49025. return _super.prototype._serialize.call(this, {
  49026. name: "IncrementValueAction",
  49027. properties: [
  49028. BABYLON.Action._GetTargetProperty(this._target),
  49029. { name: "propertyPath", value: this.propertyPath },
  49030. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) }
  49031. ]
  49032. }, parent);
  49033. };
  49034. return IncrementValueAction;
  49035. }(BABYLON.Action));
  49036. BABYLON.IncrementValueAction = IncrementValueAction;
  49037. var PlayAnimationAction = /** @class */ (function (_super) {
  49038. __extends(PlayAnimationAction, _super);
  49039. function PlayAnimationAction(triggerOptions, target, from, to, loop, condition) {
  49040. var _this = _super.call(this, triggerOptions, condition) || this;
  49041. _this.from = from;
  49042. _this.to = to;
  49043. _this.loop = loop;
  49044. _this._target = target;
  49045. return _this;
  49046. }
  49047. PlayAnimationAction.prototype._prepare = function () {
  49048. };
  49049. PlayAnimationAction.prototype.execute = function () {
  49050. var scene = this._actionManager.getScene();
  49051. scene.beginAnimation(this._target, this.from, this.to, this.loop);
  49052. };
  49053. PlayAnimationAction.prototype.serialize = function (parent) {
  49054. return _super.prototype._serialize.call(this, {
  49055. name: "PlayAnimationAction",
  49056. properties: [
  49057. BABYLON.Action._GetTargetProperty(this._target),
  49058. { name: "from", value: String(this.from) },
  49059. { name: "to", value: String(this.to) },
  49060. { name: "loop", value: BABYLON.Action._SerializeValueAsString(this.loop) || false }
  49061. ]
  49062. }, parent);
  49063. };
  49064. return PlayAnimationAction;
  49065. }(BABYLON.Action));
  49066. BABYLON.PlayAnimationAction = PlayAnimationAction;
  49067. var StopAnimationAction = /** @class */ (function (_super) {
  49068. __extends(StopAnimationAction, _super);
  49069. function StopAnimationAction(triggerOptions, target, condition) {
  49070. var _this = _super.call(this, triggerOptions, condition) || this;
  49071. _this._target = target;
  49072. return _this;
  49073. }
  49074. StopAnimationAction.prototype._prepare = function () {
  49075. };
  49076. StopAnimationAction.prototype.execute = function () {
  49077. var scene = this._actionManager.getScene();
  49078. scene.stopAnimation(this._target);
  49079. };
  49080. StopAnimationAction.prototype.serialize = function (parent) {
  49081. return _super.prototype._serialize.call(this, {
  49082. name: "StopAnimationAction",
  49083. properties: [BABYLON.Action._GetTargetProperty(this._target)]
  49084. }, parent);
  49085. };
  49086. return StopAnimationAction;
  49087. }(BABYLON.Action));
  49088. BABYLON.StopAnimationAction = StopAnimationAction;
  49089. var DoNothingAction = /** @class */ (function (_super) {
  49090. __extends(DoNothingAction, _super);
  49091. function DoNothingAction(triggerOptions, condition) {
  49092. if (triggerOptions === void 0) { triggerOptions = BABYLON.ActionManager.NothingTrigger; }
  49093. return _super.call(this, triggerOptions, condition) || this;
  49094. }
  49095. DoNothingAction.prototype.execute = function () {
  49096. };
  49097. DoNothingAction.prototype.serialize = function (parent) {
  49098. return _super.prototype._serialize.call(this, {
  49099. name: "DoNothingAction",
  49100. properties: []
  49101. }, parent);
  49102. };
  49103. return DoNothingAction;
  49104. }(BABYLON.Action));
  49105. BABYLON.DoNothingAction = DoNothingAction;
  49106. var CombineAction = /** @class */ (function (_super) {
  49107. __extends(CombineAction, _super);
  49108. function CombineAction(triggerOptions, children, condition) {
  49109. var _this = _super.call(this, triggerOptions, condition) || this;
  49110. _this.children = children;
  49111. return _this;
  49112. }
  49113. CombineAction.prototype._prepare = function () {
  49114. for (var index = 0; index < this.children.length; index++) {
  49115. this.children[index]._actionManager = this._actionManager;
  49116. this.children[index]._prepare();
  49117. }
  49118. };
  49119. CombineAction.prototype.execute = function (evt) {
  49120. for (var index = 0; index < this.children.length; index++) {
  49121. this.children[index].execute(evt);
  49122. }
  49123. };
  49124. CombineAction.prototype.serialize = function (parent) {
  49125. var serializationObject = _super.prototype._serialize.call(this, {
  49126. name: "CombineAction",
  49127. properties: [],
  49128. combine: []
  49129. }, parent);
  49130. for (var i = 0; i < this.children.length; i++) {
  49131. serializationObject.combine.push(this.children[i].serialize(null));
  49132. }
  49133. return serializationObject;
  49134. };
  49135. return CombineAction;
  49136. }(BABYLON.Action));
  49137. BABYLON.CombineAction = CombineAction;
  49138. var ExecuteCodeAction = /** @class */ (function (_super) {
  49139. __extends(ExecuteCodeAction, _super);
  49140. function ExecuteCodeAction(triggerOptions, func, condition) {
  49141. var _this = _super.call(this, triggerOptions, condition) || this;
  49142. _this.func = func;
  49143. return _this;
  49144. }
  49145. ExecuteCodeAction.prototype.execute = function (evt) {
  49146. this.func(evt);
  49147. };
  49148. return ExecuteCodeAction;
  49149. }(BABYLON.Action));
  49150. BABYLON.ExecuteCodeAction = ExecuteCodeAction;
  49151. var SetParentAction = /** @class */ (function (_super) {
  49152. __extends(SetParentAction, _super);
  49153. function SetParentAction(triggerOptions, target, parent, condition) {
  49154. var _this = _super.call(this, triggerOptions, condition) || this;
  49155. _this._target = target;
  49156. _this._parent = parent;
  49157. return _this;
  49158. }
  49159. SetParentAction.prototype._prepare = function () {
  49160. };
  49161. SetParentAction.prototype.execute = function () {
  49162. if (this._target.parent === this._parent) {
  49163. return;
  49164. }
  49165. var invertParentWorldMatrix = this._parent.getWorldMatrix().clone();
  49166. invertParentWorldMatrix.invert();
  49167. this._target.position = BABYLON.Vector3.TransformCoordinates(this._target.position, invertParentWorldMatrix);
  49168. this._target.parent = this._parent;
  49169. };
  49170. SetParentAction.prototype.serialize = function (parent) {
  49171. return _super.prototype._serialize.call(this, {
  49172. name: "SetParentAction",
  49173. properties: [
  49174. BABYLON.Action._GetTargetProperty(this._target),
  49175. BABYLON.Action._GetTargetProperty(this._parent),
  49176. ]
  49177. }, parent);
  49178. };
  49179. return SetParentAction;
  49180. }(BABYLON.Action));
  49181. BABYLON.SetParentAction = SetParentAction;
  49182. var PlaySoundAction = /** @class */ (function (_super) {
  49183. __extends(PlaySoundAction, _super);
  49184. function PlaySoundAction(triggerOptions, sound, condition) {
  49185. var _this = _super.call(this, triggerOptions, condition) || this;
  49186. _this._sound = sound;
  49187. return _this;
  49188. }
  49189. PlaySoundAction.prototype._prepare = function () {
  49190. };
  49191. PlaySoundAction.prototype.execute = function () {
  49192. if (this._sound !== undefined)
  49193. this._sound.play();
  49194. };
  49195. PlaySoundAction.prototype.serialize = function (parent) {
  49196. return _super.prototype._serialize.call(this, {
  49197. name: "PlaySoundAction",
  49198. properties: [{ name: "sound", value: this._sound.name }]
  49199. }, parent);
  49200. };
  49201. return PlaySoundAction;
  49202. }(BABYLON.Action));
  49203. BABYLON.PlaySoundAction = PlaySoundAction;
  49204. var StopSoundAction = /** @class */ (function (_super) {
  49205. __extends(StopSoundAction, _super);
  49206. function StopSoundAction(triggerOptions, sound, condition) {
  49207. var _this = _super.call(this, triggerOptions, condition) || this;
  49208. _this._sound = sound;
  49209. return _this;
  49210. }
  49211. StopSoundAction.prototype._prepare = function () {
  49212. };
  49213. StopSoundAction.prototype.execute = function () {
  49214. if (this._sound !== undefined)
  49215. this._sound.stop();
  49216. };
  49217. StopSoundAction.prototype.serialize = function (parent) {
  49218. return _super.prototype._serialize.call(this, {
  49219. name: "StopSoundAction",
  49220. properties: [{ name: "sound", value: this._sound.name }]
  49221. }, parent);
  49222. };
  49223. return StopSoundAction;
  49224. }(BABYLON.Action));
  49225. BABYLON.StopSoundAction = StopSoundAction;
  49226. })(BABYLON || (BABYLON = {}));
  49227. //# sourceMappingURL=babylon.directActions.js.map
  49228. var BABYLON;
  49229. (function (BABYLON) {
  49230. var SpriteManager = /** @class */ (function () {
  49231. function SpriteManager(name, imgUrl, capacity, cellSize, scene, epsilon, samplingMode) {
  49232. if (epsilon === void 0) { epsilon = 0.01; }
  49233. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  49234. this.name = name;
  49235. this.sprites = new Array();
  49236. this.renderingGroupId = 0;
  49237. this.layerMask = 0x0FFFFFFF;
  49238. this.fogEnabled = true;
  49239. this.isPickable = false;
  49240. /**
  49241. * An event triggered when the manager is disposed.
  49242. * @type {BABYLON.Observable}
  49243. */
  49244. this.onDisposeObservable = new BABYLON.Observable();
  49245. this._vertexBuffers = {};
  49246. this._capacity = capacity;
  49247. this._spriteTexture = new BABYLON.Texture(imgUrl, scene, true, false, samplingMode);
  49248. this._spriteTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  49249. this._spriteTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  49250. if (cellSize.width && cellSize.height) {
  49251. this.cellWidth = cellSize.width;
  49252. this.cellHeight = cellSize.height;
  49253. }
  49254. else if (cellSize !== undefined) {
  49255. this.cellWidth = cellSize;
  49256. this.cellHeight = cellSize;
  49257. }
  49258. else {
  49259. return;
  49260. }
  49261. this._epsilon = epsilon;
  49262. this._scene = scene;
  49263. this._scene.spriteManagers.push(this);
  49264. var indices = [];
  49265. var index = 0;
  49266. for (var count = 0; count < capacity; count++) {
  49267. indices.push(index);
  49268. indices.push(index + 1);
  49269. indices.push(index + 2);
  49270. indices.push(index);
  49271. indices.push(index + 2);
  49272. indices.push(index + 3);
  49273. index += 4;
  49274. }
  49275. this._indexBuffer = scene.getEngine().createIndexBuffer(indices);
  49276. // VBO
  49277. // 16 floats per sprite (x, y, z, angle, sizeX, sizeY, offsetX, offsetY, invertU, invertV, cellIndexX, cellIndexY, color r, color g, color b, color a)
  49278. this._vertexData = new Float32Array(capacity * 16 * 4);
  49279. this._buffer = new BABYLON.Buffer(scene.getEngine(), this._vertexData, true, 16);
  49280. var positions = this._buffer.createVertexBuffer(BABYLON.VertexBuffer.PositionKind, 0, 4);
  49281. var options = this._buffer.createVertexBuffer("options", 4, 4);
  49282. var cellInfo = this._buffer.createVertexBuffer("cellInfo", 8, 4);
  49283. var colors = this._buffer.createVertexBuffer(BABYLON.VertexBuffer.ColorKind, 12, 4);
  49284. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = positions;
  49285. this._vertexBuffers["options"] = options;
  49286. this._vertexBuffers["cellInfo"] = cellInfo;
  49287. this._vertexBuffers[BABYLON.VertexBuffer.ColorKind] = colors;
  49288. // Effects
  49289. this._effectBase = this._scene.getEngine().createEffect("sprites", [BABYLON.VertexBuffer.PositionKind, "options", "cellInfo", BABYLON.VertexBuffer.ColorKind], ["view", "projection", "textureInfos", "alphaTest"], ["diffuseSampler"], "");
  49290. this._effectFog = this._scene.getEngine().createEffect("sprites", [BABYLON.VertexBuffer.PositionKind, "options", "cellInfo", BABYLON.VertexBuffer.ColorKind], ["view", "projection", "textureInfos", "alphaTest", "vFogInfos", "vFogColor"], ["diffuseSampler"], "#define FOG");
  49291. }
  49292. Object.defineProperty(SpriteManager.prototype, "onDispose", {
  49293. set: function (callback) {
  49294. if (this._onDisposeObserver) {
  49295. this.onDisposeObservable.remove(this._onDisposeObserver);
  49296. }
  49297. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  49298. },
  49299. enumerable: true,
  49300. configurable: true
  49301. });
  49302. Object.defineProperty(SpriteManager.prototype, "texture", {
  49303. get: function () {
  49304. return this._spriteTexture;
  49305. },
  49306. set: function (value) {
  49307. this._spriteTexture = value;
  49308. },
  49309. enumerable: true,
  49310. configurable: true
  49311. });
  49312. SpriteManager.prototype._appendSpriteVertex = function (index, sprite, offsetX, offsetY, rowSize) {
  49313. var arrayOffset = index * 16;
  49314. if (offsetX === 0)
  49315. offsetX = this._epsilon;
  49316. else if (offsetX === 1)
  49317. offsetX = 1 - this._epsilon;
  49318. if (offsetY === 0)
  49319. offsetY = this._epsilon;
  49320. else if (offsetY === 1)
  49321. offsetY = 1 - this._epsilon;
  49322. this._vertexData[arrayOffset] = sprite.position.x;
  49323. this._vertexData[arrayOffset + 1] = sprite.position.y;
  49324. this._vertexData[arrayOffset + 2] = sprite.position.z;
  49325. this._vertexData[arrayOffset + 3] = sprite.angle;
  49326. this._vertexData[arrayOffset + 4] = sprite.width;
  49327. this._vertexData[arrayOffset + 5] = sprite.height;
  49328. this._vertexData[arrayOffset + 6] = offsetX;
  49329. this._vertexData[arrayOffset + 7] = offsetY;
  49330. this._vertexData[arrayOffset + 8] = sprite.invertU ? 1 : 0;
  49331. this._vertexData[arrayOffset + 9] = sprite.invertV ? 1 : 0;
  49332. var offset = (sprite.cellIndex / rowSize) >> 0;
  49333. this._vertexData[arrayOffset + 10] = sprite.cellIndex - offset * rowSize;
  49334. this._vertexData[arrayOffset + 11] = offset;
  49335. // Color
  49336. this._vertexData[arrayOffset + 12] = sprite.color.r;
  49337. this._vertexData[arrayOffset + 13] = sprite.color.g;
  49338. this._vertexData[arrayOffset + 14] = sprite.color.b;
  49339. this._vertexData[arrayOffset + 15] = sprite.color.a;
  49340. };
  49341. SpriteManager.prototype.intersects = function (ray, camera, predicate, fastCheck) {
  49342. var count = Math.min(this._capacity, this.sprites.length);
  49343. var min = BABYLON.Vector3.Zero();
  49344. var max = BABYLON.Vector3.Zero();
  49345. var distance = Number.MAX_VALUE;
  49346. var currentSprite = null;
  49347. var cameraSpacePosition = BABYLON.Vector3.Zero();
  49348. var cameraView = camera.getViewMatrix();
  49349. for (var index = 0; index < count; index++) {
  49350. var sprite = this.sprites[index];
  49351. if (!sprite) {
  49352. continue;
  49353. }
  49354. if (predicate) {
  49355. if (!predicate(sprite)) {
  49356. continue;
  49357. }
  49358. }
  49359. else if (!sprite.isPickable) {
  49360. continue;
  49361. }
  49362. BABYLON.Vector3.TransformCoordinatesToRef(sprite.position, cameraView, cameraSpacePosition);
  49363. min.copyFromFloats(cameraSpacePosition.x - sprite.width / 2, cameraSpacePosition.y - sprite.height / 2, cameraSpacePosition.z);
  49364. max.copyFromFloats(cameraSpacePosition.x + sprite.width / 2, cameraSpacePosition.y + sprite.height / 2, cameraSpacePosition.z);
  49365. if (ray.intersectsBoxMinMax(min, max)) {
  49366. var currentDistance = BABYLON.Vector3.Distance(cameraSpacePosition, ray.origin);
  49367. if (distance > currentDistance) {
  49368. distance = currentDistance;
  49369. currentSprite = sprite;
  49370. if (fastCheck) {
  49371. break;
  49372. }
  49373. }
  49374. }
  49375. }
  49376. if (currentSprite) {
  49377. var result = new BABYLON.PickingInfo();
  49378. result.hit = true;
  49379. result.pickedSprite = currentSprite;
  49380. result.distance = distance;
  49381. return result;
  49382. }
  49383. return null;
  49384. };
  49385. SpriteManager.prototype.render = function () {
  49386. // Check
  49387. if (!this._effectBase.isReady() || !this._effectFog.isReady() || !this._spriteTexture || !this._spriteTexture.isReady())
  49388. return;
  49389. var engine = this._scene.getEngine();
  49390. var baseSize = this._spriteTexture.getBaseSize();
  49391. // Sprites
  49392. var deltaTime = engine.getDeltaTime();
  49393. var max = Math.min(this._capacity, this.sprites.length);
  49394. var rowSize = baseSize.width / this.cellWidth;
  49395. var offset = 0;
  49396. for (var index = 0; index < max; index++) {
  49397. var sprite = this.sprites[index];
  49398. if (!sprite) {
  49399. continue;
  49400. }
  49401. sprite._animate(deltaTime);
  49402. this._appendSpriteVertex(offset++, sprite, 0, 0, rowSize);
  49403. this._appendSpriteVertex(offset++, sprite, 1, 0, rowSize);
  49404. this._appendSpriteVertex(offset++, sprite, 1, 1, rowSize);
  49405. this._appendSpriteVertex(offset++, sprite, 0, 1, rowSize);
  49406. }
  49407. this._buffer.update(this._vertexData);
  49408. // Render
  49409. var effect = this._effectBase;
  49410. if (this._scene.fogEnabled && this._scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && this.fogEnabled) {
  49411. effect = this._effectFog;
  49412. }
  49413. engine.enableEffect(effect);
  49414. var viewMatrix = this._scene.getViewMatrix();
  49415. effect.setTexture("diffuseSampler", this._spriteTexture);
  49416. effect.setMatrix("view", viewMatrix);
  49417. effect.setMatrix("projection", this._scene.getProjectionMatrix());
  49418. effect.setFloat2("textureInfos", this.cellWidth / baseSize.width, this.cellHeight / baseSize.height);
  49419. // Fog
  49420. if (this._scene.fogEnabled && this._scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && this.fogEnabled) {
  49421. effect.setFloat4("vFogInfos", this._scene.fogMode, this._scene.fogStart, this._scene.fogEnd, this._scene.fogDensity);
  49422. effect.setColor3("vFogColor", this._scene.fogColor);
  49423. }
  49424. // VBOs
  49425. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  49426. // Draw order
  49427. engine.setDepthFunctionToLessOrEqual();
  49428. effect.setBool("alphaTest", true);
  49429. engine.setColorWrite(false);
  49430. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, max * 6);
  49431. engine.setColorWrite(true);
  49432. effect.setBool("alphaTest", false);
  49433. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  49434. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, max * 6);
  49435. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  49436. };
  49437. SpriteManager.prototype.dispose = function () {
  49438. if (this._buffer) {
  49439. this._buffer.dispose();
  49440. this._buffer = null;
  49441. }
  49442. if (this._indexBuffer) {
  49443. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  49444. this._indexBuffer = null;
  49445. }
  49446. if (this._spriteTexture) {
  49447. this._spriteTexture.dispose();
  49448. this._spriteTexture = null;
  49449. }
  49450. // Remove from scene
  49451. var index = this._scene.spriteManagers.indexOf(this);
  49452. this._scene.spriteManagers.splice(index, 1);
  49453. // Callback
  49454. this.onDisposeObservable.notifyObservers(this);
  49455. this.onDisposeObservable.clear();
  49456. };
  49457. return SpriteManager;
  49458. }());
  49459. BABYLON.SpriteManager = SpriteManager;
  49460. })(BABYLON || (BABYLON = {}));
  49461. //# sourceMappingURL=babylon.spriteManager.js.map
  49462. var BABYLON;
  49463. (function (BABYLON) {
  49464. var Sprite = /** @class */ (function () {
  49465. function Sprite(name, manager) {
  49466. this.name = name;
  49467. this.color = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  49468. this.width = 1.0;
  49469. this.height = 1.0;
  49470. this.angle = 0;
  49471. this.cellIndex = 0;
  49472. this.invertU = 0;
  49473. this.invertV = 0;
  49474. this.animations = new Array();
  49475. this.isPickable = false;
  49476. this._animationStarted = false;
  49477. this._loopAnimation = false;
  49478. this._fromIndex = 0;
  49479. this._toIndex = 0;
  49480. this._delay = 0;
  49481. this._direction = 1;
  49482. this._time = 0;
  49483. this._manager = manager;
  49484. this._manager.sprites.push(this);
  49485. this.position = BABYLON.Vector3.Zero();
  49486. }
  49487. Object.defineProperty(Sprite.prototype, "size", {
  49488. get: function () {
  49489. return this.width;
  49490. },
  49491. set: function (value) {
  49492. this.width = value;
  49493. this.height = value;
  49494. },
  49495. enumerable: true,
  49496. configurable: true
  49497. });
  49498. Sprite.prototype.playAnimation = function (from, to, loop, delay, onAnimationEnd) {
  49499. this._fromIndex = from;
  49500. this._toIndex = to;
  49501. this._loopAnimation = loop;
  49502. this._delay = delay;
  49503. this._animationStarted = true;
  49504. this._direction = from < to ? 1 : -1;
  49505. this.cellIndex = from;
  49506. this._time = 0;
  49507. this._onAnimationEnd = onAnimationEnd;
  49508. };
  49509. Sprite.prototype.stopAnimation = function () {
  49510. this._animationStarted = false;
  49511. };
  49512. Sprite.prototype._animate = function (deltaTime) {
  49513. if (!this._animationStarted)
  49514. return;
  49515. this._time += deltaTime;
  49516. if (this._time > this._delay) {
  49517. this._time = this._time % this._delay;
  49518. this.cellIndex += this._direction;
  49519. if (this.cellIndex > this._toIndex) {
  49520. if (this._loopAnimation) {
  49521. this.cellIndex = this._fromIndex;
  49522. }
  49523. else {
  49524. this.cellIndex = this._toIndex;
  49525. this._animationStarted = false;
  49526. if (this._onAnimationEnd) {
  49527. this._onAnimationEnd();
  49528. }
  49529. if (this.disposeWhenFinishedAnimating) {
  49530. this.dispose();
  49531. }
  49532. }
  49533. }
  49534. }
  49535. };
  49536. Sprite.prototype.dispose = function () {
  49537. for (var i = 0; i < this._manager.sprites.length; i++) {
  49538. if (this._manager.sprites[i] == this) {
  49539. this._manager.sprites.splice(i, 1);
  49540. }
  49541. }
  49542. };
  49543. return Sprite;
  49544. }());
  49545. BABYLON.Sprite = Sprite;
  49546. })(BABYLON || (BABYLON = {}));
  49547. //# sourceMappingURL=babylon.sprite.js.map
  49548. var BABYLON;
  49549. (function (BABYLON) {
  49550. var IntersectionInfo = /** @class */ (function () {
  49551. function IntersectionInfo(bu, bv, distance) {
  49552. this.bu = bu;
  49553. this.bv = bv;
  49554. this.distance = distance;
  49555. this.faceId = 0;
  49556. this.subMeshId = 0;
  49557. }
  49558. return IntersectionInfo;
  49559. }());
  49560. BABYLON.IntersectionInfo = IntersectionInfo;
  49561. var PickingInfo = /** @class */ (function () {
  49562. function PickingInfo() {
  49563. this.hit = false;
  49564. this.distance = 0;
  49565. this.pickedPoint = null;
  49566. this.pickedMesh = null;
  49567. this.bu = 0;
  49568. this.bv = 0;
  49569. this.faceId = -1;
  49570. this.subMeshId = 0;
  49571. this.pickedSprite = null;
  49572. }
  49573. // Methods
  49574. PickingInfo.prototype.getNormal = function (useWorldCoordinates, useVerticesNormals) {
  49575. if (useWorldCoordinates === void 0) { useWorldCoordinates = false; }
  49576. if (useVerticesNormals === void 0) { useVerticesNormals = true; }
  49577. if (!this.pickedMesh || !this.pickedMesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  49578. return null;
  49579. }
  49580. var indices = this.pickedMesh.getIndices();
  49581. if (!indices) {
  49582. return null;
  49583. }
  49584. var result;
  49585. if (useVerticesNormals) {
  49586. var normals = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  49587. var normal0 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3] * 3);
  49588. var normal1 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3 + 1] * 3);
  49589. var normal2 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3 + 2] * 3);
  49590. normal0 = normal0.scale(this.bu);
  49591. normal1 = normal1.scale(this.bv);
  49592. normal2 = normal2.scale(1.0 - this.bu - this.bv);
  49593. result = new BABYLON.Vector3(normal0.x + normal1.x + normal2.x, normal0.y + normal1.y + normal2.y, normal0.z + normal1.z + normal2.z);
  49594. }
  49595. else {
  49596. var positions = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  49597. var vertex1 = BABYLON.Vector3.FromArray(positions, indices[this.faceId * 3] * 3);
  49598. var vertex2 = BABYLON.Vector3.FromArray(positions, indices[this.faceId * 3 + 1] * 3);
  49599. var vertex3 = BABYLON.Vector3.FromArray(positions, indices[this.faceId * 3 + 2] * 3);
  49600. var p1p2 = vertex1.subtract(vertex2);
  49601. var p3p2 = vertex3.subtract(vertex2);
  49602. result = BABYLON.Vector3.Cross(p1p2, p3p2);
  49603. }
  49604. if (useWorldCoordinates) {
  49605. result = BABYLON.Vector3.TransformNormal(result, this.pickedMesh.getWorldMatrix());
  49606. }
  49607. return BABYLON.Vector3.Normalize(result);
  49608. };
  49609. PickingInfo.prototype.getTextureCoordinates = function () {
  49610. if (!this.pickedMesh || !this.pickedMesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  49611. return null;
  49612. }
  49613. var indices = this.pickedMesh.getIndices();
  49614. if (!indices) {
  49615. return null;
  49616. }
  49617. var uvs = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  49618. if (!uvs) {
  49619. return null;
  49620. }
  49621. var uv0 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3] * 2);
  49622. var uv1 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3 + 1] * 2);
  49623. var uv2 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3 + 2] * 2);
  49624. uv0 = uv0.scale(1.0 - this.bu - this.bv);
  49625. uv1 = uv1.scale(this.bu);
  49626. uv2 = uv2.scale(this.bv);
  49627. return new BABYLON.Vector2(uv0.x + uv1.x + uv2.x, uv0.y + uv1.y + uv2.y);
  49628. };
  49629. return PickingInfo;
  49630. }());
  49631. BABYLON.PickingInfo = PickingInfo;
  49632. })(BABYLON || (BABYLON = {}));
  49633. //# sourceMappingURL=babylon.pickingInfo.js.map
  49634. var BABYLON;
  49635. (function (BABYLON) {
  49636. var Ray = /** @class */ (function () {
  49637. function Ray(origin, direction, length) {
  49638. if (length === void 0) { length = Number.MAX_VALUE; }
  49639. this.origin = origin;
  49640. this.direction = direction;
  49641. this.length = length;
  49642. }
  49643. // Methods
  49644. Ray.prototype.intersectsBoxMinMax = function (minimum, maximum) {
  49645. var d = 0.0;
  49646. var maxValue = Number.MAX_VALUE;
  49647. var inv;
  49648. var min;
  49649. var max;
  49650. var temp;
  49651. if (Math.abs(this.direction.x) < 0.0000001) {
  49652. if (this.origin.x < minimum.x || this.origin.x > maximum.x) {
  49653. return false;
  49654. }
  49655. }
  49656. else {
  49657. inv = 1.0 / this.direction.x;
  49658. min = (minimum.x - this.origin.x) * inv;
  49659. max = (maximum.x - this.origin.x) * inv;
  49660. if (max === -Infinity) {
  49661. max = Infinity;
  49662. }
  49663. if (min > max) {
  49664. temp = min;
  49665. min = max;
  49666. max = temp;
  49667. }
  49668. d = Math.max(min, d);
  49669. maxValue = Math.min(max, maxValue);
  49670. if (d > maxValue) {
  49671. return false;
  49672. }
  49673. }
  49674. if (Math.abs(this.direction.y) < 0.0000001) {
  49675. if (this.origin.y < minimum.y || this.origin.y > maximum.y) {
  49676. return false;
  49677. }
  49678. }
  49679. else {
  49680. inv = 1.0 / this.direction.y;
  49681. min = (minimum.y - this.origin.y) * inv;
  49682. max = (maximum.y - this.origin.y) * inv;
  49683. if (max === -Infinity) {
  49684. max = Infinity;
  49685. }
  49686. if (min > max) {
  49687. temp = min;
  49688. min = max;
  49689. max = temp;
  49690. }
  49691. d = Math.max(min, d);
  49692. maxValue = Math.min(max, maxValue);
  49693. if (d > maxValue) {
  49694. return false;
  49695. }
  49696. }
  49697. if (Math.abs(this.direction.z) < 0.0000001) {
  49698. if (this.origin.z < minimum.z || this.origin.z > maximum.z) {
  49699. return false;
  49700. }
  49701. }
  49702. else {
  49703. inv = 1.0 / this.direction.z;
  49704. min = (minimum.z - this.origin.z) * inv;
  49705. max = (maximum.z - this.origin.z) * inv;
  49706. if (max === -Infinity) {
  49707. max = Infinity;
  49708. }
  49709. if (min > max) {
  49710. temp = min;
  49711. min = max;
  49712. max = temp;
  49713. }
  49714. d = Math.max(min, d);
  49715. maxValue = Math.min(max, maxValue);
  49716. if (d > maxValue) {
  49717. return false;
  49718. }
  49719. }
  49720. return true;
  49721. };
  49722. Ray.prototype.intersectsBox = function (box) {
  49723. return this.intersectsBoxMinMax(box.minimum, box.maximum);
  49724. };
  49725. Ray.prototype.intersectsSphere = function (sphere) {
  49726. var x = sphere.center.x - this.origin.x;
  49727. var y = sphere.center.y - this.origin.y;
  49728. var z = sphere.center.z - this.origin.z;
  49729. var pyth = (x * x) + (y * y) + (z * z);
  49730. var rr = sphere.radius * sphere.radius;
  49731. if (pyth <= rr) {
  49732. return true;
  49733. }
  49734. var dot = (x * this.direction.x) + (y * this.direction.y) + (z * this.direction.z);
  49735. if (dot < 0.0) {
  49736. return false;
  49737. }
  49738. var temp = pyth - (dot * dot);
  49739. return temp <= rr;
  49740. };
  49741. Ray.prototype.intersectsTriangle = function (vertex0, vertex1, vertex2) {
  49742. if (!this._edge1) {
  49743. this._edge1 = BABYLON.Vector3.Zero();
  49744. this._edge2 = BABYLON.Vector3.Zero();
  49745. this._pvec = BABYLON.Vector3.Zero();
  49746. this._tvec = BABYLON.Vector3.Zero();
  49747. this._qvec = BABYLON.Vector3.Zero();
  49748. }
  49749. vertex1.subtractToRef(vertex0, this._edge1);
  49750. vertex2.subtractToRef(vertex0, this._edge2);
  49751. BABYLON.Vector3.CrossToRef(this.direction, this._edge2, this._pvec);
  49752. var det = BABYLON.Vector3.Dot(this._edge1, this._pvec);
  49753. if (det === 0) {
  49754. return null;
  49755. }
  49756. var invdet = 1 / det;
  49757. this.origin.subtractToRef(vertex0, this._tvec);
  49758. var bu = BABYLON.Vector3.Dot(this._tvec, this._pvec) * invdet;
  49759. if (bu < 0 || bu > 1.0) {
  49760. return null;
  49761. }
  49762. BABYLON.Vector3.CrossToRef(this._tvec, this._edge1, this._qvec);
  49763. var bv = BABYLON.Vector3.Dot(this.direction, this._qvec) * invdet;
  49764. if (bv < 0 || bu + bv > 1.0) {
  49765. return null;
  49766. }
  49767. //check if the distance is longer than the predefined length.
  49768. var distance = BABYLON.Vector3.Dot(this._edge2, this._qvec) * invdet;
  49769. if (distance > this.length) {
  49770. return null;
  49771. }
  49772. return new BABYLON.IntersectionInfo(bu, bv, distance);
  49773. };
  49774. Ray.prototype.intersectsPlane = function (plane) {
  49775. var distance;
  49776. var result1 = BABYLON.Vector3.Dot(plane.normal, this.direction);
  49777. if (Math.abs(result1) < 9.99999997475243E-07) {
  49778. return null;
  49779. }
  49780. else {
  49781. var result2 = BABYLON.Vector3.Dot(plane.normal, this.origin);
  49782. distance = (-plane.d - result2) / result1;
  49783. if (distance < 0.0) {
  49784. if (distance < -9.99999997475243E-07) {
  49785. return null;
  49786. }
  49787. else {
  49788. return 0;
  49789. }
  49790. }
  49791. return distance;
  49792. }
  49793. };
  49794. Ray.prototype.intersectsMesh = function (mesh, fastCheck) {
  49795. var tm = BABYLON.Tmp.Matrix[0];
  49796. mesh.getWorldMatrix().invertToRef(tm);
  49797. if (this._tmpRay) {
  49798. Ray.TransformToRef(this, tm, this._tmpRay);
  49799. }
  49800. else {
  49801. this._tmpRay = Ray.Transform(this, tm);
  49802. }
  49803. return mesh.intersects(this._tmpRay, fastCheck);
  49804. };
  49805. Ray.prototype.intersectsMeshes = function (meshes, fastCheck, results) {
  49806. if (results) {
  49807. results.length = 0;
  49808. }
  49809. else {
  49810. results = [];
  49811. }
  49812. for (var i = 0; i < meshes.length; i++) {
  49813. var pickInfo = this.intersectsMesh(meshes[i], fastCheck);
  49814. if (pickInfo.hit) {
  49815. results.push(pickInfo);
  49816. }
  49817. }
  49818. results.sort(this._comparePickingInfo);
  49819. return results;
  49820. };
  49821. Ray.prototype._comparePickingInfo = function (pickingInfoA, pickingInfoB) {
  49822. if (pickingInfoA.distance < pickingInfoB.distance) {
  49823. return -1;
  49824. }
  49825. else if (pickingInfoA.distance > pickingInfoB.distance) {
  49826. return 1;
  49827. }
  49828. else {
  49829. return 0;
  49830. }
  49831. };
  49832. /**
  49833. * Intersection test between the ray and a given segment whithin a given tolerance (threshold)
  49834. * @param sega the first point of the segment to test the intersection against
  49835. * @param segb the second point of the segment to test the intersection against
  49836. * @param threshold the tolerance margin, if the ray doesn't intersect the segment but is close to the given threshold, the intersection is successful
  49837. * @return the distance from the ray origin to the intersection point if there's intersection, or -1 if there's no intersection
  49838. */
  49839. Ray.prototype.intersectionSegment = function (sega, segb, threshold) {
  49840. var rsegb = this.origin.add(this.direction.multiplyByFloats(Ray.rayl, Ray.rayl, Ray.rayl));
  49841. var u = segb.subtract(sega);
  49842. var v = rsegb.subtract(this.origin);
  49843. var w = sega.subtract(this.origin);
  49844. var a = BABYLON.Vector3.Dot(u, u); // always >= 0
  49845. var b = BABYLON.Vector3.Dot(u, v);
  49846. var c = BABYLON.Vector3.Dot(v, v); // always >= 0
  49847. var d = BABYLON.Vector3.Dot(u, w);
  49848. var e = BABYLON.Vector3.Dot(v, w);
  49849. var D = a * c - b * b; // always >= 0
  49850. var sc, sN, sD = D; // sc = sN / sD, default sD = D >= 0
  49851. var tc, tN, tD = D; // tc = tN / tD, default tD = D >= 0
  49852. // compute the line parameters of the two closest points
  49853. if (D < Ray.smallnum) {
  49854. sN = 0.0; // force using point P0 on segment S1
  49855. sD = 1.0; // to prevent possible division by 0.0 later
  49856. tN = e;
  49857. tD = c;
  49858. }
  49859. else {
  49860. sN = (b * e - c * d);
  49861. tN = (a * e - b * d);
  49862. if (sN < 0.0) {
  49863. sN = 0.0;
  49864. tN = e;
  49865. tD = c;
  49866. }
  49867. else if (sN > sD) {
  49868. sN = sD;
  49869. tN = e + b;
  49870. tD = c;
  49871. }
  49872. }
  49873. if (tN < 0.0) {
  49874. tN = 0.0;
  49875. // recompute sc for this edge
  49876. if (-d < 0.0) {
  49877. sN = 0.0;
  49878. }
  49879. else if (-d > a)
  49880. sN = sD;
  49881. else {
  49882. sN = -d;
  49883. sD = a;
  49884. }
  49885. }
  49886. else if (tN > tD) {
  49887. tN = tD;
  49888. // recompute sc for this edge
  49889. if ((-d + b) < 0.0) {
  49890. sN = 0;
  49891. }
  49892. else if ((-d + b) > a) {
  49893. sN = sD;
  49894. }
  49895. else {
  49896. sN = (-d + b);
  49897. sD = a;
  49898. }
  49899. }
  49900. // finally do the division to get sc and tc
  49901. sc = (Math.abs(sN) < Ray.smallnum ? 0.0 : sN / sD);
  49902. tc = (Math.abs(tN) < Ray.smallnum ? 0.0 : tN / tD);
  49903. // get the difference of the two closest points
  49904. var qtc = v.multiplyByFloats(tc, tc, tc);
  49905. var dP = w.add(u.multiplyByFloats(sc, sc, sc)).subtract(qtc); // = S1(sc) - S2(tc)
  49906. var isIntersected = (tc > 0) && (tc <= this.length) && (dP.lengthSquared() < (threshold * threshold)); // return intersection result
  49907. if (isIntersected) {
  49908. return qtc.length();
  49909. }
  49910. return -1;
  49911. };
  49912. Ray.prototype.update = function (x, y, viewportWidth, viewportHeight, world, view, projection) {
  49913. BABYLON.Vector3.UnprojectFloatsToRef(x, y, 0, viewportWidth, viewportHeight, world, view, projection, this.origin);
  49914. BABYLON.Vector3.UnprojectFloatsToRef(x, y, 1, viewportWidth, viewportHeight, world, view, projection, BABYLON.Tmp.Vector3[0]);
  49915. BABYLON.Tmp.Vector3[0].subtractToRef(this.origin, this.direction);
  49916. this.direction.normalize();
  49917. return this;
  49918. };
  49919. // Statics
  49920. Ray.Zero = function () {
  49921. return new Ray(BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero());
  49922. };
  49923. Ray.CreateNew = function (x, y, viewportWidth, viewportHeight, world, view, projection) {
  49924. var result = Ray.Zero();
  49925. return result.update(x, y, viewportWidth, viewportHeight, world, view, projection);
  49926. };
  49927. /**
  49928. * 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
  49929. * transformed to the given world matrix.
  49930. * @param origin The origin point
  49931. * @param end The end point
  49932. * @param world a matrix to transform the ray to. Default is the identity matrix.
  49933. */
  49934. Ray.CreateNewFromTo = function (origin, end, world) {
  49935. if (world === void 0) { world = BABYLON.Matrix.Identity(); }
  49936. var direction = end.subtract(origin);
  49937. var length = Math.sqrt((direction.x * direction.x) + (direction.y * direction.y) + (direction.z * direction.z));
  49938. direction.normalize();
  49939. return Ray.Transform(new Ray(origin, direction, length), world);
  49940. };
  49941. Ray.Transform = function (ray, matrix) {
  49942. var result = new Ray(new BABYLON.Vector3(0, 0, 0), new BABYLON.Vector3(0, 0, 0));
  49943. Ray.TransformToRef(ray, matrix, result);
  49944. return result;
  49945. };
  49946. Ray.TransformToRef = function (ray, matrix, result) {
  49947. BABYLON.Vector3.TransformCoordinatesToRef(ray.origin, matrix, result.origin);
  49948. BABYLON.Vector3.TransformNormalToRef(ray.direction, matrix, result.direction);
  49949. result.length = ray.length;
  49950. var dir = result.direction;
  49951. var len = dir.length();
  49952. if (!(len === 0 || len === 1)) {
  49953. var num = 1.0 / len;
  49954. dir.x *= num;
  49955. dir.y *= num;
  49956. dir.z *= num;
  49957. result.length *= len;
  49958. }
  49959. };
  49960. Ray.smallnum = 0.00000001;
  49961. Ray.rayl = 10e8;
  49962. return Ray;
  49963. }());
  49964. BABYLON.Ray = Ray;
  49965. })(BABYLON || (BABYLON = {}));
  49966. //# sourceMappingURL=babylon.ray.js.map
  49967. var BABYLON;
  49968. (function (BABYLON) {
  49969. var intersectBoxAASphere = function (boxMin, boxMax, sphereCenter, sphereRadius) {
  49970. if (boxMin.x > sphereCenter.x + sphereRadius)
  49971. return false;
  49972. if (sphereCenter.x - sphereRadius > boxMax.x)
  49973. return false;
  49974. if (boxMin.y > sphereCenter.y + sphereRadius)
  49975. return false;
  49976. if (sphereCenter.y - sphereRadius > boxMax.y)
  49977. return false;
  49978. if (boxMin.z > sphereCenter.z + sphereRadius)
  49979. return false;
  49980. if (sphereCenter.z - sphereRadius > boxMax.z)
  49981. return false;
  49982. return true;
  49983. };
  49984. var getLowestRoot = (function () {
  49985. var result = { root: 0, found: false };
  49986. return function (a, b, c, maxR) {
  49987. result.root = 0;
  49988. result.found = false;
  49989. var determinant = b * b - 4.0 * a * c;
  49990. if (determinant < 0)
  49991. return result;
  49992. var sqrtD = Math.sqrt(determinant);
  49993. var r1 = (-b - sqrtD) / (2.0 * a);
  49994. var r2 = (-b + sqrtD) / (2.0 * a);
  49995. if (r1 > r2) {
  49996. var temp = r2;
  49997. r2 = r1;
  49998. r1 = temp;
  49999. }
  50000. if (r1 > 0 && r1 < maxR) {
  50001. result.root = r1;
  50002. result.found = true;
  50003. return result;
  50004. }
  50005. if (r2 > 0 && r2 < maxR) {
  50006. result.root = r2;
  50007. result.found = true;
  50008. return result;
  50009. }
  50010. return result;
  50011. };
  50012. })();
  50013. var Collider = /** @class */ (function () {
  50014. function Collider() {
  50015. this._collisionPoint = BABYLON.Vector3.Zero();
  50016. this._planeIntersectionPoint = BABYLON.Vector3.Zero();
  50017. this._tempVector = BABYLON.Vector3.Zero();
  50018. this._tempVector2 = BABYLON.Vector3.Zero();
  50019. this._tempVector3 = BABYLON.Vector3.Zero();
  50020. this._tempVector4 = BABYLON.Vector3.Zero();
  50021. this._edge = BABYLON.Vector3.Zero();
  50022. this._baseToVertex = BABYLON.Vector3.Zero();
  50023. this._destinationPoint = BABYLON.Vector3.Zero();
  50024. this._slidePlaneNormal = BABYLON.Vector3.Zero();
  50025. this._displacementVector = BABYLON.Vector3.Zero();
  50026. this._radius = BABYLON.Vector3.One();
  50027. this._retry = 0;
  50028. this._basePointWorld = BABYLON.Vector3.Zero();
  50029. this._velocityWorld = BABYLON.Vector3.Zero();
  50030. this._normalizedVelocity = BABYLON.Vector3.Zero();
  50031. this._collisionMask = -1;
  50032. }
  50033. Object.defineProperty(Collider.prototype, "collisionMask", {
  50034. get: function () {
  50035. return this._collisionMask;
  50036. },
  50037. set: function (mask) {
  50038. this._collisionMask = !isNaN(mask) ? mask : -1;
  50039. },
  50040. enumerable: true,
  50041. configurable: true
  50042. });
  50043. Object.defineProperty(Collider.prototype, "slidePlaneNormal", {
  50044. /**
  50045. * Gets the plane normal used to compute the sliding response (in local space)
  50046. */
  50047. get: function () {
  50048. return this._slidePlaneNormal;
  50049. },
  50050. enumerable: true,
  50051. configurable: true
  50052. });
  50053. // Methods
  50054. Collider.prototype._initialize = function (source, dir, e) {
  50055. this._velocity = dir;
  50056. BABYLON.Vector3.NormalizeToRef(dir, this._normalizedVelocity);
  50057. this._basePoint = source;
  50058. source.multiplyToRef(this._radius, this._basePointWorld);
  50059. dir.multiplyToRef(this._radius, this._velocityWorld);
  50060. this._velocityWorldLength = this._velocityWorld.length();
  50061. this._epsilon = e;
  50062. this.collisionFound = false;
  50063. };
  50064. Collider.prototype._checkPointInTriangle = function (point, pa, pb, pc, n) {
  50065. pa.subtractToRef(point, this._tempVector);
  50066. pb.subtractToRef(point, this._tempVector2);
  50067. BABYLON.Vector3.CrossToRef(this._tempVector, this._tempVector2, this._tempVector4);
  50068. var d = BABYLON.Vector3.Dot(this._tempVector4, n);
  50069. if (d < 0)
  50070. return false;
  50071. pc.subtractToRef(point, this._tempVector3);
  50072. BABYLON.Vector3.CrossToRef(this._tempVector2, this._tempVector3, this._tempVector4);
  50073. d = BABYLON.Vector3.Dot(this._tempVector4, n);
  50074. if (d < 0)
  50075. return false;
  50076. BABYLON.Vector3.CrossToRef(this._tempVector3, this._tempVector, this._tempVector4);
  50077. d = BABYLON.Vector3.Dot(this._tempVector4, n);
  50078. return d >= 0;
  50079. };
  50080. Collider.prototype._canDoCollision = function (sphereCenter, sphereRadius, vecMin, vecMax) {
  50081. var distance = BABYLON.Vector3.Distance(this._basePointWorld, sphereCenter);
  50082. var max = Math.max(this._radius.x, this._radius.y, this._radius.z);
  50083. if (distance > this._velocityWorldLength + max + sphereRadius) {
  50084. return false;
  50085. }
  50086. if (!intersectBoxAASphere(vecMin, vecMax, this._basePointWorld, this._velocityWorldLength + max))
  50087. return false;
  50088. return true;
  50089. };
  50090. Collider.prototype._testTriangle = function (faceIndex, trianglePlaneArray, p1, p2, p3, hasMaterial) {
  50091. var t0;
  50092. var embeddedInPlane = false;
  50093. //defensive programming, actually not needed.
  50094. if (!trianglePlaneArray) {
  50095. trianglePlaneArray = [];
  50096. }
  50097. if (!trianglePlaneArray[faceIndex]) {
  50098. trianglePlaneArray[faceIndex] = new BABYLON.Plane(0, 0, 0, 0);
  50099. trianglePlaneArray[faceIndex].copyFromPoints(p1, p2, p3);
  50100. }
  50101. var trianglePlane = trianglePlaneArray[faceIndex];
  50102. if ((!hasMaterial) && !trianglePlane.isFrontFacingTo(this._normalizedVelocity, 0))
  50103. return;
  50104. var signedDistToTrianglePlane = trianglePlane.signedDistanceTo(this._basePoint);
  50105. var normalDotVelocity = BABYLON.Vector3.Dot(trianglePlane.normal, this._velocity);
  50106. if (normalDotVelocity == 0) {
  50107. if (Math.abs(signedDistToTrianglePlane) >= 1.0)
  50108. return;
  50109. embeddedInPlane = true;
  50110. t0 = 0;
  50111. }
  50112. else {
  50113. t0 = (-1.0 - signedDistToTrianglePlane) / normalDotVelocity;
  50114. var t1 = (1.0 - signedDistToTrianglePlane) / normalDotVelocity;
  50115. if (t0 > t1) {
  50116. var temp = t1;
  50117. t1 = t0;
  50118. t0 = temp;
  50119. }
  50120. if (t0 > 1.0 || t1 < 0.0)
  50121. return;
  50122. if (t0 < 0)
  50123. t0 = 0;
  50124. if (t0 > 1.0)
  50125. t0 = 1.0;
  50126. }
  50127. this._collisionPoint.copyFromFloats(0, 0, 0);
  50128. var found = false;
  50129. var t = 1.0;
  50130. if (!embeddedInPlane) {
  50131. this._basePoint.subtractToRef(trianglePlane.normal, this._planeIntersectionPoint);
  50132. this._velocity.scaleToRef(t0, this._tempVector);
  50133. this._planeIntersectionPoint.addInPlace(this._tempVector);
  50134. if (this._checkPointInTriangle(this._planeIntersectionPoint, p1, p2, p3, trianglePlane.normal)) {
  50135. found = true;
  50136. t = t0;
  50137. this._collisionPoint.copyFrom(this._planeIntersectionPoint);
  50138. }
  50139. }
  50140. if (!found) {
  50141. var velocitySquaredLength = this._velocity.lengthSquared();
  50142. var a = velocitySquaredLength;
  50143. this._basePoint.subtractToRef(p1, this._tempVector);
  50144. var b = 2.0 * (BABYLON.Vector3.Dot(this._velocity, this._tempVector));
  50145. var c = this._tempVector.lengthSquared() - 1.0;
  50146. var lowestRoot = getLowestRoot(a, b, c, t);
  50147. if (lowestRoot.found) {
  50148. t = lowestRoot.root;
  50149. found = true;
  50150. this._collisionPoint.copyFrom(p1);
  50151. }
  50152. this._basePoint.subtractToRef(p2, this._tempVector);
  50153. b = 2.0 * (BABYLON.Vector3.Dot(this._velocity, this._tempVector));
  50154. c = this._tempVector.lengthSquared() - 1.0;
  50155. lowestRoot = getLowestRoot(a, b, c, t);
  50156. if (lowestRoot.found) {
  50157. t = lowestRoot.root;
  50158. found = true;
  50159. this._collisionPoint.copyFrom(p2);
  50160. }
  50161. this._basePoint.subtractToRef(p3, this._tempVector);
  50162. b = 2.0 * (BABYLON.Vector3.Dot(this._velocity, this._tempVector));
  50163. c = this._tempVector.lengthSquared() - 1.0;
  50164. lowestRoot = getLowestRoot(a, b, c, t);
  50165. if (lowestRoot.found) {
  50166. t = lowestRoot.root;
  50167. found = true;
  50168. this._collisionPoint.copyFrom(p3);
  50169. }
  50170. p2.subtractToRef(p1, this._edge);
  50171. p1.subtractToRef(this._basePoint, this._baseToVertex);
  50172. var edgeSquaredLength = this._edge.lengthSquared();
  50173. var edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this._velocity);
  50174. var edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  50175. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  50176. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this._velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  50177. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  50178. lowestRoot = getLowestRoot(a, b, c, t);
  50179. if (lowestRoot.found) {
  50180. var f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  50181. if (f >= 0.0 && f <= 1.0) {
  50182. t = lowestRoot.root;
  50183. found = true;
  50184. this._edge.scaleInPlace(f);
  50185. p1.addToRef(this._edge, this._collisionPoint);
  50186. }
  50187. }
  50188. p3.subtractToRef(p2, this._edge);
  50189. p2.subtractToRef(this._basePoint, this._baseToVertex);
  50190. edgeSquaredLength = this._edge.lengthSquared();
  50191. edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this._velocity);
  50192. edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  50193. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  50194. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this._velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  50195. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  50196. lowestRoot = getLowestRoot(a, b, c, t);
  50197. if (lowestRoot.found) {
  50198. f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  50199. if (f >= 0.0 && f <= 1.0) {
  50200. t = lowestRoot.root;
  50201. found = true;
  50202. this._edge.scaleInPlace(f);
  50203. p2.addToRef(this._edge, this._collisionPoint);
  50204. }
  50205. }
  50206. p1.subtractToRef(p3, this._edge);
  50207. p3.subtractToRef(this._basePoint, this._baseToVertex);
  50208. edgeSquaredLength = this._edge.lengthSquared();
  50209. edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this._velocity);
  50210. edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  50211. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  50212. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this._velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  50213. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  50214. lowestRoot = getLowestRoot(a, b, c, t);
  50215. if (lowestRoot.found) {
  50216. f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  50217. if (f >= 0.0 && f <= 1.0) {
  50218. t = lowestRoot.root;
  50219. found = true;
  50220. this._edge.scaleInPlace(f);
  50221. p3.addToRef(this._edge, this._collisionPoint);
  50222. }
  50223. }
  50224. }
  50225. if (found) {
  50226. var distToCollision = t * this._velocity.length();
  50227. if (!this.collisionFound || distToCollision < this._nearestDistance) {
  50228. if (!this.intersectionPoint) {
  50229. this.intersectionPoint = this._collisionPoint.clone();
  50230. }
  50231. else {
  50232. this.intersectionPoint.copyFrom(this._collisionPoint);
  50233. }
  50234. this._nearestDistance = distToCollision;
  50235. this.collisionFound = true;
  50236. }
  50237. }
  50238. };
  50239. Collider.prototype._collide = function (trianglePlaneArray, pts, indices, indexStart, indexEnd, decal, hasMaterial) {
  50240. for (var i = indexStart; i < indexEnd; i += 3) {
  50241. var p1 = pts[indices[i] - decal];
  50242. var p2 = pts[indices[i + 1] - decal];
  50243. var p3 = pts[indices[i + 2] - decal];
  50244. this._testTriangle(i, trianglePlaneArray, p3, p2, p1, hasMaterial);
  50245. }
  50246. };
  50247. Collider.prototype._getResponse = function (pos, vel) {
  50248. pos.addToRef(vel, this._destinationPoint);
  50249. vel.scaleInPlace((this._nearestDistance / vel.length()));
  50250. this._basePoint.addToRef(vel, pos);
  50251. pos.subtractToRef(this.intersectionPoint, this._slidePlaneNormal);
  50252. this._slidePlaneNormal.normalize();
  50253. this._slidePlaneNormal.scaleToRef(this._epsilon, this._displacementVector);
  50254. pos.addInPlace(this._displacementVector);
  50255. this.intersectionPoint.addInPlace(this._displacementVector);
  50256. this._slidePlaneNormal.scaleInPlace(BABYLON.Plane.SignedDistanceToPlaneFromPositionAndNormal(this.intersectionPoint, this._slidePlaneNormal, this._destinationPoint));
  50257. this._destinationPoint.subtractInPlace(this._slidePlaneNormal);
  50258. this._destinationPoint.subtractToRef(this.intersectionPoint, vel);
  50259. };
  50260. return Collider;
  50261. }());
  50262. BABYLON.Collider = Collider;
  50263. })(BABYLON || (BABYLON = {}));
  50264. //# sourceMappingURL=babylon.collider.js.map
  50265. var BABYLON;
  50266. (function (BABYLON) {
  50267. //WebWorker code will be inserted to this variable.
  50268. BABYLON.CollisionWorker = "";
  50269. var WorkerTaskType;
  50270. (function (WorkerTaskType) {
  50271. WorkerTaskType[WorkerTaskType["INIT"] = 0] = "INIT";
  50272. WorkerTaskType[WorkerTaskType["UPDATE"] = 1] = "UPDATE";
  50273. WorkerTaskType[WorkerTaskType["COLLIDE"] = 2] = "COLLIDE";
  50274. })(WorkerTaskType = BABYLON.WorkerTaskType || (BABYLON.WorkerTaskType = {}));
  50275. var WorkerReplyType;
  50276. (function (WorkerReplyType) {
  50277. WorkerReplyType[WorkerReplyType["SUCCESS"] = 0] = "SUCCESS";
  50278. WorkerReplyType[WorkerReplyType["UNKNOWN_ERROR"] = 1] = "UNKNOWN_ERROR";
  50279. })(WorkerReplyType = BABYLON.WorkerReplyType || (BABYLON.WorkerReplyType = {}));
  50280. var CollisionCoordinatorWorker = /** @class */ (function () {
  50281. function CollisionCoordinatorWorker() {
  50282. var _this = this;
  50283. this._scaledPosition = BABYLON.Vector3.Zero();
  50284. this._scaledVelocity = BABYLON.Vector3.Zero();
  50285. this.onMeshUpdated = function (transformNode) {
  50286. _this._addUpdateMeshesList[transformNode.uniqueId] = CollisionCoordinatorWorker.SerializeMesh(transformNode);
  50287. };
  50288. this.onGeometryUpdated = function (geometry) {
  50289. _this._addUpdateGeometriesList[geometry.id] = CollisionCoordinatorWorker.SerializeGeometry(geometry);
  50290. };
  50291. this._afterRender = function () {
  50292. if (!_this._init)
  50293. return;
  50294. if (_this._toRemoveGeometryArray.length == 0 && _this._toRemoveMeshesArray.length == 0 && Object.keys(_this._addUpdateGeometriesList).length == 0 && Object.keys(_this._addUpdateMeshesList).length == 0) {
  50295. return;
  50296. }
  50297. //5 concurrent updates were sent to the web worker and were not yet processed. Abort next update.
  50298. //TODO make sure update runs as fast as possible to be able to update 60 FPS.
  50299. if (_this._runningUpdated > 4) {
  50300. return;
  50301. }
  50302. ++_this._runningUpdated;
  50303. var payload = {
  50304. updatedMeshes: _this._addUpdateMeshesList,
  50305. updatedGeometries: _this._addUpdateGeometriesList,
  50306. removedGeometries: _this._toRemoveGeometryArray,
  50307. removedMeshes: _this._toRemoveMeshesArray
  50308. };
  50309. var message = {
  50310. payload: payload,
  50311. taskType: WorkerTaskType.UPDATE
  50312. };
  50313. var serializable = [];
  50314. for (var id in payload.updatedGeometries) {
  50315. if (payload.updatedGeometries.hasOwnProperty(id)) {
  50316. //prepare transferables
  50317. serializable.push(message.payload.updatedGeometries[id].indices.buffer);
  50318. serializable.push(message.payload.updatedGeometries[id].normals.buffer);
  50319. serializable.push(message.payload.updatedGeometries[id].positions.buffer);
  50320. }
  50321. }
  50322. _this._worker.postMessage(message, serializable);
  50323. _this._addUpdateMeshesList = {};
  50324. _this._addUpdateGeometriesList = {};
  50325. _this._toRemoveGeometryArray = [];
  50326. _this._toRemoveMeshesArray = [];
  50327. };
  50328. this._onMessageFromWorker = function (e) {
  50329. var returnData = e.data;
  50330. if (returnData.error != WorkerReplyType.SUCCESS) {
  50331. //TODO what errors can be returned from the worker?
  50332. BABYLON.Tools.Warn("error returned from worker!");
  50333. return;
  50334. }
  50335. switch (returnData.taskType) {
  50336. case WorkerTaskType.INIT:
  50337. _this._init = true;
  50338. //Update the worked with ALL of the scene's current state
  50339. _this._scene.meshes.forEach(function (mesh) {
  50340. _this.onMeshAdded(mesh);
  50341. });
  50342. _this._scene.getGeometries().forEach(function (geometry) {
  50343. _this.onGeometryAdded(geometry);
  50344. });
  50345. break;
  50346. case WorkerTaskType.UPDATE:
  50347. _this._runningUpdated--;
  50348. break;
  50349. case WorkerTaskType.COLLIDE:
  50350. var returnPayload = returnData.payload;
  50351. if (!_this._collisionsCallbackArray[returnPayload.collisionId])
  50352. return;
  50353. var callback = _this._collisionsCallbackArray[returnPayload.collisionId];
  50354. if (callback) {
  50355. var mesh = _this._scene.getMeshByUniqueID(returnPayload.collidedMeshUniqueId);
  50356. if (mesh) {
  50357. callback(returnPayload.collisionId, BABYLON.Vector3.FromArray(returnPayload.newPosition), mesh);
  50358. }
  50359. }
  50360. //cleanup
  50361. _this._collisionsCallbackArray[returnPayload.collisionId] = null;
  50362. break;
  50363. }
  50364. };
  50365. this._collisionsCallbackArray = [];
  50366. this._init = false;
  50367. this._runningUpdated = 0;
  50368. this._addUpdateMeshesList = {};
  50369. this._addUpdateGeometriesList = {};
  50370. this._toRemoveGeometryArray = [];
  50371. this._toRemoveMeshesArray = [];
  50372. }
  50373. CollisionCoordinatorWorker.prototype.getNewPosition = function (position, displacement, collider, maximumRetry, excludedMesh, onNewPosition, collisionIndex) {
  50374. if (!this._init)
  50375. return;
  50376. if (this._collisionsCallbackArray[collisionIndex] || this._collisionsCallbackArray[collisionIndex + 100000])
  50377. return;
  50378. position.divideToRef(collider._radius, this._scaledPosition);
  50379. displacement.divideToRef(collider._radius, this._scaledVelocity);
  50380. this._collisionsCallbackArray[collisionIndex] = onNewPosition;
  50381. var payload = {
  50382. collider: {
  50383. position: this._scaledPosition.asArray(),
  50384. velocity: this._scaledVelocity.asArray(),
  50385. radius: collider._radius.asArray()
  50386. },
  50387. collisionId: collisionIndex,
  50388. excludedMeshUniqueId: excludedMesh ? excludedMesh.uniqueId : null,
  50389. maximumRetry: maximumRetry
  50390. };
  50391. var message = {
  50392. payload: payload,
  50393. taskType: WorkerTaskType.COLLIDE
  50394. };
  50395. this._worker.postMessage(message);
  50396. };
  50397. CollisionCoordinatorWorker.prototype.init = function (scene) {
  50398. this._scene = scene;
  50399. this._scene.registerAfterRender(this._afterRender);
  50400. var workerUrl = BABYLON.WorkerIncluded ? BABYLON.Engine.CodeRepository + "Collisions/babylon.collisionWorker.js" : URL.createObjectURL(new Blob([BABYLON.CollisionWorker], { type: 'application/javascript' }));
  50401. this._worker = new Worker(workerUrl);
  50402. this._worker.onmessage = this._onMessageFromWorker;
  50403. var message = {
  50404. payload: {},
  50405. taskType: WorkerTaskType.INIT
  50406. };
  50407. this._worker.postMessage(message);
  50408. };
  50409. CollisionCoordinatorWorker.prototype.destroy = function () {
  50410. this._scene.unregisterAfterRender(this._afterRender);
  50411. this._worker.terminate();
  50412. };
  50413. CollisionCoordinatorWorker.prototype.onMeshAdded = function (mesh) {
  50414. mesh.registerAfterWorldMatrixUpdate(this.onMeshUpdated);
  50415. this.onMeshUpdated(mesh);
  50416. };
  50417. CollisionCoordinatorWorker.prototype.onMeshRemoved = function (mesh) {
  50418. this._toRemoveMeshesArray.push(mesh.uniqueId);
  50419. };
  50420. CollisionCoordinatorWorker.prototype.onGeometryAdded = function (geometry) {
  50421. //TODO this will break if the user uses his own function. This should be an array of callbacks!
  50422. geometry.onGeometryUpdated = this.onGeometryUpdated;
  50423. this.onGeometryUpdated(geometry);
  50424. };
  50425. CollisionCoordinatorWorker.prototype.onGeometryDeleted = function (geometry) {
  50426. this._toRemoveGeometryArray.push(geometry.id);
  50427. };
  50428. CollisionCoordinatorWorker.SerializeMesh = function (mesh) {
  50429. var submeshes = [];
  50430. if (mesh.subMeshes) {
  50431. submeshes = mesh.subMeshes.map(function (sm, idx) {
  50432. var boundingInfo = sm.getBoundingInfo();
  50433. return {
  50434. position: idx,
  50435. verticesStart: sm.verticesStart,
  50436. verticesCount: sm.verticesCount,
  50437. indexStart: sm.indexStart,
  50438. indexCount: sm.indexCount,
  50439. hasMaterial: !!sm.getMaterial(),
  50440. sphereCenter: boundingInfo.boundingSphere.centerWorld.asArray(),
  50441. sphereRadius: boundingInfo.boundingSphere.radiusWorld,
  50442. boxMinimum: boundingInfo.boundingBox.minimumWorld.asArray(),
  50443. boxMaximum: boundingInfo.boundingBox.maximumWorld.asArray()
  50444. };
  50445. });
  50446. }
  50447. var geometryId = null;
  50448. if (mesh instanceof BABYLON.Mesh) {
  50449. var geometry = mesh.geometry;
  50450. geometryId = geometry ? geometry.id : null;
  50451. }
  50452. else if (mesh instanceof BABYLON.InstancedMesh) {
  50453. var geometry = mesh.sourceMesh && mesh.sourceMesh.geometry;
  50454. geometryId = geometry ? geometry.id : null;
  50455. }
  50456. var boundingInfo = mesh.getBoundingInfo();
  50457. return {
  50458. uniqueId: mesh.uniqueId,
  50459. id: mesh.id,
  50460. name: mesh.name,
  50461. geometryId: geometryId,
  50462. sphereCenter: boundingInfo.boundingSphere.centerWorld.asArray(),
  50463. sphereRadius: boundingInfo.boundingSphere.radiusWorld,
  50464. boxMinimum: boundingInfo.boundingBox.minimumWorld.asArray(),
  50465. boxMaximum: boundingInfo.boundingBox.maximumWorld.asArray(),
  50466. worldMatrixFromCache: mesh.worldMatrixFromCache.asArray(),
  50467. subMeshes: submeshes,
  50468. checkCollisions: mesh.checkCollisions
  50469. };
  50470. };
  50471. CollisionCoordinatorWorker.SerializeGeometry = function (geometry) {
  50472. return {
  50473. id: geometry.id,
  50474. positions: new Float32Array(geometry.getVerticesData(BABYLON.VertexBuffer.PositionKind) || []),
  50475. normals: new Float32Array(geometry.getVerticesData(BABYLON.VertexBuffer.NormalKind) || []),
  50476. indices: new Uint32Array(geometry.getIndices() || []),
  50477. };
  50478. };
  50479. return CollisionCoordinatorWorker;
  50480. }());
  50481. BABYLON.CollisionCoordinatorWorker = CollisionCoordinatorWorker;
  50482. var CollisionCoordinatorLegacy = /** @class */ (function () {
  50483. function CollisionCoordinatorLegacy() {
  50484. this._scaledPosition = BABYLON.Vector3.Zero();
  50485. this._scaledVelocity = BABYLON.Vector3.Zero();
  50486. this._finalPosition = BABYLON.Vector3.Zero();
  50487. }
  50488. CollisionCoordinatorLegacy.prototype.getNewPosition = function (position, displacement, collider, maximumRetry, excludedMesh, onNewPosition, collisionIndex) {
  50489. position.divideToRef(collider._radius, this._scaledPosition);
  50490. displacement.divideToRef(collider._radius, this._scaledVelocity);
  50491. collider.collidedMesh = null;
  50492. collider._retry = 0;
  50493. collider._initialVelocity = this._scaledVelocity;
  50494. collider._initialPosition = this._scaledPosition;
  50495. this._collideWithWorld(this._scaledPosition, this._scaledVelocity, collider, maximumRetry, this._finalPosition, excludedMesh);
  50496. this._finalPosition.multiplyInPlace(collider._radius);
  50497. //run the callback
  50498. onNewPosition(collisionIndex, this._finalPosition, collider.collidedMesh);
  50499. };
  50500. CollisionCoordinatorLegacy.prototype.init = function (scene) {
  50501. this._scene = scene;
  50502. };
  50503. CollisionCoordinatorLegacy.prototype.destroy = function () {
  50504. //Legacy need no destruction method.
  50505. };
  50506. //No update in legacy mode
  50507. CollisionCoordinatorLegacy.prototype.onMeshAdded = function (mesh) { };
  50508. CollisionCoordinatorLegacy.prototype.onMeshUpdated = function (mesh) { };
  50509. CollisionCoordinatorLegacy.prototype.onMeshRemoved = function (mesh) { };
  50510. CollisionCoordinatorLegacy.prototype.onGeometryAdded = function (geometry) { };
  50511. CollisionCoordinatorLegacy.prototype.onGeometryUpdated = function (geometry) { };
  50512. CollisionCoordinatorLegacy.prototype.onGeometryDeleted = function (geometry) { };
  50513. CollisionCoordinatorLegacy.prototype._collideWithWorld = function (position, velocity, collider, maximumRetry, finalPosition, excludedMesh) {
  50514. if (excludedMesh === void 0) { excludedMesh = null; }
  50515. var closeDistance = BABYLON.Engine.CollisionsEpsilon * 10.0;
  50516. if (collider._retry >= maximumRetry) {
  50517. finalPosition.copyFrom(position);
  50518. return;
  50519. }
  50520. // Check if this is a mesh else camera or -1
  50521. var collisionMask = (excludedMesh ? excludedMesh.collisionMask : collider.collisionMask);
  50522. collider._initialize(position, velocity, closeDistance);
  50523. // Check all meshes
  50524. for (var index = 0; index < this._scene.meshes.length; index++) {
  50525. var mesh = this._scene.meshes[index];
  50526. if (mesh.isEnabled() && mesh.checkCollisions && mesh.subMeshes && mesh !== excludedMesh && ((collisionMask & mesh.collisionGroup) !== 0)) {
  50527. mesh._checkCollision(collider);
  50528. }
  50529. }
  50530. if (!collider.collisionFound) {
  50531. position.addToRef(velocity, finalPosition);
  50532. return;
  50533. }
  50534. if (velocity.x !== 0 || velocity.y !== 0 || velocity.z !== 0) {
  50535. collider._getResponse(position, velocity);
  50536. }
  50537. if (velocity.length() <= closeDistance) {
  50538. finalPosition.copyFrom(position);
  50539. return;
  50540. }
  50541. collider._retry++;
  50542. this._collideWithWorld(position, velocity, collider, maximumRetry, finalPosition, excludedMesh);
  50543. };
  50544. return CollisionCoordinatorLegacy;
  50545. }());
  50546. BABYLON.CollisionCoordinatorLegacy = CollisionCoordinatorLegacy;
  50547. })(BABYLON || (BABYLON = {}));
  50548. //# sourceMappingURL=babylon.collisionCoordinator.js.map
  50549. var BABYLON;
  50550. (function (BABYLON) {
  50551. /**
  50552. * A particle represents one of the element emitted by a particle system.
  50553. * This is mainly define by its coordinates, direction, velocity and age.
  50554. */
  50555. var Particle = /** @class */ (function () {
  50556. /**
  50557. * Creates a new instance of @see Particle
  50558. * @param particleSystem the particle system the particle belongs to
  50559. */
  50560. function Particle(particleSystem) {
  50561. this.particleSystem = particleSystem;
  50562. /**
  50563. * The world position of the particle in the scene.
  50564. */
  50565. this.position = BABYLON.Vector3.Zero();
  50566. /**
  50567. * The world direction of the particle in the scene.
  50568. */
  50569. this.direction = BABYLON.Vector3.Zero();
  50570. /**
  50571. * The color of the particle.
  50572. */
  50573. this.color = new BABYLON.Color4(0, 0, 0, 0);
  50574. /**
  50575. * The color change of the particle per step.
  50576. */
  50577. this.colorStep = new BABYLON.Color4(0, 0, 0, 0);
  50578. /**
  50579. * Defines how long will the life of the particle be.
  50580. */
  50581. this.lifeTime = 1.0;
  50582. /**
  50583. * The current age of the particle.
  50584. */
  50585. this.age = 0;
  50586. /**
  50587. * The current size of the particle.
  50588. */
  50589. this.size = 0;
  50590. /**
  50591. * The current angle of the particle.
  50592. */
  50593. this.angle = 0;
  50594. /**
  50595. * Defines how fast is the angle changing.
  50596. */
  50597. this.angularSpeed = 0;
  50598. /**
  50599. * Defines the cell index used by the particle to be rendered from a sprite.
  50600. */
  50601. this.cellIndex = 0;
  50602. this._currentFrameCounter = 0;
  50603. if (!this.particleSystem.isAnimationSheetEnabled) {
  50604. return;
  50605. }
  50606. this.cellIndex = this.particleSystem.startSpriteCellID;
  50607. if (this.particleSystem.spriteCellChangeSpeed == 0) {
  50608. this.updateCellIndex = this.updateCellIndexWithSpeedCalculated;
  50609. }
  50610. else {
  50611. this.updateCellIndex = this.updateCellIndexWithCustomSpeed;
  50612. }
  50613. }
  50614. Particle.prototype.updateCellIndexWithSpeedCalculated = function (scaledUpdateSpeed) {
  50615. // (ageOffset / scaledUpdateSpeed) / available cells
  50616. var numberOfScaledUpdatesPerCell = ((this.lifeTime - this.age) / scaledUpdateSpeed) / (this.particleSystem.endSpriteCellID + 1 - this.cellIndex);
  50617. this._currentFrameCounter += scaledUpdateSpeed;
  50618. if (this._currentFrameCounter >= numberOfScaledUpdatesPerCell * scaledUpdateSpeed) {
  50619. this._currentFrameCounter = 0;
  50620. this.cellIndex++;
  50621. if (this.cellIndex > this.particleSystem.endSpriteCellID) {
  50622. this.cellIndex = this.particleSystem.endSpriteCellID;
  50623. }
  50624. }
  50625. };
  50626. Particle.prototype.updateCellIndexWithCustomSpeed = function () {
  50627. if (this._currentFrameCounter >= this.particleSystem.spriteCellChangeSpeed) {
  50628. this.cellIndex++;
  50629. this._currentFrameCounter = 0;
  50630. if (this.cellIndex > this.particleSystem.endSpriteCellID) {
  50631. if (this.particleSystem.spriteCellLoop) {
  50632. this.cellIndex = this.particleSystem.startSpriteCellID;
  50633. }
  50634. else {
  50635. this.cellIndex = this.particleSystem.endSpriteCellID;
  50636. }
  50637. }
  50638. }
  50639. else {
  50640. this._currentFrameCounter++;
  50641. }
  50642. };
  50643. /**
  50644. * Copy the properties of particle to another one.
  50645. * @param other the particle to copy the information to.
  50646. */
  50647. Particle.prototype.copyTo = function (other) {
  50648. other.position.copyFrom(this.position);
  50649. other.direction.copyFrom(this.direction);
  50650. other.color.copyFrom(this.color);
  50651. other.colorStep.copyFrom(this.colorStep);
  50652. other.lifeTime = this.lifeTime;
  50653. other.age = this.age;
  50654. other.size = this.size;
  50655. other.angle = this.angle;
  50656. other.angularSpeed = this.angularSpeed;
  50657. other.particleSystem = this.particleSystem;
  50658. other.cellIndex = this.cellIndex;
  50659. };
  50660. return Particle;
  50661. }());
  50662. BABYLON.Particle = Particle;
  50663. })(BABYLON || (BABYLON = {}));
  50664. //# sourceMappingURL=babylon.particle.js.map
  50665. var BABYLON;
  50666. (function (BABYLON) {
  50667. /**
  50668. * This represents a particle system in Babylon.
  50669. * 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.
  50670. * Particles can take different shapes while emitted like box, sphere, cone or you can write your custom function.
  50671. * @example https://doc.babylonjs.com/babylon101/particles
  50672. */
  50673. var ParticleSystem = /** @class */ (function () {
  50674. /**
  50675. * Instantiates a particle system.
  50676. * 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.
  50677. * @param name The name of the particle system
  50678. * @param capacity The max number of particles alive at the same time
  50679. * @param scene The scene the particle system belongs to
  50680. * @param customEffect a custom effect used to change the way particles are rendered by default
  50681. * @param isAnimationSheetEnabled Must be true if using a spritesheet to animate the particles texture
  50682. * @param epsilon Offset used to render the particles
  50683. */
  50684. function ParticleSystem(name, capacity, scene, customEffect, isAnimationSheetEnabled, epsilon) {
  50685. if (customEffect === void 0) { customEffect = null; }
  50686. if (isAnimationSheetEnabled === void 0) { isAnimationSheetEnabled = false; }
  50687. if (epsilon === void 0) { epsilon = 0.01; }
  50688. var _this = this;
  50689. /**
  50690. * List of animations used by the particle system.
  50691. */
  50692. this.animations = [];
  50693. /**
  50694. * The rendering group used by the Particle system to chose when to render.
  50695. */
  50696. this.renderingGroupId = 0;
  50697. /**
  50698. * The emitter represents the Mesh or position we are attaching the particle system to.
  50699. */
  50700. this.emitter = null;
  50701. /**
  50702. * The maximum number of particles to emit per frame
  50703. */
  50704. this.emitRate = 10;
  50705. /**
  50706. * If you want to launch only a few particles at once, that can be done, as well.
  50707. */
  50708. this.manualEmitCount = -1;
  50709. /**
  50710. * The overall motion speed (0.01 is default update speed, faster updates = faster animation)
  50711. */
  50712. this.updateSpeed = 0.01;
  50713. /**
  50714. * The amount of time the particle system is running (depends of the overall update speed).
  50715. */
  50716. this.targetStopDuration = 0;
  50717. /**
  50718. * Specifies whether the particle system will be disposed once it reaches the end of the animation.
  50719. */
  50720. this.disposeOnStop = false;
  50721. /**
  50722. * Minimum power of emitting particles.
  50723. */
  50724. this.minEmitPower = 1;
  50725. /**
  50726. * Maximum power of emitting particles.
  50727. */
  50728. this.maxEmitPower = 1;
  50729. /**
  50730. * Minimum life time of emitting particles.
  50731. */
  50732. this.minLifeTime = 1;
  50733. /**
  50734. * Maximum life time of emitting particles.
  50735. */
  50736. this.maxLifeTime = 1;
  50737. /**
  50738. * Minimum Size of emitting particles.
  50739. */
  50740. this.minSize = 1;
  50741. /**
  50742. * Maximum Size of emitting particles.
  50743. */
  50744. this.maxSize = 1;
  50745. /**
  50746. * Minimum angular speed of emitting particles (Z-axis rotation for each particle).
  50747. */
  50748. this.minAngularSpeed = 0;
  50749. /**
  50750. * Maximum angular speed of emitting particles (Z-axis rotation for each particle).
  50751. */
  50752. this.maxAngularSpeed = 0;
  50753. /**
  50754. * The layer mask we are rendering the particles through.
  50755. */
  50756. this.layerMask = 0x0FFFFFFF;
  50757. /**
  50758. * This can help using your own shader to render the particle system.
  50759. * The according effect will be created
  50760. */
  50761. this.customShader = null;
  50762. /**
  50763. * By default particle system starts as soon as they are created. This prevents the
  50764. * automatic start to happen and let you decide when to start emitting particles.
  50765. */
  50766. this.preventAutoStart = false;
  50767. /**
  50768. * Callback triggered when the particle animation is ending.
  50769. */
  50770. this.onAnimationEnd = null;
  50771. /**
  50772. * Blend mode use to render the particle, it can be either ParticleSystem.BLENDMODE_ONEONE or ParticleSystem.BLENDMODE_STANDARD.
  50773. */
  50774. this.blendMode = ParticleSystem.BLENDMODE_ONEONE;
  50775. /**
  50776. * Forces the particle to write their depth information to the depth buffer. This can help preventing other draw calls
  50777. * to override the particles.
  50778. */
  50779. this.forceDepthWrite = false;
  50780. /**
  50781. * You can use gravity if you want to give an orientation to your particles.
  50782. */
  50783. this.gravity = BABYLON.Vector3.Zero();
  50784. /**
  50785. * Random color of each particle after it has been emitted, between color1 and color2 vectors.
  50786. */
  50787. this.color1 = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  50788. /**
  50789. * Random color of each particle after it has been emitted, between color1 and color2 vectors.
  50790. */
  50791. this.color2 = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  50792. /**
  50793. * Color the particle will have at the end of its lifetime.
  50794. */
  50795. this.colorDead = new BABYLON.Color4(0, 0, 0, 1.0);
  50796. /**
  50797. * An optional mask to filter some colors out of the texture, or filter a part of the alpha channel.
  50798. */
  50799. this.textureMask = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  50800. /**
  50801. * If using a spritesheet (isAnimationSheetEnabled), defines if the sprite animation should loop between startSpriteCellID and endSpriteCellID or not.
  50802. */
  50803. this.spriteCellLoop = true;
  50804. /**
  50805. * If using a spritesheet (isAnimationSheetEnabled) and spriteCellLoop defines the speed of the sprite loop.
  50806. */
  50807. this.spriteCellChangeSpeed = 0;
  50808. /**
  50809. * If using a spritesheet (isAnimationSheetEnabled) and spriteCellLoop defines the first sprite cell to display.
  50810. */
  50811. this.startSpriteCellID = 0;
  50812. /**
  50813. * If using a spritesheet (isAnimationSheetEnabled) and spriteCellLoop defines the last sprite cell to display.
  50814. */
  50815. this.endSpriteCellID = 0;
  50816. /**
  50817. * If using a spritesheet (isAnimationSheetEnabled), defines the sprite cell width to use.
  50818. */
  50819. this.spriteCellWidth = 0;
  50820. /**
  50821. * If using a spritesheet (isAnimationSheetEnabled), defines the sprite cell height to use.
  50822. */
  50823. this.spriteCellHeight = 0;
  50824. /**
  50825. * An event triggered when the system is disposed.
  50826. */
  50827. this.onDisposeObservable = new BABYLON.Observable();
  50828. this._particles = new Array();
  50829. this._stockParticles = new Array();
  50830. this._newPartsExcess = 0;
  50831. this._vertexBuffers = {};
  50832. this._scaledColorStep = new BABYLON.Color4(0, 0, 0, 0);
  50833. this._colorDiff = new BABYLON.Color4(0, 0, 0, 0);
  50834. this._scaledDirection = BABYLON.Vector3.Zero();
  50835. this._scaledGravity = BABYLON.Vector3.Zero();
  50836. this._currentRenderId = -1;
  50837. this._started = false;
  50838. this._stopped = false;
  50839. this._actualFrame = 0;
  50840. this._vertexBufferSize = 11;
  50841. this._appendParticleVertexes = null;
  50842. this.id = name;
  50843. this.name = name;
  50844. this._capacity = capacity;
  50845. this._epsilon = epsilon;
  50846. this._isAnimationSheetEnabled = isAnimationSheetEnabled;
  50847. if (isAnimationSheetEnabled) {
  50848. this._vertexBufferSize = 12;
  50849. }
  50850. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  50851. this._customEffect = customEffect;
  50852. scene.particleSystems.push(this);
  50853. this._createIndexBuffer();
  50854. // 11 floats per particle (x, y, z, r, g, b, a, angle, size, offsetX, offsetY) + 1 filler
  50855. this._vertexData = new Float32Array(capacity * this._vertexBufferSize * 4);
  50856. this._vertexBuffer = new BABYLON.Buffer(scene.getEngine(), this._vertexData, true, this._vertexBufferSize);
  50857. var positions = this._vertexBuffer.createVertexBuffer(BABYLON.VertexBuffer.PositionKind, 0, 3);
  50858. var colors = this._vertexBuffer.createVertexBuffer(BABYLON.VertexBuffer.ColorKind, 3, 4);
  50859. var options = this._vertexBuffer.createVertexBuffer("options", 7, 4);
  50860. if (this._isAnimationSheetEnabled) {
  50861. var cellIndexBuffer = this._vertexBuffer.createVertexBuffer("cellIndex", 11, 1);
  50862. this._vertexBuffers["cellIndex"] = cellIndexBuffer;
  50863. }
  50864. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = positions;
  50865. this._vertexBuffers[BABYLON.VertexBuffer.ColorKind] = colors;
  50866. this._vertexBuffers["options"] = options;
  50867. // Default emitter type
  50868. this.particleEmitterType = new BABYLON.BoxParticleEmitter();
  50869. this.updateFunction = function (particles) {
  50870. for (var index = 0; index < particles.length; index++) {
  50871. var particle = particles[index];
  50872. particle.age += _this._scaledUpdateSpeed;
  50873. if (particle.age >= particle.lifeTime) {
  50874. _this.recycleParticle(particle);
  50875. index--;
  50876. continue;
  50877. }
  50878. else {
  50879. particle.colorStep.scaleToRef(_this._scaledUpdateSpeed, _this._scaledColorStep);
  50880. particle.color.addInPlace(_this._scaledColorStep);
  50881. if (particle.color.a < 0)
  50882. particle.color.a = 0;
  50883. particle.angle += particle.angularSpeed * _this._scaledUpdateSpeed;
  50884. particle.direction.scaleToRef(_this._scaledUpdateSpeed, _this._scaledDirection);
  50885. particle.position.addInPlace(_this._scaledDirection);
  50886. _this.gravity.scaleToRef(_this._scaledUpdateSpeed, _this._scaledGravity);
  50887. particle.direction.addInPlace(_this._scaledGravity);
  50888. if (_this._isAnimationSheetEnabled) {
  50889. particle.updateCellIndex(_this._scaledUpdateSpeed);
  50890. }
  50891. }
  50892. }
  50893. };
  50894. }
  50895. Object.defineProperty(ParticleSystem.prototype, "direction1", {
  50896. /**
  50897. * Random direction of each particle after it has been emitted, between direction1 and direction2 vectors.
  50898. * This only works when particleEmitterTyps is a BoxParticleEmitter
  50899. */
  50900. get: function () {
  50901. if (this.particleEmitterType.direction1) {
  50902. return this.particleEmitterType.direction1;
  50903. }
  50904. return BABYLON.Vector3.Zero();
  50905. },
  50906. set: function (value) {
  50907. if (this.particleEmitterType.direction1) {
  50908. this.particleEmitterType.direction1 = value;
  50909. }
  50910. },
  50911. enumerable: true,
  50912. configurable: true
  50913. });
  50914. Object.defineProperty(ParticleSystem.prototype, "direction2", {
  50915. /**
  50916. * Random direction of each particle after it has been emitted, between direction1 and direction2 vectors.
  50917. * This only works when particleEmitterTyps is a BoxParticleEmitter
  50918. */
  50919. get: function () {
  50920. if (this.particleEmitterType.direction2) {
  50921. return this.particleEmitterType.direction2;
  50922. }
  50923. return BABYLON.Vector3.Zero();
  50924. },
  50925. set: function (value) {
  50926. if (this.particleEmitterType.direction2) {
  50927. this.particleEmitterType.direction2 = value;
  50928. }
  50929. },
  50930. enumerable: true,
  50931. configurable: true
  50932. });
  50933. Object.defineProperty(ParticleSystem.prototype, "minEmitBox", {
  50934. /**
  50935. * 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.
  50936. * This only works when particleEmitterTyps is a BoxParticleEmitter
  50937. */
  50938. get: function () {
  50939. if (this.particleEmitterType.minEmitBox) {
  50940. return this.particleEmitterType.minEmitBox;
  50941. }
  50942. return BABYLON.Vector3.Zero();
  50943. },
  50944. set: function (value) {
  50945. if (this.particleEmitterType.minEmitBox) {
  50946. this.particleEmitterType.minEmitBox = value;
  50947. }
  50948. },
  50949. enumerable: true,
  50950. configurable: true
  50951. });
  50952. Object.defineProperty(ParticleSystem.prototype, "maxEmitBox", {
  50953. /**
  50954. * 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.
  50955. * This only works when particleEmitterTyps is a BoxParticleEmitter
  50956. */
  50957. get: function () {
  50958. if (this.particleEmitterType.maxEmitBox) {
  50959. return this.particleEmitterType.maxEmitBox;
  50960. }
  50961. return BABYLON.Vector3.Zero();
  50962. },
  50963. set: function (value) {
  50964. if (this.particleEmitterType.maxEmitBox) {
  50965. this.particleEmitterType.maxEmitBox = value;
  50966. }
  50967. },
  50968. enumerable: true,
  50969. configurable: true
  50970. });
  50971. Object.defineProperty(ParticleSystem.prototype, "onDispose", {
  50972. /**
  50973. * Sets a callback that will be triggered when the system is disposed.
  50974. */
  50975. set: function (callback) {
  50976. if (this._onDisposeObserver) {
  50977. this.onDisposeObservable.remove(this._onDisposeObserver);
  50978. }
  50979. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  50980. },
  50981. enumerable: true,
  50982. configurable: true
  50983. });
  50984. Object.defineProperty(ParticleSystem.prototype, "isAnimationSheetEnabled", {
  50985. /**
  50986. * Gets wether an animation sprite sheet is enabled or not on the particle system.
  50987. */
  50988. get: function () {
  50989. return this._isAnimationSheetEnabled;
  50990. },
  50991. enumerable: true,
  50992. configurable: true
  50993. });
  50994. Object.defineProperty(ParticleSystem.prototype, "particles", {
  50995. /**
  50996. * Gets the current list of active particles
  50997. */
  50998. get: function () {
  50999. return this._particles;
  51000. },
  51001. enumerable: true,
  51002. configurable: true
  51003. });
  51004. /**
  51005. * Returns the string "ParticleSystem"
  51006. * @returns a string containing the class name
  51007. */
  51008. ParticleSystem.prototype.getClassName = function () {
  51009. return "ParticleSystem";
  51010. };
  51011. ParticleSystem.prototype._createIndexBuffer = function () {
  51012. var indices = [];
  51013. var index = 0;
  51014. for (var count = 0; count < this._capacity; count++) {
  51015. indices.push(index);
  51016. indices.push(index + 1);
  51017. indices.push(index + 2);
  51018. indices.push(index);
  51019. indices.push(index + 2);
  51020. indices.push(index + 3);
  51021. index += 4;
  51022. }
  51023. this._indexBuffer = this._scene.getEngine().createIndexBuffer(indices);
  51024. };
  51025. /**
  51026. * "Recycles" one of the particle by copying it back to the "stock" of particles and removing it from the active list.
  51027. * Its lifetime will start back at 0.
  51028. * @param particle The particle to recycle
  51029. */
  51030. ParticleSystem.prototype.recycleParticle = function (particle) {
  51031. var lastParticle = this._particles.pop();
  51032. if (lastParticle !== particle) {
  51033. lastParticle.copyTo(particle);
  51034. this._stockParticles.push(lastParticle);
  51035. }
  51036. };
  51037. /**
  51038. * Gets the maximum number of particles active at the same time.
  51039. * @returns The max number of active particles.
  51040. */
  51041. ParticleSystem.prototype.getCapacity = function () {
  51042. return this._capacity;
  51043. };
  51044. /**
  51045. * Gets Wether there are still active particles in the system.
  51046. * @returns True if it is alive, otherwise false.
  51047. */
  51048. ParticleSystem.prototype.isAlive = function () {
  51049. return this._alive;
  51050. };
  51051. /**
  51052. * Gets Wether the system has been started.
  51053. * @returns True if it has been started, otherwise false.
  51054. */
  51055. ParticleSystem.prototype.isStarted = function () {
  51056. return this._started;
  51057. };
  51058. /**
  51059. * Starts the particle system and begins to emit.
  51060. */
  51061. ParticleSystem.prototype.start = function () {
  51062. this._started = true;
  51063. this._stopped = false;
  51064. this._actualFrame = 0;
  51065. };
  51066. /**
  51067. * Stops the particle system.
  51068. */
  51069. ParticleSystem.prototype.stop = function () {
  51070. this._stopped = true;
  51071. };
  51072. /**
  51073. * Remove all active particles
  51074. */
  51075. ParticleSystem.prototype.reset = function () {
  51076. this._stockParticles = [];
  51077. this._particles = [];
  51078. };
  51079. /**
  51080. * @ignore (for internal use only)
  51081. */
  51082. ParticleSystem.prototype._appendParticleVertex = function (index, particle, offsetX, offsetY) {
  51083. var offset = index * this._vertexBufferSize;
  51084. this._vertexData[offset] = particle.position.x;
  51085. this._vertexData[offset + 1] = particle.position.y;
  51086. this._vertexData[offset + 2] = particle.position.z;
  51087. this._vertexData[offset + 3] = particle.color.r;
  51088. this._vertexData[offset + 4] = particle.color.g;
  51089. this._vertexData[offset + 5] = particle.color.b;
  51090. this._vertexData[offset + 6] = particle.color.a;
  51091. this._vertexData[offset + 7] = particle.angle;
  51092. this._vertexData[offset + 8] = particle.size;
  51093. this._vertexData[offset + 9] = offsetX;
  51094. this._vertexData[offset + 10] = offsetY;
  51095. };
  51096. /**
  51097. * @ignore (for internal use only)
  51098. */
  51099. ParticleSystem.prototype._appendParticleVertexWithAnimation = function (index, particle, offsetX, offsetY) {
  51100. if (offsetX === 0)
  51101. offsetX = this._epsilon;
  51102. else if (offsetX === 1)
  51103. offsetX = 1 - this._epsilon;
  51104. if (offsetY === 0)
  51105. offsetY = this._epsilon;
  51106. else if (offsetY === 1)
  51107. offsetY = 1 - this._epsilon;
  51108. var offset = index * this._vertexBufferSize;
  51109. this._vertexData[offset] = particle.position.x;
  51110. this._vertexData[offset + 1] = particle.position.y;
  51111. this._vertexData[offset + 2] = particle.position.z;
  51112. this._vertexData[offset + 3] = particle.color.r;
  51113. this._vertexData[offset + 4] = particle.color.g;
  51114. this._vertexData[offset + 5] = particle.color.b;
  51115. this._vertexData[offset + 6] = particle.color.a;
  51116. this._vertexData[offset + 7] = particle.angle;
  51117. this._vertexData[offset + 8] = particle.size;
  51118. this._vertexData[offset + 9] = offsetX;
  51119. this._vertexData[offset + 10] = offsetY;
  51120. this._vertexData[offset + 11] = particle.cellIndex;
  51121. };
  51122. ParticleSystem.prototype._update = function (newParticles) {
  51123. // Update current
  51124. this._alive = this._particles.length > 0;
  51125. this.updateFunction(this._particles);
  51126. // Add new ones
  51127. var worldMatrix;
  51128. if (this.emitter.position) {
  51129. var emitterMesh = this.emitter;
  51130. worldMatrix = emitterMesh.getWorldMatrix();
  51131. }
  51132. else {
  51133. var emitterPosition = this.emitter;
  51134. worldMatrix = BABYLON.Matrix.Translation(emitterPosition.x, emitterPosition.y, emitterPosition.z);
  51135. }
  51136. var particle;
  51137. for (var index = 0; index < newParticles; index++) {
  51138. if (this._particles.length === this._capacity) {
  51139. break;
  51140. }
  51141. if (this._stockParticles.length !== 0) {
  51142. particle = this._stockParticles.pop();
  51143. particle.age = 0;
  51144. particle.cellIndex = this.startSpriteCellID;
  51145. }
  51146. else {
  51147. particle = new BABYLON.Particle(this);
  51148. }
  51149. this._particles.push(particle);
  51150. var emitPower = BABYLON.Scalar.RandomRange(this.minEmitPower, this.maxEmitPower);
  51151. if (this.startPositionFunction) {
  51152. this.startPositionFunction(worldMatrix, particle.position, particle);
  51153. }
  51154. else {
  51155. this.particleEmitterType.startPositionFunction(worldMatrix, particle.position, particle);
  51156. }
  51157. if (this.startDirectionFunction) {
  51158. this.startDirectionFunction(emitPower, worldMatrix, particle.direction, particle);
  51159. }
  51160. else {
  51161. this.particleEmitterType.startDirectionFunction(emitPower, worldMatrix, particle.direction, particle);
  51162. }
  51163. particle.lifeTime = BABYLON.Scalar.RandomRange(this.minLifeTime, this.maxLifeTime);
  51164. particle.size = BABYLON.Scalar.RandomRange(this.minSize, this.maxSize);
  51165. particle.angularSpeed = BABYLON.Scalar.RandomRange(this.minAngularSpeed, this.maxAngularSpeed);
  51166. var step = BABYLON.Scalar.RandomRange(0, 1.0);
  51167. BABYLON.Color4.LerpToRef(this.color1, this.color2, step, particle.color);
  51168. this.colorDead.subtractToRef(particle.color, this._colorDiff);
  51169. this._colorDiff.scaleToRef(1.0 / particle.lifeTime, particle.colorStep);
  51170. }
  51171. };
  51172. ParticleSystem.prototype._getEffect = function () {
  51173. if (this._customEffect) {
  51174. return this._customEffect;
  51175. }
  51176. ;
  51177. var defines = [];
  51178. if (this._scene.clipPlane) {
  51179. defines.push("#define CLIPPLANE");
  51180. }
  51181. if (this._isAnimationSheetEnabled) {
  51182. defines.push("#define ANIMATESHEET");
  51183. }
  51184. // Effect
  51185. var join = defines.join("\n");
  51186. if (this._cachedDefines !== join) {
  51187. this._cachedDefines = join;
  51188. var attributesNamesOrOptions;
  51189. var effectCreationOption;
  51190. if (this._isAnimationSheetEnabled) {
  51191. attributesNamesOrOptions = [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.ColorKind, "options", "cellIndex"];
  51192. effectCreationOption = ["invView", "view", "projection", "particlesInfos", "vClipPlane", "textureMask"];
  51193. }
  51194. else {
  51195. attributesNamesOrOptions = [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.ColorKind, "options"];
  51196. effectCreationOption = ["invView", "view", "projection", "vClipPlane", "textureMask"];
  51197. }
  51198. this._effect = this._scene.getEngine().createEffect("particles", attributesNamesOrOptions, effectCreationOption, ["diffuseSampler"], join);
  51199. }
  51200. return this._effect;
  51201. };
  51202. /**
  51203. * Animates the particle system for the current frame by emitting new particles and or animating the living ones.
  51204. */
  51205. ParticleSystem.prototype.animate = function () {
  51206. if (!this._started)
  51207. return;
  51208. var effect = this._getEffect();
  51209. // Check
  51210. if (!this.emitter || !effect.isReady() || !this.particleTexture || !this.particleTexture.isReady())
  51211. return;
  51212. if (this._currentRenderId === this._scene.getRenderId()) {
  51213. return;
  51214. }
  51215. this._currentRenderId = this._scene.getRenderId();
  51216. this._scaledUpdateSpeed = this.updateSpeed * this._scene.getAnimationRatio();
  51217. // determine the number of particles we need to create
  51218. var newParticles;
  51219. if (this.manualEmitCount > -1) {
  51220. newParticles = this.manualEmitCount;
  51221. this._newPartsExcess = 0;
  51222. this.manualEmitCount = 0;
  51223. }
  51224. else {
  51225. newParticles = ((this.emitRate * this._scaledUpdateSpeed) >> 0);
  51226. this._newPartsExcess += this.emitRate * this._scaledUpdateSpeed - newParticles;
  51227. }
  51228. if (this._newPartsExcess > 1.0) {
  51229. newParticles += this._newPartsExcess >> 0;
  51230. this._newPartsExcess -= this._newPartsExcess >> 0;
  51231. }
  51232. this._alive = false;
  51233. if (!this._stopped) {
  51234. this._actualFrame += this._scaledUpdateSpeed;
  51235. if (this.targetStopDuration && this._actualFrame >= this.targetStopDuration)
  51236. this.stop();
  51237. }
  51238. else {
  51239. newParticles = 0;
  51240. }
  51241. this._update(newParticles);
  51242. // Stopped?
  51243. if (this._stopped) {
  51244. if (!this._alive) {
  51245. this._started = false;
  51246. if (this.onAnimationEnd) {
  51247. this.onAnimationEnd();
  51248. }
  51249. if (this.disposeOnStop) {
  51250. this._scene._toBeDisposed.push(this);
  51251. }
  51252. }
  51253. }
  51254. // Animation sheet
  51255. if (this._isAnimationSheetEnabled) {
  51256. this._appendParticleVertexes = this._appenedParticleVertexesWithSheet;
  51257. }
  51258. else {
  51259. this._appendParticleVertexes = this._appenedParticleVertexesNoSheet;
  51260. }
  51261. // Update VBO
  51262. var offset = 0;
  51263. for (var index = 0; index < this._particles.length; index++) {
  51264. var particle = this._particles[index];
  51265. this._appendParticleVertexes(offset, particle);
  51266. offset += 4;
  51267. }
  51268. if (this._vertexBuffer) {
  51269. this._vertexBuffer.update(this._vertexData);
  51270. }
  51271. };
  51272. ParticleSystem.prototype._appenedParticleVertexesWithSheet = function (offset, particle) {
  51273. this._appendParticleVertexWithAnimation(offset++, particle, 0, 0);
  51274. this._appendParticleVertexWithAnimation(offset++, particle, 1, 0);
  51275. this._appendParticleVertexWithAnimation(offset++, particle, 1, 1);
  51276. this._appendParticleVertexWithAnimation(offset++, particle, 0, 1);
  51277. };
  51278. ParticleSystem.prototype._appenedParticleVertexesNoSheet = function (offset, particle) {
  51279. this._appendParticleVertex(offset++, particle, 0, 0);
  51280. this._appendParticleVertex(offset++, particle, 1, 0);
  51281. this._appendParticleVertex(offset++, particle, 1, 1);
  51282. this._appendParticleVertex(offset++, particle, 0, 1);
  51283. };
  51284. /**
  51285. * Rebuilds the particle system.
  51286. */
  51287. ParticleSystem.prototype.rebuild = function () {
  51288. this._createIndexBuffer();
  51289. if (this._vertexBuffer) {
  51290. this._vertexBuffer._rebuild();
  51291. }
  51292. };
  51293. /**
  51294. * Renders the particle system in its current state.
  51295. * @returns the current number of particles
  51296. */
  51297. ParticleSystem.prototype.render = function () {
  51298. var effect = this._getEffect();
  51299. // Check
  51300. if (!this.emitter || !effect.isReady() || !this.particleTexture || !this.particleTexture.isReady() || !this._particles.length) {
  51301. return 0;
  51302. }
  51303. var engine = this._scene.getEngine();
  51304. // Render
  51305. engine.enableEffect(effect);
  51306. engine.setState(false);
  51307. var viewMatrix = this._scene.getViewMatrix();
  51308. effect.setTexture("diffuseSampler", this.particleTexture);
  51309. effect.setMatrix("view", viewMatrix);
  51310. effect.setMatrix("projection", this._scene.getProjectionMatrix());
  51311. if (this._isAnimationSheetEnabled) {
  51312. var baseSize = this.particleTexture.getBaseSize();
  51313. effect.setFloat3("particlesInfos", this.spriteCellWidth / baseSize.width, this.spriteCellHeight / baseSize.height, baseSize.width / this.spriteCellWidth);
  51314. }
  51315. effect.setFloat4("textureMask", this.textureMask.r, this.textureMask.g, this.textureMask.b, this.textureMask.a);
  51316. if (this._scene.clipPlane) {
  51317. var clipPlane = this._scene.clipPlane;
  51318. var invView = viewMatrix.clone();
  51319. invView.invert();
  51320. effect.setMatrix("invView", invView);
  51321. effect.setFloat4("vClipPlane", clipPlane.normal.x, clipPlane.normal.y, clipPlane.normal.z, clipPlane.d);
  51322. }
  51323. // VBOs
  51324. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  51325. // Draw order
  51326. if (this.blendMode === ParticleSystem.BLENDMODE_ONEONE) {
  51327. engine.setAlphaMode(BABYLON.Engine.ALPHA_ONEONE);
  51328. }
  51329. else {
  51330. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  51331. }
  51332. if (this.forceDepthWrite) {
  51333. engine.setDepthWrite(true);
  51334. }
  51335. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, this._particles.length * 6);
  51336. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  51337. return this._particles.length;
  51338. };
  51339. /**
  51340. * Disposes the particle system and free the associated resources
  51341. * @param disposeTexture defines if the particule texture must be disposed as well (true by default)
  51342. */
  51343. ParticleSystem.prototype.dispose = function (disposeTexture) {
  51344. if (disposeTexture === void 0) { disposeTexture = true; }
  51345. if (this._vertexBuffer) {
  51346. this._vertexBuffer.dispose();
  51347. this._vertexBuffer = null;
  51348. }
  51349. if (this._indexBuffer) {
  51350. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  51351. this._indexBuffer = null;
  51352. }
  51353. if (disposeTexture && this.particleTexture) {
  51354. this.particleTexture.dispose();
  51355. this.particleTexture = null;
  51356. }
  51357. // Remove from scene
  51358. var index = this._scene.particleSystems.indexOf(this);
  51359. if (index > -1) {
  51360. this._scene.particleSystems.splice(index, 1);
  51361. }
  51362. // Callback
  51363. this.onDisposeObservable.notifyObservers(this);
  51364. this.onDisposeObservable.clear();
  51365. };
  51366. /**
  51367. * Creates a Sphere Emitter for the particle system. (emits along the sphere radius)
  51368. * @param radius The radius of the sphere to emit from
  51369. * @returns the emitter
  51370. */
  51371. ParticleSystem.prototype.createSphereEmitter = function (radius) {
  51372. if (radius === void 0) { radius = 1; }
  51373. var particleEmitter = new BABYLON.SphereParticleEmitter(radius);
  51374. this.particleEmitterType = particleEmitter;
  51375. return particleEmitter;
  51376. };
  51377. /**
  51378. * Creates a Directed Sphere Emitter for the particle system. (emits between direction1 and direction2)
  51379. * @param radius The radius of the sphere to emit from
  51380. * @param direction1 Particles are emitted between the direction1 and direction2 from within the sphere
  51381. * @param direction2 Particles are emitted between the direction1 and direction2 from within the sphere
  51382. * @returns the emitter
  51383. */
  51384. ParticleSystem.prototype.createDirectedSphereEmitter = function (radius, direction1, direction2) {
  51385. if (radius === void 0) { radius = 1; }
  51386. if (direction1 === void 0) { direction1 = new BABYLON.Vector3(0, 1.0, 0); }
  51387. if (direction2 === void 0) { direction2 = new BABYLON.Vector3(0, 1.0, 0); }
  51388. var particleEmitter = new BABYLON.SphereDirectedParticleEmitter(radius, direction1, direction2);
  51389. this.particleEmitterType = particleEmitter;
  51390. return particleEmitter;
  51391. };
  51392. /**
  51393. * Creates a Cone Emitter for the particle system. (emits from the cone to the particle position)
  51394. * @param radius The radius of the cone to emit from
  51395. * @param angle The base angle of the cone
  51396. * @returns the emitter
  51397. */
  51398. ParticleSystem.prototype.createConeEmitter = function (radius, angle) {
  51399. if (radius === void 0) { radius = 1; }
  51400. if (angle === void 0) { angle = Math.PI / 4; }
  51401. var particleEmitter = new BABYLON.ConeParticleEmitter(radius, angle);
  51402. this.particleEmitterType = particleEmitter;
  51403. return particleEmitter;
  51404. };
  51405. // 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.
  51406. /**
  51407. * Creates a Box Emitter for the particle system. (emits between direction1 and direction2 from withing the box defined by minEmitBox and maxEmitBox)
  51408. * @param direction1 Particles are emitted between the direction1 and direction2 from within the box
  51409. * @param direction2 Particles are emitted between the direction1 and direction2 from within the box
  51410. * @param minEmitBox Particles are emitted from the box between minEmitBox and maxEmitBox
  51411. * @param maxEmitBox Particles are emitted from the box between minEmitBox and maxEmitBox
  51412. * @returns the emitter
  51413. */
  51414. ParticleSystem.prototype.createBoxEmitter = function (direction1, direction2, minEmitBox, maxEmitBox) {
  51415. var particleEmitter = new BABYLON.BoxParticleEmitter();
  51416. this.direction1 = direction1;
  51417. this.direction2 = direction2;
  51418. this.minEmitBox = minEmitBox;
  51419. this.maxEmitBox = maxEmitBox;
  51420. this.particleEmitterType = particleEmitter;
  51421. return particleEmitter;
  51422. };
  51423. /**
  51424. * Clones the particle system.
  51425. * @param name The name of the cloned object
  51426. * @param newEmitter The new emitter to use
  51427. * @returns the cloned particle system
  51428. */
  51429. ParticleSystem.prototype.clone = function (name, newEmitter) {
  51430. var custom = null;
  51431. var program = null;
  51432. if (this.customShader != null) {
  51433. program = this.customShader;
  51434. var defines = (program.shaderOptions.defines.length > 0) ? program.shaderOptions.defines.join("\n") : "";
  51435. custom = this._scene.getEngine().createEffectForParticles(program.shaderPath.fragmentElement, program.shaderOptions.uniforms, program.shaderOptions.samplers, defines);
  51436. }
  51437. var result = new ParticleSystem(name, this._capacity, this._scene, custom);
  51438. result.customShader = program;
  51439. BABYLON.Tools.DeepCopy(this, result, ["particles", "customShader"]);
  51440. if (newEmitter === undefined) {
  51441. newEmitter = this.emitter;
  51442. }
  51443. result.emitter = newEmitter;
  51444. if (this.particleTexture) {
  51445. result.particleTexture = new BABYLON.Texture(this.particleTexture.url, this._scene);
  51446. }
  51447. if (!this.preventAutoStart) {
  51448. result.start();
  51449. }
  51450. return result;
  51451. };
  51452. /**
  51453. * Serializes the particle system to a JSON object.
  51454. * @returns the JSON object
  51455. */
  51456. ParticleSystem.prototype.serialize = function () {
  51457. var serializationObject = {};
  51458. serializationObject.name = this.name;
  51459. serializationObject.id = this.id;
  51460. // Emitter
  51461. if (this.emitter.position) {
  51462. var emitterMesh = this.emitter;
  51463. serializationObject.emitterId = emitterMesh.id;
  51464. }
  51465. else {
  51466. var emitterPosition = this.emitter;
  51467. serializationObject.emitter = emitterPosition.asArray();
  51468. }
  51469. serializationObject.capacity = this.getCapacity();
  51470. if (this.particleTexture) {
  51471. serializationObject.textureName = this.particleTexture.name;
  51472. }
  51473. // Animations
  51474. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  51475. // Particle system
  51476. serializationObject.minAngularSpeed = this.minAngularSpeed;
  51477. serializationObject.maxAngularSpeed = this.maxAngularSpeed;
  51478. serializationObject.minSize = this.minSize;
  51479. serializationObject.maxSize = this.maxSize;
  51480. serializationObject.minEmitPower = this.minEmitPower;
  51481. serializationObject.maxEmitPower = this.maxEmitPower;
  51482. serializationObject.minLifeTime = this.minLifeTime;
  51483. serializationObject.maxLifeTime = this.maxLifeTime;
  51484. serializationObject.emitRate = this.emitRate;
  51485. serializationObject.minEmitBox = this.minEmitBox.asArray();
  51486. serializationObject.maxEmitBox = this.maxEmitBox.asArray();
  51487. serializationObject.gravity = this.gravity.asArray();
  51488. serializationObject.direction1 = this.direction1.asArray();
  51489. serializationObject.direction2 = this.direction2.asArray();
  51490. serializationObject.color1 = this.color1.asArray();
  51491. serializationObject.color2 = this.color2.asArray();
  51492. serializationObject.colorDead = this.colorDead.asArray();
  51493. serializationObject.updateSpeed = this.updateSpeed;
  51494. serializationObject.targetStopDuration = this.targetStopDuration;
  51495. serializationObject.textureMask = this.textureMask.asArray();
  51496. serializationObject.blendMode = this.blendMode;
  51497. serializationObject.customShader = this.customShader;
  51498. serializationObject.preventAutoStart = this.preventAutoStart;
  51499. serializationObject.startSpriteCellID = this.startSpriteCellID;
  51500. serializationObject.endSpriteCellID = this.endSpriteCellID;
  51501. serializationObject.spriteCellLoop = this.spriteCellLoop;
  51502. serializationObject.spriteCellChangeSpeed = this.spriteCellChangeSpeed;
  51503. serializationObject.spriteCellWidth = this.spriteCellWidth;
  51504. serializationObject.spriteCellHeight = this.spriteCellHeight;
  51505. serializationObject.isAnimationSheetEnabled = this._isAnimationSheetEnabled;
  51506. // Emitter
  51507. if (this.particleEmitterType) {
  51508. serializationObject.particleEmitterType = this.particleEmitterType.serialize();
  51509. }
  51510. return serializationObject;
  51511. };
  51512. /**
  51513. * Parses a JSON object to create a particle system.
  51514. * @param parsedParticleSystem The JSON object to parse
  51515. * @param scene The scene to create the particle system in
  51516. * @param rootUrl The root url to use to load external dependencies like texture
  51517. * @returns the Parsed particle system
  51518. */
  51519. ParticleSystem.Parse = function (parsedParticleSystem, scene, rootUrl) {
  51520. var name = parsedParticleSystem.name;
  51521. var custom = null;
  51522. var program = null;
  51523. if (parsedParticleSystem.customShader) {
  51524. program = parsedParticleSystem.customShader;
  51525. var defines = (program.shaderOptions.defines.length > 0) ? program.shaderOptions.defines.join("\n") : "";
  51526. custom = scene.getEngine().createEffectForParticles(program.shaderPath.fragmentElement, program.shaderOptions.uniforms, program.shaderOptions.samplers, defines);
  51527. }
  51528. var particleSystem = new ParticleSystem(name, parsedParticleSystem.capacity, scene, custom, parsedParticleSystem.isAnimationSheetEnabled);
  51529. particleSystem.customShader = program;
  51530. if (parsedParticleSystem.id) {
  51531. particleSystem.id = parsedParticleSystem.id;
  51532. }
  51533. // Auto start
  51534. if (parsedParticleSystem.preventAutoStart) {
  51535. particleSystem.preventAutoStart = parsedParticleSystem.preventAutoStart;
  51536. }
  51537. // Texture
  51538. if (parsedParticleSystem.textureName) {
  51539. particleSystem.particleTexture = new BABYLON.Texture(rootUrl + parsedParticleSystem.textureName, scene);
  51540. particleSystem.particleTexture.name = parsedParticleSystem.textureName;
  51541. }
  51542. // Emitter
  51543. if (parsedParticleSystem.emitterId) {
  51544. particleSystem.emitter = scene.getLastMeshByID(parsedParticleSystem.emitterId);
  51545. }
  51546. else {
  51547. particleSystem.emitter = BABYLON.Vector3.FromArray(parsedParticleSystem.emitter);
  51548. }
  51549. // Animations
  51550. if (parsedParticleSystem.animations) {
  51551. for (var animationIndex = 0; animationIndex < parsedParticleSystem.animations.length; animationIndex++) {
  51552. var parsedAnimation = parsedParticleSystem.animations[animationIndex];
  51553. particleSystem.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  51554. }
  51555. }
  51556. if (parsedParticleSystem.autoAnimate) {
  51557. scene.beginAnimation(particleSystem, parsedParticleSystem.autoAnimateFrom, parsedParticleSystem.autoAnimateTo, parsedParticleSystem.autoAnimateLoop, parsedParticleSystem.autoAnimateSpeed || 1.0);
  51558. }
  51559. // Particle system
  51560. particleSystem.minAngularSpeed = parsedParticleSystem.minAngularSpeed;
  51561. particleSystem.maxAngularSpeed = parsedParticleSystem.maxAngularSpeed;
  51562. particleSystem.minSize = parsedParticleSystem.minSize;
  51563. particleSystem.maxSize = parsedParticleSystem.maxSize;
  51564. particleSystem.minLifeTime = parsedParticleSystem.minLifeTime;
  51565. particleSystem.maxLifeTime = parsedParticleSystem.maxLifeTime;
  51566. particleSystem.minEmitPower = parsedParticleSystem.minEmitPower;
  51567. particleSystem.maxEmitPower = parsedParticleSystem.maxEmitPower;
  51568. particleSystem.emitRate = parsedParticleSystem.emitRate;
  51569. particleSystem.minEmitBox = BABYLON.Vector3.FromArray(parsedParticleSystem.minEmitBox);
  51570. particleSystem.maxEmitBox = BABYLON.Vector3.FromArray(parsedParticleSystem.maxEmitBox);
  51571. particleSystem.gravity = BABYLON.Vector3.FromArray(parsedParticleSystem.gravity);
  51572. particleSystem.direction1 = BABYLON.Vector3.FromArray(parsedParticleSystem.direction1);
  51573. particleSystem.direction2 = BABYLON.Vector3.FromArray(parsedParticleSystem.direction2);
  51574. particleSystem.color1 = BABYLON.Color4.FromArray(parsedParticleSystem.color1);
  51575. particleSystem.color2 = BABYLON.Color4.FromArray(parsedParticleSystem.color2);
  51576. particleSystem.colorDead = BABYLON.Color4.FromArray(parsedParticleSystem.colorDead);
  51577. particleSystem.updateSpeed = parsedParticleSystem.updateSpeed;
  51578. particleSystem.targetStopDuration = parsedParticleSystem.targetStopDuration;
  51579. particleSystem.textureMask = BABYLON.Color4.FromArray(parsedParticleSystem.textureMask);
  51580. particleSystem.blendMode = parsedParticleSystem.blendMode;
  51581. particleSystem.startSpriteCellID = parsedParticleSystem.startSpriteCellID;
  51582. particleSystem.endSpriteCellID = parsedParticleSystem.endSpriteCellID;
  51583. particleSystem.spriteCellLoop = parsedParticleSystem.spriteCellLoop;
  51584. particleSystem.spriteCellChangeSpeed = parsedParticleSystem.spriteCellChangeSpeed;
  51585. particleSystem.spriteCellWidth = parsedParticleSystem.spriteCellWidth;
  51586. particleSystem.spriteCellHeight = parsedParticleSystem.spriteCellHeight;
  51587. if (!particleSystem.preventAutoStart) {
  51588. particleSystem.start();
  51589. }
  51590. return particleSystem;
  51591. };
  51592. /**
  51593. * Source color is added to the destination color without alpha affecting the result.
  51594. */
  51595. ParticleSystem.BLENDMODE_ONEONE = 0;
  51596. /**
  51597. * Blend current color and particle color using particle’s alpha.
  51598. */
  51599. ParticleSystem.BLENDMODE_STANDARD = 1;
  51600. return ParticleSystem;
  51601. }());
  51602. BABYLON.ParticleSystem = ParticleSystem;
  51603. })(BABYLON || (BABYLON = {}));
  51604. //# sourceMappingURL=babylon.particleSystem.js.map
  51605. //# sourceMappingURL=babylon.IParticleEmitterType.js.map
  51606. var BABYLON;
  51607. (function (BABYLON) {
  51608. /**
  51609. * Particle emitter emitting particles from the inside of a box.
  51610. * It emits the particles randomly between 2 given directions.
  51611. */
  51612. var BoxParticleEmitter = /** @class */ (function () {
  51613. /**
  51614. * Creates a new instance of @see BoxParticleEmitter
  51615. */
  51616. function BoxParticleEmitter() {
  51617. /**
  51618. * Random direction of each particle after it has been emitted, between direction1 and direction2 vectors.
  51619. */
  51620. this.direction1 = new BABYLON.Vector3(0, 1.0, 0);
  51621. /**
  51622. * Random direction of each particle after it has been emitted, between direction1 and direction2 vectors.
  51623. */
  51624. this.direction2 = new BABYLON.Vector3(0, 1.0, 0);
  51625. /**
  51626. * 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.
  51627. */
  51628. this.minEmitBox = new BABYLON.Vector3(-0.5, -0.5, -0.5);
  51629. /**
  51630. * 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.
  51631. */
  51632. this.maxEmitBox = new BABYLON.Vector3(0.5, 0.5, 0.5);
  51633. }
  51634. /**
  51635. * Called by the particle System when the direction is computed for the created particle.
  51636. * @param emitPower is the power of the particle (speed)
  51637. * @param worldMatrix is the world matrix of the particle system
  51638. * @param directionToUpdate is the direction vector to update with the result
  51639. * @param particle is the particle we are computed the direction for
  51640. */
  51641. BoxParticleEmitter.prototype.startDirectionFunction = function (emitPower, worldMatrix, directionToUpdate, particle) {
  51642. var randX = BABYLON.Scalar.RandomRange(this.direction1.x, this.direction2.x);
  51643. var randY = BABYLON.Scalar.RandomRange(this.direction1.y, this.direction2.y);
  51644. var randZ = BABYLON.Scalar.RandomRange(this.direction1.z, this.direction2.z);
  51645. BABYLON.Vector3.TransformNormalFromFloatsToRef(randX * emitPower, randY * emitPower, randZ * emitPower, worldMatrix, directionToUpdate);
  51646. };
  51647. /**
  51648. * Called by the particle System when the position is computed for the created particle.
  51649. * @param worldMatrix is the world matrix of the particle system
  51650. * @param positionToUpdate is the position vector to update with the result
  51651. * @param particle is the particle we are computed the position for
  51652. */
  51653. BoxParticleEmitter.prototype.startPositionFunction = function (worldMatrix, positionToUpdate, particle) {
  51654. var randX = BABYLON.Scalar.RandomRange(this.minEmitBox.x, this.maxEmitBox.x);
  51655. var randY = BABYLON.Scalar.RandomRange(this.minEmitBox.y, this.maxEmitBox.y);
  51656. var randZ = BABYLON.Scalar.RandomRange(this.minEmitBox.z, this.maxEmitBox.z);
  51657. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(randX, randY, randZ, worldMatrix, positionToUpdate);
  51658. };
  51659. /**
  51660. * Clones the current emitter and returns a copy of it
  51661. * @returns the new emitter
  51662. */
  51663. BoxParticleEmitter.prototype.clone = function () {
  51664. var newOne = new BoxParticleEmitter();
  51665. BABYLON.Tools.DeepCopy(this, newOne);
  51666. return newOne;
  51667. };
  51668. /**
  51669. * Called by the {BABYLON.GPUParticleSystem} to setup the update shader
  51670. * @param effect defines the update shader
  51671. */
  51672. BoxParticleEmitter.prototype.applyToShader = function (effect) {
  51673. effect.setVector3("direction1", this.direction1);
  51674. effect.setVector3("direction2", this.direction2);
  51675. effect.setVector3("minEmitBox", this.minEmitBox);
  51676. effect.setVector3("maxEmitBox", this.maxEmitBox);
  51677. };
  51678. /**
  51679. * Returns a string to use to update the GPU particles update shader
  51680. * @returns a string containng the defines string
  51681. */
  51682. BoxParticleEmitter.prototype.getEffectDefines = function () {
  51683. return "#define BOXEMITTER";
  51684. };
  51685. /**
  51686. * Returns the string "BoxEmitter"
  51687. * @returns a string containing the class name
  51688. */
  51689. BoxParticleEmitter.prototype.getClassName = function () {
  51690. return "BoxEmitter";
  51691. };
  51692. /**
  51693. * Serializes the particle system to a JSON object.
  51694. * @returns the JSON object
  51695. */
  51696. BoxParticleEmitter.prototype.serialize = function () {
  51697. var serializationObject = {};
  51698. serializationObject.type = this.getClassName();
  51699. serializationObject.direction1 = this.direction1.asArray();
  51700. ;
  51701. serializationObject.direction2 = this.direction2.asArray();
  51702. ;
  51703. serializationObject.minEmitBox = this.minEmitBox.asArray();
  51704. ;
  51705. serializationObject.maxEmitBox = this.maxEmitBox.asArray();
  51706. ;
  51707. return serializationObject;
  51708. };
  51709. /**
  51710. * Parse properties from a JSON object
  51711. * @param serializationObject defines the JSON object
  51712. */
  51713. BoxParticleEmitter.prototype.parse = function (serializationObject) {
  51714. this.direction1.copyFrom(serializationObject.direction1);
  51715. this.direction2.copyFrom(serializationObject.direction2);
  51716. this.minEmitBox.copyFrom(serializationObject.minEmitBox);
  51717. this.maxEmitBox.copyFrom(serializationObject.maxEmitBox);
  51718. };
  51719. return BoxParticleEmitter;
  51720. }());
  51721. BABYLON.BoxParticleEmitter = BoxParticleEmitter;
  51722. })(BABYLON || (BABYLON = {}));
  51723. //# sourceMappingURL=babylon.boxParticleEmitter.js.map
  51724. var BABYLON;
  51725. (function (BABYLON) {
  51726. /**
  51727. * Particle emitter emitting particles from the inside of a cone.
  51728. * It emits the particles alongside the cone volume from the base to the particle.
  51729. * The emission direction might be randomized.
  51730. */
  51731. var ConeParticleEmitter = /** @class */ (function () {
  51732. /**
  51733. * Creates a new instance of @see ConeParticleEmitter
  51734. * @param radius the radius of the emission cone (1 by default)
  51735. * @param angles the cone base angle (PI by default)
  51736. * @param directionRandomizer defines how much to randomize the particle direction [0-1]
  51737. */
  51738. function ConeParticleEmitter(radius,
  51739. /**
  51740. * The radius of the emission cone.
  51741. */
  51742. angle,
  51743. /**
  51744. * The cone base angle.
  51745. */
  51746. directionRandomizer) {
  51747. if (radius === void 0) { radius = 1; }
  51748. if (angle === void 0) { angle = Math.PI; }
  51749. if (directionRandomizer === void 0) { directionRandomizer = 0; }
  51750. this.angle = angle;
  51751. this.directionRandomizer = directionRandomizer;
  51752. this.radius = radius;
  51753. }
  51754. Object.defineProperty(ConeParticleEmitter.prototype, "radius", {
  51755. /**
  51756. * Gets the radius of the emission cone.
  51757. */
  51758. get: function () {
  51759. return this._radius;
  51760. },
  51761. /**
  51762. * Sets the radius of the emission cone.
  51763. */
  51764. set: function (value) {
  51765. this._radius = value;
  51766. if (this.angle !== 0) {
  51767. this._height = value / Math.tan(this.angle / 2);
  51768. }
  51769. else {
  51770. this._height = 1;
  51771. }
  51772. },
  51773. enumerable: true,
  51774. configurable: true
  51775. });
  51776. /**
  51777. * Called by the particle System when the direction is computed for the created particle.
  51778. * @param emitPower is the power of the particle (speed)
  51779. * @param worldMatrix is the world matrix of the particle system
  51780. * @param directionToUpdate is the direction vector to update with the result
  51781. * @param particle is the particle we are computed the direction for
  51782. */
  51783. ConeParticleEmitter.prototype.startDirectionFunction = function (emitPower, worldMatrix, directionToUpdate, particle) {
  51784. if (this.angle === 0) {
  51785. BABYLON.Vector3.TransformNormalFromFloatsToRef(0, emitPower, 0, worldMatrix, directionToUpdate);
  51786. }
  51787. else {
  51788. // measure the direction Vector from the emitter to the particle.
  51789. var direction = particle.position.subtract(worldMatrix.getTranslation()).normalize();
  51790. var randX = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  51791. var randY = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  51792. var randZ = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  51793. direction.x += randX;
  51794. direction.y += randY;
  51795. direction.z += randZ;
  51796. direction.normalize();
  51797. BABYLON.Vector3.TransformNormalFromFloatsToRef(direction.x * emitPower, direction.y * emitPower, direction.z * emitPower, worldMatrix, directionToUpdate);
  51798. }
  51799. };
  51800. /**
  51801. * Called by the particle System when the position is computed for the created particle.
  51802. * @param worldMatrix is the world matrix of the particle system
  51803. * @param positionToUpdate is the position vector to update with the result
  51804. * @param particle is the particle we are computed the position for
  51805. */
  51806. ConeParticleEmitter.prototype.startPositionFunction = function (worldMatrix, positionToUpdate, particle) {
  51807. var s = BABYLON.Scalar.RandomRange(0, Math.PI * 2);
  51808. var h = BABYLON.Scalar.RandomRange(0, 1);
  51809. // Better distribution in a cone at normal angles.
  51810. h = 1 - h * h;
  51811. var radius = BABYLON.Scalar.RandomRange(0, this._radius);
  51812. radius = radius * h / this._height;
  51813. var randX = radius * Math.sin(s);
  51814. var randZ = radius * Math.cos(s);
  51815. var randY = h * this._height;
  51816. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(randX, randY, randZ, worldMatrix, positionToUpdate);
  51817. };
  51818. /**
  51819. * Clones the current emitter and returns a copy of it
  51820. * @returns the new emitter
  51821. */
  51822. ConeParticleEmitter.prototype.clone = function () {
  51823. var newOne = new ConeParticleEmitter(this.radius, this.angle, this.directionRandomizer);
  51824. BABYLON.Tools.DeepCopy(this, newOne);
  51825. return newOne;
  51826. };
  51827. /**
  51828. * Called by the {BABYLON.GPUParticleSystem} to setup the update shader
  51829. * @param effect defines the update shader
  51830. */
  51831. ConeParticleEmitter.prototype.applyToShader = function (effect) {
  51832. effect.setFloat("radius", this.radius);
  51833. effect.setFloat("angle", this.angle);
  51834. effect.setFloat("height", this._height);
  51835. effect.setFloat("directionRandomizer", this.directionRandomizer);
  51836. };
  51837. /**
  51838. * Returns a string to use to update the GPU particles update shader
  51839. * @returns a string containng the defines string
  51840. */
  51841. ConeParticleEmitter.prototype.getEffectDefines = function () {
  51842. return "#define CONEEMITTER";
  51843. };
  51844. /**
  51845. * Returns the string "BoxEmitter"
  51846. * @returns a string containing the class name
  51847. */
  51848. ConeParticleEmitter.prototype.getClassName = function () {
  51849. return "ConeEmitter";
  51850. };
  51851. /**
  51852. * Serializes the particle system to a JSON object.
  51853. * @returns the JSON object
  51854. */
  51855. ConeParticleEmitter.prototype.serialize = function () {
  51856. var serializationObject = {};
  51857. serializationObject.type = this.getClassName();
  51858. serializationObject.radius = this.radius;
  51859. serializationObject.angle = this.angle;
  51860. serializationObject.directionRandomizer = this.directionRandomizer;
  51861. return serializationObject;
  51862. };
  51863. /**
  51864. * Parse properties from a JSON object
  51865. * @param serializationObject defines the JSON object
  51866. */
  51867. ConeParticleEmitter.prototype.parse = function (serializationObject) {
  51868. this.radius = serializationObject.radius;
  51869. this.angle = serializationObject.angle;
  51870. this.directionRandomizer = serializationObject.directionRandomizer;
  51871. };
  51872. return ConeParticleEmitter;
  51873. }());
  51874. BABYLON.ConeParticleEmitter = ConeParticleEmitter;
  51875. })(BABYLON || (BABYLON = {}));
  51876. //# sourceMappingURL=babylon.coneParticleEmitter.js.map
  51877. var BABYLON;
  51878. (function (BABYLON) {
  51879. /**
  51880. * Particle emitter emitting particles from the inside of a sphere.
  51881. * It emits the particles alongside the sphere radius. The emission direction might be randomized.
  51882. */
  51883. var SphereParticleEmitter = /** @class */ (function () {
  51884. /**
  51885. * Creates a new instance of @see SphereParticleEmitter
  51886. * @param radius the radius of the emission sphere (1 by default)
  51887. * @param directionRandomizer defines how much to randomize the particle direction [0-1]
  51888. */
  51889. function SphereParticleEmitter(
  51890. /**
  51891. * The radius of the emission sphere.
  51892. */
  51893. radius,
  51894. /**
  51895. * How much to randomize the particle direction [0-1].
  51896. */
  51897. directionRandomizer) {
  51898. if (radius === void 0) { radius = 1; }
  51899. if (directionRandomizer === void 0) { directionRandomizer = 0; }
  51900. this.radius = radius;
  51901. this.directionRandomizer = directionRandomizer;
  51902. }
  51903. /**
  51904. * Called by the particle System when the direction is computed for the created particle.
  51905. * @param emitPower is the power of the particle (speed)
  51906. * @param worldMatrix is the world matrix of the particle system
  51907. * @param directionToUpdate is the direction vector to update with the result
  51908. * @param particle is the particle we are computed the direction for
  51909. */
  51910. SphereParticleEmitter.prototype.startDirectionFunction = function (emitPower, worldMatrix, directionToUpdate, particle) {
  51911. var direction = particle.position.subtract(worldMatrix.getTranslation()).normalize();
  51912. var randX = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  51913. var randY = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  51914. var randZ = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  51915. direction.x += randX;
  51916. direction.y += randY;
  51917. direction.z += randZ;
  51918. direction.normalize();
  51919. BABYLON.Vector3.TransformNormalFromFloatsToRef(direction.x * emitPower, direction.y * emitPower, direction.z * emitPower, worldMatrix, directionToUpdate);
  51920. };
  51921. /**
  51922. * Called by the particle System when the position is computed for the created particle.
  51923. * @param worldMatrix is the world matrix of the particle system
  51924. * @param positionToUpdate is the position vector to update with the result
  51925. * @param particle is the particle we are computed the position for
  51926. */
  51927. SphereParticleEmitter.prototype.startPositionFunction = function (worldMatrix, positionToUpdate, particle) {
  51928. var phi = BABYLON.Scalar.RandomRange(0, 2 * Math.PI);
  51929. var theta = BABYLON.Scalar.RandomRange(0, Math.PI);
  51930. var randRadius = BABYLON.Scalar.RandomRange(0, this.radius);
  51931. var randX = randRadius * Math.cos(phi) * Math.sin(theta);
  51932. var randY = randRadius * Math.cos(theta);
  51933. var randZ = randRadius * Math.sin(phi) * Math.sin(theta);
  51934. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(randX, randY, randZ, worldMatrix, positionToUpdate);
  51935. };
  51936. /**
  51937. * Clones the current emitter and returns a copy of it
  51938. * @returns the new emitter
  51939. */
  51940. SphereParticleEmitter.prototype.clone = function () {
  51941. var newOne = new SphereParticleEmitter(this.radius, this.directionRandomizer);
  51942. BABYLON.Tools.DeepCopy(this, newOne);
  51943. return newOne;
  51944. };
  51945. /**
  51946. * Called by the {BABYLON.GPUParticleSystem} to setup the update shader
  51947. * @param effect defines the update shader
  51948. */
  51949. SphereParticleEmitter.prototype.applyToShader = function (effect) {
  51950. effect.setFloat("radius", this.radius);
  51951. effect.setFloat("directionRandomizer", this.directionRandomizer);
  51952. };
  51953. /**
  51954. * Returns a string to use to update the GPU particles update shader
  51955. * @returns a string containng the defines string
  51956. */
  51957. SphereParticleEmitter.prototype.getEffectDefines = function () {
  51958. return "#define SPHEREEMITTER";
  51959. };
  51960. /**
  51961. * Returns the string "SphereParticleEmitter"
  51962. * @returns a string containing the class name
  51963. */
  51964. SphereParticleEmitter.prototype.getClassName = function () {
  51965. return "SphereParticleEmitter";
  51966. };
  51967. /**
  51968. * Serializes the particle system to a JSON object.
  51969. * @returns the JSON object
  51970. */
  51971. SphereParticleEmitter.prototype.serialize = function () {
  51972. var serializationObject = {};
  51973. serializationObject.type = this.getClassName();
  51974. serializationObject.radius = this.radius;
  51975. serializationObject.directionRandomizer = this.directionRandomizer;
  51976. return serializationObject;
  51977. };
  51978. /**
  51979. * Parse properties from a JSON object
  51980. * @param serializationObject defines the JSON object
  51981. */
  51982. SphereParticleEmitter.prototype.parse = function (serializationObject) {
  51983. this.radius = serializationObject.radius;
  51984. this.directionRandomizer = serializationObject.directionRandomizer;
  51985. };
  51986. return SphereParticleEmitter;
  51987. }());
  51988. BABYLON.SphereParticleEmitter = SphereParticleEmitter;
  51989. /**
  51990. * Particle emitter emitting particles from the inside of a sphere.
  51991. * It emits the particles randomly between two vectors.
  51992. */
  51993. var SphereDirectedParticleEmitter = /** @class */ (function (_super) {
  51994. __extends(SphereDirectedParticleEmitter, _super);
  51995. /**
  51996. * Creates a new instance of @see SphereDirectedParticleEmitter
  51997. * @param radius the radius of the emission sphere (1 by default)
  51998. * @param direction1 the min limit of the emission direction (up vector by default)
  51999. * @param direction2 the max limit of the emission direction (up vector by default)
  52000. */
  52001. function SphereDirectedParticleEmitter(radius,
  52002. /**
  52003. * The min limit of the emission direction.
  52004. */
  52005. direction1,
  52006. /**
  52007. * The max limit of the emission direction.
  52008. */
  52009. direction2) {
  52010. if (radius === void 0) { radius = 1; }
  52011. if (direction1 === void 0) { direction1 = new BABYLON.Vector3(0, 1, 0); }
  52012. if (direction2 === void 0) { direction2 = new BABYLON.Vector3(0, 1, 0); }
  52013. var _this = _super.call(this, radius) || this;
  52014. _this.direction1 = direction1;
  52015. _this.direction2 = direction2;
  52016. return _this;
  52017. }
  52018. /**
  52019. * Called by the particle System when the direction is computed for the created particle.
  52020. * @param emitPower is the power of the particle (speed)
  52021. * @param worldMatrix is the world matrix of the particle system
  52022. * @param directionToUpdate is the direction vector to update with the result
  52023. * @param particle is the particle we are computed the direction for
  52024. */
  52025. SphereDirectedParticleEmitter.prototype.startDirectionFunction = function (emitPower, worldMatrix, directionToUpdate, particle) {
  52026. var randX = BABYLON.Scalar.RandomRange(this.direction1.x, this.direction2.x);
  52027. var randY = BABYLON.Scalar.RandomRange(this.direction1.y, this.direction2.y);
  52028. var randZ = BABYLON.Scalar.RandomRange(this.direction1.z, this.direction2.z);
  52029. BABYLON.Vector3.TransformNormalFromFloatsToRef(randX * emitPower, randY * emitPower, randZ * emitPower, worldMatrix, directionToUpdate);
  52030. };
  52031. /**
  52032. * Clones the current emitter and returns a copy of it
  52033. * @returns the new emitter
  52034. */
  52035. SphereDirectedParticleEmitter.prototype.clone = function () {
  52036. var newOne = new SphereDirectedParticleEmitter(this.radius, this.direction1, this.direction2);
  52037. BABYLON.Tools.DeepCopy(this, newOne);
  52038. return newOne;
  52039. };
  52040. /**
  52041. * Called by the {BABYLON.GPUParticleSystem} to setup the update shader
  52042. * @param effect defines the update shader
  52043. */
  52044. SphereDirectedParticleEmitter.prototype.applyToShader = function (effect) {
  52045. effect.setFloat("radius", this.radius);
  52046. effect.setVector3("direction1", this.direction1);
  52047. effect.setVector3("direction2", this.direction2);
  52048. };
  52049. /**
  52050. * Returns a string to use to update the GPU particles update shader
  52051. * @returns a string containng the defines string
  52052. */
  52053. SphereDirectedParticleEmitter.prototype.getEffectDefines = function () {
  52054. return "#define SPHEREEMITTER\n#define DIRECTEDSPHEREEMITTER";
  52055. };
  52056. /**
  52057. * Returns the string "SphereDirectedParticleEmitter"
  52058. * @returns a string containing the class name
  52059. */
  52060. SphereDirectedParticleEmitter.prototype.getClassName = function () {
  52061. return "SphereDirectedParticleEmitter";
  52062. };
  52063. /**
  52064. * Serializes the particle system to a JSON object.
  52065. * @returns the JSON object
  52066. */
  52067. SphereDirectedParticleEmitter.prototype.serialize = function () {
  52068. var serializationObject = _super.prototype.serialize.call(this);
  52069. ;
  52070. serializationObject.direction1 = this.direction1.asArray();
  52071. ;
  52072. serializationObject.direction2 = this.direction2.asArray();
  52073. ;
  52074. return serializationObject;
  52075. };
  52076. /**
  52077. * Parse properties from a JSON object
  52078. * @param serializationObject defines the JSON object
  52079. */
  52080. SphereDirectedParticleEmitter.prototype.parse = function (serializationObject) {
  52081. _super.prototype.parse.call(this, serializationObject);
  52082. this.direction1.copyFrom(serializationObject.direction1);
  52083. this.direction2.copyFrom(serializationObject.direction2);
  52084. };
  52085. return SphereDirectedParticleEmitter;
  52086. }(SphereParticleEmitter));
  52087. BABYLON.SphereDirectedParticleEmitter = SphereDirectedParticleEmitter;
  52088. })(BABYLON || (BABYLON = {}));
  52089. //# sourceMappingURL=babylon.sphereParticleEmitter.js.map
  52090. var __assign = (this && this.__assign) || Object.assign || function(t) {
  52091. for (var s, i = 1, n = arguments.length; i < n; i++) {
  52092. s = arguments[i];
  52093. for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
  52094. t[p] = s[p];
  52095. }
  52096. return t;
  52097. };
  52098. var BABYLON;
  52099. (function (BABYLON) {
  52100. /**
  52101. * This represents a GPU particle system in Babylon
  52102. * This is the fastest particle system in Babylon as it uses the GPU to update the individual particle data
  52103. * @see https://www.babylonjs-playground.com/#PU4WYI#4
  52104. */
  52105. var GPUParticleSystem = /** @class */ (function () {
  52106. /**
  52107. * Instantiates a GPU particle system.
  52108. * 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.
  52109. * @param name The name of the particle system
  52110. * @param capacity The max number of particles alive at the same time
  52111. * @param scene The scene the particle system belongs to
  52112. */
  52113. function GPUParticleSystem(name, options, scene) {
  52114. /**
  52115. * The emitter represents the Mesh or position we are attaching the particle system to.
  52116. */
  52117. this.emitter = null;
  52118. /**
  52119. * The rendering group used by the Particle system to chose when to render.
  52120. */
  52121. this.renderingGroupId = 0;
  52122. /**
  52123. * The layer mask we are rendering the particles through.
  52124. */
  52125. this.layerMask = 0x0FFFFFFF;
  52126. this._targetIndex = 0;
  52127. this._currentRenderId = -1;
  52128. this._started = false;
  52129. this._stopped = false;
  52130. this._timeDelta = 0;
  52131. this._attributesStrideSize = 14;
  52132. this._actualFrame = 0;
  52133. /**
  52134. * List of animations used by the particle system.
  52135. */
  52136. this.animations = [];
  52137. /**
  52138. * An event triggered when the system is disposed.
  52139. */
  52140. this.onDisposeObservable = new BABYLON.Observable();
  52141. /**
  52142. * The overall motion speed (0.01 is default update speed, faster updates = faster animation)
  52143. */
  52144. this.updateSpeed = 0.01;
  52145. /**
  52146. * The amount of time the particle system is running (depends of the overall update speed).
  52147. */
  52148. this.targetStopDuration = 0;
  52149. /**
  52150. * Blend mode use to render the particle, it can be either ParticleSystem.BLENDMODE_ONEONE or ParticleSystem.BLENDMODE_STANDARD.
  52151. */
  52152. this.blendMode = BABYLON.ParticleSystem.BLENDMODE_ONEONE;
  52153. /**
  52154. * Minimum life time of emitting particles.
  52155. */
  52156. this.minLifeTime = 1;
  52157. /**
  52158. * Maximum life time of emitting particles.
  52159. */
  52160. this.maxLifeTime = 1;
  52161. /**
  52162. * Minimum Size of emitting particles.
  52163. */
  52164. this.minSize = 1;
  52165. /**
  52166. * Maximum Size of emitting particles.
  52167. */
  52168. this.maxSize = 1;
  52169. /**
  52170. * Random color of each particle after it has been emitted, between color1 and color2 vectors.
  52171. */
  52172. this.color1 = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  52173. /**
  52174. * Random color of each particle after it has been emitted, between color1 and color2 vectors.
  52175. */
  52176. this.color2 = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  52177. /**
  52178. * Color the particle will have at the end of its lifetime.
  52179. */
  52180. this.colorDead = new BABYLON.Color4(0, 0, 0, 0);
  52181. /**
  52182. * The maximum number of particles to emit per frame until we reach the activeParticleCount value
  52183. */
  52184. this.emitRate = 100;
  52185. /**
  52186. * You can use gravity if you want to give an orientation to your particles.
  52187. */
  52188. this.gravity = BABYLON.Vector3.Zero();
  52189. /**
  52190. * Minimum power of emitting particles.
  52191. */
  52192. this.minEmitPower = 1;
  52193. /**
  52194. * Maximum power of emitting particles.
  52195. */
  52196. this.maxEmitPower = 1;
  52197. /**
  52198. * Forces the particle to write their depth information to the depth buffer. This can help preventing other draw calls
  52199. * to override the particles.
  52200. */
  52201. this.forceDepthWrite = false;
  52202. this.id = name;
  52203. this.name = name;
  52204. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  52205. this._engine = this._scene.getEngine();
  52206. var fullOptions = __assign({ capacity: 50000, randomTextureSize: this._engine.getCaps().maxTextureSize }, options);
  52207. this._capacity = fullOptions.capacity;
  52208. this._activeCount = fullOptions.capacity;
  52209. this._currentActiveCount = 0;
  52210. this._scene.particleSystems.push(this);
  52211. this._updateEffectOptions = {
  52212. attributes: ["position", "age", "life", "seed", "size", "color", "direction"],
  52213. uniformsNames: ["currentCount", "timeDelta", "generalRandoms", "emitterWM", "lifeTime", "color1", "color2", "sizeRange", "gravity", "emitPower",
  52214. "direction1", "direction2", "minEmitBox", "maxEmitBox", "radius", "directionRandomizer", "height", "angle"],
  52215. uniformBuffersNames: [],
  52216. samplers: ["randomSampler"],
  52217. defines: "",
  52218. fallbacks: null,
  52219. onCompiled: null,
  52220. onError: null,
  52221. indexParameters: null,
  52222. maxSimultaneousLights: 0,
  52223. transformFeedbackVaryings: ["outPosition", "outAge", "outLife", "outSeed", "outSize", "outColor", "outDirection"]
  52224. };
  52225. // Random data
  52226. var maxTextureSize = Math.min(this._engine.getCaps().maxTextureSize, fullOptions.randomTextureSize);
  52227. var d = [];
  52228. for (var i = 0; i < maxTextureSize; ++i) {
  52229. d.push(Math.random());
  52230. d.push(Math.random());
  52231. d.push(Math.random());
  52232. d.push(Math.random());
  52233. }
  52234. 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);
  52235. this._randomTexture.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  52236. this._randomTexture.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  52237. this._randomTextureSize = maxTextureSize;
  52238. this.particleEmitterType = new BABYLON.BoxParticleEmitter();
  52239. }
  52240. Object.defineProperty(GPUParticleSystem, "IsSupported", {
  52241. /**
  52242. * Gets a boolean indicating if the GPU particles can be rendered on current browser
  52243. */
  52244. get: function () {
  52245. if (!BABYLON.Engine.LastCreatedEngine) {
  52246. return false;
  52247. }
  52248. return BABYLON.Engine.LastCreatedEngine.webGLVersion > 1;
  52249. },
  52250. enumerable: true,
  52251. configurable: true
  52252. });
  52253. Object.defineProperty(GPUParticleSystem.prototype, "direction1", {
  52254. /**
  52255. * Random direction of each particle after it has been emitted, between direction1 and direction2 vectors.
  52256. * This only works when particleEmitterTyps is a BoxParticleEmitter
  52257. */
  52258. get: function () {
  52259. if (this.particleEmitterType.direction1) {
  52260. return this.particleEmitterType.direction1;
  52261. }
  52262. return BABYLON.Vector3.Zero();
  52263. },
  52264. set: function (value) {
  52265. if (this.particleEmitterType.direction1) {
  52266. this.particleEmitterType.direction1 = value;
  52267. }
  52268. },
  52269. enumerable: true,
  52270. configurable: true
  52271. });
  52272. Object.defineProperty(GPUParticleSystem.prototype, "direction2", {
  52273. /**
  52274. * Random direction of each particle after it has been emitted, between direction1 and direction2 vectors.
  52275. * This only works when particleEmitterTyps is a BoxParticleEmitter
  52276. */
  52277. get: function () {
  52278. if (this.particleEmitterType.direction2) {
  52279. return this.particleEmitterType.direction2;
  52280. }
  52281. return BABYLON.Vector3.Zero();
  52282. },
  52283. set: function (value) {
  52284. if (this.particleEmitterType.direction2) {
  52285. this.particleEmitterType.direction2 = value;
  52286. }
  52287. },
  52288. enumerable: true,
  52289. configurable: true
  52290. });
  52291. Object.defineProperty(GPUParticleSystem.prototype, "minEmitBox", {
  52292. /**
  52293. * 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.
  52294. * This only works when particleEmitterTyps is a BoxParticleEmitter
  52295. */
  52296. get: function () {
  52297. if (this.particleEmitterType.minEmitBox) {
  52298. return this.particleEmitterType.minEmitBox;
  52299. }
  52300. return BABYLON.Vector3.Zero();
  52301. },
  52302. set: function (value) {
  52303. if (this.particleEmitterType.minEmitBox) {
  52304. this.particleEmitterType.minEmitBox = value;
  52305. }
  52306. },
  52307. enumerable: true,
  52308. configurable: true
  52309. });
  52310. Object.defineProperty(GPUParticleSystem.prototype, "maxEmitBox", {
  52311. /**
  52312. * 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.
  52313. * This only works when particleEmitterTyps is a BoxParticleEmitter
  52314. */
  52315. get: function () {
  52316. if (this.particleEmitterType.maxEmitBox) {
  52317. return this.particleEmitterType.maxEmitBox;
  52318. }
  52319. return BABYLON.Vector3.Zero();
  52320. },
  52321. set: function (value) {
  52322. if (this.particleEmitterType.maxEmitBox) {
  52323. this.particleEmitterType.maxEmitBox = value;
  52324. }
  52325. },
  52326. enumerable: true,
  52327. configurable: true
  52328. });
  52329. /**
  52330. * Gets the maximum number of particles active at the same time.
  52331. * @returns The max number of active particles.
  52332. */
  52333. GPUParticleSystem.prototype.getCapacity = function () {
  52334. return this._capacity;
  52335. };
  52336. Object.defineProperty(GPUParticleSystem.prototype, "activeParticleCount", {
  52337. /**
  52338. * Gets or set the number of active particles
  52339. */
  52340. get: function () {
  52341. return this._activeCount;
  52342. },
  52343. set: function (value) {
  52344. this._activeCount = Math.min(value, this._capacity);
  52345. },
  52346. enumerable: true,
  52347. configurable: true
  52348. });
  52349. /**
  52350. * Gets Wether the system has been started.
  52351. * @returns True if it has been started, otherwise false.
  52352. */
  52353. GPUParticleSystem.prototype.isStarted = function () {
  52354. return this._started;
  52355. };
  52356. /**
  52357. * Starts the particle system and begins to emit.
  52358. */
  52359. GPUParticleSystem.prototype.start = function () {
  52360. this._started = true;
  52361. this._stopped = false;
  52362. };
  52363. /**
  52364. * Stops the particle system.
  52365. */
  52366. GPUParticleSystem.prototype.stop = function () {
  52367. this._stopped = true;
  52368. };
  52369. /**
  52370. * Remove all active particles
  52371. */
  52372. GPUParticleSystem.prototype.reset = function () {
  52373. this._releaseBuffers();
  52374. this._releaseVAOs();
  52375. this._currentActiveCount = 0;
  52376. this._targetIndex = 0;
  52377. };
  52378. /**
  52379. * Returns the string "GPUParticleSystem"
  52380. * @returns a string containing the class name
  52381. */
  52382. GPUParticleSystem.prototype.getClassName = function () {
  52383. return "GPUParticleSystem";
  52384. };
  52385. GPUParticleSystem.prototype._createUpdateVAO = function (source) {
  52386. var updateVertexBuffers = {};
  52387. updateVertexBuffers["position"] = source.createVertexBuffer("position", 0, 3);
  52388. updateVertexBuffers["age"] = source.createVertexBuffer("age", 3, 1);
  52389. updateVertexBuffers["life"] = source.createVertexBuffer("life", 4, 1);
  52390. updateVertexBuffers["seed"] = source.createVertexBuffer("seed", 5, 1);
  52391. updateVertexBuffers["size"] = source.createVertexBuffer("size", 6, 1);
  52392. updateVertexBuffers["color"] = source.createVertexBuffer("color", 7, 4);
  52393. updateVertexBuffers["direction"] = source.createVertexBuffer("direction", 11, 3);
  52394. var vao = this._engine.recordVertexArrayObject(updateVertexBuffers, null, this._updateEffect);
  52395. this._engine.bindArrayBuffer(null);
  52396. return vao;
  52397. };
  52398. GPUParticleSystem.prototype._createRenderVAO = function (source, spriteSource) {
  52399. var renderVertexBuffers = {};
  52400. renderVertexBuffers["position"] = source.createVertexBuffer("position", 0, 3, this._attributesStrideSize, true);
  52401. renderVertexBuffers["age"] = source.createVertexBuffer("age", 3, 1, this._attributesStrideSize, true);
  52402. renderVertexBuffers["life"] = source.createVertexBuffer("life", 4, 1, this._attributesStrideSize, true);
  52403. renderVertexBuffers["size"] = source.createVertexBuffer("size", 6, 1, this._attributesStrideSize, true);
  52404. renderVertexBuffers["color"] = source.createVertexBuffer("color", 7, 4, this._attributesStrideSize, true);
  52405. renderVertexBuffers["offset"] = spriteSource.createVertexBuffer("offset", 0, 2);
  52406. renderVertexBuffers["uv"] = spriteSource.createVertexBuffer("uv", 2, 2);
  52407. var vao = this._engine.recordVertexArrayObject(renderVertexBuffers, null, this._renderEffect);
  52408. this._engine.bindArrayBuffer(null);
  52409. return vao;
  52410. };
  52411. GPUParticleSystem.prototype._initialize = function (force) {
  52412. if (force === void 0) { force = false; }
  52413. if (this._buffer0 && !force) {
  52414. return;
  52415. }
  52416. var engine = this._scene.getEngine();
  52417. var data = new Array();
  52418. for (var particleIndex = 0; particleIndex < this._capacity; particleIndex++) {
  52419. // position
  52420. data.push(0.0);
  52421. data.push(0.0);
  52422. data.push(0.0);
  52423. // Age and life
  52424. data.push(0.0); // create the particle as a dead one to create a new one at start
  52425. data.push(0.0);
  52426. // Seed
  52427. data.push(Math.random());
  52428. // Size
  52429. data.push(0.0);
  52430. // color
  52431. data.push(0.0);
  52432. data.push(0.0);
  52433. data.push(0.0);
  52434. data.push(0.0);
  52435. // direction
  52436. data.push(0.0);
  52437. data.push(0.0);
  52438. data.push(0.0);
  52439. }
  52440. // Sprite data
  52441. var spriteData = new Float32Array([0.5, 0.5, 1, 1,
  52442. -0.5, 0.5, 0, 1,
  52443. -0.5, -0.5, 0, 0,
  52444. 0.5, -0.5, 1, 0]);
  52445. // Buffers
  52446. this._buffer0 = new BABYLON.Buffer(engine, data, false, this._attributesStrideSize);
  52447. this._buffer1 = new BABYLON.Buffer(engine, data, false, this._attributesStrideSize);
  52448. this._spriteBuffer = new BABYLON.Buffer(engine, spriteData, false, 4);
  52449. // Update VAO
  52450. this._updateVAO = [];
  52451. this._updateVAO.push(this._createUpdateVAO(this._buffer0));
  52452. this._updateVAO.push(this._createUpdateVAO(this._buffer1));
  52453. // Render VAO
  52454. this._renderVAO = [];
  52455. this._renderVAO.push(this._createRenderVAO(this._buffer1, this._spriteBuffer));
  52456. this._renderVAO.push(this._createRenderVAO(this._buffer0, this._spriteBuffer));
  52457. // Links
  52458. this._sourceBuffer = this._buffer0;
  52459. this._targetBuffer = this._buffer1;
  52460. };
  52461. /** @ignore */
  52462. GPUParticleSystem.prototype._recreateUpdateEffect = function () {
  52463. var defines = this.particleEmitterType ? this.particleEmitterType.getEffectDefines() : "";
  52464. if (this._updateEffect && this._updateEffectOptions.defines === defines) {
  52465. return;
  52466. }
  52467. this._updateEffectOptions.defines = defines;
  52468. this._updateEffect = new BABYLON.Effect("gpuUpdateParticles", this._updateEffectOptions, this._scene.getEngine());
  52469. };
  52470. /** @ignore */
  52471. GPUParticleSystem.prototype._recreateRenderEffect = function () {
  52472. var defines = "";
  52473. if (this._scene.clipPlane) {
  52474. defines = "\n#define CLIPPLANE";
  52475. }
  52476. if (this._renderEffect && this._renderEffect.defines === defines) {
  52477. return;
  52478. }
  52479. this._renderEffect = new BABYLON.Effect("gpuRenderParticles", ["position", "age", "life", "size", "color", "offset", "uv"], ["view", "projection", "colorDead", "invView", "vClipPlane"], ["textureSampler"], this._scene.getEngine(), defines);
  52480. };
  52481. /**
  52482. * Animates the particle system for the current frame by emitting new particles and or animating the living ones.
  52483. */
  52484. GPUParticleSystem.prototype.animate = function () {
  52485. if (!this._stopped) {
  52486. this._timeDelta = this.updateSpeed * this._scene.getAnimationRatio();
  52487. this._actualFrame += this._timeDelta;
  52488. if (this.targetStopDuration && this._actualFrame >= this.targetStopDuration)
  52489. this.stop();
  52490. }
  52491. else {
  52492. this._timeDelta = 0;
  52493. }
  52494. };
  52495. /**
  52496. * Renders the particle system in its current state.
  52497. * @returns the current number of particles
  52498. */
  52499. GPUParticleSystem.prototype.render = function () {
  52500. if (!this._started) {
  52501. return 0;
  52502. }
  52503. this._recreateUpdateEffect();
  52504. this._recreateRenderEffect();
  52505. if (!this.emitter || !this._updateEffect.isReady() || !this._renderEffect.isReady()) {
  52506. return 0;
  52507. }
  52508. if (this._currentRenderId === this._scene.getRenderId()) {
  52509. return 0;
  52510. }
  52511. this._currentRenderId = this._scene.getRenderId();
  52512. // Get everything ready to render
  52513. this._initialize();
  52514. this._currentActiveCount = Math.min(this._activeCount, this._currentActiveCount + (this.emitRate * this._timeDelta) | 0);
  52515. // Enable update effect
  52516. this._engine.enableEffect(this._updateEffect);
  52517. this._engine.setState(false);
  52518. this._updateEffect.setFloat("currentCount", this._currentActiveCount);
  52519. this._updateEffect.setFloat("timeDelta", this._timeDelta);
  52520. this._updateEffect.setFloat3("generalRandoms", Math.random(), Math.random(), Math.random());
  52521. this._updateEffect.setTexture("randomSampler", this._randomTexture);
  52522. this._updateEffect.setFloat2("lifeTime", this.minLifeTime, this.maxLifeTime);
  52523. this._updateEffect.setFloat2("emitPower", this.minEmitPower, this.maxEmitPower);
  52524. this._updateEffect.setDirectColor4("color1", this.color1);
  52525. this._updateEffect.setDirectColor4("color2", this.color2);
  52526. this._updateEffect.setFloat2("sizeRange", this.minSize, this.maxSize);
  52527. this._updateEffect.setVector3("gravity", this.gravity);
  52528. if (this.particleEmitterType) {
  52529. this.particleEmitterType.applyToShader(this._updateEffect);
  52530. }
  52531. var emitterWM;
  52532. if (this.emitter.position) {
  52533. var emitterMesh = this.emitter;
  52534. emitterWM = emitterMesh.getWorldMatrix();
  52535. }
  52536. else {
  52537. var emitterPosition = this.emitter;
  52538. emitterWM = BABYLON.Matrix.Translation(emitterPosition.x, emitterPosition.y, emitterPosition.z);
  52539. }
  52540. this._updateEffect.setMatrix("emitterWM", emitterWM);
  52541. // Bind source VAO
  52542. this._engine.bindVertexArrayObject(this._updateVAO[this._targetIndex], null);
  52543. // Update
  52544. this._engine.bindTransformFeedbackBuffer(this._targetBuffer.getBuffer());
  52545. this._engine.setRasterizerState(false);
  52546. this._engine.beginTransformFeedback();
  52547. this._engine.drawArraysType(BABYLON.Material.PointListDrawMode, 0, this._currentActiveCount);
  52548. this._engine.endTransformFeedback();
  52549. this._engine.setRasterizerState(true);
  52550. this._engine.bindTransformFeedbackBuffer(null);
  52551. // Enable render effect
  52552. this._engine.enableEffect(this._renderEffect);
  52553. var viewMatrix = this._scene.getViewMatrix();
  52554. this._renderEffect.setMatrix("view", viewMatrix);
  52555. this._renderEffect.setMatrix("projection", this._scene.getProjectionMatrix());
  52556. this._renderEffect.setTexture("textureSampler", this.particleTexture);
  52557. this._renderEffect.setDirectColor4("colorDead", this.colorDead);
  52558. if (this._scene.clipPlane) {
  52559. var clipPlane = this._scene.clipPlane;
  52560. var invView = viewMatrix.clone();
  52561. invView.invert();
  52562. this._renderEffect.setMatrix("invView", invView);
  52563. this._renderEffect.setFloat4("vClipPlane", clipPlane.normal.x, clipPlane.normal.y, clipPlane.normal.z, clipPlane.d);
  52564. }
  52565. // Draw order
  52566. if (this.blendMode === BABYLON.ParticleSystem.BLENDMODE_ONEONE) {
  52567. this._engine.setAlphaMode(BABYLON.Engine.ALPHA_ONEONE);
  52568. }
  52569. else {
  52570. this._engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  52571. }
  52572. if (this.forceDepthWrite) {
  52573. this._engine.setDepthWrite(true);
  52574. }
  52575. // Bind source VAO
  52576. this._engine.bindVertexArrayObject(this._renderVAO[this._targetIndex], null);
  52577. // Render
  52578. this._engine.drawArraysType(BABYLON.Material.TriangleFanDrawMode, 0, 4, this._currentActiveCount);
  52579. this._engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  52580. // Switch VAOs
  52581. this._targetIndex++;
  52582. if (this._targetIndex === 2) {
  52583. this._targetIndex = 0;
  52584. }
  52585. // Switch buffers
  52586. var tmpBuffer = this._sourceBuffer;
  52587. this._sourceBuffer = this._targetBuffer;
  52588. this._targetBuffer = tmpBuffer;
  52589. return this._currentActiveCount;
  52590. };
  52591. /**
  52592. * Rebuilds the particle system
  52593. */
  52594. GPUParticleSystem.prototype.rebuild = function () {
  52595. this._initialize(true);
  52596. };
  52597. GPUParticleSystem.prototype._releaseBuffers = function () {
  52598. if (this._buffer0) {
  52599. this._buffer0.dispose();
  52600. this._buffer0 = null;
  52601. }
  52602. if (this._buffer1) {
  52603. this._buffer1.dispose();
  52604. this._buffer1 = null;
  52605. }
  52606. if (this._spriteBuffer) {
  52607. this._spriteBuffer.dispose();
  52608. this._spriteBuffer = null;
  52609. }
  52610. };
  52611. GPUParticleSystem.prototype._releaseVAOs = function () {
  52612. if (!this._updateVAO) {
  52613. return;
  52614. }
  52615. for (var index = 0; index < this._updateVAO.length; index++) {
  52616. this._engine.releaseVertexArrayObject(this._updateVAO[index]);
  52617. }
  52618. this._updateVAO = [];
  52619. for (var index = 0; index < this._renderVAO.length; index++) {
  52620. this._engine.releaseVertexArrayObject(this._renderVAO[index]);
  52621. }
  52622. this._renderVAO = [];
  52623. };
  52624. /**
  52625. * Disposes the particle system and free the associated resources
  52626. * @param disposeTexture defines if the particule texture must be disposed as well (true by default)
  52627. */
  52628. GPUParticleSystem.prototype.dispose = function (disposeTexture) {
  52629. if (disposeTexture === void 0) { disposeTexture = true; }
  52630. var index = this._scene.particleSystems.indexOf(this);
  52631. if (index > -1) {
  52632. this._scene.particleSystems.splice(index, 1);
  52633. }
  52634. this._releaseBuffers();
  52635. this._releaseVAOs();
  52636. if (this._randomTexture) {
  52637. this._randomTexture.dispose();
  52638. this._randomTexture = null;
  52639. }
  52640. if (disposeTexture && this.particleTexture) {
  52641. this.particleTexture.dispose();
  52642. this.particleTexture = null;
  52643. }
  52644. // Callback
  52645. this.onDisposeObservable.notifyObservers(this);
  52646. this.onDisposeObservable.clear();
  52647. };
  52648. /**
  52649. * Clones the particle system.
  52650. * @param name The name of the cloned object
  52651. * @param newEmitter The new emitter to use
  52652. * @returns the cloned particle system
  52653. */
  52654. GPUParticleSystem.prototype.clone = function (name, newEmitter) {
  52655. var result = new GPUParticleSystem(name, { capacity: this._capacity, randomTextureSize: this._randomTextureSize }, this._scene);
  52656. BABYLON.Tools.DeepCopy(this, result);
  52657. if (newEmitter === undefined) {
  52658. newEmitter = this.emitter;
  52659. }
  52660. result.emitter = newEmitter;
  52661. if (this.particleTexture) {
  52662. result.particleTexture = new BABYLON.Texture(this.particleTexture.url, this._scene);
  52663. }
  52664. return result;
  52665. };
  52666. /**
  52667. * Serializes the particle system to a JSON object.
  52668. * @returns the JSON object
  52669. */
  52670. GPUParticleSystem.prototype.serialize = function () {
  52671. var serializationObject = {};
  52672. serializationObject.name = this.name;
  52673. serializationObject.id = this.id;
  52674. // Emitter
  52675. if (this.emitter.position) {
  52676. var emitterMesh = this.emitter;
  52677. serializationObject.emitterId = emitterMesh.id;
  52678. }
  52679. else {
  52680. var emitterPosition = this.emitter;
  52681. serializationObject.emitter = emitterPosition.asArray();
  52682. }
  52683. serializationObject.capacity = this.getCapacity();
  52684. if (this.particleTexture) {
  52685. serializationObject.textureName = this.particleTexture.name;
  52686. }
  52687. // Animations
  52688. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  52689. // Particle system
  52690. serializationObject.activeParticleCount = this.activeParticleCount;
  52691. serializationObject.randomTextureSize = this._randomTextureSize;
  52692. serializationObject.minSize = this.minSize;
  52693. serializationObject.maxSize = this.maxSize;
  52694. serializationObject.minEmitPower = this.minEmitPower;
  52695. serializationObject.maxEmitPower = this.maxEmitPower;
  52696. serializationObject.minLifeTime = this.minLifeTime;
  52697. serializationObject.maxLifeTime = this.maxLifeTime;
  52698. serializationObject.emitRate = this.emitRate;
  52699. serializationObject.gravity = this.gravity.asArray();
  52700. serializationObject.color1 = this.color1.asArray();
  52701. serializationObject.color2 = this.color2.asArray();
  52702. serializationObject.colorDead = this.colorDead.asArray();
  52703. serializationObject.updateSpeed = this.updateSpeed;
  52704. serializationObject.targetStopDuration = this.targetStopDuration;
  52705. serializationObject.blendMode = this.blendMode;
  52706. // Emitter
  52707. if (this.particleEmitterType) {
  52708. serializationObject.particleEmitterType = this.particleEmitterType.serialize();
  52709. }
  52710. return serializationObject;
  52711. };
  52712. /**
  52713. * Parses a JSON object to create a GPU particle system.
  52714. * @param parsedParticleSystem The JSON object to parse
  52715. * @param scene The scene to create the particle system in
  52716. * @param rootUrl The root url to use to load external dependencies like texture
  52717. * @returns the parsed GPU particle system
  52718. */
  52719. GPUParticleSystem.Parse = function (parsedParticleSystem, scene, rootUrl) {
  52720. var name = parsedParticleSystem.name;
  52721. var particleSystem = new GPUParticleSystem(name, { capacity: parsedParticleSystem.capacity, randomTextureSize: parsedParticleSystem.randomTextureSize }, scene);
  52722. if (parsedParticleSystem.id) {
  52723. particleSystem.id = parsedParticleSystem.id;
  52724. }
  52725. // Texture
  52726. if (parsedParticleSystem.textureName) {
  52727. particleSystem.particleTexture = new BABYLON.Texture(rootUrl + parsedParticleSystem.textureName, scene);
  52728. particleSystem.particleTexture.name = parsedParticleSystem.textureName;
  52729. }
  52730. // Emitter
  52731. if (parsedParticleSystem.emitterId) {
  52732. particleSystem.emitter = scene.getLastMeshByID(parsedParticleSystem.emitterId);
  52733. }
  52734. else {
  52735. particleSystem.emitter = BABYLON.Vector3.FromArray(parsedParticleSystem.emitter);
  52736. }
  52737. // Animations
  52738. if (parsedParticleSystem.animations) {
  52739. for (var animationIndex = 0; animationIndex < parsedParticleSystem.animations.length; animationIndex++) {
  52740. var parsedAnimation = parsedParticleSystem.animations[animationIndex];
  52741. particleSystem.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  52742. }
  52743. }
  52744. // Particle system
  52745. particleSystem.activeParticleCount = parsedParticleSystem.activeParticleCount;
  52746. particleSystem.minSize = parsedParticleSystem.minSize;
  52747. particleSystem.maxSize = parsedParticleSystem.maxSize;
  52748. particleSystem.minLifeTime = parsedParticleSystem.minLifeTime;
  52749. particleSystem.maxLifeTime = parsedParticleSystem.maxLifeTime;
  52750. particleSystem.minEmitPower = parsedParticleSystem.minEmitPower;
  52751. particleSystem.maxEmitPower = parsedParticleSystem.maxEmitPower;
  52752. particleSystem.emitRate = parsedParticleSystem.emitRate;
  52753. particleSystem.gravity = BABYLON.Vector3.FromArray(parsedParticleSystem.gravity);
  52754. particleSystem.color1 = BABYLON.Color4.FromArray(parsedParticleSystem.color1);
  52755. particleSystem.color2 = BABYLON.Color4.FromArray(parsedParticleSystem.color2);
  52756. particleSystem.colorDead = BABYLON.Color4.FromArray(parsedParticleSystem.colorDead);
  52757. particleSystem.updateSpeed = parsedParticleSystem.updateSpeed;
  52758. particleSystem.targetStopDuration = parsedParticleSystem.targetStopDuration;
  52759. particleSystem.blendMode = parsedParticleSystem.blendMode;
  52760. // Emitter
  52761. if (parsedParticleSystem.particleEmitterType) {
  52762. var emitterType = void 0;
  52763. switch (parsedParticleSystem.particleEmitterType.type) {
  52764. case "SphereEmitter":
  52765. emitterType = new BABYLON.SphereParticleEmitter();
  52766. break;
  52767. case "SphereDirectedParticleEmitter":
  52768. emitterType = new BABYLON.SphereDirectedParticleEmitter();
  52769. break;
  52770. case "ConeEmitter":
  52771. emitterType = new BABYLON.ConeParticleEmitter();
  52772. break;
  52773. case "BoxEmitter":
  52774. default:
  52775. emitterType = new BABYLON.BoxParticleEmitter();
  52776. break;
  52777. }
  52778. emitterType.parse(parsedParticleSystem.particleEmitterType);
  52779. particleSystem.particleEmitterType = emitterType;
  52780. }
  52781. return particleSystem;
  52782. };
  52783. return GPUParticleSystem;
  52784. }());
  52785. BABYLON.GPUParticleSystem = GPUParticleSystem;
  52786. })(BABYLON || (BABYLON = {}));
  52787. //# sourceMappingURL=babylon.gpuParticleSystem.js.map
  52788. var BABYLON;
  52789. (function (BABYLON) {
  52790. /**
  52791. * Represents one particle of a solid particle system.
  52792. * @see SolidParticleSystem
  52793. */
  52794. var SolidParticle = /** @class */ (function () {
  52795. /**
  52796. * Creates a Solid Particle object.
  52797. * Don't create particles manually, use instead the Solid Particle System internal tools like _addParticle()
  52798. * @param particleIndex (integer) is the particle index in the Solid Particle System pool. It's also the particle identifier.
  52799. * @param positionIndex (integer) is the starting index of the particle vertices in the SPS "positions" array.
  52800. * @param indiceIndex (integer) is the starting index of the particle indices in the SPS "indices" array.
  52801. * @param model (ModelShape) is a reference to the model shape on what the particle is designed.
  52802. * @param shapeId (integer) is the model shape identifier in the SPS.
  52803. * @param idxInShape (integer) is the index of the particle in the current model (ex: the 10th box of addShape(box, 30))
  52804. * @param modelBoundingInfo is the reference to the model BoundingInfo used for intersection computations.
  52805. */
  52806. function SolidParticle(particleIndex, positionIndex, indiceIndex, model, shapeId, idxInShape, sps, modelBoundingInfo) {
  52807. if (modelBoundingInfo === void 0) { modelBoundingInfo = null; }
  52808. /**
  52809. * particle global index
  52810. */
  52811. this.idx = 0;
  52812. /**
  52813. * The color of the particle
  52814. */
  52815. this.color = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  52816. /**
  52817. * The world space position of the particle.
  52818. */
  52819. this.position = BABYLON.Vector3.Zero();
  52820. /**
  52821. * The world space rotation of the particle. (Not use if rotationQuaternion is set)
  52822. */
  52823. this.rotation = BABYLON.Vector3.Zero();
  52824. /**
  52825. * The scaling of the particle.
  52826. */
  52827. this.scaling = BABYLON.Vector3.One();
  52828. /**
  52829. * The uvs of the particle.
  52830. */
  52831. this.uvs = new BABYLON.Vector4(0.0, 0.0, 1.0, 1.0);
  52832. /**
  52833. * The current speed of the particle.
  52834. */
  52835. this.velocity = BABYLON.Vector3.Zero();
  52836. /**
  52837. * The pivot point in the particle local space.
  52838. */
  52839. this.pivot = BABYLON.Vector3.Zero();
  52840. /**
  52841. * Must the particle be translated from its pivot point in its local space ?
  52842. * In this case, the pivot point is set at the origin of the particle local space and the particle is translated.
  52843. * Default : false
  52844. */
  52845. this.translateFromPivot = false;
  52846. /**
  52847. * Is the particle active or not ?
  52848. */
  52849. this.alive = true;
  52850. /**
  52851. * Is the particle visible or not ?
  52852. */
  52853. this.isVisible = true;
  52854. /**
  52855. * Index of this particle in the global "positions" array (Internal use)
  52856. */
  52857. this._pos = 0;
  52858. /**
  52859. * Index of this particle in the global "indices" array (Internal use)
  52860. */
  52861. this._ind = 0;
  52862. /**
  52863. * ModelShape id of this particle
  52864. */
  52865. this.shapeId = 0;
  52866. /**
  52867. * Index of the particle in its shape id (Internal use)
  52868. */
  52869. this.idxInShape = 0;
  52870. /**
  52871. * Still set as invisible in order to skip useless computations (Internal use)
  52872. */
  52873. this._stillInvisible = false;
  52874. /**
  52875. * Last computed particle rotation matrix
  52876. */
  52877. this._rotationMatrix = [1.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 1.0];
  52878. /**
  52879. * Parent particle Id, if any.
  52880. * Default null.
  52881. */
  52882. this.parentId = null;
  52883. /**
  52884. * Internal global position in the SPS.
  52885. */
  52886. this._globalPosition = BABYLON.Vector3.Zero();
  52887. this.idx = particleIndex;
  52888. this._pos = positionIndex;
  52889. this._ind = indiceIndex;
  52890. this._model = model;
  52891. this.shapeId = shapeId;
  52892. this.idxInShape = idxInShape;
  52893. this._sps = sps;
  52894. if (modelBoundingInfo) {
  52895. this._modelBoundingInfo = modelBoundingInfo;
  52896. this._boundingInfo = new BABYLON.BoundingInfo(modelBoundingInfo.minimum, modelBoundingInfo.maximum);
  52897. }
  52898. }
  52899. Object.defineProperty(SolidParticle.prototype, "scale", {
  52900. /**
  52901. * Legacy support, changed scale to scaling
  52902. */
  52903. get: function () {
  52904. return this.scaling;
  52905. },
  52906. /**
  52907. * Legacy support, changed scale to scaling
  52908. */
  52909. set: function (scale) {
  52910. this.scaling = scale;
  52911. },
  52912. enumerable: true,
  52913. configurable: true
  52914. });
  52915. Object.defineProperty(SolidParticle.prototype, "quaternion", {
  52916. /**
  52917. * Legacy support, changed quaternion to rotationQuaternion
  52918. */
  52919. get: function () {
  52920. return this.rotationQuaternion;
  52921. },
  52922. /**
  52923. * Legacy support, changed quaternion to rotationQuaternion
  52924. */
  52925. set: function (q) {
  52926. this.rotationQuaternion = q;
  52927. },
  52928. enumerable: true,
  52929. configurable: true
  52930. });
  52931. /**
  52932. * Returns a boolean. True if the particle intersects another particle or another mesh, else false.
  52933. * The intersection is computed on the particle bounding sphere and Axis Aligned Bounding Box (AABB)
  52934. * @param target is the object (solid particle or mesh) what the intersection is computed against.
  52935. * @returns true if it intersects
  52936. */
  52937. SolidParticle.prototype.intersectsMesh = function (target) {
  52938. if (!this._boundingInfo || !target._boundingInfo) {
  52939. return false;
  52940. }
  52941. if (this._sps._bSphereOnly) {
  52942. return BABYLON.BoundingSphere.Intersects(this._boundingInfo.boundingSphere, target._boundingInfo.boundingSphere);
  52943. }
  52944. return this._boundingInfo.intersects(target._boundingInfo, false);
  52945. };
  52946. return SolidParticle;
  52947. }());
  52948. BABYLON.SolidParticle = SolidParticle;
  52949. /**
  52950. * Represents the shape of the model used by one particle of a solid particle system.
  52951. * SPS internal tool, don't use it manually.
  52952. * @see SolidParticleSystem
  52953. */
  52954. var ModelShape = /** @class */ (function () {
  52955. /**
  52956. * 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.
  52957. * SPS internal tool, don't use it manually.
  52958. * @ignore
  52959. */
  52960. function ModelShape(id, shape, indicesLength, shapeUV, posFunction, vtxFunction) {
  52961. /**
  52962. * length of the shape in the model indices array (internal use)
  52963. */
  52964. this._indicesLength = 0;
  52965. this.shapeID = id;
  52966. this._shape = shape;
  52967. this._indicesLength = indicesLength;
  52968. this._shapeUV = shapeUV;
  52969. this._positionFunction = posFunction;
  52970. this._vertexFunction = vtxFunction;
  52971. }
  52972. return ModelShape;
  52973. }());
  52974. BABYLON.ModelShape = ModelShape;
  52975. /**
  52976. * Represents a Depth Sorted Particle in the solid particle system.
  52977. * @see SolidParticleSystem
  52978. */
  52979. var DepthSortedParticle = /** @class */ (function () {
  52980. function DepthSortedParticle() {
  52981. /**
  52982. * Index of the particle in the "indices" array
  52983. */
  52984. this.ind = 0;
  52985. /**
  52986. * Length of the particle shape in the "indices" array
  52987. */
  52988. this.indicesLength = 0;
  52989. /**
  52990. * Squared distance from the particle to the camera
  52991. */
  52992. this.sqDistance = 0.0;
  52993. }
  52994. return DepthSortedParticle;
  52995. }());
  52996. BABYLON.DepthSortedParticle = DepthSortedParticle;
  52997. })(BABYLON || (BABYLON = {}));
  52998. //# sourceMappingURL=babylon.solidParticle.js.map
  52999. var BABYLON;
  53000. (function (BABYLON) {
  53001. /**
  53002. * The SPS is a single updatable mesh. The solid particles are simply separate parts or faces fo this big mesh.
  53003. *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.
  53004. * The SPS is also a particle system. It provides some methods to manage the particles.
  53005. * However it is behavior agnostic. This means it has no emitter, no particle physics, no particle recycler. You have to implement your own behavior.
  53006. *
  53007. * Full documentation here : http://doc.babylonjs.com/overviews/Solid_Particle_System
  53008. */
  53009. var SolidParticleSystem = /** @class */ (function () {
  53010. /**
  53011. * Creates a SPS (Solid Particle System) object.
  53012. * @param name (String) is the SPS name, this will be the underlying mesh name.
  53013. * @param scene (Scene) is the scene in which the SPS is added.
  53014. * @param updatable (optional boolean, default true) : if the SPS must be updatable or immutable.
  53015. * @param isPickable (optional boolean, default false) : if the solid particles must be pickable.
  53016. * @param enableDepthSort (optional boolean, default false) : if the solid particles must be sorted in the geometry according to their distance to the camera.
  53017. * @param particleIntersection (optional boolean, default false) : if the solid particle intersections must be computed.
  53018. * @param boundingSphereOnly (optional boolean, default false) : if the particle intersection must be computed only with the bounding sphere (no bounding box computation, so faster).
  53019. * @param bSphereRadiusFactor (optional float, default 1.0) : a number to multiply the boundind sphere radius by in order to reduce it for instance.
  53020. * @example bSphereRadiusFactor = 1.0 / Math.sqrt(3.0) => the bounding sphere exactly matches a spherical mesh.
  53021. */
  53022. function SolidParticleSystem(name, scene, options) {
  53023. /**
  53024. * The SPS array of Solid Particle objects. Just access each particle as with any classic array.
  53025. * Example : var p = SPS.particles[i];
  53026. */
  53027. this.particles = new Array();
  53028. /**
  53029. * The SPS total number of particles. Read only. Use SPS.counter instead if you need to set your own value.
  53030. */
  53031. this.nbParticles = 0;
  53032. /**
  53033. * If the particles must ever face the camera (default false). Useful for planar particles.
  53034. */
  53035. this.billboard = false;
  53036. /**
  53037. * Recompute normals when adding a shape
  53038. */
  53039. this.recomputeNormals = true;
  53040. /**
  53041. * This a counter ofr your own usage. It's not set by any SPS functions.
  53042. */
  53043. this.counter = 0;
  53044. /**
  53045. * This empty object is intended to store some SPS specific or temporary values in order to lower the Garbage Collector activity.
  53046. * Please read : http://doc.babylonjs.com/overviews/Solid_Particle_System#garbage-collector-concerns
  53047. */
  53048. this.vars = {};
  53049. /**
  53050. * If the particle intersection must be computed only with the bounding sphere (no bounding box computation, so faster). (Internal use only)
  53051. */
  53052. this._bSphereOnly = false;
  53053. /**
  53054. * A number to multiply the boundind sphere radius by in order to reduce it for instance. (Internal use only)
  53055. */
  53056. this._bSphereRadiusFactor = 1.0;
  53057. this._positions = new Array();
  53058. this._indices = new Array();
  53059. this._normals = new Array();
  53060. this._colors = new Array();
  53061. this._uvs = new Array();
  53062. this._index = 0; // indices index
  53063. this._updatable = true;
  53064. this._pickable = false;
  53065. this._isVisibilityBoxLocked = false;
  53066. this._alwaysVisible = false;
  53067. this._depthSort = false;
  53068. this._shapeCounter = 0;
  53069. this._copy = new BABYLON.SolidParticle(0, 0, 0, null, 0, 0, this);
  53070. this._color = new BABYLON.Color4(0, 0, 0, 0);
  53071. this._computeParticleColor = true;
  53072. this._computeParticleTexture = true;
  53073. this._computeParticleRotation = true;
  53074. this._computeParticleVertex = false;
  53075. this._computeBoundingBox = false;
  53076. this._depthSortParticles = true;
  53077. this._cam_axisZ = BABYLON.Vector3.Zero();
  53078. this._cam_axisY = BABYLON.Vector3.Zero();
  53079. this._cam_axisX = BABYLON.Vector3.Zero();
  53080. this._axisZ = BABYLON.Axis.Z;
  53081. this._camDir = BABYLON.Vector3.Zero();
  53082. this._camInvertedPosition = BABYLON.Vector3.Zero();
  53083. this._rotMatrix = new BABYLON.Matrix();
  53084. this._invertMatrix = new BABYLON.Matrix();
  53085. this._rotated = BABYLON.Vector3.Zero();
  53086. this._quaternion = new BABYLON.Quaternion();
  53087. this._vertex = BABYLON.Vector3.Zero();
  53088. this._normal = BABYLON.Vector3.Zero();
  53089. this._yaw = 0.0;
  53090. this._pitch = 0.0;
  53091. this._roll = 0.0;
  53092. this._halfroll = 0.0;
  53093. this._halfpitch = 0.0;
  53094. this._halfyaw = 0.0;
  53095. this._sinRoll = 0.0;
  53096. this._cosRoll = 0.0;
  53097. this._sinPitch = 0.0;
  53098. this._cosPitch = 0.0;
  53099. this._sinYaw = 0.0;
  53100. this._cosYaw = 0.0;
  53101. this._mustUnrotateFixedNormals = false;
  53102. this._minimum = BABYLON.Vector3.Zero();
  53103. this._maximum = BABYLON.Vector3.Zero();
  53104. this._minBbox = BABYLON.Vector3.Zero();
  53105. this._maxBbox = BABYLON.Vector3.Zero();
  53106. this._particlesIntersect = false;
  53107. this._depthSortFunction = function (p1, p2) {
  53108. return (p2.sqDistance - p1.sqDistance);
  53109. };
  53110. this._needs32Bits = false;
  53111. this._pivotBackTranslation = BABYLON.Vector3.Zero();
  53112. this._scaledPivot = BABYLON.Vector3.Zero();
  53113. this._particleHasParent = false;
  53114. this.name = name;
  53115. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  53116. this._camera = scene.activeCamera;
  53117. this._pickable = options ? options.isPickable : false;
  53118. this._depthSort = options ? options.enableDepthSort : false;
  53119. this._particlesIntersect = options ? options.particleIntersection : false;
  53120. this._bSphereOnly = options ? options.boundingSphereOnly : false;
  53121. this._bSphereRadiusFactor = (options && options.bSphereRadiusFactor) ? options.bSphereRadiusFactor : 1.0;
  53122. if (options && options.updatable) {
  53123. this._updatable = options.updatable;
  53124. }
  53125. else {
  53126. this._updatable = true;
  53127. }
  53128. if (this._pickable) {
  53129. this.pickedParticles = [];
  53130. }
  53131. if (this._depthSort) {
  53132. this.depthSortedParticles = [];
  53133. }
  53134. }
  53135. /**
  53136. * Builds the SPS underlying mesh. Returns a standard Mesh.
  53137. * If no model shape was added to the SPS, the returned mesh is just a single triangular plane.
  53138. * @returns the created mesh
  53139. */
  53140. SolidParticleSystem.prototype.buildMesh = function () {
  53141. if (this.nbParticles === 0) {
  53142. var triangle = BABYLON.MeshBuilder.CreateDisc("", { radius: 1, tessellation: 3 }, this._scene);
  53143. this.addShape(triangle, 1);
  53144. triangle.dispose();
  53145. }
  53146. this._indices32 = (this._needs32Bits) ? new Uint32Array(this._indices) : new Uint16Array(this._indices);
  53147. this._positions32 = new Float32Array(this._positions);
  53148. this._uvs32 = new Float32Array(this._uvs);
  53149. this._colors32 = new Float32Array(this._colors);
  53150. if (this.recomputeNormals) {
  53151. BABYLON.VertexData.ComputeNormals(this._positions32, this._indices32, this._normals);
  53152. }
  53153. this._normals32 = new Float32Array(this._normals);
  53154. this._fixedNormal32 = new Float32Array(this._normals);
  53155. if (this._mustUnrotateFixedNormals) {
  53156. this._unrotateFixedNormals();
  53157. }
  53158. var vertexData = new BABYLON.VertexData();
  53159. vertexData.indices = (this._depthSort) ? this._indices : this._indices32;
  53160. vertexData.set(this._positions32, BABYLON.VertexBuffer.PositionKind);
  53161. vertexData.set(this._normals32, BABYLON.VertexBuffer.NormalKind);
  53162. if (this._uvs32) {
  53163. vertexData.set(this._uvs32, BABYLON.VertexBuffer.UVKind);
  53164. ;
  53165. }
  53166. if (this._colors32) {
  53167. vertexData.set(this._colors32, BABYLON.VertexBuffer.ColorKind);
  53168. }
  53169. var mesh = new BABYLON.Mesh(this.name, this._scene);
  53170. vertexData.applyToMesh(mesh, this._updatable);
  53171. this.mesh = mesh;
  53172. this.mesh.isPickable = this._pickable;
  53173. // free memory
  53174. if (!this._depthSort) {
  53175. this._indices = null;
  53176. }
  53177. this._positions = null;
  53178. this._normals = null;
  53179. this._uvs = null;
  53180. this._colors = null;
  53181. if (!this._updatable) {
  53182. this.particles.length = 0;
  53183. }
  53184. return mesh;
  53185. };
  53186. /**
  53187. * Digests the mesh and generates as many solid particles in the system as wanted. Returns the SPS.
  53188. * These particles will have the same geometry than the mesh parts and will be positioned at the same localisation than the mesh original places.
  53189. * Thus the particles generated from `digest()` have their property `position` set yet.
  53190. * @param mesh ( Mesh ) is the mesh to be digested
  53191. * @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
  53192. * {delta} (optional integer, default 0) is the random extra number of facets per particle , each particle will have between `facetNb` and `facetNb + delta` facets
  53193. * {number} (optional positive integer) is the wanted number of particles : each particle is built with `mesh_total_facets / number` facets
  53194. * @returns the current SPS
  53195. */
  53196. SolidParticleSystem.prototype.digest = function (mesh, options) {
  53197. var size = (options && options.facetNb) || 1;
  53198. var number = (options && options.number) || 0;
  53199. var delta = (options && options.delta) || 0;
  53200. var meshPos = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  53201. var meshInd = mesh.getIndices();
  53202. var meshUV = mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  53203. var meshCol = mesh.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  53204. var meshNor = mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  53205. var f = 0; // facet counter
  53206. var totalFacets = meshInd.length / 3; // a facet is a triangle, so 3 indices
  53207. // compute size from number
  53208. if (number) {
  53209. number = (number > totalFacets) ? totalFacets : number;
  53210. size = Math.round(totalFacets / number);
  53211. delta = 0;
  53212. }
  53213. else {
  53214. size = (size > totalFacets) ? totalFacets : size;
  53215. }
  53216. var facetPos = []; // submesh positions
  53217. var facetInd = []; // submesh indices
  53218. var facetUV = []; // submesh UV
  53219. var facetCol = []; // submesh colors
  53220. var barycenter = BABYLON.Vector3.Zero();
  53221. var sizeO = size;
  53222. while (f < totalFacets) {
  53223. size = sizeO + Math.floor((1 + delta) * Math.random());
  53224. if (f > totalFacets - size) {
  53225. size = totalFacets - f;
  53226. }
  53227. // reset temp arrays
  53228. facetPos.length = 0;
  53229. facetInd.length = 0;
  53230. facetUV.length = 0;
  53231. facetCol.length = 0;
  53232. // iterate over "size" facets
  53233. var fi = 0;
  53234. for (var j = f * 3; j < (f + size) * 3; j++) {
  53235. facetInd.push(fi);
  53236. var i = meshInd[j];
  53237. facetPos.push(meshPos[i * 3], meshPos[i * 3 + 1], meshPos[i * 3 + 2]);
  53238. if (meshUV) {
  53239. facetUV.push(meshUV[i * 2], meshUV[i * 2 + 1]);
  53240. }
  53241. if (meshCol) {
  53242. facetCol.push(meshCol[i * 4], meshCol[i * 4 + 1], meshCol[i * 4 + 2], meshCol[i * 4 + 3]);
  53243. }
  53244. fi++;
  53245. }
  53246. // create a model shape for each single particle
  53247. var idx = this.nbParticles;
  53248. var shape = this._posToShape(facetPos);
  53249. var shapeUV = this._uvsToShapeUV(facetUV);
  53250. // compute the barycenter of the shape
  53251. var v;
  53252. for (v = 0; v < shape.length; v++) {
  53253. barycenter.addInPlace(shape[v]);
  53254. }
  53255. barycenter.scaleInPlace(1 / shape.length);
  53256. // shift the shape from its barycenter to the origin
  53257. for (v = 0; v < shape.length; v++) {
  53258. shape[v].subtractInPlace(barycenter);
  53259. }
  53260. var bInfo;
  53261. if (this._particlesIntersect) {
  53262. bInfo = new BABYLON.BoundingInfo(barycenter, barycenter);
  53263. }
  53264. var modelShape = new BABYLON.ModelShape(this._shapeCounter, shape, size * 3, shapeUV, null, null);
  53265. // add the particle in the SPS
  53266. var currentPos = this._positions.length;
  53267. var currentInd = this._indices.length;
  53268. this._meshBuilder(this._index, shape, this._positions, facetInd, this._indices, facetUV, this._uvs, facetCol, this._colors, meshNor, this._normals, idx, 0, null);
  53269. this._addParticle(idx, currentPos, currentInd, modelShape, this._shapeCounter, 0, bInfo);
  53270. // initialize the particle position
  53271. this.particles[this.nbParticles].position.addInPlace(barycenter);
  53272. this._index += shape.length;
  53273. idx++;
  53274. this.nbParticles++;
  53275. this._shapeCounter++;
  53276. f += size;
  53277. }
  53278. return this;
  53279. };
  53280. // unrotate the fixed normals in case the mesh was built with pre-rotated particles, ex : use of positionFunction in addShape()
  53281. SolidParticleSystem.prototype._unrotateFixedNormals = function () {
  53282. var index = 0;
  53283. var idx = 0;
  53284. for (var p = 0; p < this.particles.length; p++) {
  53285. this._particle = this.particles[p];
  53286. this._shape = this._particle._model._shape;
  53287. if (this._particle.rotationQuaternion) {
  53288. this._quaternion.copyFrom(this._particle.rotationQuaternion);
  53289. }
  53290. else {
  53291. this._yaw = this._particle.rotation.y;
  53292. this._pitch = this._particle.rotation.x;
  53293. this._roll = this._particle.rotation.z;
  53294. this._quaternionRotationYPR();
  53295. }
  53296. this._quaternionToRotationMatrix();
  53297. this._rotMatrix.invertToRef(this._invertMatrix);
  53298. for (var pt = 0; pt < this._shape.length; pt++) {
  53299. idx = index + pt * 3;
  53300. BABYLON.Vector3.TransformNormalFromFloatsToRef(this._normals32[idx], this._normals32[idx + 1], this._normals32[idx + 2], this._invertMatrix, this._normal);
  53301. this._fixedNormal32[idx] = this._normal.x;
  53302. this._fixedNormal32[idx + 1] = this._normal.y;
  53303. this._fixedNormal32[idx + 2] = this._normal.z;
  53304. }
  53305. index = idx + 3;
  53306. }
  53307. };
  53308. //reset copy
  53309. SolidParticleSystem.prototype._resetCopy = function () {
  53310. this._copy.position.x = 0;
  53311. this._copy.position.y = 0;
  53312. this._copy.position.z = 0;
  53313. this._copy.rotation.x = 0;
  53314. this._copy.rotation.y = 0;
  53315. this._copy.rotation.z = 0;
  53316. this._copy.rotationQuaternion = null;
  53317. this._copy.scaling.x = 1.0;
  53318. this._copy.scaling.y = 1.0;
  53319. this._copy.scaling.z = 1.0;
  53320. this._copy.uvs.x = 0;
  53321. this._copy.uvs.y = 0;
  53322. this._copy.uvs.z = 1.0;
  53323. this._copy.uvs.w = 1.0;
  53324. this._copy.color = null;
  53325. this._copy.translateFromPivot = false;
  53326. };
  53327. // _meshBuilder : inserts the shape model in the global SPS mesh
  53328. SolidParticleSystem.prototype._meshBuilder = function (p, shape, positions, meshInd, indices, meshUV, uvs, meshCol, colors, meshNor, normals, idx, idxInShape, options) {
  53329. var i;
  53330. var u = 0;
  53331. var c = 0;
  53332. var n = 0;
  53333. this._resetCopy();
  53334. if (options && options.positionFunction) {
  53335. options.positionFunction(this._copy, idx, idxInShape);
  53336. this._mustUnrotateFixedNormals = true;
  53337. }
  53338. if (this._copy.rotationQuaternion) {
  53339. this._quaternion.copyFrom(this._copy.rotationQuaternion);
  53340. }
  53341. else {
  53342. this._yaw = this._copy.rotation.y;
  53343. this._pitch = this._copy.rotation.x;
  53344. this._roll = this._copy.rotation.z;
  53345. this._quaternionRotationYPR();
  53346. }
  53347. this._quaternionToRotationMatrix();
  53348. this._scaledPivot.x = this._copy.pivot.x * this._copy.scaling.x;
  53349. this._scaledPivot.y = this._copy.pivot.y * this._copy.scaling.y;
  53350. this._scaledPivot.z = this._copy.pivot.z * this._copy.scaling.z;
  53351. if (this._copy.translateFromPivot) {
  53352. this._pivotBackTranslation.copyFromFloats(0.0, 0.0, 0.0);
  53353. }
  53354. else {
  53355. this._pivotBackTranslation.copyFrom(this._scaledPivot);
  53356. }
  53357. for (i = 0; i < shape.length; i++) {
  53358. this._vertex.x = shape[i].x;
  53359. this._vertex.y = shape[i].y;
  53360. this._vertex.z = shape[i].z;
  53361. if (options && options.vertexFunction) {
  53362. options.vertexFunction(this._copy, this._vertex, i);
  53363. }
  53364. this._vertex.x *= this._copy.scaling.x;
  53365. this._vertex.y *= this._copy.scaling.y;
  53366. this._vertex.z *= this._copy.scaling.z;
  53367. this._vertex.x -= this._scaledPivot.x;
  53368. this._vertex.y -= this._scaledPivot.y;
  53369. this._vertex.z -= this._scaledPivot.z;
  53370. BABYLON.Vector3.TransformCoordinatesToRef(this._vertex, this._rotMatrix, this._rotated);
  53371. this._rotated.addInPlace(this._pivotBackTranslation);
  53372. positions.push(this._copy.position.x + this._rotated.x, this._copy.position.y + this._rotated.y, this._copy.position.z + this._rotated.z);
  53373. if (meshUV) {
  53374. 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);
  53375. u += 2;
  53376. }
  53377. if (this._copy.color) {
  53378. this._color = this._copy.color;
  53379. }
  53380. else if (meshCol && meshCol[c] !== undefined) {
  53381. this._color.r = meshCol[c];
  53382. this._color.g = meshCol[c + 1];
  53383. this._color.b = meshCol[c + 2];
  53384. this._color.a = meshCol[c + 3];
  53385. }
  53386. else {
  53387. this._color.r = 1.0;
  53388. this._color.g = 1.0;
  53389. this._color.b = 1.0;
  53390. this._color.a = 1.0;
  53391. }
  53392. colors.push(this._color.r, this._color.g, this._color.b, this._color.a);
  53393. c += 4;
  53394. if (!this.recomputeNormals && meshNor) {
  53395. this._normal.x = meshNor[n];
  53396. this._normal.y = meshNor[n + 1];
  53397. this._normal.z = meshNor[n + 2];
  53398. BABYLON.Vector3.TransformNormalToRef(this._normal, this._rotMatrix, this._normal);
  53399. normals.push(this._normal.x, this._normal.y, this._normal.z);
  53400. n += 3;
  53401. }
  53402. }
  53403. for (i = 0; i < meshInd.length; i++) {
  53404. var current_ind = p + meshInd[i];
  53405. indices.push(current_ind);
  53406. if (current_ind > 65535) {
  53407. this._needs32Bits = true;
  53408. }
  53409. }
  53410. if (this._pickable) {
  53411. var nbfaces = meshInd.length / 3;
  53412. for (i = 0; i < nbfaces; i++) {
  53413. this.pickedParticles.push({ idx: idx, faceId: i });
  53414. }
  53415. }
  53416. if (this._depthSort) {
  53417. this.depthSortedParticles.push(new BABYLON.DepthSortedParticle());
  53418. }
  53419. return this._copy;
  53420. };
  53421. // returns a shape array from positions array
  53422. SolidParticleSystem.prototype._posToShape = function (positions) {
  53423. var shape = [];
  53424. for (var i = 0; i < positions.length; i += 3) {
  53425. shape.push(new BABYLON.Vector3(positions[i], positions[i + 1], positions[i + 2]));
  53426. }
  53427. return shape;
  53428. };
  53429. // returns a shapeUV array from a Vector4 uvs
  53430. SolidParticleSystem.prototype._uvsToShapeUV = function (uvs) {
  53431. var shapeUV = [];
  53432. if (uvs) {
  53433. for (var i = 0; i < uvs.length; i++)
  53434. shapeUV.push(uvs[i]);
  53435. }
  53436. return shapeUV;
  53437. };
  53438. // adds a new particle object in the particles array
  53439. SolidParticleSystem.prototype._addParticle = function (idx, idxpos, idxind, model, shapeId, idxInShape, bInfo) {
  53440. if (bInfo === void 0) { bInfo = null; }
  53441. var sp = new BABYLON.SolidParticle(idx, idxpos, idxind, model, shapeId, idxInShape, this, bInfo);
  53442. this.particles.push(sp);
  53443. return sp;
  53444. };
  53445. /**
  53446. * Adds some particles to the SPS from the model shape. Returns the shape id.
  53447. * Please read the doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#create-an-immutable-sps
  53448. * @param mesh is any Mesh object that will be used as a model for the solid particles.
  53449. * @param nb (positive integer) the number of particles to be created from this model
  53450. * @param options {positionFunction} is an optional javascript function to called for each particle on SPS creation.
  53451. * {vertexFunction} is an optional javascript function to called for each vertex of each particle on SPS creation
  53452. * @returns the number of shapes in the system
  53453. */
  53454. SolidParticleSystem.prototype.addShape = function (mesh, nb, options) {
  53455. var meshPos = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  53456. var meshInd = mesh.getIndices();
  53457. var meshUV = mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  53458. var meshCol = mesh.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  53459. var meshNor = mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  53460. var bbInfo;
  53461. if (this._particlesIntersect) {
  53462. bbInfo = mesh.getBoundingInfo();
  53463. }
  53464. var shape = this._posToShape(meshPos);
  53465. var shapeUV = this._uvsToShapeUV(meshUV);
  53466. var posfunc = options ? options.positionFunction : null;
  53467. var vtxfunc = options ? options.vertexFunction : null;
  53468. var modelShape = new BABYLON.ModelShape(this._shapeCounter, shape, meshInd.length, shapeUV, posfunc, vtxfunc);
  53469. // particles
  53470. var sp;
  53471. var currentCopy;
  53472. var idx = this.nbParticles;
  53473. for (var i = 0; i < nb; i++) {
  53474. var currentPos = this._positions.length;
  53475. var currentInd = this._indices.length;
  53476. currentCopy = this._meshBuilder(this._index, shape, this._positions, meshInd, this._indices, meshUV, this._uvs, meshCol, this._colors, meshNor, this._normals, idx, i, options);
  53477. if (this._updatable) {
  53478. sp = this._addParticle(idx, currentPos, currentInd, modelShape, this._shapeCounter, i, bbInfo);
  53479. sp.position.copyFrom(currentCopy.position);
  53480. sp.rotation.copyFrom(currentCopy.rotation);
  53481. if (currentCopy.rotationQuaternion && sp.rotationQuaternion) {
  53482. sp.rotationQuaternion.copyFrom(currentCopy.rotationQuaternion);
  53483. }
  53484. if (currentCopy.color && sp.color) {
  53485. sp.color.copyFrom(currentCopy.color);
  53486. }
  53487. sp.scaling.copyFrom(currentCopy.scaling);
  53488. sp.uvs.copyFrom(currentCopy.uvs);
  53489. }
  53490. this._index += shape.length;
  53491. idx++;
  53492. }
  53493. this.nbParticles += nb;
  53494. this._shapeCounter++;
  53495. return this._shapeCounter - 1;
  53496. };
  53497. // rebuilds a particle back to its just built status : if needed, recomputes the custom positions and vertices
  53498. SolidParticleSystem.prototype._rebuildParticle = function (particle) {
  53499. this._resetCopy();
  53500. if (particle._model._positionFunction) {
  53501. particle._model._positionFunction(this._copy, particle.idx, particle.idxInShape);
  53502. }
  53503. if (this._copy.rotationQuaternion) {
  53504. this._quaternion.copyFrom(this._copy.rotationQuaternion);
  53505. }
  53506. else {
  53507. this._yaw = this._copy.rotation.y;
  53508. this._pitch = this._copy.rotation.x;
  53509. this._roll = this._copy.rotation.z;
  53510. this._quaternionRotationYPR();
  53511. }
  53512. this._quaternionToRotationMatrix();
  53513. this._scaledPivot.x = this._particle.pivot.x * this._particle.scaling.x;
  53514. this._scaledPivot.y = this._particle.pivot.y * this._particle.scaling.y;
  53515. this._scaledPivot.z = this._particle.pivot.z * this._particle.scaling.z;
  53516. if (this._copy.translateFromPivot) {
  53517. this._pivotBackTranslation.copyFromFloats(0.0, 0.0, 0.0);
  53518. }
  53519. else {
  53520. this._pivotBackTranslation.copyFrom(this._scaledPivot);
  53521. }
  53522. this._shape = particle._model._shape;
  53523. for (var pt = 0; pt < this._shape.length; pt++) {
  53524. this._vertex.x = this._shape[pt].x;
  53525. this._vertex.y = this._shape[pt].y;
  53526. this._vertex.z = this._shape[pt].z;
  53527. if (particle._model._vertexFunction) {
  53528. particle._model._vertexFunction(this._copy, this._vertex, pt); // recall to stored vertexFunction
  53529. }
  53530. this._vertex.x *= this._copy.scaling.x;
  53531. this._vertex.y *= this._copy.scaling.y;
  53532. this._vertex.z *= this._copy.scaling.z;
  53533. this._vertex.x -= this._scaledPivot.x;
  53534. this._vertex.y -= this._scaledPivot.y;
  53535. this._vertex.z -= this._scaledPivot.z;
  53536. BABYLON.Vector3.TransformCoordinatesToRef(this._vertex, this._rotMatrix, this._rotated);
  53537. this._rotated.addInPlace(this._pivotBackTranslation);
  53538. this._positions32[particle._pos + pt * 3] = this._copy.position.x + this._rotated.x;
  53539. this._positions32[particle._pos + pt * 3 + 1] = this._copy.position.y + this._rotated.y;
  53540. this._positions32[particle._pos + pt * 3 + 2] = this._copy.position.z + this._rotated.z;
  53541. }
  53542. particle.position.x = 0.0;
  53543. particle.position.y = 0.0;
  53544. particle.position.z = 0.0;
  53545. particle.rotation.x = 0.0;
  53546. particle.rotation.y = 0.0;
  53547. particle.rotation.z = 0.0;
  53548. particle.rotationQuaternion = null;
  53549. particle.scaling.x = 1.0;
  53550. particle.scaling.y = 1.0;
  53551. particle.scaling.z = 1.0;
  53552. particle.uvs.x = 0.0;
  53553. particle.uvs.y = 0.0;
  53554. particle.uvs.z = 1.0;
  53555. particle.uvs.w = 1.0;
  53556. particle.pivot.x = 0.0;
  53557. particle.pivot.y = 0.0;
  53558. particle.pivot.z = 0.0;
  53559. particle.translateFromPivot = false;
  53560. particle.parentId = null;
  53561. };
  53562. /**
  53563. * Rebuilds the whole mesh and updates the VBO : custom positions and vertices are recomputed if needed.
  53564. * @returns the SPS.
  53565. */
  53566. SolidParticleSystem.prototype.rebuildMesh = function () {
  53567. for (var p = 0; p < this.particles.length; p++) {
  53568. this._rebuildParticle(this.particles[p]);
  53569. }
  53570. this.mesh.updateVerticesData(BABYLON.VertexBuffer.PositionKind, this._positions32, false, false);
  53571. return this;
  53572. };
  53573. /**
  53574. * Sets all the particles : this method actually really updates the mesh according to the particle positions, rotations, colors, textures, etc.
  53575. * This method calls `updateParticle()` for each particle of the SPS.
  53576. * For an animated SPS, it is usually called within the render loop.
  53577. * @param start The particle index in the particle array where to start to compute the particle property values _(default 0)_
  53578. * @param end The particle index in the particle array where to stop to compute the particle property values _(default nbParticle - 1)_
  53579. * @param update If the mesh must be finally updated on this call after all the particle computations _(default true)_
  53580. * @returns the SPS.
  53581. */
  53582. SolidParticleSystem.prototype.setParticles = function (start, end, update) {
  53583. if (start === void 0) { start = 0; }
  53584. if (end === void 0) { end = this.nbParticles - 1; }
  53585. if (update === void 0) { update = true; }
  53586. if (!this._updatable) {
  53587. return this;
  53588. }
  53589. // custom beforeUpdate
  53590. this.beforeUpdateParticles(start, end, update);
  53591. this._cam_axisX.x = 1.0;
  53592. this._cam_axisX.y = 0.0;
  53593. this._cam_axisX.z = 0.0;
  53594. this._cam_axisY.x = 0.0;
  53595. this._cam_axisY.y = 1.0;
  53596. this._cam_axisY.z = 0.0;
  53597. this._cam_axisZ.x = 0.0;
  53598. this._cam_axisZ.y = 0.0;
  53599. this._cam_axisZ.z = 1.0;
  53600. // cases when the World Matrix is to be computed first
  53601. if (this.billboard || this._depthSort) {
  53602. this.mesh.computeWorldMatrix(true);
  53603. this.mesh._worldMatrix.invertToRef(this._invertMatrix);
  53604. }
  53605. // if the particles will always face the camera
  53606. if (this.billboard) {
  53607. // compute the camera position and un-rotate it by the current mesh rotation
  53608. this._camera.getDirectionToRef(this._axisZ, this._camDir);
  53609. BABYLON.Vector3.TransformNormalToRef(this._camDir, this._invertMatrix, this._cam_axisZ);
  53610. this._cam_axisZ.normalize();
  53611. // same for camera up vector extracted from the cam view matrix
  53612. var view = this._camera.getViewMatrix(true);
  53613. BABYLON.Vector3.TransformNormalFromFloatsToRef(view.m[1], view.m[5], view.m[9], this._invertMatrix, this._cam_axisY);
  53614. BABYLON.Vector3.CrossToRef(this._cam_axisY, this._cam_axisZ, this._cam_axisX);
  53615. this._cam_axisY.normalize();
  53616. this._cam_axisX.normalize();
  53617. }
  53618. // if depthSort, compute the camera global position in the mesh local system
  53619. if (this._depthSort) {
  53620. BABYLON.Vector3.TransformCoordinatesToRef(this._camera.globalPosition, this._invertMatrix, this._camInvertedPosition); // then un-rotate the camera
  53621. }
  53622. BABYLON.Matrix.IdentityToRef(this._rotMatrix);
  53623. var idx = 0; // current position index in the global array positions32
  53624. var index = 0; // position start index in the global array positions32 of the current particle
  53625. var colidx = 0; // current color index in the global array colors32
  53626. var colorIndex = 0; // color start index in the global array colors32 of the current particle
  53627. var uvidx = 0; // current uv index in the global array uvs32
  53628. var uvIndex = 0; // uv start index in the global array uvs32 of the current particle
  53629. var pt = 0; // current index in the particle model shape
  53630. if (this.mesh.isFacetDataEnabled) {
  53631. this._computeBoundingBox = true;
  53632. }
  53633. end = (end >= this.nbParticles) ? this.nbParticles - 1 : end;
  53634. if (this._computeBoundingBox) {
  53635. if (start == 0 && end == this.nbParticles - 1) {
  53636. BABYLON.Vector3.FromFloatsToRef(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, this._minimum);
  53637. BABYLON.Vector3.FromFloatsToRef(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE, this._maximum);
  53638. }
  53639. else {
  53640. if (this.mesh._boundingInfo) {
  53641. this._minimum.copyFrom(this.mesh._boundingInfo.boundingBox.minimum);
  53642. this._maximum.copyFrom(this.mesh._boundingInfo.boundingBox.maximum);
  53643. }
  53644. }
  53645. }
  53646. // particle loop
  53647. index = this.particles[start]._pos;
  53648. var vpos = (index / 3) | 0;
  53649. colorIndex = vpos * 4;
  53650. uvIndex = vpos * 2;
  53651. for (var p = start; p <= end; p++) {
  53652. this._particle = this.particles[p];
  53653. this._shape = this._particle._model._shape;
  53654. this._shapeUV = this._particle._model._shapeUV;
  53655. // call to custom user function to update the particle properties
  53656. this.updateParticle(this._particle);
  53657. // camera-particle distance for depth sorting
  53658. if (this._depthSort && this._depthSortParticles) {
  53659. var dsp = this.depthSortedParticles[p];
  53660. dsp.ind = this._particle._ind;
  53661. dsp.indicesLength = this._particle._model._indicesLength;
  53662. dsp.sqDistance = BABYLON.Vector3.DistanceSquared(this._particle.position, this._camInvertedPosition);
  53663. }
  53664. // skip the computations for inactive or already invisible particles
  53665. if (!this._particle.alive || (this._particle._stillInvisible && !this._particle.isVisible)) {
  53666. // increment indexes for the next particle
  53667. pt = this._shape.length;
  53668. index += pt * 3;
  53669. colorIndex += pt * 4;
  53670. uvIndex += pt * 2;
  53671. continue;
  53672. }
  53673. if (this._particle.isVisible) {
  53674. this._particle._stillInvisible = false; // un-mark permanent invisibility
  53675. this._particleHasParent = (this._particle.parentId !== null);
  53676. this._scaledPivot.x = this._particle.pivot.x * this._particle.scaling.x;
  53677. this._scaledPivot.y = this._particle.pivot.y * this._particle.scaling.y;
  53678. this._scaledPivot.z = this._particle.pivot.z * this._particle.scaling.z;
  53679. // particle rotation matrix
  53680. if (this.billboard) {
  53681. this._particle.rotation.x = 0.0;
  53682. this._particle.rotation.y = 0.0;
  53683. }
  53684. if (this._computeParticleRotation || this.billboard) {
  53685. if (this._particle.rotationQuaternion) {
  53686. this._quaternion.copyFrom(this._particle.rotationQuaternion);
  53687. }
  53688. else {
  53689. this._yaw = this._particle.rotation.y;
  53690. this._pitch = this._particle.rotation.x;
  53691. this._roll = this._particle.rotation.z;
  53692. this._quaternionRotationYPR();
  53693. }
  53694. this._quaternionToRotationMatrix();
  53695. }
  53696. if (this._particleHasParent) {
  53697. this._parent = this.particles[this._particle.parentId];
  53698. 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];
  53699. 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];
  53700. 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];
  53701. this._particle._globalPosition.x = this._parent._globalPosition.x + this._rotated.x;
  53702. this._particle._globalPosition.y = this._parent._globalPosition.y + this._rotated.y;
  53703. this._particle._globalPosition.z = this._parent._globalPosition.z + this._rotated.z;
  53704. if (this._computeParticleRotation || this.billboard) {
  53705. 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];
  53706. 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];
  53707. 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];
  53708. 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];
  53709. 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];
  53710. 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];
  53711. 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];
  53712. 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];
  53713. 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];
  53714. }
  53715. }
  53716. else {
  53717. this._particle._globalPosition.x = this._particle.position.x;
  53718. this._particle._globalPosition.y = this._particle.position.y;
  53719. this._particle._globalPosition.z = this._particle.position.z;
  53720. if (this._computeParticleRotation || this.billboard) {
  53721. this._particle._rotationMatrix[0] = this._rotMatrix.m[0];
  53722. this._particle._rotationMatrix[1] = this._rotMatrix.m[1];
  53723. this._particle._rotationMatrix[2] = this._rotMatrix.m[2];
  53724. this._particle._rotationMatrix[3] = this._rotMatrix.m[4];
  53725. this._particle._rotationMatrix[4] = this._rotMatrix.m[5];
  53726. this._particle._rotationMatrix[5] = this._rotMatrix.m[6];
  53727. this._particle._rotationMatrix[6] = this._rotMatrix.m[8];
  53728. this._particle._rotationMatrix[7] = this._rotMatrix.m[9];
  53729. this._particle._rotationMatrix[8] = this._rotMatrix.m[10];
  53730. }
  53731. }
  53732. if (this._particle.translateFromPivot) {
  53733. this._pivotBackTranslation.x = 0.0;
  53734. this._pivotBackTranslation.y = 0.0;
  53735. this._pivotBackTranslation.z = 0.0;
  53736. }
  53737. else {
  53738. this._pivotBackTranslation.x = this._scaledPivot.x;
  53739. this._pivotBackTranslation.y = this._scaledPivot.y;
  53740. this._pivotBackTranslation.z = this._scaledPivot.z;
  53741. }
  53742. // particle vertex loop
  53743. for (pt = 0; pt < this._shape.length; pt++) {
  53744. idx = index + pt * 3;
  53745. colidx = colorIndex + pt * 4;
  53746. uvidx = uvIndex + pt * 2;
  53747. this._vertex.x = this._shape[pt].x;
  53748. this._vertex.y = this._shape[pt].y;
  53749. this._vertex.z = this._shape[pt].z;
  53750. if (this._computeParticleVertex) {
  53751. this.updateParticleVertex(this._particle, this._vertex, pt);
  53752. }
  53753. // positions
  53754. this._vertex.x *= this._particle.scaling.x;
  53755. this._vertex.y *= this._particle.scaling.y;
  53756. this._vertex.z *= this._particle.scaling.z;
  53757. this._vertex.x -= this._scaledPivot.x;
  53758. this._vertex.y -= this._scaledPivot.y;
  53759. this._vertex.z -= this._scaledPivot.z;
  53760. this._rotated.x = this._vertex.x * this._particle._rotationMatrix[0] + this._vertex.y * this._particle._rotationMatrix[3] + this._vertex.z * this._particle._rotationMatrix[6];
  53761. this._rotated.y = this._vertex.x * this._particle._rotationMatrix[1] + this._vertex.y * this._particle._rotationMatrix[4] + this._vertex.z * this._particle._rotationMatrix[7];
  53762. this._rotated.z = this._vertex.x * this._particle._rotationMatrix[2] + this._vertex.y * this._particle._rotationMatrix[5] + this._vertex.z * this._particle._rotationMatrix[8];
  53763. this._rotated.x += this._pivotBackTranslation.x;
  53764. this._rotated.y += this._pivotBackTranslation.y;
  53765. this._rotated.z += this._pivotBackTranslation.z;
  53766. 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;
  53767. 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;
  53768. 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;
  53769. if (this._computeBoundingBox) {
  53770. if (this._positions32[idx] < this._minimum.x) {
  53771. this._minimum.x = this._positions32[idx];
  53772. }
  53773. if (this._positions32[idx] > this._maximum.x) {
  53774. this._maximum.x = this._positions32[idx];
  53775. }
  53776. if (this._positions32[idx + 1] < this._minimum.y) {
  53777. this._minimum.y = this._positions32[idx + 1];
  53778. }
  53779. if (this._positions32[idx + 1] > this._maximum.y) {
  53780. this._maximum.y = this._positions32[idx + 1];
  53781. }
  53782. if (this._positions32[idx + 2] < this._minimum.z) {
  53783. this._minimum.z = this._positions32[idx + 2];
  53784. }
  53785. if (this._positions32[idx + 2] > this._maximum.z) {
  53786. this._maximum.z = this._positions32[idx + 2];
  53787. }
  53788. }
  53789. // normals : if the particles can't be morphed then just rotate the normals, what is much more faster than ComputeNormals()
  53790. if (!this._computeParticleVertex) {
  53791. this._normal.x = this._fixedNormal32[idx];
  53792. this._normal.y = this._fixedNormal32[idx + 1];
  53793. this._normal.z = this._fixedNormal32[idx + 2];
  53794. this._rotated.x = this._normal.x * this._particle._rotationMatrix[0] + this._normal.y * this._particle._rotationMatrix[3] + this._normal.z * this._particle._rotationMatrix[6];
  53795. this._rotated.y = this._normal.x * this._particle._rotationMatrix[1] + this._normal.y * this._particle._rotationMatrix[4] + this._normal.z * this._particle._rotationMatrix[7];
  53796. this._rotated.z = this._normal.x * this._particle._rotationMatrix[2] + this._normal.y * this._particle._rotationMatrix[5] + this._normal.z * this._particle._rotationMatrix[8];
  53797. this._normals32[idx] = this._cam_axisX.x * this._rotated.x + this._cam_axisY.x * this._rotated.y + this._cam_axisZ.x * this._rotated.z;
  53798. 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;
  53799. 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;
  53800. }
  53801. if (this._computeParticleColor && this._particle.color) {
  53802. this._colors32[colidx] = this._particle.color.r;
  53803. this._colors32[colidx + 1] = this._particle.color.g;
  53804. this._colors32[colidx + 2] = this._particle.color.b;
  53805. this._colors32[colidx + 3] = this._particle.color.a;
  53806. }
  53807. if (this._computeParticleTexture) {
  53808. this._uvs32[uvidx] = this._shapeUV[pt * 2] * (this._particle.uvs.z - this._particle.uvs.x) + this._particle.uvs.x;
  53809. this._uvs32[uvidx + 1] = this._shapeUV[pt * 2 + 1] * (this._particle.uvs.w - this._particle.uvs.y) + this._particle.uvs.y;
  53810. }
  53811. }
  53812. }
  53813. else {
  53814. this._particle._stillInvisible = true; // mark the particle as invisible
  53815. for (pt = 0; pt < this._shape.length; pt++) {
  53816. idx = index + pt * 3;
  53817. colidx = colorIndex + pt * 4;
  53818. uvidx = uvIndex + pt * 2;
  53819. this._positions32[idx] = 0.0;
  53820. this._positions32[idx + 1] = 0.0;
  53821. this._positions32[idx + 2] = 0.0;
  53822. this._normals32[idx] = 0.0;
  53823. this._normals32[idx + 1] = 0.0;
  53824. this._normals32[idx + 2] = 0.0;
  53825. if (this._computeParticleColor && this._particle.color) {
  53826. this._colors32[colidx] = this._particle.color.r;
  53827. this._colors32[colidx + 1] = this._particle.color.g;
  53828. this._colors32[colidx + 2] = this._particle.color.b;
  53829. this._colors32[colidx + 3] = this._particle.color.a;
  53830. }
  53831. if (this._computeParticleTexture) {
  53832. this._uvs32[uvidx] = this._shapeUV[pt * 2] * (this._particle.uvs.z - this._particle.uvs.x) + this._particle.uvs.x;
  53833. this._uvs32[uvidx + 1] = this._shapeUV[pt * 2 + 1] * (this._particle.uvs.w - this._particle.uvs.y) + this._particle.uvs.y;
  53834. }
  53835. }
  53836. }
  53837. // if the particle intersections must be computed : update the bbInfo
  53838. if (this._particlesIntersect) {
  53839. var bInfo = this._particle._boundingInfo;
  53840. var bBox = bInfo.boundingBox;
  53841. var bSphere = bInfo.boundingSphere;
  53842. if (!this._bSphereOnly) {
  53843. // place, scale and rotate the particle bbox within the SPS local system, then update it
  53844. for (var b = 0; b < bBox.vectors.length; b++) {
  53845. this._vertex.x = this._particle._modelBoundingInfo.boundingBox.vectors[b].x * this._particle.scaling.x;
  53846. this._vertex.y = this._particle._modelBoundingInfo.boundingBox.vectors[b].y * this._particle.scaling.y;
  53847. this._vertex.z = this._particle._modelBoundingInfo.boundingBox.vectors[b].z * this._particle.scaling.z;
  53848. this._rotated.x = this._vertex.x * this._particle._rotationMatrix[0] + this._vertex.y * this._particle._rotationMatrix[3] + this._vertex.z * this._particle._rotationMatrix[6];
  53849. this._rotated.y = this._vertex.x * this._particle._rotationMatrix[1] + this._vertex.y * this._particle._rotationMatrix[4] + this._vertex.z * this._particle._rotationMatrix[7];
  53850. this._rotated.z = this._vertex.x * this._particle._rotationMatrix[2] + this._vertex.y * this._particle._rotationMatrix[5] + this._vertex.z * this._particle._rotationMatrix[8];
  53851. 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;
  53852. 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;
  53853. 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;
  53854. }
  53855. bBox._update(this.mesh._worldMatrix);
  53856. }
  53857. // place and scale the particle bouding sphere in the SPS local system, then update it
  53858. this._minBbox.x = this._particle._modelBoundingInfo.minimum.x * this._particle.scaling.x;
  53859. this._minBbox.y = this._particle._modelBoundingInfo.minimum.y * this._particle.scaling.y;
  53860. this._minBbox.z = this._particle._modelBoundingInfo.minimum.z * this._particle.scaling.z;
  53861. this._maxBbox.x = this._particle._modelBoundingInfo.maximum.x * this._particle.scaling.x;
  53862. this._maxBbox.y = this._particle._modelBoundingInfo.maximum.y * this._particle.scaling.y;
  53863. this._maxBbox.z = this._particle._modelBoundingInfo.maximum.z * this._particle.scaling.z;
  53864. bSphere.center.x = this._particle._globalPosition.x + (this._minBbox.x + this._maxBbox.x) * 0.5;
  53865. bSphere.center.y = this._particle._globalPosition.y + (this._minBbox.y + this._maxBbox.y) * 0.5;
  53866. bSphere.center.z = this._particle._globalPosition.z + (this._minBbox.z + this._maxBbox.z) * 0.5;
  53867. 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));
  53868. bSphere._update(this.mesh._worldMatrix);
  53869. }
  53870. // increment indexes for the next particle
  53871. index = idx + 3;
  53872. colorIndex = colidx + 4;
  53873. uvIndex = uvidx + 2;
  53874. }
  53875. // if the VBO must be updated
  53876. if (update) {
  53877. if (this._computeParticleColor) {
  53878. this.mesh.updateVerticesData(BABYLON.VertexBuffer.ColorKind, this._colors32, false, false);
  53879. }
  53880. if (this._computeParticleTexture) {
  53881. this.mesh.updateVerticesData(BABYLON.VertexBuffer.UVKind, this._uvs32, false, false);
  53882. }
  53883. this.mesh.updateVerticesData(BABYLON.VertexBuffer.PositionKind, this._positions32, false, false);
  53884. if (!this.mesh.areNormalsFrozen || this.mesh.isFacetDataEnabled) {
  53885. if (this._computeParticleVertex || this.mesh.isFacetDataEnabled) {
  53886. // recompute the normals only if the particles can be morphed, update then also the normal reference array _fixedNormal32[]
  53887. var params = this.mesh.isFacetDataEnabled ? this.mesh.getFacetDataParameters() : null;
  53888. BABYLON.VertexData.ComputeNormals(this._positions32, this._indices32, this._normals32, params);
  53889. for (var i = 0; i < this._normals32.length; i++) {
  53890. this._fixedNormal32[i] = this._normals32[i];
  53891. }
  53892. }
  53893. if (!this.mesh.areNormalsFrozen) {
  53894. this.mesh.updateVerticesData(BABYLON.VertexBuffer.NormalKind, this._normals32, false, false);
  53895. }
  53896. }
  53897. if (this._depthSort && this._depthSortParticles) {
  53898. this.depthSortedParticles.sort(this._depthSortFunction);
  53899. var dspl = this.depthSortedParticles.length;
  53900. var sorted = 0;
  53901. var lind = 0;
  53902. var sind = 0;
  53903. var sid = 0;
  53904. for (sorted = 0; sorted < dspl; sorted++) {
  53905. lind = this.depthSortedParticles[sorted].indicesLength;
  53906. sind = this.depthSortedParticles[sorted].ind;
  53907. for (var i = 0; i < lind; i++) {
  53908. this._indices32[sid] = this._indices[sind + i];
  53909. sid++;
  53910. }
  53911. }
  53912. this.mesh.updateIndices(this._indices32);
  53913. }
  53914. }
  53915. if (this._computeBoundingBox) {
  53916. this.mesh._boundingInfo = new BABYLON.BoundingInfo(this._minimum, this._maximum);
  53917. this.mesh._boundingInfo.update(this.mesh._worldMatrix);
  53918. }
  53919. this.afterUpdateParticles(start, end, update);
  53920. return this;
  53921. };
  53922. SolidParticleSystem.prototype._quaternionRotationYPR = function () {
  53923. this._halfroll = this._roll * 0.5;
  53924. this._halfpitch = this._pitch * 0.5;
  53925. this._halfyaw = this._yaw * 0.5;
  53926. this._sinRoll = Math.sin(this._halfroll);
  53927. this._cosRoll = Math.cos(this._halfroll);
  53928. this._sinPitch = Math.sin(this._halfpitch);
  53929. this._cosPitch = Math.cos(this._halfpitch);
  53930. this._sinYaw = Math.sin(this._halfyaw);
  53931. this._cosYaw = Math.cos(this._halfyaw);
  53932. this._quaternion.x = this._cosYaw * this._sinPitch * this._cosRoll + this._sinYaw * this._cosPitch * this._sinRoll;
  53933. this._quaternion.y = this._sinYaw * this._cosPitch * this._cosRoll - this._cosYaw * this._sinPitch * this._sinRoll;
  53934. this._quaternion.z = this._cosYaw * this._cosPitch * this._sinRoll - this._sinYaw * this._sinPitch * this._cosRoll;
  53935. this._quaternion.w = this._cosYaw * this._cosPitch * this._cosRoll + this._sinYaw * this._sinPitch * this._sinRoll;
  53936. };
  53937. SolidParticleSystem.prototype._quaternionToRotationMatrix = function () {
  53938. this._rotMatrix.m[0] = 1.0 - (2.0 * (this._quaternion.y * this._quaternion.y + this._quaternion.z * this._quaternion.z));
  53939. this._rotMatrix.m[1] = 2.0 * (this._quaternion.x * this._quaternion.y + this._quaternion.z * this._quaternion.w);
  53940. this._rotMatrix.m[2] = 2.0 * (this._quaternion.z * this._quaternion.x - this._quaternion.y * this._quaternion.w);
  53941. this._rotMatrix.m[3] = 0;
  53942. this._rotMatrix.m[4] = 2.0 * (this._quaternion.x * this._quaternion.y - this._quaternion.z * this._quaternion.w);
  53943. this._rotMatrix.m[5] = 1.0 - (2.0 * (this._quaternion.z * this._quaternion.z + this._quaternion.x * this._quaternion.x));
  53944. this._rotMatrix.m[6] = 2.0 * (this._quaternion.y * this._quaternion.z + this._quaternion.x * this._quaternion.w);
  53945. this._rotMatrix.m[7] = 0;
  53946. this._rotMatrix.m[8] = 2.0 * (this._quaternion.z * this._quaternion.x + this._quaternion.y * this._quaternion.w);
  53947. this._rotMatrix.m[9] = 2.0 * (this._quaternion.y * this._quaternion.z - this._quaternion.x * this._quaternion.w);
  53948. this._rotMatrix.m[10] = 1.0 - (2.0 * (this._quaternion.y * this._quaternion.y + this._quaternion.x * this._quaternion.x));
  53949. this._rotMatrix.m[11] = 0;
  53950. this._rotMatrix.m[12] = 0;
  53951. this._rotMatrix.m[13] = 0;
  53952. this._rotMatrix.m[14] = 0;
  53953. this._rotMatrix.m[15] = 1.0;
  53954. };
  53955. /**
  53956. * Disposes the SPS.
  53957. */
  53958. SolidParticleSystem.prototype.dispose = function () {
  53959. this.mesh.dispose();
  53960. this.vars = null;
  53961. // drop references to internal big arrays for the GC
  53962. this._positions = null;
  53963. this._indices = null;
  53964. this._normals = null;
  53965. this._uvs = null;
  53966. this._colors = null;
  53967. this._indices32 = null;
  53968. this._positions32 = null;
  53969. this._normals32 = null;
  53970. this._fixedNormal32 = null;
  53971. this._uvs32 = null;
  53972. this._colors32 = null;
  53973. this.pickedParticles = null;
  53974. };
  53975. /**
  53976. * Visibilty helper : Recomputes the visible size according to the mesh bounding box
  53977. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  53978. * @returns the SPS.
  53979. */
  53980. SolidParticleSystem.prototype.refreshVisibleSize = function () {
  53981. if (!this._isVisibilityBoxLocked) {
  53982. this.mesh.refreshBoundingInfo();
  53983. }
  53984. return this;
  53985. };
  53986. /**
  53987. * Visibility helper : Sets the size of a visibility box, this sets the underlying mesh bounding box.
  53988. * @param size the size (float) of the visibility box
  53989. * note : this doesn't lock the SPS mesh bounding box.
  53990. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  53991. */
  53992. SolidParticleSystem.prototype.setVisibilityBox = function (size) {
  53993. var vis = size / 2;
  53994. this.mesh._boundingInfo = new BABYLON.BoundingInfo(new BABYLON.Vector3(-vis, -vis, -vis), new BABYLON.Vector3(vis, vis, vis));
  53995. };
  53996. Object.defineProperty(SolidParticleSystem.prototype, "isAlwaysVisible", {
  53997. /**
  53998. * Gets whether the SPS as always visible or not
  53999. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  54000. */
  54001. get: function () {
  54002. return this._alwaysVisible;
  54003. },
  54004. /**
  54005. * Sets the SPS as always visible or not
  54006. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  54007. */
  54008. set: function (val) {
  54009. this._alwaysVisible = val;
  54010. this.mesh.alwaysSelectAsActiveMesh = val;
  54011. },
  54012. enumerable: true,
  54013. configurable: true
  54014. });
  54015. Object.defineProperty(SolidParticleSystem.prototype, "isVisibilityBoxLocked", {
  54016. /**
  54017. * Gets if the SPS visibility box as locked or not. This enables/disables the underlying mesh bounding box updates.
  54018. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  54019. */
  54020. get: function () {
  54021. return this._isVisibilityBoxLocked;
  54022. },
  54023. /**
  54024. * Sets the SPS visibility box as locked or not. This enables/disables the underlying mesh bounding box updates.
  54025. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  54026. */
  54027. set: function (val) {
  54028. this._isVisibilityBoxLocked = val;
  54029. var boundingInfo = this.mesh.getBoundingInfo();
  54030. boundingInfo.isLocked = val;
  54031. },
  54032. enumerable: true,
  54033. configurable: true
  54034. });
  54035. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleRotation", {
  54036. /**
  54037. * Gets if `setParticles()` computes the particle rotations or not.
  54038. * Default value : true. The SPS is faster when it's set to false.
  54039. * Note : the particle rotations aren't stored values, so setting `computeParticleRotation` to false will prevents the particle to rotate.
  54040. */
  54041. get: function () {
  54042. return this._computeParticleRotation;
  54043. },
  54044. /**
  54045. * Tells to `setParticles()` to compute the particle rotations or not.
  54046. * Default value : true. The SPS is faster when it's set to false.
  54047. * Note : the particle rotations aren't stored values, so setting `computeParticleRotation` to false will prevents the particle to rotate.
  54048. */
  54049. set: function (val) {
  54050. this._computeParticleRotation = val;
  54051. },
  54052. enumerable: true,
  54053. configurable: true
  54054. });
  54055. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleColor", {
  54056. /**
  54057. * Gets if `setParticles()` computes the particle colors or not.
  54058. * Default value : true. The SPS is faster when it's set to false.
  54059. * Note : the particle colors are stored values, so setting `computeParticleColor` to false will keep yet the last colors set.
  54060. */
  54061. get: function () {
  54062. return this._computeParticleColor;
  54063. },
  54064. /**
  54065. * Tells to `setParticles()` to compute the particle colors or not.
  54066. * Default value : true. The SPS is faster when it's set to false.
  54067. * Note : the particle colors are stored values, so setting `computeParticleColor` to false will keep yet the last colors set.
  54068. */
  54069. set: function (val) {
  54070. this._computeParticleColor = val;
  54071. },
  54072. enumerable: true,
  54073. configurable: true
  54074. });
  54075. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleTexture", {
  54076. /**
  54077. * Gets if `setParticles()` computes the particle textures or not.
  54078. * Default value : true. The SPS is faster when it's set to false.
  54079. * Note : the particle textures are stored values, so setting `computeParticleTexture` to false will keep yet the last colors set.
  54080. */
  54081. get: function () {
  54082. return this._computeParticleTexture;
  54083. },
  54084. set: function (val) {
  54085. this._computeParticleTexture = val;
  54086. },
  54087. enumerable: true,
  54088. configurable: true
  54089. });
  54090. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleVertex", {
  54091. /**
  54092. * Gets if `setParticles()` calls the vertex function for each vertex of each particle, or not.
  54093. * Default value : false. The SPS is faster when it's set to false.
  54094. * Note : the particle custom vertex positions aren't stored values.
  54095. */
  54096. get: function () {
  54097. return this._computeParticleVertex;
  54098. },
  54099. /**
  54100. * Tells to `setParticles()` to call the vertex function for each vertex of each particle, or not.
  54101. * Default value : false. The SPS is faster when it's set to false.
  54102. * Note : the particle custom vertex positions aren't stored values.
  54103. */
  54104. set: function (val) {
  54105. this._computeParticleVertex = val;
  54106. },
  54107. enumerable: true,
  54108. configurable: true
  54109. });
  54110. Object.defineProperty(SolidParticleSystem.prototype, "computeBoundingBox", {
  54111. /**
  54112. * Gets if `setParticles()` computes or not the mesh bounding box when computing the particle positions.
  54113. */
  54114. get: function () {
  54115. return this._computeBoundingBox;
  54116. },
  54117. /**
  54118. * Tells to `setParticles()` to compute or not the mesh bounding box when computing the particle positions.
  54119. */
  54120. set: function (val) {
  54121. this._computeBoundingBox = val;
  54122. },
  54123. enumerable: true,
  54124. configurable: true
  54125. });
  54126. Object.defineProperty(SolidParticleSystem.prototype, "depthSortParticles", {
  54127. /**
  54128. * Gets if `setParticles()` sorts or not the distance between each particle and the camera.
  54129. * Skipped when `enableDepthSort` is set to `false` (default) at construction time.
  54130. * Default : `true`
  54131. */
  54132. get: function () {
  54133. return this._depthSortParticles;
  54134. },
  54135. /**
  54136. * Tells to `setParticles()` to sort or not the distance between each particle and the camera.
  54137. * Skipped when `enableDepthSort` is set to `false` (default) at construction time.
  54138. * Default : `true`
  54139. */
  54140. set: function (val) {
  54141. this._depthSortParticles = val;
  54142. },
  54143. enumerable: true,
  54144. configurable: true
  54145. });
  54146. // =======================================================================
  54147. // Particle behavior logic
  54148. // these following methods may be overwritten by the user to fit his needs
  54149. /**
  54150. * This function does nothing. It may be overwritten to set all the particle first values.
  54151. * The SPS doesn't call this function, you may have to call it by your own.
  54152. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#particle-management
  54153. */
  54154. SolidParticleSystem.prototype.initParticles = function () {
  54155. };
  54156. /**
  54157. * This function does nothing. It may be overwritten to recycle a particle.
  54158. * The SPS doesn't call this function, you may have to call it by your own.
  54159. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#particle-management
  54160. * @param particle The particle to recycle
  54161. * @returns the recycled particle
  54162. */
  54163. SolidParticleSystem.prototype.recycleParticle = function (particle) {
  54164. return particle;
  54165. };
  54166. /**
  54167. * Updates a particle : this function should be overwritten by the user.
  54168. * It is called on each particle by `setParticles()`. This is the place to code each particle behavior.
  54169. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#particle-management
  54170. * @example : just set a particle position or velocity and recycle conditions
  54171. * @param particle The particle to update
  54172. * @returns the updated particle
  54173. */
  54174. SolidParticleSystem.prototype.updateParticle = function (particle) {
  54175. return particle;
  54176. };
  54177. /**
  54178. * Updates a vertex of a particle : it can be overwritten by the user.
  54179. * This will be called on each vertex particle by `setParticles()` if `computeParticleVertex` is set to true only.
  54180. * @param particle the current particle
  54181. * @param vertex the current index of the current particle
  54182. * @param pt the index of the current vertex in the particle shape
  54183. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#update-each-particle-shape
  54184. * @example : just set a vertex particle position
  54185. * @returns the updated vertex
  54186. */
  54187. SolidParticleSystem.prototype.updateParticleVertex = function (particle, vertex, pt) {
  54188. return vertex;
  54189. };
  54190. /**
  54191. * This will be called before any other treatment by `setParticles()` and will be passed three parameters.
  54192. * This does nothing and may be overwritten by the user.
  54193. * @param start the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  54194. * @param stop the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  54195. * @param update the boolean update value actually passed to setParticles()
  54196. */
  54197. SolidParticleSystem.prototype.beforeUpdateParticles = function (start, stop, update) {
  54198. };
  54199. /**
  54200. * This will be called by `setParticles()` after all the other treatments and just before the actual mesh update.
  54201. * This will be passed three parameters.
  54202. * This does nothing and may be overwritten by the user.
  54203. * @param start the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  54204. * @param stop the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  54205. * @param update the boolean update value actually passed to setParticles()
  54206. */
  54207. SolidParticleSystem.prototype.afterUpdateParticles = function (start, stop, update) {
  54208. };
  54209. return SolidParticleSystem;
  54210. }());
  54211. BABYLON.SolidParticleSystem = SolidParticleSystem;
  54212. })(BABYLON || (BABYLON = {}));
  54213. //# sourceMappingURL=babylon.solidParticleSystem.js.map
  54214. var BABYLON;
  54215. (function (BABYLON) {
  54216. var ShaderMaterial = /** @class */ (function (_super) {
  54217. __extends(ShaderMaterial, _super);
  54218. function ShaderMaterial(name, scene, shaderPath, options) {
  54219. var _this = _super.call(this, name, scene) || this;
  54220. _this._textures = {};
  54221. _this._textureArrays = {};
  54222. _this._floats = {};
  54223. _this._ints = {};
  54224. _this._floatsArrays = {};
  54225. _this._colors3 = {};
  54226. _this._colors3Arrays = {};
  54227. _this._colors4 = {};
  54228. _this._vectors2 = {};
  54229. _this._vectors3 = {};
  54230. _this._vectors4 = {};
  54231. _this._matrices = {};
  54232. _this._matrices3x3 = {};
  54233. _this._matrices2x2 = {};
  54234. _this._vectors2Arrays = {};
  54235. _this._vectors3Arrays = {};
  54236. _this._cachedWorldViewMatrix = new BABYLON.Matrix();
  54237. _this._shaderPath = shaderPath;
  54238. options.needAlphaBlending = options.needAlphaBlending || false;
  54239. options.needAlphaTesting = options.needAlphaTesting || false;
  54240. options.attributes = options.attributes || ["position", "normal", "uv"];
  54241. options.uniforms = options.uniforms || ["worldViewProjection"];
  54242. options.uniformBuffers = options.uniformBuffers || [];
  54243. options.samplers = options.samplers || [];
  54244. options.defines = options.defines || [];
  54245. _this._options = options;
  54246. return _this;
  54247. }
  54248. ShaderMaterial.prototype.getClassName = function () {
  54249. return "ShaderMaterial";
  54250. };
  54251. ShaderMaterial.prototype.needAlphaBlending = function () {
  54252. return this._options.needAlphaBlending;
  54253. };
  54254. ShaderMaterial.prototype.needAlphaTesting = function () {
  54255. return this._options.needAlphaTesting;
  54256. };
  54257. ShaderMaterial.prototype._checkUniform = function (uniformName) {
  54258. if (this._options.uniforms.indexOf(uniformName) === -1) {
  54259. this._options.uniforms.push(uniformName);
  54260. }
  54261. };
  54262. ShaderMaterial.prototype.setTexture = function (name, texture) {
  54263. if (this._options.samplers.indexOf(name) === -1) {
  54264. this._options.samplers.push(name);
  54265. }
  54266. this._textures[name] = texture;
  54267. return this;
  54268. };
  54269. ShaderMaterial.prototype.setTextureArray = function (name, textures) {
  54270. if (this._options.samplers.indexOf(name) === -1) {
  54271. this._options.samplers.push(name);
  54272. }
  54273. this._checkUniform(name);
  54274. this._textureArrays[name] = textures;
  54275. return this;
  54276. };
  54277. ShaderMaterial.prototype.setFloat = function (name, value) {
  54278. this._checkUniform(name);
  54279. this._floats[name] = value;
  54280. return this;
  54281. };
  54282. ShaderMaterial.prototype.setInt = function (name, value) {
  54283. this._checkUniform(name);
  54284. this._ints[name] = value;
  54285. return this;
  54286. };
  54287. ShaderMaterial.prototype.setFloats = function (name, value) {
  54288. this._checkUniform(name);
  54289. this._floatsArrays[name] = value;
  54290. return this;
  54291. };
  54292. ShaderMaterial.prototype.setColor3 = function (name, value) {
  54293. this._checkUniform(name);
  54294. this._colors3[name] = value;
  54295. return this;
  54296. };
  54297. ShaderMaterial.prototype.setColor3Array = function (name, value) {
  54298. this._checkUniform(name);
  54299. this._colors3Arrays[name] = value.reduce(function (arr, color) {
  54300. color.toArray(arr, arr.length);
  54301. return arr;
  54302. }, []);
  54303. return this;
  54304. };
  54305. ShaderMaterial.prototype.setColor4 = function (name, value) {
  54306. this._checkUniform(name);
  54307. this._colors4[name] = value;
  54308. return this;
  54309. };
  54310. ShaderMaterial.prototype.setVector2 = function (name, value) {
  54311. this._checkUniform(name);
  54312. this._vectors2[name] = value;
  54313. return this;
  54314. };
  54315. ShaderMaterial.prototype.setVector3 = function (name, value) {
  54316. this._checkUniform(name);
  54317. this._vectors3[name] = value;
  54318. return this;
  54319. };
  54320. ShaderMaterial.prototype.setVector4 = function (name, value) {
  54321. this._checkUniform(name);
  54322. this._vectors4[name] = value;
  54323. return this;
  54324. };
  54325. ShaderMaterial.prototype.setMatrix = function (name, value) {
  54326. this._checkUniform(name);
  54327. this._matrices[name] = value;
  54328. return this;
  54329. };
  54330. ShaderMaterial.prototype.setMatrix3x3 = function (name, value) {
  54331. this._checkUniform(name);
  54332. this._matrices3x3[name] = value;
  54333. return this;
  54334. };
  54335. ShaderMaterial.prototype.setMatrix2x2 = function (name, value) {
  54336. this._checkUniform(name);
  54337. this._matrices2x2[name] = value;
  54338. return this;
  54339. };
  54340. ShaderMaterial.prototype.setArray2 = function (name, value) {
  54341. this._checkUniform(name);
  54342. this._vectors2Arrays[name] = value;
  54343. return this;
  54344. };
  54345. ShaderMaterial.prototype.setArray3 = function (name, value) {
  54346. this._checkUniform(name);
  54347. this._vectors3Arrays[name] = value;
  54348. return this;
  54349. };
  54350. ShaderMaterial.prototype._checkCache = function (scene, mesh, useInstances) {
  54351. if (!mesh) {
  54352. return true;
  54353. }
  54354. if (this._effect && (this._effect.defines.indexOf("#define INSTANCES") !== -1) !== useInstances) {
  54355. return false;
  54356. }
  54357. return false;
  54358. };
  54359. ShaderMaterial.prototype.isReady = function (mesh, useInstances) {
  54360. var scene = this.getScene();
  54361. var engine = scene.getEngine();
  54362. if (!this.checkReadyOnEveryCall) {
  54363. if (this._renderId === scene.getRenderId()) {
  54364. if (this._checkCache(scene, mesh, useInstances)) {
  54365. return true;
  54366. }
  54367. }
  54368. }
  54369. // Instances
  54370. var defines = [];
  54371. var attribs = [];
  54372. var fallbacks = new BABYLON.EffectFallbacks();
  54373. if (useInstances) {
  54374. defines.push("#define INSTANCES");
  54375. }
  54376. for (var index = 0; index < this._options.defines.length; index++) {
  54377. defines.push(this._options.defines[index]);
  54378. }
  54379. for (var index = 0; index < this._options.attributes.length; index++) {
  54380. attribs.push(this._options.attributes[index]);
  54381. }
  54382. if (mesh && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  54383. attribs.push(BABYLON.VertexBuffer.ColorKind);
  54384. defines.push("#define VERTEXCOLOR");
  54385. }
  54386. // Bones
  54387. if (mesh && mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  54388. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  54389. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  54390. if (mesh.numBoneInfluencers > 4) {
  54391. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  54392. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  54393. }
  54394. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  54395. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  54396. fallbacks.addCPUSkinningFallback(0, mesh);
  54397. if (this._options.uniforms.indexOf("mBones") === -1) {
  54398. this._options.uniforms.push("mBones");
  54399. }
  54400. }
  54401. else {
  54402. defines.push("#define NUM_BONE_INFLUENCERS 0");
  54403. }
  54404. // Textures
  54405. for (var name in this._textures) {
  54406. if (!this._textures[name].isReady()) {
  54407. return false;
  54408. }
  54409. }
  54410. // Alpha test
  54411. if (mesh && this._shouldTurnAlphaTestOn(mesh)) {
  54412. defines.push("#define ALPHATEST");
  54413. }
  54414. var previousEffect = this._effect;
  54415. var join = defines.join("\n");
  54416. this._effect = engine.createEffect(this._shaderPath, {
  54417. attributes: attribs,
  54418. uniformsNames: this._options.uniforms,
  54419. uniformBuffersNames: this._options.uniformBuffers,
  54420. samplers: this._options.samplers,
  54421. defines: join,
  54422. fallbacks: fallbacks,
  54423. onCompiled: this.onCompiled,
  54424. onError: this.onError
  54425. }, engine);
  54426. if (!this._effect.isReady()) {
  54427. return false;
  54428. }
  54429. if (previousEffect !== this._effect) {
  54430. scene.resetCachedMaterial();
  54431. }
  54432. this._renderId = scene.getRenderId();
  54433. return true;
  54434. };
  54435. ShaderMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  54436. var scene = this.getScene();
  54437. if (!this._effect) {
  54438. return;
  54439. }
  54440. if (this._options.uniforms.indexOf("world") !== -1) {
  54441. this._effect.setMatrix("world", world);
  54442. }
  54443. if (this._options.uniforms.indexOf("worldView") !== -1) {
  54444. world.multiplyToRef(scene.getViewMatrix(), this._cachedWorldViewMatrix);
  54445. this._effect.setMatrix("worldView", this._cachedWorldViewMatrix);
  54446. }
  54447. if (this._options.uniforms.indexOf("worldViewProjection") !== -1) {
  54448. this._effect.setMatrix("worldViewProjection", world.multiply(scene.getTransformMatrix()));
  54449. }
  54450. };
  54451. ShaderMaterial.prototype.bind = function (world, mesh) {
  54452. // Std values
  54453. this.bindOnlyWorldMatrix(world);
  54454. if (this._effect && this.getScene().getCachedMaterial() !== this) {
  54455. if (this._options.uniforms.indexOf("view") !== -1) {
  54456. this._effect.setMatrix("view", this.getScene().getViewMatrix());
  54457. }
  54458. if (this._options.uniforms.indexOf("projection") !== -1) {
  54459. this._effect.setMatrix("projection", this.getScene().getProjectionMatrix());
  54460. }
  54461. if (this._options.uniforms.indexOf("viewProjection") !== -1) {
  54462. this._effect.setMatrix("viewProjection", this.getScene().getTransformMatrix());
  54463. }
  54464. // Bones
  54465. BABYLON.MaterialHelper.BindBonesParameters(mesh, this._effect);
  54466. var name;
  54467. // Texture
  54468. for (name in this._textures) {
  54469. this._effect.setTexture(name, this._textures[name]);
  54470. }
  54471. // Texture arrays
  54472. for (name in this._textureArrays) {
  54473. this._effect.setTextureArray(name, this._textureArrays[name]);
  54474. }
  54475. // Int
  54476. for (name in this._ints) {
  54477. this._effect.setInt(name, this._ints[name]);
  54478. }
  54479. // Float
  54480. for (name in this._floats) {
  54481. this._effect.setFloat(name, this._floats[name]);
  54482. }
  54483. // Floats
  54484. for (name in this._floatsArrays) {
  54485. this._effect.setArray(name, this._floatsArrays[name]);
  54486. }
  54487. // Color3
  54488. for (name in this._colors3) {
  54489. this._effect.setColor3(name, this._colors3[name]);
  54490. }
  54491. for (name in this._colors3Arrays) {
  54492. this._effect.setArray3(name, this._colors3Arrays[name]);
  54493. }
  54494. // Color4
  54495. for (name in this._colors4) {
  54496. var color = this._colors4[name];
  54497. this._effect.setFloat4(name, color.r, color.g, color.b, color.a);
  54498. }
  54499. // Vector2
  54500. for (name in this._vectors2) {
  54501. this._effect.setVector2(name, this._vectors2[name]);
  54502. }
  54503. // Vector3
  54504. for (name in this._vectors3) {
  54505. this._effect.setVector3(name, this._vectors3[name]);
  54506. }
  54507. // Vector4
  54508. for (name in this._vectors4) {
  54509. this._effect.setVector4(name, this._vectors4[name]);
  54510. }
  54511. // Matrix
  54512. for (name in this._matrices) {
  54513. this._effect.setMatrix(name, this._matrices[name]);
  54514. }
  54515. // Matrix 3x3
  54516. for (name in this._matrices3x3) {
  54517. this._effect.setMatrix3x3(name, this._matrices3x3[name]);
  54518. }
  54519. // Matrix 2x2
  54520. for (name in this._matrices2x2) {
  54521. this._effect.setMatrix2x2(name, this._matrices2x2[name]);
  54522. }
  54523. // Vector2Array
  54524. for (name in this._vectors2Arrays) {
  54525. this._effect.setArray2(name, this._vectors2Arrays[name]);
  54526. }
  54527. // Vector3Array
  54528. for (name in this._vectors3Arrays) {
  54529. this._effect.setArray3(name, this._vectors3Arrays[name]);
  54530. }
  54531. }
  54532. this._afterBind(mesh);
  54533. };
  54534. ShaderMaterial.prototype.getActiveTextures = function () {
  54535. var activeTextures = _super.prototype.getActiveTextures.call(this);
  54536. for (var name in this._textures) {
  54537. activeTextures.push(this._textures[name]);
  54538. }
  54539. for (var name in this._textureArrays) {
  54540. var array = this._textureArrays[name];
  54541. for (var index = 0; index < array.length; index++) {
  54542. activeTextures.push(array[index]);
  54543. }
  54544. }
  54545. return activeTextures;
  54546. };
  54547. ShaderMaterial.prototype.hasTexture = function (texture) {
  54548. if (_super.prototype.hasTexture.call(this, texture)) {
  54549. return true;
  54550. }
  54551. for (var name in this._textures) {
  54552. if (this._textures[name] === texture) {
  54553. return true;
  54554. }
  54555. }
  54556. for (var name in this._textureArrays) {
  54557. var array = this._textureArrays[name];
  54558. for (var index = 0; index < array.length; index++) {
  54559. if (array[index] === texture) {
  54560. return true;
  54561. }
  54562. }
  54563. }
  54564. return false;
  54565. };
  54566. ShaderMaterial.prototype.clone = function (name) {
  54567. var newShaderMaterial = new ShaderMaterial(name, this.getScene(), this._shaderPath, this._options);
  54568. return newShaderMaterial;
  54569. };
  54570. ShaderMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  54571. if (forceDisposeTextures) {
  54572. var name;
  54573. for (name in this._textures) {
  54574. this._textures[name].dispose();
  54575. }
  54576. for (name in this._textureArrays) {
  54577. var array = this._textureArrays[name];
  54578. for (var index = 0; index < array.length; index++) {
  54579. array[index].dispose();
  54580. }
  54581. }
  54582. }
  54583. this._textures = {};
  54584. _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);
  54585. };
  54586. ShaderMaterial.prototype.serialize = function () {
  54587. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  54588. serializationObject.customType = "BABYLON.ShaderMaterial";
  54589. serializationObject.options = this._options;
  54590. serializationObject.shaderPath = this._shaderPath;
  54591. var name;
  54592. // Texture
  54593. serializationObject.textures = {};
  54594. for (name in this._textures) {
  54595. serializationObject.textures[name] = this._textures[name].serialize();
  54596. }
  54597. // Texture arrays
  54598. serializationObject.textureArrays = {};
  54599. for (name in this._textureArrays) {
  54600. serializationObject.textureArrays[name] = [];
  54601. var array = this._textureArrays[name];
  54602. for (var index = 0; index < array.length; index++) {
  54603. serializationObject.textureArrays[name].push(array[index].serialize());
  54604. }
  54605. }
  54606. // Float
  54607. serializationObject.floats = {};
  54608. for (name in this._floats) {
  54609. serializationObject.floats[name] = this._floats[name];
  54610. }
  54611. // Float s
  54612. serializationObject.FloatArrays = {};
  54613. for (name in this._floatsArrays) {
  54614. serializationObject.FloatArrays[name] = this._floatsArrays[name];
  54615. }
  54616. // Color3
  54617. serializationObject.colors3 = {};
  54618. for (name in this._colors3) {
  54619. serializationObject.colors3[name] = this._colors3[name].asArray();
  54620. }
  54621. // Color3 array
  54622. serializationObject.colors3Arrays = {};
  54623. for (name in this._colors3Arrays) {
  54624. serializationObject.colors3Arrays[name] = this._colors3Arrays[name];
  54625. }
  54626. // Color4
  54627. serializationObject.colors4 = {};
  54628. for (name in this._colors4) {
  54629. serializationObject.colors4[name] = this._colors4[name].asArray();
  54630. }
  54631. // Vector2
  54632. serializationObject.vectors2 = {};
  54633. for (name in this._vectors2) {
  54634. serializationObject.vectors2[name] = this._vectors2[name].asArray();
  54635. }
  54636. // Vector3
  54637. serializationObject.vectors3 = {};
  54638. for (name in this._vectors3) {
  54639. serializationObject.vectors3[name] = this._vectors3[name].asArray();
  54640. }
  54641. // Vector4
  54642. serializationObject.vectors4 = {};
  54643. for (name in this._vectors4) {
  54644. serializationObject.vectors4[name] = this._vectors4[name].asArray();
  54645. }
  54646. // Matrix
  54647. serializationObject.matrices = {};
  54648. for (name in this._matrices) {
  54649. serializationObject.matrices[name] = this._matrices[name].asArray();
  54650. }
  54651. // Matrix 3x3
  54652. serializationObject.matrices3x3 = {};
  54653. for (name in this._matrices3x3) {
  54654. serializationObject.matrices3x3[name] = this._matrices3x3[name];
  54655. }
  54656. // Matrix 2x2
  54657. serializationObject.matrices2x2 = {};
  54658. for (name in this._matrices2x2) {
  54659. serializationObject.matrices2x2[name] = this._matrices2x2[name];
  54660. }
  54661. // Vector2Array
  54662. serializationObject.vectors2Arrays = {};
  54663. for (name in this._vectors2Arrays) {
  54664. serializationObject.vectors2Arrays[name] = this._vectors2Arrays[name];
  54665. }
  54666. // Vector3Array
  54667. serializationObject.vectors3Arrays = {};
  54668. for (name in this._vectors3Arrays) {
  54669. serializationObject.vectors3Arrays[name] = this._vectors3Arrays[name];
  54670. }
  54671. return serializationObject;
  54672. };
  54673. ShaderMaterial.Parse = function (source, scene, rootUrl) {
  54674. var material = BABYLON.SerializationHelper.Parse(function () { return new ShaderMaterial(source.name, scene, source.shaderPath, source.options); }, source, scene, rootUrl);
  54675. var name;
  54676. // Texture
  54677. for (name in source.textures) {
  54678. material.setTexture(name, BABYLON.Texture.Parse(source.textures[name], scene, rootUrl));
  54679. }
  54680. // Texture arrays
  54681. for (name in source.textureArrays) {
  54682. var array = source.textureArrays[name];
  54683. var textureArray = new Array();
  54684. for (var index = 0; index < array.length; index++) {
  54685. textureArray.push(BABYLON.Texture.Parse(array[index], scene, rootUrl));
  54686. }
  54687. material.setTextureArray(name, textureArray);
  54688. }
  54689. // Float
  54690. for (name in source.floats) {
  54691. material.setFloat(name, source.floats[name]);
  54692. }
  54693. // Float s
  54694. for (name in source.floatsArrays) {
  54695. material.setFloats(name, source.floatsArrays[name]);
  54696. }
  54697. // Color3
  54698. for (name in source.colors3) {
  54699. material.setColor3(name, BABYLON.Color3.FromArray(source.colors3[name]));
  54700. }
  54701. // Color3 arrays
  54702. for (name in source.colors3Arrays) {
  54703. var colors = source.colors3Arrays[name].reduce(function (arr, num, i) {
  54704. if (i % 3 === 0) {
  54705. arr.push([num]);
  54706. }
  54707. else {
  54708. arr[arr.length - 1].push(num);
  54709. }
  54710. return arr;
  54711. }, []).map(function (color) { return BABYLON.Color3.FromArray(color); });
  54712. material.setColor3Array(name, colors);
  54713. }
  54714. // Color4
  54715. for (name in source.colors4) {
  54716. material.setColor4(name, BABYLON.Color4.FromArray(source.colors4[name]));
  54717. }
  54718. // Vector2
  54719. for (name in source.vectors2) {
  54720. material.setVector2(name, BABYLON.Vector2.FromArray(source.vectors2[name]));
  54721. }
  54722. // Vector3
  54723. for (name in source.vectors3) {
  54724. material.setVector3(name, BABYLON.Vector3.FromArray(source.vectors3[name]));
  54725. }
  54726. // Vector4
  54727. for (name in source.vectors4) {
  54728. material.setVector4(name, BABYLON.Vector4.FromArray(source.vectors4[name]));
  54729. }
  54730. // Matrix
  54731. for (name in source.matrices) {
  54732. material.setMatrix(name, BABYLON.Matrix.FromArray(source.matrices[name]));
  54733. }
  54734. // Matrix 3x3
  54735. for (name in source.matrices3x3) {
  54736. material.setMatrix3x3(name, source.matrices3x3[name]);
  54737. }
  54738. // Matrix 2x2
  54739. for (name in source.matrices2x2) {
  54740. material.setMatrix2x2(name, source.matrices2x2[name]);
  54741. }
  54742. // Vector2Array
  54743. for (name in source.vectors2Arrays) {
  54744. material.setArray2(name, source.vectors2Arrays[name]);
  54745. }
  54746. // Vector3Array
  54747. for (name in source.vectors3Arrays) {
  54748. material.setArray3(name, source.vectors3Arrays[name]);
  54749. }
  54750. return material;
  54751. };
  54752. return ShaderMaterial;
  54753. }(BABYLON.Material));
  54754. BABYLON.ShaderMaterial = ShaderMaterial;
  54755. })(BABYLON || (BABYLON = {}));
  54756. //# sourceMappingURL=babylon.shaderMaterial.js.map
  54757. var BABYLON;
  54758. (function (BABYLON) {
  54759. var GroundMesh = /** @class */ (function (_super) {
  54760. __extends(GroundMesh, _super);
  54761. function GroundMesh(name, scene) {
  54762. var _this = _super.call(this, name, scene) || this;
  54763. _this.generateOctree = false;
  54764. return _this;
  54765. }
  54766. GroundMesh.prototype.getClassName = function () {
  54767. return "GroundMesh";
  54768. };
  54769. Object.defineProperty(GroundMesh.prototype, "subdivisions", {
  54770. get: function () {
  54771. return Math.min(this._subdivisionsX, this._subdivisionsY);
  54772. },
  54773. enumerable: true,
  54774. configurable: true
  54775. });
  54776. Object.defineProperty(GroundMesh.prototype, "subdivisionsX", {
  54777. get: function () {
  54778. return this._subdivisionsX;
  54779. },
  54780. enumerable: true,
  54781. configurable: true
  54782. });
  54783. Object.defineProperty(GroundMesh.prototype, "subdivisionsY", {
  54784. get: function () {
  54785. return this._subdivisionsY;
  54786. },
  54787. enumerable: true,
  54788. configurable: true
  54789. });
  54790. GroundMesh.prototype.optimize = function (chunksCount, octreeBlocksSize) {
  54791. if (octreeBlocksSize === void 0) { octreeBlocksSize = 32; }
  54792. this._subdivisionsX = chunksCount;
  54793. this._subdivisionsY = chunksCount;
  54794. this.subdivide(chunksCount);
  54795. this.createOrUpdateSubmeshesOctree(octreeBlocksSize);
  54796. };
  54797. /**
  54798. * Returns a height (y) value in the Worl system :
  54799. * the ground altitude at the coordinates (x, z) expressed in the World system.
  54800. * Returns the ground y position if (x, z) are outside the ground surface.
  54801. */
  54802. GroundMesh.prototype.getHeightAtCoordinates = function (x, z) {
  54803. var world = this.getWorldMatrix();
  54804. var invMat = BABYLON.Tmp.Matrix[5];
  54805. world.invertToRef(invMat);
  54806. var tmpVect = BABYLON.Tmp.Vector3[8];
  54807. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, 0.0, z, invMat, tmpVect); // transform x,z in the mesh local space
  54808. x = tmpVect.x;
  54809. z = tmpVect.z;
  54810. if (x < this._minX || x > this._maxX || z < this._minZ || z > this._maxZ) {
  54811. return this.position.y;
  54812. }
  54813. if (!this._heightQuads || this._heightQuads.length == 0) {
  54814. this._initHeightQuads();
  54815. this._computeHeightQuads();
  54816. }
  54817. var facet = this._getFacetAt(x, z);
  54818. var y = -(facet.x * x + facet.z * z + facet.w) / facet.y;
  54819. // return y in the World system
  54820. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(0.0, y, 0.0, world, tmpVect);
  54821. return tmpVect.y;
  54822. };
  54823. /**
  54824. * Returns a normalized vector (Vector3) orthogonal to the ground
  54825. * at the ground coordinates (x, z) expressed in the World system.
  54826. * Returns Vector3(0.0, 1.0, 0.0) if (x, z) are outside the ground surface.
  54827. */
  54828. GroundMesh.prototype.getNormalAtCoordinates = function (x, z) {
  54829. var normal = new BABYLON.Vector3(0.0, 1.0, 0.0);
  54830. this.getNormalAtCoordinatesToRef(x, z, normal);
  54831. return normal;
  54832. };
  54833. /**
  54834. * Updates the Vector3 passed a reference with a normalized vector orthogonal to the ground
  54835. * at the ground coordinates (x, z) expressed in the World system.
  54836. * Doesn't uptade the reference Vector3 if (x, z) are outside the ground surface.
  54837. * Returns the GroundMesh.
  54838. */
  54839. GroundMesh.prototype.getNormalAtCoordinatesToRef = function (x, z, ref) {
  54840. var world = this.getWorldMatrix();
  54841. var tmpMat = BABYLON.Tmp.Matrix[5];
  54842. world.invertToRef(tmpMat);
  54843. var tmpVect = BABYLON.Tmp.Vector3[8];
  54844. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, 0.0, z, tmpMat, tmpVect); // transform x,z in the mesh local space
  54845. x = tmpVect.x;
  54846. z = tmpVect.z;
  54847. if (x < this._minX || x > this._maxX || z < this._minZ || z > this._maxZ) {
  54848. return this;
  54849. }
  54850. if (!this._heightQuads || this._heightQuads.length == 0) {
  54851. this._initHeightQuads();
  54852. this._computeHeightQuads();
  54853. }
  54854. var facet = this._getFacetAt(x, z);
  54855. BABYLON.Vector3.TransformNormalFromFloatsToRef(facet.x, facet.y, facet.z, world, ref);
  54856. return this;
  54857. };
  54858. /**
  54859. * Force the heights to be recomputed for getHeightAtCoordinates() or getNormalAtCoordinates()
  54860. * if the ground has been updated.
  54861. * This can be used in the render loop.
  54862. * Returns the GroundMesh.
  54863. */
  54864. GroundMesh.prototype.updateCoordinateHeights = function () {
  54865. if (!this._heightQuads || this._heightQuads.length == 0) {
  54866. this._initHeightQuads();
  54867. }
  54868. this._computeHeightQuads();
  54869. return this;
  54870. };
  54871. // Returns the element "facet" from the heightQuads array relative to (x, z) local coordinates
  54872. GroundMesh.prototype._getFacetAt = function (x, z) {
  54873. // retrieve col and row from x, z coordinates in the ground local system
  54874. var col = Math.floor((x + this._maxX) * this._subdivisionsX / this._width);
  54875. var row = Math.floor(-(z + this._maxZ) * this._subdivisionsY / this._height + this._subdivisionsY);
  54876. var quad = this._heightQuads[row * this._subdivisionsX + col];
  54877. var facet;
  54878. if (z < quad.slope.x * x + quad.slope.y) {
  54879. facet = quad.facet1;
  54880. }
  54881. else {
  54882. facet = quad.facet2;
  54883. }
  54884. return facet;
  54885. };
  54886. // Creates and populates the heightMap array with "facet" elements :
  54887. // a quad is two triangular facets separated by a slope, so a "facet" element is 1 slope + 2 facets
  54888. // slope : Vector2(c, h) = 2D diagonal line equation setting appart two triangular facets in a quad : z = cx + h
  54889. // facet1 : Vector4(a, b, c, d) = first facet 3D plane equation : ax + by + cz + d = 0
  54890. // facet2 : Vector4(a, b, c, d) = second facet 3D plane equation : ax + by + cz + d = 0
  54891. // Returns the GroundMesh.
  54892. GroundMesh.prototype._initHeightQuads = function () {
  54893. var subdivisionsX = this._subdivisionsX;
  54894. var subdivisionsY = this._subdivisionsY;
  54895. this._heightQuads = new Array();
  54896. for (var row = 0; row < subdivisionsY; row++) {
  54897. for (var col = 0; col < subdivisionsX; col++) {
  54898. 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) };
  54899. this._heightQuads[row * subdivisionsX + col] = quad;
  54900. }
  54901. }
  54902. return this;
  54903. };
  54904. // Compute each quad element values and update the the heightMap array :
  54905. // slope : Vector2(c, h) = 2D diagonal line equation setting appart two triangular facets in a quad : z = cx + h
  54906. // facet1 : Vector4(a, b, c, d) = first facet 3D plane equation : ax + by + cz + d = 0
  54907. // facet2 : Vector4(a, b, c, d) = second facet 3D plane equation : ax + by + cz + d = 0
  54908. // Returns the GroundMesh.
  54909. GroundMesh.prototype._computeHeightQuads = function () {
  54910. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  54911. if (!positions) {
  54912. return this;
  54913. }
  54914. var v1 = BABYLON.Tmp.Vector3[3];
  54915. var v2 = BABYLON.Tmp.Vector3[2];
  54916. var v3 = BABYLON.Tmp.Vector3[1];
  54917. var v4 = BABYLON.Tmp.Vector3[0];
  54918. var v1v2 = BABYLON.Tmp.Vector3[4];
  54919. var v1v3 = BABYLON.Tmp.Vector3[5];
  54920. var v1v4 = BABYLON.Tmp.Vector3[6];
  54921. var norm1 = BABYLON.Tmp.Vector3[7];
  54922. var norm2 = BABYLON.Tmp.Vector3[8];
  54923. var i = 0;
  54924. var j = 0;
  54925. var k = 0;
  54926. var cd = 0; // 2D slope coefficient : z = cd * x + h
  54927. var h = 0;
  54928. var d1 = 0; // facet plane equation : ax + by + cz + d = 0
  54929. var d2 = 0;
  54930. var subdivisionsX = this._subdivisionsX;
  54931. var subdivisionsY = this._subdivisionsY;
  54932. for (var row = 0; row < subdivisionsY; row++) {
  54933. for (var col = 0; col < subdivisionsX; col++) {
  54934. i = col * 3;
  54935. j = row * (subdivisionsX + 1) * 3;
  54936. k = (row + 1) * (subdivisionsX + 1) * 3;
  54937. v1.x = positions[j + i];
  54938. v1.y = positions[j + i + 1];
  54939. v1.z = positions[j + i + 2];
  54940. v2.x = positions[j + i + 3];
  54941. v2.y = positions[j + i + 4];
  54942. v2.z = positions[j + i + 5];
  54943. v3.x = positions[k + i];
  54944. v3.y = positions[k + i + 1];
  54945. v3.z = positions[k + i + 2];
  54946. v4.x = positions[k + i + 3];
  54947. v4.y = positions[k + i + 4];
  54948. v4.z = positions[k + i + 5];
  54949. // 2D slope V1V4
  54950. cd = (v4.z - v1.z) / (v4.x - v1.x);
  54951. h = v1.z - cd * v1.x; // v1 belongs to the slope
  54952. // facet equations :
  54953. // we compute each facet normal vector
  54954. // the equation of the facet plane is : norm.x * x + norm.y * y + norm.z * z + d = 0
  54955. // we compute the value d by applying the equation to v1 which belongs to the plane
  54956. // then we store the facet equation in a Vector4
  54957. v2.subtractToRef(v1, v1v2);
  54958. v3.subtractToRef(v1, v1v3);
  54959. v4.subtractToRef(v1, v1v4);
  54960. BABYLON.Vector3.CrossToRef(v1v4, v1v3, norm1); // caution : CrossToRef uses the Tmp class
  54961. BABYLON.Vector3.CrossToRef(v1v2, v1v4, norm2);
  54962. norm1.normalize();
  54963. norm2.normalize();
  54964. d1 = -(norm1.x * v1.x + norm1.y * v1.y + norm1.z * v1.z);
  54965. d2 = -(norm2.x * v2.x + norm2.y * v2.y + norm2.z * v2.z);
  54966. var quad = this._heightQuads[row * subdivisionsX + col];
  54967. quad.slope.copyFromFloats(cd, h);
  54968. quad.facet1.copyFromFloats(norm1.x, norm1.y, norm1.z, d1);
  54969. quad.facet2.copyFromFloats(norm2.x, norm2.y, norm2.z, d2);
  54970. }
  54971. }
  54972. return this;
  54973. };
  54974. GroundMesh.prototype.serialize = function (serializationObject) {
  54975. _super.prototype.serialize.call(this, serializationObject);
  54976. serializationObject.subdivisionsX = this._subdivisionsX;
  54977. serializationObject.subdivisionsY = this._subdivisionsY;
  54978. serializationObject.minX = this._minX;
  54979. serializationObject.maxX = this._maxX;
  54980. serializationObject.minZ = this._minZ;
  54981. serializationObject.maxZ = this._maxZ;
  54982. serializationObject.width = this._width;
  54983. serializationObject.height = this._height;
  54984. };
  54985. GroundMesh.Parse = function (parsedMesh, scene) {
  54986. var result = new GroundMesh(parsedMesh.name, scene);
  54987. result._subdivisionsX = parsedMesh.subdivisionsX || 1;
  54988. result._subdivisionsY = parsedMesh.subdivisionsY || 1;
  54989. result._minX = parsedMesh.minX;
  54990. result._maxX = parsedMesh.maxX;
  54991. result._minZ = parsedMesh.minZ;
  54992. result._maxZ = parsedMesh.maxZ;
  54993. result._width = parsedMesh.width;
  54994. result._height = parsedMesh.height;
  54995. return result;
  54996. };
  54997. return GroundMesh;
  54998. }(BABYLON.Mesh));
  54999. BABYLON.GroundMesh = GroundMesh;
  55000. })(BABYLON || (BABYLON = {}));
  55001. //# sourceMappingURL=babylon.groundMesh.js.map
  55002. var BABYLON;
  55003. (function (BABYLON) {
  55004. /**
  55005. * Creates an instance based on a source mesh.
  55006. */
  55007. var InstancedMesh = /** @class */ (function (_super) {
  55008. __extends(InstancedMesh, _super);
  55009. function InstancedMesh(name, source) {
  55010. var _this = _super.call(this, name, source.getScene()) || this;
  55011. source.instances.push(_this);
  55012. _this._sourceMesh = source;
  55013. _this.position.copyFrom(source.position);
  55014. _this.rotation.copyFrom(source.rotation);
  55015. _this.scaling.copyFrom(source.scaling);
  55016. if (source.rotationQuaternion) {
  55017. _this.rotationQuaternion = source.rotationQuaternion.clone();
  55018. }
  55019. _this.infiniteDistance = source.infiniteDistance;
  55020. _this.setPivotMatrix(source.getPivotMatrix());
  55021. _this.refreshBoundingInfo();
  55022. _this._syncSubMeshes();
  55023. return _this;
  55024. }
  55025. /**
  55026. * Returns the string "InstancedMesh".
  55027. */
  55028. InstancedMesh.prototype.getClassName = function () {
  55029. return "InstancedMesh";
  55030. };
  55031. Object.defineProperty(InstancedMesh.prototype, "receiveShadows", {
  55032. // Methods
  55033. get: function () {
  55034. return this._sourceMesh.receiveShadows;
  55035. },
  55036. enumerable: true,
  55037. configurable: true
  55038. });
  55039. Object.defineProperty(InstancedMesh.prototype, "material", {
  55040. get: function () {
  55041. return this._sourceMesh.material;
  55042. },
  55043. enumerable: true,
  55044. configurable: true
  55045. });
  55046. Object.defineProperty(InstancedMesh.prototype, "visibility", {
  55047. get: function () {
  55048. return this._sourceMesh.visibility;
  55049. },
  55050. enumerable: true,
  55051. configurable: true
  55052. });
  55053. Object.defineProperty(InstancedMesh.prototype, "skeleton", {
  55054. get: function () {
  55055. return this._sourceMesh.skeleton;
  55056. },
  55057. enumerable: true,
  55058. configurable: true
  55059. });
  55060. Object.defineProperty(InstancedMesh.prototype, "renderingGroupId", {
  55061. get: function () {
  55062. return this._sourceMesh.renderingGroupId;
  55063. },
  55064. enumerable: true,
  55065. configurable: true
  55066. });
  55067. /**
  55068. * Returns the total number of vertices (integer).
  55069. */
  55070. InstancedMesh.prototype.getTotalVertices = function () {
  55071. return this._sourceMesh.getTotalVertices();
  55072. };
  55073. Object.defineProperty(InstancedMesh.prototype, "sourceMesh", {
  55074. get: function () {
  55075. return this._sourceMesh;
  55076. },
  55077. enumerable: true,
  55078. configurable: true
  55079. });
  55080. /**
  55081. * Is this node ready to be used/rendered
  55082. * @param completeCheck defines if a complete check (including materials and lights) has to be done (false by default)
  55083. * @return {boolean} is it ready
  55084. */
  55085. InstancedMesh.prototype.isReady = function (completeCheck) {
  55086. if (completeCheck === void 0) { completeCheck = false; }
  55087. return this._sourceMesh.isReady(completeCheck, true);
  55088. };
  55089. /**
  55090. * Returns a float array or a Float32Array of the requested kind of data : positons, normals, uvs, etc.
  55091. */
  55092. InstancedMesh.prototype.getVerticesData = function (kind, copyWhenShared) {
  55093. return this._sourceMesh.getVerticesData(kind, copyWhenShared);
  55094. };
  55095. /**
  55096. * Sets the vertex data of the mesh geometry for the requested `kind`.
  55097. * If the mesh has no geometry, a new Geometry object is set to the mesh and then passed this vertex data.
  55098. * The `data` are either a numeric array either a Float32Array.
  55099. * The parameter `updatable` is passed as is to the underlying Geometry object constructor (if initianilly none) or updater.
  55100. * 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).
  55101. * Note that a new underlying VertexBuffer object is created each call.
  55102. * If the `kind` is the `PositionKind`, the mesh BoundingInfo is renewed, so the bounding box and sphere, and the mesh World Matrix is recomputed.
  55103. *
  55104. * Possible `kind` values :
  55105. * - BABYLON.VertexBuffer.PositionKind
  55106. * - BABYLON.VertexBuffer.UVKind
  55107. * - BABYLON.VertexBuffer.UV2Kind
  55108. * - BABYLON.VertexBuffer.UV3Kind
  55109. * - BABYLON.VertexBuffer.UV4Kind
  55110. * - BABYLON.VertexBuffer.UV5Kind
  55111. * - BABYLON.VertexBuffer.UV6Kind
  55112. * - BABYLON.VertexBuffer.ColorKind
  55113. * - BABYLON.VertexBuffer.MatricesIndicesKind
  55114. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  55115. * - BABYLON.VertexBuffer.MatricesWeightsKind
  55116. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  55117. *
  55118. * Returns the Mesh.
  55119. */
  55120. InstancedMesh.prototype.setVerticesData = function (kind, data, updatable, stride) {
  55121. if (this.sourceMesh) {
  55122. this.sourceMesh.setVerticesData(kind, data, updatable, stride);
  55123. }
  55124. return this.sourceMesh;
  55125. };
  55126. /**
  55127. * Updates the existing vertex data of the mesh geometry for the requested `kind`.
  55128. * If the mesh has no geometry, it is simply returned as it is.
  55129. * The `data` are either a numeric array either a Float32Array.
  55130. * No new underlying VertexBuffer object is created.
  55131. * 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.
  55132. * If the parameter `makeItUnique` is true, a new global geometry is created from this positions and is set to the mesh.
  55133. *
  55134. * Possible `kind` values :
  55135. * - BABYLON.VertexBuffer.PositionKind
  55136. * - BABYLON.VertexBuffer.UVKind
  55137. * - BABYLON.VertexBuffer.UV2Kind
  55138. * - BABYLON.VertexBuffer.UV3Kind
  55139. * - BABYLON.VertexBuffer.UV4Kind
  55140. * - BABYLON.VertexBuffer.UV5Kind
  55141. * - BABYLON.VertexBuffer.UV6Kind
  55142. * - BABYLON.VertexBuffer.ColorKind
  55143. * - BABYLON.VertexBuffer.MatricesIndicesKind
  55144. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  55145. * - BABYLON.VertexBuffer.MatricesWeightsKind
  55146. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  55147. *
  55148. * Returns the Mesh.
  55149. */
  55150. InstancedMesh.prototype.updateVerticesData = function (kind, data, updateExtends, makeItUnique) {
  55151. if (this.sourceMesh) {
  55152. this.sourceMesh.updateVerticesData(kind, data, updateExtends, makeItUnique);
  55153. }
  55154. return this.sourceMesh;
  55155. };
  55156. /**
  55157. * Sets the mesh indices.
  55158. * Expects an array populated with integers or a typed array (Int32Array, Uint32Array, Uint16Array).
  55159. * If the mesh has no geometry, a new Geometry object is created and set to the mesh.
  55160. * This method creates a new index buffer each call.
  55161. * Returns the Mesh.
  55162. */
  55163. InstancedMesh.prototype.setIndices = function (indices, totalVertices) {
  55164. if (totalVertices === void 0) { totalVertices = null; }
  55165. if (this.sourceMesh) {
  55166. this.sourceMesh.setIndices(indices, totalVertices);
  55167. }
  55168. return this.sourceMesh;
  55169. };
  55170. /**
  55171. * Boolean : True if the mesh owns the requested kind of data.
  55172. */
  55173. InstancedMesh.prototype.isVerticesDataPresent = function (kind) {
  55174. return this._sourceMesh.isVerticesDataPresent(kind);
  55175. };
  55176. /**
  55177. * Returns an array of indices (IndicesArray).
  55178. */
  55179. InstancedMesh.prototype.getIndices = function () {
  55180. return this._sourceMesh.getIndices();
  55181. };
  55182. Object.defineProperty(InstancedMesh.prototype, "_positions", {
  55183. get: function () {
  55184. return this._sourceMesh._positions;
  55185. },
  55186. enumerable: true,
  55187. configurable: true
  55188. });
  55189. /**
  55190. * Sets a new updated BoundingInfo to the mesh.
  55191. * Returns the mesh.
  55192. */
  55193. InstancedMesh.prototype.refreshBoundingInfo = function () {
  55194. var meshBB = this._sourceMesh.getBoundingInfo();
  55195. this._boundingInfo = new BABYLON.BoundingInfo(meshBB.minimum.clone(), meshBB.maximum.clone());
  55196. this._updateBoundingInfo();
  55197. return this;
  55198. };
  55199. InstancedMesh.prototype._preActivate = function () {
  55200. if (this._currentLOD) {
  55201. this._currentLOD._preActivate();
  55202. }
  55203. return this;
  55204. };
  55205. InstancedMesh.prototype._activate = function (renderId) {
  55206. if (this._currentLOD) {
  55207. this._currentLOD._registerInstanceForRenderId(this, renderId);
  55208. }
  55209. return this;
  55210. };
  55211. /**
  55212. * Returns the current associated LOD AbstractMesh.
  55213. */
  55214. InstancedMesh.prototype.getLOD = function (camera) {
  55215. if (!camera) {
  55216. return this;
  55217. }
  55218. var boundingInfo = this.getBoundingInfo();
  55219. this._currentLOD = this.sourceMesh.getLOD(camera, boundingInfo.boundingSphere);
  55220. if (this._currentLOD === this.sourceMesh) {
  55221. return this;
  55222. }
  55223. return this._currentLOD;
  55224. };
  55225. InstancedMesh.prototype._syncSubMeshes = function () {
  55226. this.releaseSubMeshes();
  55227. if (this._sourceMesh.subMeshes) {
  55228. for (var index = 0; index < this._sourceMesh.subMeshes.length; index++) {
  55229. this._sourceMesh.subMeshes[index].clone(this, this._sourceMesh);
  55230. }
  55231. }
  55232. return this;
  55233. };
  55234. InstancedMesh.prototype._generatePointsArray = function () {
  55235. return this._sourceMesh._generatePointsArray();
  55236. };
  55237. /**
  55238. * Creates a new InstancedMesh from the current mesh.
  55239. * - name (string) : the cloned mesh name
  55240. * - newParent (optional Node) : the optional Node to parent the clone to.
  55241. * - doNotCloneChildren (optional boolean, default `false`) : if `true` the model children aren't cloned.
  55242. *
  55243. * Returns the clone.
  55244. */
  55245. InstancedMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  55246. var result = this._sourceMesh.createInstance(name);
  55247. // Deep copy
  55248. BABYLON.Tools.DeepCopy(this, result, ["name", "subMeshes", "uniqueId"], []);
  55249. // Bounding info
  55250. this.refreshBoundingInfo();
  55251. // Parent
  55252. if (newParent) {
  55253. result.parent = newParent;
  55254. }
  55255. if (!doNotCloneChildren) {
  55256. // Children
  55257. for (var index = 0; index < this.getScene().meshes.length; index++) {
  55258. var mesh = this.getScene().meshes[index];
  55259. if (mesh.parent === this) {
  55260. mesh.clone(mesh.name, result);
  55261. }
  55262. }
  55263. }
  55264. result.computeWorldMatrix(true);
  55265. return result;
  55266. };
  55267. /**
  55268. * Disposes the InstancedMesh.
  55269. * Returns nothing.
  55270. */
  55271. InstancedMesh.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  55272. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  55273. // Remove from mesh
  55274. var index = this._sourceMesh.instances.indexOf(this);
  55275. this._sourceMesh.instances.splice(index, 1);
  55276. _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
  55277. };
  55278. return InstancedMesh;
  55279. }(BABYLON.AbstractMesh));
  55280. BABYLON.InstancedMesh = InstancedMesh;
  55281. })(BABYLON || (BABYLON = {}));
  55282. //# sourceMappingURL=babylon.instancedMesh.js.map
  55283. var BABYLON;
  55284. (function (BABYLON) {
  55285. var LinesMesh = /** @class */ (function (_super) {
  55286. __extends(LinesMesh, _super);
  55287. function LinesMesh(name, scene, parent, source, doNotCloneChildren, useVertexColor, useVertexAlpha) {
  55288. if (scene === void 0) { scene = null; }
  55289. if (parent === void 0) { parent = null; }
  55290. var _this = _super.call(this, name, scene, parent, source, doNotCloneChildren) || this;
  55291. _this.useVertexColor = useVertexColor;
  55292. _this.useVertexAlpha = useVertexAlpha;
  55293. _this.color = new BABYLON.Color3(1, 1, 1);
  55294. _this.alpha = 1;
  55295. if (source) {
  55296. _this.color = source.color.clone();
  55297. _this.alpha = source.alpha;
  55298. _this.useVertexColor = source.useVertexColor;
  55299. _this.useVertexAlpha = source.useVertexAlpha;
  55300. }
  55301. _this._intersectionThreshold = 0.1;
  55302. var defines = [];
  55303. var options = {
  55304. attributes: [BABYLON.VertexBuffer.PositionKind],
  55305. uniforms: ["world", "viewProjection"],
  55306. needAlphaBlending: true,
  55307. defines: defines
  55308. };
  55309. if (useVertexAlpha === false) {
  55310. options.needAlphaBlending = false;
  55311. }
  55312. if (!useVertexColor) {
  55313. options.uniforms.push("color");
  55314. }
  55315. else {
  55316. options.defines.push("#define VERTEXCOLOR");
  55317. options.attributes.push(BABYLON.VertexBuffer.ColorKind);
  55318. }
  55319. _this._colorShader = new BABYLON.ShaderMaterial("colorShader", _this.getScene(), "color", options);
  55320. return _this;
  55321. }
  55322. Object.defineProperty(LinesMesh.prototype, "intersectionThreshold", {
  55323. /**
  55324. * The intersection Threshold is the margin applied when intersection a segment of the LinesMesh with a Ray.
  55325. * This margin is expressed in world space coordinates, so its value may vary.
  55326. * Default value is 0.1
  55327. * @returns the intersection Threshold value.
  55328. */
  55329. get: function () {
  55330. return this._intersectionThreshold;
  55331. },
  55332. /**
  55333. * The intersection Threshold is the margin applied when intersection a segment of the LinesMesh with a Ray.
  55334. * This margin is expressed in world space coordinates, so its value may vary.
  55335. * @param value the new threshold to apply
  55336. */
  55337. set: function (value) {
  55338. if (this._intersectionThreshold === value) {
  55339. return;
  55340. }
  55341. this._intersectionThreshold = value;
  55342. if (this.geometry) {
  55343. this.geometry.boundingBias = new BABYLON.Vector2(0, value);
  55344. }
  55345. },
  55346. enumerable: true,
  55347. configurable: true
  55348. });
  55349. /**
  55350. * Returns the string "LineMesh"
  55351. */
  55352. LinesMesh.prototype.getClassName = function () {
  55353. return "LinesMesh";
  55354. };
  55355. Object.defineProperty(LinesMesh.prototype, "material", {
  55356. get: function () {
  55357. return this._colorShader;
  55358. },
  55359. set: function (value) {
  55360. // Do nothing
  55361. },
  55362. enumerable: true,
  55363. configurable: true
  55364. });
  55365. Object.defineProperty(LinesMesh.prototype, "checkCollisions", {
  55366. get: function () {
  55367. return false;
  55368. },
  55369. enumerable: true,
  55370. configurable: true
  55371. });
  55372. LinesMesh.prototype.createInstance = function (name) {
  55373. throw new Error("LinesMeshes do not support createInstance.");
  55374. };
  55375. LinesMesh.prototype._bind = function (subMesh, effect, fillMode) {
  55376. if (!this._geometry) {
  55377. return this;
  55378. }
  55379. // VBOs
  55380. this._geometry._bind(this._colorShader.getEffect());
  55381. // Color
  55382. if (!this.useVertexColor) {
  55383. this._colorShader.setColor4("color", this.color.toColor4(this.alpha));
  55384. }
  55385. return this;
  55386. };
  55387. LinesMesh.prototype._draw = function (subMesh, fillMode, instancesCount) {
  55388. if (!this._geometry || !this._geometry.getVertexBuffers() || !this._geometry.getIndexBuffer()) {
  55389. return this;
  55390. }
  55391. var engine = this.getScene().getEngine();
  55392. // Draw order
  55393. engine.drawElementsType(BABYLON.Material.LineListDrawMode, subMesh.indexStart, subMesh.indexCount);
  55394. return this;
  55395. };
  55396. LinesMesh.prototype.dispose = function (doNotRecurse) {
  55397. this._colorShader.dispose();
  55398. _super.prototype.dispose.call(this, doNotRecurse);
  55399. };
  55400. /**
  55401. * Returns a new LineMesh object cloned from the current one.
  55402. */
  55403. LinesMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  55404. return new LinesMesh(name, this.getScene(), newParent, this, doNotCloneChildren);
  55405. };
  55406. return LinesMesh;
  55407. }(BABYLON.Mesh));
  55408. BABYLON.LinesMesh = LinesMesh;
  55409. })(BABYLON || (BABYLON = {}));
  55410. //# sourceMappingURL=babylon.linesMesh.js.map
  55411. var BABYLON;
  55412. (function (BABYLON) {
  55413. var MeshBuilder = /** @class */ (function () {
  55414. function MeshBuilder() {
  55415. }
  55416. MeshBuilder.updateSideOrientation = function (orientation) {
  55417. if (orientation == BABYLON.Mesh.DOUBLESIDE) {
  55418. return BABYLON.Mesh.DOUBLESIDE;
  55419. }
  55420. if (orientation === undefined || orientation === null) {
  55421. return BABYLON.Mesh.FRONTSIDE;
  55422. }
  55423. return orientation;
  55424. };
  55425. /**
  55426. * Creates a box mesh.
  55427. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#box
  55428. * The parameter `size` sets the size (float) of each box side (default 1).
  55429. * You can set some different box dimensions by using the parameters `width`, `height` and `depth` (all by default have the same value than `size`).
  55430. * 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).
  55431. * Please read this tutorial : http://doc.babylonjs.com/tutorials/CreateBox_Per_Face_Textures_And_Colors
  55432. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  55433. * 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).
  55434. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  55435. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  55436. */
  55437. MeshBuilder.CreateBox = function (name, options, scene) {
  55438. if (scene === void 0) { scene = null; }
  55439. var box = new BABYLON.Mesh(name, scene);
  55440. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  55441. box._originalBuilderSideOrientation = options.sideOrientation;
  55442. var vertexData = BABYLON.VertexData.CreateBox(options);
  55443. vertexData.applyToMesh(box, options.updatable);
  55444. return box;
  55445. };
  55446. /**
  55447. * Creates a sphere mesh.
  55448. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#sphere
  55449. * The parameter `diameter` sets the diameter size (float) of the sphere (default 1).
  55450. * 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`).
  55451. * The parameter `segments` sets the sphere number of horizontal stripes (positive integer, default 32).
  55452. * 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
  55453. * 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).
  55454. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  55455. * 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).
  55456. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  55457. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  55458. */
  55459. MeshBuilder.CreateSphere = function (name, options, scene) {
  55460. var sphere = new BABYLON.Mesh(name, scene);
  55461. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  55462. sphere._originalBuilderSideOrientation = options.sideOrientation;
  55463. var vertexData = BABYLON.VertexData.CreateSphere(options);
  55464. vertexData.applyToMesh(sphere, options.updatable);
  55465. return sphere;
  55466. };
  55467. /**
  55468. * Creates a plane polygonal mesh. By default, this is a disc.
  55469. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#disc
  55470. * The parameter `radius` sets the radius size (float) of the polygon (default 0.5).
  55471. * 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.
  55472. * 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
  55473. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  55474. * 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).
  55475. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  55476. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  55477. */
  55478. MeshBuilder.CreateDisc = function (name, options, scene) {
  55479. if (scene === void 0) { scene = null; }
  55480. var disc = new BABYLON.Mesh(name, scene);
  55481. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  55482. disc._originalBuilderSideOrientation = options.sideOrientation;
  55483. var vertexData = BABYLON.VertexData.CreateDisc(options);
  55484. vertexData.applyToMesh(disc, options.updatable);
  55485. return disc;
  55486. };
  55487. /**
  55488. * Creates a sphere based upon an icosahedron with 20 triangular faces which can be subdivided.
  55489. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#icosphere
  55490. * The parameter `radius` sets the radius size (float) of the icosphere (default 1).
  55491. * 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`).
  55492. * The parameter `subdivisions` sets the number of subdivisions (postive integer, default 4). The more subdivisions, the more faces on the icosphere whatever its size.
  55493. * 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.
  55494. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  55495. * 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).
  55496. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  55497. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  55498. */
  55499. MeshBuilder.CreateIcoSphere = function (name, options, scene) {
  55500. var sphere = new BABYLON.Mesh(name, scene);
  55501. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  55502. sphere._originalBuilderSideOrientation = options.sideOrientation;
  55503. var vertexData = BABYLON.VertexData.CreateIcoSphere(options);
  55504. vertexData.applyToMesh(sphere, options.updatable);
  55505. return sphere;
  55506. };
  55507. ;
  55508. /**
  55509. * Creates a ribbon mesh.
  55510. * 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.
  55511. *
  55512. * Please read this full tutorial to understand how to design a ribbon : http://doc.babylonjs.com/tutorials/Ribbon_Tutorial
  55513. * The parameter `pathArray` is a required array of paths, what are each an array of successive Vector3. The pathArray parameter depicts the ribbon geometry.
  55514. * The parameter `closeArray` (boolean, default false) creates a seam between the first and the last paths of the path array.
  55515. * The parameter `closePath` (boolean, default false) creates a seam between the first and the last points of each path of the path array.
  55516. * 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.
  55517. * 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.
  55518. * 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
  55519. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  55520. * 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).
  55521. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  55522. * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture.
  55523. * 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.
  55524. * The parameters `colors` is an optional flat array of `Color4` to set/update each ribbon vertex with its own custom color values.
  55525. * 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
  55526. * if you set `closePath` to `true`, there's one extra vertex per path in the geometry.
  55527. * Moreover, you can use the parameter `color` with `instance` (to update the ribbon), only if you previously used it at creation time.
  55528. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  55529. */
  55530. MeshBuilder.CreateRibbon = function (name, options, scene) {
  55531. if (scene === void 0) { scene = null; }
  55532. var pathArray = options.pathArray;
  55533. var closeArray = options.closeArray;
  55534. var closePath = options.closePath;
  55535. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  55536. var instance = options.instance;
  55537. var updatable = options.updatable;
  55538. if (instance) {
  55539. // positionFunction : ribbon case
  55540. // only pathArray and sideOrientation parameters are taken into account for positions update
  55541. BABYLON.Vector3.FromFloatsToRef(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, BABYLON.Tmp.Vector3[0]); // minimum
  55542. BABYLON.Vector3.FromFloatsToRef(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE, BABYLON.Tmp.Vector3[1]);
  55543. var positionFunction = function (positions) {
  55544. var minlg = pathArray[0].length;
  55545. var i = 0;
  55546. var ns = (instance._originalBuilderSideOrientation === BABYLON.Mesh.DOUBLESIDE) ? 2 : 1;
  55547. for (var si = 1; si <= ns; si++) {
  55548. for (var p = 0; p < pathArray.length; p++) {
  55549. var path = pathArray[p];
  55550. var l = path.length;
  55551. minlg = (minlg < l) ? minlg : l;
  55552. var j = 0;
  55553. while (j < minlg) {
  55554. positions[i] = path[j].x;
  55555. positions[i + 1] = path[j].y;
  55556. positions[i + 2] = path[j].z;
  55557. if (path[j].x < BABYLON.Tmp.Vector3[0].x) {
  55558. BABYLON.Tmp.Vector3[0].x = path[j].x;
  55559. }
  55560. if (path[j].x > BABYLON.Tmp.Vector3[1].x) {
  55561. BABYLON.Tmp.Vector3[1].x = path[j].x;
  55562. }
  55563. if (path[j].y < BABYLON.Tmp.Vector3[0].y) {
  55564. BABYLON.Tmp.Vector3[0].y = path[j].y;
  55565. }
  55566. if (path[j].y > BABYLON.Tmp.Vector3[1].y) {
  55567. BABYLON.Tmp.Vector3[1].y = path[j].y;
  55568. }
  55569. if (path[j].z < BABYLON.Tmp.Vector3[0].z) {
  55570. BABYLON.Tmp.Vector3[0].z = path[j].z;
  55571. }
  55572. if (path[j].z > BABYLON.Tmp.Vector3[1].z) {
  55573. BABYLON.Tmp.Vector3[1].z = path[j].z;
  55574. }
  55575. j++;
  55576. i += 3;
  55577. }
  55578. if (instance._closePath) {
  55579. positions[i] = path[0].x;
  55580. positions[i + 1] = path[0].y;
  55581. positions[i + 2] = path[0].z;
  55582. i += 3;
  55583. }
  55584. }
  55585. }
  55586. };
  55587. var positions = instance.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  55588. positionFunction(positions);
  55589. instance._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Tmp.Vector3[0], BABYLON.Tmp.Vector3[1]);
  55590. instance._boundingInfo.update(instance._worldMatrix);
  55591. instance.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions, false, false);
  55592. if (options.colors) {
  55593. var colors = instance.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  55594. for (var c = 0; c < options.colors.length; c++) {
  55595. colors[c * 4] = options.colors[c].r;
  55596. colors[c * 4 + 1] = options.colors[c].g;
  55597. colors[c * 4 + 2] = options.colors[c].b;
  55598. colors[c * 4 + 3] = options.colors[c].a;
  55599. }
  55600. instance.updateVerticesData(BABYLON.VertexBuffer.ColorKind, colors, false, false);
  55601. }
  55602. if (options.uvs) {
  55603. var uvs = instance.getVerticesData(BABYLON.VertexBuffer.UVKind);
  55604. for (var i = 0; i < options.uvs.length; i++) {
  55605. uvs[i * 2] = options.uvs[i].x;
  55606. uvs[i * 2 + 1] = options.uvs[i].y;
  55607. }
  55608. instance.updateVerticesData(BABYLON.VertexBuffer.UVKind, uvs, false, false);
  55609. }
  55610. if (!instance.areNormalsFrozen || instance.isFacetDataEnabled) {
  55611. var indices = instance.getIndices();
  55612. var normals = instance.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  55613. var params = instance.isFacetDataEnabled ? instance.getFacetDataParameters() : null;
  55614. BABYLON.VertexData.ComputeNormals(positions, indices, normals, params);
  55615. if (instance._closePath) {
  55616. var indexFirst = 0;
  55617. var indexLast = 0;
  55618. for (var p = 0; p < pathArray.length; p++) {
  55619. indexFirst = instance._idx[p] * 3;
  55620. if (p + 1 < pathArray.length) {
  55621. indexLast = (instance._idx[p + 1] - 1) * 3;
  55622. }
  55623. else {
  55624. indexLast = normals.length - 3;
  55625. }
  55626. normals[indexFirst] = (normals[indexFirst] + normals[indexLast]) * 0.5;
  55627. normals[indexFirst + 1] = (normals[indexFirst + 1] + normals[indexLast + 1]) * 0.5;
  55628. normals[indexFirst + 2] = (normals[indexFirst + 2] + normals[indexLast + 2]) * 0.5;
  55629. normals[indexLast] = normals[indexFirst];
  55630. normals[indexLast + 1] = normals[indexFirst + 1];
  55631. normals[indexLast + 2] = normals[indexFirst + 2];
  55632. }
  55633. }
  55634. if (!(instance.areNormalsFrozen)) {
  55635. instance.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals, false, false);
  55636. }
  55637. }
  55638. return instance;
  55639. }
  55640. else {
  55641. var ribbon = new BABYLON.Mesh(name, scene);
  55642. ribbon._originalBuilderSideOrientation = sideOrientation;
  55643. var vertexData = BABYLON.VertexData.CreateRibbon(options);
  55644. if (closePath) {
  55645. ribbon._idx = vertexData._idx;
  55646. }
  55647. ribbon._closePath = closePath;
  55648. ribbon._closeArray = closeArray;
  55649. vertexData.applyToMesh(ribbon, updatable);
  55650. return ribbon;
  55651. }
  55652. };
  55653. /**
  55654. * Creates a cylinder or a cone mesh.
  55655. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#cylinder-or-cone
  55656. * The parameter `height` sets the height size (float) of the cylinder/cone (float, default 2).
  55657. * The parameter `diameter` sets the diameter of the top and bottom cap at once (float, default 1).
  55658. * 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.
  55659. * The parameter `tessellation` sets the number of cylinder sides (positive integer, default 24). Set it to 3 to get a prism for instance.
  55660. * The parameter `subdivisions` sets the number of rings along the cylinder height (positive integer, default 1).
  55661. * The parameter `hasRings` (boolean, default false) makes the subdivisions independent from each other, so they become different faces.
  55662. * The parameter `enclose` (boolean, default false) adds two extra faces per subdivision to a sliced cylinder to close it around its height axis.
  55663. * The parameter `arc` (float, default 1) is the ratio (max 1) to apply to the circumference to slice the cylinder.
  55664. * 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).
  55665. * 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
  55666. * Now, if the cylinder has 5 independent subdivisions (hasRings = true), n equals : top face + 5 stripe surfaces + bottom face = 2 + 5 = 7
  55667. * 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
  55668. * 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.
  55669. * If `enclose` is false, a ring surface is one element.
  55670. * If `enclose` is true, a ring surface is 3 successive elements in the array : the tubular surface, then the two closing faces.
  55671. * 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
  55672. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  55673. * 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).
  55674. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  55675. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  55676. */
  55677. MeshBuilder.CreateCylinder = function (name, options, scene) {
  55678. var cylinder = new BABYLON.Mesh(name, scene);
  55679. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  55680. cylinder._originalBuilderSideOrientation = options.sideOrientation;
  55681. var vertexData = BABYLON.VertexData.CreateCylinder(options);
  55682. vertexData.applyToMesh(cylinder, options.updatable);
  55683. return cylinder;
  55684. };
  55685. /**
  55686. * Creates a torus mesh.
  55687. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#torus
  55688. * The parameter `diameter` sets the diameter size (float) of the torus (default 1).
  55689. * The parameter `thickness` sets the diameter size of the tube of the torus (float, default 0.5).
  55690. * The parameter `tessellation` sets the number of torus sides (postive integer, default 16).
  55691. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  55692. * 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).
  55693. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  55694. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  55695. */
  55696. MeshBuilder.CreateTorus = function (name, options, scene) {
  55697. var torus = new BABYLON.Mesh(name, scene);
  55698. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  55699. torus._originalBuilderSideOrientation = options.sideOrientation;
  55700. var vertexData = BABYLON.VertexData.CreateTorus(options);
  55701. vertexData.applyToMesh(torus, options.updatable);
  55702. return torus;
  55703. };
  55704. /**
  55705. * Creates a torus knot mesh.
  55706. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#torus-knot
  55707. * The parameter `radius` sets the global radius size (float) of the torus knot (default 2).
  55708. * The parameter `radialSegments` sets the number of sides on each tube segments (positive integer, default 32).
  55709. * The parameter `tubularSegments` sets the number of tubes to decompose the knot into (positive integer, default 32).
  55710. * The parameters `p` and `q` are the number of windings on each axis (positive integers, default 2 and 3).
  55711. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  55712. * 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).
  55713. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  55714. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  55715. */
  55716. MeshBuilder.CreateTorusKnot = function (name, options, scene) {
  55717. var torusKnot = new BABYLON.Mesh(name, scene);
  55718. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  55719. torusKnot._originalBuilderSideOrientation = options.sideOrientation;
  55720. var vertexData = BABYLON.VertexData.CreateTorusKnot(options);
  55721. vertexData.applyToMesh(torusKnot, options.updatable);
  55722. return torusKnot;
  55723. };
  55724. /**
  55725. * Creates a line system mesh.
  55726. * A line system is a pool of many lines gathered in a single mesh.
  55727. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#linesystem
  55728. * 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.
  55729. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineSystem to this static function.
  55730. * The parameter `lines` is an array of lines, each line being an array of successive Vector3.
  55731. * 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
  55732. * The optional parameter `colors` is an array of line colors, each line colors being an array of successive Color4, one per line point.
  55733. * The optional parameter `useVertexAlpha' is to be set to `false` (default `true`) when you don't need the alpha blending (faster).
  55734. * 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
  55735. * When updating an instance, remember that only line point positions can change, not the number of points, neither the number of lines.
  55736. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  55737. */
  55738. MeshBuilder.CreateLineSystem = function (name, options, scene) {
  55739. var instance = options.instance;
  55740. var lines = options.lines;
  55741. var colors = options.colors;
  55742. if (instance) {
  55743. var positions = instance.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  55744. var vertexColor;
  55745. var lineColors;
  55746. if (colors) {
  55747. vertexColor = instance.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  55748. }
  55749. var i = 0;
  55750. var c = 0;
  55751. for (var l = 0; l < lines.length; l++) {
  55752. var points = lines[l];
  55753. for (var p = 0; p < points.length; p++) {
  55754. positions[i] = points[p].x;
  55755. positions[i + 1] = points[p].y;
  55756. positions[i + 2] = points[p].z;
  55757. if (colors && vertexColor) {
  55758. lineColors = colors[l];
  55759. vertexColor[c] = lineColors[p].r;
  55760. vertexColor[c + 1] = lineColors[p].g;
  55761. vertexColor[c + 2] = lineColors[p].b;
  55762. vertexColor[c + 3] = lineColors[p].a;
  55763. c += 4;
  55764. }
  55765. i += 3;
  55766. }
  55767. }
  55768. instance.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions, false, false);
  55769. if (colors && vertexColor) {
  55770. instance.updateVerticesData(BABYLON.VertexBuffer.ColorKind, vertexColor, false, false);
  55771. }
  55772. return instance;
  55773. }
  55774. // line system creation
  55775. var useVertexColor = (colors) ? true : false;
  55776. var lineSystem = new BABYLON.LinesMesh(name, scene, null, undefined, undefined, useVertexColor, options.useVertexAlpha);
  55777. var vertexData = BABYLON.VertexData.CreateLineSystem(options);
  55778. vertexData.applyToMesh(lineSystem, options.updatable);
  55779. return lineSystem;
  55780. };
  55781. /**
  55782. * Creates a line mesh.
  55783. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#lines
  55784. * 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.
  55785. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function.
  55786. * The parameter `points` is an array successive Vector3.
  55787. * 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
  55788. * The optional parameter `colors` is an array of successive Color4, one per line point.
  55789. * The optional parameter `useVertexAlpha' is to be set to `false` (default `true`) when you don't need alpha blending (faster).
  55790. * When updating an instance, remember that only point positions can change, not the number of points.
  55791. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  55792. */
  55793. MeshBuilder.CreateLines = function (name, options, scene) {
  55794. if (scene === void 0) { scene = null; }
  55795. var colors = (options.colors) ? [options.colors] : null;
  55796. var lines = MeshBuilder.CreateLineSystem(name, { lines: [options.points], updatable: options.updatable, instance: options.instance, colors: colors, useVertexAlpha: options.useVertexAlpha }, scene);
  55797. return lines;
  55798. };
  55799. /**
  55800. * Creates a dashed line mesh.
  55801. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#dashed-lines
  55802. * 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.
  55803. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function.
  55804. * The parameter `points` is an array successive Vector3.
  55805. * The parameter `dashNb` is the intended total number of dashes (positive integer, default 200).
  55806. * The parameter `dashSize` is the size of the dashes relatively the dash number (positive float, default 3).
  55807. * The parameter `gapSize` is the size of the gap between two successive dashes relatively the dash number (positive float, default 1).
  55808. * 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
  55809. * When updating an instance, remember that only point positions can change, not the number of points.
  55810. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  55811. */
  55812. MeshBuilder.CreateDashedLines = function (name, options, scene) {
  55813. if (scene === void 0) { scene = null; }
  55814. var points = options.points;
  55815. var instance = options.instance;
  55816. var gapSize = options.gapSize || 1;
  55817. var dashSize = options.dashSize || 3;
  55818. if (instance) {
  55819. var positionFunction = function (positions) {
  55820. var curvect = BABYLON.Vector3.Zero();
  55821. var nbSeg = positions.length / 6;
  55822. var lg = 0;
  55823. var nb = 0;
  55824. var shft = 0;
  55825. var dashshft = 0;
  55826. var curshft = 0;
  55827. var p = 0;
  55828. var i = 0;
  55829. var j = 0;
  55830. for (i = 0; i < points.length - 1; i++) {
  55831. points[i + 1].subtractToRef(points[i], curvect);
  55832. lg += curvect.length();
  55833. }
  55834. shft = lg / nbSeg;
  55835. dashshft = instance.dashSize * shft / (instance.dashSize + instance.gapSize);
  55836. for (i = 0; i < points.length - 1; i++) {
  55837. points[i + 1].subtractToRef(points[i], curvect);
  55838. nb = Math.floor(curvect.length() / shft);
  55839. curvect.normalize();
  55840. j = 0;
  55841. while (j < nb && p < positions.length) {
  55842. curshft = shft * j;
  55843. positions[p] = points[i].x + curshft * curvect.x;
  55844. positions[p + 1] = points[i].y + curshft * curvect.y;
  55845. positions[p + 2] = points[i].z + curshft * curvect.z;
  55846. positions[p + 3] = points[i].x + (curshft + dashshft) * curvect.x;
  55847. positions[p + 4] = points[i].y + (curshft + dashshft) * curvect.y;
  55848. positions[p + 5] = points[i].z + (curshft + dashshft) * curvect.z;
  55849. p += 6;
  55850. j++;
  55851. }
  55852. }
  55853. while (p < positions.length) {
  55854. positions[p] = points[i].x;
  55855. positions[p + 1] = points[i].y;
  55856. positions[p + 2] = points[i].z;
  55857. p += 3;
  55858. }
  55859. };
  55860. instance.updateMeshPositions(positionFunction, false);
  55861. return instance;
  55862. }
  55863. // dashed lines creation
  55864. var dashedLines = new BABYLON.LinesMesh(name, scene);
  55865. var vertexData = BABYLON.VertexData.CreateDashedLines(options);
  55866. vertexData.applyToMesh(dashedLines, options.updatable);
  55867. dashedLines.dashSize = dashSize;
  55868. dashedLines.gapSize = gapSize;
  55869. return dashedLines;
  55870. };
  55871. /**
  55872. * Creates an extruded shape mesh.
  55873. * 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.
  55874. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#extruded-shapes
  55875. *
  55876. * Please read this full tutorial to understand how to design an extruded shape : http://doc.babylonjs.com/tutorials/Parametric_Shapes#extrusion
  55877. * 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
  55878. * extruded along the Z axis.
  55879. * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  55880. * 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.
  55881. * The parameter `scale` (float, default 1) is the value to scale the shape.
  55882. * 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
  55883. * 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
  55884. * Remember you can only change the shape or path point positions, not their number when updating an extruded shape.
  55885. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  55886. * 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).
  55887. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  55888. * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture.
  55889. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  55890. */
  55891. MeshBuilder.ExtrudeShape = function (name, options, scene) {
  55892. if (scene === void 0) { scene = null; }
  55893. var path = options.path;
  55894. var shape = options.shape;
  55895. var scale = options.scale || 1;
  55896. var rotation = options.rotation || 0;
  55897. var cap = (options.cap === 0) ? 0 : options.cap || BABYLON.Mesh.NO_CAP;
  55898. var updatable = options.updatable;
  55899. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  55900. var instance = options.instance || null;
  55901. var invertUV = options.invertUV || false;
  55902. 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);
  55903. };
  55904. /**
  55905. * Creates an custom extruded shape mesh.
  55906. * 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.
  55907. * tuto :http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#custom-extruded-shapes
  55908. *
  55909. * Please read this full tutorial to understand how to design a custom extruded shape : http://doc.babylonjs.com/tutorials/Parametric_Shapes#extrusion
  55910. * 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
  55911. * extruded along the Z axis.
  55912. * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  55913. * 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
  55914. * and the distance of this point from the begining of the path :
  55915. * ```javascript
  55916. * var rotationFunction = function(i, distance) {
  55917. * // do things
  55918. * return rotationValue; }
  55919. * ```
  55920. * It must returns a float value that will be the rotation in radians applied to the shape on each path point.
  55921. * 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
  55922. * and the distance of this point from the begining of the path :
  55923. * ```javascript
  55924. * var scaleFunction = function(i, distance) {
  55925. * // do things
  55926. * return scaleValue;}
  55927. * ```
  55928. * It must returns a float value that will be the scale value applied to the shape on each path point.
  55929. * The parameter `ribbonClosePath` (boolean, default false) forces the extrusion underlying ribbon to close all the paths in its `pathArray`.
  55930. * The parameter `ribbonCloseArray` (boolean, default false) forces the extrusion underlying ribbon to close its `pathArray`.
  55931. * 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
  55932. * 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
  55933. * Remember you can only change the shape or path point positions, not their number when updating an extruded shape.
  55934. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  55935. * 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).
  55936. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  55937. * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture.
  55938. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  55939. */
  55940. MeshBuilder.ExtrudeShapeCustom = function (name, options, scene) {
  55941. var path = options.path;
  55942. var shape = options.shape;
  55943. var scaleFunction = options.scaleFunction || (function () { return 1; });
  55944. var rotationFunction = options.rotationFunction || (function () { return 0; });
  55945. var ribbonCloseArray = options.ribbonCloseArray || false;
  55946. var ribbonClosePath = options.ribbonClosePath || false;
  55947. var cap = (options.cap === 0) ? 0 : options.cap || BABYLON.Mesh.NO_CAP;
  55948. var updatable = options.updatable;
  55949. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  55950. var instance = options.instance;
  55951. var invertUV = options.invertUV || false;
  55952. 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);
  55953. };
  55954. /**
  55955. * Creates lathe mesh.
  55956. * The lathe is a shape with a symetry axis : a 2D model shape is rotated around this axis to design the lathe.
  55957. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#lathe
  55958. *
  55959. * 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
  55960. * rotated around the Y axis. It's usually a 2D shape, so the Vector3 z coordinates are often set to zero.
  55961. * The parameter `radius` (positive float, default 1) is the radius value of the lathe.
  55962. * The parameter `tessellation` (positive integer, default 64) is the side number of the lathe.
  55963. * 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.
  55964. * The parameter `closed` (boolean, default true) opens/closes the lathe circumference. This should be set to false when used with the parameter "arc".
  55965. * 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
  55966. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  55967. * 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).
  55968. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  55969. * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture.
  55970. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  55971. */
  55972. MeshBuilder.CreateLathe = function (name, options, scene) {
  55973. var arc = options.arc ? ((options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc) : 1.0;
  55974. var closed = (options.closed === undefined) ? true : options.closed;
  55975. var shape = options.shape;
  55976. var radius = options.radius || 1;
  55977. var tessellation = options.tessellation || 64;
  55978. var updatable = options.updatable;
  55979. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  55980. var cap = options.cap || BABYLON.Mesh.NO_CAP;
  55981. var pi2 = Math.PI * 2;
  55982. var paths = new Array();
  55983. var invertUV = options.invertUV || false;
  55984. var i = 0;
  55985. var p = 0;
  55986. var step = pi2 / tessellation * arc;
  55987. var rotated;
  55988. var path = new Array();
  55989. ;
  55990. for (i = 0; i <= tessellation; i++) {
  55991. var path = [];
  55992. if (cap == BABYLON.Mesh.CAP_START || cap == BABYLON.Mesh.CAP_ALL) {
  55993. path.push(new BABYLON.Vector3(0, shape[0].y, 0));
  55994. path.push(new BABYLON.Vector3(Math.cos(i * step) * shape[0].x * radius, shape[0].y, Math.sin(i * step) * shape[0].x * radius));
  55995. }
  55996. for (p = 0; p < shape.length; p++) {
  55997. rotated = new BABYLON.Vector3(Math.cos(i * step) * shape[p].x * radius, shape[p].y, Math.sin(i * step) * shape[p].x * radius);
  55998. path.push(rotated);
  55999. }
  56000. if (cap == BABYLON.Mesh.CAP_END || cap == BABYLON.Mesh.CAP_ALL) {
  56001. 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));
  56002. path.push(new BABYLON.Vector3(0, shape[shape.length - 1].y, 0));
  56003. }
  56004. paths.push(path);
  56005. }
  56006. // lathe ribbon
  56007. var lathe = MeshBuilder.CreateRibbon(name, { pathArray: paths, closeArray: closed, sideOrientation: sideOrientation, updatable: updatable, invertUV: invertUV, frontUVs: options.frontUVs, backUVs: options.backUVs }, scene);
  56008. return lathe;
  56009. };
  56010. /**
  56011. * Creates a plane mesh.
  56012. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#plane
  56013. * The parameter `size` sets the size (float) of both sides of the plane at once (default 1).
  56014. * You can set some different plane dimensions by using the parameters `width` and `height` (both by default have the same value than `size`).
  56015. * The parameter `sourcePlane` is a Plane instance. It builds a mesh plane from a Math plane.
  56016. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  56017. * 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).
  56018. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  56019. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  56020. */
  56021. MeshBuilder.CreatePlane = function (name, options, scene) {
  56022. var plane = new BABYLON.Mesh(name, scene);
  56023. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  56024. plane._originalBuilderSideOrientation = options.sideOrientation;
  56025. var vertexData = BABYLON.VertexData.CreatePlane(options);
  56026. vertexData.applyToMesh(plane, options.updatable);
  56027. if (options.sourcePlane) {
  56028. plane.translate(options.sourcePlane.normal, options.sourcePlane.d);
  56029. var product = Math.acos(BABYLON.Vector3.Dot(options.sourcePlane.normal, BABYLON.Axis.Z));
  56030. var vectorProduct = BABYLON.Vector3.Cross(BABYLON.Axis.Z, options.sourcePlane.normal);
  56031. plane.rotate(vectorProduct, product);
  56032. }
  56033. return plane;
  56034. };
  56035. /**
  56036. * Creates a ground mesh.
  56037. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#plane
  56038. * The parameters `width` and `height` (floats, default 1) set the width and height sizes of the ground.
  56039. * The parameter `subdivisions` (positive integer) sets the number of subdivisions per side.
  56040. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  56041. */
  56042. MeshBuilder.CreateGround = function (name, options, scene) {
  56043. var ground = new BABYLON.GroundMesh(name, scene);
  56044. ground._setReady(false);
  56045. ground._subdivisionsX = options.subdivisionsX || options.subdivisions || 1;
  56046. ground._subdivisionsY = options.subdivisionsY || options.subdivisions || 1;
  56047. ground._width = options.width || 1;
  56048. ground._height = options.height || 1;
  56049. ground._maxX = ground._width / 2;
  56050. ground._maxZ = ground._height / 2;
  56051. ground._minX = -ground._maxX;
  56052. ground._minZ = -ground._maxZ;
  56053. var vertexData = BABYLON.VertexData.CreateGround(options);
  56054. vertexData.applyToMesh(ground, options.updatable);
  56055. ground._setReady(true);
  56056. return ground;
  56057. };
  56058. /**
  56059. * Creates a tiled ground mesh.
  56060. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#tiled-ground
  56061. * The parameters `xmin` and `xmax` (floats, default -1 and 1) set the ground minimum and maximum X coordinates.
  56062. * The parameters `zmin` and `zmax` (floats, default -1 and 1) set the ground minimum and maximum Z coordinates.
  56063. * The parameter `subdivisions` is a javascript object `{w: positive integer, h: positive integer}` (default `{w: 6, h: 6}`). `w` and `h` are the
  56064. * numbers of subdivisions on the ground width and height. Each subdivision is called a tile.
  56065. * The parameter `precision` is a javascript object `{w: positive integer, h: positive integer}` (default `{w: 2, h: 2}`). `w` and `h` are the
  56066. * numbers of subdivisions on the ground width and height of each tile.
  56067. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  56068. */
  56069. MeshBuilder.CreateTiledGround = function (name, options, scene) {
  56070. var tiledGround = new BABYLON.Mesh(name, scene);
  56071. var vertexData = BABYLON.VertexData.CreateTiledGround(options);
  56072. vertexData.applyToMesh(tiledGround, options.updatable);
  56073. return tiledGround;
  56074. };
  56075. /**
  56076. * Creates a ground mesh from a height map.
  56077. * tuto : http://doc.babylonjs.com/tutorials/14._Height_Map
  56078. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#ground-from-a-height-map
  56079. * The parameter `url` sets the URL of the height map image resource.
  56080. * The parameters `width` and `height` (positive floats, default 10) set the ground width and height sizes.
  56081. * The parameter `subdivisions` (positive integer, default 1) sets the number of subdivision per side.
  56082. * The parameter `minHeight` (float, default 0) is the minimum altitude on the ground.
  56083. * The parameter `maxHeight` (float, default 1) is the maximum altitude on the ground.
  56084. * 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.
  56085. * 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).
  56086. * This function is passed the newly built mesh :
  56087. * ```javascript
  56088. * function(mesh) { // do things
  56089. * return; }
  56090. * ```
  56091. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  56092. */
  56093. MeshBuilder.CreateGroundFromHeightMap = function (name, url, options, scene) {
  56094. var width = options.width || 10.0;
  56095. var height = options.height || 10.0;
  56096. var subdivisions = options.subdivisions || 1 | 0;
  56097. var minHeight = options.minHeight || 0.0;
  56098. var maxHeight = options.maxHeight || 1.0;
  56099. var filter = options.colorFilter || new BABYLON.Color3(0.3, 0.59, 0.11);
  56100. var updatable = options.updatable;
  56101. var onReady = options.onReady;
  56102. var ground = new BABYLON.GroundMesh(name, scene);
  56103. ground._subdivisionsX = subdivisions;
  56104. ground._subdivisionsY = subdivisions;
  56105. ground._width = width;
  56106. ground._height = height;
  56107. ground._maxX = ground._width / 2.0;
  56108. ground._maxZ = ground._height / 2.0;
  56109. ground._minX = -ground._maxX;
  56110. ground._minZ = -ground._maxZ;
  56111. ground._setReady(false);
  56112. var onload = function (img) {
  56113. // Getting height map data
  56114. var canvas = document.createElement("canvas");
  56115. var context = canvas.getContext("2d");
  56116. if (!context) {
  56117. throw new Error("Unable to get 2d context for CreateGroundFromHeightMap");
  56118. }
  56119. if (scene.isDisposed) {
  56120. return;
  56121. }
  56122. var bufferWidth = img.width;
  56123. var bufferHeight = img.height;
  56124. canvas.width = bufferWidth;
  56125. canvas.height = bufferHeight;
  56126. context.drawImage(img, 0, 0);
  56127. // Create VertexData from map data
  56128. // Cast is due to wrong definition in lib.d.ts from ts 1.3 - https://github.com/Microsoft/TypeScript/issues/949
  56129. var buffer = context.getImageData(0, 0, bufferWidth, bufferHeight).data;
  56130. var vertexData = BABYLON.VertexData.CreateGroundFromHeightMap({
  56131. width: width, height: height,
  56132. subdivisions: subdivisions,
  56133. minHeight: minHeight, maxHeight: maxHeight, colorFilter: filter,
  56134. buffer: buffer, bufferWidth: bufferWidth, bufferHeight: bufferHeight
  56135. });
  56136. vertexData.applyToMesh(ground, updatable);
  56137. ground._setReady(true);
  56138. //execute ready callback, if set
  56139. if (onReady) {
  56140. onReady(ground);
  56141. }
  56142. };
  56143. BABYLON.Tools.LoadImage(url, onload, function () { }, scene.database);
  56144. return ground;
  56145. };
  56146. /**
  56147. * Creates a polygon mesh.
  56148. * The polygon's shape will depend on the input parameters and is constructed parallel to a ground mesh.
  56149. * 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.
  56150. * You can set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  56151. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  56152. * 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).
  56153. * Remember you can only change the shape positions, not their number when updating a polygon.
  56154. */
  56155. MeshBuilder.CreatePolygon = function (name, options, scene) {
  56156. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  56157. var shape = options.shape;
  56158. var holes = options.holes || [];
  56159. var depth = options.depth || 0;
  56160. var contours = [];
  56161. var hole = [];
  56162. for (var i = 0; i < shape.length; i++) {
  56163. contours[i] = new BABYLON.Vector2(shape[i].x, shape[i].z);
  56164. }
  56165. var epsilon = 0.00000001;
  56166. if (contours[0].equalsWithEpsilon(contours[contours.length - 1], epsilon)) {
  56167. contours.pop();
  56168. }
  56169. var polygonTriangulation = new BABYLON.PolygonMeshBuilder(name, contours, scene);
  56170. for (var hNb = 0; hNb < holes.length; hNb++) {
  56171. hole = [];
  56172. for (var hPoint = 0; hPoint < holes[hNb].length; hPoint++) {
  56173. hole.push(new BABYLON.Vector2(holes[hNb][hPoint].x, holes[hNb][hPoint].z));
  56174. }
  56175. polygonTriangulation.addHole(hole);
  56176. }
  56177. var polygon = polygonTriangulation.build(options.updatable, depth);
  56178. polygon._originalBuilderSideOrientation = options.sideOrientation;
  56179. var vertexData = BABYLON.VertexData.CreatePolygon(polygon, options.sideOrientation, options.faceUV, options.faceColors, options.frontUVs, options.backUVs);
  56180. vertexData.applyToMesh(polygon, options.updatable);
  56181. return polygon;
  56182. };
  56183. ;
  56184. /**
  56185. * Creates an extruded polygon mesh, with depth in the Y direction.
  56186. * 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).
  56187. * Please read this tutorial : http://doc.babylonjs.com/tutorials/CreateBox_Per_Face_Textures_And_Colors
  56188. */
  56189. MeshBuilder.ExtrudePolygon = function (name, options, scene) {
  56190. return MeshBuilder.CreatePolygon(name, options, scene);
  56191. };
  56192. ;
  56193. /**
  56194. * Creates a tube mesh.
  56195. * 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.
  56196. *
  56197. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#tube
  56198. * The parameter `path` is a required array of successive Vector3. It is the curve used as the axis of the tube.
  56199. * The parameter `radius` (positive float, default 1) sets the tube radius size.
  56200. * The parameter `tessellation` (positive float, default 64) is the number of sides on the tubular surface.
  56201. * The parameter `radiusFunction` (javascript function, default null) is a vanilla javascript function. If it is not null, it overwrittes the parameter `radius`.
  56202. * 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.
  56203. * It must return a radius value (positive float) :
  56204. * ```javascript
  56205. * var radiusFunction = function(i, distance) {
  56206. * // do things
  56207. * return radius; }
  56208. * ```
  56209. * The parameter `arc` (positive float, maximum 1, default 1) is the ratio to apply to the tube circumference : 2 x PI x arc.
  56210. * 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
  56211. * 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
  56212. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  56213. * 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).
  56214. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  56215. * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture.
  56216. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  56217. */
  56218. MeshBuilder.CreateTube = function (name, options, scene) {
  56219. var path = options.path;
  56220. var instance = options.instance;
  56221. var radius = 1.0;
  56222. if (instance) {
  56223. radius = instance.radius;
  56224. }
  56225. if (options.radius !== undefined) {
  56226. radius = options.radius;
  56227. }
  56228. ;
  56229. var tessellation = options.tessellation || 64 | 0;
  56230. var radiusFunction = options.radiusFunction || null;
  56231. var cap = options.cap || BABYLON.Mesh.NO_CAP;
  56232. var invertUV = options.invertUV || false;
  56233. var updatable = options.updatable;
  56234. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  56235. options.arc = options.arc && (options.arc <= 0.0 || options.arc > 1.0) ? 1.0 : options.arc || 1.0;
  56236. // tube geometry
  56237. var tubePathArray = function (path, path3D, circlePaths, radius, tessellation, radiusFunction, cap, arc) {
  56238. var tangents = path3D.getTangents();
  56239. var normals = path3D.getNormals();
  56240. var distances = path3D.getDistances();
  56241. var pi2 = Math.PI * 2;
  56242. var step = pi2 / tessellation * arc;
  56243. var returnRadius = function () { return radius; };
  56244. var radiusFunctionFinal = radiusFunction || returnRadius;
  56245. var circlePath;
  56246. var rad;
  56247. var normal;
  56248. var rotated;
  56249. var rotationMatrix = BABYLON.Tmp.Matrix[0];
  56250. var index = (cap === BABYLON.Mesh._NO_CAP || cap === BABYLON.Mesh.CAP_END) ? 0 : 2;
  56251. for (var i = 0; i < path.length; i++) {
  56252. rad = radiusFunctionFinal(i, distances[i]); // current radius
  56253. circlePath = Array(); // current circle array
  56254. normal = normals[i]; // current normal
  56255. for (var t = 0; t < tessellation; t++) {
  56256. BABYLON.Matrix.RotationAxisToRef(tangents[i], step * t, rotationMatrix);
  56257. rotated = circlePath[t] ? circlePath[t] : BABYLON.Vector3.Zero();
  56258. BABYLON.Vector3.TransformCoordinatesToRef(normal, rotationMatrix, rotated);
  56259. rotated.scaleInPlace(rad).addInPlace(path[i]);
  56260. circlePath[t] = rotated;
  56261. }
  56262. circlePaths[index] = circlePath;
  56263. index++;
  56264. }
  56265. // cap
  56266. var capPath = function (nbPoints, pathIndex) {
  56267. var pointCap = Array();
  56268. for (var i = 0; i < nbPoints; i++) {
  56269. pointCap.push(path[pathIndex]);
  56270. }
  56271. return pointCap;
  56272. };
  56273. switch (cap) {
  56274. case BABYLON.Mesh.NO_CAP:
  56275. break;
  56276. case BABYLON.Mesh.CAP_START:
  56277. circlePaths[0] = capPath(tessellation, 0);
  56278. circlePaths[1] = circlePaths[2].slice(0);
  56279. break;
  56280. case BABYLON.Mesh.CAP_END:
  56281. circlePaths[index] = circlePaths[index - 1].slice(0);
  56282. circlePaths[index + 1] = capPath(tessellation, path.length - 1);
  56283. break;
  56284. case BABYLON.Mesh.CAP_ALL:
  56285. circlePaths[0] = capPath(tessellation, 0);
  56286. circlePaths[1] = circlePaths[2].slice(0);
  56287. circlePaths[index] = circlePaths[index - 1].slice(0);
  56288. circlePaths[index + 1] = capPath(tessellation, path.length - 1);
  56289. break;
  56290. default:
  56291. break;
  56292. }
  56293. return circlePaths;
  56294. };
  56295. var path3D;
  56296. var pathArray;
  56297. if (instance) {
  56298. var arc = options.arc || instance.arc;
  56299. path3D = (instance.path3D).update(path);
  56300. pathArray = tubePathArray(path, path3D, instance.pathArray, radius, instance.tessellation, radiusFunction, instance.cap, arc);
  56301. instance = MeshBuilder.CreateRibbon("", { pathArray: pathArray, instance: instance });
  56302. instance.path3D = path3D;
  56303. instance.pathArray = pathArray;
  56304. instance.arc = arc;
  56305. instance.radius = radius;
  56306. return instance;
  56307. }
  56308. // tube creation
  56309. path3D = new BABYLON.Path3D(path);
  56310. var newPathArray = new Array();
  56311. cap = (cap < 0 || cap > 3) ? 0 : cap;
  56312. pathArray = tubePathArray(path, path3D, newPathArray, radius, tessellation, radiusFunction, cap, options.arc);
  56313. var tube = MeshBuilder.CreateRibbon(name, { pathArray: pathArray, closePath: true, closeArray: false, updatable: updatable, sideOrientation: sideOrientation, invertUV: invertUV, frontUVs: options.frontUVs, backUVs: options.backUVs }, scene);
  56314. tube.pathArray = pathArray;
  56315. tube.path3D = path3D;
  56316. tube.tessellation = tessellation;
  56317. tube.cap = cap;
  56318. tube.arc = options.arc;
  56319. tube.radius = radius;
  56320. return tube;
  56321. };
  56322. /**
  56323. * Creates a polyhedron mesh.
  56324. *
  56325. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#polyhedron
  56326. * 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
  56327. * to choose the wanted type.
  56328. * The parameter `size` (positive float, default 1) sets the polygon size.
  56329. * You can overwrite the `size` on each dimension bu using the parameters `sizeX`, `sizeY` or `sizeZ` (positive floats, default to `size` value).
  56330. * 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`.
  56331. * 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
  56332. * 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)`).
  56333. * 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
  56334. * 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.
  56335. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  56336. * 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).
  56337. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  56338. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  56339. */
  56340. MeshBuilder.CreatePolyhedron = function (name, options, scene) {
  56341. var polyhedron = new BABYLON.Mesh(name, scene);
  56342. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  56343. polyhedron._originalBuilderSideOrientation = options.sideOrientation;
  56344. var vertexData = BABYLON.VertexData.CreatePolyhedron(options);
  56345. vertexData.applyToMesh(polyhedron, options.updatable);
  56346. return polyhedron;
  56347. };
  56348. /**
  56349. * Creates a decal mesh.
  56350. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#decals
  56351. * 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.
  56352. * The parameter `position` (Vector3, default `(0, 0, 0)`) sets the position of the decal in World coordinates.
  56353. * The parameter `normal` (Vector3, default `Vector3.Up`) sets the normal of the mesh where the decal is applied onto in World coordinates.
  56354. * The parameter `size` (Vector3, default `(1, 1, 1)`) sets the decal scaling.
  56355. * The parameter `angle` (float in radian, default 0) sets the angle to rotate the decal.
  56356. */
  56357. MeshBuilder.CreateDecal = function (name, sourceMesh, options) {
  56358. var indices = sourceMesh.getIndices();
  56359. var positions = sourceMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  56360. var normals = sourceMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  56361. var position = options.position || BABYLON.Vector3.Zero();
  56362. var normal = options.normal || BABYLON.Vector3.Up();
  56363. var size = options.size || BABYLON.Vector3.One();
  56364. var angle = options.angle || 0;
  56365. // Getting correct rotation
  56366. if (!normal) {
  56367. var target = new BABYLON.Vector3(0, 0, 1);
  56368. var camera = sourceMesh.getScene().activeCamera;
  56369. var cameraWorldTarget = BABYLON.Vector3.TransformCoordinates(target, camera.getWorldMatrix());
  56370. normal = camera.globalPosition.subtract(cameraWorldTarget);
  56371. }
  56372. var yaw = -Math.atan2(normal.z, normal.x) - Math.PI / 2;
  56373. var len = Math.sqrt(normal.x * normal.x + normal.z * normal.z);
  56374. var pitch = Math.atan2(normal.y, len);
  56375. // Matrix
  56376. var decalWorldMatrix = BABYLON.Matrix.RotationYawPitchRoll(yaw, pitch, angle).multiply(BABYLON.Matrix.Translation(position.x, position.y, position.z));
  56377. var inverseDecalWorldMatrix = BABYLON.Matrix.Invert(decalWorldMatrix);
  56378. var meshWorldMatrix = sourceMesh.getWorldMatrix();
  56379. var transformMatrix = meshWorldMatrix.multiply(inverseDecalWorldMatrix);
  56380. var vertexData = new BABYLON.VertexData();
  56381. vertexData.indices = [];
  56382. vertexData.positions = [];
  56383. vertexData.normals = [];
  56384. vertexData.uvs = [];
  56385. var currentVertexDataIndex = 0;
  56386. var extractDecalVector3 = function (indexId) {
  56387. var result = new BABYLON.PositionNormalVertex();
  56388. if (!indices || !positions || !normals) {
  56389. return result;
  56390. }
  56391. var vertexId = indices[indexId];
  56392. result.position = new BABYLON.Vector3(positions[vertexId * 3], positions[vertexId * 3 + 1], positions[vertexId * 3 + 2]);
  56393. // Send vector to decal local world
  56394. result.position = BABYLON.Vector3.TransformCoordinates(result.position, transformMatrix);
  56395. // Get normal
  56396. result.normal = new BABYLON.Vector3(normals[vertexId * 3], normals[vertexId * 3 + 1], normals[vertexId * 3 + 2]);
  56397. result.normal = BABYLON.Vector3.TransformNormal(result.normal, transformMatrix);
  56398. return result;
  56399. }; // Inspired by https://github.com/mrdoob/three.js/blob/eee231960882f6f3b6113405f524956145148146/examples/js/geometries/DecalGeometry.js
  56400. var clip = function (vertices, axis) {
  56401. if (vertices.length === 0) {
  56402. return vertices;
  56403. }
  56404. var clipSize = 0.5 * Math.abs(BABYLON.Vector3.Dot(size, axis));
  56405. var clipVertices = function (v0, v1) {
  56406. var clipFactor = BABYLON.Vector3.GetClipFactor(v0.position, v1.position, axis, clipSize);
  56407. return new BABYLON.PositionNormalVertex(BABYLON.Vector3.Lerp(v0.position, v1.position, clipFactor), BABYLON.Vector3.Lerp(v0.normal, v1.normal, clipFactor));
  56408. };
  56409. var result = new Array();
  56410. for (var index = 0; index < vertices.length; index += 3) {
  56411. var v1Out;
  56412. var v2Out;
  56413. var v3Out;
  56414. var total = 0;
  56415. var nV1 = null;
  56416. var nV2 = null;
  56417. var nV3 = null;
  56418. var nV4 = null;
  56419. var d1 = BABYLON.Vector3.Dot(vertices[index].position, axis) - clipSize;
  56420. var d2 = BABYLON.Vector3.Dot(vertices[index + 1].position, axis) - clipSize;
  56421. var d3 = BABYLON.Vector3.Dot(vertices[index + 2].position, axis) - clipSize;
  56422. v1Out = d1 > 0;
  56423. v2Out = d2 > 0;
  56424. v3Out = d3 > 0;
  56425. total = (v1Out ? 1 : 0) + (v2Out ? 1 : 0) + (v3Out ? 1 : 0);
  56426. switch (total) {
  56427. case 0:
  56428. result.push(vertices[index]);
  56429. result.push(vertices[index + 1]);
  56430. result.push(vertices[index + 2]);
  56431. break;
  56432. case 1:
  56433. if (v1Out) {
  56434. nV1 = vertices[index + 1];
  56435. nV2 = vertices[index + 2];
  56436. nV3 = clipVertices(vertices[index], nV1);
  56437. nV4 = clipVertices(vertices[index], nV2);
  56438. }
  56439. if (v2Out) {
  56440. nV1 = vertices[index];
  56441. nV2 = vertices[index + 2];
  56442. nV3 = clipVertices(vertices[index + 1], nV1);
  56443. nV4 = clipVertices(vertices[index + 1], nV2);
  56444. result.push(nV3);
  56445. result.push(nV2.clone());
  56446. result.push(nV1.clone());
  56447. result.push(nV2.clone());
  56448. result.push(nV3.clone());
  56449. result.push(nV4);
  56450. break;
  56451. }
  56452. if (v3Out) {
  56453. nV1 = vertices[index];
  56454. nV2 = vertices[index + 1];
  56455. nV3 = clipVertices(vertices[index + 2], nV1);
  56456. nV4 = clipVertices(vertices[index + 2], nV2);
  56457. }
  56458. if (nV1 && nV2 && nV3 && nV4) {
  56459. result.push(nV1.clone());
  56460. result.push(nV2.clone());
  56461. result.push(nV3);
  56462. result.push(nV4);
  56463. result.push(nV3.clone());
  56464. result.push(nV2.clone());
  56465. }
  56466. break;
  56467. case 2:
  56468. if (!v1Out) {
  56469. nV1 = vertices[index].clone();
  56470. nV2 = clipVertices(nV1, vertices[index + 1]);
  56471. nV3 = clipVertices(nV1, vertices[index + 2]);
  56472. result.push(nV1);
  56473. result.push(nV2);
  56474. result.push(nV3);
  56475. }
  56476. if (!v2Out) {
  56477. nV1 = vertices[index + 1].clone();
  56478. nV2 = clipVertices(nV1, vertices[index + 2]);
  56479. nV3 = clipVertices(nV1, vertices[index]);
  56480. result.push(nV1);
  56481. result.push(nV2);
  56482. result.push(nV3);
  56483. }
  56484. if (!v3Out) {
  56485. nV1 = vertices[index + 2].clone();
  56486. nV2 = clipVertices(nV1, vertices[index]);
  56487. nV3 = clipVertices(nV1, vertices[index + 1]);
  56488. result.push(nV1);
  56489. result.push(nV2);
  56490. result.push(nV3);
  56491. }
  56492. break;
  56493. case 3:
  56494. break;
  56495. }
  56496. }
  56497. return result;
  56498. };
  56499. for (var index = 0; index < indices.length; index += 3) {
  56500. var faceVertices = new Array();
  56501. faceVertices.push(extractDecalVector3(index));
  56502. faceVertices.push(extractDecalVector3(index + 1));
  56503. faceVertices.push(extractDecalVector3(index + 2));
  56504. // Clip
  56505. faceVertices = clip(faceVertices, new BABYLON.Vector3(1, 0, 0));
  56506. faceVertices = clip(faceVertices, new BABYLON.Vector3(-1, 0, 0));
  56507. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, 1, 0));
  56508. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, -1, 0));
  56509. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, 0, 1));
  56510. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, 0, -1));
  56511. if (faceVertices.length === 0) {
  56512. continue;
  56513. }
  56514. // Add UVs and get back to world
  56515. for (var vIndex = 0; vIndex < faceVertices.length; vIndex++) {
  56516. var vertex = faceVertices[vIndex];
  56517. //TODO check for Int32Array | Uint32Array | Uint16Array
  56518. vertexData.indices.push(currentVertexDataIndex);
  56519. vertex.position.toArray(vertexData.positions, currentVertexDataIndex * 3);
  56520. vertex.normal.toArray(vertexData.normals, currentVertexDataIndex * 3);
  56521. vertexData.uvs.push(0.5 + vertex.position.x / size.x);
  56522. vertexData.uvs.push(0.5 + vertex.position.y / size.y);
  56523. currentVertexDataIndex++;
  56524. }
  56525. }
  56526. // Return mesh
  56527. var decal = new BABYLON.Mesh(name, sourceMesh.getScene());
  56528. vertexData.applyToMesh(decal);
  56529. decal.position = position.clone();
  56530. decal.rotation = new BABYLON.Vector3(pitch, yaw, angle);
  56531. return decal;
  56532. };
  56533. // Privates
  56534. MeshBuilder._ExtrudeShapeGeneric = function (name, shape, curve, scale, rotation, scaleFunction, rotateFunction, rbCA, rbCP, cap, custom, scene, updtbl, side, instance, invertUV, frontUVs, backUVs) {
  56535. // extrusion geometry
  56536. var extrusionPathArray = function (shape, curve, path3D, shapePaths, scale, rotation, scaleFunction, rotateFunction, cap, custom) {
  56537. var tangents = path3D.getTangents();
  56538. var normals = path3D.getNormals();
  56539. var binormals = path3D.getBinormals();
  56540. var distances = path3D.getDistances();
  56541. var angle = 0;
  56542. var returnScale = function () { return scale !== null ? scale : 1; };
  56543. var returnRotation = function () { return rotation !== null ? rotation : 0; };
  56544. var rotate = custom && rotateFunction ? rotateFunction : returnRotation;
  56545. var scl = custom && scaleFunction ? scaleFunction : returnScale;
  56546. var index = (cap === BABYLON.Mesh.NO_CAP || cap === BABYLON.Mesh.CAP_END) ? 0 : 2;
  56547. var rotationMatrix = BABYLON.Tmp.Matrix[0];
  56548. for (var i = 0; i < curve.length; i++) {
  56549. var shapePath = new Array();
  56550. var angleStep = rotate(i, distances[i]);
  56551. var scaleRatio = scl(i, distances[i]);
  56552. for (var p = 0; p < shape.length; p++) {
  56553. BABYLON.Matrix.RotationAxisToRef(tangents[i], angle, rotationMatrix);
  56554. var planed = ((tangents[i].scale(shape[p].z)).add(normals[i].scale(shape[p].x)).add(binormals[i].scale(shape[p].y)));
  56555. var rotated = shapePath[p] ? shapePath[p] : BABYLON.Vector3.Zero();
  56556. BABYLON.Vector3.TransformCoordinatesToRef(planed, rotationMatrix, rotated);
  56557. rotated.scaleInPlace(scaleRatio).addInPlace(curve[i]);
  56558. shapePath[p] = rotated;
  56559. }
  56560. shapePaths[index] = shapePath;
  56561. angle += angleStep;
  56562. index++;
  56563. }
  56564. // cap
  56565. var capPath = function (shapePath) {
  56566. var pointCap = Array();
  56567. var barycenter = BABYLON.Vector3.Zero();
  56568. var i;
  56569. for (i = 0; i < shapePath.length; i++) {
  56570. barycenter.addInPlace(shapePath[i]);
  56571. }
  56572. barycenter.scaleInPlace(1.0 / shapePath.length);
  56573. for (i = 0; i < shapePath.length; i++) {
  56574. pointCap.push(barycenter);
  56575. }
  56576. return pointCap;
  56577. };
  56578. switch (cap) {
  56579. case BABYLON.Mesh.NO_CAP:
  56580. break;
  56581. case BABYLON.Mesh.CAP_START:
  56582. shapePaths[0] = capPath(shapePaths[2]);
  56583. shapePaths[1] = shapePaths[2];
  56584. break;
  56585. case BABYLON.Mesh.CAP_END:
  56586. shapePaths[index] = shapePaths[index - 1];
  56587. shapePaths[index + 1] = capPath(shapePaths[index - 1]);
  56588. break;
  56589. case BABYLON.Mesh.CAP_ALL:
  56590. shapePaths[0] = capPath(shapePaths[2]);
  56591. shapePaths[1] = shapePaths[2];
  56592. shapePaths[index] = shapePaths[index - 1];
  56593. shapePaths[index + 1] = capPath(shapePaths[index - 1]);
  56594. break;
  56595. default:
  56596. break;
  56597. }
  56598. return shapePaths;
  56599. };
  56600. var path3D;
  56601. var pathArray;
  56602. if (instance) {
  56603. path3D = (instance.path3D).update(curve);
  56604. pathArray = extrusionPathArray(shape, curve, instance.path3D, instance.pathArray, scale, rotation, scaleFunction, rotateFunction, instance.cap, custom);
  56605. instance = BABYLON.Mesh.CreateRibbon("", pathArray, false, false, 0, scene || undefined, false, 0, instance);
  56606. return instance;
  56607. }
  56608. // extruded shape creation
  56609. path3D = new BABYLON.Path3D(curve);
  56610. var newShapePaths = new Array();
  56611. cap = (cap < 0 || cap > 3) ? 0 : cap;
  56612. pathArray = extrusionPathArray(shape, curve, path3D, newShapePaths, scale, rotation, scaleFunction, rotateFunction, cap, custom);
  56613. var extrudedGeneric = MeshBuilder.CreateRibbon(name, { pathArray: pathArray, closeArray: rbCA, closePath: rbCP, updatable: updtbl, sideOrientation: side, invertUV: invertUV, frontUVs: frontUVs || undefined, backUVs: backUVs || undefined }, scene);
  56614. extrudedGeneric.pathArray = pathArray;
  56615. extrudedGeneric.path3D = path3D;
  56616. extrudedGeneric.cap = cap;
  56617. return extrudedGeneric;
  56618. };
  56619. return MeshBuilder;
  56620. }());
  56621. BABYLON.MeshBuilder = MeshBuilder;
  56622. })(BABYLON || (BABYLON = {}));
  56623. //# sourceMappingURL=babylon.meshBuilder.js.map
  56624. var BABYLON;
  56625. (function (BABYLON) {
  56626. /**
  56627. * Draco compression (https://google.github.io/draco/)
  56628. */
  56629. var DracoCompression = /** @class */ (function () {
  56630. /**
  56631. * Constructor
  56632. * @param numWorkers The number of workers for async operations
  56633. */
  56634. function DracoCompression(numWorkers) {
  56635. if (numWorkers === void 0) { numWorkers = (navigator.hardwareConcurrency || 4); }
  56636. var workerBlobUrl = URL && URL.createObjectURL && URL.createObjectURL(new Blob(["(" + DracoCompression._Worker.toString() + ")()"], { type: "application/javascript" }));
  56637. if (!workerBlobUrl || !Worker) {
  56638. BABYLON.Tools.Error("Draco Compression disabled. The current context doesn't support worker creation or URL.createObjectURL");
  56639. return;
  56640. }
  56641. var workers = new Array(numWorkers);
  56642. for (var i = 0; i < workers.length; i++) {
  56643. var worker = new Worker(workerBlobUrl);
  56644. worker.postMessage({ id: "initDecoder", url: DracoCompression.DecoderUrl });
  56645. workers[i] = worker;
  56646. }
  56647. this._workerPool = new BABYLON.WorkerPool(workers);
  56648. }
  56649. /**
  56650. * Stop all async operations and release resources.
  56651. */
  56652. DracoCompression.prototype.dispose = function () {
  56653. this._workerPool.dispose();
  56654. delete this._workerPool;
  56655. };
  56656. /**
  56657. * Decode Draco compressed mesh data to vertex data.
  56658. * @param data The array buffer view for the Draco compression data
  56659. * @param attributes A map of attributes from vertex buffer kinds to Draco unique ids
  56660. * @returns A promise that resolves with the decoded vertex data
  56661. */
  56662. DracoCompression.prototype.decodeMeshAsync = function (data, attributes) {
  56663. var _this = this;
  56664. return new Promise(function (resolve, reject) {
  56665. _this._workerPool.push(function (worker, onComplete) {
  56666. var vertexData = new BABYLON.VertexData();
  56667. var onError = function (error) {
  56668. worker.removeEventListener("error", onError);
  56669. worker.removeEventListener("message", onMessage);
  56670. reject(error);
  56671. onComplete();
  56672. };
  56673. var onMessage = function (message) {
  56674. if (message.data === "done") {
  56675. worker.removeEventListener("error", onError);
  56676. worker.removeEventListener("message", onMessage);
  56677. resolve(vertexData);
  56678. onComplete();
  56679. }
  56680. else if (message.data.id === "indices") {
  56681. vertexData.indices = message.data.value;
  56682. }
  56683. else {
  56684. vertexData.set(message.data.value, message.data.id);
  56685. }
  56686. };
  56687. worker.addEventListener("error", onError);
  56688. worker.addEventListener("message", onMessage);
  56689. var dataCopy = new Uint8Array(data.byteLength);
  56690. dataCopy.set(new Uint8Array(data.buffer, data.byteOffset, data.byteLength));
  56691. worker.postMessage({ id: "decodeMesh", data: dataCopy, attributes: attributes }, [dataCopy.buffer]);
  56692. });
  56693. });
  56694. };
  56695. /**
  56696. * The worker function that gets converted to a blob url to pass into a worker.
  56697. */
  56698. DracoCompression._Worker = function () {
  56699. // self is actually a DedicatedWorkerGlobalScope
  56700. var _self = self;
  56701. var decodeMesh = function (data, attributes) {
  56702. var dracoModule = new DracoDecoderModule();
  56703. var buffer = new dracoModule.DecoderBuffer();
  56704. buffer.Init(data, data.byteLength);
  56705. var decoder = new dracoModule.Decoder();
  56706. var geometry;
  56707. var status;
  56708. try {
  56709. var type = decoder.GetEncodedGeometryType(buffer);
  56710. switch (type) {
  56711. case dracoModule.TRIANGULAR_MESH:
  56712. geometry = new dracoModule.Mesh();
  56713. status = decoder.DecodeBufferToMesh(buffer, geometry);
  56714. break;
  56715. case dracoModule.POINT_CLOUD:
  56716. geometry = new dracoModule.PointCloud();
  56717. status = decoder.DecodeBufferToPointCloud(buffer, geometry);
  56718. break;
  56719. default:
  56720. throw new Error("Invalid geometry type " + type);
  56721. }
  56722. if (!status.ok() || !geometry.ptr) {
  56723. throw new Error(status.error_msg());
  56724. }
  56725. var numPoints = geometry.num_points();
  56726. if (type === dracoModule.TRIANGULAR_MESH) {
  56727. var numFaces = geometry.num_faces();
  56728. var faceIndices = new dracoModule.DracoInt32Array();
  56729. try {
  56730. var indices = new Uint32Array(numFaces * 3);
  56731. for (var i = 0; i < numFaces; i++) {
  56732. decoder.GetFaceFromMesh(geometry, i, faceIndices);
  56733. var offset = i * 3;
  56734. indices[offset + 0] = faceIndices.GetValue(0);
  56735. indices[offset + 1] = faceIndices.GetValue(1);
  56736. indices[offset + 2] = faceIndices.GetValue(2);
  56737. }
  56738. _self.postMessage({ id: "indices", value: indices }, [indices.buffer]);
  56739. }
  56740. finally {
  56741. dracoModule.destroy(faceIndices);
  56742. }
  56743. }
  56744. for (var kind in attributes) {
  56745. var uniqueId = attributes[kind];
  56746. var attribute = decoder.GetAttributeByUniqueId(geometry, uniqueId);
  56747. var dracoData = new dracoModule.DracoFloat32Array();
  56748. try {
  56749. decoder.GetAttributeFloatForAllPoints(geometry, attribute, dracoData);
  56750. var babylonData = new Float32Array(numPoints * attribute.num_components());
  56751. for (var i = 0; i < babylonData.length; i++) {
  56752. babylonData[i] = dracoData.GetValue(i);
  56753. }
  56754. _self.postMessage({ id: kind, value: babylonData }, [babylonData.buffer]);
  56755. }
  56756. finally {
  56757. dracoModule.destroy(dracoData);
  56758. }
  56759. }
  56760. }
  56761. finally {
  56762. if (geometry) {
  56763. dracoModule.destroy(geometry);
  56764. }
  56765. dracoModule.destroy(decoder);
  56766. dracoModule.destroy(buffer);
  56767. }
  56768. _self.postMessage("done");
  56769. };
  56770. _self.onmessage = function (event) {
  56771. switch (event.data.id) {
  56772. case "initDecoder": {
  56773. importScripts(event.data.url);
  56774. break;
  56775. }
  56776. case "decodeMesh": {
  56777. decodeMesh(event.data.data, event.data.attributes);
  56778. break;
  56779. }
  56780. }
  56781. };
  56782. };
  56783. DracoCompression._GetDefaultDecoderUrl = function () {
  56784. if (!BABYLON.Tools.IsWindowObjectExist) {
  56785. return null;
  56786. }
  56787. for (var i = 0; i < document.scripts.length; i++) {
  56788. if (document.scripts[i].type === "text/x-draco-decoder") {
  56789. return document.scripts[i].src;
  56790. }
  56791. }
  56792. return null;
  56793. };
  56794. /**
  56795. * Gets the url to the draco decoder if available.
  56796. */
  56797. DracoCompression.DecoderUrl = DracoCompression._GetDefaultDecoderUrl();
  56798. return DracoCompression;
  56799. }());
  56800. BABYLON.DracoCompression = DracoCompression;
  56801. })(BABYLON || (BABYLON = {}));
  56802. //# sourceMappingURL=babylon.dracoCompression.js.map
  56803. var BABYLON;
  56804. (function (BABYLON) {
  56805. var AudioEngine = /** @class */ (function () {
  56806. function AudioEngine() {
  56807. this._audioContext = null;
  56808. this._audioContextInitialized = false;
  56809. this.canUseWebAudio = false;
  56810. this.WarnedWebAudioUnsupported = false;
  56811. this.unlocked = false;
  56812. this.isMP3supported = false;
  56813. this.isOGGsupported = false;
  56814. if (typeof window.AudioContext !== 'undefined' || typeof window.webkitAudioContext !== 'undefined') {
  56815. window.AudioContext = window.AudioContext || window.webkitAudioContext;
  56816. this.canUseWebAudio = true;
  56817. }
  56818. var audioElem = document.createElement('audio');
  56819. try {
  56820. if (audioElem && !!audioElem.canPlayType && audioElem.canPlayType('audio/mpeg; codecs="mp3"').replace(/^no$/, '')) {
  56821. this.isMP3supported = true;
  56822. }
  56823. }
  56824. catch (e) {
  56825. // protect error during capability check.
  56826. }
  56827. try {
  56828. if (audioElem && !!audioElem.canPlayType && audioElem.canPlayType('audio/ogg; codecs="vorbis"').replace(/^no$/, '')) {
  56829. this.isOGGsupported = true;
  56830. }
  56831. }
  56832. catch (e) {
  56833. // protect error during capability check.
  56834. }
  56835. if (/iPad|iPhone|iPod/.test(navigator.platform)) {
  56836. this._unlockiOSaudio();
  56837. }
  56838. else {
  56839. this.unlocked = true;
  56840. }
  56841. }
  56842. Object.defineProperty(AudioEngine.prototype, "audioContext", {
  56843. get: function () {
  56844. if (!this._audioContextInitialized) {
  56845. this._initializeAudioContext();
  56846. }
  56847. return this._audioContext;
  56848. },
  56849. enumerable: true,
  56850. configurable: true
  56851. });
  56852. AudioEngine.prototype._unlockiOSaudio = function () {
  56853. var _this = this;
  56854. var unlockaudio = function () {
  56855. if (!_this.audioContext) {
  56856. return;
  56857. }
  56858. var buffer = _this.audioContext.createBuffer(1, 1, 22050);
  56859. var source = _this.audioContext.createBufferSource();
  56860. source.buffer = buffer;
  56861. source.connect(_this.audioContext.destination);
  56862. source.start(0);
  56863. setTimeout(function () {
  56864. if ((source.playbackState === source.PLAYING_STATE || source.playbackState === source.FINISHED_STATE)) {
  56865. _this.unlocked = true;
  56866. window.removeEventListener('touchend', unlockaudio, false);
  56867. if (_this.onAudioUnlocked) {
  56868. _this.onAudioUnlocked();
  56869. }
  56870. }
  56871. }, 0);
  56872. };
  56873. window.addEventListener('touchend', unlockaudio, false);
  56874. };
  56875. AudioEngine.prototype._initializeAudioContext = function () {
  56876. try {
  56877. if (this.canUseWebAudio) {
  56878. this._audioContext = new AudioContext();
  56879. // create a global volume gain node
  56880. this.masterGain = this._audioContext.createGain();
  56881. this.masterGain.gain.value = 1;
  56882. this.masterGain.connect(this._audioContext.destination);
  56883. this._audioContextInitialized = true;
  56884. }
  56885. }
  56886. catch (e) {
  56887. this.canUseWebAudio = false;
  56888. BABYLON.Tools.Error("Web Audio: " + e.message);
  56889. }
  56890. };
  56891. AudioEngine.prototype.dispose = function () {
  56892. if (this.canUseWebAudio && this._audioContextInitialized) {
  56893. if (this._connectedAnalyser && this._audioContext) {
  56894. this._connectedAnalyser.stopDebugCanvas();
  56895. this._connectedAnalyser.dispose();
  56896. this.masterGain.disconnect();
  56897. this.masterGain.connect(this._audioContext.destination);
  56898. this._connectedAnalyser = null;
  56899. }
  56900. this.masterGain.gain.value = 1;
  56901. }
  56902. this.WarnedWebAudioUnsupported = false;
  56903. };
  56904. AudioEngine.prototype.getGlobalVolume = function () {
  56905. if (this.canUseWebAudio && this._audioContextInitialized) {
  56906. return this.masterGain.gain.value;
  56907. }
  56908. else {
  56909. return -1;
  56910. }
  56911. };
  56912. AudioEngine.prototype.setGlobalVolume = function (newVolume) {
  56913. if (this.canUseWebAudio && this._audioContextInitialized) {
  56914. this.masterGain.gain.value = newVolume;
  56915. }
  56916. };
  56917. AudioEngine.prototype.connectToAnalyser = function (analyser) {
  56918. if (this._connectedAnalyser) {
  56919. this._connectedAnalyser.stopDebugCanvas();
  56920. }
  56921. if (this.canUseWebAudio && this._audioContextInitialized && this._audioContext) {
  56922. this._connectedAnalyser = analyser;
  56923. this.masterGain.disconnect();
  56924. this._connectedAnalyser.connectAudioNodes(this.masterGain, this._audioContext.destination);
  56925. }
  56926. };
  56927. return AudioEngine;
  56928. }());
  56929. BABYLON.AudioEngine = AudioEngine;
  56930. })(BABYLON || (BABYLON = {}));
  56931. //# sourceMappingURL=babylon.audioEngine.js.map
  56932. var BABYLON;
  56933. (function (BABYLON) {
  56934. var Sound = /** @class */ (function () {
  56935. /**
  56936. * Create a sound and attach it to a scene
  56937. * @param name Name of your sound
  56938. * @param urlOrArrayBuffer Url to the sound to load async or ArrayBuffer
  56939. * @param readyToPlayCallback Provide a callback function if you'd like to load your code once the sound is ready to be played
  56940. * @param options Objects to provide with the current available options: autoplay, loop, volume, spatialSound, maxDistance, rolloffFactor, refDistance, distanceModel, panningModel, streaming
  56941. */
  56942. function Sound(name, urlOrArrayBuffer, scene, readyToPlayCallback, options) {
  56943. if (readyToPlayCallback === void 0) { readyToPlayCallback = null; }
  56944. var _this = this;
  56945. this.autoplay = false;
  56946. this.loop = false;
  56947. this.useCustomAttenuation = false;
  56948. this.spatialSound = false;
  56949. this.refDistance = 1;
  56950. this.rolloffFactor = 1;
  56951. this.maxDistance = 100;
  56952. this.distanceModel = "linear";
  56953. this._panningModel = "equalpower";
  56954. this._playbackRate = 1;
  56955. this._streaming = false;
  56956. this._startTime = 0;
  56957. this._startOffset = 0;
  56958. this._position = BABYLON.Vector3.Zero();
  56959. this._localDirection = new BABYLON.Vector3(1, 0, 0);
  56960. this._volume = 1;
  56961. this._isReadyToPlay = false;
  56962. this.isPlaying = false;
  56963. this.isPaused = false;
  56964. this._isDirectional = false;
  56965. // Used if you'd like to create a directional sound.
  56966. // If not set, the sound will be omnidirectional
  56967. this._coneInnerAngle = 360;
  56968. this._coneOuterAngle = 360;
  56969. this._coneOuterGain = 0;
  56970. this._isOutputConnected = false;
  56971. this._urlType = "Unknown";
  56972. this.name = name;
  56973. this._scene = scene;
  56974. this._readyToPlayCallback = readyToPlayCallback;
  56975. // Default custom attenuation function is a linear attenuation
  56976. this._customAttenuationFunction = function (currentVolume, currentDistance, maxDistance, refDistance, rolloffFactor) {
  56977. if (currentDistance < maxDistance) {
  56978. return currentVolume * (1 - currentDistance / maxDistance);
  56979. }
  56980. else {
  56981. return 0;
  56982. }
  56983. };
  56984. if (options) {
  56985. this.autoplay = options.autoplay || false;
  56986. this.loop = options.loop || false;
  56987. // if volume === 0, we need another way to check this option
  56988. if (options.volume !== undefined) {
  56989. this._volume = options.volume;
  56990. }
  56991. this.spatialSound = options.spatialSound || false;
  56992. this.maxDistance = options.maxDistance || 100;
  56993. this.useCustomAttenuation = options.useCustomAttenuation || false;
  56994. this.rolloffFactor = options.rolloffFactor || 1;
  56995. this.refDistance = options.refDistance || 1;
  56996. this.distanceModel = options.distanceModel || "linear";
  56997. this._playbackRate = options.playbackRate || 1;
  56998. this._streaming = options.streaming || false;
  56999. }
  57000. if (BABYLON.Engine.audioEngine.canUseWebAudio && BABYLON.Engine.audioEngine.audioContext) {
  57001. this._soundGain = BABYLON.Engine.audioEngine.audioContext.createGain();
  57002. this._soundGain.gain.value = this._volume;
  57003. this._inputAudioNode = this._soundGain;
  57004. this._ouputAudioNode = this._soundGain;
  57005. if (this.spatialSound) {
  57006. this._createSpatialParameters();
  57007. }
  57008. this._scene.mainSoundTrack.AddSound(this);
  57009. var validParameter = true;
  57010. // if no parameter is passed, you need to call setAudioBuffer yourself to prepare the sound
  57011. if (urlOrArrayBuffer) {
  57012. if (typeof (urlOrArrayBuffer) === "string")
  57013. this._urlType = "String";
  57014. if (Array.isArray(urlOrArrayBuffer))
  57015. this._urlType = "Array";
  57016. if (urlOrArrayBuffer instanceof ArrayBuffer)
  57017. this._urlType = "ArrayBuffer";
  57018. var urls = [];
  57019. var codecSupportedFound = false;
  57020. switch (this._urlType) {
  57021. case "ArrayBuffer":
  57022. if (urlOrArrayBuffer.byteLength > 0) {
  57023. codecSupportedFound = true;
  57024. this._soundLoaded(urlOrArrayBuffer);
  57025. }
  57026. break;
  57027. case "String":
  57028. urls.push(urlOrArrayBuffer);
  57029. case "Array":
  57030. if (urls.length === 0)
  57031. urls = urlOrArrayBuffer;
  57032. // If we found a supported format, we load it immediately and stop the loop
  57033. for (var i = 0; i < urls.length; i++) {
  57034. var url = urls[i];
  57035. if (url.indexOf(".mp3", url.length - 4) !== -1 && BABYLON.Engine.audioEngine.isMP3supported) {
  57036. codecSupportedFound = true;
  57037. }
  57038. if (url.indexOf(".ogg", url.length - 4) !== -1 && BABYLON.Engine.audioEngine.isOGGsupported) {
  57039. codecSupportedFound = true;
  57040. }
  57041. if (url.indexOf(".wav", url.length - 4) !== -1) {
  57042. codecSupportedFound = true;
  57043. }
  57044. if (url.indexOf("blob:") !== -1) {
  57045. codecSupportedFound = true;
  57046. }
  57047. if (codecSupportedFound) {
  57048. // Loading sound using XHR2
  57049. if (!this._streaming) {
  57050. this._scene._loadFile(url, function (data) { _this._soundLoaded(data); }, undefined, true, true);
  57051. }
  57052. else {
  57053. this._htmlAudioElement = new Audio(url);
  57054. this._htmlAudioElement.controls = false;
  57055. this._htmlAudioElement.loop = this.loop;
  57056. BABYLON.Tools.SetCorsBehavior(url, this._htmlAudioElement);
  57057. this._htmlAudioElement.preload = "auto";
  57058. this._htmlAudioElement.addEventListener("canplaythrough", function () {
  57059. _this._isReadyToPlay = true;
  57060. if (_this.autoplay) {
  57061. _this.play();
  57062. }
  57063. if (_this._readyToPlayCallback) {
  57064. _this._readyToPlayCallback();
  57065. }
  57066. });
  57067. document.body.appendChild(this._htmlAudioElement);
  57068. }
  57069. break;
  57070. }
  57071. }
  57072. break;
  57073. default:
  57074. validParameter = false;
  57075. break;
  57076. }
  57077. if (!validParameter) {
  57078. BABYLON.Tools.Error("Parameter must be a URL to the sound, an Array of URLs (.mp3 & .ogg) or an ArrayBuffer of the sound.");
  57079. }
  57080. else {
  57081. if (!codecSupportedFound) {
  57082. this._isReadyToPlay = true;
  57083. // Simulating a ready to play event to avoid breaking code path
  57084. if (this._readyToPlayCallback) {
  57085. window.setTimeout(function () {
  57086. if (_this._readyToPlayCallback) {
  57087. _this._readyToPlayCallback();
  57088. }
  57089. }, 1000);
  57090. }
  57091. }
  57092. }
  57093. }
  57094. }
  57095. else {
  57096. // Adding an empty sound to avoid breaking audio calls for non Web Audio browsers
  57097. this._scene.mainSoundTrack.AddSound(this);
  57098. if (!BABYLON.Engine.audioEngine.WarnedWebAudioUnsupported) {
  57099. BABYLON.Tools.Error("Web Audio is not supported by your browser.");
  57100. BABYLON.Engine.audioEngine.WarnedWebAudioUnsupported = true;
  57101. }
  57102. // Simulating a ready to play event to avoid breaking code for non web audio browsers
  57103. if (this._readyToPlayCallback) {
  57104. window.setTimeout(function () {
  57105. if (_this._readyToPlayCallback) {
  57106. _this._readyToPlayCallback();
  57107. }
  57108. }, 1000);
  57109. }
  57110. }
  57111. }
  57112. Sound.prototype.dispose = function () {
  57113. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._isReadyToPlay) {
  57114. if (this.isPlaying) {
  57115. this.stop();
  57116. }
  57117. this._isReadyToPlay = false;
  57118. if (this.soundTrackId === -1) {
  57119. this._scene.mainSoundTrack.RemoveSound(this);
  57120. }
  57121. else {
  57122. this._scene.soundTracks[this.soundTrackId].RemoveSound(this);
  57123. }
  57124. if (this._soundGain) {
  57125. this._soundGain.disconnect();
  57126. this._soundGain = null;
  57127. }
  57128. if (this._soundPanner) {
  57129. this._soundPanner.disconnect();
  57130. this._soundPanner = null;
  57131. }
  57132. if (this._soundSource) {
  57133. this._soundSource.disconnect();
  57134. this._soundSource = null;
  57135. }
  57136. this._audioBuffer = null;
  57137. if (this._htmlAudioElement) {
  57138. this._htmlAudioElement.pause();
  57139. this._htmlAudioElement.src = "";
  57140. document.body.removeChild(this._htmlAudioElement);
  57141. }
  57142. if (this._connectedMesh && this._registerFunc) {
  57143. this._connectedMesh.unregisterAfterWorldMatrixUpdate(this._registerFunc);
  57144. this._connectedMesh = null;
  57145. }
  57146. }
  57147. };
  57148. Sound.prototype.isReady = function () {
  57149. return this._isReadyToPlay;
  57150. };
  57151. Sound.prototype._soundLoaded = function (audioData) {
  57152. var _this = this;
  57153. if (!BABYLON.Engine.audioEngine.audioContext) {
  57154. return;
  57155. }
  57156. BABYLON.Engine.audioEngine.audioContext.decodeAudioData(audioData, function (buffer) {
  57157. _this._audioBuffer = buffer;
  57158. _this._isReadyToPlay = true;
  57159. if (_this.autoplay) {
  57160. _this.play();
  57161. }
  57162. if (_this._readyToPlayCallback) {
  57163. _this._readyToPlayCallback();
  57164. }
  57165. }, function (err) { BABYLON.Tools.Error("Error while decoding audio data for: " + _this.name + " / Error: " + err); });
  57166. };
  57167. Sound.prototype.setAudioBuffer = function (audioBuffer) {
  57168. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  57169. this._audioBuffer = audioBuffer;
  57170. this._isReadyToPlay = true;
  57171. }
  57172. };
  57173. Sound.prototype.updateOptions = function (options) {
  57174. if (options) {
  57175. this.loop = options.loop || this.loop;
  57176. this.maxDistance = options.maxDistance || this.maxDistance;
  57177. this.useCustomAttenuation = options.useCustomAttenuation || this.useCustomAttenuation;
  57178. this.rolloffFactor = options.rolloffFactor || this.rolloffFactor;
  57179. this.refDistance = options.refDistance || this.refDistance;
  57180. this.distanceModel = options.distanceModel || this.distanceModel;
  57181. this._playbackRate = options.playbackRate || this._playbackRate;
  57182. this._updateSpatialParameters();
  57183. if (this.isPlaying) {
  57184. if (this._streaming) {
  57185. this._htmlAudioElement.playbackRate = this._playbackRate;
  57186. }
  57187. else {
  57188. if (this._soundSource) {
  57189. this._soundSource.playbackRate.value = this._playbackRate;
  57190. }
  57191. }
  57192. }
  57193. }
  57194. };
  57195. Sound.prototype._createSpatialParameters = function () {
  57196. if (BABYLON.Engine.audioEngine.canUseWebAudio && BABYLON.Engine.audioEngine.audioContext) {
  57197. if (this._scene.headphone) {
  57198. this._panningModel = "HRTF";
  57199. }
  57200. this._soundPanner = BABYLON.Engine.audioEngine.audioContext.createPanner();
  57201. this._updateSpatialParameters();
  57202. this._soundPanner.connect(this._ouputAudioNode);
  57203. this._inputAudioNode = this._soundPanner;
  57204. }
  57205. };
  57206. Sound.prototype._updateSpatialParameters = function () {
  57207. if (this.spatialSound && this._soundPanner) {
  57208. if (this.useCustomAttenuation) {
  57209. // Tricks to disable in a way embedded Web Audio attenuation
  57210. this._soundPanner.distanceModel = "linear";
  57211. this._soundPanner.maxDistance = Number.MAX_VALUE;
  57212. this._soundPanner.refDistance = 1;
  57213. this._soundPanner.rolloffFactor = 1;
  57214. this._soundPanner.panningModel = this._panningModel;
  57215. }
  57216. else {
  57217. this._soundPanner.distanceModel = this.distanceModel;
  57218. this._soundPanner.maxDistance = this.maxDistance;
  57219. this._soundPanner.refDistance = this.refDistance;
  57220. this._soundPanner.rolloffFactor = this.rolloffFactor;
  57221. this._soundPanner.panningModel = this._panningModel;
  57222. }
  57223. }
  57224. };
  57225. Sound.prototype.switchPanningModelToHRTF = function () {
  57226. this._panningModel = "HRTF";
  57227. this._switchPanningModel();
  57228. };
  57229. Sound.prototype.switchPanningModelToEqualPower = function () {
  57230. this._panningModel = "equalpower";
  57231. this._switchPanningModel();
  57232. };
  57233. Sound.prototype._switchPanningModel = function () {
  57234. if (BABYLON.Engine.audioEngine.canUseWebAudio && this.spatialSound && this._soundPanner) {
  57235. this._soundPanner.panningModel = this._panningModel;
  57236. }
  57237. };
  57238. Sound.prototype.connectToSoundTrackAudioNode = function (soundTrackAudioNode) {
  57239. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  57240. if (this._isOutputConnected) {
  57241. this._ouputAudioNode.disconnect();
  57242. }
  57243. this._ouputAudioNode.connect(soundTrackAudioNode);
  57244. this._isOutputConnected = true;
  57245. }
  57246. };
  57247. /**
  57248. * Transform this sound into a directional source
  57249. * @param coneInnerAngle Size of the inner cone in degree
  57250. * @param coneOuterAngle Size of the outer cone in degree
  57251. * @param coneOuterGain Volume of the sound outside the outer cone (between 0.0 and 1.0)
  57252. */
  57253. Sound.prototype.setDirectionalCone = function (coneInnerAngle, coneOuterAngle, coneOuterGain) {
  57254. if (coneOuterAngle < coneInnerAngle) {
  57255. BABYLON.Tools.Error("setDirectionalCone(): outer angle of the cone must be superior or equal to the inner angle.");
  57256. return;
  57257. }
  57258. this._coneInnerAngle = coneInnerAngle;
  57259. this._coneOuterAngle = coneOuterAngle;
  57260. this._coneOuterGain = coneOuterGain;
  57261. this._isDirectional = true;
  57262. if (this.isPlaying && this.loop) {
  57263. this.stop();
  57264. this.play();
  57265. }
  57266. };
  57267. Sound.prototype.setPosition = function (newPosition) {
  57268. this._position = newPosition;
  57269. if (BABYLON.Engine.audioEngine.canUseWebAudio && this.spatialSound && this._soundPanner) {
  57270. this._soundPanner.setPosition(this._position.x, this._position.y, this._position.z);
  57271. }
  57272. };
  57273. Sound.prototype.setLocalDirectionToMesh = function (newLocalDirection) {
  57274. this._localDirection = newLocalDirection;
  57275. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._connectedMesh && this.isPlaying) {
  57276. this._updateDirection();
  57277. }
  57278. };
  57279. Sound.prototype._updateDirection = function () {
  57280. if (!this._connectedMesh || !this._soundPanner) {
  57281. return;
  57282. }
  57283. var mat = this._connectedMesh.getWorldMatrix();
  57284. var direction = BABYLON.Vector3.TransformNormal(this._localDirection, mat);
  57285. direction.normalize();
  57286. this._soundPanner.setOrientation(direction.x, direction.y, direction.z);
  57287. };
  57288. Sound.prototype.updateDistanceFromListener = function () {
  57289. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._connectedMesh && this.useCustomAttenuation && this._soundGain && this._scene.activeCamera) {
  57290. var distance = this._connectedMesh.getDistanceToCamera(this._scene.activeCamera);
  57291. this._soundGain.gain.value = this._customAttenuationFunction(this._volume, distance, this.maxDistance, this.refDistance, this.rolloffFactor);
  57292. }
  57293. };
  57294. Sound.prototype.setAttenuationFunction = function (callback) {
  57295. this._customAttenuationFunction = callback;
  57296. };
  57297. /**
  57298. * Play the sound
  57299. * @param time (optional) Start the sound after X seconds. Start immediately (0) by default.
  57300. * @param offset (optional) Start the sound setting it at a specific time
  57301. */
  57302. Sound.prototype.play = function (time, offset) {
  57303. var _this = this;
  57304. if (this._isReadyToPlay && this._scene.audioEnabled && BABYLON.Engine.audioEngine.audioContext) {
  57305. try {
  57306. if (this._startOffset < 0) {
  57307. time = -this._startOffset;
  57308. this._startOffset = 0;
  57309. }
  57310. var startTime = time ? BABYLON.Engine.audioEngine.audioContext.currentTime + time : BABYLON.Engine.audioEngine.audioContext.currentTime;
  57311. if (!this._soundSource || !this._streamingSource) {
  57312. if (this.spatialSound && this._soundPanner) {
  57313. this._soundPanner.setPosition(this._position.x, this._position.y, this._position.z);
  57314. if (this._isDirectional) {
  57315. this._soundPanner.coneInnerAngle = this._coneInnerAngle;
  57316. this._soundPanner.coneOuterAngle = this._coneOuterAngle;
  57317. this._soundPanner.coneOuterGain = this._coneOuterGain;
  57318. if (this._connectedMesh) {
  57319. this._updateDirection();
  57320. }
  57321. else {
  57322. this._soundPanner.setOrientation(this._localDirection.x, this._localDirection.y, this._localDirection.z);
  57323. }
  57324. }
  57325. }
  57326. }
  57327. if (this._streaming) {
  57328. if (!this._streamingSource) {
  57329. this._streamingSource = BABYLON.Engine.audioEngine.audioContext.createMediaElementSource(this._htmlAudioElement);
  57330. this._htmlAudioElement.onended = function () { _this._onended(); };
  57331. this._htmlAudioElement.playbackRate = this._playbackRate;
  57332. }
  57333. this._streamingSource.disconnect();
  57334. this._streamingSource.connect(this._inputAudioNode);
  57335. this._htmlAudioElement.play();
  57336. }
  57337. else {
  57338. this._soundSource = BABYLON.Engine.audioEngine.audioContext.createBufferSource();
  57339. this._soundSource.buffer = this._audioBuffer;
  57340. this._soundSource.connect(this._inputAudioNode);
  57341. this._soundSource.loop = this.loop;
  57342. this._soundSource.playbackRate.value = this._playbackRate;
  57343. this._soundSource.onended = function () { _this._onended(); };
  57344. if (this._soundSource.buffer) {
  57345. this._soundSource.start(startTime, this.isPaused ? this._startOffset % this._soundSource.buffer.duration : offset ? offset : 0);
  57346. }
  57347. }
  57348. this._startTime = startTime;
  57349. this.isPlaying = true;
  57350. this.isPaused = false;
  57351. }
  57352. catch (ex) {
  57353. BABYLON.Tools.Error("Error while trying to play audio: " + this.name + ", " + ex.message);
  57354. }
  57355. }
  57356. };
  57357. Sound.prototype._onended = function () {
  57358. this.isPlaying = false;
  57359. if (this.onended) {
  57360. this.onended();
  57361. }
  57362. };
  57363. /**
  57364. * Stop the sound
  57365. * @param time (optional) Stop the sound after X seconds. Stop immediately (0) by default.
  57366. */
  57367. Sound.prototype.stop = function (time) {
  57368. if (this.isPlaying) {
  57369. if (this._streaming) {
  57370. this._htmlAudioElement.pause();
  57371. // Test needed for Firefox or it will generate an Invalid State Error
  57372. if (this._htmlAudioElement.currentTime > 0) {
  57373. this._htmlAudioElement.currentTime = 0;
  57374. }
  57375. }
  57376. else if (BABYLON.Engine.audioEngine.audioContext && this._soundSource) {
  57377. var stopTime = time ? BABYLON.Engine.audioEngine.audioContext.currentTime + time : BABYLON.Engine.audioEngine.audioContext.currentTime;
  57378. this._soundSource.stop(stopTime);
  57379. this._soundSource.onended = function () { };
  57380. if (!this.isPaused) {
  57381. this._startOffset = 0;
  57382. }
  57383. }
  57384. this.isPlaying = false;
  57385. }
  57386. };
  57387. Sound.prototype.pause = function () {
  57388. if (this.isPlaying) {
  57389. this.isPaused = true;
  57390. if (this._streaming) {
  57391. this._htmlAudioElement.pause();
  57392. }
  57393. else if (BABYLON.Engine.audioEngine.audioContext) {
  57394. this.stop(0);
  57395. this._startOffset += BABYLON.Engine.audioEngine.audioContext.currentTime - this._startTime;
  57396. }
  57397. }
  57398. };
  57399. Sound.prototype.setVolume = function (newVolume, time) {
  57400. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._soundGain) {
  57401. if (time && BABYLON.Engine.audioEngine.audioContext) {
  57402. this._soundGain.gain.cancelScheduledValues(BABYLON.Engine.audioEngine.audioContext.currentTime);
  57403. this._soundGain.gain.setValueAtTime(this._soundGain.gain.value, BABYLON.Engine.audioEngine.audioContext.currentTime);
  57404. this._soundGain.gain.linearRampToValueAtTime(newVolume, BABYLON.Engine.audioEngine.audioContext.currentTime + time);
  57405. }
  57406. else {
  57407. this._soundGain.gain.value = newVolume;
  57408. }
  57409. }
  57410. this._volume = newVolume;
  57411. };
  57412. Sound.prototype.setPlaybackRate = function (newPlaybackRate) {
  57413. this._playbackRate = newPlaybackRate;
  57414. if (this.isPlaying) {
  57415. if (this._streaming) {
  57416. this._htmlAudioElement.playbackRate = this._playbackRate;
  57417. }
  57418. else if (this._soundSource) {
  57419. this._soundSource.playbackRate.value = this._playbackRate;
  57420. }
  57421. }
  57422. };
  57423. Sound.prototype.getVolume = function () {
  57424. return this._volume;
  57425. };
  57426. Sound.prototype.attachToMesh = function (meshToConnectTo) {
  57427. var _this = this;
  57428. if (this._connectedMesh && this._registerFunc) {
  57429. this._connectedMesh.unregisterAfterWorldMatrixUpdate(this._registerFunc);
  57430. this._registerFunc = null;
  57431. }
  57432. this._connectedMesh = meshToConnectTo;
  57433. if (!this.spatialSound) {
  57434. this.spatialSound = true;
  57435. this._createSpatialParameters();
  57436. if (this.isPlaying && this.loop) {
  57437. this.stop();
  57438. this.play();
  57439. }
  57440. }
  57441. this._onRegisterAfterWorldMatrixUpdate(this._connectedMesh);
  57442. this._registerFunc = function (connectedMesh) { return _this._onRegisterAfterWorldMatrixUpdate(connectedMesh); };
  57443. meshToConnectTo.registerAfterWorldMatrixUpdate(this._registerFunc);
  57444. };
  57445. Sound.prototype.detachFromMesh = function () {
  57446. if (this._connectedMesh && this._registerFunc) {
  57447. this._connectedMesh.unregisterAfterWorldMatrixUpdate(this._registerFunc);
  57448. this._registerFunc = null;
  57449. this._connectedMesh = null;
  57450. }
  57451. };
  57452. Sound.prototype._onRegisterAfterWorldMatrixUpdate = function (node) {
  57453. if (!node.getBoundingInfo) {
  57454. return;
  57455. }
  57456. var mesh = node;
  57457. var boundingInfo = mesh.getBoundingInfo();
  57458. this.setPosition(boundingInfo.boundingSphere.centerWorld);
  57459. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._isDirectional && this.isPlaying) {
  57460. this._updateDirection();
  57461. }
  57462. };
  57463. Sound.prototype.clone = function () {
  57464. var _this = this;
  57465. if (!this._streaming) {
  57466. var setBufferAndRun = function () {
  57467. if (_this._isReadyToPlay) {
  57468. clonedSound._audioBuffer = _this.getAudioBuffer();
  57469. clonedSound._isReadyToPlay = true;
  57470. if (clonedSound.autoplay) {
  57471. clonedSound.play();
  57472. }
  57473. }
  57474. else {
  57475. window.setTimeout(setBufferAndRun, 300);
  57476. }
  57477. };
  57478. var currentOptions = {
  57479. autoplay: this.autoplay, loop: this.loop,
  57480. volume: this._volume, spatialSound: this.spatialSound, maxDistance: this.maxDistance,
  57481. useCustomAttenuation: this.useCustomAttenuation, rolloffFactor: this.rolloffFactor,
  57482. refDistance: this.refDistance, distanceModel: this.distanceModel
  57483. };
  57484. var clonedSound = new Sound(this.name + "_cloned", new ArrayBuffer(0), this._scene, null, currentOptions);
  57485. if (this.useCustomAttenuation) {
  57486. clonedSound.setAttenuationFunction(this._customAttenuationFunction);
  57487. }
  57488. clonedSound.setPosition(this._position);
  57489. clonedSound.setPlaybackRate(this._playbackRate);
  57490. setBufferAndRun();
  57491. return clonedSound;
  57492. }
  57493. else {
  57494. return null;
  57495. }
  57496. };
  57497. Sound.prototype.getAudioBuffer = function () {
  57498. return this._audioBuffer;
  57499. };
  57500. Sound.prototype.serialize = function () {
  57501. var serializationObject = {
  57502. name: this.name,
  57503. url: this.name,
  57504. autoplay: this.autoplay,
  57505. loop: this.loop,
  57506. volume: this._volume,
  57507. spatialSound: this.spatialSound,
  57508. maxDistance: this.maxDistance,
  57509. rolloffFactor: this.rolloffFactor,
  57510. refDistance: this.refDistance,
  57511. distanceModel: this.distanceModel,
  57512. playbackRate: this._playbackRate,
  57513. panningModel: this._panningModel,
  57514. soundTrackId: this.soundTrackId
  57515. };
  57516. if (this.spatialSound) {
  57517. if (this._connectedMesh)
  57518. serializationObject.connectedMeshId = this._connectedMesh.id;
  57519. serializationObject.position = this._position.asArray();
  57520. serializationObject.refDistance = this.refDistance;
  57521. serializationObject.distanceModel = this.distanceModel;
  57522. serializationObject.isDirectional = this._isDirectional;
  57523. serializationObject.localDirectionToMesh = this._localDirection.asArray();
  57524. serializationObject.coneInnerAngle = this._coneInnerAngle;
  57525. serializationObject.coneOuterAngle = this._coneOuterAngle;
  57526. serializationObject.coneOuterGain = this._coneOuterGain;
  57527. }
  57528. return serializationObject;
  57529. };
  57530. Sound.Parse = function (parsedSound, scene, rootUrl, sourceSound) {
  57531. var soundName = parsedSound.name;
  57532. var soundUrl;
  57533. if (parsedSound.url) {
  57534. soundUrl = rootUrl + parsedSound.url;
  57535. }
  57536. else {
  57537. soundUrl = rootUrl + soundName;
  57538. }
  57539. var options = {
  57540. autoplay: parsedSound.autoplay, loop: parsedSound.loop, volume: parsedSound.volume,
  57541. spatialSound: parsedSound.spatialSound, maxDistance: parsedSound.maxDistance,
  57542. rolloffFactor: parsedSound.rolloffFactor,
  57543. refDistance: parsedSound.refDistance,
  57544. distanceModel: parsedSound.distanceModel,
  57545. playbackRate: parsedSound.playbackRate
  57546. };
  57547. var newSound;
  57548. if (!sourceSound) {
  57549. newSound = new Sound(soundName, soundUrl, scene, function () { scene._removePendingData(newSound); }, options);
  57550. scene._addPendingData(newSound);
  57551. }
  57552. else {
  57553. var setBufferAndRun = function () {
  57554. if (sourceSound._isReadyToPlay) {
  57555. newSound._audioBuffer = sourceSound.getAudioBuffer();
  57556. newSound._isReadyToPlay = true;
  57557. if (newSound.autoplay) {
  57558. newSound.play();
  57559. }
  57560. }
  57561. else {
  57562. window.setTimeout(setBufferAndRun, 300);
  57563. }
  57564. };
  57565. newSound = new Sound(soundName, new ArrayBuffer(0), scene, null, options);
  57566. setBufferAndRun();
  57567. }
  57568. if (parsedSound.position) {
  57569. var soundPosition = BABYLON.Vector3.FromArray(parsedSound.position);
  57570. newSound.setPosition(soundPosition);
  57571. }
  57572. if (parsedSound.isDirectional) {
  57573. newSound.setDirectionalCone(parsedSound.coneInnerAngle || 360, parsedSound.coneOuterAngle || 360, parsedSound.coneOuterGain || 0);
  57574. if (parsedSound.localDirectionToMesh) {
  57575. var localDirectionToMesh = BABYLON.Vector3.FromArray(parsedSound.localDirectionToMesh);
  57576. newSound.setLocalDirectionToMesh(localDirectionToMesh);
  57577. }
  57578. }
  57579. if (parsedSound.connectedMeshId) {
  57580. var connectedMesh = scene.getMeshByID(parsedSound.connectedMeshId);
  57581. if (connectedMesh) {
  57582. newSound.attachToMesh(connectedMesh);
  57583. }
  57584. }
  57585. return newSound;
  57586. };
  57587. return Sound;
  57588. }());
  57589. BABYLON.Sound = Sound;
  57590. })(BABYLON || (BABYLON = {}));
  57591. //# sourceMappingURL=babylon.sound.js.map
  57592. var BABYLON;
  57593. (function (BABYLON) {
  57594. var SoundTrack = /** @class */ (function () {
  57595. function SoundTrack(scene, options) {
  57596. this.id = -1;
  57597. this._isMainTrack = false;
  57598. this._isInitialized = false;
  57599. this._scene = scene;
  57600. this.soundCollection = new Array();
  57601. this._options = options;
  57602. if (!this._isMainTrack) {
  57603. this._scene.soundTracks.push(this);
  57604. this.id = this._scene.soundTracks.length - 1;
  57605. }
  57606. }
  57607. SoundTrack.prototype._initializeSoundTrackAudioGraph = function () {
  57608. if (BABYLON.Engine.audioEngine.canUseWebAudio && BABYLON.Engine.audioEngine.audioContext) {
  57609. this._outputAudioNode = BABYLON.Engine.audioEngine.audioContext.createGain();
  57610. this._outputAudioNode.connect(BABYLON.Engine.audioEngine.masterGain);
  57611. if (this._options) {
  57612. if (this._options.volume) {
  57613. this._outputAudioNode.gain.value = this._options.volume;
  57614. }
  57615. if (this._options.mainTrack) {
  57616. this._isMainTrack = this._options.mainTrack;
  57617. }
  57618. }
  57619. this._isInitialized = true;
  57620. }
  57621. };
  57622. SoundTrack.prototype.dispose = function () {
  57623. if (BABYLON.Engine.audioEngine && BABYLON.Engine.audioEngine.canUseWebAudio) {
  57624. if (this._connectedAnalyser) {
  57625. this._connectedAnalyser.stopDebugCanvas();
  57626. }
  57627. while (this.soundCollection.length) {
  57628. this.soundCollection[0].dispose();
  57629. }
  57630. if (this._outputAudioNode) {
  57631. this._outputAudioNode.disconnect();
  57632. }
  57633. this._outputAudioNode = null;
  57634. }
  57635. };
  57636. SoundTrack.prototype.AddSound = function (sound) {
  57637. if (!this._isInitialized) {
  57638. this._initializeSoundTrackAudioGraph();
  57639. }
  57640. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._outputAudioNode) {
  57641. sound.connectToSoundTrackAudioNode(this._outputAudioNode);
  57642. }
  57643. if (sound.soundTrackId) {
  57644. if (sound.soundTrackId === -1) {
  57645. this._scene.mainSoundTrack.RemoveSound(sound);
  57646. }
  57647. else {
  57648. this._scene.soundTracks[sound.soundTrackId].RemoveSound(sound);
  57649. }
  57650. }
  57651. this.soundCollection.push(sound);
  57652. sound.soundTrackId = this.id;
  57653. };
  57654. SoundTrack.prototype.RemoveSound = function (sound) {
  57655. var index = this.soundCollection.indexOf(sound);
  57656. if (index !== -1) {
  57657. this.soundCollection.splice(index, 1);
  57658. }
  57659. };
  57660. SoundTrack.prototype.setVolume = function (newVolume) {
  57661. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._outputAudioNode) {
  57662. this._outputAudioNode.gain.value = newVolume;
  57663. }
  57664. };
  57665. SoundTrack.prototype.switchPanningModelToHRTF = function () {
  57666. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  57667. for (var i = 0; i < this.soundCollection.length; i++) {
  57668. this.soundCollection[i].switchPanningModelToHRTF();
  57669. }
  57670. }
  57671. };
  57672. SoundTrack.prototype.switchPanningModelToEqualPower = function () {
  57673. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  57674. for (var i = 0; i < this.soundCollection.length; i++) {
  57675. this.soundCollection[i].switchPanningModelToEqualPower();
  57676. }
  57677. }
  57678. };
  57679. SoundTrack.prototype.connectToAnalyser = function (analyser) {
  57680. if (this._connectedAnalyser) {
  57681. this._connectedAnalyser.stopDebugCanvas();
  57682. }
  57683. this._connectedAnalyser = analyser;
  57684. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._outputAudioNode) {
  57685. this._outputAudioNode.disconnect();
  57686. this._connectedAnalyser.connectAudioNodes(this._outputAudioNode, BABYLON.Engine.audioEngine.masterGain);
  57687. }
  57688. };
  57689. return SoundTrack;
  57690. }());
  57691. BABYLON.SoundTrack = SoundTrack;
  57692. })(BABYLON || (BABYLON = {}));
  57693. //# sourceMappingURL=babylon.soundtrack.js.map
  57694. var BABYLON;
  57695. (function (BABYLON) {
  57696. var Analyser = /** @class */ (function () {
  57697. function Analyser(scene) {
  57698. this.SMOOTHING = 0.75;
  57699. this.FFT_SIZE = 512;
  57700. this.BARGRAPHAMPLITUDE = 256;
  57701. this.DEBUGCANVASPOS = { x: 20, y: 20 };
  57702. this.DEBUGCANVASSIZE = { width: 320, height: 200 };
  57703. this._scene = scene;
  57704. this._audioEngine = BABYLON.Engine.audioEngine;
  57705. if (this._audioEngine.canUseWebAudio && this._audioEngine.audioContext) {
  57706. this._webAudioAnalyser = this._audioEngine.audioContext.createAnalyser();
  57707. this._webAudioAnalyser.minDecibels = -140;
  57708. this._webAudioAnalyser.maxDecibels = 0;
  57709. this._byteFreqs = new Uint8Array(this._webAudioAnalyser.frequencyBinCount);
  57710. this._byteTime = new Uint8Array(this._webAudioAnalyser.frequencyBinCount);
  57711. this._floatFreqs = new Float32Array(this._webAudioAnalyser.frequencyBinCount);
  57712. }
  57713. }
  57714. Analyser.prototype.getFrequencyBinCount = function () {
  57715. if (this._audioEngine.canUseWebAudio) {
  57716. return this._webAudioAnalyser.frequencyBinCount;
  57717. }
  57718. else {
  57719. return 0;
  57720. }
  57721. };
  57722. Analyser.prototype.getByteFrequencyData = function () {
  57723. if (this._audioEngine.canUseWebAudio) {
  57724. this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
  57725. this._webAudioAnalyser.fftSize = this.FFT_SIZE;
  57726. this._webAudioAnalyser.getByteFrequencyData(this._byteFreqs);
  57727. }
  57728. return this._byteFreqs;
  57729. };
  57730. Analyser.prototype.getByteTimeDomainData = function () {
  57731. if (this._audioEngine.canUseWebAudio) {
  57732. this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
  57733. this._webAudioAnalyser.fftSize = this.FFT_SIZE;
  57734. this._webAudioAnalyser.getByteTimeDomainData(this._byteTime);
  57735. }
  57736. return this._byteTime;
  57737. };
  57738. Analyser.prototype.getFloatFrequencyData = function () {
  57739. if (this._audioEngine.canUseWebAudio) {
  57740. this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
  57741. this._webAudioAnalyser.fftSize = this.FFT_SIZE;
  57742. this._webAudioAnalyser.getFloatFrequencyData(this._floatFreqs);
  57743. }
  57744. return this._floatFreqs;
  57745. };
  57746. Analyser.prototype.drawDebugCanvas = function () {
  57747. var _this = this;
  57748. if (this._audioEngine.canUseWebAudio) {
  57749. if (!this._debugCanvas) {
  57750. this._debugCanvas = document.createElement("canvas");
  57751. this._debugCanvas.width = this.DEBUGCANVASSIZE.width;
  57752. this._debugCanvas.height = this.DEBUGCANVASSIZE.height;
  57753. this._debugCanvas.style.position = "absolute";
  57754. this._debugCanvas.style.top = this.DEBUGCANVASPOS.y + "px";
  57755. this._debugCanvas.style.left = this.DEBUGCANVASPOS.x + "px";
  57756. this._debugCanvasContext = this._debugCanvas.getContext("2d");
  57757. document.body.appendChild(this._debugCanvas);
  57758. this._registerFunc = function () {
  57759. _this.drawDebugCanvas();
  57760. };
  57761. this._scene.registerBeforeRender(this._registerFunc);
  57762. }
  57763. if (this._registerFunc && this._debugCanvasContext) {
  57764. var workingArray = this.getByteFrequencyData();
  57765. this._debugCanvasContext.fillStyle = 'rgb(0, 0, 0)';
  57766. this._debugCanvasContext.fillRect(0, 0, this.DEBUGCANVASSIZE.width, this.DEBUGCANVASSIZE.height);
  57767. // Draw the frequency domain chart.
  57768. for (var i = 0; i < this.getFrequencyBinCount(); i++) {
  57769. var value = workingArray[i];
  57770. var percent = value / this.BARGRAPHAMPLITUDE;
  57771. var height = this.DEBUGCANVASSIZE.height * percent;
  57772. var offset = this.DEBUGCANVASSIZE.height - height - 1;
  57773. var barWidth = this.DEBUGCANVASSIZE.width / this.getFrequencyBinCount();
  57774. var hue = i / this.getFrequencyBinCount() * 360;
  57775. this._debugCanvasContext.fillStyle = 'hsl(' + hue + ', 100%, 50%)';
  57776. this._debugCanvasContext.fillRect(i * barWidth, offset, barWidth, height);
  57777. }
  57778. }
  57779. }
  57780. };
  57781. Analyser.prototype.stopDebugCanvas = function () {
  57782. if (this._debugCanvas) {
  57783. if (this._registerFunc) {
  57784. this._scene.unregisterBeforeRender(this._registerFunc);
  57785. this._registerFunc = null;
  57786. }
  57787. document.body.removeChild(this._debugCanvas);
  57788. this._debugCanvas = null;
  57789. this._debugCanvasContext = null;
  57790. }
  57791. };
  57792. Analyser.prototype.connectAudioNodes = function (inputAudioNode, outputAudioNode) {
  57793. if (this._audioEngine.canUseWebAudio) {
  57794. inputAudioNode.connect(this._webAudioAnalyser);
  57795. this._webAudioAnalyser.connect(outputAudioNode);
  57796. }
  57797. };
  57798. Analyser.prototype.dispose = function () {
  57799. if (this._audioEngine.canUseWebAudio) {
  57800. this._webAudioAnalyser.disconnect();
  57801. }
  57802. };
  57803. return Analyser;
  57804. }());
  57805. BABYLON.Analyser = Analyser;
  57806. })(BABYLON || (BABYLON = {}));
  57807. //# sourceMappingURL=babylon.analyser.js.map
  57808. var BABYLON;
  57809. (function (BABYLON) {
  57810. var CubeTexture = /** @class */ (function (_super) {
  57811. __extends(CubeTexture, _super);
  57812. function CubeTexture(rootUrl, scene, extensions, noMipmap, files, onLoad, onError, format, prefiltered, forcedExtension) {
  57813. if (extensions === void 0) { extensions = null; }
  57814. if (noMipmap === void 0) { noMipmap = false; }
  57815. if (files === void 0) { files = null; }
  57816. if (onLoad === void 0) { onLoad = null; }
  57817. if (onError === void 0) { onError = null; }
  57818. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  57819. if (prefiltered === void 0) { prefiltered = false; }
  57820. if (forcedExtension === void 0) { forcedExtension = null; }
  57821. var _this = _super.call(this, scene) || this;
  57822. _this.coordinatesMode = BABYLON.Texture.CUBIC_MODE;
  57823. /**
  57824. * Gets or sets the center of the bounding box associated with the cube texture
  57825. * It must define where the camera used to render the texture was set
  57826. */
  57827. _this.boundingBoxPosition = BABYLON.Vector3.Zero();
  57828. _this.name = rootUrl;
  57829. _this.url = rootUrl;
  57830. _this._noMipmap = noMipmap;
  57831. _this.hasAlpha = false;
  57832. _this._format = format;
  57833. _this._prefiltered = prefiltered;
  57834. _this.isCube = true;
  57835. _this._textureMatrix = BABYLON.Matrix.Identity();
  57836. if (prefiltered) {
  57837. _this.gammaSpace = false;
  57838. }
  57839. if (!rootUrl && !files) {
  57840. return _this;
  57841. }
  57842. _this._texture = _this._getFromCache(rootUrl, noMipmap);
  57843. var lastDot = rootUrl.lastIndexOf(".");
  57844. var extension = forcedExtension ? forcedExtension : (lastDot > -1 ? rootUrl.substring(lastDot).toLowerCase() : "");
  57845. var isDDS = (extension === ".dds");
  57846. if (!files) {
  57847. if (!isDDS && !extensions) {
  57848. extensions = ["_px.jpg", "_py.jpg", "_pz.jpg", "_nx.jpg", "_ny.jpg", "_nz.jpg"];
  57849. }
  57850. files = [];
  57851. if (extensions) {
  57852. for (var index = 0; index < extensions.length; index++) {
  57853. files.push(rootUrl + extensions[index]);
  57854. }
  57855. }
  57856. }
  57857. _this._files = files;
  57858. if (!_this._texture) {
  57859. if (!scene.useDelayedTextureLoading) {
  57860. if (prefiltered) {
  57861. _this._texture = scene.getEngine().createPrefilteredCubeTexture(rootUrl, scene, _this.lodGenerationScale, _this.lodGenerationOffset, onLoad, onError, format, forcedExtension);
  57862. }
  57863. else {
  57864. _this._texture = scene.getEngine().createCubeTexture(rootUrl, scene, files, noMipmap, onLoad, onError, _this._format, forcedExtension);
  57865. }
  57866. }
  57867. else {
  57868. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  57869. }
  57870. }
  57871. else if (onLoad) {
  57872. if (_this._texture.isReady) {
  57873. BABYLON.Tools.SetImmediate(function () { return onLoad(); });
  57874. }
  57875. else {
  57876. _this._texture.onLoadedObservable.add(onLoad);
  57877. }
  57878. }
  57879. return _this;
  57880. }
  57881. Object.defineProperty(CubeTexture.prototype, "boundingBoxSize", {
  57882. get: function () {
  57883. return this._boundingBoxSize;
  57884. },
  57885. /**
  57886. * Gets or sets the size of the bounding box associated with the cube texture
  57887. * When defined, the cubemap will switch to local mode
  57888. * @see https://community.arm.com/graphics/b/blog/posts/reflections-based-on-local-cubemaps-in-unity
  57889. * @example https://www.babylonjs-playground.com/#RNASML
  57890. */
  57891. set: function (value) {
  57892. if (this._boundingBoxSize && this._boundingBoxSize.equals(value)) {
  57893. return;
  57894. }
  57895. this._boundingBoxSize = value;
  57896. var scene = this.getScene();
  57897. if (scene) {
  57898. scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  57899. }
  57900. },
  57901. enumerable: true,
  57902. configurable: true
  57903. });
  57904. CubeTexture.CreateFromImages = function (files, scene, noMipmap) {
  57905. var rootUrlKey = "";
  57906. files.forEach(function (url) { return rootUrlKey += url; });
  57907. return new CubeTexture(rootUrlKey, scene, null, noMipmap, files);
  57908. };
  57909. CubeTexture.CreateFromPrefilteredData = function (url, scene, forcedExtension) {
  57910. if (forcedExtension === void 0) { forcedExtension = null; }
  57911. return new CubeTexture(url, scene, null, false, null, null, null, undefined, true, forcedExtension);
  57912. };
  57913. // Methods
  57914. CubeTexture.prototype.delayLoad = function () {
  57915. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  57916. return;
  57917. }
  57918. var scene = this.getScene();
  57919. if (!scene) {
  57920. return;
  57921. }
  57922. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  57923. this._texture = this._getFromCache(this.url, this._noMipmap);
  57924. if (!this._texture) {
  57925. if (this._prefiltered) {
  57926. this._texture = scene.getEngine().createPrefilteredCubeTexture(this.url, scene, this.lodGenerationScale, this.lodGenerationOffset, undefined, undefined, this._format);
  57927. }
  57928. else {
  57929. this._texture = scene.getEngine().createCubeTexture(this.url, scene, this._files, this._noMipmap, undefined, undefined, this._format);
  57930. }
  57931. }
  57932. };
  57933. CubeTexture.prototype.getReflectionTextureMatrix = function () {
  57934. return this._textureMatrix;
  57935. };
  57936. CubeTexture.prototype.setReflectionTextureMatrix = function (value) {
  57937. this._textureMatrix = value;
  57938. };
  57939. CubeTexture.Parse = function (parsedTexture, scene, rootUrl) {
  57940. var texture = BABYLON.SerializationHelper.Parse(function () {
  57941. return new CubeTexture(rootUrl + parsedTexture.name, scene, parsedTexture.extensions);
  57942. }, parsedTexture, scene);
  57943. // Local Cubemaps
  57944. if (parsedTexture.boundingBoxPosition) {
  57945. texture.boundingBoxPosition = BABYLON.Vector3.FromArray(parsedTexture.boundingBoxPosition);
  57946. }
  57947. if (parsedTexture.boundingBoxSize) {
  57948. texture.boundingBoxSize = BABYLON.Vector3.FromArray(parsedTexture.boundingBoxSize);
  57949. }
  57950. // Animations
  57951. if (parsedTexture.animations) {
  57952. for (var animationIndex = 0; animationIndex < parsedTexture.animations.length; animationIndex++) {
  57953. var parsedAnimation = parsedTexture.animations[animationIndex];
  57954. texture.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  57955. }
  57956. }
  57957. return texture;
  57958. };
  57959. CubeTexture.prototype.clone = function () {
  57960. var _this = this;
  57961. return BABYLON.SerializationHelper.Clone(function () {
  57962. var scene = _this.getScene();
  57963. if (!scene) {
  57964. return _this;
  57965. }
  57966. return new CubeTexture(_this.url, scene, _this._extensions, _this._noMipmap, _this._files);
  57967. }, this);
  57968. };
  57969. return CubeTexture;
  57970. }(BABYLON.BaseTexture));
  57971. BABYLON.CubeTexture = CubeTexture;
  57972. })(BABYLON || (BABYLON = {}));
  57973. //# sourceMappingURL=babylon.cubeTexture.js.map
  57974. var BABYLON;
  57975. (function (BABYLON) {
  57976. var RenderTargetTexture = /** @class */ (function (_super) {
  57977. __extends(RenderTargetTexture, _super);
  57978. /**
  57979. * Instantiate a render target texture. This is mainly to render of screen the scene to for instance apply post processse
  57980. * or used a shadow, depth texture...
  57981. * @param name The friendly name of the texture
  57982. * @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)
  57983. * @param scene The scene the RTT belongs to. The latest created scene will be used if not precised.
  57984. * @param generateMipMaps True if mip maps need to be generated after render.
  57985. * @param doNotChangeAspectRatio True to not change the aspect ratio of the scene in the RTT
  57986. * @param type The type of the buffer in the RTT (int, half float, float...)
  57987. * @param isCube True if a cube texture needs to be created
  57988. * @param samplingMode The sampling mode to be usedwith the render target (Linear, Nearest...)
  57989. * @param generateDepthBuffer True to generate a depth buffer
  57990. * @param generateStencilBuffer True to generate a stencil buffer
  57991. * @param isMulti True if multiple textures need to be created (Draw Buffers)
  57992. */
  57993. function RenderTargetTexture(name, size, scene, generateMipMaps, doNotChangeAspectRatio, type, isCube, samplingMode, generateDepthBuffer, generateStencilBuffer, isMulti) {
  57994. if (doNotChangeAspectRatio === void 0) { doNotChangeAspectRatio = true; }
  57995. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  57996. if (isCube === void 0) { isCube = false; }
  57997. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  57998. if (generateDepthBuffer === void 0) { generateDepthBuffer = true; }
  57999. if (generateStencilBuffer === void 0) { generateStencilBuffer = false; }
  58000. if (isMulti === void 0) { isMulti = false; }
  58001. var _this = _super.call(this, null, scene, !generateMipMaps) || this;
  58002. _this.isCube = isCube;
  58003. /**
  58004. * Use this list to define the list of mesh you want to render.
  58005. */
  58006. _this.renderList = new Array();
  58007. _this.renderParticles = true;
  58008. _this.renderSprites = false;
  58009. _this.coordinatesMode = BABYLON.Texture.PROJECTION_MODE;
  58010. _this.ignoreCameraViewport = false;
  58011. // Events
  58012. /**
  58013. * An event triggered when the texture is unbind.
  58014. * @type {BABYLON.Observable}
  58015. */
  58016. _this.onBeforeBindObservable = new BABYLON.Observable();
  58017. /**
  58018. * An event triggered when the texture is unbind.
  58019. * @type {BABYLON.Observable}
  58020. */
  58021. _this.onAfterUnbindObservable = new BABYLON.Observable();
  58022. /**
  58023. * An event triggered before rendering the texture
  58024. * @type {BABYLON.Observable}
  58025. */
  58026. _this.onBeforeRenderObservable = new BABYLON.Observable();
  58027. /**
  58028. * An event triggered after rendering the texture
  58029. * @type {BABYLON.Observable}
  58030. */
  58031. _this.onAfterRenderObservable = new BABYLON.Observable();
  58032. /**
  58033. * An event triggered after the texture clear
  58034. * @type {BABYLON.Observable}
  58035. */
  58036. _this.onClearObservable = new BABYLON.Observable();
  58037. _this._currentRefreshId = -1;
  58038. _this._refreshRate = 1;
  58039. _this._samples = 1;
  58040. /**
  58041. * Gets or sets the center of the bounding box associated with the texture (when in cube mode)
  58042. * It must define where the camera used to render the texture is set
  58043. */
  58044. _this.boundingBoxPosition = BABYLON.Vector3.Zero();
  58045. scene = _this.getScene();
  58046. if (!scene) {
  58047. return _this;
  58048. }
  58049. _this._engine = scene.getEngine();
  58050. _this.name = name;
  58051. _this.isRenderTarget = true;
  58052. _this._initialSizeParameter = size;
  58053. _this._processSizeParameter(size);
  58054. _this._resizeObserver = _this.getScene().getEngine().onResizeObservable.add(function () {
  58055. });
  58056. _this._generateMipMaps = generateMipMaps ? true : false;
  58057. _this._doNotChangeAspectRatio = doNotChangeAspectRatio;
  58058. // Rendering groups
  58059. _this._renderingManager = new BABYLON.RenderingManager(scene);
  58060. if (isMulti) {
  58061. return _this;
  58062. }
  58063. _this._renderTargetOptions = {
  58064. generateMipMaps: generateMipMaps,
  58065. type: type,
  58066. samplingMode: samplingMode,
  58067. generateDepthBuffer: generateDepthBuffer,
  58068. generateStencilBuffer: generateStencilBuffer
  58069. };
  58070. if (samplingMode === BABYLON.Texture.NEAREST_SAMPLINGMODE) {
  58071. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  58072. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  58073. }
  58074. if (isCube) {
  58075. _this._texture = scene.getEngine().createRenderTargetCubeTexture(_this.getRenderSize(), _this._renderTargetOptions);
  58076. _this.coordinatesMode = BABYLON.Texture.INVCUBIC_MODE;
  58077. _this._textureMatrix = BABYLON.Matrix.Identity();
  58078. }
  58079. else {
  58080. _this._texture = scene.getEngine().createRenderTargetTexture(_this._size, _this._renderTargetOptions);
  58081. }
  58082. return _this;
  58083. }
  58084. Object.defineProperty(RenderTargetTexture, "REFRESHRATE_RENDER_ONCE", {
  58085. get: function () {
  58086. return RenderTargetTexture._REFRESHRATE_RENDER_ONCE;
  58087. },
  58088. enumerable: true,
  58089. configurable: true
  58090. });
  58091. Object.defineProperty(RenderTargetTexture, "REFRESHRATE_RENDER_ONEVERYFRAME", {
  58092. get: function () {
  58093. return RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYFRAME;
  58094. },
  58095. enumerable: true,
  58096. configurable: true
  58097. });
  58098. Object.defineProperty(RenderTargetTexture, "REFRESHRATE_RENDER_ONEVERYTWOFRAMES", {
  58099. get: function () {
  58100. return RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYTWOFRAMES;
  58101. },
  58102. enumerable: true,
  58103. configurable: true
  58104. });
  58105. Object.defineProperty(RenderTargetTexture.prototype, "onAfterUnbind", {
  58106. set: function (callback) {
  58107. if (this._onAfterUnbindObserver) {
  58108. this.onAfterUnbindObservable.remove(this._onAfterUnbindObserver);
  58109. }
  58110. this._onAfterUnbindObserver = this.onAfterUnbindObservable.add(callback);
  58111. },
  58112. enumerable: true,
  58113. configurable: true
  58114. });
  58115. Object.defineProperty(RenderTargetTexture.prototype, "onBeforeRender", {
  58116. set: function (callback) {
  58117. if (this._onBeforeRenderObserver) {
  58118. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  58119. }
  58120. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  58121. },
  58122. enumerable: true,
  58123. configurable: true
  58124. });
  58125. Object.defineProperty(RenderTargetTexture.prototype, "onAfterRender", {
  58126. set: function (callback) {
  58127. if (this._onAfterRenderObserver) {
  58128. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  58129. }
  58130. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  58131. },
  58132. enumerable: true,
  58133. configurable: true
  58134. });
  58135. Object.defineProperty(RenderTargetTexture.prototype, "onClear", {
  58136. set: function (callback) {
  58137. if (this._onClearObserver) {
  58138. this.onClearObservable.remove(this._onClearObserver);
  58139. }
  58140. this._onClearObserver = this.onClearObservable.add(callback);
  58141. },
  58142. enumerable: true,
  58143. configurable: true
  58144. });
  58145. Object.defineProperty(RenderTargetTexture.prototype, "renderTargetOptions", {
  58146. get: function () {
  58147. return this._renderTargetOptions;
  58148. },
  58149. enumerable: true,
  58150. configurable: true
  58151. });
  58152. RenderTargetTexture.prototype._onRatioRescale = function () {
  58153. if (this._sizeRatio) {
  58154. this.resize(this._initialSizeParameter);
  58155. }
  58156. };
  58157. Object.defineProperty(RenderTargetTexture.prototype, "boundingBoxSize", {
  58158. get: function () {
  58159. return this._boundingBoxSize;
  58160. },
  58161. /**
  58162. * Gets or sets the size of the bounding box associated with the texture (when in cube mode)
  58163. * When defined, the cubemap will switch to local mode
  58164. * @see https://community.arm.com/graphics/b/blog/posts/reflections-based-on-local-cubemaps-in-unity
  58165. * @example https://www.babylonjs-playground.com/#RNASML
  58166. */
  58167. set: function (value) {
  58168. if (this._boundingBoxSize && this._boundingBoxSize.equals(value)) {
  58169. return;
  58170. }
  58171. this._boundingBoxSize = value;
  58172. var scene = this.getScene();
  58173. if (scene) {
  58174. scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  58175. }
  58176. },
  58177. enumerable: true,
  58178. configurable: true
  58179. });
  58180. RenderTargetTexture.prototype._processSizeParameter = function (size) {
  58181. if (size.ratio) {
  58182. this._sizeRatio = size.ratio;
  58183. this._size = {
  58184. width: this._bestReflectionRenderTargetDimension(this._engine.getRenderWidth(), this._sizeRatio),
  58185. height: this._bestReflectionRenderTargetDimension(this._engine.getRenderHeight(), this._sizeRatio)
  58186. };
  58187. }
  58188. else {
  58189. this._size = size;
  58190. }
  58191. };
  58192. Object.defineProperty(RenderTargetTexture.prototype, "samples", {
  58193. get: function () {
  58194. return this._samples;
  58195. },
  58196. set: function (value) {
  58197. if (this._samples === value) {
  58198. return;
  58199. }
  58200. var scene = this.getScene();
  58201. if (!scene) {
  58202. return;
  58203. }
  58204. this._samples = scene.getEngine().updateRenderTargetTextureSampleCount(this._texture, value);
  58205. },
  58206. enumerable: true,
  58207. configurable: true
  58208. });
  58209. RenderTargetTexture.prototype.resetRefreshCounter = function () {
  58210. this._currentRefreshId = -1;
  58211. };
  58212. Object.defineProperty(RenderTargetTexture.prototype, "refreshRate", {
  58213. get: function () {
  58214. return this._refreshRate;
  58215. },
  58216. // Use 0 to render just once, 1 to render on every frame, 2 to render every two frames and so on...
  58217. set: function (value) {
  58218. this._refreshRate = value;
  58219. this.resetRefreshCounter();
  58220. },
  58221. enumerable: true,
  58222. configurable: true
  58223. });
  58224. RenderTargetTexture.prototype.addPostProcess = function (postProcess) {
  58225. if (!this._postProcessManager) {
  58226. var scene = this.getScene();
  58227. if (!scene) {
  58228. return;
  58229. }
  58230. this._postProcessManager = new BABYLON.PostProcessManager(scene);
  58231. this._postProcesses = new Array();
  58232. }
  58233. this._postProcesses.push(postProcess);
  58234. this._postProcesses[0].autoClear = false;
  58235. };
  58236. RenderTargetTexture.prototype.clearPostProcesses = function (dispose) {
  58237. if (!this._postProcesses) {
  58238. return;
  58239. }
  58240. if (dispose) {
  58241. for (var _i = 0, _a = this._postProcesses; _i < _a.length; _i++) {
  58242. var postProcess = _a[_i];
  58243. postProcess.dispose();
  58244. }
  58245. }
  58246. this._postProcesses = [];
  58247. };
  58248. RenderTargetTexture.prototype.removePostProcess = function (postProcess) {
  58249. if (!this._postProcesses) {
  58250. return;
  58251. }
  58252. var index = this._postProcesses.indexOf(postProcess);
  58253. if (index === -1) {
  58254. return;
  58255. }
  58256. this._postProcesses.splice(index, 1);
  58257. if (this._postProcesses.length > 0) {
  58258. this._postProcesses[0].autoClear = false;
  58259. }
  58260. };
  58261. RenderTargetTexture.prototype._shouldRender = function () {
  58262. if (this._currentRefreshId === -1) {
  58263. this._currentRefreshId = 1;
  58264. return true;
  58265. }
  58266. if (this.refreshRate === this._currentRefreshId) {
  58267. this._currentRefreshId = 1;
  58268. return true;
  58269. }
  58270. this._currentRefreshId++;
  58271. return false;
  58272. };
  58273. RenderTargetTexture.prototype.getRenderSize = function () {
  58274. if (this._size.width) {
  58275. return this._size.width;
  58276. }
  58277. return this._size;
  58278. };
  58279. RenderTargetTexture.prototype.getRenderWidth = function () {
  58280. if (this._size.width) {
  58281. return this._size.width;
  58282. }
  58283. return this._size;
  58284. };
  58285. RenderTargetTexture.prototype.getRenderHeight = function () {
  58286. if (this._size.width) {
  58287. return this._size.height;
  58288. }
  58289. return this._size;
  58290. };
  58291. Object.defineProperty(RenderTargetTexture.prototype, "canRescale", {
  58292. get: function () {
  58293. return true;
  58294. },
  58295. enumerable: true,
  58296. configurable: true
  58297. });
  58298. RenderTargetTexture.prototype.scale = function (ratio) {
  58299. var newSize = this.getRenderSize() * ratio;
  58300. this.resize(newSize);
  58301. };
  58302. RenderTargetTexture.prototype.getReflectionTextureMatrix = function () {
  58303. if (this.isCube) {
  58304. return this._textureMatrix;
  58305. }
  58306. return _super.prototype.getReflectionTextureMatrix.call(this);
  58307. };
  58308. RenderTargetTexture.prototype.resize = function (size) {
  58309. this.releaseInternalTexture();
  58310. var scene = this.getScene();
  58311. if (!scene) {
  58312. return;
  58313. }
  58314. this._processSizeParameter(size);
  58315. if (this.isCube) {
  58316. this._texture = scene.getEngine().createRenderTargetCubeTexture(this.getRenderSize(), this._renderTargetOptions);
  58317. }
  58318. else {
  58319. this._texture = scene.getEngine().createRenderTargetTexture(this._size, this._renderTargetOptions);
  58320. }
  58321. };
  58322. RenderTargetTexture.prototype.render = function (useCameraPostProcess, dumpForDebug) {
  58323. if (useCameraPostProcess === void 0) { useCameraPostProcess = false; }
  58324. if (dumpForDebug === void 0) { dumpForDebug = false; }
  58325. var scene = this.getScene();
  58326. if (!scene) {
  58327. return;
  58328. }
  58329. var engine = scene.getEngine();
  58330. if (this.useCameraPostProcesses !== undefined) {
  58331. useCameraPostProcess = this.useCameraPostProcesses;
  58332. }
  58333. if (this._waitingRenderList) {
  58334. this.renderList = [];
  58335. for (var index = 0; index < this._waitingRenderList.length; index++) {
  58336. var id = this._waitingRenderList[index];
  58337. var mesh_1 = scene.getMeshByID(id);
  58338. if (mesh_1) {
  58339. this.renderList.push(mesh_1);
  58340. }
  58341. }
  58342. delete this._waitingRenderList;
  58343. }
  58344. // Is predicate defined?
  58345. if (this.renderListPredicate) {
  58346. if (this.renderList) {
  58347. this.renderList.splice(0); // Clear previous renderList
  58348. }
  58349. else {
  58350. this.renderList = [];
  58351. }
  58352. var scene = this.getScene();
  58353. if (!scene) {
  58354. return;
  58355. }
  58356. var sceneMeshes = scene.meshes;
  58357. for (var index = 0; index < sceneMeshes.length; index++) {
  58358. var mesh = sceneMeshes[index];
  58359. if (this.renderListPredicate(mesh)) {
  58360. this.renderList.push(mesh);
  58361. }
  58362. }
  58363. }
  58364. this.onBeforeBindObservable.notifyObservers(this);
  58365. // Set custom projection.
  58366. // Needs to be before binding to prevent changing the aspect ratio.
  58367. var camera;
  58368. if (this.activeCamera) {
  58369. camera = this.activeCamera;
  58370. engine.setViewport(this.activeCamera.viewport, this.getRenderWidth(), this.getRenderHeight());
  58371. if (this.activeCamera !== scene.activeCamera) {
  58372. scene.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix(true));
  58373. }
  58374. }
  58375. else {
  58376. camera = scene.activeCamera;
  58377. if (camera) {
  58378. engine.setViewport(camera.viewport, this.getRenderWidth(), this.getRenderHeight());
  58379. }
  58380. }
  58381. // Prepare renderingManager
  58382. this._renderingManager.reset();
  58383. var currentRenderList = this.renderList ? this.renderList : scene.getActiveMeshes().data;
  58384. var currentRenderListLength = this.renderList ? this.renderList.length : scene.getActiveMeshes().length;
  58385. var sceneRenderId = scene.getRenderId();
  58386. for (var meshIndex = 0; meshIndex < currentRenderListLength; meshIndex++) {
  58387. var mesh = currentRenderList[meshIndex];
  58388. if (mesh) {
  58389. if (!mesh.isReady()) {
  58390. // Reset _currentRefreshId
  58391. this.resetRefreshCounter();
  58392. continue;
  58393. }
  58394. mesh._preActivateForIntermediateRendering(sceneRenderId);
  58395. var isMasked = void 0;
  58396. if (!this.renderList && camera) {
  58397. isMasked = ((mesh.layerMask & camera.layerMask) === 0);
  58398. }
  58399. else {
  58400. isMasked = false;
  58401. }
  58402. if (mesh.isEnabled() && mesh.isVisible && mesh.subMeshes && !isMasked) {
  58403. mesh._activate(sceneRenderId);
  58404. for (var subIndex = 0; subIndex < mesh.subMeshes.length; subIndex++) {
  58405. var subMesh = mesh.subMeshes[subIndex];
  58406. scene._activeIndices.addCount(subMesh.indexCount, false);
  58407. this._renderingManager.dispatch(subMesh, mesh);
  58408. }
  58409. }
  58410. }
  58411. }
  58412. for (var particleIndex = 0; particleIndex < scene.particleSystems.length; particleIndex++) {
  58413. var particleSystem = scene.particleSystems[particleIndex];
  58414. var emitter = particleSystem.emitter;
  58415. if (!particleSystem.isStarted() || !emitter || !emitter.position || !emitter.isEnabled()) {
  58416. continue;
  58417. }
  58418. if (currentRenderList.indexOf(emitter) >= 0) {
  58419. this._renderingManager.dispatchParticles(particleSystem);
  58420. }
  58421. }
  58422. if (this.isCube) {
  58423. for (var face = 0; face < 6; face++) {
  58424. this.renderToTarget(face, currentRenderList, currentRenderListLength, useCameraPostProcess, dumpForDebug);
  58425. scene.incrementRenderId();
  58426. scene.resetCachedMaterial();
  58427. }
  58428. }
  58429. else {
  58430. this.renderToTarget(0, currentRenderList, currentRenderListLength, useCameraPostProcess, dumpForDebug);
  58431. }
  58432. this.onAfterUnbindObservable.notifyObservers(this);
  58433. if (scene.activeCamera) {
  58434. if (this.activeCamera && this.activeCamera !== scene.activeCamera) {
  58435. scene.setTransformMatrix(scene.activeCamera.getViewMatrix(), scene.activeCamera.getProjectionMatrix(true));
  58436. }
  58437. engine.setViewport(scene.activeCamera.viewport);
  58438. }
  58439. scene.resetCachedMaterial();
  58440. };
  58441. RenderTargetTexture.prototype._bestReflectionRenderTargetDimension = function (renderDimension, scale) {
  58442. var minimum = 128;
  58443. var x = renderDimension * scale;
  58444. var curved = BABYLON.Tools.NearestPOT(x + (minimum * minimum / (minimum + x)));
  58445. // Ensure we don't exceed the render dimension (while staying POT)
  58446. return Math.min(BABYLON.Tools.FloorPOT(renderDimension), curved);
  58447. };
  58448. RenderTargetTexture.prototype.unbindFrameBuffer = function (engine, faceIndex) {
  58449. var _this = this;
  58450. if (!this._texture) {
  58451. return;
  58452. }
  58453. engine.unBindFramebuffer(this._texture, this.isCube, function () {
  58454. _this.onAfterRenderObservable.notifyObservers(faceIndex);
  58455. });
  58456. };
  58457. RenderTargetTexture.prototype.renderToTarget = function (faceIndex, currentRenderList, currentRenderListLength, useCameraPostProcess, dumpForDebug) {
  58458. var scene = this.getScene();
  58459. if (!scene) {
  58460. return;
  58461. }
  58462. var engine = scene.getEngine();
  58463. if (!this._texture) {
  58464. return;
  58465. }
  58466. // Bind
  58467. if (this._postProcessManager) {
  58468. this._postProcessManager._prepareFrame(this._texture, this._postProcesses);
  58469. }
  58470. else if (!useCameraPostProcess || !scene.postProcessManager._prepareFrame(this._texture)) {
  58471. if (this._texture) {
  58472. engine.bindFramebuffer(this._texture, this.isCube ? faceIndex : undefined, undefined, undefined, this.ignoreCameraViewport, this.depthStencilTexture ? this.depthStencilTexture : undefined);
  58473. }
  58474. }
  58475. this.onBeforeRenderObservable.notifyObservers(faceIndex);
  58476. // Clear
  58477. if (this.onClearObservable.hasObservers()) {
  58478. this.onClearObservable.notifyObservers(engine);
  58479. }
  58480. else {
  58481. engine.clear(this.clearColor || scene.clearColor, true, true, true);
  58482. }
  58483. if (!this._doNotChangeAspectRatio) {
  58484. scene.updateTransformMatrix(true);
  58485. }
  58486. // Render
  58487. this._renderingManager.render(this.customRenderFunction, currentRenderList, this.renderParticles, this.renderSprites);
  58488. if (this._postProcessManager) {
  58489. this._postProcessManager._finalizeFrame(false, this._texture, faceIndex, this._postProcesses, this.ignoreCameraViewport);
  58490. }
  58491. else if (useCameraPostProcess) {
  58492. scene.postProcessManager._finalizeFrame(false, this._texture, faceIndex);
  58493. }
  58494. if (!this._doNotChangeAspectRatio) {
  58495. scene.updateTransformMatrix(true);
  58496. }
  58497. // Dump ?
  58498. if (dumpForDebug) {
  58499. BABYLON.Tools.DumpFramebuffer(this.getRenderWidth(), this.getRenderHeight(), engine);
  58500. }
  58501. // Unbind
  58502. if (!this.isCube || faceIndex === 5) {
  58503. if (this.isCube) {
  58504. if (faceIndex === 5) {
  58505. engine.generateMipMapsForCubemap(this._texture);
  58506. }
  58507. }
  58508. this.unbindFrameBuffer(engine, faceIndex);
  58509. }
  58510. else {
  58511. this.onAfterRenderObservable.notifyObservers(faceIndex);
  58512. }
  58513. };
  58514. /**
  58515. * Overrides the default sort function applied in the renderging group to prepare the meshes.
  58516. * This allowed control for front to back rendering or reversly depending of the special needs.
  58517. *
  58518. * @param renderingGroupId The rendering group id corresponding to its index
  58519. * @param opaqueSortCompareFn The opaque queue comparison function use to sort.
  58520. * @param alphaTestSortCompareFn The alpha test queue comparison function use to sort.
  58521. * @param transparentSortCompareFn The transparent queue comparison function use to sort.
  58522. */
  58523. RenderTargetTexture.prototype.setRenderingOrder = function (renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  58524. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  58525. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  58526. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  58527. this._renderingManager.setRenderingOrder(renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn);
  58528. };
  58529. /**
  58530. * Specifies whether or not the stencil and depth buffer are cleared between two rendering groups.
  58531. *
  58532. * @param renderingGroupId The rendering group id corresponding to its index
  58533. * @param autoClearDepthStencil Automatically clears depth and stencil between groups if true.
  58534. */
  58535. RenderTargetTexture.prototype.setRenderingAutoClearDepthStencil = function (renderingGroupId, autoClearDepthStencil) {
  58536. this._renderingManager.setRenderingAutoClearDepthStencil(renderingGroupId, autoClearDepthStencil);
  58537. };
  58538. RenderTargetTexture.prototype.clone = function () {
  58539. var textureSize = this.getSize();
  58540. 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);
  58541. // Base texture
  58542. newTexture.hasAlpha = this.hasAlpha;
  58543. newTexture.level = this.level;
  58544. // RenderTarget Texture
  58545. newTexture.coordinatesMode = this.coordinatesMode;
  58546. if (this.renderList) {
  58547. newTexture.renderList = this.renderList.slice(0);
  58548. }
  58549. return newTexture;
  58550. };
  58551. RenderTargetTexture.prototype.serialize = function () {
  58552. if (!this.name) {
  58553. return null;
  58554. }
  58555. var serializationObject = _super.prototype.serialize.call(this);
  58556. serializationObject.renderTargetSize = this.getRenderSize();
  58557. serializationObject.renderList = [];
  58558. if (this.renderList) {
  58559. for (var index = 0; index < this.renderList.length; index++) {
  58560. serializationObject.renderList.push(this.renderList[index].id);
  58561. }
  58562. }
  58563. return serializationObject;
  58564. };
  58565. // This will remove the attached framebuffer objects. The texture will not be able to be used as render target anymore
  58566. RenderTargetTexture.prototype.disposeFramebufferObjects = function () {
  58567. var objBuffer = this.getInternalTexture();
  58568. var scene = this.getScene();
  58569. if (objBuffer && scene) {
  58570. scene.getEngine()._releaseFramebufferObjects(objBuffer);
  58571. }
  58572. };
  58573. RenderTargetTexture.prototype.dispose = function () {
  58574. if (this._postProcessManager) {
  58575. this._postProcessManager.dispose();
  58576. this._postProcessManager = null;
  58577. }
  58578. this.clearPostProcesses(true);
  58579. if (this._resizeObserver) {
  58580. this.getScene().getEngine().onResizeObservable.remove(this._resizeObserver);
  58581. this._resizeObserver = null;
  58582. }
  58583. this.renderList = null;
  58584. // Remove from custom render targets
  58585. var scene = this.getScene();
  58586. if (!scene) {
  58587. return;
  58588. }
  58589. var index = scene.customRenderTargets.indexOf(this);
  58590. if (index >= 0) {
  58591. scene.customRenderTargets.splice(index, 1);
  58592. }
  58593. for (var _i = 0, _a = scene.cameras; _i < _a.length; _i++) {
  58594. var camera = _a[_i];
  58595. index = camera.customRenderTargets.indexOf(this);
  58596. if (index >= 0) {
  58597. camera.customRenderTargets.splice(index, 1);
  58598. }
  58599. }
  58600. _super.prototype.dispose.call(this);
  58601. };
  58602. RenderTargetTexture.prototype._rebuild = function () {
  58603. if (this.refreshRate === RenderTargetTexture.REFRESHRATE_RENDER_ONCE) {
  58604. this.refreshRate = RenderTargetTexture.REFRESHRATE_RENDER_ONCE;
  58605. }
  58606. if (this._postProcessManager) {
  58607. this._postProcessManager._rebuild();
  58608. }
  58609. };
  58610. RenderTargetTexture._REFRESHRATE_RENDER_ONCE = 0;
  58611. RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYFRAME = 1;
  58612. RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYTWOFRAMES = 2;
  58613. return RenderTargetTexture;
  58614. }(BABYLON.Texture));
  58615. BABYLON.RenderTargetTexture = RenderTargetTexture;
  58616. })(BABYLON || (BABYLON = {}));
  58617. //# sourceMappingURL=babylon.renderTargetTexture.js.map
  58618. var BABYLON;
  58619. (function (BABYLON) {
  58620. ;
  58621. var MultiRenderTarget = /** @class */ (function (_super) {
  58622. __extends(MultiRenderTarget, _super);
  58623. function MultiRenderTarget(name, size, count, scene, options) {
  58624. var _this = this;
  58625. var generateMipMaps = options && options.generateMipMaps ? options.generateMipMaps : false;
  58626. var generateDepthTexture = options && options.generateDepthTexture ? options.generateDepthTexture : false;
  58627. var doNotChangeAspectRatio = !options || options.doNotChangeAspectRatio === undefined ? true : options.doNotChangeAspectRatio;
  58628. _this = _super.call(this, name, size, scene, generateMipMaps, doNotChangeAspectRatio) || this;
  58629. _this._engine = scene.getEngine();
  58630. if (!_this.isSupported) {
  58631. _this.dispose();
  58632. return;
  58633. }
  58634. var types = [];
  58635. var samplingModes = [];
  58636. for (var i = 0; i < count; i++) {
  58637. if (options && options.types && options.types[i] !== undefined) {
  58638. types.push(options.types[i]);
  58639. }
  58640. else {
  58641. types.push(options && options.defaultType ? options.defaultType : BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  58642. }
  58643. if (options && options.samplingModes && options.samplingModes[i] !== undefined) {
  58644. samplingModes.push(options.samplingModes[i]);
  58645. }
  58646. else {
  58647. samplingModes.push(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  58648. }
  58649. }
  58650. var generateDepthBuffer = !options || options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  58651. var generateStencilBuffer = !options || options.generateStencilBuffer === undefined ? false : options.generateStencilBuffer;
  58652. _this._size = size;
  58653. _this._multiRenderTargetOptions = {
  58654. samplingModes: samplingModes,
  58655. generateMipMaps: generateMipMaps,
  58656. generateDepthBuffer: generateDepthBuffer,
  58657. generateStencilBuffer: generateStencilBuffer,
  58658. generateDepthTexture: generateDepthTexture,
  58659. types: types,
  58660. textureCount: count
  58661. };
  58662. _this._createInternalTextures();
  58663. _this._createTextures();
  58664. return _this;
  58665. }
  58666. Object.defineProperty(MultiRenderTarget.prototype, "isSupported", {
  58667. get: function () {
  58668. return this._engine.webGLVersion > 1 || this._engine.getCaps().drawBuffersExtension;
  58669. },
  58670. enumerable: true,
  58671. configurable: true
  58672. });
  58673. Object.defineProperty(MultiRenderTarget.prototype, "textures", {
  58674. get: function () {
  58675. return this._textures;
  58676. },
  58677. enumerable: true,
  58678. configurable: true
  58679. });
  58680. Object.defineProperty(MultiRenderTarget.prototype, "depthTexture", {
  58681. get: function () {
  58682. return this._textures[this._textures.length - 1];
  58683. },
  58684. enumerable: true,
  58685. configurable: true
  58686. });
  58687. Object.defineProperty(MultiRenderTarget.prototype, "wrapU", {
  58688. set: function (wrap) {
  58689. if (this._textures) {
  58690. for (var i = 0; i < this._textures.length; i++) {
  58691. this._textures[i].wrapU = wrap;
  58692. }
  58693. }
  58694. },
  58695. enumerable: true,
  58696. configurable: true
  58697. });
  58698. Object.defineProperty(MultiRenderTarget.prototype, "wrapV", {
  58699. set: function (wrap) {
  58700. if (this._textures) {
  58701. for (var i = 0; i < this._textures.length; i++) {
  58702. this._textures[i].wrapV = wrap;
  58703. }
  58704. }
  58705. },
  58706. enumerable: true,
  58707. configurable: true
  58708. });
  58709. MultiRenderTarget.prototype._rebuild = function () {
  58710. this.releaseInternalTextures();
  58711. this._createInternalTextures();
  58712. for (var i = 0; i < this._internalTextures.length; i++) {
  58713. var texture = this._textures[i];
  58714. texture._texture = this._internalTextures[i];
  58715. }
  58716. // Keeps references to frame buffer and stencil/depth buffer
  58717. this._texture = this._internalTextures[0];
  58718. };
  58719. MultiRenderTarget.prototype._createInternalTextures = function () {
  58720. this._internalTextures = this._engine.createMultipleRenderTarget(this._size, this._multiRenderTargetOptions);
  58721. };
  58722. MultiRenderTarget.prototype._createTextures = function () {
  58723. this._textures = [];
  58724. for (var i = 0; i < this._internalTextures.length; i++) {
  58725. var texture = new BABYLON.Texture(null, this.getScene());
  58726. texture._texture = this._internalTextures[i];
  58727. this._textures.push(texture);
  58728. }
  58729. // Keeps references to frame buffer and stencil/depth buffer
  58730. this._texture = this._internalTextures[0];
  58731. };
  58732. Object.defineProperty(MultiRenderTarget.prototype, "samples", {
  58733. get: function () {
  58734. return this._samples;
  58735. },
  58736. set: function (value) {
  58737. if (this._samples === value) {
  58738. return;
  58739. }
  58740. this._samples = this._engine.updateMultipleRenderTargetTextureSampleCount(this._internalTextures, value);
  58741. },
  58742. enumerable: true,
  58743. configurable: true
  58744. });
  58745. MultiRenderTarget.prototype.resize = function (size) {
  58746. this.releaseInternalTextures();
  58747. this._internalTextures = this._engine.createMultipleRenderTarget(size, this._multiRenderTargetOptions);
  58748. this._createInternalTextures();
  58749. };
  58750. MultiRenderTarget.prototype.unbindFrameBuffer = function (engine, faceIndex) {
  58751. var _this = this;
  58752. engine.unBindMultiColorAttachmentFramebuffer(this._internalTextures, this.isCube, function () {
  58753. _this.onAfterRenderObservable.notifyObservers(faceIndex);
  58754. });
  58755. };
  58756. MultiRenderTarget.prototype.dispose = function () {
  58757. this.releaseInternalTextures();
  58758. _super.prototype.dispose.call(this);
  58759. };
  58760. MultiRenderTarget.prototype.releaseInternalTextures = function () {
  58761. if (!this._internalTextures) {
  58762. return;
  58763. }
  58764. for (var i = this._internalTextures.length - 1; i >= 0; i--) {
  58765. if (this._internalTextures[i] !== undefined) {
  58766. this._internalTextures[i].dispose();
  58767. this._internalTextures.splice(i, 1);
  58768. }
  58769. }
  58770. };
  58771. return MultiRenderTarget;
  58772. }(BABYLON.RenderTargetTexture));
  58773. BABYLON.MultiRenderTarget = MultiRenderTarget;
  58774. })(BABYLON || (BABYLON = {}));
  58775. //# sourceMappingURL=babylon.multiRenderTarget.js.map
  58776. var BABYLON;
  58777. (function (BABYLON) {
  58778. var MirrorTexture = /** @class */ (function (_super) {
  58779. __extends(MirrorTexture, _super);
  58780. function MirrorTexture(name, size, scene, generateMipMaps, type, samplingMode, generateDepthBuffer) {
  58781. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  58782. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  58783. if (generateDepthBuffer === void 0) { generateDepthBuffer = true; }
  58784. var _this = _super.call(this, name, size, scene, generateMipMaps, true, type, false, samplingMode, generateDepthBuffer) || this;
  58785. _this.mirrorPlane = new BABYLON.Plane(0, 1, 0, 1);
  58786. _this._transformMatrix = BABYLON.Matrix.Zero();
  58787. _this._mirrorMatrix = BABYLON.Matrix.Zero();
  58788. _this._adaptiveBlurKernel = 0;
  58789. _this._blurKernelX = 0;
  58790. _this._blurKernelY = 0;
  58791. _this._blurRatio = 1.0;
  58792. _this.ignoreCameraViewport = true;
  58793. _this.onBeforeRenderObservable.add(function () {
  58794. BABYLON.Matrix.ReflectionToRef(_this.mirrorPlane, _this._mirrorMatrix);
  58795. _this._savedViewMatrix = scene.getViewMatrix();
  58796. _this._mirrorMatrix.multiplyToRef(_this._savedViewMatrix, _this._transformMatrix);
  58797. scene.setTransformMatrix(_this._transformMatrix, scene.getProjectionMatrix());
  58798. scene.clipPlane = _this.mirrorPlane;
  58799. scene.getEngine().cullBackFaces = false;
  58800. scene._mirroredCameraPosition = BABYLON.Vector3.TransformCoordinates(scene.activeCamera.globalPosition, _this._mirrorMatrix);
  58801. });
  58802. _this.onAfterRenderObservable.add(function () {
  58803. scene.setTransformMatrix(_this._savedViewMatrix, scene.getProjectionMatrix());
  58804. scene.getEngine().cullBackFaces = true;
  58805. scene._mirroredCameraPosition = null;
  58806. delete scene.clipPlane;
  58807. });
  58808. return _this;
  58809. }
  58810. Object.defineProperty(MirrorTexture.prototype, "blurRatio", {
  58811. get: function () {
  58812. return this._blurRatio;
  58813. },
  58814. set: function (value) {
  58815. if (this._blurRatio === value) {
  58816. return;
  58817. }
  58818. this._blurRatio = value;
  58819. this._preparePostProcesses();
  58820. },
  58821. enumerable: true,
  58822. configurable: true
  58823. });
  58824. Object.defineProperty(MirrorTexture.prototype, "adaptiveBlurKernel", {
  58825. set: function (value) {
  58826. this._adaptiveBlurKernel = value;
  58827. this._autoComputeBlurKernel();
  58828. },
  58829. enumerable: true,
  58830. configurable: true
  58831. });
  58832. Object.defineProperty(MirrorTexture.prototype, "blurKernel", {
  58833. set: function (value) {
  58834. this.blurKernelX = value;
  58835. this.blurKernelY = value;
  58836. },
  58837. enumerable: true,
  58838. configurable: true
  58839. });
  58840. Object.defineProperty(MirrorTexture.prototype, "blurKernelX", {
  58841. get: function () {
  58842. return this._blurKernelX;
  58843. },
  58844. set: function (value) {
  58845. if (this._blurKernelX === value) {
  58846. return;
  58847. }
  58848. this._blurKernelX = value;
  58849. this._preparePostProcesses();
  58850. },
  58851. enumerable: true,
  58852. configurable: true
  58853. });
  58854. Object.defineProperty(MirrorTexture.prototype, "blurKernelY", {
  58855. get: function () {
  58856. return this._blurKernelY;
  58857. },
  58858. set: function (value) {
  58859. if (this._blurKernelY === value) {
  58860. return;
  58861. }
  58862. this._blurKernelY = value;
  58863. this._preparePostProcesses();
  58864. },
  58865. enumerable: true,
  58866. configurable: true
  58867. });
  58868. MirrorTexture.prototype._autoComputeBlurKernel = function () {
  58869. var engine = this.getScene().getEngine();
  58870. var dw = this.getRenderWidth() / engine.getRenderWidth();
  58871. var dh = this.getRenderHeight() / engine.getRenderHeight();
  58872. this.blurKernelX = this._adaptiveBlurKernel * dw;
  58873. this.blurKernelY = this._adaptiveBlurKernel * dh;
  58874. };
  58875. MirrorTexture.prototype._onRatioRescale = function () {
  58876. if (this._sizeRatio) {
  58877. this.resize(this._initialSizeParameter);
  58878. if (!this._adaptiveBlurKernel) {
  58879. this._preparePostProcesses();
  58880. }
  58881. }
  58882. if (this._adaptiveBlurKernel) {
  58883. this._autoComputeBlurKernel();
  58884. }
  58885. };
  58886. MirrorTexture.prototype._preparePostProcesses = function () {
  58887. this.clearPostProcesses(true);
  58888. if (this._blurKernelX && this._blurKernelY) {
  58889. var engine = this.getScene().getEngine();
  58890. var textureType = engine.getCaps().textureFloatRender ? BABYLON.Engine.TEXTURETYPE_FLOAT : BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  58891. 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);
  58892. this._blurX.autoClear = false;
  58893. if (this._blurRatio === 1 && this.samples < 2 && this._texture) {
  58894. this._blurX.inputTexture = this._texture;
  58895. }
  58896. else {
  58897. this._blurX.alwaysForcePOT = true;
  58898. }
  58899. 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);
  58900. this._blurY.autoClear = false;
  58901. this._blurY.alwaysForcePOT = this._blurRatio !== 1;
  58902. this.addPostProcess(this._blurX);
  58903. this.addPostProcess(this._blurY);
  58904. }
  58905. else {
  58906. if (this._blurY) {
  58907. this.removePostProcess(this._blurY);
  58908. this._blurY.dispose();
  58909. this._blurY = null;
  58910. }
  58911. if (this._blurX) {
  58912. this.removePostProcess(this._blurX);
  58913. this._blurX.dispose();
  58914. this._blurX = null;
  58915. }
  58916. }
  58917. };
  58918. MirrorTexture.prototype.clone = function () {
  58919. var scene = this.getScene();
  58920. if (!scene) {
  58921. return this;
  58922. }
  58923. var textureSize = this.getSize();
  58924. var newTexture = new MirrorTexture(this.name, textureSize.width, scene, this._renderTargetOptions.generateMipMaps, this._renderTargetOptions.type, this._renderTargetOptions.samplingMode, this._renderTargetOptions.generateDepthBuffer);
  58925. // Base texture
  58926. newTexture.hasAlpha = this.hasAlpha;
  58927. newTexture.level = this.level;
  58928. // Mirror Texture
  58929. newTexture.mirrorPlane = this.mirrorPlane.clone();
  58930. if (this.renderList) {
  58931. newTexture.renderList = this.renderList.slice(0);
  58932. }
  58933. return newTexture;
  58934. };
  58935. MirrorTexture.prototype.serialize = function () {
  58936. if (!this.name) {
  58937. return null;
  58938. }
  58939. var serializationObject = _super.prototype.serialize.call(this);
  58940. serializationObject.mirrorPlane = this.mirrorPlane.asArray();
  58941. return serializationObject;
  58942. };
  58943. return MirrorTexture;
  58944. }(BABYLON.RenderTargetTexture));
  58945. BABYLON.MirrorTexture = MirrorTexture;
  58946. })(BABYLON || (BABYLON = {}));
  58947. //# sourceMappingURL=babylon.mirrorTexture.js.map
  58948. var BABYLON;
  58949. (function (BABYLON) {
  58950. /**
  58951. * Creates a refraction texture used by refraction channel of the standard material.
  58952. * @param name the texture name
  58953. * @param size size of the underlying texture
  58954. * @param scene root scene
  58955. */
  58956. var RefractionTexture = /** @class */ (function (_super) {
  58957. __extends(RefractionTexture, _super);
  58958. function RefractionTexture(name, size, scene, generateMipMaps) {
  58959. var _this = _super.call(this, name, size, scene, generateMipMaps, true) || this;
  58960. _this.refractionPlane = new BABYLON.Plane(0, 1, 0, 1);
  58961. _this.depth = 2.0;
  58962. _this.onBeforeRenderObservable.add(function () {
  58963. scene.clipPlane = _this.refractionPlane;
  58964. });
  58965. _this.onAfterRenderObservable.add(function () {
  58966. delete scene.clipPlane;
  58967. });
  58968. return _this;
  58969. }
  58970. RefractionTexture.prototype.clone = function () {
  58971. var scene = this.getScene();
  58972. if (!scene) {
  58973. return this;
  58974. }
  58975. var textureSize = this.getSize();
  58976. var newTexture = new RefractionTexture(this.name, textureSize.width, scene, this._generateMipMaps);
  58977. // Base texture
  58978. newTexture.hasAlpha = this.hasAlpha;
  58979. newTexture.level = this.level;
  58980. // Refraction Texture
  58981. newTexture.refractionPlane = this.refractionPlane.clone();
  58982. if (this.renderList) {
  58983. newTexture.renderList = this.renderList.slice(0);
  58984. }
  58985. newTexture.depth = this.depth;
  58986. return newTexture;
  58987. };
  58988. RefractionTexture.prototype.serialize = function () {
  58989. if (!this.name) {
  58990. return null;
  58991. }
  58992. var serializationObject = _super.prototype.serialize.call(this);
  58993. serializationObject.mirrorPlane = this.refractionPlane.asArray();
  58994. serializationObject.depth = this.depth;
  58995. return serializationObject;
  58996. };
  58997. return RefractionTexture;
  58998. }(BABYLON.RenderTargetTexture));
  58999. BABYLON.RefractionTexture = RefractionTexture;
  59000. })(BABYLON || (BABYLON = {}));
  59001. //# sourceMappingURL=babylon.refractionTexture.js.map
  59002. var BABYLON;
  59003. (function (BABYLON) {
  59004. var DynamicTexture = /** @class */ (function (_super) {
  59005. __extends(DynamicTexture, _super);
  59006. function DynamicTexture(name, options, scene, generateMipMaps, samplingMode, format) {
  59007. if (scene === void 0) { scene = null; }
  59008. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  59009. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  59010. var _this = _super.call(this, null, scene, !generateMipMaps, undefined, samplingMode, undefined, undefined, undefined, undefined, format) || this;
  59011. _this.name = name;
  59012. _this._engine = _this.getScene().getEngine();
  59013. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  59014. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  59015. _this._generateMipMaps = generateMipMaps;
  59016. if (options.getContext) {
  59017. _this._canvas = options;
  59018. _this._texture = _this._engine.createDynamicTexture(options.width, options.height, generateMipMaps, samplingMode);
  59019. }
  59020. else {
  59021. _this._canvas = document.createElement("canvas");
  59022. if (options.width) {
  59023. _this._texture = _this._engine.createDynamicTexture(options.width, options.height, generateMipMaps, samplingMode);
  59024. }
  59025. else {
  59026. _this._texture = _this._engine.createDynamicTexture(options, options, generateMipMaps, samplingMode);
  59027. }
  59028. }
  59029. var textureSize = _this.getSize();
  59030. _this._canvas.width = textureSize.width;
  59031. _this._canvas.height = textureSize.height;
  59032. _this._context = _this._canvas.getContext("2d");
  59033. return _this;
  59034. }
  59035. Object.defineProperty(DynamicTexture.prototype, "canRescale", {
  59036. get: function () {
  59037. return true;
  59038. },
  59039. enumerable: true,
  59040. configurable: true
  59041. });
  59042. DynamicTexture.prototype._recreate = function (textureSize) {
  59043. this._canvas.width = textureSize.width;
  59044. this._canvas.height = textureSize.height;
  59045. this.releaseInternalTexture();
  59046. this._texture = this._engine.createDynamicTexture(textureSize.width, textureSize.height, this._generateMipMaps, this._samplingMode);
  59047. };
  59048. DynamicTexture.prototype.scale = function (ratio) {
  59049. var textureSize = this.getSize();
  59050. textureSize.width *= ratio;
  59051. textureSize.height *= ratio;
  59052. this._recreate(textureSize);
  59053. };
  59054. DynamicTexture.prototype.scaleTo = function (width, height) {
  59055. var textureSize = this.getSize();
  59056. textureSize.width = width;
  59057. textureSize.height = height;
  59058. this._recreate(textureSize);
  59059. };
  59060. DynamicTexture.prototype.getContext = function () {
  59061. return this._context;
  59062. };
  59063. DynamicTexture.prototype.clear = function () {
  59064. var size = this.getSize();
  59065. this._context.fillRect(0, 0, size.width, size.height);
  59066. };
  59067. DynamicTexture.prototype.update = function (invertY) {
  59068. this._engine.updateDynamicTexture(this._texture, this._canvas, invertY === undefined ? true : invertY, undefined, this._format || undefined);
  59069. };
  59070. DynamicTexture.prototype.drawText = function (text, x, y, font, color, clearColor, invertY, update) {
  59071. if (update === void 0) { update = true; }
  59072. var size = this.getSize();
  59073. if (clearColor) {
  59074. this._context.fillStyle = clearColor;
  59075. this._context.fillRect(0, 0, size.width, size.height);
  59076. }
  59077. this._context.font = font;
  59078. if (x === null || x === undefined) {
  59079. var textSize = this._context.measureText(text);
  59080. x = (size.width - textSize.width) / 2;
  59081. }
  59082. if (y === null || y === undefined) {
  59083. var fontSize = parseInt((font.replace(/\D/g, '')));
  59084. ;
  59085. y = (size.height / 2) + (fontSize / 3.65);
  59086. }
  59087. this._context.fillStyle = color;
  59088. this._context.fillText(text, x, y);
  59089. if (update) {
  59090. this.update(invertY);
  59091. }
  59092. };
  59093. DynamicTexture.prototype.clone = function () {
  59094. var scene = this.getScene();
  59095. if (!scene) {
  59096. return this;
  59097. }
  59098. var textureSize = this.getSize();
  59099. var newTexture = new DynamicTexture(this.name, textureSize, scene, this._generateMipMaps);
  59100. // Base texture
  59101. newTexture.hasAlpha = this.hasAlpha;
  59102. newTexture.level = this.level;
  59103. // Dynamic Texture
  59104. newTexture.wrapU = this.wrapU;
  59105. newTexture.wrapV = this.wrapV;
  59106. return newTexture;
  59107. };
  59108. DynamicTexture.prototype._rebuild = function () {
  59109. this.update();
  59110. };
  59111. return DynamicTexture;
  59112. }(BABYLON.Texture));
  59113. BABYLON.DynamicTexture = DynamicTexture;
  59114. })(BABYLON || (BABYLON = {}));
  59115. //# sourceMappingURL=babylon.dynamicTexture.js.map
  59116. var BABYLON;
  59117. (function (BABYLON) {
  59118. var VideoTexture = /** @class */ (function (_super) {
  59119. __extends(VideoTexture, _super);
  59120. /**
  59121. * Creates a video texture.
  59122. * Sample : https://doc.babylonjs.com/how_to/video_texture
  59123. * @param {string | null} name optional name, will detect from video source, if not defined
  59124. * @param {(string | string[] | HTMLVideoElement)} src can be used to provide an url, array of urls or an already setup HTML video element.
  59125. * @param {BABYLON.Scene} scene is obviously the current scene.
  59126. * @param {boolean} generateMipMaps can be used to turn on mipmaps (Can be expensive for videoTextures because they are often updated).
  59127. * @param {boolean} invertY is false by default but can be used to invert video on Y axis
  59128. * @param {number} samplingMode controls the sampling method and is set to TRILINEAR_SAMPLINGMODE by default
  59129. * @param {VideoTextureSettings} [settings] allows finer control over video usage
  59130. */
  59131. function VideoTexture(name, src, scene, generateMipMaps, invertY, samplingMode, settings) {
  59132. if (generateMipMaps === void 0) { generateMipMaps = false; }
  59133. if (invertY === void 0) { invertY = false; }
  59134. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  59135. if (settings === void 0) { settings = {
  59136. autoPlay: true,
  59137. loop: true,
  59138. autoUpdateTexture: true,
  59139. }; }
  59140. var _this = _super.call(this, null, scene, !generateMipMaps, invertY) || this;
  59141. _this._createInternalTexture = function () {
  59142. if (_this._texture != null) {
  59143. return;
  59144. }
  59145. if (!_this._engine.needPOTTextures ||
  59146. (BABYLON.Tools.IsExponentOfTwo(_this.video.videoWidth) && BABYLON.Tools.IsExponentOfTwo(_this.video.videoHeight))) {
  59147. _this.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  59148. _this.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  59149. }
  59150. else {
  59151. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  59152. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  59153. _this._generateMipMaps = false;
  59154. }
  59155. _this._texture = _this._engine.createDynamicTexture(_this.video.videoWidth, _this.video.videoHeight, _this._generateMipMaps, _this._samplingMode);
  59156. _this._texture.isReady = true;
  59157. _this._updateInternalTexture();
  59158. if (_this._onLoadObservable && _this._onLoadObservable.hasObservers()) {
  59159. _this.onLoadObservable.notifyObservers(_this);
  59160. }
  59161. };
  59162. _this.reset = function () {
  59163. if (_this._texture == null) {
  59164. return;
  59165. }
  59166. _this._texture.dispose();
  59167. _this._texture = null;
  59168. };
  59169. _this._updateInternalTexture = function (e) {
  59170. if (_this._texture == null || !_this._texture.isReady) {
  59171. return;
  59172. }
  59173. if (_this.video.readyState < _this.video.HAVE_CURRENT_DATA) {
  59174. return;
  59175. }
  59176. _this._engine.updateVideoTexture(_this._texture, _this.video, _this._invertY);
  59177. };
  59178. _this._engine = _this.getScene().getEngine();
  59179. _this._generateMipMaps = generateMipMaps;
  59180. _this._samplingMode = samplingMode;
  59181. _this.autoUpdateTexture = settings.autoUpdateTexture;
  59182. _this.name = name || _this._getName(src);
  59183. _this.video = _this._getVideo(src);
  59184. if (settings.autoPlay !== undefined) {
  59185. _this.video.autoplay = settings.autoPlay;
  59186. }
  59187. if (settings.loop !== undefined) {
  59188. _this.video.loop = settings.loop;
  59189. }
  59190. _this.video.addEventListener("canplay", _this._createInternalTexture);
  59191. _this.video.addEventListener("paused", _this._updateInternalTexture);
  59192. _this.video.addEventListener("seeked", _this._updateInternalTexture);
  59193. _this.video.addEventListener("emptied", _this.reset);
  59194. if (_this.video.readyState >= _this.video.HAVE_CURRENT_DATA) {
  59195. _this._createInternalTexture();
  59196. }
  59197. return _this;
  59198. }
  59199. VideoTexture.prototype._getName = function (src) {
  59200. if (src instanceof HTMLVideoElement) {
  59201. return src.currentSrc;
  59202. }
  59203. if (typeof src === "object") {
  59204. return src.toString();
  59205. }
  59206. return src;
  59207. };
  59208. ;
  59209. VideoTexture.prototype._getVideo = function (src) {
  59210. if (src instanceof HTMLVideoElement) {
  59211. BABYLON.Tools.SetCorsBehavior(src.currentSrc, src);
  59212. return src;
  59213. }
  59214. var video = document.createElement("video");
  59215. if (typeof src === "string") {
  59216. BABYLON.Tools.SetCorsBehavior(src, video);
  59217. video.src = src;
  59218. }
  59219. else {
  59220. BABYLON.Tools.SetCorsBehavior(src[0], video);
  59221. src.forEach(function (url) {
  59222. var source = document.createElement("source");
  59223. source.src = url;
  59224. video.appendChild(source);
  59225. });
  59226. }
  59227. return video;
  59228. };
  59229. ;
  59230. /**
  59231. * Internal method to initiate `update`.
  59232. */
  59233. VideoTexture.prototype._rebuild = function () {
  59234. this.update();
  59235. };
  59236. /**
  59237. * Update Texture in the `auto` mode. Does not do anything if `settings.autoUpdateTexture` is false.
  59238. */
  59239. VideoTexture.prototype.update = function () {
  59240. if (!this.autoUpdateTexture) {
  59241. // Expecting user to call `updateTexture` manually
  59242. return;
  59243. }
  59244. this.updateTexture(true);
  59245. };
  59246. /**
  59247. * Update Texture in `manual` mode. Does not do anything if not visible or paused.
  59248. * @param isVisible Visibility state, detected by user using `scene.getActiveMeshes()` or othervise.
  59249. */
  59250. VideoTexture.prototype.updateTexture = function (isVisible) {
  59251. if (!isVisible) {
  59252. return;
  59253. }
  59254. if (this.video.paused) {
  59255. return;
  59256. }
  59257. this._updateInternalTexture();
  59258. };
  59259. /**
  59260. * Change video content. Changing video instance or setting multiple urls (as in constructor) is not supported.
  59261. * @param url New url.
  59262. */
  59263. VideoTexture.prototype.updateURL = function (url) {
  59264. this.video.src = url;
  59265. };
  59266. VideoTexture.prototype.dispose = function () {
  59267. _super.prototype.dispose.call(this);
  59268. this.video.removeEventListener("canplay", this._createInternalTexture);
  59269. this.video.removeEventListener("paused", this._updateInternalTexture);
  59270. this.video.removeEventListener("seeked", this._updateInternalTexture);
  59271. this.video.removeEventListener("emptied", this.reset);
  59272. this.video.pause();
  59273. };
  59274. VideoTexture.CreateFromWebCam = function (scene, onReady, constraints) {
  59275. var video = document.createElement("video");
  59276. var constraintsDeviceId;
  59277. if (constraints && constraints.deviceId) {
  59278. constraintsDeviceId = {
  59279. exact: constraints.deviceId,
  59280. };
  59281. }
  59282. window.URL = window.URL || window.webkitURL || window.mozURL || window.msURL;
  59283. if (navigator.mediaDevices) {
  59284. navigator.mediaDevices.getUserMedia({ video: constraints })
  59285. .then(function (stream) {
  59286. if (video.mozSrcObject !== undefined) {
  59287. // hack for Firefox < 19
  59288. video.mozSrcObject = stream;
  59289. }
  59290. else {
  59291. video.srcObject = stream;
  59292. }
  59293. var onPlaying = function () {
  59294. if (onReady) {
  59295. onReady(new VideoTexture("video", video, scene, true, true));
  59296. }
  59297. video.removeEventListener("playing", onPlaying);
  59298. };
  59299. video.addEventListener("playing", onPlaying);
  59300. video.play();
  59301. })
  59302. .catch(function (err) {
  59303. BABYLON.Tools.Error(err.name);
  59304. });
  59305. }
  59306. else {
  59307. navigator.getUserMedia =
  59308. navigator.getUserMedia ||
  59309. navigator.webkitGetUserMedia ||
  59310. navigator.mozGetUserMedia ||
  59311. navigator.msGetUserMedia;
  59312. if (navigator.getUserMedia) {
  59313. navigator.getUserMedia({
  59314. video: {
  59315. deviceId: constraintsDeviceId,
  59316. width: {
  59317. min: (constraints && constraints.minWidth) || 256,
  59318. max: (constraints && constraints.maxWidth) || 640,
  59319. },
  59320. height: {
  59321. min: (constraints && constraints.minHeight) || 256,
  59322. max: (constraints && constraints.maxHeight) || 480,
  59323. },
  59324. },
  59325. }, function (stream) {
  59326. if (video.mozSrcObject !== undefined) {
  59327. // hack for Firefox < 19
  59328. video.mozSrcObject = stream;
  59329. }
  59330. else {
  59331. video.src = (window.URL && window.URL.createObjectURL(stream)) || stream;
  59332. }
  59333. video.play();
  59334. if (onReady) {
  59335. onReady(new VideoTexture("video", video, scene, true, true));
  59336. }
  59337. }, function (e) {
  59338. BABYLON.Tools.Error(e.name);
  59339. });
  59340. }
  59341. }
  59342. };
  59343. return VideoTexture;
  59344. }(BABYLON.Texture));
  59345. BABYLON.VideoTexture = VideoTexture;
  59346. })(BABYLON || (BABYLON = {}));
  59347. //# sourceMappingURL=babylon.videoTexture.js.map
  59348. var BABYLON;
  59349. (function (BABYLON) {
  59350. var RawTexture = /** @class */ (function (_super) {
  59351. __extends(RawTexture, _super);
  59352. function RawTexture(data, width, height, format, scene, generateMipMaps, invertY, samplingMode, type) {
  59353. if (generateMipMaps === void 0) { generateMipMaps = true; }
  59354. if (invertY === void 0) { invertY = false; }
  59355. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  59356. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  59357. var _this = _super.call(this, null, scene, !generateMipMaps, invertY) || this;
  59358. _this.format = format;
  59359. _this._engine = scene.getEngine();
  59360. _this._texture = scene.getEngine().createRawTexture(data, width, height, format, generateMipMaps, invertY, samplingMode, null, type);
  59361. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  59362. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  59363. return _this;
  59364. }
  59365. RawTexture.prototype.update = function (data) {
  59366. this._engine.updateRawTexture(this._texture, data, this._texture.format, this._texture.invertY, undefined, this._texture.type);
  59367. };
  59368. // Statics
  59369. RawTexture.CreateLuminanceTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  59370. if (generateMipMaps === void 0) { generateMipMaps = true; }
  59371. if (invertY === void 0) { invertY = false; }
  59372. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  59373. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_LUMINANCE, scene, generateMipMaps, invertY, samplingMode);
  59374. };
  59375. RawTexture.CreateLuminanceAlphaTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  59376. if (generateMipMaps === void 0) { generateMipMaps = true; }
  59377. if (invertY === void 0) { invertY = false; }
  59378. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  59379. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_LUMINANCE_ALPHA, scene, generateMipMaps, invertY, samplingMode);
  59380. };
  59381. RawTexture.CreateAlphaTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  59382. if (generateMipMaps === void 0) { generateMipMaps = true; }
  59383. if (invertY === void 0) { invertY = false; }
  59384. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  59385. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_ALPHA, scene, generateMipMaps, invertY, samplingMode);
  59386. };
  59387. RawTexture.CreateRGBTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode, type) {
  59388. if (generateMipMaps === void 0) { generateMipMaps = true; }
  59389. if (invertY === void 0) { invertY = false; }
  59390. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  59391. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  59392. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_RGB, scene, generateMipMaps, invertY, samplingMode, type);
  59393. };
  59394. RawTexture.CreateRGBATexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode, type) {
  59395. if (generateMipMaps === void 0) { generateMipMaps = true; }
  59396. if (invertY === void 0) { invertY = false; }
  59397. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  59398. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  59399. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_RGBA, scene, generateMipMaps, invertY, samplingMode, type);
  59400. };
  59401. return RawTexture;
  59402. }(BABYLON.Texture));
  59403. BABYLON.RawTexture = RawTexture;
  59404. })(BABYLON || (BABYLON = {}));
  59405. //# sourceMappingURL=babylon.rawTexture.js.map
  59406. var BABYLON;
  59407. (function (BABYLON) {
  59408. /**
  59409. * PostProcess can be used to apply a shader to a texture after it has been rendered
  59410. * See https://doc.babylonjs.com/how_to/how_to_use_postprocesses
  59411. */
  59412. var PostProcess = /** @class */ (function () {
  59413. /**
  59414. * Creates a new instance of @see PostProcess
  59415. * @param name The name of the PostProcess.
  59416. * @param fragmentUrl The url of the fragment shader to be used.
  59417. * @param parameters Array of the names of uniform non-sampler2D variables that will be passed to the shader.
  59418. * @param samplers Array of the names of uniform sampler2D variables that will be passed to the shader.
  59419. * @param options The required width/height ratio to downsize to before computing the render pass. (Use 1.0 for full size)
  59420. * @param camera The camera to apply the render pass to.
  59421. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  59422. * @param engine The engine which the post process will be applied. (default: current engine)
  59423. * @param reusable If the post process can be reused on the same frame. (default: false)
  59424. * @param defines String of defines that will be set when running the fragment shader. (default: null)
  59425. * @param textureType Type of textures used when performing the post process. (default: 0)
  59426. * @param vertexUrl The url of the vertex shader to be used. (default: "postprocess")
  59427. * @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
  59428. * @param blockCompilation If the shader should not be compiled imediatly. (default: false)
  59429. */
  59430. function PostProcess(/** Name of the PostProcess. */ name, fragmentUrl, parameters, samplers, options, camera, samplingMode, engine, reusable, defines, textureType, vertexUrl, indexParameters, blockCompilation) {
  59431. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE; }
  59432. if (defines === void 0) { defines = null; }
  59433. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  59434. if (vertexUrl === void 0) { vertexUrl = "postprocess"; }
  59435. if (blockCompilation === void 0) { blockCompilation = false; }
  59436. this.name = name;
  59437. /**
  59438. * Width of the texture to apply the post process on
  59439. */
  59440. this.width = -1;
  59441. /**
  59442. * Height of the texture to apply the post process on
  59443. */
  59444. this.height = -1;
  59445. /**
  59446. * If the buffer needs to be cleared before applying the post process. (default: true)
  59447. * Should be set to false if shader will overwrite all previous pixels.
  59448. */
  59449. this.autoClear = true;
  59450. /**
  59451. * Type of alpha mode to use when performing the post process (default: Engine.ALPHA_DISABLE)
  59452. */
  59453. this.alphaMode = BABYLON.Engine.ALPHA_DISABLE;
  59454. /**
  59455. * Animations to be used for the post processing
  59456. */
  59457. this.animations = new Array();
  59458. /**
  59459. * Enable Pixel Perfect mode where texture is not scaled to be power of 2.
  59460. * Can only be used on a single postprocess or on the last one of a chain. (default: false)
  59461. */
  59462. this.enablePixelPerfectMode = false;
  59463. /**
  59464. * Scale mode for the post process (default: Engine.SCALEMODE_FLOOR)
  59465. */
  59466. this.scaleMode = BABYLON.Engine.SCALEMODE_FLOOR;
  59467. /**
  59468. * Force textures to be a power of two (default: false)
  59469. */
  59470. this.alwaysForcePOT = false;
  59471. /**
  59472. * Number of sample textures (default: 1)
  59473. */
  59474. this.samples = 1;
  59475. /**
  59476. * Modify the scale of the post process to be the same as the viewport (default: false)
  59477. */
  59478. this.adaptScaleToCurrentViewport = false;
  59479. this._reusable = false;
  59480. /**
  59481. * Smart array of input and output textures for the post process.
  59482. */
  59483. this._textures = new BABYLON.SmartArray(2);
  59484. /**
  59485. * The index in _textures that corresponds to the output texture.
  59486. */
  59487. this._currentRenderTextureInd = 0;
  59488. this._scaleRatio = new BABYLON.Vector2(1, 1);
  59489. this._texelSize = BABYLON.Vector2.Zero();
  59490. // Events
  59491. /**
  59492. * An event triggered when the postprocess is activated.
  59493. * @type {BABYLON.Observable}
  59494. */
  59495. this.onActivateObservable = new BABYLON.Observable();
  59496. /**
  59497. * An event triggered when the postprocess changes its size.
  59498. * @type {BABYLON.Observable}
  59499. */
  59500. this.onSizeChangedObservable = new BABYLON.Observable();
  59501. /**
  59502. * An event triggered when the postprocess applies its effect.
  59503. * @type {BABYLON.Observable}
  59504. */
  59505. this.onApplyObservable = new BABYLON.Observable();
  59506. /**
  59507. * An event triggered before rendering the postprocess
  59508. * @type {BABYLON.Observable}
  59509. */
  59510. this.onBeforeRenderObservable = new BABYLON.Observable();
  59511. /**
  59512. * An event triggered after rendering the postprocess
  59513. * @type {BABYLON.Observable}
  59514. */
  59515. this.onAfterRenderObservable = new BABYLON.Observable();
  59516. if (camera != null) {
  59517. this._camera = camera;
  59518. this._scene = camera.getScene();
  59519. camera.attachPostProcess(this);
  59520. this._engine = this._scene.getEngine();
  59521. this._scene.postProcesses.push(this);
  59522. }
  59523. else if (engine) {
  59524. this._engine = engine;
  59525. this._engine.postProcesses.push(this);
  59526. }
  59527. this._options = options;
  59528. this.renderTargetSamplingMode = samplingMode ? samplingMode : BABYLON.Texture.NEAREST_SAMPLINGMODE;
  59529. this._reusable = reusable || false;
  59530. this._textureType = textureType;
  59531. this._samplers = samplers || [];
  59532. this._samplers.push("textureSampler");
  59533. this._fragmentUrl = fragmentUrl;
  59534. this._vertexUrl = vertexUrl;
  59535. this._parameters = parameters || [];
  59536. this._parameters.push("scale");
  59537. this._indexParameters = indexParameters;
  59538. if (!blockCompilation) {
  59539. this.updateEffect(defines);
  59540. }
  59541. }
  59542. Object.defineProperty(PostProcess.prototype, "onActivate", {
  59543. /**
  59544. * A function that is added to the onActivateObservable
  59545. */
  59546. set: function (callback) {
  59547. if (this._onActivateObserver) {
  59548. this.onActivateObservable.remove(this._onActivateObserver);
  59549. }
  59550. if (callback) {
  59551. this._onActivateObserver = this.onActivateObservable.add(callback);
  59552. }
  59553. },
  59554. enumerable: true,
  59555. configurable: true
  59556. });
  59557. Object.defineProperty(PostProcess.prototype, "onSizeChanged", {
  59558. /**
  59559. * A function that is added to the onSizeChangedObservable
  59560. */
  59561. set: function (callback) {
  59562. if (this._onSizeChangedObserver) {
  59563. this.onSizeChangedObservable.remove(this._onSizeChangedObserver);
  59564. }
  59565. this._onSizeChangedObserver = this.onSizeChangedObservable.add(callback);
  59566. },
  59567. enumerable: true,
  59568. configurable: true
  59569. });
  59570. Object.defineProperty(PostProcess.prototype, "onApply", {
  59571. /**
  59572. * A function that is added to the onApplyObservable
  59573. */
  59574. set: function (callback) {
  59575. if (this._onApplyObserver) {
  59576. this.onApplyObservable.remove(this._onApplyObserver);
  59577. }
  59578. this._onApplyObserver = this.onApplyObservable.add(callback);
  59579. },
  59580. enumerable: true,
  59581. configurable: true
  59582. });
  59583. Object.defineProperty(PostProcess.prototype, "onBeforeRender", {
  59584. /**
  59585. * A function that is added to the onBeforeRenderObservable
  59586. */
  59587. set: function (callback) {
  59588. if (this._onBeforeRenderObserver) {
  59589. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  59590. }
  59591. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  59592. },
  59593. enumerable: true,
  59594. configurable: true
  59595. });
  59596. Object.defineProperty(PostProcess.prototype, "onAfterRender", {
  59597. /**
  59598. * A function that is added to the onAfterRenderObservable
  59599. */
  59600. set: function (callback) {
  59601. if (this._onAfterRenderObserver) {
  59602. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  59603. }
  59604. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  59605. },
  59606. enumerable: true,
  59607. configurable: true
  59608. });
  59609. Object.defineProperty(PostProcess.prototype, "inputTexture", {
  59610. /**
  59611. * 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
  59612. * render it's output into this texture and this texture will be used as textureSampler in the fragment shader of this post process.
  59613. */
  59614. get: function () {
  59615. return this._textures.data[this._currentRenderTextureInd];
  59616. },
  59617. set: function (value) {
  59618. this._forcedOutputTexture = value;
  59619. },
  59620. enumerable: true,
  59621. configurable: true
  59622. });
  59623. /**
  59624. * Gets the camera which post process is applied to.
  59625. * @returns The camera the post process is applied to.
  59626. */
  59627. PostProcess.prototype.getCamera = function () {
  59628. return this._camera;
  59629. };
  59630. Object.defineProperty(PostProcess.prototype, "texelSize", {
  59631. /**
  59632. * Gets the texel size of the postprocess.
  59633. * See https://en.wikipedia.org/wiki/Texel_(graphics)
  59634. */
  59635. get: function () {
  59636. if (this._shareOutputWithPostProcess) {
  59637. return this._shareOutputWithPostProcess.texelSize;
  59638. }
  59639. if (this._forcedOutputTexture) {
  59640. this._texelSize.copyFromFloats(1.0 / this._forcedOutputTexture.width, 1.0 / this._forcedOutputTexture.height);
  59641. }
  59642. return this._texelSize;
  59643. },
  59644. enumerable: true,
  59645. configurable: true
  59646. });
  59647. /**
  59648. * Gets the engine which this post process belongs to.
  59649. * @returns The engine the post process was enabled with.
  59650. */
  59651. PostProcess.prototype.getEngine = function () {
  59652. return this._engine;
  59653. };
  59654. /**
  59655. * The effect that is created when initializing the post process.
  59656. * @returns The created effect corrisponding the the postprocess.
  59657. */
  59658. PostProcess.prototype.getEffect = function () {
  59659. return this._effect;
  59660. };
  59661. /**
  59662. * To avoid multiple redundant textures for multiple post process, the output the output texture for this post process can be shared with another.
  59663. * @param postProcess The post process to share the output with.
  59664. * @returns This post process.
  59665. */
  59666. PostProcess.prototype.shareOutputWith = function (postProcess) {
  59667. this._disposeTextures();
  59668. this._shareOutputWithPostProcess = postProcess;
  59669. return this;
  59670. };
  59671. /**
  59672. * Reverses the effect of calling shareOutputWith and returns the post process back to its original state.
  59673. * This should be called if the post process that shares output with this post process is disabled/disposed.
  59674. */
  59675. PostProcess.prototype.useOwnOutput = function () {
  59676. if (this._textures.length == 0) {
  59677. this._textures = new BABYLON.SmartArray(2);
  59678. }
  59679. this._shareOutputWithPostProcess = null;
  59680. };
  59681. /**
  59682. * Updates the effect with the current post process compile time values and recompiles the shader.
  59683. * @param defines Define statements that should be added at the beginning of the shader. (default: null)
  59684. * @param uniforms Set of uniform variables that will be passed to the shader. (default: null)
  59685. * @param samplers Set of Texture2D variables that will be passed to the shader. (default: null)
  59686. * @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
  59687. * @param onCompiled Called when the shader has been compiled.
  59688. * @param onError Called if there is an error when compiling a shader.
  59689. */
  59690. PostProcess.prototype.updateEffect = function (defines, uniforms, samplers, indexParameters, onCompiled, onError) {
  59691. if (defines === void 0) { defines = null; }
  59692. if (uniforms === void 0) { uniforms = null; }
  59693. if (samplers === void 0) { samplers = null; }
  59694. 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);
  59695. };
  59696. /**
  59697. * The post process is reusable if it can be used multiple times within one frame.
  59698. * @returns If the post process is reusable
  59699. */
  59700. PostProcess.prototype.isReusable = function () {
  59701. return this._reusable;
  59702. };
  59703. /** invalidate frameBuffer to hint the postprocess to create a depth buffer */
  59704. PostProcess.prototype.markTextureDirty = function () {
  59705. this.width = -1;
  59706. };
  59707. /**
  59708. * Activates the post process by intializing the textures to be used when executed. Notifies onActivateObservable.
  59709. * 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.
  59710. * @param camera The camera that will be used in the post process. This camera will be used when calling onActivateObservable.
  59711. * @param sourceTexture The source texture to be inspected to get the width and height if not specified in the post process constructor. (default: null)
  59712. * @param forceDepthStencil If true, a depth and stencil buffer will be generated. (default: false)
  59713. */
  59714. PostProcess.prototype.activate = function (camera, sourceTexture, forceDepthStencil) {
  59715. var _this = this;
  59716. if (sourceTexture === void 0) { sourceTexture = null; }
  59717. camera = camera || this._camera;
  59718. var scene = camera.getScene();
  59719. var engine = scene.getEngine();
  59720. var maxSize = engine.getCaps().maxTextureSize;
  59721. var requiredWidth = ((sourceTexture ? sourceTexture.width : this._engine.getRenderWidth(true)) * this._options) | 0;
  59722. var requiredHeight = ((sourceTexture ? sourceTexture.height : this._engine.getRenderHeight(true)) * this._options) | 0;
  59723. // 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
  59724. var webVRCamera = camera.parent;
  59725. if (webVRCamera && (webVRCamera.leftCamera == camera || webVRCamera.rightCamera == camera)) {
  59726. requiredWidth /= 2;
  59727. }
  59728. var desiredWidth = (this._options.width || requiredWidth);
  59729. var desiredHeight = this._options.height || requiredHeight;
  59730. if (!this._shareOutputWithPostProcess && !this._forcedOutputTexture) {
  59731. if (this.adaptScaleToCurrentViewport) {
  59732. var currentViewport = engine.currentViewport;
  59733. if (currentViewport) {
  59734. desiredWidth *= currentViewport.width;
  59735. desiredHeight *= currentViewport.height;
  59736. }
  59737. }
  59738. if (this.renderTargetSamplingMode === BABYLON.Texture.TRILINEAR_SAMPLINGMODE || this.alwaysForcePOT) {
  59739. if (!this._options.width) {
  59740. desiredWidth = engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(desiredWidth, maxSize, this.scaleMode) : desiredWidth;
  59741. }
  59742. if (!this._options.height) {
  59743. desiredHeight = engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(desiredHeight, maxSize, this.scaleMode) : desiredHeight;
  59744. }
  59745. }
  59746. if (this.width !== desiredWidth || this.height !== desiredHeight) {
  59747. if (this._textures.length > 0) {
  59748. for (var i = 0; i < this._textures.length; i++) {
  59749. this._engine._releaseTexture(this._textures.data[i]);
  59750. }
  59751. this._textures.reset();
  59752. }
  59753. this.width = desiredWidth;
  59754. this.height = desiredHeight;
  59755. var textureSize = { width: this.width, height: this.height };
  59756. var textureOptions = {
  59757. generateMipMaps: false,
  59758. generateDepthBuffer: forceDepthStencil || camera._postProcesses.indexOf(this) === 0,
  59759. generateStencilBuffer: (forceDepthStencil || camera._postProcesses.indexOf(this) === 0) && this._engine.isStencilEnable,
  59760. samplingMode: this.renderTargetSamplingMode,
  59761. type: this._textureType
  59762. };
  59763. this._textures.push(this._engine.createRenderTargetTexture(textureSize, textureOptions));
  59764. if (this._reusable) {
  59765. this._textures.push(this._engine.createRenderTargetTexture(textureSize, textureOptions));
  59766. }
  59767. this._texelSize.copyFromFloats(1.0 / this.width, 1.0 / this.height);
  59768. this.onSizeChangedObservable.notifyObservers(this);
  59769. }
  59770. this._textures.forEach(function (texture) {
  59771. if (texture.samples !== _this.samples) {
  59772. _this._engine.updateRenderTargetTextureSampleCount(texture, _this.samples);
  59773. }
  59774. });
  59775. }
  59776. var target;
  59777. if (this._shareOutputWithPostProcess) {
  59778. target = this._shareOutputWithPostProcess.inputTexture;
  59779. }
  59780. else if (this._forcedOutputTexture) {
  59781. target = this._forcedOutputTexture;
  59782. this.width = this._forcedOutputTexture.width;
  59783. this.height = this._forcedOutputTexture.height;
  59784. }
  59785. else {
  59786. target = this.inputTexture;
  59787. }
  59788. // Bind the input of this post process to be used as the output of the previous post process.
  59789. if (this.enablePixelPerfectMode) {
  59790. this._scaleRatio.copyFromFloats(requiredWidth / desiredWidth, requiredHeight / desiredHeight);
  59791. this._engine.bindFramebuffer(target, 0, requiredWidth, requiredHeight, true);
  59792. }
  59793. else {
  59794. this._scaleRatio.copyFromFloats(1, 1);
  59795. this._engine.bindFramebuffer(target, 0, undefined, undefined, true);
  59796. }
  59797. this.onActivateObservable.notifyObservers(camera);
  59798. // Clear
  59799. if (this.autoClear && this.alphaMode === BABYLON.Engine.ALPHA_DISABLE) {
  59800. this._engine.clear(this.clearColor ? this.clearColor : scene.clearColor, true, true, true);
  59801. }
  59802. if (this._reusable) {
  59803. this._currentRenderTextureInd = (this._currentRenderTextureInd + 1) % 2;
  59804. }
  59805. };
  59806. Object.defineProperty(PostProcess.prototype, "isSupported", {
  59807. /**
  59808. * If the post process is supported.
  59809. */
  59810. get: function () {
  59811. return this._effect.isSupported;
  59812. },
  59813. enumerable: true,
  59814. configurable: true
  59815. });
  59816. Object.defineProperty(PostProcess.prototype, "aspectRatio", {
  59817. /**
  59818. * The aspect ratio of the output texture.
  59819. */
  59820. get: function () {
  59821. if (this._shareOutputWithPostProcess) {
  59822. return this._shareOutputWithPostProcess.aspectRatio;
  59823. }
  59824. if (this._forcedOutputTexture) {
  59825. return this._forcedOutputTexture.width / this._forcedOutputTexture.height;
  59826. }
  59827. return this.width / this.height;
  59828. },
  59829. enumerable: true,
  59830. configurable: true
  59831. });
  59832. /**
  59833. * Get a value indicating if the post-process is ready to be used
  59834. * @returns true if the post-process is ready (shader is compiled)
  59835. */
  59836. PostProcess.prototype.isReady = function () {
  59837. return this._effect && this._effect.isReady();
  59838. };
  59839. /**
  59840. * Binds all textures and uniforms to the shader, this will be run on every pass.
  59841. * @returns the effect corrisponding to this post process. Null if not compiled or not ready.
  59842. */
  59843. PostProcess.prototype.apply = function () {
  59844. // Check
  59845. if (!this._effect || !this._effect.isReady())
  59846. return null;
  59847. // States
  59848. this._engine.enableEffect(this._effect);
  59849. this._engine.setState(false);
  59850. this._engine.setDepthBuffer(false);
  59851. this._engine.setDepthWrite(false);
  59852. // Alpha
  59853. this._engine.setAlphaMode(this.alphaMode);
  59854. if (this.alphaConstants) {
  59855. this.getEngine().setAlphaConstants(this.alphaConstants.r, this.alphaConstants.g, this.alphaConstants.b, this.alphaConstants.a);
  59856. }
  59857. // Bind the output texture of the preivous post process as the input to this post process.
  59858. var source;
  59859. if (this._shareOutputWithPostProcess) {
  59860. source = this._shareOutputWithPostProcess.inputTexture;
  59861. }
  59862. else if (this._forcedOutputTexture) {
  59863. source = this._forcedOutputTexture;
  59864. }
  59865. else {
  59866. source = this.inputTexture;
  59867. }
  59868. this._effect._bindTexture("textureSampler", source);
  59869. // Parameters
  59870. this._effect.setVector2("scale", this._scaleRatio);
  59871. this.onApplyObservable.notifyObservers(this._effect);
  59872. return this._effect;
  59873. };
  59874. PostProcess.prototype._disposeTextures = function () {
  59875. if (this._shareOutputWithPostProcess || this._forcedOutputTexture) {
  59876. return;
  59877. }
  59878. if (this._textures.length > 0) {
  59879. for (var i = 0; i < this._textures.length; i++) {
  59880. this._engine._releaseTexture(this._textures.data[i]);
  59881. }
  59882. }
  59883. this._textures.dispose();
  59884. };
  59885. /**
  59886. * Disposes the post process.
  59887. * @param camera The camera to dispose the post process on.
  59888. */
  59889. PostProcess.prototype.dispose = function (camera) {
  59890. camera = camera || this._camera;
  59891. this._disposeTextures();
  59892. if (this._scene) {
  59893. var index_1 = this._scene.postProcesses.indexOf(this);
  59894. if (index_1 !== -1) {
  59895. this._scene.postProcesses.splice(index_1, 1);
  59896. }
  59897. }
  59898. else {
  59899. var index_2 = this._engine.postProcesses.indexOf(this);
  59900. if (index_2 !== -1) {
  59901. this._engine.postProcesses.splice(index_2, 1);
  59902. }
  59903. }
  59904. if (!camera) {
  59905. return;
  59906. }
  59907. camera.detachPostProcess(this);
  59908. var index = camera._postProcesses.indexOf(this);
  59909. if (index === 0 && camera._postProcesses.length > 0) {
  59910. this._camera._postProcesses[0].markTextureDirty();
  59911. }
  59912. this.onActivateObservable.clear();
  59913. this.onAfterRenderObservable.clear();
  59914. this.onApplyObservable.clear();
  59915. this.onBeforeRenderObservable.clear();
  59916. this.onSizeChangedObservable.clear();
  59917. };
  59918. return PostProcess;
  59919. }());
  59920. BABYLON.PostProcess = PostProcess;
  59921. })(BABYLON || (BABYLON = {}));
  59922. //# sourceMappingURL=babylon.postProcess.js.map
  59923. var BABYLON;
  59924. (function (BABYLON) {
  59925. var PassPostProcess = /** @class */ (function (_super) {
  59926. __extends(PassPostProcess, _super);
  59927. function PassPostProcess(name, options, camera, samplingMode, engine, reusable, textureType) {
  59928. if (camera === void 0) { camera = null; }
  59929. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  59930. return _super.call(this, name, "pass", null, null, options, camera, samplingMode, engine, reusable, undefined, textureType) || this;
  59931. }
  59932. return PassPostProcess;
  59933. }(BABYLON.PostProcess));
  59934. BABYLON.PassPostProcess = PassPostProcess;
  59935. })(BABYLON || (BABYLON = {}));
  59936. //# sourceMappingURL=babylon.passPostProcess.js.map
  59937. var __assign = (this && this.__assign) || Object.assign || function(t) {
  59938. for (var s, i = 1, n = arguments.length; i < n; i++) {
  59939. s = arguments[i];
  59940. for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
  59941. t[p] = s[p];
  59942. }
  59943. return t;
  59944. };
  59945. var BABYLON;
  59946. (function (BABYLON) {
  59947. /**
  59948. * Default implementation of @see IShadowGenerator.
  59949. * This is the main object responsible of generating shadows in the framework.
  59950. * Documentation: https://doc.babylonjs.com/babylon101/shadows
  59951. */
  59952. var ShadowGenerator = /** @class */ (function () {
  59953. /**
  59954. * Creates a ShadowGenerator object.
  59955. * A ShadowGenerator is the required tool to use the shadows.
  59956. * Each light casting shadows needs to use its own ShadowGenerator.
  59957. * Documentation : http://doc.babylonjs.com/tutorials/shadows
  59958. * @param mapSize The size of the texture what stores the shadows. Example : 1024.
  59959. * @param light The light object generating the shadows.
  59960. * @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.
  59961. */
  59962. function ShadowGenerator(mapSize, light, useFullFloatFirst) {
  59963. this._bias = 0.00005;
  59964. this._blurBoxOffset = 1;
  59965. this._blurScale = 2;
  59966. this._blurKernel = 1;
  59967. this._useKernelBlur = false;
  59968. this._filter = ShadowGenerator.FILTER_NONE;
  59969. this._darkness = 0;
  59970. this._transparencyShadow = false;
  59971. /**
  59972. * Controls the extent to which the shadows fade out at the edge of the frustum
  59973. * Used only by directionals and spots
  59974. */
  59975. this.frustumEdgeFalloff = 0;
  59976. /**
  59977. * If true the shadow map is generated by rendering the back face of the mesh instead of the front face.
  59978. * This can help with self-shadowing as the geometry making up the back of objects is slightly offset.
  59979. * It might on the other hand introduce peter panning.
  59980. */
  59981. this.forceBackFacesOnly = false;
  59982. this._lightDirection = BABYLON.Vector3.Zero();
  59983. this._viewMatrix = BABYLON.Matrix.Zero();
  59984. this._projectionMatrix = BABYLON.Matrix.Zero();
  59985. this._transformMatrix = BABYLON.Matrix.Zero();
  59986. this._cachedPosition = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  59987. this._cachedDirection = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  59988. this._currentFaceIndex = 0;
  59989. this._currentFaceIndexCache = 0;
  59990. this._defaultTextureMatrix = BABYLON.Matrix.Identity();
  59991. this._mapSize = mapSize;
  59992. this._light = light;
  59993. this._scene = light.getScene();
  59994. light._shadowGenerator = this;
  59995. // Texture type fallback from float to int if not supported.
  59996. var caps = this._scene.getEngine().getCaps();
  59997. if (!useFullFloatFirst) {
  59998. if (caps.textureHalfFloatRender && caps.textureHalfFloatLinearFiltering) {
  59999. this._textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  60000. }
  60001. else if (caps.textureFloatRender && caps.textureFloatLinearFiltering) {
  60002. this._textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  60003. }
  60004. else {
  60005. this._textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  60006. }
  60007. }
  60008. else {
  60009. if (caps.textureFloatRender && caps.textureFloatLinearFiltering) {
  60010. this._textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  60011. }
  60012. else if (caps.textureHalfFloatRender && caps.textureHalfFloatLinearFiltering) {
  60013. this._textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  60014. }
  60015. else {
  60016. this._textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  60017. }
  60018. }
  60019. this._initializeGenerator();
  60020. }
  60021. Object.defineProperty(ShadowGenerator, "FILTER_NONE", {
  60022. /**
  60023. * Shadow generator mode None: no filtering applied.
  60024. */
  60025. get: function () {
  60026. return ShadowGenerator._FILTER_NONE;
  60027. },
  60028. enumerable: true,
  60029. configurable: true
  60030. });
  60031. Object.defineProperty(ShadowGenerator, "FILTER_POISSONSAMPLING", {
  60032. /**
  60033. * Shadow generator mode Poisson Sampling: Percentage Closer Filtering.
  60034. * (Multiple Tap around evenly distributed around the pixel are used to evaluate the shadow strength)
  60035. */
  60036. get: function () {
  60037. return ShadowGenerator._FILTER_POISSONSAMPLING;
  60038. },
  60039. enumerable: true,
  60040. configurable: true
  60041. });
  60042. Object.defineProperty(ShadowGenerator, "FILTER_EXPONENTIALSHADOWMAP", {
  60043. /**
  60044. * Shadow generator mode ESM: Exponential Shadow Mapping.
  60045. * (http://developer.download.nvidia.com/presentations/2008/GDC/GDC08_SoftShadowMapping.pdf)
  60046. */
  60047. get: function () {
  60048. return ShadowGenerator._FILTER_EXPONENTIALSHADOWMAP;
  60049. },
  60050. enumerable: true,
  60051. configurable: true
  60052. });
  60053. Object.defineProperty(ShadowGenerator, "FILTER_BLUREXPONENTIALSHADOWMAP", {
  60054. /**
  60055. * Shadow generator mode ESM: Blurred Exponential Shadow Mapping.
  60056. * (http://developer.download.nvidia.com/presentations/2008/GDC/GDC08_SoftShadowMapping.pdf)
  60057. */
  60058. get: function () {
  60059. return ShadowGenerator._FILTER_BLUREXPONENTIALSHADOWMAP;
  60060. },
  60061. enumerable: true,
  60062. configurable: true
  60063. });
  60064. Object.defineProperty(ShadowGenerator, "FILTER_CLOSEEXPONENTIALSHADOWMAP", {
  60065. /**
  60066. * Shadow generator mode ESM: Exponential Shadow Mapping using the inverse of the exponential preventing
  60067. * edge artifacts on steep falloff.
  60068. * (http://developer.download.nvidia.com/presentations/2008/GDC/GDC08_SoftShadowMapping.pdf)
  60069. */
  60070. get: function () {
  60071. return ShadowGenerator._FILTER_CLOSEEXPONENTIALSHADOWMAP;
  60072. },
  60073. enumerable: true,
  60074. configurable: true
  60075. });
  60076. Object.defineProperty(ShadowGenerator, "FILTER_BLURCLOSEEXPONENTIALSHADOWMAP", {
  60077. /**
  60078. * Shadow generator mode ESM: Blurred Exponential Shadow Mapping using the inverse of the exponential preventing
  60079. * edge artifacts on steep falloff.
  60080. * (http://developer.download.nvidia.com/presentations/2008/GDC/GDC08_SoftShadowMapping.pdf)
  60081. */
  60082. get: function () {
  60083. return ShadowGenerator._FILTER_BLURCLOSEEXPONENTIALSHADOWMAP;
  60084. },
  60085. enumerable: true,
  60086. configurable: true
  60087. });
  60088. Object.defineProperty(ShadowGenerator.prototype, "bias", {
  60089. /**
  60090. * Gets the bias: offset applied on the depth preventing acnea.
  60091. */
  60092. get: function () {
  60093. return this._bias;
  60094. },
  60095. /**
  60096. * Sets the bias: offset applied on the depth preventing acnea.
  60097. */
  60098. set: function (bias) {
  60099. this._bias = bias;
  60100. },
  60101. enumerable: true,
  60102. configurable: true
  60103. });
  60104. Object.defineProperty(ShadowGenerator.prototype, "blurBoxOffset", {
  60105. /**
  60106. * Gets the blur box offset: offset applied during the blur pass.
  60107. * Only usefull if useKernelBlur = false
  60108. */
  60109. get: function () {
  60110. return this._blurBoxOffset;
  60111. },
  60112. /**
  60113. * Sets the blur box offset: offset applied during the blur pass.
  60114. * Only usefull if useKernelBlur = false
  60115. */
  60116. set: function (value) {
  60117. if (this._blurBoxOffset === value) {
  60118. return;
  60119. }
  60120. this._blurBoxOffset = value;
  60121. this._disposeBlurPostProcesses();
  60122. },
  60123. enumerable: true,
  60124. configurable: true
  60125. });
  60126. Object.defineProperty(ShadowGenerator.prototype, "blurScale", {
  60127. /**
  60128. * Gets the blur scale: scale of the blurred texture compared to the main shadow map.
  60129. * 2 means half of the size.
  60130. */
  60131. get: function () {
  60132. return this._blurScale;
  60133. },
  60134. /**
  60135. * Sets the blur scale: scale of the blurred texture compared to the main shadow map.
  60136. * 2 means half of the size.
  60137. */
  60138. set: function (value) {
  60139. if (this._blurScale === value) {
  60140. return;
  60141. }
  60142. this._blurScale = value;
  60143. this._disposeBlurPostProcesses();
  60144. },
  60145. enumerable: true,
  60146. configurable: true
  60147. });
  60148. Object.defineProperty(ShadowGenerator.prototype, "blurKernel", {
  60149. /**
  60150. * Gets the blur kernel: kernel size of the blur pass.
  60151. * Only usefull if useKernelBlur = true
  60152. */
  60153. get: function () {
  60154. return this._blurKernel;
  60155. },
  60156. /**
  60157. * Sets the blur kernel: kernel size of the blur pass.
  60158. * Only usefull if useKernelBlur = true
  60159. */
  60160. set: function (value) {
  60161. if (this._blurKernel === value) {
  60162. return;
  60163. }
  60164. this._blurKernel = value;
  60165. this._disposeBlurPostProcesses();
  60166. },
  60167. enumerable: true,
  60168. configurable: true
  60169. });
  60170. Object.defineProperty(ShadowGenerator.prototype, "useKernelBlur", {
  60171. /**
  60172. * Gets whether the blur pass is a kernel blur (if true) or box blur.
  60173. * Only usefull in filtered mode (useBlurExponentialShadowMap...)
  60174. */
  60175. get: function () {
  60176. return this._useKernelBlur;
  60177. },
  60178. /**
  60179. * Sets whether the blur pass is a kernel blur (if true) or box blur.
  60180. * Only usefull in filtered mode (useBlurExponentialShadowMap...)
  60181. */
  60182. set: function (value) {
  60183. if (this._useKernelBlur === value) {
  60184. return;
  60185. }
  60186. this._useKernelBlur = value;
  60187. this._disposeBlurPostProcesses();
  60188. },
  60189. enumerable: true,
  60190. configurable: true
  60191. });
  60192. Object.defineProperty(ShadowGenerator.prototype, "depthScale", {
  60193. /**
  60194. * Gets the depth scale used in ESM mode.
  60195. */
  60196. get: function () {
  60197. return this._depthScale !== undefined ? this._depthScale : this._light.getDepthScale();
  60198. },
  60199. /**
  60200. * Sets the depth scale used in ESM mode.
  60201. * This can override the scale stored on the light.
  60202. */
  60203. set: function (value) {
  60204. this._depthScale = value;
  60205. },
  60206. enumerable: true,
  60207. configurable: true
  60208. });
  60209. Object.defineProperty(ShadowGenerator.prototype, "filter", {
  60210. /**
  60211. * Gets the current mode of the shadow generator (normal, PCF, ESM...).
  60212. * The returned value is a number equal to one of the available mode defined in ShadowMap.FILTER_x like _FILTER_NONE
  60213. */
  60214. get: function () {
  60215. return this._filter;
  60216. },
  60217. /**
  60218. * Sets the current mode of the shadow generator (normal, PCF, ESM...).
  60219. * The returned value is a number equal to one of the available mode defined in ShadowMap.FILTER_x like _FILTER_NONE
  60220. */
  60221. set: function (value) {
  60222. // Blurring the cubemap is going to be too expensive. Reverting to unblurred version
  60223. if (this._light.needCube()) {
  60224. if (value === ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP) {
  60225. this.useExponentialShadowMap = true;
  60226. return;
  60227. }
  60228. else if (value === ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP) {
  60229. this.useCloseExponentialShadowMap = true;
  60230. return;
  60231. }
  60232. }
  60233. if (this._filter === value) {
  60234. return;
  60235. }
  60236. this._filter = value;
  60237. this._disposeBlurPostProcesses();
  60238. this._applyFilterValues();
  60239. this._light._markMeshesAsLightDirty();
  60240. },
  60241. enumerable: true,
  60242. configurable: true
  60243. });
  60244. Object.defineProperty(ShadowGenerator.prototype, "usePoissonSampling", {
  60245. /**
  60246. * Gets if the current filter is set to Poisson Sampling aka PCF.
  60247. */
  60248. get: function () {
  60249. return this.filter === ShadowGenerator.FILTER_POISSONSAMPLING;
  60250. },
  60251. /**
  60252. * Sets the current filter to Poisson Sampling aka PCF.
  60253. */
  60254. set: function (value) {
  60255. if (!value && this.filter !== ShadowGenerator.FILTER_POISSONSAMPLING) {
  60256. return;
  60257. }
  60258. this.filter = (value ? ShadowGenerator.FILTER_POISSONSAMPLING : ShadowGenerator.FILTER_NONE);
  60259. },
  60260. enumerable: true,
  60261. configurable: true
  60262. });
  60263. Object.defineProperty(ShadowGenerator.prototype, "useVarianceShadowMap", {
  60264. /**
  60265. * Gets if the current filter is set to VSM.
  60266. * DEPRECATED. Should use useExponentialShadowMap instead.
  60267. */
  60268. get: function () {
  60269. BABYLON.Tools.Warn("VSM are now replaced by ESM. Please use useExponentialShadowMap instead.");
  60270. return this.useExponentialShadowMap;
  60271. },
  60272. /**
  60273. * Sets the current filter is to VSM.
  60274. * DEPRECATED. Should use useExponentialShadowMap instead.
  60275. */
  60276. set: function (value) {
  60277. BABYLON.Tools.Warn("VSM are now replaced by ESM. Please use useExponentialShadowMap instead.");
  60278. this.useExponentialShadowMap = value;
  60279. },
  60280. enumerable: true,
  60281. configurable: true
  60282. });
  60283. Object.defineProperty(ShadowGenerator.prototype, "useBlurVarianceShadowMap", {
  60284. /**
  60285. * Gets if the current filter is set to blurred VSM.
  60286. * DEPRECATED. Should use useBlurExponentialShadowMap instead.
  60287. */
  60288. get: function () {
  60289. BABYLON.Tools.Warn("VSM are now replaced by ESM. Please use useBlurExponentialShadowMap instead.");
  60290. return this.useBlurExponentialShadowMap;
  60291. },
  60292. /**
  60293. * Sets the current filter is to blurred VSM.
  60294. * DEPRECATED. Should use useBlurExponentialShadowMap instead.
  60295. */
  60296. set: function (value) {
  60297. BABYLON.Tools.Warn("VSM are now replaced by ESM. Please use useBlurExponentialShadowMap instead.");
  60298. this.useBlurExponentialShadowMap = value;
  60299. },
  60300. enumerable: true,
  60301. configurable: true
  60302. });
  60303. Object.defineProperty(ShadowGenerator.prototype, "useExponentialShadowMap", {
  60304. /**
  60305. * Gets if the current filter is set to ESM.
  60306. */
  60307. get: function () {
  60308. return this.filter === ShadowGenerator.FILTER_EXPONENTIALSHADOWMAP;
  60309. },
  60310. /**
  60311. * Sets the current filter is to ESM.
  60312. */
  60313. set: function (value) {
  60314. if (!value && this.filter !== ShadowGenerator.FILTER_EXPONENTIALSHADOWMAP) {
  60315. return;
  60316. }
  60317. this.filter = (value ? ShadowGenerator.FILTER_EXPONENTIALSHADOWMAP : ShadowGenerator.FILTER_NONE);
  60318. },
  60319. enumerable: true,
  60320. configurable: true
  60321. });
  60322. Object.defineProperty(ShadowGenerator.prototype, "useBlurExponentialShadowMap", {
  60323. /**
  60324. * Gets if the current filter is set to filtered ESM.
  60325. */
  60326. get: function () {
  60327. return this.filter === ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP;
  60328. },
  60329. /**
  60330. * Gets if the current filter is set to filtered ESM.
  60331. */
  60332. set: function (value) {
  60333. if (!value && this.filter !== ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP) {
  60334. return;
  60335. }
  60336. this.filter = (value ? ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP : ShadowGenerator.FILTER_NONE);
  60337. },
  60338. enumerable: true,
  60339. configurable: true
  60340. });
  60341. Object.defineProperty(ShadowGenerator.prototype, "useCloseExponentialShadowMap", {
  60342. /**
  60343. * Gets if the current filter is set to "close ESM" (using the inverse of the
  60344. * exponential to prevent steep falloff artifacts).
  60345. */
  60346. get: function () {
  60347. return this.filter === ShadowGenerator.FILTER_CLOSEEXPONENTIALSHADOWMAP;
  60348. },
  60349. /**
  60350. * Sets the current filter to "close ESM" (using the inverse of the
  60351. * exponential to prevent steep falloff artifacts).
  60352. */
  60353. set: function (value) {
  60354. if (!value && this.filter !== ShadowGenerator.FILTER_CLOSEEXPONENTIALSHADOWMAP) {
  60355. return;
  60356. }
  60357. this.filter = (value ? ShadowGenerator.FILTER_CLOSEEXPONENTIALSHADOWMAP : ShadowGenerator.FILTER_NONE);
  60358. },
  60359. enumerable: true,
  60360. configurable: true
  60361. });
  60362. Object.defineProperty(ShadowGenerator.prototype, "useBlurCloseExponentialShadowMap", {
  60363. /**
  60364. * Gets if the current filter is set to filtered "close ESM" (using the inverse of the
  60365. * exponential to prevent steep falloff artifacts).
  60366. */
  60367. get: function () {
  60368. return this.filter === ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP;
  60369. },
  60370. /**
  60371. * Sets the current filter to fileterd "close ESM" (using the inverse of the
  60372. * exponential to prevent steep falloff artifacts).
  60373. */
  60374. set: function (value) {
  60375. if (!value && this.filter !== ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP) {
  60376. return;
  60377. }
  60378. this.filter = (value ? ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP : ShadowGenerator.FILTER_NONE);
  60379. },
  60380. enumerable: true,
  60381. configurable: true
  60382. });
  60383. /**
  60384. * Returns the darkness value (float). This can only decrease the actual darkness of a shadow.
  60385. * 0 means strongest and 1 would means no shadow.
  60386. * @returns the darkness.
  60387. */
  60388. ShadowGenerator.prototype.getDarkness = function () {
  60389. return this._darkness;
  60390. };
  60391. /**
  60392. * Sets the darkness value (float). This can only decrease the actual darkness of a shadow.
  60393. * @param darkness The darkness value 0 means strongest and 1 would means no shadow.
  60394. * @returns the shadow generator allowing fluent coding.
  60395. */
  60396. ShadowGenerator.prototype.setDarkness = function (darkness) {
  60397. if (darkness >= 1.0)
  60398. this._darkness = 1.0;
  60399. else if (darkness <= 0.0)
  60400. this._darkness = 0.0;
  60401. else
  60402. this._darkness = darkness;
  60403. return this;
  60404. };
  60405. /**
  60406. * Sets the ability to have transparent shadow (boolean).
  60407. * @param transparent True if transparent else False
  60408. * @returns the shadow generator allowing fluent coding
  60409. */
  60410. ShadowGenerator.prototype.setTransparencyShadow = function (transparent) {
  60411. this._transparencyShadow = transparent;
  60412. return this;
  60413. };
  60414. /**
  60415. * Gets the main RTT containing the shadow map (usually storing depth from the light point of view).
  60416. * @returns The render target texture if present otherwise, null
  60417. */
  60418. ShadowGenerator.prototype.getShadowMap = function () {
  60419. return this._shadowMap;
  60420. };
  60421. /**
  60422. * Gets the RTT used during rendering (can be a blurred version of the shadow map or the shadow map itself).
  60423. * @returns The render target texture if the shadow map is present otherwise, null
  60424. */
  60425. ShadowGenerator.prototype.getShadowMapForRendering = function () {
  60426. if (this._shadowMap2) {
  60427. return this._shadowMap2;
  60428. }
  60429. return this._shadowMap;
  60430. };
  60431. /**
  60432. * Helper function to add a mesh and its descendants to the list of shadow casters.
  60433. * @param mesh Mesh to add
  60434. * @param includeDescendants boolean indicating if the descendants should be added. Default to true
  60435. * @returns the Shadow Generator itself
  60436. */
  60437. ShadowGenerator.prototype.addShadowCaster = function (mesh, includeDescendants) {
  60438. if (includeDescendants === void 0) { includeDescendants = true; }
  60439. if (!this._shadowMap) {
  60440. return this;
  60441. }
  60442. if (!this._shadowMap.renderList) {
  60443. this._shadowMap.renderList = [];
  60444. }
  60445. this._shadowMap.renderList.push(mesh);
  60446. if (includeDescendants) {
  60447. (_a = this._shadowMap.renderList).push.apply(_a, mesh.getChildMeshes());
  60448. }
  60449. return this;
  60450. var _a;
  60451. };
  60452. /**
  60453. * Helper function to remove a mesh and its descendants from the list of shadow casters
  60454. * @param mesh Mesh to remove
  60455. * @param includeDescendants boolean indicating if the descendants should be removed. Default to true
  60456. * @returns the Shadow Generator itself
  60457. */
  60458. ShadowGenerator.prototype.removeShadowCaster = function (mesh, includeDescendants) {
  60459. if (includeDescendants === void 0) { includeDescendants = true; }
  60460. if (!this._shadowMap || !this._shadowMap.renderList) {
  60461. return this;
  60462. }
  60463. var index = this._shadowMap.renderList.indexOf(mesh);
  60464. if (index !== -1) {
  60465. this._shadowMap.renderList.splice(index, 1);
  60466. }
  60467. if (includeDescendants) {
  60468. for (var _i = 0, _a = mesh.getChildren(); _i < _a.length; _i++) {
  60469. var child = _a[_i];
  60470. this.removeShadowCaster(child);
  60471. }
  60472. }
  60473. return this;
  60474. };
  60475. /**
  60476. * Returns the associated light object.
  60477. * @returns the light generating the shadow
  60478. */
  60479. ShadowGenerator.prototype.getLight = function () {
  60480. return this._light;
  60481. };
  60482. ShadowGenerator.prototype._initializeGenerator = function () {
  60483. this._light._markMeshesAsLightDirty();
  60484. this._initializeShadowMap();
  60485. };
  60486. ShadowGenerator.prototype._initializeShadowMap = function () {
  60487. var _this = this;
  60488. // Render target
  60489. this._shadowMap = new BABYLON.RenderTargetTexture(this._light.name + "_shadowMap", this._mapSize, this._scene, false, true, this._textureType, this._light.needCube());
  60490. this._shadowMap.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  60491. this._shadowMap.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  60492. this._shadowMap.anisotropicFilteringLevel = 1;
  60493. this._shadowMap.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  60494. this._shadowMap.renderParticles = false;
  60495. this._shadowMap.ignoreCameraViewport = true;
  60496. // Record Face Index before render.
  60497. this._shadowMap.onBeforeRenderObservable.add(function (faceIndex) {
  60498. _this._currentFaceIndex = faceIndex;
  60499. });
  60500. // Custom render function.
  60501. this._shadowMap.customRenderFunction = this._renderForShadowMap.bind(this);
  60502. // Blur if required afer render.
  60503. this._shadowMap.onAfterUnbindObservable.add(function () {
  60504. if (!_this.useBlurExponentialShadowMap && !_this.useBlurCloseExponentialShadowMap) {
  60505. return;
  60506. }
  60507. var shadowMap = _this.getShadowMapForRendering();
  60508. if (shadowMap) {
  60509. _this._scene.postProcessManager.directRender(_this._blurPostProcesses, shadowMap.getInternalTexture(), true);
  60510. }
  60511. });
  60512. // Clear according to the chosen filter.
  60513. var zero = new BABYLON.Color4(0, 0, 0, 0);
  60514. var one = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  60515. this._shadowMap.onClearObservable.add(function (engine) {
  60516. if (_this.useExponentialShadowMap || _this.useBlurExponentialShadowMap) {
  60517. engine.clear(zero, true, true, true);
  60518. }
  60519. else {
  60520. engine.clear(one, true, true, true);
  60521. }
  60522. });
  60523. };
  60524. ShadowGenerator.prototype._initializeBlurRTTAndPostProcesses = function () {
  60525. var _this = this;
  60526. var engine = this._scene.getEngine();
  60527. var targetSize = this._mapSize / this.blurScale;
  60528. if (!this.useKernelBlur || this.blurScale !== 1.0) {
  60529. this._shadowMap2 = new BABYLON.RenderTargetTexture(this._light.name + "_shadowMap2", targetSize, this._scene, false, true, this._textureType);
  60530. this._shadowMap2.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  60531. this._shadowMap2.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  60532. this._shadowMap2.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  60533. }
  60534. if (this.useKernelBlur) {
  60535. 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);
  60536. this._kernelBlurXPostprocess.width = targetSize;
  60537. this._kernelBlurXPostprocess.height = targetSize;
  60538. this._kernelBlurXPostprocess.onApplyObservable.add(function (effect) {
  60539. effect.setTexture("textureSampler", _this._shadowMap);
  60540. });
  60541. 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);
  60542. this._kernelBlurXPostprocess.autoClear = false;
  60543. this._kernelBlurYPostprocess.autoClear = false;
  60544. if (this._textureType === BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT) {
  60545. this._kernelBlurXPostprocess.packedFloat = true;
  60546. this._kernelBlurYPostprocess.packedFloat = true;
  60547. }
  60548. this._blurPostProcesses = [this._kernelBlurXPostprocess, this._kernelBlurYPostprocess];
  60549. }
  60550. else {
  60551. 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);
  60552. this._boxBlurPostprocess.onApplyObservable.add(function (effect) {
  60553. effect.setFloat2("screenSize", targetSize, targetSize);
  60554. effect.setTexture("textureSampler", _this._shadowMap);
  60555. });
  60556. this._boxBlurPostprocess.autoClear = false;
  60557. this._blurPostProcesses = [this._boxBlurPostprocess];
  60558. }
  60559. };
  60560. ShadowGenerator.prototype._renderForShadowMap = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes) {
  60561. var index;
  60562. var engine = this._scene.getEngine();
  60563. if (depthOnlySubMeshes.length) {
  60564. engine.setColorWrite(false);
  60565. for (index = 0; index < depthOnlySubMeshes.length; index++) {
  60566. this._renderSubMeshForShadowMap(depthOnlySubMeshes.data[index]);
  60567. }
  60568. engine.setColorWrite(true);
  60569. }
  60570. for (index = 0; index < opaqueSubMeshes.length; index++) {
  60571. this._renderSubMeshForShadowMap(opaqueSubMeshes.data[index]);
  60572. }
  60573. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  60574. this._renderSubMeshForShadowMap(alphaTestSubMeshes.data[index]);
  60575. }
  60576. if (this._transparencyShadow) {
  60577. for (index = 0; index < transparentSubMeshes.length; index++) {
  60578. this._renderSubMeshForShadowMap(transparentSubMeshes.data[index]);
  60579. }
  60580. }
  60581. };
  60582. ShadowGenerator.prototype._renderSubMeshForShadowMap = function (subMesh) {
  60583. var _this = this;
  60584. var mesh = subMesh.getRenderingMesh();
  60585. var scene = this._scene;
  60586. var engine = scene.getEngine();
  60587. var material = subMesh.getMaterial();
  60588. if (!material) {
  60589. return;
  60590. }
  60591. // Culling
  60592. engine.setState(material.backFaceCulling);
  60593. // Managing instances
  60594. var batch = mesh._getInstancesRenderList(subMesh._id);
  60595. if (batch.mustReturn) {
  60596. return;
  60597. }
  60598. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  60599. if (this.isReady(subMesh, hardwareInstancedRendering)) {
  60600. engine.enableEffect(this._effect);
  60601. mesh._bind(subMesh, this._effect, BABYLON.Material.TriangleFillMode);
  60602. this._effect.setFloat2("biasAndScale", this.bias, this.depthScale);
  60603. this._effect.setMatrix("viewProjection", this.getTransformMatrix());
  60604. this._effect.setVector3("lightPosition", this.getLight().position);
  60605. if (scene.activeCamera) {
  60606. this._effect.setFloat2("depthValues", this.getLight().getDepthMinZ(scene.activeCamera), this.getLight().getDepthMinZ(scene.activeCamera) + this.getLight().getDepthMaxZ(scene.activeCamera));
  60607. }
  60608. // Alpha test
  60609. if (material && material.needAlphaTesting()) {
  60610. var alphaTexture = material.getAlphaTestTexture();
  60611. if (alphaTexture) {
  60612. this._effect.setTexture("diffuseSampler", alphaTexture);
  60613. this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix() || this._defaultTextureMatrix);
  60614. }
  60615. }
  60616. // Bones
  60617. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  60618. this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices((mesh)));
  60619. }
  60620. if (this.forceBackFacesOnly) {
  60621. engine.setState(true, 0, false, true);
  60622. }
  60623. // Draw
  60624. mesh._processRendering(subMesh, this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effect.setMatrix("world", world); });
  60625. if (this.forceBackFacesOnly) {
  60626. engine.setState(true, 0, false, false);
  60627. }
  60628. }
  60629. else {
  60630. // Need to reset refresh rate of the shadowMap
  60631. if (this._shadowMap) {
  60632. this._shadowMap.resetRefreshCounter();
  60633. }
  60634. }
  60635. };
  60636. ShadowGenerator.prototype._applyFilterValues = function () {
  60637. if (!this._shadowMap) {
  60638. return;
  60639. }
  60640. if (this.filter === ShadowGenerator.FILTER_NONE) {
  60641. this._shadowMap.updateSamplingMode(BABYLON.Texture.NEAREST_SAMPLINGMODE);
  60642. }
  60643. else {
  60644. this._shadowMap.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  60645. }
  60646. };
  60647. /**
  60648. * Forces all the attached effect to compile to enable rendering only once ready vs. lazyly compiling effects.
  60649. * @param onCompiled Callback triggered at the and of the effects compilation
  60650. * @param options Sets of optional options forcing the compilation with different modes
  60651. */
  60652. ShadowGenerator.prototype.forceCompilation = function (onCompiled, options) {
  60653. var _this = this;
  60654. var localOptions = __assign({ useInstances: false }, options);
  60655. var shadowMap = this.getShadowMap();
  60656. if (!shadowMap) {
  60657. if (onCompiled) {
  60658. onCompiled(this);
  60659. }
  60660. return;
  60661. }
  60662. var renderList = shadowMap.renderList;
  60663. if (!renderList) {
  60664. if (onCompiled) {
  60665. onCompiled(this);
  60666. }
  60667. return;
  60668. }
  60669. var subMeshes = new Array();
  60670. for (var _i = 0, renderList_1 = renderList; _i < renderList_1.length; _i++) {
  60671. var mesh = renderList_1[_i];
  60672. subMeshes.push.apply(subMeshes, mesh.subMeshes);
  60673. }
  60674. if (subMeshes.length === 0) {
  60675. if (onCompiled) {
  60676. onCompiled(this);
  60677. }
  60678. return;
  60679. }
  60680. var currentIndex = 0;
  60681. var checkReady = function () {
  60682. if (!_this._scene || !_this._scene.getEngine()) {
  60683. return;
  60684. }
  60685. while (_this.isReady(subMeshes[currentIndex], localOptions.useInstances)) {
  60686. currentIndex++;
  60687. if (currentIndex >= subMeshes.length) {
  60688. if (onCompiled) {
  60689. onCompiled(_this);
  60690. }
  60691. return;
  60692. }
  60693. }
  60694. setTimeout(checkReady, 16);
  60695. };
  60696. checkReady();
  60697. };
  60698. /**
  60699. * Forces all the attached effect to compile to enable rendering only once ready vs. lazyly compiling effects.
  60700. * @param options Sets of optional options forcing the compilation with different modes
  60701. * @returns A promise that resolves when the compilation completes
  60702. */
  60703. ShadowGenerator.prototype.forceCompilationAsync = function (options) {
  60704. var _this = this;
  60705. return new Promise(function (resolve) {
  60706. _this.forceCompilation(function () {
  60707. resolve();
  60708. }, options);
  60709. });
  60710. };
  60711. /**
  60712. * Determine wheter the shadow generator is ready or not (mainly all effects and related post processes needs to be ready).
  60713. * @param subMesh The submesh we want to render in the shadow map
  60714. * @param useInstances Defines wether will draw in the map using instances
  60715. * @returns true if ready otherwise, false
  60716. */
  60717. ShadowGenerator.prototype.isReady = function (subMesh, useInstances) {
  60718. var defines = [];
  60719. if (this._textureType !== BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT) {
  60720. defines.push("#define FLOAT");
  60721. }
  60722. if (this.useExponentialShadowMap || this.useBlurExponentialShadowMap) {
  60723. defines.push("#define ESM");
  60724. }
  60725. var attribs = [BABYLON.VertexBuffer.PositionKind];
  60726. var mesh = subMesh.getMesh();
  60727. var material = subMesh.getMaterial();
  60728. // Alpha test
  60729. if (material && material.needAlphaTesting()) {
  60730. var alphaTexture = material.getAlphaTestTexture();
  60731. if (alphaTexture) {
  60732. defines.push("#define ALPHATEST");
  60733. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  60734. attribs.push(BABYLON.VertexBuffer.UVKind);
  60735. defines.push("#define UV1");
  60736. }
  60737. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  60738. if (alphaTexture.coordinatesIndex === 1) {
  60739. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  60740. defines.push("#define UV2");
  60741. }
  60742. }
  60743. }
  60744. }
  60745. // Bones
  60746. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  60747. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  60748. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  60749. if (mesh.numBoneInfluencers > 4) {
  60750. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  60751. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  60752. }
  60753. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  60754. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  60755. }
  60756. else {
  60757. defines.push("#define NUM_BONE_INFLUENCERS 0");
  60758. }
  60759. // Instances
  60760. if (useInstances) {
  60761. defines.push("#define INSTANCES");
  60762. attribs.push("world0");
  60763. attribs.push("world1");
  60764. attribs.push("world2");
  60765. attribs.push("world3");
  60766. }
  60767. // Get correct effect
  60768. var join = defines.join("\n");
  60769. if (this._cachedDefines !== join) {
  60770. this._cachedDefines = join;
  60771. this._effect = this._scene.getEngine().createEffect("shadowMap", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "lightPosition", "depthValues", "biasAndScale"], ["diffuseSampler"], join);
  60772. }
  60773. if (!this._effect.isReady()) {
  60774. return false;
  60775. }
  60776. if (this.useBlurExponentialShadowMap || this.useBlurCloseExponentialShadowMap) {
  60777. if (!this._blurPostProcesses || !this._blurPostProcesses.length) {
  60778. this._initializeBlurRTTAndPostProcesses();
  60779. }
  60780. }
  60781. if (this._kernelBlurXPostprocess && !this._kernelBlurXPostprocess.isReady()) {
  60782. return false;
  60783. }
  60784. if (this._kernelBlurYPostprocess && !this._kernelBlurYPostprocess.isReady()) {
  60785. return false;
  60786. }
  60787. if (this._boxBlurPostprocess && !this._boxBlurPostprocess.isReady()) {
  60788. return false;
  60789. }
  60790. return true;
  60791. };
  60792. /**
  60793. * Prepare all the defines in a material relying on a shadow map at the specified light index.
  60794. * @param defines Defines of the material we want to update
  60795. * @param lightIndex Index of the light in the enabled light list of the material
  60796. */
  60797. ShadowGenerator.prototype.prepareDefines = function (defines, lightIndex) {
  60798. var scene = this._scene;
  60799. var light = this._light;
  60800. if (!scene.shadowsEnabled || !light.shadowEnabled) {
  60801. return;
  60802. }
  60803. defines["SHADOW" + lightIndex] = true;
  60804. if (this.usePoissonSampling) {
  60805. defines["SHADOWPCF" + lightIndex] = true;
  60806. }
  60807. else if (this.useExponentialShadowMap || this.useBlurExponentialShadowMap) {
  60808. defines["SHADOWESM" + lightIndex] = true;
  60809. }
  60810. else if (this.useCloseExponentialShadowMap || this.useBlurCloseExponentialShadowMap) {
  60811. defines["SHADOWCLOSEESM" + lightIndex] = true;
  60812. }
  60813. if (light.needCube()) {
  60814. defines["SHADOWCUBE" + lightIndex] = true;
  60815. }
  60816. };
  60817. /**
  60818. * Binds the shadow related information inside of an effect (information like near, far, darkness...
  60819. * defined in the generator but impacting the effect).
  60820. * @param lightIndex Index of the light in the enabled light list of the material owning the effect
  60821. * @param effect The effect we are binfing the information for
  60822. */
  60823. ShadowGenerator.prototype.bindShadowLight = function (lightIndex, effect) {
  60824. var light = this._light;
  60825. var scene = this._scene;
  60826. if (!scene.shadowsEnabled || !light.shadowEnabled) {
  60827. return;
  60828. }
  60829. var camera = scene.activeCamera;
  60830. if (!camera) {
  60831. return;
  60832. }
  60833. var shadowMap = this.getShadowMap();
  60834. if (!shadowMap) {
  60835. return;
  60836. }
  60837. if (!light.needCube()) {
  60838. effect.setMatrix("lightMatrix" + lightIndex, this.getTransformMatrix());
  60839. }
  60840. effect.setTexture("shadowSampler" + lightIndex, this.getShadowMapForRendering());
  60841. light._uniformBuffer.updateFloat4("shadowsInfo", this.getDarkness(), this.blurScale / shadowMap.getSize().width, this.depthScale, this.frustumEdgeFalloff, lightIndex);
  60842. light._uniformBuffer.updateFloat2("depthValues", this.getLight().getDepthMinZ(camera), this.getLight().getDepthMinZ(camera) + this.getLight().getDepthMaxZ(camera), lightIndex);
  60843. };
  60844. /**
  60845. * Gets the transformation matrix used to project the meshes into the map from the light point of view.
  60846. * (eq to shadow prjection matrix * light transform matrix)
  60847. * @returns The transform matrix used to create the shadow map
  60848. */
  60849. ShadowGenerator.prototype.getTransformMatrix = function () {
  60850. var scene = this._scene;
  60851. if (this._currentRenderID === scene.getRenderId() && this._currentFaceIndexCache === this._currentFaceIndex) {
  60852. return this._transformMatrix;
  60853. }
  60854. this._currentRenderID = scene.getRenderId();
  60855. this._currentFaceIndexCache = this._currentFaceIndex;
  60856. var lightPosition = this._light.position;
  60857. if (this._light.computeTransformedInformation()) {
  60858. lightPosition = this._light.transformedPosition;
  60859. }
  60860. BABYLON.Vector3.NormalizeToRef(this._light.getShadowDirection(this._currentFaceIndex), this._lightDirection);
  60861. if (Math.abs(BABYLON.Vector3.Dot(this._lightDirection, BABYLON.Vector3.Up())) === 1.0) {
  60862. this._lightDirection.z = 0.0000000000001; // Required to avoid perfectly perpendicular light
  60863. }
  60864. if (this._light.needProjectionMatrixCompute() || !this._cachedPosition || !this._cachedDirection || !lightPosition.equals(this._cachedPosition) || !this._lightDirection.equals(this._cachedDirection)) {
  60865. this._cachedPosition.copyFrom(lightPosition);
  60866. this._cachedDirection.copyFrom(this._lightDirection);
  60867. BABYLON.Matrix.LookAtLHToRef(lightPosition, lightPosition.add(this._lightDirection), BABYLON.Vector3.Up(), this._viewMatrix);
  60868. var shadowMap = this.getShadowMap();
  60869. if (shadowMap) {
  60870. var renderList = shadowMap.renderList;
  60871. if (renderList) {
  60872. this._light.setShadowProjectionMatrix(this._projectionMatrix, this._viewMatrix, renderList);
  60873. }
  60874. }
  60875. this._viewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  60876. }
  60877. return this._transformMatrix;
  60878. };
  60879. /**
  60880. * Recreates the shadow map dependencies like RTT and post processes. This can be used during the switch between
  60881. * Cube and 2D textures for instance.
  60882. */
  60883. ShadowGenerator.prototype.recreateShadowMap = function () {
  60884. var shadowMap = this._shadowMap;
  60885. if (!shadowMap) {
  60886. return;
  60887. }
  60888. // Track render list.
  60889. var renderList = shadowMap.renderList;
  60890. // Clean up existing data.
  60891. this._disposeRTTandPostProcesses();
  60892. // Reinitializes.
  60893. this._initializeGenerator();
  60894. // Reaffect the filter to ensure a correct fallback if necessary.
  60895. this.filter = this.filter;
  60896. // Reaffect the filter.
  60897. this._applyFilterValues();
  60898. // Reaffect Render List.
  60899. this._shadowMap.renderList = renderList;
  60900. };
  60901. ShadowGenerator.prototype._disposeBlurPostProcesses = function () {
  60902. if (this._shadowMap2) {
  60903. this._shadowMap2.dispose();
  60904. this._shadowMap2 = null;
  60905. }
  60906. if (this._boxBlurPostprocess) {
  60907. this._boxBlurPostprocess.dispose();
  60908. this._boxBlurPostprocess = null;
  60909. }
  60910. if (this._kernelBlurXPostprocess) {
  60911. this._kernelBlurXPostprocess.dispose();
  60912. this._kernelBlurXPostprocess = null;
  60913. }
  60914. if (this._kernelBlurYPostprocess) {
  60915. this._kernelBlurYPostprocess.dispose();
  60916. this._kernelBlurYPostprocess = null;
  60917. }
  60918. this._blurPostProcesses = [];
  60919. };
  60920. ShadowGenerator.prototype._disposeRTTandPostProcesses = function () {
  60921. if (this._shadowMap) {
  60922. this._shadowMap.dispose();
  60923. this._shadowMap = null;
  60924. }
  60925. this._disposeBlurPostProcesses();
  60926. };
  60927. /**
  60928. * Disposes the ShadowGenerator.
  60929. * Returns nothing.
  60930. */
  60931. ShadowGenerator.prototype.dispose = function () {
  60932. this._disposeRTTandPostProcesses();
  60933. if (this._light) {
  60934. this._light._shadowGenerator = null;
  60935. this._light._markMeshesAsLightDirty();
  60936. }
  60937. };
  60938. /**
  60939. * Serializes the shadow generator setup to a json object.
  60940. * @returns The serialized JSON object
  60941. */
  60942. ShadowGenerator.prototype.serialize = function () {
  60943. var serializationObject = {};
  60944. var shadowMap = this.getShadowMap();
  60945. if (!shadowMap) {
  60946. return serializationObject;
  60947. }
  60948. serializationObject.lightId = this._light.id;
  60949. serializationObject.mapSize = shadowMap.getRenderSize();
  60950. serializationObject.useExponentialShadowMap = this.useExponentialShadowMap;
  60951. serializationObject.useBlurExponentialShadowMap = this.useBlurExponentialShadowMap;
  60952. serializationObject.useCloseExponentialShadowMap = this.useBlurExponentialShadowMap;
  60953. serializationObject.useBlurCloseExponentialShadowMap = this.useBlurExponentialShadowMap;
  60954. serializationObject.usePoissonSampling = this.usePoissonSampling;
  60955. serializationObject.forceBackFacesOnly = this.forceBackFacesOnly;
  60956. serializationObject.depthScale = this.depthScale;
  60957. serializationObject.darkness = this.getDarkness();
  60958. serializationObject.blurBoxOffset = this.blurBoxOffset;
  60959. serializationObject.blurKernel = this.blurKernel;
  60960. serializationObject.blurScale = this.blurScale;
  60961. serializationObject.useKernelBlur = this.useKernelBlur;
  60962. serializationObject.transparencyShadow = this._transparencyShadow;
  60963. serializationObject.renderList = [];
  60964. if (shadowMap.renderList) {
  60965. for (var meshIndex = 0; meshIndex < shadowMap.renderList.length; meshIndex++) {
  60966. var mesh = shadowMap.renderList[meshIndex];
  60967. serializationObject.renderList.push(mesh.id);
  60968. }
  60969. }
  60970. return serializationObject;
  60971. };
  60972. /**
  60973. * Parses a serialized ShadowGenerator and returns a new ShadowGenerator.
  60974. * @param parsedShadowGenerator The JSON object to parse
  60975. * @param scene The scene to create the shadow map for
  60976. * @returns The parsed shadow generator
  60977. */
  60978. ShadowGenerator.Parse = function (parsedShadowGenerator, scene) {
  60979. //casting to point light, as light is missing the position attr and typescript complains.
  60980. var light = scene.getLightByID(parsedShadowGenerator.lightId);
  60981. var shadowGenerator = new ShadowGenerator(parsedShadowGenerator.mapSize, light);
  60982. var shadowMap = shadowGenerator.getShadowMap();
  60983. for (var meshIndex = 0; meshIndex < parsedShadowGenerator.renderList.length; meshIndex++) {
  60984. var meshes = scene.getMeshesByID(parsedShadowGenerator.renderList[meshIndex]);
  60985. meshes.forEach(function (mesh) {
  60986. if (!shadowMap) {
  60987. return;
  60988. }
  60989. if (!shadowMap.renderList) {
  60990. shadowMap.renderList = [];
  60991. }
  60992. shadowMap.renderList.push(mesh);
  60993. });
  60994. }
  60995. if (parsedShadowGenerator.usePoissonSampling) {
  60996. shadowGenerator.usePoissonSampling = true;
  60997. }
  60998. else if (parsedShadowGenerator.useExponentialShadowMap) {
  60999. shadowGenerator.useExponentialShadowMap = true;
  61000. }
  61001. else if (parsedShadowGenerator.useBlurExponentialShadowMap) {
  61002. shadowGenerator.useBlurExponentialShadowMap = true;
  61003. }
  61004. else if (parsedShadowGenerator.useCloseExponentialShadowMap) {
  61005. shadowGenerator.useCloseExponentialShadowMap = true;
  61006. }
  61007. else if (parsedShadowGenerator.useBlurCloseExponentialShadowMap) {
  61008. shadowGenerator.useBlurCloseExponentialShadowMap = true;
  61009. }
  61010. else if (parsedShadowGenerator.useVarianceShadowMap) {
  61011. shadowGenerator.useExponentialShadowMap = true;
  61012. }
  61013. else if (parsedShadowGenerator.useBlurVarianceShadowMap) {
  61014. shadowGenerator.useBlurExponentialShadowMap = true;
  61015. }
  61016. if (parsedShadowGenerator.depthScale) {
  61017. shadowGenerator.depthScale = parsedShadowGenerator.depthScale;
  61018. }
  61019. if (parsedShadowGenerator.blurScale) {
  61020. shadowGenerator.blurScale = parsedShadowGenerator.blurScale;
  61021. }
  61022. if (parsedShadowGenerator.blurBoxOffset) {
  61023. shadowGenerator.blurBoxOffset = parsedShadowGenerator.blurBoxOffset;
  61024. }
  61025. if (parsedShadowGenerator.useKernelBlur) {
  61026. shadowGenerator.useKernelBlur = parsedShadowGenerator.useKernelBlur;
  61027. }
  61028. if (parsedShadowGenerator.blurKernel) {
  61029. shadowGenerator.blurKernel = parsedShadowGenerator.blurKernel;
  61030. }
  61031. if (parsedShadowGenerator.bias !== undefined) {
  61032. shadowGenerator.bias = parsedShadowGenerator.bias;
  61033. }
  61034. if (parsedShadowGenerator.darkness) {
  61035. shadowGenerator.setDarkness(parsedShadowGenerator.darkness);
  61036. }
  61037. if (parsedShadowGenerator.transparencyShadow) {
  61038. shadowGenerator.setTransparencyShadow(true);
  61039. }
  61040. shadowGenerator.forceBackFacesOnly = parsedShadowGenerator.forceBackFacesOnly;
  61041. return shadowGenerator;
  61042. };
  61043. ShadowGenerator._FILTER_NONE = 0;
  61044. ShadowGenerator._FILTER_EXPONENTIALSHADOWMAP = 1;
  61045. ShadowGenerator._FILTER_POISSONSAMPLING = 2;
  61046. ShadowGenerator._FILTER_BLUREXPONENTIALSHADOWMAP = 3;
  61047. ShadowGenerator._FILTER_CLOSEEXPONENTIALSHADOWMAP = 4;
  61048. ShadowGenerator._FILTER_BLURCLOSEEXPONENTIALSHADOWMAP = 5;
  61049. return ShadowGenerator;
  61050. }());
  61051. BABYLON.ShadowGenerator = ShadowGenerator;
  61052. })(BABYLON || (BABYLON = {}));
  61053. //# sourceMappingURL=babylon.shadowGenerator.js.map
  61054. var BABYLON;
  61055. (function (BABYLON) {
  61056. var DefaultLoadingScreen = /** @class */ (function () {
  61057. function DefaultLoadingScreen(_renderingCanvas, _loadingText, _loadingDivBackgroundColor) {
  61058. if (_loadingText === void 0) { _loadingText = ""; }
  61059. if (_loadingDivBackgroundColor === void 0) { _loadingDivBackgroundColor = "black"; }
  61060. var _this = this;
  61061. this._renderingCanvas = _renderingCanvas;
  61062. this._loadingText = _loadingText;
  61063. this._loadingDivBackgroundColor = _loadingDivBackgroundColor;
  61064. // Resize
  61065. this._resizeLoadingUI = function () {
  61066. var canvasRect = _this._renderingCanvas.getBoundingClientRect();
  61067. var canvasPositioning = window.getComputedStyle(_this._renderingCanvas).position;
  61068. if (!_this._loadingDiv) {
  61069. return;
  61070. }
  61071. _this._loadingDiv.style.position = (canvasPositioning === "fixed") ? "fixed" : "absolute";
  61072. _this._loadingDiv.style.left = canvasRect.left + "px";
  61073. _this._loadingDiv.style.top = canvasRect.top + "px";
  61074. _this._loadingDiv.style.width = canvasRect.width + "px";
  61075. _this._loadingDiv.style.height = canvasRect.height + "px";
  61076. };
  61077. }
  61078. DefaultLoadingScreen.prototype.displayLoadingUI = function () {
  61079. if (this._loadingDiv) {
  61080. // Do not add a loading screen if there is already one
  61081. return;
  61082. }
  61083. this._loadingDiv = document.createElement("div");
  61084. this._loadingDiv.id = "babylonjsLoadingDiv";
  61085. this._loadingDiv.style.opacity = "0";
  61086. this._loadingDiv.style.transition = "opacity 1.5s ease";
  61087. this._loadingDiv.style.pointerEvents = "none";
  61088. // Loading text
  61089. this._loadingTextDiv = document.createElement("div");
  61090. this._loadingTextDiv.style.position = "absolute";
  61091. this._loadingTextDiv.style.left = "0";
  61092. this._loadingTextDiv.style.top = "50%";
  61093. this._loadingTextDiv.style.marginTop = "80px";
  61094. this._loadingTextDiv.style.width = "100%";
  61095. this._loadingTextDiv.style.height = "20px";
  61096. this._loadingTextDiv.style.fontFamily = "Arial";
  61097. this._loadingTextDiv.style.fontSize = "14px";
  61098. this._loadingTextDiv.style.color = "white";
  61099. this._loadingTextDiv.style.textAlign = "center";
  61100. this._loadingTextDiv.innerHTML = "Loading";
  61101. this._loadingDiv.appendChild(this._loadingTextDiv);
  61102. //set the predefined text
  61103. this._loadingTextDiv.innerHTML = this._loadingText;
  61104. // Generating keyframes
  61105. var style = document.createElement('style');
  61106. style.type = 'text/css';
  61107. 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 }";
  61108. style.innerHTML = keyFrames;
  61109. document.getElementsByTagName('head')[0].appendChild(style);
  61110. // Loading img
  61111. var imgBack = new Image();
  61112. 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";
  61113. imgBack.style.position = "absolute";
  61114. imgBack.style.left = "50%";
  61115. imgBack.style.top = "50%";
  61116. imgBack.style.marginLeft = "-60px";
  61117. imgBack.style.marginTop = "-60px";
  61118. imgBack.style.animation = "spin1 2s infinite ease-in-out";
  61119. imgBack.style.webkitAnimation = "spin1 2s infinite ease-in-out";
  61120. imgBack.style.transformOrigin = "50% 50%";
  61121. imgBack.style.webkitTransformOrigin = "50% 50%";
  61122. this._loadingDiv.appendChild(imgBack);
  61123. this._resizeLoadingUI();
  61124. window.addEventListener("resize", this._resizeLoadingUI);
  61125. this._loadingDiv.style.backgroundColor = this._loadingDivBackgroundColor;
  61126. document.body.appendChild(this._loadingDiv);
  61127. this._loadingDiv.style.opacity = "1";
  61128. };
  61129. DefaultLoadingScreen.prototype.hideLoadingUI = function () {
  61130. var _this = this;
  61131. if (!this._loadingDiv) {
  61132. return;
  61133. }
  61134. var onTransitionEnd = function () {
  61135. if (!_this._loadingDiv) {
  61136. return;
  61137. }
  61138. document.body.removeChild(_this._loadingDiv);
  61139. window.removeEventListener("resize", _this._resizeLoadingUI);
  61140. _this._loadingDiv = null;
  61141. };
  61142. this._loadingDiv.style.opacity = "0";
  61143. this._loadingDiv.addEventListener("transitionend", onTransitionEnd);
  61144. };
  61145. Object.defineProperty(DefaultLoadingScreen.prototype, "loadingUIText", {
  61146. set: function (text) {
  61147. this._loadingText = text;
  61148. if (this._loadingTextDiv) {
  61149. this._loadingTextDiv.innerHTML = this._loadingText;
  61150. }
  61151. },
  61152. enumerable: true,
  61153. configurable: true
  61154. });
  61155. Object.defineProperty(DefaultLoadingScreen.prototype, "loadingUIBackgroundColor", {
  61156. get: function () {
  61157. return this._loadingDivBackgroundColor;
  61158. },
  61159. set: function (color) {
  61160. this._loadingDivBackgroundColor = color;
  61161. if (!this._loadingDiv) {
  61162. return;
  61163. }
  61164. this._loadingDiv.style.backgroundColor = this._loadingDivBackgroundColor;
  61165. },
  61166. enumerable: true,
  61167. configurable: true
  61168. });
  61169. return DefaultLoadingScreen;
  61170. }());
  61171. BABYLON.DefaultLoadingScreen = DefaultLoadingScreen;
  61172. })(BABYLON || (BABYLON = {}));
  61173. //# sourceMappingURL=babylon.loadingScreen.js.map
  61174. var BABYLON;
  61175. (function (BABYLON) {
  61176. var SceneLoaderProgressEvent = /** @class */ (function () {
  61177. function SceneLoaderProgressEvent(lengthComputable, loaded, total) {
  61178. this.lengthComputable = lengthComputable;
  61179. this.loaded = loaded;
  61180. this.total = total;
  61181. }
  61182. SceneLoaderProgressEvent.FromProgressEvent = function (event) {
  61183. return new SceneLoaderProgressEvent(event.lengthComputable, event.loaded, event.total);
  61184. };
  61185. return SceneLoaderProgressEvent;
  61186. }());
  61187. BABYLON.SceneLoaderProgressEvent = SceneLoaderProgressEvent;
  61188. var SceneLoader = /** @class */ (function () {
  61189. function SceneLoader() {
  61190. }
  61191. Object.defineProperty(SceneLoader, "NO_LOGGING", {
  61192. get: function () {
  61193. return 0;
  61194. },
  61195. enumerable: true,
  61196. configurable: true
  61197. });
  61198. Object.defineProperty(SceneLoader, "MINIMAL_LOGGING", {
  61199. get: function () {
  61200. return 1;
  61201. },
  61202. enumerable: true,
  61203. configurable: true
  61204. });
  61205. Object.defineProperty(SceneLoader, "SUMMARY_LOGGING", {
  61206. get: function () {
  61207. return 2;
  61208. },
  61209. enumerable: true,
  61210. configurable: true
  61211. });
  61212. Object.defineProperty(SceneLoader, "DETAILED_LOGGING", {
  61213. get: function () {
  61214. return 3;
  61215. },
  61216. enumerable: true,
  61217. configurable: true
  61218. });
  61219. Object.defineProperty(SceneLoader, "ForceFullSceneLoadingForIncremental", {
  61220. get: function () {
  61221. return SceneLoader._ForceFullSceneLoadingForIncremental;
  61222. },
  61223. set: function (value) {
  61224. SceneLoader._ForceFullSceneLoadingForIncremental = value;
  61225. },
  61226. enumerable: true,
  61227. configurable: true
  61228. });
  61229. Object.defineProperty(SceneLoader, "ShowLoadingScreen", {
  61230. get: function () {
  61231. return SceneLoader._ShowLoadingScreen;
  61232. },
  61233. set: function (value) {
  61234. SceneLoader._ShowLoadingScreen = value;
  61235. },
  61236. enumerable: true,
  61237. configurable: true
  61238. });
  61239. Object.defineProperty(SceneLoader, "loggingLevel", {
  61240. get: function () {
  61241. return SceneLoader._loggingLevel;
  61242. },
  61243. set: function (value) {
  61244. SceneLoader._loggingLevel = value;
  61245. },
  61246. enumerable: true,
  61247. configurable: true
  61248. });
  61249. Object.defineProperty(SceneLoader, "CleanBoneMatrixWeights", {
  61250. get: function () {
  61251. return SceneLoader._CleanBoneMatrixWeights;
  61252. },
  61253. set: function (value) {
  61254. SceneLoader._CleanBoneMatrixWeights = value;
  61255. },
  61256. enumerable: true,
  61257. configurable: true
  61258. });
  61259. SceneLoader._getDefaultPlugin = function () {
  61260. return SceneLoader._registeredPlugins[".babylon"];
  61261. };
  61262. SceneLoader._getPluginForExtension = function (extension) {
  61263. var registeredPlugin = SceneLoader._registeredPlugins[extension];
  61264. if (registeredPlugin) {
  61265. return registeredPlugin;
  61266. }
  61267. BABYLON.Tools.Warn("Unable to find a plugin to load " + extension + " files. Trying to use .babylon default plugin.");
  61268. return SceneLoader._getDefaultPlugin();
  61269. };
  61270. SceneLoader._getPluginForDirectLoad = function (data) {
  61271. for (var extension in SceneLoader._registeredPlugins) {
  61272. var plugin = SceneLoader._registeredPlugins[extension].plugin;
  61273. if (plugin.canDirectLoad && plugin.canDirectLoad(data)) {
  61274. return SceneLoader._registeredPlugins[extension];
  61275. }
  61276. }
  61277. return SceneLoader._getDefaultPlugin();
  61278. };
  61279. SceneLoader._getPluginForFilename = function (sceneFilename) {
  61280. if (sceneFilename.name) {
  61281. sceneFilename = sceneFilename.name;
  61282. }
  61283. var queryStringPosition = sceneFilename.indexOf("?");
  61284. if (queryStringPosition !== -1) {
  61285. sceneFilename = sceneFilename.substring(0, queryStringPosition);
  61286. }
  61287. var dotPosition = sceneFilename.lastIndexOf(".");
  61288. var extension = sceneFilename.substring(dotPosition, sceneFilename.length).toLowerCase();
  61289. return SceneLoader._getPluginForExtension(extension);
  61290. };
  61291. // use babylon file loader directly if sceneFilename is prefixed with "data:"
  61292. SceneLoader._getDirectLoad = function (sceneFilename) {
  61293. if (sceneFilename.substr && sceneFilename.substr(0, 5) === "data:") {
  61294. return sceneFilename.substr(5);
  61295. }
  61296. return null;
  61297. };
  61298. SceneLoader._loadData = function (rootUrl, sceneFilename, scene, onSuccess, onProgress, onError, onDispose, pluginExtension) {
  61299. var directLoad = SceneLoader._getDirectLoad(sceneFilename);
  61300. var registeredPlugin = pluginExtension ? SceneLoader._getPluginForExtension(pluginExtension) : (directLoad ? SceneLoader._getPluginForDirectLoad(sceneFilename) : SceneLoader._getPluginForFilename(sceneFilename));
  61301. var plugin;
  61302. if (registeredPlugin.plugin.createPlugin) {
  61303. plugin = registeredPlugin.plugin.createPlugin();
  61304. }
  61305. else {
  61306. plugin = registeredPlugin.plugin;
  61307. }
  61308. var useArrayBuffer = registeredPlugin.isBinary;
  61309. var database;
  61310. SceneLoader.OnPluginActivatedObservable.notifyObservers(plugin);
  61311. var dataCallback = function (data, responseURL) {
  61312. if (scene.isDisposed) {
  61313. onError("Scene has been disposed");
  61314. return;
  61315. }
  61316. scene.database = database;
  61317. onSuccess(plugin, data, responseURL);
  61318. };
  61319. var request = null;
  61320. var pluginDisposed = false;
  61321. var onDisposeObservable = plugin.onDisposeObservable;
  61322. if (onDisposeObservable) {
  61323. onDisposeObservable.add(function () {
  61324. pluginDisposed = true;
  61325. if (request) {
  61326. request.abort();
  61327. request = null;
  61328. }
  61329. onDispose();
  61330. });
  61331. }
  61332. var manifestChecked = function () {
  61333. if (pluginDisposed) {
  61334. return;
  61335. }
  61336. var url = rootUrl + sceneFilename;
  61337. request = BABYLON.Tools.LoadFile(url, dataCallback, onProgress ? function (event) {
  61338. onProgress(SceneLoaderProgressEvent.FromProgressEvent(event));
  61339. } : undefined, database, useArrayBuffer, function (request, exception) {
  61340. onError("Failed to load scene." + (exception ? "" : " " + exception.message), exception);
  61341. });
  61342. };
  61343. if (directLoad) {
  61344. dataCallback(directLoad);
  61345. return plugin;
  61346. }
  61347. if (rootUrl.indexOf("file:") === -1) {
  61348. if (scene.getEngine().enableOfflineSupport) {
  61349. // Checking if a manifest file has been set for this scene and if offline mode has been requested
  61350. database = new BABYLON.Database(rootUrl + sceneFilename, manifestChecked);
  61351. }
  61352. else {
  61353. manifestChecked();
  61354. }
  61355. }
  61356. else {
  61357. var fileOrString = sceneFilename;
  61358. if (fileOrString.name) {
  61359. request = BABYLON.Tools.ReadFile(fileOrString, dataCallback, onProgress, useArrayBuffer);
  61360. }
  61361. else if (BABYLON.FilesInput.FilesToLoad[sceneFilename]) {
  61362. request = BABYLON.Tools.ReadFile(BABYLON.FilesInput.FilesToLoad[sceneFilename], dataCallback, onProgress, useArrayBuffer);
  61363. }
  61364. else {
  61365. onError("Unable to find file named " + sceneFilename);
  61366. }
  61367. }
  61368. return plugin;
  61369. };
  61370. // Public functions
  61371. SceneLoader.GetPluginForExtension = function (extension) {
  61372. return SceneLoader._getPluginForExtension(extension).plugin;
  61373. };
  61374. SceneLoader.IsPluginForExtensionAvailable = function (extension) {
  61375. return !!SceneLoader._registeredPlugins[extension];
  61376. };
  61377. SceneLoader.RegisterPlugin = function (plugin) {
  61378. if (typeof plugin.extensions === "string") {
  61379. var extension = plugin.extensions;
  61380. SceneLoader._registeredPlugins[extension.toLowerCase()] = {
  61381. plugin: plugin,
  61382. isBinary: false
  61383. };
  61384. }
  61385. else {
  61386. var extensions = plugin.extensions;
  61387. Object.keys(extensions).forEach(function (extension) {
  61388. SceneLoader._registeredPlugins[extension.toLowerCase()] = {
  61389. plugin: plugin,
  61390. isBinary: extensions[extension].isBinary
  61391. };
  61392. });
  61393. }
  61394. };
  61395. /**
  61396. * Import meshes into a scene
  61397. * @param meshNames an array of mesh names, a single mesh name, or empty string for all meshes that filter what meshes are imported
  61398. * @param rootUrl a string that defines the root url for scene and resources
  61399. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  61400. * @param scene the instance of BABYLON.Scene to append to
  61401. * @param onSuccess a callback with a list of imported meshes, particleSystems, and skeletons when import succeeds
  61402. * @param onProgress a callback with a progress event for each file being loaded
  61403. * @param onError a callback with the scene, a message, and possibly an exception when import fails
  61404. * @param pluginExtension the extension used to determine the plugin
  61405. * @returns The loaded plugin
  61406. */
  61407. SceneLoader.ImportMesh = function (meshNames, rootUrl, sceneFilename, scene, onSuccess, onProgress, onError, pluginExtension) {
  61408. if (onSuccess === void 0) { onSuccess = null; }
  61409. if (onProgress === void 0) { onProgress = null; }
  61410. if (onError === void 0) { onError = null; }
  61411. if (pluginExtension === void 0) { pluginExtension = null; }
  61412. if (sceneFilename.substr && sceneFilename.substr(0, 1) === "/") {
  61413. BABYLON.Tools.Error("Wrong sceneFilename parameter");
  61414. return null;
  61415. }
  61416. var loadingToken = {};
  61417. scene._addPendingData(loadingToken);
  61418. var disposeHandler = function () {
  61419. scene._removePendingData(loadingToken);
  61420. };
  61421. var errorHandler = function (message, exception) {
  61422. var errorMessage = "Unable to import meshes from " + rootUrl + sceneFilename + ": " + message;
  61423. if (onError) {
  61424. onError(scene, errorMessage, exception);
  61425. }
  61426. else {
  61427. BABYLON.Tools.Error(errorMessage);
  61428. // should the exception be thrown?
  61429. }
  61430. disposeHandler();
  61431. };
  61432. var progressHandler = onProgress ? function (event) {
  61433. try {
  61434. onProgress(event);
  61435. }
  61436. catch (e) {
  61437. errorHandler("Error in onProgress callback", e);
  61438. }
  61439. } : undefined;
  61440. var successHandler = function (meshes, particleSystems, skeletons) {
  61441. scene.importedMeshesFiles.push(rootUrl + sceneFilename);
  61442. if (onSuccess) {
  61443. try {
  61444. onSuccess(meshes, particleSystems, skeletons);
  61445. }
  61446. catch (e) {
  61447. errorHandler("Error in onSuccess callback", e);
  61448. }
  61449. }
  61450. scene._removePendingData(loadingToken);
  61451. };
  61452. return SceneLoader._loadData(rootUrl, sceneFilename, scene, function (plugin, data, responseURL) {
  61453. if (plugin.rewriteRootURL) {
  61454. rootUrl = plugin.rewriteRootURL(rootUrl, responseURL);
  61455. }
  61456. if (sceneFilename === "") {
  61457. if (sceneFilename === "") {
  61458. rootUrl = BABYLON.Tools.GetFolderPath(rootUrl, true);
  61459. }
  61460. }
  61461. if (plugin.importMesh) {
  61462. var syncedPlugin = plugin;
  61463. var meshes = new Array();
  61464. var particleSystems = new Array();
  61465. var skeletons = new Array();
  61466. if (!syncedPlugin.importMesh(meshNames, scene, data, rootUrl, meshes, particleSystems, skeletons, errorHandler)) {
  61467. return;
  61468. }
  61469. scene.loadingPluginName = plugin.name;
  61470. successHandler(meshes, particleSystems, skeletons);
  61471. }
  61472. else {
  61473. var asyncedPlugin = plugin;
  61474. asyncedPlugin.importMeshAsync(meshNames, scene, data, rootUrl, progressHandler).then(function (result) {
  61475. scene.loadingPluginName = plugin.name;
  61476. successHandler(result.meshes, result.particleSystems, result.skeletons);
  61477. }).catch(function (error) {
  61478. errorHandler(error.message, error);
  61479. });
  61480. }
  61481. }, progressHandler, errorHandler, disposeHandler, pluginExtension);
  61482. };
  61483. /**
  61484. * Import meshes into a scene
  61485. * @param meshNames an array of mesh names, a single mesh name, or empty string for all meshes that filter what meshes are imported
  61486. * @param rootUrl a string that defines the root url for scene and resources
  61487. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  61488. * @param scene the instance of BABYLON.Scene to append to
  61489. * @param onProgress a callback with a progress event for each file being loaded
  61490. * @param pluginExtension the extension used to determine the plugin
  61491. * @returns The loaded list of imported meshes, particleSystems, and skeletons
  61492. */
  61493. SceneLoader.ImportMeshAsync = function (meshNames, rootUrl, sceneFilename, scene, onProgress, pluginExtension) {
  61494. if (onProgress === void 0) { onProgress = null; }
  61495. if (pluginExtension === void 0) { pluginExtension = null; }
  61496. return new Promise(function (resolve, reject) {
  61497. SceneLoader.ImportMesh(meshNames, rootUrl, sceneFilename, scene, function (meshes, particleSystems, skeletons) {
  61498. resolve({
  61499. meshes: meshes,
  61500. particleSystems: particleSystems,
  61501. skeletons: skeletons
  61502. });
  61503. }, onProgress, function (scene, message, exception) {
  61504. reject(exception || new Error(message));
  61505. });
  61506. });
  61507. };
  61508. /**
  61509. * Load a scene
  61510. * @param rootUrl a string that defines the root url for scene and resources
  61511. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  61512. * @param engine is the instance of BABYLON.Engine to use to create the scene
  61513. * @param onSuccess a callback with the scene when import succeeds
  61514. * @param onProgress a callback with a progress event for each file being loaded
  61515. * @param onError a callback with the scene, a message, and possibly an exception when import fails
  61516. * @param pluginExtension the extension used to determine the plugin
  61517. * @returns The loaded plugin
  61518. */
  61519. SceneLoader.Load = function (rootUrl, sceneFilename, engine, onSuccess, onProgress, onError, pluginExtension) {
  61520. if (onSuccess === void 0) { onSuccess = null; }
  61521. if (onProgress === void 0) { onProgress = null; }
  61522. if (onError === void 0) { onError = null; }
  61523. if (pluginExtension === void 0) { pluginExtension = null; }
  61524. return SceneLoader.Append(rootUrl, sceneFilename, new BABYLON.Scene(engine), onSuccess, onProgress, onError, pluginExtension);
  61525. };
  61526. /**
  61527. * Load a scene
  61528. * @param rootUrl a string that defines the root url for scene and resources
  61529. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  61530. * @param engine is the instance of BABYLON.Engine to use to create the scene
  61531. * @param onProgress a callback with a progress event for each file being loaded
  61532. * @param pluginExtension the extension used to determine the plugin
  61533. * @returns The loaded scene
  61534. */
  61535. SceneLoader.LoadAsync = function (rootUrl, sceneFilename, engine, onProgress, pluginExtension) {
  61536. if (onProgress === void 0) { onProgress = null; }
  61537. if (pluginExtension === void 0) { pluginExtension = null; }
  61538. return new Promise(function (resolve, reject) {
  61539. SceneLoader.Load(rootUrl, sceneFilename, engine, function (scene) {
  61540. resolve(scene);
  61541. }, onProgress, function (scene, message, exception) {
  61542. reject(exception || new Error(message));
  61543. }, pluginExtension);
  61544. });
  61545. };
  61546. /**
  61547. * Append a scene
  61548. * @param rootUrl a string that defines the root url for scene and resources
  61549. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  61550. * @param scene is the instance of BABYLON.Scene to append to
  61551. * @param onSuccess a callback with the scene when import succeeds
  61552. * @param onProgress a callback with a progress event for each file being loaded
  61553. * @param onError a callback with the scene, a message, and possibly an exception when import fails
  61554. * @param pluginExtension the extension used to determine the plugin
  61555. * @returns The loaded plugin
  61556. */
  61557. SceneLoader.Append = function (rootUrl, sceneFilename, scene, onSuccess, onProgress, onError, pluginExtension) {
  61558. if (onSuccess === void 0) { onSuccess = null; }
  61559. if (onProgress === void 0) { onProgress = null; }
  61560. if (onError === void 0) { onError = null; }
  61561. if (pluginExtension === void 0) { pluginExtension = null; }
  61562. if (sceneFilename.substr && sceneFilename.substr(0, 1) === "/") {
  61563. BABYLON.Tools.Error("Wrong sceneFilename parameter");
  61564. return null;
  61565. }
  61566. if (SceneLoader.ShowLoadingScreen) {
  61567. scene.getEngine().displayLoadingUI();
  61568. }
  61569. var loadingToken = {};
  61570. scene._addPendingData(loadingToken);
  61571. var disposeHandler = function () {
  61572. scene._removePendingData(loadingToken);
  61573. scene.getEngine().hideLoadingUI();
  61574. };
  61575. var errorHandler = function (message, exception) {
  61576. var errorMessage = "Unable to load from " + rootUrl + sceneFilename + (message ? ": " + message : "");
  61577. if (onError) {
  61578. onError(scene, errorMessage, exception);
  61579. }
  61580. else {
  61581. BABYLON.Tools.Error(errorMessage);
  61582. // should the exception be thrown?
  61583. }
  61584. disposeHandler();
  61585. };
  61586. var progressHandler = onProgress ? function (event) {
  61587. try {
  61588. onProgress(event);
  61589. }
  61590. catch (e) {
  61591. errorHandler("Error in onProgress callback", e);
  61592. }
  61593. } : undefined;
  61594. var successHandler = function () {
  61595. if (onSuccess) {
  61596. try {
  61597. onSuccess(scene);
  61598. }
  61599. catch (e) {
  61600. errorHandler("Error in onSuccess callback", e);
  61601. }
  61602. }
  61603. scene._removePendingData(loadingToken);
  61604. };
  61605. return SceneLoader._loadData(rootUrl, sceneFilename, scene, function (plugin, data, responseURL) {
  61606. if (sceneFilename === "") {
  61607. rootUrl = BABYLON.Tools.GetFolderPath(rootUrl, true);
  61608. }
  61609. if (plugin.load) {
  61610. var syncedPlugin = plugin;
  61611. if (!syncedPlugin.load(scene, data, rootUrl, errorHandler)) {
  61612. return;
  61613. }
  61614. scene.loadingPluginName = plugin.name;
  61615. successHandler();
  61616. }
  61617. else {
  61618. var asyncedPlugin = plugin;
  61619. asyncedPlugin.loadAsync(scene, data, rootUrl, progressHandler).then(function () {
  61620. scene.loadingPluginName = plugin.name;
  61621. successHandler();
  61622. }).catch(function (error) {
  61623. errorHandler(error.message, error);
  61624. });
  61625. }
  61626. if (SceneLoader.ShowLoadingScreen) {
  61627. scene.executeWhenReady(function () {
  61628. scene.getEngine().hideLoadingUI();
  61629. });
  61630. }
  61631. }, progressHandler, errorHandler, disposeHandler, pluginExtension);
  61632. };
  61633. /**
  61634. * Append a scene
  61635. * @param rootUrl a string that defines the root url for scene and resources
  61636. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  61637. * @param scene is the instance of BABYLON.Scene to append to
  61638. * @param onProgress a callback with a progress event for each file being loaded
  61639. * @param pluginExtension the extension used to determine the plugin
  61640. * @returns The given scene
  61641. */
  61642. SceneLoader.AppendAsync = function (rootUrl, sceneFilename, scene, onProgress, pluginExtension) {
  61643. if (onProgress === void 0) { onProgress = null; }
  61644. if (pluginExtension === void 0) { pluginExtension = null; }
  61645. return new Promise(function (resolve, reject) {
  61646. SceneLoader.Append(rootUrl, sceneFilename, scene, function (scene) {
  61647. resolve(scene);
  61648. }, onProgress, function (scene, message, exception) {
  61649. reject(exception || new Error(message));
  61650. }, pluginExtension);
  61651. });
  61652. };
  61653. /**
  61654. * Load a scene into an asset container
  61655. * @param rootUrl a string that defines the root url for scene and resources
  61656. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  61657. * @param scene is the instance of BABYLON.Scene to append to
  61658. * @param onSuccess a callback with the scene when import succeeds
  61659. * @param onProgress a callback with a progress event for each file being loaded
  61660. * @param onError a callback with the scene, a message, and possibly an exception when import fails
  61661. * @param pluginExtension the extension used to determine the plugin
  61662. * @returns The loaded plugin
  61663. */
  61664. SceneLoader.LoadAssetContainer = function (rootUrl, sceneFilename, scene, onSuccess, onProgress, onError, pluginExtension) {
  61665. if (onSuccess === void 0) { onSuccess = null; }
  61666. if (onProgress === void 0) { onProgress = null; }
  61667. if (onError === void 0) { onError = null; }
  61668. if (pluginExtension === void 0) { pluginExtension = null; }
  61669. if (sceneFilename.substr && sceneFilename.substr(0, 1) === "/") {
  61670. BABYLON.Tools.Error("Wrong sceneFilename parameter");
  61671. return null;
  61672. }
  61673. var loadingToken = {};
  61674. scene._addPendingData(loadingToken);
  61675. var disposeHandler = function () {
  61676. scene._removePendingData(loadingToken);
  61677. };
  61678. var errorHandler = function (message, exception) {
  61679. var errorMessage = "Unable to load assets from " + rootUrl + sceneFilename + (message ? ": " + message : "");
  61680. if (onError) {
  61681. onError(scene, errorMessage, exception);
  61682. }
  61683. else {
  61684. BABYLON.Tools.Error(errorMessage);
  61685. // should the exception be thrown?
  61686. }
  61687. disposeHandler();
  61688. };
  61689. var progressHandler = onProgress ? function (event) {
  61690. try {
  61691. onProgress(event);
  61692. }
  61693. catch (e) {
  61694. errorHandler("Error in onProgress callback", e);
  61695. }
  61696. } : undefined;
  61697. var successHandler = function (assets) {
  61698. if (onSuccess) {
  61699. try {
  61700. onSuccess(assets);
  61701. }
  61702. catch (e) {
  61703. errorHandler("Error in onSuccess callback", e);
  61704. }
  61705. }
  61706. scene._removePendingData(loadingToken);
  61707. };
  61708. return SceneLoader._loadData(rootUrl, sceneFilename, scene, function (plugin, data, responseURL) {
  61709. if (plugin.loadAssetContainer) {
  61710. var syncedPlugin = plugin;
  61711. var assetContainer = syncedPlugin.loadAssetContainer(scene, data, rootUrl, errorHandler);
  61712. if (!assetContainer) {
  61713. return;
  61714. }
  61715. scene.loadingPluginName = plugin.name;
  61716. successHandler(assetContainer);
  61717. }
  61718. else if (plugin.loadAssetContainerAsync) {
  61719. var asyncedPlugin = plugin;
  61720. asyncedPlugin.loadAssetContainerAsync(scene, data, rootUrl, progressHandler).then(function (assetContainer) {
  61721. scene.loadingPluginName = plugin.name;
  61722. successHandler(assetContainer);
  61723. }).catch(function (error) {
  61724. errorHandler(error.message, error);
  61725. });
  61726. }
  61727. else {
  61728. errorHandler("LoadAssetContainer is not supported by this plugin. Plugin did not provide a loadAssetContainer or loadAssetContainerAsync method.");
  61729. }
  61730. if (SceneLoader.ShowLoadingScreen) {
  61731. scene.executeWhenReady(function () {
  61732. scene.getEngine().hideLoadingUI();
  61733. });
  61734. }
  61735. }, progressHandler, errorHandler, disposeHandler, pluginExtension);
  61736. };
  61737. /**
  61738. * Load a scene into an asset container
  61739. * @param rootUrl a string that defines the root url for scene and resources
  61740. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  61741. * @param scene is the instance of BABYLON.Scene to append to
  61742. * @param onProgress a callback with a progress event for each file being loaded
  61743. * @param pluginExtension the extension used to determine the plugin
  61744. * @returns The loaded asset container
  61745. */
  61746. SceneLoader.LoadAssetContainerAsync = function (rootUrl, sceneFilename, scene, onProgress, pluginExtension) {
  61747. if (onProgress === void 0) { onProgress = null; }
  61748. if (pluginExtension === void 0) { pluginExtension = null; }
  61749. return new Promise(function (resolve, reject) {
  61750. SceneLoader.LoadAssetContainer(rootUrl, sceneFilename, scene, function (assetContainer) {
  61751. resolve(assetContainer);
  61752. }, onProgress, function (scene, message, exception) {
  61753. reject(exception || new Error(message));
  61754. }, pluginExtension);
  61755. });
  61756. };
  61757. // Flags
  61758. SceneLoader._ForceFullSceneLoadingForIncremental = false;
  61759. SceneLoader._ShowLoadingScreen = true;
  61760. SceneLoader._CleanBoneMatrixWeights = false;
  61761. SceneLoader._loggingLevel = SceneLoader.NO_LOGGING;
  61762. // Members
  61763. SceneLoader.OnPluginActivatedObservable = new BABYLON.Observable();
  61764. SceneLoader._registeredPlugins = {};
  61765. return SceneLoader;
  61766. }());
  61767. BABYLON.SceneLoader = SceneLoader;
  61768. ;
  61769. })(BABYLON || (BABYLON = {}));
  61770. //# sourceMappingURL=babylon.sceneLoader.js.map
  61771. var BABYLON;
  61772. (function (BABYLON) {
  61773. var parseMaterialById = function (id, parsedData, scene, rootUrl) {
  61774. for (var index = 0, cache = parsedData.materials.length; index < cache; index++) {
  61775. var parsedMaterial = parsedData.materials[index];
  61776. if (parsedMaterial.id === id) {
  61777. return BABYLON.Material.Parse(parsedMaterial, scene, rootUrl);
  61778. }
  61779. }
  61780. return null;
  61781. };
  61782. var isDescendantOf = function (mesh, names, hierarchyIds) {
  61783. for (var i in names) {
  61784. if (mesh.name === names[i]) {
  61785. hierarchyIds.push(mesh.id);
  61786. return true;
  61787. }
  61788. }
  61789. if (mesh.parentId && hierarchyIds.indexOf(mesh.parentId) !== -1) {
  61790. hierarchyIds.push(mesh.id);
  61791. return true;
  61792. }
  61793. return false;
  61794. };
  61795. var logOperation = function (operation, producer) {
  61796. return operation + " of " + (producer ? producer.file + " from " + producer.name + " version: " + producer.version + ", exporter version: " + producer.exporter_version : "unknown");
  61797. };
  61798. var loadAssetContainer = function (scene, data, rootUrl, onError, addToScene) {
  61799. if (addToScene === void 0) { addToScene = false; }
  61800. var container = new BABYLON.AssetContainer(scene);
  61801. // Entire method running in try block, so ALWAYS logs as far as it got, only actually writes details
  61802. // when SceneLoader.debugLogging = true (default), or exception encountered.
  61803. // Everything stored in var log instead of writing separate lines to support only writing in exception,
  61804. // and avoid problems with multiple concurrent .babylon loads.
  61805. var log = "importScene has failed JSON parse";
  61806. try {
  61807. var parsedData = JSON.parse(data);
  61808. log = "";
  61809. var fullDetails = BABYLON.SceneLoader.loggingLevel === BABYLON.SceneLoader.DETAILED_LOGGING;
  61810. var index;
  61811. var cache;
  61812. // Lights
  61813. if (parsedData.lights !== undefined && parsedData.lights !== null) {
  61814. for (index = 0, cache = parsedData.lights.length; index < cache; index++) {
  61815. var parsedLight = parsedData.lights[index];
  61816. var light = BABYLON.Light.Parse(parsedLight, scene);
  61817. if (light) {
  61818. container.lights.push(light);
  61819. log += (index === 0 ? "\n\tLights:" : "");
  61820. log += "\n\t\t" + light.toString(fullDetails);
  61821. }
  61822. }
  61823. }
  61824. // Animations
  61825. if (parsedData.animations !== undefined && parsedData.animations !== null) {
  61826. for (index = 0, cache = parsedData.animations.length; index < cache; index++) {
  61827. var parsedAnimation = parsedData.animations[index];
  61828. var animation = BABYLON.Animation.Parse(parsedAnimation);
  61829. scene.animations.push(animation);
  61830. container.animations.push(animation);
  61831. log += (index === 0 ? "\n\tAnimations:" : "");
  61832. log += "\n\t\t" + animation.toString(fullDetails);
  61833. }
  61834. }
  61835. // Materials
  61836. if (parsedData.materials !== undefined && parsedData.materials !== null) {
  61837. for (index = 0, cache = parsedData.materials.length; index < cache; index++) {
  61838. var parsedMaterial = parsedData.materials[index];
  61839. var mat = BABYLON.Material.Parse(parsedMaterial, scene, rootUrl);
  61840. container.materials.push(mat);
  61841. log += (index === 0 ? "\n\tMaterials:" : "");
  61842. log += "\n\t\t" + mat.toString(fullDetails);
  61843. }
  61844. }
  61845. if (parsedData.multiMaterials !== undefined && parsedData.multiMaterials !== null) {
  61846. for (index = 0, cache = parsedData.multiMaterials.length; index < cache; index++) {
  61847. var parsedMultiMaterial = parsedData.multiMaterials[index];
  61848. var mmat = BABYLON.Material.ParseMultiMaterial(parsedMultiMaterial, scene);
  61849. container.multiMaterials.push(mmat);
  61850. log += (index === 0 ? "\n\tMultiMaterials:" : "");
  61851. log += "\n\t\t" + mmat.toString(fullDetails);
  61852. }
  61853. }
  61854. // Morph targets
  61855. if (parsedData.morphTargetManagers !== undefined && parsedData.morphTargetManagers !== null) {
  61856. for (var _i = 0, _a = parsedData.morphTargetManagers; _i < _a.length; _i++) {
  61857. var managerData = _a[_i];
  61858. container.morphTargetManagers.push(BABYLON.MorphTargetManager.Parse(managerData, scene));
  61859. }
  61860. }
  61861. // Skeletons
  61862. if (parsedData.skeletons !== undefined && parsedData.skeletons !== null) {
  61863. for (index = 0, cache = parsedData.skeletons.length; index < cache; index++) {
  61864. var parsedSkeleton = parsedData.skeletons[index];
  61865. var skeleton = BABYLON.Skeleton.Parse(parsedSkeleton, scene);
  61866. container.skeletons.push(skeleton);
  61867. log += (index === 0 ? "\n\tSkeletons:" : "");
  61868. log += "\n\t\t" + skeleton.toString(fullDetails);
  61869. }
  61870. }
  61871. // Geometries
  61872. var geometries = parsedData.geometries;
  61873. if (geometries !== undefined && geometries !== null) {
  61874. var addedGeometry = new Array();
  61875. // Boxes
  61876. var boxes = geometries.boxes;
  61877. if (boxes !== undefined && boxes !== null) {
  61878. for (index = 0, cache = boxes.length; index < cache; index++) {
  61879. var parsedBox = boxes[index];
  61880. addedGeometry.push(BABYLON.BoxGeometry.Parse(parsedBox, scene));
  61881. }
  61882. }
  61883. // Spheres
  61884. var spheres = geometries.spheres;
  61885. if (spheres !== undefined && spheres !== null) {
  61886. for (index = 0, cache = spheres.length; index < cache; index++) {
  61887. var parsedSphere = spheres[index];
  61888. addedGeometry.push(BABYLON.SphereGeometry.Parse(parsedSphere, scene));
  61889. }
  61890. }
  61891. // Cylinders
  61892. var cylinders = geometries.cylinders;
  61893. if (cylinders !== undefined && cylinders !== null) {
  61894. for (index = 0, cache = cylinders.length; index < cache; index++) {
  61895. var parsedCylinder = cylinders[index];
  61896. addedGeometry.push(BABYLON.CylinderGeometry.Parse(parsedCylinder, scene));
  61897. }
  61898. }
  61899. // Toruses
  61900. var toruses = geometries.toruses;
  61901. if (toruses !== undefined && toruses !== null) {
  61902. for (index = 0, cache = toruses.length; index < cache; index++) {
  61903. var parsedTorus = toruses[index];
  61904. addedGeometry.push(BABYLON.TorusGeometry.Parse(parsedTorus, scene));
  61905. }
  61906. }
  61907. // Grounds
  61908. var grounds = geometries.grounds;
  61909. if (grounds !== undefined && grounds !== null) {
  61910. for (index = 0, cache = grounds.length; index < cache; index++) {
  61911. var parsedGround = grounds[index];
  61912. addedGeometry.push(BABYLON.GroundGeometry.Parse(parsedGround, scene));
  61913. }
  61914. }
  61915. // Planes
  61916. var planes = geometries.planes;
  61917. if (planes !== undefined && planes !== null) {
  61918. for (index = 0, cache = planes.length; index < cache; index++) {
  61919. var parsedPlane = planes[index];
  61920. addedGeometry.push(BABYLON.PlaneGeometry.Parse(parsedPlane, scene));
  61921. }
  61922. }
  61923. // TorusKnots
  61924. var torusKnots = geometries.torusKnots;
  61925. if (torusKnots !== undefined && torusKnots !== null) {
  61926. for (index = 0, cache = torusKnots.length; index < cache; index++) {
  61927. var parsedTorusKnot = torusKnots[index];
  61928. addedGeometry.push(BABYLON.TorusKnotGeometry.Parse(parsedTorusKnot, scene));
  61929. }
  61930. }
  61931. // VertexData
  61932. var vertexData = geometries.vertexData;
  61933. if (vertexData !== undefined && vertexData !== null) {
  61934. for (index = 0, cache = vertexData.length; index < cache; index++) {
  61935. var parsedVertexData = vertexData[index];
  61936. addedGeometry.push(BABYLON.Geometry.Parse(parsedVertexData, scene, rootUrl));
  61937. }
  61938. }
  61939. addedGeometry.forEach(function (g) {
  61940. if (g) {
  61941. container.geometries.push(g);
  61942. }
  61943. });
  61944. }
  61945. // Transform nodes
  61946. if (parsedData.transformNodes !== undefined && parsedData.transformNodes !== null) {
  61947. for (index = 0, cache = parsedData.transformNodes.length; index < cache; index++) {
  61948. var parsedTransformNode = parsedData.transformNodes[index];
  61949. var node = BABYLON.TransformNode.Parse(parsedTransformNode, scene, rootUrl);
  61950. container.transformNodes.push(node);
  61951. }
  61952. }
  61953. // Meshes
  61954. if (parsedData.meshes !== undefined && parsedData.meshes !== null) {
  61955. for (index = 0, cache = parsedData.meshes.length; index < cache; index++) {
  61956. var parsedMesh = parsedData.meshes[index];
  61957. var mesh = BABYLON.Mesh.Parse(parsedMesh, scene, rootUrl);
  61958. container.meshes.push(mesh);
  61959. log += (index === 0 ? "\n\tMeshes:" : "");
  61960. log += "\n\t\t" + mesh.toString(fullDetails);
  61961. }
  61962. }
  61963. // Cameras
  61964. if (parsedData.cameras !== undefined && parsedData.cameras !== null) {
  61965. for (index = 0, cache = parsedData.cameras.length; index < cache; index++) {
  61966. var parsedCamera = parsedData.cameras[index];
  61967. var camera = BABYLON.Camera.Parse(parsedCamera, scene);
  61968. container.cameras.push(camera);
  61969. log += (index === 0 ? "\n\tCameras:" : "");
  61970. log += "\n\t\t" + camera.toString(fullDetails);
  61971. }
  61972. }
  61973. // Browsing all the graph to connect the dots
  61974. for (index = 0, cache = scene.cameras.length; index < cache; index++) {
  61975. var camera = scene.cameras[index];
  61976. if (camera._waitingParentId) {
  61977. camera.parent = scene.getLastEntryByID(camera._waitingParentId);
  61978. camera._waitingParentId = null;
  61979. }
  61980. }
  61981. for (index = 0, cache = scene.lights.length; index < cache; index++) {
  61982. var light_1 = scene.lights[index];
  61983. if (light_1 && light_1._waitingParentId) {
  61984. light_1.parent = scene.getLastEntryByID(light_1._waitingParentId);
  61985. light_1._waitingParentId = null;
  61986. }
  61987. }
  61988. // Sounds
  61989. // TODO: add sound
  61990. var loadedSounds = [];
  61991. var loadedSound;
  61992. if (BABYLON.AudioEngine && parsedData.sounds !== undefined && parsedData.sounds !== null) {
  61993. for (index = 0, cache = parsedData.sounds.length; index < cache; index++) {
  61994. var parsedSound = parsedData.sounds[index];
  61995. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  61996. if (!parsedSound.url)
  61997. parsedSound.url = parsedSound.name;
  61998. if (!loadedSounds[parsedSound.url]) {
  61999. loadedSound = BABYLON.Sound.Parse(parsedSound, scene, rootUrl);
  62000. loadedSounds[parsedSound.url] = loadedSound;
  62001. container.sounds.push(loadedSound);
  62002. }
  62003. else {
  62004. container.sounds.push(BABYLON.Sound.Parse(parsedSound, scene, rootUrl, loadedSounds[parsedSound.url]));
  62005. }
  62006. }
  62007. else {
  62008. container.sounds.push(new BABYLON.Sound(parsedSound.name, null, scene));
  62009. }
  62010. }
  62011. }
  62012. loadedSounds = [];
  62013. // Connect parents & children and parse actions
  62014. for (index = 0, cache = scene.transformNodes.length; index < cache; index++) {
  62015. var transformNode = scene.transformNodes[index];
  62016. if (transformNode._waitingParentId) {
  62017. transformNode.parent = scene.getLastEntryByID(transformNode._waitingParentId);
  62018. transformNode._waitingParentId = null;
  62019. }
  62020. }
  62021. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  62022. var mesh = scene.meshes[index];
  62023. if (mesh._waitingParentId) {
  62024. mesh.parent = scene.getLastEntryByID(mesh._waitingParentId);
  62025. mesh._waitingParentId = null;
  62026. }
  62027. if (mesh._waitingActions) {
  62028. BABYLON.ActionManager.Parse(mesh._waitingActions, mesh, scene);
  62029. mesh._waitingActions = null;
  62030. }
  62031. }
  62032. // freeze world matrix application
  62033. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  62034. var currentMesh = scene.meshes[index];
  62035. if (currentMesh._waitingFreezeWorldMatrix) {
  62036. currentMesh.freezeWorldMatrix();
  62037. currentMesh._waitingFreezeWorldMatrix = null;
  62038. }
  62039. else {
  62040. currentMesh.computeWorldMatrix(true);
  62041. }
  62042. }
  62043. // Particles Systems
  62044. if (parsedData.particleSystems !== undefined && parsedData.particleSystems !== null) {
  62045. for (index = 0, cache = parsedData.particleSystems.length; index < cache; index++) {
  62046. var parsedParticleSystem = parsedData.particleSystems[index];
  62047. if (parsedParticleSystem.activeParticleCount) {
  62048. var ps = BABYLON.GPUParticleSystem.Parse(parsedParticleSystem, scene, rootUrl);
  62049. container.particleSystems.push(ps);
  62050. }
  62051. else {
  62052. var ps = BABYLON.ParticleSystem.Parse(parsedParticleSystem, scene, rootUrl);
  62053. container.particleSystems.push(ps);
  62054. }
  62055. }
  62056. }
  62057. // Lens flares
  62058. if (parsedData.lensFlareSystems !== undefined && parsedData.lensFlareSystems !== null) {
  62059. for (index = 0, cache = parsedData.lensFlareSystems.length; index < cache; index++) {
  62060. var parsedLensFlareSystem = parsedData.lensFlareSystems[index];
  62061. var lf = BABYLON.LensFlareSystem.Parse(parsedLensFlareSystem, scene, rootUrl);
  62062. container.lensFlareSystems.push(lf);
  62063. }
  62064. }
  62065. // Shadows
  62066. if (parsedData.shadowGenerators !== undefined && parsedData.shadowGenerators !== null) {
  62067. for (index = 0, cache = parsedData.shadowGenerators.length; index < cache; index++) {
  62068. var parsedShadowGenerator = parsedData.shadowGenerators[index];
  62069. var sg = BABYLON.ShadowGenerator.Parse(parsedShadowGenerator, scene);
  62070. container.shadowGenerators.push(sg);
  62071. }
  62072. }
  62073. // Lights exclusions / inclusions
  62074. for (index = 0, cache = scene.lights.length; index < cache; index++) {
  62075. var light_2 = scene.lights[index];
  62076. // Excluded check
  62077. if (light_2._excludedMeshesIds.length > 0) {
  62078. for (var excludedIndex = 0; excludedIndex < light_2._excludedMeshesIds.length; excludedIndex++) {
  62079. var excludedMesh = scene.getMeshByID(light_2._excludedMeshesIds[excludedIndex]);
  62080. if (excludedMesh) {
  62081. light_2.excludedMeshes.push(excludedMesh);
  62082. }
  62083. }
  62084. light_2._excludedMeshesIds = [];
  62085. }
  62086. // Included check
  62087. if (light_2._includedOnlyMeshesIds.length > 0) {
  62088. for (var includedOnlyIndex = 0; includedOnlyIndex < light_2._includedOnlyMeshesIds.length; includedOnlyIndex++) {
  62089. var includedOnlyMesh = scene.getMeshByID(light_2._includedOnlyMeshesIds[includedOnlyIndex]);
  62090. if (includedOnlyMesh) {
  62091. light_2.includedOnlyMeshes.push(includedOnlyMesh);
  62092. }
  62093. }
  62094. light_2._includedOnlyMeshesIds = [];
  62095. }
  62096. }
  62097. // Actions (scene)
  62098. if (parsedData.actions !== undefined && parsedData.actions !== null) {
  62099. BABYLON.ActionManager.Parse(parsedData.actions, null, scene);
  62100. }
  62101. if (!addToScene) {
  62102. container.removeAllFromScene();
  62103. }
  62104. }
  62105. catch (err) {
  62106. var msg = logOperation("loadAssts", parsedData ? parsedData.producer : "Unknown") + log;
  62107. if (onError) {
  62108. onError(msg, err);
  62109. }
  62110. else {
  62111. BABYLON.Tools.Log(msg);
  62112. throw err;
  62113. }
  62114. }
  62115. finally {
  62116. if (log !== null && BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.NO_LOGGING) {
  62117. BABYLON.Tools.Log(logOperation("loadAssts", parsedData ? parsedData.producer : "Unknown") + (BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.MINIMAL_LOGGING ? log : ""));
  62118. }
  62119. }
  62120. return container;
  62121. };
  62122. BABYLON.SceneLoader.RegisterPlugin({
  62123. name: "babylon.js",
  62124. extensions: ".babylon",
  62125. canDirectLoad: function (data) {
  62126. if (data.indexOf("babylon") !== -1) {
  62127. return true;
  62128. }
  62129. return false;
  62130. },
  62131. importMesh: function (meshesNames, scene, data, rootUrl, meshes, particleSystems, skeletons, onError) {
  62132. // Entire method running in try block, so ALWAYS logs as far as it got, only actually writes details
  62133. // when SceneLoader.debugLogging = true (default), or exception encountered.
  62134. // Everything stored in var log instead of writing separate lines to support only writing in exception,
  62135. // and avoid problems with multiple concurrent .babylon loads.
  62136. var log = "importMesh has failed JSON parse";
  62137. try {
  62138. var parsedData = JSON.parse(data);
  62139. log = "";
  62140. var fullDetails = BABYLON.SceneLoader.loggingLevel === BABYLON.SceneLoader.DETAILED_LOGGING;
  62141. if (!meshesNames) {
  62142. meshesNames = null;
  62143. }
  62144. else if (!Array.isArray(meshesNames)) {
  62145. meshesNames = [meshesNames];
  62146. }
  62147. var hierarchyIds = new Array();
  62148. if (parsedData.meshes !== undefined && parsedData.meshes !== null) {
  62149. var loadedSkeletonsIds = [];
  62150. var loadedMaterialsIds = [];
  62151. var index;
  62152. var cache;
  62153. for (index = 0, cache = parsedData.meshes.length; index < cache; index++) {
  62154. var parsedMesh = parsedData.meshes[index];
  62155. if (meshesNames === null || isDescendantOf(parsedMesh, meshesNames, hierarchyIds)) {
  62156. if (meshesNames !== null) {
  62157. // Remove found mesh name from list.
  62158. delete meshesNames[meshesNames.indexOf(parsedMesh.name)];
  62159. }
  62160. //Geometry?
  62161. if (parsedMesh.geometryId !== undefined && parsedMesh.geometryId !== null) {
  62162. //does the file contain geometries?
  62163. if (parsedData.geometries !== undefined && parsedData.geometries !== null) {
  62164. //find the correct geometry and add it to the scene
  62165. var found = false;
  62166. ["boxes", "spheres", "cylinders", "toruses", "grounds", "planes", "torusKnots", "vertexData"].forEach(function (geometryType) {
  62167. if (found === true || !parsedData.geometries[geometryType] || !(Array.isArray(parsedData.geometries[geometryType]))) {
  62168. return;
  62169. }
  62170. else {
  62171. parsedData.geometries[geometryType].forEach(function (parsedGeometryData) {
  62172. if (parsedGeometryData.id === parsedMesh.geometryId) {
  62173. switch (geometryType) {
  62174. case "boxes":
  62175. BABYLON.BoxGeometry.Parse(parsedGeometryData, scene);
  62176. break;
  62177. case "spheres":
  62178. BABYLON.SphereGeometry.Parse(parsedGeometryData, scene);
  62179. break;
  62180. case "cylinders":
  62181. BABYLON.CylinderGeometry.Parse(parsedGeometryData, scene);
  62182. break;
  62183. case "toruses":
  62184. BABYLON.TorusGeometry.Parse(parsedGeometryData, scene);
  62185. break;
  62186. case "grounds":
  62187. BABYLON.GroundGeometry.Parse(parsedGeometryData, scene);
  62188. break;
  62189. case "planes":
  62190. BABYLON.PlaneGeometry.Parse(parsedGeometryData, scene);
  62191. break;
  62192. case "torusKnots":
  62193. BABYLON.TorusKnotGeometry.Parse(parsedGeometryData, scene);
  62194. break;
  62195. case "vertexData":
  62196. BABYLON.Geometry.Parse(parsedGeometryData, scene, rootUrl);
  62197. break;
  62198. }
  62199. found = true;
  62200. }
  62201. });
  62202. }
  62203. });
  62204. if (found === false) {
  62205. BABYLON.Tools.Warn("Geometry not found for mesh " + parsedMesh.id);
  62206. }
  62207. }
  62208. }
  62209. // Material ?
  62210. if (parsedMesh.materialId) {
  62211. var materialFound = (loadedMaterialsIds.indexOf(parsedMesh.materialId) !== -1);
  62212. if (materialFound === false && parsedData.multiMaterials !== undefined && parsedData.multiMaterials !== null) {
  62213. for (var multimatIndex = 0, multimatCache = parsedData.multiMaterials.length; multimatIndex < multimatCache; multimatIndex++) {
  62214. var parsedMultiMaterial = parsedData.multiMaterials[multimatIndex];
  62215. if (parsedMultiMaterial.id === parsedMesh.materialId) {
  62216. for (var matIndex = 0, matCache = parsedMultiMaterial.materials.length; matIndex < matCache; matIndex++) {
  62217. var subMatId = parsedMultiMaterial.materials[matIndex];
  62218. loadedMaterialsIds.push(subMatId);
  62219. var mat = parseMaterialById(subMatId, parsedData, scene, rootUrl);
  62220. if (mat) {
  62221. log += "\n\tMaterial " + mat.toString(fullDetails);
  62222. }
  62223. }
  62224. loadedMaterialsIds.push(parsedMultiMaterial.id);
  62225. var mmat = BABYLON.Material.ParseMultiMaterial(parsedMultiMaterial, scene);
  62226. if (mmat) {
  62227. materialFound = true;
  62228. log += "\n\tMulti-Material " + mmat.toString(fullDetails);
  62229. }
  62230. break;
  62231. }
  62232. }
  62233. }
  62234. if (materialFound === false) {
  62235. loadedMaterialsIds.push(parsedMesh.materialId);
  62236. var mat = parseMaterialById(parsedMesh.materialId, parsedData, scene, rootUrl);
  62237. if (!mat) {
  62238. BABYLON.Tools.Warn("Material not found for mesh " + parsedMesh.id);
  62239. }
  62240. else {
  62241. log += "\n\tMaterial " + mat.toString(fullDetails);
  62242. }
  62243. }
  62244. }
  62245. // Skeleton ?
  62246. if (parsedMesh.skeletonId > -1 && parsedData.skeletons !== undefined && parsedData.skeletons !== null) {
  62247. var skeletonAlreadyLoaded = (loadedSkeletonsIds.indexOf(parsedMesh.skeletonId) > -1);
  62248. if (skeletonAlreadyLoaded === false) {
  62249. for (var skeletonIndex = 0, skeletonCache = parsedData.skeletons.length; skeletonIndex < skeletonCache; skeletonIndex++) {
  62250. var parsedSkeleton = parsedData.skeletons[skeletonIndex];
  62251. if (parsedSkeleton.id === parsedMesh.skeletonId) {
  62252. var skeleton = BABYLON.Skeleton.Parse(parsedSkeleton, scene);
  62253. skeletons.push(skeleton);
  62254. loadedSkeletonsIds.push(parsedSkeleton.id);
  62255. log += "\n\tSkeleton " + skeleton.toString(fullDetails);
  62256. }
  62257. }
  62258. }
  62259. }
  62260. var mesh = BABYLON.Mesh.Parse(parsedMesh, scene, rootUrl);
  62261. meshes.push(mesh);
  62262. log += "\n\tMesh " + mesh.toString(fullDetails);
  62263. }
  62264. }
  62265. // Connecting parents
  62266. var currentMesh;
  62267. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  62268. currentMesh = scene.meshes[index];
  62269. if (currentMesh._waitingParentId) {
  62270. currentMesh.parent = scene.getLastEntryByID(currentMesh._waitingParentId);
  62271. currentMesh._waitingParentId = null;
  62272. }
  62273. }
  62274. // freeze and compute world matrix application
  62275. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  62276. currentMesh = scene.meshes[index];
  62277. if (currentMesh._waitingFreezeWorldMatrix) {
  62278. currentMesh.freezeWorldMatrix();
  62279. currentMesh._waitingFreezeWorldMatrix = null;
  62280. }
  62281. else {
  62282. currentMesh.computeWorldMatrix(true);
  62283. }
  62284. }
  62285. }
  62286. // Particles
  62287. if (parsedData.particleSystems !== undefined && parsedData.particleSystems !== null) {
  62288. for (index = 0, cache = parsedData.particleSystems.length; index < cache; index++) {
  62289. var parsedParticleSystem = parsedData.particleSystems[index];
  62290. if (hierarchyIds.indexOf(parsedParticleSystem.emitterId) !== -1) {
  62291. particleSystems.push(BABYLON.ParticleSystem.Parse(parsedParticleSystem, scene, rootUrl));
  62292. }
  62293. }
  62294. }
  62295. return true;
  62296. }
  62297. catch (err) {
  62298. var msg = logOperation("importMesh", parsedData ? parsedData.producer : "Unknown") + log;
  62299. if (onError) {
  62300. onError(msg, err);
  62301. }
  62302. else {
  62303. BABYLON.Tools.Log(msg);
  62304. throw err;
  62305. }
  62306. }
  62307. finally {
  62308. if (log !== null && BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.NO_LOGGING) {
  62309. BABYLON.Tools.Log(logOperation("importMesh", parsedData ? parsedData.producer : "Unknown") + (BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.MINIMAL_LOGGING ? log : ""));
  62310. }
  62311. }
  62312. return false;
  62313. },
  62314. load: function (scene, data, rootUrl, onError) {
  62315. // Entire method running in try block, so ALWAYS logs as far as it got, only actually writes details
  62316. // when SceneLoader.debugLogging = true (default), or exception encountered.
  62317. // Everything stored in var log instead of writing separate lines to support only writing in exception,
  62318. // and avoid problems with multiple concurrent .babylon loads.
  62319. var log = "importScene has failed JSON parse";
  62320. try {
  62321. var parsedData = JSON.parse(data);
  62322. log = "";
  62323. // Scene
  62324. if (parsedData.useDelayedTextureLoading !== undefined && parsedData.useDelayedTextureLoading !== null) {
  62325. scene.useDelayedTextureLoading = parsedData.useDelayedTextureLoading && !BABYLON.SceneLoader.ForceFullSceneLoadingForIncremental;
  62326. }
  62327. if (parsedData.autoClear !== undefined && parsedData.autoClear !== null) {
  62328. scene.autoClear = parsedData.autoClear;
  62329. }
  62330. if (parsedData.clearColor !== undefined && parsedData.clearColor !== null) {
  62331. scene.clearColor = BABYLON.Color4.FromArray(parsedData.clearColor);
  62332. }
  62333. if (parsedData.ambientColor !== undefined && parsedData.ambientColor !== null) {
  62334. scene.ambientColor = BABYLON.Color3.FromArray(parsedData.ambientColor);
  62335. }
  62336. if (parsedData.gravity !== undefined && parsedData.gravity !== null) {
  62337. scene.gravity = BABYLON.Vector3.FromArray(parsedData.gravity);
  62338. }
  62339. // Fog
  62340. if (parsedData.fogMode && parsedData.fogMode !== 0) {
  62341. scene.fogMode = parsedData.fogMode;
  62342. scene.fogColor = BABYLON.Color3.FromArray(parsedData.fogColor);
  62343. scene.fogStart = parsedData.fogStart;
  62344. scene.fogEnd = parsedData.fogEnd;
  62345. scene.fogDensity = parsedData.fogDensity;
  62346. log += "\tFog mode for scene: ";
  62347. switch (scene.fogMode) {
  62348. // getters not compiling, so using hardcoded
  62349. case 1:
  62350. log += "exp\n";
  62351. break;
  62352. case 2:
  62353. log += "exp2\n";
  62354. break;
  62355. case 3:
  62356. log += "linear\n";
  62357. break;
  62358. }
  62359. }
  62360. //Physics
  62361. if (parsedData.physicsEnabled) {
  62362. var physicsPlugin;
  62363. if (parsedData.physicsEngine === "cannon") {
  62364. physicsPlugin = new BABYLON.CannonJSPlugin();
  62365. }
  62366. else if (parsedData.physicsEngine === "oimo") {
  62367. physicsPlugin = new BABYLON.OimoJSPlugin();
  62368. }
  62369. log = "\tPhysics engine " + (parsedData.physicsEngine ? parsedData.physicsEngine : "oimo") + " enabled\n";
  62370. //else - default engine, which is currently oimo
  62371. var physicsGravity = parsedData.physicsGravity ? BABYLON.Vector3.FromArray(parsedData.physicsGravity) : null;
  62372. scene.enablePhysics(physicsGravity, physicsPlugin);
  62373. }
  62374. // Metadata
  62375. if (parsedData.metadata !== undefined && parsedData.metadata !== null) {
  62376. scene.metadata = parsedData.metadata;
  62377. }
  62378. //collisions, if defined. otherwise, default is true
  62379. if (parsedData.collisionsEnabled !== undefined && parsedData.collisionsEnabled !== null) {
  62380. scene.collisionsEnabled = parsedData.collisionsEnabled;
  62381. }
  62382. scene.workerCollisions = !!parsedData.workerCollisions;
  62383. var container = loadAssetContainer(scene, data, rootUrl, onError, true);
  62384. if (!container) {
  62385. return false;
  62386. }
  62387. if (parsedData.autoAnimate) {
  62388. scene.beginAnimation(scene, parsedData.autoAnimateFrom, parsedData.autoAnimateTo, parsedData.autoAnimateLoop, parsedData.autoAnimateSpeed || 1.0);
  62389. }
  62390. if (parsedData.activeCameraID !== undefined && parsedData.activeCameraID !== null) {
  62391. scene.setActiveCameraByID(parsedData.activeCameraID);
  62392. }
  62393. // Environment texture
  62394. if (parsedData.environmentTexture !== undefined && parsedData.environmentTexture !== null) {
  62395. scene.environmentTexture = BABYLON.CubeTexture.CreateFromPrefilteredData(rootUrl + parsedData.environmentTexture, scene);
  62396. if (parsedData.createDefaultSkybox === true) {
  62397. var skyboxScale = (scene.activeCamera !== undefined && scene.activeCamera !== null) ? (scene.activeCamera.maxZ - scene.activeCamera.minZ) / 2 : 1000;
  62398. var skyboxBlurLevel = parsedData.skyboxBlurLevel || 0;
  62399. scene.createDefaultSkybox(undefined, true, skyboxScale, skyboxBlurLevel);
  62400. }
  62401. }
  62402. // Finish
  62403. return true;
  62404. }
  62405. catch (err) {
  62406. var msg = logOperation("importScene", parsedData ? parsedData.producer : "Unknown") + log;
  62407. if (onError) {
  62408. onError(msg, err);
  62409. }
  62410. else {
  62411. BABYLON.Tools.Log(msg);
  62412. throw err;
  62413. }
  62414. }
  62415. finally {
  62416. if (log !== null && BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.NO_LOGGING) {
  62417. BABYLON.Tools.Log(logOperation("importScene", parsedData ? parsedData.producer : "Unknown") + (BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.MINIMAL_LOGGING ? log : ""));
  62418. }
  62419. }
  62420. return false;
  62421. },
  62422. loadAssetContainer: function (scene, data, rootUrl, onError) {
  62423. var container = loadAssetContainer(scene, data, rootUrl, onError);
  62424. return container;
  62425. }
  62426. });
  62427. })(BABYLON || (BABYLON = {}));
  62428. //# sourceMappingURL=babylon.babylonFileLoader.js.map
  62429. var BABYLON;
  62430. (function (BABYLON) {
  62431. var FilesInput = /** @class */ (function () {
  62432. function FilesInput(engine, scene, sceneLoadedCallback, progressCallback, additionalRenderLoopLogicCallback, textureLoadingCallback, startingProcessingFilesCallback, onReloadCallback, errorCallback) {
  62433. this.onProcessFileCallback = function () { return true; };
  62434. this._engine = engine;
  62435. this._currentScene = scene;
  62436. this._sceneLoadedCallback = sceneLoadedCallback;
  62437. this._progressCallback = progressCallback;
  62438. this._additionalRenderLoopLogicCallback = additionalRenderLoopLogicCallback;
  62439. this._textureLoadingCallback = textureLoadingCallback;
  62440. this._startingProcessingFilesCallback = startingProcessingFilesCallback;
  62441. this._onReloadCallback = onReloadCallback;
  62442. this._errorCallback = errorCallback;
  62443. }
  62444. FilesInput.prototype.monitorElementForDragNDrop = function (elementToMonitor) {
  62445. var _this = this;
  62446. if (elementToMonitor) {
  62447. this._elementToMonitor = elementToMonitor;
  62448. this._dragEnterHandler = function (e) { _this.drag(e); };
  62449. this._dragOverHandler = function (e) { _this.drag(e); };
  62450. this._dropHandler = function (e) { _this.drop(e); };
  62451. this._elementToMonitor.addEventListener("dragenter", this._dragEnterHandler, false);
  62452. this._elementToMonitor.addEventListener("dragover", this._dragOverHandler, false);
  62453. this._elementToMonitor.addEventListener("drop", this._dropHandler, false);
  62454. }
  62455. };
  62456. FilesInput.prototype.dispose = function () {
  62457. if (!this._elementToMonitor) {
  62458. return;
  62459. }
  62460. this._elementToMonitor.removeEventListener("dragenter", this._dragEnterHandler);
  62461. this._elementToMonitor.removeEventListener("dragover", this._dragOverHandler);
  62462. this._elementToMonitor.removeEventListener("drop", this._dropHandler);
  62463. };
  62464. FilesInput.prototype.renderFunction = function () {
  62465. if (this._additionalRenderLoopLogicCallback) {
  62466. this._additionalRenderLoopLogicCallback();
  62467. }
  62468. if (this._currentScene) {
  62469. if (this._textureLoadingCallback) {
  62470. var remaining = this._currentScene.getWaitingItemsCount();
  62471. if (remaining > 0) {
  62472. this._textureLoadingCallback(remaining);
  62473. }
  62474. }
  62475. this._currentScene.render();
  62476. }
  62477. };
  62478. FilesInput.prototype.drag = function (e) {
  62479. e.stopPropagation();
  62480. e.preventDefault();
  62481. };
  62482. FilesInput.prototype.drop = function (eventDrop) {
  62483. eventDrop.stopPropagation();
  62484. eventDrop.preventDefault();
  62485. this.loadFiles(eventDrop);
  62486. };
  62487. FilesInput.prototype._traverseFolder = function (folder, files, remaining, callback) {
  62488. var _this = this;
  62489. var reader = folder.createReader();
  62490. var relativePath = folder.fullPath.replace(/^\//, "").replace(/(.+?)\/?$/, "$1/");
  62491. reader.readEntries(function (entries) {
  62492. remaining.count += entries.length;
  62493. for (var _i = 0, entries_1 = entries; _i < entries_1.length; _i++) {
  62494. var entry = entries_1[_i];
  62495. if (entry.isFile) {
  62496. entry.file(function (file) {
  62497. file.correctName = relativePath + file.name;
  62498. files.push(file);
  62499. if (--remaining.count === 0) {
  62500. callback();
  62501. }
  62502. });
  62503. }
  62504. else if (entry.isDirectory) {
  62505. _this._traverseFolder(entry, files, remaining, callback);
  62506. }
  62507. }
  62508. if (--remaining.count) {
  62509. callback();
  62510. }
  62511. });
  62512. };
  62513. FilesInput.prototype._processFiles = function (files) {
  62514. for (var i = 0; i < files.length; i++) {
  62515. var name = files[i].correctName.toLowerCase();
  62516. var extension = name.split('.').pop();
  62517. if (!this.onProcessFileCallback(files[i], name, extension)) {
  62518. continue;
  62519. }
  62520. if ((extension === "babylon" || extension === "stl" || extension === "obj" || extension === "gltf" || extension === "glb")
  62521. && name.indexOf(".binary.babylon") === -1 && name.indexOf(".incremental.babylon") === -1) {
  62522. this._sceneFileToLoad = files[i];
  62523. }
  62524. else {
  62525. FilesInput.FilesToLoad[name] = files[i];
  62526. }
  62527. }
  62528. };
  62529. FilesInput.prototype.loadFiles = function (event) {
  62530. var _this = this;
  62531. if (this._startingProcessingFilesCallback)
  62532. this._startingProcessingFilesCallback();
  62533. // Handling data transfer via drag'n'drop
  62534. if (event && event.dataTransfer && event.dataTransfer.files) {
  62535. this._filesToLoad = event.dataTransfer.files;
  62536. }
  62537. // Handling files from input files
  62538. if (event && event.target && event.target.files) {
  62539. this._filesToLoad = event.target.files;
  62540. }
  62541. if (this._filesToLoad && this._filesToLoad.length > 0) {
  62542. var files_1 = new Array();
  62543. var folders = [];
  62544. var items = event.dataTransfer ? event.dataTransfer.items : null;
  62545. for (var i = 0; i < this._filesToLoad.length; i++) {
  62546. var fileToLoad = this._filesToLoad[i];
  62547. var name_1 = fileToLoad.name.toLowerCase();
  62548. var entry = void 0;
  62549. fileToLoad.correctName = name_1;
  62550. if (items) {
  62551. var item = items[i];
  62552. if (item.getAsEntry) {
  62553. entry = item.getAsEntry();
  62554. }
  62555. else if (item.webkitGetAsEntry) {
  62556. entry = item.webkitGetAsEntry();
  62557. }
  62558. }
  62559. if (!entry) {
  62560. files_1.push(fileToLoad);
  62561. }
  62562. else {
  62563. if (entry.isDirectory) {
  62564. folders.push(entry);
  62565. }
  62566. else {
  62567. files_1.push(fileToLoad);
  62568. }
  62569. }
  62570. }
  62571. if (folders.length === 0) {
  62572. this._processFiles(files_1);
  62573. this._processReload();
  62574. }
  62575. else {
  62576. var remaining = { count: folders.length };
  62577. for (var _i = 0, folders_1 = folders; _i < folders_1.length; _i++) {
  62578. var folder = folders_1[_i];
  62579. this._traverseFolder(folder, files_1, remaining, function () {
  62580. _this._processFiles(files_1);
  62581. if (remaining.count === 0) {
  62582. _this._processReload();
  62583. }
  62584. });
  62585. }
  62586. }
  62587. }
  62588. };
  62589. FilesInput.prototype._processReload = function () {
  62590. if (this._onReloadCallback) {
  62591. this._onReloadCallback(this._sceneFileToLoad);
  62592. }
  62593. else {
  62594. this.reload();
  62595. }
  62596. };
  62597. FilesInput.prototype.reload = function () {
  62598. var _this = this;
  62599. // If a scene file has been provided
  62600. if (this._sceneFileToLoad) {
  62601. if (this._currentScene) {
  62602. if (BABYLON.Tools.errorsCount > 0) {
  62603. BABYLON.Tools.ClearLogCache();
  62604. }
  62605. this._engine.stopRenderLoop();
  62606. this._currentScene.dispose();
  62607. }
  62608. BABYLON.SceneLoader.LoadAsync("file:", this._sceneFileToLoad, this._engine, function (progress) {
  62609. if (_this._progressCallback) {
  62610. _this._progressCallback(progress);
  62611. }
  62612. }).then(function (scene) {
  62613. _this._currentScene = scene;
  62614. if (_this._sceneLoadedCallback) {
  62615. _this._sceneLoadedCallback(_this._sceneFileToLoad, _this._currentScene);
  62616. }
  62617. // Wait for textures and shaders to be ready
  62618. _this._currentScene.executeWhenReady(function () {
  62619. _this._engine.runRenderLoop(function () {
  62620. _this.renderFunction();
  62621. });
  62622. });
  62623. }).catch(function (error) {
  62624. if (_this._errorCallback) {
  62625. _this._errorCallback(_this._sceneFileToLoad, _this._currentScene, error.message);
  62626. }
  62627. });
  62628. }
  62629. else {
  62630. BABYLON.Tools.Error("Please provide a valid .babylon file.");
  62631. }
  62632. };
  62633. FilesInput.FilesToLoad = {};
  62634. return FilesInput;
  62635. }());
  62636. BABYLON.FilesInput = FilesInput;
  62637. })(BABYLON || (BABYLON = {}));
  62638. //# sourceMappingURL=babylon.filesInput.js.map
  62639. var BABYLON;
  62640. (function (BABYLON) {
  62641. /**
  62642. * This class implement a typical dictionary using a string as key and the generic type T as value.
  62643. * The underlying implementation relies on an associative array to ensure the best performances.
  62644. * The value can be anything including 'null' but except 'undefined'
  62645. */
  62646. var StringDictionary = /** @class */ (function () {
  62647. function StringDictionary() {
  62648. this._count = 0;
  62649. this._data = {};
  62650. }
  62651. /**
  62652. * This will clear this dictionary and copy the content from the 'source' one.
  62653. * If the T value is a custom object, it won't be copied/cloned, the same object will be used
  62654. * @param source the dictionary to take the content from and copy to this dictionary
  62655. */
  62656. StringDictionary.prototype.copyFrom = function (source) {
  62657. var _this = this;
  62658. this.clear();
  62659. source.forEach(function (t, v) { return _this.add(t, v); });
  62660. };
  62661. /**
  62662. * Get a value based from its key
  62663. * @param key the given key to get the matching value from
  62664. * @return the value if found, otherwise undefined is returned
  62665. */
  62666. StringDictionary.prototype.get = function (key) {
  62667. var val = this._data[key];
  62668. if (val !== undefined) {
  62669. return val;
  62670. }
  62671. return undefined;
  62672. };
  62673. /**
  62674. * Get a value from its key or add it if it doesn't exist.
  62675. * This method will ensure you that a given key/data will be present in the dictionary.
  62676. * @param key the given key to get the matching value from
  62677. * @param factory the factory that will create the value if the key is not present in the dictionary.
  62678. * The factory will only be invoked if there's no data for the given key.
  62679. * @return the value corresponding to the key.
  62680. */
  62681. StringDictionary.prototype.getOrAddWithFactory = function (key, factory) {
  62682. var val = this.get(key);
  62683. if (val !== undefined) {
  62684. return val;
  62685. }
  62686. val = factory(key);
  62687. if (val) {
  62688. this.add(key, val);
  62689. }
  62690. return val;
  62691. };
  62692. /**
  62693. * Get a value from its key if present in the dictionary otherwise add it
  62694. * @param key the key to get the value from
  62695. * @param val if there's no such key/value pair in the dictionary add it with this value
  62696. * @return the value corresponding to the key
  62697. */
  62698. StringDictionary.prototype.getOrAdd = function (key, val) {
  62699. var curVal = this.get(key);
  62700. if (curVal !== undefined) {
  62701. return curVal;
  62702. }
  62703. this.add(key, val);
  62704. return val;
  62705. };
  62706. /**
  62707. * Check if there's a given key in the dictionary
  62708. * @param key the key to check for
  62709. * @return true if the key is present, false otherwise
  62710. */
  62711. StringDictionary.prototype.contains = function (key) {
  62712. return this._data[key] !== undefined;
  62713. };
  62714. /**
  62715. * Add a new key and its corresponding value
  62716. * @param key the key to add
  62717. * @param value the value corresponding to the key
  62718. * @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
  62719. */
  62720. StringDictionary.prototype.add = function (key, value) {
  62721. if (this._data[key] !== undefined) {
  62722. return false;
  62723. }
  62724. this._data[key] = value;
  62725. ++this._count;
  62726. return true;
  62727. };
  62728. StringDictionary.prototype.set = function (key, value) {
  62729. if (this._data[key] === undefined) {
  62730. return false;
  62731. }
  62732. this._data[key] = value;
  62733. return true;
  62734. };
  62735. /**
  62736. * Get the element of the given key and remove it from the dictionary
  62737. * @param key
  62738. */
  62739. StringDictionary.prototype.getAndRemove = function (key) {
  62740. var val = this.get(key);
  62741. if (val !== undefined) {
  62742. delete this._data[key];
  62743. --this._count;
  62744. return val;
  62745. }
  62746. return null;
  62747. };
  62748. /**
  62749. * Remove a key/value from the dictionary.
  62750. * @param key the key to remove
  62751. * @return true if the item was successfully deleted, false if no item with such key exist in the dictionary
  62752. */
  62753. StringDictionary.prototype.remove = function (key) {
  62754. if (this.contains(key)) {
  62755. delete this._data[key];
  62756. --this._count;
  62757. return true;
  62758. }
  62759. return false;
  62760. };
  62761. /**
  62762. * Clear the whole content of the dictionary
  62763. */
  62764. StringDictionary.prototype.clear = function () {
  62765. this._data = {};
  62766. this._count = 0;
  62767. };
  62768. Object.defineProperty(StringDictionary.prototype, "count", {
  62769. get: function () {
  62770. return this._count;
  62771. },
  62772. enumerable: true,
  62773. configurable: true
  62774. });
  62775. /**
  62776. * Execute a callback on each key/val of the dictionary.
  62777. * Note that you can remove any element in this dictionary in the callback implementation
  62778. * @param callback the callback to execute on a given key/value pair
  62779. */
  62780. StringDictionary.prototype.forEach = function (callback) {
  62781. for (var cur in this._data) {
  62782. var val = this._data[cur];
  62783. callback(cur, val);
  62784. }
  62785. };
  62786. /**
  62787. * Execute a callback on every occurrence of the dictionary until it returns a valid TRes object.
  62788. * If the callback returns null or undefined the method will iterate to the next key/value pair
  62789. * Note that you can remove any element in this dictionary in the callback implementation
  62790. * @param callback the callback to execute, if it return a valid T instanced object the enumeration will stop and the object will be returned
  62791. */
  62792. StringDictionary.prototype.first = function (callback) {
  62793. for (var cur in this._data) {
  62794. var val = this._data[cur];
  62795. var res = callback(cur, val);
  62796. if (res) {
  62797. return res;
  62798. }
  62799. }
  62800. return null;
  62801. };
  62802. return StringDictionary;
  62803. }());
  62804. BABYLON.StringDictionary = StringDictionary;
  62805. })(BABYLON || (BABYLON = {}));
  62806. //# sourceMappingURL=babylon.stringDictionary.js.map
  62807. var BABYLON;
  62808. (function (BABYLON) {
  62809. var Tags = /** @class */ (function () {
  62810. function Tags() {
  62811. }
  62812. Tags.EnableFor = function (obj) {
  62813. obj._tags = obj._tags || {};
  62814. obj.hasTags = function () {
  62815. return Tags.HasTags(obj);
  62816. };
  62817. obj.addTags = function (tagsString) {
  62818. return Tags.AddTagsTo(obj, tagsString);
  62819. };
  62820. obj.removeTags = function (tagsString) {
  62821. return Tags.RemoveTagsFrom(obj, tagsString);
  62822. };
  62823. obj.matchesTagsQuery = function (tagsQuery) {
  62824. return Tags.MatchesQuery(obj, tagsQuery);
  62825. };
  62826. };
  62827. Tags.DisableFor = function (obj) {
  62828. delete obj._tags;
  62829. delete obj.hasTags;
  62830. delete obj.addTags;
  62831. delete obj.removeTags;
  62832. delete obj.matchesTagsQuery;
  62833. };
  62834. Tags.HasTags = function (obj) {
  62835. if (!obj._tags) {
  62836. return false;
  62837. }
  62838. return !BABYLON.Tools.IsEmpty(obj._tags);
  62839. };
  62840. Tags.GetTags = function (obj, asString) {
  62841. if (asString === void 0) { asString = true; }
  62842. if (!obj._tags) {
  62843. return null;
  62844. }
  62845. if (asString) {
  62846. var tagsArray = [];
  62847. for (var tag in obj._tags) {
  62848. if (obj._tags.hasOwnProperty(tag) && obj._tags[tag] === true) {
  62849. tagsArray.push(tag);
  62850. }
  62851. }
  62852. return tagsArray.join(" ");
  62853. }
  62854. else {
  62855. return obj._tags;
  62856. }
  62857. };
  62858. // the tags 'true' and 'false' are reserved and cannot be used as tags
  62859. // a tag cannot start with '||', '&&', and '!'
  62860. // it cannot contain whitespaces
  62861. Tags.AddTagsTo = function (obj, tagsString) {
  62862. if (!tagsString) {
  62863. return;
  62864. }
  62865. if (typeof tagsString !== "string") {
  62866. return;
  62867. }
  62868. var tags = tagsString.split(" ");
  62869. tags.forEach(function (tag, index, array) {
  62870. Tags._AddTagTo(obj, tag);
  62871. });
  62872. };
  62873. Tags._AddTagTo = function (obj, tag) {
  62874. tag = tag.trim();
  62875. if (tag === "" || tag === "true" || tag === "false") {
  62876. return;
  62877. }
  62878. if (tag.match(/[\s]/) || tag.match(/^([!]|([|]|[&]){2})/)) {
  62879. return;
  62880. }
  62881. Tags.EnableFor(obj);
  62882. obj._tags[tag] = true;
  62883. };
  62884. Tags.RemoveTagsFrom = function (obj, tagsString) {
  62885. if (!Tags.HasTags(obj)) {
  62886. return;
  62887. }
  62888. var tags = tagsString.split(" ");
  62889. for (var t in tags) {
  62890. Tags._RemoveTagFrom(obj, tags[t]);
  62891. }
  62892. };
  62893. Tags._RemoveTagFrom = function (obj, tag) {
  62894. delete obj._tags[tag];
  62895. };
  62896. Tags.MatchesQuery = function (obj, tagsQuery) {
  62897. if (tagsQuery === undefined) {
  62898. return true;
  62899. }
  62900. if (tagsQuery === "") {
  62901. return Tags.HasTags(obj);
  62902. }
  62903. return BABYLON.AndOrNotEvaluator.Eval(tagsQuery, function (r) { return Tags.HasTags(obj) && obj._tags[r]; });
  62904. };
  62905. return Tags;
  62906. }());
  62907. BABYLON.Tags = Tags;
  62908. })(BABYLON || (BABYLON = {}));
  62909. //# sourceMappingURL=babylon.tags.js.map
  62910. var BABYLON;
  62911. (function (BABYLON) {
  62912. var AndOrNotEvaluator = /** @class */ (function () {
  62913. function AndOrNotEvaluator() {
  62914. }
  62915. AndOrNotEvaluator.Eval = function (query, evaluateCallback) {
  62916. if (!query.match(/\([^\(\)]*\)/g)) {
  62917. query = AndOrNotEvaluator._HandleParenthesisContent(query, evaluateCallback);
  62918. }
  62919. else {
  62920. query = query.replace(/\([^\(\)]*\)/g, function (r) {
  62921. // remove parenthesis
  62922. r = r.slice(1, r.length - 1);
  62923. return AndOrNotEvaluator._HandleParenthesisContent(r, evaluateCallback);
  62924. });
  62925. }
  62926. if (query === "true") {
  62927. return true;
  62928. }
  62929. if (query === "false") {
  62930. return false;
  62931. }
  62932. return AndOrNotEvaluator.Eval(query, evaluateCallback);
  62933. };
  62934. AndOrNotEvaluator._HandleParenthesisContent = function (parenthesisContent, evaluateCallback) {
  62935. evaluateCallback = evaluateCallback || (function (r) {
  62936. return r === "true" ? true : false;
  62937. });
  62938. var result;
  62939. var or = parenthesisContent.split("||");
  62940. for (var i in or) {
  62941. if (or.hasOwnProperty(i)) {
  62942. var ori = AndOrNotEvaluator._SimplifyNegation(or[i].trim());
  62943. var and = ori.split("&&");
  62944. if (and.length > 1) {
  62945. for (var j = 0; j < and.length; ++j) {
  62946. var andj = AndOrNotEvaluator._SimplifyNegation(and[j].trim());
  62947. if (andj !== "true" && andj !== "false") {
  62948. if (andj[0] === "!") {
  62949. result = !evaluateCallback(andj.substring(1));
  62950. }
  62951. else {
  62952. result = evaluateCallback(andj);
  62953. }
  62954. }
  62955. else {
  62956. result = andj === "true" ? true : false;
  62957. }
  62958. if (!result) {
  62959. ori = "false";
  62960. break;
  62961. }
  62962. }
  62963. }
  62964. if (result || ori === "true") {
  62965. result = true;
  62966. break;
  62967. }
  62968. // result equals false (or undefined)
  62969. if (ori !== "true" && ori !== "false") {
  62970. if (ori[0] === "!") {
  62971. result = !evaluateCallback(ori.substring(1));
  62972. }
  62973. else {
  62974. result = evaluateCallback(ori);
  62975. }
  62976. }
  62977. else {
  62978. result = ori === "true" ? true : false;
  62979. }
  62980. }
  62981. }
  62982. // the whole parenthesis scope is replaced by 'true' or 'false'
  62983. return result ? "true" : "false";
  62984. };
  62985. AndOrNotEvaluator._SimplifyNegation = function (booleanString) {
  62986. booleanString = booleanString.replace(/^[\s!]+/, function (r) {
  62987. // remove whitespaces
  62988. r = r.replace(/[\s]/g, function () { return ""; });
  62989. return r.length % 2 ? "!" : "";
  62990. });
  62991. booleanString = booleanString.trim();
  62992. if (booleanString === "!true") {
  62993. booleanString = "false";
  62994. }
  62995. else if (booleanString === "!false") {
  62996. booleanString = "true";
  62997. }
  62998. return booleanString;
  62999. };
  63000. return AndOrNotEvaluator;
  63001. }());
  63002. BABYLON.AndOrNotEvaluator = AndOrNotEvaluator;
  63003. })(BABYLON || (BABYLON = {}));
  63004. //# sourceMappingURL=babylon.andOrNotEvaluator.js.map
  63005. var BABYLON;
  63006. (function (BABYLON) {
  63007. var Database = /** @class */ (function () {
  63008. function Database(urlToScene, callbackManifestChecked) {
  63009. // Handling various flavors of prefixed version of IndexedDB
  63010. this.idbFactory = (window.indexedDB || window.mozIndexedDB || window.webkitIndexedDB || window.msIndexedDB);
  63011. this.callbackManifestChecked = callbackManifestChecked;
  63012. this.currentSceneUrl = Database.ReturnFullUrlLocation(urlToScene);
  63013. this.db = null;
  63014. this._enableSceneOffline = false;
  63015. this._enableTexturesOffline = false;
  63016. this.manifestVersionFound = 0;
  63017. this.mustUpdateRessources = false;
  63018. this.hasReachedQuota = false;
  63019. if (!Database.IDBStorageEnabled) {
  63020. this.callbackManifestChecked(true);
  63021. }
  63022. else {
  63023. this.checkManifestFile();
  63024. }
  63025. }
  63026. Object.defineProperty(Database.prototype, "enableSceneOffline", {
  63027. get: function () {
  63028. return this._enableSceneOffline;
  63029. },
  63030. enumerable: true,
  63031. configurable: true
  63032. });
  63033. Object.defineProperty(Database.prototype, "enableTexturesOffline", {
  63034. get: function () {
  63035. return this._enableTexturesOffline;
  63036. },
  63037. enumerable: true,
  63038. configurable: true
  63039. });
  63040. Database.prototype.checkManifestFile = function () {
  63041. var _this = this;
  63042. var noManifestFile = function () {
  63043. _this._enableSceneOffline = false;
  63044. _this._enableTexturesOffline = false;
  63045. _this.callbackManifestChecked(false);
  63046. };
  63047. var timeStampUsed = false;
  63048. var manifestURL = this.currentSceneUrl + ".manifest";
  63049. var xhr = new XMLHttpRequest();
  63050. if (navigator.onLine) {
  63051. // Adding a timestamp to by-pass browsers' cache
  63052. timeStampUsed = true;
  63053. manifestURL = manifestURL + (manifestURL.match(/\?/) == null ? "?" : "&") + (new Date()).getTime();
  63054. }
  63055. xhr.open("GET", manifestURL, true);
  63056. xhr.addEventListener("load", function () {
  63057. if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, 1)) {
  63058. try {
  63059. var manifestFile = JSON.parse(xhr.response);
  63060. _this._enableSceneOffline = manifestFile.enableSceneOffline;
  63061. _this._enableTexturesOffline = manifestFile.enableTexturesOffline;
  63062. if (manifestFile.version && !isNaN(parseInt(manifestFile.version))) {
  63063. _this.manifestVersionFound = manifestFile.version;
  63064. }
  63065. if (_this.callbackManifestChecked) {
  63066. _this.callbackManifestChecked(true);
  63067. }
  63068. }
  63069. catch (ex) {
  63070. noManifestFile();
  63071. }
  63072. }
  63073. else {
  63074. noManifestFile();
  63075. }
  63076. }, false);
  63077. xhr.addEventListener("error", function (event) {
  63078. if (timeStampUsed) {
  63079. timeStampUsed = false;
  63080. // Let's retry without the timeStamp
  63081. // It could fail when coupled with HTML5 Offline API
  63082. var retryManifestURL = _this.currentSceneUrl + ".manifest";
  63083. xhr.open("GET", retryManifestURL, true);
  63084. xhr.send();
  63085. }
  63086. else {
  63087. noManifestFile();
  63088. }
  63089. }, false);
  63090. try {
  63091. xhr.send();
  63092. }
  63093. catch (ex) {
  63094. BABYLON.Tools.Error("Error on XHR send request.");
  63095. this.callbackManifestChecked(false);
  63096. }
  63097. };
  63098. Database.prototype.openAsync = function (successCallback, errorCallback) {
  63099. var _this = this;
  63100. var handleError = function () {
  63101. _this.isSupported = false;
  63102. if (errorCallback)
  63103. errorCallback();
  63104. };
  63105. if (!this.idbFactory || !(this._enableSceneOffline || this._enableTexturesOffline)) {
  63106. // Your browser doesn't support IndexedDB
  63107. this.isSupported = false;
  63108. if (errorCallback)
  63109. errorCallback();
  63110. }
  63111. else {
  63112. // If the DB hasn't been opened or created yet
  63113. if (!this.db) {
  63114. this.hasReachedQuota = false;
  63115. this.isSupported = true;
  63116. var request = this.idbFactory.open("babylonjs", 1);
  63117. // Could occur if user is blocking the quota for the DB and/or doesn't grant access to IndexedDB
  63118. request.onerror = function (event) {
  63119. handleError();
  63120. };
  63121. // executes when a version change transaction cannot complete due to other active transactions
  63122. request.onblocked = function (event) {
  63123. BABYLON.Tools.Error("IDB request blocked. Please reload the page.");
  63124. handleError();
  63125. };
  63126. // DB has been opened successfully
  63127. request.onsuccess = function (event) {
  63128. _this.db = request.result;
  63129. successCallback();
  63130. };
  63131. // Initialization of the DB. Creating Scenes & Textures stores
  63132. request.onupgradeneeded = function (event) {
  63133. _this.db = (event.target).result;
  63134. if (_this.db) {
  63135. try {
  63136. _this.db.createObjectStore("scenes", { keyPath: "sceneUrl" });
  63137. _this.db.createObjectStore("versions", { keyPath: "sceneUrl" });
  63138. _this.db.createObjectStore("textures", { keyPath: "textureUrl" });
  63139. }
  63140. catch (ex) {
  63141. BABYLON.Tools.Error("Error while creating object stores. Exception: " + ex.message);
  63142. handleError();
  63143. }
  63144. }
  63145. };
  63146. }
  63147. else {
  63148. if (successCallback)
  63149. successCallback();
  63150. }
  63151. }
  63152. };
  63153. Database.prototype.loadImageFromDB = function (url, image) {
  63154. var _this = this;
  63155. var completeURL = Database.ReturnFullUrlLocation(url);
  63156. var saveAndLoadImage = function () {
  63157. if (!_this.hasReachedQuota && _this.db !== null) {
  63158. // the texture is not yet in the DB, let's try to save it
  63159. _this._saveImageIntoDBAsync(completeURL, image);
  63160. }
  63161. else {
  63162. image.src = url;
  63163. }
  63164. };
  63165. if (!this.mustUpdateRessources) {
  63166. this._loadImageFromDBAsync(completeURL, image, saveAndLoadImage);
  63167. }
  63168. else {
  63169. saveAndLoadImage();
  63170. }
  63171. };
  63172. Database.prototype._loadImageFromDBAsync = function (url, image, notInDBCallback) {
  63173. if (this.isSupported && this.db !== null) {
  63174. var texture;
  63175. var transaction = this.db.transaction(["textures"]);
  63176. transaction.onabort = function (event) {
  63177. image.src = url;
  63178. };
  63179. transaction.oncomplete = function (event) {
  63180. var blobTextureURL;
  63181. if (texture) {
  63182. var URL = window.URL || window.webkitURL;
  63183. blobTextureURL = URL.createObjectURL(texture.data, { oneTimeOnly: true });
  63184. image.onerror = function () {
  63185. BABYLON.Tools.Error("Error loading image from blob URL: " + blobTextureURL + " switching back to web url: " + url);
  63186. image.src = url;
  63187. };
  63188. image.src = blobTextureURL;
  63189. }
  63190. else {
  63191. notInDBCallback();
  63192. }
  63193. };
  63194. var getRequest = transaction.objectStore("textures").get(url);
  63195. getRequest.onsuccess = function (event) {
  63196. texture = (event.target).result;
  63197. };
  63198. getRequest.onerror = function (event) {
  63199. BABYLON.Tools.Error("Error loading texture " + url + " from DB.");
  63200. image.src = url;
  63201. };
  63202. }
  63203. else {
  63204. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  63205. image.src = url;
  63206. }
  63207. };
  63208. Database.prototype._saveImageIntoDBAsync = function (url, image) {
  63209. var _this = this;
  63210. if (this.isSupported) {
  63211. // In case of error (type not supported or quota exceeded), we're at least sending back XHR data to allow texture loading later on
  63212. var generateBlobUrl = function () {
  63213. var blobTextureURL;
  63214. if (blob) {
  63215. var URL = window.URL || window.webkitURL;
  63216. try {
  63217. blobTextureURL = URL.createObjectURL(blob, { oneTimeOnly: true });
  63218. }
  63219. // Chrome is raising a type error if we're setting the oneTimeOnly parameter
  63220. catch (ex) {
  63221. blobTextureURL = URL.createObjectURL(blob);
  63222. }
  63223. }
  63224. if (blobTextureURL) {
  63225. image.src = blobTextureURL;
  63226. }
  63227. };
  63228. if (Database.IsUASupportingBlobStorage) {
  63229. var xhr = new XMLHttpRequest(), blob;
  63230. xhr.open("GET", url, true);
  63231. xhr.responseType = "blob";
  63232. xhr.addEventListener("load", function () {
  63233. if (xhr.status === 200 && _this.db) {
  63234. // Blob as response (XHR2)
  63235. blob = xhr.response;
  63236. var transaction = _this.db.transaction(["textures"], "readwrite");
  63237. // the transaction could abort because of a QuotaExceededError error
  63238. transaction.onabort = function (event) {
  63239. try {
  63240. //backwards compatibility with ts 1.0, srcElement doesn't have an "error" according to ts 1.3
  63241. var srcElement = (event.srcElement || event.target);
  63242. var error = srcElement.error;
  63243. if (error && error.name === "QuotaExceededError") {
  63244. _this.hasReachedQuota = true;
  63245. }
  63246. }
  63247. catch (ex) { }
  63248. generateBlobUrl();
  63249. };
  63250. transaction.oncomplete = function (event) {
  63251. generateBlobUrl();
  63252. };
  63253. var newTexture = { textureUrl: url, data: blob };
  63254. try {
  63255. // Put the blob into the dabase
  63256. var addRequest = transaction.objectStore("textures").put(newTexture);
  63257. addRequest.onsuccess = function (event) {
  63258. };
  63259. addRequest.onerror = function (event) {
  63260. generateBlobUrl();
  63261. };
  63262. }
  63263. catch (ex) {
  63264. // "DataCloneError" generated by Chrome when you try to inject blob into IndexedDB
  63265. if (ex.code === 25) {
  63266. Database.IsUASupportingBlobStorage = false;
  63267. }
  63268. image.src = url;
  63269. }
  63270. }
  63271. else {
  63272. image.src = url;
  63273. }
  63274. }, false);
  63275. xhr.addEventListener("error", function (event) {
  63276. BABYLON.Tools.Error("Error in XHR request in BABYLON.Database.");
  63277. image.src = url;
  63278. }, false);
  63279. xhr.send();
  63280. }
  63281. else {
  63282. image.src = url;
  63283. }
  63284. }
  63285. else {
  63286. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  63287. image.src = url;
  63288. }
  63289. };
  63290. Database.prototype._checkVersionFromDB = function (url, versionLoaded) {
  63291. var _this = this;
  63292. var updateVersion = function () {
  63293. // the version is not yet in the DB or we need to update it
  63294. _this._saveVersionIntoDBAsync(url, versionLoaded);
  63295. };
  63296. this._loadVersionFromDBAsync(url, versionLoaded, updateVersion);
  63297. };
  63298. Database.prototype._loadVersionFromDBAsync = function (url, callback, updateInDBCallback) {
  63299. var _this = this;
  63300. if (this.isSupported && this.db) {
  63301. var version;
  63302. try {
  63303. var transaction = this.db.transaction(["versions"]);
  63304. transaction.oncomplete = function (event) {
  63305. if (version) {
  63306. // If the version in the JSON file is > than the version in DB
  63307. if (_this.manifestVersionFound > version.data) {
  63308. _this.mustUpdateRessources = true;
  63309. updateInDBCallback();
  63310. }
  63311. else {
  63312. callback(version.data);
  63313. }
  63314. }
  63315. else {
  63316. _this.mustUpdateRessources = true;
  63317. updateInDBCallback();
  63318. }
  63319. };
  63320. transaction.onabort = function (event) {
  63321. callback(-1);
  63322. };
  63323. var getRequest = transaction.objectStore("versions").get(url);
  63324. getRequest.onsuccess = function (event) {
  63325. version = (event.target).result;
  63326. };
  63327. getRequest.onerror = function (event) {
  63328. BABYLON.Tools.Error("Error loading version for scene " + url + " from DB.");
  63329. callback(-1);
  63330. };
  63331. }
  63332. catch (ex) {
  63333. BABYLON.Tools.Error("Error while accessing 'versions' object store (READ OP). Exception: " + ex.message);
  63334. callback(-1);
  63335. }
  63336. }
  63337. else {
  63338. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  63339. callback(-1);
  63340. }
  63341. };
  63342. Database.prototype._saveVersionIntoDBAsync = function (url, callback) {
  63343. var _this = this;
  63344. if (this.isSupported && !this.hasReachedQuota && this.db) {
  63345. try {
  63346. // Open a transaction to the database
  63347. var transaction = this.db.transaction(["versions"], "readwrite");
  63348. // the transaction could abort because of a QuotaExceededError error
  63349. transaction.onabort = function (event) {
  63350. try {
  63351. var error = event.srcElement['error'];
  63352. if (error && error.name === "QuotaExceededError") {
  63353. _this.hasReachedQuota = true;
  63354. }
  63355. }
  63356. catch (ex) { }
  63357. callback(-1);
  63358. };
  63359. transaction.oncomplete = function (event) {
  63360. callback(_this.manifestVersionFound);
  63361. };
  63362. var newVersion = { sceneUrl: url, data: this.manifestVersionFound };
  63363. // Put the scene into the database
  63364. var addRequest = transaction.objectStore("versions").put(newVersion);
  63365. addRequest.onsuccess = function (event) {
  63366. };
  63367. addRequest.onerror = function (event) {
  63368. BABYLON.Tools.Error("Error in DB add version request in BABYLON.Database.");
  63369. };
  63370. }
  63371. catch (ex) {
  63372. BABYLON.Tools.Error("Error while accessing 'versions' object store (WRITE OP). Exception: " + ex.message);
  63373. callback(-1);
  63374. }
  63375. }
  63376. else {
  63377. callback(-1);
  63378. }
  63379. };
  63380. Database.prototype.loadFileFromDB = function (url, sceneLoaded, progressCallBack, errorCallback, useArrayBuffer) {
  63381. var _this = this;
  63382. var completeUrl = Database.ReturnFullUrlLocation(url);
  63383. var saveAndLoadFile = function () {
  63384. // the scene is not yet in the DB, let's try to save it
  63385. _this._saveFileIntoDBAsync(completeUrl, sceneLoaded, progressCallBack);
  63386. };
  63387. this._checkVersionFromDB(completeUrl, function (version) {
  63388. if (version !== -1) {
  63389. if (!_this.mustUpdateRessources) {
  63390. _this._loadFileFromDBAsync(completeUrl, sceneLoaded, saveAndLoadFile, useArrayBuffer);
  63391. }
  63392. else {
  63393. _this._saveFileIntoDBAsync(completeUrl, sceneLoaded, progressCallBack, useArrayBuffer);
  63394. }
  63395. }
  63396. else {
  63397. if (errorCallback) {
  63398. errorCallback();
  63399. }
  63400. }
  63401. });
  63402. };
  63403. Database.prototype._loadFileFromDBAsync = function (url, callback, notInDBCallback, useArrayBuffer) {
  63404. if (this.isSupported && this.db) {
  63405. var targetStore;
  63406. if (url.indexOf(".babylon") !== -1) {
  63407. targetStore = "scenes";
  63408. }
  63409. else {
  63410. targetStore = "textures";
  63411. }
  63412. var file;
  63413. var transaction = this.db.transaction([targetStore]);
  63414. transaction.oncomplete = function (event) {
  63415. if (file) {
  63416. callback(file.data);
  63417. }
  63418. else {
  63419. notInDBCallback();
  63420. }
  63421. };
  63422. transaction.onabort = function (event) {
  63423. notInDBCallback();
  63424. };
  63425. var getRequest = transaction.objectStore(targetStore).get(url);
  63426. getRequest.onsuccess = function (event) {
  63427. file = (event.target).result;
  63428. };
  63429. getRequest.onerror = function (event) {
  63430. BABYLON.Tools.Error("Error loading file " + url + " from DB.");
  63431. notInDBCallback();
  63432. };
  63433. }
  63434. else {
  63435. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  63436. callback();
  63437. }
  63438. };
  63439. Database.prototype._saveFileIntoDBAsync = function (url, callback, progressCallback, useArrayBuffer) {
  63440. var _this = this;
  63441. if (this.isSupported) {
  63442. var targetStore;
  63443. if (url.indexOf(".babylon") !== -1) {
  63444. targetStore = "scenes";
  63445. }
  63446. else {
  63447. targetStore = "textures";
  63448. }
  63449. // Create XHR
  63450. var xhr = new XMLHttpRequest();
  63451. var fileData;
  63452. xhr.open("GET", url, true);
  63453. if (useArrayBuffer) {
  63454. xhr.responseType = "arraybuffer";
  63455. }
  63456. if (progressCallback) {
  63457. xhr.onprogress = progressCallback;
  63458. }
  63459. xhr.addEventListener("load", function () {
  63460. if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, !useArrayBuffer ? 1 : 6)) {
  63461. // Blob as response (XHR2)
  63462. //fileData = xhr.responseText;
  63463. fileData = !useArrayBuffer ? xhr.responseText : xhr.response;
  63464. if (!_this.hasReachedQuota && _this.db) {
  63465. // Open a transaction to the database
  63466. var transaction = _this.db.transaction([targetStore], "readwrite");
  63467. // the transaction could abort because of a QuotaExceededError error
  63468. transaction.onabort = function (event) {
  63469. try {
  63470. //backwards compatibility with ts 1.0, srcElement doesn't have an "error" according to ts 1.3
  63471. var error = event.srcElement['error'];
  63472. if (error && error.name === "QuotaExceededError") {
  63473. _this.hasReachedQuota = true;
  63474. }
  63475. }
  63476. catch (ex) { }
  63477. callback(fileData);
  63478. };
  63479. transaction.oncomplete = function (event) {
  63480. callback(fileData);
  63481. };
  63482. var newFile;
  63483. if (targetStore === "scenes") {
  63484. newFile = { sceneUrl: url, data: fileData, version: _this.manifestVersionFound };
  63485. }
  63486. else {
  63487. newFile = { textureUrl: url, data: fileData };
  63488. }
  63489. try {
  63490. // Put the scene into the database
  63491. var addRequest = transaction.objectStore(targetStore).put(newFile);
  63492. addRequest.onsuccess = function (event) {
  63493. };
  63494. addRequest.onerror = function (event) {
  63495. BABYLON.Tools.Error("Error in DB add file request in BABYLON.Database.");
  63496. };
  63497. }
  63498. catch (ex) {
  63499. callback(fileData);
  63500. }
  63501. }
  63502. else {
  63503. callback(fileData);
  63504. }
  63505. }
  63506. else {
  63507. callback();
  63508. }
  63509. }, false);
  63510. xhr.addEventListener("error", function (event) {
  63511. BABYLON.Tools.Error("error on XHR request.");
  63512. callback();
  63513. }, false);
  63514. xhr.send();
  63515. }
  63516. else {
  63517. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  63518. callback();
  63519. }
  63520. };
  63521. Database.IsUASupportingBlobStorage = true;
  63522. Database.IDBStorageEnabled = true;
  63523. Database.parseURL = function (url) {
  63524. var a = document.createElement('a');
  63525. a.href = url;
  63526. var urlWithoutHash = url.substring(0, url.lastIndexOf("#"));
  63527. var fileName = url.substring(urlWithoutHash.lastIndexOf("/") + 1, url.length);
  63528. var absLocation = url.substring(0, url.indexOf(fileName, 0));
  63529. return absLocation;
  63530. };
  63531. Database.ReturnFullUrlLocation = function (url) {
  63532. if (url.indexOf("http:/") === -1 && url.indexOf("https:/") === -1) {
  63533. return (Database.parseURL(window.location.href) + url);
  63534. }
  63535. else {
  63536. return url;
  63537. }
  63538. };
  63539. return Database;
  63540. }());
  63541. BABYLON.Database = Database;
  63542. })(BABYLON || (BABYLON = {}));
  63543. //# sourceMappingURL=babylon.database.js.map
  63544. var BABYLON;
  63545. (function (BABYLON) {
  63546. var FresnelParameters = /** @class */ (function () {
  63547. function FresnelParameters() {
  63548. this._isEnabled = true;
  63549. this.leftColor = BABYLON.Color3.White();
  63550. this.rightColor = BABYLON.Color3.Black();
  63551. this.bias = 0;
  63552. this.power = 1;
  63553. }
  63554. Object.defineProperty(FresnelParameters.prototype, "isEnabled", {
  63555. get: function () {
  63556. return this._isEnabled;
  63557. },
  63558. set: function (value) {
  63559. if (this._isEnabled === value) {
  63560. return;
  63561. }
  63562. this._isEnabled = value;
  63563. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.FresnelDirtyFlag | BABYLON.Material.MiscDirtyFlag);
  63564. },
  63565. enumerable: true,
  63566. configurable: true
  63567. });
  63568. FresnelParameters.prototype.clone = function () {
  63569. var newFresnelParameters = new FresnelParameters();
  63570. BABYLON.Tools.DeepCopy(this, newFresnelParameters);
  63571. return newFresnelParameters;
  63572. };
  63573. FresnelParameters.prototype.serialize = function () {
  63574. var serializationObject = {};
  63575. serializationObject.isEnabled = this.isEnabled;
  63576. serializationObject.leftColor = this.leftColor;
  63577. serializationObject.rightColor = this.rightColor;
  63578. serializationObject.bias = this.bias;
  63579. serializationObject.power = this.power;
  63580. return serializationObject;
  63581. };
  63582. FresnelParameters.Parse = function (parsedFresnelParameters) {
  63583. var fresnelParameters = new FresnelParameters();
  63584. fresnelParameters.isEnabled = parsedFresnelParameters.isEnabled;
  63585. fresnelParameters.leftColor = BABYLON.Color3.FromArray(parsedFresnelParameters.leftColor);
  63586. fresnelParameters.rightColor = BABYLON.Color3.FromArray(parsedFresnelParameters.rightColor);
  63587. fresnelParameters.bias = parsedFresnelParameters.bias;
  63588. fresnelParameters.power = parsedFresnelParameters.power || 1.0;
  63589. return fresnelParameters;
  63590. };
  63591. return FresnelParameters;
  63592. }());
  63593. BABYLON.FresnelParameters = FresnelParameters;
  63594. })(BABYLON || (BABYLON = {}));
  63595. //# sourceMappingURL=babylon.fresnelParameters.js.map
  63596. var BABYLON;
  63597. (function (BABYLON) {
  63598. var MultiMaterial = /** @class */ (function (_super) {
  63599. __extends(MultiMaterial, _super);
  63600. function MultiMaterial(name, scene) {
  63601. var _this = _super.call(this, name, scene, true) || this;
  63602. scene.multiMaterials.push(_this);
  63603. _this.subMaterials = new Array();
  63604. _this.storeEffectOnSubMeshes = true; // multimaterial is considered like a push material
  63605. return _this;
  63606. }
  63607. Object.defineProperty(MultiMaterial.prototype, "subMaterials", {
  63608. get: function () {
  63609. return this._subMaterials;
  63610. },
  63611. set: function (value) {
  63612. this._subMaterials = value;
  63613. this._hookArray(value);
  63614. },
  63615. enumerable: true,
  63616. configurable: true
  63617. });
  63618. MultiMaterial.prototype._hookArray = function (array) {
  63619. var _this = this;
  63620. var oldPush = array.push;
  63621. array.push = function () {
  63622. var items = [];
  63623. for (var _i = 0; _i < arguments.length; _i++) {
  63624. items[_i] = arguments[_i];
  63625. }
  63626. var result = oldPush.apply(array, items);
  63627. _this._markAllSubMeshesAsTexturesDirty();
  63628. return result;
  63629. };
  63630. var oldSplice = array.splice;
  63631. array.splice = function (index, deleteCount) {
  63632. var deleted = oldSplice.apply(array, [index, deleteCount]);
  63633. _this._markAllSubMeshesAsTexturesDirty();
  63634. return deleted;
  63635. };
  63636. };
  63637. // Properties
  63638. MultiMaterial.prototype.getSubMaterial = function (index) {
  63639. if (index < 0 || index >= this.subMaterials.length) {
  63640. return this.getScene().defaultMaterial;
  63641. }
  63642. return this.subMaterials[index];
  63643. };
  63644. MultiMaterial.prototype.getActiveTextures = function () {
  63645. return (_a = _super.prototype.getActiveTextures.call(this)).concat.apply(_a, this.subMaterials.map(function (subMaterial) {
  63646. if (subMaterial) {
  63647. return subMaterial.getActiveTextures();
  63648. }
  63649. else {
  63650. return [];
  63651. }
  63652. }));
  63653. var _a;
  63654. };
  63655. // Methods
  63656. MultiMaterial.prototype.getClassName = function () {
  63657. return "MultiMaterial";
  63658. };
  63659. MultiMaterial.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  63660. for (var index = 0; index < this.subMaterials.length; index++) {
  63661. var subMaterial = this.subMaterials[index];
  63662. if (subMaterial) {
  63663. if (subMaterial.storeEffectOnSubMeshes) {
  63664. if (!subMaterial.isReadyForSubMesh(mesh, subMesh, useInstances)) {
  63665. return false;
  63666. }
  63667. continue;
  63668. }
  63669. if (!subMaterial.isReady(mesh)) {
  63670. return false;
  63671. }
  63672. }
  63673. }
  63674. return true;
  63675. };
  63676. MultiMaterial.prototype.clone = function (name, cloneChildren) {
  63677. var newMultiMaterial = new MultiMaterial(name, this.getScene());
  63678. for (var index = 0; index < this.subMaterials.length; index++) {
  63679. var subMaterial = null;
  63680. var current = this.subMaterials[index];
  63681. if (cloneChildren && current) {
  63682. subMaterial = current.clone(name + "-" + current.name);
  63683. }
  63684. else {
  63685. subMaterial = this.subMaterials[index];
  63686. }
  63687. newMultiMaterial.subMaterials.push(subMaterial);
  63688. }
  63689. return newMultiMaterial;
  63690. };
  63691. MultiMaterial.prototype.serialize = function () {
  63692. var serializationObject = {};
  63693. serializationObject.name = this.name;
  63694. serializationObject.id = this.id;
  63695. if (BABYLON.Tags) {
  63696. serializationObject.tags = BABYLON.Tags.GetTags(this);
  63697. }
  63698. serializationObject.materials = [];
  63699. for (var matIndex = 0; matIndex < this.subMaterials.length; matIndex++) {
  63700. var subMat = this.subMaterials[matIndex];
  63701. if (subMat) {
  63702. serializationObject.materials.push(subMat.id);
  63703. }
  63704. else {
  63705. serializationObject.materials.push(null);
  63706. }
  63707. }
  63708. return serializationObject;
  63709. };
  63710. MultiMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  63711. var scene = this.getScene();
  63712. if (!scene) {
  63713. return;
  63714. }
  63715. var index = scene.multiMaterials.indexOf(this);
  63716. if (index >= 0) {
  63717. scene.multiMaterials.splice(index, 1);
  63718. }
  63719. _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);
  63720. };
  63721. return MultiMaterial;
  63722. }(BABYLON.Material));
  63723. BABYLON.MultiMaterial = MultiMaterial;
  63724. })(BABYLON || (BABYLON = {}));
  63725. //# sourceMappingURL=babylon.multiMaterial.js.map
  63726. var BABYLON;
  63727. (function (BABYLON) {
  63728. var FreeCameraTouchInput = /** @class */ (function () {
  63729. function FreeCameraTouchInput() {
  63730. this._offsetX = null;
  63731. this._offsetY = null;
  63732. this._pointerPressed = new Array();
  63733. this.touchAngularSensibility = 200000.0;
  63734. this.touchMoveSensibility = 250.0;
  63735. }
  63736. FreeCameraTouchInput.prototype.attachControl = function (element, noPreventDefault) {
  63737. var _this = this;
  63738. var previousPosition = null;
  63739. if (this._pointerInput === undefined) {
  63740. this._onLostFocus = function (evt) {
  63741. _this._offsetX = null;
  63742. _this._offsetY = null;
  63743. };
  63744. this._pointerInput = function (p, s) {
  63745. var evt = p.event;
  63746. if (evt.pointerType === "mouse") {
  63747. return;
  63748. }
  63749. if (p.type === BABYLON.PointerEventTypes.POINTERDOWN) {
  63750. if (!noPreventDefault) {
  63751. evt.preventDefault();
  63752. }
  63753. _this._pointerPressed.push(evt.pointerId);
  63754. if (_this._pointerPressed.length !== 1) {
  63755. return;
  63756. }
  63757. previousPosition = {
  63758. x: evt.clientX,
  63759. y: evt.clientY
  63760. };
  63761. }
  63762. else if (p.type === BABYLON.PointerEventTypes.POINTERUP) {
  63763. if (!noPreventDefault) {
  63764. evt.preventDefault();
  63765. }
  63766. var index = _this._pointerPressed.indexOf(evt.pointerId);
  63767. if (index === -1) {
  63768. return;
  63769. }
  63770. _this._pointerPressed.splice(index, 1);
  63771. if (index != 0) {
  63772. return;
  63773. }
  63774. previousPosition = null;
  63775. _this._offsetX = null;
  63776. _this._offsetY = null;
  63777. }
  63778. else if (p.type === BABYLON.PointerEventTypes.POINTERMOVE) {
  63779. if (!noPreventDefault) {
  63780. evt.preventDefault();
  63781. }
  63782. if (!previousPosition) {
  63783. return;
  63784. }
  63785. var index = _this._pointerPressed.indexOf(evt.pointerId);
  63786. if (index != 0) {
  63787. return;
  63788. }
  63789. _this._offsetX = evt.clientX - previousPosition.x;
  63790. _this._offsetY = -(evt.clientY - previousPosition.y);
  63791. }
  63792. };
  63793. }
  63794. this._observer = this.camera.getScene().onPointerObservable.add(this._pointerInput, BABYLON.PointerEventTypes.POINTERDOWN | BABYLON.PointerEventTypes.POINTERUP | BABYLON.PointerEventTypes.POINTERMOVE);
  63795. if (this._onLostFocus) {
  63796. element.addEventListener("blur", this._onLostFocus);
  63797. }
  63798. };
  63799. FreeCameraTouchInput.prototype.detachControl = function (element) {
  63800. if (this._pointerInput && element) {
  63801. if (this._observer) {
  63802. this.camera.getScene().onPointerObservable.remove(this._observer);
  63803. this._observer = null;
  63804. }
  63805. if (this._onLostFocus) {
  63806. element.removeEventListener("blur", this._onLostFocus);
  63807. this._onLostFocus = null;
  63808. }
  63809. this._pointerPressed = [];
  63810. this._offsetX = null;
  63811. this._offsetY = null;
  63812. }
  63813. };
  63814. FreeCameraTouchInput.prototype.checkInputs = function () {
  63815. if (this._offsetX && this._offsetY) {
  63816. var camera = this.camera;
  63817. camera.cameraRotation.y += this._offsetX / this.touchAngularSensibility;
  63818. if (this._pointerPressed.length > 1) {
  63819. camera.cameraRotation.x += -this._offsetY / this.touchAngularSensibility;
  63820. }
  63821. else {
  63822. var speed = camera._computeLocalCameraSpeed();
  63823. var direction = new BABYLON.Vector3(0, 0, speed * this._offsetY / this.touchMoveSensibility);
  63824. BABYLON.Matrix.RotationYawPitchRollToRef(camera.rotation.y, camera.rotation.x, 0, camera._cameraRotationMatrix);
  63825. camera.cameraDirection.addInPlace(BABYLON.Vector3.TransformCoordinates(direction, camera._cameraRotationMatrix));
  63826. }
  63827. }
  63828. };
  63829. FreeCameraTouchInput.prototype.getClassName = function () {
  63830. return "FreeCameraTouchInput";
  63831. };
  63832. FreeCameraTouchInput.prototype.getSimpleName = function () {
  63833. return "touch";
  63834. };
  63835. __decorate([
  63836. BABYLON.serialize()
  63837. ], FreeCameraTouchInput.prototype, "touchAngularSensibility", void 0);
  63838. __decorate([
  63839. BABYLON.serialize()
  63840. ], FreeCameraTouchInput.prototype, "touchMoveSensibility", void 0);
  63841. return FreeCameraTouchInput;
  63842. }());
  63843. BABYLON.FreeCameraTouchInput = FreeCameraTouchInput;
  63844. BABYLON.CameraInputTypes["FreeCameraTouchInput"] = FreeCameraTouchInput;
  63845. })(BABYLON || (BABYLON = {}));
  63846. //# sourceMappingURL=babylon.freeCameraTouchInput.js.map
  63847. var BABYLON;
  63848. (function (BABYLON) {
  63849. // We're mainly based on the logic defined into the FreeCamera code
  63850. var TouchCamera = /** @class */ (function (_super) {
  63851. __extends(TouchCamera, _super);
  63852. //-- end properties for backward compatibility for inputs
  63853. function TouchCamera(name, position, scene) {
  63854. var _this = _super.call(this, name, position, scene) || this;
  63855. _this.inputs.addTouch();
  63856. _this._setupInputs();
  63857. return _this;
  63858. }
  63859. Object.defineProperty(TouchCamera.prototype, "touchAngularSensibility", {
  63860. //-- Begin properties for backward compatibility for inputs
  63861. get: function () {
  63862. var touch = this.inputs.attached["touch"];
  63863. if (touch)
  63864. return touch.touchAngularSensibility;
  63865. return 0;
  63866. },
  63867. set: function (value) {
  63868. var touch = this.inputs.attached["touch"];
  63869. if (touch)
  63870. touch.touchAngularSensibility = value;
  63871. },
  63872. enumerable: true,
  63873. configurable: true
  63874. });
  63875. Object.defineProperty(TouchCamera.prototype, "touchMoveSensibility", {
  63876. get: function () {
  63877. var touch = this.inputs.attached["touch"];
  63878. if (touch)
  63879. return touch.touchMoveSensibility;
  63880. return 0;
  63881. },
  63882. set: function (value) {
  63883. var touch = this.inputs.attached["touch"];
  63884. if (touch)
  63885. touch.touchMoveSensibility = value;
  63886. },
  63887. enumerable: true,
  63888. configurable: true
  63889. });
  63890. TouchCamera.prototype.getClassName = function () {
  63891. return "TouchCamera";
  63892. };
  63893. TouchCamera.prototype._setupInputs = function () {
  63894. var mouse = this.inputs.attached["mouse"];
  63895. if (mouse) {
  63896. mouse.touchEnabled = false;
  63897. }
  63898. };
  63899. return TouchCamera;
  63900. }(BABYLON.FreeCamera));
  63901. BABYLON.TouchCamera = TouchCamera;
  63902. })(BABYLON || (BABYLON = {}));
  63903. //# sourceMappingURL=babylon.touchCamera.js.map
  63904. var BABYLON;
  63905. (function (BABYLON) {
  63906. var ProceduralTexture = /** @class */ (function (_super) {
  63907. __extends(ProceduralTexture, _super);
  63908. function ProceduralTexture(name, size, fragment, scene, fallbackTexture, generateMipMaps, isCube) {
  63909. if (fallbackTexture === void 0) { fallbackTexture = null; }
  63910. if (generateMipMaps === void 0) { generateMipMaps = true; }
  63911. if (isCube === void 0) { isCube = false; }
  63912. var _this = _super.call(this, null, scene, !generateMipMaps) || this;
  63913. _this.isCube = isCube;
  63914. _this.isEnabled = true;
  63915. _this._currentRefreshId = -1;
  63916. _this._refreshRate = 1;
  63917. _this._vertexBuffers = {};
  63918. _this._uniforms = new Array();
  63919. _this._samplers = new Array();
  63920. _this._textures = {};
  63921. _this._floats = {};
  63922. _this._floatsArrays = {};
  63923. _this._colors3 = {};
  63924. _this._colors4 = {};
  63925. _this._vectors2 = {};
  63926. _this._vectors3 = {};
  63927. _this._matrices = {};
  63928. _this._fallbackTextureUsed = false;
  63929. scene._proceduralTextures.push(_this);
  63930. _this._engine = scene.getEngine();
  63931. _this.name = name;
  63932. _this.isRenderTarget = true;
  63933. _this._size = size;
  63934. _this._generateMipMaps = generateMipMaps;
  63935. _this.setFragment(fragment);
  63936. _this._fallbackTexture = fallbackTexture;
  63937. if (isCube) {
  63938. _this._texture = _this._engine.createRenderTargetCubeTexture(size, { generateMipMaps: generateMipMaps });
  63939. _this.setFloat("face", 0);
  63940. }
  63941. else {
  63942. _this._texture = _this._engine.createRenderTargetTexture(size, generateMipMaps);
  63943. }
  63944. // VBO
  63945. var vertices = [];
  63946. vertices.push(1, 1);
  63947. vertices.push(-1, 1);
  63948. vertices.push(-1, -1);
  63949. vertices.push(1, -1);
  63950. _this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(_this._engine, vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  63951. _this._createIndexBuffer();
  63952. return _this;
  63953. }
  63954. ProceduralTexture.prototype._createIndexBuffer = function () {
  63955. var engine = this._engine;
  63956. // Indices
  63957. var indices = [];
  63958. indices.push(0);
  63959. indices.push(1);
  63960. indices.push(2);
  63961. indices.push(0);
  63962. indices.push(2);
  63963. indices.push(3);
  63964. this._indexBuffer = engine.createIndexBuffer(indices);
  63965. };
  63966. ProceduralTexture.prototype._rebuild = function () {
  63967. var vb = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  63968. if (vb) {
  63969. vb._rebuild();
  63970. }
  63971. this._createIndexBuffer();
  63972. if (this.refreshRate === BABYLON.RenderTargetTexture.REFRESHRATE_RENDER_ONCE) {
  63973. this.refreshRate = BABYLON.RenderTargetTexture.REFRESHRATE_RENDER_ONCE;
  63974. }
  63975. };
  63976. ProceduralTexture.prototype.reset = function () {
  63977. if (this._effect === undefined) {
  63978. return;
  63979. }
  63980. var engine = this._engine;
  63981. engine._releaseEffect(this._effect);
  63982. };
  63983. ProceduralTexture.prototype.isReady = function () {
  63984. var _this = this;
  63985. var engine = this._engine;
  63986. var shaders;
  63987. if (!this._fragment) {
  63988. return false;
  63989. }
  63990. if (this._fallbackTextureUsed) {
  63991. return true;
  63992. }
  63993. if (this._fragment.fragmentElement !== undefined) {
  63994. shaders = { vertex: "procedural", fragmentElement: this._fragment.fragmentElement };
  63995. }
  63996. else {
  63997. shaders = { vertex: "procedural", fragment: this._fragment };
  63998. }
  63999. this._effect = engine.createEffect(shaders, [BABYLON.VertexBuffer.PositionKind], this._uniforms, this._samplers, "", undefined, undefined, function () {
  64000. _this.releaseInternalTexture();
  64001. if (_this._fallbackTexture) {
  64002. _this._texture = _this._fallbackTexture._texture;
  64003. if (_this._texture) {
  64004. _this._texture.incrementReferences();
  64005. }
  64006. }
  64007. _this._fallbackTextureUsed = true;
  64008. });
  64009. return this._effect.isReady();
  64010. };
  64011. ProceduralTexture.prototype.resetRefreshCounter = function () {
  64012. this._currentRefreshId = -1;
  64013. };
  64014. ProceduralTexture.prototype.setFragment = function (fragment) {
  64015. this._fragment = fragment;
  64016. };
  64017. Object.defineProperty(ProceduralTexture.prototype, "refreshRate", {
  64018. get: function () {
  64019. return this._refreshRate;
  64020. },
  64021. // Use 0 to render just once, 1 to render on every frame, 2 to render every two frames and so on...
  64022. set: function (value) {
  64023. this._refreshRate = value;
  64024. this.resetRefreshCounter();
  64025. },
  64026. enumerable: true,
  64027. configurable: true
  64028. });
  64029. ProceduralTexture.prototype._shouldRender = function () {
  64030. if (!this.isEnabled || !this.isReady() || !this._texture) {
  64031. return false;
  64032. }
  64033. if (this._fallbackTextureUsed) {
  64034. return false;
  64035. }
  64036. if (this._currentRefreshId === -1) {
  64037. this._currentRefreshId = 1;
  64038. return true;
  64039. }
  64040. if (this.refreshRate === this._currentRefreshId) {
  64041. this._currentRefreshId = 1;
  64042. return true;
  64043. }
  64044. this._currentRefreshId++;
  64045. return false;
  64046. };
  64047. ProceduralTexture.prototype.getRenderSize = function () {
  64048. return this._size;
  64049. };
  64050. ProceduralTexture.prototype.resize = function (size, generateMipMaps) {
  64051. if (this._fallbackTextureUsed) {
  64052. return;
  64053. }
  64054. this.releaseInternalTexture();
  64055. this._texture = this._engine.createRenderTargetTexture(size, generateMipMaps);
  64056. };
  64057. ProceduralTexture.prototype._checkUniform = function (uniformName) {
  64058. if (this._uniforms.indexOf(uniformName) === -1) {
  64059. this._uniforms.push(uniformName);
  64060. }
  64061. };
  64062. ProceduralTexture.prototype.setTexture = function (name, texture) {
  64063. if (this._samplers.indexOf(name) === -1) {
  64064. this._samplers.push(name);
  64065. }
  64066. this._textures[name] = texture;
  64067. return this;
  64068. };
  64069. ProceduralTexture.prototype.setFloat = function (name, value) {
  64070. this._checkUniform(name);
  64071. this._floats[name] = value;
  64072. return this;
  64073. };
  64074. ProceduralTexture.prototype.setFloats = function (name, value) {
  64075. this._checkUniform(name);
  64076. this._floatsArrays[name] = value;
  64077. return this;
  64078. };
  64079. ProceduralTexture.prototype.setColor3 = function (name, value) {
  64080. this._checkUniform(name);
  64081. this._colors3[name] = value;
  64082. return this;
  64083. };
  64084. ProceduralTexture.prototype.setColor4 = function (name, value) {
  64085. this._checkUniform(name);
  64086. this._colors4[name] = value;
  64087. return this;
  64088. };
  64089. ProceduralTexture.prototype.setVector2 = function (name, value) {
  64090. this._checkUniform(name);
  64091. this._vectors2[name] = value;
  64092. return this;
  64093. };
  64094. ProceduralTexture.prototype.setVector3 = function (name, value) {
  64095. this._checkUniform(name);
  64096. this._vectors3[name] = value;
  64097. return this;
  64098. };
  64099. ProceduralTexture.prototype.setMatrix = function (name, value) {
  64100. this._checkUniform(name);
  64101. this._matrices[name] = value;
  64102. return this;
  64103. };
  64104. ProceduralTexture.prototype.render = function (useCameraPostProcess) {
  64105. var scene = this.getScene();
  64106. if (!scene) {
  64107. return;
  64108. }
  64109. var engine = this._engine;
  64110. // Render
  64111. engine.enableEffect(this._effect);
  64112. engine.setState(false);
  64113. // Texture
  64114. for (var name in this._textures) {
  64115. this._effect.setTexture(name, this._textures[name]);
  64116. }
  64117. // Float
  64118. for (name in this._floats) {
  64119. this._effect.setFloat(name, this._floats[name]);
  64120. }
  64121. // Floats
  64122. for (name in this._floatsArrays) {
  64123. this._effect.setArray(name, this._floatsArrays[name]);
  64124. }
  64125. // Color3
  64126. for (name in this._colors3) {
  64127. this._effect.setColor3(name, this._colors3[name]);
  64128. }
  64129. // Color4
  64130. for (name in this._colors4) {
  64131. var color = this._colors4[name];
  64132. this._effect.setFloat4(name, color.r, color.g, color.b, color.a);
  64133. }
  64134. // Vector2
  64135. for (name in this._vectors2) {
  64136. this._effect.setVector2(name, this._vectors2[name]);
  64137. }
  64138. // Vector3
  64139. for (name in this._vectors3) {
  64140. this._effect.setVector3(name, this._vectors3[name]);
  64141. }
  64142. // Matrix
  64143. for (name in this._matrices) {
  64144. this._effect.setMatrix(name, this._matrices[name]);
  64145. }
  64146. if (!this._texture) {
  64147. return;
  64148. }
  64149. if (this.isCube) {
  64150. for (var face = 0; face < 6; face++) {
  64151. engine.bindFramebuffer(this._texture, face, undefined, undefined, true);
  64152. // VBOs
  64153. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._effect);
  64154. this._effect.setFloat("face", face);
  64155. // Clear
  64156. engine.clear(scene.clearColor, true, true, true);
  64157. // Draw order
  64158. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  64159. // Mipmaps
  64160. if (face === 5) {
  64161. engine.generateMipMapsForCubemap(this._texture);
  64162. }
  64163. }
  64164. }
  64165. else {
  64166. engine.bindFramebuffer(this._texture, 0, undefined, undefined, true);
  64167. // VBOs
  64168. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._effect);
  64169. // Clear
  64170. engine.clear(scene.clearColor, true, true, true);
  64171. // Draw order
  64172. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  64173. }
  64174. // Unbind
  64175. engine.unBindFramebuffer(this._texture, this.isCube);
  64176. if (this.onGenerated) {
  64177. this.onGenerated();
  64178. }
  64179. };
  64180. ProceduralTexture.prototype.clone = function () {
  64181. var textureSize = this.getSize();
  64182. var newTexture = new ProceduralTexture(this.name, textureSize.width, this._fragment, this.getScene(), this._fallbackTexture, this._generateMipMaps);
  64183. // Base texture
  64184. newTexture.hasAlpha = this.hasAlpha;
  64185. newTexture.level = this.level;
  64186. // RenderTarget Texture
  64187. newTexture.coordinatesMode = this.coordinatesMode;
  64188. return newTexture;
  64189. };
  64190. ProceduralTexture.prototype.dispose = function () {
  64191. var scene = this.getScene();
  64192. if (!scene) {
  64193. return;
  64194. }
  64195. var index = scene._proceduralTextures.indexOf(this);
  64196. if (index >= 0) {
  64197. scene._proceduralTextures.splice(index, 1);
  64198. }
  64199. var vertexBuffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  64200. if (vertexBuffer) {
  64201. vertexBuffer.dispose();
  64202. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  64203. }
  64204. if (this._indexBuffer && this._engine._releaseBuffer(this._indexBuffer)) {
  64205. this._indexBuffer = null;
  64206. }
  64207. _super.prototype.dispose.call(this);
  64208. };
  64209. return ProceduralTexture;
  64210. }(BABYLON.Texture));
  64211. BABYLON.ProceduralTexture = ProceduralTexture;
  64212. })(BABYLON || (BABYLON = {}));
  64213. //# sourceMappingURL=babylon.proceduralTexture.js.map
  64214. var BABYLON;
  64215. (function (BABYLON) {
  64216. var CustomProceduralTexture = /** @class */ (function (_super) {
  64217. __extends(CustomProceduralTexture, _super);
  64218. function CustomProceduralTexture(name, texturePath, size, scene, fallbackTexture, generateMipMaps) {
  64219. var _this = _super.call(this, name, size, null, scene, fallbackTexture, generateMipMaps) || this;
  64220. _this._animate = true;
  64221. _this._time = 0;
  64222. _this._texturePath = texturePath;
  64223. //Try to load json
  64224. _this.loadJson(texturePath);
  64225. _this.refreshRate = 1;
  64226. return _this;
  64227. }
  64228. CustomProceduralTexture.prototype.loadJson = function (jsonUrl) {
  64229. var _this = this;
  64230. var noConfigFile = function () {
  64231. BABYLON.Tools.Log("No config file found in " + jsonUrl + " trying to use ShadersStore or DOM element");
  64232. try {
  64233. _this.setFragment(_this._texturePath);
  64234. }
  64235. catch (ex) {
  64236. BABYLON.Tools.Error("No json or ShaderStore or DOM element found for CustomProceduralTexture");
  64237. }
  64238. };
  64239. var configFileUrl = jsonUrl + "/config.json";
  64240. var xhr = new XMLHttpRequest();
  64241. xhr.open("GET", configFileUrl, true);
  64242. xhr.addEventListener("load", function () {
  64243. if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, 1)) {
  64244. try {
  64245. _this._config = JSON.parse(xhr.response);
  64246. _this.updateShaderUniforms();
  64247. _this.updateTextures();
  64248. _this.setFragment(_this._texturePath + "/custom");
  64249. _this._animate = _this._config.animate;
  64250. _this.refreshRate = _this._config.refreshrate;
  64251. }
  64252. catch (ex) {
  64253. noConfigFile();
  64254. }
  64255. }
  64256. else {
  64257. noConfigFile();
  64258. }
  64259. }, false);
  64260. xhr.addEventListener("error", function () {
  64261. noConfigFile();
  64262. }, false);
  64263. try {
  64264. xhr.send();
  64265. }
  64266. catch (ex) {
  64267. BABYLON.Tools.Error("CustomProceduralTexture: Error on XHR send request.");
  64268. }
  64269. };
  64270. CustomProceduralTexture.prototype.isReady = function () {
  64271. if (!_super.prototype.isReady.call(this)) {
  64272. return false;
  64273. }
  64274. for (var name in this._textures) {
  64275. var texture = this._textures[name];
  64276. if (!texture.isReady()) {
  64277. return false;
  64278. }
  64279. }
  64280. return true;
  64281. };
  64282. CustomProceduralTexture.prototype.render = function (useCameraPostProcess) {
  64283. var scene = this.getScene();
  64284. if (this._animate && scene) {
  64285. this._time += scene.getAnimationRatio() * 0.03;
  64286. this.updateShaderUniforms();
  64287. }
  64288. _super.prototype.render.call(this, useCameraPostProcess);
  64289. };
  64290. CustomProceduralTexture.prototype.updateTextures = function () {
  64291. for (var i = 0; i < this._config.sampler2Ds.length; i++) {
  64292. this.setTexture(this._config.sampler2Ds[i].sample2Dname, new BABYLON.Texture(this._texturePath + "/" + this._config.sampler2Ds[i].textureRelativeUrl, this.getScene()));
  64293. }
  64294. };
  64295. CustomProceduralTexture.prototype.updateShaderUniforms = function () {
  64296. if (this._config) {
  64297. for (var j = 0; j < this._config.uniforms.length; j++) {
  64298. var uniform = this._config.uniforms[j];
  64299. switch (uniform.type) {
  64300. case "float":
  64301. this.setFloat(uniform.name, uniform.value);
  64302. break;
  64303. case "color3":
  64304. this.setColor3(uniform.name, new BABYLON.Color3(uniform.r, uniform.g, uniform.b));
  64305. break;
  64306. case "color4":
  64307. this.setColor4(uniform.name, new BABYLON.Color4(uniform.r, uniform.g, uniform.b, uniform.a));
  64308. break;
  64309. case "vector2":
  64310. this.setVector2(uniform.name, new BABYLON.Vector2(uniform.x, uniform.y));
  64311. break;
  64312. case "vector3":
  64313. this.setVector3(uniform.name, new BABYLON.Vector3(uniform.x, uniform.y, uniform.z));
  64314. break;
  64315. }
  64316. }
  64317. }
  64318. this.setFloat("time", this._time);
  64319. };
  64320. Object.defineProperty(CustomProceduralTexture.prototype, "animate", {
  64321. get: function () {
  64322. return this._animate;
  64323. },
  64324. set: function (value) {
  64325. this._animate = value;
  64326. },
  64327. enumerable: true,
  64328. configurable: true
  64329. });
  64330. return CustomProceduralTexture;
  64331. }(BABYLON.ProceduralTexture));
  64332. BABYLON.CustomProceduralTexture = CustomProceduralTexture;
  64333. })(BABYLON || (BABYLON = {}));
  64334. //# sourceMappingURL=babylon.customProceduralTexture.js.map
  64335. var BABYLON;
  64336. (function (BABYLON) {
  64337. var FreeCameraGamepadInput = /** @class */ (function () {
  64338. function FreeCameraGamepadInput() {
  64339. this.gamepadAngularSensibility = 200;
  64340. this.gamepadMoveSensibility = 40;
  64341. // private members
  64342. this._cameraTransform = BABYLON.Matrix.Identity();
  64343. this._deltaTransform = BABYLON.Vector3.Zero();
  64344. this._vector3 = BABYLON.Vector3.Zero();
  64345. this._vector2 = BABYLON.Vector2.Zero();
  64346. }
  64347. FreeCameraGamepadInput.prototype.attachControl = function (element, noPreventDefault) {
  64348. var _this = this;
  64349. var manager = this.camera.getScene().gamepadManager;
  64350. this._onGamepadConnectedObserver = manager.onGamepadConnectedObservable.add(function (gamepad) {
  64351. if (gamepad.type !== BABYLON.Gamepad.POSE_ENABLED) {
  64352. // prioritize XBOX gamepads.
  64353. if (!_this.gamepad || gamepad.type === BABYLON.Gamepad.XBOX) {
  64354. _this.gamepad = gamepad;
  64355. }
  64356. }
  64357. });
  64358. this._onGamepadDisconnectedObserver = manager.onGamepadDisconnectedObservable.add(function (gamepad) {
  64359. if (_this.gamepad === gamepad) {
  64360. _this.gamepad = null;
  64361. }
  64362. });
  64363. this.gamepad = manager.getGamepadByType(BABYLON.Gamepad.XBOX);
  64364. };
  64365. FreeCameraGamepadInput.prototype.detachControl = function (element) {
  64366. this.camera.getScene().gamepadManager.onGamepadConnectedObservable.remove(this._onGamepadConnectedObserver);
  64367. this.camera.getScene().gamepadManager.onGamepadDisconnectedObservable.remove(this._onGamepadDisconnectedObserver);
  64368. this.gamepad = null;
  64369. };
  64370. FreeCameraGamepadInput.prototype.checkInputs = function () {
  64371. if (this.gamepad && this.gamepad.leftStick) {
  64372. var camera = this.camera;
  64373. var LSValues = this.gamepad.leftStick;
  64374. var normalizedLX = LSValues.x / this.gamepadMoveSensibility;
  64375. var normalizedLY = LSValues.y / this.gamepadMoveSensibility;
  64376. LSValues.x = Math.abs(normalizedLX) > 0.005 ? 0 + normalizedLX : 0;
  64377. LSValues.y = Math.abs(normalizedLY) > 0.005 ? 0 + normalizedLY : 0;
  64378. var RSValues = this.gamepad.rightStick;
  64379. if (RSValues) {
  64380. var normalizedRX = RSValues.x / this.gamepadAngularSensibility;
  64381. var normalizedRY = RSValues.y / this.gamepadAngularSensibility;
  64382. RSValues.x = Math.abs(normalizedRX) > 0.001 ? 0 + normalizedRX : 0;
  64383. RSValues.y = Math.abs(normalizedRY) > 0.001 ? 0 + normalizedRY : 0;
  64384. }
  64385. else {
  64386. RSValues = { x: 0, y: 0 };
  64387. }
  64388. if (!camera.rotationQuaternion) {
  64389. BABYLON.Matrix.RotationYawPitchRollToRef(camera.rotation.y, camera.rotation.x, 0, this._cameraTransform);
  64390. }
  64391. else {
  64392. camera.rotationQuaternion.toRotationMatrix(this._cameraTransform);
  64393. }
  64394. var speed = camera._computeLocalCameraSpeed() * 50.0;
  64395. this._vector3.copyFromFloats(LSValues.x * speed, 0, -LSValues.y * speed);
  64396. BABYLON.Vector3.TransformCoordinatesToRef(this._vector3, this._cameraTransform, this._deltaTransform);
  64397. camera.cameraDirection.addInPlace(this._deltaTransform);
  64398. this._vector2.copyFromFloats(RSValues.y, RSValues.x);
  64399. camera.cameraRotation.addInPlace(this._vector2);
  64400. }
  64401. };
  64402. FreeCameraGamepadInput.prototype.getClassName = function () {
  64403. return "FreeCameraGamepadInput";
  64404. };
  64405. FreeCameraGamepadInput.prototype.getSimpleName = function () {
  64406. return "gamepad";
  64407. };
  64408. __decorate([
  64409. BABYLON.serialize()
  64410. ], FreeCameraGamepadInput.prototype, "gamepadAngularSensibility", void 0);
  64411. __decorate([
  64412. BABYLON.serialize()
  64413. ], FreeCameraGamepadInput.prototype, "gamepadMoveSensibility", void 0);
  64414. return FreeCameraGamepadInput;
  64415. }());
  64416. BABYLON.FreeCameraGamepadInput = FreeCameraGamepadInput;
  64417. BABYLON.CameraInputTypes["FreeCameraGamepadInput"] = FreeCameraGamepadInput;
  64418. })(BABYLON || (BABYLON = {}));
  64419. //# sourceMappingURL=babylon.freeCameraGamepadInput.js.map
  64420. var BABYLON;
  64421. (function (BABYLON) {
  64422. var ArcRotateCameraGamepadInput = /** @class */ (function () {
  64423. function ArcRotateCameraGamepadInput() {
  64424. this.gamepadRotationSensibility = 80;
  64425. this.gamepadMoveSensibility = 40;
  64426. }
  64427. ArcRotateCameraGamepadInput.prototype.attachControl = function (element, noPreventDefault) {
  64428. var _this = this;
  64429. var manager = this.camera.getScene().gamepadManager;
  64430. this._onGamepadConnectedObserver = manager.onGamepadConnectedObservable.add(function (gamepad) {
  64431. if (gamepad.type !== BABYLON.Gamepad.POSE_ENABLED) {
  64432. // prioritize XBOX gamepads.
  64433. if (!_this.gamepad || gamepad.type === BABYLON.Gamepad.XBOX) {
  64434. _this.gamepad = gamepad;
  64435. }
  64436. }
  64437. });
  64438. this._onGamepadDisconnectedObserver = manager.onGamepadDisconnectedObservable.add(function (gamepad) {
  64439. if (_this.gamepad === gamepad) {
  64440. _this.gamepad = null;
  64441. }
  64442. });
  64443. this.gamepad = manager.getGamepadByType(BABYLON.Gamepad.XBOX);
  64444. };
  64445. ArcRotateCameraGamepadInput.prototype.detachControl = function (element) {
  64446. this.camera.getScene().gamepadManager.onGamepadConnectedObservable.remove(this._onGamepadConnectedObserver);
  64447. this.camera.getScene().gamepadManager.onGamepadDisconnectedObservable.remove(this._onGamepadDisconnectedObserver);
  64448. this.gamepad = null;
  64449. };
  64450. ArcRotateCameraGamepadInput.prototype.checkInputs = function () {
  64451. if (this.gamepad) {
  64452. var camera = this.camera;
  64453. var RSValues = this.gamepad.rightStick;
  64454. if (RSValues) {
  64455. if (RSValues.x != 0) {
  64456. var normalizedRX = RSValues.x / this.gamepadRotationSensibility;
  64457. if (normalizedRX != 0 && Math.abs(normalizedRX) > 0.005) {
  64458. camera.inertialAlphaOffset += normalizedRX;
  64459. }
  64460. }
  64461. if (RSValues.y != 0) {
  64462. var normalizedRY = RSValues.y / this.gamepadRotationSensibility;
  64463. if (normalizedRY != 0 && Math.abs(normalizedRY) > 0.005) {
  64464. camera.inertialBetaOffset += normalizedRY;
  64465. }
  64466. }
  64467. }
  64468. var LSValues = this.gamepad.leftStick;
  64469. if (LSValues && LSValues.y != 0) {
  64470. var normalizedLY = LSValues.y / this.gamepadMoveSensibility;
  64471. if (normalizedLY != 0 && Math.abs(normalizedLY) > 0.005) {
  64472. this.camera.inertialRadiusOffset -= normalizedLY;
  64473. }
  64474. }
  64475. }
  64476. };
  64477. ArcRotateCameraGamepadInput.prototype.getClassName = function () {
  64478. return "ArcRotateCameraGamepadInput";
  64479. };
  64480. ArcRotateCameraGamepadInput.prototype.getSimpleName = function () {
  64481. return "gamepad";
  64482. };
  64483. __decorate([
  64484. BABYLON.serialize()
  64485. ], ArcRotateCameraGamepadInput.prototype, "gamepadRotationSensibility", void 0);
  64486. __decorate([
  64487. BABYLON.serialize()
  64488. ], ArcRotateCameraGamepadInput.prototype, "gamepadMoveSensibility", void 0);
  64489. return ArcRotateCameraGamepadInput;
  64490. }());
  64491. BABYLON.ArcRotateCameraGamepadInput = ArcRotateCameraGamepadInput;
  64492. BABYLON.CameraInputTypes["ArcRotateCameraGamepadInput"] = ArcRotateCameraGamepadInput;
  64493. })(BABYLON || (BABYLON = {}));
  64494. //# sourceMappingURL=babylon.arcRotateCameraGamepadInput.js.map
  64495. var BABYLON;
  64496. (function (BABYLON) {
  64497. var GamepadManager = /** @class */ (function () {
  64498. function GamepadManager(_scene) {
  64499. var _this = this;
  64500. this._scene = _scene;
  64501. this._babylonGamepads = [];
  64502. this._oneGamepadConnected = false;
  64503. this._isMonitoring = false;
  64504. this.onGamepadDisconnectedObservable = new BABYLON.Observable();
  64505. if (!BABYLON.Tools.IsWindowObjectExist()) {
  64506. this._gamepadEventSupported = false;
  64507. }
  64508. else {
  64509. this._gamepadEventSupported = 'GamepadEvent' in window;
  64510. this._gamepadSupport = (navigator.getGamepads ||
  64511. navigator.webkitGetGamepads || navigator.msGetGamepads || navigator.webkitGamepads);
  64512. }
  64513. this.onGamepadConnectedObservable = new BABYLON.Observable(function (observer) {
  64514. // This will be used to raise the onGamepadConnected for all gamepads ALREADY connected
  64515. for (var i in _this._babylonGamepads) {
  64516. var gamepad = _this._babylonGamepads[i];
  64517. if (gamepad && gamepad._isConnected) {
  64518. _this.onGamepadConnectedObservable.notifyObserver(observer, gamepad);
  64519. }
  64520. }
  64521. });
  64522. this._onGamepadConnectedEvent = function (evt) {
  64523. var gamepad = evt.gamepad;
  64524. if (gamepad.index in _this._babylonGamepads) {
  64525. if (_this._babylonGamepads[gamepad.index].isConnected) {
  64526. return;
  64527. }
  64528. }
  64529. var newGamepad;
  64530. if (_this._babylonGamepads[gamepad.index]) {
  64531. newGamepad = _this._babylonGamepads[gamepad.index];
  64532. newGamepad.browserGamepad = gamepad;
  64533. newGamepad._isConnected = true;
  64534. }
  64535. else {
  64536. newGamepad = _this._addNewGamepad(gamepad);
  64537. }
  64538. _this.onGamepadConnectedObservable.notifyObservers(newGamepad);
  64539. _this._startMonitoringGamepads();
  64540. };
  64541. this._onGamepadDisconnectedEvent = function (evt) {
  64542. var gamepad = evt.gamepad;
  64543. // Remove the gamepad from the list of gamepads to monitor.
  64544. for (var i in _this._babylonGamepads) {
  64545. if (_this._babylonGamepads[i].index === gamepad.index) {
  64546. var disconnectedGamepad = _this._babylonGamepads[i];
  64547. disconnectedGamepad._isConnected = false;
  64548. _this.onGamepadDisconnectedObservable.notifyObservers(disconnectedGamepad);
  64549. break;
  64550. }
  64551. }
  64552. };
  64553. if (this._gamepadSupport) {
  64554. //first add already-connected gamepads
  64555. this._updateGamepadObjects();
  64556. if (this._babylonGamepads.length) {
  64557. this._startMonitoringGamepads();
  64558. }
  64559. // Checking if the gamepad connected event is supported (like in Firefox)
  64560. if (this._gamepadEventSupported) {
  64561. window.addEventListener('gamepadconnected', this._onGamepadConnectedEvent, false);
  64562. window.addEventListener('gamepaddisconnected', this._onGamepadDisconnectedEvent, false);
  64563. }
  64564. else {
  64565. this._startMonitoringGamepads();
  64566. }
  64567. }
  64568. }
  64569. Object.defineProperty(GamepadManager.prototype, "gamepads", {
  64570. get: function () {
  64571. return this._babylonGamepads;
  64572. },
  64573. enumerable: true,
  64574. configurable: true
  64575. });
  64576. GamepadManager.prototype.getGamepadByType = function (type) {
  64577. if (type === void 0) { type = BABYLON.Gamepad.XBOX; }
  64578. for (var _i = 0, _a = this._babylonGamepads; _i < _a.length; _i++) {
  64579. var gamepad = _a[_i];
  64580. if (gamepad && gamepad.type === type) {
  64581. return gamepad;
  64582. }
  64583. }
  64584. return null;
  64585. };
  64586. GamepadManager.prototype.dispose = function () {
  64587. if (this._gamepadEventSupported) {
  64588. if (this._onGamepadConnectedEvent) {
  64589. window.removeEventListener('gamepadconnected', this._onGamepadConnectedEvent);
  64590. }
  64591. if (this._onGamepadDisconnectedEvent) {
  64592. window.removeEventListener('gamepaddisconnected', this._onGamepadDisconnectedEvent);
  64593. }
  64594. this._onGamepadConnectedEvent = null;
  64595. this._onGamepadDisconnectedEvent = null;
  64596. }
  64597. this._babylonGamepads.forEach(function (gamepad) {
  64598. gamepad.dispose();
  64599. });
  64600. this.onGamepadConnectedObservable.clear();
  64601. this.onGamepadDisconnectedObservable.clear();
  64602. this._oneGamepadConnected = false;
  64603. this._stopMonitoringGamepads();
  64604. this._babylonGamepads = [];
  64605. };
  64606. GamepadManager.prototype._addNewGamepad = function (gamepad) {
  64607. if (!this._oneGamepadConnected) {
  64608. this._oneGamepadConnected = true;
  64609. }
  64610. var newGamepad;
  64611. var xboxOne = (gamepad.id.search("Xbox One") !== -1);
  64612. if (xboxOne || gamepad.id.search("Xbox 360") !== -1 || gamepad.id.search("xinput") !== -1) {
  64613. newGamepad = new BABYLON.Xbox360Pad(gamepad.id, gamepad.index, gamepad, xboxOne);
  64614. }
  64615. else if (gamepad.pose) {
  64616. newGamepad = BABYLON.PoseEnabledControllerHelper.InitiateController(gamepad);
  64617. }
  64618. else {
  64619. newGamepad = new BABYLON.GenericPad(gamepad.id, gamepad.index, gamepad);
  64620. }
  64621. this._babylonGamepads[newGamepad.index] = newGamepad;
  64622. return newGamepad;
  64623. };
  64624. GamepadManager.prototype._startMonitoringGamepads = function () {
  64625. if (!this._isMonitoring) {
  64626. this._isMonitoring = true;
  64627. //back-comp
  64628. if (!this._scene) {
  64629. this._checkGamepadsStatus();
  64630. }
  64631. }
  64632. };
  64633. GamepadManager.prototype._stopMonitoringGamepads = function () {
  64634. this._isMonitoring = false;
  64635. };
  64636. GamepadManager.prototype._checkGamepadsStatus = function () {
  64637. var _this = this;
  64638. // Hack to be compatible Chrome
  64639. this._updateGamepadObjects();
  64640. for (var i in this._babylonGamepads) {
  64641. var gamepad = this._babylonGamepads[i];
  64642. if (!gamepad || !gamepad.isConnected) {
  64643. continue;
  64644. }
  64645. gamepad.update();
  64646. }
  64647. if (this._isMonitoring && !this._scene) {
  64648. BABYLON.Tools.QueueNewFrame(function () { _this._checkGamepadsStatus(); });
  64649. }
  64650. };
  64651. // This function is called only on Chrome, which does not properly support
  64652. // connection/disconnection events and forces you to recopy again the gamepad object
  64653. GamepadManager.prototype._updateGamepadObjects = function () {
  64654. var gamepads = navigator.getGamepads ? navigator.getGamepads() : (navigator.webkitGetGamepads ? navigator.webkitGetGamepads() : []);
  64655. for (var i = 0; i < gamepads.length; i++) {
  64656. if (gamepads[i]) {
  64657. if (!this._babylonGamepads[gamepads[i].index]) {
  64658. var newGamepad = this._addNewGamepad(gamepads[i]);
  64659. this.onGamepadConnectedObservable.notifyObservers(newGamepad);
  64660. }
  64661. else {
  64662. // Forced to copy again this object for Chrome for unknown reason
  64663. this._babylonGamepads[i].browserGamepad = gamepads[i];
  64664. if (!this._babylonGamepads[i].isConnected) {
  64665. this._babylonGamepads[i]._isConnected = true;
  64666. this.onGamepadConnectedObservable.notifyObservers(this._babylonGamepads[i]);
  64667. }
  64668. }
  64669. }
  64670. }
  64671. };
  64672. return GamepadManager;
  64673. }());
  64674. BABYLON.GamepadManager = GamepadManager;
  64675. })(BABYLON || (BABYLON = {}));
  64676. //# sourceMappingURL=babylon.gamepadManager.js.map
  64677. var BABYLON;
  64678. (function (BABYLON) {
  64679. var StickValues = /** @class */ (function () {
  64680. function StickValues(x, y) {
  64681. this.x = x;
  64682. this.y = y;
  64683. }
  64684. return StickValues;
  64685. }());
  64686. BABYLON.StickValues = StickValues;
  64687. var Gamepad = /** @class */ (function () {
  64688. function Gamepad(id, index, browserGamepad, leftStickX, leftStickY, rightStickX, rightStickY) {
  64689. if (leftStickX === void 0) { leftStickX = 0; }
  64690. if (leftStickY === void 0) { leftStickY = 1; }
  64691. if (rightStickX === void 0) { rightStickX = 2; }
  64692. if (rightStickY === void 0) { rightStickY = 3; }
  64693. this.id = id;
  64694. this.index = index;
  64695. this.browserGamepad = browserGamepad;
  64696. this._isConnected = true;
  64697. this._invertLeftStickY = false;
  64698. this.type = Gamepad.GAMEPAD;
  64699. this._leftStickAxisX = leftStickX;
  64700. this._leftStickAxisY = leftStickY;
  64701. this._rightStickAxisX = rightStickX;
  64702. this._rightStickAxisY = rightStickY;
  64703. if (this.browserGamepad.axes.length >= 2) {
  64704. this._leftStick = { x: this.browserGamepad.axes[this._leftStickAxisX], y: this.browserGamepad.axes[this._leftStickAxisY] };
  64705. }
  64706. if (this.browserGamepad.axes.length >= 4) {
  64707. this._rightStick = { x: this.browserGamepad.axes[this._rightStickAxisX], y: this.browserGamepad.axes[this._rightStickAxisY] };
  64708. }
  64709. }
  64710. Object.defineProperty(Gamepad.prototype, "isConnected", {
  64711. get: function () {
  64712. return this._isConnected;
  64713. },
  64714. enumerable: true,
  64715. configurable: true
  64716. });
  64717. Gamepad.prototype.onleftstickchanged = function (callback) {
  64718. this._onleftstickchanged = callback;
  64719. };
  64720. Gamepad.prototype.onrightstickchanged = function (callback) {
  64721. this._onrightstickchanged = callback;
  64722. };
  64723. Object.defineProperty(Gamepad.prototype, "leftStick", {
  64724. get: function () {
  64725. return this._leftStick;
  64726. },
  64727. set: function (newValues) {
  64728. if (this._onleftstickchanged && (this._leftStick.x !== newValues.x || this._leftStick.y !== newValues.y)) {
  64729. this._onleftstickchanged(newValues);
  64730. }
  64731. this._leftStick = newValues;
  64732. },
  64733. enumerable: true,
  64734. configurable: true
  64735. });
  64736. Object.defineProperty(Gamepad.prototype, "rightStick", {
  64737. get: function () {
  64738. return this._rightStick;
  64739. },
  64740. set: function (newValues) {
  64741. if (this._onrightstickchanged && (this._rightStick.x !== newValues.x || this._rightStick.y !== newValues.y)) {
  64742. this._onrightstickchanged(newValues);
  64743. }
  64744. this._rightStick = newValues;
  64745. },
  64746. enumerable: true,
  64747. configurable: true
  64748. });
  64749. Gamepad.prototype.update = function () {
  64750. if (this._leftStick) {
  64751. this.leftStick = { x: this.browserGamepad.axes[this._leftStickAxisX], y: this.browserGamepad.axes[this._leftStickAxisY] };
  64752. if (this._invertLeftStickY) {
  64753. this.leftStick.y *= -1;
  64754. }
  64755. }
  64756. if (this._rightStick) {
  64757. this.rightStick = { x: this.browserGamepad.axes[this._rightStickAxisX], y: this.browserGamepad.axes[this._rightStickAxisY] };
  64758. }
  64759. };
  64760. Gamepad.prototype.dispose = function () {
  64761. };
  64762. Gamepad.GAMEPAD = 0;
  64763. Gamepad.GENERIC = 1;
  64764. Gamepad.XBOX = 2;
  64765. Gamepad.POSE_ENABLED = 3;
  64766. return Gamepad;
  64767. }());
  64768. BABYLON.Gamepad = Gamepad;
  64769. var GenericPad = /** @class */ (function (_super) {
  64770. __extends(GenericPad, _super);
  64771. function GenericPad(id, index, browserGamepad) {
  64772. var _this = _super.call(this, id, index, browserGamepad) || this;
  64773. _this.onButtonDownObservable = new BABYLON.Observable();
  64774. _this.onButtonUpObservable = new BABYLON.Observable();
  64775. _this.type = Gamepad.GENERIC;
  64776. _this._buttons = new Array(browserGamepad.buttons.length);
  64777. return _this;
  64778. }
  64779. GenericPad.prototype.onbuttondown = function (callback) {
  64780. this._onbuttondown = callback;
  64781. };
  64782. GenericPad.prototype.onbuttonup = function (callback) {
  64783. this._onbuttonup = callback;
  64784. };
  64785. GenericPad.prototype._setButtonValue = function (newValue, currentValue, buttonIndex) {
  64786. if (newValue !== currentValue) {
  64787. if (newValue === 1) {
  64788. if (this._onbuttondown) {
  64789. this._onbuttondown(buttonIndex);
  64790. }
  64791. this.onButtonDownObservable.notifyObservers(buttonIndex);
  64792. }
  64793. if (newValue === 0) {
  64794. if (this._onbuttonup) {
  64795. this._onbuttonup(buttonIndex);
  64796. }
  64797. this.onButtonUpObservable.notifyObservers(buttonIndex);
  64798. }
  64799. }
  64800. return newValue;
  64801. };
  64802. GenericPad.prototype.update = function () {
  64803. _super.prototype.update.call(this);
  64804. for (var index = 0; index < this._buttons.length; index++) {
  64805. this._buttons[index] = this._setButtonValue(this.browserGamepad.buttons[index].value, this._buttons[index], index);
  64806. }
  64807. };
  64808. GenericPad.prototype.dispose = function () {
  64809. _super.prototype.dispose.call(this);
  64810. this.onButtonDownObservable.clear();
  64811. this.onButtonUpObservable.clear();
  64812. };
  64813. return GenericPad;
  64814. }(Gamepad));
  64815. BABYLON.GenericPad = GenericPad;
  64816. })(BABYLON || (BABYLON = {}));
  64817. //# sourceMappingURL=babylon.gamepad.js.map
  64818. var BABYLON;
  64819. (function (BABYLON) {
  64820. var Xbox360Button;
  64821. (function (Xbox360Button) {
  64822. Xbox360Button[Xbox360Button["A"] = 0] = "A";
  64823. Xbox360Button[Xbox360Button["B"] = 1] = "B";
  64824. Xbox360Button[Xbox360Button["X"] = 2] = "X";
  64825. Xbox360Button[Xbox360Button["Y"] = 3] = "Y";
  64826. Xbox360Button[Xbox360Button["Start"] = 4] = "Start";
  64827. Xbox360Button[Xbox360Button["Back"] = 5] = "Back";
  64828. Xbox360Button[Xbox360Button["LB"] = 6] = "LB";
  64829. Xbox360Button[Xbox360Button["RB"] = 7] = "RB";
  64830. Xbox360Button[Xbox360Button["LeftStick"] = 8] = "LeftStick";
  64831. Xbox360Button[Xbox360Button["RightStick"] = 9] = "RightStick";
  64832. })(Xbox360Button = BABYLON.Xbox360Button || (BABYLON.Xbox360Button = {}));
  64833. var Xbox360Dpad;
  64834. (function (Xbox360Dpad) {
  64835. Xbox360Dpad[Xbox360Dpad["Up"] = 0] = "Up";
  64836. Xbox360Dpad[Xbox360Dpad["Down"] = 1] = "Down";
  64837. Xbox360Dpad[Xbox360Dpad["Left"] = 2] = "Left";
  64838. Xbox360Dpad[Xbox360Dpad["Right"] = 3] = "Right";
  64839. })(Xbox360Dpad = BABYLON.Xbox360Dpad || (BABYLON.Xbox360Dpad = {}));
  64840. var Xbox360Pad = /** @class */ (function (_super) {
  64841. __extends(Xbox360Pad, _super);
  64842. function Xbox360Pad(id, index, gamepad, xboxOne) {
  64843. if (xboxOne === void 0) { xboxOne = false; }
  64844. var _this = _super.call(this, id, index, gamepad, 0, 1, 2, 3) || this;
  64845. _this._leftTrigger = 0;
  64846. _this._rightTrigger = 0;
  64847. _this.onButtonDownObservable = new BABYLON.Observable();
  64848. _this.onButtonUpObservable = new BABYLON.Observable();
  64849. _this.onPadDownObservable = new BABYLON.Observable();
  64850. _this.onPadUpObservable = new BABYLON.Observable();
  64851. _this._buttonA = 0;
  64852. _this._buttonB = 0;
  64853. _this._buttonX = 0;
  64854. _this._buttonY = 0;
  64855. _this._buttonBack = 0;
  64856. _this._buttonStart = 0;
  64857. _this._buttonLB = 0;
  64858. _this._buttonRB = 0;
  64859. _this._buttonLeftStick = 0;
  64860. _this._buttonRightStick = 0;
  64861. _this._dPadUp = 0;
  64862. _this._dPadDown = 0;
  64863. _this._dPadLeft = 0;
  64864. _this._dPadRight = 0;
  64865. _this._isXboxOnePad = false;
  64866. _this.type = BABYLON.Gamepad.XBOX;
  64867. _this._isXboxOnePad = xboxOne;
  64868. return _this;
  64869. }
  64870. Xbox360Pad.prototype.onlefttriggerchanged = function (callback) {
  64871. this._onlefttriggerchanged = callback;
  64872. };
  64873. Xbox360Pad.prototype.onrighttriggerchanged = function (callback) {
  64874. this._onrighttriggerchanged = callback;
  64875. };
  64876. Object.defineProperty(Xbox360Pad.prototype, "leftTrigger", {
  64877. get: function () {
  64878. return this._leftTrigger;
  64879. },
  64880. set: function (newValue) {
  64881. if (this._onlefttriggerchanged && this._leftTrigger !== newValue) {
  64882. this._onlefttriggerchanged(newValue);
  64883. }
  64884. this._leftTrigger = newValue;
  64885. },
  64886. enumerable: true,
  64887. configurable: true
  64888. });
  64889. Object.defineProperty(Xbox360Pad.prototype, "rightTrigger", {
  64890. get: function () {
  64891. return this._rightTrigger;
  64892. },
  64893. set: function (newValue) {
  64894. if (this._onrighttriggerchanged && this._rightTrigger !== newValue) {
  64895. this._onrighttriggerchanged(newValue);
  64896. }
  64897. this._rightTrigger = newValue;
  64898. },
  64899. enumerable: true,
  64900. configurable: true
  64901. });
  64902. Xbox360Pad.prototype.onbuttondown = function (callback) {
  64903. this._onbuttondown = callback;
  64904. };
  64905. Xbox360Pad.prototype.onbuttonup = function (callback) {
  64906. this._onbuttonup = callback;
  64907. };
  64908. Xbox360Pad.prototype.ondpaddown = function (callback) {
  64909. this._ondpaddown = callback;
  64910. };
  64911. Xbox360Pad.prototype.ondpadup = function (callback) {
  64912. this._ondpadup = callback;
  64913. };
  64914. Xbox360Pad.prototype._setButtonValue = function (newValue, currentValue, buttonType) {
  64915. if (newValue !== currentValue) {
  64916. if (newValue === 1) {
  64917. if (this._onbuttondown) {
  64918. this._onbuttondown(buttonType);
  64919. }
  64920. this.onButtonDownObservable.notifyObservers(buttonType);
  64921. }
  64922. if (newValue === 0) {
  64923. if (this._onbuttonup) {
  64924. this._onbuttonup(buttonType);
  64925. }
  64926. this.onButtonUpObservable.notifyObservers(buttonType);
  64927. }
  64928. }
  64929. return newValue;
  64930. };
  64931. Xbox360Pad.prototype._setDPadValue = function (newValue, currentValue, buttonType) {
  64932. if (newValue !== currentValue) {
  64933. if (newValue === 1) {
  64934. if (this._ondpaddown) {
  64935. this._ondpaddown(buttonType);
  64936. }
  64937. this.onPadDownObservable.notifyObservers(buttonType);
  64938. }
  64939. if (newValue === 0) {
  64940. if (this._ondpadup) {
  64941. this._ondpadup(buttonType);
  64942. }
  64943. this.onPadUpObservable.notifyObservers(buttonType);
  64944. }
  64945. }
  64946. return newValue;
  64947. };
  64948. Object.defineProperty(Xbox360Pad.prototype, "buttonA", {
  64949. get: function () {
  64950. return this._buttonA;
  64951. },
  64952. set: function (value) {
  64953. this._buttonA = this._setButtonValue(value, this._buttonA, Xbox360Button.A);
  64954. },
  64955. enumerable: true,
  64956. configurable: true
  64957. });
  64958. Object.defineProperty(Xbox360Pad.prototype, "buttonB", {
  64959. get: function () {
  64960. return this._buttonB;
  64961. },
  64962. set: function (value) {
  64963. this._buttonB = this._setButtonValue(value, this._buttonB, Xbox360Button.B);
  64964. },
  64965. enumerable: true,
  64966. configurable: true
  64967. });
  64968. Object.defineProperty(Xbox360Pad.prototype, "buttonX", {
  64969. get: function () {
  64970. return this._buttonX;
  64971. },
  64972. set: function (value) {
  64973. this._buttonX = this._setButtonValue(value, this._buttonX, Xbox360Button.X);
  64974. },
  64975. enumerable: true,
  64976. configurable: true
  64977. });
  64978. Object.defineProperty(Xbox360Pad.prototype, "buttonY", {
  64979. get: function () {
  64980. return this._buttonY;
  64981. },
  64982. set: function (value) {
  64983. this._buttonY = this._setButtonValue(value, this._buttonY, Xbox360Button.Y);
  64984. },
  64985. enumerable: true,
  64986. configurable: true
  64987. });
  64988. Object.defineProperty(Xbox360Pad.prototype, "buttonStart", {
  64989. get: function () {
  64990. return this._buttonStart;
  64991. },
  64992. set: function (value) {
  64993. this._buttonStart = this._setButtonValue(value, this._buttonStart, Xbox360Button.Start);
  64994. },
  64995. enumerable: true,
  64996. configurable: true
  64997. });
  64998. Object.defineProperty(Xbox360Pad.prototype, "buttonBack", {
  64999. get: function () {
  65000. return this._buttonBack;
  65001. },
  65002. set: function (value) {
  65003. this._buttonBack = this._setButtonValue(value, this._buttonBack, Xbox360Button.Back);
  65004. },
  65005. enumerable: true,
  65006. configurable: true
  65007. });
  65008. Object.defineProperty(Xbox360Pad.prototype, "buttonLB", {
  65009. get: function () {
  65010. return this._buttonLB;
  65011. },
  65012. set: function (value) {
  65013. this._buttonLB = this._setButtonValue(value, this._buttonLB, Xbox360Button.LB);
  65014. },
  65015. enumerable: true,
  65016. configurable: true
  65017. });
  65018. Object.defineProperty(Xbox360Pad.prototype, "buttonRB", {
  65019. get: function () {
  65020. return this._buttonRB;
  65021. },
  65022. set: function (value) {
  65023. this._buttonRB = this._setButtonValue(value, this._buttonRB, Xbox360Button.RB);
  65024. },
  65025. enumerable: true,
  65026. configurable: true
  65027. });
  65028. Object.defineProperty(Xbox360Pad.prototype, "buttonLeftStick", {
  65029. get: function () {
  65030. return this._buttonLeftStick;
  65031. },
  65032. set: function (value) {
  65033. this._buttonLeftStick = this._setButtonValue(value, this._buttonLeftStick, Xbox360Button.LeftStick);
  65034. },
  65035. enumerable: true,
  65036. configurable: true
  65037. });
  65038. Object.defineProperty(Xbox360Pad.prototype, "buttonRightStick", {
  65039. get: function () {
  65040. return this._buttonRightStick;
  65041. },
  65042. set: function (value) {
  65043. this._buttonRightStick = this._setButtonValue(value, this._buttonRightStick, Xbox360Button.RightStick);
  65044. },
  65045. enumerable: true,
  65046. configurable: true
  65047. });
  65048. Object.defineProperty(Xbox360Pad.prototype, "dPadUp", {
  65049. get: function () {
  65050. return this._dPadUp;
  65051. },
  65052. set: function (value) {
  65053. this._dPadUp = this._setDPadValue(value, this._dPadUp, Xbox360Dpad.Up);
  65054. },
  65055. enumerable: true,
  65056. configurable: true
  65057. });
  65058. Object.defineProperty(Xbox360Pad.prototype, "dPadDown", {
  65059. get: function () {
  65060. return this._dPadDown;
  65061. },
  65062. set: function (value) {
  65063. this._dPadDown = this._setDPadValue(value, this._dPadDown, Xbox360Dpad.Down);
  65064. },
  65065. enumerable: true,
  65066. configurable: true
  65067. });
  65068. Object.defineProperty(Xbox360Pad.prototype, "dPadLeft", {
  65069. get: function () {
  65070. return this._dPadLeft;
  65071. },
  65072. set: function (value) {
  65073. this._dPadLeft = this._setDPadValue(value, this._dPadLeft, Xbox360Dpad.Left);
  65074. },
  65075. enumerable: true,
  65076. configurable: true
  65077. });
  65078. Object.defineProperty(Xbox360Pad.prototype, "dPadRight", {
  65079. get: function () {
  65080. return this._dPadRight;
  65081. },
  65082. set: function (value) {
  65083. this._dPadRight = this._setDPadValue(value, this._dPadRight, Xbox360Dpad.Right);
  65084. },
  65085. enumerable: true,
  65086. configurable: true
  65087. });
  65088. Xbox360Pad.prototype.update = function () {
  65089. _super.prototype.update.call(this);
  65090. if (this._isXboxOnePad) {
  65091. this.buttonA = this.browserGamepad.buttons[0].value;
  65092. this.buttonB = this.browserGamepad.buttons[1].value;
  65093. this.buttonX = this.browserGamepad.buttons[2].value;
  65094. this.buttonY = this.browserGamepad.buttons[3].value;
  65095. this.buttonLB = this.browserGamepad.buttons[4].value;
  65096. this.buttonRB = this.browserGamepad.buttons[5].value;
  65097. this.leftTrigger = this.browserGamepad.axes[2];
  65098. this.rightTrigger = this.browserGamepad.axes[5];
  65099. this.buttonBack = this.browserGamepad.buttons[9].value;
  65100. this.buttonStart = this.browserGamepad.buttons[8].value;
  65101. this.buttonLeftStick = this.browserGamepad.buttons[6].value;
  65102. this.buttonRightStick = this.browserGamepad.buttons[7].value;
  65103. this.dPadUp = this.browserGamepad.buttons[11].value;
  65104. this.dPadDown = this.browserGamepad.buttons[12].value;
  65105. this.dPadLeft = this.browserGamepad.buttons[13].value;
  65106. this.dPadRight = this.browserGamepad.buttons[14].value;
  65107. }
  65108. else {
  65109. this.buttonA = this.browserGamepad.buttons[0].value;
  65110. this.buttonB = this.browserGamepad.buttons[1].value;
  65111. this.buttonX = this.browserGamepad.buttons[2].value;
  65112. this.buttonY = this.browserGamepad.buttons[3].value;
  65113. this.buttonLB = this.browserGamepad.buttons[4].value;
  65114. this.buttonRB = this.browserGamepad.buttons[5].value;
  65115. this.leftTrigger = this.browserGamepad.buttons[6].value;
  65116. this.rightTrigger = this.browserGamepad.buttons[7].value;
  65117. this.buttonBack = this.browserGamepad.buttons[8].value;
  65118. this.buttonStart = this.browserGamepad.buttons[9].value;
  65119. this.buttonLeftStick = this.browserGamepad.buttons[10].value;
  65120. this.buttonRightStick = this.browserGamepad.buttons[11].value;
  65121. this.dPadUp = this.browserGamepad.buttons[12].value;
  65122. this.dPadDown = this.browserGamepad.buttons[13].value;
  65123. this.dPadLeft = this.browserGamepad.buttons[14].value;
  65124. this.dPadRight = this.browserGamepad.buttons[15].value;
  65125. }
  65126. };
  65127. Xbox360Pad.prototype.dispose = function () {
  65128. _super.prototype.dispose.call(this);
  65129. this.onButtonDownObservable.clear();
  65130. this.onButtonUpObservable.clear();
  65131. this.onPadDownObservable.clear();
  65132. this.onPadUpObservable.clear();
  65133. };
  65134. return Xbox360Pad;
  65135. }(BABYLON.Gamepad));
  65136. BABYLON.Xbox360Pad = Xbox360Pad;
  65137. })(BABYLON || (BABYLON = {}));
  65138. //# sourceMappingURL=babylon.xboxGamepad.js.map
  65139. var BABYLON;
  65140. (function (BABYLON) {
  65141. var PoseEnabledControllerType;
  65142. (function (PoseEnabledControllerType) {
  65143. PoseEnabledControllerType[PoseEnabledControllerType["VIVE"] = 0] = "VIVE";
  65144. PoseEnabledControllerType[PoseEnabledControllerType["OCULUS"] = 1] = "OCULUS";
  65145. PoseEnabledControllerType[PoseEnabledControllerType["WINDOWS"] = 2] = "WINDOWS";
  65146. PoseEnabledControllerType[PoseEnabledControllerType["GEAR_VR"] = 3] = "GEAR_VR";
  65147. /**
  65148. * Google Daydream
  65149. */
  65150. PoseEnabledControllerType[PoseEnabledControllerType["DAYDREAM"] = 4] = "DAYDREAM";
  65151. PoseEnabledControllerType[PoseEnabledControllerType["GENERIC"] = 5] = "GENERIC";
  65152. })(PoseEnabledControllerType = BABYLON.PoseEnabledControllerType || (BABYLON.PoseEnabledControllerType = {}));
  65153. var PoseEnabledControllerHelper = /** @class */ (function () {
  65154. function PoseEnabledControllerHelper() {
  65155. }
  65156. PoseEnabledControllerHelper.InitiateController = function (vrGamepad) {
  65157. // Oculus Touch
  65158. if (vrGamepad.id.indexOf('Oculus Touch') !== -1) {
  65159. return new BABYLON.OculusTouchController(vrGamepad);
  65160. }
  65161. else if (vrGamepad.id.indexOf(BABYLON.WindowsMotionController.GAMEPAD_ID_PREFIX) === 0) {
  65162. return new BABYLON.WindowsMotionController(vrGamepad);
  65163. }
  65164. else if (vrGamepad.id.toLowerCase().indexOf('openvr') !== -1) {
  65165. return new BABYLON.ViveController(vrGamepad);
  65166. }
  65167. else if (vrGamepad.id.indexOf(BABYLON.GearVRController.GAMEPAD_ID_PREFIX) === 0) {
  65168. return new BABYLON.GearVRController(vrGamepad);
  65169. }
  65170. else if (vrGamepad.id.indexOf(BABYLON.DaydreamController.GAMEPAD_ID_PREFIX) === 0) {
  65171. return new BABYLON.DaydreamController(vrGamepad);
  65172. }
  65173. else {
  65174. return new BABYLON.GenericController(vrGamepad);
  65175. }
  65176. };
  65177. return PoseEnabledControllerHelper;
  65178. }());
  65179. BABYLON.PoseEnabledControllerHelper = PoseEnabledControllerHelper;
  65180. var PoseEnabledController = /** @class */ (function (_super) {
  65181. __extends(PoseEnabledController, _super);
  65182. function PoseEnabledController(browserGamepad) {
  65183. var _this = _super.call(this, browserGamepad.id, browserGamepad.index, browserGamepad) || this;
  65184. // Represents device position and rotation in room space. Should only be used to help calculate babylon space values
  65185. _this._deviceRoomPosition = BABYLON.Vector3.Zero();
  65186. _this._deviceRoomRotationQuaternion = new BABYLON.Quaternion();
  65187. // Represents device position and rotation in babylon space
  65188. _this.devicePosition = BABYLON.Vector3.Zero();
  65189. _this.deviceRotationQuaternion = new BABYLON.Quaternion();
  65190. _this.deviceScaleFactor = 1;
  65191. _this._leftHandSystemQuaternion = new BABYLON.Quaternion();
  65192. _this._deviceToWorld = BABYLON.Matrix.Identity();
  65193. /**
  65194. * Node to be used when casting a ray from the controller
  65195. */
  65196. _this._pointingPoseNode = null;
  65197. _this._workingMatrix = BABYLON.Matrix.Identity();
  65198. _this.type = BABYLON.Gamepad.POSE_ENABLED;
  65199. _this.controllerType = PoseEnabledControllerType.GENERIC;
  65200. _this.position = BABYLON.Vector3.Zero();
  65201. _this.rotationQuaternion = new BABYLON.Quaternion();
  65202. _this._calculatedPosition = BABYLON.Vector3.Zero();
  65203. _this._calculatedRotation = new BABYLON.Quaternion();
  65204. BABYLON.Quaternion.RotationYawPitchRollToRef(Math.PI, 0, 0, _this._leftHandSystemQuaternion);
  65205. return _this;
  65206. }
  65207. PoseEnabledController.prototype.update = function () {
  65208. _super.prototype.update.call(this);
  65209. var pose = this.browserGamepad.pose;
  65210. this.updateFromDevice(pose);
  65211. BABYLON.Vector3.TransformCoordinatesToRef(this._calculatedPosition, this._deviceToWorld, this.devicePosition);
  65212. this._deviceToWorld.getRotationMatrixToRef(this._workingMatrix);
  65213. BABYLON.Quaternion.FromRotationMatrixToRef(this._workingMatrix, this.deviceRotationQuaternion);
  65214. this.deviceRotationQuaternion.multiplyInPlace(this._calculatedRotation);
  65215. if (this._mesh) {
  65216. this._mesh.position.copyFrom(this.devicePosition);
  65217. if (this._mesh.rotationQuaternion) {
  65218. this._mesh.rotationQuaternion.copyFrom(this.deviceRotationQuaternion);
  65219. }
  65220. }
  65221. };
  65222. PoseEnabledController.prototype.updateFromDevice = function (poseData) {
  65223. if (poseData) {
  65224. this.rawPose = poseData;
  65225. if (poseData.position) {
  65226. this._deviceRoomPosition.copyFromFloats(poseData.position[0], poseData.position[1], -poseData.position[2]);
  65227. if (this._mesh && this._mesh.getScene().useRightHandedSystem) {
  65228. this._deviceRoomPosition.z *= -1;
  65229. }
  65230. this._deviceRoomPosition.scaleToRef(this.deviceScaleFactor, this._calculatedPosition);
  65231. this._calculatedPosition.addInPlace(this.position);
  65232. }
  65233. var pose = this.rawPose;
  65234. if (poseData.orientation && pose.orientation) {
  65235. this._deviceRoomRotationQuaternion.copyFromFloats(pose.orientation[0], pose.orientation[1], -pose.orientation[2], -pose.orientation[3]);
  65236. if (this._mesh) {
  65237. if (this._mesh.getScene().useRightHandedSystem) {
  65238. this._deviceRoomRotationQuaternion.z *= -1;
  65239. this._deviceRoomRotationQuaternion.w *= -1;
  65240. }
  65241. else {
  65242. this._deviceRoomRotationQuaternion.multiplyToRef(this._leftHandSystemQuaternion, this._deviceRoomRotationQuaternion);
  65243. }
  65244. }
  65245. // if the camera is set, rotate to the camera's rotation
  65246. this._deviceRoomRotationQuaternion.multiplyToRef(this.rotationQuaternion, this._calculatedRotation);
  65247. }
  65248. }
  65249. };
  65250. PoseEnabledController.prototype.attachToMesh = function (mesh) {
  65251. if (this._mesh) {
  65252. this._mesh.parent = null;
  65253. }
  65254. this._mesh = mesh;
  65255. if (this._poseControlledCamera) {
  65256. this._mesh.parent = this._poseControlledCamera;
  65257. }
  65258. if (!this._mesh.rotationQuaternion) {
  65259. this._mesh.rotationQuaternion = new BABYLON.Quaternion();
  65260. }
  65261. };
  65262. PoseEnabledController.prototype.attachToPoseControlledCamera = function (camera) {
  65263. this._poseControlledCamera = camera;
  65264. if (this._mesh) {
  65265. this._mesh.parent = this._poseControlledCamera;
  65266. }
  65267. };
  65268. PoseEnabledController.prototype.dispose = function () {
  65269. if (this._mesh) {
  65270. this._mesh.dispose();
  65271. }
  65272. this._mesh = null;
  65273. _super.prototype.dispose.call(this);
  65274. };
  65275. Object.defineProperty(PoseEnabledController.prototype, "mesh", {
  65276. get: function () {
  65277. return this._mesh;
  65278. },
  65279. enumerable: true,
  65280. configurable: true
  65281. });
  65282. PoseEnabledController.prototype.getForwardRay = function (length) {
  65283. if (length === void 0) { length = 100; }
  65284. if (!this.mesh) {
  65285. return new BABYLON.Ray(BABYLON.Vector3.Zero(), new BABYLON.Vector3(0, 0, 1), length);
  65286. }
  65287. var m = this._pointingPoseNode ? this._pointingPoseNode.getWorldMatrix() : this.mesh.getWorldMatrix();
  65288. var origin = m.getTranslation();
  65289. var forward = new BABYLON.Vector3(0, 0, -1);
  65290. var forwardWorld = BABYLON.Vector3.TransformNormal(forward, m);
  65291. var direction = BABYLON.Vector3.Normalize(forwardWorld);
  65292. return new BABYLON.Ray(origin, direction, length);
  65293. };
  65294. /**
  65295. * Name of the child mesh that can be used to cast a ray from the controller
  65296. */
  65297. PoseEnabledController.POINTING_POSE = "POINTING_POSE";
  65298. return PoseEnabledController;
  65299. }(BABYLON.Gamepad));
  65300. BABYLON.PoseEnabledController = PoseEnabledController;
  65301. })(BABYLON || (BABYLON = {}));
  65302. //# sourceMappingURL=babylon.poseEnabledController.js.map
  65303. var BABYLON;
  65304. (function (BABYLON) {
  65305. var WebVRController = /** @class */ (function (_super) {
  65306. __extends(WebVRController, _super);
  65307. function WebVRController(vrGamepad) {
  65308. var _this = _super.call(this, vrGamepad) || this;
  65309. // Observables
  65310. _this.onTriggerStateChangedObservable = new BABYLON.Observable();
  65311. _this.onMainButtonStateChangedObservable = new BABYLON.Observable();
  65312. _this.onSecondaryButtonStateChangedObservable = new BABYLON.Observable();
  65313. _this.onPadStateChangedObservable = new BABYLON.Observable();
  65314. _this.onPadValuesChangedObservable = new BABYLON.Observable();
  65315. _this.pad = { x: 0, y: 0 };
  65316. // avoid GC, store state in a tmp object
  65317. _this._changes = {
  65318. pressChanged: false,
  65319. touchChanged: false,
  65320. valueChanged: false,
  65321. changed: false
  65322. };
  65323. _this._buttons = new Array(vrGamepad.buttons.length);
  65324. _this.hand = vrGamepad.hand;
  65325. return _this;
  65326. }
  65327. WebVRController.prototype.onButtonStateChange = function (callback) {
  65328. this._onButtonStateChange = callback;
  65329. };
  65330. Object.defineProperty(WebVRController.prototype, "defaultModel", {
  65331. get: function () {
  65332. return this._defaultModel;
  65333. },
  65334. enumerable: true,
  65335. configurable: true
  65336. });
  65337. WebVRController.prototype.update = function () {
  65338. _super.prototype.update.call(this);
  65339. for (var index = 0; index < this._buttons.length; index++) {
  65340. this._setButtonValue(this.browserGamepad.buttons[index], this._buttons[index], index);
  65341. }
  65342. ;
  65343. if (this.leftStick.x !== this.pad.x || this.leftStick.y !== this.pad.y) {
  65344. this.pad.x = this.leftStick.x;
  65345. this.pad.y = this.leftStick.y;
  65346. this.onPadValuesChangedObservable.notifyObservers(this.pad);
  65347. }
  65348. };
  65349. WebVRController.prototype._setButtonValue = function (newState, currentState, buttonIndex) {
  65350. if (!newState) {
  65351. newState = {
  65352. pressed: false,
  65353. touched: false,
  65354. value: 0
  65355. };
  65356. }
  65357. if (!currentState) {
  65358. this._buttons[buttonIndex] = {
  65359. pressed: newState.pressed,
  65360. touched: newState.touched,
  65361. value: newState.value
  65362. };
  65363. return;
  65364. }
  65365. this._checkChanges(newState, currentState);
  65366. if (this._changes.changed) {
  65367. this._onButtonStateChange && this._onButtonStateChange(this.index, buttonIndex, newState);
  65368. this._handleButtonChange(buttonIndex, newState, this._changes);
  65369. }
  65370. this._buttons[buttonIndex].pressed = newState.pressed;
  65371. this._buttons[buttonIndex].touched = newState.touched;
  65372. // oculus triggers are never 0, thou not touched.
  65373. this._buttons[buttonIndex].value = newState.value < 0.00000001 ? 0 : newState.value;
  65374. };
  65375. WebVRController.prototype._checkChanges = function (newState, currentState) {
  65376. this._changes.pressChanged = newState.pressed !== currentState.pressed;
  65377. this._changes.touchChanged = newState.touched !== currentState.touched;
  65378. this._changes.valueChanged = newState.value !== currentState.value;
  65379. this._changes.changed = this._changes.pressChanged || this._changes.touchChanged || this._changes.valueChanged;
  65380. return this._changes;
  65381. };
  65382. WebVRController.prototype.dispose = function () {
  65383. _super.prototype.dispose.call(this);
  65384. this.onTriggerStateChangedObservable.clear();
  65385. this.onMainButtonStateChangedObservable.clear();
  65386. this.onSecondaryButtonStateChangedObservable.clear();
  65387. this.onPadStateChangedObservable.clear();
  65388. this.onPadValuesChangedObservable.clear();
  65389. };
  65390. return WebVRController;
  65391. }(BABYLON.PoseEnabledController));
  65392. BABYLON.WebVRController = WebVRController;
  65393. })(BABYLON || (BABYLON = {}));
  65394. //# sourceMappingURL=babylon.webVRController.js.map
  65395. var BABYLON;
  65396. (function (BABYLON) {
  65397. var OculusTouchController = /** @class */ (function (_super) {
  65398. __extends(OculusTouchController, _super);
  65399. function OculusTouchController(vrGamepad) {
  65400. var _this = _super.call(this, vrGamepad) || this;
  65401. _this.onSecondaryTriggerStateChangedObservable = new BABYLON.Observable();
  65402. _this.onThumbRestChangedObservable = new BABYLON.Observable();
  65403. _this.controllerType = BABYLON.PoseEnabledControllerType.OCULUS;
  65404. return _this;
  65405. }
  65406. OculusTouchController.prototype.initControllerMesh = function (scene, meshLoaded) {
  65407. var _this = this;
  65408. var meshName;
  65409. // Hand
  65410. if (this.hand === 'left') {
  65411. meshName = OculusTouchController.MODEL_LEFT_FILENAME;
  65412. }
  65413. else {
  65414. meshName = OculusTouchController.MODEL_RIGHT_FILENAME;
  65415. }
  65416. BABYLON.SceneLoader.ImportMesh("", OculusTouchController.MODEL_BASE_URL, meshName, scene, function (newMeshes) {
  65417. /*
  65418. Parent Mesh name: oculus_touch_left
  65419. - body
  65420. - trigger
  65421. - thumbstick
  65422. - grip
  65423. - button_y
  65424. - button_x
  65425. - button_enter
  65426. */
  65427. _this._defaultModel = newMeshes[1];
  65428. _this.attachToMesh(_this._defaultModel);
  65429. if (meshLoaded) {
  65430. meshLoaded(_this._defaultModel);
  65431. }
  65432. });
  65433. };
  65434. Object.defineProperty(OculusTouchController.prototype, "onAButtonStateChangedObservable", {
  65435. // helper getters for left and right hand.
  65436. get: function () {
  65437. if (this.hand === 'right') {
  65438. return this.onMainButtonStateChangedObservable;
  65439. }
  65440. else {
  65441. throw new Error('No A button on left hand');
  65442. }
  65443. },
  65444. enumerable: true,
  65445. configurable: true
  65446. });
  65447. Object.defineProperty(OculusTouchController.prototype, "onBButtonStateChangedObservable", {
  65448. get: function () {
  65449. if (this.hand === 'right') {
  65450. return this.onSecondaryButtonStateChangedObservable;
  65451. }
  65452. else {
  65453. throw new Error('No B button on left hand');
  65454. }
  65455. },
  65456. enumerable: true,
  65457. configurable: true
  65458. });
  65459. Object.defineProperty(OculusTouchController.prototype, "onXButtonStateChangedObservable", {
  65460. get: function () {
  65461. if (this.hand === 'left') {
  65462. return this.onMainButtonStateChangedObservable;
  65463. }
  65464. else {
  65465. throw new Error('No X button on right hand');
  65466. }
  65467. },
  65468. enumerable: true,
  65469. configurable: true
  65470. });
  65471. Object.defineProperty(OculusTouchController.prototype, "onYButtonStateChangedObservable", {
  65472. get: function () {
  65473. if (this.hand === 'left') {
  65474. return this.onSecondaryButtonStateChangedObservable;
  65475. }
  65476. else {
  65477. throw new Error('No Y button on right hand');
  65478. }
  65479. },
  65480. enumerable: true,
  65481. configurable: true
  65482. });
  65483. /*
  65484. 0) thumb stick (touch, press, value = pressed (0,1)). value is in this.leftStick
  65485. 1) index trigger (touch (?), press (only when value > 0.1), value 0 to 1)
  65486. 2) secondary trigger (same)
  65487. 3) A (right) X (left), touch, pressed = value
  65488. 4) B / Y
  65489. 5) thumb rest
  65490. */
  65491. OculusTouchController.prototype._handleButtonChange = function (buttonIdx, state, changes) {
  65492. var notifyObject = state; //{ state: state, changes: changes };
  65493. var triggerDirection = this.hand === 'right' ? -1 : 1;
  65494. switch (buttonIdx) {
  65495. case 0:
  65496. this.onPadStateChangedObservable.notifyObservers(notifyObject);
  65497. return;
  65498. case 1:// index trigger
  65499. if (this._defaultModel) {
  65500. (this._defaultModel.getChildren()[3]).rotation.x = -notifyObject.value * 0.20;
  65501. (this._defaultModel.getChildren()[3]).position.y = -notifyObject.value * 0.005;
  65502. (this._defaultModel.getChildren()[3]).position.z = -notifyObject.value * 0.005;
  65503. }
  65504. this.onTriggerStateChangedObservable.notifyObservers(notifyObject);
  65505. return;
  65506. case 2:// secondary trigger
  65507. if (this._defaultModel) {
  65508. (this._defaultModel.getChildren()[4]).position.x = triggerDirection * notifyObject.value * 0.0035;
  65509. }
  65510. this.onSecondaryTriggerStateChangedObservable.notifyObservers(notifyObject);
  65511. return;
  65512. case 3:
  65513. if (this._defaultModel) {
  65514. if (notifyObject.pressed) {
  65515. (this._defaultModel.getChildren()[1]).position.y = -0.001;
  65516. }
  65517. else {
  65518. (this._defaultModel.getChildren()[1]).position.y = 0;
  65519. }
  65520. }
  65521. this.onMainButtonStateChangedObservable.notifyObservers(notifyObject);
  65522. return;
  65523. case 4:
  65524. if (this._defaultModel) {
  65525. if (notifyObject.pressed) {
  65526. (this._defaultModel.getChildren()[2]).position.y = -0.001;
  65527. }
  65528. else {
  65529. (this._defaultModel.getChildren()[2]).position.y = 0;
  65530. }
  65531. }
  65532. this.onSecondaryButtonStateChangedObservable.notifyObservers(notifyObject);
  65533. return;
  65534. case 5:
  65535. this.onThumbRestChangedObservable.notifyObservers(notifyObject);
  65536. return;
  65537. }
  65538. };
  65539. OculusTouchController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/oculus/';
  65540. OculusTouchController.MODEL_LEFT_FILENAME = 'left.babylon';
  65541. OculusTouchController.MODEL_RIGHT_FILENAME = 'right.babylon';
  65542. return OculusTouchController;
  65543. }(BABYLON.WebVRController));
  65544. BABYLON.OculusTouchController = OculusTouchController;
  65545. })(BABYLON || (BABYLON = {}));
  65546. //# sourceMappingURL=babylon.oculusTouchController.js.map
  65547. var BABYLON;
  65548. (function (BABYLON) {
  65549. var ViveController = /** @class */ (function (_super) {
  65550. __extends(ViveController, _super);
  65551. function ViveController(vrGamepad) {
  65552. var _this = _super.call(this, vrGamepad) || this;
  65553. _this.controllerType = BABYLON.PoseEnabledControllerType.VIVE;
  65554. _this._invertLeftStickY = true;
  65555. return _this;
  65556. }
  65557. ViveController.prototype.initControllerMesh = function (scene, meshLoaded) {
  65558. var _this = this;
  65559. BABYLON.SceneLoader.ImportMesh("", ViveController.MODEL_BASE_URL, ViveController.MODEL_FILENAME, scene, function (newMeshes) {
  65560. /*
  65561. Parent Mesh name: ViveWand
  65562. - body
  65563. - r_gripper
  65564. - l_gripper
  65565. - menu_button
  65566. - system_button
  65567. - trackpad
  65568. - trigger
  65569. - LED
  65570. */
  65571. _this._defaultModel = newMeshes[1];
  65572. _this.attachToMesh(_this._defaultModel);
  65573. if (meshLoaded) {
  65574. meshLoaded(_this._defaultModel);
  65575. }
  65576. });
  65577. };
  65578. Object.defineProperty(ViveController.prototype, "onLeftButtonStateChangedObservable", {
  65579. get: function () {
  65580. return this.onMainButtonStateChangedObservable;
  65581. },
  65582. enumerable: true,
  65583. configurable: true
  65584. });
  65585. Object.defineProperty(ViveController.prototype, "onRightButtonStateChangedObservable", {
  65586. get: function () {
  65587. return this.onMainButtonStateChangedObservable;
  65588. },
  65589. enumerable: true,
  65590. configurable: true
  65591. });
  65592. Object.defineProperty(ViveController.prototype, "onMenuButtonStateChangedObservable", {
  65593. get: function () {
  65594. return this.onSecondaryButtonStateChangedObservable;
  65595. },
  65596. enumerable: true,
  65597. configurable: true
  65598. });
  65599. /**
  65600. * Vive mapping:
  65601. * 0: touchpad
  65602. * 1: trigger
  65603. * 2: left AND right buttons
  65604. * 3: menu button
  65605. */
  65606. ViveController.prototype._handleButtonChange = function (buttonIdx, state, changes) {
  65607. var notifyObject = state; //{ state: state, changes: changes };
  65608. switch (buttonIdx) {
  65609. case 0:
  65610. this.onPadStateChangedObservable.notifyObservers(notifyObject);
  65611. return;
  65612. case 1:// index trigger
  65613. if (this._defaultModel) {
  65614. (this._defaultModel.getChildren()[6]).rotation.x = -notifyObject.value * 0.15;
  65615. }
  65616. this.onTriggerStateChangedObservable.notifyObservers(notifyObject);
  65617. return;
  65618. case 2:// left AND right button
  65619. this.onMainButtonStateChangedObservable.notifyObservers(notifyObject);
  65620. return;
  65621. case 3:
  65622. if (this._defaultModel) {
  65623. if (notifyObject.pressed) {
  65624. (this._defaultModel.getChildren()[2]).position.y = -0.001;
  65625. }
  65626. else {
  65627. (this._defaultModel.getChildren()[2]).position.y = 0;
  65628. }
  65629. }
  65630. this.onSecondaryButtonStateChangedObservable.notifyObservers(notifyObject);
  65631. return;
  65632. }
  65633. };
  65634. ViveController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/vive/';
  65635. ViveController.MODEL_FILENAME = 'wand.babylon';
  65636. return ViveController;
  65637. }(BABYLON.WebVRController));
  65638. BABYLON.ViveController = ViveController;
  65639. })(BABYLON || (BABYLON = {}));
  65640. //# sourceMappingURL=babylon.viveController.js.map
  65641. var BABYLON;
  65642. (function (BABYLON) {
  65643. var GenericController = /** @class */ (function (_super) {
  65644. __extends(GenericController, _super);
  65645. function GenericController(vrGamepad) {
  65646. return _super.call(this, vrGamepad) || this;
  65647. }
  65648. GenericController.prototype.initControllerMesh = function (scene, meshLoaded) {
  65649. var _this = this;
  65650. BABYLON.SceneLoader.ImportMesh("", GenericController.MODEL_BASE_URL, GenericController.MODEL_FILENAME, scene, function (newMeshes) {
  65651. _this._defaultModel = newMeshes[1];
  65652. _this.attachToMesh(_this._defaultModel);
  65653. if (meshLoaded) {
  65654. meshLoaded(_this._defaultModel);
  65655. }
  65656. });
  65657. };
  65658. GenericController.prototype._handleButtonChange = function (buttonIdx, state, changes) {
  65659. console.log("Button id: " + buttonIdx + "state: ");
  65660. console.dir(state);
  65661. };
  65662. GenericController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/generic/';
  65663. GenericController.MODEL_FILENAME = 'generic.babylon';
  65664. return GenericController;
  65665. }(BABYLON.WebVRController));
  65666. BABYLON.GenericController = GenericController;
  65667. })(BABYLON || (BABYLON = {}));
  65668. //# sourceMappingURL=babylon.genericController.js.map
  65669. var BABYLON;
  65670. (function (BABYLON) {
  65671. var LoadedMeshInfo = /** @class */ (function () {
  65672. function LoadedMeshInfo() {
  65673. this.buttonMeshes = {};
  65674. this.axisMeshes = {};
  65675. }
  65676. return LoadedMeshInfo;
  65677. }());
  65678. var WindowsMotionController = /** @class */ (function (_super) {
  65679. __extends(WindowsMotionController, _super);
  65680. function WindowsMotionController(vrGamepad) {
  65681. var _this = _super.call(this, vrGamepad) || this;
  65682. _this._mapping = {
  65683. // Semantic button names
  65684. buttons: ['thumbstick', 'trigger', 'grip', 'menu', 'trackpad'],
  65685. // A mapping of the button name to glTF model node name
  65686. // that should be transformed by button value.
  65687. buttonMeshNames: {
  65688. 'trigger': 'SELECT',
  65689. 'menu': 'MENU',
  65690. 'grip': 'GRASP',
  65691. 'thumbstick': 'THUMBSTICK_PRESS',
  65692. 'trackpad': 'TOUCHPAD_PRESS'
  65693. },
  65694. // This mapping is used to translate from the Motion Controller to Babylon semantics
  65695. buttonObservableNames: {
  65696. 'trigger': 'onTriggerStateChangedObservable',
  65697. 'menu': 'onSecondaryButtonStateChangedObservable',
  65698. 'grip': 'onMainButtonStateChangedObservable',
  65699. 'thumbstick': 'onPadStateChangedObservable',
  65700. 'trackpad': 'onTrackpadChangedObservable'
  65701. },
  65702. // A mapping of the axis name to glTF model node name
  65703. // that should be transformed by axis value.
  65704. // This array mirrors the browserGamepad.axes array, such that
  65705. // the mesh corresponding to axis 0 is in this array index 0.
  65706. axisMeshNames: [
  65707. 'THUMBSTICK_X',
  65708. 'THUMBSTICK_Y',
  65709. 'TOUCHPAD_TOUCH_X',
  65710. 'TOUCHPAD_TOUCH_Y'
  65711. ],
  65712. pointingPoseMeshName: BABYLON.PoseEnabledController.POINTING_POSE
  65713. };
  65714. _this.onTrackpadChangedObservable = new BABYLON.Observable();
  65715. _this.onTrackpadValuesChangedObservable = new BABYLON.Observable();
  65716. _this.trackpad = { x: 0, y: 0 };
  65717. _this.controllerType = BABYLON.PoseEnabledControllerType.WINDOWS;
  65718. _this._loadedMeshInfo = null;
  65719. return _this;
  65720. }
  65721. Object.defineProperty(WindowsMotionController.prototype, "onTriggerButtonStateChangedObservable", {
  65722. get: function () {
  65723. return this.onTriggerStateChangedObservable;
  65724. },
  65725. enumerable: true,
  65726. configurable: true
  65727. });
  65728. Object.defineProperty(WindowsMotionController.prototype, "onMenuButtonStateChangedObservable", {
  65729. get: function () {
  65730. return this.onSecondaryButtonStateChangedObservable;
  65731. },
  65732. enumerable: true,
  65733. configurable: true
  65734. });
  65735. Object.defineProperty(WindowsMotionController.prototype, "onGripButtonStateChangedObservable", {
  65736. get: function () {
  65737. return this.onMainButtonStateChangedObservable;
  65738. },
  65739. enumerable: true,
  65740. configurable: true
  65741. });
  65742. Object.defineProperty(WindowsMotionController.prototype, "onThumbstickButtonStateChangedObservable", {
  65743. get: function () {
  65744. return this.onPadStateChangedObservable;
  65745. },
  65746. enumerable: true,
  65747. configurable: true
  65748. });
  65749. Object.defineProperty(WindowsMotionController.prototype, "onTouchpadButtonStateChangedObservable", {
  65750. get: function () {
  65751. return this.onTrackpadChangedObservable;
  65752. },
  65753. enumerable: true,
  65754. configurable: true
  65755. });
  65756. Object.defineProperty(WindowsMotionController.prototype, "onTouchpadValuesChangedObservable", {
  65757. get: function () {
  65758. return this.onTrackpadValuesChangedObservable;
  65759. },
  65760. enumerable: true,
  65761. configurable: true
  65762. });
  65763. /**
  65764. * Called once per frame by the engine.
  65765. */
  65766. WindowsMotionController.prototype.update = function () {
  65767. _super.prototype.update.call(this);
  65768. if (this.browserGamepad.axes) {
  65769. if (this.browserGamepad.axes[2] != this.trackpad.x || this.browserGamepad.axes[3] != this.trackpad.y) {
  65770. this.trackpad.x = this.browserGamepad["axes"][2];
  65771. this.trackpad.y = this.browserGamepad["axes"][3];
  65772. this.onTrackpadValuesChangedObservable.notifyObservers(this.trackpad);
  65773. }
  65774. // Only need to animate axes if there is a loaded mesh
  65775. if (this._loadedMeshInfo) {
  65776. for (var axis = 0; axis < this._mapping.axisMeshNames.length; axis++) {
  65777. this.lerpAxisTransform(axis, this.browserGamepad.axes[axis]);
  65778. }
  65779. }
  65780. }
  65781. };
  65782. /**
  65783. * Called once for each button that changed state since the last frame
  65784. * @param buttonIdx Which button index changed
  65785. * @param state New state of the button
  65786. * @param changes Which properties on the state changed since last frame
  65787. */
  65788. WindowsMotionController.prototype._handleButtonChange = function (buttonIdx, state, changes) {
  65789. var buttonName = this._mapping.buttons[buttonIdx];
  65790. if (!buttonName) {
  65791. return;
  65792. }
  65793. // Only emit events for buttons that we know how to map from index to name
  65794. var observable = this[(this._mapping.buttonObservableNames)[buttonName]];
  65795. if (observable) {
  65796. observable.notifyObservers(state);
  65797. }
  65798. this.lerpButtonTransform(buttonName, state.value);
  65799. };
  65800. WindowsMotionController.prototype.lerpButtonTransform = function (buttonName, buttonValue) {
  65801. // If there is no loaded mesh, there is nothing to transform.
  65802. if (!this._loadedMeshInfo) {
  65803. return;
  65804. }
  65805. var meshInfo = this._loadedMeshInfo.buttonMeshes[buttonName];
  65806. if (!meshInfo.unpressed.rotationQuaternion || !meshInfo.pressed.rotationQuaternion || !meshInfo.value.rotationQuaternion) {
  65807. return;
  65808. }
  65809. BABYLON.Quaternion.SlerpToRef(meshInfo.unpressed.rotationQuaternion, meshInfo.pressed.rotationQuaternion, buttonValue, meshInfo.value.rotationQuaternion);
  65810. BABYLON.Vector3.LerpToRef(meshInfo.unpressed.position, meshInfo.pressed.position, buttonValue, meshInfo.value.position);
  65811. };
  65812. WindowsMotionController.prototype.lerpAxisTransform = function (axis, axisValue) {
  65813. if (!this._loadedMeshInfo) {
  65814. return;
  65815. }
  65816. var meshInfo = this._loadedMeshInfo.axisMeshes[axis];
  65817. if (!meshInfo) {
  65818. return;
  65819. }
  65820. if (!meshInfo.min.rotationQuaternion || !meshInfo.max.rotationQuaternion || !meshInfo.value.rotationQuaternion) {
  65821. return;
  65822. }
  65823. // Convert from gamepad value range (-1 to +1) to lerp range (0 to 1)
  65824. var lerpValue = axisValue * 0.5 + 0.5;
  65825. BABYLON.Quaternion.SlerpToRef(meshInfo.min.rotationQuaternion, meshInfo.max.rotationQuaternion, lerpValue, meshInfo.value.rotationQuaternion);
  65826. BABYLON.Vector3.LerpToRef(meshInfo.min.position, meshInfo.max.position, lerpValue, meshInfo.value.position);
  65827. };
  65828. /**
  65829. * Implements abstract method on WebVRController class, loading controller meshes and calling this.attachToMesh if successful.
  65830. * @param scene scene in which to add meshes
  65831. * @param meshLoaded optional callback function that will be called if the mesh loads successfully.
  65832. */
  65833. WindowsMotionController.prototype.initControllerMesh = function (scene, meshLoaded, forceDefault) {
  65834. var _this = this;
  65835. if (forceDefault === void 0) { forceDefault = false; }
  65836. var path;
  65837. var filename;
  65838. // Checking if GLB loader is present
  65839. if (BABYLON.SceneLoader.IsPluginForExtensionAvailable(".glb")) {
  65840. // Determine the device specific folder based on the ID suffix
  65841. var device = 'default';
  65842. if (this.id && !forceDefault) {
  65843. var match = this.id.match(WindowsMotionController.GAMEPAD_ID_PATTERN);
  65844. device = ((match && match[0]) || device);
  65845. }
  65846. // Hand
  65847. if (this.hand === 'left') {
  65848. filename = WindowsMotionController.MODEL_LEFT_FILENAME;
  65849. }
  65850. else {
  65851. filename = WindowsMotionController.MODEL_RIGHT_FILENAME;
  65852. }
  65853. path = WindowsMotionController.MODEL_BASE_URL + device + '/';
  65854. }
  65855. else {
  65856. BABYLON.Tools.Warn("You need to reference GLTF loader to load Windows Motion Controllers model. Falling back to generic models");
  65857. path = BABYLON.GenericController.MODEL_BASE_URL;
  65858. filename = BABYLON.GenericController.MODEL_FILENAME;
  65859. }
  65860. BABYLON.SceneLoader.ImportMesh("", path, filename, scene, function (meshes) {
  65861. // glTF files successfully loaded from the remote server, now process them to ensure they are in the right format.
  65862. _this._loadedMeshInfo = _this.processModel(scene, meshes);
  65863. if (!_this._loadedMeshInfo) {
  65864. return;
  65865. }
  65866. _this._defaultModel = _this._loadedMeshInfo.rootNode;
  65867. _this.attachToMesh(_this._defaultModel);
  65868. if (meshLoaded) {
  65869. meshLoaded(_this._defaultModel);
  65870. }
  65871. }, null, function (scene, message) {
  65872. BABYLON.Tools.Log(message);
  65873. BABYLON.Tools.Warn('Failed to retrieve controller model from the remote server: ' + path + filename);
  65874. if (!forceDefault) {
  65875. _this.initControllerMesh(scene, meshLoaded, true);
  65876. }
  65877. });
  65878. };
  65879. /**
  65880. * Takes a list of meshes (as loaded from the glTF file) and finds the root node, as well as nodes that
  65881. * can be transformed by button presses and axes values, based on this._mapping.
  65882. *
  65883. * @param scene scene in which the meshes exist
  65884. * @param meshes list of meshes that make up the controller model to process
  65885. * @return structured view of the given meshes, with mapping of buttons and axes to meshes that can be transformed.
  65886. */
  65887. WindowsMotionController.prototype.processModel = function (scene, meshes) {
  65888. var loadedMeshInfo = null;
  65889. // Create a new mesh to contain the glTF hierarchy
  65890. var parentMesh = new BABYLON.Mesh(this.id + " " + this.hand, scene);
  65891. // Find the root node in the loaded glTF scene, and attach it as a child of 'parentMesh'
  65892. var childMesh = null;
  65893. for (var i = 0; i < meshes.length; i++) {
  65894. var mesh = meshes[i];
  65895. if (!mesh.parent) {
  65896. // Exclude controller meshes from picking results
  65897. mesh.isPickable = false;
  65898. // Handle root node, attach to the new parentMesh
  65899. childMesh = mesh;
  65900. break;
  65901. }
  65902. }
  65903. if (childMesh) {
  65904. childMesh.setParent(parentMesh);
  65905. // Create our mesh info. Note that this method will always return non-null.
  65906. loadedMeshInfo = this.createMeshInfo(parentMesh);
  65907. }
  65908. else {
  65909. BABYLON.Tools.Warn('Could not find root node in model file.');
  65910. }
  65911. return loadedMeshInfo;
  65912. };
  65913. WindowsMotionController.prototype.createMeshInfo = function (rootNode) {
  65914. var loadedMeshInfo = new LoadedMeshInfo();
  65915. var i;
  65916. loadedMeshInfo.rootNode = rootNode;
  65917. // Reset the caches
  65918. loadedMeshInfo.buttonMeshes = {};
  65919. loadedMeshInfo.axisMeshes = {};
  65920. // Button Meshes
  65921. for (i = 0; i < this._mapping.buttons.length; i++) {
  65922. var buttonMeshName = this._mapping.buttonMeshNames[this._mapping.buttons[i]];
  65923. if (!buttonMeshName) {
  65924. BABYLON.Tools.Log('Skipping unknown button at index: ' + i + ' with mapped name: ' + this._mapping.buttons[i]);
  65925. continue;
  65926. }
  65927. var buttonMesh = getChildByName(rootNode, buttonMeshName);
  65928. if (!buttonMesh) {
  65929. BABYLON.Tools.Warn('Missing button mesh with name: ' + buttonMeshName);
  65930. continue;
  65931. }
  65932. var buttonMeshInfo = {
  65933. index: i,
  65934. value: getImmediateChildByName(buttonMesh, 'VALUE'),
  65935. pressed: getImmediateChildByName(buttonMesh, 'PRESSED'),
  65936. unpressed: getImmediateChildByName(buttonMesh, 'UNPRESSED')
  65937. };
  65938. if (buttonMeshInfo.value && buttonMeshInfo.pressed && buttonMeshInfo.unpressed) {
  65939. loadedMeshInfo.buttonMeshes[this._mapping.buttons[i]] = buttonMeshInfo;
  65940. }
  65941. else {
  65942. // If we didn't find the mesh, it simply means this button won't have transforms applied as mapped button value changes.
  65943. BABYLON.Tools.Warn('Missing button submesh under mesh with name: ' + buttonMeshName +
  65944. '(VALUE: ' + !!buttonMeshInfo.value +
  65945. ', PRESSED: ' + !!buttonMeshInfo.pressed +
  65946. ', UNPRESSED:' + !!buttonMeshInfo.unpressed +
  65947. ')');
  65948. }
  65949. }
  65950. // Axis Meshes
  65951. for (i = 0; i < this._mapping.axisMeshNames.length; i++) {
  65952. var axisMeshName = this._mapping.axisMeshNames[i];
  65953. if (!axisMeshName) {
  65954. BABYLON.Tools.Log('Skipping unknown axis at index: ' + i);
  65955. continue;
  65956. }
  65957. var axisMesh = getChildByName(rootNode, axisMeshName);
  65958. if (!axisMesh) {
  65959. BABYLON.Tools.Warn('Missing axis mesh with name: ' + axisMeshName);
  65960. continue;
  65961. }
  65962. var axisMeshInfo = {
  65963. index: i,
  65964. value: getImmediateChildByName(axisMesh, 'VALUE'),
  65965. min: getImmediateChildByName(axisMesh, 'MIN'),
  65966. max: getImmediateChildByName(axisMesh, 'MAX')
  65967. };
  65968. if (axisMeshInfo.value && axisMeshInfo.min && axisMeshInfo.max) {
  65969. loadedMeshInfo.axisMeshes[i] = axisMeshInfo;
  65970. }
  65971. else {
  65972. // If we didn't find the mesh, it simply means thit axis won't have transforms applied as mapped axis values change.
  65973. BABYLON.Tools.Warn('Missing axis submesh under mesh with name: ' + axisMeshName +
  65974. '(VALUE: ' + !!axisMeshInfo.value +
  65975. ', MIN: ' + !!axisMeshInfo.min +
  65976. ', MAX:' + !!axisMeshInfo.max +
  65977. ')');
  65978. }
  65979. }
  65980. // Pointing Ray
  65981. loadedMeshInfo.pointingPoseNode = getChildByName(rootNode, this._mapping.pointingPoseMeshName);
  65982. if (!loadedMeshInfo.pointingPoseNode) {
  65983. BABYLON.Tools.Warn('Missing pointing pose mesh with name: ' + this._mapping.pointingPoseMeshName);
  65984. }
  65985. return loadedMeshInfo;
  65986. // Look through all children recursively. This will return null if no mesh exists with the given name.
  65987. function getChildByName(node, name) {
  65988. return node.getChildMeshes(false, function (n) { return n.name === name; })[0];
  65989. }
  65990. // Look through only immediate children. This will return null if no mesh exists with the given name.
  65991. function getImmediateChildByName(node, name) {
  65992. return node.getChildMeshes(true, function (n) { return n.name == name; })[0];
  65993. }
  65994. };
  65995. WindowsMotionController.prototype.getForwardRay = function (length) {
  65996. if (length === void 0) { length = 100; }
  65997. if (!(this._loadedMeshInfo && this._loadedMeshInfo.pointingPoseNode)) {
  65998. return _super.prototype.getForwardRay.call(this, length);
  65999. }
  66000. var m = this._loadedMeshInfo.pointingPoseNode.getWorldMatrix();
  66001. var origin = m.getTranslation();
  66002. var forward = new BABYLON.Vector3(0, 0, -1);
  66003. var forwardWorld = BABYLON.Vector3.TransformNormal(forward, m);
  66004. var direction = BABYLON.Vector3.Normalize(forwardWorld);
  66005. return new BABYLON.Ray(origin, direction, length);
  66006. };
  66007. WindowsMotionController.prototype.dispose = function () {
  66008. _super.prototype.dispose.call(this);
  66009. this.onTrackpadChangedObservable.clear();
  66010. };
  66011. WindowsMotionController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/microsoft/';
  66012. WindowsMotionController.MODEL_LEFT_FILENAME = 'left.glb';
  66013. WindowsMotionController.MODEL_RIGHT_FILENAME = 'right.glb';
  66014. WindowsMotionController.GAMEPAD_ID_PREFIX = 'Spatial Controller (Spatial Interaction Source) ';
  66015. WindowsMotionController.GAMEPAD_ID_PATTERN = /([0-9a-zA-Z]+-[0-9a-zA-Z]+)$/;
  66016. return WindowsMotionController;
  66017. }(BABYLON.WebVRController));
  66018. BABYLON.WindowsMotionController = WindowsMotionController;
  66019. })(BABYLON || (BABYLON = {}));
  66020. //# sourceMappingURL=babylon.windowsMotionController.js.map
  66021. var BABYLON;
  66022. (function (BABYLON) {
  66023. var GearVRController = /** @class */ (function (_super) {
  66024. __extends(GearVRController, _super);
  66025. function GearVRController(vrGamepad) {
  66026. var _this = _super.call(this, vrGamepad) || this;
  66027. _this._buttonIndexToObservableNameMap = [
  66028. 'onTrackpadChangedObservable',
  66029. 'onTriggerStateChangedObservable' // Trigger
  66030. ];
  66031. _this.controllerType = BABYLON.PoseEnabledControllerType.GEAR_VR;
  66032. return _this;
  66033. }
  66034. GearVRController.prototype.initControllerMesh = function (scene, meshLoaded) {
  66035. var _this = this;
  66036. BABYLON.SceneLoader.ImportMesh("", GearVRController.MODEL_BASE_URL, GearVRController.MODEL_FILENAME, scene, function (newMeshes) {
  66037. _this._defaultModel = newMeshes[1];
  66038. _this.attachToMesh(_this._defaultModel);
  66039. if (meshLoaded) {
  66040. meshLoaded(_this._defaultModel);
  66041. }
  66042. });
  66043. };
  66044. GearVRController.prototype._handleButtonChange = function (buttonIdx, state, changes) {
  66045. if (buttonIdx < this._buttonIndexToObservableNameMap.length) {
  66046. var observableName = this._buttonIndexToObservableNameMap[buttonIdx];
  66047. // Only emit events for buttons that we know how to map from index to observable
  66048. var observable = this[observableName];
  66049. if (observable) {
  66050. observable.notifyObservers(state);
  66051. }
  66052. }
  66053. };
  66054. GearVRController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/generic/';
  66055. GearVRController.MODEL_FILENAME = 'generic.babylon';
  66056. GearVRController.GAMEPAD_ID_PREFIX = 'Gear VR'; // id is 'Gear VR Controller'
  66057. return GearVRController;
  66058. }(BABYLON.WebVRController));
  66059. BABYLON.GearVRController = GearVRController;
  66060. })(BABYLON || (BABYLON = {}));
  66061. //# sourceMappingURL=babylon.gearVRController.js.map
  66062. var BABYLON;
  66063. (function (BABYLON) {
  66064. /**
  66065. * Google Daydream controller
  66066. */
  66067. var DaydreamController = /** @class */ (function (_super) {
  66068. __extends(DaydreamController, _super);
  66069. function DaydreamController(vrGamepad) {
  66070. var _this = _super.call(this, vrGamepad) || this;
  66071. _this.controllerType = BABYLON.PoseEnabledControllerType.DAYDREAM;
  66072. return _this;
  66073. }
  66074. DaydreamController.prototype.initControllerMesh = function (scene, meshLoaded) {
  66075. var _this = this;
  66076. BABYLON.SceneLoader.ImportMesh("", DaydreamController.MODEL_BASE_URL, DaydreamController.MODEL_FILENAME, scene, function (newMeshes) {
  66077. _this._defaultModel = newMeshes[1];
  66078. _this.attachToMesh(_this._defaultModel);
  66079. if (meshLoaded) {
  66080. meshLoaded(_this._defaultModel);
  66081. }
  66082. });
  66083. };
  66084. DaydreamController.prototype._handleButtonChange = function (buttonIdx, state, changes) {
  66085. // Daydream controller only has 1 GamepadButton (on the trackpad).
  66086. if (buttonIdx === 0) {
  66087. var observable = this.onTriggerStateChangedObservable;
  66088. if (observable) {
  66089. observable.notifyObservers(state);
  66090. }
  66091. }
  66092. else {
  66093. // If the app or home buttons are ever made available
  66094. BABYLON.Tools.Warn("Unrecognized Daydream button index: " + buttonIdx);
  66095. }
  66096. };
  66097. /**
  66098. * Base Url for the controller model.
  66099. */
  66100. DaydreamController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/generic/';
  66101. /**
  66102. * File name for the controller model.
  66103. */
  66104. DaydreamController.MODEL_FILENAME = 'generic.babylon';
  66105. /**
  66106. * Gamepad Id prefix used to identify Daydream Controller.
  66107. */
  66108. DaydreamController.GAMEPAD_ID_PREFIX = 'Daydream'; // id is 'Daydream Controller'
  66109. return DaydreamController;
  66110. }(BABYLON.WebVRController));
  66111. BABYLON.DaydreamController = DaydreamController;
  66112. })(BABYLON || (BABYLON = {}));
  66113. //# sourceMappingURL=babylon.daydreamController.js.map
  66114. var BABYLON;
  66115. (function (BABYLON) {
  66116. var FollowCamera = /** @class */ (function (_super) {
  66117. __extends(FollowCamera, _super);
  66118. function FollowCamera(name, position, scene, lockedTarget) {
  66119. if (lockedTarget === void 0) { lockedTarget = null; }
  66120. var _this = _super.call(this, name, position, scene) || this;
  66121. _this.radius = 12;
  66122. _this.rotationOffset = 0;
  66123. _this.heightOffset = 4;
  66124. _this.cameraAcceleration = 0.05;
  66125. _this.maxCameraSpeed = 20;
  66126. _this.lockedTarget = lockedTarget;
  66127. return _this;
  66128. }
  66129. FollowCamera.prototype.getRadians = function (degrees) {
  66130. return degrees * Math.PI / 180;
  66131. };
  66132. FollowCamera.prototype.follow = function (cameraTarget) {
  66133. if (!cameraTarget)
  66134. return;
  66135. var yRotation;
  66136. if (cameraTarget.rotationQuaternion) {
  66137. var rotMatrix = new BABYLON.Matrix();
  66138. cameraTarget.rotationQuaternion.toRotationMatrix(rotMatrix);
  66139. yRotation = Math.atan2(rotMatrix.m[8], rotMatrix.m[10]);
  66140. }
  66141. else {
  66142. yRotation = cameraTarget.rotation.y;
  66143. }
  66144. var radians = this.getRadians(this.rotationOffset) + yRotation;
  66145. var targetPosition = cameraTarget.getAbsolutePosition();
  66146. var targetX = targetPosition.x + Math.sin(radians) * this.radius;
  66147. var targetZ = targetPosition.z + Math.cos(radians) * this.radius;
  66148. var dx = targetX - this.position.x;
  66149. var dy = (targetPosition.y + this.heightOffset) - this.position.y;
  66150. var dz = (targetZ) - this.position.z;
  66151. var vx = dx * this.cameraAcceleration * 2; //this is set to .05
  66152. var vy = dy * this.cameraAcceleration;
  66153. var vz = dz * this.cameraAcceleration * 2;
  66154. if (vx > this.maxCameraSpeed || vx < -this.maxCameraSpeed) {
  66155. vx = vx < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  66156. }
  66157. if (vy > this.maxCameraSpeed || vy < -this.maxCameraSpeed) {
  66158. vy = vy < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  66159. }
  66160. if (vz > this.maxCameraSpeed || vz < -this.maxCameraSpeed) {
  66161. vz = vz < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  66162. }
  66163. this.position = new BABYLON.Vector3(this.position.x + vx, this.position.y + vy, this.position.z + vz);
  66164. this.setTarget(targetPosition);
  66165. };
  66166. FollowCamera.prototype._checkInputs = function () {
  66167. _super.prototype._checkInputs.call(this);
  66168. if (this.lockedTarget) {
  66169. this.follow(this.lockedTarget);
  66170. }
  66171. };
  66172. FollowCamera.prototype.getClassName = function () {
  66173. return "FollowCamera";
  66174. };
  66175. __decorate([
  66176. BABYLON.serialize()
  66177. ], FollowCamera.prototype, "radius", void 0);
  66178. __decorate([
  66179. BABYLON.serialize()
  66180. ], FollowCamera.prototype, "rotationOffset", void 0);
  66181. __decorate([
  66182. BABYLON.serialize()
  66183. ], FollowCamera.prototype, "heightOffset", void 0);
  66184. __decorate([
  66185. BABYLON.serialize()
  66186. ], FollowCamera.prototype, "cameraAcceleration", void 0);
  66187. __decorate([
  66188. BABYLON.serialize()
  66189. ], FollowCamera.prototype, "maxCameraSpeed", void 0);
  66190. __decorate([
  66191. BABYLON.serializeAsMeshReference("lockedTargetId")
  66192. ], FollowCamera.prototype, "lockedTarget", void 0);
  66193. return FollowCamera;
  66194. }(BABYLON.TargetCamera));
  66195. BABYLON.FollowCamera = FollowCamera;
  66196. var ArcFollowCamera = /** @class */ (function (_super) {
  66197. __extends(ArcFollowCamera, _super);
  66198. function ArcFollowCamera(name, alpha, beta, radius, target, scene) {
  66199. var _this = _super.call(this, name, BABYLON.Vector3.Zero(), scene) || this;
  66200. _this.alpha = alpha;
  66201. _this.beta = beta;
  66202. _this.radius = radius;
  66203. _this.target = target;
  66204. _this._cartesianCoordinates = BABYLON.Vector3.Zero();
  66205. _this.follow();
  66206. return _this;
  66207. }
  66208. ArcFollowCamera.prototype.follow = function () {
  66209. if (!this.target) {
  66210. return;
  66211. }
  66212. this._cartesianCoordinates.x = this.radius * Math.cos(this.alpha) * Math.cos(this.beta);
  66213. this._cartesianCoordinates.y = this.radius * Math.sin(this.beta);
  66214. this._cartesianCoordinates.z = this.radius * Math.sin(this.alpha) * Math.cos(this.beta);
  66215. var targetPosition = this.target.getAbsolutePosition();
  66216. this.position = targetPosition.add(this._cartesianCoordinates);
  66217. this.setTarget(targetPosition);
  66218. };
  66219. ArcFollowCamera.prototype._checkInputs = function () {
  66220. _super.prototype._checkInputs.call(this);
  66221. this.follow();
  66222. };
  66223. ArcFollowCamera.prototype.getClassName = function () {
  66224. return "ArcFollowCamera";
  66225. };
  66226. return ArcFollowCamera;
  66227. }(BABYLON.TargetCamera));
  66228. BABYLON.ArcFollowCamera = ArcFollowCamera;
  66229. })(BABYLON || (BABYLON = {}));
  66230. //# sourceMappingURL=babylon.followCamera.js.map
  66231. var BABYLON;
  66232. (function (BABYLON) {
  66233. // We're mainly based on the logic defined into the FreeCamera code
  66234. var UniversalCamera = /** @class */ (function (_super) {
  66235. __extends(UniversalCamera, _super);
  66236. //-- end properties for backward compatibility for inputs
  66237. function UniversalCamera(name, position, scene) {
  66238. var _this = _super.call(this, name, position, scene) || this;
  66239. _this.inputs.addGamepad();
  66240. return _this;
  66241. }
  66242. Object.defineProperty(UniversalCamera.prototype, "gamepadAngularSensibility", {
  66243. //-- Begin properties for backward compatibility for inputs
  66244. get: function () {
  66245. var gamepad = this.inputs.attached["gamepad"];
  66246. if (gamepad)
  66247. return gamepad.gamepadAngularSensibility;
  66248. return 0;
  66249. },
  66250. set: function (value) {
  66251. var gamepad = this.inputs.attached["gamepad"];
  66252. if (gamepad)
  66253. gamepad.gamepadAngularSensibility = value;
  66254. },
  66255. enumerable: true,
  66256. configurable: true
  66257. });
  66258. Object.defineProperty(UniversalCamera.prototype, "gamepadMoveSensibility", {
  66259. get: function () {
  66260. var gamepad = this.inputs.attached["gamepad"];
  66261. if (gamepad)
  66262. return gamepad.gamepadMoveSensibility;
  66263. return 0;
  66264. },
  66265. set: function (value) {
  66266. var gamepad = this.inputs.attached["gamepad"];
  66267. if (gamepad)
  66268. gamepad.gamepadMoveSensibility = value;
  66269. },
  66270. enumerable: true,
  66271. configurable: true
  66272. });
  66273. UniversalCamera.prototype.getClassName = function () {
  66274. return "UniversalCamera";
  66275. };
  66276. return UniversalCamera;
  66277. }(BABYLON.TouchCamera));
  66278. BABYLON.UniversalCamera = UniversalCamera;
  66279. })(BABYLON || (BABYLON = {}));
  66280. //# sourceMappingURL=babylon.universalCamera.js.map
  66281. var BABYLON;
  66282. (function (BABYLON) {
  66283. // We're mainly based on the logic defined into the FreeCamera code
  66284. var GamepadCamera = /** @class */ (function (_super) {
  66285. __extends(GamepadCamera, _super);
  66286. //-- end properties for backward compatibility for inputs
  66287. function GamepadCamera(name, position, scene) {
  66288. return _super.call(this, name, position, scene) || this;
  66289. }
  66290. Object.defineProperty(GamepadCamera.prototype, "gamepadAngularSensibility", {
  66291. //-- Begin properties for backward compatibility for inputs
  66292. get: function () {
  66293. var gamepad = this.inputs.attached["gamepad"];
  66294. if (gamepad)
  66295. return gamepad.gamepadAngularSensibility;
  66296. return 0;
  66297. },
  66298. set: function (value) {
  66299. var gamepad = this.inputs.attached["gamepad"];
  66300. if (gamepad)
  66301. gamepad.gamepadAngularSensibility = value;
  66302. },
  66303. enumerable: true,
  66304. configurable: true
  66305. });
  66306. Object.defineProperty(GamepadCamera.prototype, "gamepadMoveSensibility", {
  66307. get: function () {
  66308. var gamepad = this.inputs.attached["gamepad"];
  66309. if (gamepad)
  66310. return gamepad.gamepadMoveSensibility;
  66311. return 0;
  66312. },
  66313. set: function (value) {
  66314. var gamepad = this.inputs.attached["gamepad"];
  66315. if (gamepad)
  66316. gamepad.gamepadMoveSensibility = value;
  66317. },
  66318. enumerable: true,
  66319. configurable: true
  66320. });
  66321. GamepadCamera.prototype.getClassName = function () {
  66322. return "GamepadCamera";
  66323. };
  66324. return GamepadCamera;
  66325. }(BABYLON.UniversalCamera));
  66326. BABYLON.GamepadCamera = GamepadCamera;
  66327. })(BABYLON || (BABYLON = {}));
  66328. //# sourceMappingURL=babylon.gamepadCamera.js.map
  66329. var BABYLON;
  66330. (function (BABYLON) {
  66331. var PostProcessRenderPipelineManager = /** @class */ (function () {
  66332. function PostProcessRenderPipelineManager() {
  66333. this._renderPipelines = {};
  66334. }
  66335. PostProcessRenderPipelineManager.prototype.addPipeline = function (renderPipeline) {
  66336. this._renderPipelines[renderPipeline._name] = renderPipeline;
  66337. };
  66338. PostProcessRenderPipelineManager.prototype.attachCamerasToRenderPipeline = function (renderPipelineName, cameras, unique) {
  66339. if (unique === void 0) { unique = false; }
  66340. var renderPipeline = this._renderPipelines[renderPipelineName];
  66341. if (!renderPipeline) {
  66342. return;
  66343. }
  66344. renderPipeline._attachCameras(cameras, unique);
  66345. };
  66346. PostProcessRenderPipelineManager.prototype.detachCamerasFromRenderPipeline = function (renderPipelineName, cameras) {
  66347. var renderPipeline = this._renderPipelines[renderPipelineName];
  66348. if (!renderPipeline) {
  66349. return;
  66350. }
  66351. renderPipeline._detachCameras(cameras);
  66352. };
  66353. PostProcessRenderPipelineManager.prototype.enableEffectInPipeline = function (renderPipelineName, renderEffectName, cameras) {
  66354. var renderPipeline = this._renderPipelines[renderPipelineName];
  66355. if (!renderPipeline) {
  66356. return;
  66357. }
  66358. renderPipeline._enableEffect(renderEffectName, cameras);
  66359. };
  66360. PostProcessRenderPipelineManager.prototype.disableEffectInPipeline = function (renderPipelineName, renderEffectName, cameras) {
  66361. var renderPipeline = this._renderPipelines[renderPipelineName];
  66362. if (!renderPipeline) {
  66363. return;
  66364. }
  66365. renderPipeline._disableEffect(renderEffectName, cameras);
  66366. };
  66367. PostProcessRenderPipelineManager.prototype.update = function () {
  66368. for (var renderPipelineName in this._renderPipelines) {
  66369. if (this._renderPipelines.hasOwnProperty(renderPipelineName)) {
  66370. var pipeline = this._renderPipelines[renderPipelineName];
  66371. if (!pipeline.isSupported) {
  66372. pipeline.dispose();
  66373. delete this._renderPipelines[renderPipelineName];
  66374. }
  66375. else {
  66376. pipeline._update();
  66377. }
  66378. }
  66379. }
  66380. };
  66381. PostProcessRenderPipelineManager.prototype._rebuild = function () {
  66382. for (var renderPipelineName in this._renderPipelines) {
  66383. if (this._renderPipelines.hasOwnProperty(renderPipelineName)) {
  66384. var pipeline = this._renderPipelines[renderPipelineName];
  66385. pipeline._rebuild();
  66386. }
  66387. }
  66388. };
  66389. PostProcessRenderPipelineManager.prototype.dispose = function () {
  66390. for (var renderPipelineName in this._renderPipelines) {
  66391. if (this._renderPipelines.hasOwnProperty(renderPipelineName)) {
  66392. var pipeline = this._renderPipelines[renderPipelineName];
  66393. pipeline.dispose();
  66394. }
  66395. }
  66396. };
  66397. return PostProcessRenderPipelineManager;
  66398. }());
  66399. BABYLON.PostProcessRenderPipelineManager = PostProcessRenderPipelineManager;
  66400. })(BABYLON || (BABYLON = {}));
  66401. //# sourceMappingURL=babylon.postProcessRenderPipelineManager.js.map
  66402. var BABYLON;
  66403. (function (BABYLON) {
  66404. /**
  66405. * This represents a set of one or more post processes in Babylon.
  66406. * A post process can be used to apply a shader to a texture after it is rendered.
  66407. * @example https://doc.babylonjs.com/how_to/how_to_use_postprocessrenderpipeline
  66408. */
  66409. var PostProcessRenderEffect = /** @class */ (function () {
  66410. /**
  66411. * Instantiates a post process render effect.
  66412. * A post process can be used to apply a shader to a texture after it is rendered.
  66413. * @param engine The engine the effect is tied to
  66414. * @param name The name of the effect
  66415. * @param getPostProcesses A function that returns a set of post processes which the effect will run in order to be run.
  66416. * @param singleInstance False if this post process can be run on multiple cameras. (default: true)
  66417. */
  66418. function PostProcessRenderEffect(engine, name, getPostProcesses, singleInstance) {
  66419. this._name = name;
  66420. this._singleInstance = singleInstance || true;
  66421. this._getPostProcesses = getPostProcesses;
  66422. this._cameras = {};
  66423. this._indicesForCamera = {};
  66424. this._postProcesses = {};
  66425. }
  66426. Object.defineProperty(PostProcessRenderEffect.prototype, "isSupported", {
  66427. /**
  66428. * Checks if all the post processes in the effect are supported.
  66429. */
  66430. get: function () {
  66431. for (var index in this._postProcesses) {
  66432. for (var ppIndex in this._postProcesses[index]) {
  66433. if (!this._postProcesses[index][ppIndex].isSupported) {
  66434. return false;
  66435. }
  66436. }
  66437. }
  66438. return true;
  66439. },
  66440. enumerable: true,
  66441. configurable: true
  66442. });
  66443. /**
  66444. * Updates the current state of the effect
  66445. */
  66446. PostProcessRenderEffect.prototype._update = function () {
  66447. };
  66448. /**
  66449. * Attaches the effect on cameras
  66450. * @param cameras The camera to attach to.
  66451. */
  66452. PostProcessRenderEffect.prototype._attachCameras = function (cameras) {
  66453. var _this = this;
  66454. var cameraKey;
  66455. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  66456. if (!cams) {
  66457. return;
  66458. }
  66459. for (var i = 0; i < cams.length; i++) {
  66460. var camera = cams[i];
  66461. var cameraName = camera.name;
  66462. if (this._singleInstance) {
  66463. cameraKey = 0;
  66464. }
  66465. else {
  66466. cameraKey = cameraName;
  66467. }
  66468. if (!this._postProcesses[cameraKey]) {
  66469. var postProcess = this._getPostProcesses();
  66470. if (postProcess) {
  66471. this._postProcesses[cameraKey] = Array.isArray(postProcess) ? postProcess : [postProcess];
  66472. }
  66473. }
  66474. if (!this._indicesForCamera[cameraName]) {
  66475. this._indicesForCamera[cameraName] = [];
  66476. }
  66477. this._postProcesses[cameraKey].forEach(function (postProcess) {
  66478. var index = camera.attachPostProcess(postProcess);
  66479. _this._indicesForCamera[cameraName].push(index);
  66480. });
  66481. if (!this._cameras[cameraName]) {
  66482. this._cameras[cameraName] = camera;
  66483. }
  66484. }
  66485. };
  66486. /**
  66487. * Detatches the effect on cameras
  66488. * @param cameras The camera to detatch from.
  66489. */
  66490. PostProcessRenderEffect.prototype._detachCameras = function (cameras) {
  66491. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  66492. if (!cams) {
  66493. return;
  66494. }
  66495. for (var i = 0; i < cams.length; i++) {
  66496. var camera = cams[i];
  66497. var cameraName = camera.name;
  66498. this._postProcesses[this._singleInstance ? 0 : cameraName].forEach(function (postProcess) {
  66499. camera.detachPostProcess(postProcess);
  66500. });
  66501. if (this._cameras[cameraName]) {
  66502. //this._indicesForCamera.splice(index, 1);
  66503. this._cameras[cameraName] = null;
  66504. }
  66505. }
  66506. };
  66507. /**
  66508. * Enables the effect on given cameras
  66509. * @param cameras The camera to enable.
  66510. */
  66511. PostProcessRenderEffect.prototype._enable = function (cameras) {
  66512. var _this = this;
  66513. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  66514. if (!cams) {
  66515. return;
  66516. }
  66517. for (var i = 0; i < cams.length; i++) {
  66518. var camera = cams[i];
  66519. var cameraName = camera.name;
  66520. for (var j = 0; j < this._indicesForCamera[cameraName].length; j++) {
  66521. if (camera._postProcesses[this._indicesForCamera[cameraName][j]] === undefined) {
  66522. this._postProcesses[this._singleInstance ? 0 : cameraName].forEach(function (postProcess) {
  66523. cams[i].attachPostProcess(postProcess, _this._indicesForCamera[cameraName][j]);
  66524. });
  66525. }
  66526. }
  66527. }
  66528. };
  66529. /**
  66530. * Disables the effect on the given cameras
  66531. * @param cameras The camera to disable.
  66532. */
  66533. PostProcessRenderEffect.prototype._disable = function (cameras) {
  66534. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  66535. if (!cams) {
  66536. return;
  66537. }
  66538. for (var i = 0; i < cams.length; i++) {
  66539. var camera = cams[i];
  66540. var cameraName = camera.name;
  66541. this._postProcesses[this._singleInstance ? 0 : cameraName].forEach(function (postProcess) {
  66542. camera.detachPostProcess(postProcess);
  66543. });
  66544. }
  66545. };
  66546. /**
  66547. * Gets a list of the post processes contained in the effect.
  66548. * @param camera The camera to get the post processes on.
  66549. * @returns The list of the post processes in the effect.
  66550. */
  66551. PostProcessRenderEffect.prototype.getPostProcesses = function (camera) {
  66552. if (this._singleInstance) {
  66553. return this._postProcesses[0];
  66554. }
  66555. else {
  66556. if (!camera) {
  66557. return null;
  66558. }
  66559. return this._postProcesses[camera.name];
  66560. }
  66561. };
  66562. return PostProcessRenderEffect;
  66563. }());
  66564. BABYLON.PostProcessRenderEffect = PostProcessRenderEffect;
  66565. })(BABYLON || (BABYLON = {}));
  66566. //# sourceMappingURL=babylon.postProcessRenderEffect.js.map
  66567. var BABYLON;
  66568. (function (BABYLON) {
  66569. var PostProcessRenderPipeline = /** @class */ (function () {
  66570. function PostProcessRenderPipeline(engine, name) {
  66571. this.engine = engine;
  66572. this._name = name;
  66573. this._renderEffects = {};
  66574. this._renderEffectsForIsolatedPass = new Array();
  66575. this._cameras = [];
  66576. }
  66577. PostProcessRenderPipeline.prototype.getClassName = function () {
  66578. return "PostProcessRenderPipeline";
  66579. };
  66580. Object.defineProperty(PostProcessRenderPipeline.prototype, "isSupported", {
  66581. get: function () {
  66582. for (var renderEffectName in this._renderEffects) {
  66583. if (this._renderEffects.hasOwnProperty(renderEffectName)) {
  66584. if (!this._renderEffects[renderEffectName].isSupported) {
  66585. return false;
  66586. }
  66587. }
  66588. }
  66589. return true;
  66590. },
  66591. enumerable: true,
  66592. configurable: true
  66593. });
  66594. PostProcessRenderPipeline.prototype.addEffect = function (renderEffect) {
  66595. this._renderEffects[renderEffect._name] = renderEffect;
  66596. };
  66597. // private
  66598. PostProcessRenderPipeline.prototype._rebuild = function () {
  66599. };
  66600. PostProcessRenderPipeline.prototype._enableEffect = function (renderEffectName, cameras) {
  66601. var renderEffects = this._renderEffects[renderEffectName];
  66602. if (!renderEffects) {
  66603. return;
  66604. }
  66605. renderEffects._enable(BABYLON.Tools.MakeArray(cameras || this._cameras));
  66606. };
  66607. PostProcessRenderPipeline.prototype._disableEffect = function (renderEffectName, cameras) {
  66608. var renderEffects = this._renderEffects[renderEffectName];
  66609. if (!renderEffects) {
  66610. return;
  66611. }
  66612. renderEffects._disable(BABYLON.Tools.MakeArray(cameras || this._cameras));
  66613. };
  66614. PostProcessRenderPipeline.prototype._attachCameras = function (cameras, unique) {
  66615. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  66616. if (!cams) {
  66617. return;
  66618. }
  66619. var indicesToDelete = [];
  66620. var i;
  66621. for (i = 0; i < cams.length; i++) {
  66622. var camera = cams[i];
  66623. var cameraName = camera.name;
  66624. if (this._cameras.indexOf(camera) === -1) {
  66625. this._cameras[cameraName] = camera;
  66626. }
  66627. else if (unique) {
  66628. indicesToDelete.push(i);
  66629. }
  66630. }
  66631. for (i = 0; i < indicesToDelete.length; i++) {
  66632. cameras.splice(indicesToDelete[i], 1);
  66633. }
  66634. for (var renderEffectName in this._renderEffects) {
  66635. if (this._renderEffects.hasOwnProperty(renderEffectName)) {
  66636. this._renderEffects[renderEffectName]._attachCameras(cams);
  66637. }
  66638. }
  66639. };
  66640. PostProcessRenderPipeline.prototype._detachCameras = function (cameras) {
  66641. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  66642. if (!cams) {
  66643. return;
  66644. }
  66645. for (var renderEffectName in this._renderEffects) {
  66646. if (this._renderEffects.hasOwnProperty(renderEffectName)) {
  66647. this._renderEffects[renderEffectName]._detachCameras(cams);
  66648. }
  66649. }
  66650. for (var i = 0; i < cams.length; i++) {
  66651. this._cameras.splice(this._cameras.indexOf(cams[i]), 1);
  66652. }
  66653. };
  66654. PostProcessRenderPipeline.prototype._update = function () {
  66655. for (var renderEffectName in this._renderEffects) {
  66656. if (this._renderEffects.hasOwnProperty(renderEffectName)) {
  66657. this._renderEffects[renderEffectName]._update();
  66658. }
  66659. }
  66660. for (var i = 0; i < this._cameras.length; i++) {
  66661. var cameraName = this._cameras[i].name;
  66662. if (this._renderEffectsForIsolatedPass[cameraName]) {
  66663. this._renderEffectsForIsolatedPass[cameraName]._update();
  66664. }
  66665. }
  66666. };
  66667. PostProcessRenderPipeline.prototype._reset = function () {
  66668. this._renderEffects = {};
  66669. this._renderEffectsForIsolatedPass = new Array();
  66670. };
  66671. PostProcessRenderPipeline.prototype._enableMSAAOnFirstPostProcess = function () {
  66672. // 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)
  66673. var effectKeys = Object.keys(this._renderEffects);
  66674. if (this.engine.webGLVersion >= 2 && effectKeys.length > 0) {
  66675. var postProcesses = this._renderEffects[effectKeys[0]].getPostProcesses();
  66676. if (postProcesses) {
  66677. postProcesses[0].samples = 4;
  66678. return true;
  66679. }
  66680. }
  66681. return false;
  66682. };
  66683. PostProcessRenderPipeline.prototype.dispose = function () {
  66684. // Must be implemented by children
  66685. };
  66686. __decorate([
  66687. BABYLON.serialize()
  66688. ], PostProcessRenderPipeline.prototype, "_name", void 0);
  66689. return PostProcessRenderPipeline;
  66690. }());
  66691. BABYLON.PostProcessRenderPipeline = PostProcessRenderPipeline;
  66692. })(BABYLON || (BABYLON = {}));
  66693. //# sourceMappingURL=babylon.postProcessRenderPipeline.js.map
  66694. var BABYLON;
  66695. (function (BABYLON) {
  66696. /**
  66697. * This represents a depth renderer in Babylon.
  66698. * A depth renderer will render to it's depth map every frame which can be displayed or used in post processing
  66699. */
  66700. var DepthRenderer = /** @class */ (function () {
  66701. /**
  66702. * Instantiates a depth renderer
  66703. * @param scene The scene the renderer belongs to
  66704. * @param type The texture type of the depth map (default: Engine.TEXTURETYPE_FLOAT)
  66705. * @param camera The camera to be used to render the depth map (default: scene's active camera)
  66706. */
  66707. function DepthRenderer(scene, type, camera) {
  66708. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_FLOAT; }
  66709. if (camera === void 0) { camera = null; }
  66710. var _this = this;
  66711. this._scene = scene;
  66712. this._camera = camera;
  66713. var engine = scene.getEngine();
  66714. // Render target
  66715. this._depthMap = new BABYLON.RenderTargetTexture("depthMap", { width: engine.getRenderWidth(), height: engine.getRenderHeight() }, this._scene, false, true, type);
  66716. this._depthMap.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  66717. this._depthMap.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  66718. this._depthMap.refreshRate = 1;
  66719. this._depthMap.renderParticles = false;
  66720. this._depthMap.renderList = null;
  66721. // Camera to get depth map from to support multiple concurrent cameras
  66722. this._depthMap.activeCamera = this._camera;
  66723. this._depthMap.ignoreCameraViewport = true;
  66724. this._depthMap.useCameraPostProcesses = false;
  66725. // set default depth value to 1.0 (far away)
  66726. this._depthMap.onClearObservable.add(function (engine) {
  66727. engine.clear(new BABYLON.Color4(1.0, 1.0, 1.0, 1.0), true, true, true);
  66728. });
  66729. // Custom render function
  66730. var renderSubMesh = function (subMesh) {
  66731. var mesh = subMesh.getRenderingMesh();
  66732. var scene = _this._scene;
  66733. var engine = scene.getEngine();
  66734. var material = subMesh.getMaterial();
  66735. if (!material) {
  66736. return;
  66737. }
  66738. // Culling and reverse (right handed system)
  66739. engine.setState(material.backFaceCulling, 0, false, scene.useRightHandedSystem);
  66740. // Managing instances
  66741. var batch = mesh._getInstancesRenderList(subMesh._id);
  66742. if (batch.mustReturn) {
  66743. return;
  66744. }
  66745. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null);
  66746. var camera = _this._camera || scene.activeCamera;
  66747. if (_this.isReady(subMesh, hardwareInstancedRendering) && camera) {
  66748. engine.enableEffect(_this._effect);
  66749. mesh._bind(subMesh, _this._effect, BABYLON.Material.TriangleFillMode);
  66750. _this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  66751. _this._effect.setFloat2("depthValues", camera.minZ, camera.minZ + camera.maxZ);
  66752. // Alpha test
  66753. if (material && material.needAlphaTesting()) {
  66754. var alphaTexture = material.getAlphaTestTexture();
  66755. if (alphaTexture) {
  66756. _this._effect.setTexture("diffuseSampler", alphaTexture);
  66757. _this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  66758. }
  66759. }
  66760. // Bones
  66761. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  66762. _this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  66763. }
  66764. // Draw
  66765. mesh._processRendering(subMesh, _this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effect.setMatrix("world", world); });
  66766. }
  66767. };
  66768. this._depthMap.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes) {
  66769. var index;
  66770. if (depthOnlySubMeshes.length) {
  66771. engine.setColorWrite(false);
  66772. for (index = 0; index < depthOnlySubMeshes.length; index++) {
  66773. renderSubMesh(depthOnlySubMeshes.data[index]);
  66774. }
  66775. engine.setColorWrite(true);
  66776. }
  66777. for (index = 0; index < opaqueSubMeshes.length; index++) {
  66778. renderSubMesh(opaqueSubMeshes.data[index]);
  66779. }
  66780. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  66781. renderSubMesh(alphaTestSubMeshes.data[index]);
  66782. }
  66783. };
  66784. }
  66785. /**
  66786. * Creates the depth rendering effect and checks if the effect is ready.
  66787. * @param subMesh The submesh to be used to render the depth map of
  66788. * @param useInstances If multiple world instances should be used
  66789. * @returns if the depth renderer is ready to render the depth map
  66790. */
  66791. DepthRenderer.prototype.isReady = function (subMesh, useInstances) {
  66792. var material = subMesh.getMaterial();
  66793. if (material.disableDepthWrite) {
  66794. return false;
  66795. }
  66796. var defines = [];
  66797. var attribs = [BABYLON.VertexBuffer.PositionKind];
  66798. var mesh = subMesh.getMesh();
  66799. // Alpha test
  66800. if (material && material.needAlphaTesting() && material.getAlphaTestTexture()) {
  66801. defines.push("#define ALPHATEST");
  66802. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  66803. attribs.push(BABYLON.VertexBuffer.UVKind);
  66804. defines.push("#define UV1");
  66805. }
  66806. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  66807. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  66808. defines.push("#define UV2");
  66809. }
  66810. }
  66811. // Bones
  66812. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  66813. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  66814. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  66815. if (mesh.numBoneInfluencers > 4) {
  66816. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  66817. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  66818. }
  66819. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  66820. defines.push("#define BonesPerMesh " + (mesh.skeleton ? mesh.skeleton.bones.length + 1 : 0));
  66821. }
  66822. else {
  66823. defines.push("#define NUM_BONE_INFLUENCERS 0");
  66824. }
  66825. // Instances
  66826. if (useInstances) {
  66827. defines.push("#define INSTANCES");
  66828. attribs.push("world0");
  66829. attribs.push("world1");
  66830. attribs.push("world2");
  66831. attribs.push("world3");
  66832. }
  66833. // Get correct effect
  66834. var join = defines.join("\n");
  66835. if (this._cachedDefines !== join) {
  66836. this._cachedDefines = join;
  66837. this._effect = this._scene.getEngine().createEffect("depth", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "depthValues"], ["diffuseSampler"], join);
  66838. }
  66839. return this._effect.isReady();
  66840. };
  66841. /**
  66842. * Gets the texture which the depth map will be written to.
  66843. * @returns The depth map texture
  66844. */
  66845. DepthRenderer.prototype.getDepthMap = function () {
  66846. return this._depthMap;
  66847. };
  66848. /**
  66849. * Disposes of the depth renderer.
  66850. */
  66851. DepthRenderer.prototype.dispose = function () {
  66852. this._depthMap.dispose();
  66853. };
  66854. return DepthRenderer;
  66855. }());
  66856. BABYLON.DepthRenderer = DepthRenderer;
  66857. })(BABYLON || (BABYLON = {}));
  66858. //# sourceMappingURL=babylon.depthRenderer.js.map
  66859. var BABYLON;
  66860. (function (BABYLON) {
  66861. var SSAORenderingPipeline = /** @class */ (function (_super) {
  66862. __extends(SSAORenderingPipeline, _super);
  66863. /**
  66864. * @constructor
  66865. * @param {string} name - The rendering pipeline name
  66866. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  66867. * @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 }
  66868. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  66869. */
  66870. function SSAORenderingPipeline(name, scene, ratio, cameras) {
  66871. var _this = _super.call(this, scene.getEngine(), name) || this;
  66872. // Members
  66873. /**
  66874. * The PassPostProcess id in the pipeline that contains the original scene color
  66875. * @type {string}
  66876. */
  66877. _this.SSAOOriginalSceneColorEffect = "SSAOOriginalSceneColorEffect";
  66878. /**
  66879. * The SSAO PostProcess id in the pipeline
  66880. * @type {string}
  66881. */
  66882. _this.SSAORenderEffect = "SSAORenderEffect";
  66883. /**
  66884. * The horizontal blur PostProcess id in the pipeline
  66885. * @type {string}
  66886. */
  66887. _this.SSAOBlurHRenderEffect = "SSAOBlurHRenderEffect";
  66888. /**
  66889. * The vertical blur PostProcess id in the pipeline
  66890. * @type {string}
  66891. */
  66892. _this.SSAOBlurVRenderEffect = "SSAOBlurVRenderEffect";
  66893. /**
  66894. * The PostProcess id in the pipeline that combines the SSAO-Blur output with the original scene color (SSAOOriginalSceneColorEffect)
  66895. * @type {string}
  66896. */
  66897. _this.SSAOCombineRenderEffect = "SSAOCombineRenderEffect";
  66898. /**
  66899. * The output strength of the SSAO post-process. Default value is 1.0.
  66900. * @type {number}
  66901. */
  66902. _this.totalStrength = 1.0;
  66903. /**
  66904. * The radius around the analyzed pixel used by the SSAO post-process. Default value is 0.0006
  66905. * @type {number}
  66906. */
  66907. _this.radius = 0.0001;
  66908. /**
  66909. * Related to fallOff, used to interpolate SSAO samples (first interpolate function input) based on the occlusion difference of each pixel
  66910. * Must not be equal to fallOff and superior to fallOff.
  66911. * Default value is 0.975
  66912. * @type {number}
  66913. */
  66914. _this.area = 0.0075;
  66915. /**
  66916. * Related to area, used to interpolate SSAO samples (second interpolate function input) based on the occlusion difference of each pixel
  66917. * Must not be equal to area and inferior to area.
  66918. * Default value is 0.0
  66919. * @type {number}
  66920. */
  66921. _this.fallOff = 0.000001;
  66922. /**
  66923. * The base color of the SSAO post-process
  66924. * The final result is "base + ssao" between [0, 1]
  66925. * @type {number}
  66926. */
  66927. _this.base = 0.5;
  66928. _this._firstUpdate = true;
  66929. _this._scene = scene;
  66930. // Set up assets
  66931. _this._createRandomTexture();
  66932. _this._depthTexture = scene.enableDepthRenderer().getDepthMap(); // Force depth renderer "on"
  66933. var ssaoRatio = ratio.ssaoRatio || ratio;
  66934. var combineRatio = ratio.combineRatio || ratio;
  66935. _this._originalColorPostProcess = new BABYLON.PassPostProcess("SSAOOriginalSceneColor", combineRatio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false);
  66936. _this._createSSAOPostProcess(ssaoRatio);
  66937. _this._createBlurPostProcess(ssaoRatio);
  66938. _this._createSSAOCombinePostProcess(combineRatio);
  66939. // Set up pipeline
  66940. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOOriginalSceneColorEffect, function () { return _this._originalColorPostProcess; }, true));
  66941. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAORenderEffect, function () { return _this._ssaoPostProcess; }, true));
  66942. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOBlurHRenderEffect, function () { return _this._blurHPostProcess; }, true));
  66943. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOBlurVRenderEffect, function () { return _this._blurVPostProcess; }, true));
  66944. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOCombineRenderEffect, function () { return _this._ssaoCombinePostProcess; }, true));
  66945. // Finish
  66946. scene.postProcessRenderPipelineManager.addPipeline(_this);
  66947. if (cameras)
  66948. scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);
  66949. return _this;
  66950. }
  66951. // Public Methods
  66952. /**
  66953. * Removes the internal pipeline assets and detatches the pipeline from the scene cameras
  66954. */
  66955. SSAORenderingPipeline.prototype.dispose = function (disableDepthRender) {
  66956. if (disableDepthRender === void 0) { disableDepthRender = false; }
  66957. for (var i = 0; i < this._scene.cameras.length; i++) {
  66958. var camera = this._scene.cameras[i];
  66959. this._originalColorPostProcess.dispose(camera);
  66960. this._ssaoPostProcess.dispose(camera);
  66961. this._blurHPostProcess.dispose(camera);
  66962. this._blurVPostProcess.dispose(camera);
  66963. this._ssaoCombinePostProcess.dispose(camera);
  66964. }
  66965. this._randomTexture.dispose();
  66966. if (disableDepthRender)
  66967. this._scene.disableDepthRenderer();
  66968. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._scene.cameras);
  66969. _super.prototype.dispose.call(this);
  66970. };
  66971. // Private Methods
  66972. SSAORenderingPipeline.prototype._createBlurPostProcess = function (ratio) {
  66973. var _this = this;
  66974. var size = 16;
  66975. 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);
  66976. 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);
  66977. this._blurHPostProcess.onActivateObservable.add(function () {
  66978. var dw = _this._blurHPostProcess.width / _this._scene.getEngine().getRenderWidth();
  66979. _this._blurHPostProcess.kernel = size * dw;
  66980. });
  66981. this._blurVPostProcess.onActivateObservable.add(function () {
  66982. var dw = _this._blurVPostProcess.height / _this._scene.getEngine().getRenderHeight();
  66983. _this._blurVPostProcess.kernel = size * dw;
  66984. });
  66985. };
  66986. SSAORenderingPipeline.prototype._rebuild = function () {
  66987. this._firstUpdate = true;
  66988. _super.prototype._rebuild.call(this);
  66989. };
  66990. SSAORenderingPipeline.prototype._createSSAOPostProcess = function (ratio) {
  66991. var _this = this;
  66992. var numSamples = 16;
  66993. var sampleSphere = [
  66994. 0.5381, 0.1856, -0.4319,
  66995. 0.1379, 0.2486, 0.4430,
  66996. 0.3371, 0.5679, -0.0057,
  66997. -0.6999, -0.0451, -0.0019,
  66998. 0.0689, -0.1598, -0.8547,
  66999. 0.0560, 0.0069, -0.1843,
  67000. -0.0146, 0.1402, 0.0762,
  67001. 0.0100, -0.1924, -0.0344,
  67002. -0.3577, -0.5301, -0.4358,
  67003. -0.3169, 0.1063, 0.0158,
  67004. 0.0103, -0.5869, 0.0046,
  67005. -0.0897, -0.4940, 0.3287,
  67006. 0.7119, -0.0154, -0.0918,
  67007. -0.0533, 0.0596, -0.5411,
  67008. 0.0352, -0.0631, 0.5460,
  67009. -0.4776, 0.2847, -0.0271
  67010. ];
  67011. var samplesFactor = 1.0 / numSamples;
  67012. this._ssaoPostProcess = new BABYLON.PostProcess("ssao", "ssao", [
  67013. "sampleSphere", "samplesFactor", "randTextureTiles", "totalStrength", "radius",
  67014. "area", "fallOff", "base", "range", "viewport"
  67015. ], ["randomSampler"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, "#define SAMPLES " + numSamples + "\n#define SSAO");
  67016. this._ssaoPostProcess.onApply = function (effect) {
  67017. if (_this._firstUpdate) {
  67018. effect.setArray3("sampleSphere", sampleSphere);
  67019. effect.setFloat("samplesFactor", samplesFactor);
  67020. effect.setFloat("randTextureTiles", 4.0);
  67021. }
  67022. effect.setFloat("totalStrength", _this.totalStrength);
  67023. effect.setFloat("radius", _this.radius);
  67024. effect.setFloat("area", _this.area);
  67025. effect.setFloat("fallOff", _this.fallOff);
  67026. effect.setFloat("base", _this.base);
  67027. effect.setTexture("textureSampler", _this._depthTexture);
  67028. effect.setTexture("randomSampler", _this._randomTexture);
  67029. };
  67030. };
  67031. SSAORenderingPipeline.prototype._createSSAOCombinePostProcess = function (ratio) {
  67032. var _this = this;
  67033. this._ssaoCombinePostProcess = new BABYLON.PostProcess("ssaoCombine", "ssaoCombine", [], ["originalColor"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  67034. this._ssaoCombinePostProcess.onApply = function (effect) {
  67035. effect.setTextureFromPostProcess("originalColor", _this._originalColorPostProcess);
  67036. };
  67037. };
  67038. SSAORenderingPipeline.prototype._createRandomTexture = function () {
  67039. var size = 512;
  67040. this._randomTexture = new BABYLON.DynamicTexture("SSAORandomTexture", size, this._scene, false, BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  67041. this._randomTexture.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  67042. this._randomTexture.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  67043. var context = this._randomTexture.getContext();
  67044. var rand = function (min, max) {
  67045. return Math.random() * (max - min) + min;
  67046. };
  67047. var randVector = BABYLON.Vector3.Zero();
  67048. for (var x = 0; x < size; x++) {
  67049. for (var y = 0; y < size; y++) {
  67050. randVector.x = Math.floor(rand(-1.0, 1.0) * 255);
  67051. randVector.y = Math.floor(rand(-1.0, 1.0) * 255);
  67052. randVector.z = Math.floor(rand(-1.0, 1.0) * 255);
  67053. context.fillStyle = 'rgb(' + randVector.x + ', ' + randVector.y + ', ' + randVector.z + ')';
  67054. context.fillRect(x, y, 1, 1);
  67055. }
  67056. }
  67057. this._randomTexture.update(false);
  67058. };
  67059. __decorate([
  67060. BABYLON.serialize()
  67061. ], SSAORenderingPipeline.prototype, "totalStrength", void 0);
  67062. __decorate([
  67063. BABYLON.serialize()
  67064. ], SSAORenderingPipeline.prototype, "radius", void 0);
  67065. __decorate([
  67066. BABYLON.serialize()
  67067. ], SSAORenderingPipeline.prototype, "area", void 0);
  67068. __decorate([
  67069. BABYLON.serialize()
  67070. ], SSAORenderingPipeline.prototype, "fallOff", void 0);
  67071. __decorate([
  67072. BABYLON.serialize()
  67073. ], SSAORenderingPipeline.prototype, "base", void 0);
  67074. return SSAORenderingPipeline;
  67075. }(BABYLON.PostProcessRenderPipeline));
  67076. BABYLON.SSAORenderingPipeline = SSAORenderingPipeline;
  67077. })(BABYLON || (BABYLON = {}));
  67078. //# sourceMappingURL=babylon.ssaoRenderingPipeline.js.map
  67079. var BABYLON;
  67080. (function (BABYLON) {
  67081. var SSAO2RenderingPipeline = /** @class */ (function (_super) {
  67082. __extends(SSAO2RenderingPipeline, _super);
  67083. /**
  67084. * @constructor
  67085. * @param {string} name - The rendering pipeline name
  67086. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  67087. * @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 }
  67088. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  67089. */
  67090. function SSAO2RenderingPipeline(name, scene, ratio, cameras) {
  67091. var _this = _super.call(this, scene.getEngine(), name) || this;
  67092. // Members
  67093. /**
  67094. * The PassPostProcess id in the pipeline that contains the original scene color
  67095. * @type {string}
  67096. */
  67097. _this.SSAOOriginalSceneColorEffect = "SSAOOriginalSceneColorEffect";
  67098. /**
  67099. * The SSAO PostProcess id in the pipeline
  67100. * @type {string}
  67101. */
  67102. _this.SSAORenderEffect = "SSAORenderEffect";
  67103. /**
  67104. * The horizontal blur PostProcess id in the pipeline
  67105. * @type {string}
  67106. */
  67107. _this.SSAOBlurHRenderEffect = "SSAOBlurHRenderEffect";
  67108. /**
  67109. * The vertical blur PostProcess id in the pipeline
  67110. * @type {string}
  67111. */
  67112. _this.SSAOBlurVRenderEffect = "SSAOBlurVRenderEffect";
  67113. /**
  67114. * The PostProcess id in the pipeline that combines the SSAO-Blur output with the original scene color (SSAOOriginalSceneColorEffect)
  67115. * @type {string}
  67116. */
  67117. _this.SSAOCombineRenderEffect = "SSAOCombineRenderEffect";
  67118. /**
  67119. * The output strength of the SSAO post-process. Default value is 1.0.
  67120. * @type {number}
  67121. */
  67122. _this.totalStrength = 1.0;
  67123. /**
  67124. * Maximum depth value to still render AO. A smooth falloff makes the dimming more natural, so there will be no abrupt shading change.
  67125. * @type {number}
  67126. */
  67127. _this.maxZ = 100.0;
  67128. /**
  67129. * In order to save performances, SSAO radius is clamped on close geometry. This ratio changes by how much
  67130. * @type {number}
  67131. */
  67132. _this.minZAspect = 0.2;
  67133. /**
  67134. * Number of samples used for the SSAO calculations. Default value is 8
  67135. * @type {number}
  67136. */
  67137. _this._samples = 8;
  67138. /**
  67139. * Are we using bilateral blur ?
  67140. * @type {boolean}
  67141. */
  67142. _this._expensiveBlur = true;
  67143. /**
  67144. * The radius around the analyzed pixel used by the SSAO post-process. Default value is 2.0
  67145. * @type {number}
  67146. */
  67147. _this.radius = 2.0;
  67148. /**
  67149. * The base color of the SSAO post-process
  67150. * The final result is "base + ssao" between [0, 1]
  67151. * @type {number}
  67152. */
  67153. _this.base = 0.1;
  67154. _this._firstUpdate = true;
  67155. _this._scene = scene;
  67156. if (!_this.isSupported) {
  67157. BABYLON.Tools.Error("SSAO 2 needs WebGL 2 support.");
  67158. return _this;
  67159. }
  67160. var ssaoRatio = ratio.ssaoRatio || ratio;
  67161. var blurRatio = ratio.blurRatio || ratio;
  67162. // Set up assets
  67163. var geometryBufferRenderer = scene.enableGeometryBufferRenderer();
  67164. _this._createRandomTexture();
  67165. _this._depthTexture = geometryBufferRenderer.getGBuffer().textures[0];
  67166. _this._normalTexture = geometryBufferRenderer.getGBuffer().textures[1];
  67167. _this._originalColorPostProcess = new BABYLON.PassPostProcess("SSAOOriginalSceneColor", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false);
  67168. _this._createSSAOPostProcess(1.0);
  67169. _this._createBlurPostProcess(ssaoRatio, blurRatio);
  67170. _this._createSSAOCombinePostProcess(blurRatio);
  67171. // Set up pipeline
  67172. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOOriginalSceneColorEffect, function () { return _this._originalColorPostProcess; }, true));
  67173. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAORenderEffect, function () { return _this._ssaoPostProcess; }, true));
  67174. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOBlurHRenderEffect, function () { return _this._blurHPostProcess; }, true));
  67175. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOBlurVRenderEffect, function () { return _this._blurVPostProcess; }, true));
  67176. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOCombineRenderEffect, function () { return _this._ssaoCombinePostProcess; }, true));
  67177. // Finish
  67178. scene.postProcessRenderPipelineManager.addPipeline(_this);
  67179. if (cameras)
  67180. scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);
  67181. return _this;
  67182. }
  67183. Object.defineProperty(SSAO2RenderingPipeline.prototype, "samples", {
  67184. get: function () {
  67185. return this._samples;
  67186. },
  67187. set: function (n) {
  67188. this._ssaoPostProcess.updateEffect("#define SAMPLES " + n + "\n#define SSAO");
  67189. this._samples = n;
  67190. this._sampleSphere = this._generateHemisphere();
  67191. this._firstUpdate = true;
  67192. },
  67193. enumerable: true,
  67194. configurable: true
  67195. });
  67196. Object.defineProperty(SSAO2RenderingPipeline.prototype, "expensiveBlur", {
  67197. get: function () {
  67198. return this._expensiveBlur;
  67199. },
  67200. set: function (b) {
  67201. 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"]);
  67202. this._blurVPostProcess.updateEffect("#define BILATERAL_BLUR\n#define SAMPLES 16\n#define EXPENSIVE " + (b ? "1" : "0") + "\n", null, ["textureSampler", "depthSampler"]);
  67203. this._expensiveBlur = b;
  67204. this._firstUpdate = true;
  67205. },
  67206. enumerable: true,
  67207. configurable: true
  67208. });
  67209. Object.defineProperty(SSAO2RenderingPipeline, "IsSupported", {
  67210. /**
  67211. * Support test.
  67212. * @type {boolean}
  67213. */
  67214. get: function () {
  67215. var engine = BABYLON.Engine.LastCreatedEngine;
  67216. if (!engine) {
  67217. return false;
  67218. }
  67219. return engine.getCaps().drawBuffersExtension;
  67220. },
  67221. enumerable: true,
  67222. configurable: true
  67223. });
  67224. // Public Methods
  67225. /**
  67226. * Removes the internal pipeline assets and detatches the pipeline from the scene cameras
  67227. */
  67228. SSAO2RenderingPipeline.prototype.dispose = function (disableGeometryBufferRenderer) {
  67229. if (disableGeometryBufferRenderer === void 0) { disableGeometryBufferRenderer = false; }
  67230. for (var i = 0; i < this._scene.cameras.length; i++) {
  67231. var camera = this._scene.cameras[i];
  67232. this._originalColorPostProcess.dispose(camera);
  67233. this._ssaoPostProcess.dispose(camera);
  67234. this._blurHPostProcess.dispose(camera);
  67235. this._blurVPostProcess.dispose(camera);
  67236. this._ssaoCombinePostProcess.dispose(camera);
  67237. }
  67238. this._randomTexture.dispose();
  67239. if (disableGeometryBufferRenderer)
  67240. this._scene.disableGeometryBufferRenderer();
  67241. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._scene.cameras);
  67242. _super.prototype.dispose.call(this);
  67243. };
  67244. // Private Methods
  67245. SSAO2RenderingPipeline.prototype._createBlurPostProcess = function (ssaoRatio, blurRatio) {
  67246. var _this = this;
  67247. this._samplerOffsets = [];
  67248. var expensive = this.expensiveBlur;
  67249. for (var i = -8; i < 8; i++) {
  67250. this._samplerOffsets.push(i * 2 + 0.5);
  67251. }
  67252. 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");
  67253. this._blurHPostProcess.onApply = function (effect) {
  67254. if (!_this._scene.activeCamera) {
  67255. return;
  67256. }
  67257. effect.setFloat("outSize", _this._ssaoCombinePostProcess.width > 0 ? _this._ssaoCombinePostProcess.width : _this._originalColorPostProcess.width);
  67258. effect.setFloat("near", _this._scene.activeCamera.minZ);
  67259. effect.setFloat("far", _this._scene.activeCamera.maxZ);
  67260. effect.setFloat("radius", _this.radius);
  67261. effect.setTexture("depthSampler", _this._depthTexture);
  67262. if (_this._firstUpdate) {
  67263. effect.setArray("samplerOffsets", _this._samplerOffsets);
  67264. }
  67265. };
  67266. 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");
  67267. this._blurVPostProcess.onApply = function (effect) {
  67268. if (!_this._scene.activeCamera) {
  67269. return;
  67270. }
  67271. effect.setFloat("outSize", _this._ssaoCombinePostProcess.height > 0 ? _this._ssaoCombinePostProcess.height : _this._originalColorPostProcess.height);
  67272. effect.setFloat("near", _this._scene.activeCamera.minZ);
  67273. effect.setFloat("far", _this._scene.activeCamera.maxZ);
  67274. effect.setFloat("radius", _this.radius);
  67275. effect.setTexture("depthSampler", _this._depthTexture);
  67276. if (_this._firstUpdate) {
  67277. effect.setArray("samplerOffsets", _this._samplerOffsets);
  67278. _this._firstUpdate = false;
  67279. }
  67280. };
  67281. };
  67282. SSAO2RenderingPipeline.prototype._rebuild = function () {
  67283. this._firstUpdate = true;
  67284. _super.prototype._rebuild.call(this);
  67285. };
  67286. SSAO2RenderingPipeline.prototype._generateHemisphere = function () {
  67287. var numSamples = this.samples;
  67288. var result = [];
  67289. var vector, scale;
  67290. var rand = function (min, max) {
  67291. return Math.random() * (max - min) + min;
  67292. };
  67293. var i = 0;
  67294. while (i < numSamples) {
  67295. vector = new BABYLON.Vector3(rand(-1.0, 1.0), rand(-1.0, 1.0), rand(0.30, 1.0));
  67296. vector.normalize();
  67297. scale = i / numSamples;
  67298. scale = BABYLON.Scalar.Lerp(0.1, 1.0, scale * scale);
  67299. vector.scaleInPlace(scale);
  67300. result.push(vector.x, vector.y, vector.z);
  67301. i++;
  67302. }
  67303. return result;
  67304. };
  67305. SSAO2RenderingPipeline.prototype._createSSAOPostProcess = function (ratio) {
  67306. var _this = this;
  67307. var numSamples = this.samples;
  67308. this._sampleSphere = this._generateHemisphere();
  67309. this._ssaoPostProcess = new BABYLON.PostProcess("ssao2", "ssao2", [
  67310. "sampleSphere", "samplesFactor", "randTextureTiles", "totalStrength", "radius",
  67311. "base", "range", "projection", "near", "far", "texelSize",
  67312. "xViewport", "yViewport", "maxZ", "minZAspect"
  67313. ], ["randomSampler", "normalSampler"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, "#define SAMPLES " + numSamples + "\n#define SSAO");
  67314. this._ssaoPostProcess.onApply = function (effect) {
  67315. if (_this._firstUpdate) {
  67316. effect.setArray3("sampleSphere", _this._sampleSphere);
  67317. effect.setFloat("randTextureTiles", 4.0);
  67318. }
  67319. if (!_this._scene.activeCamera) {
  67320. return;
  67321. }
  67322. effect.setFloat("samplesFactor", 1 / _this.samples);
  67323. effect.setFloat("totalStrength", _this.totalStrength);
  67324. effect.setFloat2("texelSize", 1 / _this._ssaoPostProcess.width, 1 / _this._ssaoPostProcess.height);
  67325. effect.setFloat("radius", _this.radius);
  67326. effect.setFloat("maxZ", _this.maxZ);
  67327. effect.setFloat("minZAspect", _this.minZAspect);
  67328. effect.setFloat("base", _this.base);
  67329. effect.setFloat("near", _this._scene.activeCamera.minZ);
  67330. effect.setFloat("far", _this._scene.activeCamera.maxZ);
  67331. effect.setFloat("xViewport", Math.tan(_this._scene.activeCamera.fov / 2) * _this._scene.getEngine().getAspectRatio(_this._scene.activeCamera, true));
  67332. effect.setFloat("yViewport", Math.tan(_this._scene.activeCamera.fov / 2));
  67333. effect.setMatrix("projection", _this._scene.getProjectionMatrix());
  67334. effect.setTexture("textureSampler", _this._depthTexture);
  67335. effect.setTexture("normalSampler", _this._normalTexture);
  67336. effect.setTexture("randomSampler", _this._randomTexture);
  67337. };
  67338. };
  67339. SSAO2RenderingPipeline.prototype._createSSAOCombinePostProcess = function (ratio) {
  67340. var _this = this;
  67341. this._ssaoCombinePostProcess = new BABYLON.PostProcess("ssaoCombine", "ssaoCombine", [], ["originalColor"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  67342. this._ssaoCombinePostProcess.onApply = function (effect) {
  67343. effect.setTextureFromPostProcess("originalColor", _this._originalColorPostProcess);
  67344. };
  67345. };
  67346. SSAO2RenderingPipeline.prototype._createRandomTexture = function () {
  67347. var size = 512;
  67348. this._randomTexture = new BABYLON.DynamicTexture("SSAORandomTexture", size, this._scene, false, BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  67349. this._randomTexture.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  67350. this._randomTexture.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  67351. var context = this._randomTexture.getContext();
  67352. var rand = function (min, max) {
  67353. return Math.random() * (max - min) + min;
  67354. };
  67355. var randVector = BABYLON.Vector3.Zero();
  67356. for (var x = 0; x < size; x++) {
  67357. for (var y = 0; y < size; y++) {
  67358. randVector.x = rand(0.0, 1.0);
  67359. randVector.y = rand(0.0, 1.0);
  67360. randVector.z = 0.0;
  67361. randVector.normalize();
  67362. randVector.scaleInPlace(255);
  67363. randVector.x = Math.floor(randVector.x);
  67364. randVector.y = Math.floor(randVector.y);
  67365. context.fillStyle = 'rgb(' + randVector.x + ', ' + randVector.y + ', ' + randVector.z + ')';
  67366. context.fillRect(x, y, 1, 1);
  67367. }
  67368. }
  67369. this._randomTexture.update(false);
  67370. };
  67371. __decorate([
  67372. BABYLON.serialize()
  67373. ], SSAO2RenderingPipeline.prototype, "totalStrength", void 0);
  67374. __decorate([
  67375. BABYLON.serialize()
  67376. ], SSAO2RenderingPipeline.prototype, "maxZ", void 0);
  67377. __decorate([
  67378. BABYLON.serialize()
  67379. ], SSAO2RenderingPipeline.prototype, "minZAspect", void 0);
  67380. __decorate([
  67381. BABYLON.serialize("samples")
  67382. ], SSAO2RenderingPipeline.prototype, "_samples", void 0);
  67383. __decorate([
  67384. BABYLON.serialize("expensiveBlur")
  67385. ], SSAO2RenderingPipeline.prototype, "_expensiveBlur", void 0);
  67386. __decorate([
  67387. BABYLON.serialize()
  67388. ], SSAO2RenderingPipeline.prototype, "radius", void 0);
  67389. __decorate([
  67390. BABYLON.serialize()
  67391. ], SSAO2RenderingPipeline.prototype, "base", void 0);
  67392. return SSAO2RenderingPipeline;
  67393. }(BABYLON.PostProcessRenderPipeline));
  67394. BABYLON.SSAO2RenderingPipeline = SSAO2RenderingPipeline;
  67395. })(BABYLON || (BABYLON = {}));
  67396. //# sourceMappingURL=babylon.ssao2RenderingPipeline.js.map
  67397. // BABYLON.JS Chromatic Aberration GLSL Shader
  67398. // Author: Olivier Guyot
  67399. // Separates very slightly R, G and B colors on the edges of the screen
  67400. // Inspired by Francois Tarlier & Martins Upitis
  67401. var BABYLON;
  67402. (function (BABYLON) {
  67403. var LensRenderingPipeline = /** @class */ (function (_super) {
  67404. __extends(LensRenderingPipeline, _super);
  67405. /**
  67406. * @constructor
  67407. *
  67408. * Effect parameters are as follow:
  67409. * {
  67410. * chromatic_aberration: number; // from 0 to x (1 for realism)
  67411. * edge_blur: number; // from 0 to x (1 for realism)
  67412. * distortion: number; // from 0 to x (1 for realism)
  67413. * grain_amount: number; // from 0 to 1
  67414. * grain_texture: BABYLON.Texture; // texture to use for grain effect; if unset, use random B&W noise
  67415. * dof_focus_distance: number; // depth-of-field: focus distance; unset to disable (disabled by default)
  67416. * dof_aperture: number; // depth-of-field: focus blur bias (default: 1)
  67417. * dof_darken: number; // depth-of-field: darken that which is out of focus (from 0 to 1, disabled by default)
  67418. * dof_pentagon: boolean; // depth-of-field: makes a pentagon-like "bokeh" effect
  67419. * dof_gain: number; // depth-of-field: highlights gain; unset to disable (disabled by default)
  67420. * dof_threshold: number; // depth-of-field: highlights threshold (default: 1)
  67421. * blur_noise: boolean; // add a little bit of noise to the blur (default: true)
  67422. * }
  67423. * Note: if an effect parameter is unset, effect is disabled
  67424. *
  67425. * @param {string} name - The rendering pipeline name
  67426. * @param {object} parameters - An object containing all parameters (see above)
  67427. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  67428. * @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)
  67429. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  67430. */
  67431. function LensRenderingPipeline(name, parameters, scene, ratio, cameras) {
  67432. if (ratio === void 0) { ratio = 1.0; }
  67433. var _this = _super.call(this, scene.getEngine(), name) || this;
  67434. // Lens effects can be of the following:
  67435. // - chromatic aberration (slight shift of RGB colors)
  67436. // - blur on the edge of the lens
  67437. // - lens distortion
  67438. // - depth-of-field blur & highlights enhancing
  67439. // - depth-of-field 'bokeh' effect (shapes appearing in blurred areas)
  67440. // - grain effect (noise or custom texture)
  67441. // Two additional texture samplers are needed:
  67442. // - depth map (for depth-of-field)
  67443. // - grain texture
  67444. /**
  67445. * The chromatic aberration PostProcess id in the pipeline
  67446. * @type {string}
  67447. */
  67448. _this.LensChromaticAberrationEffect = "LensChromaticAberrationEffect";
  67449. /**
  67450. * The highlights enhancing PostProcess id in the pipeline
  67451. * @type {string}
  67452. */
  67453. _this.HighlightsEnhancingEffect = "HighlightsEnhancingEffect";
  67454. /**
  67455. * The depth-of-field PostProcess id in the pipeline
  67456. * @type {string}
  67457. */
  67458. _this.LensDepthOfFieldEffect = "LensDepthOfFieldEffect";
  67459. _this._scene = scene;
  67460. // Fetch texture samplers
  67461. _this._depthTexture = scene.enableDepthRenderer().getDepthMap(); // Force depth renderer "on"
  67462. if (parameters.grain_texture) {
  67463. _this._grainTexture = parameters.grain_texture;
  67464. }
  67465. else {
  67466. _this._createGrainTexture();
  67467. }
  67468. // save parameters
  67469. _this._edgeBlur = parameters.edge_blur ? parameters.edge_blur : 0;
  67470. _this._grainAmount = parameters.grain_amount ? parameters.grain_amount : 0;
  67471. _this._chromaticAberration = parameters.chromatic_aberration ? parameters.chromatic_aberration : 0;
  67472. _this._distortion = parameters.distortion ? parameters.distortion : 0;
  67473. _this._highlightsGain = parameters.dof_gain !== undefined ? parameters.dof_gain : -1;
  67474. _this._highlightsThreshold = parameters.dof_threshold ? parameters.dof_threshold : 1;
  67475. _this._dofDistance = parameters.dof_focus_distance !== undefined ? parameters.dof_focus_distance : -1;
  67476. _this._dofAperture = parameters.dof_aperture ? parameters.dof_aperture : 1;
  67477. _this._dofDarken = parameters.dof_darken ? parameters.dof_darken : 0;
  67478. _this._dofPentagon = parameters.dof_pentagon !== undefined ? parameters.dof_pentagon : true;
  67479. _this._blurNoise = parameters.blur_noise !== undefined ? parameters.blur_noise : true;
  67480. // Create effects
  67481. _this._createChromaticAberrationPostProcess(ratio);
  67482. _this._createHighlightsPostProcess(ratio);
  67483. _this._createDepthOfFieldPostProcess(ratio / 4);
  67484. // Set up pipeline
  67485. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.LensChromaticAberrationEffect, function () { return _this._chromaticAberrationPostProcess; }, true));
  67486. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.HighlightsEnhancingEffect, function () { return _this._highlightsPostProcess; }, true));
  67487. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.LensDepthOfFieldEffect, function () { return _this._depthOfFieldPostProcess; }, true));
  67488. if (_this._highlightsGain === -1) {
  67489. _this._disableEffect(_this.HighlightsEnhancingEffect, null);
  67490. }
  67491. // Finish
  67492. scene.postProcessRenderPipelineManager.addPipeline(_this);
  67493. if (cameras) {
  67494. scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);
  67495. }
  67496. return _this;
  67497. }
  67498. // public methods (self explanatory)
  67499. LensRenderingPipeline.prototype.setEdgeBlur = function (amount) { this._edgeBlur = amount; };
  67500. LensRenderingPipeline.prototype.disableEdgeBlur = function () { this._edgeBlur = 0; };
  67501. LensRenderingPipeline.prototype.setGrainAmount = function (amount) { this._grainAmount = amount; };
  67502. LensRenderingPipeline.prototype.disableGrain = function () { this._grainAmount = 0; };
  67503. LensRenderingPipeline.prototype.setChromaticAberration = function (amount) { this._chromaticAberration = amount; };
  67504. LensRenderingPipeline.prototype.disableChromaticAberration = function () { this._chromaticAberration = 0; };
  67505. LensRenderingPipeline.prototype.setEdgeDistortion = function (amount) { this._distortion = amount; };
  67506. LensRenderingPipeline.prototype.disableEdgeDistortion = function () { this._distortion = 0; };
  67507. LensRenderingPipeline.prototype.setFocusDistance = function (amount) { this._dofDistance = amount; };
  67508. LensRenderingPipeline.prototype.disableDepthOfField = function () { this._dofDistance = -1; };
  67509. LensRenderingPipeline.prototype.setAperture = function (amount) { this._dofAperture = amount; };
  67510. LensRenderingPipeline.prototype.setDarkenOutOfFocus = function (amount) { this._dofDarken = amount; };
  67511. LensRenderingPipeline.prototype.enablePentagonBokeh = function () {
  67512. this._highlightsPostProcess.updateEffect("#define PENTAGON\n");
  67513. };
  67514. LensRenderingPipeline.prototype.disablePentagonBokeh = function () {
  67515. this._highlightsPostProcess.updateEffect();
  67516. };
  67517. LensRenderingPipeline.prototype.enableNoiseBlur = function () { this._blurNoise = true; };
  67518. LensRenderingPipeline.prototype.disableNoiseBlur = function () { this._blurNoise = false; };
  67519. LensRenderingPipeline.prototype.setHighlightsGain = function (amount) {
  67520. this._highlightsGain = amount;
  67521. };
  67522. LensRenderingPipeline.prototype.setHighlightsThreshold = function (amount) {
  67523. if (this._highlightsGain === -1) {
  67524. this._highlightsGain = 1.0;
  67525. }
  67526. this._highlightsThreshold = amount;
  67527. };
  67528. LensRenderingPipeline.prototype.disableHighlights = function () {
  67529. this._highlightsGain = -1;
  67530. };
  67531. /**
  67532. * Removes the internal pipeline assets and detaches the pipeline from the scene cameras
  67533. */
  67534. LensRenderingPipeline.prototype.dispose = function (disableDepthRender) {
  67535. if (disableDepthRender === void 0) { disableDepthRender = false; }
  67536. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._scene.cameras);
  67537. this._chromaticAberrationPostProcess = null;
  67538. this._highlightsPostProcess = null;
  67539. this._depthOfFieldPostProcess = null;
  67540. this._grainTexture.dispose();
  67541. if (disableDepthRender)
  67542. this._scene.disableDepthRenderer();
  67543. };
  67544. // colors shifting and distortion
  67545. LensRenderingPipeline.prototype._createChromaticAberrationPostProcess = function (ratio) {
  67546. var _this = this;
  67547. this._chromaticAberrationPostProcess = new BABYLON.PostProcess("LensChromaticAberration", "chromaticAberration", ["chromatic_aberration", "screen_width", "screen_height", "direction", "radialIntensity", "centerPosition"], // uniforms
  67548. [], // samplers
  67549. ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  67550. this._chromaticAberrationPostProcess.onApply = function (effect) {
  67551. effect.setFloat('chromatic_aberration', _this._chromaticAberration);
  67552. effect.setFloat('screen_width', _this._scene.getEngine().getRenderWidth());
  67553. effect.setFloat('screen_height', _this._scene.getEngine().getRenderHeight());
  67554. effect.setFloat('radialIntensity', 1);
  67555. effect.setFloat2('direction', 17, 17);
  67556. effect.setFloat2('centerPosition', 0.5, 0.5);
  67557. };
  67558. };
  67559. // highlights enhancing
  67560. LensRenderingPipeline.prototype._createHighlightsPostProcess = function (ratio) {
  67561. var _this = this;
  67562. this._highlightsPostProcess = new BABYLON.PostProcess("LensHighlights", "lensHighlights", ["gain", "threshold", "screen_width", "screen_height"], // uniforms
  67563. [], // samplers
  67564. ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, this._dofPentagon ? "#define PENTAGON\n" : "");
  67565. this._highlightsPostProcess.onApply = function (effect) {
  67566. effect.setFloat('gain', _this._highlightsGain);
  67567. effect.setFloat('threshold', _this._highlightsThreshold);
  67568. effect.setTextureFromPostProcess("textureSampler", _this._chromaticAberrationPostProcess);
  67569. effect.setFloat('screen_width', _this._scene.getEngine().getRenderWidth());
  67570. effect.setFloat('screen_height', _this._scene.getEngine().getRenderHeight());
  67571. };
  67572. };
  67573. // colors shifting and distortion
  67574. LensRenderingPipeline.prototype._createDepthOfFieldPostProcess = function (ratio) {
  67575. var _this = this;
  67576. this._depthOfFieldPostProcess = new BABYLON.PostProcess("LensDepthOfField", "depthOfField", [
  67577. "grain_amount", "blur_noise", "screen_width", "screen_height", "distortion", "dof_enabled",
  67578. "screen_distance", "aperture", "darken", "edge_blur", "highlights", "near", "far"
  67579. ], ["depthSampler", "grainSampler", "highlightsSampler"], ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  67580. this._depthOfFieldPostProcess.onApply = function (effect) {
  67581. effect.setTexture("depthSampler", _this._depthTexture);
  67582. effect.setTexture("grainSampler", _this._grainTexture);
  67583. effect.setTextureFromPostProcess("textureSampler", _this._highlightsPostProcess);
  67584. effect.setTextureFromPostProcess("highlightsSampler", _this._depthOfFieldPostProcess);
  67585. effect.setFloat('grain_amount', _this._grainAmount);
  67586. effect.setBool('blur_noise', _this._blurNoise);
  67587. effect.setFloat('screen_width', _this._scene.getEngine().getRenderWidth());
  67588. effect.setFloat('screen_height', _this._scene.getEngine().getRenderHeight());
  67589. effect.setFloat('distortion', _this._distortion);
  67590. effect.setBool('dof_enabled', (_this._dofDistance !== -1));
  67591. effect.setFloat('screen_distance', 1.0 / (0.1 - 1.0 / _this._dofDistance));
  67592. effect.setFloat('aperture', _this._dofAperture);
  67593. effect.setFloat('darken', _this._dofDarken);
  67594. effect.setFloat('edge_blur', _this._edgeBlur);
  67595. effect.setBool('highlights', (_this._highlightsGain !== -1));
  67596. if (_this._scene.activeCamera) {
  67597. effect.setFloat('near', _this._scene.activeCamera.minZ);
  67598. effect.setFloat('far', _this._scene.activeCamera.maxZ);
  67599. }
  67600. };
  67601. };
  67602. // creates a black and white random noise texture, 512x512
  67603. LensRenderingPipeline.prototype._createGrainTexture = function () {
  67604. var size = 512;
  67605. this._grainTexture = new BABYLON.DynamicTexture("LensNoiseTexture", size, this._scene, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  67606. this._grainTexture.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  67607. this._grainTexture.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  67608. var context = this._grainTexture.getContext();
  67609. var rand = function (min, max) {
  67610. return Math.random() * (max - min) + min;
  67611. };
  67612. var value;
  67613. for (var x = 0; x < size; x++) {
  67614. for (var y = 0; y < size; y++) {
  67615. value = Math.floor(rand(0.42, 0.58) * 255);
  67616. context.fillStyle = 'rgb(' + value + ', ' + value + ', ' + value + ')';
  67617. context.fillRect(x, y, 1, 1);
  67618. }
  67619. }
  67620. this._grainTexture.update(false);
  67621. };
  67622. return LensRenderingPipeline;
  67623. }(BABYLON.PostProcessRenderPipeline));
  67624. BABYLON.LensRenderingPipeline = LensRenderingPipeline;
  67625. })(BABYLON || (BABYLON = {}));
  67626. //# sourceMappingURL=babylon.lensRenderingPipeline.js.map
  67627. var BABYLON;
  67628. (function (BABYLON) {
  67629. var StandardRenderingPipeline = /** @class */ (function (_super) {
  67630. __extends(StandardRenderingPipeline, _super);
  67631. /**
  67632. * @constructor
  67633. * @param {string} name - The rendering pipeline name
  67634. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  67635. * @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)
  67636. * @param {BABYLON.PostProcess} originalPostProcess - the custom original color post-process. Must be "reusable". Can be null.
  67637. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  67638. */
  67639. function StandardRenderingPipeline(name, scene, ratio, originalPostProcess, cameras) {
  67640. if (originalPostProcess === void 0) { originalPostProcess = null; }
  67641. var _this = _super.call(this, scene.getEngine(), name) || this;
  67642. _this.downSampleX4PostProcess = null;
  67643. _this.brightPassPostProcess = null;
  67644. _this.blurHPostProcesses = [];
  67645. _this.blurVPostProcesses = [];
  67646. _this.textureAdderPostProcess = null;
  67647. _this.volumetricLightPostProcess = null;
  67648. _this.volumetricLightSmoothXPostProcess = null;
  67649. _this.volumetricLightSmoothYPostProcess = null;
  67650. _this.volumetricLightMergePostProces = null;
  67651. _this.volumetricLightFinalPostProcess = null;
  67652. _this.luminancePostProcess = null;
  67653. _this.luminanceDownSamplePostProcesses = [];
  67654. _this.hdrPostProcess = null;
  67655. _this.textureAdderFinalPostProcess = null;
  67656. _this.lensFlareFinalPostProcess = null;
  67657. _this.hdrFinalPostProcess = null;
  67658. _this.lensFlarePostProcess = null;
  67659. _this.lensFlareComposePostProcess = null;
  67660. _this.motionBlurPostProcess = null;
  67661. _this.depthOfFieldPostProcess = null;
  67662. // Values
  67663. _this.brightThreshold = 1.0;
  67664. _this.blurWidth = 512.0;
  67665. _this.horizontalBlur = false;
  67666. _this.exposure = 1.0;
  67667. _this.lensTexture = null;
  67668. _this.volumetricLightCoefficient = 0.2;
  67669. _this.volumetricLightPower = 4.0;
  67670. _this.volumetricLightBlurScale = 64.0;
  67671. _this.sourceLight = null;
  67672. _this.hdrMinimumLuminance = 1.0;
  67673. _this.hdrDecreaseRate = 0.5;
  67674. _this.hdrIncreaseRate = 0.5;
  67675. _this.lensColorTexture = null;
  67676. _this.lensFlareStrength = 20.0;
  67677. _this.lensFlareGhostDispersal = 1.4;
  67678. _this.lensFlareHaloWidth = 0.7;
  67679. _this.lensFlareDistortionStrength = 16.0;
  67680. _this.lensStarTexture = null;
  67681. _this.lensFlareDirtTexture = null;
  67682. _this.depthOfFieldDistance = 10.0;
  67683. _this.depthOfFieldBlurWidth = 64.0;
  67684. _this.motionStrength = 1.0;
  67685. // IAnimatable
  67686. _this.animations = [];
  67687. _this._currentDepthOfFieldSource = null;
  67688. _this._hdrCurrentLuminance = 1.0;
  67689. // Getters and setters
  67690. _this._bloomEnabled = true;
  67691. _this._depthOfFieldEnabled = false;
  67692. _this._vlsEnabled = false;
  67693. _this._lensFlareEnabled = false;
  67694. _this._hdrEnabled = false;
  67695. _this._motionBlurEnabled = false;
  67696. _this._motionBlurSamples = 64.0;
  67697. _this._volumetricLightStepsCount = 50.0;
  67698. _this._cameras = cameras || [];
  67699. // Initialize
  67700. _this._scene = scene;
  67701. _this._basePostProcess = originalPostProcess;
  67702. _this._ratio = ratio;
  67703. // Misc
  67704. _this._floatTextureType = scene.getEngine().getCaps().textureFloatRender ? BABYLON.Engine.TEXTURETYPE_FLOAT : BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  67705. // Finish
  67706. scene.postProcessRenderPipelineManager.addPipeline(_this);
  67707. _this._buildPipeline();
  67708. return _this;
  67709. }
  67710. Object.defineProperty(StandardRenderingPipeline.prototype, "BloomEnabled", {
  67711. get: function () {
  67712. return this._bloomEnabled;
  67713. },
  67714. set: function (enabled) {
  67715. if (this._bloomEnabled === enabled) {
  67716. return;
  67717. }
  67718. this._bloomEnabled = enabled;
  67719. this._buildPipeline();
  67720. },
  67721. enumerable: true,
  67722. configurable: true
  67723. });
  67724. Object.defineProperty(StandardRenderingPipeline.prototype, "DepthOfFieldEnabled", {
  67725. get: function () {
  67726. return this._depthOfFieldEnabled;
  67727. },
  67728. set: function (enabled) {
  67729. if (this._depthOfFieldEnabled === enabled) {
  67730. return;
  67731. }
  67732. this._depthOfFieldEnabled = enabled;
  67733. this._buildPipeline();
  67734. },
  67735. enumerable: true,
  67736. configurable: true
  67737. });
  67738. Object.defineProperty(StandardRenderingPipeline.prototype, "LensFlareEnabled", {
  67739. get: function () {
  67740. return this._lensFlareEnabled;
  67741. },
  67742. set: function (enabled) {
  67743. if (this._lensFlareEnabled === enabled) {
  67744. return;
  67745. }
  67746. this._lensFlareEnabled = enabled;
  67747. this._buildPipeline();
  67748. },
  67749. enumerable: true,
  67750. configurable: true
  67751. });
  67752. Object.defineProperty(StandardRenderingPipeline.prototype, "HDREnabled", {
  67753. get: function () {
  67754. return this._hdrEnabled;
  67755. },
  67756. set: function (enabled) {
  67757. if (this._hdrEnabled === enabled) {
  67758. return;
  67759. }
  67760. this._hdrEnabled = enabled;
  67761. this._buildPipeline();
  67762. },
  67763. enumerable: true,
  67764. configurable: true
  67765. });
  67766. Object.defineProperty(StandardRenderingPipeline.prototype, "VLSEnabled", {
  67767. get: function () {
  67768. return this._vlsEnabled;
  67769. },
  67770. set: function (enabled) {
  67771. if (this._vlsEnabled === enabled) {
  67772. return;
  67773. }
  67774. if (enabled) {
  67775. var geometry = this._scene.enableGeometryBufferRenderer();
  67776. if (!geometry) {
  67777. BABYLON.Tools.Warn("Geometry renderer is not supported, cannot create volumetric lights in Standard Rendering Pipeline");
  67778. return;
  67779. }
  67780. }
  67781. this._vlsEnabled = enabled;
  67782. this._buildPipeline();
  67783. },
  67784. enumerable: true,
  67785. configurable: true
  67786. });
  67787. Object.defineProperty(StandardRenderingPipeline.prototype, "MotionBlurEnabled", {
  67788. get: function () {
  67789. return this._motionBlurEnabled;
  67790. },
  67791. set: function (enabled) {
  67792. if (this._motionBlurEnabled === enabled) {
  67793. return;
  67794. }
  67795. this._motionBlurEnabled = enabled;
  67796. this._buildPipeline();
  67797. },
  67798. enumerable: true,
  67799. configurable: true
  67800. });
  67801. Object.defineProperty(StandardRenderingPipeline.prototype, "volumetricLightStepsCount", {
  67802. get: function () {
  67803. return this._volumetricLightStepsCount;
  67804. },
  67805. set: function (count) {
  67806. if (this.volumetricLightPostProcess) {
  67807. this.volumetricLightPostProcess.updateEffect("#define VLS\n#define NB_STEPS " + count.toFixed(1));
  67808. }
  67809. this._volumetricLightStepsCount = count;
  67810. },
  67811. enumerable: true,
  67812. configurable: true
  67813. });
  67814. Object.defineProperty(StandardRenderingPipeline.prototype, "motionBlurSamples", {
  67815. get: function () {
  67816. return this._motionBlurSamples;
  67817. },
  67818. set: function (samples) {
  67819. if (this.motionBlurPostProcess) {
  67820. this.motionBlurPostProcess.updateEffect("#define MOTION_BLUR\n#define MAX_MOTION_SAMPLES " + samples.toFixed(1));
  67821. }
  67822. this._motionBlurSamples = samples;
  67823. },
  67824. enumerable: true,
  67825. configurable: true
  67826. });
  67827. StandardRenderingPipeline.prototype._buildPipeline = function () {
  67828. var _this = this;
  67829. var ratio = this._ratio;
  67830. var scene = this._scene;
  67831. this._disposePostProcesses();
  67832. this._reset();
  67833. // Create pass post-process
  67834. if (!this._basePostProcess) {
  67835. this.originalPostProcess = new BABYLON.PostProcess("HDRPass", "standard", [], [], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define PASS_POST_PROCESS", this._floatTextureType);
  67836. this.originalPostProcess.onApply = function (effect) {
  67837. _this._currentDepthOfFieldSource = _this.originalPostProcess;
  67838. };
  67839. }
  67840. else {
  67841. this.originalPostProcess = this._basePostProcess;
  67842. }
  67843. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRPassPostProcess", function () { return _this.originalPostProcess; }, true));
  67844. this._currentDepthOfFieldSource = this.originalPostProcess;
  67845. if (this._vlsEnabled) {
  67846. // Create volumetric light
  67847. this._createVolumetricLightPostProcess(scene, ratio);
  67848. // Create volumetric light final post-process
  67849. 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);
  67850. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRVLSFinal", function () { return _this.volumetricLightFinalPostProcess; }, true));
  67851. }
  67852. if (this._bloomEnabled) {
  67853. // Create down sample X4 post-process
  67854. this._createDownSampleX4PostProcess(scene, ratio / 2);
  67855. // Create bright pass post-process
  67856. this._createBrightPassPostProcess(scene, ratio / 2);
  67857. // Create gaussian blur post-processes (down sampling blurs)
  67858. this._createBlurPostProcesses(scene, ratio / 4, 1);
  67859. // Create texture adder post-process
  67860. this._createTextureAdderPostProcess(scene, ratio);
  67861. // Create depth-of-field source post-process
  67862. 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);
  67863. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRBaseDepthOfFieldSource", function () { return _this.textureAdderFinalPostProcess; }, true));
  67864. }
  67865. if (this._lensFlareEnabled) {
  67866. // Create lens flare post-process
  67867. this._createLensFlarePostProcess(scene, ratio);
  67868. // Create depth-of-field source post-process post lens-flare and disable it now
  67869. 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);
  67870. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRPostLensFlareDepthOfFieldSource", function () { return _this.lensFlareFinalPostProcess; }, true));
  67871. }
  67872. if (this._hdrEnabled) {
  67873. // Create luminance
  67874. this._createLuminancePostProcesses(scene, this._floatTextureType);
  67875. // Create HDR
  67876. this._createHdrPostProcess(scene, ratio);
  67877. // Create depth-of-field source post-process post hdr and disable it now
  67878. 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);
  67879. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRPostHDReDepthOfFieldSource", function () { return _this.hdrFinalPostProcess; }, true));
  67880. }
  67881. if (this._depthOfFieldEnabled) {
  67882. // Create gaussian blur used by depth-of-field
  67883. this._createBlurPostProcesses(scene, ratio / 2, 3, "depthOfFieldBlurWidth");
  67884. // Create depth-of-field post-process
  67885. this._createDepthOfFieldPostProcess(scene, ratio);
  67886. }
  67887. if (this._motionBlurEnabled) {
  67888. // Create motion blur post-process
  67889. this._createMotionBlurPostProcess(scene, ratio);
  67890. }
  67891. if (this._cameras !== null) {
  67892. this._scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(this._name, this._cameras);
  67893. }
  67894. };
  67895. // Down Sample X4 Post-Processs
  67896. StandardRenderingPipeline.prototype._createDownSampleX4PostProcess = function (scene, ratio) {
  67897. var _this = this;
  67898. var downSampleX4Offsets = new Array(32);
  67899. 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);
  67900. this.downSampleX4PostProcess.onApply = function (effect) {
  67901. var id = 0;
  67902. var width = _this.downSampleX4PostProcess.width;
  67903. var height = _this.downSampleX4PostProcess.height;
  67904. for (var i = -2; i < 2; i++) {
  67905. for (var j = -2; j < 2; j++) {
  67906. downSampleX4Offsets[id] = (i + 0.5) * (1.0 / width);
  67907. downSampleX4Offsets[id + 1] = (j + 0.5) * (1.0 / height);
  67908. id += 2;
  67909. }
  67910. }
  67911. effect.setArray2("dsOffsets", downSampleX4Offsets);
  67912. };
  67913. // Add to pipeline
  67914. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRDownSampleX4", function () { return _this.downSampleX4PostProcess; }, true));
  67915. };
  67916. // Brightpass Post-Process
  67917. StandardRenderingPipeline.prototype._createBrightPassPostProcess = function (scene, ratio) {
  67918. var _this = this;
  67919. var brightOffsets = new Array(8);
  67920. 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);
  67921. this.brightPassPostProcess.onApply = function (effect) {
  67922. var sU = (1.0 / _this.brightPassPostProcess.width);
  67923. var sV = (1.0 / _this.brightPassPostProcess.height);
  67924. brightOffsets[0] = -0.5 * sU;
  67925. brightOffsets[1] = 0.5 * sV;
  67926. brightOffsets[2] = 0.5 * sU;
  67927. brightOffsets[3] = 0.5 * sV;
  67928. brightOffsets[4] = -0.5 * sU;
  67929. brightOffsets[5] = -0.5 * sV;
  67930. brightOffsets[6] = 0.5 * sU;
  67931. brightOffsets[7] = -0.5 * sV;
  67932. effect.setArray2("dsOffsets", brightOffsets);
  67933. effect.setFloat("brightThreshold", _this.brightThreshold);
  67934. };
  67935. // Add to pipeline
  67936. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRBrightPass", function () { return _this.brightPassPostProcess; }, true));
  67937. };
  67938. // Create blur H&V post-processes
  67939. StandardRenderingPipeline.prototype._createBlurPostProcesses = function (scene, ratio, indice, blurWidthKey) {
  67940. var _this = this;
  67941. if (blurWidthKey === void 0) { blurWidthKey = "blurWidth"; }
  67942. var engine = scene.getEngine();
  67943. 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);
  67944. 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);
  67945. blurX.onActivateObservable.add(function () {
  67946. var dw = blurX.width / engine.getRenderWidth();
  67947. blurX.kernel = _this[blurWidthKey] * dw;
  67948. });
  67949. blurY.onActivateObservable.add(function () {
  67950. var dw = blurY.height / engine.getRenderHeight();
  67951. blurY.kernel = _this.horizontalBlur ? 64 * dw : _this[blurWidthKey] * dw;
  67952. });
  67953. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRBlurH" + indice, function () { return blurX; }, true));
  67954. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRBlurV" + indice, function () { return blurY; }, true));
  67955. this.blurHPostProcesses.push(blurX);
  67956. this.blurVPostProcesses.push(blurY);
  67957. };
  67958. // Create texture adder post-process
  67959. StandardRenderingPipeline.prototype._createTextureAdderPostProcess = function (scene, ratio) {
  67960. var _this = this;
  67961. 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);
  67962. this.textureAdderPostProcess.onApply = function (effect) {
  67963. effect.setTextureFromPostProcess("otherSampler", _this._vlsEnabled ? _this._currentDepthOfFieldSource : _this.originalPostProcess);
  67964. effect.setTexture("lensSampler", _this.lensTexture);
  67965. effect.setFloat("exposure", _this.exposure);
  67966. _this._currentDepthOfFieldSource = _this.textureAdderFinalPostProcess;
  67967. };
  67968. // Add to pipeline
  67969. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRTextureAdder", function () { return _this.textureAdderPostProcess; }, true));
  67970. };
  67971. StandardRenderingPipeline.prototype._createVolumetricLightPostProcess = function (scene, ratio) {
  67972. var _this = this;
  67973. var geometryRenderer = scene.enableGeometryBufferRenderer();
  67974. geometryRenderer.enablePosition = true;
  67975. var geometry = geometryRenderer.getGBuffer();
  67976. // Base post-process
  67977. 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));
  67978. var depthValues = BABYLON.Vector2.Zero();
  67979. this.volumetricLightPostProcess.onApply = function (effect) {
  67980. if (_this.sourceLight && _this.sourceLight.getShadowGenerator() && _this._scene.activeCamera) {
  67981. var generator = _this.sourceLight.getShadowGenerator();
  67982. effect.setTexture("shadowMapSampler", generator.getShadowMap());
  67983. effect.setTexture("positionSampler", geometry.textures[2]);
  67984. effect.setColor3("sunColor", _this.sourceLight.diffuse);
  67985. effect.setVector3("sunDirection", _this.sourceLight.getShadowDirection());
  67986. effect.setVector3("cameraPosition", _this._scene.activeCamera.globalPosition);
  67987. effect.setMatrix("shadowViewProjection", generator.getTransformMatrix());
  67988. effect.setFloat("scatteringCoefficient", _this.volumetricLightCoefficient);
  67989. effect.setFloat("scatteringPower", _this.volumetricLightPower);
  67990. depthValues.x = generator.getLight().getDepthMinZ(_this._scene.activeCamera);
  67991. depthValues.y = generator.getLight().getDepthMaxZ(_this._scene.activeCamera);
  67992. effect.setVector2("depthValues", depthValues);
  67993. }
  67994. };
  67995. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRVLS", function () { return _this.volumetricLightPostProcess; }, true));
  67996. // Smooth
  67997. this._createBlurPostProcesses(scene, ratio / 4, 0, "volumetricLightBlurScale");
  67998. // Merge
  67999. this.volumetricLightMergePostProces = new BABYLON.PostProcess("HDRVLSMerge", "standard", [], ["originalSampler"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define VLSMERGE");
  68000. this.volumetricLightMergePostProces.onApply = function (effect) {
  68001. effect.setTextureFromPostProcess("originalSampler", _this.originalPostProcess);
  68002. _this._currentDepthOfFieldSource = _this.volumetricLightFinalPostProcess;
  68003. };
  68004. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRVLSMerge", function () { return _this.volumetricLightMergePostProces; }, true));
  68005. };
  68006. // Create luminance
  68007. StandardRenderingPipeline.prototype._createLuminancePostProcesses = function (scene, textureType) {
  68008. var _this = this;
  68009. // Create luminance
  68010. var size = Math.pow(3, StandardRenderingPipeline.LuminanceSteps);
  68011. this.luminancePostProcess = new BABYLON.PostProcess("HDRLuminance", "standard", ["lumOffsets"], [], { width: size, height: size }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define LUMINANCE", textureType);
  68012. var offsets = [];
  68013. this.luminancePostProcess.onApply = function (effect) {
  68014. var sU = (1.0 / _this.luminancePostProcess.width);
  68015. var sV = (1.0 / _this.luminancePostProcess.height);
  68016. offsets[0] = -0.5 * sU;
  68017. offsets[1] = 0.5 * sV;
  68018. offsets[2] = 0.5 * sU;
  68019. offsets[3] = 0.5 * sV;
  68020. offsets[4] = -0.5 * sU;
  68021. offsets[5] = -0.5 * sV;
  68022. offsets[6] = 0.5 * sU;
  68023. offsets[7] = -0.5 * sV;
  68024. effect.setArray2("lumOffsets", offsets);
  68025. };
  68026. // Add to pipeline
  68027. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRLuminance", function () { return _this.luminancePostProcess; }, true));
  68028. // Create down sample luminance
  68029. for (var i = StandardRenderingPipeline.LuminanceSteps - 1; i >= 0; i--) {
  68030. var size = Math.pow(3, i);
  68031. var defines = "#define LUMINANCE_DOWN_SAMPLE\n";
  68032. if (i === 0) {
  68033. defines += "#define FINAL_DOWN_SAMPLER";
  68034. }
  68035. var postProcess = new BABYLON.PostProcess("HDRLuminanceDownSample" + i, "standard", ["dsOffsets", "halfDestPixelSize"], [], { width: size, height: size }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, defines, textureType);
  68036. this.luminanceDownSamplePostProcesses.push(postProcess);
  68037. }
  68038. // Create callbacks and add effects
  68039. var lastLuminance = this.luminancePostProcess;
  68040. this.luminanceDownSamplePostProcesses.forEach(function (pp, index) {
  68041. var downSampleOffsets = new Array(18);
  68042. pp.onApply = function (effect) {
  68043. if (!lastLuminance) {
  68044. return;
  68045. }
  68046. var id = 0;
  68047. for (var x = -1; x < 2; x++) {
  68048. for (var y = -1; y < 2; y++) {
  68049. downSampleOffsets[id] = x / lastLuminance.width;
  68050. downSampleOffsets[id + 1] = y / lastLuminance.height;
  68051. id += 2;
  68052. }
  68053. }
  68054. effect.setArray2("dsOffsets", downSampleOffsets);
  68055. effect.setFloat("halfDestPixelSize", 0.5 / lastLuminance.width);
  68056. if (index === _this.luminanceDownSamplePostProcesses.length - 1) {
  68057. lastLuminance = _this.luminancePostProcess;
  68058. }
  68059. else {
  68060. lastLuminance = pp;
  68061. }
  68062. };
  68063. if (index === _this.luminanceDownSamplePostProcesses.length - 1) {
  68064. pp.onAfterRender = function (effect) {
  68065. var pixel = scene.getEngine().readPixels(0, 0, 1, 1);
  68066. 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);
  68067. _this._hdrCurrentLuminance = (pixel[0] * bit_shift.x + pixel[1] * bit_shift.y + pixel[2] * bit_shift.z + pixel[3] * bit_shift.w) / 100.0;
  68068. };
  68069. }
  68070. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRLuminanceDownSample" + index, function () { return pp; }, true));
  68071. });
  68072. };
  68073. // Create HDR post-process
  68074. StandardRenderingPipeline.prototype._createHdrPostProcess = function (scene, ratio) {
  68075. var _this = this;
  68076. 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);
  68077. var outputLiminance = 1;
  68078. var time = 0;
  68079. var lastTime = 0;
  68080. this.hdrPostProcess.onApply = function (effect) {
  68081. effect.setTextureFromPostProcess("textureAdderSampler", _this._currentDepthOfFieldSource);
  68082. time += scene.getEngine().getDeltaTime();
  68083. if (outputLiminance < 0) {
  68084. outputLiminance = _this._hdrCurrentLuminance;
  68085. }
  68086. else {
  68087. var dt = (lastTime - time) / 1000.0;
  68088. if (_this._hdrCurrentLuminance < outputLiminance + _this.hdrDecreaseRate * dt) {
  68089. outputLiminance += _this.hdrDecreaseRate * dt;
  68090. }
  68091. else if (_this._hdrCurrentLuminance > outputLiminance - _this.hdrIncreaseRate * dt) {
  68092. outputLiminance -= _this.hdrIncreaseRate * dt;
  68093. }
  68094. else {
  68095. outputLiminance = _this._hdrCurrentLuminance;
  68096. }
  68097. }
  68098. outputLiminance = BABYLON.Scalar.Clamp(outputLiminance, _this.hdrMinimumLuminance, 1e20);
  68099. effect.setFloat("averageLuminance", outputLiminance);
  68100. lastTime = time;
  68101. _this._currentDepthOfFieldSource = _this.hdrFinalPostProcess;
  68102. };
  68103. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDR", function () { return _this.hdrPostProcess; }, true));
  68104. };
  68105. // Create lens flare post-process
  68106. StandardRenderingPipeline.prototype._createLensFlarePostProcess = function (scene, ratio) {
  68107. var _this = this;
  68108. 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);
  68109. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRLensFlare", function () { return _this.lensFlarePostProcess; }, true));
  68110. this._createBlurPostProcesses(scene, ratio / 4, 2);
  68111. 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);
  68112. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRLensFlareCompose", function () { return _this.lensFlareComposePostProcess; }, true));
  68113. var resolution = new BABYLON.Vector2(0, 0);
  68114. // Lens flare
  68115. this.lensFlarePostProcess.onApply = function (effect) {
  68116. effect.setTextureFromPostProcess("textureSampler", _this._bloomEnabled ? _this.blurHPostProcesses[0] : _this.originalPostProcess);
  68117. effect.setTexture("lensColorSampler", _this.lensColorTexture);
  68118. effect.setFloat("strength", _this.lensFlareStrength);
  68119. effect.setFloat("ghostDispersal", _this.lensFlareGhostDispersal);
  68120. effect.setFloat("haloWidth", _this.lensFlareHaloWidth);
  68121. // Shift
  68122. resolution.x = _this.lensFlarePostProcess.width;
  68123. resolution.y = _this.lensFlarePostProcess.height;
  68124. effect.setVector2("resolution", resolution);
  68125. effect.setFloat("distortionStrength", _this.lensFlareDistortionStrength);
  68126. };
  68127. // Compose
  68128. 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);
  68129. 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);
  68130. this.lensFlareComposePostProcess.onApply = function (effect) {
  68131. if (!_this._scene.activeCamera) {
  68132. return;
  68133. }
  68134. effect.setTextureFromPostProcess("otherSampler", _this._currentDepthOfFieldSource);
  68135. effect.setTexture("lensDirtSampler", _this.lensFlareDirtTexture);
  68136. effect.setTexture("lensStarSampler", _this.lensStarTexture);
  68137. // Lens start rotation matrix
  68138. var camerax = _this._scene.activeCamera.getViewMatrix().getRow(0);
  68139. var cameraz = _this._scene.activeCamera.getViewMatrix().getRow(2);
  68140. 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));
  68141. camRot *= 4.0;
  68142. 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);
  68143. var lensStarMatrix = scaleBias2.multiply(starRotation).multiply(scaleBias1);
  68144. effect.setMatrix("lensStarMatrix", lensStarMatrix);
  68145. _this._currentDepthOfFieldSource = _this.lensFlareFinalPostProcess;
  68146. };
  68147. };
  68148. // Create depth-of-field post-process
  68149. StandardRenderingPipeline.prototype._createDepthOfFieldPostProcess = function (scene, ratio) {
  68150. var _this = this;
  68151. 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);
  68152. this.depthOfFieldPostProcess.onApply = function (effect) {
  68153. effect.setTextureFromPostProcess("otherSampler", _this._currentDepthOfFieldSource);
  68154. effect.setTexture("depthSampler", _this._getDepthTexture());
  68155. effect.setFloat("distance", _this.depthOfFieldDistance);
  68156. };
  68157. // Add to pipeline
  68158. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRDepthOfField", function () { return _this.depthOfFieldPostProcess; }, true));
  68159. };
  68160. // Create motion blur post-process
  68161. StandardRenderingPipeline.prototype._createMotionBlurPostProcess = function (scene, ratio) {
  68162. var _this = this;
  68163. 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);
  68164. var motionScale = 0;
  68165. var prevViewProjection = BABYLON.Matrix.Identity();
  68166. var invViewProjection = BABYLON.Matrix.Identity();
  68167. var viewProjection = BABYLON.Matrix.Identity();
  68168. var screenSize = BABYLON.Vector2.Zero();
  68169. this.motionBlurPostProcess.onApply = function (effect) {
  68170. viewProjection = scene.getProjectionMatrix().multiply(scene.getViewMatrix());
  68171. viewProjection.invertToRef(invViewProjection);
  68172. effect.setMatrix("inverseViewProjection", invViewProjection);
  68173. effect.setMatrix("prevViewProjection", prevViewProjection);
  68174. prevViewProjection = viewProjection;
  68175. screenSize.x = _this.motionBlurPostProcess.width;
  68176. screenSize.y = _this.motionBlurPostProcess.height;
  68177. effect.setVector2("screenSize", screenSize);
  68178. motionScale = scene.getEngine().getFps() / 60.0;
  68179. effect.setFloat("motionScale", motionScale);
  68180. effect.setFloat("motionStrength", _this.motionStrength);
  68181. effect.setTexture("depthSampler", _this._getDepthTexture());
  68182. };
  68183. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRMotionBlur", function () { return _this.motionBlurPostProcess; }, true));
  68184. };
  68185. StandardRenderingPipeline.prototype._getDepthTexture = function () {
  68186. if (this._scene.getEngine().getCaps().drawBuffersExtension) {
  68187. var renderer = this._scene.enableGeometryBufferRenderer();
  68188. return renderer.getGBuffer().textures[0];
  68189. }
  68190. return this._scene.enableDepthRenderer().getDepthMap();
  68191. };
  68192. StandardRenderingPipeline.prototype._disposePostProcesses = function () {
  68193. for (var i = 0; i < this._cameras.length; i++) {
  68194. var camera = this._cameras[i];
  68195. if (this.originalPostProcess) {
  68196. this.originalPostProcess.dispose(camera);
  68197. }
  68198. if (this.downSampleX4PostProcess) {
  68199. this.downSampleX4PostProcess.dispose(camera);
  68200. }
  68201. if (this.brightPassPostProcess) {
  68202. this.brightPassPostProcess.dispose(camera);
  68203. }
  68204. if (this.textureAdderPostProcess) {
  68205. this.textureAdderPostProcess.dispose(camera);
  68206. }
  68207. if (this.textureAdderFinalPostProcess) {
  68208. this.textureAdderFinalPostProcess.dispose(camera);
  68209. }
  68210. if (this.volumetricLightPostProcess) {
  68211. this.volumetricLightPostProcess.dispose(camera);
  68212. }
  68213. if (this.volumetricLightSmoothXPostProcess) {
  68214. this.volumetricLightSmoothXPostProcess.dispose(camera);
  68215. }
  68216. if (this.volumetricLightSmoothYPostProcess) {
  68217. this.volumetricLightSmoothYPostProcess.dispose(camera);
  68218. }
  68219. if (this.volumetricLightMergePostProces) {
  68220. this.volumetricLightMergePostProces.dispose(camera);
  68221. }
  68222. if (this.volumetricLightFinalPostProcess) {
  68223. this.volumetricLightFinalPostProcess.dispose(camera);
  68224. }
  68225. if (this.lensFlarePostProcess) {
  68226. this.lensFlarePostProcess.dispose(camera);
  68227. }
  68228. if (this.lensFlareComposePostProcess) {
  68229. this.lensFlareComposePostProcess.dispose(camera);
  68230. }
  68231. for (var j = 0; j < this.luminanceDownSamplePostProcesses.length; j++) {
  68232. this.luminanceDownSamplePostProcesses[j].dispose(camera);
  68233. }
  68234. if (this.luminancePostProcess) {
  68235. this.luminancePostProcess.dispose(camera);
  68236. }
  68237. if (this.hdrPostProcess) {
  68238. this.hdrPostProcess.dispose(camera);
  68239. }
  68240. if (this.hdrFinalPostProcess) {
  68241. this.hdrFinalPostProcess.dispose(camera);
  68242. }
  68243. if (this.depthOfFieldPostProcess) {
  68244. this.depthOfFieldPostProcess.dispose(camera);
  68245. }
  68246. if (this.motionBlurPostProcess) {
  68247. this.motionBlurPostProcess.dispose(camera);
  68248. }
  68249. for (var j = 0; j < this.blurHPostProcesses.length; j++) {
  68250. this.blurHPostProcesses[j].dispose(camera);
  68251. }
  68252. for (var j = 0; j < this.blurVPostProcesses.length; j++) {
  68253. this.blurVPostProcesses[j].dispose(camera);
  68254. }
  68255. }
  68256. this.originalPostProcess = null;
  68257. this.downSampleX4PostProcess = null;
  68258. this.brightPassPostProcess = null;
  68259. this.textureAdderPostProcess = null;
  68260. this.textureAdderFinalPostProcess = null;
  68261. this.volumetricLightPostProcess = null;
  68262. this.volumetricLightSmoothXPostProcess = null;
  68263. this.volumetricLightSmoothYPostProcess = null;
  68264. this.volumetricLightMergePostProces = null;
  68265. this.volumetricLightFinalPostProcess = null;
  68266. this.lensFlarePostProcess = null;
  68267. this.lensFlareComposePostProcess = null;
  68268. this.luminancePostProcess = null;
  68269. this.hdrPostProcess = null;
  68270. this.hdrFinalPostProcess = null;
  68271. this.depthOfFieldPostProcess = null;
  68272. this.motionBlurPostProcess = null;
  68273. this.luminanceDownSamplePostProcesses = [];
  68274. this.blurHPostProcesses = [];
  68275. this.blurVPostProcesses = [];
  68276. };
  68277. // Dispose
  68278. StandardRenderingPipeline.prototype.dispose = function () {
  68279. this._disposePostProcesses();
  68280. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._cameras);
  68281. _super.prototype.dispose.call(this);
  68282. };
  68283. // Serialize rendering pipeline
  68284. StandardRenderingPipeline.prototype.serialize = function () {
  68285. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  68286. serializationObject.customType = "StandardRenderingPipeline";
  68287. return serializationObject;
  68288. };
  68289. /**
  68290. * Static members
  68291. */
  68292. // Parse serialized pipeline
  68293. StandardRenderingPipeline.Parse = function (source, scene, rootUrl) {
  68294. return BABYLON.SerializationHelper.Parse(function () { return new StandardRenderingPipeline(source._name, scene, source._ratio); }, source, scene, rootUrl);
  68295. };
  68296. // Luminance steps
  68297. StandardRenderingPipeline.LuminanceSteps = 6;
  68298. __decorate([
  68299. BABYLON.serialize()
  68300. ], StandardRenderingPipeline.prototype, "brightThreshold", void 0);
  68301. __decorate([
  68302. BABYLON.serialize()
  68303. ], StandardRenderingPipeline.prototype, "blurWidth", void 0);
  68304. __decorate([
  68305. BABYLON.serialize()
  68306. ], StandardRenderingPipeline.prototype, "horizontalBlur", void 0);
  68307. __decorate([
  68308. BABYLON.serialize()
  68309. ], StandardRenderingPipeline.prototype, "exposure", void 0);
  68310. __decorate([
  68311. BABYLON.serializeAsTexture("lensTexture")
  68312. ], StandardRenderingPipeline.prototype, "lensTexture", void 0);
  68313. __decorate([
  68314. BABYLON.serialize()
  68315. ], StandardRenderingPipeline.prototype, "volumetricLightCoefficient", void 0);
  68316. __decorate([
  68317. BABYLON.serialize()
  68318. ], StandardRenderingPipeline.prototype, "volumetricLightPower", void 0);
  68319. __decorate([
  68320. BABYLON.serialize()
  68321. ], StandardRenderingPipeline.prototype, "volumetricLightBlurScale", void 0);
  68322. __decorate([
  68323. BABYLON.serialize()
  68324. ], StandardRenderingPipeline.prototype, "hdrMinimumLuminance", void 0);
  68325. __decorate([
  68326. BABYLON.serialize()
  68327. ], StandardRenderingPipeline.prototype, "hdrDecreaseRate", void 0);
  68328. __decorate([
  68329. BABYLON.serialize()
  68330. ], StandardRenderingPipeline.prototype, "hdrIncreaseRate", void 0);
  68331. __decorate([
  68332. BABYLON.serializeAsTexture("lensColorTexture")
  68333. ], StandardRenderingPipeline.prototype, "lensColorTexture", void 0);
  68334. __decorate([
  68335. BABYLON.serialize()
  68336. ], StandardRenderingPipeline.prototype, "lensFlareStrength", void 0);
  68337. __decorate([
  68338. BABYLON.serialize()
  68339. ], StandardRenderingPipeline.prototype, "lensFlareGhostDispersal", void 0);
  68340. __decorate([
  68341. BABYLON.serialize()
  68342. ], StandardRenderingPipeline.prototype, "lensFlareHaloWidth", void 0);
  68343. __decorate([
  68344. BABYLON.serialize()
  68345. ], StandardRenderingPipeline.prototype, "lensFlareDistortionStrength", void 0);
  68346. __decorate([
  68347. BABYLON.serializeAsTexture("lensStarTexture")
  68348. ], StandardRenderingPipeline.prototype, "lensStarTexture", void 0);
  68349. __decorate([
  68350. BABYLON.serializeAsTexture("lensFlareDirtTexture")
  68351. ], StandardRenderingPipeline.prototype, "lensFlareDirtTexture", void 0);
  68352. __decorate([
  68353. BABYLON.serialize()
  68354. ], StandardRenderingPipeline.prototype, "depthOfFieldDistance", void 0);
  68355. __decorate([
  68356. BABYLON.serialize()
  68357. ], StandardRenderingPipeline.prototype, "depthOfFieldBlurWidth", void 0);
  68358. __decorate([
  68359. BABYLON.serialize()
  68360. ], StandardRenderingPipeline.prototype, "motionStrength", void 0);
  68361. __decorate([
  68362. BABYLON.serialize()
  68363. ], StandardRenderingPipeline.prototype, "_ratio", void 0);
  68364. __decorate([
  68365. BABYLON.serialize()
  68366. ], StandardRenderingPipeline.prototype, "BloomEnabled", null);
  68367. __decorate([
  68368. BABYLON.serialize()
  68369. ], StandardRenderingPipeline.prototype, "DepthOfFieldEnabled", null);
  68370. __decorate([
  68371. BABYLON.serialize()
  68372. ], StandardRenderingPipeline.prototype, "LensFlareEnabled", null);
  68373. __decorate([
  68374. BABYLON.serialize()
  68375. ], StandardRenderingPipeline.prototype, "HDREnabled", null);
  68376. __decorate([
  68377. BABYLON.serialize()
  68378. ], StandardRenderingPipeline.prototype, "VLSEnabled", null);
  68379. __decorate([
  68380. BABYLON.serialize()
  68381. ], StandardRenderingPipeline.prototype, "MotionBlurEnabled", null);
  68382. __decorate([
  68383. BABYLON.serialize()
  68384. ], StandardRenderingPipeline.prototype, "volumetricLightStepsCount", null);
  68385. __decorate([
  68386. BABYLON.serialize()
  68387. ], StandardRenderingPipeline.prototype, "motionBlurSamples", null);
  68388. return StandardRenderingPipeline;
  68389. }(BABYLON.PostProcessRenderPipeline));
  68390. BABYLON.StandardRenderingPipeline = StandardRenderingPipeline;
  68391. })(BABYLON || (BABYLON = {}));
  68392. //# sourceMappingURL=babylon.standardRenderingPipeline.js.map
  68393. var BABYLON;
  68394. (function (BABYLON) {
  68395. var FxaaPostProcess = /** @class */ (function (_super) {
  68396. __extends(FxaaPostProcess, _super);
  68397. function FxaaPostProcess(name, options, camera, samplingMode, engine, reusable, textureType) {
  68398. if (camera === void 0) { camera = null; }
  68399. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  68400. var _this = _super.call(this, name, "fxaa", ["texelSize"], null, options, camera, samplingMode || BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, reusable, null, textureType, "fxaa") || this;
  68401. _this.onApplyObservable.add(function (effect) {
  68402. var texelSize = _this.texelSize;
  68403. effect.setFloat2("texelSize", texelSize.x, texelSize.y);
  68404. });
  68405. return _this;
  68406. }
  68407. return FxaaPostProcess;
  68408. }(BABYLON.PostProcess));
  68409. BABYLON.FxaaPostProcess = FxaaPostProcess;
  68410. })(BABYLON || (BABYLON = {}));
  68411. //# sourceMappingURL=babylon.fxaaPostProcess.js.map
  68412. var BABYLON;
  68413. (function (BABYLON) {
  68414. /**
  68415. * The ChromaticAberrationPostProcess separates the rgb channels in an image to produce chromatic distortion around the edges of the screen
  68416. */
  68417. var ChromaticAberrationPostProcess = /** @class */ (function (_super) {
  68418. __extends(ChromaticAberrationPostProcess, _super);
  68419. /**
  68420. * Creates a new instance of @see ChromaticAberrationPostProcess
  68421. * @param name The name of the effect.
  68422. * @param screenWidth The width of the screen to apply the effect on.
  68423. * @param screenHeight The height of the screen to apply the effect on.
  68424. * @param options The required width/height ratio to downsize to before computing the render pass.
  68425. * @param camera The camera to apply the render pass to.
  68426. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  68427. * @param engine The engine which the post process will be applied. (default: current engine)
  68428. * @param reusable If the post process can be reused on the same frame. (default: false)
  68429. * @param textureType Type of textures used when performing the post process. (default: 0)
  68430. */
  68431. function ChromaticAberrationPostProcess(name, screenWidth, screenHeight, options, camera, samplingMode, engine, reusable, textureType) {
  68432. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  68433. var _this = _super.call(this, name, "chromaticAberration", ["chromatic_aberration", "screen_width", "screen_height", "direction", "radialIntensity", "centerPosition"], [], options, camera, samplingMode, engine, reusable, null, textureType) || this;
  68434. /**
  68435. * The amount of seperation of rgb channels (default: 0)
  68436. */
  68437. _this.aberrationAmount = 0;
  68438. /**
  68439. * The amount the effect will increase for pixels closer to the edge of the screen. (default: 0)
  68440. */
  68441. _this.radialIntensity = 0;
  68442. /**
  68443. * 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))
  68444. */
  68445. _this.direction = new BABYLON.Vector2(0.707, 0.707);
  68446. /**
  68447. * 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))
  68448. */
  68449. _this.centerPosition = new BABYLON.Vector2(0.5, 0.5);
  68450. _this.onApplyObservable.add(function (effect) {
  68451. effect.setFloat('chromatic_aberration', _this.aberrationAmount);
  68452. effect.setFloat('screen_width', screenWidth);
  68453. effect.setFloat('screen_height', screenHeight);
  68454. effect.setFloat('radialIntensity', _this.radialIntensity);
  68455. effect.setFloat2('direction', _this.direction.x, _this.direction.y);
  68456. effect.setFloat2('centerPosition', _this.centerPosition.x, _this.centerPosition.y);
  68457. });
  68458. return _this;
  68459. }
  68460. return ChromaticAberrationPostProcess;
  68461. }(BABYLON.PostProcess));
  68462. BABYLON.ChromaticAberrationPostProcess = ChromaticAberrationPostProcess;
  68463. })(BABYLON || (BABYLON = {}));
  68464. //# sourceMappingURL=babylon.chromaticAberrationPostProcess.js.map
  68465. var BABYLON;
  68466. (function (BABYLON) {
  68467. /**
  68468. * The SharpenPostProcess applies a sharpen kernel to every pixel
  68469. * See http://en.wikipedia.org/wiki/Kernel_(image_processing)
  68470. */
  68471. var SharpenPostProcess = /** @class */ (function (_super) {
  68472. __extends(SharpenPostProcess, _super);
  68473. /**
  68474. * Creates a new instance of @see ConvolutionPostProcess
  68475. * @param name The name of the effect.
  68476. * @param options The required width/height ratio to downsize to before computing the render pass.
  68477. * @param camera The camera to apply the render pass to.
  68478. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  68479. * @param engine The engine which the post process will be applied. (default: current engine)
  68480. * @param reusable If the post process can be reused on the same frame. (default: false)
  68481. * @param textureType Type of textures used when performing the post process. (default: 0)
  68482. */
  68483. function SharpenPostProcess(name, options, camera, samplingMode, engine, reusable, textureType) {
  68484. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  68485. var _this = _super.call(this, name, "sharpen", ["sharpnessAmounts", "screenSize"], null, options, camera, samplingMode, engine, reusable, null, textureType) || this;
  68486. /**
  68487. * How much of the original color should be applied. Setting this to 0 will display edge detection. (default: 1)
  68488. */
  68489. _this.colorAmount = 1.0;
  68490. /**
  68491. * How much sharpness should be applied (default: 0.3)
  68492. */
  68493. _this.edgeAmount = 0.3;
  68494. _this.onApply = function (effect) {
  68495. effect.setFloat2("screenSize", _this.width, _this.height);
  68496. effect.setFloat2("sharpnessAmounts", _this.edgeAmount, _this.colorAmount);
  68497. };
  68498. return _this;
  68499. }
  68500. return SharpenPostProcess;
  68501. }(BABYLON.PostProcess));
  68502. BABYLON.SharpenPostProcess = SharpenPostProcess;
  68503. })(BABYLON || (BABYLON = {}));
  68504. //# sourceMappingURL=babylon.sharpenPostProcess.js.map
  68505. var BABYLON;
  68506. (function (BABYLON) {
  68507. /**
  68508. * The Blur Post Process which blurs an image based on a kernel and direction.
  68509. * Can be used twice in x and y directions to perform a guassian blur in two passes.
  68510. */
  68511. var BlurPostProcess = /** @class */ (function (_super) {
  68512. __extends(BlurPostProcess, _super);
  68513. /**
  68514. * Creates a new instance of @see BlurPostProcess
  68515. * @param name The name of the effect.
  68516. * @param direction The direction in which to blur the image.
  68517. * @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.
  68518. * @param options The required width/height ratio to downsize to before computing the render pass. (Use 1.0 for full size)
  68519. * @param camera The camera to apply the render pass to.
  68520. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  68521. * @param engine The engine which the post process will be applied. (default: current engine)
  68522. * @param reusable If the post process can be reused on the same frame. (default: false)
  68523. * @param textureType Type of textures used when performing the post process. (default: 0)
  68524. */
  68525. function BlurPostProcess(name, /** The direction in which to blur the image. */ direction, kernel, options, camera, samplingMode, engine, reusable, textureType, defines) {
  68526. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  68527. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  68528. if (defines === void 0) { defines = ""; }
  68529. 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;
  68530. _this.direction = direction;
  68531. _this._packedFloat = false;
  68532. _this._staticDefines = "";
  68533. _this._staticDefines = defines;
  68534. _this.onApplyObservable.add(function (effect) {
  68535. effect.setFloat2('delta', (1 / _this.width) * _this.direction.x, (1 / _this.height) * _this.direction.y);
  68536. });
  68537. _this.kernel = kernel;
  68538. return _this;
  68539. }
  68540. Object.defineProperty(BlurPostProcess.prototype, "kernel", {
  68541. /**
  68542. * Gets the length in pixels of the blur sample region
  68543. */
  68544. get: function () {
  68545. return this._idealKernel;
  68546. },
  68547. /**
  68548. * Sets the length in pixels of the blur sample region
  68549. */
  68550. set: function (v) {
  68551. if (this._idealKernel === v) {
  68552. return;
  68553. }
  68554. v = Math.max(v, 1);
  68555. this._idealKernel = v;
  68556. this._kernel = this._nearestBestKernel(v);
  68557. this._updateParameters();
  68558. },
  68559. enumerable: true,
  68560. configurable: true
  68561. });
  68562. Object.defineProperty(BlurPostProcess.prototype, "packedFloat", {
  68563. /**
  68564. * Gets wether or not the blur is unpacking/repacking floats
  68565. */
  68566. get: function () {
  68567. return this._packedFloat;
  68568. },
  68569. /**
  68570. * Sets wether or not the blur needs to unpack/repack floats
  68571. */
  68572. set: function (v) {
  68573. if (this._packedFloat === v) {
  68574. return;
  68575. }
  68576. this._packedFloat = v;
  68577. this._updateParameters();
  68578. },
  68579. enumerable: true,
  68580. configurable: true
  68581. });
  68582. BlurPostProcess.prototype._updateParameters = function () {
  68583. // Generate sampling offsets and weights
  68584. var N = this._kernel;
  68585. var centerIndex = (N - 1) / 2;
  68586. // Generate Gaussian sampling weights over kernel
  68587. var offsets = [];
  68588. var weights = [];
  68589. var totalWeight = 0;
  68590. for (var i = 0; i < N; i++) {
  68591. var u = i / (N - 1);
  68592. var w = this._gaussianWeight(u * 2.0 - 1);
  68593. offsets[i] = (i - centerIndex);
  68594. weights[i] = w;
  68595. totalWeight += w;
  68596. }
  68597. // Normalize weights
  68598. for (var i = 0; i < weights.length; i++) {
  68599. weights[i] /= totalWeight;
  68600. }
  68601. // Optimize: combine samples to take advantage of hardware linear sampling
  68602. // Walk from left to center, combining pairs (symmetrically)
  68603. var linearSamplingWeights = [];
  68604. var linearSamplingOffsets = [];
  68605. var linearSamplingMap = [];
  68606. for (var i = 0; i <= centerIndex; i += 2) {
  68607. var j = Math.min(i + 1, Math.floor(centerIndex));
  68608. var singleCenterSample = i === j;
  68609. if (singleCenterSample) {
  68610. linearSamplingMap.push({ o: offsets[i], w: weights[i] });
  68611. }
  68612. else {
  68613. var sharedCell = j === centerIndex;
  68614. var weightLinear = (weights[i] + weights[j] * (sharedCell ? .5 : 1.));
  68615. var offsetLinear = offsets[i] + 1 / (1 + weights[i] / weights[j]);
  68616. if (offsetLinear === 0) {
  68617. linearSamplingMap.push({ o: offsets[i], w: weights[i] });
  68618. linearSamplingMap.push({ o: offsets[i + 1], w: weights[i + 1] });
  68619. }
  68620. else {
  68621. linearSamplingMap.push({ o: offsetLinear, w: weightLinear });
  68622. linearSamplingMap.push({ o: -offsetLinear, w: weightLinear });
  68623. }
  68624. }
  68625. }
  68626. for (var i = 0; i < linearSamplingMap.length; i++) {
  68627. linearSamplingOffsets[i] = linearSamplingMap[i].o;
  68628. linearSamplingWeights[i] = linearSamplingMap[i].w;
  68629. }
  68630. // Replace with optimized
  68631. offsets = linearSamplingOffsets;
  68632. weights = linearSamplingWeights;
  68633. // Generate shaders
  68634. var maxVaryingRows = this.getEngine().getCaps().maxVaryingVectors;
  68635. var freeVaryingVec2 = Math.max(maxVaryingRows, 0.) - 1; // Because of sampleCenter
  68636. var varyingCount = Math.min(offsets.length, freeVaryingVec2);
  68637. var defines = "";
  68638. defines += this._staticDefines;
  68639. for (var i = 0; i < varyingCount; i++) {
  68640. defines += "#define KERNEL_OFFSET" + i + " " + this._glslFloat(offsets[i]) + "\r\n";
  68641. defines += "#define KERNEL_WEIGHT" + i + " " + this._glslFloat(weights[i]) + "\r\n";
  68642. }
  68643. var depCount = 0;
  68644. for (var i = freeVaryingVec2; i < offsets.length; i++) {
  68645. defines += "#define KERNEL_DEP_OFFSET" + depCount + " " + this._glslFloat(offsets[i]) + "\r\n";
  68646. defines += "#define KERNEL_DEP_WEIGHT" + depCount + " " + this._glslFloat(weights[i]) + "\r\n";
  68647. depCount++;
  68648. }
  68649. if (this.packedFloat) {
  68650. defines += "#define PACKEDFLOAT 1";
  68651. }
  68652. this.updateEffect(defines, null, null, {
  68653. varyingCount: varyingCount,
  68654. depCount: depCount
  68655. });
  68656. };
  68657. /**
  68658. * Best kernels are odd numbers that when divided by 2, their integer part is even, so 5, 9 or 13.
  68659. * Other odd kernels optimize correctly but require proportionally more samples, even kernels are
  68660. * possible but will produce minor visual artifacts. Since each new kernel requires a new shader we
  68661. * want to minimize kernel changes, having gaps between physical kernels is helpful in that regard.
  68662. * The gaps between physical kernels are compensated for in the weighting of the samples
  68663. * @param idealKernel Ideal blur kernel.
  68664. * @return Nearest best kernel.
  68665. */
  68666. BlurPostProcess.prototype._nearestBestKernel = function (idealKernel) {
  68667. var v = Math.round(idealKernel);
  68668. for (var _i = 0, _a = [v, v - 1, v + 1, v - 2, v + 2]; _i < _a.length; _i++) {
  68669. var k = _a[_i];
  68670. if (((k % 2) !== 0) && ((Math.floor(k / 2) % 2) === 0) && k > 0) {
  68671. return Math.max(k, 3);
  68672. }
  68673. }
  68674. return Math.max(v, 3);
  68675. };
  68676. /**
  68677. * Calculates the value of a Gaussian distribution with sigma 3 at a given point.
  68678. * @param x The point on the Gaussian distribution to sample.
  68679. * @return the value of the Gaussian function at x.
  68680. */
  68681. BlurPostProcess.prototype._gaussianWeight = function (x) {
  68682. //reference: Engine/ImageProcessingBlur.cpp #dcc760
  68683. // We are evaluating the Gaussian (normal) distribution over a kernel parameter space of [-1,1],
  68684. // so we truncate at three standard deviations by setting stddev (sigma) to 1/3.
  68685. // The choice of 3-sigma truncation is common but arbitrary, and means that the signal is
  68686. // truncated at around 1.3% of peak strength.
  68687. //the distribution is scaled to account for the difference between the actual kernel size and the requested kernel size
  68688. var sigma = (1 / 3);
  68689. var denominator = Math.sqrt(2.0 * Math.PI) * sigma;
  68690. var exponent = -((x * x) / (2.0 * sigma * sigma));
  68691. var weight = (1.0 / denominator) * Math.exp(exponent);
  68692. return weight;
  68693. };
  68694. /**
  68695. * Generates a string that can be used as a floating point number in GLSL.
  68696. * @param x Value to print.
  68697. * @param decimalFigures Number of decimal places to print the number to (excluding trailing 0s).
  68698. * @return GLSL float string.
  68699. */
  68700. BlurPostProcess.prototype._glslFloat = function (x, decimalFigures) {
  68701. if (decimalFigures === void 0) { decimalFigures = 8; }
  68702. return x.toFixed(decimalFigures).replace(/0+$/, '');
  68703. };
  68704. return BlurPostProcess;
  68705. }(BABYLON.PostProcess));
  68706. BABYLON.BlurPostProcess = BlurPostProcess;
  68707. })(BABYLON || (BABYLON = {}));
  68708. //# sourceMappingURL=babylon.blurPostProcess.js.map
  68709. var BABYLON;
  68710. (function (BABYLON) {
  68711. /**
  68712. * The DepthOfFieldBlurPostProcess applied a blur in a give direction.
  68713. * This blur differs from the standard BlurPostProcess as it attempts to avoid blurring pixels
  68714. * based on samples that have a large difference in distance than the center pixel.
  68715. * See section 2.6.2 http://fileadmin.cs.lth.se/cs/education/edan35/lectures/12dof.pdf
  68716. */
  68717. var DepthOfFieldBlurPostProcess = /** @class */ (function (_super) {
  68718. __extends(DepthOfFieldBlurPostProcess, _super);
  68719. /**
  68720. * Creates a new instance of @see CircleOfConfusionPostProcess
  68721. * @param name The name of the effect.
  68722. * @param scene The scene the effect belongs to.
  68723. * @param direction The direction the blur should be applied.
  68724. * @param kernel The size of the kernel used to blur.
  68725. * @param options The required width/height ratio to downsize to before computing the render pass.
  68726. * @param camera The camera to apply the render pass to.
  68727. * @param circleOfConfusion The circle of confusion + depth map to be used to avoid blurring accross edges
  68728. * @param imageToBlur The image to apply the blur to (default: Current rendered frame)
  68729. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  68730. * @param engine The engine which the post process will be applied. (default: current engine)
  68731. * @param reusable If the post process can be reused on the same frame. (default: false)
  68732. * @param textureType Type of textures used when performing the post process. (default: 0)
  68733. */
  68734. function DepthOfFieldBlurPostProcess(name, scene, direction, kernel, options, camera, circleOfConfusion, imageToBlur, samplingMode, engine, reusable, textureType) {
  68735. if (imageToBlur === void 0) { imageToBlur = null; }
  68736. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  68737. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  68738. 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") || this;
  68739. _this.direction = direction;
  68740. _this.onApplyObservable.add(function (effect) {
  68741. if (imageToBlur != null) {
  68742. effect.setTextureFromPostProcess("textureSampler", imageToBlur);
  68743. }
  68744. effect.setTextureFromPostProcess("circleOfConfusionSampler", circleOfConfusion);
  68745. if (scene.activeCamera) {
  68746. effect.setFloat2('cameraMinMaxZ', scene.activeCamera.minZ, scene.activeCamera.maxZ);
  68747. }
  68748. });
  68749. return _this;
  68750. }
  68751. return DepthOfFieldBlurPostProcess;
  68752. }(BABYLON.BlurPostProcess));
  68753. BABYLON.DepthOfFieldBlurPostProcess = DepthOfFieldBlurPostProcess;
  68754. })(BABYLON || (BABYLON = {}));
  68755. //# sourceMappingURL=babylon.depthOfFieldBlurPostProcess.js.map
  68756. var BABYLON;
  68757. (function (BABYLON) {
  68758. /**
  68759. * The DepthOfFieldMergePostProcess merges blurred images with the original based on the values of the circle of confusion.
  68760. */
  68761. var DepthOfFieldMergePostProcess = /** @class */ (function (_super) {
  68762. __extends(DepthOfFieldMergePostProcess, _super);
  68763. /**
  68764. * Creates a new instance of @see CircleOfConfusionPostProcess
  68765. * @param name The name of the effect.
  68766. * @param original The non-blurred image to be modified
  68767. * @param circleOfConfusion The circle of confusion post process that will determine how blurred each pixel should become.
  68768. * @param blurSteps Incrimental bluring post processes.
  68769. * @param options The required width/height ratio to downsize to before computing the render pass.
  68770. * @param camera The camera to apply the render pass to.
  68771. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  68772. * @param engine The engine which the post process will be applied. (default: current engine)
  68773. * @param reusable If the post process can be reused on the same frame. (default: false)
  68774. * @param textureType Type of textures used when performing the post process. (default: 0)
  68775. */
  68776. function DepthOfFieldMergePostProcess(name, original, circleOfConfusion, blurSteps, options, camera, samplingMode, engine, reusable, textureType) {
  68777. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  68778. var _this = _super.call(this, name, "depthOfFieldMerge", [], ["circleOfConfusionSampler", "originalSampler", "blurStep1", "blurStep2"], options, camera, samplingMode, engine, reusable, "#define BLUR_LEVEL " + blurSteps.length + "\n", textureType) || this;
  68779. _this.onApplyObservable.add(function (effect) {
  68780. effect.setTextureFromPostProcess("circleOfConfusionSampler", circleOfConfusion);
  68781. effect.setTextureFromPostProcess("originalSampler", original);
  68782. blurSteps.forEach(function (step, index) {
  68783. effect.setTextureFromPostProcess("blurStep" + (index + 1), step);
  68784. });
  68785. });
  68786. return _this;
  68787. }
  68788. return DepthOfFieldMergePostProcess;
  68789. }(BABYLON.PostProcess));
  68790. BABYLON.DepthOfFieldMergePostProcess = DepthOfFieldMergePostProcess;
  68791. })(BABYLON || (BABYLON = {}));
  68792. //# sourceMappingURL=babylon.depthOfFieldMergePostProcess.js.map
  68793. var BABYLON;
  68794. (function (BABYLON) {
  68795. /**
  68796. * The CircleOfConfusionPostProcess computes the circle of confusion value for each pixel given required lens parameters. See https://en.wikipedia.org/wiki/Circle_of_confusion
  68797. */
  68798. var CircleOfConfusionPostProcess = /** @class */ (function (_super) {
  68799. __extends(CircleOfConfusionPostProcess, _super);
  68800. /**
  68801. * Creates a new instance of @see CircleOfConfusionPostProcess
  68802. * @param name The name of the effect.
  68803. * @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.
  68804. * @param options The required width/height ratio to downsize to before computing the render pass.
  68805. * @param camera The camera to apply the render pass to.
  68806. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  68807. * @param engine The engine which the post process will be applied. (default: current engine)
  68808. * @param reusable If the post process can be reused on the same frame. (default: false)
  68809. * @param textureType Type of textures used when performing the post process. (default: 0)
  68810. */
  68811. function CircleOfConfusionPostProcess(name, depthTexture, options, camera, samplingMode, engine, reusable, textureType) {
  68812. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  68813. var _this = _super.call(this, name, "circleOfConfusion", ["cameraMinMaxZ", "focusDistance", "cocPrecalculation"], ["depthSampler"], options, camera, samplingMode, engine, reusable, null, textureType) || this;
  68814. /**
  68815. * 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.
  68816. */
  68817. _this.lensSize = 50;
  68818. /**
  68819. * F-Stop of the effect's camera. The diamater of the resulting aperture can be computed by lensSize/fStop. (default: 1.4)
  68820. */
  68821. _this.fStop = 1.4;
  68822. /**
  68823. * Distance away from the camera to focus on in scene units/1000 (eg. millimeter). (default: 2000)
  68824. */
  68825. _this.focusDistance = 2000;
  68826. /**
  68827. * Focal length of the effect's camera in scene units/1000 (eg. millimeter). (default: 50)
  68828. */
  68829. _this.focalLength = 50;
  68830. _this._depthTexture = null;
  68831. _this._depthTexture = depthTexture;
  68832. _this.onApplyObservable.add(function (effect) {
  68833. if (!_this._depthTexture) {
  68834. BABYLON.Tools.Warn("No depth texture set on CircleOfConfusionPostProcess");
  68835. return;
  68836. }
  68837. effect.setTexture("depthSampler", _this._depthTexture);
  68838. // Circle of confusion calculation, See https://developer.nvidia.com/gpugems/GPUGems/gpugems_ch23.html
  68839. var aperture = _this.lensSize / _this.fStop;
  68840. var cocPrecalculation = ((aperture * _this.focalLength) / ((_this.focusDistance - _this.focalLength))); // * ((this.focusDistance - pixelDistance)/pixelDistance) [This part is done in shader]
  68841. effect.setFloat('focusDistance', _this.focusDistance);
  68842. effect.setFloat('cocPrecalculation', cocPrecalculation);
  68843. effect.setFloat2('cameraMinMaxZ', _this._depthTexture.activeCamera.minZ, _this._depthTexture.activeCamera.maxZ);
  68844. });
  68845. return _this;
  68846. }
  68847. Object.defineProperty(CircleOfConfusionPostProcess.prototype, "depthTexture", {
  68848. /**
  68849. * 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.
  68850. */
  68851. set: function (value) {
  68852. this._depthTexture = value;
  68853. },
  68854. enumerable: true,
  68855. configurable: true
  68856. });
  68857. return CircleOfConfusionPostProcess;
  68858. }(BABYLON.PostProcess));
  68859. BABYLON.CircleOfConfusionPostProcess = CircleOfConfusionPostProcess;
  68860. })(BABYLON || (BABYLON = {}));
  68861. //# sourceMappingURL=babylon.circleOfConfusionPostProcess.js.map
  68862. var BABYLON;
  68863. (function (BABYLON) {
  68864. /**
  68865. * Specifies the level of max blur that should be applied when using the depth of field effect
  68866. */
  68867. var DepthOfFieldEffectBlurLevel;
  68868. (function (DepthOfFieldEffectBlurLevel) {
  68869. /**
  68870. * Subtle blur
  68871. */
  68872. DepthOfFieldEffectBlurLevel[DepthOfFieldEffectBlurLevel["Low"] = 0] = "Low";
  68873. /**
  68874. * Medium blur
  68875. */
  68876. DepthOfFieldEffectBlurLevel[DepthOfFieldEffectBlurLevel["Medium"] = 1] = "Medium";
  68877. /**
  68878. * Large blur
  68879. */
  68880. DepthOfFieldEffectBlurLevel[DepthOfFieldEffectBlurLevel["High"] = 2] = "High";
  68881. })(DepthOfFieldEffectBlurLevel = BABYLON.DepthOfFieldEffectBlurLevel || (BABYLON.DepthOfFieldEffectBlurLevel = {}));
  68882. ;
  68883. /**
  68884. * The depth of field effect applies a blur to objects that are closer or further from where the camera is focusing.
  68885. */
  68886. var DepthOfFieldEffect = /** @class */ (function (_super) {
  68887. __extends(DepthOfFieldEffect, _super);
  68888. /**
  68889. * Creates a new instance of @see DepthOfFieldEffect
  68890. * @param scene The scene the effect belongs to.
  68891. * @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.
  68892. * @param pipelineTextureType The type of texture to be used when performing the post processing.
  68893. */
  68894. function DepthOfFieldEffect(scene, depthTexture, blurLevel, pipelineTextureType) {
  68895. if (blurLevel === void 0) { blurLevel = DepthOfFieldEffectBlurLevel.Low; }
  68896. if (pipelineTextureType === void 0) { pipelineTextureType = 0; }
  68897. var _this = _super.call(this, scene.getEngine(), "depth of field", function () {
  68898. return _this._effects;
  68899. }, true) || this;
  68900. _this._effects = [];
  68901. // Circle of confusion value for each pixel is used to determine how much to blur that pixel
  68902. _this._circleOfConfusion = new BABYLON.CircleOfConfusionPostProcess("circleOfConfusion", depthTexture, 1, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, pipelineTextureType);
  68903. // Capture circle of confusion texture
  68904. _this._depthOfFieldPass = new BABYLON.PassPostProcess("depthOfFieldPass", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, pipelineTextureType);
  68905. _this._depthOfFieldPass.autoClear = false;
  68906. // 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)
  68907. // Blur the image but do not blur on sharp far to near distance changes to avoid bleeding artifacts
  68908. // See section 2.6.2 http://fileadmin.cs.lth.se/cs/education/edan35/lectures/12dof.pdf
  68909. _this._depthOfFieldBlurY = [];
  68910. _this._depthOfFieldBlurX = [];
  68911. var blurCount = 1;
  68912. var kernelSize = 15;
  68913. switch (blurLevel) {
  68914. case DepthOfFieldEffectBlurLevel.High: {
  68915. blurCount = 3;
  68916. kernelSize = 51;
  68917. break;
  68918. }
  68919. case DepthOfFieldEffectBlurLevel.Medium: {
  68920. blurCount = 2;
  68921. kernelSize = 31;
  68922. break;
  68923. }
  68924. default: {
  68925. kernelSize = 15;
  68926. blurCount = 1;
  68927. break;
  68928. }
  68929. }
  68930. var adjustedKernelSize = kernelSize / Math.pow(2, blurCount - 1);
  68931. for (var i = 0; i < blurCount; i++) {
  68932. var blurY = new BABYLON.DepthOfFieldBlurPostProcess("verticle blur", scene, new BABYLON.Vector2(0, 1.0), adjustedKernelSize, 1.0 / Math.pow(2, i), null, _this._depthOfFieldPass, i == 0 ? _this._circleOfConfusion : null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, pipelineTextureType);
  68933. blurY.autoClear = false;
  68934. var blurX = new BABYLON.DepthOfFieldBlurPostProcess("horizontal blur", scene, new BABYLON.Vector2(1.0, 0), adjustedKernelSize, 1.0 / Math.pow(2, i), null, _this._depthOfFieldPass, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, pipelineTextureType);
  68935. blurX.autoClear = false;
  68936. _this._depthOfFieldBlurY.push(blurY);
  68937. _this._depthOfFieldBlurX.push(blurX);
  68938. }
  68939. // Merge blurred images with original image based on circleOfConfusion
  68940. _this._depthOfFieldMerge = new BABYLON.DepthOfFieldMergePostProcess("depthOfFieldMerge", _this._circleOfConfusion, _this._depthOfFieldPass, _this._depthOfFieldBlurY.slice(1), 1, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, pipelineTextureType);
  68941. _this._depthOfFieldMerge.autoClear = false;
  68942. // Set all post processes on the effect.
  68943. _this._effects = [_this._circleOfConfusion, _this._depthOfFieldPass];
  68944. for (var i = 0; i < _this._depthOfFieldBlurX.length; i++) {
  68945. _this._effects.push(_this._depthOfFieldBlurY[i]);
  68946. _this._effects.push(_this._depthOfFieldBlurX[i]);
  68947. }
  68948. _this._effects.push(_this._depthOfFieldMerge);
  68949. return _this;
  68950. }
  68951. Object.defineProperty(DepthOfFieldEffect.prototype, "focalLength", {
  68952. get: function () {
  68953. return this._circleOfConfusion.focalLength;
  68954. },
  68955. /**
  68956. * The focal the length of the camera used in the effect
  68957. */
  68958. set: function (value) {
  68959. this._circleOfConfusion.focalLength = value;
  68960. },
  68961. enumerable: true,
  68962. configurable: true
  68963. });
  68964. Object.defineProperty(DepthOfFieldEffect.prototype, "fStop", {
  68965. get: function () {
  68966. return this._circleOfConfusion.fStop;
  68967. },
  68968. /**
  68969. * F-Stop of the effect's camera. The diamater of the resulting aperture can be computed by lensSize/fStop. (default: 1.4)
  68970. */
  68971. set: function (value) {
  68972. this._circleOfConfusion.fStop = value;
  68973. },
  68974. enumerable: true,
  68975. configurable: true
  68976. });
  68977. Object.defineProperty(DepthOfFieldEffect.prototype, "focusDistance", {
  68978. get: function () {
  68979. return this._circleOfConfusion.focusDistance;
  68980. },
  68981. /**
  68982. * Distance away from the camera to focus on in scene units/1000 (eg. millimeter). (default: 2000)
  68983. */
  68984. set: function (value) {
  68985. this._circleOfConfusion.focusDistance = value;
  68986. },
  68987. enumerable: true,
  68988. configurable: true
  68989. });
  68990. Object.defineProperty(DepthOfFieldEffect.prototype, "lensSize", {
  68991. get: function () {
  68992. return this._circleOfConfusion.lensSize;
  68993. },
  68994. /**
  68995. * 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.
  68996. */
  68997. set: function (value) {
  68998. this._circleOfConfusion.lensSize = value;
  68999. },
  69000. enumerable: true,
  69001. configurable: true
  69002. });
  69003. Object.defineProperty(DepthOfFieldEffect.prototype, "depthTexture", {
  69004. /**
  69005. * 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.
  69006. */
  69007. set: function (value) {
  69008. this._circleOfConfusion.depthTexture = value;
  69009. },
  69010. enumerable: true,
  69011. configurable: true
  69012. });
  69013. /**
  69014. * Disposes each of the internal effects for a given camera.
  69015. * @param camera The camera to dispose the effect on.
  69016. */
  69017. DepthOfFieldEffect.prototype.disposeEffects = function (camera) {
  69018. this._depthOfFieldPass.dispose(camera);
  69019. this._circleOfConfusion.dispose(camera);
  69020. this._depthOfFieldBlurX.forEach(function (element) {
  69021. element.dispose(camera);
  69022. });
  69023. this._depthOfFieldBlurY.forEach(function (element) {
  69024. element.dispose(camera);
  69025. });
  69026. this._depthOfFieldMerge.dispose(camera);
  69027. };
  69028. return DepthOfFieldEffect;
  69029. }(BABYLON.PostProcessRenderEffect));
  69030. BABYLON.DepthOfFieldEffect = DepthOfFieldEffect;
  69031. })(BABYLON || (BABYLON = {}));
  69032. //# sourceMappingURL=babylon.depthOfFieldEffect.js.map
  69033. var BABYLON;
  69034. (function (BABYLON) {
  69035. /**
  69036. * The default rendering pipeline can be added to a scene to apply common post processing effects such as anti-aliasing or depth of field.
  69037. * See https://doc.babylonjs.com/how_to/using_default_rendering_pipeline
  69038. */
  69039. var DefaultRenderingPipeline = /** @class */ (function (_super) {
  69040. __extends(DefaultRenderingPipeline, _super);
  69041. /**
  69042. * @constructor
  69043. * @param {string} name - The rendering pipeline name
  69044. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  69045. * @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)
  69046. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  69047. * @param {boolean} automaticBuild - if false, you will have to manually call prepare() to update the pipeline
  69048. */
  69049. function DefaultRenderingPipeline(name, hdr, scene, cameras, automaticBuild) {
  69050. if (automaticBuild === void 0) { automaticBuild = true; }
  69051. var _this = _super.call(this, scene.getEngine(), name) || this;
  69052. _this._originalCameras = [];
  69053. /**
  69054. * ID of the sharpen post process,
  69055. */
  69056. _this.SharpenPostProcessId = "SharpenPostProcessEffect";
  69057. /**
  69058. * ID of the pass post process used for bloom,
  69059. */
  69060. _this.PassPostProcessId = "PassPostProcessEffect";
  69061. /**
  69062. * ID of the highlight post process used for bloom,
  69063. */
  69064. _this.HighLightsPostProcessId = "HighLightsPostProcessEffect";
  69065. /**
  69066. * ID of the blurX post process used for bloom,
  69067. */
  69068. _this.BlurXPostProcessId = "BlurXPostProcessEffect";
  69069. /**
  69070. * ID of the blurY post process used for bloom,
  69071. */
  69072. _this.BlurYPostProcessId = "BlurYPostProcessEffect";
  69073. /**
  69074. * ID of the copy back post process used for bloom,
  69075. */
  69076. _this.CopyBackPostProcessId = "CopyBackPostProcessEffect";
  69077. /**
  69078. * ID of the image processing post process;
  69079. */
  69080. _this.ImageProcessingPostProcessId = "ImageProcessingPostProcessEffect";
  69081. /**
  69082. * ID of the Fast Approximate Anti-Aliasing post process;
  69083. */
  69084. _this.FxaaPostProcessId = "FxaaPostProcessEffect";
  69085. /**
  69086. * ID of the final merge post process;
  69087. */
  69088. _this.FinalMergePostProcessId = "FinalMergePostProcessEffect";
  69089. /**
  69090. * ID of the chromatic aberration post process,
  69091. */
  69092. _this.ChromaticAberrationPostProcessId = "ChromaticAberrationPostProcessEffect";
  69093. /**
  69094. * Animations which can be used to tweak settings over a period of time
  69095. */
  69096. _this.animations = [];
  69097. // Values
  69098. _this._sharpenEnabled = false;
  69099. _this._bloomEnabled = false;
  69100. _this._depthOfFieldEnabled = false;
  69101. _this._depthOfFieldBlurLevel = BABYLON.DepthOfFieldEffectBlurLevel.Low;
  69102. _this._fxaaEnabled = false;
  69103. _this._msaaEnabled = false;
  69104. _this._imageProcessingEnabled = true;
  69105. _this._bloomScale = 0.6;
  69106. _this._chromaticAberrationEnabled = false;
  69107. _this._buildAllowed = true;
  69108. /**
  69109. * Specifies the size of the bloom blur kernel, relative to the final output size
  69110. */
  69111. _this.bloomKernel = 64;
  69112. /**
  69113. * Specifies the weight of the bloom in the final rendering
  69114. */
  69115. _this._bloomWeight = 0.15;
  69116. _this._prevPostProcess = null;
  69117. _this._prevPrevPostProcess = null;
  69118. _this._cameras = cameras || [];
  69119. _this._originalCameras = _this._cameras.slice();
  69120. _this._buildAllowed = automaticBuild;
  69121. // Initialize
  69122. _this._scene = scene;
  69123. var caps = _this._scene.getEngine().getCaps();
  69124. _this._hdr = hdr && (caps.textureHalfFloatRender || caps.textureFloatRender);
  69125. // Misc
  69126. if (_this._hdr) {
  69127. if (caps.textureHalfFloatRender) {
  69128. _this._defaultPipelineTextureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  69129. }
  69130. else if (caps.textureFloatRender) {
  69131. _this._defaultPipelineTextureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  69132. }
  69133. }
  69134. else {
  69135. _this._defaultPipelineTextureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  69136. }
  69137. // Attach
  69138. scene.postProcessRenderPipelineManager.addPipeline(_this);
  69139. var engine = _this._scene.getEngine();
  69140. _this.sharpen = new BABYLON.SharpenPostProcess("sharpen", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, _this._defaultPipelineTextureType);
  69141. _this._sharpenEffect = new BABYLON.PostProcessRenderEffect(engine, _this.SharpenPostProcessId, function () { return _this.sharpen; }, true);
  69142. _this.depthOfField = new BABYLON.DepthOfFieldEffect(_this._scene, null, _this._depthOfFieldBlurLevel, _this._defaultPipelineTextureType);
  69143. _this.chromaticAberration = new BABYLON.ChromaticAberrationPostProcess("ChromaticAberration", engine.getRenderWidth(), engine.getRenderHeight(), 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, _this._defaultPipelineTextureType);
  69144. _this._chromaticAberrationEffect = new BABYLON.PostProcessRenderEffect(engine, _this.ChromaticAberrationPostProcessId, function () { return _this.chromaticAberration; }, true);
  69145. _this._buildPipeline();
  69146. return _this;
  69147. }
  69148. Object.defineProperty(DefaultRenderingPipeline.prototype, "sharpenEnabled", {
  69149. get: function () {
  69150. return this._sharpenEnabled;
  69151. },
  69152. /**
  69153. * Enable or disable the sharpen process from the pipeline
  69154. */
  69155. set: function (enabled) {
  69156. if (this._sharpenEnabled === enabled) {
  69157. return;
  69158. }
  69159. this._sharpenEnabled = enabled;
  69160. this._buildPipeline();
  69161. },
  69162. enumerable: true,
  69163. configurable: true
  69164. });
  69165. Object.defineProperty(DefaultRenderingPipeline.prototype, "bloomWeight", {
  69166. get: function () {
  69167. return this._bloomWeight;
  69168. },
  69169. /**
  69170. * The strength of the bloom.
  69171. */
  69172. set: function (value) {
  69173. if (this._bloomWeight === value) {
  69174. return;
  69175. }
  69176. this._bloomWeight = value;
  69177. if (this._hdr && this.copyBack) {
  69178. this.copyBack.alphaConstants = new BABYLON.Color4(value, value, value, value);
  69179. }
  69180. },
  69181. enumerable: true,
  69182. configurable: true
  69183. });
  69184. Object.defineProperty(DefaultRenderingPipeline.prototype, "bloomScale", {
  69185. get: function () {
  69186. return this._bloomScale;
  69187. },
  69188. /**
  69189. * The scale of the bloom, lower value will provide better performance.
  69190. */
  69191. set: function (value) {
  69192. if (this._bloomScale === value) {
  69193. return;
  69194. }
  69195. this._bloomScale = value;
  69196. this._buildPipeline();
  69197. },
  69198. enumerable: true,
  69199. configurable: true
  69200. });
  69201. Object.defineProperty(DefaultRenderingPipeline.prototype, "bloomEnabled", {
  69202. get: function () {
  69203. return this._bloomEnabled;
  69204. },
  69205. /**
  69206. * Enable or disable the bloom from the pipeline
  69207. */
  69208. set: function (enabled) {
  69209. if (this._bloomEnabled === enabled) {
  69210. return;
  69211. }
  69212. this._bloomEnabled = enabled;
  69213. this._buildPipeline();
  69214. },
  69215. enumerable: true,
  69216. configurable: true
  69217. });
  69218. Object.defineProperty(DefaultRenderingPipeline.prototype, "depthOfFieldEnabled", {
  69219. /**
  69220. * If the depth of field is enabled.
  69221. */
  69222. get: function () {
  69223. return this._depthOfFieldEnabled;
  69224. },
  69225. set: function (enabled) {
  69226. if (this._depthOfFieldEnabled === enabled) {
  69227. return;
  69228. }
  69229. this._depthOfFieldEnabled = enabled;
  69230. this._buildPipeline();
  69231. },
  69232. enumerable: true,
  69233. configurable: true
  69234. });
  69235. Object.defineProperty(DefaultRenderingPipeline.prototype, "depthOfFieldBlurLevel", {
  69236. /**
  69237. * Blur level of the depth of field effect. (Higher blur will effect performance)
  69238. */
  69239. get: function () {
  69240. return this._depthOfFieldBlurLevel;
  69241. },
  69242. set: function (value) {
  69243. if (this._depthOfFieldBlurLevel === value) {
  69244. return;
  69245. }
  69246. this._depthOfFieldBlurLevel = value;
  69247. // recreate dof and dispose old as this setting is not dynamic
  69248. var oldDof = this.depthOfField;
  69249. this.depthOfField = new BABYLON.DepthOfFieldEffect(this._scene, null, this._depthOfFieldBlurLevel, this._defaultPipelineTextureType);
  69250. this.depthOfField.focalLength = oldDof.focalLength;
  69251. this.depthOfField.focusDistance = oldDof.focusDistance;
  69252. this.depthOfField.fStop = oldDof.fStop;
  69253. this.depthOfField.lensSize = oldDof.lensSize;
  69254. for (var i = 0; i < this._cameras.length; i++) {
  69255. oldDof.disposeEffects(this._cameras[i]);
  69256. }
  69257. this._buildPipeline();
  69258. },
  69259. enumerable: true,
  69260. configurable: true
  69261. });
  69262. Object.defineProperty(DefaultRenderingPipeline.prototype, "fxaaEnabled", {
  69263. get: function () {
  69264. return this._fxaaEnabled;
  69265. },
  69266. /**
  69267. * If the anti aliasing is enabled.
  69268. */
  69269. set: function (enabled) {
  69270. if (this._fxaaEnabled === enabled) {
  69271. return;
  69272. }
  69273. this._fxaaEnabled = enabled;
  69274. this._buildPipeline();
  69275. },
  69276. enumerable: true,
  69277. configurable: true
  69278. });
  69279. Object.defineProperty(DefaultRenderingPipeline.prototype, "msaaEnabled", {
  69280. get: function () {
  69281. return this._msaaEnabled;
  69282. },
  69283. /**
  69284. * If the multisample anti-aliasing is enabled.
  69285. */
  69286. set: function (enabled) {
  69287. if (this._msaaEnabled === enabled) {
  69288. return;
  69289. }
  69290. this._msaaEnabled = enabled;
  69291. this._buildPipeline();
  69292. },
  69293. enumerable: true,
  69294. configurable: true
  69295. });
  69296. Object.defineProperty(DefaultRenderingPipeline.prototype, "imageProcessingEnabled", {
  69297. get: function () {
  69298. return this._imageProcessingEnabled;
  69299. },
  69300. /**
  69301. * If image processing is enabled.
  69302. */
  69303. set: function (enabled) {
  69304. if (this._imageProcessingEnabled === enabled) {
  69305. return;
  69306. }
  69307. this._imageProcessingEnabled = enabled;
  69308. this._buildPipeline();
  69309. },
  69310. enumerable: true,
  69311. configurable: true
  69312. });
  69313. Object.defineProperty(DefaultRenderingPipeline.prototype, "chromaticAberrationEnabled", {
  69314. get: function () {
  69315. return this._chromaticAberrationEnabled;
  69316. },
  69317. /**
  69318. * Enable or disable the chromaticAberration process from the pipeline
  69319. */
  69320. set: function (enabled) {
  69321. if (this._chromaticAberrationEnabled === enabled) {
  69322. return;
  69323. }
  69324. this._chromaticAberrationEnabled = enabled;
  69325. this._buildPipeline();
  69326. },
  69327. enumerable: true,
  69328. configurable: true
  69329. });
  69330. /**
  69331. * Force the compilation of the entire pipeline.
  69332. */
  69333. DefaultRenderingPipeline.prototype.prepare = function () {
  69334. var previousState = this._buildAllowed;
  69335. this._buildAllowed = true;
  69336. this._buildPipeline();
  69337. this._buildAllowed = previousState;
  69338. };
  69339. DefaultRenderingPipeline.prototype._setAutoClearAndTextureSharing = function (postProcess, skipTextureSharing) {
  69340. if (skipTextureSharing === void 0) { skipTextureSharing = false; }
  69341. if (this._prevPostProcess && this._prevPostProcess.autoClear) {
  69342. postProcess.autoClear = false;
  69343. }
  69344. else {
  69345. postProcess.autoClear = true;
  69346. }
  69347. if (!skipTextureSharing) {
  69348. if (this._prevPrevPostProcess) {
  69349. postProcess.shareOutputWith(this._prevPrevPostProcess);
  69350. }
  69351. else {
  69352. postProcess.useOwnOutput();
  69353. }
  69354. if (this._prevPostProcess) {
  69355. this._prevPrevPostProcess = this._prevPostProcess;
  69356. }
  69357. this._prevPostProcess = postProcess;
  69358. }
  69359. };
  69360. DefaultRenderingPipeline.prototype._buildPipeline = function () {
  69361. var _this = this;
  69362. if (!this._buildAllowed) {
  69363. return;
  69364. }
  69365. var engine = this._scene.getEngine();
  69366. this._disposePostProcesses();
  69367. if (this._cameras !== null) {
  69368. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._cameras);
  69369. // get back cameras to be used to reattach pipeline
  69370. this._cameras = this._originalCameras.slice();
  69371. }
  69372. this._reset();
  69373. this._prevPostProcess = null;
  69374. this._prevPrevPostProcess = null;
  69375. if (this.sharpenEnabled) {
  69376. this.addEffect(this._sharpenEffect);
  69377. this._setAutoClearAndTextureSharing(this.sharpen);
  69378. }
  69379. if (this.depthOfFieldEnabled) {
  69380. var depthTexture = this._scene.enableDepthRenderer(this._cameras[0]).getDepthMap();
  69381. this.depthOfField.depthTexture = depthTexture;
  69382. this.addEffect(this.depthOfField);
  69383. this._setAutoClearAndTextureSharing(this.depthOfField._depthOfFieldMerge);
  69384. }
  69385. if (this.bloomEnabled) {
  69386. this.pass = new BABYLON.PassPostProcess("sceneRenderTarget", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, this._defaultPipelineTextureType);
  69387. this._setAutoClearAndTextureSharing(this.pass, true);
  69388. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.PassPostProcessId, function () { return _this.pass; }, true));
  69389. if (!this._hdr) {
  69390. this.highlights = new BABYLON.HighlightsPostProcess("highlights", this.bloomScale, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, this._defaultPipelineTextureType);
  69391. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.HighLightsPostProcessId, function () { return _this.highlights; }, true));
  69392. this.highlights.autoClear = false;
  69393. this.highlights.alwaysForcePOT = true;
  69394. }
  69395. this.blurX = new BABYLON.BlurPostProcess("horizontal blur", new BABYLON.Vector2(1.0, 0), 10.0, this.bloomScale, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, this._defaultPipelineTextureType);
  69396. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.BlurXPostProcessId, function () { return _this.blurX; }, true));
  69397. this.blurX.alwaysForcePOT = true;
  69398. this.blurX.autoClear = false;
  69399. this.blurX.onActivateObservable.add(function () {
  69400. var dw = _this.blurX.width / engine.getRenderWidth(true);
  69401. _this.blurX.kernel = _this.bloomKernel * dw;
  69402. });
  69403. this.blurY = new BABYLON.BlurPostProcess("vertical blur", new BABYLON.Vector2(0, 1.0), 10.0, this.bloomScale, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, this._defaultPipelineTextureType);
  69404. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.BlurYPostProcessId, function () { return _this.blurY; }, true));
  69405. this.blurY.alwaysForcePOT = true;
  69406. this.blurY.autoClear = false;
  69407. this.blurY.onActivateObservable.add(function () {
  69408. var dh = _this.blurY.height / engine.getRenderHeight(true);
  69409. _this.blurY.kernel = _this.bloomKernel * dh;
  69410. });
  69411. this.copyBack = new BABYLON.PassPostProcess("bloomBlendBlit", this.bloomScale, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, this._defaultPipelineTextureType);
  69412. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.CopyBackPostProcessId, function () { return _this.copyBack; }, true));
  69413. this.copyBack.alwaysForcePOT = true;
  69414. if (this._hdr) {
  69415. this.copyBack.alphaMode = BABYLON.Engine.ALPHA_INTERPOLATE;
  69416. var w = this.bloomWeight;
  69417. this.copyBack.alphaConstants = new BABYLON.Color4(w, w, w, w);
  69418. }
  69419. else {
  69420. this.copyBack.alphaMode = BABYLON.Engine.ALPHA_SCREENMODE;
  69421. }
  69422. this.copyBack.autoClear = false;
  69423. }
  69424. if (this._imageProcessingEnabled) {
  69425. this.imageProcessing = new BABYLON.ImageProcessingPostProcess("imageProcessing", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, this._defaultPipelineTextureType);
  69426. if (this._hdr) {
  69427. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.ImageProcessingPostProcessId, function () { return _this.imageProcessing; }, true));
  69428. }
  69429. else {
  69430. this._scene.imageProcessingConfiguration.applyByPostProcess = false;
  69431. }
  69432. }
  69433. if (this._hdr && this.imageProcessing) {
  69434. this.finalMerge = this.imageProcessing;
  69435. }
  69436. else {
  69437. this.finalMerge = new BABYLON.PassPostProcess("finalMerge", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, this._defaultPipelineTextureType);
  69438. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.FinalMergePostProcessId, function () { return _this.finalMerge; }, true));
  69439. this._setAutoClearAndTextureSharing(this.finalMerge, true);
  69440. this.finalMerge.autoClear = !this.bloomEnabled && (!this._hdr || !this.imageProcessing);
  69441. }
  69442. if (this.bloomEnabled) {
  69443. if (this._hdr) {
  69444. this.copyBack.shareOutputWith(this.blurX);
  69445. if (this.imageProcessing) {
  69446. this.imageProcessing.shareOutputWith(this.pass);
  69447. this.imageProcessing.autoClear = false;
  69448. }
  69449. else {
  69450. this.finalMerge.shareOutputWith(this.pass);
  69451. }
  69452. }
  69453. else {
  69454. this.finalMerge.shareOutputWith(this.pass);
  69455. }
  69456. }
  69457. if (this.fxaaEnabled) {
  69458. this.fxaa = new BABYLON.FxaaPostProcess("fxaa", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, this._defaultPipelineTextureType);
  69459. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.FxaaPostProcessId, function () { return _this.fxaa; }, true));
  69460. this._setAutoClearAndTextureSharing(this.fxaa);
  69461. }
  69462. if (this.chromaticAberrationEnabled) {
  69463. this.addEffect(this._chromaticAberrationEffect);
  69464. this._setAutoClearAndTextureSharing(this.chromaticAberration);
  69465. }
  69466. if (this._cameras !== null) {
  69467. this._scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(this._name, this._cameras);
  69468. }
  69469. if (this.msaaEnabled) {
  69470. if (!this._enableMSAAOnFirstPostProcess()) {
  69471. BABYLON.Tools.Warn("MSAA failed to enable, MSAA is only supported in browsers that support webGL >= 2.0");
  69472. }
  69473. }
  69474. };
  69475. DefaultRenderingPipeline.prototype._disposePostProcesses = function (disposeNonRecreated) {
  69476. if (disposeNonRecreated === void 0) { disposeNonRecreated = false; }
  69477. for (var i = 0; i < this._cameras.length; i++) {
  69478. var camera = this._cameras[i];
  69479. if (this.pass) {
  69480. this.pass.dispose(camera);
  69481. }
  69482. if (this.highlights) {
  69483. this.highlights.dispose(camera);
  69484. }
  69485. if (this.blurX) {
  69486. this.blurX.dispose(camera);
  69487. }
  69488. if (this.blurY) {
  69489. this.blurY.dispose(camera);
  69490. }
  69491. if (this.copyBack) {
  69492. this.copyBack.dispose(camera);
  69493. }
  69494. if (this.imageProcessing) {
  69495. this.imageProcessing.dispose(camera);
  69496. }
  69497. if (this.fxaa) {
  69498. this.fxaa.dispose(camera);
  69499. }
  69500. if (this.finalMerge) {
  69501. this.finalMerge.dispose(camera);
  69502. }
  69503. // These are created in the constructor and should not be disposed on every pipeline change
  69504. if (disposeNonRecreated) {
  69505. if (this.sharpen) {
  69506. this.sharpen.dispose(camera);
  69507. }
  69508. if (this.depthOfField) {
  69509. this.depthOfField.disposeEffects(camera);
  69510. }
  69511. if (this.chromaticAberration) {
  69512. this.chromaticAberration.dispose(camera);
  69513. }
  69514. }
  69515. }
  69516. this.pass = null;
  69517. this.highlights = null;
  69518. this.blurX = null;
  69519. this.blurY = null;
  69520. this.copyBack = null;
  69521. this.imageProcessing = null;
  69522. this.fxaa = null;
  69523. this.finalMerge = null;
  69524. if (disposeNonRecreated) {
  69525. this.sharpen = null;
  69526. this.depthOfField = null;
  69527. this.chromaticAberration = null;
  69528. }
  69529. };
  69530. /**
  69531. * Dispose of the pipeline and stop all post processes
  69532. */
  69533. DefaultRenderingPipeline.prototype.dispose = function () {
  69534. this._disposePostProcesses(true);
  69535. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._cameras);
  69536. _super.prototype.dispose.call(this);
  69537. };
  69538. /**
  69539. * Serialize the rendering pipeline (Used when exporting)
  69540. * @returns the serialized object
  69541. */
  69542. DefaultRenderingPipeline.prototype.serialize = function () {
  69543. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  69544. serializationObject.customType = "DefaultRenderingPipeline";
  69545. return serializationObject;
  69546. };
  69547. /**
  69548. * Parse the serialized pipeline
  69549. * @param source Source pipeline.
  69550. * @param scene The scene to load the pipeline to.
  69551. * @param rootUrl The URL of the serialized pipeline.
  69552. * @returns An instantiated pipeline from the serialized object.
  69553. */
  69554. DefaultRenderingPipeline.Parse = function (source, scene, rootUrl) {
  69555. return BABYLON.SerializationHelper.Parse(function () { return new DefaultRenderingPipeline(source._name, source._name._hdr, scene); }, source, scene, rootUrl);
  69556. };
  69557. __decorate([
  69558. BABYLON.serialize()
  69559. ], DefaultRenderingPipeline.prototype, "sharpenEnabled", null);
  69560. __decorate([
  69561. BABYLON.serialize()
  69562. ], DefaultRenderingPipeline.prototype, "bloomKernel", void 0);
  69563. __decorate([
  69564. BABYLON.serialize()
  69565. ], DefaultRenderingPipeline.prototype, "_bloomWeight", void 0);
  69566. __decorate([
  69567. BABYLON.serialize()
  69568. ], DefaultRenderingPipeline.prototype, "_hdr", void 0);
  69569. __decorate([
  69570. BABYLON.serialize()
  69571. ], DefaultRenderingPipeline.prototype, "bloomWeight", null);
  69572. __decorate([
  69573. BABYLON.serialize()
  69574. ], DefaultRenderingPipeline.prototype, "bloomScale", null);
  69575. __decorate([
  69576. BABYLON.serialize()
  69577. ], DefaultRenderingPipeline.prototype, "bloomEnabled", null);
  69578. __decorate([
  69579. BABYLON.serialize()
  69580. ], DefaultRenderingPipeline.prototype, "depthOfFieldEnabled", null);
  69581. __decorate([
  69582. BABYLON.serialize()
  69583. ], DefaultRenderingPipeline.prototype, "depthOfFieldBlurLevel", null);
  69584. __decorate([
  69585. BABYLON.serialize()
  69586. ], DefaultRenderingPipeline.prototype, "fxaaEnabled", null);
  69587. __decorate([
  69588. BABYLON.serialize()
  69589. ], DefaultRenderingPipeline.prototype, "msaaEnabled", null);
  69590. __decorate([
  69591. BABYLON.serialize()
  69592. ], DefaultRenderingPipeline.prototype, "imageProcessingEnabled", null);
  69593. __decorate([
  69594. BABYLON.serialize()
  69595. ], DefaultRenderingPipeline.prototype, "chromaticAberrationEnabled", null);
  69596. return DefaultRenderingPipeline;
  69597. }(BABYLON.PostProcessRenderPipeline));
  69598. BABYLON.DefaultRenderingPipeline = DefaultRenderingPipeline;
  69599. })(BABYLON || (BABYLON = {}));
  69600. //# sourceMappingURL=babylon.defaultRenderingPipeline.js.map
  69601. var BABYLON;
  69602. (function (BABYLON) {
  69603. /**
  69604. * This renderer is helpfull to fill one of the render target with a geometry buffer.
  69605. */
  69606. var GeometryBufferRenderer = /** @class */ (function () {
  69607. /**
  69608. * Creates a new G Buffer for the scene. @see GeometryBufferRenderer
  69609. * @param scene The scene the buffer belongs to
  69610. * @param ratio How big is the buffer related to the main canvas.
  69611. */
  69612. function GeometryBufferRenderer(scene, ratio) {
  69613. if (ratio === void 0) { ratio = 1; }
  69614. this._enablePosition = false;
  69615. this._scene = scene;
  69616. this._ratio = ratio;
  69617. // Render target
  69618. this._createRenderTargets();
  69619. }
  69620. Object.defineProperty(GeometryBufferRenderer.prototype, "renderList", {
  69621. /**
  69622. * Set the render list (meshes to be rendered) used in the G buffer.
  69623. */
  69624. set: function (meshes) {
  69625. this._multiRenderTarget.renderList = meshes;
  69626. },
  69627. enumerable: true,
  69628. configurable: true
  69629. });
  69630. Object.defineProperty(GeometryBufferRenderer.prototype, "isSupported", {
  69631. /**
  69632. * Gets wether or not G buffer are supported by the running hardware.
  69633. * This requires draw buffer supports
  69634. */
  69635. get: function () {
  69636. return this._multiRenderTarget.isSupported;
  69637. },
  69638. enumerable: true,
  69639. configurable: true
  69640. });
  69641. Object.defineProperty(GeometryBufferRenderer.prototype, "enablePosition", {
  69642. /**
  69643. * Gets wether or not position are enabled for the G buffer.
  69644. */
  69645. get: function () {
  69646. return this._enablePosition;
  69647. },
  69648. /**
  69649. * Sets wether or not position are enabled for the G buffer.
  69650. */
  69651. set: function (enable) {
  69652. this._enablePosition = enable;
  69653. this.dispose();
  69654. this._createRenderTargets();
  69655. },
  69656. enumerable: true,
  69657. configurable: true
  69658. });
  69659. Object.defineProperty(GeometryBufferRenderer.prototype, "scene", {
  69660. /**
  69661. * Gets the scene associated with the buffer.
  69662. */
  69663. get: function () {
  69664. return this._scene;
  69665. },
  69666. enumerable: true,
  69667. configurable: true
  69668. });
  69669. Object.defineProperty(GeometryBufferRenderer.prototype, "ratio", {
  69670. /**
  69671. * Gets the ratio used by the buffer during its creation.
  69672. * How big is the buffer related to the main canvas.
  69673. */
  69674. get: function () {
  69675. return this._ratio;
  69676. },
  69677. enumerable: true,
  69678. configurable: true
  69679. });
  69680. /**
  69681. * Checks wether everything is ready to render a submesh to the G buffer.
  69682. * @param subMesh the submesh to check readiness for
  69683. * @param useInstances is the mesh drawn using instance or not
  69684. * @returns true if ready otherwise false
  69685. */
  69686. GeometryBufferRenderer.prototype.isReady = function (subMesh, useInstances) {
  69687. var material = subMesh.getMaterial();
  69688. if (material && material.disableDepthWrite) {
  69689. return false;
  69690. }
  69691. var defines = [];
  69692. var attribs = [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.NormalKind];
  69693. var mesh = subMesh.getMesh();
  69694. // Alpha test
  69695. if (material && material.needAlphaTesting()) {
  69696. defines.push("#define ALPHATEST");
  69697. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  69698. attribs.push(BABYLON.VertexBuffer.UVKind);
  69699. defines.push("#define UV1");
  69700. }
  69701. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  69702. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  69703. defines.push("#define UV2");
  69704. }
  69705. }
  69706. // Buffers
  69707. if (this._enablePosition) {
  69708. defines.push("#define POSITION");
  69709. }
  69710. // Bones
  69711. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  69712. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  69713. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  69714. if (mesh.numBoneInfluencers > 4) {
  69715. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  69716. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  69717. }
  69718. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  69719. defines.push("#define BonesPerMesh " + (mesh.skeleton ? mesh.skeleton.bones.length + 1 : 0));
  69720. }
  69721. else {
  69722. defines.push("#define NUM_BONE_INFLUENCERS 0");
  69723. }
  69724. // Instances
  69725. if (useInstances) {
  69726. defines.push("#define INSTANCES");
  69727. attribs.push("world0");
  69728. attribs.push("world1");
  69729. attribs.push("world2");
  69730. attribs.push("world3");
  69731. }
  69732. // Get correct effect
  69733. var join = defines.join("\n");
  69734. if (this._cachedDefines !== join) {
  69735. this._cachedDefines = join;
  69736. this._effect = this._scene.getEngine().createEffect("geometry", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "view"], ["diffuseSampler"], join, undefined, undefined, undefined, { buffersCount: this._enablePosition ? 3 : 2 });
  69737. }
  69738. return this._effect.isReady();
  69739. };
  69740. /**
  69741. * Gets the current underlying G Buffer.
  69742. * @returns the buffer
  69743. */
  69744. GeometryBufferRenderer.prototype.getGBuffer = function () {
  69745. return this._multiRenderTarget;
  69746. };
  69747. Object.defineProperty(GeometryBufferRenderer.prototype, "samples", {
  69748. /**
  69749. * Gets the number of samples used to render the buffer (anti aliasing).
  69750. */
  69751. get: function () {
  69752. return this._multiRenderTarget.samples;
  69753. },
  69754. /**
  69755. * Sets the number of samples used to render the buffer (anti aliasing).
  69756. */
  69757. set: function (value) {
  69758. this._multiRenderTarget.samples = value;
  69759. },
  69760. enumerable: true,
  69761. configurable: true
  69762. });
  69763. /**
  69764. * Disposes the renderer and frees up associated resources.
  69765. */
  69766. GeometryBufferRenderer.prototype.dispose = function () {
  69767. this.getGBuffer().dispose();
  69768. };
  69769. GeometryBufferRenderer.prototype._createRenderTargets = function () {
  69770. var _this = this;
  69771. var engine = this._scene.getEngine();
  69772. var count = this._enablePosition ? 3 : 2;
  69773. 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 });
  69774. if (!this.isSupported) {
  69775. return;
  69776. }
  69777. this._multiRenderTarget.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  69778. this._multiRenderTarget.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  69779. this._multiRenderTarget.refreshRate = 1;
  69780. this._multiRenderTarget.renderParticles = false;
  69781. this._multiRenderTarget.renderList = null;
  69782. // set default depth value to 1.0 (far away)
  69783. this._multiRenderTarget.onClearObservable.add(function (engine) {
  69784. engine.clear(new BABYLON.Color4(0.0, 0.0, 0.0, 1.0), true, true, true);
  69785. });
  69786. // Custom render function
  69787. var renderSubMesh = function (subMesh) {
  69788. var mesh = subMesh.getRenderingMesh();
  69789. var scene = _this._scene;
  69790. var engine = scene.getEngine();
  69791. var material = subMesh.getMaterial();
  69792. if (!material) {
  69793. return;
  69794. }
  69795. // Culling
  69796. engine.setState(material.backFaceCulling, 0, false, scene.useRightHandedSystem);
  69797. // Managing instances
  69798. var batch = mesh._getInstancesRenderList(subMesh._id);
  69799. if (batch.mustReturn) {
  69800. return;
  69801. }
  69802. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null);
  69803. if (_this.isReady(subMesh, hardwareInstancedRendering)) {
  69804. engine.enableEffect(_this._effect);
  69805. mesh._bind(subMesh, _this._effect, BABYLON.Material.TriangleFillMode);
  69806. _this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  69807. _this._effect.setMatrix("view", scene.getViewMatrix());
  69808. // Alpha test
  69809. if (material && material.needAlphaTesting()) {
  69810. var alphaTexture = material.getAlphaTestTexture();
  69811. if (alphaTexture) {
  69812. _this._effect.setTexture("diffuseSampler", alphaTexture);
  69813. _this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  69814. }
  69815. }
  69816. // Bones
  69817. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  69818. _this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  69819. }
  69820. // Draw
  69821. mesh._processRendering(subMesh, _this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effect.setMatrix("world", world); });
  69822. }
  69823. };
  69824. this._multiRenderTarget.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes) {
  69825. var index;
  69826. if (depthOnlySubMeshes.length) {
  69827. engine.setColorWrite(false);
  69828. for (index = 0; index < depthOnlySubMeshes.length; index++) {
  69829. renderSubMesh(depthOnlySubMeshes.data[index]);
  69830. }
  69831. engine.setColorWrite(true);
  69832. }
  69833. for (index = 0; index < opaqueSubMeshes.length; index++) {
  69834. renderSubMesh(opaqueSubMeshes.data[index]);
  69835. }
  69836. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  69837. renderSubMesh(alphaTestSubMeshes.data[index]);
  69838. }
  69839. };
  69840. };
  69841. return GeometryBufferRenderer;
  69842. }());
  69843. BABYLON.GeometryBufferRenderer = GeometryBufferRenderer;
  69844. })(BABYLON || (BABYLON = {}));
  69845. //# sourceMappingURL=babylon.geometryBufferRenderer.js.map
  69846. var BABYLON;
  69847. (function (BABYLON) {
  69848. var RefractionPostProcess = /** @class */ (function (_super) {
  69849. __extends(RefractionPostProcess, _super);
  69850. function RefractionPostProcess(name, refractionTextureUrl, color, depth, colorLevel, options, camera, samplingMode, engine, reusable) {
  69851. var _this = _super.call(this, name, "refraction", ["baseColor", "depth", "colorLevel"], ["refractionSampler"], options, camera, samplingMode, engine, reusable) || this;
  69852. _this.color = color;
  69853. _this.depth = depth;
  69854. _this.colorLevel = colorLevel;
  69855. _this._ownRefractionTexture = true;
  69856. _this.onActivateObservable.add(function (cam) {
  69857. _this._refTexture = _this._refTexture || new BABYLON.Texture(refractionTextureUrl, cam.getScene());
  69858. });
  69859. _this.onApplyObservable.add(function (effect) {
  69860. effect.setColor3("baseColor", _this.color);
  69861. effect.setFloat("depth", _this.depth);
  69862. effect.setFloat("colorLevel", _this.colorLevel);
  69863. effect.setTexture("refractionSampler", _this._refTexture);
  69864. });
  69865. return _this;
  69866. }
  69867. Object.defineProperty(RefractionPostProcess.prototype, "refractionTexture", {
  69868. /**
  69869. * Gets or sets the refraction texture
  69870. * Please note that you are responsible for disposing the texture if you set it manually
  69871. */
  69872. get: function () {
  69873. return this._refTexture;
  69874. },
  69875. set: function (value) {
  69876. if (this._refTexture && this._ownRefractionTexture) {
  69877. this._refTexture.dispose();
  69878. }
  69879. this._refTexture = value;
  69880. this._ownRefractionTexture = false;
  69881. },
  69882. enumerable: true,
  69883. configurable: true
  69884. });
  69885. // Methods
  69886. RefractionPostProcess.prototype.dispose = function (camera) {
  69887. if (this._refTexture && this._ownRefractionTexture) {
  69888. this._refTexture.dispose();
  69889. this._refTexture = null;
  69890. }
  69891. _super.prototype.dispose.call(this, camera);
  69892. };
  69893. return RefractionPostProcess;
  69894. }(BABYLON.PostProcess));
  69895. BABYLON.RefractionPostProcess = RefractionPostProcess;
  69896. })(BABYLON || (BABYLON = {}));
  69897. //# sourceMappingURL=babylon.refractionPostProcess.js.map
  69898. var BABYLON;
  69899. (function (BABYLON) {
  69900. var BlackAndWhitePostProcess = /** @class */ (function (_super) {
  69901. __extends(BlackAndWhitePostProcess, _super);
  69902. function BlackAndWhitePostProcess(name, options, camera, samplingMode, engine, reusable) {
  69903. var _this = _super.call(this, name, "blackAndWhite", ["degree"], null, options, camera, samplingMode, engine, reusable) || this;
  69904. _this.degree = 1;
  69905. _this.onApplyObservable.add(function (effect) {
  69906. effect.setFloat("degree", _this.degree);
  69907. });
  69908. return _this;
  69909. }
  69910. return BlackAndWhitePostProcess;
  69911. }(BABYLON.PostProcess));
  69912. BABYLON.BlackAndWhitePostProcess = BlackAndWhitePostProcess;
  69913. })(BABYLON || (BABYLON = {}));
  69914. //# sourceMappingURL=babylon.blackAndWhitePostProcess.js.map
  69915. var BABYLON;
  69916. (function (BABYLON) {
  69917. /**
  69918. * The ConvolutionPostProcess applies a 3x3 kernel to every pixel of the
  69919. * input texture to perform effects such as edge detection or sharpening
  69920. * See http://en.wikipedia.org/wiki/Kernel_(image_processing)
  69921. */
  69922. var ConvolutionPostProcess = /** @class */ (function (_super) {
  69923. __extends(ConvolutionPostProcess, _super);
  69924. /**
  69925. * Creates a new instance of @see ConvolutionPostProcess
  69926. * @param name The name of the effect.
  69927. * @param kernel Array of 9 values corrisponding to the 3x3 kernel to be applied
  69928. * @param options The required width/height ratio to downsize to before computing the render pass.
  69929. * @param camera The camera to apply the render pass to.
  69930. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  69931. * @param engine The engine which the post process will be applied. (default: current engine)
  69932. * @param reusable If the post process can be reused on the same frame. (default: false)
  69933. * @param textureType Type of textures used when performing the post process. (default: 0)
  69934. */
  69935. function ConvolutionPostProcess(name, /** Array of 9 values corrisponding to the 3x3 kernel to be applied */ kernel, options, camera, samplingMode, engine, reusable, textureType) {
  69936. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  69937. var _this = _super.call(this, name, "convolution", ["kernel", "screenSize"], null, options, camera, samplingMode, engine, reusable, null, textureType) || this;
  69938. _this.kernel = kernel;
  69939. _this.onApply = function (effect) {
  69940. effect.setFloat2("screenSize", _this.width, _this.height);
  69941. effect.setArray("kernel", _this.kernel);
  69942. };
  69943. return _this;
  69944. }
  69945. // Statics
  69946. /**
  69947. * Edge detection 0 see https://en.wikipedia.org/wiki/Kernel_(image_processing)
  69948. */
  69949. ConvolutionPostProcess.EdgeDetect0Kernel = [1, 0, -1, 0, 0, 0, -1, 0, 1];
  69950. /**
  69951. * Edge detection 1 see https://en.wikipedia.org/wiki/Kernel_(image_processing)
  69952. */
  69953. ConvolutionPostProcess.EdgeDetect1Kernel = [0, 1, 0, 1, -4, 1, 0, 1, 0];
  69954. /**
  69955. * Edge detection 2 see https://en.wikipedia.org/wiki/Kernel_(image_processing)
  69956. */
  69957. ConvolutionPostProcess.EdgeDetect2Kernel = [-1, -1, -1, -1, 8, -1, -1, -1, -1];
  69958. /**
  69959. * Kernel to sharpen an image see https://en.wikipedia.org/wiki/Kernel_(image_processing)
  69960. */
  69961. ConvolutionPostProcess.SharpenKernel = [0, -1, 0, -1, 5, -1, 0, -1, 0];
  69962. /**
  69963. * Kernel to emboss an image see https://en.wikipedia.org/wiki/Kernel_(image_processing)
  69964. */
  69965. ConvolutionPostProcess.EmbossKernel = [-2, -1, 0, -1, 1, 1, 0, 1, 2];
  69966. /**
  69967. * Kernel to blur an image see https://en.wikipedia.org/wiki/Kernel_(image_processing)
  69968. */
  69969. ConvolutionPostProcess.GaussianKernel = [0, 1, 0, 1, 1, 1, 0, 1, 0];
  69970. return ConvolutionPostProcess;
  69971. }(BABYLON.PostProcess));
  69972. BABYLON.ConvolutionPostProcess = ConvolutionPostProcess;
  69973. })(BABYLON || (BABYLON = {}));
  69974. //# sourceMappingURL=babylon.convolutionPostProcess.js.map
  69975. var BABYLON;
  69976. (function (BABYLON) {
  69977. var FilterPostProcess = /** @class */ (function (_super) {
  69978. __extends(FilterPostProcess, _super);
  69979. function FilterPostProcess(name, kernelMatrix, options, camera, samplingMode, engine, reusable) {
  69980. var _this = _super.call(this, name, "filter", ["kernelMatrix"], null, options, camera, samplingMode, engine, reusable) || this;
  69981. _this.kernelMatrix = kernelMatrix;
  69982. _this.onApply = function (effect) {
  69983. effect.setMatrix("kernelMatrix", _this.kernelMatrix);
  69984. };
  69985. return _this;
  69986. }
  69987. return FilterPostProcess;
  69988. }(BABYLON.PostProcess));
  69989. BABYLON.FilterPostProcess = FilterPostProcess;
  69990. })(BABYLON || (BABYLON = {}));
  69991. //# sourceMappingURL=babylon.filterPostProcess.js.map
  69992. var BABYLON;
  69993. (function (BABYLON) {
  69994. // Inspired by http://http.developer.nvidia.com/GPUGems3/gpugems3_ch13.html
  69995. var VolumetricLightScatteringPostProcess = /** @class */ (function (_super) {
  69996. __extends(VolumetricLightScatteringPostProcess, _super);
  69997. /**
  69998. * @constructor
  69999. * @param {string} name - The post-process name
  70000. * @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)
  70001. * @param {BABYLON.Camera} camera - The camera that the post-process will be attached to
  70002. * @param {BABYLON.Mesh} mesh - The mesh used to create the light scattering
  70003. * @param {number} samples - The post-process quality, default 100
  70004. * @param {number} samplingMode - The post-process filtering mode
  70005. * @param {BABYLON.Engine} engine - The babylon engine
  70006. * @param {boolean} reusable - If the post-process is reusable
  70007. * @param {BABYLON.Scene} scene - The constructor needs a scene reference to initialize internal components. If "camera" is null (RenderPipelineà, "scene" must be provided
  70008. */
  70009. function VolumetricLightScatteringPostProcess(name, ratio, camera, mesh, samples, samplingMode, engine, reusable, scene) {
  70010. if (samples === void 0) { samples = 100; }
  70011. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  70012. 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;
  70013. _this._screenCoordinates = BABYLON.Vector2.Zero();
  70014. /**
  70015. * Custom position of the mesh. Used if "useCustomMeshPosition" is set to "true"
  70016. * @type {Vector3}
  70017. */
  70018. _this.customMeshPosition = BABYLON.Vector3.Zero();
  70019. /**
  70020. * Set if the post-process should use a custom position for the light source (true) or the internal mesh position (false)
  70021. * @type {boolean}
  70022. */
  70023. _this.useCustomMeshPosition = false;
  70024. /**
  70025. * If the post-process should inverse the light scattering direction
  70026. * @type {boolean}
  70027. */
  70028. _this.invert = true;
  70029. /**
  70030. * Array containing the excluded meshes not rendered in the internal pass
  70031. */
  70032. _this.excludedMeshes = new Array();
  70033. /**
  70034. * Controls the overall intensity of the post-process
  70035. * @type {number}
  70036. */
  70037. _this.exposure = 0.3;
  70038. /**
  70039. * Dissipates each sample's contribution in range [0, 1]
  70040. * @type {number}
  70041. */
  70042. _this.decay = 0.96815;
  70043. /**
  70044. * Controls the overall intensity of each sample
  70045. * @type {number}
  70046. */
  70047. _this.weight = 0.58767;
  70048. /**
  70049. * Controls the density of each sample
  70050. * @type {number}
  70051. */
  70052. _this.density = 0.926;
  70053. scene = ((camera === null) ? scene : camera.getScene()); // parameter "scene" can be null.
  70054. engine = scene.getEngine();
  70055. _this._viewPort = new BABYLON.Viewport(0, 0, 1, 1).toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  70056. // Configure mesh
  70057. _this.mesh = ((mesh !== null) ? mesh : VolumetricLightScatteringPostProcess.CreateDefaultMesh("VolumetricLightScatteringMesh", scene));
  70058. // Configure
  70059. _this._createPass(scene, ratio.passRatio || ratio);
  70060. _this.onActivate = function (camera) {
  70061. if (!_this.isSupported) {
  70062. _this.dispose(camera);
  70063. }
  70064. _this.onActivate = null;
  70065. };
  70066. _this.onApplyObservable.add(function (effect) {
  70067. _this._updateMeshScreenCoordinates(scene);
  70068. effect.setTexture("lightScatteringSampler", _this._volumetricLightScatteringRTT);
  70069. effect.setFloat("exposure", _this.exposure);
  70070. effect.setFloat("decay", _this.decay);
  70071. effect.setFloat("weight", _this.weight);
  70072. effect.setFloat("density", _this.density);
  70073. effect.setVector2("meshPositionOnScreen", _this._screenCoordinates);
  70074. });
  70075. return _this;
  70076. }
  70077. Object.defineProperty(VolumetricLightScatteringPostProcess.prototype, "useDiffuseColor", {
  70078. get: function () {
  70079. BABYLON.Tools.Warn("VolumetricLightScatteringPostProcess.useDiffuseColor is no longer used, use the mesh material directly instead");
  70080. return false;
  70081. },
  70082. set: function (useDiffuseColor) {
  70083. BABYLON.Tools.Warn("VolumetricLightScatteringPostProcess.useDiffuseColor is no longer used, use the mesh material directly instead");
  70084. },
  70085. enumerable: true,
  70086. configurable: true
  70087. });
  70088. VolumetricLightScatteringPostProcess.prototype.getClassName = function () {
  70089. return "VolumetricLightScatteringPostProcess";
  70090. };
  70091. VolumetricLightScatteringPostProcess.prototype._isReady = function (subMesh, useInstances) {
  70092. var mesh = subMesh.getMesh();
  70093. // Render this.mesh as default
  70094. if (mesh === this.mesh && mesh.material) {
  70095. return mesh.material.isReady(mesh);
  70096. }
  70097. var defines = [];
  70098. var attribs = [BABYLON.VertexBuffer.PositionKind];
  70099. var material = subMesh.getMaterial();
  70100. // Alpha test
  70101. if (material) {
  70102. if (material.needAlphaTesting()) {
  70103. defines.push("#define ALPHATEST");
  70104. }
  70105. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  70106. attribs.push(BABYLON.VertexBuffer.UVKind);
  70107. defines.push("#define UV1");
  70108. }
  70109. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  70110. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  70111. defines.push("#define UV2");
  70112. }
  70113. }
  70114. // Bones
  70115. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  70116. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  70117. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  70118. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  70119. defines.push("#define BonesPerMesh " + (mesh.skeleton ? (mesh.skeleton.bones.length + 1) : 0));
  70120. }
  70121. else {
  70122. defines.push("#define NUM_BONE_INFLUENCERS 0");
  70123. }
  70124. // Instances
  70125. if (useInstances) {
  70126. defines.push("#define INSTANCES");
  70127. attribs.push("world0");
  70128. attribs.push("world1");
  70129. attribs.push("world2");
  70130. attribs.push("world3");
  70131. }
  70132. // Get correct effect
  70133. var join = defines.join("\n");
  70134. if (this._cachedDefines !== join) {
  70135. this._cachedDefines = join;
  70136. this._volumetricLightScatteringPass = mesh.getScene().getEngine().createEffect({ vertexElement: "depth", fragmentElement: "volumetricLightScatteringPass" }, attribs, ["world", "mBones", "viewProjection", "diffuseMatrix"], ["diffuseSampler"], join);
  70137. }
  70138. return this._volumetricLightScatteringPass.isReady();
  70139. };
  70140. /**
  70141. * Sets the new light position for light scattering effect
  70142. * @param {BABYLON.Vector3} The new custom light position
  70143. */
  70144. VolumetricLightScatteringPostProcess.prototype.setCustomMeshPosition = function (position) {
  70145. this.customMeshPosition = position;
  70146. };
  70147. /**
  70148. * Returns the light position for light scattering effect
  70149. * @return {BABYLON.Vector3} The custom light position
  70150. */
  70151. VolumetricLightScatteringPostProcess.prototype.getCustomMeshPosition = function () {
  70152. return this.customMeshPosition;
  70153. };
  70154. /**
  70155. * Disposes the internal assets and detaches the post-process from the camera
  70156. */
  70157. VolumetricLightScatteringPostProcess.prototype.dispose = function (camera) {
  70158. var rttIndex = camera.getScene().customRenderTargets.indexOf(this._volumetricLightScatteringRTT);
  70159. if (rttIndex !== -1) {
  70160. camera.getScene().customRenderTargets.splice(rttIndex, 1);
  70161. }
  70162. this._volumetricLightScatteringRTT.dispose();
  70163. _super.prototype.dispose.call(this, camera);
  70164. };
  70165. /**
  70166. * Returns the render target texture used by the post-process
  70167. * @return {BABYLON.RenderTargetTexture} The render target texture used by the post-process
  70168. */
  70169. VolumetricLightScatteringPostProcess.prototype.getPass = function () {
  70170. return this._volumetricLightScatteringRTT;
  70171. };
  70172. // Private methods
  70173. VolumetricLightScatteringPostProcess.prototype._meshExcluded = function (mesh) {
  70174. if (this.excludedMeshes.length > 0 && this.excludedMeshes.indexOf(mesh) !== -1) {
  70175. return true;
  70176. }
  70177. return false;
  70178. };
  70179. VolumetricLightScatteringPostProcess.prototype._createPass = function (scene, ratio) {
  70180. var _this = this;
  70181. var engine = scene.getEngine();
  70182. this._volumetricLightScatteringRTT = new BABYLON.RenderTargetTexture("volumetricLightScatteringMap", { width: engine.getRenderWidth() * ratio, height: engine.getRenderHeight() * ratio }, scene, false, true, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  70183. this._volumetricLightScatteringRTT.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  70184. this._volumetricLightScatteringRTT.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  70185. this._volumetricLightScatteringRTT.renderList = null;
  70186. this._volumetricLightScatteringRTT.renderParticles = false;
  70187. this._volumetricLightScatteringRTT.ignoreCameraViewport = true;
  70188. var camera = this.getCamera();
  70189. if (camera) {
  70190. camera.customRenderTargets.push(this._volumetricLightScatteringRTT);
  70191. }
  70192. else {
  70193. scene.customRenderTargets.push(this._volumetricLightScatteringRTT);
  70194. }
  70195. // Custom render function for submeshes
  70196. var renderSubMesh = function (subMesh) {
  70197. var mesh = subMesh.getRenderingMesh();
  70198. if (_this._meshExcluded(mesh)) {
  70199. return;
  70200. }
  70201. var material = subMesh.getMaterial();
  70202. if (!material) {
  70203. return;
  70204. }
  70205. var scene = mesh.getScene();
  70206. var engine = scene.getEngine();
  70207. // Culling
  70208. engine.setState(material.backFaceCulling);
  70209. // Managing instances
  70210. var batch = mesh._getInstancesRenderList(subMesh._id);
  70211. if (batch.mustReturn) {
  70212. return;
  70213. }
  70214. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null);
  70215. if (_this._isReady(subMesh, hardwareInstancedRendering)) {
  70216. var effect = _this._volumetricLightScatteringPass;
  70217. if (mesh === _this.mesh) {
  70218. if (subMesh.effect) {
  70219. effect = subMesh.effect;
  70220. }
  70221. else {
  70222. effect = material.getEffect();
  70223. }
  70224. }
  70225. engine.enableEffect(effect);
  70226. mesh._bind(subMesh, effect, BABYLON.Material.TriangleFillMode);
  70227. if (mesh === _this.mesh) {
  70228. material.bind(mesh.getWorldMatrix(), mesh);
  70229. }
  70230. else {
  70231. _this._volumetricLightScatteringPass.setMatrix("viewProjection", scene.getTransformMatrix());
  70232. // Alpha test
  70233. if (material && material.needAlphaTesting()) {
  70234. var alphaTexture = material.getAlphaTestTexture();
  70235. _this._volumetricLightScatteringPass.setTexture("diffuseSampler", alphaTexture);
  70236. if (alphaTexture) {
  70237. _this._volumetricLightScatteringPass.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  70238. }
  70239. }
  70240. // Bones
  70241. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  70242. _this._volumetricLightScatteringPass.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  70243. }
  70244. }
  70245. // Draw
  70246. mesh._processRendering(subMesh, _this._volumetricLightScatteringPass, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return effect.setMatrix("world", world); });
  70247. }
  70248. };
  70249. // Render target texture callbacks
  70250. var savedSceneClearColor;
  70251. var sceneClearColor = new BABYLON.Color4(0.0, 0.0, 0.0, 1.0);
  70252. this._volumetricLightScatteringRTT.onBeforeRenderObservable.add(function () {
  70253. savedSceneClearColor = scene.clearColor;
  70254. scene.clearColor = sceneClearColor;
  70255. });
  70256. this._volumetricLightScatteringRTT.onAfterRenderObservable.add(function () {
  70257. scene.clearColor = savedSceneClearColor;
  70258. });
  70259. this._volumetricLightScatteringRTT.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes) {
  70260. var engine = scene.getEngine();
  70261. var index;
  70262. if (depthOnlySubMeshes.length) {
  70263. engine.setColorWrite(false);
  70264. for (index = 0; index < depthOnlySubMeshes.length; index++) {
  70265. renderSubMesh(depthOnlySubMeshes.data[index]);
  70266. }
  70267. engine.setColorWrite(true);
  70268. }
  70269. for (index = 0; index < opaqueSubMeshes.length; index++) {
  70270. renderSubMesh(opaqueSubMeshes.data[index]);
  70271. }
  70272. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  70273. renderSubMesh(alphaTestSubMeshes.data[index]);
  70274. }
  70275. if (transparentSubMeshes.length) {
  70276. // Sort sub meshes
  70277. for (index = 0; index < transparentSubMeshes.length; index++) {
  70278. var submesh = transparentSubMeshes.data[index];
  70279. var boundingInfo = submesh.getBoundingInfo();
  70280. if (boundingInfo && scene.activeCamera) {
  70281. submesh._alphaIndex = submesh.getMesh().alphaIndex;
  70282. submesh._distanceToCamera = boundingInfo.boundingSphere.centerWorld.subtract(scene.activeCamera.position).length();
  70283. }
  70284. }
  70285. var sortedArray = transparentSubMeshes.data.slice(0, transparentSubMeshes.length);
  70286. sortedArray.sort(function (a, b) {
  70287. // Alpha index first
  70288. if (a._alphaIndex > b._alphaIndex) {
  70289. return 1;
  70290. }
  70291. if (a._alphaIndex < b._alphaIndex) {
  70292. return -1;
  70293. }
  70294. // Then distance to camera
  70295. if (a._distanceToCamera < b._distanceToCamera) {
  70296. return 1;
  70297. }
  70298. if (a._distanceToCamera > b._distanceToCamera) {
  70299. return -1;
  70300. }
  70301. return 0;
  70302. });
  70303. // Render sub meshes
  70304. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  70305. for (index = 0; index < sortedArray.length; index++) {
  70306. renderSubMesh(sortedArray[index]);
  70307. }
  70308. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  70309. }
  70310. };
  70311. };
  70312. VolumetricLightScatteringPostProcess.prototype._updateMeshScreenCoordinates = function (scene) {
  70313. var transform = scene.getTransformMatrix();
  70314. var meshPosition;
  70315. if (this.useCustomMeshPosition) {
  70316. meshPosition = this.customMeshPosition;
  70317. }
  70318. else if (this.attachedNode) {
  70319. meshPosition = this.attachedNode.position;
  70320. }
  70321. else {
  70322. meshPosition = this.mesh.parent ? this.mesh.getAbsolutePosition() : this.mesh.position;
  70323. }
  70324. var pos = BABYLON.Vector3.Project(meshPosition, BABYLON.Matrix.Identity(), transform, this._viewPort);
  70325. this._screenCoordinates.x = pos.x / this._viewPort.width;
  70326. this._screenCoordinates.y = pos.y / this._viewPort.height;
  70327. if (this.invert)
  70328. this._screenCoordinates.y = 1.0 - this._screenCoordinates.y;
  70329. };
  70330. // Static methods
  70331. /**
  70332. * Creates a default mesh for the Volumeric Light Scattering post-process
  70333. * @param {string} The mesh name
  70334. * @param {BABYLON.Scene} The scene where to create the mesh
  70335. * @return {BABYLON.Mesh} the default mesh
  70336. */
  70337. VolumetricLightScatteringPostProcess.CreateDefaultMesh = function (name, scene) {
  70338. var mesh = BABYLON.Mesh.CreatePlane(name, 1, scene);
  70339. mesh.billboardMode = BABYLON.AbstractMesh.BILLBOARDMODE_ALL;
  70340. var material = new BABYLON.StandardMaterial(name + "Material", scene);
  70341. material.emissiveColor = new BABYLON.Color3(1, 1, 1);
  70342. mesh.material = material;
  70343. return mesh;
  70344. };
  70345. __decorate([
  70346. BABYLON.serializeAsVector3()
  70347. ], VolumetricLightScatteringPostProcess.prototype, "customMeshPosition", void 0);
  70348. __decorate([
  70349. BABYLON.serialize()
  70350. ], VolumetricLightScatteringPostProcess.prototype, "useCustomMeshPosition", void 0);
  70351. __decorate([
  70352. BABYLON.serialize()
  70353. ], VolumetricLightScatteringPostProcess.prototype, "invert", void 0);
  70354. __decorate([
  70355. BABYLON.serializeAsMeshReference()
  70356. ], VolumetricLightScatteringPostProcess.prototype, "mesh", void 0);
  70357. __decorate([
  70358. BABYLON.serialize()
  70359. ], VolumetricLightScatteringPostProcess.prototype, "excludedMeshes", void 0);
  70360. __decorate([
  70361. BABYLON.serialize()
  70362. ], VolumetricLightScatteringPostProcess.prototype, "exposure", void 0);
  70363. __decorate([
  70364. BABYLON.serialize()
  70365. ], VolumetricLightScatteringPostProcess.prototype, "decay", void 0);
  70366. __decorate([
  70367. BABYLON.serialize()
  70368. ], VolumetricLightScatteringPostProcess.prototype, "weight", void 0);
  70369. __decorate([
  70370. BABYLON.serialize()
  70371. ], VolumetricLightScatteringPostProcess.prototype, "density", void 0);
  70372. return VolumetricLightScatteringPostProcess;
  70373. }(BABYLON.PostProcess));
  70374. BABYLON.VolumetricLightScatteringPostProcess = VolumetricLightScatteringPostProcess;
  70375. })(BABYLON || (BABYLON = {}));
  70376. //# sourceMappingURL=babylon.volumetricLightScatteringPostProcess.js.map
  70377. //
  70378. // This post-process allows the modification of rendered colors by using
  70379. // a 'look-up table' (LUT). This effect is also called Color Grading.
  70380. //
  70381. // The object needs to be provided an url to a texture containing the color
  70382. // look-up table: the texture must be 256 pixels wide and 16 pixels high.
  70383. // Use an image editing software to tweak the LUT to match your needs.
  70384. //
  70385. // For an example of a color LUT, see here:
  70386. // http://udn.epicgames.com/Three/rsrc/Three/ColorGrading/RGBTable16x1.png
  70387. // For explanations on color grading, see here:
  70388. // http://udn.epicgames.com/Three/ColorGrading.html
  70389. //
  70390. var BABYLON;
  70391. (function (BABYLON) {
  70392. var ColorCorrectionPostProcess = /** @class */ (function (_super) {
  70393. __extends(ColorCorrectionPostProcess, _super);
  70394. function ColorCorrectionPostProcess(name, colorTableUrl, options, camera, samplingMode, engine, reusable) {
  70395. var _this = _super.call(this, name, 'colorCorrection', null, ['colorTable'], options, camera, samplingMode, engine, reusable) || this;
  70396. _this._colorTableTexture = new BABYLON.Texture(colorTableUrl, camera.getScene(), true, false, BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  70397. _this._colorTableTexture.anisotropicFilteringLevel = 1;
  70398. _this._colorTableTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  70399. _this._colorTableTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  70400. _this.onApply = function (effect) {
  70401. effect.setTexture("colorTable", _this._colorTableTexture);
  70402. };
  70403. return _this;
  70404. }
  70405. return ColorCorrectionPostProcess;
  70406. }(BABYLON.PostProcess));
  70407. BABYLON.ColorCorrectionPostProcess = ColorCorrectionPostProcess;
  70408. })(BABYLON || (BABYLON = {}));
  70409. //# sourceMappingURL=babylon.colorCorrectionPostProcess.js.map
  70410. var BABYLON;
  70411. (function (BABYLON) {
  70412. var TonemappingOperator;
  70413. (function (TonemappingOperator) {
  70414. TonemappingOperator[TonemappingOperator["Hable"] = 0] = "Hable";
  70415. TonemappingOperator[TonemappingOperator["Reinhard"] = 1] = "Reinhard";
  70416. TonemappingOperator[TonemappingOperator["HejiDawson"] = 2] = "HejiDawson";
  70417. TonemappingOperator[TonemappingOperator["Photographic"] = 3] = "Photographic";
  70418. })(TonemappingOperator = BABYLON.TonemappingOperator || (BABYLON.TonemappingOperator = {}));
  70419. ;
  70420. var TonemapPostProcess = /** @class */ (function (_super) {
  70421. __extends(TonemapPostProcess, _super);
  70422. function TonemapPostProcess(name, _operator, exposureAdjustment, camera, samplingMode, engine, textureFormat) {
  70423. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  70424. if (textureFormat === void 0) { textureFormat = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  70425. var _this = _super.call(this, name, "tonemap", ["_ExposureAdjustment"], null, 1.0, camera, samplingMode, engine, true, null, textureFormat) || this;
  70426. _this._operator = _operator;
  70427. _this.exposureAdjustment = exposureAdjustment;
  70428. var defines = "#define ";
  70429. if (_this._operator === TonemappingOperator.Hable)
  70430. defines += "HABLE_TONEMAPPING";
  70431. else if (_this._operator === TonemappingOperator.Reinhard)
  70432. defines += "REINHARD_TONEMAPPING";
  70433. else if (_this._operator === TonemappingOperator.HejiDawson)
  70434. defines += "OPTIMIZED_HEJIDAWSON_TONEMAPPING";
  70435. else if (_this._operator === TonemappingOperator.Photographic)
  70436. defines += "PHOTOGRAPHIC_TONEMAPPING";
  70437. //sadly a second call to create the effect.
  70438. _this.updateEffect(defines);
  70439. _this.onApply = function (effect) {
  70440. effect.setFloat("_ExposureAdjustment", _this.exposureAdjustment);
  70441. };
  70442. return _this;
  70443. }
  70444. return TonemapPostProcess;
  70445. }(BABYLON.PostProcess));
  70446. BABYLON.TonemapPostProcess = TonemapPostProcess;
  70447. })(BABYLON || (BABYLON = {}));
  70448. //# sourceMappingURL=babylon.tonemapPostProcess.js.map
  70449. var BABYLON;
  70450. (function (BABYLON) {
  70451. var DisplayPassPostProcess = /** @class */ (function (_super) {
  70452. __extends(DisplayPassPostProcess, _super);
  70453. function DisplayPassPostProcess(name, options, camera, samplingMode, engine, reusable) {
  70454. return _super.call(this, name, "displayPass", ["passSampler"], ["passSampler"], options, camera, samplingMode, engine, reusable) || this;
  70455. }
  70456. return DisplayPassPostProcess;
  70457. }(BABYLON.PostProcess));
  70458. BABYLON.DisplayPassPostProcess = DisplayPassPostProcess;
  70459. })(BABYLON || (BABYLON = {}));
  70460. //# sourceMappingURL=babylon.displayPassPostProcess.js.map
  70461. var BABYLON;
  70462. (function (BABYLON) {
  70463. var HighlightsPostProcess = /** @class */ (function (_super) {
  70464. __extends(HighlightsPostProcess, _super);
  70465. function HighlightsPostProcess(name, options, camera, samplingMode, engine, reusable, textureType) {
  70466. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  70467. return _super.call(this, name, "highlights", null, null, options, camera, samplingMode, engine, reusable, null, textureType) || this;
  70468. }
  70469. return HighlightsPostProcess;
  70470. }(BABYLON.PostProcess));
  70471. BABYLON.HighlightsPostProcess = HighlightsPostProcess;
  70472. })(BABYLON || (BABYLON = {}));
  70473. //# sourceMappingURL=babylon.highlightsPostProcess.js.map
  70474. var BABYLON;
  70475. (function (BABYLON) {
  70476. var ImageProcessingPostProcess = /** @class */ (function (_super) {
  70477. __extends(ImageProcessingPostProcess, _super);
  70478. function ImageProcessingPostProcess(name, options, camera, samplingMode, engine, reusable, textureType, imageProcessingConfiguration) {
  70479. if (camera === void 0) { camera = null; }
  70480. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  70481. var _this = _super.call(this, name, "imageProcessing", [], [], options, camera, samplingMode, engine, reusable, null, textureType, "postprocess", null, true) || this;
  70482. _this._fromLinearSpace = true;
  70483. /**
  70484. * Defines cache preventing GC.
  70485. */
  70486. _this._defines = {
  70487. IMAGEPROCESSING: false,
  70488. VIGNETTE: false,
  70489. VIGNETTEBLENDMODEMULTIPLY: false,
  70490. VIGNETTEBLENDMODEOPAQUE: false,
  70491. TONEMAPPING: false,
  70492. CONTRAST: false,
  70493. COLORCURVES: false,
  70494. COLORGRADING: false,
  70495. COLORGRADING3D: false,
  70496. FROMLINEARSPACE: false,
  70497. SAMPLER3DGREENDEPTH: false,
  70498. SAMPLER3DBGRMAP: false,
  70499. IMAGEPROCESSINGPOSTPROCESS: false,
  70500. EXPOSURE: false,
  70501. GRAIN: false,
  70502. };
  70503. // Setup the configuration as forced by the constructor. This would then not force the
  70504. // scene materials output in linear space and let untouched the default forward pass.
  70505. if (imageProcessingConfiguration) {
  70506. imageProcessingConfiguration.applyByPostProcess = true;
  70507. _this._attachImageProcessingConfiguration(imageProcessingConfiguration, true);
  70508. // This will cause the shader to be compiled
  70509. _this.fromLinearSpace = false;
  70510. }
  70511. else {
  70512. _this._attachImageProcessingConfiguration(null, true);
  70513. _this.imageProcessingConfiguration.applyByPostProcess = true;
  70514. }
  70515. _this.onApply = function (effect) {
  70516. _this.imageProcessingConfiguration.bind(effect, _this.aspectRatio);
  70517. };
  70518. return _this;
  70519. }
  70520. Object.defineProperty(ImageProcessingPostProcess.prototype, "imageProcessingConfiguration", {
  70521. /**
  70522. * Gets the image processing configuration used either in this material.
  70523. */
  70524. get: function () {
  70525. return this._imageProcessingConfiguration;
  70526. },
  70527. /**
  70528. * Sets the Default image processing configuration used either in the this material.
  70529. *
  70530. * If sets to null, the scene one is in use.
  70531. */
  70532. set: function (value) {
  70533. this._attachImageProcessingConfiguration(value);
  70534. },
  70535. enumerable: true,
  70536. configurable: true
  70537. });
  70538. /**
  70539. * Attaches a new image processing configuration to the PBR Material.
  70540. * @param configuration
  70541. */
  70542. ImageProcessingPostProcess.prototype._attachImageProcessingConfiguration = function (configuration, doNotBuild) {
  70543. var _this = this;
  70544. if (doNotBuild === void 0) { doNotBuild = false; }
  70545. if (configuration === this._imageProcessingConfiguration) {
  70546. return;
  70547. }
  70548. // Detaches observer.
  70549. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  70550. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  70551. }
  70552. // Pick the scene configuration if needed.
  70553. if (!configuration) {
  70554. var scene = null;
  70555. var engine = this.getEngine();
  70556. var camera = this.getCamera();
  70557. if (camera) {
  70558. scene = camera.getScene();
  70559. }
  70560. else if (engine && engine.scenes) {
  70561. var scenes = engine.scenes;
  70562. scene = scenes[scenes.length - 1];
  70563. }
  70564. else {
  70565. scene = BABYLON.Engine.LastCreatedScene;
  70566. }
  70567. this._imageProcessingConfiguration = scene.imageProcessingConfiguration;
  70568. }
  70569. else {
  70570. this._imageProcessingConfiguration = configuration;
  70571. }
  70572. // Attaches observer.
  70573. this._imageProcessingObserver = this._imageProcessingConfiguration.onUpdateParameters.add(function (conf) {
  70574. _this._updateParameters();
  70575. });
  70576. // Ensure the effect will be rebuilt.
  70577. if (!doNotBuild) {
  70578. this._updateParameters();
  70579. }
  70580. };
  70581. Object.defineProperty(ImageProcessingPostProcess.prototype, "colorCurves", {
  70582. /**
  70583. * Gets Color curves setup used in the effect if colorCurvesEnabled is set to true .
  70584. */
  70585. get: function () {
  70586. return this.imageProcessingConfiguration.colorCurves;
  70587. },
  70588. /**
  70589. * Sets Color curves setup used in the effect if colorCurvesEnabled is set to true .
  70590. */
  70591. set: function (value) {
  70592. this.imageProcessingConfiguration.colorCurves = value;
  70593. },
  70594. enumerable: true,
  70595. configurable: true
  70596. });
  70597. Object.defineProperty(ImageProcessingPostProcess.prototype, "colorCurvesEnabled", {
  70598. /**
  70599. * Gets wether the color curves effect is enabled.
  70600. */
  70601. get: function () {
  70602. return this.imageProcessingConfiguration.colorCurvesEnabled;
  70603. },
  70604. /**
  70605. * Sets wether the color curves effect is enabled.
  70606. */
  70607. set: function (value) {
  70608. this.imageProcessingConfiguration.colorCurvesEnabled = value;
  70609. },
  70610. enumerable: true,
  70611. configurable: true
  70612. });
  70613. Object.defineProperty(ImageProcessingPostProcess.prototype, "colorGradingTexture", {
  70614. /**
  70615. * Gets Color grading LUT texture used in the effect if colorGradingEnabled is set to true.
  70616. */
  70617. get: function () {
  70618. return this.imageProcessingConfiguration.colorGradingTexture;
  70619. },
  70620. /**
  70621. * Sets Color grading LUT texture used in the effect if colorGradingEnabled is set to true.
  70622. */
  70623. set: function (value) {
  70624. this.imageProcessingConfiguration.colorGradingTexture = value;
  70625. },
  70626. enumerable: true,
  70627. configurable: true
  70628. });
  70629. Object.defineProperty(ImageProcessingPostProcess.prototype, "colorGradingEnabled", {
  70630. /**
  70631. * Gets wether the color grading effect is enabled.
  70632. */
  70633. get: function () {
  70634. return this.imageProcessingConfiguration.colorGradingEnabled;
  70635. },
  70636. /**
  70637. * Gets wether the color grading effect is enabled.
  70638. */
  70639. set: function (value) {
  70640. this.imageProcessingConfiguration.colorGradingEnabled = value;
  70641. },
  70642. enumerable: true,
  70643. configurable: true
  70644. });
  70645. Object.defineProperty(ImageProcessingPostProcess.prototype, "exposure", {
  70646. /**
  70647. * Gets exposure used in the effect.
  70648. */
  70649. get: function () {
  70650. return this.imageProcessingConfiguration.exposure;
  70651. },
  70652. /**
  70653. * Sets exposure used in the effect.
  70654. */
  70655. set: function (value) {
  70656. this.imageProcessingConfiguration.exposure = value;
  70657. },
  70658. enumerable: true,
  70659. configurable: true
  70660. });
  70661. Object.defineProperty(ImageProcessingPostProcess.prototype, "toneMappingEnabled", {
  70662. /**
  70663. * Gets wether tonemapping is enabled or not.
  70664. */
  70665. get: function () {
  70666. return this._imageProcessingConfiguration.toneMappingEnabled;
  70667. },
  70668. /**
  70669. * Sets wether tonemapping is enabled or not
  70670. */
  70671. set: function (value) {
  70672. this._imageProcessingConfiguration.toneMappingEnabled = value;
  70673. },
  70674. enumerable: true,
  70675. configurable: true
  70676. });
  70677. ;
  70678. ;
  70679. Object.defineProperty(ImageProcessingPostProcess.prototype, "contrast", {
  70680. /**
  70681. * Gets contrast used in the effect.
  70682. */
  70683. get: function () {
  70684. return this.imageProcessingConfiguration.contrast;
  70685. },
  70686. /**
  70687. * Sets contrast used in the effect.
  70688. */
  70689. set: function (value) {
  70690. this.imageProcessingConfiguration.contrast = value;
  70691. },
  70692. enumerable: true,
  70693. configurable: true
  70694. });
  70695. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteStretch", {
  70696. /**
  70697. * Gets Vignette stretch size.
  70698. */
  70699. get: function () {
  70700. return this.imageProcessingConfiguration.vignetteStretch;
  70701. },
  70702. /**
  70703. * Sets Vignette stretch size.
  70704. */
  70705. set: function (value) {
  70706. this.imageProcessingConfiguration.vignetteStretch = value;
  70707. },
  70708. enumerable: true,
  70709. configurable: true
  70710. });
  70711. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteCentreX", {
  70712. /**
  70713. * Gets Vignette centre X Offset.
  70714. */
  70715. get: function () {
  70716. return this.imageProcessingConfiguration.vignetteCentreX;
  70717. },
  70718. /**
  70719. * Sets Vignette centre X Offset.
  70720. */
  70721. set: function (value) {
  70722. this.imageProcessingConfiguration.vignetteCentreX = value;
  70723. },
  70724. enumerable: true,
  70725. configurable: true
  70726. });
  70727. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteCentreY", {
  70728. /**
  70729. * Gets Vignette centre Y Offset.
  70730. */
  70731. get: function () {
  70732. return this.imageProcessingConfiguration.vignetteCentreY;
  70733. },
  70734. /**
  70735. * Sets Vignette centre Y Offset.
  70736. */
  70737. set: function (value) {
  70738. this.imageProcessingConfiguration.vignetteCentreY = value;
  70739. },
  70740. enumerable: true,
  70741. configurable: true
  70742. });
  70743. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteWeight", {
  70744. /**
  70745. * Gets Vignette weight or intensity of the vignette effect.
  70746. */
  70747. get: function () {
  70748. return this.imageProcessingConfiguration.vignetteWeight;
  70749. },
  70750. /**
  70751. * Sets Vignette weight or intensity of the vignette effect.
  70752. */
  70753. set: function (value) {
  70754. this.imageProcessingConfiguration.vignetteWeight = value;
  70755. },
  70756. enumerable: true,
  70757. configurable: true
  70758. });
  70759. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteColor", {
  70760. /**
  70761. * Gets Color of the vignette applied on the screen through the chosen blend mode (vignetteBlendMode)
  70762. * if vignetteEnabled is set to true.
  70763. */
  70764. get: function () {
  70765. return this.imageProcessingConfiguration.vignetteColor;
  70766. },
  70767. /**
  70768. * Sets Color of the vignette applied on the screen through the chosen blend mode (vignetteBlendMode)
  70769. * if vignetteEnabled is set to true.
  70770. */
  70771. set: function (value) {
  70772. this.imageProcessingConfiguration.vignetteColor = value;
  70773. },
  70774. enumerable: true,
  70775. configurable: true
  70776. });
  70777. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteCameraFov", {
  70778. /**
  70779. * Gets Camera field of view used by the Vignette effect.
  70780. */
  70781. get: function () {
  70782. return this.imageProcessingConfiguration.vignetteCameraFov;
  70783. },
  70784. /**
  70785. * Sets Camera field of view used by the Vignette effect.
  70786. */
  70787. set: function (value) {
  70788. this.imageProcessingConfiguration.vignetteCameraFov = value;
  70789. },
  70790. enumerable: true,
  70791. configurable: true
  70792. });
  70793. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteBlendMode", {
  70794. /**
  70795. * Gets the vignette blend mode allowing different kind of effect.
  70796. */
  70797. get: function () {
  70798. return this.imageProcessingConfiguration.vignetteBlendMode;
  70799. },
  70800. /**
  70801. * Sets the vignette blend mode allowing different kind of effect.
  70802. */
  70803. set: function (value) {
  70804. this.imageProcessingConfiguration.vignetteBlendMode = value;
  70805. },
  70806. enumerable: true,
  70807. configurable: true
  70808. });
  70809. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteEnabled", {
  70810. /**
  70811. * Gets wether the vignette effect is enabled.
  70812. */
  70813. get: function () {
  70814. return this.imageProcessingConfiguration.vignetteEnabled;
  70815. },
  70816. /**
  70817. * Sets wether the vignette effect is enabled.
  70818. */
  70819. set: function (value) {
  70820. this.imageProcessingConfiguration.vignetteEnabled = value;
  70821. },
  70822. enumerable: true,
  70823. configurable: true
  70824. });
  70825. Object.defineProperty(ImageProcessingPostProcess.prototype, "grainEnabled", {
  70826. /**
  70827. * Gets wether the grain effect is enabled.
  70828. */
  70829. get: function () {
  70830. return this.imageProcessingConfiguration.grainEnabled;
  70831. },
  70832. /**
  70833. * Sets wether the grain effect is enabled.
  70834. */
  70835. set: function (value) {
  70836. this.imageProcessingConfiguration.grainEnabled = value;
  70837. },
  70838. enumerable: true,
  70839. configurable: true
  70840. });
  70841. Object.defineProperty(ImageProcessingPostProcess.prototype, "grainIntensity", {
  70842. /**
  70843. * Gets the grain effect's intensity.
  70844. */
  70845. get: function () {
  70846. return this.imageProcessingConfiguration.grainIntensity;
  70847. },
  70848. /**
  70849. * Sets the grain effect's intensity.
  70850. */
  70851. set: function (value) {
  70852. this.imageProcessingConfiguration.grainIntensity = value;
  70853. },
  70854. enumerable: true,
  70855. configurable: true
  70856. });
  70857. Object.defineProperty(ImageProcessingPostProcess.prototype, "grainAnimated", {
  70858. /**
  70859. * Gets wether the grain effect is animated.
  70860. */
  70861. get: function () {
  70862. return this.imageProcessingConfiguration.grainAnimated;
  70863. },
  70864. /**
  70865. * Sets wether the grain effect is animated.
  70866. */
  70867. set: function (value) {
  70868. this.imageProcessingConfiguration.grainAnimated = value;
  70869. },
  70870. enumerable: true,
  70871. configurable: true
  70872. });
  70873. Object.defineProperty(ImageProcessingPostProcess.prototype, "fromLinearSpace", {
  70874. /**
  70875. * Gets wether the input of the processing is in Gamma or Linear Space.
  70876. */
  70877. get: function () {
  70878. return this._fromLinearSpace;
  70879. },
  70880. /**
  70881. * Sets wether the input of the processing is in Gamma or Linear Space.
  70882. */
  70883. set: function (value) {
  70884. if (this._fromLinearSpace === value) {
  70885. return;
  70886. }
  70887. this._fromLinearSpace = value;
  70888. this._updateParameters();
  70889. },
  70890. enumerable: true,
  70891. configurable: true
  70892. });
  70893. ImageProcessingPostProcess.prototype.getClassName = function () {
  70894. return "ImageProcessingPostProcess";
  70895. };
  70896. ImageProcessingPostProcess.prototype._updateParameters = function () {
  70897. this._defines.FROMLINEARSPACE = this._fromLinearSpace;
  70898. this.imageProcessingConfiguration.prepareDefines(this._defines, true);
  70899. var defines = "";
  70900. for (var define in this._defines) {
  70901. if (this._defines[define]) {
  70902. defines += "#define " + define + ";\r\n";
  70903. }
  70904. }
  70905. var samplers = ["textureSampler"];
  70906. BABYLON.ImageProcessingConfiguration.PrepareSamplers(samplers, this._defines);
  70907. var uniforms = ["scale"];
  70908. BABYLON.ImageProcessingConfiguration.PrepareUniforms(uniforms, this._defines);
  70909. this.updateEffect(defines, uniforms, samplers);
  70910. };
  70911. ImageProcessingPostProcess.prototype.dispose = function (camera) {
  70912. _super.prototype.dispose.call(this, camera);
  70913. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  70914. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  70915. }
  70916. this.imageProcessingConfiguration.applyByPostProcess = false;
  70917. };
  70918. __decorate([
  70919. BABYLON.serialize()
  70920. ], ImageProcessingPostProcess.prototype, "_fromLinearSpace", void 0);
  70921. return ImageProcessingPostProcess;
  70922. }(BABYLON.PostProcess));
  70923. BABYLON.ImageProcessingPostProcess = ImageProcessingPostProcess;
  70924. })(BABYLON || (BABYLON = {}));
  70925. //# sourceMappingURL=babylon.imageProcessingPostProcess.js.map
  70926. var BABYLON;
  70927. (function (BABYLON) {
  70928. var Bone = /** @class */ (function (_super) {
  70929. __extends(Bone, _super);
  70930. function Bone(name, skeleton, parentBone, localMatrix, restPose, baseMatrix, index) {
  70931. if (parentBone === void 0) { parentBone = null; }
  70932. if (localMatrix === void 0) { localMatrix = null; }
  70933. if (restPose === void 0) { restPose = null; }
  70934. if (baseMatrix === void 0) { baseMatrix = null; }
  70935. if (index === void 0) { index = null; }
  70936. var _this = _super.call(this, name, skeleton.getScene()) || this;
  70937. _this.name = name;
  70938. _this.children = new Array();
  70939. _this.animations = new Array();
  70940. // Set this value to map this bone to a different index in the transform matrices.
  70941. // Set this value to -1 to exclude the bone from the transform matrices.
  70942. _this._index = null;
  70943. _this._worldTransform = new BABYLON.Matrix();
  70944. _this._absoluteTransform = new BABYLON.Matrix();
  70945. _this._invertedAbsoluteTransform = new BABYLON.Matrix();
  70946. _this._scaleMatrix = BABYLON.Matrix.Identity();
  70947. _this._scaleVector = BABYLON.Vector3.One();
  70948. _this._negateScaleChildren = BABYLON.Vector3.One();
  70949. _this._scalingDeterminant = 1;
  70950. _this._skeleton = skeleton;
  70951. _this._localMatrix = localMatrix ? localMatrix : BABYLON.Matrix.Identity();
  70952. _this._restPose = restPose ? restPose : _this._localMatrix.clone();
  70953. _this._baseMatrix = baseMatrix ? baseMatrix : _this._localMatrix.clone();
  70954. _this._index = index;
  70955. skeleton.bones.push(_this);
  70956. _this.setParent(parentBone, false);
  70957. _this._updateDifferenceMatrix();
  70958. return _this;
  70959. }
  70960. Object.defineProperty(Bone.prototype, "_matrix", {
  70961. get: function () {
  70962. return this._localMatrix;
  70963. },
  70964. set: function (val) {
  70965. if (this._localMatrix) {
  70966. this._localMatrix.copyFrom(val);
  70967. }
  70968. else {
  70969. this._localMatrix = val;
  70970. }
  70971. },
  70972. enumerable: true,
  70973. configurable: true
  70974. });
  70975. // Members
  70976. Bone.prototype.getSkeleton = function () {
  70977. return this._skeleton;
  70978. };
  70979. Bone.prototype.getParent = function () {
  70980. return this._parent;
  70981. };
  70982. Bone.prototype.setParent = function (parent, updateDifferenceMatrix) {
  70983. if (updateDifferenceMatrix === void 0) { updateDifferenceMatrix = true; }
  70984. if (this._parent === parent) {
  70985. return;
  70986. }
  70987. if (this._parent) {
  70988. var index = this._parent.children.indexOf(this);
  70989. if (index !== -1) {
  70990. this._parent.children.splice(index, 1);
  70991. }
  70992. }
  70993. this._parent = parent;
  70994. if (this._parent) {
  70995. this._parent.children.push(this);
  70996. }
  70997. if (updateDifferenceMatrix) {
  70998. this._updateDifferenceMatrix();
  70999. }
  71000. };
  71001. Bone.prototype.getLocalMatrix = function () {
  71002. return this._localMatrix;
  71003. };
  71004. Bone.prototype.getBaseMatrix = function () {
  71005. return this._baseMatrix;
  71006. };
  71007. Bone.prototype.getRestPose = function () {
  71008. return this._restPose;
  71009. };
  71010. Bone.prototype.returnToRest = function () {
  71011. this.updateMatrix(this._restPose.clone());
  71012. };
  71013. Bone.prototype.getWorldMatrix = function () {
  71014. return this._worldTransform;
  71015. };
  71016. Bone.prototype.getInvertedAbsoluteTransform = function () {
  71017. return this._invertedAbsoluteTransform;
  71018. };
  71019. Bone.prototype.getAbsoluteTransform = function () {
  71020. return this._absoluteTransform;
  71021. };
  71022. Object.defineProperty(Bone.prototype, "position", {
  71023. // Properties (matches AbstractMesh properties)
  71024. get: function () {
  71025. return this.getPosition();
  71026. },
  71027. set: function (newPosition) {
  71028. this.setPosition(newPosition);
  71029. },
  71030. enumerable: true,
  71031. configurable: true
  71032. });
  71033. Object.defineProperty(Bone.prototype, "rotation", {
  71034. get: function () {
  71035. return this.getRotation();
  71036. },
  71037. set: function (newRotation) {
  71038. this.setRotation(newRotation);
  71039. },
  71040. enumerable: true,
  71041. configurable: true
  71042. });
  71043. Object.defineProperty(Bone.prototype, "rotationQuaternion", {
  71044. get: function () {
  71045. return this.getRotationQuaternion();
  71046. },
  71047. set: function (newRotation) {
  71048. this.setRotationQuaternion(newRotation);
  71049. },
  71050. enumerable: true,
  71051. configurable: true
  71052. });
  71053. Object.defineProperty(Bone.prototype, "scaling", {
  71054. get: function () {
  71055. return this.getScale();
  71056. },
  71057. set: function (newScaling) {
  71058. this.setScale(newScaling.x, newScaling.y, newScaling.z);
  71059. },
  71060. enumerable: true,
  71061. configurable: true
  71062. });
  71063. Object.defineProperty(Bone.prototype, "animationPropertiesOverride", {
  71064. /**
  71065. * Gets the animation properties override
  71066. */
  71067. get: function () {
  71068. return this._skeleton.animationPropertiesOverride;
  71069. },
  71070. enumerable: true,
  71071. configurable: true
  71072. });
  71073. // Methods
  71074. Bone.prototype.updateMatrix = function (matrix, updateDifferenceMatrix) {
  71075. if (updateDifferenceMatrix === void 0) { updateDifferenceMatrix = true; }
  71076. this._baseMatrix = matrix.clone();
  71077. this._localMatrix = matrix.clone();
  71078. this._skeleton._markAsDirty();
  71079. if (updateDifferenceMatrix) {
  71080. this._updateDifferenceMatrix();
  71081. }
  71082. };
  71083. Bone.prototype._updateDifferenceMatrix = function (rootMatrix) {
  71084. if (!rootMatrix) {
  71085. rootMatrix = this._baseMatrix;
  71086. }
  71087. if (this._parent) {
  71088. rootMatrix.multiplyToRef(this._parent._absoluteTransform, this._absoluteTransform);
  71089. }
  71090. else {
  71091. this._absoluteTransform.copyFrom(rootMatrix);
  71092. }
  71093. this._absoluteTransform.invertToRef(this._invertedAbsoluteTransform);
  71094. for (var index = 0; index < this.children.length; index++) {
  71095. this.children[index]._updateDifferenceMatrix();
  71096. }
  71097. this._scalingDeterminant = (this._absoluteTransform.determinant() < 0 ? -1 : 1);
  71098. };
  71099. Bone.prototype.markAsDirty = function () {
  71100. this._currentRenderId++;
  71101. this._skeleton._markAsDirty();
  71102. };
  71103. Bone.prototype.copyAnimationRange = function (source, rangeName, frameOffset, rescaleAsRequired, skelDimensionsRatio) {
  71104. if (rescaleAsRequired === void 0) { rescaleAsRequired = false; }
  71105. if (skelDimensionsRatio === void 0) { skelDimensionsRatio = null; }
  71106. // all animation may be coming from a library skeleton, so may need to create animation
  71107. if (this.animations.length === 0) {
  71108. this.animations.push(new BABYLON.Animation(this.name, "_matrix", source.animations[0].framePerSecond, BABYLON.Animation.ANIMATIONTYPE_MATRIX, 0));
  71109. this.animations[0].setKeys([]);
  71110. }
  71111. // get animation info / verify there is such a range from the source bone
  71112. var sourceRange = source.animations[0].getRange(rangeName);
  71113. if (!sourceRange) {
  71114. return false;
  71115. }
  71116. var from = sourceRange.from;
  71117. var to = sourceRange.to;
  71118. var sourceKeys = source.animations[0].getKeys();
  71119. // rescaling prep
  71120. var sourceBoneLength = source.length;
  71121. var sourceParent = source.getParent();
  71122. var parent = this.getParent();
  71123. var parentScalingReqd = rescaleAsRequired && sourceParent && sourceBoneLength && this.length && sourceBoneLength !== this.length;
  71124. var parentRatio = parentScalingReqd && parent && sourceParent ? parent.length / sourceParent.length : 1;
  71125. var dimensionsScalingReqd = rescaleAsRequired && !parent && skelDimensionsRatio && (skelDimensionsRatio.x !== 1 || skelDimensionsRatio.y !== 1 || skelDimensionsRatio.z !== 1);
  71126. var destKeys = this.animations[0].getKeys();
  71127. // loop vars declaration
  71128. var orig;
  71129. var origTranslation;
  71130. var mat;
  71131. for (var key = 0, nKeys = sourceKeys.length; key < nKeys; key++) {
  71132. orig = sourceKeys[key];
  71133. if (orig.frame >= from && orig.frame <= to) {
  71134. if (rescaleAsRequired) {
  71135. mat = orig.value.clone();
  71136. // scale based on parent ratio, when bone has parent
  71137. if (parentScalingReqd) {
  71138. origTranslation = mat.getTranslation();
  71139. mat.setTranslation(origTranslation.scaleInPlace(parentRatio));
  71140. // scale based on skeleton dimension ratio when root bone, and value is passed
  71141. }
  71142. else if (dimensionsScalingReqd && skelDimensionsRatio) {
  71143. origTranslation = mat.getTranslation();
  71144. mat.setTranslation(origTranslation.multiplyInPlace(skelDimensionsRatio));
  71145. // use original when root bone, and no data for skelDimensionsRatio
  71146. }
  71147. else {
  71148. mat = orig.value;
  71149. }
  71150. }
  71151. else {
  71152. mat = orig.value;
  71153. }
  71154. destKeys.push({ frame: orig.frame + frameOffset, value: mat });
  71155. }
  71156. }
  71157. this.animations[0].createRange(rangeName, from + frameOffset, to + frameOffset);
  71158. return true;
  71159. };
  71160. /**
  71161. * Translate the bone in local or world space.
  71162. * @param vec The amount to translate the bone.
  71163. * @param space The space that the translation is in.
  71164. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  71165. */
  71166. Bone.prototype.translate = function (vec, space, mesh) {
  71167. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  71168. var lm = this.getLocalMatrix();
  71169. if (space == BABYLON.Space.LOCAL) {
  71170. lm.m[12] += vec.x;
  71171. lm.m[13] += vec.y;
  71172. lm.m[14] += vec.z;
  71173. }
  71174. else {
  71175. var wm = null;
  71176. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  71177. if (mesh) {
  71178. wm = mesh.getWorldMatrix();
  71179. }
  71180. this._skeleton.computeAbsoluteTransforms();
  71181. var tmat = Bone._tmpMats[0];
  71182. var tvec = Bone._tmpVecs[0];
  71183. if (this._parent) {
  71184. if (mesh && wm) {
  71185. tmat.copyFrom(this._parent.getAbsoluteTransform());
  71186. tmat.multiplyToRef(wm, tmat);
  71187. }
  71188. else {
  71189. tmat.copyFrom(this._parent.getAbsoluteTransform());
  71190. }
  71191. }
  71192. tmat.m[12] = 0;
  71193. tmat.m[13] = 0;
  71194. tmat.m[14] = 0;
  71195. tmat.invert();
  71196. BABYLON.Vector3.TransformCoordinatesToRef(vec, tmat, tvec);
  71197. lm.m[12] += tvec.x;
  71198. lm.m[13] += tvec.y;
  71199. lm.m[14] += tvec.z;
  71200. }
  71201. this.markAsDirty();
  71202. };
  71203. /**
  71204. * Set the postion of the bone in local or world space.
  71205. * @param position The position to set the bone.
  71206. * @param space The space that the position is in.
  71207. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  71208. */
  71209. Bone.prototype.setPosition = function (position, space, mesh) {
  71210. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  71211. var lm = this.getLocalMatrix();
  71212. if (space == BABYLON.Space.LOCAL) {
  71213. lm.m[12] = position.x;
  71214. lm.m[13] = position.y;
  71215. lm.m[14] = position.z;
  71216. }
  71217. else {
  71218. var wm = null;
  71219. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  71220. if (mesh) {
  71221. wm = mesh.getWorldMatrix();
  71222. }
  71223. this._skeleton.computeAbsoluteTransforms();
  71224. var tmat = Bone._tmpMats[0];
  71225. var vec = Bone._tmpVecs[0];
  71226. if (this._parent) {
  71227. if (mesh && wm) {
  71228. tmat.copyFrom(this._parent.getAbsoluteTransform());
  71229. tmat.multiplyToRef(wm, tmat);
  71230. }
  71231. else {
  71232. tmat.copyFrom(this._parent.getAbsoluteTransform());
  71233. }
  71234. }
  71235. tmat.invert();
  71236. BABYLON.Vector3.TransformCoordinatesToRef(position, tmat, vec);
  71237. lm.m[12] = vec.x;
  71238. lm.m[13] = vec.y;
  71239. lm.m[14] = vec.z;
  71240. }
  71241. this.markAsDirty();
  71242. };
  71243. /**
  71244. * Set the absolute postion of the bone (world space).
  71245. * @param position The position to set the bone.
  71246. * @param mesh The mesh that this bone is attached to.
  71247. */
  71248. Bone.prototype.setAbsolutePosition = function (position, mesh) {
  71249. this.setPosition(position, BABYLON.Space.WORLD, mesh);
  71250. };
  71251. /**
  71252. * Set the scale of the bone on the x, y and z axes.
  71253. * @param x The scale of the bone on the x axis.
  71254. * @param x The scale of the bone on the y axis.
  71255. * @param z The scale of the bone on the z axis.
  71256. * @param scaleChildren Set this to true if children of the bone should be scaled.
  71257. */
  71258. Bone.prototype.setScale = function (x, y, z, scaleChildren) {
  71259. if (scaleChildren === void 0) { scaleChildren = false; }
  71260. if (this.animations[0] && !this.animations[0].hasRunningRuntimeAnimations) {
  71261. if (!scaleChildren) {
  71262. this._negateScaleChildren.x = 1 / x;
  71263. this._negateScaleChildren.y = 1 / y;
  71264. this._negateScaleChildren.z = 1 / z;
  71265. }
  71266. this._syncScaleVector();
  71267. }
  71268. this.scale(x / this._scaleVector.x, y / this._scaleVector.y, z / this._scaleVector.z, scaleChildren);
  71269. };
  71270. /**
  71271. * Scale the bone on the x, y and z axes.
  71272. * @param x The amount to scale the bone on the x axis.
  71273. * @param x The amount to scale the bone on the y axis.
  71274. * @param z The amount to scale the bone on the z axis.
  71275. * @param scaleChildren Set this to true if children of the bone should be scaled.
  71276. */
  71277. Bone.prototype.scale = function (x, y, z, scaleChildren) {
  71278. if (scaleChildren === void 0) { scaleChildren = false; }
  71279. var locMat = this.getLocalMatrix();
  71280. var origLocMat = Bone._tmpMats[0];
  71281. origLocMat.copyFrom(locMat);
  71282. var origLocMatInv = Bone._tmpMats[1];
  71283. origLocMatInv.copyFrom(origLocMat);
  71284. origLocMatInv.invert();
  71285. var scaleMat = Bone._tmpMats[2];
  71286. BABYLON.Matrix.FromValuesToRef(x, 0, 0, 0, 0, y, 0, 0, 0, 0, z, 0, 0, 0, 0, 1, scaleMat);
  71287. this._scaleMatrix.multiplyToRef(scaleMat, this._scaleMatrix);
  71288. this._scaleVector.x *= x;
  71289. this._scaleVector.y *= y;
  71290. this._scaleVector.z *= z;
  71291. locMat.multiplyToRef(origLocMatInv, locMat);
  71292. locMat.multiplyToRef(scaleMat, locMat);
  71293. locMat.multiplyToRef(origLocMat, locMat);
  71294. var parent = this.getParent();
  71295. if (parent) {
  71296. locMat.multiplyToRef(parent.getAbsoluteTransform(), this.getAbsoluteTransform());
  71297. }
  71298. else {
  71299. this.getAbsoluteTransform().copyFrom(locMat);
  71300. }
  71301. var len = this.children.length;
  71302. scaleMat.invert();
  71303. for (var i = 0; i < len; i++) {
  71304. var child = this.children[i];
  71305. var cm = child.getLocalMatrix();
  71306. cm.multiplyToRef(scaleMat, cm);
  71307. var lm = child.getLocalMatrix();
  71308. lm.m[12] *= x;
  71309. lm.m[13] *= y;
  71310. lm.m[14] *= z;
  71311. }
  71312. this.computeAbsoluteTransforms();
  71313. if (scaleChildren) {
  71314. for (var i = 0; i < len; i++) {
  71315. this.children[i].scale(x, y, z, scaleChildren);
  71316. }
  71317. }
  71318. this.markAsDirty();
  71319. };
  71320. /**
  71321. * Set the yaw, pitch, and roll of the bone in local or world space.
  71322. * @param yaw The rotation of the bone on the y axis.
  71323. * @param pitch The rotation of the bone on the x axis.
  71324. * @param roll The rotation of the bone on the z axis.
  71325. * @param space The space that the axes of rotation are in.
  71326. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  71327. */
  71328. Bone.prototype.setYawPitchRoll = function (yaw, pitch, roll, space, mesh) {
  71329. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  71330. var rotMat = Bone._tmpMats[0];
  71331. BABYLON.Matrix.RotationYawPitchRollToRef(yaw, pitch, roll, rotMat);
  71332. var rotMatInv = Bone._tmpMats[1];
  71333. this._getNegativeRotationToRef(rotMatInv, space, mesh);
  71334. rotMatInv.multiplyToRef(rotMat, rotMat);
  71335. this._rotateWithMatrix(rotMat, space, mesh);
  71336. };
  71337. /**
  71338. * Rotate the bone on an axis in local or world space.
  71339. * @param axis The axis to rotate the bone on.
  71340. * @param amount The amount to rotate the bone.
  71341. * @param space The space that the axis is in.
  71342. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  71343. */
  71344. Bone.prototype.rotate = function (axis, amount, space, mesh) {
  71345. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  71346. var rmat = Bone._tmpMats[0];
  71347. rmat.m[12] = 0;
  71348. rmat.m[13] = 0;
  71349. rmat.m[14] = 0;
  71350. BABYLON.Matrix.RotationAxisToRef(axis, amount, rmat);
  71351. this._rotateWithMatrix(rmat, space, mesh);
  71352. };
  71353. /**
  71354. * Set the rotation of the bone to a particular axis angle in local or world space.
  71355. * @param axis The axis to rotate the bone on.
  71356. * @param angle The angle that the bone should be rotated to.
  71357. * @param space The space that the axis is in.
  71358. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  71359. */
  71360. Bone.prototype.setAxisAngle = function (axis, angle, space, mesh) {
  71361. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  71362. var rotMat = Bone._tmpMats[0];
  71363. BABYLON.Matrix.RotationAxisToRef(axis, angle, rotMat);
  71364. var rotMatInv = Bone._tmpMats[1];
  71365. this._getNegativeRotationToRef(rotMatInv, space, mesh);
  71366. rotMatInv.multiplyToRef(rotMat, rotMat);
  71367. this._rotateWithMatrix(rotMat, space, mesh);
  71368. };
  71369. /**
  71370. * Set the euler rotation of the bone in local of world space.
  71371. * @param rotation The euler rotation that the bone should be set to.
  71372. * @param space The space that the rotation is in.
  71373. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  71374. */
  71375. Bone.prototype.setRotation = function (rotation, space, mesh) {
  71376. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  71377. this.setYawPitchRoll(rotation.y, rotation.x, rotation.z, space, mesh);
  71378. };
  71379. /**
  71380. * Set the quaternion rotation of the bone in local of world space.
  71381. * @param quat The quaternion rotation that the bone should be set to.
  71382. * @param space The space that the rotation is in.
  71383. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  71384. */
  71385. Bone.prototype.setRotationQuaternion = function (quat, space, mesh) {
  71386. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  71387. var rotMatInv = Bone._tmpMats[0];
  71388. this._getNegativeRotationToRef(rotMatInv, space, mesh);
  71389. var rotMat = Bone._tmpMats[1];
  71390. BABYLON.Matrix.FromQuaternionToRef(quat, rotMat);
  71391. rotMatInv.multiplyToRef(rotMat, rotMat);
  71392. this._rotateWithMatrix(rotMat, space, mesh);
  71393. };
  71394. /**
  71395. * Set the rotation matrix of the bone in local of world space.
  71396. * @param rotMat The rotation matrix that the bone should be set to.
  71397. * @param space The space that the rotation is in.
  71398. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  71399. */
  71400. Bone.prototype.setRotationMatrix = function (rotMat, space, mesh) {
  71401. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  71402. var rotMatInv = Bone._tmpMats[0];
  71403. this._getNegativeRotationToRef(rotMatInv, space, mesh);
  71404. var rotMat2 = Bone._tmpMats[1];
  71405. rotMat2.copyFrom(rotMat);
  71406. rotMatInv.multiplyToRef(rotMat, rotMat2);
  71407. this._rotateWithMatrix(rotMat2, space, mesh);
  71408. };
  71409. Bone.prototype._rotateWithMatrix = function (rmat, space, mesh) {
  71410. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  71411. var lmat = this.getLocalMatrix();
  71412. var lx = lmat.m[12];
  71413. var ly = lmat.m[13];
  71414. var lz = lmat.m[14];
  71415. var parent = this.getParent();
  71416. var parentScale = Bone._tmpMats[3];
  71417. var parentScaleInv = Bone._tmpMats[4];
  71418. if (parent) {
  71419. if (space == BABYLON.Space.WORLD) {
  71420. if (mesh) {
  71421. parentScale.copyFrom(mesh.getWorldMatrix());
  71422. parent.getAbsoluteTransform().multiplyToRef(parentScale, parentScale);
  71423. }
  71424. else {
  71425. parentScale.copyFrom(parent.getAbsoluteTransform());
  71426. }
  71427. }
  71428. else {
  71429. parentScale = parent._scaleMatrix;
  71430. }
  71431. parentScaleInv.copyFrom(parentScale);
  71432. parentScaleInv.invert();
  71433. lmat.multiplyToRef(parentScale, lmat);
  71434. lmat.multiplyToRef(rmat, lmat);
  71435. lmat.multiplyToRef(parentScaleInv, lmat);
  71436. }
  71437. else {
  71438. if (space == BABYLON.Space.WORLD && mesh) {
  71439. parentScale.copyFrom(mesh.getWorldMatrix());
  71440. parentScaleInv.copyFrom(parentScale);
  71441. parentScaleInv.invert();
  71442. lmat.multiplyToRef(parentScale, lmat);
  71443. lmat.multiplyToRef(rmat, lmat);
  71444. lmat.multiplyToRef(parentScaleInv, lmat);
  71445. }
  71446. else {
  71447. lmat.multiplyToRef(rmat, lmat);
  71448. }
  71449. }
  71450. lmat.m[12] = lx;
  71451. lmat.m[13] = ly;
  71452. lmat.m[14] = lz;
  71453. this.computeAbsoluteTransforms();
  71454. this.markAsDirty();
  71455. };
  71456. Bone.prototype._getNegativeRotationToRef = function (rotMatInv, space, mesh) {
  71457. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  71458. if (space == BABYLON.Space.WORLD) {
  71459. var scaleMatrix = Bone._tmpMats[2];
  71460. scaleMatrix.copyFrom(this._scaleMatrix);
  71461. rotMatInv.copyFrom(this.getAbsoluteTransform());
  71462. if (mesh) {
  71463. rotMatInv.multiplyToRef(mesh.getWorldMatrix(), rotMatInv);
  71464. var meshScale = Bone._tmpMats[3];
  71465. BABYLON.Matrix.ScalingToRef(mesh.scaling.x, mesh.scaling.y, mesh.scaling.z, meshScale);
  71466. scaleMatrix.multiplyToRef(meshScale, scaleMatrix);
  71467. }
  71468. rotMatInv.invert();
  71469. scaleMatrix.m[0] *= this._scalingDeterminant;
  71470. rotMatInv.multiplyToRef(scaleMatrix, rotMatInv);
  71471. }
  71472. else {
  71473. rotMatInv.copyFrom(this.getLocalMatrix());
  71474. rotMatInv.invert();
  71475. var scaleMatrix = Bone._tmpMats[2];
  71476. scaleMatrix.copyFrom(this._scaleMatrix);
  71477. if (this._parent) {
  71478. var pscaleMatrix = Bone._tmpMats[3];
  71479. pscaleMatrix.copyFrom(this._parent._scaleMatrix);
  71480. pscaleMatrix.invert();
  71481. pscaleMatrix.multiplyToRef(rotMatInv, rotMatInv);
  71482. }
  71483. else {
  71484. scaleMatrix.m[0] *= this._scalingDeterminant;
  71485. }
  71486. rotMatInv.multiplyToRef(scaleMatrix, rotMatInv);
  71487. }
  71488. };
  71489. /**
  71490. * Get the scale of the bone
  71491. * @returns the scale of the bone
  71492. */
  71493. Bone.prototype.getScale = function () {
  71494. return this._scaleVector.clone();
  71495. };
  71496. /**
  71497. * Copy the scale of the bone to a vector3.
  71498. * @param result The vector3 to copy the scale to
  71499. */
  71500. Bone.prototype.getScaleToRef = function (result) {
  71501. result.copyFrom(this._scaleVector);
  71502. };
  71503. /**
  71504. * Get the position of the bone in local or world space.
  71505. * @param space The space that the returned position is in.
  71506. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  71507. * @returns The position of the bone
  71508. */
  71509. Bone.prototype.getPosition = function (space, mesh) {
  71510. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  71511. if (mesh === void 0) { mesh = null; }
  71512. var pos = BABYLON.Vector3.Zero();
  71513. this.getPositionToRef(space, mesh, pos);
  71514. return pos;
  71515. };
  71516. /**
  71517. * Copy the position of the bone to a vector3 in local or world space.
  71518. * @param space The space that the returned position is in.
  71519. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  71520. * @param result The vector3 to copy the position to.
  71521. */
  71522. Bone.prototype.getPositionToRef = function (space, mesh, result) {
  71523. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  71524. if (space == BABYLON.Space.LOCAL) {
  71525. var lm = this.getLocalMatrix();
  71526. result.x = lm.m[12];
  71527. result.y = lm.m[13];
  71528. result.z = lm.m[14];
  71529. }
  71530. else {
  71531. var wm = null;
  71532. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  71533. if (mesh) {
  71534. wm = mesh.getWorldMatrix();
  71535. }
  71536. this._skeleton.computeAbsoluteTransforms();
  71537. var tmat = Bone._tmpMats[0];
  71538. if (mesh && wm) {
  71539. tmat.copyFrom(this.getAbsoluteTransform());
  71540. tmat.multiplyToRef(wm, tmat);
  71541. }
  71542. else {
  71543. tmat = this.getAbsoluteTransform();
  71544. }
  71545. result.x = tmat.m[12];
  71546. result.y = tmat.m[13];
  71547. result.z = tmat.m[14];
  71548. }
  71549. };
  71550. /**
  71551. * Get the absolute position of the bone (world space).
  71552. * @param mesh The mesh that this bone is attached to.
  71553. * @returns The absolute position of the bone
  71554. */
  71555. Bone.prototype.getAbsolutePosition = function (mesh) {
  71556. if (mesh === void 0) { mesh = null; }
  71557. var pos = BABYLON.Vector3.Zero();
  71558. this.getPositionToRef(BABYLON.Space.WORLD, mesh, pos);
  71559. return pos;
  71560. };
  71561. /**
  71562. * Copy the absolute position of the bone (world space) to the result param.
  71563. * @param mesh The mesh that this bone is attached to.
  71564. * @param result The vector3 to copy the absolute position to.
  71565. */
  71566. Bone.prototype.getAbsolutePositionToRef = function (mesh, result) {
  71567. this.getPositionToRef(BABYLON.Space.WORLD, mesh, result);
  71568. };
  71569. /**
  71570. * Compute the absolute transforms of this bone and its children.
  71571. */
  71572. Bone.prototype.computeAbsoluteTransforms = function () {
  71573. if (this._parent) {
  71574. this._localMatrix.multiplyToRef(this._parent._absoluteTransform, this._absoluteTransform);
  71575. }
  71576. else {
  71577. this._absoluteTransform.copyFrom(this._localMatrix);
  71578. var poseMatrix = this._skeleton.getPoseMatrix();
  71579. if (poseMatrix) {
  71580. this._absoluteTransform.multiplyToRef(poseMatrix, this._absoluteTransform);
  71581. }
  71582. }
  71583. var children = this.children;
  71584. var len = children.length;
  71585. for (var i = 0; i < len; i++) {
  71586. children[i].computeAbsoluteTransforms();
  71587. }
  71588. };
  71589. Bone.prototype._syncScaleVector = function () {
  71590. var lm = this.getLocalMatrix();
  71591. var xsq = (lm.m[0] * lm.m[0] + lm.m[1] * lm.m[1] + lm.m[2] * lm.m[2]);
  71592. var ysq = (lm.m[4] * lm.m[4] + lm.m[5] * lm.m[5] + lm.m[6] * lm.m[6]);
  71593. var zsq = (lm.m[8] * lm.m[8] + lm.m[9] * lm.m[9] + lm.m[10] * lm.m[10]);
  71594. var xs = lm.m[0] * lm.m[1] * lm.m[2] * lm.m[3] < 0 ? -1 : 1;
  71595. var ys = lm.m[4] * lm.m[5] * lm.m[6] * lm.m[7] < 0 ? -1 : 1;
  71596. var zs = lm.m[8] * lm.m[9] * lm.m[10] * lm.m[11] < 0 ? -1 : 1;
  71597. this._scaleVector.x = xs * Math.sqrt(xsq);
  71598. this._scaleVector.y = ys * Math.sqrt(ysq);
  71599. this._scaleVector.z = zs * Math.sqrt(zsq);
  71600. if (this._parent) {
  71601. this._scaleVector.x /= this._parent._negateScaleChildren.x;
  71602. this._scaleVector.y /= this._parent._negateScaleChildren.y;
  71603. this._scaleVector.z /= this._parent._negateScaleChildren.z;
  71604. }
  71605. 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);
  71606. };
  71607. /**
  71608. * Get the world direction from an axis that is in the local space of the bone.
  71609. * @param localAxis The local direction that is used to compute the world direction.
  71610. * @param mesh The mesh that this bone is attached to.
  71611. * @returns The world direction
  71612. */
  71613. Bone.prototype.getDirection = function (localAxis, mesh) {
  71614. if (mesh === void 0) { mesh = null; }
  71615. var result = BABYLON.Vector3.Zero();
  71616. this.getDirectionToRef(localAxis, mesh, result);
  71617. return result;
  71618. };
  71619. /**
  71620. * Copy the world direction to a vector3 from an axis that is in the local space of the bone.
  71621. * @param localAxis The local direction that is used to compute the world direction.
  71622. * @param mesh The mesh that this bone is attached to.
  71623. * @param result The vector3 that the world direction will be copied to.
  71624. */
  71625. Bone.prototype.getDirectionToRef = function (localAxis, mesh, result) {
  71626. if (mesh === void 0) { mesh = null; }
  71627. var wm = null;
  71628. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  71629. if (mesh) {
  71630. wm = mesh.getWorldMatrix();
  71631. }
  71632. this._skeleton.computeAbsoluteTransforms();
  71633. var mat = Bone._tmpMats[0];
  71634. mat.copyFrom(this.getAbsoluteTransform());
  71635. if (mesh && wm) {
  71636. mat.multiplyToRef(wm, mat);
  71637. }
  71638. BABYLON.Vector3.TransformNormalToRef(localAxis, mat, result);
  71639. result.normalize();
  71640. };
  71641. /**
  71642. * Get the euler rotation of the bone in local or world space.
  71643. * @param space The space that the rotation should be in.
  71644. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  71645. * @returns The euler rotation
  71646. */
  71647. Bone.prototype.getRotation = function (space, mesh) {
  71648. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  71649. if (mesh === void 0) { mesh = null; }
  71650. var result = BABYLON.Vector3.Zero();
  71651. this.getRotationToRef(space, mesh, result);
  71652. return result;
  71653. };
  71654. /**
  71655. * Copy the euler rotation of the bone to a vector3. The rotation can be in either local or world space.
  71656. * @param space The space that the rotation should be in.
  71657. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  71658. * @param result The vector3 that the rotation should be copied to.
  71659. */
  71660. Bone.prototype.getRotationToRef = function (space, mesh, result) {
  71661. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  71662. if (mesh === void 0) { mesh = null; }
  71663. var quat = Bone._tmpQuat;
  71664. this.getRotationQuaternionToRef(space, mesh, quat);
  71665. quat.toEulerAnglesToRef(result);
  71666. };
  71667. /**
  71668. * Get the quaternion rotation of the bone in either local or world space.
  71669. * @param space The space that the rotation should be in.
  71670. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  71671. * @returns The quaternion rotation
  71672. */
  71673. Bone.prototype.getRotationQuaternion = function (space, mesh) {
  71674. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  71675. if (mesh === void 0) { mesh = null; }
  71676. var result = BABYLON.Quaternion.Identity();
  71677. this.getRotationQuaternionToRef(space, mesh, result);
  71678. return result;
  71679. };
  71680. /**
  71681. * Copy the quaternion rotation of the bone to a quaternion. The rotation can be in either local or world space.
  71682. * @param space The space that the rotation should be in.
  71683. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  71684. * @param result The quaternion that the rotation should be copied to.
  71685. */
  71686. Bone.prototype.getRotationQuaternionToRef = function (space, mesh, result) {
  71687. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  71688. if (mesh === void 0) { mesh = null; }
  71689. if (space == BABYLON.Space.LOCAL) {
  71690. this.getLocalMatrix().decompose(Bone._tmpVecs[0], result, Bone._tmpVecs[1]);
  71691. }
  71692. else {
  71693. var mat = Bone._tmpMats[0];
  71694. var amat = this.getAbsoluteTransform();
  71695. if (mesh) {
  71696. amat.multiplyToRef(mesh.getWorldMatrix(), mat);
  71697. }
  71698. else {
  71699. mat.copyFrom(amat);
  71700. }
  71701. mat.m[0] *= this._scalingDeterminant;
  71702. mat.m[1] *= this._scalingDeterminant;
  71703. mat.m[2] *= this._scalingDeterminant;
  71704. mat.decompose(Bone._tmpVecs[0], result, Bone._tmpVecs[1]);
  71705. }
  71706. };
  71707. /**
  71708. * Get the rotation matrix of the bone in local or world space.
  71709. * @param space The space that the rotation should be in.
  71710. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  71711. * @returns The rotation matrix
  71712. */
  71713. Bone.prototype.getRotationMatrix = function (space, mesh) {
  71714. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  71715. var result = BABYLON.Matrix.Identity();
  71716. this.getRotationMatrixToRef(space, mesh, result);
  71717. return result;
  71718. };
  71719. /**
  71720. * Copy the rotation matrix of the bone to a matrix. The rotation can be in either local or world space.
  71721. * @param space The space that the rotation should be in.
  71722. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  71723. * @param result The quaternion that the rotation should be copied to.
  71724. */
  71725. Bone.prototype.getRotationMatrixToRef = function (space, mesh, result) {
  71726. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  71727. if (space == BABYLON.Space.LOCAL) {
  71728. this.getLocalMatrix().getRotationMatrixToRef(result);
  71729. }
  71730. else {
  71731. var mat = Bone._tmpMats[0];
  71732. var amat = this.getAbsoluteTransform();
  71733. if (mesh) {
  71734. amat.multiplyToRef(mesh.getWorldMatrix(), mat);
  71735. }
  71736. else {
  71737. mat.copyFrom(amat);
  71738. }
  71739. mat.m[0] *= this._scalingDeterminant;
  71740. mat.m[1] *= this._scalingDeterminant;
  71741. mat.m[2] *= this._scalingDeterminant;
  71742. mat.getRotationMatrixToRef(result);
  71743. }
  71744. };
  71745. /**
  71746. * Get the world position of a point that is in the local space of the bone.
  71747. * @param position The local position
  71748. * @param mesh The mesh that this bone is attached to.
  71749. * @returns The world position
  71750. */
  71751. Bone.prototype.getAbsolutePositionFromLocal = function (position, mesh) {
  71752. if (mesh === void 0) { mesh = null; }
  71753. var result = BABYLON.Vector3.Zero();
  71754. this.getAbsolutePositionFromLocalToRef(position, mesh, result);
  71755. return result;
  71756. };
  71757. /**
  71758. * Get the world position of a point that is in the local space of the bone and copy it to the result param.
  71759. * @param position The local position
  71760. * @param mesh The mesh that this bone is attached to.
  71761. * @param result The vector3 that the world position should be copied to.
  71762. */
  71763. Bone.prototype.getAbsolutePositionFromLocalToRef = function (position, mesh, result) {
  71764. if (mesh === void 0) { mesh = null; }
  71765. var wm = null;
  71766. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  71767. if (mesh) {
  71768. wm = mesh.getWorldMatrix();
  71769. }
  71770. this._skeleton.computeAbsoluteTransforms();
  71771. var tmat = Bone._tmpMats[0];
  71772. if (mesh && wm) {
  71773. tmat.copyFrom(this.getAbsoluteTransform());
  71774. tmat.multiplyToRef(wm, tmat);
  71775. }
  71776. else {
  71777. tmat = this.getAbsoluteTransform();
  71778. }
  71779. BABYLON.Vector3.TransformCoordinatesToRef(position, tmat, result);
  71780. };
  71781. /**
  71782. * Get the local position of a point that is in world space.
  71783. * @param position The world position
  71784. * @param mesh The mesh that this bone is attached to.
  71785. * @returns The local position
  71786. */
  71787. Bone.prototype.getLocalPositionFromAbsolute = function (position, mesh) {
  71788. if (mesh === void 0) { mesh = null; }
  71789. var result = BABYLON.Vector3.Zero();
  71790. this.getLocalPositionFromAbsoluteToRef(position, mesh, result);
  71791. return result;
  71792. };
  71793. /**
  71794. * Get the local position of a point that is in world space and copy it to the result param.
  71795. * @param position The world position
  71796. * @param mesh The mesh that this bone is attached to.
  71797. * @param result The vector3 that the local position should be copied to.
  71798. */
  71799. Bone.prototype.getLocalPositionFromAbsoluteToRef = function (position, mesh, result) {
  71800. if (mesh === void 0) { mesh = null; }
  71801. var wm = null;
  71802. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  71803. if (mesh) {
  71804. wm = mesh.getWorldMatrix();
  71805. }
  71806. this._skeleton.computeAbsoluteTransforms();
  71807. var tmat = Bone._tmpMats[0];
  71808. tmat.copyFrom(this.getAbsoluteTransform());
  71809. if (mesh && wm) {
  71810. tmat.multiplyToRef(wm, tmat);
  71811. }
  71812. tmat.invert();
  71813. BABYLON.Vector3.TransformCoordinatesToRef(position, tmat, result);
  71814. };
  71815. Bone._tmpVecs = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  71816. Bone._tmpQuat = BABYLON.Quaternion.Identity();
  71817. Bone._tmpMats = [BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity()];
  71818. return Bone;
  71819. }(BABYLON.Node));
  71820. BABYLON.Bone = Bone;
  71821. })(BABYLON || (BABYLON = {}));
  71822. //# sourceMappingURL=babylon.bone.js.map
  71823. var BABYLON;
  71824. (function (BABYLON) {
  71825. var BoneIKController = /** @class */ (function () {
  71826. function BoneIKController(mesh, bone, options) {
  71827. this.targetPosition = BABYLON.Vector3.Zero();
  71828. this.poleTargetPosition = BABYLON.Vector3.Zero();
  71829. this.poleTargetLocalOffset = BABYLON.Vector3.Zero();
  71830. this.poleAngle = 0;
  71831. this.slerpAmount = 1;
  71832. this._bone1Quat = BABYLON.Quaternion.Identity();
  71833. this._bone1Mat = BABYLON.Matrix.Identity();
  71834. this._bone2Ang = Math.PI;
  71835. this._maxAngle = Math.PI;
  71836. this._rightHandedSystem = false;
  71837. this._bendAxis = BABYLON.Vector3.Right();
  71838. this._slerping = false;
  71839. this._adjustRoll = 0;
  71840. this._bone2 = bone;
  71841. this._bone1 = bone.getParent();
  71842. if (!this._bone1) {
  71843. return;
  71844. }
  71845. this.mesh = mesh;
  71846. var bonePos = bone.getPosition();
  71847. if (bone.getAbsoluteTransform().determinant() > 0) {
  71848. this._rightHandedSystem = true;
  71849. this._bendAxis.x = 0;
  71850. this._bendAxis.y = 0;
  71851. this._bendAxis.z = -1;
  71852. if (bonePos.x > bonePos.y && bonePos.x > bonePos.z) {
  71853. this._adjustRoll = Math.PI * .5;
  71854. this._bendAxis.z = 1;
  71855. }
  71856. }
  71857. if (this._bone1.length) {
  71858. var boneScale1 = this._bone1.getScale();
  71859. var boneScale2 = this._bone2.getScale();
  71860. this._bone1Length = this._bone1.length * boneScale1.y * this.mesh.scaling.y;
  71861. this._bone2Length = this._bone2.length * boneScale2.y * this.mesh.scaling.y;
  71862. }
  71863. else if (this._bone1.children[0]) {
  71864. mesh.computeWorldMatrix(true);
  71865. var pos1 = this._bone2.children[0].getAbsolutePosition(mesh);
  71866. var pos2 = this._bone2.getAbsolutePosition(mesh);
  71867. var pos3 = this._bone1.getAbsolutePosition(mesh);
  71868. this._bone1Length = BABYLON.Vector3.Distance(pos1, pos2);
  71869. this._bone2Length = BABYLON.Vector3.Distance(pos2, pos3);
  71870. }
  71871. this._bone1.getRotationMatrixToRef(BABYLON.Space.WORLD, mesh, this._bone1Mat);
  71872. this.maxAngle = Math.PI;
  71873. if (options) {
  71874. if (options.targetMesh) {
  71875. this.targetMesh = options.targetMesh;
  71876. this.targetMesh.computeWorldMatrix(true);
  71877. }
  71878. if (options.poleTargetMesh) {
  71879. this.poleTargetMesh = options.poleTargetMesh;
  71880. this.poleTargetMesh.computeWorldMatrix(true);
  71881. }
  71882. else if (options.poleTargetBone) {
  71883. this.poleTargetBone = options.poleTargetBone;
  71884. }
  71885. else if (this._bone1.getParent()) {
  71886. this.poleTargetBone = this._bone1.getParent();
  71887. }
  71888. if (options.poleTargetLocalOffset) {
  71889. this.poleTargetLocalOffset.copyFrom(options.poleTargetLocalOffset);
  71890. }
  71891. if (options.poleAngle) {
  71892. this.poleAngle = options.poleAngle;
  71893. }
  71894. if (options.bendAxis) {
  71895. this._bendAxis.copyFrom(options.bendAxis);
  71896. }
  71897. if (options.maxAngle) {
  71898. this.maxAngle = options.maxAngle;
  71899. }
  71900. if (options.slerpAmount) {
  71901. this.slerpAmount = options.slerpAmount;
  71902. }
  71903. }
  71904. }
  71905. Object.defineProperty(BoneIKController.prototype, "maxAngle", {
  71906. get: function () {
  71907. return this._maxAngle;
  71908. },
  71909. set: function (value) {
  71910. this._setMaxAngle(value);
  71911. },
  71912. enumerable: true,
  71913. configurable: true
  71914. });
  71915. BoneIKController.prototype._setMaxAngle = function (ang) {
  71916. if (ang < 0) {
  71917. ang = 0;
  71918. }
  71919. if (ang > Math.PI || ang == undefined) {
  71920. ang = Math.PI;
  71921. }
  71922. this._maxAngle = ang;
  71923. var a = this._bone1Length;
  71924. var b = this._bone2Length;
  71925. this._maxReach = Math.sqrt(a * a + b * b - 2 * a * b * Math.cos(ang));
  71926. };
  71927. BoneIKController.prototype.update = function () {
  71928. var bone1 = this._bone1;
  71929. if (!bone1) {
  71930. return;
  71931. }
  71932. var target = this.targetPosition;
  71933. var poleTarget = this.poleTargetPosition;
  71934. var mat1 = BoneIKController._tmpMats[0];
  71935. var mat2 = BoneIKController._tmpMats[1];
  71936. if (this.targetMesh) {
  71937. target.copyFrom(this.targetMesh.getAbsolutePosition());
  71938. }
  71939. if (this.poleTargetBone) {
  71940. this.poleTargetBone.getAbsolutePositionFromLocalToRef(this.poleTargetLocalOffset, this.mesh, poleTarget);
  71941. }
  71942. else if (this.poleTargetMesh) {
  71943. BABYLON.Vector3.TransformCoordinatesToRef(this.poleTargetLocalOffset, this.poleTargetMesh.getWorldMatrix(), poleTarget);
  71944. }
  71945. var bonePos = BoneIKController._tmpVecs[0];
  71946. var zaxis = BoneIKController._tmpVecs[1];
  71947. var xaxis = BoneIKController._tmpVecs[2];
  71948. var yaxis = BoneIKController._tmpVecs[3];
  71949. var upAxis = BoneIKController._tmpVecs[4];
  71950. var _tmpQuat = BoneIKController._tmpQuat;
  71951. bone1.getAbsolutePositionToRef(this.mesh, bonePos);
  71952. poleTarget.subtractToRef(bonePos, upAxis);
  71953. if (upAxis.x == 0 && upAxis.y == 0 && upAxis.z == 0) {
  71954. upAxis.y = 1;
  71955. }
  71956. else {
  71957. upAxis.normalize();
  71958. }
  71959. target.subtractToRef(bonePos, yaxis);
  71960. yaxis.normalize();
  71961. BABYLON.Vector3.CrossToRef(yaxis, upAxis, zaxis);
  71962. zaxis.normalize();
  71963. BABYLON.Vector3.CrossToRef(yaxis, zaxis, xaxis);
  71964. xaxis.normalize();
  71965. BABYLON.Matrix.FromXYZAxesToRef(xaxis, yaxis, zaxis, mat1);
  71966. var a = this._bone1Length;
  71967. var b = this._bone2Length;
  71968. var c = BABYLON.Vector3.Distance(bonePos, target);
  71969. if (this._maxReach > 0) {
  71970. c = Math.min(this._maxReach, c);
  71971. }
  71972. var acosa = (b * b + c * c - a * a) / (2 * b * c);
  71973. var acosb = (c * c + a * a - b * b) / (2 * c * a);
  71974. if (acosa > 1) {
  71975. acosa = 1;
  71976. }
  71977. if (acosb > 1) {
  71978. acosb = 1;
  71979. }
  71980. if (acosa < -1) {
  71981. acosa = -1;
  71982. }
  71983. if (acosb < -1) {
  71984. acosb = -1;
  71985. }
  71986. var angA = Math.acos(acosa);
  71987. var angB = Math.acos(acosb);
  71988. var angC = -angA - angB;
  71989. if (this._rightHandedSystem) {
  71990. BABYLON.Matrix.RotationYawPitchRollToRef(0, 0, this._adjustRoll, mat2);
  71991. mat2.multiplyToRef(mat1, mat1);
  71992. BABYLON.Matrix.RotationAxisToRef(this._bendAxis, angB, mat2);
  71993. mat2.multiplyToRef(mat1, mat1);
  71994. }
  71995. else {
  71996. var _tmpVec = BoneIKController._tmpVecs[5];
  71997. _tmpVec.copyFrom(this._bendAxis);
  71998. _tmpVec.x *= -1;
  71999. BABYLON.Matrix.RotationAxisToRef(_tmpVec, -angB, mat2);
  72000. mat2.multiplyToRef(mat1, mat1);
  72001. }
  72002. if (this.poleAngle) {
  72003. BABYLON.Matrix.RotationAxisToRef(yaxis, this.poleAngle, mat2);
  72004. mat1.multiplyToRef(mat2, mat1);
  72005. }
  72006. if (this._bone1) {
  72007. if (this.slerpAmount < 1) {
  72008. if (!this._slerping) {
  72009. BABYLON.Quaternion.FromRotationMatrixToRef(this._bone1Mat, this._bone1Quat);
  72010. }
  72011. BABYLON.Quaternion.FromRotationMatrixToRef(mat1, _tmpQuat);
  72012. BABYLON.Quaternion.SlerpToRef(this._bone1Quat, _tmpQuat, this.slerpAmount, this._bone1Quat);
  72013. angC = this._bone2Ang * (1.0 - this.slerpAmount) + angC * this.slerpAmount;
  72014. this._bone1.setRotationQuaternion(this._bone1Quat, BABYLON.Space.WORLD, this.mesh);
  72015. this._slerping = true;
  72016. }
  72017. else {
  72018. this._bone1.setRotationMatrix(mat1, BABYLON.Space.WORLD, this.mesh);
  72019. this._bone1Mat.copyFrom(mat1);
  72020. this._slerping = false;
  72021. }
  72022. }
  72023. this._bone2.setAxisAngle(this._bendAxis, angC, BABYLON.Space.LOCAL);
  72024. this._bone2Ang = angC;
  72025. };
  72026. BoneIKController._tmpVecs = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  72027. BoneIKController._tmpQuat = BABYLON.Quaternion.Identity();
  72028. BoneIKController._tmpMats = [BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity()];
  72029. return BoneIKController;
  72030. }());
  72031. BABYLON.BoneIKController = BoneIKController;
  72032. })(BABYLON || (BABYLON = {}));
  72033. //# sourceMappingURL=babylon.boneIKController.js.map
  72034. var BABYLON;
  72035. (function (BABYLON) {
  72036. var BoneLookController = /** @class */ (function () {
  72037. /**
  72038. * Create a BoneLookController
  72039. * @param mesh the mesh that the bone belongs to
  72040. * @param bone the bone that will be looking to the target
  72041. * @param target the target Vector3 to look at
  72042. * @param settings optional settings:
  72043. * - maxYaw: the maximum angle the bone will yaw to
  72044. * - minYaw: the minimum angle the bone will yaw to
  72045. * - maxPitch: the maximum angle the bone will pitch to
  72046. * - minPitch: the minimum angle the bone will yaw to
  72047. * - slerpAmount: set the between 0 and 1 to make the bone slerp to the target.
  72048. * - upAxis: the up axis of the coordinate system
  72049. * - upAxisSpace: the space that the up axis is in - BABYLON.Space.BONE, BABYLON.Space.LOCAL (default), or BABYLON.Space.WORLD.
  72050. * - yawAxis: set yawAxis if the bone does not yaw on the y axis
  72051. * - pitchAxis: set pitchAxis if the bone does not pitch on the x axis
  72052. * - adjustYaw: used to make an adjustment to the yaw of the bone
  72053. * - adjustPitch: used to make an adjustment to the pitch of the bone
  72054. * - adjustRoll: used to make an adjustment to the roll of the bone
  72055. **/
  72056. function BoneLookController(mesh, bone, target, options) {
  72057. /**
  72058. * The up axis of the coordinate system that is used when the bone is rotated.
  72059. */
  72060. this.upAxis = BABYLON.Vector3.Up();
  72061. /**
  72062. * The space that the up axis is in - BABYLON.Space.BONE, BABYLON.Space.LOCAL (default), or BABYLON.Space.WORLD.
  72063. */
  72064. this.upAxisSpace = BABYLON.Space.LOCAL;
  72065. /**
  72066. * Used to make an adjustment to the yaw of the bone.
  72067. */
  72068. this.adjustYaw = 0;
  72069. /**
  72070. * Used to make an adjustment to the pitch of the bone.
  72071. */
  72072. this.adjustPitch = 0;
  72073. /**
  72074. * Used to make an adjustment to the roll of the bone.
  72075. */
  72076. this.adjustRoll = 0;
  72077. /**
  72078. * 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).
  72079. */
  72080. this.slerpAmount = 1;
  72081. this._boneQuat = BABYLON.Quaternion.Identity();
  72082. this._slerping = false;
  72083. this._firstFrameSkipped = false;
  72084. this._fowardAxis = BABYLON.Vector3.Forward();
  72085. this.mesh = mesh;
  72086. this.bone = bone;
  72087. this.target = target;
  72088. if (options) {
  72089. if (options.adjustYaw) {
  72090. this.adjustYaw = options.adjustYaw;
  72091. }
  72092. if (options.adjustPitch) {
  72093. this.adjustPitch = options.adjustPitch;
  72094. }
  72095. if (options.adjustRoll) {
  72096. this.adjustRoll = options.adjustRoll;
  72097. }
  72098. if (options.maxYaw != null) {
  72099. this.maxYaw = options.maxYaw;
  72100. }
  72101. else {
  72102. this.maxYaw = Math.PI;
  72103. }
  72104. if (options.minYaw != null) {
  72105. this.minYaw = options.minYaw;
  72106. }
  72107. else {
  72108. this.minYaw = -Math.PI;
  72109. }
  72110. if (options.maxPitch != null) {
  72111. this.maxPitch = options.maxPitch;
  72112. }
  72113. else {
  72114. this.maxPitch = Math.PI;
  72115. }
  72116. if (options.minPitch != null) {
  72117. this.minPitch = options.minPitch;
  72118. }
  72119. else {
  72120. this.minPitch = -Math.PI;
  72121. }
  72122. if (options.slerpAmount != null) {
  72123. this.slerpAmount = options.slerpAmount;
  72124. }
  72125. if (options.upAxis != null) {
  72126. this.upAxis = options.upAxis;
  72127. }
  72128. if (options.upAxisSpace != null) {
  72129. this.upAxisSpace = options.upAxisSpace;
  72130. }
  72131. if (options.yawAxis != null || options.pitchAxis != null) {
  72132. var newYawAxis = BABYLON.Axis.Y;
  72133. var newPitchAxis = BABYLON.Axis.X;
  72134. if (options.yawAxis != null) {
  72135. newYawAxis = options.yawAxis.clone();
  72136. newYawAxis.normalize();
  72137. }
  72138. if (options.pitchAxis != null) {
  72139. newPitchAxis = options.pitchAxis.clone();
  72140. newPitchAxis.normalize();
  72141. }
  72142. var newRollAxis = BABYLON.Vector3.Cross(newPitchAxis, newYawAxis);
  72143. this._transformYawPitch = BABYLON.Matrix.Identity();
  72144. BABYLON.Matrix.FromXYZAxesToRef(newPitchAxis, newYawAxis, newRollAxis, this._transformYawPitch);
  72145. this._transformYawPitchInv = this._transformYawPitch.clone();
  72146. this._transformYawPitch.invert();
  72147. }
  72148. }
  72149. if (!bone.getParent() && this.upAxisSpace == BABYLON.Space.BONE) {
  72150. this.upAxisSpace = BABYLON.Space.LOCAL;
  72151. }
  72152. }
  72153. Object.defineProperty(BoneLookController.prototype, "minYaw", {
  72154. /**
  72155. * Get/set the minimum yaw angle that the bone can look to.
  72156. */
  72157. get: function () {
  72158. return this._minYaw;
  72159. },
  72160. set: function (value) {
  72161. this._minYaw = value;
  72162. this._minYawSin = Math.sin(value);
  72163. this._minYawCos = Math.cos(value);
  72164. if (this._maxYaw != null) {
  72165. this._midYawConstraint = this._getAngleDiff(this._minYaw, this._maxYaw) * .5 + this._minYaw;
  72166. this._yawRange = this._maxYaw - this._minYaw;
  72167. }
  72168. },
  72169. enumerable: true,
  72170. configurable: true
  72171. });
  72172. Object.defineProperty(BoneLookController.prototype, "maxYaw", {
  72173. /**
  72174. * Get/set the maximum yaw angle that the bone can look to.
  72175. */
  72176. get: function () {
  72177. return this._maxYaw;
  72178. },
  72179. set: function (value) {
  72180. this._maxYaw = value;
  72181. this._maxYawSin = Math.sin(value);
  72182. this._maxYawCos = Math.cos(value);
  72183. if (this._minYaw != null) {
  72184. this._midYawConstraint = this._getAngleDiff(this._minYaw, this._maxYaw) * .5 + this._minYaw;
  72185. this._yawRange = this._maxYaw - this._minYaw;
  72186. }
  72187. },
  72188. enumerable: true,
  72189. configurable: true
  72190. });
  72191. Object.defineProperty(BoneLookController.prototype, "minPitch", {
  72192. /**
  72193. * Get/set the minimum pitch angle that the bone can look to.
  72194. */
  72195. get: function () {
  72196. return this._minPitch;
  72197. },
  72198. set: function (value) {
  72199. this._minPitch = value;
  72200. this._minPitchTan = Math.tan(value);
  72201. },
  72202. enumerable: true,
  72203. configurable: true
  72204. });
  72205. Object.defineProperty(BoneLookController.prototype, "maxPitch", {
  72206. /**
  72207. * Get/set the maximum pitch angle that the bone can look to.
  72208. */
  72209. get: function () {
  72210. return this._maxPitch;
  72211. },
  72212. set: function (value) {
  72213. this._maxPitch = value;
  72214. this._maxPitchTan = Math.tan(value);
  72215. },
  72216. enumerable: true,
  72217. configurable: true
  72218. });
  72219. /**
  72220. * Update the bone to look at the target. This should be called before the scene is rendered (use scene.registerBeforeRender()).
  72221. */
  72222. BoneLookController.prototype.update = function () {
  72223. //skip the first frame when slerping so that the mesh rotation is correct
  72224. if (this.slerpAmount < 1 && !this._firstFrameSkipped) {
  72225. this._firstFrameSkipped = true;
  72226. return;
  72227. }
  72228. var bone = this.bone;
  72229. var bonePos = BoneLookController._tmpVecs[0];
  72230. bone.getAbsolutePositionToRef(this.mesh, bonePos);
  72231. var target = this.target;
  72232. var _tmpMat1 = BoneLookController._tmpMats[0];
  72233. var _tmpMat2 = BoneLookController._tmpMats[1];
  72234. var mesh = this.mesh;
  72235. var parentBone = bone.getParent();
  72236. var upAxis = BoneLookController._tmpVecs[1];
  72237. upAxis.copyFrom(this.upAxis);
  72238. if (this.upAxisSpace == BABYLON.Space.BONE && parentBone) {
  72239. if (this._transformYawPitch) {
  72240. BABYLON.Vector3.TransformCoordinatesToRef(upAxis, this._transformYawPitchInv, upAxis);
  72241. }
  72242. parentBone.getDirectionToRef(upAxis, this.mesh, upAxis);
  72243. }
  72244. else if (this.upAxisSpace == BABYLON.Space.LOCAL) {
  72245. mesh.getDirectionToRef(upAxis, upAxis);
  72246. if (mesh.scaling.x != 1 || mesh.scaling.y != 1 || mesh.scaling.z != 1) {
  72247. upAxis.normalize();
  72248. }
  72249. }
  72250. var checkYaw = false;
  72251. var checkPitch = false;
  72252. if (this._maxYaw != Math.PI || this._minYaw != -Math.PI) {
  72253. checkYaw = true;
  72254. }
  72255. if (this._maxPitch != Math.PI || this._minPitch != -Math.PI) {
  72256. checkPitch = true;
  72257. }
  72258. if (checkYaw || checkPitch) {
  72259. var spaceMat = BoneLookController._tmpMats[2];
  72260. var spaceMatInv = BoneLookController._tmpMats[3];
  72261. if (this.upAxisSpace == BABYLON.Space.BONE && upAxis.y == 1 && parentBone) {
  72262. parentBone.getRotationMatrixToRef(BABYLON.Space.WORLD, this.mesh, spaceMat);
  72263. }
  72264. else if (this.upAxisSpace == BABYLON.Space.LOCAL && upAxis.y == 1 && !parentBone) {
  72265. spaceMat.copyFrom(mesh.getWorldMatrix());
  72266. }
  72267. else {
  72268. var forwardAxis = BoneLookController._tmpVecs[2];
  72269. forwardAxis.copyFrom(this._fowardAxis);
  72270. if (this._transformYawPitch) {
  72271. BABYLON.Vector3.TransformCoordinatesToRef(forwardAxis, this._transformYawPitchInv, forwardAxis);
  72272. }
  72273. if (parentBone) {
  72274. parentBone.getDirectionToRef(forwardAxis, this.mesh, forwardAxis);
  72275. }
  72276. else {
  72277. mesh.getDirectionToRef(forwardAxis, forwardAxis);
  72278. }
  72279. var rightAxis = BABYLON.Vector3.Cross(upAxis, forwardAxis);
  72280. rightAxis.normalize();
  72281. var forwardAxis = BABYLON.Vector3.Cross(rightAxis, upAxis);
  72282. BABYLON.Matrix.FromXYZAxesToRef(rightAxis, upAxis, forwardAxis, spaceMat);
  72283. }
  72284. spaceMat.invertToRef(spaceMatInv);
  72285. var xzlen = null;
  72286. if (checkPitch) {
  72287. var localTarget = BoneLookController._tmpVecs[3];
  72288. target.subtractToRef(bonePos, localTarget);
  72289. BABYLON.Vector3.TransformCoordinatesToRef(localTarget, spaceMatInv, localTarget);
  72290. xzlen = Math.sqrt(localTarget.x * localTarget.x + localTarget.z * localTarget.z);
  72291. var pitch = Math.atan2(localTarget.y, xzlen);
  72292. var newPitch = pitch;
  72293. if (pitch > this._maxPitch) {
  72294. localTarget.y = this._maxPitchTan * xzlen;
  72295. newPitch = this._maxPitch;
  72296. }
  72297. else if (pitch < this._minPitch) {
  72298. localTarget.y = this._minPitchTan * xzlen;
  72299. newPitch = this._minPitch;
  72300. }
  72301. if (pitch != newPitch) {
  72302. BABYLON.Vector3.TransformCoordinatesToRef(localTarget, spaceMat, localTarget);
  72303. localTarget.addInPlace(bonePos);
  72304. target = localTarget;
  72305. }
  72306. }
  72307. if (checkYaw) {
  72308. var localTarget = BoneLookController._tmpVecs[4];
  72309. target.subtractToRef(bonePos, localTarget);
  72310. BABYLON.Vector3.TransformCoordinatesToRef(localTarget, spaceMatInv, localTarget);
  72311. var yaw = Math.atan2(localTarget.x, localTarget.z);
  72312. var newYaw = yaw;
  72313. if (yaw > this._maxYaw || yaw < this._minYaw) {
  72314. if (xzlen == null) {
  72315. xzlen = Math.sqrt(localTarget.x * localTarget.x + localTarget.z * localTarget.z);
  72316. }
  72317. if (this._yawRange > Math.PI) {
  72318. if (this._isAngleBetween(yaw, this._maxYaw, this._midYawConstraint)) {
  72319. localTarget.z = this._maxYawCos * xzlen;
  72320. localTarget.x = this._maxYawSin * xzlen;
  72321. newYaw = this._maxYaw;
  72322. }
  72323. else if (this._isAngleBetween(yaw, this._midYawConstraint, this._minYaw)) {
  72324. localTarget.z = this._minYawCos * xzlen;
  72325. localTarget.x = this._minYawSin * xzlen;
  72326. newYaw = this._minYaw;
  72327. }
  72328. }
  72329. else {
  72330. if (yaw > this._maxYaw) {
  72331. localTarget.z = this._maxYawCos * xzlen;
  72332. localTarget.x = this._maxYawSin * xzlen;
  72333. newYaw = this._maxYaw;
  72334. }
  72335. else if (yaw < this._minYaw) {
  72336. localTarget.z = this._minYawCos * xzlen;
  72337. localTarget.x = this._minYawSin * xzlen;
  72338. newYaw = this._minYaw;
  72339. }
  72340. }
  72341. }
  72342. if (this._slerping && this._yawRange > Math.PI) {
  72343. //are we going to be crossing into the min/max region?
  72344. var boneFwd = BoneLookController._tmpVecs[8];
  72345. boneFwd.copyFrom(BABYLON.Axis.Z);
  72346. if (this._transformYawPitch) {
  72347. BABYLON.Vector3.TransformCoordinatesToRef(boneFwd, this._transformYawPitchInv, boneFwd);
  72348. }
  72349. var boneRotMat = BoneLookController._tmpMats[4];
  72350. this._boneQuat.toRotationMatrix(boneRotMat);
  72351. this.mesh.getWorldMatrix().multiplyToRef(boneRotMat, boneRotMat);
  72352. BABYLON.Vector3.TransformCoordinatesToRef(boneFwd, boneRotMat, boneFwd);
  72353. BABYLON.Vector3.TransformCoordinatesToRef(boneFwd, spaceMatInv, boneFwd);
  72354. var boneYaw = Math.atan2(boneFwd.x, boneFwd.z);
  72355. var angBtwTar = this._getAngleBetween(boneYaw, yaw);
  72356. var angBtwMidYaw = this._getAngleBetween(boneYaw, this._midYawConstraint);
  72357. if (angBtwTar > angBtwMidYaw) {
  72358. if (xzlen == null) {
  72359. xzlen = Math.sqrt(localTarget.x * localTarget.x + localTarget.z * localTarget.z);
  72360. }
  72361. var angBtwMax = this._getAngleBetween(boneYaw, this._maxYaw);
  72362. var angBtwMin = this._getAngleBetween(boneYaw, this._minYaw);
  72363. if (angBtwMin < angBtwMax) {
  72364. newYaw = boneYaw + Math.PI * .75;
  72365. localTarget.z = Math.cos(newYaw) * xzlen;
  72366. localTarget.x = Math.sin(newYaw) * xzlen;
  72367. }
  72368. else {
  72369. newYaw = boneYaw - Math.PI * .75;
  72370. localTarget.z = Math.cos(newYaw) * xzlen;
  72371. localTarget.x = Math.sin(newYaw) * xzlen;
  72372. }
  72373. }
  72374. }
  72375. if (yaw != newYaw) {
  72376. BABYLON.Vector3.TransformCoordinatesToRef(localTarget, spaceMat, localTarget);
  72377. localTarget.addInPlace(bonePos);
  72378. target = localTarget;
  72379. }
  72380. }
  72381. }
  72382. var zaxis = BoneLookController._tmpVecs[5];
  72383. var xaxis = BoneLookController._tmpVecs[6];
  72384. var yaxis = BoneLookController._tmpVecs[7];
  72385. var _tmpQuat = BoneLookController._tmpQuat;
  72386. target.subtractToRef(bonePos, zaxis);
  72387. zaxis.normalize();
  72388. BABYLON.Vector3.CrossToRef(upAxis, zaxis, xaxis);
  72389. xaxis.normalize();
  72390. BABYLON.Vector3.CrossToRef(zaxis, xaxis, yaxis);
  72391. yaxis.normalize();
  72392. BABYLON.Matrix.FromXYZAxesToRef(xaxis, yaxis, zaxis, _tmpMat1);
  72393. if (xaxis.x === 0 && xaxis.y === 0 && xaxis.z === 0) {
  72394. return;
  72395. }
  72396. if (yaxis.x === 0 && yaxis.y === 0 && yaxis.z === 0) {
  72397. return;
  72398. }
  72399. if (zaxis.x === 0 && zaxis.y === 0 && zaxis.z === 0) {
  72400. return;
  72401. }
  72402. if (this.adjustYaw || this.adjustPitch || this.adjustRoll) {
  72403. BABYLON.Matrix.RotationYawPitchRollToRef(this.adjustYaw, this.adjustPitch, this.adjustRoll, _tmpMat2);
  72404. _tmpMat2.multiplyToRef(_tmpMat1, _tmpMat1);
  72405. }
  72406. if (this.slerpAmount < 1) {
  72407. if (!this._slerping) {
  72408. this.bone.getRotationQuaternionToRef(BABYLON.Space.WORLD, this.mesh, this._boneQuat);
  72409. }
  72410. if (this._transformYawPitch) {
  72411. this._transformYawPitch.multiplyToRef(_tmpMat1, _tmpMat1);
  72412. }
  72413. BABYLON.Quaternion.FromRotationMatrixToRef(_tmpMat1, _tmpQuat);
  72414. BABYLON.Quaternion.SlerpToRef(this._boneQuat, _tmpQuat, this.slerpAmount, this._boneQuat);
  72415. this.bone.setRotationQuaternion(this._boneQuat, BABYLON.Space.WORLD, this.mesh);
  72416. this._slerping = true;
  72417. }
  72418. else {
  72419. if (this._transformYawPitch) {
  72420. this._transformYawPitch.multiplyToRef(_tmpMat1, _tmpMat1);
  72421. }
  72422. this.bone.setRotationMatrix(_tmpMat1, BABYLON.Space.WORLD, this.mesh);
  72423. this._slerping = false;
  72424. }
  72425. };
  72426. BoneLookController.prototype._getAngleDiff = function (ang1, ang2) {
  72427. var angDiff = ang2 - ang1;
  72428. angDiff %= Math.PI * 2;
  72429. if (angDiff > Math.PI) {
  72430. angDiff -= Math.PI * 2;
  72431. }
  72432. else if (angDiff < -Math.PI) {
  72433. angDiff += Math.PI * 2;
  72434. }
  72435. return angDiff;
  72436. };
  72437. BoneLookController.prototype._getAngleBetween = function (ang1, ang2) {
  72438. ang1 %= (2 * Math.PI);
  72439. ang1 = (ang1 < 0) ? ang1 + (2 * Math.PI) : ang1;
  72440. ang2 %= (2 * Math.PI);
  72441. ang2 = (ang2 < 0) ? ang2 + (2 * Math.PI) : ang2;
  72442. var ab = 0;
  72443. if (ang1 < ang2) {
  72444. ab = ang2 - ang1;
  72445. }
  72446. else {
  72447. ab = ang1 - ang2;
  72448. }
  72449. if (ab > Math.PI) {
  72450. ab = Math.PI * 2 - ab;
  72451. }
  72452. return ab;
  72453. };
  72454. BoneLookController.prototype._isAngleBetween = function (ang, ang1, ang2) {
  72455. ang %= (2 * Math.PI);
  72456. ang = (ang < 0) ? ang + (2 * Math.PI) : ang;
  72457. ang1 %= (2 * Math.PI);
  72458. ang1 = (ang1 < 0) ? ang1 + (2 * Math.PI) : ang1;
  72459. ang2 %= (2 * Math.PI);
  72460. ang2 = (ang2 < 0) ? ang2 + (2 * Math.PI) : ang2;
  72461. if (ang1 < ang2) {
  72462. if (ang > ang1 && ang < ang2) {
  72463. return true;
  72464. }
  72465. }
  72466. else {
  72467. if (ang > ang2 && ang < ang1) {
  72468. return true;
  72469. }
  72470. }
  72471. return false;
  72472. };
  72473. 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()];
  72474. BoneLookController._tmpQuat = BABYLON.Quaternion.Identity();
  72475. BoneLookController._tmpMats = [BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity()];
  72476. return BoneLookController;
  72477. }());
  72478. BABYLON.BoneLookController = BoneLookController;
  72479. })(BABYLON || (BABYLON = {}));
  72480. //# sourceMappingURL=babylon.boneLookController.js.map
  72481. var BABYLON;
  72482. (function (BABYLON) {
  72483. var Skeleton = /** @class */ (function () {
  72484. function Skeleton(name, id, scene) {
  72485. this.name = name;
  72486. this.id = id;
  72487. this.bones = new Array();
  72488. this.needInitialSkinMatrix = false;
  72489. this._isDirty = true;
  72490. this._meshesWithPoseMatrix = new Array();
  72491. this._identity = BABYLON.Matrix.Identity();
  72492. this._ranges = {};
  72493. this._lastAbsoluteTransformsUpdateId = -1;
  72494. /**
  72495. * Specifies if the skeleton should be serialized.
  72496. */
  72497. this.doNotSerialize = false;
  72498. // Events
  72499. /**
  72500. * An event triggered before computing the skeleton's matrices
  72501. * @type {BABYLON.Observable}
  72502. */
  72503. this.onBeforeComputeObservable = new BABYLON.Observable();
  72504. this.bones = [];
  72505. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  72506. scene.skeletons.push(this);
  72507. //make sure it will recalculate the matrix next time prepare is called.
  72508. this._isDirty = true;
  72509. }
  72510. // Members
  72511. Skeleton.prototype.getTransformMatrices = function (mesh) {
  72512. if (this.needInitialSkinMatrix && mesh._bonesTransformMatrices) {
  72513. return mesh._bonesTransformMatrices;
  72514. }
  72515. if (!this._transformMatrices) {
  72516. this.prepare();
  72517. }
  72518. return this._transformMatrices;
  72519. };
  72520. Skeleton.prototype.getScene = function () {
  72521. return this._scene;
  72522. };
  72523. // Methods
  72524. /**
  72525. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  72526. */
  72527. Skeleton.prototype.toString = function (fullDetails) {
  72528. var ret = "Name: " + this.name + ", nBones: " + this.bones.length;
  72529. ret += ", nAnimationRanges: " + (this._ranges ? Object.keys(this._ranges).length : "none");
  72530. if (fullDetails) {
  72531. ret += ", Ranges: {";
  72532. var first = true;
  72533. for (var name_1 in this._ranges) {
  72534. if (first) {
  72535. ret += ", ";
  72536. first = false;
  72537. }
  72538. ret += name_1;
  72539. }
  72540. ret += "}";
  72541. }
  72542. return ret;
  72543. };
  72544. /**
  72545. * Get bone's index searching by name
  72546. * @param {string} name is bone's name to search for
  72547. * @return {number} Indice of the bone. Returns -1 if not found
  72548. */
  72549. Skeleton.prototype.getBoneIndexByName = function (name) {
  72550. for (var boneIndex = 0, cache = this.bones.length; boneIndex < cache; boneIndex++) {
  72551. if (this.bones[boneIndex].name === name) {
  72552. return boneIndex;
  72553. }
  72554. }
  72555. return -1;
  72556. };
  72557. Skeleton.prototype.createAnimationRange = function (name, from, to) {
  72558. // check name not already in use
  72559. if (!this._ranges[name]) {
  72560. this._ranges[name] = new BABYLON.AnimationRange(name, from, to);
  72561. for (var i = 0, nBones = this.bones.length; i < nBones; i++) {
  72562. if (this.bones[i].animations[0]) {
  72563. this.bones[i].animations[0].createRange(name, from, to);
  72564. }
  72565. }
  72566. }
  72567. };
  72568. Skeleton.prototype.deleteAnimationRange = function (name, deleteFrames) {
  72569. if (deleteFrames === void 0) { deleteFrames = true; }
  72570. for (var i = 0, nBones = this.bones.length; i < nBones; i++) {
  72571. if (this.bones[i].animations[0]) {
  72572. this.bones[i].animations[0].deleteRange(name, deleteFrames);
  72573. }
  72574. }
  72575. this._ranges[name] = null; // said much faster than 'delete this._range[name]'
  72576. };
  72577. Skeleton.prototype.getAnimationRange = function (name) {
  72578. return this._ranges[name];
  72579. };
  72580. /**
  72581. * Returns as an Array, all AnimationRanges defined on this skeleton
  72582. */
  72583. Skeleton.prototype.getAnimationRanges = function () {
  72584. var animationRanges = [];
  72585. var name;
  72586. var i = 0;
  72587. for (name in this._ranges) {
  72588. animationRanges[i] = this._ranges[name];
  72589. i++;
  72590. }
  72591. return animationRanges;
  72592. };
  72593. /**
  72594. * note: This is not for a complete retargeting, only between very similar skeleton's with only possible bone length differences
  72595. */
  72596. Skeleton.prototype.copyAnimationRange = function (source, name, rescaleAsRequired) {
  72597. if (rescaleAsRequired === void 0) { rescaleAsRequired = false; }
  72598. if (this._ranges[name] || !source.getAnimationRange(name)) {
  72599. return false;
  72600. }
  72601. var ret = true;
  72602. var frameOffset = this._getHighestAnimationFrame() + 1;
  72603. // make a dictionary of source skeleton's bones, so exact same order or doublely nested loop is not required
  72604. var boneDict = {};
  72605. var sourceBones = source.bones;
  72606. var nBones;
  72607. var i;
  72608. for (i = 0, nBones = sourceBones.length; i < nBones; i++) {
  72609. boneDict[sourceBones[i].name] = sourceBones[i];
  72610. }
  72611. if (this.bones.length !== sourceBones.length) {
  72612. BABYLON.Tools.Warn("copyAnimationRange: this rig has " + this.bones.length + " bones, while source as " + sourceBones.length);
  72613. ret = false;
  72614. }
  72615. var skelDimensionsRatio = (rescaleAsRequired && this.dimensionsAtRest && source.dimensionsAtRest) ? this.dimensionsAtRest.divide(source.dimensionsAtRest) : null;
  72616. for (i = 0, nBones = this.bones.length; i < nBones; i++) {
  72617. var boneName = this.bones[i].name;
  72618. var sourceBone = boneDict[boneName];
  72619. if (sourceBone) {
  72620. ret = ret && this.bones[i].copyAnimationRange(sourceBone, name, frameOffset, rescaleAsRequired, skelDimensionsRatio);
  72621. }
  72622. else {
  72623. BABYLON.Tools.Warn("copyAnimationRange: not same rig, missing source bone " + boneName);
  72624. ret = false;
  72625. }
  72626. }
  72627. // do not call createAnimationRange(), since it also is done to bones, which was already done
  72628. var range = source.getAnimationRange(name);
  72629. if (range) {
  72630. this._ranges[name] = new BABYLON.AnimationRange(name, range.from + frameOffset, range.to + frameOffset);
  72631. }
  72632. return ret;
  72633. };
  72634. Skeleton.prototype.returnToRest = function () {
  72635. for (var index = 0; index < this.bones.length; index++) {
  72636. this.bones[index].returnToRest();
  72637. }
  72638. };
  72639. Skeleton.prototype._getHighestAnimationFrame = function () {
  72640. var ret = 0;
  72641. for (var i = 0, nBones = this.bones.length; i < nBones; i++) {
  72642. if (this.bones[i].animations[0]) {
  72643. var highest = this.bones[i].animations[0].getHighestFrame();
  72644. if (ret < highest) {
  72645. ret = highest;
  72646. }
  72647. }
  72648. }
  72649. return ret;
  72650. };
  72651. Skeleton.prototype.beginAnimation = function (name, loop, speedRatio, onAnimationEnd) {
  72652. var range = this.getAnimationRange(name);
  72653. if (!range) {
  72654. return null;
  72655. }
  72656. return this._scene.beginAnimation(this, range.from, range.to, loop, speedRatio, onAnimationEnd);
  72657. };
  72658. Skeleton.prototype._markAsDirty = function () {
  72659. this._isDirty = true;
  72660. };
  72661. Skeleton.prototype._registerMeshWithPoseMatrix = function (mesh) {
  72662. this._meshesWithPoseMatrix.push(mesh);
  72663. };
  72664. Skeleton.prototype._unregisterMeshWithPoseMatrix = function (mesh) {
  72665. var index = this._meshesWithPoseMatrix.indexOf(mesh);
  72666. if (index > -1) {
  72667. this._meshesWithPoseMatrix.splice(index, 1);
  72668. }
  72669. };
  72670. Skeleton.prototype._computeTransformMatrices = function (targetMatrix, initialSkinMatrix) {
  72671. this.onBeforeComputeObservable.notifyObservers(this);
  72672. for (var index = 0; index < this.bones.length; index++) {
  72673. var bone = this.bones[index];
  72674. var parentBone = bone.getParent();
  72675. if (parentBone) {
  72676. bone.getLocalMatrix().multiplyToRef(parentBone.getWorldMatrix(), bone.getWorldMatrix());
  72677. }
  72678. else {
  72679. if (initialSkinMatrix) {
  72680. bone.getLocalMatrix().multiplyToRef(initialSkinMatrix, bone.getWorldMatrix());
  72681. }
  72682. else {
  72683. bone.getWorldMatrix().copyFrom(bone.getLocalMatrix());
  72684. }
  72685. }
  72686. if (bone._index !== -1) {
  72687. var mappedIndex = bone._index === null ? index : bone._index;
  72688. bone.getInvertedAbsoluteTransform().multiplyToArray(bone.getWorldMatrix(), targetMatrix, mappedIndex * 16);
  72689. }
  72690. }
  72691. this._identity.copyToArray(targetMatrix, this.bones.length * 16);
  72692. };
  72693. Skeleton.prototype.prepare = function () {
  72694. if (!this._isDirty) {
  72695. return;
  72696. }
  72697. if (this.needInitialSkinMatrix) {
  72698. for (var index = 0; index < this._meshesWithPoseMatrix.length; index++) {
  72699. var mesh = this._meshesWithPoseMatrix[index];
  72700. var poseMatrix = mesh.getPoseMatrix();
  72701. if (!mesh._bonesTransformMatrices || mesh._bonesTransformMatrices.length !== 16 * (this.bones.length + 1)) {
  72702. mesh._bonesTransformMatrices = new Float32Array(16 * (this.bones.length + 1));
  72703. }
  72704. if (this._synchronizedWithMesh !== mesh) {
  72705. this._synchronizedWithMesh = mesh;
  72706. // Prepare bones
  72707. for (var boneIndex = 0; boneIndex < this.bones.length; boneIndex++) {
  72708. var bone = this.bones[boneIndex];
  72709. if (!bone.getParent()) {
  72710. var matrix = bone.getBaseMatrix();
  72711. matrix.multiplyToRef(poseMatrix, BABYLON.Tmp.Matrix[1]);
  72712. bone._updateDifferenceMatrix(BABYLON.Tmp.Matrix[1]);
  72713. }
  72714. }
  72715. }
  72716. this._computeTransformMatrices(mesh._bonesTransformMatrices, poseMatrix);
  72717. }
  72718. }
  72719. else {
  72720. if (!this._transformMatrices || this._transformMatrices.length !== 16 * (this.bones.length + 1)) {
  72721. this._transformMatrices = new Float32Array(16 * (this.bones.length + 1));
  72722. }
  72723. this._computeTransformMatrices(this._transformMatrices, null);
  72724. }
  72725. this._isDirty = false;
  72726. this._scene._activeBones.addCount(this.bones.length, false);
  72727. };
  72728. Skeleton.prototype.getAnimatables = function () {
  72729. if (!this._animatables || this._animatables.length !== this.bones.length) {
  72730. this._animatables = [];
  72731. for (var index = 0; index < this.bones.length; index++) {
  72732. this._animatables.push(this.bones[index]);
  72733. }
  72734. }
  72735. return this._animatables;
  72736. };
  72737. Skeleton.prototype.clone = function (name, id) {
  72738. var result = new Skeleton(name, id || name, this._scene);
  72739. result.needInitialSkinMatrix = this.needInitialSkinMatrix;
  72740. for (var index = 0; index < this.bones.length; index++) {
  72741. var source = this.bones[index];
  72742. var parentBone = null;
  72743. var parent_1 = source.getParent();
  72744. if (parent_1) {
  72745. var parentIndex = this.bones.indexOf(parent_1);
  72746. parentBone = result.bones[parentIndex];
  72747. }
  72748. var bone = new BABYLON.Bone(source.name, result, parentBone, source.getBaseMatrix().clone(), source.getRestPose().clone());
  72749. BABYLON.Tools.DeepCopy(source.animations, bone.animations);
  72750. }
  72751. if (this._ranges) {
  72752. result._ranges = {};
  72753. for (var rangeName in this._ranges) {
  72754. var range = this._ranges[rangeName];
  72755. if (range) {
  72756. result._ranges[rangeName] = range.clone();
  72757. }
  72758. }
  72759. }
  72760. this._isDirty = true;
  72761. return result;
  72762. };
  72763. Skeleton.prototype.enableBlending = function (blendingSpeed) {
  72764. if (blendingSpeed === void 0) { blendingSpeed = 0.01; }
  72765. this.bones.forEach(function (bone) {
  72766. bone.animations.forEach(function (animation) {
  72767. animation.enableBlending = true;
  72768. animation.blendingSpeed = blendingSpeed;
  72769. });
  72770. });
  72771. };
  72772. Skeleton.prototype.dispose = function () {
  72773. this._meshesWithPoseMatrix = [];
  72774. // Animations
  72775. this.getScene().stopAnimation(this);
  72776. // Remove from scene
  72777. this.getScene().removeSkeleton(this);
  72778. };
  72779. Skeleton.prototype.serialize = function () {
  72780. var serializationObject = {};
  72781. serializationObject.name = this.name;
  72782. serializationObject.id = this.id;
  72783. serializationObject.dimensionsAtRest = this.dimensionsAtRest;
  72784. serializationObject.bones = [];
  72785. serializationObject.needInitialSkinMatrix = this.needInitialSkinMatrix;
  72786. for (var index = 0; index < this.bones.length; index++) {
  72787. var bone = this.bones[index];
  72788. var parent_2 = bone.getParent();
  72789. var serializedBone = {
  72790. parentBoneIndex: parent_2 ? this.bones.indexOf(parent_2) : -1,
  72791. name: bone.name,
  72792. matrix: bone.getBaseMatrix().toArray(),
  72793. rest: bone.getRestPose().toArray()
  72794. };
  72795. serializationObject.bones.push(serializedBone);
  72796. if (bone.length) {
  72797. serializedBone.length = bone.length;
  72798. }
  72799. if (bone.animations && bone.animations.length > 0) {
  72800. serializedBone.animation = bone.animations[0].serialize();
  72801. }
  72802. serializationObject.ranges = [];
  72803. for (var name in this._ranges) {
  72804. var source = this._ranges[name];
  72805. if (!source) {
  72806. continue;
  72807. }
  72808. var range = {};
  72809. range.name = name;
  72810. range.from = source.from;
  72811. range.to = source.to;
  72812. serializationObject.ranges.push(range);
  72813. }
  72814. }
  72815. return serializationObject;
  72816. };
  72817. Skeleton.Parse = function (parsedSkeleton, scene) {
  72818. var skeleton = new Skeleton(parsedSkeleton.name, parsedSkeleton.id, scene);
  72819. if (parsedSkeleton.dimensionsAtRest) {
  72820. skeleton.dimensionsAtRest = BABYLON.Vector3.FromArray(parsedSkeleton.dimensionsAtRest);
  72821. }
  72822. skeleton.needInitialSkinMatrix = parsedSkeleton.needInitialSkinMatrix;
  72823. var index;
  72824. for (index = 0; index < parsedSkeleton.bones.length; index++) {
  72825. var parsedBone = parsedSkeleton.bones[index];
  72826. var parentBone = null;
  72827. if (parsedBone.parentBoneIndex > -1) {
  72828. parentBone = skeleton.bones[parsedBone.parentBoneIndex];
  72829. }
  72830. var rest = parsedBone.rest ? BABYLON.Matrix.FromArray(parsedBone.rest) : null;
  72831. var bone = new BABYLON.Bone(parsedBone.name, skeleton, parentBone, BABYLON.Matrix.FromArray(parsedBone.matrix), rest);
  72832. if (parsedBone.length) {
  72833. bone.length = parsedBone.length;
  72834. }
  72835. if (parsedBone.animation) {
  72836. bone.animations.push(BABYLON.Animation.Parse(parsedBone.animation));
  72837. }
  72838. }
  72839. // placed after bones, so createAnimationRange can cascade down
  72840. if (parsedSkeleton.ranges) {
  72841. for (index = 0; index < parsedSkeleton.ranges.length; index++) {
  72842. var data = parsedSkeleton.ranges[index];
  72843. skeleton.createAnimationRange(data.name, data.from, data.to);
  72844. }
  72845. }
  72846. return skeleton;
  72847. };
  72848. Skeleton.prototype.computeAbsoluteTransforms = function (forceUpdate) {
  72849. if (forceUpdate === void 0) { forceUpdate = false; }
  72850. var renderId = this._scene.getRenderId();
  72851. if (this._lastAbsoluteTransformsUpdateId != renderId || forceUpdate) {
  72852. this.bones[0].computeAbsoluteTransforms();
  72853. this._lastAbsoluteTransformsUpdateId = renderId;
  72854. }
  72855. };
  72856. Skeleton.prototype.getPoseMatrix = function () {
  72857. var poseMatrix = null;
  72858. if (this._meshesWithPoseMatrix.length > 0) {
  72859. poseMatrix = this._meshesWithPoseMatrix[0].getPoseMatrix();
  72860. }
  72861. return poseMatrix;
  72862. };
  72863. Skeleton.prototype.sortBones = function () {
  72864. var bones = new Array();
  72865. var visited = new Array(this.bones.length);
  72866. for (var index = 0; index < this.bones.length; index++) {
  72867. this._sortBones(index, bones, visited);
  72868. }
  72869. this.bones = bones;
  72870. };
  72871. Skeleton.prototype._sortBones = function (index, bones, visited) {
  72872. if (visited[index]) {
  72873. return;
  72874. }
  72875. visited[index] = true;
  72876. var bone = this.bones[index];
  72877. if (bone._index === undefined) {
  72878. bone._index = index;
  72879. }
  72880. var parentBone = bone.getParent();
  72881. if (parentBone) {
  72882. this._sortBones(this.bones.indexOf(parentBone), bones, visited);
  72883. }
  72884. bones.push(bone);
  72885. };
  72886. return Skeleton;
  72887. }());
  72888. BABYLON.Skeleton = Skeleton;
  72889. })(BABYLON || (BABYLON = {}));
  72890. //# sourceMappingURL=babylon.skeleton.js.map
  72891. var BABYLON;
  72892. (function (BABYLON) {
  72893. var SphericalPolynomial = /** @class */ (function () {
  72894. function SphericalPolynomial() {
  72895. this.x = BABYLON.Vector3.Zero();
  72896. this.y = BABYLON.Vector3.Zero();
  72897. this.z = BABYLON.Vector3.Zero();
  72898. this.xx = BABYLON.Vector3.Zero();
  72899. this.yy = BABYLON.Vector3.Zero();
  72900. this.zz = BABYLON.Vector3.Zero();
  72901. this.xy = BABYLON.Vector3.Zero();
  72902. this.yz = BABYLON.Vector3.Zero();
  72903. this.zx = BABYLON.Vector3.Zero();
  72904. }
  72905. SphericalPolynomial.prototype.addAmbient = function (color) {
  72906. var colorVector = new BABYLON.Vector3(color.r, color.g, color.b);
  72907. this.xx = this.xx.add(colorVector);
  72908. this.yy = this.yy.add(colorVector);
  72909. this.zz = this.zz.add(colorVector);
  72910. };
  72911. SphericalPolynomial.getSphericalPolynomialFromHarmonics = function (harmonics) {
  72912. var result = new SphericalPolynomial();
  72913. result.x = harmonics.L11.scale(1.02333);
  72914. result.y = harmonics.L1_1.scale(1.02333);
  72915. result.z = harmonics.L10.scale(1.02333);
  72916. result.xx = harmonics.L00.scale(0.886277).subtract(harmonics.L20.scale(0.247708)).add(harmonics.L22.scale(0.429043));
  72917. result.yy = harmonics.L00.scale(0.886277).subtract(harmonics.L20.scale(0.247708)).subtract(harmonics.L22.scale(0.429043));
  72918. result.zz = harmonics.L00.scale(0.886277).add(harmonics.L20.scale(0.495417));
  72919. result.yz = harmonics.L2_1.scale(0.858086);
  72920. result.zx = harmonics.L21.scale(0.858086);
  72921. result.xy = harmonics.L2_2.scale(0.858086);
  72922. result.scale(1.0 / Math.PI);
  72923. return result;
  72924. };
  72925. SphericalPolynomial.prototype.scale = function (scale) {
  72926. this.x = this.x.scale(scale);
  72927. this.y = this.y.scale(scale);
  72928. this.z = this.z.scale(scale);
  72929. this.xx = this.xx.scale(scale);
  72930. this.yy = this.yy.scale(scale);
  72931. this.zz = this.zz.scale(scale);
  72932. this.yz = this.yz.scale(scale);
  72933. this.zx = this.zx.scale(scale);
  72934. this.xy = this.xy.scale(scale);
  72935. };
  72936. return SphericalPolynomial;
  72937. }());
  72938. BABYLON.SphericalPolynomial = SphericalPolynomial;
  72939. var SphericalHarmonics = /** @class */ (function () {
  72940. function SphericalHarmonics() {
  72941. this.L00 = BABYLON.Vector3.Zero();
  72942. this.L1_1 = BABYLON.Vector3.Zero();
  72943. this.L10 = BABYLON.Vector3.Zero();
  72944. this.L11 = BABYLON.Vector3.Zero();
  72945. this.L2_2 = BABYLON.Vector3.Zero();
  72946. this.L2_1 = BABYLON.Vector3.Zero();
  72947. this.L20 = BABYLON.Vector3.Zero();
  72948. this.L21 = BABYLON.Vector3.Zero();
  72949. this.L22 = BABYLON.Vector3.Zero();
  72950. }
  72951. SphericalHarmonics.prototype.addLight = function (direction, color, deltaSolidAngle) {
  72952. var colorVector = new BABYLON.Vector3(color.r, color.g, color.b);
  72953. var c = colorVector.scale(deltaSolidAngle);
  72954. this.L00 = this.L00.add(c.scale(0.282095));
  72955. this.L1_1 = this.L1_1.add(c.scale(0.488603 * direction.y));
  72956. this.L10 = this.L10.add(c.scale(0.488603 * direction.z));
  72957. this.L11 = this.L11.add(c.scale(0.488603 * direction.x));
  72958. this.L2_2 = this.L2_2.add(c.scale(1.092548 * direction.x * direction.y));
  72959. this.L2_1 = this.L2_1.add(c.scale(1.092548 * direction.y * direction.z));
  72960. this.L21 = this.L21.add(c.scale(1.092548 * direction.x * direction.z));
  72961. this.L20 = this.L20.add(c.scale(0.315392 * (3.0 * direction.z * direction.z - 1.0)));
  72962. this.L22 = this.L22.add(c.scale(0.546274 * (direction.x * direction.x - direction.y * direction.y)));
  72963. };
  72964. SphericalHarmonics.prototype.scale = function (scale) {
  72965. this.L00 = this.L00.scale(scale);
  72966. this.L1_1 = this.L1_1.scale(scale);
  72967. this.L10 = this.L10.scale(scale);
  72968. this.L11 = this.L11.scale(scale);
  72969. this.L2_2 = this.L2_2.scale(scale);
  72970. this.L2_1 = this.L2_1.scale(scale);
  72971. this.L20 = this.L20.scale(scale);
  72972. this.L21 = this.L21.scale(scale);
  72973. this.L22 = this.L22.scale(scale);
  72974. };
  72975. SphericalHarmonics.prototype.convertIncidentRadianceToIrradiance = function () {
  72976. // Convert from incident radiance (Li) to irradiance (E) by applying convolution with the cosine-weighted hemisphere.
  72977. //
  72978. // E_lm = A_l * L_lm
  72979. //
  72980. // In spherical harmonics this convolution amounts to scaling factors for each frequency band.
  72981. // This corresponds to equation 5 in "An Efficient Representation for Irradiance Environment Maps", where
  72982. // the scaling factors are given in equation 9.
  72983. // Constant (Band 0)
  72984. this.L00 = this.L00.scale(3.141593);
  72985. // Linear (Band 1)
  72986. this.L1_1 = this.L1_1.scale(2.094395);
  72987. this.L10 = this.L10.scale(2.094395);
  72988. this.L11 = this.L11.scale(2.094395);
  72989. // Quadratic (Band 2)
  72990. this.L2_2 = this.L2_2.scale(0.785398);
  72991. this.L2_1 = this.L2_1.scale(0.785398);
  72992. this.L20 = this.L20.scale(0.785398);
  72993. this.L21 = this.L21.scale(0.785398);
  72994. this.L22 = this.L22.scale(0.785398);
  72995. };
  72996. SphericalHarmonics.prototype.convertIrradianceToLambertianRadiance = function () {
  72997. // Convert from irradiance to outgoing radiance for Lambertian BDRF, suitable for efficient shader evaluation.
  72998. // L = (1/pi) * E * rho
  72999. //
  73000. // This is done by an additional scale by 1/pi, so is a fairly trivial operation but important conceptually.
  73001. this.scale(1.0 / Math.PI);
  73002. // The resultant SH now represents outgoing radiance, so includes the Lambert 1/pi normalisation factor but without albedo (rho) applied
  73003. // (The pixel shader must apply albedo after texture fetches, etc).
  73004. };
  73005. SphericalHarmonics.getsphericalHarmonicsFromPolynomial = function (polynomial) {
  73006. var result = new SphericalHarmonics();
  73007. result.L00 = polynomial.xx.scale(0.376127).add(polynomial.yy.scale(0.376127)).add(polynomial.zz.scale(0.376126));
  73008. result.L1_1 = polynomial.y.scale(0.977204);
  73009. result.L10 = polynomial.z.scale(0.977204);
  73010. result.L11 = polynomial.x.scale(0.977204);
  73011. result.L2_2 = polynomial.xy.scale(1.16538);
  73012. result.L2_1 = polynomial.yz.scale(1.16538);
  73013. result.L20 = polynomial.zz.scale(1.34567).subtract(polynomial.xx.scale(0.672834)).subtract(polynomial.yy.scale(0.672834));
  73014. result.L21 = polynomial.zx.scale(1.16538);
  73015. result.L22 = polynomial.xx.scale(1.16538).subtract(polynomial.yy.scale(1.16538));
  73016. result.scale(Math.PI);
  73017. return result;
  73018. };
  73019. return SphericalHarmonics;
  73020. }());
  73021. BABYLON.SphericalHarmonics = SphericalHarmonics;
  73022. })(BABYLON || (BABYLON = {}));
  73023. //# sourceMappingURL=babylon.sphericalPolynomial.js.map
  73024. var BABYLON;
  73025. (function (BABYLON) {
  73026. var FileFaceOrientation = /** @class */ (function () {
  73027. function FileFaceOrientation(name, worldAxisForNormal, worldAxisForFileX, worldAxisForFileY) {
  73028. this.name = name;
  73029. this.worldAxisForNormal = worldAxisForNormal;
  73030. this.worldAxisForFileX = worldAxisForFileX;
  73031. this.worldAxisForFileY = worldAxisForFileY;
  73032. }
  73033. return FileFaceOrientation;
  73034. }());
  73035. ;
  73036. /**
  73037. * Helper class dealing with the extraction of spherical polynomial dataArray
  73038. * from a cube map.
  73039. */
  73040. var CubeMapToSphericalPolynomialTools = /** @class */ (function () {
  73041. function CubeMapToSphericalPolynomialTools() {
  73042. }
  73043. /**
  73044. * Converts a texture to the according Spherical Polynomial data.
  73045. * This extracts the first 3 orders only as they are the only one used in the lighting.
  73046. *
  73047. * @param texture The texture to extract the information from.
  73048. * @return The Spherical Polynomial data.
  73049. */
  73050. CubeMapToSphericalPolynomialTools.ConvertCubeMapTextureToSphericalPolynomial = function (texture) {
  73051. if (!texture.isCube) {
  73052. // Only supports cube Textures currently.
  73053. return null;
  73054. }
  73055. var size = texture.getSize().width;
  73056. var right = texture.readPixels(0);
  73057. var left = texture.readPixels(1);
  73058. var up;
  73059. var down;
  73060. if (texture.isRenderTarget) {
  73061. up = texture.readPixels(3);
  73062. down = texture.readPixels(2);
  73063. }
  73064. else {
  73065. up = texture.readPixels(2);
  73066. down = texture.readPixels(3);
  73067. }
  73068. var front = texture.readPixels(4);
  73069. var back = texture.readPixels(5);
  73070. var gammaSpace = texture.gammaSpace;
  73071. // Always read as RGBA.
  73072. var format = BABYLON.Engine.TEXTUREFORMAT_RGBA;
  73073. var type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  73074. if (texture.textureType && texture.textureType !== BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT) {
  73075. type = BABYLON.Engine.TEXTURETYPE_FLOAT;
  73076. }
  73077. var cubeInfo = {
  73078. size: size,
  73079. right: right,
  73080. left: left,
  73081. up: up,
  73082. down: down,
  73083. front: front,
  73084. back: back,
  73085. format: format,
  73086. type: type,
  73087. gammaSpace: gammaSpace,
  73088. };
  73089. return this.ConvertCubeMapToSphericalPolynomial(cubeInfo);
  73090. };
  73091. /**
  73092. * Converts a cubemap to the according Spherical Polynomial data.
  73093. * This extracts the first 3 orders only as they are the only one used in the lighting.
  73094. *
  73095. * @param cubeInfo The Cube map to extract the information from.
  73096. * @return The Spherical Polynomial data.
  73097. */
  73098. CubeMapToSphericalPolynomialTools.ConvertCubeMapToSphericalPolynomial = function (cubeInfo) {
  73099. var sphericalHarmonics = new BABYLON.SphericalHarmonics();
  73100. var totalSolidAngle = 0.0;
  73101. // The (u,v) range is [-1,+1], so the distance between each texel is 2/Size.
  73102. var du = 2.0 / cubeInfo.size;
  73103. var dv = du;
  73104. // The (u,v) of the first texel is half a texel from the corner (-1,-1).
  73105. var minUV = du * 0.5 - 1.0;
  73106. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  73107. var fileFace = this.FileFaces[faceIndex];
  73108. var dataArray = cubeInfo[fileFace.name];
  73109. var v = minUV;
  73110. // TODO: we could perform the summation directly into a SphericalPolynomial (SP), which is more efficient than SphericalHarmonic (SH).
  73111. // This is possible because during the summation we do not need the SH-specific properties, e.g. orthogonality.
  73112. // Because SP is still linear, so summation is fine in that basis.
  73113. var stride = cubeInfo.format === BABYLON.Engine.TEXTUREFORMAT_RGBA ? 4 : 3;
  73114. for (var y = 0; y < cubeInfo.size; y++) {
  73115. var u = minUV;
  73116. for (var x = 0; x < cubeInfo.size; x++) {
  73117. // World direction (not normalised)
  73118. var worldDirection = fileFace.worldAxisForFileX.scale(u).add(fileFace.worldAxisForFileY.scale(v)).add(fileFace.worldAxisForNormal);
  73119. worldDirection.normalize();
  73120. var deltaSolidAngle = Math.pow(1.0 + u * u + v * v, -3.0 / 2.0);
  73121. var r = dataArray[(y * cubeInfo.size * stride) + (x * stride) + 0];
  73122. var g = dataArray[(y * cubeInfo.size * stride) + (x * stride) + 1];
  73123. var b = dataArray[(y * cubeInfo.size * stride) + (x * stride) + 2];
  73124. // Handle Integer types.
  73125. if (cubeInfo.type === BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT) {
  73126. r /= 255;
  73127. g /= 255;
  73128. b /= 255;
  73129. }
  73130. // Handle Gamma space textures.
  73131. if (cubeInfo.gammaSpace) {
  73132. r = Math.pow(BABYLON.Scalar.Clamp(r), BABYLON.ToLinearSpace);
  73133. g = Math.pow(BABYLON.Scalar.Clamp(g), BABYLON.ToLinearSpace);
  73134. b = Math.pow(BABYLON.Scalar.Clamp(b), BABYLON.ToLinearSpace);
  73135. }
  73136. var color = new BABYLON.Color3(r, g, b);
  73137. sphericalHarmonics.addLight(worldDirection, color, deltaSolidAngle);
  73138. totalSolidAngle += deltaSolidAngle;
  73139. u += du;
  73140. }
  73141. v += dv;
  73142. }
  73143. }
  73144. // Solid angle for entire sphere is 4*pi
  73145. var sphereSolidAngle = 4.0 * Math.PI;
  73146. // Adjust the solid angle to allow for how many faces we processed.
  73147. var facesProcessed = 6.0;
  73148. var expectedSolidAngle = sphereSolidAngle * facesProcessed / 6.0;
  73149. // Adjust the harmonics so that the accumulated solid angle matches the expected solid angle.
  73150. // This is needed because the numerical integration over the cube uses a
  73151. // small angle approximation of solid angle for each texel (see deltaSolidAngle),
  73152. // and also to compensate for accumulative error due to float precision in the summation.
  73153. var correctionFactor = expectedSolidAngle / totalSolidAngle;
  73154. sphericalHarmonics.scale(correctionFactor);
  73155. sphericalHarmonics.convertIncidentRadianceToIrradiance();
  73156. sphericalHarmonics.convertIrradianceToLambertianRadiance();
  73157. return BABYLON.SphericalPolynomial.getSphericalPolynomialFromHarmonics(sphericalHarmonics);
  73158. };
  73159. CubeMapToSphericalPolynomialTools.FileFaces = [
  73160. new FileFaceOrientation("right", new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, 0, -1), new BABYLON.Vector3(0, -1, 0)),
  73161. new FileFaceOrientation("left", new BABYLON.Vector3(-1, 0, 0), new BABYLON.Vector3(0, 0, 1), new BABYLON.Vector3(0, -1, 0)),
  73162. new FileFaceOrientation("up", new BABYLON.Vector3(0, 1, 0), new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, 0, 1)),
  73163. new FileFaceOrientation("down", new BABYLON.Vector3(0, -1, 0), new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, 0, -1)),
  73164. new FileFaceOrientation("front", new BABYLON.Vector3(0, 0, 1), new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, -1, 0)),
  73165. new FileFaceOrientation("back", new BABYLON.Vector3(0, 0, -1), new BABYLON.Vector3(-1, 0, 0), new BABYLON.Vector3(0, -1, 0)) // -Z bottom
  73166. ];
  73167. return CubeMapToSphericalPolynomialTools;
  73168. }());
  73169. BABYLON.CubeMapToSphericalPolynomialTools = CubeMapToSphericalPolynomialTools;
  73170. })(BABYLON || (BABYLON = {}));
  73171. //# sourceMappingURL=babylon.cubemapToSphericalPolynomial.js.map
  73172. var BABYLON;
  73173. (function (BABYLON) {
  73174. /**
  73175. * Helper class usefull to convert panorama picture to their cubemap representation in 6 faces.
  73176. */
  73177. var PanoramaToCubeMapTools = /** @class */ (function () {
  73178. function PanoramaToCubeMapTools() {
  73179. }
  73180. /**
  73181. * Converts a panorma stored in RGB right to left up to down format into a cubemap (6 faces).
  73182. *
  73183. * @param float32Array The source data.
  73184. * @param inputWidth The width of the input panorama.
  73185. * @param inputhHeight The height of the input panorama.
  73186. * @param size The willing size of the generated cubemap (each faces will be size * size pixels)
  73187. * @return The cubemap data
  73188. */
  73189. PanoramaToCubeMapTools.ConvertPanoramaToCubemap = function (float32Array, inputWidth, inputHeight, size) {
  73190. if (!float32Array) {
  73191. throw "ConvertPanoramaToCubemap: input cannot be null";
  73192. }
  73193. if (float32Array.length != inputWidth * inputHeight * 3) {
  73194. throw "ConvertPanoramaToCubemap: input size is wrong";
  73195. }
  73196. var textureFront = this.CreateCubemapTexture(size, this.FACE_FRONT, float32Array, inputWidth, inputHeight);
  73197. var textureBack = this.CreateCubemapTexture(size, this.FACE_BACK, float32Array, inputWidth, inputHeight);
  73198. var textureLeft = this.CreateCubemapTexture(size, this.FACE_LEFT, float32Array, inputWidth, inputHeight);
  73199. var textureRight = this.CreateCubemapTexture(size, this.FACE_RIGHT, float32Array, inputWidth, inputHeight);
  73200. var textureUp = this.CreateCubemapTexture(size, this.FACE_UP, float32Array, inputWidth, inputHeight);
  73201. var textureDown = this.CreateCubemapTexture(size, this.FACE_DOWN, float32Array, inputWidth, inputHeight);
  73202. return {
  73203. front: textureFront,
  73204. back: textureBack,
  73205. left: textureLeft,
  73206. right: textureRight,
  73207. up: textureUp,
  73208. down: textureDown,
  73209. size: size,
  73210. type: BABYLON.Engine.TEXTURETYPE_FLOAT,
  73211. format: BABYLON.Engine.TEXTUREFORMAT_RGB,
  73212. gammaSpace: false,
  73213. };
  73214. };
  73215. PanoramaToCubeMapTools.CreateCubemapTexture = function (texSize, faceData, float32Array, inputWidth, inputHeight) {
  73216. var buffer = new ArrayBuffer(texSize * texSize * 4 * 3);
  73217. var textureArray = new Float32Array(buffer);
  73218. var rotDX1 = faceData[1].subtract(faceData[0]).scale(1 / texSize);
  73219. var rotDX2 = faceData[3].subtract(faceData[2]).scale(1 / texSize);
  73220. var dy = 1 / texSize;
  73221. var fy = 0;
  73222. for (var y = 0; y < texSize; y++) {
  73223. var xv1 = faceData[0];
  73224. var xv2 = faceData[2];
  73225. for (var x = 0; x < texSize; x++) {
  73226. var v = xv2.subtract(xv1).scale(fy).add(xv1);
  73227. v.normalize();
  73228. var color = this.CalcProjectionSpherical(v, float32Array, inputWidth, inputHeight);
  73229. // 3 channels per pixels
  73230. textureArray[y * texSize * 3 + (x * 3) + 0] = color.r;
  73231. textureArray[y * texSize * 3 + (x * 3) + 1] = color.g;
  73232. textureArray[y * texSize * 3 + (x * 3) + 2] = color.b;
  73233. xv1 = xv1.add(rotDX1);
  73234. xv2 = xv2.add(rotDX2);
  73235. }
  73236. fy += dy;
  73237. }
  73238. return textureArray;
  73239. };
  73240. PanoramaToCubeMapTools.CalcProjectionSpherical = function (vDir, float32Array, inputWidth, inputHeight) {
  73241. var theta = Math.atan2(vDir.z, vDir.x);
  73242. var phi = Math.acos(vDir.y);
  73243. while (theta < -Math.PI)
  73244. theta += 2 * Math.PI;
  73245. while (theta > Math.PI)
  73246. theta -= 2 * Math.PI;
  73247. var dx = theta / Math.PI;
  73248. var dy = phi / Math.PI;
  73249. // recenter.
  73250. dx = dx * 0.5 + 0.5;
  73251. var px = Math.round(dx * inputWidth);
  73252. if (px < 0)
  73253. px = 0;
  73254. else if (px >= inputWidth)
  73255. px = inputWidth - 1;
  73256. var py = Math.round(dy * inputHeight);
  73257. if (py < 0)
  73258. py = 0;
  73259. else if (py >= inputHeight)
  73260. py = inputHeight - 1;
  73261. var inputY = (inputHeight - py - 1);
  73262. var r = float32Array[inputY * inputWidth * 3 + (px * 3) + 0];
  73263. var g = float32Array[inputY * inputWidth * 3 + (px * 3) + 1];
  73264. var b = float32Array[inputY * inputWidth * 3 + (px * 3) + 2];
  73265. return {
  73266. r: r,
  73267. g: g,
  73268. b: b
  73269. };
  73270. };
  73271. PanoramaToCubeMapTools.FACE_FRONT = [
  73272. new BABYLON.Vector3(-1.0, -1.0, -1.0),
  73273. new BABYLON.Vector3(1.0, -1.0, -1.0),
  73274. new BABYLON.Vector3(-1.0, 1.0, -1.0),
  73275. new BABYLON.Vector3(1.0, 1.0, -1.0)
  73276. ];
  73277. PanoramaToCubeMapTools.FACE_BACK = [
  73278. new BABYLON.Vector3(1.0, -1.0, 1.0),
  73279. new BABYLON.Vector3(-1.0, -1.0, 1.0),
  73280. new BABYLON.Vector3(1.0, 1.0, 1.0),
  73281. new BABYLON.Vector3(-1.0, 1.0, 1.0)
  73282. ];
  73283. PanoramaToCubeMapTools.FACE_RIGHT = [
  73284. new BABYLON.Vector3(1.0, -1.0, -1.0),
  73285. new BABYLON.Vector3(1.0, -1.0, 1.0),
  73286. new BABYLON.Vector3(1.0, 1.0, -1.0),
  73287. new BABYLON.Vector3(1.0, 1.0, 1.0)
  73288. ];
  73289. PanoramaToCubeMapTools.FACE_LEFT = [
  73290. new BABYLON.Vector3(-1.0, -1.0, 1.0),
  73291. new BABYLON.Vector3(-1.0, -1.0, -1.0),
  73292. new BABYLON.Vector3(-1.0, 1.0, 1.0),
  73293. new BABYLON.Vector3(-1.0, 1.0, -1.0)
  73294. ];
  73295. PanoramaToCubeMapTools.FACE_DOWN = [
  73296. new BABYLON.Vector3(-1.0, 1.0, -1.0),
  73297. new BABYLON.Vector3(1.0, 1.0, -1.0),
  73298. new BABYLON.Vector3(-1.0, 1.0, 1.0),
  73299. new BABYLON.Vector3(1.0, 1.0, 1.0)
  73300. ];
  73301. PanoramaToCubeMapTools.FACE_UP = [
  73302. new BABYLON.Vector3(-1.0, -1.0, 1.0),
  73303. new BABYLON.Vector3(1.0, -1.0, 1.0),
  73304. new BABYLON.Vector3(-1.0, -1.0, -1.0),
  73305. new BABYLON.Vector3(1.0, -1.0, -1.0)
  73306. ];
  73307. return PanoramaToCubeMapTools;
  73308. }());
  73309. BABYLON.PanoramaToCubeMapTools = PanoramaToCubeMapTools;
  73310. })(BABYLON || (BABYLON = {}));
  73311. //# sourceMappingURL=babylon.panoramaToCubemap.js.map
  73312. var BABYLON;
  73313. (function (BABYLON) {
  73314. ;
  73315. /**
  73316. * This groups tools to convert HDR texture to native colors array.
  73317. */
  73318. var HDRTools = /** @class */ (function () {
  73319. function HDRTools() {
  73320. }
  73321. HDRTools.Ldexp = function (mantissa, exponent) {
  73322. if (exponent > 1023) {
  73323. return mantissa * Math.pow(2, 1023) * Math.pow(2, exponent - 1023);
  73324. }
  73325. if (exponent < -1074) {
  73326. return mantissa * Math.pow(2, -1074) * Math.pow(2, exponent + 1074);
  73327. }
  73328. return mantissa * Math.pow(2, exponent);
  73329. };
  73330. HDRTools.Rgbe2float = function (float32array, red, green, blue, exponent, index) {
  73331. if (exponent > 0) {
  73332. exponent = this.Ldexp(1.0, exponent - (128 + 8));
  73333. float32array[index + 0] = red * exponent;
  73334. float32array[index + 1] = green * exponent;
  73335. float32array[index + 2] = blue * exponent;
  73336. }
  73337. else {
  73338. float32array[index + 0] = 0;
  73339. float32array[index + 1] = 0;
  73340. float32array[index + 2] = 0;
  73341. }
  73342. };
  73343. HDRTools.readStringLine = function (uint8array, startIndex) {
  73344. var line = "";
  73345. var character = "";
  73346. for (var i = startIndex; i < uint8array.length - startIndex; i++) {
  73347. character = String.fromCharCode(uint8array[i]);
  73348. if (character == "\n") {
  73349. break;
  73350. }
  73351. line += character;
  73352. }
  73353. return line;
  73354. };
  73355. /**
  73356. * Reads header information from an RGBE texture stored in a native array.
  73357. * More information on this format are available here:
  73358. * https://en.wikipedia.org/wiki/RGBE_image_format
  73359. *
  73360. * @param uint8array The binary file stored in native array.
  73361. * @return The header information.
  73362. */
  73363. HDRTools.RGBE_ReadHeader = function (uint8array) {
  73364. var height = 0;
  73365. var width = 0;
  73366. var line = this.readStringLine(uint8array, 0);
  73367. if (line[0] != '#' || line[1] != '?') {
  73368. throw "Bad HDR Format.";
  73369. }
  73370. var endOfHeader = false;
  73371. var findFormat = false;
  73372. var lineIndex = 0;
  73373. do {
  73374. lineIndex += (line.length + 1);
  73375. line = this.readStringLine(uint8array, lineIndex);
  73376. if (line == "FORMAT=32-bit_rle_rgbe") {
  73377. findFormat = true;
  73378. }
  73379. else if (line.length == 0) {
  73380. endOfHeader = true;
  73381. }
  73382. } while (!endOfHeader);
  73383. if (!findFormat) {
  73384. throw "HDR Bad header format, unsupported FORMAT";
  73385. }
  73386. lineIndex += (line.length + 1);
  73387. line = this.readStringLine(uint8array, lineIndex);
  73388. var sizeRegexp = /^\-Y (.*) \+X (.*)$/g;
  73389. var match = sizeRegexp.exec(line);
  73390. // TODO. Support +Y and -X if needed.
  73391. if (!match || match.length < 3) {
  73392. throw "HDR Bad header format, no size";
  73393. }
  73394. width = parseInt(match[2]);
  73395. height = parseInt(match[1]);
  73396. if (width < 8 || width > 0x7fff) {
  73397. throw "HDR Bad header format, unsupported size";
  73398. }
  73399. lineIndex += (line.length + 1);
  73400. return {
  73401. height: height,
  73402. width: width,
  73403. dataPosition: lineIndex
  73404. };
  73405. };
  73406. /**
  73407. * Returns the cubemap information (each faces texture data) extracted from an RGBE texture.
  73408. * This RGBE texture needs to store the information as a panorama.
  73409. *
  73410. * More information on this format are available here:
  73411. * https://en.wikipedia.org/wiki/RGBE_image_format
  73412. *
  73413. * @param buffer The binary file stored in an array buffer.
  73414. * @param size The expected size of the extracted cubemap.
  73415. * @return The Cube Map information.
  73416. */
  73417. HDRTools.GetCubeMapTextureData = function (buffer, size) {
  73418. var uint8array = new Uint8Array(buffer);
  73419. var hdrInfo = this.RGBE_ReadHeader(uint8array);
  73420. var data = this.RGBE_ReadPixels_RLE(uint8array, hdrInfo);
  73421. var cubeMapData = BABYLON.PanoramaToCubeMapTools.ConvertPanoramaToCubemap(data, hdrInfo.width, hdrInfo.height, size);
  73422. return cubeMapData;
  73423. };
  73424. /**
  73425. * Returns the pixels data extracted from an RGBE texture.
  73426. * This pixels will be stored left to right up to down in the R G B order in one array.
  73427. *
  73428. * More information on this format are available here:
  73429. * https://en.wikipedia.org/wiki/RGBE_image_format
  73430. *
  73431. * @param uint8array The binary file stored in an array buffer.
  73432. * @param hdrInfo The header information of the file.
  73433. * @return The pixels data in RGB right to left up to down order.
  73434. */
  73435. HDRTools.RGBE_ReadPixels = function (uint8array, hdrInfo) {
  73436. // Keep for multi format supports.
  73437. return this.RGBE_ReadPixels_RLE(uint8array, hdrInfo);
  73438. };
  73439. HDRTools.RGBE_ReadPixels_RLE = function (uint8array, hdrInfo) {
  73440. var num_scanlines = hdrInfo.height;
  73441. var scanline_width = hdrInfo.width;
  73442. var a, b, c, d, count;
  73443. var dataIndex = hdrInfo.dataPosition;
  73444. var index = 0, endIndex = 0, i = 0;
  73445. var scanLineArrayBuffer = new ArrayBuffer(scanline_width * 4); // four channel R G B E
  73446. var scanLineArray = new Uint8Array(scanLineArrayBuffer);
  73447. // 3 channels of 4 bytes per pixel in float.
  73448. var resultBuffer = new ArrayBuffer(hdrInfo.width * hdrInfo.height * 4 * 3);
  73449. var resultArray = new Float32Array(resultBuffer);
  73450. // read in each successive scanline
  73451. while (num_scanlines > 0) {
  73452. a = uint8array[dataIndex++];
  73453. b = uint8array[dataIndex++];
  73454. c = uint8array[dataIndex++];
  73455. d = uint8array[dataIndex++];
  73456. if (a != 2 || b != 2 || (c & 0x80)) {
  73457. // this file is not run length encoded
  73458. throw "HDR Bad header format, not RLE";
  73459. }
  73460. if (((c << 8) | d) != scanline_width) {
  73461. throw "HDR Bad header format, wrong scan line width";
  73462. }
  73463. index = 0;
  73464. // read each of the four channels for the scanline into the buffer
  73465. for (i = 0; i < 4; i++) {
  73466. endIndex = (i + 1) * scanline_width;
  73467. while (index < endIndex) {
  73468. a = uint8array[dataIndex++];
  73469. b = uint8array[dataIndex++];
  73470. if (a > 128) {
  73471. // a run of the same value
  73472. count = a - 128;
  73473. if ((count == 0) || (count > endIndex - index)) {
  73474. throw "HDR Bad Format, bad scanline data (run)";
  73475. }
  73476. while (count-- > 0) {
  73477. scanLineArray[index++] = b;
  73478. }
  73479. }
  73480. else {
  73481. // a non-run
  73482. count = a;
  73483. if ((count == 0) || (count > endIndex - index)) {
  73484. throw "HDR Bad Format, bad scanline data (non-run)";
  73485. }
  73486. scanLineArray[index++] = b;
  73487. if (--count > 0) {
  73488. for (var j = 0; j < count; j++) {
  73489. scanLineArray[index++] = uint8array[dataIndex++];
  73490. }
  73491. }
  73492. }
  73493. }
  73494. }
  73495. // now convert data from buffer into floats
  73496. for (i = 0; i < scanline_width; i++) {
  73497. a = scanLineArray[i];
  73498. b = scanLineArray[i + scanline_width];
  73499. c = scanLineArray[i + 2 * scanline_width];
  73500. d = scanLineArray[i + 3 * scanline_width];
  73501. this.Rgbe2float(resultArray, a, b, c, d, (hdrInfo.height - num_scanlines) * scanline_width * 3 + i * 3);
  73502. }
  73503. num_scanlines--;
  73504. }
  73505. return resultArray;
  73506. };
  73507. return HDRTools;
  73508. }());
  73509. BABYLON.HDRTools = HDRTools;
  73510. })(BABYLON || (BABYLON = {}));
  73511. //# sourceMappingURL=babylon.hdr.js.map
  73512. var BABYLON;
  73513. (function (BABYLON) {
  73514. /**
  73515. * This represents a texture coming from an HDR input.
  73516. *
  73517. * The only supported format is currently panorama picture stored in RGBE format.
  73518. * Example of such files can be found on HDRLib: http://hdrlib.com/
  73519. */
  73520. var HDRCubeTexture = /** @class */ (function (_super) {
  73521. __extends(HDRCubeTexture, _super);
  73522. /**
  73523. * Instantiates an HDRTexture from the following parameters.
  73524. *
  73525. * @param url The location of the HDR raw data (Panorama stored in RGBE format)
  73526. * @param scene The scene the texture will be used in
  73527. * @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.
  73528. * @param noMipmap Forces to not generate the mipmap if true
  73529. * @param generateHarmonics Specifies whether you want to extract the polynomial harmonics during the generation process
  73530. * @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)
  73531. * @param usePMREMGenerator Specifies whether or not to generate the CubeMap through CubeMapGen to avoid seams issue at run time.
  73532. */
  73533. function HDRCubeTexture(url, scene, size, noMipmap, generateHarmonics, useInGammaSpace, usePMREMGenerator, onLoad, onError) {
  73534. if (noMipmap === void 0) { noMipmap = false; }
  73535. if (generateHarmonics === void 0) { generateHarmonics = true; }
  73536. if (useInGammaSpace === void 0) { useInGammaSpace = false; }
  73537. if (usePMREMGenerator === void 0) { usePMREMGenerator = false; }
  73538. if (onLoad === void 0) { onLoad = null; }
  73539. if (onError === void 0) { onError = null; }
  73540. var _this = _super.call(this, scene) || this;
  73541. _this._useInGammaSpace = false;
  73542. _this._generateHarmonics = true;
  73543. _this._isBABYLONPreprocessed = false;
  73544. _this._onLoad = null;
  73545. _this._onError = null;
  73546. /**
  73547. * The texture coordinates mode. As this texture is stored in a cube format, please modify carefully.
  73548. */
  73549. _this.coordinatesMode = BABYLON.Texture.CUBIC_MODE;
  73550. /**
  73551. * Specifies wether the texture has been generated through the PMREMGenerator tool.
  73552. * This is usefull at run time to apply the good shader.
  73553. */
  73554. _this.isPMREM = false;
  73555. _this._isBlocking = true;
  73556. /**
  73557. * Gets or sets the center of the bounding box associated with the cube texture
  73558. * It must define where the camera used to render the texture was set
  73559. */
  73560. _this.boundingBoxPosition = BABYLON.Vector3.Zero();
  73561. if (!url) {
  73562. return _this;
  73563. }
  73564. _this.name = url;
  73565. _this.url = url;
  73566. _this.hasAlpha = false;
  73567. _this.isCube = true;
  73568. _this._textureMatrix = BABYLON.Matrix.Identity();
  73569. _this._onLoad = onLoad;
  73570. _this._onError = onError;
  73571. _this.gammaSpace = false;
  73572. var caps = scene.getEngine().getCaps();
  73573. if (size) {
  73574. _this._isBABYLONPreprocessed = false;
  73575. _this._noMipmap = noMipmap;
  73576. _this._size = size;
  73577. _this._useInGammaSpace = useInGammaSpace;
  73578. _this._usePMREMGenerator = usePMREMGenerator &&
  73579. caps.textureLOD &&
  73580. caps.textureFloat &&
  73581. !_this._useInGammaSpace;
  73582. }
  73583. else {
  73584. _this._isBABYLONPreprocessed = true;
  73585. _this._noMipmap = false;
  73586. _this._useInGammaSpace = false;
  73587. _this._usePMREMGenerator = caps.textureLOD && caps.textureFloat &&
  73588. !_this._useInGammaSpace;
  73589. }
  73590. _this.isPMREM = _this._usePMREMGenerator;
  73591. _this._texture = _this._getFromCache(url, _this._noMipmap);
  73592. if (!_this._texture) {
  73593. if (!scene.useDelayedTextureLoading) {
  73594. _this.loadTexture();
  73595. }
  73596. else {
  73597. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  73598. }
  73599. }
  73600. return _this;
  73601. }
  73602. Object.defineProperty(HDRCubeTexture.prototype, "isBlocking", {
  73603. /**
  73604. * Gets wether or not the texture is blocking during loading.
  73605. */
  73606. get: function () {
  73607. return this._isBlocking;
  73608. },
  73609. /**
  73610. * Sets wether or not the texture is blocking during loading.
  73611. */
  73612. set: function (value) {
  73613. this._isBlocking = value;
  73614. },
  73615. enumerable: true,
  73616. configurable: true
  73617. });
  73618. Object.defineProperty(HDRCubeTexture.prototype, "boundingBoxSize", {
  73619. get: function () {
  73620. return this._boundingBoxSize;
  73621. },
  73622. /**
  73623. * Gets or sets the size of the bounding box associated with the cube texture
  73624. * When defined, the cubemap will switch to local mode
  73625. * @see https://community.arm.com/graphics/b/blog/posts/reflections-based-on-local-cubemaps-in-unity
  73626. * @example https://www.babylonjs-playground.com/#RNASML
  73627. */
  73628. set: function (value) {
  73629. if (this._boundingBoxSize && this._boundingBoxSize.equals(value)) {
  73630. return;
  73631. }
  73632. this._boundingBoxSize = value;
  73633. var scene = this.getScene();
  73634. if (scene) {
  73635. scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  73636. }
  73637. },
  73638. enumerable: true,
  73639. configurable: true
  73640. });
  73641. /**
  73642. * Occurs when the file is a preprocessed .babylon.hdr file.
  73643. */
  73644. HDRCubeTexture.prototype.loadBabylonTexture = function () {
  73645. var _this = this;
  73646. var mipLevels = 0;
  73647. var floatArrayView = null;
  73648. var scene = this.getScene();
  73649. var mipmapGenerator = (!this._useInGammaSpace && scene && scene.getEngine().getCaps().textureFloat) ? function (data) {
  73650. var mips = new Array();
  73651. if (!floatArrayView) {
  73652. return mips;
  73653. }
  73654. var startIndex = 30;
  73655. for (var level = 0; level < mipLevels; level++) {
  73656. mips.push([]);
  73657. // Fill each pixel of the mip level.
  73658. var faceSize = Math.pow(_this._size >> level, 2) * 3;
  73659. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  73660. var faceData = floatArrayView.subarray(startIndex, startIndex + faceSize);
  73661. mips[level].push(faceData);
  73662. startIndex += faceSize;
  73663. }
  73664. }
  73665. return mips;
  73666. } : null;
  73667. var callback = function (buffer) {
  73668. var scene = _this.getScene();
  73669. if (!scene) {
  73670. return null;
  73671. }
  73672. // Create Native Array Views
  73673. var intArrayView = new Int32Array(buffer);
  73674. floatArrayView = new Float32Array(buffer);
  73675. // Fill header.
  73676. var version = intArrayView[0]; // Version 1. (MAy be use in case of format changes for backward compaibility)
  73677. _this._size = intArrayView[1]; // CubeMap max mip face size.
  73678. // Update Texture Information.
  73679. if (!_this._texture) {
  73680. return null;
  73681. }
  73682. _this._texture.updateSize(_this._size, _this._size);
  73683. // Fill polynomial information.
  73684. var sphericalPolynomial = new BABYLON.SphericalPolynomial();
  73685. sphericalPolynomial.x.copyFromFloats(floatArrayView[2], floatArrayView[3], floatArrayView[4]);
  73686. sphericalPolynomial.y.copyFromFloats(floatArrayView[5], floatArrayView[6], floatArrayView[7]);
  73687. sphericalPolynomial.z.copyFromFloats(floatArrayView[8], floatArrayView[9], floatArrayView[10]);
  73688. sphericalPolynomial.xx.copyFromFloats(floatArrayView[11], floatArrayView[12], floatArrayView[13]);
  73689. sphericalPolynomial.yy.copyFromFloats(floatArrayView[14], floatArrayView[15], floatArrayView[16]);
  73690. sphericalPolynomial.zz.copyFromFloats(floatArrayView[17], floatArrayView[18], floatArrayView[19]);
  73691. sphericalPolynomial.xy.copyFromFloats(floatArrayView[20], floatArrayView[21], floatArrayView[22]);
  73692. sphericalPolynomial.yz.copyFromFloats(floatArrayView[23], floatArrayView[24], floatArrayView[25]);
  73693. sphericalPolynomial.zx.copyFromFloats(floatArrayView[26], floatArrayView[27], floatArrayView[28]);
  73694. _this.sphericalPolynomial = sphericalPolynomial;
  73695. // Fill pixel data.
  73696. mipLevels = intArrayView[29]; // Number of mip levels.
  73697. var startIndex = 30;
  73698. var data = [];
  73699. var faceSize = Math.pow(_this._size, 2) * 3;
  73700. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  73701. data.push(floatArrayView.subarray(startIndex, startIndex + faceSize));
  73702. startIndex += faceSize;
  73703. }
  73704. var results = [];
  73705. var byteArray = null;
  73706. // Push each faces.
  73707. for (var k = 0; k < 6; k++) {
  73708. var dataFace = null;
  73709. // To be deprecated.
  73710. if (version === 1) {
  73711. var j = ([0, 2, 4, 1, 3, 5])[k]; // Transforms +X+Y+Z... to +X-X+Y-Y...
  73712. dataFace = data[j];
  73713. }
  73714. // If special cases.
  73715. if (!mipmapGenerator && dataFace) {
  73716. if (!scene.getEngine().getCaps().textureFloat) {
  73717. // 3 channels of 1 bytes per pixel in bytes.
  73718. var byteBuffer = new ArrayBuffer(faceSize);
  73719. byteArray = new Uint8Array(byteBuffer);
  73720. }
  73721. for (var i = 0; i < _this._size * _this._size; i++) {
  73722. // Put in gamma space if requested.
  73723. if (_this._useInGammaSpace) {
  73724. dataFace[(i * 3) + 0] = Math.pow(dataFace[(i * 3) + 0], BABYLON.ToGammaSpace);
  73725. dataFace[(i * 3) + 1] = Math.pow(dataFace[(i * 3) + 1], BABYLON.ToGammaSpace);
  73726. dataFace[(i * 3) + 2] = Math.pow(dataFace[(i * 3) + 2], BABYLON.ToGammaSpace);
  73727. }
  73728. // Convert to int texture for fallback.
  73729. if (byteArray) {
  73730. var r = Math.max(dataFace[(i * 3) + 0] * 255, 0);
  73731. var g = Math.max(dataFace[(i * 3) + 1] * 255, 0);
  73732. var b = Math.max(dataFace[(i * 3) + 2] * 255, 0);
  73733. // May use luminance instead if the result is not accurate.
  73734. var max = Math.max(Math.max(r, g), b);
  73735. if (max > 255) {
  73736. var scale = 255 / max;
  73737. r *= scale;
  73738. g *= scale;
  73739. b *= scale;
  73740. }
  73741. byteArray[(i * 3) + 0] = r;
  73742. byteArray[(i * 3) + 1] = g;
  73743. byteArray[(i * 3) + 2] = b;
  73744. }
  73745. }
  73746. }
  73747. // Fill the array accordingly.
  73748. if (byteArray) {
  73749. results.push(byteArray);
  73750. }
  73751. else {
  73752. results.push(dataFace);
  73753. }
  73754. }
  73755. return results;
  73756. };
  73757. if (scene) {
  73758. 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);
  73759. }
  73760. };
  73761. /**
  73762. * Occurs when the file is raw .hdr file.
  73763. */
  73764. HDRCubeTexture.prototype.loadHDRTexture = function () {
  73765. var _this = this;
  73766. var callback = function (buffer) {
  73767. var scene = _this.getScene();
  73768. if (!scene) {
  73769. return null;
  73770. }
  73771. // Extract the raw linear data.
  73772. var data = BABYLON.HDRTools.GetCubeMapTextureData(buffer, _this._size);
  73773. // Generate harmonics if needed.
  73774. if (_this._generateHarmonics) {
  73775. var sphericalPolynomial = BABYLON.CubeMapToSphericalPolynomialTools.ConvertCubeMapToSphericalPolynomial(data);
  73776. _this.sphericalPolynomial = sphericalPolynomial;
  73777. }
  73778. var results = [];
  73779. var byteArray = null;
  73780. // Push each faces.
  73781. for (var j = 0; j < 6; j++) {
  73782. // Create uintarray fallback.
  73783. if (!scene.getEngine().getCaps().textureFloat) {
  73784. // 3 channels of 1 bytes per pixel in bytes.
  73785. var byteBuffer = new ArrayBuffer(_this._size * _this._size * 3);
  73786. byteArray = new Uint8Array(byteBuffer);
  73787. }
  73788. var dataFace = (data[HDRCubeTexture._facesMapping[j]]);
  73789. // If special cases.
  73790. if (_this._useInGammaSpace || byteArray) {
  73791. for (var i = 0; i < _this._size * _this._size; i++) {
  73792. // Put in gamma space if requested.
  73793. if (_this._useInGammaSpace) {
  73794. dataFace[(i * 3) + 0] = Math.pow(dataFace[(i * 3) + 0], BABYLON.ToGammaSpace);
  73795. dataFace[(i * 3) + 1] = Math.pow(dataFace[(i * 3) + 1], BABYLON.ToGammaSpace);
  73796. dataFace[(i * 3) + 2] = Math.pow(dataFace[(i * 3) + 2], BABYLON.ToGammaSpace);
  73797. }
  73798. // Convert to int texture for fallback.
  73799. if (byteArray) {
  73800. var r = Math.max(dataFace[(i * 3) + 0] * 255, 0);
  73801. var g = Math.max(dataFace[(i * 3) + 1] * 255, 0);
  73802. var b = Math.max(dataFace[(i * 3) + 2] * 255, 0);
  73803. // May use luminance instead if the result is not accurate.
  73804. var max = Math.max(Math.max(r, g), b);
  73805. if (max > 255) {
  73806. var scale = 255 / max;
  73807. r *= scale;
  73808. g *= scale;
  73809. b *= scale;
  73810. }
  73811. byteArray[(i * 3) + 0] = r;
  73812. byteArray[(i * 3) + 1] = g;
  73813. byteArray[(i * 3) + 2] = b;
  73814. }
  73815. }
  73816. }
  73817. if (byteArray) {
  73818. results.push(byteArray);
  73819. }
  73820. else {
  73821. results.push(dataFace);
  73822. }
  73823. }
  73824. return results;
  73825. };
  73826. var mipmapGenerator = null;
  73827. // TODO. Implement In code PMREM Generator following the LYS toolset generation.
  73828. // if (!this._noMipmap &&
  73829. // this._usePMREMGenerator) {
  73830. // mipmapGenerator = (data: ArrayBufferView[]) => {
  73831. // // Custom setup of the generator matching with the PBR shader values.
  73832. // var generator = new BABYLON.PMREMGenerator(data,
  73833. // this._size,
  73834. // this._size,
  73835. // 0,
  73836. // 3,
  73837. // this.getScene().getEngine().getCaps().textureFloat,
  73838. // 2048,
  73839. // 0.25,
  73840. // false,
  73841. // true);
  73842. // return generator.filterCubeMap();
  73843. // };
  73844. // }
  73845. var scene = this.getScene();
  73846. if (scene) {
  73847. 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);
  73848. }
  73849. };
  73850. /**
  73851. * Starts the loading process of the texture.
  73852. */
  73853. HDRCubeTexture.prototype.loadTexture = function () {
  73854. if (this._isBABYLONPreprocessed) {
  73855. this.loadBabylonTexture();
  73856. }
  73857. else {
  73858. this.loadHDRTexture();
  73859. }
  73860. };
  73861. HDRCubeTexture.prototype.clone = function () {
  73862. var scene = this.getScene();
  73863. if (!scene) {
  73864. return this;
  73865. }
  73866. var size = (this._isBABYLONPreprocessed ? null : this._size);
  73867. var newTexture = new HDRCubeTexture(this.url, scene, size, this._noMipmap, this._generateHarmonics, this._useInGammaSpace, this._usePMREMGenerator);
  73868. // Base texture
  73869. newTexture.level = this.level;
  73870. newTexture.wrapU = this.wrapU;
  73871. newTexture.wrapV = this.wrapV;
  73872. newTexture.coordinatesIndex = this.coordinatesIndex;
  73873. newTexture.coordinatesMode = this.coordinatesMode;
  73874. return newTexture;
  73875. };
  73876. // Methods
  73877. HDRCubeTexture.prototype.delayLoad = function () {
  73878. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  73879. return;
  73880. }
  73881. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  73882. this._texture = this._getFromCache(this.url, this._noMipmap);
  73883. if (!this._texture) {
  73884. this.loadTexture();
  73885. }
  73886. };
  73887. HDRCubeTexture.prototype.getReflectionTextureMatrix = function () {
  73888. return this._textureMatrix;
  73889. };
  73890. HDRCubeTexture.prototype.setReflectionTextureMatrix = function (value) {
  73891. this._textureMatrix = value;
  73892. };
  73893. HDRCubeTexture.Parse = function (parsedTexture, scene, rootUrl) {
  73894. var texture = null;
  73895. if (parsedTexture.name && !parsedTexture.isRenderTarget) {
  73896. var size = parsedTexture.isBABYLONPreprocessed ? null : parsedTexture.size;
  73897. texture = new HDRCubeTexture(rootUrl + parsedTexture.name, scene, size, parsedTexture.noMipmap, parsedTexture.generateHarmonics, parsedTexture.useInGammaSpace, parsedTexture.usePMREMGenerator);
  73898. texture.name = parsedTexture.name;
  73899. texture.hasAlpha = parsedTexture.hasAlpha;
  73900. texture.level = parsedTexture.level;
  73901. texture.coordinatesMode = parsedTexture.coordinatesMode;
  73902. texture.isBlocking = parsedTexture.isBlocking;
  73903. }
  73904. if (texture) {
  73905. if (parsedTexture.boundingBoxPosition) {
  73906. texture.boundingBoxPosition = BABYLON.Vector3.FromArray(parsedTexture.boundingBoxPosition);
  73907. }
  73908. if (parsedTexture.boundingBoxSize) {
  73909. texture.boundingBoxSize = BABYLON.Vector3.FromArray(parsedTexture.boundingBoxSize);
  73910. }
  73911. }
  73912. return texture;
  73913. };
  73914. HDRCubeTexture.prototype.serialize = function () {
  73915. if (!this.name) {
  73916. return null;
  73917. }
  73918. var serializationObject = {};
  73919. serializationObject.name = this.name;
  73920. serializationObject.hasAlpha = this.hasAlpha;
  73921. serializationObject.isCube = true;
  73922. serializationObject.level = this.level;
  73923. serializationObject.size = this._size;
  73924. serializationObject.coordinatesMode = this.coordinatesMode;
  73925. serializationObject.useInGammaSpace = this._useInGammaSpace;
  73926. serializationObject.generateHarmonics = this._generateHarmonics;
  73927. serializationObject.usePMREMGenerator = this._usePMREMGenerator;
  73928. serializationObject.isBABYLONPreprocessed = this._isBABYLONPreprocessed;
  73929. serializationObject.customType = "BABYLON.HDRCubeTexture";
  73930. serializationObject.noMipmap = this._noMipmap;
  73931. serializationObject.isBlocking = this._isBlocking;
  73932. return serializationObject;
  73933. };
  73934. /**
  73935. * Saves as a file the data contained in the texture in a binary format.
  73936. * This can be used to prevent the long loading tie associated with creating the seamless texture as well
  73937. * as the spherical used in the lighting.
  73938. * @param url The HDR file url.
  73939. * @param size The size of the texture data to generate (one of the cubemap face desired width).
  73940. * @param onError Method called if any error happens during download.
  73941. * @return The packed binary data.
  73942. */
  73943. HDRCubeTexture.generateBabylonHDROnDisk = function (url, size, onError) {
  73944. if (onError === void 0) { onError = null; }
  73945. var callback = function (buffer) {
  73946. var data = new Blob([buffer], { type: 'application/octet-stream' });
  73947. // Returns a URL you can use as a href.
  73948. var objUrl = window.URL.createObjectURL(data);
  73949. // Simulates a link to it and click to dowload.
  73950. var a = document.createElement("a");
  73951. document.body.appendChild(a);
  73952. a.style.display = "none";
  73953. a.href = objUrl;
  73954. a.download = "envmap.babylon.hdr";
  73955. a.click();
  73956. };
  73957. HDRCubeTexture.generateBabylonHDR(url, size, callback, onError);
  73958. };
  73959. /**
  73960. * Serializes the data contained in the texture in a binary format.
  73961. * This can be used to prevent the long loading tie associated with creating the seamless texture as well
  73962. * as the spherical used in the lighting.
  73963. * @param url The HDR file url.
  73964. * @param size The size of the texture data to generate (one of the cubemap face desired width).
  73965. * @param onError Method called if any error happens during download.
  73966. * @return The packed binary data.
  73967. */
  73968. HDRCubeTexture.generateBabylonHDR = function (url, size, callback, onError) {
  73969. if (onError === void 0) { onError = null; }
  73970. // Needs the url tho create the texture.
  73971. if (!url) {
  73972. return;
  73973. }
  73974. // Check Power of two size.
  73975. if (!BABYLON.Tools.IsExponentOfTwo(size)) {
  73976. return;
  73977. }
  73978. // Coming Back in 3.x.
  73979. BABYLON.Tools.Error("Generation of Babylon HDR is coming back in 3.2.");
  73980. };
  73981. HDRCubeTexture._facesMapping = [
  73982. "right",
  73983. "left",
  73984. "up",
  73985. "down",
  73986. "front",
  73987. "back"
  73988. ];
  73989. return HDRCubeTexture;
  73990. }(BABYLON.BaseTexture));
  73991. BABYLON.HDRCubeTexture = HDRCubeTexture;
  73992. })(BABYLON || (BABYLON = {}));
  73993. //# sourceMappingURL=babylon.hdrCubeTexture.js.map
  73994. // All the credit goes to this project and the guy who's behind it https://github.com/mapbox/earcut
  73995. // Huge respect for a such great lib.
  73996. // Earcut license:
  73997. // Copyright (c) 2016, Mapbox
  73998. //
  73999. // Permission to use, copy, modify, and/or distribute this software for any purpose
  74000. // with or without fee is hereby granted, provided that the above copyright notice
  74001. // and this permission notice appear in all copies.
  74002. //
  74003. // THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH
  74004. // REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND
  74005. // FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,
  74006. // INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS
  74007. // OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER
  74008. // TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF
  74009. // THIS SOFTWARE.
  74010. var Earcut;
  74011. (function (Earcut) {
  74012. /**
  74013. * The fastest and smallest JavaScript polygon triangulation library for your WebGL apps
  74014. * @param data is a flat array of vertice coordinates like [x0, y0, x1, y1, x2, y2, ...].
  74015. * @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).
  74016. * @param dim is the number of coordinates per vertice in the input array (2 by default).
  74017. */
  74018. function earcut(data, holeIndices, dim) {
  74019. dim = dim || 2;
  74020. var hasHoles = holeIndices && holeIndices.length, outerLen = hasHoles ? holeIndices[0] * dim : data.length, outerNode = linkedList(data, 0, outerLen, dim, true), triangles = new Array();
  74021. if (!outerNode)
  74022. return triangles;
  74023. var minX = 0, minY = 0, maxX, maxY, x, y, size = 0;
  74024. if (hasHoles)
  74025. outerNode = eliminateHoles(data, holeIndices, outerNode, dim);
  74026. // if the shape is not too simple, we'll use z-order curve hash later; calculate polygon bbox
  74027. if (data.length > 80 * dim) {
  74028. minX = maxX = data[0];
  74029. minY = maxY = data[1];
  74030. for (var i = dim; i < outerLen; i += dim) {
  74031. x = data[i];
  74032. y = data[i + 1];
  74033. if (x < minX)
  74034. minX = x;
  74035. if (y < minY)
  74036. minY = y;
  74037. if (x > maxX)
  74038. maxX = x;
  74039. if (y > maxY)
  74040. maxY = y;
  74041. }
  74042. // minX, minY and size are later used to transform coords into integers for z-order calculation
  74043. size = Math.max(maxX - minX, maxY - minY);
  74044. }
  74045. earcutLinked(outerNode, triangles, dim, minX, minY, size, 0);
  74046. return triangles;
  74047. }
  74048. Earcut.earcut = earcut;
  74049. var Node = /** @class */ (function () {
  74050. function Node(i, x, y) {
  74051. this.i = i;
  74052. this.x = x;
  74053. this.y = y;
  74054. this.prev = null;
  74055. this.next = null;
  74056. this.z = null;
  74057. this.prevZ = null;
  74058. this.nextZ = null;
  74059. this.steiner = false;
  74060. }
  74061. return Node;
  74062. }());
  74063. // create a circular doubly linked list from polygon points in the specified winding order
  74064. function linkedList(data, start, end, dim, clockwise) {
  74065. var i, last = null;
  74066. if (clockwise === (signedArea(data, start, end, dim) > 0)) {
  74067. for (i = start; i < end; i += dim)
  74068. last = insertNode(i, data[i], data[i + 1], last);
  74069. }
  74070. else {
  74071. for (i = end - dim; i >= start; i -= dim)
  74072. last = insertNode(i, data[i], data[i + 1], last);
  74073. }
  74074. if (last && equals(last, last.next)) {
  74075. removeNode(last);
  74076. last = last.next;
  74077. }
  74078. return last;
  74079. }
  74080. // eliminate colinear or duplicate points
  74081. function filterPoints(start, end) {
  74082. if (!start)
  74083. return start;
  74084. if (!end)
  74085. end = start;
  74086. var p = start, again;
  74087. do {
  74088. again = false;
  74089. if (!p.steiner && (equals(p, p.next) || area(p.prev, p, p.next) === 0)) {
  74090. removeNode(p);
  74091. p = end = p.prev;
  74092. if (p === p.next)
  74093. return undefined;
  74094. again = true;
  74095. }
  74096. else {
  74097. p = p.next;
  74098. }
  74099. } while (again || p !== end);
  74100. return end;
  74101. }
  74102. // main ear slicing loop which triangulates a polygon (given as a linked list)
  74103. function earcutLinked(ear, triangles, dim, minX, minY, size, pass) {
  74104. if (!ear)
  74105. return;
  74106. // interlink polygon nodes in z-order
  74107. if (!pass && size)
  74108. indexCurve(ear, minX, minY, size);
  74109. var stop = ear, prev, next;
  74110. // iterate through ears, slicing them one by one
  74111. while (ear.prev !== ear.next) {
  74112. prev = ear.prev;
  74113. next = ear.next;
  74114. if (size ? isEarHashed(ear, minX, minY, size) : isEar(ear)) {
  74115. // cut off the triangle
  74116. triangles.push(prev.i / dim);
  74117. triangles.push(ear.i / dim);
  74118. triangles.push(next.i / dim);
  74119. removeNode(ear);
  74120. // skipping the next vertice leads to less sliver triangles
  74121. ear = next.next;
  74122. stop = next.next;
  74123. continue;
  74124. }
  74125. ear = next;
  74126. // if we looped through the whole remaining polygon and can't find any more ears
  74127. if (ear === stop) {
  74128. // try filtering points and slicing again
  74129. if (!pass) {
  74130. earcutLinked(filterPoints(ear, undefined), triangles, dim, minX, minY, size, 1);
  74131. // if this didn't work, try curing all small self-intersections locally
  74132. }
  74133. else if (pass === 1) {
  74134. ear = cureLocalIntersections(ear, triangles, dim);
  74135. earcutLinked(ear, triangles, dim, minX, minY, size, 2);
  74136. // as a last resort, try splitting the remaining polygon into two
  74137. }
  74138. else if (pass === 2) {
  74139. splitEarcut(ear, triangles, dim, minX, minY, size);
  74140. }
  74141. break;
  74142. }
  74143. }
  74144. }
  74145. // check whether a polygon node forms a valid ear with adjacent nodes
  74146. function isEar(ear) {
  74147. var a = ear.prev, b = ear, c = ear.next;
  74148. if (area(a, b, c) >= 0)
  74149. return false; // reflex, can't be an ear
  74150. // now make sure we don't have other points inside the potential ear
  74151. var p = ear.next.next;
  74152. while (p !== ear.prev) {
  74153. if (pointInTriangle(a.x, a.y, b.x, b.y, c.x, c.y, p.x, p.y) &&
  74154. area(p.prev, p, p.next) >= 0)
  74155. return false;
  74156. p = p.next;
  74157. }
  74158. return true;
  74159. }
  74160. function isEarHashed(ear, minX, minY, size) {
  74161. var a = ear.prev, b = ear, c = ear.next;
  74162. if (area(a, b, c) >= 0)
  74163. return false; // reflex, can't be an ear
  74164. // triangle bbox; min & max are calculated like this for speed
  74165. 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);
  74166. // z-order range for the current triangle bbox;
  74167. var minZ = zOrder(minTX, minTY, minX, minY, size), maxZ = zOrder(maxTX, maxTY, minX, minY, size);
  74168. // first look for points inside the triangle in increasing z-order
  74169. var p = ear.nextZ;
  74170. while (p && p.z <= maxZ) {
  74171. if (p !== ear.prev &&
  74172. p !== ear.next &&
  74173. pointInTriangle(a.x, a.y, b.x, b.y, c.x, c.y, p.x, p.y) &&
  74174. area(p.prev, p, p.next) >= 0)
  74175. return false;
  74176. p = p.nextZ;
  74177. }
  74178. // then look for points in decreasing z-order
  74179. p = ear.prevZ;
  74180. while (p && p.z >= minZ) {
  74181. if (p !== ear.prev &&
  74182. p !== ear.next &&
  74183. pointInTriangle(a.x, a.y, b.x, b.y, c.x, c.y, p.x, p.y) &&
  74184. area(p.prev, p, p.next) >= 0)
  74185. return false;
  74186. p = p.prevZ;
  74187. }
  74188. return true;
  74189. }
  74190. // go through all polygon nodes and cure small local self-intersections
  74191. function cureLocalIntersections(start, triangles, dim) {
  74192. var p = start;
  74193. do {
  74194. var a = p.prev, b = p.next.next;
  74195. if (!equals(a, b) && intersects(a, p, p.next, b) && locallyInside(a, b) && locallyInside(b, a)) {
  74196. triangles.push(a.i / dim);
  74197. triangles.push(p.i / dim);
  74198. triangles.push(b.i / dim);
  74199. // remove two nodes involved
  74200. removeNode(p);
  74201. removeNode(p.next);
  74202. p = start = b;
  74203. }
  74204. p = p.next;
  74205. } while (p !== start);
  74206. return p;
  74207. }
  74208. // try splitting polygon into two and triangulate them independently
  74209. function splitEarcut(start, triangles, dim, minX, minY, size) {
  74210. // look for a valid diagonal that divides the polygon into two
  74211. var a = start;
  74212. do {
  74213. var b = a.next.next;
  74214. while (b !== a.prev) {
  74215. if (a.i !== b.i && isValidDiagonal(a, b)) {
  74216. // split the polygon in two by the diagonal
  74217. var c = splitPolygon(a, b);
  74218. // filter colinear points around the cuts
  74219. a = filterPoints(a, a.next);
  74220. c = filterPoints(c, c.next);
  74221. // run earcut on each half
  74222. earcutLinked(a, triangles, dim, minX, minY, size, undefined);
  74223. earcutLinked(c, triangles, dim, minX, minY, size, undefined);
  74224. return;
  74225. }
  74226. b = b.next;
  74227. }
  74228. a = a.next;
  74229. } while (a !== start);
  74230. }
  74231. // link every hole into the outer loop, producing a single-ring polygon without holes
  74232. function eliminateHoles(data, holeIndices, outerNode, dim) {
  74233. var queue = [], i, len, start, end, list;
  74234. for (i = 0, len = holeIndices.length; i < len; i++) {
  74235. start = holeIndices[i] * dim;
  74236. end = i < len - 1 ? holeIndices[i + 1] * dim : data.length;
  74237. list = linkedList(data, start, end, dim, false);
  74238. if (list === list.next)
  74239. list.steiner = true;
  74240. queue.push(getLeftmost(list));
  74241. }
  74242. queue.sort(compareX);
  74243. // process holes from left to right
  74244. for (i = 0; i < queue.length; i++) {
  74245. eliminateHole(queue[i], outerNode);
  74246. outerNode = filterPoints(outerNode, outerNode.next);
  74247. }
  74248. return outerNode;
  74249. }
  74250. function compareX(a, b) {
  74251. return a.x - b.x;
  74252. }
  74253. // find a bridge between vertices that connects hole with an outer ring and and link it
  74254. function eliminateHole(hole, outerNode) {
  74255. outerNode = findHoleBridge(hole, outerNode);
  74256. if (outerNode) {
  74257. var b = splitPolygon(outerNode, hole);
  74258. filterPoints(b, b.next);
  74259. }
  74260. }
  74261. // David Eberly's algorithm for finding a bridge between hole and outer polygon
  74262. function findHoleBridge(hole, outerNode) {
  74263. var p = outerNode, hx = hole.x, hy = hole.y, qx = -Infinity, m;
  74264. // find a segment intersected by a ray from the hole's leftmost point to the left;
  74265. // segment's endpoint with lesser x will be potential connection point
  74266. do {
  74267. if (hy <= p.y && hy >= p.next.y) {
  74268. var x = p.x + (hy - p.y) * (p.next.x - p.x) / (p.next.y - p.y);
  74269. if (x <= hx && x > qx) {
  74270. qx = x;
  74271. if (x === hx) {
  74272. if (hy === p.y)
  74273. return p;
  74274. if (hy === p.next.y)
  74275. return p.next;
  74276. }
  74277. m = p.x < p.next.x ? p : p.next;
  74278. }
  74279. }
  74280. p = p.next;
  74281. } while (p !== outerNode);
  74282. if (!m)
  74283. return null;
  74284. if (hx === qx)
  74285. return m.prev; // hole touches outer segment; pick lower endpoint
  74286. // look for points inside the triangle of hole point, segment intersection and endpoint;
  74287. // if there are no points found, we have a valid connection;
  74288. // otherwise choose the point of the minimum angle with the ray as connection point
  74289. var stop = m, mx = m.x, my = m.y, tanMin = Infinity, tan;
  74290. p = m.next;
  74291. while (p !== stop) {
  74292. if (hx >= p.x &&
  74293. p.x >= mx &&
  74294. pointInTriangle(hy < my ? hx : qx, hy, mx, my, hy < my ? qx : hx, hy, p.x, p.y)) {
  74295. tan = Math.abs(hy - p.y) / (hx - p.x); // tangential
  74296. if ((tan < tanMin || (tan === tanMin && p.x > m.x)) && locallyInside(p, hole)) {
  74297. m = p;
  74298. tanMin = tan;
  74299. }
  74300. }
  74301. p = p.next;
  74302. }
  74303. return m;
  74304. }
  74305. // interlink polygon nodes in z-order
  74306. function indexCurve(start, minX, minY, size) {
  74307. var p = start;
  74308. do {
  74309. if (p.z === null)
  74310. p.z = zOrder(p.x, p.y, minX, minY, size);
  74311. p.prevZ = p.prev;
  74312. p.nextZ = p.next;
  74313. p = p.next;
  74314. } while (p !== start);
  74315. p.prevZ.nextZ = null;
  74316. p.prevZ = null;
  74317. sortLinked(p);
  74318. }
  74319. // Simon Tatham's linked list merge sort algorithm
  74320. // http://www.chiark.greenend.org.uk/~sgtatham/algorithms/listsort.html
  74321. function sortLinked(list) {
  74322. var i, p, q, e, tail, numMerges, pSize, qSize, inSize = 1;
  74323. do {
  74324. p = list;
  74325. list = null;
  74326. tail = null;
  74327. numMerges = 0;
  74328. while (p) {
  74329. numMerges++;
  74330. q = p;
  74331. pSize = 0;
  74332. for (i = 0; i < inSize; i++) {
  74333. pSize++;
  74334. q = q.nextZ;
  74335. if (!q)
  74336. break;
  74337. }
  74338. qSize = inSize;
  74339. while (pSize > 0 || (qSize > 0 && q)) {
  74340. if (pSize === 0) {
  74341. e = q;
  74342. q = q.nextZ;
  74343. qSize--;
  74344. }
  74345. else if (qSize === 0 || !q) {
  74346. e = p;
  74347. p = p.nextZ;
  74348. pSize--;
  74349. }
  74350. else if (p.z <= q.z) {
  74351. e = p;
  74352. p = p.nextZ;
  74353. pSize--;
  74354. }
  74355. else {
  74356. e = q;
  74357. q = q.nextZ;
  74358. qSize--;
  74359. }
  74360. if (tail)
  74361. tail.nextZ = e;
  74362. else
  74363. list = e;
  74364. e.prevZ = tail;
  74365. tail = e;
  74366. }
  74367. p = q;
  74368. }
  74369. tail.nextZ = null;
  74370. inSize *= 2;
  74371. } while (numMerges > 1);
  74372. return list;
  74373. }
  74374. // z-order of a point given coords and size of the data bounding box
  74375. function zOrder(x, y, minX, minY, size) {
  74376. // coords are transformed into non-negative 15-bit integer range
  74377. x = 32767 * (x - minX) / size;
  74378. y = 32767 * (y - minY) / size;
  74379. x = (x | (x << 8)) & 0x00FF00FF;
  74380. x = (x | (x << 4)) & 0x0F0F0F0F;
  74381. x = (x | (x << 2)) & 0x33333333;
  74382. x = (x | (x << 1)) & 0x55555555;
  74383. y = (y | (y << 8)) & 0x00FF00FF;
  74384. y = (y | (y << 4)) & 0x0F0F0F0F;
  74385. y = (y | (y << 2)) & 0x33333333;
  74386. y = (y | (y << 1)) & 0x55555555;
  74387. return x | (y << 1);
  74388. }
  74389. // find the leftmost node of a polygon ring
  74390. function getLeftmost(start) {
  74391. var p = start, leftmost = start;
  74392. do {
  74393. if (p.x < leftmost.x)
  74394. leftmost = p;
  74395. p = p.next;
  74396. } while (p !== start);
  74397. return leftmost;
  74398. }
  74399. // check if a point lies within a convex triangle
  74400. function pointInTriangle(ax, ay, bx, by, cx, cy, px, py) {
  74401. return (cx - px) * (ay - py) - (ax - px) * (cy - py) >= 0 &&
  74402. (ax - px) * (by - py) - (bx - px) * (ay - py) >= 0 &&
  74403. (bx - px) * (cy - py) - (cx - px) * (by - py) >= 0;
  74404. }
  74405. // check if a diagonal between two polygon nodes is valid (lies in polygon interior)
  74406. function isValidDiagonal(a, b) {
  74407. return a.next.i !== b.i &&
  74408. a.prev.i !== b.i &&
  74409. !intersectsPolygon(a, b) &&
  74410. locallyInside(a, b) &&
  74411. locallyInside(b, a) &&
  74412. middleInside(a, b);
  74413. }
  74414. // signed area of a triangle
  74415. function area(p, q, r) {
  74416. return (q.y - p.y) * (r.x - q.x) - (q.x - p.x) * (r.y - q.y);
  74417. }
  74418. // check if two points are equal
  74419. function equals(p1, p2) {
  74420. return p1.x === p2.x && p1.y === p2.y;
  74421. }
  74422. // check if two segments intersect
  74423. function intersects(p1, q1, p2, q2) {
  74424. if ((equals(p1, q1) && equals(p2, q2)) ||
  74425. (equals(p1, q2) && equals(p2, q1)))
  74426. return true;
  74427. return area(p1, q1, p2) > 0 !== area(p1, q1, q2) > 0 &&
  74428. area(p2, q2, p1) > 0 !== area(p2, q2, q1) > 0;
  74429. }
  74430. // check if a polygon diagonal intersects any polygon segments
  74431. function intersectsPolygon(a, b) {
  74432. var p = a;
  74433. do {
  74434. if (p.i !== a.i &&
  74435. p.next.i !== a.i &&
  74436. p.i !== b.i &&
  74437. p.next.i !== b.i &&
  74438. intersects(p, p.next, a, b))
  74439. return true;
  74440. p = p.next;
  74441. } while (p !== a);
  74442. return false;
  74443. }
  74444. // check if a polygon diagonal is locally inside the polygon
  74445. function locallyInside(a, b) {
  74446. return area(a.prev, a, a.next) < 0
  74447. ? area(a, b, a.next) >= 0 && area(a, a.prev, b) >= 0
  74448. : area(a, b, a.prev) < 0 || area(a, a.next, b) < 0;
  74449. }
  74450. // check if the middle point of a polygon diagonal is inside the polygon
  74451. function middleInside(a, b) {
  74452. var p = a, inside = false, px = (a.x + b.x) / 2, py = (a.y + b.y) / 2;
  74453. do {
  74454. if (((p.y > py) !== (p.next.y > py)) && (px < (p.next.x - p.x) * (py - p.y) / (p.next.y - p.y) + p.x))
  74455. inside = !inside;
  74456. p = p.next;
  74457. } while (p !== a);
  74458. return inside;
  74459. }
  74460. // link two polygon vertices with a bridge; if the vertices belong to the same ring, it splits polygon into two;
  74461. // if one belongs to the outer ring and another to a hole, it merges it into a single ring
  74462. function splitPolygon(a, b) {
  74463. 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;
  74464. a.next = b;
  74465. b.prev = a;
  74466. a2.next = an;
  74467. an.prev = a2;
  74468. b2.next = a2;
  74469. a2.prev = b2;
  74470. bp.next = b2;
  74471. b2.prev = bp;
  74472. return b2;
  74473. }
  74474. // create a node and optionally link it with previous one (in a circular doubly linked list)
  74475. function insertNode(i, x, y, last) {
  74476. var p = new Node(i, x, y);
  74477. if (!last) {
  74478. p.prev = p;
  74479. p.next = p;
  74480. }
  74481. else {
  74482. p.next = last.next;
  74483. p.prev = last;
  74484. last.next.prev = p;
  74485. last.next = p;
  74486. }
  74487. return p;
  74488. }
  74489. function removeNode(p) {
  74490. p.next.prev = p.prev;
  74491. p.prev.next = p.next;
  74492. if (p.prevZ)
  74493. p.prevZ.nextZ = p.nextZ;
  74494. if (p.nextZ)
  74495. p.nextZ.prevZ = p.prevZ;
  74496. }
  74497. /**
  74498. * return a percentage difference between the polygon area and its triangulation area;
  74499. * used to verify correctness of triangulation
  74500. */
  74501. function deviation(data, holeIndices, dim, triangles) {
  74502. var hasHoles = holeIndices && holeIndices.length;
  74503. var outerLen = hasHoles ? holeIndices[0] * dim : data.length;
  74504. var polygonArea = Math.abs(signedArea(data, 0, outerLen, dim));
  74505. if (hasHoles) {
  74506. for (var i = 0, len = holeIndices.length; i < len; i++) {
  74507. var start = holeIndices[i] * dim;
  74508. var end = i < len - 1 ? holeIndices[i + 1] * dim : data.length;
  74509. polygonArea -= Math.abs(signedArea(data, start, end, dim));
  74510. }
  74511. }
  74512. var trianglesArea = 0;
  74513. for (i = 0; i < triangles.length; i += 3) {
  74514. var a = triangles[i] * dim;
  74515. var b = triangles[i + 1] * dim;
  74516. var c = triangles[i + 2] * dim;
  74517. trianglesArea += Math.abs((data[a] - data[c]) * (data[b + 1] - data[a + 1]) -
  74518. (data[a] - data[b]) * (data[c + 1] - data[a + 1]));
  74519. }
  74520. return polygonArea === 0 && trianglesArea === 0 ? 0 : Math.abs((trianglesArea - polygonArea) / polygonArea);
  74521. }
  74522. Earcut.deviation = deviation;
  74523. ;
  74524. function signedArea(data, start, end, dim) {
  74525. var sum = 0;
  74526. for (var i = start, j = end - dim; i < end; i += dim) {
  74527. sum += (data[j] - data[i]) * (data[i + 1] + data[j + 1]);
  74528. j = i;
  74529. }
  74530. return sum;
  74531. }
  74532. /**
  74533. * turn a polygon in a multi-dimensional array form (e.g. as in GeoJSON) into a form Earcut accepts
  74534. */
  74535. function flatten(data) {
  74536. var dim = data[0][0].length, result = { vertices: new Array(), holes: new Array(), dimensions: dim }, holeIndex = 0;
  74537. for (var i = 0; i < data.length; i++) {
  74538. for (var j = 0; j < data[i].length; j++) {
  74539. for (var d = 0; d < dim; d++)
  74540. result.vertices.push(data[i][j][d]);
  74541. }
  74542. if (i > 0) {
  74543. holeIndex += data[i - 1].length;
  74544. result.holes.push(holeIndex);
  74545. }
  74546. }
  74547. return result;
  74548. }
  74549. Earcut.flatten = flatten;
  74550. ;
  74551. })(Earcut || (Earcut = {}));
  74552. //# sourceMappingURL=babylon.earcut.js.map
  74553. var BABYLON;
  74554. (function (BABYLON) {
  74555. var IndexedVector2 = /** @class */ (function (_super) {
  74556. __extends(IndexedVector2, _super);
  74557. function IndexedVector2(original, index) {
  74558. var _this = _super.call(this, original.x, original.y) || this;
  74559. _this.index = index;
  74560. return _this;
  74561. }
  74562. return IndexedVector2;
  74563. }(BABYLON.Vector2));
  74564. var PolygonPoints = /** @class */ (function () {
  74565. function PolygonPoints() {
  74566. this.elements = new Array();
  74567. }
  74568. PolygonPoints.prototype.add = function (originalPoints) {
  74569. var _this = this;
  74570. var result = new Array();
  74571. originalPoints.forEach(function (point) {
  74572. if (result.length === 0 || !point.equalsWithEpsilon(result[0])) {
  74573. var newPoint = new IndexedVector2(point, _this.elements.length);
  74574. result.push(newPoint);
  74575. _this.elements.push(newPoint);
  74576. }
  74577. });
  74578. return result;
  74579. };
  74580. PolygonPoints.prototype.computeBounds = function () {
  74581. var lmin = new BABYLON.Vector2(this.elements[0].x, this.elements[0].y);
  74582. var lmax = new BABYLON.Vector2(this.elements[0].x, this.elements[0].y);
  74583. this.elements.forEach(function (point) {
  74584. // x
  74585. if (point.x < lmin.x) {
  74586. lmin.x = point.x;
  74587. }
  74588. else if (point.x > lmax.x) {
  74589. lmax.x = point.x;
  74590. }
  74591. // y
  74592. if (point.y < lmin.y) {
  74593. lmin.y = point.y;
  74594. }
  74595. else if (point.y > lmax.y) {
  74596. lmax.y = point.y;
  74597. }
  74598. });
  74599. return {
  74600. min: lmin,
  74601. max: lmax,
  74602. width: lmax.x - lmin.x,
  74603. height: lmax.y - lmin.y
  74604. };
  74605. };
  74606. return PolygonPoints;
  74607. }());
  74608. var Polygon = /** @class */ (function () {
  74609. function Polygon() {
  74610. }
  74611. Polygon.Rectangle = function (xmin, ymin, xmax, ymax) {
  74612. return [
  74613. new BABYLON.Vector2(xmin, ymin),
  74614. new BABYLON.Vector2(xmax, ymin),
  74615. new BABYLON.Vector2(xmax, ymax),
  74616. new BABYLON.Vector2(xmin, ymax)
  74617. ];
  74618. };
  74619. Polygon.Circle = function (radius, cx, cy, numberOfSides) {
  74620. if (cx === void 0) { cx = 0; }
  74621. if (cy === void 0) { cy = 0; }
  74622. if (numberOfSides === void 0) { numberOfSides = 32; }
  74623. var result = new Array();
  74624. var angle = 0;
  74625. var increment = (Math.PI * 2) / numberOfSides;
  74626. for (var i = 0; i < numberOfSides; i++) {
  74627. result.push(new BABYLON.Vector2(cx + Math.cos(angle) * radius, cy + Math.sin(angle) * radius));
  74628. angle -= increment;
  74629. }
  74630. return result;
  74631. };
  74632. Polygon.Parse = function (input) {
  74633. var floats = input.split(/[^-+eE\.\d]+/).map(parseFloat).filter(function (val) { return (!isNaN(val)); });
  74634. var i, result = [];
  74635. for (i = 0; i < (floats.length & 0x7FFFFFFE); i += 2) {
  74636. result.push(new BABYLON.Vector2(floats[i], floats[i + 1]));
  74637. }
  74638. return result;
  74639. };
  74640. Polygon.StartingAt = function (x, y) {
  74641. return BABYLON.Path2.StartingAt(x, y);
  74642. };
  74643. return Polygon;
  74644. }());
  74645. BABYLON.Polygon = Polygon;
  74646. var PolygonMeshBuilder = /** @class */ (function () {
  74647. function PolygonMeshBuilder(name, contours, scene) {
  74648. this._points = new PolygonPoints();
  74649. this._outlinepoints = new PolygonPoints();
  74650. this._holes = new Array();
  74651. this._epoints = new Array();
  74652. this._eholes = new Array();
  74653. this._name = name;
  74654. this._scene = scene;
  74655. var points;
  74656. if (contours instanceof BABYLON.Path2) {
  74657. points = contours.getPoints();
  74658. }
  74659. else {
  74660. points = contours;
  74661. }
  74662. this._addToepoint(points);
  74663. this._points.add(points);
  74664. this._outlinepoints.add(points);
  74665. }
  74666. PolygonMeshBuilder.prototype._addToepoint = function (points) {
  74667. for (var _i = 0, points_1 = points; _i < points_1.length; _i++) {
  74668. var p = points_1[_i];
  74669. this._epoints.push(p.x, p.y);
  74670. }
  74671. };
  74672. PolygonMeshBuilder.prototype.addHole = function (hole) {
  74673. this._points.add(hole);
  74674. var holepoints = new PolygonPoints();
  74675. holepoints.add(hole);
  74676. this._holes.push(holepoints);
  74677. this._eholes.push(this._epoints.length / 2);
  74678. this._addToepoint(hole);
  74679. return this;
  74680. };
  74681. PolygonMeshBuilder.prototype.build = function (updatable, depth) {
  74682. var _this = this;
  74683. if (updatable === void 0) { updatable = false; }
  74684. if (depth === void 0) { depth = 0; }
  74685. var result = new BABYLON.Mesh(this._name, this._scene);
  74686. var normals = new Array();
  74687. var positions = new Array();
  74688. var uvs = new Array();
  74689. var bounds = this._points.computeBounds();
  74690. this._points.elements.forEach(function (p) {
  74691. normals.push(0, 1.0, 0);
  74692. positions.push(p.x, 0, p.y);
  74693. uvs.push((p.x - bounds.min.x) / bounds.width, (p.y - bounds.min.y) / bounds.height);
  74694. });
  74695. var indices = new Array();
  74696. var res = Earcut.earcut(this._epoints, this._eholes, 2);
  74697. for (var i = 0; i < res.length; i++) {
  74698. indices.push(res[i]);
  74699. }
  74700. if (depth > 0) {
  74701. var positionscount = (positions.length / 3); //get the current pointcount
  74702. this._points.elements.forEach(function (p) {
  74703. normals.push(0, -1.0, 0);
  74704. positions.push(p.x, -depth, p.y);
  74705. uvs.push(1 - (p.x - bounds.min.x) / bounds.width, 1 - (p.y - bounds.min.y) / bounds.height);
  74706. });
  74707. var totalCount = indices.length;
  74708. for (var i = 0; i < totalCount; i += 3) {
  74709. var i0 = indices[i + 0];
  74710. var i1 = indices[i + 1];
  74711. var i2 = indices[i + 2];
  74712. indices.push(i2 + positionscount);
  74713. indices.push(i1 + positionscount);
  74714. indices.push(i0 + positionscount);
  74715. }
  74716. //Add the sides
  74717. this.addSide(positions, normals, uvs, indices, bounds, this._outlinepoints, depth, false);
  74718. this._holes.forEach(function (hole) {
  74719. _this.addSide(positions, normals, uvs, indices, bounds, hole, depth, true);
  74720. });
  74721. }
  74722. result.setVerticesData(BABYLON.VertexBuffer.PositionKind, positions, updatable);
  74723. result.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals, updatable);
  74724. result.setVerticesData(BABYLON.VertexBuffer.UVKind, uvs, updatable);
  74725. result.setIndices(indices);
  74726. return result;
  74727. };
  74728. PolygonMeshBuilder.prototype.addSide = function (positions, normals, uvs, indices, bounds, points, depth, flip) {
  74729. var StartIndex = positions.length / 3;
  74730. var ulength = 0;
  74731. for (var i = 0; i < points.elements.length; i++) {
  74732. var p = points.elements[i];
  74733. var p1;
  74734. if ((i + 1) > points.elements.length - 1) {
  74735. p1 = points.elements[0];
  74736. }
  74737. else {
  74738. p1 = points.elements[i + 1];
  74739. }
  74740. positions.push(p.x, 0, p.y);
  74741. positions.push(p.x, -depth, p.y);
  74742. positions.push(p1.x, 0, p1.y);
  74743. positions.push(p1.x, -depth, p1.y);
  74744. var v1 = new BABYLON.Vector3(p.x, 0, p.y);
  74745. var v2 = new BABYLON.Vector3(p1.x, 0, p1.y);
  74746. var v3 = v2.subtract(v1);
  74747. var v4 = new BABYLON.Vector3(0, 1, 0);
  74748. var vn = BABYLON.Vector3.Cross(v3, v4);
  74749. vn = vn.normalize();
  74750. uvs.push(ulength / bounds.width, 0);
  74751. uvs.push(ulength / bounds.width, 1);
  74752. ulength += v3.length();
  74753. uvs.push((ulength / bounds.width), 0);
  74754. uvs.push((ulength / bounds.width), 1);
  74755. if (!flip) {
  74756. normals.push(-vn.x, -vn.y, -vn.z);
  74757. normals.push(-vn.x, -vn.y, -vn.z);
  74758. normals.push(-vn.x, -vn.y, -vn.z);
  74759. normals.push(-vn.x, -vn.y, -vn.z);
  74760. indices.push(StartIndex);
  74761. indices.push(StartIndex + 1);
  74762. indices.push(StartIndex + 2);
  74763. indices.push(StartIndex + 1);
  74764. indices.push(StartIndex + 3);
  74765. indices.push(StartIndex + 2);
  74766. }
  74767. else {
  74768. normals.push(vn.x, vn.y, vn.z);
  74769. normals.push(vn.x, vn.y, vn.z);
  74770. normals.push(vn.x, vn.y, vn.z);
  74771. normals.push(vn.x, vn.y, vn.z);
  74772. indices.push(StartIndex);
  74773. indices.push(StartIndex + 2);
  74774. indices.push(StartIndex + 1);
  74775. indices.push(StartIndex + 1);
  74776. indices.push(StartIndex + 2);
  74777. indices.push(StartIndex + 3);
  74778. }
  74779. StartIndex += 4;
  74780. }
  74781. ;
  74782. };
  74783. return PolygonMeshBuilder;
  74784. }());
  74785. BABYLON.PolygonMeshBuilder = PolygonMeshBuilder;
  74786. })(BABYLON || (BABYLON = {}));
  74787. //# sourceMappingURL=babylon.polygonMesh.js.map
  74788. var BABYLON;
  74789. (function (BABYLON) {
  74790. // Unique ID when we import meshes from Babylon to CSG
  74791. var currentCSGMeshId = 0;
  74792. // # class Vertex
  74793. // Represents a vertex of a polygon. Use your own vertex class instead of this
  74794. // one to provide additional features like texture coordinates and vertex
  74795. // colors. Custom vertex classes need to provide a `pos` property and `clone()`,
  74796. // `flip()`, and `interpolate()` methods that behave analogous to the ones
  74797. // defined by `BABYLON.CSG.Vertex`. This class provides `normal` so convenience
  74798. // functions like `BABYLON.CSG.sphere()` can return a smooth vertex normal, but `normal`
  74799. // is not used anywhere else.
  74800. // Same goes for uv, it allows to keep the original vertex uv coordinates of the 2 meshes
  74801. var Vertex = /** @class */ (function () {
  74802. function Vertex(pos, normal, uv) {
  74803. this.pos = pos;
  74804. this.normal = normal;
  74805. this.uv = uv;
  74806. }
  74807. Vertex.prototype.clone = function () {
  74808. return new Vertex(this.pos.clone(), this.normal.clone(), this.uv.clone());
  74809. };
  74810. // Invert all orientation-specific data (e.g. vertex normal). Called when the
  74811. // orientation of a polygon is flipped.
  74812. Vertex.prototype.flip = function () {
  74813. this.normal = this.normal.scale(-1);
  74814. };
  74815. // Create a new vertex between this vertex and `other` by linearly
  74816. // interpolating all properties using a parameter of `t`. Subclasses should
  74817. // override this to interpolate additional properties.
  74818. Vertex.prototype.interpolate = function (other, t) {
  74819. 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));
  74820. };
  74821. return Vertex;
  74822. }());
  74823. // # class Plane
  74824. // Represents a plane in 3D space.
  74825. var Plane = /** @class */ (function () {
  74826. function Plane(normal, w) {
  74827. this.normal = normal;
  74828. this.w = w;
  74829. }
  74830. Plane.FromPoints = function (a, b, c) {
  74831. var v0 = c.subtract(a);
  74832. var v1 = b.subtract(a);
  74833. if (v0.lengthSquared() === 0 || v1.lengthSquared() === 0) {
  74834. return null;
  74835. }
  74836. var n = BABYLON.Vector3.Normalize(BABYLON.Vector3.Cross(v0, v1));
  74837. return new Plane(n, BABYLON.Vector3.Dot(n, a));
  74838. };
  74839. Plane.prototype.clone = function () {
  74840. return new Plane(this.normal.clone(), this.w);
  74841. };
  74842. Plane.prototype.flip = function () {
  74843. this.normal.scaleInPlace(-1);
  74844. this.w = -this.w;
  74845. };
  74846. // Split `polygon` by this plane if needed, then put the polygon or polygon
  74847. // fragments in the appropriate lists. Coplanar polygons go into either
  74848. // `coplanarFront` or `coplanarBack` depending on their orientation with
  74849. // respect to this plane. Polygons in front or in back of this plane go into
  74850. // either `front` or `back`.
  74851. Plane.prototype.splitPolygon = function (polygon, coplanarFront, coplanarBack, front, back) {
  74852. var COPLANAR = 0;
  74853. var FRONT = 1;
  74854. var BACK = 2;
  74855. var SPANNING = 3;
  74856. // Classify each point as well as the entire polygon into one of the above
  74857. // four classes.
  74858. var polygonType = 0;
  74859. var types = [];
  74860. var i;
  74861. var t;
  74862. for (i = 0; i < polygon.vertices.length; i++) {
  74863. t = BABYLON.Vector3.Dot(this.normal, polygon.vertices[i].pos) - this.w;
  74864. var type = (t < -Plane.EPSILON) ? BACK : (t > Plane.EPSILON) ? FRONT : COPLANAR;
  74865. polygonType |= type;
  74866. types.push(type);
  74867. }
  74868. // Put the polygon in the correct list, splitting it when necessary.
  74869. switch (polygonType) {
  74870. case COPLANAR:
  74871. (BABYLON.Vector3.Dot(this.normal, polygon.plane.normal) > 0 ? coplanarFront : coplanarBack).push(polygon);
  74872. break;
  74873. case FRONT:
  74874. front.push(polygon);
  74875. break;
  74876. case BACK:
  74877. back.push(polygon);
  74878. break;
  74879. case SPANNING:
  74880. var f = [], b = [];
  74881. for (i = 0; i < polygon.vertices.length; i++) {
  74882. var j = (i + 1) % polygon.vertices.length;
  74883. var ti = types[i], tj = types[j];
  74884. var vi = polygon.vertices[i], vj = polygon.vertices[j];
  74885. if (ti !== BACK)
  74886. f.push(vi);
  74887. if (ti !== FRONT)
  74888. b.push(ti !== BACK ? vi.clone() : vi);
  74889. if ((ti | tj) === SPANNING) {
  74890. t = (this.w - BABYLON.Vector3.Dot(this.normal, vi.pos)) / BABYLON.Vector3.Dot(this.normal, vj.pos.subtract(vi.pos));
  74891. var v = vi.interpolate(vj, t);
  74892. f.push(v);
  74893. b.push(v.clone());
  74894. }
  74895. }
  74896. var poly;
  74897. if (f.length >= 3) {
  74898. poly = new Polygon(f, polygon.shared);
  74899. if (poly.plane)
  74900. front.push(poly);
  74901. }
  74902. if (b.length >= 3) {
  74903. poly = new Polygon(b, polygon.shared);
  74904. if (poly.plane)
  74905. back.push(poly);
  74906. }
  74907. break;
  74908. }
  74909. };
  74910. // `BABYLON.CSG.Plane.EPSILON` is the tolerance used by `splitPolygon()` to decide if a
  74911. // point is on the plane.
  74912. Plane.EPSILON = 1e-5;
  74913. return Plane;
  74914. }());
  74915. // # class Polygon
  74916. // Represents a convex polygon. The vertices used to initialize a polygon must
  74917. // be coplanar and form a convex loop.
  74918. //
  74919. // Each convex polygon has a `shared` property, which is shared between all
  74920. // polygons that are clones of each other or were split from the same polygon.
  74921. // This can be used to define per-polygon properties (such as surface color).
  74922. var Polygon = /** @class */ (function () {
  74923. function Polygon(vertices, shared) {
  74924. this.vertices = vertices;
  74925. this.shared = shared;
  74926. this.plane = Plane.FromPoints(vertices[0].pos, vertices[1].pos, vertices[2].pos);
  74927. }
  74928. Polygon.prototype.clone = function () {
  74929. var vertices = this.vertices.map(function (v) { return v.clone(); });
  74930. return new Polygon(vertices, this.shared);
  74931. };
  74932. Polygon.prototype.flip = function () {
  74933. this.vertices.reverse().map(function (v) { v.flip(); });
  74934. this.plane.flip();
  74935. };
  74936. return Polygon;
  74937. }());
  74938. // # class Node
  74939. // Holds a node in a BSP tree. A BSP tree is built from a collection of polygons
  74940. // by picking a polygon to split along. That polygon (and all other coplanar
  74941. // polygons) are added directly to that node and the other polygons are added to
  74942. // the front and/or back subtrees. This is not a leafy BSP tree since there is
  74943. // no distinction between internal and leaf nodes.
  74944. var Node = /** @class */ (function () {
  74945. function Node(polygons) {
  74946. this.plane = null;
  74947. this.front = null;
  74948. this.back = null;
  74949. this.polygons = new Array();
  74950. if (polygons) {
  74951. this.build(polygons);
  74952. }
  74953. }
  74954. Node.prototype.clone = function () {
  74955. var node = new Node();
  74956. node.plane = this.plane && this.plane.clone();
  74957. node.front = this.front && this.front.clone();
  74958. node.back = this.back && this.back.clone();
  74959. node.polygons = this.polygons.map(function (p) { return p.clone(); });
  74960. return node;
  74961. };
  74962. // Convert solid space to empty space and empty space to solid space.
  74963. Node.prototype.invert = function () {
  74964. for (var i = 0; i < this.polygons.length; i++) {
  74965. this.polygons[i].flip();
  74966. }
  74967. if (this.plane) {
  74968. this.plane.flip();
  74969. }
  74970. if (this.front) {
  74971. this.front.invert();
  74972. }
  74973. if (this.back) {
  74974. this.back.invert();
  74975. }
  74976. var temp = this.front;
  74977. this.front = this.back;
  74978. this.back = temp;
  74979. };
  74980. // Recursively remove all polygons in `polygons` that are inside this BSP
  74981. // tree.
  74982. Node.prototype.clipPolygons = function (polygons) {
  74983. if (!this.plane)
  74984. return polygons.slice();
  74985. var front = new Array(), back = new Array();
  74986. for (var i = 0; i < polygons.length; i++) {
  74987. this.plane.splitPolygon(polygons[i], front, back, front, back);
  74988. }
  74989. if (this.front) {
  74990. front = this.front.clipPolygons(front);
  74991. }
  74992. if (this.back) {
  74993. back = this.back.clipPolygons(back);
  74994. }
  74995. else {
  74996. back = [];
  74997. }
  74998. return front.concat(back);
  74999. };
  75000. // Remove all polygons in this BSP tree that are inside the other BSP tree
  75001. // `bsp`.
  75002. Node.prototype.clipTo = function (bsp) {
  75003. this.polygons = bsp.clipPolygons(this.polygons);
  75004. if (this.front)
  75005. this.front.clipTo(bsp);
  75006. if (this.back)
  75007. this.back.clipTo(bsp);
  75008. };
  75009. // Return a list of all polygons in this BSP tree.
  75010. Node.prototype.allPolygons = function () {
  75011. var polygons = this.polygons.slice();
  75012. if (this.front)
  75013. polygons = polygons.concat(this.front.allPolygons());
  75014. if (this.back)
  75015. polygons = polygons.concat(this.back.allPolygons());
  75016. return polygons;
  75017. };
  75018. // Build a BSP tree out of `polygons`. When called on an existing tree, the
  75019. // new polygons are filtered down to the bottom of the tree and become new
  75020. // nodes there. Each set of polygons is partitioned using the first polygon
  75021. // (no heuristic is used to pick a good split).
  75022. Node.prototype.build = function (polygons) {
  75023. if (!polygons.length)
  75024. return;
  75025. if (!this.plane)
  75026. this.plane = polygons[0].plane.clone();
  75027. var front = new Array(), back = new Array();
  75028. for (var i = 0; i < polygons.length; i++) {
  75029. this.plane.splitPolygon(polygons[i], this.polygons, this.polygons, front, back);
  75030. }
  75031. if (front.length) {
  75032. if (!this.front)
  75033. this.front = new Node();
  75034. this.front.build(front);
  75035. }
  75036. if (back.length) {
  75037. if (!this.back)
  75038. this.back = new Node();
  75039. this.back.build(back);
  75040. }
  75041. };
  75042. return Node;
  75043. }());
  75044. var CSG = /** @class */ (function () {
  75045. function CSG() {
  75046. this.polygons = new Array();
  75047. }
  75048. // Convert BABYLON.Mesh to BABYLON.CSG
  75049. CSG.FromMesh = function (mesh) {
  75050. var vertex, normal, uv, position, polygon, polygons = new Array(), vertices;
  75051. var matrix, meshPosition, meshRotation, meshRotationQuaternion = null, meshScaling;
  75052. if (mesh instanceof BABYLON.Mesh) {
  75053. mesh.computeWorldMatrix(true);
  75054. matrix = mesh.getWorldMatrix();
  75055. meshPosition = mesh.position.clone();
  75056. meshRotation = mesh.rotation.clone();
  75057. if (mesh.rotationQuaternion) {
  75058. meshRotationQuaternion = mesh.rotationQuaternion.clone();
  75059. }
  75060. meshScaling = mesh.scaling.clone();
  75061. }
  75062. else {
  75063. throw 'BABYLON.CSG: Wrong Mesh type, must be BABYLON.Mesh';
  75064. }
  75065. var indices = mesh.getIndices(), positions = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind), normals = mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind), uvs = mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  75066. var subMeshes = mesh.subMeshes;
  75067. for (var sm = 0, sml = subMeshes.length; sm < sml; sm++) {
  75068. for (var i = subMeshes[sm].indexStart, il = subMeshes[sm].indexCount + subMeshes[sm].indexStart; i < il; i += 3) {
  75069. vertices = [];
  75070. for (var j = 0; j < 3; j++) {
  75071. var sourceNormal = new BABYLON.Vector3(normals[indices[i + j] * 3], normals[indices[i + j] * 3 + 1], normals[indices[i + j] * 3 + 2]);
  75072. uv = new BABYLON.Vector2(uvs[indices[i + j] * 2], uvs[indices[i + j] * 2 + 1]);
  75073. var sourcePosition = new BABYLON.Vector3(positions[indices[i + j] * 3], positions[indices[i + j] * 3 + 1], positions[indices[i + j] * 3 + 2]);
  75074. position = BABYLON.Vector3.TransformCoordinates(sourcePosition, matrix);
  75075. normal = BABYLON.Vector3.TransformNormal(sourceNormal, matrix);
  75076. vertex = new Vertex(position, normal, uv);
  75077. vertices.push(vertex);
  75078. }
  75079. polygon = new Polygon(vertices, { subMeshId: sm, meshId: currentCSGMeshId, materialIndex: subMeshes[sm].materialIndex });
  75080. // To handle the case of degenerated triangle
  75081. // polygon.plane == null <=> the polygon does not represent 1 single plane <=> the triangle is degenerated
  75082. if (polygon.plane)
  75083. polygons.push(polygon);
  75084. }
  75085. }
  75086. var csg = CSG.FromPolygons(polygons);
  75087. csg.matrix = matrix;
  75088. csg.position = meshPosition;
  75089. csg.rotation = meshRotation;
  75090. csg.scaling = meshScaling;
  75091. csg.rotationQuaternion = meshRotationQuaternion;
  75092. currentCSGMeshId++;
  75093. return csg;
  75094. };
  75095. // Construct a BABYLON.CSG solid from a list of `BABYLON.CSG.Polygon` instances.
  75096. CSG.FromPolygons = function (polygons) {
  75097. var csg = new CSG();
  75098. csg.polygons = polygons;
  75099. return csg;
  75100. };
  75101. CSG.prototype.clone = function () {
  75102. var csg = new CSG();
  75103. csg.polygons = this.polygons.map(function (p) { return p.clone(); });
  75104. csg.copyTransformAttributes(this);
  75105. return csg;
  75106. };
  75107. CSG.prototype.union = function (csg) {
  75108. var a = new Node(this.clone().polygons);
  75109. var b = new Node(csg.clone().polygons);
  75110. a.clipTo(b);
  75111. b.clipTo(a);
  75112. b.invert();
  75113. b.clipTo(a);
  75114. b.invert();
  75115. a.build(b.allPolygons());
  75116. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  75117. };
  75118. CSG.prototype.unionInPlace = function (csg) {
  75119. var a = new Node(this.polygons);
  75120. var b = new Node(csg.polygons);
  75121. a.clipTo(b);
  75122. b.clipTo(a);
  75123. b.invert();
  75124. b.clipTo(a);
  75125. b.invert();
  75126. a.build(b.allPolygons());
  75127. this.polygons = a.allPolygons();
  75128. };
  75129. CSG.prototype.subtract = function (csg) {
  75130. var a = new Node(this.clone().polygons);
  75131. var b = new Node(csg.clone().polygons);
  75132. a.invert();
  75133. a.clipTo(b);
  75134. b.clipTo(a);
  75135. b.invert();
  75136. b.clipTo(a);
  75137. b.invert();
  75138. a.build(b.allPolygons());
  75139. a.invert();
  75140. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  75141. };
  75142. CSG.prototype.subtractInPlace = function (csg) {
  75143. var a = new Node(this.polygons);
  75144. var b = new Node(csg.polygons);
  75145. a.invert();
  75146. a.clipTo(b);
  75147. b.clipTo(a);
  75148. b.invert();
  75149. b.clipTo(a);
  75150. b.invert();
  75151. a.build(b.allPolygons());
  75152. a.invert();
  75153. this.polygons = a.allPolygons();
  75154. };
  75155. CSG.prototype.intersect = function (csg) {
  75156. var a = new Node(this.clone().polygons);
  75157. var b = new Node(csg.clone().polygons);
  75158. a.invert();
  75159. b.clipTo(a);
  75160. b.invert();
  75161. a.clipTo(b);
  75162. b.clipTo(a);
  75163. a.build(b.allPolygons());
  75164. a.invert();
  75165. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  75166. };
  75167. CSG.prototype.intersectInPlace = function (csg) {
  75168. var a = new Node(this.polygons);
  75169. var b = new Node(csg.polygons);
  75170. a.invert();
  75171. b.clipTo(a);
  75172. b.invert();
  75173. a.clipTo(b);
  75174. b.clipTo(a);
  75175. a.build(b.allPolygons());
  75176. a.invert();
  75177. this.polygons = a.allPolygons();
  75178. };
  75179. // Return a new BABYLON.CSG solid with solid and empty space switched. This solid is
  75180. // not modified.
  75181. CSG.prototype.inverse = function () {
  75182. var csg = this.clone();
  75183. csg.inverseInPlace();
  75184. return csg;
  75185. };
  75186. CSG.prototype.inverseInPlace = function () {
  75187. this.polygons.map(function (p) { p.flip(); });
  75188. };
  75189. // This is used to keep meshes transformations so they can be restored
  75190. // when we build back a Babylon Mesh
  75191. // NB : All CSG operations are performed in world coordinates
  75192. CSG.prototype.copyTransformAttributes = function (csg) {
  75193. this.matrix = csg.matrix;
  75194. this.position = csg.position;
  75195. this.rotation = csg.rotation;
  75196. this.scaling = csg.scaling;
  75197. this.rotationQuaternion = csg.rotationQuaternion;
  75198. return this;
  75199. };
  75200. // Build Raw mesh from CSG
  75201. // Coordinates here are in world space
  75202. CSG.prototype.buildMeshGeometry = function (name, scene, keepSubMeshes) {
  75203. var matrix = this.matrix.clone();
  75204. matrix.invert();
  75205. 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;
  75206. if (keepSubMeshes) {
  75207. // Sort Polygons, since subMeshes are indices range
  75208. polygons.sort(function (a, b) {
  75209. if (a.shared.meshId === b.shared.meshId) {
  75210. return a.shared.subMeshId - b.shared.subMeshId;
  75211. }
  75212. else {
  75213. return a.shared.meshId - b.shared.meshId;
  75214. }
  75215. });
  75216. }
  75217. for (var i = 0, il = polygons.length; i < il; i++) {
  75218. polygon = polygons[i];
  75219. // Building SubMeshes
  75220. if (!subMesh_dict[polygon.shared.meshId]) {
  75221. subMesh_dict[polygon.shared.meshId] = {};
  75222. }
  75223. if (!subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId]) {
  75224. subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId] = {
  75225. indexStart: +Infinity,
  75226. indexEnd: -Infinity,
  75227. materialIndex: polygon.shared.materialIndex
  75228. };
  75229. }
  75230. subMesh_obj = subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId];
  75231. for (var j = 2, jl = polygon.vertices.length; j < jl; j++) {
  75232. polygonIndices[0] = 0;
  75233. polygonIndices[1] = j - 1;
  75234. polygonIndices[2] = j;
  75235. for (var k = 0; k < 3; k++) {
  75236. vertex.copyFrom(polygon.vertices[polygonIndices[k]].pos);
  75237. normal.copyFrom(polygon.vertices[polygonIndices[k]].normal);
  75238. uv.copyFrom(polygon.vertices[polygonIndices[k]].uv);
  75239. var localVertex = BABYLON.Vector3.TransformCoordinates(vertex, matrix);
  75240. var localNormal = BABYLON.Vector3.TransformNormal(normal, matrix);
  75241. vertex_idx = vertice_dict[localVertex.x + ',' + localVertex.y + ',' + localVertex.z];
  75242. // Check if 2 points can be merged
  75243. if (!(typeof vertex_idx !== 'undefined' &&
  75244. normals[vertex_idx * 3] === localNormal.x &&
  75245. normals[vertex_idx * 3 + 1] === localNormal.y &&
  75246. normals[vertex_idx * 3 + 2] === localNormal.z &&
  75247. uvs[vertex_idx * 2] === uv.x &&
  75248. uvs[vertex_idx * 2 + 1] === uv.y)) {
  75249. vertices.push(localVertex.x, localVertex.y, localVertex.z);
  75250. uvs.push(uv.x, uv.y);
  75251. normals.push(normal.x, normal.y, normal.z);
  75252. vertex_idx = vertice_dict[localVertex.x + ',' + localVertex.y + ',' + localVertex.z] = (vertices.length / 3) - 1;
  75253. }
  75254. indices.push(vertex_idx);
  75255. subMesh_obj.indexStart = Math.min(currentIndex, subMesh_obj.indexStart);
  75256. subMesh_obj.indexEnd = Math.max(currentIndex, subMesh_obj.indexEnd);
  75257. currentIndex++;
  75258. }
  75259. }
  75260. }
  75261. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, vertices);
  75262. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals);
  75263. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, uvs);
  75264. mesh.setIndices(indices, null);
  75265. if (keepSubMeshes) {
  75266. // We offset the materialIndex by the previous number of materials in the CSG mixed meshes
  75267. var materialIndexOffset = 0, materialMaxIndex;
  75268. mesh.subMeshes = new Array();
  75269. for (var m in subMesh_dict) {
  75270. materialMaxIndex = -1;
  75271. for (var sm in subMesh_dict[m]) {
  75272. subMesh_obj = subMesh_dict[m][sm];
  75273. BABYLON.SubMesh.CreateFromIndices(subMesh_obj.materialIndex + materialIndexOffset, subMesh_obj.indexStart, subMesh_obj.indexEnd - subMesh_obj.indexStart + 1, mesh);
  75274. materialMaxIndex = Math.max(subMesh_obj.materialIndex, materialMaxIndex);
  75275. }
  75276. materialIndexOffset += ++materialMaxIndex;
  75277. }
  75278. }
  75279. return mesh;
  75280. };
  75281. // Build Mesh from CSG taking material and transforms into account
  75282. CSG.prototype.toMesh = function (name, material, scene, keepSubMeshes) {
  75283. var mesh = this.buildMeshGeometry(name, scene, keepSubMeshes);
  75284. mesh.material = material;
  75285. mesh.position.copyFrom(this.position);
  75286. mesh.rotation.copyFrom(this.rotation);
  75287. if (this.rotationQuaternion) {
  75288. mesh.rotationQuaternion = this.rotationQuaternion.clone();
  75289. }
  75290. mesh.scaling.copyFrom(this.scaling);
  75291. mesh.computeWorldMatrix(true);
  75292. return mesh;
  75293. };
  75294. return CSG;
  75295. }());
  75296. BABYLON.CSG = CSG;
  75297. })(BABYLON || (BABYLON = {}));
  75298. //# sourceMappingURL=babylon.csg.js.map
  75299. var BABYLON;
  75300. (function (BABYLON) {
  75301. var LensFlare = /** @class */ (function () {
  75302. function LensFlare(size, position, color, imgUrl, system) {
  75303. this.size = size;
  75304. this.position = position;
  75305. this.alphaMode = BABYLON.Engine.ALPHA_ONEONE;
  75306. this.color = color || new BABYLON.Color3(1, 1, 1);
  75307. this.texture = imgUrl ? new BABYLON.Texture(imgUrl, system.getScene(), true) : null;
  75308. this._system = system;
  75309. system.lensFlares.push(this);
  75310. }
  75311. LensFlare.AddFlare = function (size, position, color, imgUrl, system) {
  75312. return new LensFlare(size, position, color, imgUrl, system);
  75313. };
  75314. LensFlare.prototype.dispose = function () {
  75315. if (this.texture) {
  75316. this.texture.dispose();
  75317. }
  75318. // Remove from scene
  75319. var index = this._system.lensFlares.indexOf(this);
  75320. this._system.lensFlares.splice(index, 1);
  75321. };
  75322. ;
  75323. return LensFlare;
  75324. }());
  75325. BABYLON.LensFlare = LensFlare;
  75326. })(BABYLON || (BABYLON = {}));
  75327. //# sourceMappingURL=babylon.lensFlare.js.map
  75328. var BABYLON;
  75329. (function (BABYLON) {
  75330. var LensFlareSystem = /** @class */ (function () {
  75331. function LensFlareSystem(name, emitter, scene) {
  75332. this.name = name;
  75333. this.lensFlares = new Array();
  75334. this.borderLimit = 300;
  75335. this.viewportBorder = 0;
  75336. this.layerMask = 0x0FFFFFFF;
  75337. this._vertexBuffers = {};
  75338. this._isEnabled = true;
  75339. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  75340. this._emitter = emitter;
  75341. this.id = name;
  75342. scene.lensFlareSystems.push(this);
  75343. this.meshesSelectionPredicate = function (m) { return (scene.activeCamera && m.material && m.isVisible && m.isEnabled() && m.isBlocker && ((m.layerMask & scene.activeCamera.layerMask) != 0)); };
  75344. var engine = scene.getEngine();
  75345. // VBO
  75346. var vertices = [];
  75347. vertices.push(1, 1);
  75348. vertices.push(-1, 1);
  75349. vertices.push(-1, -1);
  75350. vertices.push(1, -1);
  75351. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(engine, vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  75352. // Indices
  75353. var indices = [];
  75354. indices.push(0);
  75355. indices.push(1);
  75356. indices.push(2);
  75357. indices.push(0);
  75358. indices.push(2);
  75359. indices.push(3);
  75360. this._indexBuffer = engine.createIndexBuffer(indices);
  75361. // Effects
  75362. this._effect = engine.createEffect("lensFlare", [BABYLON.VertexBuffer.PositionKind], ["color", "viewportMatrix"], ["textureSampler"], "");
  75363. }
  75364. Object.defineProperty(LensFlareSystem.prototype, "isEnabled", {
  75365. get: function () {
  75366. return this._isEnabled;
  75367. },
  75368. set: function (value) {
  75369. this._isEnabled = value;
  75370. },
  75371. enumerable: true,
  75372. configurable: true
  75373. });
  75374. LensFlareSystem.prototype.getScene = function () {
  75375. return this._scene;
  75376. };
  75377. LensFlareSystem.prototype.getEmitter = function () {
  75378. return this._emitter;
  75379. };
  75380. LensFlareSystem.prototype.setEmitter = function (newEmitter) {
  75381. this._emitter = newEmitter;
  75382. };
  75383. LensFlareSystem.prototype.getEmitterPosition = function () {
  75384. return this._emitter.getAbsolutePosition ? this._emitter.getAbsolutePosition() : this._emitter.position;
  75385. };
  75386. LensFlareSystem.prototype.computeEffectivePosition = function (globalViewport) {
  75387. var position = this.getEmitterPosition();
  75388. position = BABYLON.Vector3.Project(position, BABYLON.Matrix.Identity(), this._scene.getTransformMatrix(), globalViewport);
  75389. this._positionX = position.x;
  75390. this._positionY = position.y;
  75391. position = BABYLON.Vector3.TransformCoordinates(this.getEmitterPosition(), this._scene.getViewMatrix());
  75392. if (this.viewportBorder > 0) {
  75393. globalViewport.x -= this.viewportBorder;
  75394. globalViewport.y -= this.viewportBorder;
  75395. globalViewport.width += this.viewportBorder * 2;
  75396. globalViewport.height += this.viewportBorder * 2;
  75397. position.x += this.viewportBorder;
  75398. position.y += this.viewportBorder;
  75399. this._positionX += this.viewportBorder;
  75400. this._positionY += this.viewportBorder;
  75401. }
  75402. if (position.z > 0) {
  75403. if ((this._positionX > globalViewport.x) && (this._positionX < globalViewport.x + globalViewport.width)) {
  75404. if ((this._positionY > globalViewport.y) && (this._positionY < globalViewport.y + globalViewport.height))
  75405. return true;
  75406. }
  75407. return true;
  75408. }
  75409. return false;
  75410. };
  75411. LensFlareSystem.prototype._isVisible = function () {
  75412. if (!this._isEnabled || !this._scene.activeCamera) {
  75413. return false;
  75414. }
  75415. var emitterPosition = this.getEmitterPosition();
  75416. var direction = emitterPosition.subtract(this._scene.activeCamera.globalPosition);
  75417. var distance = direction.length();
  75418. direction.normalize();
  75419. var ray = new BABYLON.Ray(this._scene.activeCamera.globalPosition, direction);
  75420. var pickInfo = this._scene.pickWithRay(ray, this.meshesSelectionPredicate, true);
  75421. return !pickInfo || !pickInfo.hit || pickInfo.distance > distance;
  75422. };
  75423. LensFlareSystem.prototype.render = function () {
  75424. if (!this._effect.isReady() || !this._scene.activeCamera)
  75425. return false;
  75426. var engine = this._scene.getEngine();
  75427. var viewport = this._scene.activeCamera.viewport;
  75428. var globalViewport = viewport.toGlobal(engine.getRenderWidth(true), engine.getRenderHeight(true));
  75429. // Position
  75430. if (!this.computeEffectivePosition(globalViewport)) {
  75431. return false;
  75432. }
  75433. // Visibility
  75434. if (!this._isVisible()) {
  75435. return false;
  75436. }
  75437. // Intensity
  75438. var awayX;
  75439. var awayY;
  75440. if (this._positionX < this.borderLimit + globalViewport.x) {
  75441. awayX = this.borderLimit + globalViewport.x - this._positionX;
  75442. }
  75443. else if (this._positionX > globalViewport.x + globalViewport.width - this.borderLimit) {
  75444. awayX = this._positionX - globalViewport.x - globalViewport.width + this.borderLimit;
  75445. }
  75446. else {
  75447. awayX = 0;
  75448. }
  75449. if (this._positionY < this.borderLimit + globalViewport.y) {
  75450. awayY = this.borderLimit + globalViewport.y - this._positionY;
  75451. }
  75452. else if (this._positionY > globalViewport.y + globalViewport.height - this.borderLimit) {
  75453. awayY = this._positionY - globalViewport.y - globalViewport.height + this.borderLimit;
  75454. }
  75455. else {
  75456. awayY = 0;
  75457. }
  75458. var away = (awayX > awayY) ? awayX : awayY;
  75459. away -= this.viewportBorder;
  75460. if (away > this.borderLimit) {
  75461. away = this.borderLimit;
  75462. }
  75463. var intensity = 1.0 - (away / this.borderLimit);
  75464. if (intensity < 0) {
  75465. return false;
  75466. }
  75467. if (intensity > 1.0) {
  75468. intensity = 1.0;
  75469. }
  75470. if (this.viewportBorder > 0) {
  75471. globalViewport.x += this.viewportBorder;
  75472. globalViewport.y += this.viewportBorder;
  75473. globalViewport.width -= this.viewportBorder * 2;
  75474. globalViewport.height -= this.viewportBorder * 2;
  75475. this._positionX -= this.viewportBorder;
  75476. this._positionY -= this.viewportBorder;
  75477. }
  75478. // Position
  75479. var centerX = globalViewport.x + globalViewport.width / 2;
  75480. var centerY = globalViewport.y + globalViewport.height / 2;
  75481. var distX = centerX - this._positionX;
  75482. var distY = centerY - this._positionY;
  75483. // Effects
  75484. engine.enableEffect(this._effect);
  75485. engine.setState(false);
  75486. engine.setDepthBuffer(false);
  75487. // VBOs
  75488. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._effect);
  75489. // Flares
  75490. for (var index = 0; index < this.lensFlares.length; index++) {
  75491. var flare = this.lensFlares[index];
  75492. engine.setAlphaMode(flare.alphaMode);
  75493. var x = centerX - (distX * flare.position);
  75494. var y = centerY - (distY * flare.position);
  75495. var cw = flare.size;
  75496. var ch = flare.size * engine.getAspectRatio(this._scene.activeCamera, true);
  75497. var cx = 2 * (x / (globalViewport.width + globalViewport.x * 2)) - 1.0;
  75498. var cy = 1.0 - 2 * (y / (globalViewport.height + globalViewport.y * 2));
  75499. var viewportMatrix = BABYLON.Matrix.FromValues(cw / 2, 0, 0, 0, 0, ch / 2, 0, 0, 0, 0, 1, 0, cx, cy, 0, 1);
  75500. this._effect.setMatrix("viewportMatrix", viewportMatrix);
  75501. // Texture
  75502. this._effect.setTexture("textureSampler", flare.texture);
  75503. // Color
  75504. this._effect.setFloat4("color", flare.color.r * intensity, flare.color.g * intensity, flare.color.b * intensity, 1.0);
  75505. // Draw order
  75506. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  75507. }
  75508. engine.setDepthBuffer(true);
  75509. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  75510. return true;
  75511. };
  75512. LensFlareSystem.prototype.dispose = function () {
  75513. var vertexBuffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  75514. if (vertexBuffer) {
  75515. vertexBuffer.dispose();
  75516. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  75517. }
  75518. if (this._indexBuffer) {
  75519. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  75520. this._indexBuffer = null;
  75521. }
  75522. while (this.lensFlares.length) {
  75523. this.lensFlares[0].dispose();
  75524. }
  75525. // Remove from scene
  75526. var index = this._scene.lensFlareSystems.indexOf(this);
  75527. this._scene.lensFlareSystems.splice(index, 1);
  75528. };
  75529. LensFlareSystem.Parse = function (parsedLensFlareSystem, scene, rootUrl) {
  75530. var emitter = scene.getLastEntryByID(parsedLensFlareSystem.emitterId);
  75531. var name = parsedLensFlareSystem.name || "lensFlareSystem#" + parsedLensFlareSystem.emitterId;
  75532. var lensFlareSystem = new LensFlareSystem(name, emitter, scene);
  75533. lensFlareSystem.id = parsedLensFlareSystem.id || name;
  75534. lensFlareSystem.borderLimit = parsedLensFlareSystem.borderLimit;
  75535. for (var index = 0; index < parsedLensFlareSystem.flares.length; index++) {
  75536. var parsedFlare = parsedLensFlareSystem.flares[index];
  75537. BABYLON.LensFlare.AddFlare(parsedFlare.size, parsedFlare.position, BABYLON.Color3.FromArray(parsedFlare.color), parsedFlare.textureName ? rootUrl + parsedFlare.textureName : "", lensFlareSystem);
  75538. }
  75539. return lensFlareSystem;
  75540. };
  75541. LensFlareSystem.prototype.serialize = function () {
  75542. var serializationObject = {};
  75543. serializationObject.id = this.id;
  75544. serializationObject.name = this.name;
  75545. serializationObject.emitterId = this.getEmitter().id;
  75546. serializationObject.borderLimit = this.borderLimit;
  75547. serializationObject.flares = [];
  75548. for (var index = 0; index < this.lensFlares.length; index++) {
  75549. var flare = this.lensFlares[index];
  75550. serializationObject.flares.push({
  75551. size: flare.size,
  75552. position: flare.position,
  75553. color: flare.color.asArray(),
  75554. textureName: BABYLON.Tools.GetFilename(flare.texture ? flare.texture.name : "")
  75555. });
  75556. }
  75557. return serializationObject;
  75558. };
  75559. return LensFlareSystem;
  75560. }());
  75561. BABYLON.LensFlareSystem = LensFlareSystem;
  75562. })(BABYLON || (BABYLON = {}));
  75563. //# sourceMappingURL=babylon.lensFlareSystem.js.map
  75564. var BABYLON;
  75565. (function (BABYLON) {
  75566. /**
  75567. * This is a holder class for the physics joint created by the physics plugin.
  75568. * It holds a set of functions to control the underlying joint.
  75569. */
  75570. var PhysicsJoint = /** @class */ (function () {
  75571. function PhysicsJoint(type, jointData) {
  75572. this.type = type;
  75573. this.jointData = jointData;
  75574. jointData.nativeParams = jointData.nativeParams || {};
  75575. }
  75576. Object.defineProperty(PhysicsJoint.prototype, "physicsJoint", {
  75577. get: function () {
  75578. return this._physicsJoint;
  75579. },
  75580. set: function (newJoint) {
  75581. if (this._physicsJoint) {
  75582. //remove from the wolrd
  75583. }
  75584. this._physicsJoint = newJoint;
  75585. },
  75586. enumerable: true,
  75587. configurable: true
  75588. });
  75589. Object.defineProperty(PhysicsJoint.prototype, "physicsPlugin", {
  75590. set: function (physicsPlugin) {
  75591. this._physicsPlugin = physicsPlugin;
  75592. },
  75593. enumerable: true,
  75594. configurable: true
  75595. });
  75596. /**
  75597. * Execute a function that is physics-plugin specific.
  75598. * @param {Function} func the function that will be executed.
  75599. * It accepts two parameters: the physics world and the physics joint.
  75600. */
  75601. PhysicsJoint.prototype.executeNativeFunction = function (func) {
  75602. func(this._physicsPlugin.world, this._physicsJoint);
  75603. };
  75604. //TODO check if the native joints are the same
  75605. //Joint Types
  75606. PhysicsJoint.DistanceJoint = 0;
  75607. PhysicsJoint.HingeJoint = 1;
  75608. PhysicsJoint.BallAndSocketJoint = 2;
  75609. PhysicsJoint.WheelJoint = 3;
  75610. PhysicsJoint.SliderJoint = 4;
  75611. //OIMO
  75612. PhysicsJoint.PrismaticJoint = 5;
  75613. //ENERGY FTW! (compare with this - http://ode-wiki.org/wiki/index.php?title=Manual:_Joint_Types_and_Functions)
  75614. PhysicsJoint.UniversalJoint = 6;
  75615. PhysicsJoint.Hinge2Joint = PhysicsJoint.WheelJoint;
  75616. //Cannon
  75617. //Similar to a Ball-Joint. Different in params
  75618. PhysicsJoint.PointToPointJoint = 8;
  75619. //Cannon only at the moment
  75620. PhysicsJoint.SpringJoint = 9;
  75621. PhysicsJoint.LockJoint = 10;
  75622. return PhysicsJoint;
  75623. }());
  75624. BABYLON.PhysicsJoint = PhysicsJoint;
  75625. /**
  75626. * A class representing a physics distance joint.
  75627. */
  75628. var DistanceJoint = /** @class */ (function (_super) {
  75629. __extends(DistanceJoint, _super);
  75630. function DistanceJoint(jointData) {
  75631. return _super.call(this, PhysicsJoint.DistanceJoint, jointData) || this;
  75632. }
  75633. /**
  75634. * Update the predefined distance.
  75635. */
  75636. DistanceJoint.prototype.updateDistance = function (maxDistance, minDistance) {
  75637. this._physicsPlugin.updateDistanceJoint(this, maxDistance, minDistance);
  75638. };
  75639. return DistanceJoint;
  75640. }(PhysicsJoint));
  75641. BABYLON.DistanceJoint = DistanceJoint;
  75642. var MotorEnabledJoint = /** @class */ (function (_super) {
  75643. __extends(MotorEnabledJoint, _super);
  75644. function MotorEnabledJoint(type, jointData) {
  75645. return _super.call(this, type, jointData) || this;
  75646. }
  75647. /**
  75648. * Set the motor values.
  75649. * Attention, this function is plugin specific. Engines won't react 100% the same.
  75650. * @param {number} force the force to apply
  75651. * @param {number} maxForce max force for this motor.
  75652. */
  75653. MotorEnabledJoint.prototype.setMotor = function (force, maxForce) {
  75654. this._physicsPlugin.setMotor(this, force || 0, maxForce);
  75655. };
  75656. /**
  75657. * Set the motor's limits.
  75658. * Attention, this function is plugin specific. Engines won't react 100% the same.
  75659. */
  75660. MotorEnabledJoint.prototype.setLimit = function (upperLimit, lowerLimit) {
  75661. this._physicsPlugin.setLimit(this, upperLimit, lowerLimit);
  75662. };
  75663. return MotorEnabledJoint;
  75664. }(PhysicsJoint));
  75665. BABYLON.MotorEnabledJoint = MotorEnabledJoint;
  75666. /**
  75667. * This class represents a single hinge physics joint
  75668. */
  75669. var HingeJoint = /** @class */ (function (_super) {
  75670. __extends(HingeJoint, _super);
  75671. function HingeJoint(jointData) {
  75672. return _super.call(this, PhysicsJoint.HingeJoint, jointData) || this;
  75673. }
  75674. /**
  75675. * Set the motor values.
  75676. * Attention, this function is plugin specific. Engines won't react 100% the same.
  75677. * @param {number} force the force to apply
  75678. * @param {number} maxForce max force for this motor.
  75679. */
  75680. HingeJoint.prototype.setMotor = function (force, maxForce) {
  75681. this._physicsPlugin.setMotor(this, force || 0, maxForce);
  75682. };
  75683. /**
  75684. * Set the motor's limits.
  75685. * Attention, this function is plugin specific. Engines won't react 100% the same.
  75686. */
  75687. HingeJoint.prototype.setLimit = function (upperLimit, lowerLimit) {
  75688. this._physicsPlugin.setLimit(this, upperLimit, lowerLimit);
  75689. };
  75690. return HingeJoint;
  75691. }(MotorEnabledJoint));
  75692. BABYLON.HingeJoint = HingeJoint;
  75693. /**
  75694. * This class represents a dual hinge physics joint (same as wheel joint)
  75695. */
  75696. var Hinge2Joint = /** @class */ (function (_super) {
  75697. __extends(Hinge2Joint, _super);
  75698. function Hinge2Joint(jointData) {
  75699. return _super.call(this, PhysicsJoint.Hinge2Joint, jointData) || this;
  75700. }
  75701. /**
  75702. * Set the motor values.
  75703. * Attention, this function is plugin specific. Engines won't react 100% the same.
  75704. * @param {number} force the force to apply
  75705. * @param {number} maxForce max force for this motor.
  75706. * @param {motorIndex} the motor's index, 0 or 1.
  75707. */
  75708. Hinge2Joint.prototype.setMotor = function (force, maxForce, motorIndex) {
  75709. if (motorIndex === void 0) { motorIndex = 0; }
  75710. this._physicsPlugin.setMotor(this, force || 0, maxForce, motorIndex);
  75711. };
  75712. /**
  75713. * Set the motor limits.
  75714. * Attention, this function is plugin specific. Engines won't react 100% the same.
  75715. * @param {number} upperLimit the upper limit
  75716. * @param {number} lowerLimit lower limit
  75717. * @param {motorIndex} the motor's index, 0 or 1.
  75718. */
  75719. Hinge2Joint.prototype.setLimit = function (upperLimit, lowerLimit, motorIndex) {
  75720. if (motorIndex === void 0) { motorIndex = 0; }
  75721. this._physicsPlugin.setLimit(this, upperLimit, lowerLimit, motorIndex);
  75722. };
  75723. return Hinge2Joint;
  75724. }(MotorEnabledJoint));
  75725. BABYLON.Hinge2Joint = Hinge2Joint;
  75726. })(BABYLON || (BABYLON = {}));
  75727. //# sourceMappingURL=babylon.physicsJoint.js.map
  75728. var BABYLON;
  75729. (function (BABYLON) {
  75730. var PhysicsImpostor = /** @class */ (function () {
  75731. function PhysicsImpostor(object, type, _options, _scene) {
  75732. if (_options === void 0) { _options = { mass: 0 }; }
  75733. var _this = this;
  75734. this.object = object;
  75735. this.type = type;
  75736. this._options = _options;
  75737. this._scene = _scene;
  75738. this._bodyUpdateRequired = false;
  75739. this._onBeforePhysicsStepCallbacks = new Array();
  75740. this._onAfterPhysicsStepCallbacks = new Array();
  75741. this._onPhysicsCollideCallbacks = [];
  75742. this._deltaPosition = BABYLON.Vector3.Zero();
  75743. this._isDisposed = false;
  75744. //temp variables for parent rotation calculations
  75745. //private _mats: Array<Matrix> = [new Matrix(), new Matrix()];
  75746. this._tmpQuat = new BABYLON.Quaternion();
  75747. this._tmpQuat2 = new BABYLON.Quaternion();
  75748. /**
  75749. * this function is executed by the physics engine.
  75750. */
  75751. this.beforeStep = function () {
  75752. if (!_this._physicsEngine) {
  75753. return;
  75754. }
  75755. _this.object.translate(_this._deltaPosition, -1);
  75756. _this._deltaRotationConjugated && _this.object.rotationQuaternion && _this.object.rotationQuaternion.multiplyToRef(_this._deltaRotationConjugated, _this.object.rotationQuaternion);
  75757. _this.object.computeWorldMatrix(false);
  75758. if (_this.object.parent && _this.object.rotationQuaternion) {
  75759. _this.getParentsRotation();
  75760. _this._tmpQuat.multiplyToRef(_this.object.rotationQuaternion, _this._tmpQuat);
  75761. }
  75762. else {
  75763. _this._tmpQuat.copyFrom(_this.object.rotationQuaternion || new BABYLON.Quaternion());
  75764. }
  75765. if (!_this._options.disableBidirectionalTransformation) {
  75766. _this.object.rotationQuaternion && _this._physicsEngine.getPhysicsPlugin().setPhysicsBodyTransformation(_this, /*bInfo.boundingBox.centerWorld*/ _this.object.getAbsolutePivotPoint(), _this._tmpQuat);
  75767. }
  75768. _this._onBeforePhysicsStepCallbacks.forEach(function (func) {
  75769. func(_this);
  75770. });
  75771. };
  75772. /**
  75773. * this function is executed by the physics engine.
  75774. */
  75775. this.afterStep = function () {
  75776. if (!_this._physicsEngine) {
  75777. return;
  75778. }
  75779. _this._onAfterPhysicsStepCallbacks.forEach(function (func) {
  75780. func(_this);
  75781. });
  75782. _this._physicsEngine.getPhysicsPlugin().setTransformationFromPhysicsBody(_this);
  75783. // object has now its world rotation. needs to be converted to local.
  75784. if (_this.object.parent && _this.object.rotationQuaternion) {
  75785. _this.getParentsRotation();
  75786. _this._tmpQuat.conjugateInPlace();
  75787. _this._tmpQuat.multiplyToRef(_this.object.rotationQuaternion, _this.object.rotationQuaternion);
  75788. }
  75789. // take the position set and make it the absolute position of this object.
  75790. _this.object.setAbsolutePosition(_this.object.position);
  75791. _this._deltaRotation && _this.object.rotationQuaternion && _this.object.rotationQuaternion.multiplyToRef(_this._deltaRotation, _this.object.rotationQuaternion);
  75792. _this.object.translate(_this._deltaPosition, 1);
  75793. };
  75794. /**
  75795. * Legacy collision detection event support
  75796. */
  75797. this.onCollideEvent = null;
  75798. //event and body object due to cannon's event-based architecture.
  75799. this.onCollide = function (e) {
  75800. if (!_this._onPhysicsCollideCallbacks.length && !_this.onCollideEvent) {
  75801. return;
  75802. }
  75803. if (!_this._physicsEngine) {
  75804. return;
  75805. }
  75806. var otherImpostor = _this._physicsEngine.getImpostorWithPhysicsBody(e.body);
  75807. if (otherImpostor) {
  75808. // Legacy collision detection event support
  75809. if (_this.onCollideEvent) {
  75810. _this.onCollideEvent(_this, otherImpostor);
  75811. }
  75812. _this._onPhysicsCollideCallbacks.filter(function (obj) {
  75813. return obj.otherImpostors.indexOf(otherImpostor) !== -1;
  75814. }).forEach(function (obj) {
  75815. obj.callback(_this, otherImpostor);
  75816. });
  75817. }
  75818. };
  75819. //sanity check!
  75820. if (!this.object) {
  75821. BABYLON.Tools.Error("No object was provided. A physics object is obligatory");
  75822. return;
  75823. }
  75824. //legacy support for old syntax.
  75825. if (!this._scene && object.getScene) {
  75826. this._scene = object.getScene();
  75827. }
  75828. if (!this._scene) {
  75829. return;
  75830. }
  75831. this._physicsEngine = this._scene.getPhysicsEngine();
  75832. if (!this._physicsEngine) {
  75833. BABYLON.Tools.Error("Physics not enabled. Please use scene.enablePhysics(...) before creating impostors.");
  75834. }
  75835. else {
  75836. //set the object's quaternion, if not set
  75837. if (!this.object.rotationQuaternion) {
  75838. if (this.object.rotation) {
  75839. this.object.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(this.object.rotation.y, this.object.rotation.x, this.object.rotation.z);
  75840. }
  75841. else {
  75842. this.object.rotationQuaternion = new BABYLON.Quaternion();
  75843. }
  75844. }
  75845. //default options params
  75846. this._options.mass = (_options.mass === void 0) ? 0 : _options.mass;
  75847. this._options.friction = (_options.friction === void 0) ? 0.2 : _options.friction;
  75848. this._options.restitution = (_options.restitution === void 0) ? 0.2 : _options.restitution;
  75849. this._joints = [];
  75850. //If the mesh has a parent, don't initialize the physicsBody. Instead wait for the parent to do that.
  75851. if (!this.object.parent || this._options.ignoreParent) {
  75852. this._init();
  75853. }
  75854. else if (this.object.parent.physicsImpostor) {
  75855. BABYLON.Tools.Warn("You must affect impostors to children before affecting impostor to parent.");
  75856. }
  75857. }
  75858. }
  75859. Object.defineProperty(PhysicsImpostor.prototype, "isDisposed", {
  75860. get: function () {
  75861. return this._isDisposed;
  75862. },
  75863. enumerable: true,
  75864. configurable: true
  75865. });
  75866. Object.defineProperty(PhysicsImpostor.prototype, "mass", {
  75867. get: function () {
  75868. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getBodyMass(this) : 0;
  75869. },
  75870. set: function (value) {
  75871. this.setMass(value);
  75872. },
  75873. enumerable: true,
  75874. configurable: true
  75875. });
  75876. Object.defineProperty(PhysicsImpostor.prototype, "friction", {
  75877. get: function () {
  75878. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getBodyFriction(this) : 0;
  75879. },
  75880. set: function (value) {
  75881. if (!this._physicsEngine) {
  75882. return;
  75883. }
  75884. this._physicsEngine.getPhysicsPlugin().setBodyFriction(this, value);
  75885. },
  75886. enumerable: true,
  75887. configurable: true
  75888. });
  75889. Object.defineProperty(PhysicsImpostor.prototype, "restitution", {
  75890. get: function () {
  75891. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getBodyRestitution(this) : 0;
  75892. },
  75893. set: function (value) {
  75894. if (!this._physicsEngine) {
  75895. return;
  75896. }
  75897. this._physicsEngine.getPhysicsPlugin().setBodyRestitution(this, value);
  75898. },
  75899. enumerable: true,
  75900. configurable: true
  75901. });
  75902. /**
  75903. * This function will completly initialize this impostor.
  75904. * It will create a new body - but only if this mesh has no parent.
  75905. * If it has, this impostor will not be used other than to define the impostor
  75906. * of the child mesh.
  75907. */
  75908. PhysicsImpostor.prototype._init = function () {
  75909. if (!this._physicsEngine) {
  75910. return;
  75911. }
  75912. this._physicsEngine.removeImpostor(this);
  75913. this.physicsBody = null;
  75914. this._parent = this._parent || this._getPhysicsParent();
  75915. if (!this._isDisposed && (!this.parent || this._options.ignoreParent)) {
  75916. this._physicsEngine.addImpostor(this);
  75917. }
  75918. };
  75919. PhysicsImpostor.prototype._getPhysicsParent = function () {
  75920. if (this.object.parent instanceof BABYLON.AbstractMesh) {
  75921. var parentMesh = this.object.parent;
  75922. return parentMesh.physicsImpostor;
  75923. }
  75924. return null;
  75925. };
  75926. /**
  75927. * Should a new body be generated.
  75928. */
  75929. PhysicsImpostor.prototype.isBodyInitRequired = function () {
  75930. return this._bodyUpdateRequired || (!this._physicsBody && !this._parent);
  75931. };
  75932. PhysicsImpostor.prototype.setScalingUpdated = function (updated) {
  75933. this.forceUpdate();
  75934. };
  75935. /**
  75936. * Force a regeneration of this or the parent's impostor's body.
  75937. * Use under cautious - This will remove all joints already implemented.
  75938. */
  75939. PhysicsImpostor.prototype.forceUpdate = function () {
  75940. this._init();
  75941. if (this.parent && !this._options.ignoreParent) {
  75942. this.parent.forceUpdate();
  75943. }
  75944. };
  75945. Object.defineProperty(PhysicsImpostor.prototype, "physicsBody", {
  75946. /*public get mesh(): AbstractMesh {
  75947. return this._mesh;
  75948. }*/
  75949. /**
  75950. * Gets the body that holds this impostor. Either its own, or its parent.
  75951. */
  75952. get: function () {
  75953. return (this._parent && !this._options.ignoreParent) ? this._parent.physicsBody : this._physicsBody;
  75954. },
  75955. /**
  75956. * Set the physics body. Used mainly by the physics engine/plugin
  75957. */
  75958. set: function (physicsBody) {
  75959. if (this._physicsBody && this._physicsEngine) {
  75960. this._physicsEngine.getPhysicsPlugin().removePhysicsBody(this);
  75961. }
  75962. this._physicsBody = physicsBody;
  75963. this.resetUpdateFlags();
  75964. },
  75965. enumerable: true,
  75966. configurable: true
  75967. });
  75968. Object.defineProperty(PhysicsImpostor.prototype, "parent", {
  75969. get: function () {
  75970. return !this._options.ignoreParent && this._parent ? this._parent : null;
  75971. },
  75972. set: function (value) {
  75973. this._parent = value;
  75974. },
  75975. enumerable: true,
  75976. configurable: true
  75977. });
  75978. PhysicsImpostor.prototype.resetUpdateFlags = function () {
  75979. this._bodyUpdateRequired = false;
  75980. };
  75981. PhysicsImpostor.prototype.getObjectExtendSize = function () {
  75982. if (this.object.getBoundingInfo) {
  75983. var q = this.object.rotationQuaternion;
  75984. //reset rotation
  75985. this.object.rotationQuaternion = PhysicsImpostor.IDENTITY_QUATERNION;
  75986. //calculate the world matrix with no rotation
  75987. this.object.computeWorldMatrix && this.object.computeWorldMatrix(true);
  75988. var boundingInfo = this.object.getBoundingInfo();
  75989. var size = boundingInfo.boundingBox.extendSizeWorld.scale(2);
  75990. //bring back the rotation
  75991. this.object.rotationQuaternion = q;
  75992. //calculate the world matrix with the new rotation
  75993. this.object.computeWorldMatrix && this.object.computeWorldMatrix(true);
  75994. return size;
  75995. }
  75996. else {
  75997. return PhysicsImpostor.DEFAULT_OBJECT_SIZE;
  75998. }
  75999. };
  76000. PhysicsImpostor.prototype.getObjectCenter = function () {
  76001. if (this.object.getBoundingInfo) {
  76002. var boundingInfo = this.object.getBoundingInfo();
  76003. return boundingInfo.boundingBox.centerWorld;
  76004. }
  76005. else {
  76006. return this.object.position;
  76007. }
  76008. };
  76009. /**
  76010. * Get a specific parametes from the options parameter.
  76011. */
  76012. PhysicsImpostor.prototype.getParam = function (paramName) {
  76013. return this._options[paramName];
  76014. };
  76015. /**
  76016. * Sets a specific parameter in the options given to the physics plugin
  76017. */
  76018. PhysicsImpostor.prototype.setParam = function (paramName, value) {
  76019. this._options[paramName] = value;
  76020. this._bodyUpdateRequired = true;
  76021. };
  76022. /**
  76023. * Specifically change the body's mass option. Won't recreate the physics body object
  76024. */
  76025. PhysicsImpostor.prototype.setMass = function (mass) {
  76026. if (this.getParam("mass") !== mass) {
  76027. this.setParam("mass", mass);
  76028. }
  76029. if (this._physicsEngine) {
  76030. this._physicsEngine.getPhysicsPlugin().setBodyMass(this, mass);
  76031. }
  76032. };
  76033. PhysicsImpostor.prototype.getLinearVelocity = function () {
  76034. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getLinearVelocity(this) : BABYLON.Vector3.Zero();
  76035. };
  76036. PhysicsImpostor.prototype.setLinearVelocity = function (velocity) {
  76037. if (this._physicsEngine) {
  76038. this._physicsEngine.getPhysicsPlugin().setLinearVelocity(this, velocity);
  76039. }
  76040. };
  76041. PhysicsImpostor.prototype.getAngularVelocity = function () {
  76042. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getAngularVelocity(this) : BABYLON.Vector3.Zero();
  76043. };
  76044. PhysicsImpostor.prototype.setAngularVelocity = function (velocity) {
  76045. if (this._physicsEngine) {
  76046. this._physicsEngine.getPhysicsPlugin().setAngularVelocity(this, velocity);
  76047. }
  76048. };
  76049. /**
  76050. * Execute a function with the physics plugin native code.
  76051. * Provide a function the will have two variables - the world object and the physics body object.
  76052. */
  76053. PhysicsImpostor.prototype.executeNativeFunction = function (func) {
  76054. if (this._physicsEngine) {
  76055. func(this._physicsEngine.getPhysicsPlugin().world, this.physicsBody);
  76056. }
  76057. };
  76058. /**
  76059. * Register a function that will be executed before the physics world is stepping forward.
  76060. */
  76061. PhysicsImpostor.prototype.registerBeforePhysicsStep = function (func) {
  76062. this._onBeforePhysicsStepCallbacks.push(func);
  76063. };
  76064. PhysicsImpostor.prototype.unregisterBeforePhysicsStep = function (func) {
  76065. var index = this._onBeforePhysicsStepCallbacks.indexOf(func);
  76066. if (index > -1) {
  76067. this._onBeforePhysicsStepCallbacks.splice(index, 1);
  76068. }
  76069. else {
  76070. BABYLON.Tools.Warn("Function to remove was not found");
  76071. }
  76072. };
  76073. /**
  76074. * Register a function that will be executed after the physics step
  76075. */
  76076. PhysicsImpostor.prototype.registerAfterPhysicsStep = function (func) {
  76077. this._onAfterPhysicsStepCallbacks.push(func);
  76078. };
  76079. PhysicsImpostor.prototype.unregisterAfterPhysicsStep = function (func) {
  76080. var index = this._onAfterPhysicsStepCallbacks.indexOf(func);
  76081. if (index > -1) {
  76082. this._onAfterPhysicsStepCallbacks.splice(index, 1);
  76083. }
  76084. else {
  76085. BABYLON.Tools.Warn("Function to remove was not found");
  76086. }
  76087. };
  76088. /**
  76089. * register a function that will be executed when this impostor collides against a different body.
  76090. */
  76091. PhysicsImpostor.prototype.registerOnPhysicsCollide = function (collideAgainst, func) {
  76092. var collidedAgainstList = collideAgainst instanceof Array ? collideAgainst : [collideAgainst];
  76093. this._onPhysicsCollideCallbacks.push({ callback: func, otherImpostors: collidedAgainstList });
  76094. };
  76095. PhysicsImpostor.prototype.unregisterOnPhysicsCollide = function (collideAgainst, func) {
  76096. var collidedAgainstList = collideAgainst instanceof Array ? collideAgainst : [collideAgainst];
  76097. var index = this._onPhysicsCollideCallbacks.indexOf({ callback: func, otherImpostors: collidedAgainstList });
  76098. if (index > -1) {
  76099. this._onPhysicsCollideCallbacks.splice(index, 1);
  76100. }
  76101. else {
  76102. BABYLON.Tools.Warn("Function to remove was not found");
  76103. }
  76104. };
  76105. PhysicsImpostor.prototype.getParentsRotation = function () {
  76106. var parent = this.object.parent;
  76107. this._tmpQuat.copyFromFloats(0, 0, 0, 1);
  76108. while (parent) {
  76109. if (parent.rotationQuaternion) {
  76110. this._tmpQuat2.copyFrom(parent.rotationQuaternion);
  76111. }
  76112. else {
  76113. BABYLON.Quaternion.RotationYawPitchRollToRef(parent.rotation.y, parent.rotation.x, parent.rotation.z, this._tmpQuat2);
  76114. }
  76115. this._tmpQuat.multiplyToRef(this._tmpQuat2, this._tmpQuat);
  76116. parent = parent.parent;
  76117. }
  76118. return this._tmpQuat;
  76119. };
  76120. /**
  76121. * Apply a force
  76122. */
  76123. PhysicsImpostor.prototype.applyForce = function (force, contactPoint) {
  76124. if (this._physicsEngine) {
  76125. this._physicsEngine.getPhysicsPlugin().applyForce(this, force, contactPoint);
  76126. }
  76127. return this;
  76128. };
  76129. /**
  76130. * Apply an impulse
  76131. */
  76132. PhysicsImpostor.prototype.applyImpulse = function (force, contactPoint) {
  76133. if (this._physicsEngine) {
  76134. this._physicsEngine.getPhysicsPlugin().applyImpulse(this, force, contactPoint);
  76135. }
  76136. return this;
  76137. };
  76138. /**
  76139. * A help function to create a joint.
  76140. */
  76141. PhysicsImpostor.prototype.createJoint = function (otherImpostor, jointType, jointData) {
  76142. var joint = new BABYLON.PhysicsJoint(jointType, jointData);
  76143. this.addJoint(otherImpostor, joint);
  76144. return this;
  76145. };
  76146. /**
  76147. * Add a joint to this impostor with a different impostor.
  76148. */
  76149. PhysicsImpostor.prototype.addJoint = function (otherImpostor, joint) {
  76150. this._joints.push({
  76151. otherImpostor: otherImpostor,
  76152. joint: joint
  76153. });
  76154. if (this._physicsEngine) {
  76155. this._physicsEngine.addJoint(this, otherImpostor, joint);
  76156. }
  76157. return this;
  76158. };
  76159. /**
  76160. * Will keep this body still, in a sleep mode.
  76161. */
  76162. PhysicsImpostor.prototype.sleep = function () {
  76163. if (this._physicsEngine) {
  76164. this._physicsEngine.getPhysicsPlugin().sleepBody(this);
  76165. }
  76166. return this;
  76167. };
  76168. /**
  76169. * Wake the body up.
  76170. */
  76171. PhysicsImpostor.prototype.wakeUp = function () {
  76172. if (this._physicsEngine) {
  76173. this._physicsEngine.getPhysicsPlugin().wakeUpBody(this);
  76174. }
  76175. return this;
  76176. };
  76177. PhysicsImpostor.prototype.clone = function (newObject) {
  76178. if (!newObject)
  76179. return null;
  76180. return new PhysicsImpostor(newObject, this.type, this._options, this._scene);
  76181. };
  76182. PhysicsImpostor.prototype.dispose = function () {
  76183. var _this = this;
  76184. //no dispose if no physics engine is available.
  76185. if (!this._physicsEngine) {
  76186. return;
  76187. }
  76188. this._joints.forEach(function (j) {
  76189. if (_this._physicsEngine) {
  76190. _this._physicsEngine.removeJoint(_this, j.otherImpostor, j.joint);
  76191. }
  76192. });
  76193. //dispose the physics body
  76194. this._physicsEngine.removeImpostor(this);
  76195. if (this.parent) {
  76196. this.parent.forceUpdate();
  76197. }
  76198. else {
  76199. /*this._object.getChildMeshes().forEach(function(mesh) {
  76200. if (mesh.physicsImpostor) {
  76201. if (disposeChildren) {
  76202. mesh.physicsImpostor.dispose();
  76203. mesh.physicsImpostor = null;
  76204. }
  76205. }
  76206. })*/
  76207. }
  76208. this._isDisposed = true;
  76209. };
  76210. PhysicsImpostor.prototype.setDeltaPosition = function (position) {
  76211. this._deltaPosition.copyFrom(position);
  76212. };
  76213. PhysicsImpostor.prototype.setDeltaRotation = function (rotation) {
  76214. if (!this._deltaRotation) {
  76215. this._deltaRotation = new BABYLON.Quaternion();
  76216. }
  76217. this._deltaRotation.copyFrom(rotation);
  76218. this._deltaRotationConjugated = this._deltaRotation.conjugate();
  76219. };
  76220. PhysicsImpostor.prototype.getBoxSizeToRef = function (result) {
  76221. if (this._physicsEngine) {
  76222. this._physicsEngine.getPhysicsPlugin().getBoxSizeToRef(this, result);
  76223. }
  76224. return this;
  76225. };
  76226. PhysicsImpostor.prototype.getRadius = function () {
  76227. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getRadius(this) : 0;
  76228. };
  76229. /**
  76230. * Sync a bone with this impostor
  76231. * @param bone The bone to sync to the impostor.
  76232. * @param boneMesh The mesh that the bone is influencing.
  76233. * @param jointPivot The pivot of the joint / bone in local space.
  76234. * @param distToJoint Optional distance from the impostor to the joint.
  76235. * @param adjustRotation Optional quaternion for adjusting the local rotation of the bone.
  76236. */
  76237. PhysicsImpostor.prototype.syncBoneWithImpostor = function (bone, boneMesh, jointPivot, distToJoint, adjustRotation) {
  76238. var tempVec = PhysicsImpostor._tmpVecs[0];
  76239. var mesh = this.object;
  76240. if (mesh.rotationQuaternion) {
  76241. if (adjustRotation) {
  76242. var tempQuat = PhysicsImpostor._tmpQuat;
  76243. mesh.rotationQuaternion.multiplyToRef(adjustRotation, tempQuat);
  76244. bone.setRotationQuaternion(tempQuat, BABYLON.Space.WORLD, boneMesh);
  76245. }
  76246. else {
  76247. bone.setRotationQuaternion(mesh.rotationQuaternion, BABYLON.Space.WORLD, boneMesh);
  76248. }
  76249. }
  76250. tempVec.x = 0;
  76251. tempVec.y = 0;
  76252. tempVec.z = 0;
  76253. if (jointPivot) {
  76254. tempVec.x = jointPivot.x;
  76255. tempVec.y = jointPivot.y;
  76256. tempVec.z = jointPivot.z;
  76257. bone.getDirectionToRef(tempVec, boneMesh, tempVec);
  76258. if (distToJoint === undefined || distToJoint === null) {
  76259. distToJoint = jointPivot.length();
  76260. }
  76261. tempVec.x *= distToJoint;
  76262. tempVec.y *= distToJoint;
  76263. tempVec.z *= distToJoint;
  76264. }
  76265. if (bone.getParent()) {
  76266. tempVec.addInPlace(mesh.getAbsolutePosition());
  76267. bone.setAbsolutePosition(tempVec, boneMesh);
  76268. }
  76269. else {
  76270. boneMesh.setAbsolutePosition(mesh.getAbsolutePosition());
  76271. boneMesh.position.x -= tempVec.x;
  76272. boneMesh.position.y -= tempVec.y;
  76273. boneMesh.position.z -= tempVec.z;
  76274. }
  76275. };
  76276. /**
  76277. * Sync impostor to a bone
  76278. * @param bone The bone that the impostor will be synced to.
  76279. * @param boneMesh The mesh that the bone is influencing.
  76280. * @param jointPivot The pivot of the joint / bone in local space.
  76281. * @param distToJoint Optional distance from the impostor to the joint.
  76282. * @param adjustRotation Optional quaternion for adjusting the local rotation of the bone.
  76283. * @param boneAxis Optional vector3 axis the bone is aligned with
  76284. */
  76285. PhysicsImpostor.prototype.syncImpostorWithBone = function (bone, boneMesh, jointPivot, distToJoint, adjustRotation, boneAxis) {
  76286. var mesh = this.object;
  76287. if (mesh.rotationQuaternion) {
  76288. if (adjustRotation) {
  76289. var tempQuat = PhysicsImpostor._tmpQuat;
  76290. bone.getRotationQuaternionToRef(BABYLON.Space.WORLD, boneMesh, tempQuat);
  76291. tempQuat.multiplyToRef(adjustRotation, mesh.rotationQuaternion);
  76292. }
  76293. else {
  76294. bone.getRotationQuaternionToRef(BABYLON.Space.WORLD, boneMesh, mesh.rotationQuaternion);
  76295. }
  76296. }
  76297. var pos = PhysicsImpostor._tmpVecs[0];
  76298. var boneDir = PhysicsImpostor._tmpVecs[1];
  76299. if (!boneAxis) {
  76300. boneAxis = PhysicsImpostor._tmpVecs[2];
  76301. boneAxis.x = 0;
  76302. boneAxis.y = 1;
  76303. boneAxis.z = 0;
  76304. }
  76305. bone.getDirectionToRef(boneAxis, boneMesh, boneDir);
  76306. bone.getAbsolutePositionToRef(boneMesh, pos);
  76307. if ((distToJoint === undefined || distToJoint === null) && jointPivot) {
  76308. distToJoint = jointPivot.length();
  76309. }
  76310. if (distToJoint !== undefined && distToJoint !== null) {
  76311. pos.x += boneDir.x * distToJoint;
  76312. pos.y += boneDir.y * distToJoint;
  76313. pos.z += boneDir.z * distToJoint;
  76314. }
  76315. mesh.setAbsolutePosition(pos);
  76316. };
  76317. PhysicsImpostor.DEFAULT_OBJECT_SIZE = new BABYLON.Vector3(1, 1, 1);
  76318. PhysicsImpostor.IDENTITY_QUATERNION = BABYLON.Quaternion.Identity();
  76319. PhysicsImpostor._tmpVecs = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  76320. PhysicsImpostor._tmpQuat = BABYLON.Quaternion.Identity();
  76321. //Impostor types
  76322. PhysicsImpostor.NoImpostor = 0;
  76323. PhysicsImpostor.SphereImpostor = 1;
  76324. PhysicsImpostor.BoxImpostor = 2;
  76325. PhysicsImpostor.PlaneImpostor = 3;
  76326. PhysicsImpostor.MeshImpostor = 4;
  76327. PhysicsImpostor.CylinderImpostor = 7;
  76328. PhysicsImpostor.ParticleImpostor = 8;
  76329. PhysicsImpostor.HeightmapImpostor = 9;
  76330. return PhysicsImpostor;
  76331. }());
  76332. BABYLON.PhysicsImpostor = PhysicsImpostor;
  76333. })(BABYLON || (BABYLON = {}));
  76334. //# sourceMappingURL=babylon.physicsImpostor.js.map
  76335. var BABYLON;
  76336. (function (BABYLON) {
  76337. var PhysicsEngine = /** @class */ (function () {
  76338. function PhysicsEngine(gravity, _physicsPlugin) {
  76339. if (_physicsPlugin === void 0) { _physicsPlugin = new BABYLON.CannonJSPlugin(); }
  76340. this._physicsPlugin = _physicsPlugin;
  76341. //new methods and parameters
  76342. this._impostors = [];
  76343. this._joints = [];
  76344. if (!this._physicsPlugin.isSupported()) {
  76345. throw new Error("Physics Engine " + this._physicsPlugin.name + " cannot be found. "
  76346. + "Please make sure it is included.");
  76347. }
  76348. gravity = gravity || new BABYLON.Vector3(0, -9.807, 0);
  76349. this.setGravity(gravity);
  76350. this.setTimeStep();
  76351. }
  76352. PhysicsEngine.prototype.setGravity = function (gravity) {
  76353. this.gravity = gravity;
  76354. this._physicsPlugin.setGravity(this.gravity);
  76355. };
  76356. /**
  76357. * Set the time step of the physics engine.
  76358. * default is 1/60.
  76359. * To slow it down, enter 1/600 for example.
  76360. * To speed it up, 1/30
  76361. * @param {number} newTimeStep the new timestep to apply to this world.
  76362. */
  76363. PhysicsEngine.prototype.setTimeStep = function (newTimeStep) {
  76364. if (newTimeStep === void 0) { newTimeStep = 1 / 60; }
  76365. this._physicsPlugin.setTimeStep(newTimeStep);
  76366. };
  76367. /**
  76368. * Get the time step of the physics engine.
  76369. */
  76370. PhysicsEngine.prototype.getTimeStep = function () {
  76371. return this._physicsPlugin.getTimeStep();
  76372. };
  76373. PhysicsEngine.prototype.dispose = function () {
  76374. this._impostors.forEach(function (impostor) {
  76375. impostor.dispose();
  76376. });
  76377. this._physicsPlugin.dispose();
  76378. };
  76379. PhysicsEngine.prototype.getPhysicsPluginName = function () {
  76380. return this._physicsPlugin.name;
  76381. };
  76382. /**
  76383. * Adding a new impostor for the impostor tracking.
  76384. * This will be done by the impostor itself.
  76385. * @param {PhysicsImpostor} impostor the impostor to add
  76386. */
  76387. PhysicsEngine.prototype.addImpostor = function (impostor) {
  76388. impostor.uniqueId = this._impostors.push(impostor);
  76389. //if no parent, generate the body
  76390. if (!impostor.parent) {
  76391. this._physicsPlugin.generatePhysicsBody(impostor);
  76392. }
  76393. };
  76394. /**
  76395. * Remove an impostor from the engine.
  76396. * This impostor and its mesh will not longer be updated by the physics engine.
  76397. * @param {PhysicsImpostor} impostor the impostor to remove
  76398. */
  76399. PhysicsEngine.prototype.removeImpostor = function (impostor) {
  76400. var index = this._impostors.indexOf(impostor);
  76401. if (index > -1) {
  76402. var removed = this._impostors.splice(index, 1);
  76403. //Is it needed?
  76404. if (removed.length) {
  76405. //this will also remove it from the world.
  76406. removed[0].physicsBody = null;
  76407. }
  76408. }
  76409. };
  76410. /**
  76411. * Add a joint to the physics engine
  76412. * @param {PhysicsImpostor} mainImpostor the main impostor to which the joint is added.
  76413. * @param {PhysicsImpostor} connectedImpostor the impostor that is connected to the main impostor using this joint
  76414. * @param {PhysicsJoint} the joint that will connect both impostors.
  76415. */
  76416. PhysicsEngine.prototype.addJoint = function (mainImpostor, connectedImpostor, joint) {
  76417. var impostorJoint = {
  76418. mainImpostor: mainImpostor,
  76419. connectedImpostor: connectedImpostor,
  76420. joint: joint
  76421. };
  76422. joint.physicsPlugin = this._physicsPlugin;
  76423. this._joints.push(impostorJoint);
  76424. this._physicsPlugin.generateJoint(impostorJoint);
  76425. };
  76426. PhysicsEngine.prototype.removeJoint = function (mainImpostor, connectedImpostor, joint) {
  76427. var matchingJoints = this._joints.filter(function (impostorJoint) {
  76428. return (impostorJoint.connectedImpostor === connectedImpostor
  76429. && impostorJoint.joint === joint
  76430. && impostorJoint.mainImpostor === mainImpostor);
  76431. });
  76432. if (matchingJoints.length) {
  76433. this._physicsPlugin.removeJoint(matchingJoints[0]);
  76434. //TODO remove it from the list as well
  76435. }
  76436. };
  76437. /**
  76438. * Called by the scene. no need to call it.
  76439. */
  76440. PhysicsEngine.prototype._step = function (delta) {
  76441. var _this = this;
  76442. //check if any mesh has no body / requires an update
  76443. this._impostors.forEach(function (impostor) {
  76444. if (impostor.isBodyInitRequired()) {
  76445. _this._physicsPlugin.generatePhysicsBody(impostor);
  76446. }
  76447. });
  76448. if (delta > 0.1) {
  76449. delta = 0.1;
  76450. }
  76451. else if (delta <= 0) {
  76452. delta = 1.0 / 60.0;
  76453. }
  76454. this._physicsPlugin.executeStep(delta, this._impostors);
  76455. };
  76456. PhysicsEngine.prototype.getPhysicsPlugin = function () {
  76457. return this._physicsPlugin;
  76458. };
  76459. PhysicsEngine.prototype.getImpostors = function () {
  76460. return this._impostors;
  76461. };
  76462. PhysicsEngine.prototype.getImpostorForPhysicsObject = function (object) {
  76463. for (var i = 0; i < this._impostors.length; ++i) {
  76464. if (this._impostors[i].object === object) {
  76465. return this._impostors[i];
  76466. }
  76467. }
  76468. return null;
  76469. };
  76470. PhysicsEngine.prototype.getImpostorWithPhysicsBody = function (body) {
  76471. for (var i = 0; i < this._impostors.length; ++i) {
  76472. if (this._impostors[i].physicsBody === body) {
  76473. return this._impostors[i];
  76474. }
  76475. }
  76476. return null;
  76477. };
  76478. // Statics
  76479. PhysicsEngine.Epsilon = 0.001;
  76480. return PhysicsEngine;
  76481. }());
  76482. BABYLON.PhysicsEngine = PhysicsEngine;
  76483. })(BABYLON || (BABYLON = {}));
  76484. //# sourceMappingURL=babylon.physicsEngine.js.map
  76485. var BABYLON;
  76486. (function (BABYLON) {
  76487. var PhysicsHelper = /** @class */ (function () {
  76488. function PhysicsHelper(scene) {
  76489. this._scene = scene;
  76490. this._physicsEngine = this._scene.getPhysicsEngine();
  76491. if (!this._physicsEngine) {
  76492. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you can use the methods.');
  76493. }
  76494. }
  76495. /**
  76496. * @param {Vector3} origin the origin of the explosion
  76497. * @param {number} radius the explosion radius
  76498. * @param {number} strength the explosion strength
  76499. * @param {PhysicsRadialImpulseFalloff} falloff possible options: Constant & Linear. Defaults to Constant
  76500. */
  76501. PhysicsHelper.prototype.applyRadialExplosionImpulse = function (origin, radius, strength, falloff) {
  76502. if (falloff === void 0) { falloff = PhysicsRadialImpulseFalloff.Constant; }
  76503. if (!this._physicsEngine) {
  76504. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you call this method.');
  76505. return null;
  76506. }
  76507. var impostors = this._physicsEngine.getImpostors();
  76508. if (impostors.length === 0) {
  76509. return null;
  76510. }
  76511. var event = new PhysicsRadialExplosionEvent(this._scene);
  76512. impostors.forEach(function (impostor) {
  76513. var impostorForceAndContactPoint = event.getImpostorForceAndContactPoint(impostor, origin, radius, strength, falloff);
  76514. if (!impostorForceAndContactPoint) {
  76515. return;
  76516. }
  76517. impostor.applyImpulse(impostorForceAndContactPoint.force, impostorForceAndContactPoint.contactPoint);
  76518. });
  76519. event.dispose(false);
  76520. return event;
  76521. };
  76522. /**
  76523. * @param {Vector3} origin the origin of the explosion
  76524. * @param {number} radius the explosion radius
  76525. * @param {number} strength the explosion strength
  76526. * @param {PhysicsRadialImpulseFalloff} falloff possible options: Constant & Linear. Defaults to Constant
  76527. */
  76528. PhysicsHelper.prototype.applyRadialExplosionForce = function (origin, radius, strength, falloff) {
  76529. if (falloff === void 0) { falloff = PhysicsRadialImpulseFalloff.Constant; }
  76530. if (!this._physicsEngine) {
  76531. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you call the PhysicsHelper.');
  76532. return null;
  76533. }
  76534. var impostors = this._physicsEngine.getImpostors();
  76535. if (impostors.length === 0) {
  76536. return null;
  76537. }
  76538. var event = new PhysicsRadialExplosionEvent(this._scene);
  76539. impostors.forEach(function (impostor) {
  76540. var impostorForceAndContactPoint = event.getImpostorForceAndContactPoint(impostor, origin, radius, strength, falloff);
  76541. if (!impostorForceAndContactPoint) {
  76542. return;
  76543. }
  76544. impostor.applyForce(impostorForceAndContactPoint.force, impostorForceAndContactPoint.contactPoint);
  76545. });
  76546. event.dispose(false);
  76547. return event;
  76548. };
  76549. /**
  76550. * @param {Vector3} origin the origin of the explosion
  76551. * @param {number} radius the explosion radius
  76552. * @param {number} strength the explosion strength
  76553. * @param {PhysicsRadialImpulseFalloff} falloff possible options: Constant & Linear. Defaults to Constant
  76554. */
  76555. PhysicsHelper.prototype.gravitationalField = function (origin, radius, strength, falloff) {
  76556. if (falloff === void 0) { falloff = PhysicsRadialImpulseFalloff.Constant; }
  76557. if (!this._physicsEngine) {
  76558. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you call the PhysicsHelper.');
  76559. return null;
  76560. }
  76561. var impostors = this._physicsEngine.getImpostors();
  76562. if (impostors.length === 0) {
  76563. return null;
  76564. }
  76565. var event = new PhysicsGravitationalFieldEvent(this, this._scene, origin, radius, strength, falloff);
  76566. event.dispose(false);
  76567. return event;
  76568. };
  76569. /**
  76570. * @param {Vector3} origin the origin of the updraft
  76571. * @param {number} radius the radius of the updraft
  76572. * @param {number} strength the strength of the updraft
  76573. * @param {number} height the height of the updraft
  76574. * @param {PhysicsUpdraftMode} updraftMode possible options: Center & Perpendicular. Defaults to Center
  76575. */
  76576. PhysicsHelper.prototype.updraft = function (origin, radius, strength, height, updraftMode) {
  76577. if (updraftMode === void 0) { updraftMode = PhysicsUpdraftMode.Center; }
  76578. if (!this._physicsEngine) {
  76579. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you call the PhysicsHelper.');
  76580. return null;
  76581. }
  76582. if (this._physicsEngine.getImpostors().length === 0) {
  76583. return null;
  76584. }
  76585. var event = new PhysicsUpdraftEvent(this._scene, origin, radius, strength, height, updraftMode);
  76586. event.dispose(false);
  76587. return event;
  76588. };
  76589. /**
  76590. * @param {Vector3} origin the of the vortex
  76591. * @param {number} radius the radius of the vortex
  76592. * @param {number} strength the strength of the vortex
  76593. * @param {number} height the height of the vortex
  76594. */
  76595. PhysicsHelper.prototype.vortex = function (origin, radius, strength, height) {
  76596. if (!this._physicsEngine) {
  76597. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you call the PhysicsHelper.');
  76598. return null;
  76599. }
  76600. if (this._physicsEngine.getImpostors().length === 0) {
  76601. return null;
  76602. }
  76603. var event = new PhysicsVortexEvent(this._scene, origin, radius, strength, height);
  76604. event.dispose(false);
  76605. return event;
  76606. };
  76607. return PhysicsHelper;
  76608. }());
  76609. BABYLON.PhysicsHelper = PhysicsHelper;
  76610. /***** Radial explosion *****/
  76611. var PhysicsRadialExplosionEvent = /** @class */ (function () {
  76612. function PhysicsRadialExplosionEvent(scene) {
  76613. this._sphereOptions = { segments: 32, diameter: 1 }; // TODO: make configurable
  76614. this._rays = [];
  76615. this._dataFetched = false; // check if the data has been fetched. If not, do cleanup
  76616. this._scene = scene;
  76617. }
  76618. /**
  76619. * Returns the data related to the radial explosion event (sphere & rays).
  76620. * @returns {PhysicsRadialExplosionEventData}
  76621. */
  76622. PhysicsRadialExplosionEvent.prototype.getData = function () {
  76623. this._dataFetched = true;
  76624. return {
  76625. sphere: this._sphere,
  76626. rays: this._rays,
  76627. };
  76628. };
  76629. /**
  76630. * Returns the force and contact point of the impostor or false, if the impostor is not affected by the force/impulse.
  76631. * @param impostor
  76632. * @param {Vector3} origin the origin of the explosion
  76633. * @param {number} radius the explosion radius
  76634. * @param {number} strength the explosion strength
  76635. * @param {PhysicsRadialImpulseFalloff} falloff possible options: Constant & Linear
  76636. * @returns {Nullable<PhysicsForceAndContactPoint>}
  76637. */
  76638. PhysicsRadialExplosionEvent.prototype.getImpostorForceAndContactPoint = function (impostor, origin, radius, strength, falloff) {
  76639. if (impostor.mass === 0) {
  76640. return null;
  76641. }
  76642. if (!this._intersectsWithSphere(impostor, origin, radius)) {
  76643. return null;
  76644. }
  76645. if (impostor.object.getClassName() !== 'Mesh') {
  76646. return null;
  76647. }
  76648. var impostorObject = impostor.object;
  76649. var impostorObjectCenter = impostor.getObjectCenter();
  76650. var direction = impostorObjectCenter.subtract(origin);
  76651. var ray = new BABYLON.Ray(origin, direction, radius);
  76652. this._rays.push(ray);
  76653. var hit = ray.intersectsMesh(impostorObject);
  76654. var contactPoint = hit.pickedPoint;
  76655. if (!contactPoint) {
  76656. return null;
  76657. }
  76658. var distanceFromOrigin = BABYLON.Vector3.Distance(origin, contactPoint);
  76659. if (distanceFromOrigin > radius) {
  76660. return null;
  76661. }
  76662. var multiplier = falloff === PhysicsRadialImpulseFalloff.Constant
  76663. ? strength
  76664. : strength * (1 - (distanceFromOrigin / radius));
  76665. var force = direction.multiplyByFloats(multiplier, multiplier, multiplier);
  76666. return { force: force, contactPoint: contactPoint };
  76667. };
  76668. /**
  76669. * Disposes the sphere.
  76670. * @param {bolean} force
  76671. */
  76672. PhysicsRadialExplosionEvent.prototype.dispose = function (force) {
  76673. var _this = this;
  76674. if (force === void 0) { force = true; }
  76675. if (force) {
  76676. this._sphere.dispose();
  76677. }
  76678. else {
  76679. setTimeout(function () {
  76680. if (!_this._dataFetched) {
  76681. _this._sphere.dispose();
  76682. }
  76683. }, 0);
  76684. }
  76685. };
  76686. /*** Helpers ***/
  76687. PhysicsRadialExplosionEvent.prototype._prepareSphere = function () {
  76688. if (!this._sphere) {
  76689. this._sphere = BABYLON.MeshBuilder.CreateSphere("radialExplosionEventSphere", this._sphereOptions, this._scene);
  76690. this._sphere.isVisible = false;
  76691. }
  76692. };
  76693. PhysicsRadialExplosionEvent.prototype._intersectsWithSphere = function (impostor, origin, radius) {
  76694. var impostorObject = impostor.object;
  76695. this._prepareSphere();
  76696. this._sphere.position = origin;
  76697. this._sphere.scaling = new BABYLON.Vector3(radius * 2, radius * 2, radius * 2);
  76698. this._sphere._updateBoundingInfo();
  76699. this._sphere.computeWorldMatrix(true);
  76700. return this._sphere.intersectsMesh(impostorObject, true);
  76701. };
  76702. return PhysicsRadialExplosionEvent;
  76703. }());
  76704. BABYLON.PhysicsRadialExplosionEvent = PhysicsRadialExplosionEvent;
  76705. /***** Gravitational Field *****/
  76706. var PhysicsGravitationalFieldEvent = /** @class */ (function () {
  76707. function PhysicsGravitationalFieldEvent(physicsHelper, scene, origin, radius, strength, falloff) {
  76708. if (falloff === void 0) { falloff = PhysicsRadialImpulseFalloff.Constant; }
  76709. this._dataFetched = false; // check if the has been fetched the data. If not, do cleanup
  76710. this._physicsHelper = physicsHelper;
  76711. this._scene = scene;
  76712. this._origin = origin;
  76713. this._radius = radius;
  76714. this._strength = strength;
  76715. this._falloff = falloff;
  76716. this._tickCallback = this._tick.bind(this);
  76717. }
  76718. /**
  76719. * Returns the data related to the gravitational field event (sphere).
  76720. * @returns {PhysicsGravitationalFieldEventData}
  76721. */
  76722. PhysicsGravitationalFieldEvent.prototype.getData = function () {
  76723. this._dataFetched = true;
  76724. return {
  76725. sphere: this._sphere,
  76726. };
  76727. };
  76728. /**
  76729. * Enables the gravitational field.
  76730. */
  76731. PhysicsGravitationalFieldEvent.prototype.enable = function () {
  76732. this._tickCallback.call(this);
  76733. this._scene.registerBeforeRender(this._tickCallback);
  76734. };
  76735. /**
  76736. * Disables the gravitational field.
  76737. */
  76738. PhysicsGravitationalFieldEvent.prototype.disable = function () {
  76739. this._scene.unregisterBeforeRender(this._tickCallback);
  76740. };
  76741. /**
  76742. * Disposes the sphere.
  76743. * @param {bolean} force
  76744. */
  76745. PhysicsGravitationalFieldEvent.prototype.dispose = function (force) {
  76746. var _this = this;
  76747. if (force === void 0) { force = true; }
  76748. if (force) {
  76749. this._sphere.dispose();
  76750. }
  76751. else {
  76752. setTimeout(function () {
  76753. if (!_this._dataFetched) {
  76754. _this._sphere.dispose();
  76755. }
  76756. }, 0);
  76757. }
  76758. };
  76759. PhysicsGravitationalFieldEvent.prototype._tick = function () {
  76760. // Since the params won't change, we fetch the event only once
  76761. if (this._sphere) {
  76762. this._physicsHelper.applyRadialExplosionForce(this._origin, this._radius, this._strength * -1, this._falloff);
  76763. }
  76764. else {
  76765. var radialExplosionEvent = this._physicsHelper.applyRadialExplosionForce(this._origin, this._radius, this._strength * -1, this._falloff);
  76766. if (radialExplosionEvent) {
  76767. this._sphere = radialExplosionEvent.getData().sphere.clone('radialExplosionEventSphereClone');
  76768. }
  76769. }
  76770. };
  76771. return PhysicsGravitationalFieldEvent;
  76772. }());
  76773. BABYLON.PhysicsGravitationalFieldEvent = PhysicsGravitationalFieldEvent;
  76774. /***** Updraft *****/
  76775. var PhysicsUpdraftEvent = /** @class */ (function () {
  76776. function PhysicsUpdraftEvent(_scene, _origin, _radius, _strength, _height, _updraftMode) {
  76777. this._scene = _scene;
  76778. this._origin = _origin;
  76779. this._radius = _radius;
  76780. this._strength = _strength;
  76781. this._height = _height;
  76782. this._updraftMode = _updraftMode;
  76783. this._originTop = BABYLON.Vector3.Zero(); // the most upper part of the cylinder
  76784. this._originDirection = BABYLON.Vector3.Zero(); // used if the updraftMode is perpendicular
  76785. this._cylinderPosition = BABYLON.Vector3.Zero(); // to keep the cylinders position, because normally the origin is in the center and not on the bottom
  76786. this._dataFetched = false; // check if the has been fetched the data. If not, do cleanup
  76787. this._physicsEngine = this._scene.getPhysicsEngine();
  76788. this._origin.addToRef(new BABYLON.Vector3(0, this._height / 2, 0), this._cylinderPosition);
  76789. this._origin.addToRef(new BABYLON.Vector3(0, this._height, 0), this._originTop);
  76790. if (this._updraftMode === PhysicsUpdraftMode.Perpendicular) {
  76791. this._originDirection = this._origin.subtract(this._originTop).normalize();
  76792. }
  76793. this._tickCallback = this._tick.bind(this);
  76794. }
  76795. /**
  76796. * Returns the data related to the updraft event (cylinder).
  76797. * @returns {PhysicsUpdraftEventData}
  76798. */
  76799. PhysicsUpdraftEvent.prototype.getData = function () {
  76800. this._dataFetched = true;
  76801. return {
  76802. cylinder: this._cylinder,
  76803. };
  76804. };
  76805. /**
  76806. * Enables the updraft.
  76807. */
  76808. PhysicsUpdraftEvent.prototype.enable = function () {
  76809. this._tickCallback.call(this);
  76810. this._scene.registerBeforeRender(this._tickCallback);
  76811. };
  76812. /**
  76813. * Disables the cortex.
  76814. */
  76815. PhysicsUpdraftEvent.prototype.disable = function () {
  76816. this._scene.unregisterBeforeRender(this._tickCallback);
  76817. };
  76818. /**
  76819. * Disposes the sphere.
  76820. * @param {bolean} force
  76821. */
  76822. PhysicsUpdraftEvent.prototype.dispose = function (force) {
  76823. var _this = this;
  76824. if (force === void 0) { force = true; }
  76825. if (force) {
  76826. this._cylinder.dispose();
  76827. }
  76828. else {
  76829. setTimeout(function () {
  76830. if (!_this._dataFetched) {
  76831. _this._cylinder.dispose();
  76832. }
  76833. }, 0);
  76834. }
  76835. };
  76836. PhysicsUpdraftEvent.prototype.getImpostorForceAndContactPoint = function (impostor) {
  76837. if (impostor.mass === 0) {
  76838. return null;
  76839. }
  76840. if (!this._intersectsWithCylinder(impostor)) {
  76841. return null;
  76842. }
  76843. var impostorObjectCenter = impostor.getObjectCenter();
  76844. if (this._updraftMode === PhysicsUpdraftMode.Perpendicular) {
  76845. var direction = this._originDirection;
  76846. }
  76847. else {
  76848. var direction = impostorObjectCenter.subtract(this._originTop);
  76849. }
  76850. var multiplier = this._strength * -1;
  76851. var force = direction.multiplyByFloats(multiplier, multiplier, multiplier);
  76852. return { force: force, contactPoint: impostorObjectCenter };
  76853. };
  76854. PhysicsUpdraftEvent.prototype._tick = function () {
  76855. var _this = this;
  76856. this._physicsEngine.getImpostors().forEach(function (impostor) {
  76857. var impostorForceAndContactPoint = _this.getImpostorForceAndContactPoint(impostor);
  76858. if (!impostorForceAndContactPoint) {
  76859. return;
  76860. }
  76861. impostor.applyForce(impostorForceAndContactPoint.force, impostorForceAndContactPoint.contactPoint);
  76862. });
  76863. };
  76864. /*** Helpers ***/
  76865. PhysicsUpdraftEvent.prototype._prepareCylinder = function () {
  76866. if (!this._cylinder) {
  76867. this._cylinder = BABYLON.MeshBuilder.CreateCylinder("updraftEventCylinder", {
  76868. height: this._height,
  76869. diameter: this._radius * 2,
  76870. }, this._scene);
  76871. this._cylinder.isVisible = false;
  76872. }
  76873. };
  76874. PhysicsUpdraftEvent.prototype._intersectsWithCylinder = function (impostor) {
  76875. var impostorObject = impostor.object;
  76876. this._prepareCylinder();
  76877. this._cylinder.position = this._cylinderPosition;
  76878. return this._cylinder.intersectsMesh(impostorObject, true);
  76879. };
  76880. return PhysicsUpdraftEvent;
  76881. }());
  76882. BABYLON.PhysicsUpdraftEvent = PhysicsUpdraftEvent;
  76883. /***** Vortex *****/
  76884. var PhysicsVortexEvent = /** @class */ (function () {
  76885. function PhysicsVortexEvent(_scene, _origin, _radius, _strength, _height) {
  76886. this._scene = _scene;
  76887. this._origin = _origin;
  76888. this._radius = _radius;
  76889. this._strength = _strength;
  76890. this._height = _height;
  76891. this._originTop = BABYLON.Vector3.Zero(); // the most upper part of the cylinder
  76892. this._centripetalForceThreshold = 0.7; // at which distance, relative to the radius the centripetal forces should kick in
  76893. this._updraftMultiplier = 0.02;
  76894. this._cylinderPosition = BABYLON.Vector3.Zero(); // to keep the cylinders position, because normally the origin is in the center and not on the bottom
  76895. this._dataFetched = false; // check if the has been fetched the data. If not, do cleanup
  76896. this._physicsEngine = this._scene.getPhysicsEngine();
  76897. this._origin.addToRef(new BABYLON.Vector3(0, this._height / 2, 0), this._cylinderPosition);
  76898. this._origin.addToRef(new BABYLON.Vector3(0, this._height, 0), this._originTop);
  76899. this._tickCallback = this._tick.bind(this);
  76900. }
  76901. /**
  76902. * Returns the data related to the vortex event (cylinder).
  76903. * @returns {PhysicsVortexEventData}
  76904. */
  76905. PhysicsVortexEvent.prototype.getData = function () {
  76906. this._dataFetched = true;
  76907. return {
  76908. cylinder: this._cylinder,
  76909. };
  76910. };
  76911. /**
  76912. * Enables the vortex.
  76913. */
  76914. PhysicsVortexEvent.prototype.enable = function () {
  76915. this._tickCallback.call(this);
  76916. this._scene.registerBeforeRender(this._tickCallback);
  76917. };
  76918. /**
  76919. * Disables the cortex.
  76920. */
  76921. PhysicsVortexEvent.prototype.disable = function () {
  76922. this._scene.unregisterBeforeRender(this._tickCallback);
  76923. };
  76924. /**
  76925. * Disposes the sphere.
  76926. * @param {bolean} force
  76927. */
  76928. PhysicsVortexEvent.prototype.dispose = function (force) {
  76929. var _this = this;
  76930. if (force === void 0) { force = true; }
  76931. if (force) {
  76932. this._cylinder.dispose();
  76933. }
  76934. else {
  76935. setTimeout(function () {
  76936. if (!_this._dataFetched) {
  76937. _this._cylinder.dispose();
  76938. }
  76939. }, 0);
  76940. }
  76941. };
  76942. PhysicsVortexEvent.prototype.getImpostorForceAndContactPoint = function (impostor) {
  76943. if (impostor.mass === 0) {
  76944. return null;
  76945. }
  76946. if (!this._intersectsWithCylinder(impostor)) {
  76947. return null;
  76948. }
  76949. if (impostor.object.getClassName() !== 'Mesh') {
  76950. return null;
  76951. }
  76952. var impostorObject = impostor.object;
  76953. var impostorObjectCenter = impostor.getObjectCenter();
  76954. 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)
  76955. var originToImpostorDirection = impostorObjectCenter.subtract(originOnPlane);
  76956. var ray = new BABYLON.Ray(originOnPlane, originToImpostorDirection, this._radius);
  76957. var hit = ray.intersectsMesh(impostorObject);
  76958. var contactPoint = hit.pickedPoint;
  76959. if (!contactPoint) {
  76960. return null;
  76961. }
  76962. var absoluteDistanceFromOrigin = hit.distance / this._radius;
  76963. var perpendicularDirection = BABYLON.Vector3.Cross(originOnPlane, impostorObjectCenter).normalize();
  76964. var directionToOrigin = contactPoint.normalize();
  76965. if (absoluteDistanceFromOrigin > this._centripetalForceThreshold) {
  76966. directionToOrigin = directionToOrigin.negate();
  76967. }
  76968. // TODO: find a more physically based solution
  76969. if (absoluteDistanceFromOrigin > this._centripetalForceThreshold) {
  76970. var forceX = directionToOrigin.x * this._strength / 8;
  76971. var forceY = directionToOrigin.y * this._updraftMultiplier;
  76972. var forceZ = directionToOrigin.z * this._strength / 8;
  76973. }
  76974. else {
  76975. var forceX = (perpendicularDirection.x + directionToOrigin.x) / 2;
  76976. var forceY = this._originTop.y * this._updraftMultiplier;
  76977. var forceZ = (perpendicularDirection.z + directionToOrigin.z) / 2;
  76978. }
  76979. var force = new BABYLON.Vector3(forceX, forceY, forceZ);
  76980. force = force.multiplyByFloats(this._strength, this._strength, this._strength);
  76981. return { force: force, contactPoint: impostorObjectCenter };
  76982. };
  76983. PhysicsVortexEvent.prototype._tick = function () {
  76984. var _this = this;
  76985. this._physicsEngine.getImpostors().forEach(function (impostor) {
  76986. var impostorForceAndContactPoint = _this.getImpostorForceAndContactPoint(impostor);
  76987. if (!impostorForceAndContactPoint) {
  76988. return;
  76989. }
  76990. impostor.applyForce(impostorForceAndContactPoint.force, impostorForceAndContactPoint.contactPoint);
  76991. });
  76992. };
  76993. /*** Helpers ***/
  76994. PhysicsVortexEvent.prototype._prepareCylinder = function () {
  76995. if (!this._cylinder) {
  76996. this._cylinder = BABYLON.MeshBuilder.CreateCylinder("vortexEventCylinder", {
  76997. height: this._height,
  76998. diameter: this._radius * 2,
  76999. }, this._scene);
  77000. this._cylinder.isVisible = false;
  77001. }
  77002. };
  77003. PhysicsVortexEvent.prototype._intersectsWithCylinder = function (impostor) {
  77004. var impostorObject = impostor.object;
  77005. this._prepareCylinder();
  77006. this._cylinder.position = this._cylinderPosition;
  77007. return this._cylinder.intersectsMesh(impostorObject, true);
  77008. };
  77009. return PhysicsVortexEvent;
  77010. }());
  77011. BABYLON.PhysicsVortexEvent = PhysicsVortexEvent;
  77012. /***** Enums *****/
  77013. /**
  77014. * The strenght of the force in correspondence to the distance of the affected object
  77015. */
  77016. var PhysicsRadialImpulseFalloff;
  77017. (function (PhysicsRadialImpulseFalloff) {
  77018. PhysicsRadialImpulseFalloff[PhysicsRadialImpulseFalloff["Constant"] = 0] = "Constant";
  77019. PhysicsRadialImpulseFalloff[PhysicsRadialImpulseFalloff["Linear"] = 1] = "Linear"; // impulse gets weaker if it's further from the origin
  77020. })(PhysicsRadialImpulseFalloff = BABYLON.PhysicsRadialImpulseFalloff || (BABYLON.PhysicsRadialImpulseFalloff = {}));
  77021. /**
  77022. * The strenght of the force in correspondence to the distance of the affected object
  77023. */
  77024. var PhysicsUpdraftMode;
  77025. (function (PhysicsUpdraftMode) {
  77026. PhysicsUpdraftMode[PhysicsUpdraftMode["Center"] = 0] = "Center";
  77027. PhysicsUpdraftMode[PhysicsUpdraftMode["Perpendicular"] = 1] = "Perpendicular"; // once a impostor is inside the cylinder, it will shoot out perpendicular from the ground of the cylinder
  77028. })(PhysicsUpdraftMode = BABYLON.PhysicsUpdraftMode || (BABYLON.PhysicsUpdraftMode = {}));
  77029. })(BABYLON || (BABYLON = {}));
  77030. //# sourceMappingURL=babylon.physicsHelper.js.map
  77031. var BABYLON;
  77032. (function (BABYLON) {
  77033. var CannonJSPlugin = /** @class */ (function () {
  77034. function CannonJSPlugin(_useDeltaForWorldStep, iterations) {
  77035. if (_useDeltaForWorldStep === void 0) { _useDeltaForWorldStep = true; }
  77036. if (iterations === void 0) { iterations = 10; }
  77037. this._useDeltaForWorldStep = _useDeltaForWorldStep;
  77038. this.name = "CannonJSPlugin";
  77039. this._physicsMaterials = new Array();
  77040. this._fixedTimeStep = 1 / 60;
  77041. //See https://github.com/schteppe/CANNON.js/blob/gh-pages/demos/collisionFilter.html
  77042. this.BJSCANNON = typeof CANNON !== 'undefined' ? CANNON : (typeof require !== 'undefined' ? require('cannon') : undefined);
  77043. this._minus90X = new BABYLON.Quaternion(-0.7071067811865475, 0, 0, 0.7071067811865475);
  77044. this._plus90X = new BABYLON.Quaternion(0.7071067811865475, 0, 0, 0.7071067811865475);
  77045. this._tmpPosition = BABYLON.Vector3.Zero();
  77046. this._tmpDeltaPosition = BABYLON.Vector3.Zero();
  77047. this._tmpUnityRotation = new BABYLON.Quaternion();
  77048. if (!this.isSupported()) {
  77049. BABYLON.Tools.Error("CannonJS is not available. Please make sure you included the js file.");
  77050. return;
  77051. }
  77052. this._extendNamespace();
  77053. this.world = new this.BJSCANNON.World();
  77054. this.world.broadphase = new this.BJSCANNON.NaiveBroadphase();
  77055. this.world.solver.iterations = iterations;
  77056. }
  77057. CannonJSPlugin.prototype.setGravity = function (gravity) {
  77058. this.world.gravity.copy(gravity);
  77059. };
  77060. CannonJSPlugin.prototype.setTimeStep = function (timeStep) {
  77061. this._fixedTimeStep = timeStep;
  77062. };
  77063. CannonJSPlugin.prototype.getTimeStep = function () {
  77064. return this._fixedTimeStep;
  77065. };
  77066. CannonJSPlugin.prototype.executeStep = function (delta, impostors) {
  77067. this.world.step(this._fixedTimeStep, this._useDeltaForWorldStep ? delta : 0, 3);
  77068. };
  77069. CannonJSPlugin.prototype.applyImpulse = function (impostor, force, contactPoint) {
  77070. var worldPoint = new this.BJSCANNON.Vec3(contactPoint.x, contactPoint.y, contactPoint.z);
  77071. var impulse = new this.BJSCANNON.Vec3(force.x, force.y, force.z);
  77072. impostor.physicsBody.applyImpulse(impulse, worldPoint);
  77073. };
  77074. CannonJSPlugin.prototype.applyForce = function (impostor, force, contactPoint) {
  77075. var worldPoint = new this.BJSCANNON.Vec3(contactPoint.x, contactPoint.y, contactPoint.z);
  77076. var impulse = new this.BJSCANNON.Vec3(force.x, force.y, force.z);
  77077. impostor.physicsBody.applyForce(impulse, worldPoint);
  77078. };
  77079. CannonJSPlugin.prototype.generatePhysicsBody = function (impostor) {
  77080. //parent-child relationship. Does this impostor has a parent impostor?
  77081. if (impostor.parent) {
  77082. if (impostor.physicsBody) {
  77083. this.removePhysicsBody(impostor);
  77084. //TODO is that needed?
  77085. impostor.forceUpdate();
  77086. }
  77087. return;
  77088. }
  77089. //should a new body be created for this impostor?
  77090. if (impostor.isBodyInitRequired()) {
  77091. var shape = this._createShape(impostor);
  77092. //unregister events, if body is being changed
  77093. var oldBody = impostor.physicsBody;
  77094. if (oldBody) {
  77095. this.removePhysicsBody(impostor);
  77096. }
  77097. //create the body and material
  77098. var material = this._addMaterial("mat-" + impostor.uniqueId, impostor.getParam("friction"), impostor.getParam("restitution"));
  77099. var bodyCreationObject = {
  77100. mass: impostor.getParam("mass"),
  77101. material: material
  77102. };
  77103. // A simple extend, in case native options were used.
  77104. var nativeOptions = impostor.getParam("nativeOptions");
  77105. for (var key in nativeOptions) {
  77106. if (nativeOptions.hasOwnProperty(key)) {
  77107. bodyCreationObject[key] = nativeOptions[key];
  77108. }
  77109. }
  77110. impostor.physicsBody = new this.BJSCANNON.Body(bodyCreationObject);
  77111. impostor.physicsBody.addEventListener("collide", impostor.onCollide);
  77112. this.world.addEventListener("preStep", impostor.beforeStep);
  77113. this.world.addEventListener("postStep", impostor.afterStep);
  77114. impostor.physicsBody.addShape(shape);
  77115. this.world.add(impostor.physicsBody);
  77116. //try to keep the body moving in the right direction by taking old properties.
  77117. //Should be tested!
  77118. if (oldBody) {
  77119. ['force', 'torque', 'velocity', 'angularVelocity'].forEach(function (param) {
  77120. impostor.physicsBody[param].copy(oldBody[param]);
  77121. });
  77122. }
  77123. this._processChildMeshes(impostor);
  77124. }
  77125. //now update the body's transformation
  77126. this._updatePhysicsBodyTransformation(impostor);
  77127. };
  77128. CannonJSPlugin.prototype._processChildMeshes = function (mainImpostor) {
  77129. var _this = this;
  77130. var meshChildren = mainImpostor.object.getChildMeshes ? mainImpostor.object.getChildMeshes(true) : [];
  77131. var currentRotation = mainImpostor.object.rotationQuaternion;
  77132. if (meshChildren.length) {
  77133. var processMesh = function (localPosition, mesh) {
  77134. if (!currentRotation || !mesh.rotationQuaternion) {
  77135. return;
  77136. }
  77137. var childImpostor = mesh.getPhysicsImpostor();
  77138. if (childImpostor) {
  77139. var parent = childImpostor.parent;
  77140. if (parent !== mainImpostor) {
  77141. var pPosition = mesh.getAbsolutePosition().subtract(mainImpostor.object.getAbsolutePosition());
  77142. var localRotation = mesh.rotationQuaternion.multiply(BABYLON.Quaternion.Inverse(currentRotation));
  77143. if (childImpostor.physicsBody) {
  77144. _this.removePhysicsBody(childImpostor);
  77145. childImpostor.physicsBody = null;
  77146. }
  77147. childImpostor.parent = mainImpostor;
  77148. childImpostor.resetUpdateFlags();
  77149. 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));
  77150. //Add the mass of the children.
  77151. mainImpostor.physicsBody.mass += childImpostor.getParam("mass");
  77152. }
  77153. }
  77154. currentRotation.multiplyInPlace(mesh.rotationQuaternion);
  77155. mesh.getChildMeshes(true).filter(function (m) { return !!m.physicsImpostor; }).forEach(processMesh.bind(_this, mesh.getAbsolutePosition()));
  77156. };
  77157. meshChildren.filter(function (m) { return !!m.physicsImpostor; }).forEach(processMesh.bind(this, mainImpostor.object.getAbsolutePosition()));
  77158. }
  77159. };
  77160. CannonJSPlugin.prototype.removePhysicsBody = function (impostor) {
  77161. impostor.physicsBody.removeEventListener("collide", impostor.onCollide);
  77162. this.world.removeEventListener("preStep", impostor.beforeStep);
  77163. this.world.removeEventListener("postStep", impostor.afterStep);
  77164. this.world.remove(impostor.physicsBody);
  77165. };
  77166. CannonJSPlugin.prototype.generateJoint = function (impostorJoint) {
  77167. var mainBody = impostorJoint.mainImpostor.physicsBody;
  77168. var connectedBody = impostorJoint.connectedImpostor.physicsBody;
  77169. if (!mainBody || !connectedBody) {
  77170. return;
  77171. }
  77172. var constraint;
  77173. var jointData = impostorJoint.joint.jointData;
  77174. //TODO - https://github.com/schteppe/this.BJSCANNON.js/blob/gh-pages/demos/collisionFilter.html
  77175. var constraintData = {
  77176. pivotA: jointData.mainPivot ? new this.BJSCANNON.Vec3().copy(jointData.mainPivot) : null,
  77177. pivotB: jointData.connectedPivot ? new this.BJSCANNON.Vec3().copy(jointData.connectedPivot) : null,
  77178. axisA: jointData.mainAxis ? new this.BJSCANNON.Vec3().copy(jointData.mainAxis) : null,
  77179. axisB: jointData.connectedAxis ? new this.BJSCANNON.Vec3().copy(jointData.connectedAxis) : null,
  77180. maxForce: jointData.nativeParams.maxForce,
  77181. collideConnected: !!jointData.collision
  77182. };
  77183. switch (impostorJoint.joint.type) {
  77184. case BABYLON.PhysicsJoint.HingeJoint:
  77185. case BABYLON.PhysicsJoint.Hinge2Joint:
  77186. constraint = new this.BJSCANNON.HingeConstraint(mainBody, connectedBody, constraintData);
  77187. break;
  77188. case BABYLON.PhysicsJoint.DistanceJoint:
  77189. constraint = new this.BJSCANNON.DistanceConstraint(mainBody, connectedBody, jointData.maxDistance || 2);
  77190. break;
  77191. case BABYLON.PhysicsJoint.SpringJoint:
  77192. var springData = jointData;
  77193. constraint = new this.BJSCANNON.Spring(mainBody, connectedBody, {
  77194. restLength: springData.length,
  77195. stiffness: springData.stiffness,
  77196. damping: springData.damping,
  77197. localAnchorA: constraintData.pivotA,
  77198. localAnchorB: constraintData.pivotB
  77199. });
  77200. break;
  77201. case BABYLON.PhysicsJoint.LockJoint:
  77202. constraint = new this.BJSCANNON.LockConstraint(mainBody, connectedBody, constraintData);
  77203. break;
  77204. case BABYLON.PhysicsJoint.PointToPointJoint:
  77205. case BABYLON.PhysicsJoint.BallAndSocketJoint:
  77206. default:
  77207. constraint = new this.BJSCANNON.PointToPointConstraint(mainBody, constraintData.pivotA, connectedBody, constraintData.pivotA, constraintData.maxForce);
  77208. break;
  77209. }
  77210. //set the collideConnected flag after the creation, since DistanceJoint ignores it.
  77211. constraint.collideConnected = !!jointData.collision;
  77212. impostorJoint.joint.physicsJoint = constraint;
  77213. //don't add spring as constraint, as it is not one.
  77214. if (impostorJoint.joint.type !== BABYLON.PhysicsJoint.SpringJoint) {
  77215. this.world.addConstraint(constraint);
  77216. }
  77217. else {
  77218. impostorJoint.mainImpostor.registerAfterPhysicsStep(function () {
  77219. constraint.applyForce();
  77220. });
  77221. }
  77222. };
  77223. CannonJSPlugin.prototype.removeJoint = function (impostorJoint) {
  77224. this.world.removeConstraint(impostorJoint.joint.physicsJoint);
  77225. };
  77226. CannonJSPlugin.prototype._addMaterial = function (name, friction, restitution) {
  77227. var index;
  77228. var mat;
  77229. for (index = 0; index < this._physicsMaterials.length; index++) {
  77230. mat = this._physicsMaterials[index];
  77231. if (mat.friction === friction && mat.restitution === restitution) {
  77232. return mat;
  77233. }
  77234. }
  77235. var currentMat = new this.BJSCANNON.Material(name);
  77236. currentMat.friction = friction;
  77237. currentMat.restitution = restitution;
  77238. this._physicsMaterials.push(currentMat);
  77239. return currentMat;
  77240. };
  77241. CannonJSPlugin.prototype._checkWithEpsilon = function (value) {
  77242. return value < BABYLON.PhysicsEngine.Epsilon ? BABYLON.PhysicsEngine.Epsilon : value;
  77243. };
  77244. CannonJSPlugin.prototype._createShape = function (impostor) {
  77245. var object = impostor.object;
  77246. var returnValue;
  77247. var extendSize = impostor.getObjectExtendSize();
  77248. switch (impostor.type) {
  77249. case BABYLON.PhysicsImpostor.SphereImpostor:
  77250. var radiusX = extendSize.x;
  77251. var radiusY = extendSize.y;
  77252. var radiusZ = extendSize.z;
  77253. returnValue = new this.BJSCANNON.Sphere(Math.max(this._checkWithEpsilon(radiusX), this._checkWithEpsilon(radiusY), this._checkWithEpsilon(radiusZ)) / 2);
  77254. break;
  77255. //TMP also for cylinder - TODO Cannon supports cylinder natively.
  77256. case BABYLON.PhysicsImpostor.CylinderImpostor:
  77257. returnValue = new this.BJSCANNON.Cylinder(this._checkWithEpsilon(extendSize.x) / 2, this._checkWithEpsilon(extendSize.x) / 2, this._checkWithEpsilon(extendSize.y), 16);
  77258. break;
  77259. case BABYLON.PhysicsImpostor.BoxImpostor:
  77260. var box = extendSize.scale(0.5);
  77261. returnValue = new this.BJSCANNON.Box(new this.BJSCANNON.Vec3(this._checkWithEpsilon(box.x), this._checkWithEpsilon(box.y), this._checkWithEpsilon(box.z)));
  77262. break;
  77263. case BABYLON.PhysicsImpostor.PlaneImpostor:
  77264. BABYLON.Tools.Warn("Attention, PlaneImposter might not behave as you expect. Consider using BoxImposter instead");
  77265. returnValue = new this.BJSCANNON.Plane();
  77266. break;
  77267. case BABYLON.PhysicsImpostor.MeshImpostor:
  77268. // should transform the vertex data to world coordinates!!
  77269. var rawVerts = object.getVerticesData ? object.getVerticesData(BABYLON.VertexBuffer.PositionKind) : [];
  77270. var rawFaces = object.getIndices ? object.getIndices() : [];
  77271. if (!rawVerts)
  77272. return;
  77273. // get only scale! so the object could transform correctly.
  77274. var oldPosition = object.position.clone();
  77275. var oldRotation = object.rotation && object.rotation.clone();
  77276. var oldQuaternion = object.rotationQuaternion && object.rotationQuaternion.clone();
  77277. object.position.copyFromFloats(0, 0, 0);
  77278. object.rotation && object.rotation.copyFromFloats(0, 0, 0);
  77279. object.rotationQuaternion && object.rotationQuaternion.copyFrom(impostor.getParentsRotation());
  77280. object.rotationQuaternion && object.parent && object.rotationQuaternion.conjugateInPlace();
  77281. var transform = object.computeWorldMatrix(true);
  77282. // convert rawVerts to object space
  77283. var temp = new Array();
  77284. var index;
  77285. for (index = 0; index < rawVerts.length; index += 3) {
  77286. BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.FromArray(rawVerts, index), transform).toArray(temp, index);
  77287. }
  77288. BABYLON.Tools.Warn("MeshImpostor only collides against spheres.");
  77289. returnValue = new this.BJSCANNON.Trimesh(temp, rawFaces);
  77290. //now set back the transformation!
  77291. object.position.copyFrom(oldPosition);
  77292. oldRotation && object.rotation && object.rotation.copyFrom(oldRotation);
  77293. oldQuaternion && object.rotationQuaternion && object.rotationQuaternion.copyFrom(oldQuaternion);
  77294. break;
  77295. case BABYLON.PhysicsImpostor.HeightmapImpostor:
  77296. var oldPosition2 = object.position.clone();
  77297. var oldRotation2 = object.rotation && object.rotation.clone();
  77298. var oldQuaternion2 = object.rotationQuaternion && object.rotationQuaternion.clone();
  77299. object.position.copyFromFloats(0, 0, 0);
  77300. object.rotation && object.rotation.copyFromFloats(0, 0, 0);
  77301. object.rotationQuaternion && object.rotationQuaternion.copyFrom(impostor.getParentsRotation());
  77302. object.rotationQuaternion && object.parent && object.rotationQuaternion.conjugateInPlace();
  77303. object.rotationQuaternion && object.rotationQuaternion.multiplyInPlace(this._minus90X);
  77304. returnValue = this._createHeightmap(object);
  77305. object.position.copyFrom(oldPosition2);
  77306. oldRotation2 && object.rotation && object.rotation.copyFrom(oldRotation2);
  77307. oldQuaternion2 && object.rotationQuaternion && object.rotationQuaternion.copyFrom(oldQuaternion2);
  77308. object.computeWorldMatrix(true);
  77309. break;
  77310. case BABYLON.PhysicsImpostor.ParticleImpostor:
  77311. returnValue = new this.BJSCANNON.Particle();
  77312. break;
  77313. }
  77314. return returnValue;
  77315. };
  77316. CannonJSPlugin.prototype._createHeightmap = function (object, pointDepth) {
  77317. var pos = (object.getVerticesData(BABYLON.VertexBuffer.PositionKind));
  77318. var transform = object.computeWorldMatrix(true);
  77319. // convert rawVerts to object space
  77320. var temp = new Array();
  77321. var index;
  77322. for (index = 0; index < pos.length; index += 3) {
  77323. BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.FromArray(pos, index), transform).toArray(temp, index);
  77324. }
  77325. pos = temp;
  77326. var matrix = new Array();
  77327. //For now pointDepth will not be used and will be automatically calculated.
  77328. //Future reference - try and find the best place to add a reference to the pointDepth variable.
  77329. var arraySize = pointDepth || ~~(Math.sqrt(pos.length / 3) - 1);
  77330. var boundingInfo = object.getBoundingInfo();
  77331. var dim = Math.min(boundingInfo.boundingBox.extendSizeWorld.x, boundingInfo.boundingBox.extendSizeWorld.y);
  77332. var minY = boundingInfo.boundingBox.extendSizeWorld.z;
  77333. var elementSize = dim * 2 / arraySize;
  77334. for (var i = 0; i < pos.length; i = i + 3) {
  77335. var x = Math.round((pos[i + 0]) / elementSize + arraySize / 2);
  77336. var z = Math.round(((pos[i + 1]) / elementSize - arraySize / 2) * -1);
  77337. var y = -pos[i + 2] + minY;
  77338. if (!matrix[x]) {
  77339. matrix[x] = [];
  77340. }
  77341. if (!matrix[x][z]) {
  77342. matrix[x][z] = y;
  77343. }
  77344. matrix[x][z] = Math.max(y, matrix[x][z]);
  77345. }
  77346. for (var x = 0; x <= arraySize; ++x) {
  77347. if (!matrix[x]) {
  77348. var loc = 1;
  77349. while (!matrix[(x + loc) % arraySize]) {
  77350. loc++;
  77351. }
  77352. matrix[x] = matrix[(x + loc) % arraySize].slice();
  77353. //console.log("missing x", x);
  77354. }
  77355. for (var z = 0; z <= arraySize; ++z) {
  77356. if (!matrix[x][z]) {
  77357. var loc = 1;
  77358. var newValue;
  77359. while (newValue === undefined) {
  77360. newValue = matrix[x][(z + loc++) % arraySize];
  77361. }
  77362. matrix[x][z] = newValue;
  77363. }
  77364. }
  77365. }
  77366. var shape = new this.BJSCANNON.Heightfield(matrix, {
  77367. elementSize: elementSize
  77368. });
  77369. //For future reference, needed for body transformation
  77370. shape.minY = minY;
  77371. return shape;
  77372. };
  77373. CannonJSPlugin.prototype._updatePhysicsBodyTransformation = function (impostor) {
  77374. var object = impostor.object;
  77375. //make sure it is updated...
  77376. object.computeWorldMatrix && object.computeWorldMatrix(true);
  77377. // The delta between the mesh position and the mesh bounding box center
  77378. var bInfo = object.getBoundingInfo();
  77379. if (!bInfo)
  77380. return;
  77381. var center = impostor.getObjectCenter();
  77382. //m.getAbsolutePosition().subtract(m.getBoundingInfo().boundingBox.centerWorld)
  77383. this._tmpDeltaPosition.copyFrom(object.getAbsolutePivotPoint().subtract(center));
  77384. this._tmpDeltaPosition.divideInPlace(impostor.object.scaling);
  77385. this._tmpPosition.copyFrom(center);
  77386. var quaternion = object.rotationQuaternion;
  77387. if (!quaternion) {
  77388. return;
  77389. }
  77390. //is shape is a plane or a heightmap, it must be rotated 90 degs in the X axis.
  77391. if (impostor.type === BABYLON.PhysicsImpostor.PlaneImpostor || impostor.type === BABYLON.PhysicsImpostor.HeightmapImpostor || impostor.type === BABYLON.PhysicsImpostor.CylinderImpostor) {
  77392. //-90 DEG in X, precalculated
  77393. quaternion = quaternion.multiply(this._minus90X);
  77394. //Invert! (Precalculated, 90 deg in X)
  77395. //No need to clone. this will never change.
  77396. impostor.setDeltaRotation(this._plus90X);
  77397. }
  77398. //If it is a heightfield, if should be centered.
  77399. if (impostor.type === BABYLON.PhysicsImpostor.HeightmapImpostor) {
  77400. var mesh = object;
  77401. var boundingInfo = mesh.getBoundingInfo();
  77402. //calculate the correct body position:
  77403. var rotationQuaternion = mesh.rotationQuaternion;
  77404. mesh.rotationQuaternion = this._tmpUnityRotation;
  77405. mesh.computeWorldMatrix(true);
  77406. //get original center with no rotation
  77407. var c = center.clone();
  77408. var oldPivot = mesh.getPivotMatrix() || BABYLON.Matrix.Translation(0, 0, 0);
  77409. //calculate the new center using a pivot (since this.BJSCANNON.js doesn't center height maps)
  77410. var p = BABYLON.Matrix.Translation(boundingInfo.boundingBox.extendSizeWorld.x, 0, -boundingInfo.boundingBox.extendSizeWorld.z);
  77411. mesh.setPreTransformMatrix(p);
  77412. mesh.computeWorldMatrix(true);
  77413. //calculate the translation
  77414. var translation = boundingInfo.boundingBox.centerWorld.subtract(center).subtract(mesh.position).negate();
  77415. this._tmpPosition.copyFromFloats(translation.x, translation.y - boundingInfo.boundingBox.extendSizeWorld.y, translation.z);
  77416. //add it inverted to the delta
  77417. this._tmpDeltaPosition.copyFrom(boundingInfo.boundingBox.centerWorld.subtract(c));
  77418. this._tmpDeltaPosition.y += boundingInfo.boundingBox.extendSizeWorld.y;
  77419. //rotation is back
  77420. mesh.rotationQuaternion = rotationQuaternion;
  77421. mesh.setPreTransformMatrix(oldPivot);
  77422. mesh.computeWorldMatrix(true);
  77423. }
  77424. else if (impostor.type === BABYLON.PhysicsImpostor.MeshImpostor) {
  77425. this._tmpDeltaPosition.copyFromFloats(0, 0, 0);
  77426. //this._tmpPosition.copyFrom(object.position);
  77427. }
  77428. impostor.setDeltaPosition(this._tmpDeltaPosition);
  77429. //Now update the impostor object
  77430. impostor.physicsBody.position.copy(this._tmpPosition);
  77431. impostor.physicsBody.quaternion.copy(quaternion);
  77432. };
  77433. CannonJSPlugin.prototype.setTransformationFromPhysicsBody = function (impostor) {
  77434. impostor.object.position.copyFrom(impostor.physicsBody.position);
  77435. if (impostor.object.rotationQuaternion) {
  77436. impostor.object.rotationQuaternion.copyFrom(impostor.physicsBody.quaternion);
  77437. }
  77438. };
  77439. CannonJSPlugin.prototype.setPhysicsBodyTransformation = function (impostor, newPosition, newRotation) {
  77440. impostor.physicsBody.position.copy(newPosition);
  77441. impostor.physicsBody.quaternion.copy(newRotation);
  77442. };
  77443. CannonJSPlugin.prototype.isSupported = function () {
  77444. return this.BJSCANNON !== undefined;
  77445. };
  77446. CannonJSPlugin.prototype.setLinearVelocity = function (impostor, velocity) {
  77447. impostor.physicsBody.velocity.copy(velocity);
  77448. };
  77449. CannonJSPlugin.prototype.setAngularVelocity = function (impostor, velocity) {
  77450. impostor.physicsBody.angularVelocity.copy(velocity);
  77451. };
  77452. CannonJSPlugin.prototype.getLinearVelocity = function (impostor) {
  77453. var v = impostor.physicsBody.velocity;
  77454. if (!v) {
  77455. return null;
  77456. }
  77457. return new BABYLON.Vector3(v.x, v.y, v.z);
  77458. };
  77459. CannonJSPlugin.prototype.getAngularVelocity = function (impostor) {
  77460. var v = impostor.physicsBody.angularVelocity;
  77461. if (!v) {
  77462. return null;
  77463. }
  77464. return new BABYLON.Vector3(v.x, v.y, v.z);
  77465. };
  77466. CannonJSPlugin.prototype.setBodyMass = function (impostor, mass) {
  77467. impostor.physicsBody.mass = mass;
  77468. impostor.physicsBody.updateMassProperties();
  77469. };
  77470. CannonJSPlugin.prototype.getBodyMass = function (impostor) {
  77471. return impostor.physicsBody.mass;
  77472. };
  77473. CannonJSPlugin.prototype.getBodyFriction = function (impostor) {
  77474. return impostor.physicsBody.material.friction;
  77475. };
  77476. CannonJSPlugin.prototype.setBodyFriction = function (impostor, friction) {
  77477. impostor.physicsBody.material.friction = friction;
  77478. };
  77479. CannonJSPlugin.prototype.getBodyRestitution = function (impostor) {
  77480. return impostor.physicsBody.material.restitution;
  77481. };
  77482. CannonJSPlugin.prototype.setBodyRestitution = function (impostor, restitution) {
  77483. impostor.physicsBody.material.restitution = restitution;
  77484. };
  77485. CannonJSPlugin.prototype.sleepBody = function (impostor) {
  77486. impostor.physicsBody.sleep();
  77487. };
  77488. CannonJSPlugin.prototype.wakeUpBody = function (impostor) {
  77489. impostor.physicsBody.wakeUp();
  77490. };
  77491. CannonJSPlugin.prototype.updateDistanceJoint = function (joint, maxDistance, minDistance) {
  77492. joint.physicsJoint.distance = maxDistance;
  77493. };
  77494. // private enableMotor(joint: IMotorEnabledJoint, motorIndex?: number) {
  77495. // if (!motorIndex) {
  77496. // joint.physicsJoint.enableMotor();
  77497. // }
  77498. // }
  77499. // private disableMotor(joint: IMotorEnabledJoint, motorIndex?: number) {
  77500. // if (!motorIndex) {
  77501. // joint.physicsJoint.disableMotor();
  77502. // }
  77503. // }
  77504. CannonJSPlugin.prototype.setMotor = function (joint, speed, maxForce, motorIndex) {
  77505. if (!motorIndex) {
  77506. joint.physicsJoint.enableMotor();
  77507. joint.physicsJoint.setMotorSpeed(speed);
  77508. if (maxForce) {
  77509. this.setLimit(joint, maxForce);
  77510. }
  77511. }
  77512. };
  77513. CannonJSPlugin.prototype.setLimit = function (joint, upperLimit, lowerLimit) {
  77514. joint.physicsJoint.motorEquation.maxForce = upperLimit;
  77515. joint.physicsJoint.motorEquation.minForce = lowerLimit === void 0 ? -upperLimit : lowerLimit;
  77516. };
  77517. CannonJSPlugin.prototype.syncMeshWithImpostor = function (mesh, impostor) {
  77518. var body = impostor.physicsBody;
  77519. mesh.position.x = body.position.x;
  77520. mesh.position.y = body.position.y;
  77521. mesh.position.z = body.position.z;
  77522. if (mesh.rotationQuaternion) {
  77523. mesh.rotationQuaternion.x = body.quaternion.x;
  77524. mesh.rotationQuaternion.y = body.quaternion.y;
  77525. mesh.rotationQuaternion.z = body.quaternion.z;
  77526. mesh.rotationQuaternion.w = body.quaternion.w;
  77527. }
  77528. };
  77529. CannonJSPlugin.prototype.getRadius = function (impostor) {
  77530. var shape = impostor.physicsBody.shapes[0];
  77531. return shape.boundingSphereRadius;
  77532. };
  77533. CannonJSPlugin.prototype.getBoxSizeToRef = function (impostor, result) {
  77534. var shape = impostor.physicsBody.shapes[0];
  77535. result.x = shape.halfExtents.x * 2;
  77536. result.y = shape.halfExtents.y * 2;
  77537. result.z = shape.halfExtents.z * 2;
  77538. };
  77539. CannonJSPlugin.prototype.dispose = function () {
  77540. };
  77541. CannonJSPlugin.prototype._extendNamespace = function () {
  77542. //this will force cannon to execute at least one step when using interpolation
  77543. var step_tmp1 = new this.BJSCANNON.Vec3();
  77544. var Engine = this.BJSCANNON;
  77545. this.BJSCANNON.World.prototype.step = function (dt, timeSinceLastCalled, maxSubSteps) {
  77546. maxSubSteps = maxSubSteps || 10;
  77547. timeSinceLastCalled = timeSinceLastCalled || 0;
  77548. if (timeSinceLastCalled === 0) {
  77549. this.internalStep(dt);
  77550. this.time += dt;
  77551. }
  77552. else {
  77553. var internalSteps = Math.floor((this.time + timeSinceLastCalled) / dt) - Math.floor(this.time / dt);
  77554. internalSteps = Math.min(internalSteps, maxSubSteps) || 1;
  77555. var t0 = performance.now();
  77556. for (var i = 0; i !== internalSteps; i++) {
  77557. this.internalStep(dt);
  77558. if (performance.now() - t0 > dt * 1000) {
  77559. break;
  77560. }
  77561. }
  77562. this.time += timeSinceLastCalled;
  77563. var h = this.time % dt;
  77564. var h_div_dt = h / dt;
  77565. var interpvelo = step_tmp1;
  77566. var bodies = this.bodies;
  77567. for (var j = 0; j !== bodies.length; j++) {
  77568. var b = bodies[j];
  77569. if (b.type !== Engine.Body.STATIC && b.sleepState !== Engine.Body.SLEEPING) {
  77570. b.position.vsub(b.previousPosition, interpvelo);
  77571. interpvelo.scale(h_div_dt, interpvelo);
  77572. b.position.vadd(interpvelo, b.interpolatedPosition);
  77573. }
  77574. else {
  77575. b.interpolatedPosition.copy(b.position);
  77576. b.interpolatedQuaternion.copy(b.quaternion);
  77577. }
  77578. }
  77579. }
  77580. };
  77581. };
  77582. return CannonJSPlugin;
  77583. }());
  77584. BABYLON.CannonJSPlugin = CannonJSPlugin;
  77585. })(BABYLON || (BABYLON = {}));
  77586. //# sourceMappingURL=babylon.cannonJSPlugin.js.map
  77587. var BABYLON;
  77588. (function (BABYLON) {
  77589. var OimoJSPlugin = /** @class */ (function () {
  77590. function OimoJSPlugin(iterations) {
  77591. this.name = "OimoJSPlugin";
  77592. this._tmpImpostorsArray = [];
  77593. this._tmpPositionVector = BABYLON.Vector3.Zero();
  77594. this.BJSOIMO = typeof OIMO !== 'undefined' ? OIMO : (typeof require !== 'undefined' ? require('./Oimo') : undefined);
  77595. this.world = new this.BJSOIMO.World(1 / 60, 2, iterations, true);
  77596. this.world.worldscale(1);
  77597. this.world.clear();
  77598. //making sure no stats are calculated
  77599. this.world.isNoStat = true;
  77600. }
  77601. OimoJSPlugin.prototype.setGravity = function (gravity) {
  77602. this.world.gravity.copy(gravity);
  77603. };
  77604. OimoJSPlugin.prototype.setTimeStep = function (timeStep) {
  77605. this.world.timeStep = timeStep;
  77606. };
  77607. OimoJSPlugin.prototype.getTimeStep = function () {
  77608. return this.world.timeStep;
  77609. };
  77610. OimoJSPlugin.prototype.executeStep = function (delta, impostors) {
  77611. var _this = this;
  77612. impostors.forEach(function (impostor) {
  77613. impostor.beforeStep();
  77614. });
  77615. this.world.step();
  77616. impostors.forEach(function (impostor) {
  77617. impostor.afterStep();
  77618. //update the ordered impostors array
  77619. _this._tmpImpostorsArray[impostor.uniqueId] = impostor;
  77620. });
  77621. //check for collisions
  77622. var contact = this.world.contacts;
  77623. while (contact !== null) {
  77624. if (contact.touching && !contact.body1.sleeping && !contact.body2.sleeping) {
  77625. contact = contact.next;
  77626. continue;
  77627. }
  77628. //is this body colliding with any other? get the impostor
  77629. var mainImpostor = this._tmpImpostorsArray[+contact.body1.name];
  77630. var collidingImpostor = this._tmpImpostorsArray[+contact.body2.name];
  77631. if (!mainImpostor || !collidingImpostor) {
  77632. contact = contact.next;
  77633. continue;
  77634. }
  77635. mainImpostor.onCollide({ body: collidingImpostor.physicsBody });
  77636. collidingImpostor.onCollide({ body: mainImpostor.physicsBody });
  77637. contact = contact.next;
  77638. }
  77639. };
  77640. OimoJSPlugin.prototype.applyImpulse = function (impostor, force, contactPoint) {
  77641. var mass = impostor.physicsBody.massInfo.mass;
  77642. impostor.physicsBody.applyImpulse(contactPoint.scale(this.BJSOIMO.INV_SCALE), force.scale(this.BJSOIMO.INV_SCALE * mass));
  77643. };
  77644. OimoJSPlugin.prototype.applyForce = function (impostor, force, contactPoint) {
  77645. BABYLON.Tools.Warn("Oimo doesn't support applying force. Using impule instead.");
  77646. this.applyImpulse(impostor, force, contactPoint);
  77647. };
  77648. OimoJSPlugin.prototype.generatePhysicsBody = function (impostor) {
  77649. var _this = this;
  77650. //parent-child relationship. Does this impostor has a parent impostor?
  77651. if (impostor.parent) {
  77652. if (impostor.physicsBody) {
  77653. this.removePhysicsBody(impostor);
  77654. //TODO is that needed?
  77655. impostor.forceUpdate();
  77656. }
  77657. return;
  77658. }
  77659. if (impostor.isBodyInitRequired()) {
  77660. var bodyConfig = {
  77661. name: impostor.uniqueId,
  77662. //Oimo must have mass, also for static objects.
  77663. config: [impostor.getParam("mass") || 1, impostor.getParam("friction"), impostor.getParam("restitution")],
  77664. size: [],
  77665. type: [],
  77666. pos: [],
  77667. rot: [],
  77668. move: impostor.getParam("mass") !== 0,
  77669. //Supporting older versions of Oimo
  77670. world: this.world
  77671. };
  77672. var impostors = [impostor];
  77673. var addToArray = function (parent) {
  77674. if (!parent.getChildMeshes)
  77675. return;
  77676. parent.getChildMeshes().forEach(function (m) {
  77677. if (m.physicsImpostor) {
  77678. impostors.push(m.physicsImpostor);
  77679. //m.physicsImpostor._init();
  77680. }
  77681. });
  77682. };
  77683. addToArray(impostor.object);
  77684. var checkWithEpsilon_1 = function (value) {
  77685. return Math.max(value, BABYLON.PhysicsEngine.Epsilon);
  77686. };
  77687. impostors.forEach(function (i) {
  77688. if (!impostor.object.rotationQuaternion) {
  77689. return;
  77690. }
  77691. //get the correct bounding box
  77692. var oldQuaternion = i.object.rotationQuaternion;
  77693. var rot = new _this.BJSOIMO.Euler().setFromQuaternion({
  77694. x: impostor.object.rotationQuaternion.x,
  77695. y: impostor.object.rotationQuaternion.y,
  77696. z: impostor.object.rotationQuaternion.z,
  77697. s: impostor.object.rotationQuaternion.w
  77698. });
  77699. var extendSize = i.getObjectExtendSize();
  77700. if (i === impostor) {
  77701. var center = impostor.getObjectCenter();
  77702. impostor.object.getAbsolutePivotPoint().subtractToRef(center, _this._tmpPositionVector);
  77703. _this._tmpPositionVector.divideInPlace(impostor.object.scaling);
  77704. //Can also use Array.prototype.push.apply
  77705. bodyConfig.pos.push(center.x);
  77706. bodyConfig.pos.push(center.y);
  77707. bodyConfig.pos.push(center.z);
  77708. //tmp solution
  77709. bodyConfig.rot.push(rot.x / (_this.BJSOIMO.degtorad || _this.BJSOIMO.TO_RAD));
  77710. bodyConfig.rot.push(rot.y / (_this.BJSOIMO.degtorad || _this.BJSOIMO.TO_RAD));
  77711. bodyConfig.rot.push(rot.z / (_this.BJSOIMO.degtorad || _this.BJSOIMO.TO_RAD));
  77712. }
  77713. else {
  77714. var localPosition = i.object.getAbsolutePosition().subtract(impostor.object.getAbsolutePosition());
  77715. bodyConfig.pos.push(localPosition.x);
  77716. bodyConfig.pos.push(localPosition.y);
  77717. bodyConfig.pos.push(localPosition.z);
  77718. //tmp solution until https://github.com/lo-th/OIMO.js/pull/37 is merged
  77719. bodyConfig.rot.push(0);
  77720. bodyConfig.rot.push(0);
  77721. bodyConfig.rot.push(0);
  77722. }
  77723. // register mesh
  77724. switch (i.type) {
  77725. case BABYLON.PhysicsImpostor.ParticleImpostor:
  77726. BABYLON.Tools.Warn("No Particle support in this.BJSOIMO.js. using SphereImpostor instead");
  77727. case BABYLON.PhysicsImpostor.SphereImpostor:
  77728. var radiusX = extendSize.x;
  77729. var radiusY = extendSize.y;
  77730. var radiusZ = extendSize.z;
  77731. var size = Math.max(checkWithEpsilon_1(radiusX), checkWithEpsilon_1(radiusY), checkWithEpsilon_1(radiusZ)) / 2;
  77732. bodyConfig.type.push('sphere');
  77733. //due to the way oimo works with compounds, add 3 times
  77734. bodyConfig.size.push(size);
  77735. bodyConfig.size.push(size);
  77736. bodyConfig.size.push(size);
  77737. break;
  77738. case BABYLON.PhysicsImpostor.CylinderImpostor:
  77739. var sizeX = checkWithEpsilon_1(extendSize.x) / 2;
  77740. var sizeY = checkWithEpsilon_1(extendSize.y);
  77741. bodyConfig.type.push('cylinder');
  77742. bodyConfig.size.push(sizeX);
  77743. bodyConfig.size.push(sizeY);
  77744. //due to the way oimo works with compounds, add one more value.
  77745. bodyConfig.size.push(sizeY);
  77746. break;
  77747. case BABYLON.PhysicsImpostor.PlaneImpostor:
  77748. case BABYLON.PhysicsImpostor.BoxImpostor:
  77749. default:
  77750. var sizeX = checkWithEpsilon_1(extendSize.x);
  77751. var sizeY = checkWithEpsilon_1(extendSize.y);
  77752. var sizeZ = checkWithEpsilon_1(extendSize.z);
  77753. bodyConfig.type.push('box');
  77754. bodyConfig.size.push(sizeX);
  77755. bodyConfig.size.push(sizeY);
  77756. bodyConfig.size.push(sizeZ);
  77757. break;
  77758. }
  77759. //actually not needed, but hey...
  77760. i.object.rotationQuaternion = oldQuaternion;
  77761. });
  77762. impostor.physicsBody = new this.BJSOIMO.Body(bodyConfig).body; //this.world.add(bodyConfig);
  77763. }
  77764. else {
  77765. this._tmpPositionVector.copyFromFloats(0, 0, 0);
  77766. }
  77767. impostor.setDeltaPosition(this._tmpPositionVector);
  77768. //this._tmpPositionVector.addInPlace(impostor.mesh.getBoundingInfo().boundingBox.center);
  77769. //this.setPhysicsBodyTransformation(impostor, this._tmpPositionVector, impostor.mesh.rotationQuaternion);
  77770. };
  77771. OimoJSPlugin.prototype.removePhysicsBody = function (impostor) {
  77772. //impostor.physicsBody.dispose();
  77773. //Same as : (older oimo versions)
  77774. this.world.removeRigidBody(impostor.physicsBody);
  77775. };
  77776. OimoJSPlugin.prototype.generateJoint = function (impostorJoint) {
  77777. var mainBody = impostorJoint.mainImpostor.physicsBody;
  77778. var connectedBody = impostorJoint.connectedImpostor.physicsBody;
  77779. if (!mainBody || !connectedBody) {
  77780. return;
  77781. }
  77782. var jointData = impostorJoint.joint.jointData;
  77783. var options = jointData.nativeParams || {};
  77784. var type;
  77785. var nativeJointData = {
  77786. body1: mainBody,
  77787. body2: connectedBody,
  77788. axe1: options.axe1 || (jointData.mainAxis ? jointData.mainAxis.asArray() : null),
  77789. axe2: options.axe2 || (jointData.connectedAxis ? jointData.connectedAxis.asArray() : null),
  77790. pos1: options.pos1 || (jointData.mainPivot ? jointData.mainPivot.asArray() : null),
  77791. pos2: options.pos2 || (jointData.connectedPivot ? jointData.connectedPivot.asArray() : null),
  77792. min: options.min,
  77793. max: options.max,
  77794. collision: options.collision || jointData.collision,
  77795. spring: options.spring,
  77796. //supporting older version of Oimo
  77797. world: this.world
  77798. };
  77799. switch (impostorJoint.joint.type) {
  77800. case BABYLON.PhysicsJoint.BallAndSocketJoint:
  77801. type = "jointBall";
  77802. break;
  77803. case BABYLON.PhysicsJoint.SpringJoint:
  77804. BABYLON.Tools.Warn("this.BJSOIMO.js doesn't support Spring Constraint. Simulating using DistanceJoint instead");
  77805. var springData = jointData;
  77806. nativeJointData.min = springData.length || nativeJointData.min;
  77807. //Max should also be set, just make sure it is at least min
  77808. nativeJointData.max = Math.max(nativeJointData.min, nativeJointData.max);
  77809. case BABYLON.PhysicsJoint.DistanceJoint:
  77810. type = "jointDistance";
  77811. nativeJointData.max = jointData.maxDistance;
  77812. break;
  77813. case BABYLON.PhysicsJoint.PrismaticJoint:
  77814. type = "jointPrisme";
  77815. break;
  77816. case BABYLON.PhysicsJoint.SliderJoint:
  77817. type = "jointSlide";
  77818. break;
  77819. case BABYLON.PhysicsJoint.WheelJoint:
  77820. type = "jointWheel";
  77821. break;
  77822. case BABYLON.PhysicsJoint.HingeJoint:
  77823. default:
  77824. type = "jointHinge";
  77825. break;
  77826. }
  77827. nativeJointData.type = type;
  77828. impostorJoint.joint.physicsJoint = new this.BJSOIMO.Link(nativeJointData).joint; //this.world.add(nativeJointData);
  77829. };
  77830. OimoJSPlugin.prototype.removeJoint = function (impostorJoint) {
  77831. //Bug in Oimo prevents us from disposing a joint in the playground
  77832. //joint.joint.physicsJoint.dispose();
  77833. //So we will bruteforce it!
  77834. try {
  77835. this.world.removeJoint(impostorJoint.joint.physicsJoint);
  77836. }
  77837. catch (e) {
  77838. BABYLON.Tools.Warn(e);
  77839. }
  77840. };
  77841. OimoJSPlugin.prototype.isSupported = function () {
  77842. return this.BJSOIMO !== undefined;
  77843. };
  77844. OimoJSPlugin.prototype.setTransformationFromPhysicsBody = function (impostor) {
  77845. if (!impostor.physicsBody.sleeping) {
  77846. //TODO check that
  77847. if (impostor.physicsBody.shapes.next) {
  77848. var parentShape = this._getLastShape(impostor.physicsBody);
  77849. impostor.object.position.x = parentShape.position.x * this.BJSOIMO.WORLD_SCALE;
  77850. impostor.object.position.y = parentShape.position.y * this.BJSOIMO.WORLD_SCALE;
  77851. impostor.object.position.z = parentShape.position.z * this.BJSOIMO.WORLD_SCALE;
  77852. }
  77853. else {
  77854. impostor.object.position.copyFrom(impostor.physicsBody.getPosition());
  77855. }
  77856. if (impostor.object.rotationQuaternion) {
  77857. impostor.object.rotationQuaternion.copyFrom(impostor.physicsBody.getQuaternion());
  77858. impostor.object.rotationQuaternion.normalize();
  77859. }
  77860. }
  77861. };
  77862. OimoJSPlugin.prototype.setPhysicsBodyTransformation = function (impostor, newPosition, newRotation) {
  77863. var body = impostor.physicsBody;
  77864. body.position.init(newPosition.x * this.BJSOIMO.INV_SCALE, newPosition.y * this.BJSOIMO.INV_SCALE, newPosition.z * this.BJSOIMO.INV_SCALE);
  77865. body.orientation.init(newRotation.w, newRotation.x, newRotation.y, newRotation.z);
  77866. body.syncShapes();
  77867. body.awake();
  77868. };
  77869. OimoJSPlugin.prototype._getLastShape = function (body) {
  77870. var lastShape = body.shapes;
  77871. while (lastShape.next) {
  77872. lastShape = lastShape.next;
  77873. }
  77874. return lastShape;
  77875. };
  77876. OimoJSPlugin.prototype.setLinearVelocity = function (impostor, velocity) {
  77877. impostor.physicsBody.linearVelocity.init(velocity.x, velocity.y, velocity.z);
  77878. };
  77879. OimoJSPlugin.prototype.setAngularVelocity = function (impostor, velocity) {
  77880. impostor.physicsBody.angularVelocity.init(velocity.x, velocity.y, velocity.z);
  77881. };
  77882. OimoJSPlugin.prototype.getLinearVelocity = function (impostor) {
  77883. var v = impostor.physicsBody.linearVelocity;
  77884. if (!v) {
  77885. return null;
  77886. }
  77887. return new BABYLON.Vector3(v.x, v.y, v.z);
  77888. };
  77889. OimoJSPlugin.prototype.getAngularVelocity = function (impostor) {
  77890. var v = impostor.physicsBody.angularVelocity;
  77891. if (!v) {
  77892. return null;
  77893. }
  77894. return new BABYLON.Vector3(v.x, v.y, v.z);
  77895. };
  77896. OimoJSPlugin.prototype.setBodyMass = function (impostor, mass) {
  77897. var staticBody = mass === 0;
  77898. //this will actually set the body's density and not its mass.
  77899. //But this is how oimo treats the mass variable.
  77900. impostor.physicsBody.shapes.density = staticBody ? 1 : mass;
  77901. impostor.physicsBody.setupMass(staticBody ? 0x2 : 0x1);
  77902. };
  77903. OimoJSPlugin.prototype.getBodyMass = function (impostor) {
  77904. return impostor.physicsBody.shapes.density;
  77905. };
  77906. OimoJSPlugin.prototype.getBodyFriction = function (impostor) {
  77907. return impostor.physicsBody.shapes.friction;
  77908. };
  77909. OimoJSPlugin.prototype.setBodyFriction = function (impostor, friction) {
  77910. impostor.physicsBody.shapes.friction = friction;
  77911. };
  77912. OimoJSPlugin.prototype.getBodyRestitution = function (impostor) {
  77913. return impostor.physicsBody.shapes.restitution;
  77914. };
  77915. OimoJSPlugin.prototype.setBodyRestitution = function (impostor, restitution) {
  77916. impostor.physicsBody.shapes.restitution = restitution;
  77917. };
  77918. OimoJSPlugin.prototype.sleepBody = function (impostor) {
  77919. impostor.physicsBody.sleep();
  77920. };
  77921. OimoJSPlugin.prototype.wakeUpBody = function (impostor) {
  77922. impostor.physicsBody.awake();
  77923. };
  77924. OimoJSPlugin.prototype.updateDistanceJoint = function (joint, maxDistance, minDistance) {
  77925. joint.physicsJoint.limitMotor.upperLimit = maxDistance;
  77926. if (minDistance !== void 0) {
  77927. joint.physicsJoint.limitMotor.lowerLimit = minDistance;
  77928. }
  77929. };
  77930. OimoJSPlugin.prototype.setMotor = function (joint, speed, maxForce, motorIndex) {
  77931. //TODO separate rotational and transational motors.
  77932. var motor = motorIndex ? joint.physicsJoint.rotationalLimitMotor2 : joint.physicsJoint.rotationalLimitMotor1 || joint.physicsJoint.rotationalLimitMotor || joint.physicsJoint.limitMotor;
  77933. if (motor) {
  77934. motor.setMotor(speed, maxForce);
  77935. }
  77936. };
  77937. OimoJSPlugin.prototype.setLimit = function (joint, upperLimit, lowerLimit, motorIndex) {
  77938. //TODO separate rotational and transational motors.
  77939. var motor = motorIndex ? joint.physicsJoint.rotationalLimitMotor2 : joint.physicsJoint.rotationalLimitMotor1 || joint.physicsJoint.rotationalLimitMotor || joint.physicsJoint.limitMotor;
  77940. if (motor) {
  77941. motor.setLimit(upperLimit, lowerLimit === void 0 ? -upperLimit : lowerLimit);
  77942. }
  77943. };
  77944. OimoJSPlugin.prototype.syncMeshWithImpostor = function (mesh, impostor) {
  77945. var body = impostor.physicsBody;
  77946. mesh.position.x = body.position.x;
  77947. mesh.position.y = body.position.y;
  77948. mesh.position.z = body.position.z;
  77949. if (mesh.rotationQuaternion) {
  77950. mesh.rotationQuaternion.x = body.orientation.x;
  77951. mesh.rotationQuaternion.y = body.orientation.y;
  77952. mesh.rotationQuaternion.z = body.orientation.z;
  77953. mesh.rotationQuaternion.w = body.orientation.s;
  77954. }
  77955. };
  77956. OimoJSPlugin.prototype.getRadius = function (impostor) {
  77957. return impostor.physicsBody.shapes.radius;
  77958. };
  77959. OimoJSPlugin.prototype.getBoxSizeToRef = function (impostor, result) {
  77960. var shape = impostor.physicsBody.shapes;
  77961. result.x = shape.halfWidth * 2;
  77962. result.y = shape.halfHeight * 2;
  77963. result.z = shape.halfDepth * 2;
  77964. };
  77965. OimoJSPlugin.prototype.dispose = function () {
  77966. this.world.clear();
  77967. };
  77968. return OimoJSPlugin;
  77969. }());
  77970. BABYLON.OimoJSPlugin = OimoJSPlugin;
  77971. })(BABYLON || (BABYLON = {}));
  77972. //# sourceMappingURL=babylon.oimoJSPlugin.js.map
  77973. var BABYLON;
  77974. (function (BABYLON) {
  77975. /*
  77976. * Based on jsTGALoader - Javascript loader for TGA file
  77977. * By Vincent Thibault
  77978. * @blog http://blog.robrowser.com/javascript-tga-loader.html
  77979. */
  77980. var TGATools = /** @class */ (function () {
  77981. function TGATools() {
  77982. }
  77983. TGATools.GetTGAHeader = function (data) {
  77984. var offset = 0;
  77985. var header = {
  77986. id_length: data[offset++],
  77987. colormap_type: data[offset++],
  77988. image_type: data[offset++],
  77989. colormap_index: data[offset++] | data[offset++] << 8,
  77990. colormap_length: data[offset++] | data[offset++] << 8,
  77991. colormap_size: data[offset++],
  77992. origin: [
  77993. data[offset++] | data[offset++] << 8,
  77994. data[offset++] | data[offset++] << 8
  77995. ],
  77996. width: data[offset++] | data[offset++] << 8,
  77997. height: data[offset++] | data[offset++] << 8,
  77998. pixel_size: data[offset++],
  77999. flags: data[offset++]
  78000. };
  78001. return header;
  78002. };
  78003. TGATools.UploadContent = function (gl, data) {
  78004. // Not enough data to contain header ?
  78005. if (data.length < 19) {
  78006. BABYLON.Tools.Error("Unable to load TGA file - Not enough data to contain header");
  78007. return;
  78008. }
  78009. // Read Header
  78010. var offset = 18;
  78011. var header = TGATools.GetTGAHeader(data);
  78012. // Assume it's a valid Targa file.
  78013. if (header.id_length + offset > data.length) {
  78014. BABYLON.Tools.Error("Unable to load TGA file - Not enough data");
  78015. return;
  78016. }
  78017. // Skip not needed data
  78018. offset += header.id_length;
  78019. var use_rle = false;
  78020. var use_pal = false;
  78021. var use_grey = false;
  78022. // Get some informations.
  78023. switch (header.image_type) {
  78024. case TGATools._TYPE_RLE_INDEXED:
  78025. use_rle = true;
  78026. case TGATools._TYPE_INDEXED:
  78027. use_pal = true;
  78028. break;
  78029. case TGATools._TYPE_RLE_RGB:
  78030. use_rle = true;
  78031. case TGATools._TYPE_RGB:
  78032. // use_rgb = true;
  78033. break;
  78034. case TGATools._TYPE_RLE_GREY:
  78035. use_rle = true;
  78036. case TGATools._TYPE_GREY:
  78037. use_grey = true;
  78038. break;
  78039. }
  78040. var pixel_data;
  78041. // var numAlphaBits = header.flags & 0xf;
  78042. var pixel_size = header.pixel_size >> 3;
  78043. var pixel_total = header.width * header.height * pixel_size;
  78044. // Read palettes
  78045. var palettes;
  78046. if (use_pal) {
  78047. palettes = data.subarray(offset, offset += header.colormap_length * (header.colormap_size >> 3));
  78048. }
  78049. // Read LRE
  78050. if (use_rle) {
  78051. pixel_data = new Uint8Array(pixel_total);
  78052. var c, count, i;
  78053. var localOffset = 0;
  78054. var pixels = new Uint8Array(pixel_size);
  78055. while (offset < pixel_total && localOffset < pixel_total) {
  78056. c = data[offset++];
  78057. count = (c & 0x7f) + 1;
  78058. // RLE pixels
  78059. if (c & 0x80) {
  78060. // Bind pixel tmp array
  78061. for (i = 0; i < pixel_size; ++i) {
  78062. pixels[i] = data[offset++];
  78063. }
  78064. // Copy pixel array
  78065. for (i = 0; i < count; ++i) {
  78066. pixel_data.set(pixels, localOffset + i * pixel_size);
  78067. }
  78068. localOffset += pixel_size * count;
  78069. }
  78070. else {
  78071. count *= pixel_size;
  78072. for (i = 0; i < count; ++i) {
  78073. pixel_data[localOffset + i] = data[offset++];
  78074. }
  78075. localOffset += count;
  78076. }
  78077. }
  78078. }
  78079. else {
  78080. pixel_data = data.subarray(offset, offset += (use_pal ? header.width * header.height : pixel_total));
  78081. }
  78082. // Load to texture
  78083. var x_start, y_start, x_step, y_step, y_end, x_end;
  78084. switch ((header.flags & TGATools._ORIGIN_MASK) >> TGATools._ORIGIN_SHIFT) {
  78085. default:
  78086. case TGATools._ORIGIN_UL:
  78087. x_start = 0;
  78088. x_step = 1;
  78089. x_end = header.width;
  78090. y_start = 0;
  78091. y_step = 1;
  78092. y_end = header.height;
  78093. break;
  78094. case TGATools._ORIGIN_BL:
  78095. x_start = 0;
  78096. x_step = 1;
  78097. x_end = header.width;
  78098. y_start = header.height - 1;
  78099. y_step = -1;
  78100. y_end = -1;
  78101. break;
  78102. case TGATools._ORIGIN_UR:
  78103. x_start = header.width - 1;
  78104. x_step = -1;
  78105. x_end = -1;
  78106. y_start = 0;
  78107. y_step = 1;
  78108. y_end = header.height;
  78109. break;
  78110. case TGATools._ORIGIN_BR:
  78111. x_start = header.width - 1;
  78112. x_step = -1;
  78113. x_end = -1;
  78114. y_start = header.height - 1;
  78115. y_step = -1;
  78116. y_end = -1;
  78117. break;
  78118. }
  78119. // Load the specify method
  78120. var func = '_getImageData' + (use_grey ? 'Grey' : '') + (header.pixel_size) + 'bits';
  78121. var imageData = TGATools[func](header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end);
  78122. gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, header.width, header.height, 0, gl.RGBA, gl.UNSIGNED_BYTE, imageData);
  78123. };
  78124. TGATools._getImageData8bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  78125. var image = pixel_data, colormap = palettes;
  78126. var width = header.width, height = header.height;
  78127. var color, i = 0, x, y;
  78128. var imageData = new Uint8Array(width * height * 4);
  78129. for (y = y_start; y !== y_end; y += y_step) {
  78130. for (x = x_start; x !== x_end; x += x_step, i++) {
  78131. color = image[i];
  78132. imageData[(x + width * y) * 4 + 3] = 255;
  78133. imageData[(x + width * y) * 4 + 2] = colormap[(color * 3) + 0];
  78134. imageData[(x + width * y) * 4 + 1] = colormap[(color * 3) + 1];
  78135. imageData[(x + width * y) * 4 + 0] = colormap[(color * 3) + 2];
  78136. }
  78137. }
  78138. return imageData;
  78139. };
  78140. TGATools._getImageData16bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  78141. var image = pixel_data;
  78142. var width = header.width, height = header.height;
  78143. var color, i = 0, x, y;
  78144. var imageData = new Uint8Array(width * height * 4);
  78145. for (y = y_start; y !== y_end; y += y_step) {
  78146. for (x = x_start; x !== x_end; x += x_step, i += 2) {
  78147. color = image[i + 0] + (image[i + 1] << 8); // Inversed ?
  78148. var r = (((color & 0x7C00) >> 10) * 255) / 0x1F | 0;
  78149. var g = (((color & 0x03E0) >> 5) * 255) / 0x1F | 0;
  78150. var b = ((color & 0x001F) * 255) / 0x1F | 0;
  78151. imageData[(x + width * y) * 4 + 0] = r;
  78152. imageData[(x + width * y) * 4 + 1] = g;
  78153. imageData[(x + width * y) * 4 + 2] = b;
  78154. imageData[(x + width * y) * 4 + 3] = (color & 0x8000) ? 0 : 255;
  78155. }
  78156. }
  78157. return imageData;
  78158. };
  78159. TGATools._getImageData24bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  78160. var image = pixel_data;
  78161. var width = header.width, height = header.height;
  78162. var i = 0, x, y;
  78163. var imageData = new Uint8Array(width * height * 4);
  78164. for (y = y_start; y !== y_end; y += y_step) {
  78165. for (x = x_start; x !== x_end; x += x_step, i += 3) {
  78166. imageData[(x + width * y) * 4 + 3] = 255;
  78167. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  78168. imageData[(x + width * y) * 4 + 1] = image[i + 1];
  78169. imageData[(x + width * y) * 4 + 0] = image[i + 2];
  78170. }
  78171. }
  78172. return imageData;
  78173. };
  78174. TGATools._getImageData32bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  78175. var image = pixel_data;
  78176. var width = header.width, height = header.height;
  78177. var i = 0, x, y;
  78178. var imageData = new Uint8Array(width * height * 4);
  78179. for (y = y_start; y !== y_end; y += y_step) {
  78180. for (x = x_start; x !== x_end; x += x_step, i += 4) {
  78181. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  78182. imageData[(x + width * y) * 4 + 1] = image[i + 1];
  78183. imageData[(x + width * y) * 4 + 0] = image[i + 2];
  78184. imageData[(x + width * y) * 4 + 3] = image[i + 3];
  78185. }
  78186. }
  78187. return imageData;
  78188. };
  78189. TGATools._getImageDataGrey8bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  78190. var image = pixel_data;
  78191. var width = header.width, height = header.height;
  78192. var color, i = 0, x, y;
  78193. var imageData = new Uint8Array(width * height * 4);
  78194. for (y = y_start; y !== y_end; y += y_step) {
  78195. for (x = x_start; x !== x_end; x += x_step, i++) {
  78196. color = image[i];
  78197. imageData[(x + width * y) * 4 + 0] = color;
  78198. imageData[(x + width * y) * 4 + 1] = color;
  78199. imageData[(x + width * y) * 4 + 2] = color;
  78200. imageData[(x + width * y) * 4 + 3] = 255;
  78201. }
  78202. }
  78203. return imageData;
  78204. };
  78205. TGATools._getImageDataGrey16bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  78206. var image = pixel_data;
  78207. var width = header.width, height = header.height;
  78208. var i = 0, x, y;
  78209. var imageData = new Uint8Array(width * height * 4);
  78210. for (y = y_start; y !== y_end; y += y_step) {
  78211. for (x = x_start; x !== x_end; x += x_step, i += 2) {
  78212. imageData[(x + width * y) * 4 + 0] = image[i + 0];
  78213. imageData[(x + width * y) * 4 + 1] = image[i + 0];
  78214. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  78215. imageData[(x + width * y) * 4 + 3] = image[i + 1];
  78216. }
  78217. }
  78218. return imageData;
  78219. };
  78220. //private static _TYPE_NO_DATA = 0;
  78221. TGATools._TYPE_INDEXED = 1;
  78222. TGATools._TYPE_RGB = 2;
  78223. TGATools._TYPE_GREY = 3;
  78224. TGATools._TYPE_RLE_INDEXED = 9;
  78225. TGATools._TYPE_RLE_RGB = 10;
  78226. TGATools._TYPE_RLE_GREY = 11;
  78227. TGATools._ORIGIN_MASK = 0x30;
  78228. TGATools._ORIGIN_SHIFT = 0x04;
  78229. TGATools._ORIGIN_BL = 0x00;
  78230. TGATools._ORIGIN_BR = 0x01;
  78231. TGATools._ORIGIN_UL = 0x02;
  78232. TGATools._ORIGIN_UR = 0x03;
  78233. return TGATools;
  78234. }());
  78235. BABYLON.TGATools = TGATools;
  78236. })(BABYLON || (BABYLON = {}));
  78237. //# sourceMappingURL=babylon.tga.js.map
  78238. var BABYLON;
  78239. (function (BABYLON) {
  78240. // Based on demo done by Brandon Jones - http://media.tojicode.com/webgl-samples/dds.html
  78241. // All values and structures referenced from:
  78242. // http://msdn.microsoft.com/en-us/library/bb943991.aspx/
  78243. var DDS_MAGIC = 0x20534444;
  78244. var
  78245. //DDSD_CAPS = 0x1,
  78246. //DDSD_HEIGHT = 0x2,
  78247. //DDSD_WIDTH = 0x4,
  78248. //DDSD_PITCH = 0x8,
  78249. //DDSD_PIXELFORMAT = 0x1000,
  78250. DDSD_MIPMAPCOUNT = 0x20000;
  78251. //DDSD_LINEARSIZE = 0x80000,
  78252. //DDSD_DEPTH = 0x800000;
  78253. // var DDSCAPS_COMPLEX = 0x8,
  78254. // DDSCAPS_MIPMAP = 0x400000,
  78255. // DDSCAPS_TEXTURE = 0x1000;
  78256. var DDSCAPS2_CUBEMAP = 0x200;
  78257. // DDSCAPS2_CUBEMAP_POSITIVEX = 0x400,
  78258. // DDSCAPS2_CUBEMAP_NEGATIVEX = 0x800,
  78259. // DDSCAPS2_CUBEMAP_POSITIVEY = 0x1000,
  78260. // DDSCAPS2_CUBEMAP_NEGATIVEY = 0x2000,
  78261. // DDSCAPS2_CUBEMAP_POSITIVEZ = 0x4000,
  78262. // DDSCAPS2_CUBEMAP_NEGATIVEZ = 0x8000,
  78263. // DDSCAPS2_VOLUME = 0x200000;
  78264. var
  78265. //DDPF_ALPHAPIXELS = 0x1,
  78266. //DDPF_ALPHA = 0x2,
  78267. DDPF_FOURCC = 0x4, DDPF_RGB = 0x40,
  78268. //DDPF_YUV = 0x200,
  78269. DDPF_LUMINANCE = 0x20000;
  78270. function FourCCToInt32(value) {
  78271. return value.charCodeAt(0) +
  78272. (value.charCodeAt(1) << 8) +
  78273. (value.charCodeAt(2) << 16) +
  78274. (value.charCodeAt(3) << 24);
  78275. }
  78276. function Int32ToFourCC(value) {
  78277. return String.fromCharCode(value & 0xff, (value >> 8) & 0xff, (value >> 16) & 0xff, (value >> 24) & 0xff);
  78278. }
  78279. var FOURCC_DXT1 = FourCCToInt32("DXT1");
  78280. var FOURCC_DXT3 = FourCCToInt32("DXT3");
  78281. var FOURCC_DXT5 = FourCCToInt32("DXT5");
  78282. var FOURCC_DX10 = FourCCToInt32("DX10");
  78283. var FOURCC_D3DFMT_R16G16B16A16F = 113;
  78284. var FOURCC_D3DFMT_R32G32B32A32F = 116;
  78285. var DXGI_FORMAT_R16G16B16A16_FLOAT = 10;
  78286. var DXGI_FORMAT_B8G8R8X8_UNORM = 88;
  78287. var headerLengthInt = 31; // The header length in 32 bit ints
  78288. // Offsets into the header array
  78289. var off_magic = 0;
  78290. var off_size = 1;
  78291. var off_flags = 2;
  78292. var off_height = 3;
  78293. var off_width = 4;
  78294. var off_mipmapCount = 7;
  78295. var off_pfFlags = 20;
  78296. var off_pfFourCC = 21;
  78297. var off_RGBbpp = 22;
  78298. var off_RMask = 23;
  78299. var off_GMask = 24;
  78300. var off_BMask = 25;
  78301. var off_AMask = 26;
  78302. // var off_caps1 = 27;
  78303. var off_caps2 = 28;
  78304. // var off_caps3 = 29;
  78305. // var off_caps4 = 30;
  78306. var off_dxgiFormat = 32;
  78307. ;
  78308. var DDSTools = /** @class */ (function () {
  78309. function DDSTools() {
  78310. }
  78311. DDSTools.GetDDSInfo = function (arrayBuffer) {
  78312. var header = new Int32Array(arrayBuffer, 0, headerLengthInt);
  78313. var extendedHeader = new Int32Array(arrayBuffer, 0, headerLengthInt + 4);
  78314. var mipmapCount = 1;
  78315. if (header[off_flags] & DDSD_MIPMAPCOUNT) {
  78316. mipmapCount = Math.max(1, header[off_mipmapCount]);
  78317. }
  78318. var fourCC = header[off_pfFourCC];
  78319. var dxgiFormat = (fourCC === FOURCC_DX10) ? extendedHeader[off_dxgiFormat] : 0;
  78320. var textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  78321. switch (fourCC) {
  78322. case FOURCC_D3DFMT_R16G16B16A16F:
  78323. textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  78324. break;
  78325. case FOURCC_D3DFMT_R32G32B32A32F:
  78326. textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  78327. break;
  78328. case FOURCC_DX10:
  78329. if (dxgiFormat === DXGI_FORMAT_R16G16B16A16_FLOAT) {
  78330. textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  78331. break;
  78332. }
  78333. }
  78334. return {
  78335. width: header[off_width],
  78336. height: header[off_height],
  78337. mipmapCount: mipmapCount,
  78338. isFourCC: (header[off_pfFlags] & DDPF_FOURCC) === DDPF_FOURCC,
  78339. isRGB: (header[off_pfFlags] & DDPF_RGB) === DDPF_RGB,
  78340. isLuminance: (header[off_pfFlags] & DDPF_LUMINANCE) === DDPF_LUMINANCE,
  78341. isCube: (header[off_caps2] & DDSCAPS2_CUBEMAP) === DDSCAPS2_CUBEMAP,
  78342. isCompressed: (fourCC === FOURCC_DXT1 || fourCC === FOURCC_DXT3 || fourCC === FOURCC_DXT5),
  78343. dxgiFormat: dxgiFormat,
  78344. textureType: textureType
  78345. };
  78346. };
  78347. DDSTools._ToHalfFloat = function (value) {
  78348. if (!DDSTools._FloatView) {
  78349. DDSTools._FloatView = new Float32Array(1);
  78350. DDSTools._Int32View = new Int32Array(DDSTools._FloatView.buffer);
  78351. }
  78352. DDSTools._FloatView[0] = value;
  78353. var x = DDSTools._Int32View[0];
  78354. var bits = (x >> 16) & 0x8000; /* Get the sign */
  78355. var m = (x >> 12) & 0x07ff; /* Keep one extra bit for rounding */
  78356. var e = (x >> 23) & 0xff; /* Using int is faster here */
  78357. /* If zero, or denormal, or exponent underflows too much for a denormal
  78358. * half, return signed zero. */
  78359. if (e < 103) {
  78360. return bits;
  78361. }
  78362. /* If NaN, return NaN. If Inf or exponent overflow, return Inf. */
  78363. if (e > 142) {
  78364. bits |= 0x7c00;
  78365. /* If exponent was 0xff and one mantissa bit was set, it means NaN,
  78366. * not Inf, so make sure we set one mantissa bit too. */
  78367. bits |= ((e == 255) ? 0 : 1) && (x & 0x007fffff);
  78368. return bits;
  78369. }
  78370. /* If exponent underflows but not too much, return a denormal */
  78371. if (e < 113) {
  78372. m |= 0x0800;
  78373. /* Extra rounding may overflow and set mantissa to 0 and exponent
  78374. * to 1, which is OK. */
  78375. bits |= (m >> (114 - e)) + ((m >> (113 - e)) & 1);
  78376. return bits;
  78377. }
  78378. bits |= ((e - 112) << 10) | (m >> 1);
  78379. bits += m & 1;
  78380. return bits;
  78381. };
  78382. DDSTools._FromHalfFloat = function (value) {
  78383. var s = (value & 0x8000) >> 15;
  78384. var e = (value & 0x7C00) >> 10;
  78385. var f = value & 0x03FF;
  78386. if (e === 0) {
  78387. return (s ? -1 : 1) * Math.pow(2, -14) * (f / Math.pow(2, 10));
  78388. }
  78389. else if (e == 0x1F) {
  78390. return f ? NaN : ((s ? -1 : 1) * Infinity);
  78391. }
  78392. return (s ? -1 : 1) * Math.pow(2, e - 15) * (1 + (f / Math.pow(2, 10)));
  78393. };
  78394. DDSTools._GetHalfFloatAsFloatRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  78395. var destArray = new Float32Array(dataLength);
  78396. var srcData = new Uint16Array(arrayBuffer, dataOffset);
  78397. var index = 0;
  78398. for (var y = 0; y < height; y++) {
  78399. for (var x = 0; x < width; x++) {
  78400. var srcPos = (x + y * width) * 4;
  78401. destArray[index] = DDSTools._FromHalfFloat(srcData[srcPos]);
  78402. destArray[index + 1] = DDSTools._FromHalfFloat(srcData[srcPos + 1]);
  78403. destArray[index + 2] = DDSTools._FromHalfFloat(srcData[srcPos + 2]);
  78404. if (DDSTools.StoreLODInAlphaChannel) {
  78405. destArray[index + 3] = lod;
  78406. }
  78407. else {
  78408. destArray[index + 3] = DDSTools._FromHalfFloat(srcData[srcPos + 3]);
  78409. }
  78410. index += 4;
  78411. }
  78412. }
  78413. return destArray;
  78414. };
  78415. DDSTools._GetHalfFloatRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  78416. if (DDSTools.StoreLODInAlphaChannel) {
  78417. var destArray = new Uint16Array(dataLength);
  78418. var srcData = new Uint16Array(arrayBuffer, dataOffset);
  78419. var index = 0;
  78420. for (var y = 0; y < height; y++) {
  78421. for (var x = 0; x < width; x++) {
  78422. var srcPos = (x + y * width) * 4;
  78423. destArray[index] = srcData[srcPos];
  78424. destArray[index + 1] = srcData[srcPos + 1];
  78425. destArray[index + 2] = srcData[srcPos + 2];
  78426. destArray[index + 3] = DDSTools._ToHalfFloat(lod);
  78427. index += 4;
  78428. }
  78429. }
  78430. return destArray;
  78431. }
  78432. return new Uint16Array(arrayBuffer, dataOffset, dataLength);
  78433. };
  78434. DDSTools._GetFloatRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  78435. if (DDSTools.StoreLODInAlphaChannel) {
  78436. var destArray = new Float32Array(dataLength);
  78437. var srcData = new Float32Array(arrayBuffer, dataOffset);
  78438. var index = 0;
  78439. for (var y = 0; y < height; y++) {
  78440. for (var x = 0; x < width; x++) {
  78441. var srcPos = (x + y * width) * 4;
  78442. destArray[index] = srcData[srcPos];
  78443. destArray[index + 1] = srcData[srcPos + 1];
  78444. destArray[index + 2] = srcData[srcPos + 2];
  78445. destArray[index + 3] = lod;
  78446. index += 4;
  78447. }
  78448. }
  78449. return destArray;
  78450. }
  78451. return new Float32Array(arrayBuffer, dataOffset, dataLength);
  78452. };
  78453. DDSTools._GetFloatAsUIntRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  78454. var destArray = new Uint8Array(dataLength);
  78455. var srcData = new Float32Array(arrayBuffer, dataOffset);
  78456. var index = 0;
  78457. for (var y = 0; y < height; y++) {
  78458. for (var x = 0; x < width; x++) {
  78459. var srcPos = (x + y * width) * 4;
  78460. destArray[index] = BABYLON.Scalar.Clamp(srcData[srcPos]) * 255;
  78461. destArray[index + 1] = BABYLON.Scalar.Clamp(srcData[srcPos + 1]) * 255;
  78462. destArray[index + 2] = BABYLON.Scalar.Clamp(srcData[srcPos + 2]) * 255;
  78463. if (DDSTools.StoreLODInAlphaChannel) {
  78464. destArray[index + 3] = lod;
  78465. }
  78466. else {
  78467. destArray[index + 3] = BABYLON.Scalar.Clamp(srcData[srcPos + 3]) * 255;
  78468. }
  78469. index += 4;
  78470. }
  78471. }
  78472. return destArray;
  78473. };
  78474. DDSTools._GetHalfFloatAsUIntRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  78475. var destArray = new Uint8Array(dataLength);
  78476. var srcData = new Uint16Array(arrayBuffer, dataOffset);
  78477. var index = 0;
  78478. for (var y = 0; y < height; y++) {
  78479. for (var x = 0; x < width; x++) {
  78480. var srcPos = (x + y * width) * 4;
  78481. destArray[index] = BABYLON.Scalar.Clamp(DDSTools._FromHalfFloat(srcData[srcPos])) * 255;
  78482. destArray[index + 1] = BABYLON.Scalar.Clamp(DDSTools._FromHalfFloat(srcData[srcPos + 1])) * 255;
  78483. destArray[index + 2] = BABYLON.Scalar.Clamp(DDSTools._FromHalfFloat(srcData[srcPos + 2])) * 255;
  78484. if (DDSTools.StoreLODInAlphaChannel) {
  78485. destArray[index + 3] = lod;
  78486. }
  78487. else {
  78488. destArray[index + 3] = BABYLON.Scalar.Clamp(DDSTools._FromHalfFloat(srcData[srcPos + 3])) * 255;
  78489. }
  78490. index += 4;
  78491. }
  78492. }
  78493. return destArray;
  78494. };
  78495. DDSTools._GetRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, rOffset, gOffset, bOffset, aOffset) {
  78496. var byteArray = new Uint8Array(dataLength);
  78497. var srcData = new Uint8Array(arrayBuffer, dataOffset);
  78498. var index = 0;
  78499. for (var y = 0; y < height; y++) {
  78500. for (var x = 0; x < width; x++) {
  78501. var srcPos = (x + y * width) * 4;
  78502. byteArray[index] = srcData[srcPos + rOffset];
  78503. byteArray[index + 1] = srcData[srcPos + gOffset];
  78504. byteArray[index + 2] = srcData[srcPos + bOffset];
  78505. byteArray[index + 3] = srcData[srcPos + aOffset];
  78506. index += 4;
  78507. }
  78508. }
  78509. return byteArray;
  78510. };
  78511. DDSTools._ExtractLongWordOrder = function (value) {
  78512. if (value === 0 || value === 255 || value === -16777216) {
  78513. return 0;
  78514. }
  78515. return 1 + DDSTools._ExtractLongWordOrder(value >> 8);
  78516. };
  78517. DDSTools._GetRGBArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, rOffset, gOffset, bOffset) {
  78518. var byteArray = new Uint8Array(dataLength);
  78519. var srcData = new Uint8Array(arrayBuffer, dataOffset);
  78520. var index = 0;
  78521. for (var y = 0; y < height; y++) {
  78522. for (var x = 0; x < width; x++) {
  78523. var srcPos = (x + y * width) * 3;
  78524. byteArray[index] = srcData[srcPos + rOffset];
  78525. byteArray[index + 1] = srcData[srcPos + gOffset];
  78526. byteArray[index + 2] = srcData[srcPos + bOffset];
  78527. index += 3;
  78528. }
  78529. }
  78530. return byteArray;
  78531. };
  78532. DDSTools._GetLuminanceArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer) {
  78533. var byteArray = new Uint8Array(dataLength);
  78534. var srcData = new Uint8Array(arrayBuffer, dataOffset);
  78535. var index = 0;
  78536. for (var y = 0; y < height; y++) {
  78537. for (var x = 0; x < width; x++) {
  78538. var srcPos = (x + y * width);
  78539. byteArray[index] = srcData[srcPos];
  78540. index++;
  78541. }
  78542. }
  78543. return byteArray;
  78544. };
  78545. DDSTools.UploadDDSLevels = function (engine, gl, arrayBuffer, info, loadMipmaps, faces, lodIndex, currentFace) {
  78546. if (lodIndex === void 0) { lodIndex = -1; }
  78547. var ext = engine.getCaps().s3tc;
  78548. var header = new Int32Array(arrayBuffer, 0, headerLengthInt);
  78549. var fourCC, width, height, dataLength = 0, dataOffset;
  78550. var byteArray, mipmapCount, mip;
  78551. var internalFormat = 0;
  78552. var format = 0;
  78553. var blockBytes = 1;
  78554. if (header[off_magic] !== DDS_MAGIC) {
  78555. BABYLON.Tools.Error("Invalid magic number in DDS header");
  78556. return;
  78557. }
  78558. if (!info.isFourCC && !info.isRGB && !info.isLuminance) {
  78559. BABYLON.Tools.Error("Unsupported format, must contain a FourCC, RGB or LUMINANCE code");
  78560. return;
  78561. }
  78562. if (info.isCompressed && !ext) {
  78563. BABYLON.Tools.Error("Compressed textures are not supported on this platform.");
  78564. return;
  78565. }
  78566. var bpp = header[off_RGBbpp];
  78567. dataOffset = header[off_size] + 4;
  78568. var computeFormats = false;
  78569. if (info.isFourCC) {
  78570. fourCC = header[off_pfFourCC];
  78571. switch (fourCC) {
  78572. case FOURCC_DXT1:
  78573. blockBytes = 8;
  78574. internalFormat = ext.COMPRESSED_RGBA_S3TC_DXT1_EXT;
  78575. break;
  78576. case FOURCC_DXT3:
  78577. blockBytes = 16;
  78578. internalFormat = ext.COMPRESSED_RGBA_S3TC_DXT3_EXT;
  78579. break;
  78580. case FOURCC_DXT5:
  78581. blockBytes = 16;
  78582. internalFormat = ext.COMPRESSED_RGBA_S3TC_DXT5_EXT;
  78583. break;
  78584. case FOURCC_D3DFMT_R16G16B16A16F:
  78585. computeFormats = true;
  78586. break;
  78587. case FOURCC_D3DFMT_R32G32B32A32F:
  78588. computeFormats = true;
  78589. break;
  78590. case FOURCC_DX10:
  78591. // There is an additionnal header so dataOffset need to be changed
  78592. dataOffset += 5 * 4; // 5 uints
  78593. var supported = false;
  78594. switch (info.dxgiFormat) {
  78595. case DXGI_FORMAT_R16G16B16A16_FLOAT:
  78596. computeFormats = true;
  78597. supported = true;
  78598. break;
  78599. case DXGI_FORMAT_B8G8R8X8_UNORM:
  78600. info.isRGB = true;
  78601. info.isFourCC = false;
  78602. bpp = 32;
  78603. supported = true;
  78604. break;
  78605. }
  78606. if (supported) {
  78607. break;
  78608. }
  78609. default:
  78610. console.error("Unsupported FourCC code:", Int32ToFourCC(fourCC));
  78611. return;
  78612. }
  78613. }
  78614. var rOffset = DDSTools._ExtractLongWordOrder(header[off_RMask]);
  78615. var gOffset = DDSTools._ExtractLongWordOrder(header[off_GMask]);
  78616. var bOffset = DDSTools._ExtractLongWordOrder(header[off_BMask]);
  78617. var aOffset = DDSTools._ExtractLongWordOrder(header[off_AMask]);
  78618. if (computeFormats) {
  78619. format = engine._getWebGLTextureType(info.textureType);
  78620. internalFormat = engine._getRGBABufferInternalSizedFormat(info.textureType);
  78621. }
  78622. mipmapCount = 1;
  78623. if (header[off_flags] & DDSD_MIPMAPCOUNT && loadMipmaps !== false) {
  78624. mipmapCount = Math.max(1, header[off_mipmapCount]);
  78625. }
  78626. for (var face = 0; face < faces; face++) {
  78627. var sampler = faces === 1 ? gl.TEXTURE_2D : (gl.TEXTURE_CUBE_MAP_POSITIVE_X + face + (currentFace ? currentFace : 0));
  78628. width = header[off_width];
  78629. height = header[off_height];
  78630. for (mip = 0; mip < mipmapCount; ++mip) {
  78631. if (lodIndex === -1 || lodIndex === mip) {
  78632. // In case of fixed LOD, if the lod has just been uploaded, early exit.
  78633. var i = (lodIndex === -1) ? mip : 0;
  78634. if (!info.isCompressed && info.isFourCC) {
  78635. dataLength = width * height * 4;
  78636. var floatArray = null;
  78637. if (engine.badOS || engine.badDesktopOS || (!engine.getCaps().textureHalfFloat && !engine.getCaps().textureFloat)) {
  78638. if (bpp === 128) {
  78639. floatArray = DDSTools._GetFloatAsUIntRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  78640. }
  78641. else if (bpp === 64) {
  78642. floatArray = DDSTools._GetHalfFloatAsUIntRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  78643. }
  78644. info.textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  78645. format = engine._getWebGLTextureType(info.textureType);
  78646. internalFormat = engine._getRGBABufferInternalSizedFormat(info.textureType);
  78647. }
  78648. else {
  78649. if (bpp === 128) {
  78650. floatArray = DDSTools._GetFloatRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  78651. }
  78652. else if (bpp === 64 && !engine.getCaps().textureHalfFloat) {
  78653. floatArray = DDSTools._GetHalfFloatAsFloatRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  78654. info.textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  78655. format = engine._getWebGLTextureType(info.textureType);
  78656. internalFormat = engine._getRGBABufferInternalSizedFormat(info.textureType);
  78657. }
  78658. else {
  78659. floatArray = DDSTools._GetHalfFloatRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  78660. }
  78661. }
  78662. if (floatArray) {
  78663. engine._uploadDataToTexture(sampler, i, internalFormat, width, height, gl.RGBA, format, floatArray);
  78664. }
  78665. }
  78666. else if (info.isRGB) {
  78667. if (bpp === 24) {
  78668. dataLength = width * height * 3;
  78669. byteArray = DDSTools._GetRGBArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, rOffset, gOffset, bOffset);
  78670. engine._uploadDataToTexture(sampler, i, gl.RGB, width, height, gl.RGB, gl.UNSIGNED_BYTE, byteArray);
  78671. }
  78672. else {
  78673. dataLength = width * height * 4;
  78674. byteArray = DDSTools._GetRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, rOffset, gOffset, bOffset, aOffset);
  78675. engine._uploadDataToTexture(sampler, i, gl.RGBA, width, height, gl.RGBA, gl.UNSIGNED_BYTE, byteArray);
  78676. }
  78677. }
  78678. else if (info.isLuminance) {
  78679. var unpackAlignment = gl.getParameter(gl.UNPACK_ALIGNMENT);
  78680. var unpaddedRowSize = width;
  78681. var paddedRowSize = Math.floor((width + unpackAlignment - 1) / unpackAlignment) * unpackAlignment;
  78682. dataLength = paddedRowSize * (height - 1) + unpaddedRowSize;
  78683. byteArray = DDSTools._GetLuminanceArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer);
  78684. engine._uploadDataToTexture(sampler, i, gl.LUMINANCE, width, height, gl.LUMINANCE, gl.UNSIGNED_BYTE, byteArray);
  78685. }
  78686. else {
  78687. dataLength = Math.max(4, width) / 4 * Math.max(4, height) / 4 * blockBytes;
  78688. byteArray = new Uint8Array(arrayBuffer, dataOffset, dataLength);
  78689. engine._uploadCompressedDataToTexture(sampler, i, internalFormat, width, height, byteArray);
  78690. }
  78691. }
  78692. dataOffset += bpp ? (width * height * (bpp / 8)) : dataLength;
  78693. width *= 0.5;
  78694. height *= 0.5;
  78695. width = Math.max(1.0, width);
  78696. height = Math.max(1.0, height);
  78697. }
  78698. if (currentFace !== undefined) {
  78699. // Loading a single face
  78700. break;
  78701. }
  78702. }
  78703. };
  78704. DDSTools.StoreLODInAlphaChannel = false;
  78705. return DDSTools;
  78706. }());
  78707. BABYLON.DDSTools = DDSTools;
  78708. })(BABYLON || (BABYLON = {}));
  78709. //# sourceMappingURL=babylon.dds.js.map
  78710. var BABYLON;
  78711. (function (BABYLON) {
  78712. /**
  78713. * for description see https://www.khronos.org/opengles/sdk/tools/KTX/
  78714. * for file layout see https://www.khronos.org/opengles/sdk/tools/KTX/file_format_spec/
  78715. */
  78716. var KhronosTextureContainer = /** @class */ (function () {
  78717. /**
  78718. * @param {ArrayBuffer} arrayBuffer- contents of the KTX container file
  78719. * @param {number} facesExpected- should be either 1 or 6, based whether a cube texture or or
  78720. * @param {boolean} threeDExpected- provision for indicating that data should be a 3D texture, not implemented
  78721. * @param {boolean} textureArrayExpected- provision for indicating that data should be a texture array, not implemented
  78722. */
  78723. function KhronosTextureContainer(arrayBuffer, facesExpected, threeDExpected, textureArrayExpected) {
  78724. this.arrayBuffer = arrayBuffer;
  78725. // Test that it is a ktx formatted file, based on the first 12 bytes, character representation is:
  78726. // '�', 'K', 'T', 'X', ' ', '1', '1', '�', '\r', '\n', '\x1A', '\n'
  78727. // 0xAB, 0x4B, 0x54, 0x58, 0x20, 0x31, 0x31, 0xBB, 0x0D, 0x0A, 0x1A, 0x0A
  78728. var identifier = new Uint8Array(this.arrayBuffer, 0, 12);
  78729. if (identifier[0] !== 0xAB || identifier[1] !== 0x4B || identifier[2] !== 0x54 || identifier[3] !== 0x58 || identifier[4] !== 0x20 || identifier[5] !== 0x31 ||
  78730. identifier[6] !== 0x31 || identifier[7] !== 0xBB || identifier[8] !== 0x0D || identifier[9] !== 0x0A || identifier[10] !== 0x1A || identifier[11] !== 0x0A) {
  78731. BABYLON.Tools.Error("texture missing KTX identifier");
  78732. return;
  78733. }
  78734. // load the reset of the header in native 32 bit int
  78735. var header = new Int32Array(this.arrayBuffer, 12, 13);
  78736. // determine of the remaining header values are recorded in the opposite endianness & require conversion
  78737. var oppositeEndianess = header[0] === 0x01020304;
  78738. // read all the header elements in order they exist in the file, without modification (sans endainness)
  78739. this.glType = oppositeEndianess ? this.switchEndainness(header[1]) : header[1]; // must be 0 for compressed textures
  78740. this.glTypeSize = oppositeEndianess ? this.switchEndainness(header[2]) : header[2]; // must be 1 for compressed textures
  78741. this.glFormat = oppositeEndianess ? this.switchEndainness(header[3]) : header[3]; // must be 0 for compressed textures
  78742. this.glInternalFormat = oppositeEndianess ? this.switchEndainness(header[4]) : header[4]; // the value of arg passed to gl.compressedTexImage2D(,,x,,,,)
  78743. this.glBaseInternalFormat = oppositeEndianess ? this.switchEndainness(header[5]) : header[5]; // specify GL_RGB, GL_RGBA, GL_ALPHA, etc (un-compressed only)
  78744. this.pixelWidth = oppositeEndianess ? this.switchEndainness(header[6]) : header[6]; // level 0 value of arg passed to gl.compressedTexImage2D(,,,x,,,)
  78745. this.pixelHeight = oppositeEndianess ? this.switchEndainness(header[7]) : header[7]; // level 0 value of arg passed to gl.compressedTexImage2D(,,,,x,,)
  78746. this.pixelDepth = oppositeEndianess ? this.switchEndainness(header[8]) : header[8]; // level 0 value of arg passed to gl.compressedTexImage3D(,,,,,x,,)
  78747. this.numberOfArrayElements = oppositeEndianess ? this.switchEndainness(header[9]) : header[9]; // used for texture arrays
  78748. this.numberOfFaces = oppositeEndianess ? this.switchEndainness(header[10]) : header[10]; // used for cubemap textures, should either be 1 or 6
  78749. this.numberOfMipmapLevels = oppositeEndianess ? this.switchEndainness(header[11]) : header[11]; // number of levels; disregard possibility of 0 for compressed textures
  78750. this.bytesOfKeyValueData = oppositeEndianess ? this.switchEndainness(header[12]) : header[12]; // the amount of space after the header for meta-data
  78751. // Make sure we have a compressed type. Not only reduces work, but probably better to let dev know they are not compressing.
  78752. if (this.glType !== 0) {
  78753. BABYLON.Tools.Error("only compressed formats currently supported");
  78754. return;
  78755. }
  78756. else {
  78757. // value of zero is an indication to generate mipmaps @ runtime. Not usually allowed for compressed, so disregard.
  78758. this.numberOfMipmapLevels = Math.max(1, this.numberOfMipmapLevels);
  78759. }
  78760. if (this.pixelHeight === 0 || this.pixelDepth !== 0) {
  78761. BABYLON.Tools.Error("only 2D textures currently supported");
  78762. return;
  78763. }
  78764. if (this.numberOfArrayElements !== 0) {
  78765. BABYLON.Tools.Error("texture arrays not currently supported");
  78766. return;
  78767. }
  78768. if (this.numberOfFaces !== facesExpected) {
  78769. BABYLON.Tools.Error("number of faces expected" + facesExpected + ", but found " + this.numberOfFaces);
  78770. return;
  78771. }
  78772. // we now have a completely validated file, so could use existence of loadType as success
  78773. // would need to make this more elaborate & adjust checks above to support more than one load type
  78774. this.loadType = KhronosTextureContainer.COMPRESSED_2D;
  78775. }
  78776. // not as fast hardware based, but will probably never need to use
  78777. KhronosTextureContainer.prototype.switchEndainness = function (val) {
  78778. return ((val & 0xFF) << 24)
  78779. | ((val & 0xFF00) << 8)
  78780. | ((val >> 8) & 0xFF00)
  78781. | ((val >> 24) & 0xFF);
  78782. };
  78783. /**
  78784. * It is assumed that the texture has already been created & is currently bound
  78785. */
  78786. KhronosTextureContainer.prototype.uploadLevels = function (gl, loadMipmaps) {
  78787. switch (this.loadType) {
  78788. case KhronosTextureContainer.COMPRESSED_2D:
  78789. this._upload2DCompressedLevels(gl, loadMipmaps);
  78790. break;
  78791. case KhronosTextureContainer.TEX_2D:
  78792. case KhronosTextureContainer.COMPRESSED_3D:
  78793. case KhronosTextureContainer.TEX_3D:
  78794. }
  78795. };
  78796. KhronosTextureContainer.prototype._upload2DCompressedLevels = function (gl, loadMipmaps) {
  78797. // initialize width & height for level 1
  78798. var dataOffset = KhronosTextureContainer.HEADER_LEN + this.bytesOfKeyValueData;
  78799. var width = this.pixelWidth;
  78800. var height = this.pixelHeight;
  78801. var mipmapCount = loadMipmaps ? this.numberOfMipmapLevels : 1;
  78802. for (var level = 0; level < mipmapCount; level++) {
  78803. var imageSize = new Int32Array(this.arrayBuffer, dataOffset, 1)[0]; // size per face, since not supporting array cubemaps
  78804. for (var face = 0; face < this.numberOfFaces; face++) {
  78805. var sampler = this.numberOfFaces === 1 ? gl.TEXTURE_2D : (gl.TEXTURE_CUBE_MAP_POSITIVE_X + face);
  78806. var byteArray = new Uint8Array(this.arrayBuffer, dataOffset + 4, imageSize);
  78807. gl.compressedTexImage2D(sampler, level, this.glInternalFormat, width, height, 0, byteArray);
  78808. dataOffset += imageSize + 4; // size of the image + 4 for the imageSize field
  78809. dataOffset += 3 - ((imageSize + 3) % 4); // add padding for odd sized image
  78810. }
  78811. width = Math.max(1.0, width * 0.5);
  78812. height = Math.max(1.0, height * 0.5);
  78813. }
  78814. };
  78815. KhronosTextureContainer.HEADER_LEN = 12 + (13 * 4); // identifier + header elements (not including key value meta-data pairs)
  78816. // load types
  78817. KhronosTextureContainer.COMPRESSED_2D = 0; // uses a gl.compressedTexImage2D()
  78818. KhronosTextureContainer.COMPRESSED_3D = 1; // uses a gl.compressedTexImage3D()
  78819. KhronosTextureContainer.TEX_2D = 2; // uses a gl.texImage2D()
  78820. KhronosTextureContainer.TEX_3D = 3; // uses a gl.texImage3D()
  78821. return KhronosTextureContainer;
  78822. }());
  78823. BABYLON.KhronosTextureContainer = KhronosTextureContainer;
  78824. })(BABYLON || (BABYLON = {}));
  78825. //# sourceMappingURL=babylon.khronosTextureContainer.js.map
  78826. var BABYLON;
  78827. (function (BABYLON) {
  78828. var Debug = /** @class */ (function () {
  78829. function Debug() {
  78830. }
  78831. Debug.AxesViewer = /** @class */ (function () {
  78832. function AxesViewer(scene, scaleLines) {
  78833. if (scaleLines === void 0) { scaleLines = 1; }
  78834. this._xline = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  78835. this._yline = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  78836. this._zline = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  78837. this.scaleLines = 1;
  78838. this.scaleLines = scaleLines;
  78839. this._xmesh = BABYLON.Mesh.CreateLines("xline", this._xline, scene, true);
  78840. this._ymesh = BABYLON.Mesh.CreateLines("yline", this._yline, scene, true);
  78841. this._zmesh = BABYLON.Mesh.CreateLines("zline", this._zline, scene, true);
  78842. this._xmesh.renderingGroupId = 2;
  78843. this._ymesh.renderingGroupId = 2;
  78844. this._zmesh.renderingGroupId = 2;
  78845. this._xmesh.material.checkReadyOnlyOnce = true;
  78846. this._xmesh.color = new BABYLON.Color3(1, 0, 0);
  78847. this._ymesh.material.checkReadyOnlyOnce = true;
  78848. this._ymesh.color = new BABYLON.Color3(0, 1, 0);
  78849. this._zmesh.material.checkReadyOnlyOnce = true;
  78850. this._zmesh.color = new BABYLON.Color3(0, 0, 1);
  78851. this.scene = scene;
  78852. }
  78853. AxesViewer.prototype.update = function (position, xaxis, yaxis, zaxis) {
  78854. var scaleLines = this.scaleLines;
  78855. if (this._xmesh) {
  78856. this._xmesh.position.copyFrom(position);
  78857. }
  78858. if (this._ymesh) {
  78859. this._ymesh.position.copyFrom(position);
  78860. }
  78861. if (this._zmesh) {
  78862. this._zmesh.position.copyFrom(position);
  78863. }
  78864. var point2 = this._xline[1];
  78865. point2.x = xaxis.x * scaleLines;
  78866. point2.y = xaxis.y * scaleLines;
  78867. point2.z = xaxis.z * scaleLines;
  78868. BABYLON.Mesh.CreateLines("", this._xline, null, false, this._xmesh);
  78869. point2 = this._yline[1];
  78870. point2.x = yaxis.x * scaleLines;
  78871. point2.y = yaxis.y * scaleLines;
  78872. point2.z = yaxis.z * scaleLines;
  78873. BABYLON.Mesh.CreateLines("", this._yline, null, false, this._ymesh);
  78874. point2 = this._zline[1];
  78875. point2.x = zaxis.x * scaleLines;
  78876. point2.y = zaxis.y * scaleLines;
  78877. point2.z = zaxis.z * scaleLines;
  78878. BABYLON.Mesh.CreateLines("", this._zline, null, false, this._zmesh);
  78879. };
  78880. AxesViewer.prototype.dispose = function () {
  78881. if (this._xmesh) {
  78882. this._xmesh.dispose();
  78883. }
  78884. if (this._ymesh) {
  78885. this._ymesh.dispose();
  78886. }
  78887. if (this._zmesh) {
  78888. this._zmesh.dispose();
  78889. }
  78890. this._xmesh = null;
  78891. this._ymesh = null;
  78892. this._zmesh = null;
  78893. this.scene = null;
  78894. };
  78895. return AxesViewer;
  78896. }());
  78897. Debug.BoneAxesViewer = /** @class */ (function (_super) {
  78898. __extends(BoneAxesViewer, _super);
  78899. function BoneAxesViewer(scene, bone, mesh, scaleLines) {
  78900. if (scaleLines === void 0) { scaleLines = 1; }
  78901. var _this = _super.call(this, scene, scaleLines) || this;
  78902. _this.pos = BABYLON.Vector3.Zero();
  78903. _this.xaxis = BABYLON.Vector3.Zero();
  78904. _this.yaxis = BABYLON.Vector3.Zero();
  78905. _this.zaxis = BABYLON.Vector3.Zero();
  78906. _this.mesh = mesh;
  78907. _this.bone = bone;
  78908. return _this;
  78909. }
  78910. BoneAxesViewer.prototype.update = function () {
  78911. if (!this.mesh || !this.bone) {
  78912. return;
  78913. }
  78914. var bone = this.bone;
  78915. bone.getAbsolutePositionToRef(this.mesh, this.pos);
  78916. bone.getDirectionToRef(BABYLON.Axis.X, this.mesh, this.xaxis);
  78917. bone.getDirectionToRef(BABYLON.Axis.Y, this.mesh, this.yaxis);
  78918. bone.getDirectionToRef(BABYLON.Axis.Z, this.mesh, this.zaxis);
  78919. _super.prototype.update.call(this, this.pos, this.xaxis, this.yaxis, this.zaxis);
  78920. };
  78921. BoneAxesViewer.prototype.dispose = function () {
  78922. if (this.mesh) {
  78923. this.mesh = null;
  78924. this.bone = null;
  78925. _super.prototype.dispose.call(this);
  78926. }
  78927. };
  78928. return BoneAxesViewer;
  78929. }(Debug.AxesViewer));
  78930. Debug.PhysicsViewer = /** @class */ (function () {
  78931. function PhysicsViewer(scene) {
  78932. this._impostors = [];
  78933. this._meshes = [];
  78934. this._numMeshes = 0;
  78935. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  78936. var physicEngine = this._scene.getPhysicsEngine();
  78937. if (physicEngine) {
  78938. this._physicsEnginePlugin = physicEngine.getPhysicsPlugin();
  78939. }
  78940. }
  78941. PhysicsViewer.prototype._updateDebugMeshes = function () {
  78942. var plugin = this._physicsEnginePlugin;
  78943. for (var i = 0; i < this._numMeshes; i++) {
  78944. var impostor = this._impostors[i];
  78945. if (!impostor) {
  78946. continue;
  78947. }
  78948. if (impostor.isDisposed) {
  78949. this.hideImpostor(this._impostors[i--]);
  78950. }
  78951. else {
  78952. var mesh = this._meshes[i];
  78953. if (mesh && plugin) {
  78954. plugin.syncMeshWithImpostor(mesh, impostor);
  78955. }
  78956. }
  78957. }
  78958. };
  78959. PhysicsViewer.prototype.showImpostor = function (impostor) {
  78960. if (!this._scene) {
  78961. return;
  78962. }
  78963. for (var i = 0; i < this._numMeshes; i++) {
  78964. if (this._impostors[i] == impostor) {
  78965. return;
  78966. }
  78967. }
  78968. var debugMesh = this._getDebugMesh(impostor, this._scene);
  78969. if (debugMesh) {
  78970. this._impostors[this._numMeshes] = impostor;
  78971. this._meshes[this._numMeshes] = debugMesh;
  78972. if (this._numMeshes === 0) {
  78973. this._renderFunction = this._updateDebugMeshes.bind(this);
  78974. this._scene.registerBeforeRender(this._renderFunction);
  78975. }
  78976. this._numMeshes++;
  78977. }
  78978. };
  78979. PhysicsViewer.prototype.hideImpostor = function (impostor) {
  78980. if (!impostor || !this._scene) {
  78981. return;
  78982. }
  78983. var removed = false;
  78984. for (var i = 0; i < this._numMeshes; i++) {
  78985. if (this._impostors[i] == impostor) {
  78986. var mesh = this._meshes[i];
  78987. if (!mesh) {
  78988. continue;
  78989. }
  78990. this._scene.removeMesh(mesh);
  78991. mesh.dispose();
  78992. this._numMeshes--;
  78993. if (this._numMeshes > 0) {
  78994. this._meshes[i] = this._meshes[this._numMeshes];
  78995. this._impostors[i] = this._impostors[this._numMeshes];
  78996. this._meshes[this._numMeshes] = null;
  78997. this._impostors[this._numMeshes] = null;
  78998. }
  78999. else {
  79000. this._meshes[0] = null;
  79001. this._impostors[0] = null;
  79002. }
  79003. removed = true;
  79004. break;
  79005. }
  79006. }
  79007. if (removed && this._numMeshes === 0) {
  79008. this._scene.unregisterBeforeRender(this._renderFunction);
  79009. }
  79010. };
  79011. PhysicsViewer.prototype._getDebugMaterial = function (scene) {
  79012. if (!this._debugMaterial) {
  79013. this._debugMaterial = new BABYLON.StandardMaterial('', scene);
  79014. this._debugMaterial.wireframe = true;
  79015. }
  79016. return this._debugMaterial;
  79017. };
  79018. PhysicsViewer.prototype._getDebugBoxMesh = function (scene) {
  79019. if (!this._debugBoxMesh) {
  79020. this._debugBoxMesh = BABYLON.MeshBuilder.CreateBox('physicsBodyBoxViewMesh', { size: 1 }, scene);
  79021. this._debugBoxMesh.renderingGroupId = 1;
  79022. this._debugBoxMesh.rotationQuaternion = BABYLON.Quaternion.Identity();
  79023. this._debugBoxMesh.material = this._getDebugMaterial(scene);
  79024. scene.removeMesh(this._debugBoxMesh);
  79025. }
  79026. return this._debugBoxMesh.createInstance('physicsBodyBoxViewInstance');
  79027. };
  79028. PhysicsViewer.prototype._getDebugSphereMesh = function (scene) {
  79029. if (!this._debugSphereMesh) {
  79030. this._debugSphereMesh = BABYLON.MeshBuilder.CreateSphere('physicsBodySphereViewMesh', { diameter: 1 }, scene);
  79031. this._debugSphereMesh.renderingGroupId = 1;
  79032. this._debugSphereMesh.rotationQuaternion = BABYLON.Quaternion.Identity();
  79033. this._debugSphereMesh.material = this._getDebugMaterial(scene);
  79034. scene.removeMesh(this._debugSphereMesh);
  79035. }
  79036. return this._debugSphereMesh.createInstance('physicsBodyBoxViewInstance');
  79037. };
  79038. PhysicsViewer.prototype._getDebugMesh = function (impostor, scene) {
  79039. var mesh = null;
  79040. if (impostor.type == BABYLON.PhysicsImpostor.BoxImpostor) {
  79041. mesh = this._getDebugBoxMesh(scene);
  79042. impostor.getBoxSizeToRef(mesh.scaling);
  79043. }
  79044. else if (impostor.type == BABYLON.PhysicsImpostor.SphereImpostor) {
  79045. mesh = this._getDebugSphereMesh(scene);
  79046. var radius = impostor.getRadius();
  79047. mesh.scaling.x = radius * 2;
  79048. mesh.scaling.y = radius * 2;
  79049. mesh.scaling.z = radius * 2;
  79050. }
  79051. return mesh;
  79052. };
  79053. PhysicsViewer.prototype.dispose = function () {
  79054. for (var i = 0; i < this._numMeshes; i++) {
  79055. this.hideImpostor(this._impostors[i]);
  79056. }
  79057. if (this._debugBoxMesh) {
  79058. this._debugBoxMesh.dispose();
  79059. }
  79060. if (this._debugSphereMesh) {
  79061. this._debugSphereMesh.dispose();
  79062. }
  79063. if (this._debugMaterial) {
  79064. this._debugMaterial.dispose();
  79065. }
  79066. this._impostors.length = 0;
  79067. this._scene = null;
  79068. this._physicsEnginePlugin = null;
  79069. };
  79070. return PhysicsViewer;
  79071. }());
  79072. Debug.SkeletonViewer = /** @class */ (function () {
  79073. function SkeletonViewer(skeleton, mesh, scene, autoUpdateBonesMatrices, renderingGroupId) {
  79074. if (autoUpdateBonesMatrices === void 0) { autoUpdateBonesMatrices = true; }
  79075. if (renderingGroupId === void 0) { renderingGroupId = 1; }
  79076. this.skeleton = skeleton;
  79077. this.mesh = mesh;
  79078. this.autoUpdateBonesMatrices = autoUpdateBonesMatrices;
  79079. this.renderingGroupId = renderingGroupId;
  79080. this.color = BABYLON.Color3.White();
  79081. this._debugLines = new Array();
  79082. this._isEnabled = false;
  79083. this._scene = scene;
  79084. this.update();
  79085. this._renderFunction = this.update.bind(this);
  79086. }
  79087. Object.defineProperty(SkeletonViewer.prototype, "isEnabled", {
  79088. get: function () {
  79089. return this._isEnabled;
  79090. },
  79091. set: function (value) {
  79092. if (this._isEnabled === value) {
  79093. return;
  79094. }
  79095. this._isEnabled = value;
  79096. if (value) {
  79097. this._scene.registerBeforeRender(this._renderFunction);
  79098. }
  79099. else {
  79100. this._scene.unregisterBeforeRender(this._renderFunction);
  79101. }
  79102. },
  79103. enumerable: true,
  79104. configurable: true
  79105. });
  79106. SkeletonViewer.prototype._getBonePosition = function (position, bone, meshMat, x, y, z) {
  79107. if (x === void 0) { x = 0; }
  79108. if (y === void 0) { y = 0; }
  79109. if (z === void 0) { z = 0; }
  79110. var tmat = BABYLON.Tmp.Matrix[0];
  79111. var parentBone = bone.getParent();
  79112. tmat.copyFrom(bone.getLocalMatrix());
  79113. if (x !== 0 || y !== 0 || z !== 0) {
  79114. var tmat2 = BABYLON.Tmp.Matrix[1];
  79115. BABYLON.Matrix.IdentityToRef(tmat2);
  79116. tmat2.m[12] = x;
  79117. tmat2.m[13] = y;
  79118. tmat2.m[14] = z;
  79119. tmat2.multiplyToRef(tmat, tmat);
  79120. }
  79121. if (parentBone) {
  79122. tmat.multiplyToRef(parentBone.getAbsoluteTransform(), tmat);
  79123. }
  79124. tmat.multiplyToRef(meshMat, tmat);
  79125. position.x = tmat.m[12];
  79126. position.y = tmat.m[13];
  79127. position.z = tmat.m[14];
  79128. };
  79129. SkeletonViewer.prototype._getLinesForBonesWithLength = function (bones, meshMat) {
  79130. var len = bones.length;
  79131. var meshPos = this.mesh.position;
  79132. for (var i = 0; i < len; i++) {
  79133. var bone = bones[i];
  79134. var points = this._debugLines[i];
  79135. if (!points) {
  79136. points = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  79137. this._debugLines[i] = points;
  79138. }
  79139. this._getBonePosition(points[0], bone, meshMat);
  79140. this._getBonePosition(points[1], bone, meshMat, 0, bone.length, 0);
  79141. points[0].subtractInPlace(meshPos);
  79142. points[1].subtractInPlace(meshPos);
  79143. }
  79144. };
  79145. SkeletonViewer.prototype._getLinesForBonesNoLength = function (bones, meshMat) {
  79146. var len = bones.length;
  79147. var boneNum = 0;
  79148. var meshPos = this.mesh.position;
  79149. for (var i = len - 1; i >= 0; i--) {
  79150. var childBone = bones[i];
  79151. var parentBone = childBone.getParent();
  79152. if (!parentBone) {
  79153. continue;
  79154. }
  79155. var points = this._debugLines[boneNum];
  79156. if (!points) {
  79157. points = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  79158. this._debugLines[boneNum] = points;
  79159. }
  79160. childBone.getAbsolutePositionToRef(this.mesh, points[0]);
  79161. parentBone.getAbsolutePositionToRef(this.mesh, points[1]);
  79162. points[0].subtractInPlace(meshPos);
  79163. points[1].subtractInPlace(meshPos);
  79164. boneNum++;
  79165. }
  79166. };
  79167. SkeletonViewer.prototype.update = function () {
  79168. if (this.autoUpdateBonesMatrices) {
  79169. this.skeleton.computeAbsoluteTransforms();
  79170. }
  79171. if (this.skeleton.bones[0].length === undefined) {
  79172. this._getLinesForBonesNoLength(this.skeleton.bones, this.mesh.getWorldMatrix());
  79173. }
  79174. else {
  79175. this._getLinesForBonesWithLength(this.skeleton.bones, this.mesh.getWorldMatrix());
  79176. }
  79177. if (!this._debugMesh) {
  79178. this._debugMesh = BABYLON.MeshBuilder.CreateLineSystem("", { lines: this._debugLines, updatable: true, instance: null }, this._scene);
  79179. this._debugMesh.renderingGroupId = this.renderingGroupId;
  79180. }
  79181. else {
  79182. BABYLON.MeshBuilder.CreateLineSystem("", { lines: this._debugLines, updatable: true, instance: this._debugMesh }, this._scene);
  79183. }
  79184. this._debugMesh.position.copyFrom(this.mesh.position);
  79185. this._debugMesh.color = this.color;
  79186. };
  79187. SkeletonViewer.prototype.dispose = function () {
  79188. if (this._debugMesh) {
  79189. this.isEnabled = false;
  79190. this._debugMesh.dispose();
  79191. this._debugMesh = null;
  79192. }
  79193. };
  79194. return SkeletonViewer;
  79195. }());
  79196. return Debug;
  79197. }());
  79198. BABYLON.Debug = Debug;
  79199. })(BABYLON || (BABYLON = {}));
  79200. //# sourceMappingURL=babylon.debugModules.js.map
  79201. var BABYLON;
  79202. (function (BABYLON) {
  79203. var RayHelper = /** @class */ (function () {
  79204. function RayHelper(ray) {
  79205. this.ray = ray;
  79206. }
  79207. RayHelper.CreateAndShow = function (ray, scene, color) {
  79208. var helper = new RayHelper(ray);
  79209. helper.show(scene, color);
  79210. return helper;
  79211. };
  79212. RayHelper.prototype.show = function (scene, color) {
  79213. if (!this._renderFunction && this.ray) {
  79214. var ray = this.ray;
  79215. this._renderFunction = this._render.bind(this);
  79216. this._scene = scene;
  79217. this._renderPoints = [ray.origin, ray.origin.add(ray.direction.scale(ray.length))];
  79218. this._renderLine = BABYLON.Mesh.CreateLines("ray", this._renderPoints, scene, true);
  79219. if (this._renderFunction) {
  79220. this._scene.registerBeforeRender(this._renderFunction);
  79221. }
  79222. }
  79223. if (color && this._renderLine) {
  79224. this._renderLine.color.copyFrom(color);
  79225. }
  79226. };
  79227. RayHelper.prototype.hide = function () {
  79228. if (this._renderFunction && this._scene) {
  79229. this._scene.unregisterBeforeRender(this._renderFunction);
  79230. this._scene = null;
  79231. this._renderFunction = null;
  79232. if (this._renderLine) {
  79233. this._renderLine.dispose();
  79234. this._renderLine = null;
  79235. }
  79236. this._renderPoints = [];
  79237. }
  79238. };
  79239. RayHelper.prototype._render = function () {
  79240. var ray = this.ray;
  79241. if (!ray) {
  79242. return;
  79243. }
  79244. var point = this._renderPoints[1];
  79245. var len = Math.min(ray.length, 1000000);
  79246. point.copyFrom(ray.direction);
  79247. point.scaleInPlace(len);
  79248. point.addInPlace(ray.origin);
  79249. BABYLON.Mesh.CreateLines("ray", this._renderPoints, this._scene, true, this._renderLine);
  79250. };
  79251. RayHelper.prototype.attachToMesh = function (mesh, meshSpaceDirection, meshSpaceOrigin, length) {
  79252. this._attachedToMesh = mesh;
  79253. var ray = this.ray;
  79254. if (!ray) {
  79255. return;
  79256. }
  79257. if (!ray.direction) {
  79258. ray.direction = BABYLON.Vector3.Zero();
  79259. }
  79260. if (!ray.origin) {
  79261. ray.origin = BABYLON.Vector3.Zero();
  79262. }
  79263. if (length) {
  79264. ray.length = length;
  79265. }
  79266. if (!meshSpaceOrigin) {
  79267. meshSpaceOrigin = BABYLON.Vector3.Zero();
  79268. }
  79269. if (!meshSpaceDirection) {
  79270. // -1 so that this will work with Mesh.lookAt
  79271. meshSpaceDirection = new BABYLON.Vector3(0, 0, -1);
  79272. }
  79273. if (!this._meshSpaceDirection) {
  79274. this._meshSpaceDirection = meshSpaceDirection.clone();
  79275. this._meshSpaceOrigin = meshSpaceOrigin.clone();
  79276. }
  79277. else {
  79278. this._meshSpaceDirection.copyFrom(meshSpaceDirection);
  79279. this._meshSpaceOrigin.copyFrom(meshSpaceOrigin);
  79280. }
  79281. if (!this._updateToMeshFunction) {
  79282. this._updateToMeshFunction = this._updateToMesh.bind(this);
  79283. this._attachedToMesh.getScene().registerBeforeRender(this._updateToMeshFunction);
  79284. }
  79285. this._updateToMesh();
  79286. };
  79287. RayHelper.prototype.detachFromMesh = function () {
  79288. if (this._attachedToMesh) {
  79289. if (this._updateToMeshFunction) {
  79290. this._attachedToMesh.getScene().unregisterBeforeRender(this._updateToMeshFunction);
  79291. }
  79292. this._attachedToMesh = null;
  79293. this._updateToMeshFunction = null;
  79294. }
  79295. };
  79296. RayHelper.prototype._updateToMesh = function () {
  79297. var ray = this.ray;
  79298. if (!this._attachedToMesh || !ray) {
  79299. return;
  79300. }
  79301. if (this._attachedToMesh._isDisposed) {
  79302. this.detachFromMesh();
  79303. return;
  79304. }
  79305. this._attachedToMesh.getDirectionToRef(this._meshSpaceDirection, ray.direction);
  79306. BABYLON.Vector3.TransformCoordinatesToRef(this._meshSpaceOrigin, this._attachedToMesh.getWorldMatrix(), ray.origin);
  79307. };
  79308. RayHelper.prototype.dispose = function () {
  79309. this.hide();
  79310. this.detachFromMesh();
  79311. this.ray = null;
  79312. };
  79313. return RayHelper;
  79314. }());
  79315. BABYLON.RayHelper = RayHelper;
  79316. })(BABYLON || (BABYLON = {}));
  79317. //# sourceMappingURL=babylon.rayHelper.js.map
  79318. var BABYLON;
  79319. (function (BABYLON) {
  79320. // load the inspector using require, if not present in the global namespace.
  79321. var DebugLayer = /** @class */ (function () {
  79322. function DebugLayer(scene) {
  79323. this.BJSINSPECTOR = typeof INSPECTOR !== 'undefined' ? INSPECTOR : undefined;
  79324. this._scene = scene;
  79325. // load inspector using require, if it doesn't exist on the global namespace.
  79326. }
  79327. /** Creates the inspector window. */
  79328. DebugLayer.prototype._createInspector = function (config) {
  79329. if (config === void 0) { config = {}; }
  79330. var popup = config.popup || false;
  79331. var initialTab = config.initialTab || 0;
  79332. var parentElement = config.parentElement || null;
  79333. if (!this._inspector) {
  79334. this.BJSINSPECTOR = this.BJSINSPECTOR || typeof INSPECTOR !== 'undefined' ? INSPECTOR : undefined;
  79335. this._inspector = new this.BJSINSPECTOR.Inspector(this._scene, popup, initialTab, parentElement, config.newColors);
  79336. } // else nothing to do,; instance is already existing
  79337. };
  79338. DebugLayer.prototype.isVisible = function () {
  79339. if (!this._inspector) {
  79340. return false;
  79341. }
  79342. return true;
  79343. };
  79344. DebugLayer.prototype.hide = function () {
  79345. if (this._inspector) {
  79346. try {
  79347. this._inspector.dispose();
  79348. }
  79349. catch (e) {
  79350. // If the inspector has been removed directly from the inspector tool
  79351. }
  79352. this._inspector = null;
  79353. }
  79354. };
  79355. DebugLayer.prototype.show = function (config) {
  79356. if (config === void 0) { config = {}; }
  79357. if (typeof this.BJSINSPECTOR == 'undefined') {
  79358. // Load inspector and add it to the DOM
  79359. BABYLON.Tools.LoadScript(DebugLayer.InspectorURL, this._createInspector.bind(this, config));
  79360. }
  79361. else {
  79362. // Otherwise creates the inspector
  79363. this._createInspector(config);
  79364. }
  79365. };
  79366. DebugLayer.InspectorURL = 'https://preview.babylonjs.com/inspector/babylon.inspector.bundle.js';
  79367. return DebugLayer;
  79368. }());
  79369. BABYLON.DebugLayer = DebugLayer;
  79370. })(BABYLON || (BABYLON = {}));
  79371. //# sourceMappingURL=babylon.debugLayer.js.map
  79372. var BABYLON;
  79373. (function (BABYLON) {
  79374. var BoundingBoxRenderer = /** @class */ (function () {
  79375. function BoundingBoxRenderer(scene) {
  79376. this.frontColor = new BABYLON.Color3(1, 1, 1);
  79377. this.backColor = new BABYLON.Color3(0.1, 0.1, 0.1);
  79378. this.showBackLines = true;
  79379. this.renderList = new BABYLON.SmartArray(32);
  79380. this._vertexBuffers = {};
  79381. this._scene = scene;
  79382. }
  79383. BoundingBoxRenderer.prototype._prepareRessources = function () {
  79384. if (this._colorShader) {
  79385. return;
  79386. }
  79387. this._colorShader = new BABYLON.ShaderMaterial("colorShader", this._scene, "color", {
  79388. attributes: [BABYLON.VertexBuffer.PositionKind],
  79389. uniforms: ["world", "viewProjection", "color"]
  79390. });
  79391. var engine = this._scene.getEngine();
  79392. var boxdata = BABYLON.VertexData.CreateBox({ size: 1.0 });
  79393. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(engine, boxdata.positions, BABYLON.VertexBuffer.PositionKind, false);
  79394. this._createIndexBuffer();
  79395. };
  79396. BoundingBoxRenderer.prototype._createIndexBuffer = function () {
  79397. var engine = this._scene.getEngine();
  79398. 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]);
  79399. };
  79400. BoundingBoxRenderer.prototype._rebuild = function () {
  79401. var vb = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  79402. if (vb) {
  79403. vb._rebuild();
  79404. }
  79405. this._createIndexBuffer();
  79406. };
  79407. BoundingBoxRenderer.prototype.reset = function () {
  79408. this.renderList.reset();
  79409. };
  79410. BoundingBoxRenderer.prototype.render = function () {
  79411. if (this.renderList.length === 0) {
  79412. return;
  79413. }
  79414. this._prepareRessources();
  79415. if (!this._colorShader.isReady()) {
  79416. return;
  79417. }
  79418. var engine = this._scene.getEngine();
  79419. engine.setDepthWrite(false);
  79420. this._colorShader._preBind();
  79421. for (var boundingBoxIndex = 0; boundingBoxIndex < this.renderList.length; boundingBoxIndex++) {
  79422. var boundingBox = this.renderList.data[boundingBoxIndex];
  79423. var min = boundingBox.minimum;
  79424. var max = boundingBox.maximum;
  79425. var diff = max.subtract(min);
  79426. var median = min.add(diff.scale(0.5));
  79427. var worldMatrix = BABYLON.Matrix.Scaling(diff.x, diff.y, diff.z)
  79428. .multiply(BABYLON.Matrix.Translation(median.x, median.y, median.z))
  79429. .multiply(boundingBox.getWorldMatrix());
  79430. // VBOs
  79431. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._colorShader.getEffect());
  79432. if (this.showBackLines) {
  79433. // Back
  79434. engine.setDepthFunctionToGreaterOrEqual();
  79435. this._scene.resetCachedMaterial();
  79436. this._colorShader.setColor4("color", this.backColor.toColor4());
  79437. this._colorShader.bind(worldMatrix);
  79438. // Draw order
  79439. engine.drawElementsType(BABYLON.Material.LineListDrawMode, 0, 24);
  79440. }
  79441. // Front
  79442. engine.setDepthFunctionToLess();
  79443. this._scene.resetCachedMaterial();
  79444. this._colorShader.setColor4("color", this.frontColor.toColor4());
  79445. this._colorShader.bind(worldMatrix);
  79446. // Draw order
  79447. engine.drawElementsType(BABYLON.Material.LineListDrawMode, 0, 24);
  79448. }
  79449. this._colorShader.unbind();
  79450. engine.setDepthFunctionToLessOrEqual();
  79451. engine.setDepthWrite(true);
  79452. };
  79453. BoundingBoxRenderer.prototype.renderOcclusionBoundingBox = function (mesh) {
  79454. this._prepareRessources();
  79455. if (!this._colorShader.isReady() || !mesh._boundingInfo) {
  79456. return;
  79457. }
  79458. var engine = this._scene.getEngine();
  79459. engine.setDepthWrite(false);
  79460. engine.setColorWrite(false);
  79461. this._colorShader._preBind();
  79462. var boundingBox = mesh._boundingInfo.boundingBox;
  79463. var min = boundingBox.minimum;
  79464. var max = boundingBox.maximum;
  79465. var diff = max.subtract(min);
  79466. var median = min.add(diff.scale(0.5));
  79467. var worldMatrix = BABYLON.Matrix.Scaling(diff.x, diff.y, diff.z)
  79468. .multiply(BABYLON.Matrix.Translation(median.x, median.y, median.z))
  79469. .multiply(boundingBox.getWorldMatrix());
  79470. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._colorShader.getEffect());
  79471. engine.setDepthFunctionToLess();
  79472. this._scene.resetCachedMaterial();
  79473. this._colorShader.bind(worldMatrix);
  79474. engine.drawElementsType(BABYLON.Material.LineListDrawMode, 0, 24);
  79475. this._colorShader.unbind();
  79476. engine.setDepthFunctionToLessOrEqual();
  79477. engine.setDepthWrite(true);
  79478. engine.setColorWrite(true);
  79479. };
  79480. BoundingBoxRenderer.prototype.dispose = function () {
  79481. if (!this._colorShader) {
  79482. return;
  79483. }
  79484. this.renderList.dispose();
  79485. this._colorShader.dispose();
  79486. var buffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  79487. if (buffer) {
  79488. buffer.dispose();
  79489. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  79490. }
  79491. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  79492. };
  79493. return BoundingBoxRenderer;
  79494. }());
  79495. BABYLON.BoundingBoxRenderer = BoundingBoxRenderer;
  79496. })(BABYLON || (BABYLON = {}));
  79497. //# sourceMappingURL=babylon.boundingBoxRenderer.js.map
  79498. var BABYLON;
  79499. (function (BABYLON) {
  79500. var MorphTarget = /** @class */ (function () {
  79501. function MorphTarget(name, influence) {
  79502. if (influence === void 0) { influence = 0; }
  79503. this.name = name;
  79504. this.animations = new Array();
  79505. this._positions = null;
  79506. this._normals = null;
  79507. this._tangents = null;
  79508. this.onInfluenceChanged = new BABYLON.Observable();
  79509. this.influence = influence;
  79510. }
  79511. Object.defineProperty(MorphTarget.prototype, "influence", {
  79512. get: function () {
  79513. return this._influence;
  79514. },
  79515. set: function (influence) {
  79516. if (this._influence === influence) {
  79517. return;
  79518. }
  79519. var previous = this._influence;
  79520. this._influence = influence;
  79521. if (this.onInfluenceChanged.hasObservers) {
  79522. this.onInfluenceChanged.notifyObservers(previous === 0 || influence === 0);
  79523. }
  79524. },
  79525. enumerable: true,
  79526. configurable: true
  79527. });
  79528. Object.defineProperty(MorphTarget.prototype, "hasPositions", {
  79529. get: function () {
  79530. return !!this._positions;
  79531. },
  79532. enumerable: true,
  79533. configurable: true
  79534. });
  79535. Object.defineProperty(MorphTarget.prototype, "hasNormals", {
  79536. get: function () {
  79537. return !!this._normals;
  79538. },
  79539. enumerable: true,
  79540. configurable: true
  79541. });
  79542. Object.defineProperty(MorphTarget.prototype, "hasTangents", {
  79543. get: function () {
  79544. return !!this._tangents;
  79545. },
  79546. enumerable: true,
  79547. configurable: true
  79548. });
  79549. MorphTarget.prototype.setPositions = function (data) {
  79550. this._positions = data;
  79551. };
  79552. MorphTarget.prototype.getPositions = function () {
  79553. return this._positions;
  79554. };
  79555. MorphTarget.prototype.setNormals = function (data) {
  79556. this._normals = data;
  79557. };
  79558. MorphTarget.prototype.getNormals = function () {
  79559. return this._normals;
  79560. };
  79561. MorphTarget.prototype.setTangents = function (data) {
  79562. this._tangents = data;
  79563. };
  79564. MorphTarget.prototype.getTangents = function () {
  79565. return this._tangents;
  79566. };
  79567. /**
  79568. * Serializes the current target into a Serialization object.
  79569. * Returns the serialized object.
  79570. */
  79571. MorphTarget.prototype.serialize = function () {
  79572. var serializationObject = {};
  79573. serializationObject.name = this.name;
  79574. serializationObject.influence = this.influence;
  79575. serializationObject.positions = Array.prototype.slice.call(this.getPositions());
  79576. if (this.hasNormals) {
  79577. serializationObject.normals = Array.prototype.slice.call(this.getNormals());
  79578. }
  79579. if (this.hasTangents) {
  79580. serializationObject.tangents = Array.prototype.slice.call(this.getTangents());
  79581. }
  79582. // Animations
  79583. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  79584. return serializationObject;
  79585. };
  79586. // Statics
  79587. MorphTarget.Parse = function (serializationObject) {
  79588. var result = new MorphTarget(serializationObject.name, serializationObject.influence);
  79589. result.setPositions(serializationObject.positions);
  79590. if (serializationObject.normals) {
  79591. result.setNormals(serializationObject.normals);
  79592. }
  79593. if (serializationObject.tangents) {
  79594. result.setTangents(serializationObject.tangents);
  79595. }
  79596. // Animations
  79597. if (serializationObject.animations) {
  79598. for (var animationIndex = 0; animationIndex < serializationObject.animations.length; animationIndex++) {
  79599. var parsedAnimation = serializationObject.animations[animationIndex];
  79600. result.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  79601. }
  79602. }
  79603. return result;
  79604. };
  79605. MorphTarget.FromMesh = function (mesh, name, influence) {
  79606. if (!name) {
  79607. name = mesh.name;
  79608. }
  79609. var result = new MorphTarget(name, influence);
  79610. result.setPositions(mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind));
  79611. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  79612. result.setNormals(mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind));
  79613. }
  79614. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind)) {
  79615. result.setTangents(mesh.getVerticesData(BABYLON.VertexBuffer.TangentKind));
  79616. }
  79617. return result;
  79618. };
  79619. return MorphTarget;
  79620. }());
  79621. BABYLON.MorphTarget = MorphTarget;
  79622. })(BABYLON || (BABYLON = {}));
  79623. //# sourceMappingURL=babylon.morphTarget.js.map
  79624. var BABYLON;
  79625. (function (BABYLON) {
  79626. var MorphTargetManager = /** @class */ (function () {
  79627. function MorphTargetManager(scene) {
  79628. if (scene === void 0) { scene = null; }
  79629. this._targets = new Array();
  79630. this._targetObservable = new Array();
  79631. this._activeTargets = new BABYLON.SmartArray(16);
  79632. this._supportsNormals = false;
  79633. this._supportsTangents = false;
  79634. this._vertexCount = 0;
  79635. this._uniqueId = 0;
  79636. this._tempInfluences = new Array();
  79637. if (!scene) {
  79638. scene = BABYLON.Engine.LastCreatedScene;
  79639. }
  79640. this._scene = scene;
  79641. if (this._scene) {
  79642. this._scene.morphTargetManagers.push(this);
  79643. this._uniqueId = this._scene.getUniqueId();
  79644. }
  79645. }
  79646. Object.defineProperty(MorphTargetManager.prototype, "uniqueId", {
  79647. get: function () {
  79648. return this._uniqueId;
  79649. },
  79650. enumerable: true,
  79651. configurable: true
  79652. });
  79653. Object.defineProperty(MorphTargetManager.prototype, "vertexCount", {
  79654. get: function () {
  79655. return this._vertexCount;
  79656. },
  79657. enumerable: true,
  79658. configurable: true
  79659. });
  79660. Object.defineProperty(MorphTargetManager.prototype, "supportsNormals", {
  79661. get: function () {
  79662. return this._supportsNormals;
  79663. },
  79664. enumerable: true,
  79665. configurable: true
  79666. });
  79667. Object.defineProperty(MorphTargetManager.prototype, "supportsTangents", {
  79668. get: function () {
  79669. return this._supportsTangents;
  79670. },
  79671. enumerable: true,
  79672. configurable: true
  79673. });
  79674. Object.defineProperty(MorphTargetManager.prototype, "numTargets", {
  79675. get: function () {
  79676. return this._targets.length;
  79677. },
  79678. enumerable: true,
  79679. configurable: true
  79680. });
  79681. Object.defineProperty(MorphTargetManager.prototype, "numInfluencers", {
  79682. get: function () {
  79683. return this._activeTargets.length;
  79684. },
  79685. enumerable: true,
  79686. configurable: true
  79687. });
  79688. Object.defineProperty(MorphTargetManager.prototype, "influences", {
  79689. get: function () {
  79690. return this._influences;
  79691. },
  79692. enumerable: true,
  79693. configurable: true
  79694. });
  79695. MorphTargetManager.prototype.getActiveTarget = function (index) {
  79696. return this._activeTargets.data[index];
  79697. };
  79698. MorphTargetManager.prototype.getTarget = function (index) {
  79699. return this._targets[index];
  79700. };
  79701. MorphTargetManager.prototype.addTarget = function (target) {
  79702. var _this = this;
  79703. this._targets.push(target);
  79704. this._targetObservable.push(target.onInfluenceChanged.add(function (needUpdate) {
  79705. _this._syncActiveTargets(needUpdate);
  79706. }));
  79707. this._syncActiveTargets(true);
  79708. };
  79709. MorphTargetManager.prototype.removeTarget = function (target) {
  79710. var index = this._targets.indexOf(target);
  79711. if (index >= 0) {
  79712. this._targets.splice(index, 1);
  79713. target.onInfluenceChanged.remove(this._targetObservable.splice(index, 1)[0]);
  79714. this._syncActiveTargets(true);
  79715. }
  79716. };
  79717. /**
  79718. * Serializes the current manager into a Serialization object.
  79719. * Returns the serialized object.
  79720. */
  79721. MorphTargetManager.prototype.serialize = function () {
  79722. var serializationObject = {};
  79723. serializationObject.id = this.uniqueId;
  79724. serializationObject.targets = [];
  79725. for (var _i = 0, _a = this._targets; _i < _a.length; _i++) {
  79726. var target = _a[_i];
  79727. serializationObject.targets.push(target.serialize());
  79728. }
  79729. return serializationObject;
  79730. };
  79731. MorphTargetManager.prototype._syncActiveTargets = function (needUpdate) {
  79732. var influenceCount = 0;
  79733. this._activeTargets.reset();
  79734. this._supportsNormals = true;
  79735. this._supportsTangents = true;
  79736. this._vertexCount = 0;
  79737. for (var _i = 0, _a = this._targets; _i < _a.length; _i++) {
  79738. var target = _a[_i];
  79739. this._activeTargets.push(target);
  79740. this._tempInfluences[influenceCount++] = target.influence;
  79741. var positions = target.getPositions();
  79742. if (positions) {
  79743. this._supportsNormals = this._supportsNormals && target.hasNormals;
  79744. this._supportsTangents = this._supportsTangents && target.hasTangents;
  79745. var vertexCount = positions.length / 3;
  79746. if (this._vertexCount === 0) {
  79747. this._vertexCount = vertexCount;
  79748. }
  79749. else if (this._vertexCount !== vertexCount) {
  79750. BABYLON.Tools.Error("Incompatible target. Targets must all have the same vertices count.");
  79751. return;
  79752. }
  79753. }
  79754. }
  79755. if (!this._influences || this._influences.length !== influenceCount) {
  79756. this._influences = new Float32Array(influenceCount);
  79757. }
  79758. for (var index = 0; index < influenceCount; index++) {
  79759. this._influences[index] = this._tempInfluences[index];
  79760. }
  79761. if (needUpdate && this._scene) {
  79762. // Flag meshes as dirty to resync with the active targets
  79763. for (var _b = 0, _c = this._scene.meshes; _b < _c.length; _b++) {
  79764. var mesh = _c[_b];
  79765. if (mesh.morphTargetManager === this) {
  79766. mesh._syncGeometryWithMorphTargetManager();
  79767. }
  79768. }
  79769. }
  79770. };
  79771. // Statics
  79772. MorphTargetManager.Parse = function (serializationObject, scene) {
  79773. var result = new MorphTargetManager(scene);
  79774. result._uniqueId = serializationObject.id;
  79775. for (var _i = 0, _a = serializationObject.targets; _i < _a.length; _i++) {
  79776. var targetData = _a[_i];
  79777. result.addTarget(BABYLON.MorphTarget.Parse(targetData));
  79778. }
  79779. return result;
  79780. };
  79781. return MorphTargetManager;
  79782. }());
  79783. BABYLON.MorphTargetManager = MorphTargetManager;
  79784. })(BABYLON || (BABYLON = {}));
  79785. //# sourceMappingURL=babylon.morphTargetManager.js.map
  79786. var BABYLON;
  79787. (function (BABYLON) {
  79788. var Octree = /** @class */ (function () {
  79789. function Octree(creationFunc, maxBlockCapacity, maxDepth) {
  79790. if (maxDepth === void 0) { maxDepth = 2; }
  79791. this.maxDepth = maxDepth;
  79792. this.dynamicContent = new Array();
  79793. this._maxBlockCapacity = maxBlockCapacity || 64;
  79794. this._selectionContent = new BABYLON.SmartArrayNoDuplicate(1024);
  79795. this._creationFunc = creationFunc;
  79796. }
  79797. // Methods
  79798. Octree.prototype.update = function (worldMin, worldMax, entries) {
  79799. Octree._CreateBlocks(worldMin, worldMax, entries, this._maxBlockCapacity, 0, this.maxDepth, this, this._creationFunc);
  79800. };
  79801. Octree.prototype.addMesh = function (entry) {
  79802. for (var index = 0; index < this.blocks.length; index++) {
  79803. var block = this.blocks[index];
  79804. block.addEntry(entry);
  79805. }
  79806. };
  79807. Octree.prototype.select = function (frustumPlanes, allowDuplicate) {
  79808. this._selectionContent.reset();
  79809. for (var index = 0; index < this.blocks.length; index++) {
  79810. var block = this.blocks[index];
  79811. block.select(frustumPlanes, this._selectionContent, allowDuplicate);
  79812. }
  79813. if (allowDuplicate) {
  79814. this._selectionContent.concat(this.dynamicContent);
  79815. }
  79816. else {
  79817. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  79818. }
  79819. return this._selectionContent;
  79820. };
  79821. Octree.prototype.intersects = function (sphereCenter, sphereRadius, allowDuplicate) {
  79822. this._selectionContent.reset();
  79823. for (var index = 0; index < this.blocks.length; index++) {
  79824. var block = this.blocks[index];
  79825. block.intersects(sphereCenter, sphereRadius, this._selectionContent, allowDuplicate);
  79826. }
  79827. if (allowDuplicate) {
  79828. this._selectionContent.concat(this.dynamicContent);
  79829. }
  79830. else {
  79831. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  79832. }
  79833. return this._selectionContent;
  79834. };
  79835. Octree.prototype.intersectsRay = function (ray) {
  79836. this._selectionContent.reset();
  79837. for (var index = 0; index < this.blocks.length; index++) {
  79838. var block = this.blocks[index];
  79839. block.intersectsRay(ray, this._selectionContent);
  79840. }
  79841. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  79842. return this._selectionContent;
  79843. };
  79844. Octree._CreateBlocks = function (worldMin, worldMax, entries, maxBlockCapacity, currentDepth, maxDepth, target, creationFunc) {
  79845. target.blocks = new Array();
  79846. var blockSize = new BABYLON.Vector3((worldMax.x - worldMin.x) / 2, (worldMax.y - worldMin.y) / 2, (worldMax.z - worldMin.z) / 2);
  79847. // Segmenting space
  79848. for (var x = 0; x < 2; x++) {
  79849. for (var y = 0; y < 2; y++) {
  79850. for (var z = 0; z < 2; z++) {
  79851. var localMin = worldMin.add(blockSize.multiplyByFloats(x, y, z));
  79852. var localMax = worldMin.add(blockSize.multiplyByFloats(x + 1, y + 1, z + 1));
  79853. var block = new BABYLON.OctreeBlock(localMin, localMax, maxBlockCapacity, currentDepth + 1, maxDepth, creationFunc);
  79854. block.addEntries(entries);
  79855. target.blocks.push(block);
  79856. }
  79857. }
  79858. }
  79859. };
  79860. Octree.CreationFuncForMeshes = function (entry, block) {
  79861. var boundingInfo = entry.getBoundingInfo();
  79862. if (!entry.isBlocked && boundingInfo.boundingBox.intersectsMinMax(block.minPoint, block.maxPoint)) {
  79863. block.entries.push(entry);
  79864. }
  79865. };
  79866. Octree.CreationFuncForSubMeshes = function (entry, block) {
  79867. var boundingInfo = entry.getBoundingInfo();
  79868. if (boundingInfo.boundingBox.intersectsMinMax(block.minPoint, block.maxPoint)) {
  79869. block.entries.push(entry);
  79870. }
  79871. };
  79872. return Octree;
  79873. }());
  79874. BABYLON.Octree = Octree;
  79875. })(BABYLON || (BABYLON = {}));
  79876. //# sourceMappingURL=babylon.octree.js.map
  79877. var BABYLON;
  79878. (function (BABYLON) {
  79879. var OctreeBlock = /** @class */ (function () {
  79880. function OctreeBlock(minPoint, maxPoint, capacity, depth, maxDepth, creationFunc) {
  79881. this.entries = new Array();
  79882. this._boundingVectors = new Array();
  79883. this._capacity = capacity;
  79884. this._depth = depth;
  79885. this._maxDepth = maxDepth;
  79886. this._creationFunc = creationFunc;
  79887. this._minPoint = minPoint;
  79888. this._maxPoint = maxPoint;
  79889. this._boundingVectors.push(minPoint.clone());
  79890. this._boundingVectors.push(maxPoint.clone());
  79891. this._boundingVectors.push(minPoint.clone());
  79892. this._boundingVectors[2].x = maxPoint.x;
  79893. this._boundingVectors.push(minPoint.clone());
  79894. this._boundingVectors[3].y = maxPoint.y;
  79895. this._boundingVectors.push(minPoint.clone());
  79896. this._boundingVectors[4].z = maxPoint.z;
  79897. this._boundingVectors.push(maxPoint.clone());
  79898. this._boundingVectors[5].z = minPoint.z;
  79899. this._boundingVectors.push(maxPoint.clone());
  79900. this._boundingVectors[6].x = minPoint.x;
  79901. this._boundingVectors.push(maxPoint.clone());
  79902. this._boundingVectors[7].y = minPoint.y;
  79903. }
  79904. Object.defineProperty(OctreeBlock.prototype, "capacity", {
  79905. // Property
  79906. get: function () {
  79907. return this._capacity;
  79908. },
  79909. enumerable: true,
  79910. configurable: true
  79911. });
  79912. Object.defineProperty(OctreeBlock.prototype, "minPoint", {
  79913. get: function () {
  79914. return this._minPoint;
  79915. },
  79916. enumerable: true,
  79917. configurable: true
  79918. });
  79919. Object.defineProperty(OctreeBlock.prototype, "maxPoint", {
  79920. get: function () {
  79921. return this._maxPoint;
  79922. },
  79923. enumerable: true,
  79924. configurable: true
  79925. });
  79926. // Methods
  79927. OctreeBlock.prototype.addEntry = function (entry) {
  79928. if (this.blocks) {
  79929. for (var index = 0; index < this.blocks.length; index++) {
  79930. var block = this.blocks[index];
  79931. block.addEntry(entry);
  79932. }
  79933. return;
  79934. }
  79935. this._creationFunc(entry, this);
  79936. if (this.entries.length > this.capacity && this._depth < this._maxDepth) {
  79937. this.createInnerBlocks();
  79938. }
  79939. };
  79940. OctreeBlock.prototype.addEntries = function (entries) {
  79941. for (var index = 0; index < entries.length; index++) {
  79942. var mesh = entries[index];
  79943. this.addEntry(mesh);
  79944. }
  79945. };
  79946. OctreeBlock.prototype.select = function (frustumPlanes, selection, allowDuplicate) {
  79947. if (BABYLON.BoundingBox.IsInFrustum(this._boundingVectors, frustumPlanes)) {
  79948. if (this.blocks) {
  79949. for (var index = 0; index < this.blocks.length; index++) {
  79950. var block = this.blocks[index];
  79951. block.select(frustumPlanes, selection, allowDuplicate);
  79952. }
  79953. return;
  79954. }
  79955. if (allowDuplicate) {
  79956. selection.concat(this.entries);
  79957. }
  79958. else {
  79959. selection.concatWithNoDuplicate(this.entries);
  79960. }
  79961. }
  79962. };
  79963. OctreeBlock.prototype.intersects = function (sphereCenter, sphereRadius, selection, allowDuplicate) {
  79964. if (BABYLON.BoundingBox.IntersectsSphere(this._minPoint, this._maxPoint, sphereCenter, sphereRadius)) {
  79965. if (this.blocks) {
  79966. for (var index = 0; index < this.blocks.length; index++) {
  79967. var block = this.blocks[index];
  79968. block.intersects(sphereCenter, sphereRadius, selection, allowDuplicate);
  79969. }
  79970. return;
  79971. }
  79972. if (allowDuplicate) {
  79973. selection.concat(this.entries);
  79974. }
  79975. else {
  79976. selection.concatWithNoDuplicate(this.entries);
  79977. }
  79978. }
  79979. };
  79980. OctreeBlock.prototype.intersectsRay = function (ray, selection) {
  79981. if (ray.intersectsBoxMinMax(this._minPoint, this._maxPoint)) {
  79982. if (this.blocks) {
  79983. for (var index = 0; index < this.blocks.length; index++) {
  79984. var block = this.blocks[index];
  79985. block.intersectsRay(ray, selection);
  79986. }
  79987. return;
  79988. }
  79989. selection.concatWithNoDuplicate(this.entries);
  79990. }
  79991. };
  79992. OctreeBlock.prototype.createInnerBlocks = function () {
  79993. BABYLON.Octree._CreateBlocks(this._minPoint, this._maxPoint, this.entries, this._capacity, this._depth, this._maxDepth, this, this._creationFunc);
  79994. };
  79995. return OctreeBlock;
  79996. }());
  79997. BABYLON.OctreeBlock = OctreeBlock;
  79998. })(BABYLON || (BABYLON = {}));
  79999. //# sourceMappingURL=babylon.octreeBlock.js.map
  80000. var BABYLON;
  80001. (function (BABYLON) {
  80002. var VRDistortionCorrectionPostProcess = /** @class */ (function (_super) {
  80003. __extends(VRDistortionCorrectionPostProcess, _super);
  80004. function VRDistortionCorrectionPostProcess(name, camera, isRightEye, vrMetrics) {
  80005. var _this = _super.call(this, name, "vrDistortionCorrection", [
  80006. 'LensCenter',
  80007. 'Scale',
  80008. 'ScaleIn',
  80009. 'HmdWarpParam'
  80010. ], null, vrMetrics.postProcessScaleFactor, camera, BABYLON.Texture.BILINEAR_SAMPLINGMODE) || this;
  80011. _this._isRightEye = isRightEye;
  80012. _this._distortionFactors = vrMetrics.distortionK;
  80013. _this._postProcessScaleFactor = vrMetrics.postProcessScaleFactor;
  80014. _this._lensCenterOffset = vrMetrics.lensCenterOffset;
  80015. _this.adaptScaleToCurrentViewport = true;
  80016. _this.onSizeChangedObservable.add(function () {
  80017. _this.aspectRatio = _this.width * .5 / _this.height;
  80018. _this._scaleIn = new BABYLON.Vector2(2, 2 / _this.aspectRatio);
  80019. _this._scaleFactor = new BABYLON.Vector2(.5 * (1 / _this._postProcessScaleFactor), .5 * (1 / _this._postProcessScaleFactor) * _this.aspectRatio);
  80020. _this._lensCenter = new BABYLON.Vector2(_this._isRightEye ? 0.5 - _this._lensCenterOffset * 0.5 : 0.5 + _this._lensCenterOffset * 0.5, 0.5);
  80021. });
  80022. _this.onApplyObservable.add(function (effect) {
  80023. effect.setFloat2("LensCenter", _this._lensCenter.x, _this._lensCenter.y);
  80024. effect.setFloat2("Scale", _this._scaleFactor.x, _this._scaleFactor.y);
  80025. effect.setFloat2("ScaleIn", _this._scaleIn.x, _this._scaleIn.y);
  80026. effect.setFloat4("HmdWarpParam", _this._distortionFactors[0], _this._distortionFactors[1], _this._distortionFactors[2], _this._distortionFactors[3]);
  80027. });
  80028. return _this;
  80029. }
  80030. return VRDistortionCorrectionPostProcess;
  80031. }(BABYLON.PostProcess));
  80032. BABYLON.VRDistortionCorrectionPostProcess = VRDistortionCorrectionPostProcess;
  80033. })(BABYLON || (BABYLON = {}));
  80034. //# sourceMappingURL=babylon.vrDistortionCorrectionPostProcess.js.map
  80035. var BABYLON;
  80036. (function (BABYLON) {
  80037. var AnaglyphPostProcess = /** @class */ (function (_super) {
  80038. __extends(AnaglyphPostProcess, _super);
  80039. function AnaglyphPostProcess(name, options, rigCameras, samplingMode, engine, reusable) {
  80040. var _this = _super.call(this, name, "anaglyph", null, ["leftSampler"], options, rigCameras[1], samplingMode, engine, reusable) || this;
  80041. _this._passedProcess = rigCameras[0]._rigPostProcess;
  80042. _this.onApplyObservable.add(function (effect) {
  80043. effect.setTextureFromPostProcess("leftSampler", _this._passedProcess);
  80044. });
  80045. return _this;
  80046. }
  80047. return AnaglyphPostProcess;
  80048. }(BABYLON.PostProcess));
  80049. BABYLON.AnaglyphPostProcess = AnaglyphPostProcess;
  80050. })(BABYLON || (BABYLON = {}));
  80051. //# sourceMappingURL=babylon.anaglyphPostProcess.js.map
  80052. var BABYLON;
  80053. (function (BABYLON) {
  80054. var StereoscopicInterlacePostProcess = /** @class */ (function (_super) {
  80055. __extends(StereoscopicInterlacePostProcess, _super);
  80056. function StereoscopicInterlacePostProcess(name, rigCameras, isStereoscopicHoriz, samplingMode, engine, reusable) {
  80057. var _this = _super.call(this, name, "stereoscopicInterlace", ['stepSize'], ['camASampler'], 1, rigCameras[1], samplingMode, engine, reusable, isStereoscopicHoriz ? "#define IS_STEREOSCOPIC_HORIZ 1" : undefined) || this;
  80058. _this._passedProcess = rigCameras[0]._rigPostProcess;
  80059. _this._stepSize = new BABYLON.Vector2(1 / _this.width, 1 / _this.height);
  80060. _this.onSizeChangedObservable.add(function () {
  80061. _this._stepSize = new BABYLON.Vector2(1 / _this.width, 1 / _this.height);
  80062. });
  80063. _this.onApplyObservable.add(function (effect) {
  80064. effect.setTextureFromPostProcess("camASampler", _this._passedProcess);
  80065. effect.setFloat2("stepSize", _this._stepSize.x, _this._stepSize.y);
  80066. });
  80067. return _this;
  80068. }
  80069. return StereoscopicInterlacePostProcess;
  80070. }(BABYLON.PostProcess));
  80071. BABYLON.StereoscopicInterlacePostProcess = StereoscopicInterlacePostProcess;
  80072. })(BABYLON || (BABYLON = {}));
  80073. //# sourceMappingURL=babylon.stereoscopicInterlacePostProcess.js.map
  80074. var BABYLON;
  80075. (function (BABYLON) {
  80076. /**
  80077. * Takes information about the orientation of the device as reported by the deviceorientation event to orient the camera.
  80078. * Screen rotation is taken into account.
  80079. */
  80080. var FreeCameraDeviceOrientationInput = /** @class */ (function () {
  80081. function FreeCameraDeviceOrientationInput() {
  80082. var _this = this;
  80083. this._screenOrientationAngle = 0;
  80084. this._screenQuaternion = new BABYLON.Quaternion();
  80085. this._alpha = 0;
  80086. this._beta = 0;
  80087. this._gamma = 0;
  80088. this._orientationChanged = function () {
  80089. _this._screenOrientationAngle = (window.orientation !== undefined ? +window.orientation : (window.screen.orientation && window.screen.orientation['angle'] ? window.screen.orientation.angle : 0));
  80090. _this._screenOrientationAngle = -BABYLON.Tools.ToRadians(_this._screenOrientationAngle / 2);
  80091. _this._screenQuaternion.copyFromFloats(0, Math.sin(_this._screenOrientationAngle), 0, Math.cos(_this._screenOrientationAngle));
  80092. };
  80093. this._deviceOrientation = function (evt) {
  80094. _this._alpha = evt.alpha !== null ? evt.alpha : 0;
  80095. _this._beta = evt.beta !== null ? evt.beta : 0;
  80096. _this._gamma = evt.gamma !== null ? evt.gamma : 0;
  80097. };
  80098. this._constantTranform = new BABYLON.Quaternion(-Math.sqrt(0.5), 0, 0, Math.sqrt(0.5));
  80099. this._orientationChanged();
  80100. }
  80101. Object.defineProperty(FreeCameraDeviceOrientationInput.prototype, "camera", {
  80102. get: function () {
  80103. return this._camera;
  80104. },
  80105. set: function (camera) {
  80106. this._camera = camera;
  80107. if (this._camera != null && !this._camera.rotationQuaternion) {
  80108. this._camera.rotationQuaternion = new BABYLON.Quaternion();
  80109. }
  80110. },
  80111. enumerable: true,
  80112. configurable: true
  80113. });
  80114. FreeCameraDeviceOrientationInput.prototype.attachControl = function (element, noPreventDefault) {
  80115. window.addEventListener("orientationchange", this._orientationChanged);
  80116. window.addEventListener("deviceorientation", this._deviceOrientation);
  80117. //In certain cases, the attach control is called AFTER orientation was changed,
  80118. //So this is needed.
  80119. this._orientationChanged();
  80120. };
  80121. FreeCameraDeviceOrientationInput.prototype.detachControl = function (element) {
  80122. window.removeEventListener("orientationchange", this._orientationChanged);
  80123. window.removeEventListener("deviceorientation", this._deviceOrientation);
  80124. };
  80125. FreeCameraDeviceOrientationInput.prototype.checkInputs = function () {
  80126. //if no device orientation provided, don't update the rotation.
  80127. //Only testing against alpha under the assumption thatnorientation will never be so exact when set.
  80128. if (!this._alpha)
  80129. return;
  80130. BABYLON.Quaternion.RotationYawPitchRollToRef(BABYLON.Tools.ToRadians(this._alpha), BABYLON.Tools.ToRadians(this._beta), -BABYLON.Tools.ToRadians(this._gamma), this.camera.rotationQuaternion);
  80131. this._camera.rotationQuaternion.multiplyInPlace(this._screenQuaternion);
  80132. this._camera.rotationQuaternion.multiplyInPlace(this._constantTranform);
  80133. //Mirror on XY Plane
  80134. this._camera.rotationQuaternion.z *= -1;
  80135. this._camera.rotationQuaternion.w *= -1;
  80136. };
  80137. FreeCameraDeviceOrientationInput.prototype.getClassName = function () {
  80138. return "FreeCameraDeviceOrientationInput";
  80139. };
  80140. FreeCameraDeviceOrientationInput.prototype.getSimpleName = function () {
  80141. return "deviceOrientation";
  80142. };
  80143. return FreeCameraDeviceOrientationInput;
  80144. }());
  80145. BABYLON.FreeCameraDeviceOrientationInput = FreeCameraDeviceOrientationInput;
  80146. BABYLON.CameraInputTypes["FreeCameraDeviceOrientationInput"] = FreeCameraDeviceOrientationInput;
  80147. })(BABYLON || (BABYLON = {}));
  80148. //# sourceMappingURL=babylon.freeCameraDeviceOrientationInput.js.map
  80149. var BABYLON;
  80150. (function (BABYLON) {
  80151. var ArcRotateCameraVRDeviceOrientationInput = /** @class */ (function () {
  80152. function ArcRotateCameraVRDeviceOrientationInput() {
  80153. this.alphaCorrection = 1;
  80154. this.betaCorrection = 1;
  80155. this.gammaCorrection = 1;
  80156. this._alpha = 0;
  80157. this._gamma = 0;
  80158. this._dirty = false;
  80159. this._deviceOrientationHandler = this._onOrientationEvent.bind(this);
  80160. }
  80161. ArcRotateCameraVRDeviceOrientationInput.prototype.attachControl = function (element, noPreventDefault) {
  80162. this.camera.attachControl(element, noPreventDefault);
  80163. window.addEventListener("deviceorientation", this._deviceOrientationHandler);
  80164. };
  80165. ArcRotateCameraVRDeviceOrientationInput.prototype._onOrientationEvent = function (evt) {
  80166. if (evt.alpha !== null) {
  80167. this._alpha = +evt.alpha | 0;
  80168. }
  80169. if (evt.gamma !== null) {
  80170. this._gamma = +evt.gamma | 0;
  80171. }
  80172. this._dirty = true;
  80173. };
  80174. ArcRotateCameraVRDeviceOrientationInput.prototype.checkInputs = function () {
  80175. if (this._dirty) {
  80176. this._dirty = false;
  80177. if (this._gamma < 0) {
  80178. this._gamma = 180 + this._gamma;
  80179. }
  80180. this.camera.alpha = (-this._alpha / 180.0 * Math.PI) % Math.PI * 2;
  80181. this.camera.beta = (this._gamma / 180.0 * Math.PI);
  80182. }
  80183. };
  80184. ArcRotateCameraVRDeviceOrientationInput.prototype.detachControl = function (element) {
  80185. window.removeEventListener("deviceorientation", this._deviceOrientationHandler);
  80186. };
  80187. ArcRotateCameraVRDeviceOrientationInput.prototype.getClassName = function () {
  80188. return "ArcRotateCameraVRDeviceOrientationInput";
  80189. };
  80190. ArcRotateCameraVRDeviceOrientationInput.prototype.getSimpleName = function () {
  80191. return "VRDeviceOrientation";
  80192. };
  80193. return ArcRotateCameraVRDeviceOrientationInput;
  80194. }());
  80195. BABYLON.ArcRotateCameraVRDeviceOrientationInput = ArcRotateCameraVRDeviceOrientationInput;
  80196. BABYLON.CameraInputTypes["ArcRotateCameraVRDeviceOrientationInput"] = ArcRotateCameraVRDeviceOrientationInput;
  80197. })(BABYLON || (BABYLON = {}));
  80198. //# sourceMappingURL=babylon.arcRotateCameraVRDeviceOrientationInput.js.map
  80199. var BABYLON;
  80200. (function (BABYLON) {
  80201. var VRCameraMetrics = /** @class */ (function () {
  80202. function VRCameraMetrics() {
  80203. this.compensateDistortion = true;
  80204. }
  80205. Object.defineProperty(VRCameraMetrics.prototype, "aspectRatio", {
  80206. get: function () {
  80207. return this.hResolution / (2 * this.vResolution);
  80208. },
  80209. enumerable: true,
  80210. configurable: true
  80211. });
  80212. Object.defineProperty(VRCameraMetrics.prototype, "aspectRatioFov", {
  80213. get: function () {
  80214. return (2 * Math.atan((this.postProcessScaleFactor * this.vScreenSize) / (2 * this.eyeToScreenDistance)));
  80215. },
  80216. enumerable: true,
  80217. configurable: true
  80218. });
  80219. Object.defineProperty(VRCameraMetrics.prototype, "leftHMatrix", {
  80220. get: function () {
  80221. var meters = (this.hScreenSize / 4) - (this.lensSeparationDistance / 2);
  80222. var h = (4 * meters) / this.hScreenSize;
  80223. return BABYLON.Matrix.Translation(h, 0, 0);
  80224. },
  80225. enumerable: true,
  80226. configurable: true
  80227. });
  80228. Object.defineProperty(VRCameraMetrics.prototype, "rightHMatrix", {
  80229. get: function () {
  80230. var meters = (this.hScreenSize / 4) - (this.lensSeparationDistance / 2);
  80231. var h = (4 * meters) / this.hScreenSize;
  80232. return BABYLON.Matrix.Translation(-h, 0, 0);
  80233. },
  80234. enumerable: true,
  80235. configurable: true
  80236. });
  80237. Object.defineProperty(VRCameraMetrics.prototype, "leftPreViewMatrix", {
  80238. get: function () {
  80239. return BABYLON.Matrix.Translation(0.5 * this.interpupillaryDistance, 0, 0);
  80240. },
  80241. enumerable: true,
  80242. configurable: true
  80243. });
  80244. Object.defineProperty(VRCameraMetrics.prototype, "rightPreViewMatrix", {
  80245. get: function () {
  80246. return BABYLON.Matrix.Translation(-0.5 * this.interpupillaryDistance, 0, 0);
  80247. },
  80248. enumerable: true,
  80249. configurable: true
  80250. });
  80251. VRCameraMetrics.GetDefault = function () {
  80252. var result = new VRCameraMetrics();
  80253. result.hResolution = 1280;
  80254. result.vResolution = 800;
  80255. result.hScreenSize = 0.149759993;
  80256. result.vScreenSize = 0.0935999975;
  80257. result.vScreenCenter = 0.0467999987;
  80258. result.eyeToScreenDistance = 0.0410000011;
  80259. result.lensSeparationDistance = 0.0635000020;
  80260. result.interpupillaryDistance = 0.0640000030;
  80261. result.distortionK = [1.0, 0.219999999, 0.239999995, 0.0];
  80262. result.chromaAbCorrection = [0.995999992, -0.00400000019, 1.01400006, 0.0];
  80263. result.postProcessScaleFactor = 1.714605507808412;
  80264. result.lensCenterOffset = 0.151976421;
  80265. return result;
  80266. };
  80267. return VRCameraMetrics;
  80268. }());
  80269. BABYLON.VRCameraMetrics = VRCameraMetrics;
  80270. })(BABYLON || (BABYLON = {}));
  80271. //# sourceMappingURL=babylon.vrCameraMetrics.js.map
  80272. var BABYLON;
  80273. (function (BABYLON) {
  80274. /**
  80275. * This represents a WebVR camera.
  80276. * The WebVR camera is Babylon's simple interface to interaction with Windows Mixed Reality, HTC Vive and Oculus Rift.
  80277. * @example http://doc.babylonjs.com/how_to/webvr_camera
  80278. */
  80279. var WebVRFreeCamera = /** @class */ (function (_super) {
  80280. __extends(WebVRFreeCamera, _super);
  80281. /**
  80282. * Instantiates a WebVRFreeCamera.
  80283. * @param name The name of the WebVRFreeCamera
  80284. * @param position The starting anchor position for the camera
  80285. * @param scene The scene the camera belongs to
  80286. * @param webVROptions a set of customizable options for the webVRCamera
  80287. */
  80288. function WebVRFreeCamera(name, position, scene, webVROptions) {
  80289. if (webVROptions === void 0) { webVROptions = {}; }
  80290. var _this = _super.call(this, name, position, scene) || this;
  80291. _this.webVROptions = webVROptions;
  80292. /**
  80293. * The vrDisplay tied to the camera. See https://developer.mozilla.org/en-US/docs/Web/API/VRDisplay
  80294. */
  80295. _this._vrDevice = null;
  80296. /**
  80297. * The rawPose of the vrDevice.
  80298. */
  80299. _this.rawPose = null;
  80300. _this._specsVersion = "1.1";
  80301. _this._attached = false;
  80302. _this._descendants = [];
  80303. // Represents device position and rotation in room space. Should only be used to help calculate babylon space values
  80304. _this._deviceRoomPosition = BABYLON.Vector3.Zero();
  80305. _this._deviceRoomRotationQuaternion = BABYLON.Quaternion.Identity();
  80306. _this._standingMatrix = null;
  80307. /**
  80308. * Represents device position in babylon space.
  80309. */
  80310. _this.devicePosition = BABYLON.Vector3.Zero();
  80311. /**
  80312. * Represents device rotation in babylon space.
  80313. */
  80314. _this.deviceRotationQuaternion = BABYLON.Quaternion.Identity();
  80315. /**
  80316. * The scale of the device to be used when translating from device space to babylon space.
  80317. */
  80318. _this.deviceScaleFactor = 1;
  80319. _this._deviceToWorld = BABYLON.Matrix.Identity();
  80320. _this._worldToDevice = BABYLON.Matrix.Identity();
  80321. /**
  80322. * References to the webVR controllers for the vrDevice.
  80323. */
  80324. _this.controllers = [];
  80325. /**
  80326. * Emits an event when a controller is attached.
  80327. */
  80328. _this.onControllersAttachedObservable = new BABYLON.Observable();
  80329. /**
  80330. * Emits an event when a controller's mesh has been loaded;
  80331. */
  80332. _this.onControllerMeshLoadedObservable = new BABYLON.Observable();
  80333. /**
  80334. * If the rig cameras be used as parent instead of this camera.
  80335. */
  80336. _this.rigParenting = true;
  80337. _this._defaultHeight = undefined;
  80338. _this._workingVector = BABYLON.Vector3.Zero();
  80339. _this._oneVector = BABYLON.Vector3.One();
  80340. _this._workingMatrix = BABYLON.Matrix.Identity();
  80341. _this._cache.position = BABYLON.Vector3.Zero();
  80342. if (webVROptions.defaultHeight) {
  80343. _this._defaultHeight = webVROptions.defaultHeight;
  80344. _this.position.y = _this._defaultHeight;
  80345. }
  80346. _this.minZ = 0.1;
  80347. //legacy support - the compensation boolean was removed.
  80348. if (arguments.length === 5) {
  80349. _this.webVROptions = arguments[4];
  80350. }
  80351. // default webVR options
  80352. if (_this.webVROptions.trackPosition == undefined) {
  80353. _this.webVROptions.trackPosition = true;
  80354. }
  80355. if (_this.webVROptions.controllerMeshes == undefined) {
  80356. _this.webVROptions.controllerMeshes = true;
  80357. }
  80358. if (_this.webVROptions.defaultLightingOnControllers == undefined) {
  80359. _this.webVROptions.defaultLightingOnControllers = true;
  80360. }
  80361. _this.rotationQuaternion = new BABYLON.Quaternion();
  80362. if (_this.webVROptions && _this.webVROptions.positionScale) {
  80363. _this.deviceScaleFactor = _this.webVROptions.positionScale;
  80364. }
  80365. //enable VR
  80366. var engine = _this.getEngine();
  80367. _this._onVREnabled = function (success) { if (success) {
  80368. _this.initControllers();
  80369. } };
  80370. engine.onVRRequestPresentComplete.add(_this._onVREnabled);
  80371. engine.initWebVR().add(function (event) {
  80372. if (!event.vrDisplay || _this._vrDevice === event.vrDisplay) {
  80373. return;
  80374. }
  80375. _this._vrDevice = event.vrDisplay;
  80376. //reset the rig parameters.
  80377. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_WEBVR, { parentCamera: _this, vrDisplay: _this._vrDevice, frameData: _this._frameData, specs: _this._specsVersion });
  80378. if (_this._attached) {
  80379. _this.getEngine().enableVR();
  80380. }
  80381. });
  80382. if (typeof (VRFrameData) !== "undefined")
  80383. _this._frameData = new VRFrameData();
  80384. /**
  80385. * The idea behind the following lines:
  80386. * objects that have the camera as parent should actually have the rig cameras as a parent.
  80387. * BUT, each of those cameras has a different view matrix, which means that if we set the parent to the first rig camera,
  80388. * the second will not show it correctly.
  80389. *
  80390. * To solve this - each object that has the camera as parent will be added to a protected array.
  80391. * When the rig camera renders, it will take this array and set all of those to be its children.
  80392. * This way, the right camera will be used as a parent, and the mesh will be rendered correctly.
  80393. * Amazing!
  80394. */
  80395. scene.onBeforeCameraRenderObservable.add(function (camera) {
  80396. if (camera.parent === _this && _this.rigParenting) {
  80397. _this._descendants = _this.getDescendants(true, function (n) {
  80398. // don't take the cameras or the controllers!
  80399. var isController = _this.controllers.some(function (controller) { return controller._mesh === n; });
  80400. var isRigCamera = _this._rigCameras.indexOf(n) !== -1;
  80401. return !isController && !isRigCamera;
  80402. });
  80403. _this._descendants.forEach(function (node) {
  80404. node.parent = camera;
  80405. });
  80406. }
  80407. });
  80408. scene.onAfterCameraRenderObservable.add(function (camera) {
  80409. if (camera.parent === _this && _this.rigParenting) {
  80410. _this._descendants.forEach(function (node) {
  80411. node.parent = _this;
  80412. });
  80413. }
  80414. });
  80415. return _this;
  80416. }
  80417. /**
  80418. * Gets the device distance from the ground in meters.
  80419. * @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.
  80420. */
  80421. WebVRFreeCamera.prototype.deviceDistanceToRoomGround = function () {
  80422. if (this._standingMatrix) {
  80423. // Add standing matrix offset to get real offset from ground in room
  80424. this._standingMatrix.getTranslationToRef(this._workingVector);
  80425. return this._deviceRoomPosition.y + this._workingVector.y;
  80426. }
  80427. //If VRDisplay does not inform stage parameters and no default height is set we fallback to zero.
  80428. return this._defaultHeight || 0;
  80429. };
  80430. /**
  80431. * Enables the standing matrix when supported. This can be used to position the user's view the correct height from the ground.
  80432. * @param callback will be called when the standing matrix is set. Callback parameter is if the standing matrix is supported.
  80433. */
  80434. WebVRFreeCamera.prototype.useStandingMatrix = function (callback) {
  80435. var _this = this;
  80436. if (callback === void 0) { callback = function (bool) { }; }
  80437. // Use standing matrix if available
  80438. this.getEngine().initWebVRAsync().then(function (result) {
  80439. if (!result.vrDisplay || !result.vrDisplay.stageParameters || !result.vrDisplay.stageParameters.sittingToStandingTransform) {
  80440. callback(false);
  80441. }
  80442. else {
  80443. _this._standingMatrix = new BABYLON.Matrix();
  80444. BABYLON.Matrix.FromFloat32ArrayToRefScaled(result.vrDisplay.stageParameters.sittingToStandingTransform, 0, 1, _this._standingMatrix);
  80445. if (!_this.getScene().useRightHandedSystem) {
  80446. [2, 6, 8, 9, 14].forEach(function (num) {
  80447. if (_this._standingMatrix) {
  80448. _this._standingMatrix.m[num] *= -1;
  80449. }
  80450. });
  80451. }
  80452. callback(true);
  80453. }
  80454. });
  80455. };
  80456. /**
  80457. * Enables the standing matrix when supported. This can be used to position the user's view the correct height from the ground.
  80458. * @returns A promise with a boolean set to if the standing matrix is supported.
  80459. */
  80460. WebVRFreeCamera.prototype.useStandingMatrixAsync = function () {
  80461. var _this = this;
  80462. return new Promise(function (res, rej) {
  80463. _this.useStandingMatrix(function (supported) {
  80464. res(supported);
  80465. });
  80466. });
  80467. };
  80468. /**
  80469. * Disposes the camera
  80470. */
  80471. WebVRFreeCamera.prototype.dispose = function () {
  80472. this.getEngine().onVRRequestPresentComplete.removeCallback(this._onVREnabled);
  80473. _super.prototype.dispose.call(this);
  80474. };
  80475. /**
  80476. * Gets a vrController by name.
  80477. * @param name The name of the controller to retreive
  80478. * @returns the controller matching the name specified or null if not found
  80479. */
  80480. WebVRFreeCamera.prototype.getControllerByName = function (name) {
  80481. for (var _i = 0, _a = this.controllers; _i < _a.length; _i++) {
  80482. var gp = _a[_i];
  80483. if (gp.hand === name) {
  80484. return gp;
  80485. }
  80486. }
  80487. return null;
  80488. };
  80489. Object.defineProperty(WebVRFreeCamera.prototype, "leftController", {
  80490. /**
  80491. * The controller corrisponding to the users left hand.
  80492. */
  80493. get: function () {
  80494. if (!this._leftController) {
  80495. this._leftController = this.getControllerByName("left");
  80496. }
  80497. return this._leftController;
  80498. },
  80499. enumerable: true,
  80500. configurable: true
  80501. });
  80502. ;
  80503. Object.defineProperty(WebVRFreeCamera.prototype, "rightController", {
  80504. /**
  80505. * The controller corrisponding to the users right hand.
  80506. */
  80507. get: function () {
  80508. if (!this._rightController) {
  80509. this._rightController = this.getControllerByName("right");
  80510. }
  80511. return this._rightController;
  80512. },
  80513. enumerable: true,
  80514. configurable: true
  80515. });
  80516. ;
  80517. /**
  80518. * Casts a ray forward from the vrCamera's gaze.
  80519. * @param length Length of the ray (default: 100)
  80520. * @returns the ray corrisponding to the gaze
  80521. */
  80522. WebVRFreeCamera.prototype.getForwardRay = function (length) {
  80523. if (length === void 0) { length = 100; }
  80524. if (this.leftCamera) {
  80525. // Use left eye to avoid computation to compute center on every call
  80526. return _super.prototype.getForwardRay.call(this, length, this.leftCamera.getWorldMatrix(), this.leftCamera.globalPosition); // Need the actual rendered camera
  80527. }
  80528. else {
  80529. return _super.prototype.getForwardRay.call(this, length);
  80530. }
  80531. };
  80532. /**
  80533. * Updates the camera based on device's frame data
  80534. */
  80535. WebVRFreeCamera.prototype._checkInputs = function () {
  80536. if (this._vrDevice && this._vrDevice.isPresenting) {
  80537. this._vrDevice.getFrameData(this._frameData);
  80538. this.updateFromDevice(this._frameData.pose);
  80539. }
  80540. _super.prototype._checkInputs.call(this);
  80541. };
  80542. /**
  80543. * Updates the poseControlled values based on the input device pose.
  80544. * @param poseData Pose coming from the device
  80545. */
  80546. WebVRFreeCamera.prototype.updateFromDevice = function (poseData) {
  80547. if (poseData && poseData.orientation) {
  80548. this.rawPose = poseData;
  80549. this._deviceRoomRotationQuaternion.copyFromFloats(poseData.orientation[0], poseData.orientation[1], -poseData.orientation[2], -poseData.orientation[3]);
  80550. if (this.getScene().useRightHandedSystem) {
  80551. this._deviceRoomRotationQuaternion.z *= -1;
  80552. this._deviceRoomRotationQuaternion.w *= -1;
  80553. }
  80554. if (this.webVROptions.trackPosition && this.rawPose.position) {
  80555. this._deviceRoomPosition.copyFromFloats(this.rawPose.position[0], this.rawPose.position[1], -this.rawPose.position[2]);
  80556. if (this.getScene().useRightHandedSystem) {
  80557. this._deviceRoomPosition.z *= -1;
  80558. }
  80559. }
  80560. }
  80561. };
  80562. /**
  80563. * WebVR's attach control will start broadcasting frames to the device.
  80564. * Note that in certain browsers (chrome for example) this function must be called
  80565. * within a user-interaction callback. Example:
  80566. * <pre> scene.onPointerDown = function() { camera.attachControl(canvas); }</pre>
  80567. *
  80568. * @param element html element to attach the vrDevice to
  80569. * @param noPreventDefault prevent the default html element operation when attaching the vrDevice
  80570. */
  80571. WebVRFreeCamera.prototype.attachControl = function (element, noPreventDefault) {
  80572. _super.prototype.attachControl.call(this, element, noPreventDefault);
  80573. this._attached = true;
  80574. noPreventDefault = BABYLON.Camera.ForceAttachControlToAlwaysPreventDefault ? false : noPreventDefault;
  80575. if (this._vrDevice) {
  80576. this.getEngine().enableVR();
  80577. }
  80578. };
  80579. /**
  80580. * Detaches the camera from the html element and disables VR
  80581. *
  80582. * @param element html element to detach from
  80583. */
  80584. WebVRFreeCamera.prototype.detachControl = function (element) {
  80585. this.getScene().gamepadManager.onGamepadConnectedObservable.remove(this._onGamepadConnectedObserver);
  80586. this.getScene().gamepadManager.onGamepadDisconnectedObservable.remove(this._onGamepadDisconnectedObserver);
  80587. _super.prototype.detachControl.call(this, element);
  80588. this._attached = false;
  80589. this.getEngine().disableVR();
  80590. };
  80591. /**
  80592. * @returns the name of this class
  80593. */
  80594. WebVRFreeCamera.prototype.getClassName = function () {
  80595. return "WebVRFreeCamera";
  80596. };
  80597. /**
  80598. * Calls resetPose on the vrDisplay
  80599. * See: https://developer.mozilla.org/en-US/docs/Web/API/VRDisplay/resetPose
  80600. */
  80601. WebVRFreeCamera.prototype.resetToCurrentRotation = function () {
  80602. //uses the vrDisplay's "resetPose()".
  80603. //pitch and roll won't be affected.
  80604. this._vrDevice.resetPose();
  80605. };
  80606. /**
  80607. * Updates the rig cameras (left and right eye)
  80608. */
  80609. WebVRFreeCamera.prototype._updateRigCameras = function () {
  80610. var camLeft = this._rigCameras[0];
  80611. var camRight = this._rigCameras[1];
  80612. camLeft.rotationQuaternion.copyFrom(this._deviceRoomRotationQuaternion);
  80613. camRight.rotationQuaternion.copyFrom(this._deviceRoomRotationQuaternion);
  80614. camLeft.position.copyFrom(this._deviceRoomPosition);
  80615. camRight.position.copyFrom(this._deviceRoomPosition);
  80616. };
  80617. /**
  80618. * Updates the cached values of the camera
  80619. * @param ignoreParentClass ignores updating the parent class's cache (default: false)
  80620. */
  80621. WebVRFreeCamera.prototype._updateCache = function (ignoreParentClass) {
  80622. var _this = this;
  80623. if (!this.rotationQuaternion.equals(this._cache.rotationQuaternion) || !this.position.equals(this._cache.position)) {
  80624. // Update to ensure devicePosition is up to date with most recent _deviceRoomPosition
  80625. if (!this.updateCacheCalled) {
  80626. // make sure it is only called once per loop. this.update() might cause an infinite loop.
  80627. this.updateCacheCalled = true;
  80628. this.update();
  80629. }
  80630. // Set working vector to the device position in room space rotated by the new rotation
  80631. this.rotationQuaternion.toRotationMatrix(this._workingMatrix);
  80632. BABYLON.Vector3.TransformCoordinatesToRef(this._deviceRoomPosition, this._workingMatrix, this._workingVector);
  80633. // Subtract this vector from the current device position in world to get the translation for the device world matrix
  80634. this.devicePosition.subtractToRef(this._workingVector, this._workingVector);
  80635. BABYLON.Matrix.ComposeToRef(this._oneVector, this.rotationQuaternion, this._workingVector, this._deviceToWorld);
  80636. // Add translation from anchor position
  80637. this._deviceToWorld.getTranslationToRef(this._workingVector);
  80638. this._workingVector.addInPlace(this.position);
  80639. this._workingVector.subtractInPlace(this._cache.position);
  80640. this._deviceToWorld.setTranslation(this._workingVector);
  80641. // Set an inverted matrix to be used when updating the camera
  80642. this._deviceToWorld.invertToRef(this._worldToDevice);
  80643. // Update the gamepad to ensure the mesh is updated on the same frame as camera
  80644. this.controllers.forEach(function (controller) {
  80645. controller._deviceToWorld.copyFrom(_this._deviceToWorld);
  80646. controller.update();
  80647. });
  80648. }
  80649. if (!ignoreParentClass) {
  80650. _super.prototype._updateCache.call(this);
  80651. }
  80652. this.updateCacheCalled = false;
  80653. };
  80654. /**
  80655. * Updates the current device position and rotation in the babylon world
  80656. */
  80657. WebVRFreeCamera.prototype.update = function () {
  80658. // Get current device position in babylon world
  80659. BABYLON.Vector3.TransformCoordinatesToRef(this._deviceRoomPosition, this._deviceToWorld, this.devicePosition);
  80660. // Get current device rotation in babylon world
  80661. BABYLON.Matrix.FromQuaternionToRef(this._deviceRoomRotationQuaternion, this._workingMatrix);
  80662. this._workingMatrix.multiplyToRef(this._deviceToWorld, this._workingMatrix);
  80663. BABYLON.Quaternion.FromRotationMatrixToRef(this._workingMatrix, this.deviceRotationQuaternion);
  80664. _super.prototype.update.call(this);
  80665. };
  80666. /**
  80667. * Gets the view matrix of this camera (Always set to identity as left and right eye cameras contain the actual view matrix)
  80668. * @returns an identity matrix
  80669. */
  80670. WebVRFreeCamera.prototype._getViewMatrix = function () {
  80671. return BABYLON.Matrix.Identity();
  80672. };
  80673. /**
  80674. * This function is called by the two RIG cameras.
  80675. * 'this' is the left or right camera (and NOT (!!!) the WebVRFreeCamera instance)
  80676. */
  80677. WebVRFreeCamera.prototype._getWebVRViewMatrix = function () {
  80678. var _this = this;
  80679. // Update the parent camera prior to using a child camera to avoid desynchronization
  80680. var parentCamera = this._cameraRigParams["parentCamera"];
  80681. parentCamera._updateCache();
  80682. //WebVR 1.1
  80683. var viewArray = this._cameraRigParams["left"] ? this._cameraRigParams["frameData"].leftViewMatrix : this._cameraRigParams["frameData"].rightViewMatrix;
  80684. BABYLON.Matrix.FromArrayToRef(viewArray, 0, this._webvrViewMatrix);
  80685. if (!this.getScene().useRightHandedSystem) {
  80686. [2, 6, 8, 9, 14].forEach(function (num) {
  80687. _this._webvrViewMatrix.m[num] *= -1;
  80688. });
  80689. }
  80690. // update the camera rotation matrix
  80691. this._webvrViewMatrix.getRotationMatrixToRef(this._cameraRotationMatrix);
  80692. BABYLON.Vector3.TransformCoordinatesToRef(this._referencePoint, this._cameraRotationMatrix, this._transformedReferencePoint);
  80693. // Computing target and final matrix
  80694. this.position.addToRef(this._transformedReferencePoint, this._currentTarget);
  80695. // should the view matrix be updated with scale and position offset?
  80696. if (parentCamera.deviceScaleFactor !== 1) {
  80697. this._webvrViewMatrix.invert();
  80698. // scale the position, if set
  80699. if (parentCamera.deviceScaleFactor) {
  80700. this._webvrViewMatrix.m[12] *= parentCamera.deviceScaleFactor;
  80701. this._webvrViewMatrix.m[13] *= parentCamera.deviceScaleFactor;
  80702. this._webvrViewMatrix.m[14] *= parentCamera.deviceScaleFactor;
  80703. }
  80704. this._webvrViewMatrix.invert();
  80705. }
  80706. parentCamera._worldToDevice.multiplyToRef(this._webvrViewMatrix, this._webvrViewMatrix);
  80707. return this._webvrViewMatrix;
  80708. };
  80709. WebVRFreeCamera.prototype._getWebVRProjectionMatrix = function () {
  80710. var _this = this;
  80711. var parentCamera = this.parent;
  80712. parentCamera._vrDevice.depthNear = parentCamera.minZ;
  80713. parentCamera._vrDevice.depthFar = parentCamera.maxZ;
  80714. var projectionArray = this._cameraRigParams["left"] ? this._cameraRigParams["frameData"].leftProjectionMatrix : this._cameraRigParams["frameData"].rightProjectionMatrix;
  80715. BABYLON.Matrix.FromArrayToRef(projectionArray, 0, this._projectionMatrix);
  80716. //babylon compatible matrix
  80717. if (!this.getScene().useRightHandedSystem) {
  80718. [8, 9, 10, 11].forEach(function (num) {
  80719. _this._projectionMatrix.m[num] *= -1;
  80720. });
  80721. }
  80722. return this._projectionMatrix;
  80723. };
  80724. /**
  80725. * Initializes the controllers and their meshes
  80726. */
  80727. WebVRFreeCamera.prototype.initControllers = function () {
  80728. var _this = this;
  80729. this.controllers = [];
  80730. var manager = this.getScene().gamepadManager;
  80731. this._onGamepadDisconnectedObserver = manager.onGamepadDisconnectedObservable.add(function (gamepad) {
  80732. if (gamepad.type === BABYLON.Gamepad.POSE_ENABLED) {
  80733. var webVrController = gamepad;
  80734. if (webVrController.defaultModel) {
  80735. webVrController.defaultModel.setEnabled(false);
  80736. }
  80737. if (webVrController.hand === "right") {
  80738. _this._rightController = null;
  80739. }
  80740. if (webVrController.hand === "left") {
  80741. _this._leftController = null;
  80742. }
  80743. var controllerIndex = _this.controllers.indexOf(webVrController);
  80744. if (controllerIndex !== -1) {
  80745. _this.controllers.splice(controllerIndex, 1);
  80746. }
  80747. }
  80748. });
  80749. this._onGamepadConnectedObserver = manager.onGamepadConnectedObservable.add(function (gamepad) {
  80750. if (gamepad.type === BABYLON.Gamepad.POSE_ENABLED) {
  80751. var webVrController_1 = gamepad;
  80752. webVrController_1.deviceScaleFactor = _this.deviceScaleFactor;
  80753. webVrController_1._deviceToWorld.copyFrom(_this._deviceToWorld);
  80754. if (_this.webVROptions.controllerMeshes) {
  80755. if (webVrController_1.defaultModel) {
  80756. webVrController_1.defaultModel.setEnabled(true);
  80757. }
  80758. else {
  80759. // Load the meshes
  80760. webVrController_1.initControllerMesh(_this.getScene(), function (loadedMesh) {
  80761. loadedMesh.scaling.scaleInPlace(_this.deviceScaleFactor);
  80762. _this.onControllerMeshLoadedObservable.notifyObservers(webVrController_1);
  80763. if (_this.webVROptions.defaultLightingOnControllers) {
  80764. if (!_this._lightOnControllers) {
  80765. _this._lightOnControllers = new BABYLON.HemisphericLight("vrControllersLight", new BABYLON.Vector3(0, 1, 0), _this.getScene());
  80766. }
  80767. var activateLightOnSubMeshes_1 = function (mesh, light) {
  80768. var children = mesh.getChildren();
  80769. if (children.length !== 0) {
  80770. children.forEach(function (mesh) {
  80771. light.includedOnlyMeshes.push(mesh);
  80772. activateLightOnSubMeshes_1(mesh, light);
  80773. });
  80774. }
  80775. };
  80776. _this._lightOnControllers.includedOnlyMeshes.push(loadedMesh);
  80777. activateLightOnSubMeshes_1(loadedMesh, _this._lightOnControllers);
  80778. }
  80779. });
  80780. }
  80781. }
  80782. webVrController_1.attachToPoseControlledCamera(_this);
  80783. // since this is async - sanity check. Is the controller already stored?
  80784. if (_this.controllers.indexOf(webVrController_1) === -1) {
  80785. //add to the controllers array
  80786. _this.controllers.push(webVrController_1);
  80787. // Forced to add some control code for Vive as it doesn't always fill properly the "hand" property
  80788. // Sometimes, both controllers are set correctly (left and right), sometimes none, sometimes only one of them...
  80789. // So we're overriding setting left & right manually to be sure
  80790. var firstViveWandDetected = false;
  80791. for (var i = 0; i < _this.controllers.length; i++) {
  80792. if (_this.controllers[i].controllerType === BABYLON.PoseEnabledControllerType.VIVE) {
  80793. if (!firstViveWandDetected) {
  80794. firstViveWandDetected = true;
  80795. _this.controllers[i].hand = "left";
  80796. }
  80797. else {
  80798. _this.controllers[i].hand = "right";
  80799. }
  80800. }
  80801. }
  80802. //did we find enough controllers? Great! let the developer know.
  80803. if (_this.controllers.length >= 2) {
  80804. _this.onControllersAttachedObservable.notifyObservers(_this.controllers);
  80805. }
  80806. }
  80807. }
  80808. });
  80809. };
  80810. return WebVRFreeCamera;
  80811. }(BABYLON.FreeCamera));
  80812. BABYLON.WebVRFreeCamera = WebVRFreeCamera;
  80813. })(BABYLON || (BABYLON = {}));
  80814. //# sourceMappingURL=babylon.webVRCamera.js.map
  80815. var BABYLON;
  80816. (function (BABYLON) {
  80817. // We're mainly based on the logic defined into the FreeCamera code
  80818. /**
  80819. * This is a camera specifically designed to react to device orientation events such as a modern mobile device
  80820. * being tilted forward or back and left or right.
  80821. */
  80822. var DeviceOrientationCamera = /** @class */ (function (_super) {
  80823. __extends(DeviceOrientationCamera, _super);
  80824. /**
  80825. * Creates a new device orientation camera. @see DeviceOrientationCamera
  80826. * @param name The name of the camera
  80827. * @param position The start position camera
  80828. * @param scene The scene the camera belongs to
  80829. */
  80830. function DeviceOrientationCamera(name, position, scene) {
  80831. var _this = _super.call(this, name, position, scene) || this;
  80832. _this._quaternionCache = new BABYLON.Quaternion();
  80833. _this.inputs.addDeviceOrientation();
  80834. return _this;
  80835. }
  80836. /**
  80837. * Gets the current instance class name ("DeviceOrientationCamera").
  80838. * This helps avoiding instanceof at run time.
  80839. * @returns the class name
  80840. */
  80841. DeviceOrientationCamera.prototype.getClassName = function () {
  80842. return "DeviceOrientationCamera";
  80843. };
  80844. /**
  80845. * Checks and applies the current values of the inputs to the camera. (Internal use only)
  80846. */
  80847. DeviceOrientationCamera.prototype._checkInputs = function () {
  80848. _super.prototype._checkInputs.call(this);
  80849. this._quaternionCache.copyFrom(this.rotationQuaternion);
  80850. if (this._initialQuaternion) {
  80851. this._initialQuaternion.multiplyToRef(this.rotationQuaternion, this.rotationQuaternion);
  80852. }
  80853. };
  80854. /**
  80855. * Reset the camera to its default orientation on the specified axis only.
  80856. * @param axis The axis to reset
  80857. */
  80858. DeviceOrientationCamera.prototype.resetToCurrentRotation = function (axis) {
  80859. var _this = this;
  80860. if (axis === void 0) { axis = BABYLON.Axis.Y; }
  80861. //can only work if this camera has a rotation quaternion already.
  80862. if (!this.rotationQuaternion)
  80863. return;
  80864. if (!this._initialQuaternion) {
  80865. this._initialQuaternion = new BABYLON.Quaternion();
  80866. }
  80867. this._initialQuaternion.copyFrom(this._quaternionCache || this.rotationQuaternion);
  80868. ['x', 'y', 'z'].forEach(function (axisName) {
  80869. if (!axis[axisName]) {
  80870. _this._initialQuaternion[axisName] = 0;
  80871. }
  80872. else {
  80873. _this._initialQuaternion[axisName] *= -1;
  80874. }
  80875. });
  80876. this._initialQuaternion.normalize();
  80877. //force rotation update
  80878. this._initialQuaternion.multiplyToRef(this.rotationQuaternion, this.rotationQuaternion);
  80879. };
  80880. return DeviceOrientationCamera;
  80881. }(BABYLON.FreeCamera));
  80882. BABYLON.DeviceOrientationCamera = DeviceOrientationCamera;
  80883. })(BABYLON || (BABYLON = {}));
  80884. //# sourceMappingURL=babylon.deviceOrientationCamera.js.map
  80885. var BABYLON;
  80886. (function (BABYLON) {
  80887. var VRDeviceOrientationFreeCamera = /** @class */ (function (_super) {
  80888. __extends(VRDeviceOrientationFreeCamera, _super);
  80889. function VRDeviceOrientationFreeCamera(name, position, scene, compensateDistortion, vrCameraMetrics) {
  80890. if (compensateDistortion === void 0) { compensateDistortion = true; }
  80891. if (vrCameraMetrics === void 0) { vrCameraMetrics = BABYLON.VRCameraMetrics.GetDefault(); }
  80892. var _this = _super.call(this, name, position, scene) || this;
  80893. vrCameraMetrics.compensateDistortion = compensateDistortion;
  80894. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_VR, { vrCameraMetrics: vrCameraMetrics });
  80895. return _this;
  80896. }
  80897. VRDeviceOrientationFreeCamera.prototype.getClassName = function () {
  80898. return "VRDeviceOrientationFreeCamera";
  80899. };
  80900. return VRDeviceOrientationFreeCamera;
  80901. }(BABYLON.DeviceOrientationCamera));
  80902. BABYLON.VRDeviceOrientationFreeCamera = VRDeviceOrientationFreeCamera;
  80903. var VRDeviceOrientationGamepadCamera = /** @class */ (function (_super) {
  80904. __extends(VRDeviceOrientationGamepadCamera, _super);
  80905. function VRDeviceOrientationGamepadCamera(name, position, scene, compensateDistortion, vrCameraMetrics) {
  80906. if (compensateDistortion === void 0) { compensateDistortion = true; }
  80907. if (vrCameraMetrics === void 0) { vrCameraMetrics = BABYLON.VRCameraMetrics.GetDefault(); }
  80908. var _this = _super.call(this, name, position, scene, compensateDistortion, vrCameraMetrics) || this;
  80909. _this.inputs.addGamepad();
  80910. return _this;
  80911. }
  80912. VRDeviceOrientationGamepadCamera.prototype.getClassName = function () {
  80913. return "VRDeviceOrientationGamepadCamera";
  80914. };
  80915. return VRDeviceOrientationGamepadCamera;
  80916. }(VRDeviceOrientationFreeCamera));
  80917. BABYLON.VRDeviceOrientationGamepadCamera = VRDeviceOrientationGamepadCamera;
  80918. var VRDeviceOrientationArcRotateCamera = /** @class */ (function (_super) {
  80919. __extends(VRDeviceOrientationArcRotateCamera, _super);
  80920. function VRDeviceOrientationArcRotateCamera(name, alpha, beta, radius, target, scene, compensateDistortion, vrCameraMetrics) {
  80921. if (compensateDistortion === void 0) { compensateDistortion = true; }
  80922. if (vrCameraMetrics === void 0) { vrCameraMetrics = BABYLON.VRCameraMetrics.GetDefault(); }
  80923. var _this = _super.call(this, name, alpha, beta, radius, target, scene) || this;
  80924. vrCameraMetrics.compensateDistortion = compensateDistortion;
  80925. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_VR, { vrCameraMetrics: vrCameraMetrics });
  80926. _this.inputs.addVRDeviceOrientation();
  80927. return _this;
  80928. }
  80929. VRDeviceOrientationArcRotateCamera.prototype.getClassName = function () {
  80930. return "VRDeviceOrientationArcRotateCamera";
  80931. };
  80932. return VRDeviceOrientationArcRotateCamera;
  80933. }(BABYLON.ArcRotateCamera));
  80934. BABYLON.VRDeviceOrientationArcRotateCamera = VRDeviceOrientationArcRotateCamera;
  80935. })(BABYLON || (BABYLON = {}));
  80936. //# sourceMappingURL=babylon.vrDeviceOrientationCamera.js.map
  80937. var BABYLON;
  80938. (function (BABYLON) {
  80939. var AnaglyphFreeCamera = /** @class */ (function (_super) {
  80940. __extends(AnaglyphFreeCamera, _super);
  80941. function AnaglyphFreeCamera(name, position, interaxialDistance, scene) {
  80942. var _this = _super.call(this, name, position, scene) || this;
  80943. _this.interaxialDistance = interaxialDistance;
  80944. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  80945. return _this;
  80946. }
  80947. AnaglyphFreeCamera.prototype.getClassName = function () {
  80948. return "AnaglyphFreeCamera";
  80949. };
  80950. return AnaglyphFreeCamera;
  80951. }(BABYLON.FreeCamera));
  80952. BABYLON.AnaglyphFreeCamera = AnaglyphFreeCamera;
  80953. var AnaglyphArcRotateCamera = /** @class */ (function (_super) {
  80954. __extends(AnaglyphArcRotateCamera, _super);
  80955. function AnaglyphArcRotateCamera(name, alpha, beta, radius, target, interaxialDistance, scene) {
  80956. var _this = _super.call(this, name, alpha, beta, radius, target, scene) || this;
  80957. _this.interaxialDistance = interaxialDistance;
  80958. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  80959. return _this;
  80960. }
  80961. AnaglyphArcRotateCamera.prototype.getClassName = function () {
  80962. return "AnaglyphArcRotateCamera";
  80963. };
  80964. return AnaglyphArcRotateCamera;
  80965. }(BABYLON.ArcRotateCamera));
  80966. BABYLON.AnaglyphArcRotateCamera = AnaglyphArcRotateCamera;
  80967. var AnaglyphGamepadCamera = /** @class */ (function (_super) {
  80968. __extends(AnaglyphGamepadCamera, _super);
  80969. function AnaglyphGamepadCamera(name, position, interaxialDistance, scene) {
  80970. var _this = _super.call(this, name, position, scene) || this;
  80971. _this.interaxialDistance = interaxialDistance;
  80972. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  80973. return _this;
  80974. }
  80975. AnaglyphGamepadCamera.prototype.getClassName = function () {
  80976. return "AnaglyphGamepadCamera";
  80977. };
  80978. return AnaglyphGamepadCamera;
  80979. }(BABYLON.GamepadCamera));
  80980. BABYLON.AnaglyphGamepadCamera = AnaglyphGamepadCamera;
  80981. var AnaglyphUniversalCamera = /** @class */ (function (_super) {
  80982. __extends(AnaglyphUniversalCamera, _super);
  80983. function AnaglyphUniversalCamera(name, position, interaxialDistance, scene) {
  80984. var _this = _super.call(this, name, position, scene) || this;
  80985. _this.interaxialDistance = interaxialDistance;
  80986. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  80987. return _this;
  80988. }
  80989. AnaglyphUniversalCamera.prototype.getClassName = function () {
  80990. return "AnaglyphUniversalCamera";
  80991. };
  80992. return AnaglyphUniversalCamera;
  80993. }(BABYLON.UniversalCamera));
  80994. BABYLON.AnaglyphUniversalCamera = AnaglyphUniversalCamera;
  80995. var StereoscopicFreeCamera = /** @class */ (function (_super) {
  80996. __extends(StereoscopicFreeCamera, _super);
  80997. function StereoscopicFreeCamera(name, position, interaxialDistance, isStereoscopicSideBySide, scene) {
  80998. var _this = _super.call(this, name, position, scene) || this;
  80999. _this.interaxialDistance = interaxialDistance;
  81000. _this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  81001. _this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  81002. return _this;
  81003. }
  81004. StereoscopicFreeCamera.prototype.getClassName = function () {
  81005. return "StereoscopicFreeCamera";
  81006. };
  81007. return StereoscopicFreeCamera;
  81008. }(BABYLON.FreeCamera));
  81009. BABYLON.StereoscopicFreeCamera = StereoscopicFreeCamera;
  81010. var StereoscopicArcRotateCamera = /** @class */ (function (_super) {
  81011. __extends(StereoscopicArcRotateCamera, _super);
  81012. function StereoscopicArcRotateCamera(name, alpha, beta, radius, target, interaxialDistance, isStereoscopicSideBySide, scene) {
  81013. var _this = _super.call(this, name, alpha, beta, radius, target, scene) || this;
  81014. _this.interaxialDistance = interaxialDistance;
  81015. _this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  81016. _this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  81017. return _this;
  81018. }
  81019. StereoscopicArcRotateCamera.prototype.getClassName = function () {
  81020. return "StereoscopicArcRotateCamera";
  81021. };
  81022. return StereoscopicArcRotateCamera;
  81023. }(BABYLON.ArcRotateCamera));
  81024. BABYLON.StereoscopicArcRotateCamera = StereoscopicArcRotateCamera;
  81025. var StereoscopicGamepadCamera = /** @class */ (function (_super) {
  81026. __extends(StereoscopicGamepadCamera, _super);
  81027. function StereoscopicGamepadCamera(name, position, interaxialDistance, isStereoscopicSideBySide, scene) {
  81028. var _this = _super.call(this, name, position, scene) || this;
  81029. _this.interaxialDistance = interaxialDistance;
  81030. _this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  81031. _this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  81032. return _this;
  81033. }
  81034. StereoscopicGamepadCamera.prototype.getClassName = function () {
  81035. return "StereoscopicGamepadCamera";
  81036. };
  81037. return StereoscopicGamepadCamera;
  81038. }(BABYLON.GamepadCamera));
  81039. BABYLON.StereoscopicGamepadCamera = StereoscopicGamepadCamera;
  81040. var StereoscopicUniversalCamera = /** @class */ (function (_super) {
  81041. __extends(StereoscopicUniversalCamera, _super);
  81042. function StereoscopicUniversalCamera(name, position, interaxialDistance, isStereoscopicSideBySide, scene) {
  81043. var _this = _super.call(this, name, position, scene) || this;
  81044. _this.interaxialDistance = interaxialDistance;
  81045. _this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  81046. _this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  81047. return _this;
  81048. }
  81049. StereoscopicUniversalCamera.prototype.getClassName = function () {
  81050. return "StereoscopicUniversalCamera";
  81051. };
  81052. return StereoscopicUniversalCamera;
  81053. }(BABYLON.UniversalCamera));
  81054. BABYLON.StereoscopicUniversalCamera = StereoscopicUniversalCamera;
  81055. })(BABYLON || (BABYLON = {}));
  81056. //# sourceMappingURL=babylon.stereoscopicCameras.js.map
  81057. var BABYLON;
  81058. (function (BABYLON) {
  81059. var VRExperienceHelperGazer = /** @class */ (function () {
  81060. function VRExperienceHelperGazer(scene, gazeTrackerToClone) {
  81061. if (gazeTrackerToClone === void 0) { gazeTrackerToClone = null; }
  81062. this.scene = scene;
  81063. this._pointerDownOnMeshAsked = false;
  81064. this._isActionableMesh = false;
  81065. this._teleportationRequestInitiated = false;
  81066. this._teleportationBackRequestInitiated = false;
  81067. this._dpadPressed = true;
  81068. this._activePointer = false;
  81069. this._id = VRExperienceHelperGazer._idCounter++;
  81070. // Gaze tracker
  81071. if (!gazeTrackerToClone) {
  81072. this._gazeTracker = BABYLON.Mesh.CreateTorus("gazeTracker", 0.0035, 0.0025, 20, scene, false);
  81073. this._gazeTracker.bakeCurrentTransformIntoVertices();
  81074. this._gazeTracker.isPickable = false;
  81075. this._gazeTracker.isVisible = false;
  81076. var targetMat = new BABYLON.StandardMaterial("targetMat", scene);
  81077. targetMat.specularColor = BABYLON.Color3.Black();
  81078. targetMat.emissiveColor = new BABYLON.Color3(0.7, 0.7, 0.7);
  81079. targetMat.backFaceCulling = false;
  81080. this._gazeTracker.material = targetMat;
  81081. }
  81082. else {
  81083. this._gazeTracker = gazeTrackerToClone.clone("gazeTracker");
  81084. }
  81085. }
  81086. VRExperienceHelperGazer.prototype._getForwardRay = function (length) {
  81087. return new BABYLON.Ray(BABYLON.Vector3.Zero(), new BABYLON.Vector3(0, 0, length));
  81088. };
  81089. VRExperienceHelperGazer.prototype._selectionPointerDown = function () {
  81090. this._pointerDownOnMeshAsked = true;
  81091. if (this._currentMeshSelected && this._currentHit) {
  81092. this.scene.simulatePointerDown(this._currentHit, { pointerId: this._id });
  81093. }
  81094. };
  81095. VRExperienceHelperGazer.prototype._selectionPointerUp = function () {
  81096. if (this._currentMeshSelected && this._currentHit) {
  81097. this.scene.simulatePointerUp(this._currentHit, { pointerId: this._id });
  81098. }
  81099. this._pointerDownOnMeshAsked = false;
  81100. };
  81101. VRExperienceHelperGazer.prototype._activatePointer = function () {
  81102. this._activePointer = true;
  81103. };
  81104. VRExperienceHelperGazer.prototype._deactivatePointer = function () {
  81105. this._activePointer = false;
  81106. };
  81107. VRExperienceHelperGazer.prototype._updatePointerDistance = function (distance) {
  81108. };
  81109. VRExperienceHelperGazer.prototype.dispose = function () {
  81110. this._interactionsEnabled = false;
  81111. this._teleportationEnabled = false;
  81112. };
  81113. VRExperienceHelperGazer._idCounter = 0;
  81114. return VRExperienceHelperGazer;
  81115. }());
  81116. var VRExperienceHelperControllerGazer = /** @class */ (function (_super) {
  81117. __extends(VRExperienceHelperControllerGazer, _super);
  81118. function VRExperienceHelperControllerGazer(webVRController, scene, gazeTrackerToClone) {
  81119. var _this = _super.call(this, scene, gazeTrackerToClone) || this;
  81120. _this.webVRController = webVRController;
  81121. // Laser pointer
  81122. _this._laserPointer = BABYLON.Mesh.CreateCylinder("laserPointer", 1, 0.004, 0.0002, 20, 1, scene, false);
  81123. var laserPointerMaterial = new BABYLON.StandardMaterial("laserPointerMat", scene);
  81124. laserPointerMaterial.emissiveColor = new BABYLON.Color3(0.7, 0.7, 0.7);
  81125. laserPointerMaterial.alpha = 0.6;
  81126. _this._laserPointer.material = laserPointerMaterial;
  81127. _this._laserPointer.rotation.x = Math.PI / 2;
  81128. _this._laserPointer.position.z = -0.5;
  81129. _this._laserPointer.isVisible = false;
  81130. if (!webVRController.mesh) {
  81131. // Create an empty mesh that is used prior to loading the high quality model
  81132. var preloadMesh = new BABYLON.Mesh("preloadControllerMesh", scene);
  81133. var preloadPointerPose = new BABYLON.Mesh(BABYLON.PoseEnabledController.POINTING_POSE, scene);
  81134. preloadPointerPose.rotation.x = -0.7;
  81135. preloadMesh.addChild(preloadPointerPose);
  81136. webVRController.attachToMesh(preloadMesh);
  81137. }
  81138. _this._setLaserPointerParent(webVRController.mesh);
  81139. return _this;
  81140. }
  81141. VRExperienceHelperControllerGazer.prototype._getForwardRay = function (length) {
  81142. return this.webVRController.getForwardRay(length);
  81143. };
  81144. VRExperienceHelperControllerGazer.prototype._activatePointer = function () {
  81145. _super.prototype._activatePointer.call(this);
  81146. this._laserPointer.isVisible = true;
  81147. };
  81148. VRExperienceHelperControllerGazer.prototype._deactivatePointer = function () {
  81149. _super.prototype._deactivatePointer.call(this);
  81150. this._laserPointer.isVisible = false;
  81151. };
  81152. VRExperienceHelperControllerGazer.prototype._setLaserPointerColor = function (color) {
  81153. this._laserPointer.material.emissiveColor = color;
  81154. };
  81155. VRExperienceHelperControllerGazer.prototype._setLaserPointerParent = function (mesh) {
  81156. var makeNotPick = function (root) {
  81157. root.name += " laserPointer";
  81158. root.getChildMeshes().forEach(function (c) {
  81159. makeNotPick(c);
  81160. });
  81161. };
  81162. makeNotPick(mesh);
  81163. var childMeshes = mesh.getChildMeshes();
  81164. this.webVRController._pointingPoseNode = null;
  81165. for (var i = 0; i < childMeshes.length; i++) {
  81166. if (childMeshes[i].name && childMeshes[i].name.indexOf(BABYLON.PoseEnabledController.POINTING_POSE) >= 0) {
  81167. mesh = childMeshes[i];
  81168. this.webVRController._pointingPoseNode = mesh;
  81169. break;
  81170. }
  81171. }
  81172. this._laserPointer.parent = mesh;
  81173. };
  81174. VRExperienceHelperControllerGazer.prototype._updatePointerDistance = function (distance) {
  81175. this._laserPointer.scaling.y = distance;
  81176. this._laserPointer.position.z = -distance / 2;
  81177. };
  81178. VRExperienceHelperControllerGazer.prototype.dispose = function () {
  81179. _super.prototype.dispose.call(this);
  81180. this._laserPointer.dispose();
  81181. };
  81182. return VRExperienceHelperControllerGazer;
  81183. }(VRExperienceHelperGazer));
  81184. var VRExperienceHelperCameraGazer = /** @class */ (function (_super) {
  81185. __extends(VRExperienceHelperCameraGazer, _super);
  81186. function VRExperienceHelperCameraGazer(getCamera, scene) {
  81187. var _this = _super.call(this, scene) || this;
  81188. _this.getCamera = getCamera;
  81189. return _this;
  81190. }
  81191. VRExperienceHelperCameraGazer.prototype._getForwardRay = function (length) {
  81192. var camera = this.getCamera();
  81193. if (camera) {
  81194. return camera.getForwardRay(length);
  81195. }
  81196. else {
  81197. return new BABYLON.Ray(BABYLON.Vector3.Zero(), BABYLON.Vector3.Forward());
  81198. }
  81199. };
  81200. return VRExperienceHelperCameraGazer;
  81201. }(VRExperienceHelperGazer));
  81202. /**
  81203. * Helps to quickly add VR support to an existing scene.
  81204. * See http://doc.babylonjs.com/how_to/webvr_helper
  81205. */
  81206. var VRExperienceHelper = /** @class */ (function () {
  81207. /**
  81208. * Instantiates a VRExperienceHelper.
  81209. * Helps to quickly add VR support to an existing scene.
  81210. * @param scene The scene the VRExperienceHelper belongs to.
  81211. * @param webVROptions Options to modify the vr experience helper's behavior.
  81212. */
  81213. function VRExperienceHelper(scene, /** Options to modify the vr experience helper's behavior. */ webVROptions) {
  81214. if (webVROptions === void 0) { webVROptions = {}; }
  81215. var _this = this;
  81216. this.webVROptions = webVROptions;
  81217. // Can the system support WebVR, even if a headset isn't plugged in?
  81218. this._webVRsupported = false;
  81219. // If WebVR is supported, is a headset plugged in and are we ready to present?
  81220. this._webVRready = false;
  81221. // Are we waiting for the requestPresent callback to complete?
  81222. this._webVRrequesting = false;
  81223. // Are we presenting to the headset right now?
  81224. this._webVRpresenting = false;
  81225. // Are we presenting in the fullscreen fallback?
  81226. this._fullscreenVRpresenting = false;
  81227. /**
  81228. * Observable raised when entering VR.
  81229. */
  81230. this.onEnteringVRObservable = new BABYLON.Observable();
  81231. /**
  81232. * Observable raised when exiting VR.
  81233. */
  81234. this.onExitingVRObservable = new BABYLON.Observable();
  81235. /**
  81236. * Observable raised when controller mesh is loaded.
  81237. */
  81238. this.onControllerMeshLoadedObservable = new BABYLON.Observable();
  81239. this._useCustomVRButton = false;
  81240. this._teleportationRequested = false;
  81241. this._teleportActive = false;
  81242. this._floorMeshesCollection = [];
  81243. this._rotationAllowed = true;
  81244. this._teleportBackwardsVector = new BABYLON.Vector3(0, -1, -1);
  81245. this._rotationRightAsked = false;
  81246. this._rotationLeftAsked = false;
  81247. this._isDefaultTeleportationTarget = true;
  81248. this._teleportationFillColor = "#444444";
  81249. this._teleportationBorderColor = "#FFFFFF";
  81250. this._rotationAngle = 0;
  81251. this._haloCenter = new BABYLON.Vector3(0, 0, 0);
  81252. this._padSensibilityUp = 0.65;
  81253. this._padSensibilityDown = 0.35;
  81254. this.leftController = null;
  81255. this.rightController = null;
  81256. /**
  81257. * Observable raised when a new mesh is selected based on meshSelectionPredicate
  81258. */
  81259. this.onNewMeshSelected = new BABYLON.Observable();
  81260. /**
  81261. * Observable raised when a new mesh is picked based on meshSelectionPredicate
  81262. */
  81263. this.onNewMeshPicked = new BABYLON.Observable();
  81264. /**
  81265. * Observable raised before camera teleportation
  81266. */
  81267. this.onBeforeCameraTeleport = new BABYLON.Observable();
  81268. /**
  81269. * Observable raised after camera teleportation
  81270. */
  81271. this.onAfterCameraTeleport = new BABYLON.Observable();
  81272. /**
  81273. * Observable raised when current selected mesh gets unselected
  81274. */
  81275. this.onSelectedMeshUnselected = new BABYLON.Observable();
  81276. /**
  81277. * Set teleportation enabled. If set to false camera teleportation will be disabled but camera rotation will be kept.
  81278. */
  81279. this.teleportationEnabled = true;
  81280. this._teleportationInitialized = false;
  81281. this._interactionsEnabled = false;
  81282. this._interactionsRequested = false;
  81283. this._displayGaze = true;
  81284. this._displayLaserPointer = true;
  81285. this._onResize = function () {
  81286. _this.moveButtonToBottomRight();
  81287. if (_this._fullscreenVRpresenting && _this._webVRready) {
  81288. _this.exitVR();
  81289. }
  81290. };
  81291. this._onFullscreenChange = function () {
  81292. if (document.fullscreen !== undefined) {
  81293. _this._fullscreenVRpresenting = document.fullscreen;
  81294. }
  81295. else if (document.mozFullScreen !== undefined) {
  81296. _this._fullscreenVRpresenting = document.mozFullScreen;
  81297. }
  81298. else if (document.webkitIsFullScreen !== undefined) {
  81299. _this._fullscreenVRpresenting = document.webkitIsFullScreen;
  81300. }
  81301. else if (document.msIsFullScreen !== undefined) {
  81302. _this._fullscreenVRpresenting = document.msIsFullScreen;
  81303. }
  81304. if (!_this._fullscreenVRpresenting && _this._canvas) {
  81305. _this.exitVR();
  81306. if (!_this._useCustomVRButton) {
  81307. _this._btnVR.style.top = _this._canvas.offsetTop + _this._canvas.offsetHeight - 70 + "px";
  81308. _this._btnVR.style.left = _this._canvas.offsetLeft + _this._canvas.offsetWidth - 100 + "px";
  81309. }
  81310. }
  81311. };
  81312. this.beforeRender = function () {
  81313. if (_this.leftController && _this.leftController._activePointer) {
  81314. _this._castRayAndSelectObject(_this.leftController);
  81315. }
  81316. if (_this.rightController && _this.rightController._activePointer) {
  81317. _this._castRayAndSelectObject(_this.rightController);
  81318. }
  81319. if (!(_this.leftController && _this.leftController._activePointer) && !(_this.rightController && _this.rightController._activePointer)) {
  81320. _this._castRayAndSelectObject(_this._cameraGazer);
  81321. }
  81322. else {
  81323. _this._cameraGazer._gazeTracker.isVisible = false;
  81324. }
  81325. };
  81326. this._onNewGamepadConnected = function (gamepad) {
  81327. if (gamepad.type !== BABYLON.Gamepad.POSE_ENABLED) {
  81328. if (gamepad.leftStick) {
  81329. gamepad.onleftstickchanged(function (stickValues) {
  81330. if (_this._teleportationInitialized && _this.teleportationEnabled) {
  81331. // Listening to classic/xbox gamepad only if no VR controller is active
  81332. if ((!_this.leftController && !_this.rightController) ||
  81333. ((_this.leftController && !_this.leftController._activePointer) &&
  81334. (_this.rightController && !_this.rightController._activePointer))) {
  81335. _this._checkTeleportWithRay(stickValues, _this._cameraGazer);
  81336. _this._checkTeleportBackwards(stickValues, _this._cameraGazer);
  81337. }
  81338. }
  81339. });
  81340. }
  81341. if (gamepad.rightStick) {
  81342. gamepad.onrightstickchanged(function (stickValues) {
  81343. if (_this._teleportationInitialized) {
  81344. _this._checkRotate(stickValues, _this._cameraGazer);
  81345. }
  81346. });
  81347. }
  81348. if (gamepad.type === BABYLON.Gamepad.XBOX) {
  81349. gamepad.onbuttondown(function (buttonPressed) {
  81350. if (_this._interactionsEnabled && buttonPressed === BABYLON.Xbox360Button.A) {
  81351. _this._cameraGazer._selectionPointerDown();
  81352. }
  81353. });
  81354. gamepad.onbuttonup(function (buttonPressed) {
  81355. if (_this._interactionsEnabled && buttonPressed === BABYLON.Xbox360Button.A) {
  81356. _this._cameraGazer._selectionPointerUp();
  81357. }
  81358. });
  81359. }
  81360. }
  81361. else {
  81362. var webVRController = gamepad;
  81363. var controller = new VRExperienceHelperControllerGazer(webVRController, _this._scene, _this._cameraGazer._gazeTracker);
  81364. if (webVRController.hand === "right" || (_this.leftController && _this.leftController.webVRController != webVRController)) {
  81365. _this.rightController = controller;
  81366. }
  81367. else {
  81368. _this.leftController = controller;
  81369. }
  81370. _this._tryEnableInteractionOnController(controller);
  81371. }
  81372. };
  81373. // 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
  81374. this._tryEnableInteractionOnController = function (controller) {
  81375. if (_this._interactionsRequested && !controller._interactionsEnabled) {
  81376. _this._enableInteractionOnController(controller);
  81377. }
  81378. if (_this._teleportationRequested && !controller._teleportationEnabled) {
  81379. _this._enableTeleportationOnController(controller);
  81380. }
  81381. };
  81382. this._onNewGamepadDisconnected = function (gamepad) {
  81383. if (gamepad instanceof BABYLON.WebVRController) {
  81384. if (gamepad.hand === "left" && _this.leftController != null) {
  81385. _this.leftController.dispose();
  81386. _this.leftController = null;
  81387. }
  81388. if (gamepad.hand === "right" && _this.rightController != null) {
  81389. _this.rightController.dispose();
  81390. _this.rightController = null;
  81391. }
  81392. }
  81393. };
  81394. this._workingVector = BABYLON.Vector3.Zero();
  81395. this._workingQuaternion = BABYLON.Quaternion.Identity();
  81396. this._workingMatrix = BABYLON.Matrix.Identity();
  81397. this._scene = scene;
  81398. this._canvas = scene.getEngine().getRenderingCanvas();
  81399. // Parse options
  81400. if (webVROptions.createFallbackVRDeviceOrientationFreeCamera === undefined) {
  81401. webVROptions.createFallbackVRDeviceOrientationFreeCamera = true;
  81402. }
  81403. if (webVROptions.createDeviceOrientationCamera === undefined) {
  81404. webVROptions.createDeviceOrientationCamera = true;
  81405. }
  81406. if (webVROptions.defaultHeight === undefined) {
  81407. webVROptions.defaultHeight = 1.7;
  81408. }
  81409. if (webVROptions.useCustomVRButton) {
  81410. this._useCustomVRButton = true;
  81411. if (webVROptions.customVRButton) {
  81412. this._btnVR = webVROptions.customVRButton;
  81413. }
  81414. }
  81415. if (webVROptions.rayLength) {
  81416. this._rayLength = webVROptions.rayLength;
  81417. }
  81418. this._defaultHeight = webVROptions.defaultHeight;
  81419. if (webVROptions.positionScale) {
  81420. this._rayLength *= webVROptions.positionScale;
  81421. this._defaultHeight *= webVROptions.positionScale;
  81422. }
  81423. // Set position
  81424. if (this._scene.activeCamera) {
  81425. this._position = this._scene.activeCamera.position.clone();
  81426. }
  81427. else {
  81428. this._position = new BABYLON.Vector3(0, this._defaultHeight, 0);
  81429. }
  81430. // Set non-vr camera
  81431. if (webVROptions.createDeviceOrientationCamera || !this._scene.activeCamera) {
  81432. this._deviceOrientationCamera = new BABYLON.DeviceOrientationCamera("deviceOrientationVRHelper", this._position.clone(), scene);
  81433. // Copy data from existing camera
  81434. if (this._scene.activeCamera) {
  81435. this._deviceOrientationCamera.minZ = this._scene.activeCamera.minZ;
  81436. this._deviceOrientationCamera.maxZ = this._scene.activeCamera.maxZ;
  81437. // Set rotation from previous camera
  81438. if (this._scene.activeCamera instanceof BABYLON.TargetCamera && this._scene.activeCamera.rotation) {
  81439. var targetCamera = this._scene.activeCamera;
  81440. if (targetCamera.rotationQuaternion) {
  81441. this._deviceOrientationCamera.rotationQuaternion.copyFrom(targetCamera.rotationQuaternion);
  81442. }
  81443. else {
  81444. this._deviceOrientationCamera.rotationQuaternion.copyFrom(BABYLON.Quaternion.RotationYawPitchRoll(targetCamera.rotation.y, targetCamera.rotation.x, targetCamera.rotation.z));
  81445. }
  81446. this._deviceOrientationCamera.rotation = targetCamera.rotation.clone();
  81447. }
  81448. }
  81449. this._scene.activeCamera = this._deviceOrientationCamera;
  81450. if (this._canvas) {
  81451. this._scene.activeCamera.attachControl(this._canvas);
  81452. }
  81453. }
  81454. else {
  81455. this._existingCamera = this._scene.activeCamera;
  81456. }
  81457. // Create VR cameras
  81458. if (webVROptions.createFallbackVRDeviceOrientationFreeCamera) {
  81459. this._vrDeviceOrientationCamera = new BABYLON.VRDeviceOrientationFreeCamera("VRDeviceOrientationVRHelper", this._position, this._scene);
  81460. }
  81461. this._webVRCamera = new BABYLON.WebVRFreeCamera("WebVRHelper", this._position, this._scene, webVROptions);
  81462. this._webVRCamera.useStandingMatrix();
  81463. this._cameraGazer = new VRExperienceHelperCameraGazer(function () { return _this.currentVRCamera; }, scene);
  81464. // Create default button
  81465. if (!this._useCustomVRButton) {
  81466. this._btnVR = document.createElement("BUTTON");
  81467. this._btnVR.className = "babylonVRicon";
  81468. this._btnVR.id = "babylonVRiconbtn";
  81469. this._btnVR.title = "Click to switch to VR";
  81470. 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) }";
  81471. css += ".babylonVRicon.vrdisplaypresenting { display: none; }";
  81472. // TODO: Add user feedback so that they know what state the VRDisplay is in (disconnected, connected, entering-VR)
  81473. // css += ".babylonVRicon.vrdisplaysupported { }";
  81474. // css += ".babylonVRicon.vrdisplayready { }";
  81475. // css += ".babylonVRicon.vrdisplayrequesting { }";
  81476. var style = document.createElement('style');
  81477. style.appendChild(document.createTextNode(css));
  81478. document.getElementsByTagName('head')[0].appendChild(style);
  81479. this.moveButtonToBottomRight();
  81480. }
  81481. // VR button click event
  81482. if (this._btnVR) {
  81483. this._btnVR.addEventListener("click", function () {
  81484. if (!_this.isInVRMode) {
  81485. _this.enterVR();
  81486. }
  81487. else {
  81488. _this.exitVR();
  81489. }
  81490. });
  81491. }
  81492. // Window events
  81493. window.addEventListener("resize", this._onResize);
  81494. document.addEventListener("fullscreenchange", this._onFullscreenChange, false);
  81495. document.addEventListener("mozfullscreenchange", this._onFullscreenChange, false);
  81496. document.addEventListener("webkitfullscreenchange", this._onFullscreenChange, false);
  81497. document.addEventListener("msfullscreenchange", this._onFullscreenChange, false);
  81498. // Display vr button when headset is connected
  81499. if (webVROptions.createFallbackVRDeviceOrientationFreeCamera) {
  81500. this.displayVRButton();
  81501. }
  81502. else {
  81503. this._scene.getEngine().onVRDisplayChangedObservable.add(function (e) {
  81504. if (e.vrDisplay) {
  81505. _this.displayVRButton();
  81506. }
  81507. });
  81508. }
  81509. // Exiting VR mode using 'ESC' key on desktop
  81510. this._onKeyDown = function (event) {
  81511. if (event.keyCode === 27 && _this.isInVRMode) {
  81512. _this.exitVR();
  81513. }
  81514. };
  81515. document.addEventListener("keydown", this._onKeyDown);
  81516. // Exiting VR mode double tapping the touch screen
  81517. this._scene.onPrePointerObservable.add(function (pointerInfo, eventState) {
  81518. if (_this.isInVRMode) {
  81519. _this.exitVR();
  81520. if (_this._fullscreenVRpresenting) {
  81521. _this._scene.getEngine().switchFullscreen(true);
  81522. }
  81523. }
  81524. }, BABYLON.PointerEventTypes.POINTERDOUBLETAP, false);
  81525. // Listen for WebVR display changes
  81526. this._onVRDisplayChanged = function (eventArgs) { return _this.onVRDisplayChanged(eventArgs); };
  81527. this._onVrDisplayPresentChange = function () { return _this.onVrDisplayPresentChange(); };
  81528. this._onVRRequestPresentStart = function () {
  81529. _this._webVRrequesting = true;
  81530. _this.updateButtonVisibility();
  81531. };
  81532. this._onVRRequestPresentComplete = function (success) {
  81533. _this._webVRrequesting = false;
  81534. _this.updateButtonVisibility();
  81535. };
  81536. scene.getEngine().onVRDisplayChangedObservable.add(this._onVRDisplayChanged);
  81537. scene.getEngine().onVRRequestPresentStart.add(this._onVRRequestPresentStart);
  81538. scene.getEngine().onVRRequestPresentComplete.add(this._onVRRequestPresentComplete);
  81539. window.addEventListener('vrdisplaypresentchange', this._onVrDisplayPresentChange);
  81540. scene.onDisposeObservable.add(function () {
  81541. _this.dispose();
  81542. });
  81543. // Gamepad connection events
  81544. this._webVRCamera.onControllerMeshLoadedObservable.add(function (webVRController) { return _this._onDefaultMeshLoaded(webVRController); });
  81545. this._scene.gamepadManager.onGamepadConnectedObservable.add(this._onNewGamepadConnected);
  81546. this._scene.gamepadManager.onGamepadDisconnectedObservable.add(this._onNewGamepadDisconnected);
  81547. this.updateButtonVisibility();
  81548. //create easing functions
  81549. this._circleEase = new BABYLON.CircleEase();
  81550. this._circleEase.setEasingMode(BABYLON.EasingFunction.EASINGMODE_EASEINOUT);
  81551. }
  81552. Object.defineProperty(VRExperienceHelper.prototype, "onEnteringVR", {
  81553. /** Return this.onEnteringVRObservable
  81554. * Note: This one is for backward compatibility. Please use onEnteringVRObservable directly
  81555. */
  81556. get: function () {
  81557. return this.onEnteringVRObservable;
  81558. },
  81559. enumerable: true,
  81560. configurable: true
  81561. });
  81562. Object.defineProperty(VRExperienceHelper.prototype, "onExitingVR", {
  81563. /** Return this.onExitingVRObservable
  81564. * Note: This one is for backward compatibility. Please use onExitingVRObservable directly
  81565. */
  81566. get: function () {
  81567. return this.onExitingVRObservable;
  81568. },
  81569. enumerable: true,
  81570. configurable: true
  81571. });
  81572. Object.defineProperty(VRExperienceHelper.prototype, "onControllerMeshLoaded", {
  81573. /** Return this.onControllerMeshLoadedObservable
  81574. * Note: This one is for backward compatibility. Please use onControllerMeshLoadedObservable directly
  81575. */
  81576. get: function () {
  81577. return this.onControllerMeshLoadedObservable;
  81578. },
  81579. enumerable: true,
  81580. configurable: true
  81581. });
  81582. Object.defineProperty(VRExperienceHelper.prototype, "teleportationTarget", {
  81583. /**
  81584. * The mesh used to display where the user is going to teleport.
  81585. */
  81586. get: function () {
  81587. return this._teleportationTarget;
  81588. },
  81589. /**
  81590. * Sets the mesh to be used to display where the user is going to teleport.
  81591. */
  81592. set: function (value) {
  81593. if (value) {
  81594. value.name = "teleportationTarget";
  81595. this._isDefaultTeleportationTarget = false;
  81596. this._teleportationTarget = value;
  81597. }
  81598. },
  81599. enumerable: true,
  81600. configurable: true
  81601. });
  81602. Object.defineProperty(VRExperienceHelper.prototype, "gazeTrackerMesh", {
  81603. /**
  81604. * The mesh used to display where the user is selecting,
  81605. * when set bakeCurrentTransformIntoVertices will be called on the mesh.
  81606. * See http://doc.babylonjs.com/resources/baking_transformations
  81607. */
  81608. get: function () {
  81609. return this._cameraGazer._gazeTracker;
  81610. },
  81611. set: function (value) {
  81612. if (value) {
  81613. this._cameraGazer._gazeTracker = value;
  81614. this._cameraGazer._gazeTracker.bakeCurrentTransformIntoVertices();
  81615. this._cameraGazer._gazeTracker.isPickable = false;
  81616. this._cameraGazer._gazeTracker.isVisible = false;
  81617. this._cameraGazer._gazeTracker.name = "gazeTracker";
  81618. if (this.leftController) {
  81619. this.leftController._gazeTracker = this._cameraGazer._gazeTracker.clone("gazeTracker");
  81620. }
  81621. if (this.rightController) {
  81622. this.rightController._gazeTracker = this._cameraGazer._gazeTracker.clone("gazeTracker");
  81623. }
  81624. }
  81625. },
  81626. enumerable: true,
  81627. configurable: true
  81628. });
  81629. Object.defineProperty(VRExperienceHelper.prototype, "displayGaze", {
  81630. /**
  81631. * If the ray of the gaze should be displayed.
  81632. */
  81633. get: function () {
  81634. return this._displayGaze;
  81635. },
  81636. /**
  81637. * Sets if the ray of the gaze should be displayed.
  81638. */
  81639. set: function (value) {
  81640. this._displayGaze = value;
  81641. if (!value) {
  81642. this._cameraGazer._gazeTracker.isVisible = false;
  81643. if (this.leftController) {
  81644. this.leftController._gazeTracker.isVisible = false;
  81645. }
  81646. if (this.rightController) {
  81647. this.rightController._gazeTracker.isVisible = false;
  81648. }
  81649. }
  81650. },
  81651. enumerable: true,
  81652. configurable: true
  81653. });
  81654. Object.defineProperty(VRExperienceHelper.prototype, "displayLaserPointer", {
  81655. /**
  81656. * If the ray of the LaserPointer should be displayed.
  81657. */
  81658. get: function () {
  81659. return this._displayLaserPointer;
  81660. },
  81661. /**
  81662. * Sets if the ray of the LaserPointer should be displayed.
  81663. */
  81664. set: function (value) {
  81665. this._displayLaserPointer = value;
  81666. if (!value) {
  81667. if (this.rightController) {
  81668. this.rightController._deactivatePointer();
  81669. this.rightController._gazeTracker.isVisible = false;
  81670. }
  81671. if (this.leftController) {
  81672. this.leftController._deactivatePointer();
  81673. this.leftController._gazeTracker.isVisible = false;
  81674. }
  81675. }
  81676. else {
  81677. if (this.rightController) {
  81678. this.rightController._activatePointer();
  81679. }
  81680. else if (this.leftController) {
  81681. this.leftController._activatePointer();
  81682. }
  81683. }
  81684. },
  81685. enumerable: true,
  81686. configurable: true
  81687. });
  81688. Object.defineProperty(VRExperienceHelper.prototype, "deviceOrientationCamera", {
  81689. /**
  81690. * The deviceOrientationCamera used as the camera when not in VR.
  81691. */
  81692. get: function () {
  81693. return this._deviceOrientationCamera;
  81694. },
  81695. enumerable: true,
  81696. configurable: true
  81697. });
  81698. Object.defineProperty(VRExperienceHelper.prototype, "currentVRCamera", {
  81699. /**
  81700. * Based on the current WebVR support, returns the current VR camera used.
  81701. */
  81702. get: function () {
  81703. if (this._webVRready) {
  81704. return this._webVRCamera;
  81705. }
  81706. else {
  81707. return this._scene.activeCamera;
  81708. }
  81709. },
  81710. enumerable: true,
  81711. configurable: true
  81712. });
  81713. Object.defineProperty(VRExperienceHelper.prototype, "webVRCamera", {
  81714. /**
  81715. * The webVRCamera which is used when in VR.
  81716. */
  81717. get: function () {
  81718. return this._webVRCamera;
  81719. },
  81720. enumerable: true,
  81721. configurable: true
  81722. });
  81723. Object.defineProperty(VRExperienceHelper.prototype, "vrDeviceOrientationCamera", {
  81724. /**
  81725. * The deviceOrientationCamera that is used as a fallback when vr device is not connected.
  81726. */
  81727. get: function () {
  81728. return this._vrDeviceOrientationCamera;
  81729. },
  81730. enumerable: true,
  81731. configurable: true
  81732. });
  81733. Object.defineProperty(VRExperienceHelper.prototype, "_teleportationRequestInitiated", {
  81734. get: function () {
  81735. var result = this._cameraGazer._teleportationRequestInitiated
  81736. || (this.leftController !== null && this.leftController._teleportationRequestInitiated)
  81737. || (this.rightController !== null && this.rightController._teleportationRequestInitiated);
  81738. return result;
  81739. },
  81740. enumerable: true,
  81741. configurable: true
  81742. });
  81743. // Raised when one of the controller has loaded successfully its associated default mesh
  81744. VRExperienceHelper.prototype._onDefaultMeshLoaded = function (webVRController) {
  81745. if (this.leftController && this.leftController.webVRController == webVRController) {
  81746. if (webVRController.mesh) {
  81747. this.leftController._setLaserPointerParent(webVRController.mesh);
  81748. }
  81749. }
  81750. if (this.rightController && this.rightController.webVRController == webVRController) {
  81751. if (webVRController.mesh) {
  81752. this.rightController._setLaserPointerParent(webVRController.mesh);
  81753. }
  81754. }
  81755. try {
  81756. this.onControllerMeshLoadedObservable.notifyObservers(webVRController);
  81757. }
  81758. catch (err) {
  81759. BABYLON.Tools.Warn("Error in your custom logic onControllerMeshLoaded: " + err);
  81760. }
  81761. };
  81762. Object.defineProperty(VRExperienceHelper.prototype, "isInVRMode", {
  81763. /**
  81764. * Gets a value indicating if we are currently in VR mode.
  81765. */
  81766. get: function () {
  81767. return this._webVRpresenting || this._fullscreenVRpresenting;
  81768. },
  81769. enumerable: true,
  81770. configurable: true
  81771. });
  81772. VRExperienceHelper.prototype.onVrDisplayPresentChange = function () {
  81773. var vrDisplay = this._scene.getEngine().getVRDevice();
  81774. if (vrDisplay) {
  81775. var wasPresenting = this._webVRpresenting;
  81776. // A VR display is connected
  81777. this._webVRpresenting = vrDisplay.isPresenting;
  81778. if (wasPresenting && !this._webVRpresenting)
  81779. this.exitVR();
  81780. }
  81781. else {
  81782. BABYLON.Tools.Warn('Detected VRDisplayPresentChange on an unknown VRDisplay. Did you can enterVR on the vrExperienceHelper?');
  81783. }
  81784. this.updateButtonVisibility();
  81785. };
  81786. VRExperienceHelper.prototype.onVRDisplayChanged = function (eventArgs) {
  81787. this._webVRsupported = eventArgs.vrSupported;
  81788. this._webVRready = !!eventArgs.vrDisplay;
  81789. this._webVRpresenting = eventArgs.vrDisplay && eventArgs.vrDisplay.isPresenting;
  81790. this.updateButtonVisibility();
  81791. };
  81792. VRExperienceHelper.prototype.moveButtonToBottomRight = function () {
  81793. if (this._canvas && !this._useCustomVRButton) {
  81794. this._btnVR.style.top = this._canvas.offsetTop + this._canvas.offsetHeight - 70 + "px";
  81795. this._btnVR.style.left = this._canvas.offsetLeft + this._canvas.offsetWidth - 100 + "px";
  81796. }
  81797. };
  81798. VRExperienceHelper.prototype.displayVRButton = function () {
  81799. if (!this._useCustomVRButton && !this._btnVRDisplayed) {
  81800. document.body.appendChild(this._btnVR);
  81801. this._btnVRDisplayed = true;
  81802. }
  81803. };
  81804. VRExperienceHelper.prototype.updateButtonVisibility = function () {
  81805. if (!this._btnVR || this._useCustomVRButton) {
  81806. return;
  81807. }
  81808. this._btnVR.className = "babylonVRicon";
  81809. if (this.isInVRMode) {
  81810. this._btnVR.className += " vrdisplaypresenting";
  81811. }
  81812. else {
  81813. if (this._webVRready)
  81814. this._btnVR.className += " vrdisplayready";
  81815. if (this._webVRsupported)
  81816. this._btnVR.className += " vrdisplaysupported";
  81817. if (this._webVRrequesting)
  81818. this._btnVR.className += " vrdisplayrequesting";
  81819. }
  81820. };
  81821. /**
  81822. * Attempt to enter VR. If a headset is connected and ready, will request present on that.
  81823. * Otherwise, will use the fullscreen API.
  81824. */
  81825. VRExperienceHelper.prototype.enterVR = function () {
  81826. if (this.onEnteringVRObservable) {
  81827. try {
  81828. this.onEnteringVRObservable.notifyObservers(this);
  81829. }
  81830. catch (err) {
  81831. BABYLON.Tools.Warn("Error in your custom logic onEnteringVR: " + err);
  81832. }
  81833. }
  81834. if (this._scene.activeCamera) {
  81835. this._position = this._scene.activeCamera.position.clone();
  81836. // make sure that we return to the last active camera
  81837. this._existingCamera = this._scene.activeCamera;
  81838. }
  81839. if (this._webVRrequesting)
  81840. return;
  81841. // If WebVR is supported and a headset is connected
  81842. if (this._webVRready) {
  81843. if (!this._webVRpresenting) {
  81844. this._webVRCamera.position = this._position;
  81845. this._scene.activeCamera = this._webVRCamera;
  81846. }
  81847. }
  81848. else if (this._vrDeviceOrientationCamera) {
  81849. this._vrDeviceOrientationCamera.position = this._position;
  81850. this._scene.activeCamera = this._vrDeviceOrientationCamera;
  81851. this._scene.getEngine().switchFullscreen(true);
  81852. this.updateButtonVisibility();
  81853. }
  81854. if (this._scene.activeCamera && this._canvas) {
  81855. this._scene.activeCamera.attachControl(this._canvas);
  81856. }
  81857. if (this._interactionsEnabled) {
  81858. this._scene.registerBeforeRender(this.beforeRender);
  81859. }
  81860. };
  81861. /**
  81862. * Attempt to exit VR, or fullscreen.
  81863. */
  81864. VRExperienceHelper.prototype.exitVR = function () {
  81865. if (this.onExitingVRObservable) {
  81866. try {
  81867. this.onExitingVRObservable.notifyObservers(this);
  81868. }
  81869. catch (err) {
  81870. BABYLON.Tools.Warn("Error in your custom logic onExitingVR: " + err);
  81871. }
  81872. }
  81873. if (this._webVRpresenting) {
  81874. this._scene.getEngine().disableVR();
  81875. }
  81876. if (this._scene.activeCamera) {
  81877. this._position = this._scene.activeCamera.position.clone();
  81878. }
  81879. if (this._deviceOrientationCamera) {
  81880. this._deviceOrientationCamera.position = this._position;
  81881. this._scene.activeCamera = this._deviceOrientationCamera;
  81882. if (this._canvas) {
  81883. this._scene.activeCamera.attachControl(this._canvas);
  81884. }
  81885. }
  81886. else if (this._existingCamera) {
  81887. this._existingCamera.position = this._position;
  81888. this._scene.activeCamera = this._existingCamera;
  81889. }
  81890. this.updateButtonVisibility();
  81891. if (this._interactionsEnabled) {
  81892. this._scene.unregisterBeforeRender(this.beforeRender);
  81893. }
  81894. };
  81895. Object.defineProperty(VRExperienceHelper.prototype, "position", {
  81896. /**
  81897. * The position of the vr experience helper.
  81898. */
  81899. get: function () {
  81900. return this._position;
  81901. },
  81902. /**
  81903. * Sets the position of the vr experience helper.
  81904. */
  81905. set: function (value) {
  81906. this._position = value;
  81907. if (this._scene.activeCamera) {
  81908. this._scene.activeCamera.position = value;
  81909. }
  81910. },
  81911. enumerable: true,
  81912. configurable: true
  81913. });
  81914. /**
  81915. * Enables controllers and user interactions suck as selecting and object or clicking on an object.
  81916. */
  81917. VRExperienceHelper.prototype.enableInteractions = function () {
  81918. var _this = this;
  81919. if (!this._interactionsEnabled) {
  81920. this._interactionsRequested = true;
  81921. if (this.leftController) {
  81922. this._enableInteractionOnController(this.leftController);
  81923. }
  81924. if (this.rightController) {
  81925. this._enableInteractionOnController(this.rightController);
  81926. }
  81927. this.raySelectionPredicate = function (mesh) {
  81928. return mesh.isVisible;
  81929. };
  81930. this.meshSelectionPredicate = function (mesh) {
  81931. return true;
  81932. };
  81933. this._raySelectionPredicate = function (mesh) {
  81934. if (_this._isTeleportationFloor(mesh) || (mesh.name.indexOf("gazeTracker") === -1
  81935. && mesh.name.indexOf("teleportationTarget") === -1
  81936. && mesh.name.indexOf("torusTeleportation") === -1
  81937. && mesh.name.indexOf("laserPointer") === -1)) {
  81938. return _this.raySelectionPredicate(mesh);
  81939. }
  81940. return false;
  81941. };
  81942. this._interactionsEnabled = true;
  81943. }
  81944. };
  81945. VRExperienceHelper.prototype._isTeleportationFloor = function (mesh) {
  81946. for (var i = 0; i < this._floorMeshesCollection.length; i++) {
  81947. if (this._floorMeshesCollection[i].id === mesh.id) {
  81948. return true;
  81949. }
  81950. }
  81951. if (this._floorMeshName && mesh.name === this._floorMeshName) {
  81952. return true;
  81953. }
  81954. return false;
  81955. };
  81956. /**
  81957. * Adds a floor mesh to be used for teleportation.
  81958. * @param floorMesh the mesh to be used for teleportation.
  81959. */
  81960. VRExperienceHelper.prototype.addFloorMesh = function (floorMesh) {
  81961. if (!this._floorMeshesCollection) {
  81962. return;
  81963. }
  81964. if (this._floorMeshesCollection.indexOf(floorMesh) > -1) {
  81965. return;
  81966. }
  81967. this._floorMeshesCollection.push(floorMesh);
  81968. };
  81969. /**
  81970. * Removes a floor mesh from being used for teleportation.
  81971. * @param floorMesh the mesh to be removed.
  81972. */
  81973. VRExperienceHelper.prototype.removeFloorMesh = function (floorMesh) {
  81974. if (!this._floorMeshesCollection) {
  81975. return;
  81976. }
  81977. var meshIndex = this._floorMeshesCollection.indexOf(floorMesh);
  81978. if (meshIndex !== -1) {
  81979. this._floorMeshesCollection.splice(meshIndex, 1);
  81980. }
  81981. };
  81982. /**
  81983. * Enables interactions and teleportation using the VR controllers and gaze.
  81984. * @param vrTeleportationOptions options to modify teleportation behavior.
  81985. */
  81986. VRExperienceHelper.prototype.enableTeleportation = function (vrTeleportationOptions) {
  81987. if (vrTeleportationOptions === void 0) { vrTeleportationOptions = {}; }
  81988. if (!this._teleportationInitialized) {
  81989. this._teleportationRequested = true;
  81990. this.enableInteractions();
  81991. if (vrTeleportationOptions.floorMeshName) {
  81992. this._floorMeshName = vrTeleportationOptions.floorMeshName;
  81993. }
  81994. if (vrTeleportationOptions.floorMeshes) {
  81995. this._floorMeshesCollection = vrTeleportationOptions.floorMeshes;
  81996. }
  81997. if (this.leftController != null) {
  81998. this._enableTeleportationOnController(this.leftController);
  81999. }
  82000. if (this.rightController != null) {
  82001. this._enableTeleportationOnController(this.rightController);
  82002. }
  82003. // Creates an image processing post process for the vignette not relying
  82004. // on the main scene configuration for image processing to reduce setup and spaces
  82005. // (gamma/linear) conflicts.
  82006. var imageProcessingConfiguration = new BABYLON.ImageProcessingConfiguration();
  82007. imageProcessingConfiguration.vignetteColor = new BABYLON.Color4(0, 0, 0, 0);
  82008. imageProcessingConfiguration.vignetteEnabled = true;
  82009. this._postProcessMove = new BABYLON.ImageProcessingPostProcess("postProcessMove", 1.0, this._webVRCamera, undefined, undefined, undefined, undefined, imageProcessingConfiguration);
  82010. this._webVRCamera.detachPostProcess(this._postProcessMove);
  82011. this._teleportationInitialized = true;
  82012. if (this._isDefaultTeleportationTarget) {
  82013. this._createTeleportationCircles();
  82014. this._teleportationTarget.scaling.scaleInPlace(this._webVRCamera.deviceScaleFactor);
  82015. }
  82016. }
  82017. };
  82018. VRExperienceHelper.prototype._enableInteractionOnController = function (controller) {
  82019. var _this = this;
  82020. var controllerMesh = controller.webVRController.mesh;
  82021. if (controllerMesh) {
  82022. controller._interactionsEnabled = true;
  82023. controller._activatePointer();
  82024. controller.webVRController.onMainButtonStateChangedObservable.add(function (stateObject) {
  82025. // Enabling / disabling laserPointer
  82026. if (_this._displayLaserPointer && stateObject.value === 1) {
  82027. if (controller._activePointer) {
  82028. controller._deactivatePointer();
  82029. }
  82030. else {
  82031. controller._activatePointer();
  82032. }
  82033. if (_this.displayGaze) {
  82034. controller._gazeTracker.isVisible = controller._activePointer;
  82035. }
  82036. }
  82037. });
  82038. controller.webVRController.onTriggerStateChangedObservable.add(function (stateObject) {
  82039. if (!controller._pointerDownOnMeshAsked) {
  82040. if (stateObject.value > _this._padSensibilityUp) {
  82041. controller._selectionPointerDown();
  82042. }
  82043. }
  82044. else if (stateObject.value < _this._padSensibilityDown) {
  82045. controller._selectionPointerUp();
  82046. }
  82047. });
  82048. }
  82049. };
  82050. VRExperienceHelper.prototype._checkTeleportWithRay = function (stateObject, gazer) {
  82051. // Dont teleport if another gaze already requested teleportation
  82052. if (this._teleportationRequestInitiated && !gazer._teleportationRequestInitiated) {
  82053. return;
  82054. }
  82055. if (!gazer._teleportationRequestInitiated) {
  82056. if (stateObject.y < -this._padSensibilityUp && gazer._dpadPressed) {
  82057. gazer._activatePointer();
  82058. gazer._teleportationRequestInitiated = true;
  82059. }
  82060. }
  82061. else {
  82062. // Listening to the proper controller values changes to confirm teleportation
  82063. if (Math.sqrt(stateObject.y * stateObject.y + stateObject.x * stateObject.x) < this._padSensibilityDown) {
  82064. if (this._teleportActive) {
  82065. this._teleportCamera(this._haloCenter);
  82066. }
  82067. gazer._teleportationRequestInitiated = false;
  82068. }
  82069. }
  82070. };
  82071. VRExperienceHelper.prototype._checkRotate = function (stateObject, gazer) {
  82072. // Only rotate when user is not currently selecting a teleportation location
  82073. if (gazer._teleportationRequestInitiated) {
  82074. return;
  82075. }
  82076. if (!this._rotationLeftAsked) {
  82077. if (stateObject.x < -this._padSensibilityUp && gazer._dpadPressed) {
  82078. this._rotationLeftAsked = true;
  82079. if (this._rotationAllowed) {
  82080. this._rotateCamera(false);
  82081. }
  82082. }
  82083. }
  82084. else {
  82085. if (stateObject.x > -this._padSensibilityDown) {
  82086. this._rotationLeftAsked = false;
  82087. }
  82088. }
  82089. if (!this._rotationRightAsked) {
  82090. if (stateObject.x > this._padSensibilityUp && gazer._dpadPressed) {
  82091. this._rotationRightAsked = true;
  82092. if (this._rotationAllowed) {
  82093. this._rotateCamera(true);
  82094. }
  82095. }
  82096. }
  82097. else {
  82098. if (stateObject.x < this._padSensibilityDown) {
  82099. this._rotationRightAsked = false;
  82100. }
  82101. }
  82102. };
  82103. VRExperienceHelper.prototype._checkTeleportBackwards = function (stateObject, gazer) {
  82104. // Only teleport backwards when user is not currently selecting a teleportation location
  82105. if (gazer._teleportationRequestInitiated) {
  82106. return;
  82107. }
  82108. // Teleport backwards
  82109. if (stateObject.y > this._padSensibilityUp && gazer._dpadPressed) {
  82110. if (!gazer._teleportationBackRequestInitiated) {
  82111. if (!this.currentVRCamera) {
  82112. return;
  82113. }
  82114. // Get rotation and position of the current camera
  82115. var rotation = BABYLON.Quaternion.FromRotationMatrix(this.currentVRCamera.getWorldMatrix().getRotationMatrix());
  82116. var position = this.currentVRCamera.position;
  82117. // If the camera has device position, use that instead
  82118. if (this.currentVRCamera.devicePosition && this.currentVRCamera.deviceRotationQuaternion) {
  82119. rotation = this.currentVRCamera.deviceRotationQuaternion;
  82120. position = this.currentVRCamera.devicePosition;
  82121. }
  82122. // Get matrix with only the y rotation of the device rotation
  82123. rotation.toEulerAnglesToRef(this._workingVector);
  82124. this._workingVector.z = 0;
  82125. this._workingVector.x = 0;
  82126. BABYLON.Quaternion.RotationYawPitchRollToRef(this._workingVector.y, this._workingVector.x, this._workingVector.z, this._workingQuaternion);
  82127. this._workingQuaternion.toRotationMatrix(this._workingMatrix);
  82128. // Rotate backwards ray by device rotation to cast at the ground behind the user
  82129. BABYLON.Vector3.TransformCoordinatesToRef(this._teleportBackwardsVector, this._workingMatrix, this._workingVector);
  82130. // Teleport if ray hit the ground and is not to far away eg. backwards off a cliff
  82131. var ray = new BABYLON.Ray(position, this._workingVector);
  82132. var hit = this._scene.pickWithRay(ray, this._raySelectionPredicate);
  82133. if (hit && hit.pickedPoint && hit.pickedMesh && this._isTeleportationFloor(hit.pickedMesh) && hit.distance < 5) {
  82134. this._teleportCamera(hit.pickedPoint);
  82135. }
  82136. gazer._teleportationBackRequestInitiated = true;
  82137. }
  82138. }
  82139. else {
  82140. gazer._teleportationBackRequestInitiated = false;
  82141. }
  82142. };
  82143. VRExperienceHelper.prototype._enableTeleportationOnController = function (controller) {
  82144. var _this = this;
  82145. var controllerMesh = controller.webVRController.mesh;
  82146. if (controllerMesh) {
  82147. if (!controller._interactionsEnabled) {
  82148. this._enableInteractionOnController(controller);
  82149. }
  82150. controller._interactionsEnabled = true;
  82151. controller._teleportationEnabled = true;
  82152. if (controller.webVRController.controllerType === BABYLON.PoseEnabledControllerType.VIVE) {
  82153. controller._dpadPressed = false;
  82154. controller.webVRController.onPadStateChangedObservable.add(function (stateObject) {
  82155. controller._dpadPressed = stateObject.pressed;
  82156. if (!controller._dpadPressed) {
  82157. _this._rotationLeftAsked = false;
  82158. _this._rotationRightAsked = false;
  82159. controller._teleportationBackRequestInitiated = false;
  82160. }
  82161. });
  82162. }
  82163. controller.webVRController.onPadValuesChangedObservable.add(function (stateObject) {
  82164. if (_this.teleportationEnabled) {
  82165. _this._checkTeleportBackwards(stateObject, controller);
  82166. _this._checkTeleportWithRay(stateObject, controller);
  82167. }
  82168. _this._checkRotate(stateObject, controller);
  82169. });
  82170. }
  82171. };
  82172. VRExperienceHelper.prototype._createTeleportationCircles = function () {
  82173. this._teleportationTarget = BABYLON.Mesh.CreateGround("teleportationTarget", 2, 2, 2, this._scene);
  82174. this._teleportationTarget.isPickable = false;
  82175. var length = 512;
  82176. var dynamicTexture = new BABYLON.DynamicTexture("DynamicTexture", length, this._scene, true);
  82177. dynamicTexture.hasAlpha = true;
  82178. var context = dynamicTexture.getContext();
  82179. var centerX = length / 2;
  82180. var centerY = length / 2;
  82181. var radius = 200;
  82182. context.beginPath();
  82183. context.arc(centerX, centerY, radius, 0, 2 * Math.PI, false);
  82184. context.fillStyle = this._teleportationFillColor;
  82185. context.fill();
  82186. context.lineWidth = 10;
  82187. context.strokeStyle = this._teleportationBorderColor;
  82188. context.stroke();
  82189. context.closePath();
  82190. dynamicTexture.update();
  82191. var teleportationCircleMaterial = new BABYLON.StandardMaterial("TextPlaneMaterial", this._scene);
  82192. teleportationCircleMaterial.diffuseTexture = dynamicTexture;
  82193. this._teleportationTarget.material = teleportationCircleMaterial;
  82194. var torus = BABYLON.Mesh.CreateTorus("torusTeleportation", 0.75, 0.1, 25, this._scene, false);
  82195. torus.isPickable = false;
  82196. torus.parent = this._teleportationTarget;
  82197. var animationInnerCircle = new BABYLON.Animation("animationInnerCircle", "position.y", 30, BABYLON.Animation.ANIMATIONTYPE_FLOAT, BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE);
  82198. var keys = [];
  82199. keys.push({
  82200. frame: 0,
  82201. value: 0
  82202. });
  82203. keys.push({
  82204. frame: 30,
  82205. value: 0.4
  82206. });
  82207. keys.push({
  82208. frame: 60,
  82209. value: 0
  82210. });
  82211. animationInnerCircle.setKeys(keys);
  82212. var easingFunction = new BABYLON.SineEase();
  82213. easingFunction.setEasingMode(BABYLON.EasingFunction.EASINGMODE_EASEINOUT);
  82214. animationInnerCircle.setEasingFunction(easingFunction);
  82215. torus.animations = [];
  82216. torus.animations.push(animationInnerCircle);
  82217. this._scene.beginAnimation(torus, 0, 60, true);
  82218. this._hideTeleportationTarget();
  82219. };
  82220. VRExperienceHelper.prototype._displayTeleportationTarget = function () {
  82221. this._teleportActive = true;
  82222. if (this._teleportationInitialized) {
  82223. this._teleportationTarget.isVisible = true;
  82224. if (this._isDefaultTeleportationTarget) {
  82225. this._teleportationTarget.getChildren()[0].isVisible = true;
  82226. }
  82227. }
  82228. };
  82229. VRExperienceHelper.prototype._hideTeleportationTarget = function () {
  82230. this._teleportActive = false;
  82231. if (this._teleportationInitialized) {
  82232. this._teleportationTarget.isVisible = false;
  82233. if (this._isDefaultTeleportationTarget) {
  82234. this._teleportationTarget.getChildren()[0].isVisible = false;
  82235. }
  82236. }
  82237. };
  82238. VRExperienceHelper.prototype._rotateCamera = function (right) {
  82239. var _this = this;
  82240. if (!(this.currentVRCamera instanceof BABYLON.FreeCamera)) {
  82241. return;
  82242. }
  82243. if (right) {
  82244. this._rotationAngle++;
  82245. }
  82246. else {
  82247. this._rotationAngle--;
  82248. }
  82249. this.currentVRCamera.animations = [];
  82250. var target = BABYLON.Quaternion.FromRotationMatrix(BABYLON.Matrix.RotationY(Math.PI / 4 * this._rotationAngle));
  82251. var animationRotation = new BABYLON.Animation("animationRotation", "rotationQuaternion", 90, BABYLON.Animation.ANIMATIONTYPE_QUATERNION, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  82252. var animationRotationKeys = [];
  82253. animationRotationKeys.push({
  82254. frame: 0,
  82255. value: this.currentVRCamera.rotationQuaternion
  82256. });
  82257. animationRotationKeys.push({
  82258. frame: 6,
  82259. value: target
  82260. });
  82261. animationRotation.setKeys(animationRotationKeys);
  82262. animationRotation.setEasingFunction(this._circleEase);
  82263. this.currentVRCamera.animations.push(animationRotation);
  82264. this._postProcessMove.animations = [];
  82265. var animationPP = new BABYLON.Animation("animationPP", "vignetteWeight", 90, BABYLON.Animation.ANIMATIONTYPE_FLOAT, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  82266. var vignetteWeightKeys = [];
  82267. vignetteWeightKeys.push({
  82268. frame: 0,
  82269. value: 0
  82270. });
  82271. vignetteWeightKeys.push({
  82272. frame: 3,
  82273. value: 4
  82274. });
  82275. vignetteWeightKeys.push({
  82276. frame: 6,
  82277. value: 0
  82278. });
  82279. animationPP.setKeys(vignetteWeightKeys);
  82280. animationPP.setEasingFunction(this._circleEase);
  82281. this._postProcessMove.animations.push(animationPP);
  82282. var animationPP2 = new BABYLON.Animation("animationPP2", "vignetteStretch", 90, BABYLON.Animation.ANIMATIONTYPE_FLOAT, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  82283. var vignetteStretchKeys = [];
  82284. vignetteStretchKeys.push({
  82285. frame: 0,
  82286. value: 0
  82287. });
  82288. vignetteStretchKeys.push({
  82289. frame: 3,
  82290. value: 10
  82291. });
  82292. vignetteStretchKeys.push({
  82293. frame: 6,
  82294. value: 0
  82295. });
  82296. animationPP2.setKeys(vignetteStretchKeys);
  82297. animationPP2.setEasingFunction(this._circleEase);
  82298. this._postProcessMove.animations.push(animationPP2);
  82299. this._postProcessMove.imageProcessingConfiguration.vignetteWeight = 0;
  82300. this._postProcessMove.imageProcessingConfiguration.vignetteStretch = 0;
  82301. this._postProcessMove.samples = 4;
  82302. this._webVRCamera.attachPostProcess(this._postProcessMove);
  82303. this._scene.beginAnimation(this._postProcessMove, 0, 6, false, 1, function () {
  82304. _this._webVRCamera.detachPostProcess(_this._postProcessMove);
  82305. });
  82306. this._scene.beginAnimation(this.currentVRCamera, 0, 6, false, 1);
  82307. };
  82308. VRExperienceHelper.prototype._moveTeleportationSelectorTo = function (hit, gazer) {
  82309. if (hit.pickedPoint) {
  82310. if (gazer._teleportationRequestInitiated) {
  82311. this._displayTeleportationTarget();
  82312. this._haloCenter.copyFrom(hit.pickedPoint);
  82313. this._teleportationTarget.position.copyFrom(hit.pickedPoint);
  82314. }
  82315. var pickNormal = hit.getNormal(true, false);
  82316. if (pickNormal) {
  82317. var axis1 = BABYLON.Vector3.Cross(BABYLON.Axis.Y, pickNormal);
  82318. var axis2 = BABYLON.Vector3.Cross(pickNormal, axis1);
  82319. BABYLON.Vector3.RotationFromAxisToRef(axis2, pickNormal, axis1, this._teleportationTarget.rotation);
  82320. }
  82321. this._teleportationTarget.position.y += 0.1;
  82322. }
  82323. };
  82324. VRExperienceHelper.prototype._teleportCamera = function (location) {
  82325. var _this = this;
  82326. if (!(this.currentVRCamera instanceof BABYLON.FreeCamera)) {
  82327. return;
  82328. }
  82329. // Teleport the hmd to where the user is looking by moving the anchor to where they are looking minus the
  82330. // offset of the headset from the anchor.
  82331. if (this.webVRCamera.leftCamera) {
  82332. this._workingVector.copyFrom(this.webVRCamera.leftCamera.globalPosition);
  82333. this._workingVector.subtractInPlace(this.webVRCamera.position);
  82334. location.subtractToRef(this._workingVector, this._workingVector);
  82335. }
  82336. else {
  82337. this._workingVector.copyFrom(location);
  82338. }
  82339. // Add height to account for user's height offset
  82340. if (this.isInVRMode) {
  82341. this._workingVector.y += this.webVRCamera.deviceDistanceToRoomGround() * this._webVRCamera.deviceScaleFactor;
  82342. }
  82343. else {
  82344. this._workingVector.y += this._defaultHeight;
  82345. }
  82346. this.onBeforeCameraTeleport.notifyObservers(this._workingVector);
  82347. // Create animation from the camera's position to the new location
  82348. this.currentVRCamera.animations = [];
  82349. var animationCameraTeleportation = new BABYLON.Animation("animationCameraTeleportation", "position", 90, BABYLON.Animation.ANIMATIONTYPE_VECTOR3, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  82350. var animationCameraTeleportationKeys = [{
  82351. frame: 0,
  82352. value: this.currentVRCamera.position
  82353. },
  82354. {
  82355. frame: 11,
  82356. value: this._workingVector
  82357. }
  82358. ];
  82359. animationCameraTeleportation.setKeys(animationCameraTeleportationKeys);
  82360. animationCameraTeleportation.setEasingFunction(this._circleEase);
  82361. this.currentVRCamera.animations.push(animationCameraTeleportation);
  82362. this._postProcessMove.animations = [];
  82363. var animationPP = new BABYLON.Animation("animationPP", "vignetteWeight", 90, BABYLON.Animation.ANIMATIONTYPE_FLOAT, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  82364. var vignetteWeightKeys = [];
  82365. vignetteWeightKeys.push({
  82366. frame: 0,
  82367. value: 0
  82368. });
  82369. vignetteWeightKeys.push({
  82370. frame: 5,
  82371. value: 8
  82372. });
  82373. vignetteWeightKeys.push({
  82374. frame: 11,
  82375. value: 0
  82376. });
  82377. animationPP.setKeys(vignetteWeightKeys);
  82378. this._postProcessMove.animations.push(animationPP);
  82379. var animationPP2 = new BABYLON.Animation("animationPP2", "vignetteStretch", 90, BABYLON.Animation.ANIMATIONTYPE_FLOAT, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  82380. var vignetteStretchKeys = [];
  82381. vignetteStretchKeys.push({
  82382. frame: 0,
  82383. value: 0
  82384. });
  82385. vignetteStretchKeys.push({
  82386. frame: 5,
  82387. value: 10
  82388. });
  82389. vignetteStretchKeys.push({
  82390. frame: 11,
  82391. value: 0
  82392. });
  82393. animationPP2.setKeys(vignetteStretchKeys);
  82394. this._postProcessMove.animations.push(animationPP2);
  82395. this._postProcessMove.imageProcessingConfiguration.vignetteWeight = 0;
  82396. this._postProcessMove.imageProcessingConfiguration.vignetteStretch = 0;
  82397. this._webVRCamera.attachPostProcess(this._postProcessMove);
  82398. this._scene.beginAnimation(this._postProcessMove, 0, 11, false, 1, function () {
  82399. _this._webVRCamera.detachPostProcess(_this._postProcessMove);
  82400. });
  82401. this._scene.beginAnimation(this.currentVRCamera, 0, 11, false, 1, function () {
  82402. _this.onAfterCameraTeleport.notifyObservers(_this._workingVector);
  82403. });
  82404. this._hideTeleportationTarget();
  82405. };
  82406. VRExperienceHelper.prototype._castRayAndSelectObject = function (gazer) {
  82407. if (!(this.currentVRCamera instanceof BABYLON.FreeCamera)) {
  82408. return;
  82409. }
  82410. var hit = this._scene.pickWithRay(gazer._getForwardRay(this._rayLength), this._raySelectionPredicate);
  82411. // Moving the gazeTracker on the mesh face targetted
  82412. if (hit && hit.pickedPoint) {
  82413. if (this._displayGaze) {
  82414. var multiplier = 1;
  82415. gazer._gazeTracker.isVisible = true;
  82416. if (gazer._isActionableMesh) {
  82417. multiplier = 3;
  82418. }
  82419. gazer._gazeTracker.scaling.x = hit.distance * multiplier;
  82420. gazer._gazeTracker.scaling.y = hit.distance * multiplier;
  82421. gazer._gazeTracker.scaling.z = hit.distance * multiplier;
  82422. var pickNormal = hit.getNormal();
  82423. // To avoid z-fighting
  82424. var deltaFighting = 0.002;
  82425. if (pickNormal) {
  82426. var axis1 = BABYLON.Vector3.Cross(BABYLON.Axis.Y, pickNormal);
  82427. var axis2 = BABYLON.Vector3.Cross(pickNormal, axis1);
  82428. BABYLON.Vector3.RotationFromAxisToRef(axis2, pickNormal, axis1, gazer._gazeTracker.rotation);
  82429. }
  82430. gazer._gazeTracker.position.copyFrom(hit.pickedPoint);
  82431. if (gazer._gazeTracker.position.x < 0) {
  82432. gazer._gazeTracker.position.x += deltaFighting;
  82433. }
  82434. else {
  82435. gazer._gazeTracker.position.x -= deltaFighting;
  82436. }
  82437. if (gazer._gazeTracker.position.y < 0) {
  82438. gazer._gazeTracker.position.y += deltaFighting;
  82439. }
  82440. else {
  82441. gazer._gazeTracker.position.y -= deltaFighting;
  82442. }
  82443. if (gazer._gazeTracker.position.z < 0) {
  82444. gazer._gazeTracker.position.z += deltaFighting;
  82445. }
  82446. else {
  82447. gazer._gazeTracker.position.z -= deltaFighting;
  82448. }
  82449. }
  82450. // Changing the size of the laser pointer based on the distance from the targetted point
  82451. gazer._updatePointerDistance(hit.distance);
  82452. }
  82453. else {
  82454. gazer._gazeTracker.isVisible = false;
  82455. }
  82456. if (hit && hit.pickedMesh) {
  82457. gazer._currentHit = hit;
  82458. if (gazer._pointerDownOnMeshAsked) {
  82459. this._scene.simulatePointerMove(gazer._currentHit, { pointerId: gazer._id });
  82460. }
  82461. // The object selected is the floor, we're in a teleportation scenario
  82462. if (this._teleportationInitialized && this._isTeleportationFloor(hit.pickedMesh) && hit.pickedPoint) {
  82463. // Moving the teleportation area to this targetted point
  82464. //Raise onSelectedMeshUnselected observable if ray collided floor mesh/meshes and a non floor mesh was previously selected
  82465. if (gazer._currentMeshSelected && !this._isTeleportationFloor(gazer._currentMeshSelected)) {
  82466. this._notifySelectedMeshUnselected(gazer._currentMeshSelected);
  82467. }
  82468. gazer._currentMeshSelected = null;
  82469. if (gazer._teleportationRequestInitiated) {
  82470. this._moveTeleportationSelectorTo(hit, gazer);
  82471. }
  82472. return;
  82473. }
  82474. // If not, we're in a selection scenario
  82475. //this._teleportationAllowed = false;
  82476. if (hit.pickedMesh !== gazer._currentMeshSelected) {
  82477. if (this.meshSelectionPredicate(hit.pickedMesh)) {
  82478. this.onNewMeshPicked.notifyObservers(hit);
  82479. gazer._currentMeshSelected = hit.pickedMesh;
  82480. if (hit.pickedMesh.isPickable && hit.pickedMesh.actionManager) {
  82481. this.changeGazeColor(new BABYLON.Color3(0, 0, 1));
  82482. this.changeLaserColor(new BABYLON.Color3(0.2, 0.2, 1));
  82483. gazer._isActionableMesh = true;
  82484. }
  82485. else {
  82486. this.changeGazeColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  82487. this.changeLaserColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  82488. gazer._isActionableMesh = false;
  82489. }
  82490. try {
  82491. this.onNewMeshSelected.notifyObservers(hit.pickedMesh);
  82492. }
  82493. catch (err) {
  82494. BABYLON.Tools.Warn("Error in your custom logic onNewMeshSelected: " + err);
  82495. }
  82496. }
  82497. else {
  82498. this._notifySelectedMeshUnselected(gazer._currentMeshSelected);
  82499. gazer._currentMeshSelected = null;
  82500. this.changeGazeColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  82501. this.changeLaserColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  82502. }
  82503. }
  82504. }
  82505. else {
  82506. gazer._currentHit = null;
  82507. this._notifySelectedMeshUnselected(gazer._currentMeshSelected);
  82508. gazer._currentMeshSelected = null;
  82509. //this._teleportationAllowed = false;
  82510. this.changeGazeColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  82511. this.changeLaserColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  82512. }
  82513. };
  82514. VRExperienceHelper.prototype._notifySelectedMeshUnselected = function (mesh) {
  82515. if (mesh) {
  82516. this.onSelectedMeshUnselected.notifyObservers(mesh);
  82517. }
  82518. };
  82519. /**
  82520. * Sets the color of the laser ray from the vr controllers.
  82521. * @param color new color for the ray.
  82522. */
  82523. VRExperienceHelper.prototype.changeLaserColor = function (color) {
  82524. if (this.leftController) {
  82525. this.leftController._setLaserPointerColor(color);
  82526. }
  82527. if (this.rightController) {
  82528. this.rightController._setLaserPointerColor(color);
  82529. }
  82530. };
  82531. /**
  82532. * Sets the color of the ray from the vr headsets gaze.
  82533. * @param color new color for the ray.
  82534. */
  82535. VRExperienceHelper.prototype.changeGazeColor = function (color) {
  82536. if (!this._cameraGazer._gazeTracker.material) {
  82537. return;
  82538. }
  82539. this._cameraGazer._gazeTracker.material.emissiveColor = color;
  82540. if (this.leftController) {
  82541. this.leftController._gazeTracker.material.emissiveColor = color;
  82542. }
  82543. if (this.rightController) {
  82544. this.rightController._gazeTracker.material.emissiveColor = color;
  82545. }
  82546. };
  82547. /**
  82548. * Exits VR and disposes of the vr experience helper
  82549. */
  82550. VRExperienceHelper.prototype.dispose = function () {
  82551. if (this.isInVRMode) {
  82552. this.exitVR();
  82553. }
  82554. if (this._postProcessMove) {
  82555. this._postProcessMove.dispose();
  82556. }
  82557. if (this._webVRCamera) {
  82558. this._webVRCamera.dispose();
  82559. }
  82560. if (this._vrDeviceOrientationCamera) {
  82561. this._vrDeviceOrientationCamera.dispose();
  82562. }
  82563. if (!this._useCustomVRButton && this._btnVR.parentNode) {
  82564. document.body.removeChild(this._btnVR);
  82565. }
  82566. if (this._deviceOrientationCamera && (this._scene.activeCamera != this._deviceOrientationCamera)) {
  82567. this._deviceOrientationCamera.dispose();
  82568. }
  82569. if (this._cameraGazer) {
  82570. this._cameraGazer.dispose();
  82571. }
  82572. if (this.leftController) {
  82573. this.leftController.dispose();
  82574. }
  82575. if (this.rightController) {
  82576. this.rightController.dispose();
  82577. }
  82578. if (this._teleportationTarget) {
  82579. this._teleportationTarget.dispose();
  82580. }
  82581. this._floorMeshesCollection = [];
  82582. document.removeEventListener("keydown", this._onKeyDown);
  82583. window.removeEventListener('vrdisplaypresentchange', this._onVrDisplayPresentChange);
  82584. window.removeEventListener("resize", this._onResize);
  82585. document.removeEventListener("fullscreenchange", this._onFullscreenChange);
  82586. document.removeEventListener("mozfullscreenchange", this._onFullscreenChange);
  82587. document.removeEventListener("webkitfullscreenchange", this._onFullscreenChange);
  82588. document.removeEventListener("msfullscreenchange", this._onFullscreenChange);
  82589. this._scene.getEngine().onVRDisplayChangedObservable.removeCallback(this._onVRDisplayChanged);
  82590. this._scene.getEngine().onVRRequestPresentStart.removeCallback(this._onVRRequestPresentStart);
  82591. this._scene.getEngine().onVRRequestPresentComplete.removeCallback(this._onVRRequestPresentComplete);
  82592. window.removeEventListener('vrdisplaypresentchange', this._onVrDisplayPresentChange);
  82593. this._scene.gamepadManager.onGamepadConnectedObservable.removeCallback(this._onNewGamepadConnected);
  82594. this._scene.gamepadManager.onGamepadDisconnectedObservable.removeCallback(this._onNewGamepadDisconnected);
  82595. this._scene.unregisterBeforeRender(this.beforeRender);
  82596. };
  82597. /**
  82598. * Gets the name of the VRExperienceHelper class
  82599. * @returns "VRExperienceHelper"
  82600. */
  82601. VRExperienceHelper.prototype.getClassName = function () {
  82602. return "VRExperienceHelper";
  82603. };
  82604. return VRExperienceHelper;
  82605. }());
  82606. BABYLON.VRExperienceHelper = VRExperienceHelper;
  82607. })(BABYLON || (BABYLON = {}));
  82608. //# sourceMappingURL=babylon.vrExperienceHelper.js.map
  82609. // Mainly based on these 2 articles :
  82610. // 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
  82611. // & on Seb Lee-Delisle original work: http://seb.ly/2011/04/multi-touch-game-controller-in-javascripthtml5-for-ipad/
  82612. var BABYLON;
  82613. (function (BABYLON) {
  82614. var JoystickAxis;
  82615. (function (JoystickAxis) {
  82616. JoystickAxis[JoystickAxis["X"] = 0] = "X";
  82617. JoystickAxis[JoystickAxis["Y"] = 1] = "Y";
  82618. JoystickAxis[JoystickAxis["Z"] = 2] = "Z";
  82619. })(JoystickAxis = BABYLON.JoystickAxis || (BABYLON.JoystickAxis = {}));
  82620. var VirtualJoystick = /** @class */ (function () {
  82621. function VirtualJoystick(leftJoystick) {
  82622. var _this = this;
  82623. if (leftJoystick) {
  82624. this._leftJoystick = true;
  82625. }
  82626. else {
  82627. this._leftJoystick = false;
  82628. }
  82629. VirtualJoystick._globalJoystickIndex++;
  82630. // By default left & right arrow keys are moving the X
  82631. // and up & down keys are moving the Y
  82632. this._axisTargetedByLeftAndRight = JoystickAxis.X;
  82633. this._axisTargetedByUpAndDown = JoystickAxis.Y;
  82634. this.reverseLeftRight = false;
  82635. this.reverseUpDown = false;
  82636. // collections of pointers
  82637. this._touches = new BABYLON.StringDictionary();
  82638. this.deltaPosition = BABYLON.Vector3.Zero();
  82639. this._joystickSensibility = 25;
  82640. this._inversedSensibility = 1 / (this._joystickSensibility / 1000);
  82641. this._onResize = function (evt) {
  82642. VirtualJoystick.vjCanvasWidth = window.innerWidth;
  82643. VirtualJoystick.vjCanvasHeight = window.innerHeight;
  82644. if (VirtualJoystick.vjCanvas) {
  82645. VirtualJoystick.vjCanvas.width = VirtualJoystick.vjCanvasWidth;
  82646. VirtualJoystick.vjCanvas.height = VirtualJoystick.vjCanvasHeight;
  82647. }
  82648. VirtualJoystick.halfWidth = VirtualJoystick.vjCanvasWidth / 2;
  82649. };
  82650. // injecting a canvas element on top of the canvas 3D game
  82651. if (!VirtualJoystick.vjCanvas) {
  82652. window.addEventListener("resize", this._onResize, false);
  82653. VirtualJoystick.vjCanvas = document.createElement("canvas");
  82654. VirtualJoystick.vjCanvasWidth = window.innerWidth;
  82655. VirtualJoystick.vjCanvasHeight = window.innerHeight;
  82656. VirtualJoystick.vjCanvas.width = window.innerWidth;
  82657. VirtualJoystick.vjCanvas.height = window.innerHeight;
  82658. VirtualJoystick.vjCanvas.style.width = "100%";
  82659. VirtualJoystick.vjCanvas.style.height = "100%";
  82660. VirtualJoystick.vjCanvas.style.position = "absolute";
  82661. VirtualJoystick.vjCanvas.style.backgroundColor = "transparent";
  82662. VirtualJoystick.vjCanvas.style.top = "0px";
  82663. VirtualJoystick.vjCanvas.style.left = "0px";
  82664. VirtualJoystick.vjCanvas.style.zIndex = "5";
  82665. VirtualJoystick.vjCanvas.style.msTouchAction = "none";
  82666. // Support for jQuery PEP polyfill
  82667. VirtualJoystick.vjCanvas.setAttribute("touch-action", "none");
  82668. var context = VirtualJoystick.vjCanvas.getContext('2d');
  82669. if (!context) {
  82670. throw new Error("Unable to create canvas for virtual joystick");
  82671. }
  82672. VirtualJoystick.vjCanvasContext = context;
  82673. VirtualJoystick.vjCanvasContext.strokeStyle = "#ffffff";
  82674. VirtualJoystick.vjCanvasContext.lineWidth = 2;
  82675. document.body.appendChild(VirtualJoystick.vjCanvas);
  82676. }
  82677. VirtualJoystick.halfWidth = VirtualJoystick.vjCanvas.width / 2;
  82678. this.pressed = false;
  82679. // default joystick color
  82680. this._joystickColor = "cyan";
  82681. this._joystickPointerID = -1;
  82682. // current joystick position
  82683. this._joystickPointerPos = new BABYLON.Vector2(0, 0);
  82684. this._joystickPreviousPointerPos = new BABYLON.Vector2(0, 0);
  82685. // origin joystick position
  82686. this._joystickPointerStartPos = new BABYLON.Vector2(0, 0);
  82687. this._deltaJoystickVector = new BABYLON.Vector2(0, 0);
  82688. this._onPointerDownHandlerRef = function (evt) {
  82689. _this._onPointerDown(evt);
  82690. };
  82691. this._onPointerMoveHandlerRef = function (evt) {
  82692. _this._onPointerMove(evt);
  82693. };
  82694. this._onPointerUpHandlerRef = function (evt) {
  82695. _this._onPointerUp(evt);
  82696. };
  82697. VirtualJoystick.vjCanvas.addEventListener('pointerdown', this._onPointerDownHandlerRef, false);
  82698. VirtualJoystick.vjCanvas.addEventListener('pointermove', this._onPointerMoveHandlerRef, false);
  82699. VirtualJoystick.vjCanvas.addEventListener('pointerup', this._onPointerUpHandlerRef, false);
  82700. VirtualJoystick.vjCanvas.addEventListener('pointerout', this._onPointerUpHandlerRef, false);
  82701. VirtualJoystick.vjCanvas.addEventListener("contextmenu", function (evt) {
  82702. evt.preventDefault(); // Disables system menu
  82703. }, false);
  82704. requestAnimationFrame(function () { _this._drawVirtualJoystick(); });
  82705. }
  82706. VirtualJoystick.prototype.setJoystickSensibility = function (newJoystickSensibility) {
  82707. this._joystickSensibility = newJoystickSensibility;
  82708. this._inversedSensibility = 1 / (this._joystickSensibility / 1000);
  82709. };
  82710. VirtualJoystick.prototype._onPointerDown = function (e) {
  82711. var positionOnScreenCondition;
  82712. e.preventDefault();
  82713. if (this._leftJoystick === true) {
  82714. positionOnScreenCondition = (e.clientX < VirtualJoystick.halfWidth);
  82715. }
  82716. else {
  82717. positionOnScreenCondition = (e.clientX > VirtualJoystick.halfWidth);
  82718. }
  82719. if (positionOnScreenCondition && this._joystickPointerID < 0) {
  82720. // First contact will be dedicated to the virtual joystick
  82721. this._joystickPointerID = e.pointerId;
  82722. this._joystickPointerStartPos.x = e.clientX;
  82723. this._joystickPointerStartPos.y = e.clientY;
  82724. this._joystickPointerPos = this._joystickPointerStartPos.clone();
  82725. this._joystickPreviousPointerPos = this._joystickPointerStartPos.clone();
  82726. this._deltaJoystickVector.x = 0;
  82727. this._deltaJoystickVector.y = 0;
  82728. this.pressed = true;
  82729. this._touches.add(e.pointerId.toString(), e);
  82730. }
  82731. else {
  82732. // You can only trigger the action buttons with a joystick declared
  82733. if (VirtualJoystick._globalJoystickIndex < 2 && this._action) {
  82734. this._action();
  82735. this._touches.add(e.pointerId.toString(), { x: e.clientX, y: e.clientY, prevX: e.clientX, prevY: e.clientY });
  82736. }
  82737. }
  82738. };
  82739. VirtualJoystick.prototype._onPointerMove = function (e) {
  82740. // If the current pointer is the one associated to the joystick (first touch contact)
  82741. if (this._joystickPointerID == e.pointerId) {
  82742. this._joystickPointerPos.x = e.clientX;
  82743. this._joystickPointerPos.y = e.clientY;
  82744. this._deltaJoystickVector = this._joystickPointerPos.clone();
  82745. this._deltaJoystickVector = this._deltaJoystickVector.subtract(this._joystickPointerStartPos);
  82746. var directionLeftRight = this.reverseLeftRight ? -1 : 1;
  82747. var deltaJoystickX = directionLeftRight * this._deltaJoystickVector.x / this._inversedSensibility;
  82748. switch (this._axisTargetedByLeftAndRight) {
  82749. case JoystickAxis.X:
  82750. this.deltaPosition.x = Math.min(1, Math.max(-1, deltaJoystickX));
  82751. break;
  82752. case JoystickAxis.Y:
  82753. this.deltaPosition.y = Math.min(1, Math.max(-1, deltaJoystickX));
  82754. break;
  82755. case JoystickAxis.Z:
  82756. this.deltaPosition.z = Math.min(1, Math.max(-1, deltaJoystickX));
  82757. break;
  82758. }
  82759. var directionUpDown = this.reverseUpDown ? 1 : -1;
  82760. var deltaJoystickY = directionUpDown * this._deltaJoystickVector.y / this._inversedSensibility;
  82761. switch (this._axisTargetedByUpAndDown) {
  82762. case JoystickAxis.X:
  82763. this.deltaPosition.x = Math.min(1, Math.max(-1, deltaJoystickY));
  82764. break;
  82765. case JoystickAxis.Y:
  82766. this.deltaPosition.y = Math.min(1, Math.max(-1, deltaJoystickY));
  82767. break;
  82768. case JoystickAxis.Z:
  82769. this.deltaPosition.z = Math.min(1, Math.max(-1, deltaJoystickY));
  82770. break;
  82771. }
  82772. }
  82773. else {
  82774. var data = this._touches.get(e.pointerId.toString());
  82775. if (data) {
  82776. data.x = e.clientX;
  82777. data.y = e.clientY;
  82778. }
  82779. }
  82780. };
  82781. VirtualJoystick.prototype._onPointerUp = function (e) {
  82782. if (this._joystickPointerID == e.pointerId) {
  82783. VirtualJoystick.vjCanvasContext.clearRect(this._joystickPointerStartPos.x - 64, this._joystickPointerStartPos.y - 64, 128, 128);
  82784. VirtualJoystick.vjCanvasContext.clearRect(this._joystickPreviousPointerPos.x - 42, this._joystickPreviousPointerPos.y - 42, 84, 84);
  82785. this._joystickPointerID = -1;
  82786. this.pressed = false;
  82787. }
  82788. else {
  82789. var touch = this._touches.get(e.pointerId.toString());
  82790. if (touch) {
  82791. VirtualJoystick.vjCanvasContext.clearRect(touch.prevX - 44, touch.prevY - 44, 88, 88);
  82792. }
  82793. }
  82794. this._deltaJoystickVector.x = 0;
  82795. this._deltaJoystickVector.y = 0;
  82796. this._touches.remove(e.pointerId.toString());
  82797. };
  82798. /**
  82799. * Change the color of the virtual joystick
  82800. * @param newColor a string that must be a CSS color value (like "red") or the hexa value (like "#FF0000")
  82801. */
  82802. VirtualJoystick.prototype.setJoystickColor = function (newColor) {
  82803. this._joystickColor = newColor;
  82804. };
  82805. VirtualJoystick.prototype.setActionOnTouch = function (action) {
  82806. this._action = action;
  82807. };
  82808. // Define which axis you'd like to control for left & right
  82809. VirtualJoystick.prototype.setAxisForLeftRight = function (axis) {
  82810. switch (axis) {
  82811. case JoystickAxis.X:
  82812. case JoystickAxis.Y:
  82813. case JoystickAxis.Z:
  82814. this._axisTargetedByLeftAndRight = axis;
  82815. break;
  82816. default:
  82817. this._axisTargetedByLeftAndRight = JoystickAxis.X;
  82818. break;
  82819. }
  82820. };
  82821. // Define which axis you'd like to control for up & down
  82822. VirtualJoystick.prototype.setAxisForUpDown = function (axis) {
  82823. switch (axis) {
  82824. case JoystickAxis.X:
  82825. case JoystickAxis.Y:
  82826. case JoystickAxis.Z:
  82827. this._axisTargetedByUpAndDown = axis;
  82828. break;
  82829. default:
  82830. this._axisTargetedByUpAndDown = JoystickAxis.Y;
  82831. break;
  82832. }
  82833. };
  82834. VirtualJoystick.prototype._drawVirtualJoystick = function () {
  82835. var _this = this;
  82836. if (this.pressed) {
  82837. this._touches.forEach(function (key, touch) {
  82838. if (touch.pointerId === _this._joystickPointerID) {
  82839. VirtualJoystick.vjCanvasContext.clearRect(_this._joystickPointerStartPos.x - 64, _this._joystickPointerStartPos.y - 64, 128, 128);
  82840. VirtualJoystick.vjCanvasContext.clearRect(_this._joystickPreviousPointerPos.x - 42, _this._joystickPreviousPointerPos.y - 42, 84, 84);
  82841. VirtualJoystick.vjCanvasContext.beginPath();
  82842. VirtualJoystick.vjCanvasContext.lineWidth = 6;
  82843. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  82844. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerStartPos.x, _this._joystickPointerStartPos.y, 40, 0, Math.PI * 2, true);
  82845. VirtualJoystick.vjCanvasContext.stroke();
  82846. VirtualJoystick.vjCanvasContext.closePath();
  82847. VirtualJoystick.vjCanvasContext.beginPath();
  82848. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  82849. VirtualJoystick.vjCanvasContext.lineWidth = 2;
  82850. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerStartPos.x, _this._joystickPointerStartPos.y, 60, 0, Math.PI * 2, true);
  82851. VirtualJoystick.vjCanvasContext.stroke();
  82852. VirtualJoystick.vjCanvasContext.closePath();
  82853. VirtualJoystick.vjCanvasContext.beginPath();
  82854. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  82855. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerPos.x, _this._joystickPointerPos.y, 40, 0, Math.PI * 2, true);
  82856. VirtualJoystick.vjCanvasContext.stroke();
  82857. VirtualJoystick.vjCanvasContext.closePath();
  82858. _this._joystickPreviousPointerPos = _this._joystickPointerPos.clone();
  82859. }
  82860. else {
  82861. VirtualJoystick.vjCanvasContext.clearRect(touch.prevX - 44, touch.prevY - 44, 88, 88);
  82862. VirtualJoystick.vjCanvasContext.beginPath();
  82863. VirtualJoystick.vjCanvasContext.fillStyle = "white";
  82864. VirtualJoystick.vjCanvasContext.beginPath();
  82865. VirtualJoystick.vjCanvasContext.strokeStyle = "red";
  82866. VirtualJoystick.vjCanvasContext.lineWidth = 6;
  82867. VirtualJoystick.vjCanvasContext.arc(touch.x, touch.y, 40, 0, Math.PI * 2, true);
  82868. VirtualJoystick.vjCanvasContext.stroke();
  82869. VirtualJoystick.vjCanvasContext.closePath();
  82870. touch.prevX = touch.x;
  82871. touch.prevY = touch.y;
  82872. }
  82873. ;
  82874. });
  82875. }
  82876. requestAnimationFrame(function () { _this._drawVirtualJoystick(); });
  82877. };
  82878. VirtualJoystick.prototype.releaseCanvas = function () {
  82879. if (VirtualJoystick.vjCanvas) {
  82880. VirtualJoystick.vjCanvas.removeEventListener('pointerdown', this._onPointerDownHandlerRef);
  82881. VirtualJoystick.vjCanvas.removeEventListener('pointermove', this._onPointerMoveHandlerRef);
  82882. VirtualJoystick.vjCanvas.removeEventListener('pointerup', this._onPointerUpHandlerRef);
  82883. VirtualJoystick.vjCanvas.removeEventListener('pointerout', this._onPointerUpHandlerRef);
  82884. window.removeEventListener("resize", this._onResize);
  82885. document.body.removeChild(VirtualJoystick.vjCanvas);
  82886. VirtualJoystick.vjCanvas = null;
  82887. }
  82888. };
  82889. // Used to draw the virtual joystick inside a 2D canvas on top of the WebGL rendering canvas
  82890. VirtualJoystick._globalJoystickIndex = 0;
  82891. return VirtualJoystick;
  82892. }());
  82893. BABYLON.VirtualJoystick = VirtualJoystick;
  82894. })(BABYLON || (BABYLON = {}));
  82895. //# sourceMappingURL=babylon.virtualJoystick.js.map
  82896. var BABYLON;
  82897. (function (BABYLON) {
  82898. // We're mainly based on the logic defined into the FreeCamera code
  82899. var VirtualJoysticksCamera = /** @class */ (function (_super) {
  82900. __extends(VirtualJoysticksCamera, _super);
  82901. function VirtualJoysticksCamera(name, position, scene) {
  82902. var _this = _super.call(this, name, position, scene) || this;
  82903. _this.inputs.addVirtualJoystick();
  82904. return _this;
  82905. }
  82906. VirtualJoysticksCamera.prototype.getClassName = function () {
  82907. return "VirtualJoysticksCamera";
  82908. };
  82909. return VirtualJoysticksCamera;
  82910. }(BABYLON.FreeCamera));
  82911. BABYLON.VirtualJoysticksCamera = VirtualJoysticksCamera;
  82912. })(BABYLON || (BABYLON = {}));
  82913. //# sourceMappingURL=babylon.virtualJoysticksCamera.js.map
  82914. var BABYLON;
  82915. (function (BABYLON) {
  82916. var FreeCameraVirtualJoystickInput = /** @class */ (function () {
  82917. function FreeCameraVirtualJoystickInput() {
  82918. }
  82919. FreeCameraVirtualJoystickInput.prototype.getLeftJoystick = function () {
  82920. return this._leftjoystick;
  82921. };
  82922. FreeCameraVirtualJoystickInput.prototype.getRightJoystick = function () {
  82923. return this._rightjoystick;
  82924. };
  82925. FreeCameraVirtualJoystickInput.prototype.checkInputs = function () {
  82926. if (this._leftjoystick) {
  82927. var camera = this.camera;
  82928. var speed = camera._computeLocalCameraSpeed() * 50;
  82929. var cameraTransform = BABYLON.Matrix.RotationYawPitchRoll(camera.rotation.y, camera.rotation.x, 0);
  82930. var deltaTransform = BABYLON.Vector3.TransformCoordinates(new BABYLON.Vector3(this._leftjoystick.deltaPosition.x * speed, this._leftjoystick.deltaPosition.y * speed, this._leftjoystick.deltaPosition.z * speed), cameraTransform);
  82931. camera.cameraDirection = camera.cameraDirection.add(deltaTransform);
  82932. camera.cameraRotation = camera.cameraRotation.addVector3(this._rightjoystick.deltaPosition);
  82933. if (!this._leftjoystick.pressed) {
  82934. this._leftjoystick.deltaPosition = this._leftjoystick.deltaPosition.scale(0.9);
  82935. }
  82936. if (!this._rightjoystick.pressed) {
  82937. this._rightjoystick.deltaPosition = this._rightjoystick.deltaPosition.scale(0.9);
  82938. }
  82939. }
  82940. };
  82941. FreeCameraVirtualJoystickInput.prototype.attachControl = function (element, noPreventDefault) {
  82942. this._leftjoystick = new BABYLON.VirtualJoystick(true);
  82943. this._leftjoystick.setAxisForUpDown(BABYLON.JoystickAxis.Z);
  82944. this._leftjoystick.setAxisForLeftRight(BABYLON.JoystickAxis.X);
  82945. this._leftjoystick.setJoystickSensibility(0.15);
  82946. this._rightjoystick = new BABYLON.VirtualJoystick(false);
  82947. this._rightjoystick.setAxisForUpDown(BABYLON.JoystickAxis.X);
  82948. this._rightjoystick.setAxisForLeftRight(BABYLON.JoystickAxis.Y);
  82949. this._rightjoystick.reverseUpDown = true;
  82950. this._rightjoystick.setJoystickSensibility(0.05);
  82951. this._rightjoystick.setJoystickColor("yellow");
  82952. };
  82953. FreeCameraVirtualJoystickInput.prototype.detachControl = function (element) {
  82954. this._leftjoystick.releaseCanvas();
  82955. this._rightjoystick.releaseCanvas();
  82956. };
  82957. FreeCameraVirtualJoystickInput.prototype.getClassName = function () {
  82958. return "FreeCameraVirtualJoystickInput";
  82959. };
  82960. FreeCameraVirtualJoystickInput.prototype.getSimpleName = function () {
  82961. return "virtualJoystick";
  82962. };
  82963. return FreeCameraVirtualJoystickInput;
  82964. }());
  82965. BABYLON.FreeCameraVirtualJoystickInput = FreeCameraVirtualJoystickInput;
  82966. BABYLON.CameraInputTypes["FreeCameraVirtualJoystickInput"] = FreeCameraVirtualJoystickInput;
  82967. })(BABYLON || (BABYLON = {}));
  82968. //# sourceMappingURL=babylon.freeCameraVirtualJoystickInput.js.map
  82969. var BABYLON;
  82970. (function (BABYLON) {
  82971. var SimplificationSettings = /** @class */ (function () {
  82972. function SimplificationSettings(quality, distance, optimizeMesh) {
  82973. this.quality = quality;
  82974. this.distance = distance;
  82975. this.optimizeMesh = optimizeMesh;
  82976. }
  82977. return SimplificationSettings;
  82978. }());
  82979. BABYLON.SimplificationSettings = SimplificationSettings;
  82980. var SimplificationQueue = /** @class */ (function () {
  82981. function SimplificationQueue() {
  82982. this.running = false;
  82983. this._simplificationArray = [];
  82984. }
  82985. SimplificationQueue.prototype.addTask = function (task) {
  82986. this._simplificationArray.push(task);
  82987. };
  82988. SimplificationQueue.prototype.executeNext = function () {
  82989. var task = this._simplificationArray.pop();
  82990. if (task) {
  82991. this.running = true;
  82992. this.runSimplification(task);
  82993. }
  82994. else {
  82995. this.running = false;
  82996. }
  82997. };
  82998. SimplificationQueue.prototype.runSimplification = function (task) {
  82999. var _this = this;
  83000. if (task.parallelProcessing) {
  83001. //parallel simplifier
  83002. task.settings.forEach(function (setting) {
  83003. var simplifier = _this.getSimplifier(task);
  83004. simplifier.simplify(setting, function (newMesh) {
  83005. task.mesh.addLODLevel(setting.distance, newMesh);
  83006. newMesh.isVisible = true;
  83007. //check if it is the last
  83008. if (setting.quality === task.settings[task.settings.length - 1].quality && task.successCallback) {
  83009. //all done, run the success callback.
  83010. task.successCallback();
  83011. }
  83012. _this.executeNext();
  83013. });
  83014. });
  83015. }
  83016. else {
  83017. //single simplifier.
  83018. var simplifier = this.getSimplifier(task);
  83019. var runDecimation = function (setting, callback) {
  83020. simplifier.simplify(setting, function (newMesh) {
  83021. task.mesh.addLODLevel(setting.distance, newMesh);
  83022. newMesh.isVisible = true;
  83023. //run the next quality level
  83024. callback();
  83025. });
  83026. };
  83027. BABYLON.AsyncLoop.Run(task.settings.length, function (loop) {
  83028. runDecimation(task.settings[loop.index], function () {
  83029. loop.executeNext();
  83030. });
  83031. }, function () {
  83032. //execution ended, run the success callback.
  83033. if (task.successCallback) {
  83034. task.successCallback();
  83035. }
  83036. _this.executeNext();
  83037. });
  83038. }
  83039. };
  83040. SimplificationQueue.prototype.getSimplifier = function (task) {
  83041. switch (task.simplificationType) {
  83042. case SimplificationType.QUADRATIC:
  83043. default:
  83044. return new QuadraticErrorSimplification(task.mesh);
  83045. }
  83046. };
  83047. return SimplificationQueue;
  83048. }());
  83049. BABYLON.SimplificationQueue = SimplificationQueue;
  83050. /**
  83051. * The implemented types of simplification.
  83052. * At the moment only Quadratic Error Decimation is implemented.
  83053. */
  83054. var SimplificationType;
  83055. (function (SimplificationType) {
  83056. SimplificationType[SimplificationType["QUADRATIC"] = 0] = "QUADRATIC";
  83057. })(SimplificationType = BABYLON.SimplificationType || (BABYLON.SimplificationType = {}));
  83058. var DecimationTriangle = /** @class */ (function () {
  83059. function DecimationTriangle(vertices) {
  83060. this.vertices = vertices;
  83061. this.error = new Array(4);
  83062. this.deleted = false;
  83063. this.isDirty = false;
  83064. this.deletePending = false;
  83065. this.borderFactor = 0;
  83066. }
  83067. return DecimationTriangle;
  83068. }());
  83069. BABYLON.DecimationTriangle = DecimationTriangle;
  83070. var DecimationVertex = /** @class */ (function () {
  83071. function DecimationVertex(position, id) {
  83072. this.position = position;
  83073. this.id = id;
  83074. this.isBorder = true;
  83075. this.q = new QuadraticMatrix();
  83076. this.triangleCount = 0;
  83077. this.triangleStart = 0;
  83078. this.originalOffsets = [];
  83079. }
  83080. DecimationVertex.prototype.updatePosition = function (newPosition) {
  83081. this.position.copyFrom(newPosition);
  83082. };
  83083. return DecimationVertex;
  83084. }());
  83085. BABYLON.DecimationVertex = DecimationVertex;
  83086. var QuadraticMatrix = /** @class */ (function () {
  83087. function QuadraticMatrix(data) {
  83088. this.data = new Array(10);
  83089. for (var i = 0; i < 10; ++i) {
  83090. if (data && data[i]) {
  83091. this.data[i] = data[i];
  83092. }
  83093. else {
  83094. this.data[i] = 0;
  83095. }
  83096. }
  83097. }
  83098. QuadraticMatrix.prototype.det = function (a11, a12, a13, a21, a22, a23, a31, a32, a33) {
  83099. var det = this.data[a11] * this.data[a22] * this.data[a33] + this.data[a13] * this.data[a21] * this.data[a32] +
  83100. this.data[a12] * this.data[a23] * this.data[a31] - this.data[a13] * this.data[a22] * this.data[a31] -
  83101. this.data[a11] * this.data[a23] * this.data[a32] - this.data[a12] * this.data[a21] * this.data[a33];
  83102. return det;
  83103. };
  83104. QuadraticMatrix.prototype.addInPlace = function (matrix) {
  83105. for (var i = 0; i < 10; ++i) {
  83106. this.data[i] += matrix.data[i];
  83107. }
  83108. };
  83109. QuadraticMatrix.prototype.addArrayInPlace = function (data) {
  83110. for (var i = 0; i < 10; ++i) {
  83111. this.data[i] += data[i];
  83112. }
  83113. };
  83114. QuadraticMatrix.prototype.add = function (matrix) {
  83115. var m = new QuadraticMatrix();
  83116. for (var i = 0; i < 10; ++i) {
  83117. m.data[i] = this.data[i] + matrix.data[i];
  83118. }
  83119. return m;
  83120. };
  83121. QuadraticMatrix.FromData = function (a, b, c, d) {
  83122. return new QuadraticMatrix(QuadraticMatrix.DataFromNumbers(a, b, c, d));
  83123. };
  83124. //returning an array to avoid garbage collection
  83125. QuadraticMatrix.DataFromNumbers = function (a, b, c, d) {
  83126. return [a * a, a * b, a * c, a * d, b * b, b * c, b * d, c * c, c * d, d * d];
  83127. };
  83128. return QuadraticMatrix;
  83129. }());
  83130. BABYLON.QuadraticMatrix = QuadraticMatrix;
  83131. var Reference = /** @class */ (function () {
  83132. function Reference(vertexId, triangleId) {
  83133. this.vertexId = vertexId;
  83134. this.triangleId = triangleId;
  83135. }
  83136. return Reference;
  83137. }());
  83138. BABYLON.Reference = Reference;
  83139. /**
  83140. * An implementation of the Quadratic Error simplification algorithm.
  83141. * Original paper : http://www1.cs.columbia.edu/~cs4162/html05s/garland97.pdf
  83142. * Ported mostly from QSlim and http://voxels.blogspot.de/2014/05/quadric-mesh-simplification-with-source.html to babylon JS
  83143. * @author RaananW
  83144. */
  83145. var QuadraticErrorSimplification = /** @class */ (function () {
  83146. function QuadraticErrorSimplification(_mesh) {
  83147. this._mesh = _mesh;
  83148. this.syncIterations = 5000;
  83149. this.aggressiveness = 7;
  83150. this.decimationIterations = 100;
  83151. this.boundingBoxEpsilon = BABYLON.Epsilon;
  83152. }
  83153. QuadraticErrorSimplification.prototype.simplify = function (settings, successCallback) {
  83154. var _this = this;
  83155. this.initDecimatedMesh();
  83156. //iterating through the submeshes array, one after the other.
  83157. BABYLON.AsyncLoop.Run(this._mesh.subMeshes.length, function (loop) {
  83158. _this.initWithMesh(loop.index, function () {
  83159. _this.runDecimation(settings, loop.index, function () {
  83160. loop.executeNext();
  83161. });
  83162. }, settings.optimizeMesh);
  83163. }, function () {
  83164. setTimeout(function () {
  83165. successCallback(_this._reconstructedMesh);
  83166. }, 0);
  83167. });
  83168. };
  83169. QuadraticErrorSimplification.prototype.runDecimation = function (settings, submeshIndex, successCallback) {
  83170. var _this = this;
  83171. var targetCount = ~~(this.triangles.length * settings.quality);
  83172. var deletedTriangles = 0;
  83173. var triangleCount = this.triangles.length;
  83174. var iterationFunction = function (iteration, callback) {
  83175. setTimeout(function () {
  83176. if (iteration % 5 === 0) {
  83177. _this.updateMesh(iteration === 0);
  83178. }
  83179. for (var i = 0; i < _this.triangles.length; ++i) {
  83180. _this.triangles[i].isDirty = false;
  83181. }
  83182. var threshold = 0.000000001 * Math.pow((iteration + 3), _this.aggressiveness);
  83183. var trianglesIterator = function (i) {
  83184. var tIdx = ~~(((_this.triangles.length / 2) + i) % _this.triangles.length);
  83185. var t = _this.triangles[tIdx];
  83186. if (!t)
  83187. return;
  83188. if (t.error[3] > threshold || t.deleted || t.isDirty) {
  83189. return;
  83190. }
  83191. for (var j = 0; j < 3; ++j) {
  83192. if (t.error[j] < threshold) {
  83193. var deleted0 = [];
  83194. var deleted1 = [];
  83195. var v0 = t.vertices[j];
  83196. var v1 = t.vertices[(j + 1) % 3];
  83197. if (v0.isBorder || v1.isBorder)
  83198. continue;
  83199. var p = BABYLON.Vector3.Zero();
  83200. var n = BABYLON.Vector3.Zero();
  83201. var uv = BABYLON.Vector2.Zero();
  83202. var color = new BABYLON.Color4(0, 0, 0, 1);
  83203. _this.calculateError(v0, v1, p, n, uv, color);
  83204. var delTr = new Array();
  83205. if (_this.isFlipped(v0, v1, p, deleted0, t.borderFactor, delTr))
  83206. continue;
  83207. if (_this.isFlipped(v1, v0, p, deleted1, t.borderFactor, delTr))
  83208. continue;
  83209. if (deleted0.indexOf(true) < 0 || deleted1.indexOf(true) < 0)
  83210. continue;
  83211. var uniqueArray = new Array();
  83212. delTr.forEach(function (deletedT) {
  83213. if (uniqueArray.indexOf(deletedT) === -1) {
  83214. deletedT.deletePending = true;
  83215. uniqueArray.push(deletedT);
  83216. }
  83217. });
  83218. if (uniqueArray.length % 2 !== 0) {
  83219. continue;
  83220. }
  83221. v0.q = v1.q.add(v0.q);
  83222. v0.updatePosition(p);
  83223. var tStart = _this.references.length;
  83224. deletedTriangles = _this.updateTriangles(v0, v0, deleted0, deletedTriangles);
  83225. deletedTriangles = _this.updateTriangles(v0, v1, deleted1, deletedTriangles);
  83226. var tCount = _this.references.length - tStart;
  83227. if (tCount <= v0.triangleCount) {
  83228. if (tCount) {
  83229. for (var c = 0; c < tCount; c++) {
  83230. _this.references[v0.triangleStart + c] = _this.references[tStart + c];
  83231. }
  83232. }
  83233. }
  83234. else {
  83235. v0.triangleStart = tStart;
  83236. }
  83237. v0.triangleCount = tCount;
  83238. break;
  83239. }
  83240. }
  83241. };
  83242. BABYLON.AsyncLoop.SyncAsyncForLoop(_this.triangles.length, _this.syncIterations, trianglesIterator, callback, function () { return (triangleCount - deletedTriangles <= targetCount); });
  83243. }, 0);
  83244. };
  83245. BABYLON.AsyncLoop.Run(this.decimationIterations, function (loop) {
  83246. if (triangleCount - deletedTriangles <= targetCount)
  83247. loop.breakLoop();
  83248. else {
  83249. iterationFunction(loop.index, function () {
  83250. loop.executeNext();
  83251. });
  83252. }
  83253. }, function () {
  83254. setTimeout(function () {
  83255. //reconstruct this part of the mesh
  83256. _this.reconstructMesh(submeshIndex);
  83257. successCallback();
  83258. }, 0);
  83259. });
  83260. };
  83261. QuadraticErrorSimplification.prototype.initWithMesh = function (submeshIndex, callback, optimizeMesh) {
  83262. var _this = this;
  83263. this.vertices = [];
  83264. this.triangles = [];
  83265. var positionData = this._mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  83266. var indices = this._mesh.getIndices();
  83267. var submesh = this._mesh.subMeshes[submeshIndex];
  83268. var findInVertices = function (positionToSearch) {
  83269. if (optimizeMesh) {
  83270. for (var ii = 0; ii < _this.vertices.length; ++ii) {
  83271. if (_this.vertices[ii].position.equals(positionToSearch)) {
  83272. return _this.vertices[ii];
  83273. }
  83274. }
  83275. }
  83276. return null;
  83277. };
  83278. var vertexReferences = [];
  83279. var vertexInit = function (i) {
  83280. if (!positionData) {
  83281. return;
  83282. }
  83283. var offset = i + submesh.verticesStart;
  83284. var position = BABYLON.Vector3.FromArray(positionData, offset * 3);
  83285. var vertex = findInVertices(position) || new DecimationVertex(position, _this.vertices.length);
  83286. vertex.originalOffsets.push(offset);
  83287. if (vertex.id === _this.vertices.length) {
  83288. _this.vertices.push(vertex);
  83289. }
  83290. vertexReferences.push(vertex.id);
  83291. };
  83292. //var totalVertices = mesh.getTotalVertices();
  83293. var totalVertices = submesh.verticesCount;
  83294. BABYLON.AsyncLoop.SyncAsyncForLoop(totalVertices, (this.syncIterations / 4) >> 0, vertexInit, function () {
  83295. var indicesInit = function (i) {
  83296. if (!indices) {
  83297. return;
  83298. }
  83299. var offset = (submesh.indexStart / 3) + i;
  83300. var pos = (offset * 3);
  83301. var i0 = indices[pos + 0];
  83302. var i1 = indices[pos + 1];
  83303. var i2 = indices[pos + 2];
  83304. var v0 = _this.vertices[vertexReferences[i0 - submesh.verticesStart]];
  83305. var v1 = _this.vertices[vertexReferences[i1 - submesh.verticesStart]];
  83306. var v2 = _this.vertices[vertexReferences[i2 - submesh.verticesStart]];
  83307. var triangle = new DecimationTriangle([v0, v1, v2]);
  83308. triangle.originalOffset = pos;
  83309. _this.triangles.push(triangle);
  83310. };
  83311. BABYLON.AsyncLoop.SyncAsyncForLoop(submesh.indexCount / 3, _this.syncIterations, indicesInit, function () {
  83312. _this.init(callback);
  83313. });
  83314. });
  83315. };
  83316. QuadraticErrorSimplification.prototype.init = function (callback) {
  83317. var _this = this;
  83318. var triangleInit1 = function (i) {
  83319. var t = _this.triangles[i];
  83320. t.normal = BABYLON.Vector3.Cross(t.vertices[1].position.subtract(t.vertices[0].position), t.vertices[2].position.subtract(t.vertices[0].position)).normalize();
  83321. for (var j = 0; j < 3; j++) {
  83322. 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))));
  83323. }
  83324. };
  83325. BABYLON.AsyncLoop.SyncAsyncForLoop(this.triangles.length, this.syncIterations, triangleInit1, function () {
  83326. var triangleInit2 = function (i) {
  83327. var t = _this.triangles[i];
  83328. for (var j = 0; j < 3; ++j) {
  83329. t.error[j] = _this.calculateError(t.vertices[j], t.vertices[(j + 1) % 3]);
  83330. }
  83331. t.error[3] = Math.min(t.error[0], t.error[1], t.error[2]);
  83332. };
  83333. BABYLON.AsyncLoop.SyncAsyncForLoop(_this.triangles.length, _this.syncIterations, triangleInit2, function () {
  83334. callback();
  83335. });
  83336. });
  83337. };
  83338. QuadraticErrorSimplification.prototype.reconstructMesh = function (submeshIndex) {
  83339. var newTriangles = [];
  83340. var i;
  83341. for (i = 0; i < this.vertices.length; ++i) {
  83342. this.vertices[i].triangleCount = 0;
  83343. }
  83344. var t;
  83345. var j;
  83346. for (i = 0; i < this.triangles.length; ++i) {
  83347. if (!this.triangles[i].deleted) {
  83348. t = this.triangles[i];
  83349. for (j = 0; j < 3; ++j) {
  83350. t.vertices[j].triangleCount = 1;
  83351. }
  83352. newTriangles.push(t);
  83353. }
  83354. }
  83355. var newPositionData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind) || []);
  83356. var newNormalData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind) || []);
  83357. var newUVsData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.UVKind) || []);
  83358. var newColorsData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.ColorKind) || []);
  83359. var normalData = this._mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  83360. var uvs = this._mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  83361. var colorsData = this._mesh.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  83362. var vertexCount = 0;
  83363. for (i = 0; i < this.vertices.length; ++i) {
  83364. var vertex = this.vertices[i];
  83365. vertex.id = vertexCount;
  83366. if (vertex.triangleCount) {
  83367. vertex.originalOffsets.forEach(function (originalOffset) {
  83368. if (!normalData) {
  83369. return;
  83370. }
  83371. newPositionData.push(vertex.position.x);
  83372. newPositionData.push(vertex.position.y);
  83373. newPositionData.push(vertex.position.z);
  83374. newNormalData.push(normalData[originalOffset * 3]);
  83375. newNormalData.push(normalData[(originalOffset * 3) + 1]);
  83376. newNormalData.push(normalData[(originalOffset * 3) + 2]);
  83377. if (uvs && uvs.length) {
  83378. newUVsData.push(uvs[(originalOffset * 2)]);
  83379. newUVsData.push(uvs[(originalOffset * 2) + 1]);
  83380. }
  83381. else if (colorsData && colorsData.length) {
  83382. newColorsData.push(colorsData[(originalOffset * 4)]);
  83383. newColorsData.push(colorsData[(originalOffset * 4) + 1]);
  83384. newColorsData.push(colorsData[(originalOffset * 4) + 2]);
  83385. newColorsData.push(colorsData[(originalOffset * 4) + 3]);
  83386. }
  83387. ++vertexCount;
  83388. });
  83389. }
  83390. }
  83391. var startingIndex = this._reconstructedMesh.getTotalIndices();
  83392. var startingVertex = this._reconstructedMesh.getTotalVertices();
  83393. var submeshesArray = this._reconstructedMesh.subMeshes;
  83394. this._reconstructedMesh.subMeshes = [];
  83395. var newIndicesArray = this._reconstructedMesh.getIndices(); //[];
  83396. var originalIndices = this._mesh.getIndices();
  83397. for (i = 0; i < newTriangles.length; ++i) {
  83398. t = newTriangles[i]; //now get the new referencing point for each vertex
  83399. [0, 1, 2].forEach(function (idx) {
  83400. var id = originalIndices[t.originalOffset + idx];
  83401. var offset = t.vertices[idx].originalOffsets.indexOf(id);
  83402. if (offset < 0)
  83403. offset = 0;
  83404. newIndicesArray.push(t.vertices[idx].id + offset + startingVertex);
  83405. });
  83406. }
  83407. //overwriting the old vertex buffers and indices.
  83408. this._reconstructedMesh.setIndices(newIndicesArray);
  83409. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, newPositionData);
  83410. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, newNormalData);
  83411. if (newUVsData.length > 0)
  83412. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.UVKind, newUVsData);
  83413. if (newColorsData.length > 0)
  83414. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, newColorsData);
  83415. //create submesh
  83416. var originalSubmesh = this._mesh.subMeshes[submeshIndex];
  83417. if (submeshIndex > 0) {
  83418. this._reconstructedMesh.subMeshes = [];
  83419. submeshesArray.forEach(function (submesh) {
  83420. BABYLON.SubMesh.AddToMesh(submesh.materialIndex, submesh.verticesStart, submesh.verticesCount, /* 0, newPositionData.length/3, */ submesh.indexStart, submesh.indexCount, submesh.getMesh());
  83421. });
  83422. BABYLON.SubMesh.AddToMesh(originalSubmesh.materialIndex, startingVertex, vertexCount, /* 0, newPositionData.length / 3, */ startingIndex, newTriangles.length * 3, this._reconstructedMesh);
  83423. }
  83424. };
  83425. QuadraticErrorSimplification.prototype.initDecimatedMesh = function () {
  83426. this._reconstructedMesh = new BABYLON.Mesh(this._mesh.name + "Decimated", this._mesh.getScene());
  83427. this._reconstructedMesh.material = this._mesh.material;
  83428. this._reconstructedMesh.parent = this._mesh.parent;
  83429. this._reconstructedMesh.isVisible = false;
  83430. this._reconstructedMesh.renderingGroupId = this._mesh.renderingGroupId;
  83431. };
  83432. QuadraticErrorSimplification.prototype.isFlipped = function (vertex1, vertex2, point, deletedArray, borderFactor, delTr) {
  83433. for (var i = 0; i < vertex1.triangleCount; ++i) {
  83434. var t = this.triangles[this.references[vertex1.triangleStart + i].triangleId];
  83435. if (t.deleted)
  83436. continue;
  83437. var s = this.references[vertex1.triangleStart + i].vertexId;
  83438. var v1 = t.vertices[(s + 1) % 3];
  83439. var v2 = t.vertices[(s + 2) % 3];
  83440. if ((v1 === vertex2 || v2 === vertex2)) {
  83441. deletedArray[i] = true;
  83442. delTr.push(t);
  83443. continue;
  83444. }
  83445. var d1 = v1.position.subtract(point);
  83446. d1 = d1.normalize();
  83447. var d2 = v2.position.subtract(point);
  83448. d2 = d2.normalize();
  83449. if (Math.abs(BABYLON.Vector3.Dot(d1, d2)) > 0.999)
  83450. return true;
  83451. var normal = BABYLON.Vector3.Cross(d1, d2).normalize();
  83452. deletedArray[i] = false;
  83453. if (BABYLON.Vector3.Dot(normal, t.normal) < 0.2)
  83454. return true;
  83455. }
  83456. return false;
  83457. };
  83458. QuadraticErrorSimplification.prototype.updateTriangles = function (origVertex, vertex, deletedArray, deletedTriangles) {
  83459. var newDeleted = deletedTriangles;
  83460. for (var i = 0; i < vertex.triangleCount; ++i) {
  83461. var ref = this.references[vertex.triangleStart + i];
  83462. var t = this.triangles[ref.triangleId];
  83463. if (t.deleted)
  83464. continue;
  83465. if (deletedArray[i] && t.deletePending) {
  83466. t.deleted = true;
  83467. newDeleted++;
  83468. continue;
  83469. }
  83470. t.vertices[ref.vertexId] = origVertex;
  83471. t.isDirty = true;
  83472. t.error[0] = this.calculateError(t.vertices[0], t.vertices[1]) + (t.borderFactor / 2);
  83473. t.error[1] = this.calculateError(t.vertices[1], t.vertices[2]) + (t.borderFactor / 2);
  83474. t.error[2] = this.calculateError(t.vertices[2], t.vertices[0]) + (t.borderFactor / 2);
  83475. t.error[3] = Math.min(t.error[0], t.error[1], t.error[2]);
  83476. this.references.push(ref);
  83477. }
  83478. return newDeleted;
  83479. };
  83480. QuadraticErrorSimplification.prototype.identifyBorder = function () {
  83481. for (var i = 0; i < this.vertices.length; ++i) {
  83482. var vCount = [];
  83483. var vId = [];
  83484. var v = this.vertices[i];
  83485. var j;
  83486. for (j = 0; j < v.triangleCount; ++j) {
  83487. var triangle = this.triangles[this.references[v.triangleStart + j].triangleId];
  83488. for (var ii = 0; ii < 3; ii++) {
  83489. var ofs = 0;
  83490. var vv = triangle.vertices[ii];
  83491. while (ofs < vCount.length) {
  83492. if (vId[ofs] === vv.id)
  83493. break;
  83494. ++ofs;
  83495. }
  83496. if (ofs === vCount.length) {
  83497. vCount.push(1);
  83498. vId.push(vv.id);
  83499. }
  83500. else {
  83501. vCount[ofs]++;
  83502. }
  83503. }
  83504. }
  83505. for (j = 0; j < vCount.length; ++j) {
  83506. if (vCount[j] === 1) {
  83507. this.vertices[vId[j]].isBorder = true;
  83508. }
  83509. else {
  83510. this.vertices[vId[j]].isBorder = false;
  83511. }
  83512. }
  83513. }
  83514. };
  83515. QuadraticErrorSimplification.prototype.updateMesh = function (identifyBorders) {
  83516. if (identifyBorders === void 0) { identifyBorders = false; }
  83517. var i;
  83518. if (!identifyBorders) {
  83519. var newTrianglesVector = [];
  83520. for (i = 0; i < this.triangles.length; ++i) {
  83521. if (!this.triangles[i].deleted) {
  83522. newTrianglesVector.push(this.triangles[i]);
  83523. }
  83524. }
  83525. this.triangles = newTrianglesVector;
  83526. }
  83527. for (i = 0; i < this.vertices.length; ++i) {
  83528. this.vertices[i].triangleCount = 0;
  83529. this.vertices[i].triangleStart = 0;
  83530. }
  83531. var t;
  83532. var j;
  83533. var v;
  83534. for (i = 0; i < this.triangles.length; ++i) {
  83535. t = this.triangles[i];
  83536. for (j = 0; j < 3; ++j) {
  83537. v = t.vertices[j];
  83538. v.triangleCount++;
  83539. }
  83540. }
  83541. var tStart = 0;
  83542. for (i = 0; i < this.vertices.length; ++i) {
  83543. this.vertices[i].triangleStart = tStart;
  83544. tStart += this.vertices[i].triangleCount;
  83545. this.vertices[i].triangleCount = 0;
  83546. }
  83547. var newReferences = new Array(this.triangles.length * 3);
  83548. for (i = 0; i < this.triangles.length; ++i) {
  83549. t = this.triangles[i];
  83550. for (j = 0; j < 3; ++j) {
  83551. v = t.vertices[j];
  83552. newReferences[v.triangleStart + v.triangleCount] = new Reference(j, i);
  83553. v.triangleCount++;
  83554. }
  83555. }
  83556. this.references = newReferences;
  83557. if (identifyBorders) {
  83558. this.identifyBorder();
  83559. }
  83560. };
  83561. QuadraticErrorSimplification.prototype.vertexError = function (q, point) {
  83562. var x = point.x;
  83563. var y = point.y;
  83564. var z = point.z;
  83565. 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
  83566. + 2 * q.data[5] * y * z + 2 * q.data[6] * y + q.data[7] * z * z + 2 * q.data[8] * z + q.data[9];
  83567. };
  83568. QuadraticErrorSimplification.prototype.calculateError = function (vertex1, vertex2, pointResult, normalResult, uvResult, colorResult) {
  83569. var q = vertex1.q.add(vertex2.q);
  83570. var border = vertex1.isBorder && vertex2.isBorder;
  83571. var error = 0;
  83572. var qDet = q.det(0, 1, 2, 1, 4, 5, 2, 5, 7);
  83573. if (qDet !== 0 && !border) {
  83574. if (!pointResult) {
  83575. pointResult = BABYLON.Vector3.Zero();
  83576. }
  83577. pointResult.x = -1 / qDet * (q.det(1, 2, 3, 4, 5, 6, 5, 7, 8));
  83578. pointResult.y = 1 / qDet * (q.det(0, 2, 3, 1, 5, 6, 2, 7, 8));
  83579. pointResult.z = -1 / qDet * (q.det(0, 1, 3, 1, 4, 6, 2, 5, 8));
  83580. error = this.vertexError(q, pointResult);
  83581. }
  83582. else {
  83583. var p3 = (vertex1.position.add(vertex2.position)).divide(new BABYLON.Vector3(2, 2, 2));
  83584. //var norm3 = (vertex1.normal.add(vertex2.normal)).divide(new Vector3(2, 2, 2)).normalize();
  83585. var error1 = this.vertexError(q, vertex1.position);
  83586. var error2 = this.vertexError(q, vertex2.position);
  83587. var error3 = this.vertexError(q, p3);
  83588. error = Math.min(error1, error2, error3);
  83589. if (error === error1) {
  83590. if (pointResult) {
  83591. pointResult.copyFrom(vertex1.position);
  83592. }
  83593. }
  83594. else if (error === error2) {
  83595. if (pointResult) {
  83596. pointResult.copyFrom(vertex2.position);
  83597. }
  83598. }
  83599. else {
  83600. if (pointResult) {
  83601. pointResult.copyFrom(p3);
  83602. }
  83603. }
  83604. }
  83605. return error;
  83606. };
  83607. return QuadraticErrorSimplification;
  83608. }());
  83609. BABYLON.QuadraticErrorSimplification = QuadraticErrorSimplification;
  83610. })(BABYLON || (BABYLON = {}));
  83611. //# sourceMappingURL=babylon.meshSimplification.js.map
  83612. var BABYLON;
  83613. (function (BABYLON) {
  83614. var MeshLODLevel = /** @class */ (function () {
  83615. function MeshLODLevel(distance, mesh) {
  83616. this.distance = distance;
  83617. this.mesh = mesh;
  83618. }
  83619. return MeshLODLevel;
  83620. }());
  83621. BABYLON.MeshLODLevel = MeshLODLevel;
  83622. })(BABYLON || (BABYLON = {}));
  83623. //# sourceMappingURL=babylon.meshLODLevel.js.map
  83624. var BABYLON;
  83625. (function (BABYLON) {
  83626. /**
  83627. * Defines the root class used to create scene optimization to use with SceneOptimizer
  83628. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  83629. */
  83630. var SceneOptimization = /** @class */ (function () {
  83631. /**
  83632. * Creates the SceneOptimization object
  83633. * @param priority defines the priority of this optimization (0 by default which means first in the list)
  83634. * @param desc defines the description associated with the optimization
  83635. */
  83636. function SceneOptimization(
  83637. /**
  83638. * Defines the priority of this optimization (0 by default which means first in the list)
  83639. */
  83640. priority) {
  83641. if (priority === void 0) { priority = 0; }
  83642. this.priority = priority;
  83643. }
  83644. /**
  83645. * Gets a string describing the action executed by the current optimization
  83646. * @returns description string
  83647. */
  83648. SceneOptimization.prototype.getDescription = function () {
  83649. return "";
  83650. };
  83651. /**
  83652. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  83653. * @param scene defines the current scene where to apply this optimization
  83654. * @param optimizer defines the current optimizer
  83655. * @returns true if everything that can be done was applied
  83656. */
  83657. SceneOptimization.prototype.apply = function (scene, optimizer) {
  83658. return true;
  83659. };
  83660. ;
  83661. return SceneOptimization;
  83662. }());
  83663. BABYLON.SceneOptimization = SceneOptimization;
  83664. /**
  83665. * Defines an optimization used to reduce the size of render target textures
  83666. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  83667. */
  83668. var TextureOptimization = /** @class */ (function (_super) {
  83669. __extends(TextureOptimization, _super);
  83670. /**
  83671. * Creates the TextureOptimization object
  83672. * @param priority defines the priority of this optimization (0 by default which means first in the list)
  83673. * @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
  83674. * @param step defines the factor (0.5 by default) used to scale down textures bigger than maximum sized allowed.
  83675. */
  83676. function TextureOptimization(
  83677. /**
  83678. * Defines the priority of this optimization (0 by default which means first in the list)
  83679. */
  83680. priority,
  83681. /**
  83682. * 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
  83683. */
  83684. maximumSize,
  83685. /**
  83686. * Defines the factor (0.5 by default) used to scale down textures bigger than maximum sized allowed.
  83687. */
  83688. step) {
  83689. if (priority === void 0) { priority = 0; }
  83690. if (maximumSize === void 0) { maximumSize = 1024; }
  83691. if (step === void 0) { step = 0.5; }
  83692. var _this = _super.call(this, priority) || this;
  83693. _this.priority = priority;
  83694. _this.maximumSize = maximumSize;
  83695. _this.step = step;
  83696. return _this;
  83697. }
  83698. /**
  83699. * Gets a string describing the action executed by the current optimization
  83700. * @returns description string
  83701. */
  83702. TextureOptimization.prototype.getDescription = function () {
  83703. return "Reducing render target texture size to " + this.maximumSize;
  83704. };
  83705. /**
  83706. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  83707. * @param scene defines the current scene where to apply this optimization
  83708. * @param optimizer defines the current optimizer
  83709. * @returns true if everything that can be done was applied
  83710. */
  83711. TextureOptimization.prototype.apply = function (scene, optimizer) {
  83712. var allDone = true;
  83713. for (var index = 0; index < scene.textures.length; index++) {
  83714. var texture = scene.textures[index];
  83715. if (!texture.canRescale || texture.getContext) {
  83716. continue;
  83717. }
  83718. var currentSize = texture.getSize();
  83719. var maxDimension = Math.max(currentSize.width, currentSize.height);
  83720. if (maxDimension > this.maximumSize) {
  83721. texture.scale(this.step);
  83722. allDone = false;
  83723. }
  83724. }
  83725. return allDone;
  83726. };
  83727. return TextureOptimization;
  83728. }(SceneOptimization));
  83729. BABYLON.TextureOptimization = TextureOptimization;
  83730. /**
  83731. * Defines an optimization used to increase or decrease the rendering resolution
  83732. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  83733. */
  83734. var HardwareScalingOptimization = /** @class */ (function (_super) {
  83735. __extends(HardwareScalingOptimization, _super);
  83736. /**
  83737. * Creates the HardwareScalingOptimization object
  83738. * @param priority defines the priority of this optimization (0 by default which means first in the list)
  83739. * @param maximumScale defines the maximum scale to use (2 by default)
  83740. * @param step defines the step to use between two passes (0.5 by default)
  83741. */
  83742. function HardwareScalingOptimization(
  83743. /**
  83744. * Defines the priority of this optimization (0 by default which means first in the list)
  83745. */
  83746. priority,
  83747. /**
  83748. * Defines the maximum scale to use (2 by default)
  83749. */
  83750. maximumScale,
  83751. /**
  83752. * Defines the step to use between two passes (0.5 by default)
  83753. */
  83754. step) {
  83755. if (priority === void 0) { priority = 0; }
  83756. if (maximumScale === void 0) { maximumScale = 2; }
  83757. if (step === void 0) { step = 0.25; }
  83758. var _this = _super.call(this, priority) || this;
  83759. _this.priority = priority;
  83760. _this.maximumScale = maximumScale;
  83761. _this.step = step;
  83762. _this._currentScale = -1;
  83763. _this._directionOffset = 1;
  83764. return _this;
  83765. }
  83766. /**
  83767. * Gets a string describing the action executed by the current optimization
  83768. * @return description string
  83769. */
  83770. HardwareScalingOptimization.prototype.getDescription = function () {
  83771. return "Setting hardware scaling level to " + this._currentScale;
  83772. };
  83773. /**
  83774. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  83775. * @param scene defines the current scene where to apply this optimization
  83776. * @param optimizer defines the current optimizer
  83777. * @returns true if everything that can be done was applied
  83778. */
  83779. HardwareScalingOptimization.prototype.apply = function (scene, optimizer) {
  83780. if (this._currentScale === -1) {
  83781. this._currentScale = scene.getEngine().getHardwareScalingLevel();
  83782. if (this._currentScale > this.maximumScale) {
  83783. this._directionOffset = -1;
  83784. }
  83785. }
  83786. this._currentScale += this._directionOffset * this.step;
  83787. scene.getEngine().setHardwareScalingLevel(this._currentScale);
  83788. return this._directionOffset === 1 ? this._currentScale >= this.maximumScale : this._currentScale <= this.maximumScale;
  83789. };
  83790. ;
  83791. return HardwareScalingOptimization;
  83792. }(SceneOptimization));
  83793. BABYLON.HardwareScalingOptimization = HardwareScalingOptimization;
  83794. /**
  83795. * Defines an optimization used to remove shadows
  83796. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  83797. */
  83798. var ShadowsOptimization = /** @class */ (function (_super) {
  83799. __extends(ShadowsOptimization, _super);
  83800. function ShadowsOptimization() {
  83801. return _super !== null && _super.apply(this, arguments) || this;
  83802. }
  83803. /**
  83804. * Gets a string describing the action executed by the current optimization
  83805. * @return description string
  83806. */
  83807. ShadowsOptimization.prototype.getDescription = function () {
  83808. return "Turning shadows on/off";
  83809. };
  83810. /**
  83811. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  83812. * @param scene defines the current scene where to apply this optimization
  83813. * @param optimizer defines the current optimizer
  83814. * @returns true if everything that can be done was applied
  83815. */
  83816. ShadowsOptimization.prototype.apply = function (scene, optimizer) {
  83817. scene.shadowsEnabled = optimizer.isInImprovementMode;
  83818. return true;
  83819. };
  83820. ;
  83821. return ShadowsOptimization;
  83822. }(SceneOptimization));
  83823. BABYLON.ShadowsOptimization = ShadowsOptimization;
  83824. /**
  83825. * Defines an optimization used to turn post-processes off
  83826. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  83827. */
  83828. var PostProcessesOptimization = /** @class */ (function (_super) {
  83829. __extends(PostProcessesOptimization, _super);
  83830. function PostProcessesOptimization() {
  83831. return _super !== null && _super.apply(this, arguments) || this;
  83832. }
  83833. /**
  83834. * Gets a string describing the action executed by the current optimization
  83835. * @return description string
  83836. */
  83837. PostProcessesOptimization.prototype.getDescription = function () {
  83838. return "Turning post-processes on/off";
  83839. };
  83840. /**
  83841. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  83842. * @param scene defines the current scene where to apply this optimization
  83843. * @param optimizer defines the current optimizer
  83844. * @returns true if everything that can be done was applied
  83845. */
  83846. PostProcessesOptimization.prototype.apply = function (scene, optimizer) {
  83847. scene.postProcessesEnabled = optimizer.isInImprovementMode;
  83848. return true;
  83849. };
  83850. ;
  83851. return PostProcessesOptimization;
  83852. }(SceneOptimization));
  83853. BABYLON.PostProcessesOptimization = PostProcessesOptimization;
  83854. /**
  83855. * Defines an optimization used to turn lens flares off
  83856. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  83857. */
  83858. var LensFlaresOptimization = /** @class */ (function (_super) {
  83859. __extends(LensFlaresOptimization, _super);
  83860. function LensFlaresOptimization() {
  83861. return _super !== null && _super.apply(this, arguments) || this;
  83862. }
  83863. /**
  83864. * Gets a string describing the action executed by the current optimization
  83865. * @return description string
  83866. */
  83867. LensFlaresOptimization.prototype.getDescription = function () {
  83868. return "Turning lens flares on/off";
  83869. };
  83870. /**
  83871. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  83872. * @param scene defines the current scene where to apply this optimization
  83873. * @param optimizer defines the current optimizer
  83874. * @returns true if everything that can be done was applied
  83875. */
  83876. LensFlaresOptimization.prototype.apply = function (scene, optimizer) {
  83877. scene.lensFlaresEnabled = optimizer.isInImprovementMode;
  83878. return true;
  83879. };
  83880. ;
  83881. return LensFlaresOptimization;
  83882. }(SceneOptimization));
  83883. BABYLON.LensFlaresOptimization = LensFlaresOptimization;
  83884. /**
  83885. * Defines an optimization based on user defined callback.
  83886. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  83887. */
  83888. var CustomOptimization = /** @class */ (function (_super) {
  83889. __extends(CustomOptimization, _super);
  83890. function CustomOptimization() {
  83891. return _super !== null && _super.apply(this, arguments) || this;
  83892. }
  83893. /**
  83894. * Gets a string describing the action executed by the current optimization
  83895. * @returns description string
  83896. */
  83897. CustomOptimization.prototype.getDescription = function () {
  83898. if (this.onGetDescription) {
  83899. return this.onGetDescription();
  83900. }
  83901. return "Running user defined callback";
  83902. };
  83903. /**
  83904. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  83905. * @param scene defines the current scene where to apply this optimization
  83906. * @param optimizer defines the current optimizer
  83907. * @returns true if everything that can be done was applied
  83908. */
  83909. CustomOptimization.prototype.apply = function (scene, optimizer) {
  83910. if (this.onApply) {
  83911. return this.onApply(scene, optimizer);
  83912. }
  83913. return true;
  83914. };
  83915. ;
  83916. return CustomOptimization;
  83917. }(SceneOptimization));
  83918. BABYLON.CustomOptimization = CustomOptimization;
  83919. /**
  83920. * Defines an optimization used to turn particles off
  83921. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  83922. */
  83923. var ParticlesOptimization = /** @class */ (function (_super) {
  83924. __extends(ParticlesOptimization, _super);
  83925. function ParticlesOptimization() {
  83926. return _super !== null && _super.apply(this, arguments) || this;
  83927. }
  83928. /**
  83929. * Gets a string describing the action executed by the current optimization
  83930. * @return description string
  83931. */
  83932. ParticlesOptimization.prototype.getDescription = function () {
  83933. return "Turning particles on/off";
  83934. };
  83935. /**
  83936. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  83937. * @param scene defines the current scene where to apply this optimization
  83938. * @param optimizer defines the current optimizer
  83939. * @returns true if everything that can be done was applied
  83940. */
  83941. ParticlesOptimization.prototype.apply = function (scene, optimizer) {
  83942. scene.particlesEnabled = optimizer.isInImprovementMode;
  83943. return true;
  83944. };
  83945. ;
  83946. return ParticlesOptimization;
  83947. }(SceneOptimization));
  83948. BABYLON.ParticlesOptimization = ParticlesOptimization;
  83949. /**
  83950. * Defines an optimization used to turn render targets off
  83951. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  83952. */
  83953. var RenderTargetsOptimization = /** @class */ (function (_super) {
  83954. __extends(RenderTargetsOptimization, _super);
  83955. function RenderTargetsOptimization() {
  83956. return _super !== null && _super.apply(this, arguments) || this;
  83957. }
  83958. /**
  83959. * Gets a string describing the action executed by the current optimization
  83960. * @return description string
  83961. */
  83962. RenderTargetsOptimization.prototype.getDescription = function () {
  83963. return "Turning render targets off";
  83964. };
  83965. /**
  83966. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  83967. * @param scene defines the current scene where to apply this optimization
  83968. * @param optimizer defines the current optimizer
  83969. * @returns true if everything that can be done was applied
  83970. */
  83971. RenderTargetsOptimization.prototype.apply = function (scene, optimizer) {
  83972. scene.renderTargetsEnabled = optimizer.isInImprovementMode;
  83973. return true;
  83974. };
  83975. ;
  83976. return RenderTargetsOptimization;
  83977. }(SceneOptimization));
  83978. BABYLON.RenderTargetsOptimization = RenderTargetsOptimization;
  83979. /**
  83980. * Defines an optimization used to merge meshes with compatible materials
  83981. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  83982. */
  83983. var MergeMeshesOptimization = /** @class */ (function (_super) {
  83984. __extends(MergeMeshesOptimization, _super);
  83985. function MergeMeshesOptimization() {
  83986. var _this = _super !== null && _super.apply(this, arguments) || this;
  83987. _this._canBeMerged = function (abstractMesh) {
  83988. if (!(abstractMesh instanceof BABYLON.Mesh)) {
  83989. return false;
  83990. }
  83991. var mesh = abstractMesh;
  83992. if (!mesh.isVisible || !mesh.isEnabled()) {
  83993. return false;
  83994. }
  83995. if (mesh.instances.length > 0) {
  83996. return false;
  83997. }
  83998. if (mesh.skeleton || mesh.hasLODLevels) {
  83999. return false;
  84000. }
  84001. if (mesh.parent) {
  84002. return false;
  84003. }
  84004. return true;
  84005. };
  84006. return _this;
  84007. }
  84008. Object.defineProperty(MergeMeshesOptimization, "UpdateSelectionTree", {
  84009. /**
  84010. * Gets or sets a boolean which defines if optimization octree has to be updated
  84011. */
  84012. get: function () {
  84013. return MergeMeshesOptimization._UpdateSelectionTree;
  84014. },
  84015. /**
  84016. * Gets or sets a boolean which defines if optimization octree has to be updated
  84017. */
  84018. set: function (value) {
  84019. MergeMeshesOptimization._UpdateSelectionTree = value;
  84020. },
  84021. enumerable: true,
  84022. configurable: true
  84023. });
  84024. /**
  84025. * Gets a string describing the action executed by the current optimization
  84026. * @return description string
  84027. */
  84028. MergeMeshesOptimization.prototype.getDescription = function () {
  84029. return "Merging similar meshes together";
  84030. };
  84031. /**
  84032. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  84033. * @param scene defines the current scene where to apply this optimization
  84034. * @param optimizer defines the current optimizer
  84035. * @param updateSelectionTree defines that the selection octree has to be updated (false by default)
  84036. * @returns true if everything that can be done was applied
  84037. */
  84038. MergeMeshesOptimization.prototype.apply = function (scene, optimizer, updateSelectionTree) {
  84039. var globalPool = scene.meshes.slice(0);
  84040. var globalLength = globalPool.length;
  84041. for (var index = 0; index < globalLength; index++) {
  84042. var currentPool = new Array();
  84043. var current = globalPool[index];
  84044. // Checks
  84045. if (!this._canBeMerged(current)) {
  84046. continue;
  84047. }
  84048. currentPool.push(current);
  84049. // Find compatible meshes
  84050. for (var subIndex = index + 1; subIndex < globalLength; subIndex++) {
  84051. var otherMesh = globalPool[subIndex];
  84052. if (!this._canBeMerged(otherMesh)) {
  84053. continue;
  84054. }
  84055. if (otherMesh.material !== current.material) {
  84056. continue;
  84057. }
  84058. if (otherMesh.checkCollisions !== current.checkCollisions) {
  84059. continue;
  84060. }
  84061. currentPool.push(otherMesh);
  84062. globalLength--;
  84063. globalPool.splice(subIndex, 1);
  84064. subIndex--;
  84065. }
  84066. if (currentPool.length < 2) {
  84067. continue;
  84068. }
  84069. // Merge meshes
  84070. BABYLON.Mesh.MergeMeshes(currentPool);
  84071. }
  84072. if (updateSelectionTree != undefined) {
  84073. if (updateSelectionTree) {
  84074. scene.createOrUpdateSelectionOctree();
  84075. }
  84076. }
  84077. else if (MergeMeshesOptimization.UpdateSelectionTree) {
  84078. scene.createOrUpdateSelectionOctree();
  84079. }
  84080. return true;
  84081. };
  84082. ;
  84083. MergeMeshesOptimization._UpdateSelectionTree = false;
  84084. return MergeMeshesOptimization;
  84085. }(SceneOptimization));
  84086. BABYLON.MergeMeshesOptimization = MergeMeshesOptimization;
  84087. /**
  84088. * Defines a list of options used by SceneOptimizer
  84089. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  84090. */
  84091. var SceneOptimizerOptions = /** @class */ (function () {
  84092. /**
  84093. * Creates a new list of options used by SceneOptimizer
  84094. * @param targetFrameRate defines the target frame rate to reach (60 by default)
  84095. * @param trackerDuration defines the interval between two checkes (2000ms by default)
  84096. */
  84097. function SceneOptimizerOptions(
  84098. /**
  84099. * Defines the target frame rate to reach (60 by default)
  84100. */
  84101. targetFrameRate,
  84102. /**
  84103. * Defines the interval between two checkes (2000ms by default)
  84104. */
  84105. trackerDuration) {
  84106. if (targetFrameRate === void 0) { targetFrameRate = 60; }
  84107. if (trackerDuration === void 0) { trackerDuration = 2000; }
  84108. this.targetFrameRate = targetFrameRate;
  84109. this.trackerDuration = trackerDuration;
  84110. /**
  84111. * Gets the list of optimizations to apply
  84112. */
  84113. this.optimizations = new Array();
  84114. }
  84115. /**
  84116. * Add a new optimization
  84117. * @param optimization defines the SceneOptimization to add to the list of active optimizations
  84118. * @returns the current SceneOptimizerOptions
  84119. */
  84120. SceneOptimizerOptions.prototype.addOptimization = function (optimization) {
  84121. this.optimizations.push(optimization);
  84122. return this;
  84123. };
  84124. /**
  84125. * Add a new custom optimization
  84126. * @param onApply defines the callback called to apply the custom optimization (true if everything that can be done was applied)
  84127. * @param onGetDescription defines the callback called to get the description attached with the optimization.
  84128. * @param priority defines the priority of this optimization (0 by default which means first in the list)
  84129. * @returns the current SceneOptimizerOptions
  84130. */
  84131. SceneOptimizerOptions.prototype.addCustomOptimization = function (onApply, onGetDescription, priority) {
  84132. if (priority === void 0) { priority = 0; }
  84133. var optimization = new CustomOptimization(priority);
  84134. optimization.onApply = onApply;
  84135. optimization.onGetDescription = onGetDescription;
  84136. this.optimizations.push(optimization);
  84137. return this;
  84138. };
  84139. /**
  84140. * Creates a list of pre-defined optimizations aimed to reduce the visual impact on the scene
  84141. * @param targetFrameRate defines the target frame rate (60 by default)
  84142. * @returns a SceneOptimizerOptions object
  84143. */
  84144. SceneOptimizerOptions.LowDegradationAllowed = function (targetFrameRate) {
  84145. var result = new SceneOptimizerOptions(targetFrameRate);
  84146. var priority = 0;
  84147. result.addOptimization(new MergeMeshesOptimization(priority));
  84148. result.addOptimization(new ShadowsOptimization(priority));
  84149. result.addOptimization(new LensFlaresOptimization(priority));
  84150. // Next priority
  84151. priority++;
  84152. result.addOptimization(new PostProcessesOptimization(priority));
  84153. result.addOptimization(new ParticlesOptimization(priority));
  84154. // Next priority
  84155. priority++;
  84156. result.addOptimization(new TextureOptimization(priority, 1024));
  84157. return result;
  84158. };
  84159. /**
  84160. * Creates a list of pre-defined optimizations aimed to have a moderate impact on the scene visual
  84161. * @param targetFrameRate defines the target frame rate (60 by default)
  84162. * @returns a SceneOptimizerOptions object
  84163. */
  84164. SceneOptimizerOptions.ModerateDegradationAllowed = function (targetFrameRate) {
  84165. var result = new SceneOptimizerOptions(targetFrameRate);
  84166. var priority = 0;
  84167. result.addOptimization(new MergeMeshesOptimization(priority));
  84168. result.addOptimization(new ShadowsOptimization(priority));
  84169. result.addOptimization(new LensFlaresOptimization(priority));
  84170. // Next priority
  84171. priority++;
  84172. result.addOptimization(new PostProcessesOptimization(priority));
  84173. result.addOptimization(new ParticlesOptimization(priority));
  84174. // Next priority
  84175. priority++;
  84176. result.addOptimization(new TextureOptimization(priority, 512));
  84177. // Next priority
  84178. priority++;
  84179. result.addOptimization(new RenderTargetsOptimization(priority));
  84180. // Next priority
  84181. priority++;
  84182. result.addOptimization(new HardwareScalingOptimization(priority, 2));
  84183. return result;
  84184. };
  84185. /**
  84186. * Creates a list of pre-defined optimizations aimed to have a big impact on the scene visual
  84187. * @param targetFrameRate defines the target frame rate (60 by default)
  84188. * @returns a SceneOptimizerOptions object
  84189. */
  84190. SceneOptimizerOptions.HighDegradationAllowed = function (targetFrameRate) {
  84191. var result = new SceneOptimizerOptions(targetFrameRate);
  84192. var priority = 0;
  84193. result.addOptimization(new MergeMeshesOptimization(priority));
  84194. result.addOptimization(new ShadowsOptimization(priority));
  84195. result.addOptimization(new LensFlaresOptimization(priority));
  84196. // Next priority
  84197. priority++;
  84198. result.addOptimization(new PostProcessesOptimization(priority));
  84199. result.addOptimization(new ParticlesOptimization(priority));
  84200. // Next priority
  84201. priority++;
  84202. result.addOptimization(new TextureOptimization(priority, 256));
  84203. // Next priority
  84204. priority++;
  84205. result.addOptimization(new RenderTargetsOptimization(priority));
  84206. // Next priority
  84207. priority++;
  84208. result.addOptimization(new HardwareScalingOptimization(priority, 4));
  84209. return result;
  84210. };
  84211. return SceneOptimizerOptions;
  84212. }());
  84213. BABYLON.SceneOptimizerOptions = SceneOptimizerOptions;
  84214. /**
  84215. * Class used to run optimizations in order to reach a target frame rate
  84216. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  84217. */
  84218. var SceneOptimizer = /** @class */ (function () {
  84219. /**
  84220. * Creates a new SceneOptimizer
  84221. * @param scene defines the scene to work on
  84222. * @param options defines the options to use with the SceneOptimizer
  84223. * @param autoGeneratePriorities defines if priorities must be generated and not read from SceneOptimization property (true by default)
  84224. * @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)
  84225. */
  84226. function SceneOptimizer(scene, options, autoGeneratePriorities, improvementMode) {
  84227. if (autoGeneratePriorities === void 0) { autoGeneratePriorities = true; }
  84228. if (improvementMode === void 0) { improvementMode = false; }
  84229. var _this = this;
  84230. this._isRunning = false;
  84231. this._currentPriorityLevel = 0;
  84232. this._targetFrameRate = 60;
  84233. this._trackerDuration = 2000;
  84234. this._currentFrameRate = 0;
  84235. this._improvementMode = false;
  84236. /**
  84237. * Defines an observable called when the optimizer reaches the target frame rate
  84238. */
  84239. this.onSuccessObservable = new BABYLON.Observable();
  84240. /**
  84241. * Defines an observable called when the optimizer enables an optimization
  84242. */
  84243. this.onNewOptimizationAppliedObservable = new BABYLON.Observable();
  84244. /**
  84245. * Defines an observable called when the optimizer is not able to reach the target frame rate
  84246. */
  84247. this.onFailureObservable = new BABYLON.Observable();
  84248. if (!options) {
  84249. this._options = new SceneOptimizerOptions();
  84250. }
  84251. else {
  84252. this._options = options;
  84253. }
  84254. if (this._options.targetFrameRate) {
  84255. this._targetFrameRate = this._options.targetFrameRate;
  84256. }
  84257. if (this._options.trackerDuration) {
  84258. this._trackerDuration = this._options.trackerDuration;
  84259. }
  84260. if (autoGeneratePriorities) {
  84261. var priority = 0;
  84262. for (var _i = 0, _a = this._options.optimizations; _i < _a.length; _i++) {
  84263. var optim = _a[_i];
  84264. optim.priority = priority++;
  84265. }
  84266. }
  84267. this._improvementMode = improvementMode;
  84268. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  84269. this._sceneDisposeObserver = this._scene.onDisposeObservable.add(function () {
  84270. _this._sceneDisposeObserver = null;
  84271. _this.dispose();
  84272. });
  84273. }
  84274. Object.defineProperty(SceneOptimizer.prototype, "isInImprovementMode", {
  84275. /**
  84276. * Gets a boolean indicating if the optimizer is in improvement mode
  84277. */
  84278. get: function () {
  84279. return this._improvementMode;
  84280. },
  84281. enumerable: true,
  84282. configurable: true
  84283. });
  84284. Object.defineProperty(SceneOptimizer.prototype, "currentPriorityLevel", {
  84285. /**
  84286. * Gets the current priority level (0 at start)
  84287. */
  84288. get: function () {
  84289. return this._currentPriorityLevel;
  84290. },
  84291. enumerable: true,
  84292. configurable: true
  84293. });
  84294. Object.defineProperty(SceneOptimizer.prototype, "currentFrameRate", {
  84295. /**
  84296. * Gets the current frame rate checked by the SceneOptimizer
  84297. */
  84298. get: function () {
  84299. return this._currentFrameRate;
  84300. },
  84301. enumerable: true,
  84302. configurable: true
  84303. });
  84304. Object.defineProperty(SceneOptimizer.prototype, "targetFrameRate", {
  84305. /**
  84306. * Gets or sets the current target frame rate (60 by default)
  84307. */
  84308. get: function () {
  84309. return this._targetFrameRate;
  84310. },
  84311. /**
  84312. * Gets or sets the current target frame rate (60 by default)
  84313. */
  84314. set: function (value) {
  84315. this._targetFrameRate = value;
  84316. },
  84317. enumerable: true,
  84318. configurable: true
  84319. });
  84320. Object.defineProperty(SceneOptimizer.prototype, "trackerDuration", {
  84321. /**
  84322. * Gets or sets the current interval between two checks (every 2000ms by default)
  84323. */
  84324. get: function () {
  84325. return this._trackerDuration;
  84326. },
  84327. /**
  84328. * Gets or sets the current interval between two checks (every 2000ms by default)
  84329. */
  84330. set: function (value) {
  84331. this._trackerDuration = value;
  84332. },
  84333. enumerable: true,
  84334. configurable: true
  84335. });
  84336. Object.defineProperty(SceneOptimizer.prototype, "optimizations", {
  84337. /**
  84338. * Gets the list of active optimizations
  84339. */
  84340. get: function () {
  84341. return this._options.optimizations;
  84342. },
  84343. enumerable: true,
  84344. configurable: true
  84345. });
  84346. /**
  84347. * Stops the current optimizer
  84348. */
  84349. SceneOptimizer.prototype.stop = function () {
  84350. this._isRunning = false;
  84351. };
  84352. /**
  84353. * Reset the optimizer to initial step (current priority level = 0)
  84354. */
  84355. SceneOptimizer.prototype.reset = function () {
  84356. this._currentPriorityLevel = 0;
  84357. };
  84358. /**
  84359. * Start the optimizer. By default it will try to reach a specific framerate
  84360. * but if the optimizer is set with improvementMode === true then it will run all optimiatiation while frame rate is above the target frame rate
  84361. */
  84362. SceneOptimizer.prototype.start = function () {
  84363. var _this = this;
  84364. if (this._isRunning) {
  84365. return;
  84366. }
  84367. this._isRunning = true;
  84368. // Let's wait for the scene to be ready before running our check
  84369. this._scene.executeWhenReady(function () {
  84370. setTimeout(function () {
  84371. _this._checkCurrentState();
  84372. }, _this._trackerDuration);
  84373. });
  84374. };
  84375. SceneOptimizer.prototype._checkCurrentState = function () {
  84376. var _this = this;
  84377. if (!this._isRunning) {
  84378. return;
  84379. }
  84380. var scene = this._scene;
  84381. var options = this._options;
  84382. this._currentFrameRate = Math.round(scene.getEngine().getFps());
  84383. if (this._improvementMode && this._currentFrameRate <= this._targetFrameRate ||
  84384. !this._improvementMode && this._currentFrameRate >= this._targetFrameRate) {
  84385. this._isRunning = false;
  84386. this.onSuccessObservable.notifyObservers(this);
  84387. return;
  84388. }
  84389. // Apply current level of optimizations
  84390. var allDone = true;
  84391. var noOptimizationApplied = true;
  84392. for (var index = 0; index < options.optimizations.length; index++) {
  84393. var optimization = options.optimizations[index];
  84394. if (optimization.priority === this._currentPriorityLevel) {
  84395. noOptimizationApplied = false;
  84396. allDone = allDone && optimization.apply(scene, this);
  84397. this.onNewOptimizationAppliedObservable.notifyObservers(optimization);
  84398. }
  84399. }
  84400. // If no optimization was applied, this is a failure :(
  84401. if (noOptimizationApplied) {
  84402. this._isRunning = false;
  84403. this.onFailureObservable.notifyObservers(this);
  84404. return;
  84405. }
  84406. // If all optimizations were done, move to next level
  84407. if (allDone) {
  84408. this._currentPriorityLevel++;
  84409. }
  84410. // Let's the system running for a specific amount of time before checking FPS
  84411. scene.executeWhenReady(function () {
  84412. setTimeout(function () {
  84413. _this._checkCurrentState();
  84414. }, _this._trackerDuration);
  84415. });
  84416. };
  84417. /**
  84418. * Release all resources
  84419. */
  84420. SceneOptimizer.prototype.dispose = function () {
  84421. this.stop();
  84422. this.onSuccessObservable.clear();
  84423. this.onFailureObservable.clear();
  84424. this.onNewOptimizationAppliedObservable.clear();
  84425. if (this._sceneDisposeObserver) {
  84426. this._scene.onDisposeObservable.remove(this._sceneDisposeObserver);
  84427. }
  84428. };
  84429. /**
  84430. * Helper function to create a SceneOptimizer with one single line of code
  84431. * @param scene defines the scene to work on
  84432. * @param options defines the options to use with the SceneOptimizer
  84433. * @param onSuccess defines a callback to call on success
  84434. * @param onFailure defines a callback to call on failure
  84435. * @returns the new SceneOptimizer object
  84436. */
  84437. SceneOptimizer.OptimizeAsync = function (scene, options, onSuccess, onFailure) {
  84438. var optimizer = new SceneOptimizer(scene, options || SceneOptimizerOptions.ModerateDegradationAllowed(), false);
  84439. if (onSuccess) {
  84440. optimizer.onSuccessObservable.add(function () {
  84441. onSuccess();
  84442. });
  84443. }
  84444. if (onFailure) {
  84445. optimizer.onFailureObservable.add(function () {
  84446. onFailure();
  84447. });
  84448. }
  84449. optimizer.start();
  84450. return optimizer;
  84451. };
  84452. return SceneOptimizer;
  84453. }());
  84454. BABYLON.SceneOptimizer = SceneOptimizer;
  84455. })(BABYLON || (BABYLON = {}));
  84456. //# sourceMappingURL=babylon.sceneOptimizer.js.map
  84457. var BABYLON;
  84458. (function (BABYLON) {
  84459. var OutlineRenderer = /** @class */ (function () {
  84460. function OutlineRenderer(scene) {
  84461. this.zOffset = 1;
  84462. this._scene = scene;
  84463. }
  84464. OutlineRenderer.prototype.render = function (subMesh, batch, useOverlay) {
  84465. var _this = this;
  84466. if (useOverlay === void 0) { useOverlay = false; }
  84467. var scene = this._scene;
  84468. var engine = this._scene.getEngine();
  84469. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  84470. if (!this.isReady(subMesh, hardwareInstancedRendering)) {
  84471. return;
  84472. }
  84473. var mesh = subMesh.getRenderingMesh();
  84474. var material = subMesh.getMaterial();
  84475. if (!material || !scene.activeCamera) {
  84476. return;
  84477. }
  84478. engine.enableEffect(this._effect);
  84479. // Logarithmic depth
  84480. if (material.useLogarithmicDepth) {
  84481. this._effect.setFloat("logarithmicDepthConstant", 2.0 / (Math.log(scene.activeCamera.maxZ + 1.0) / Math.LN2));
  84482. }
  84483. this._effect.setFloat("offset", useOverlay ? 0 : mesh.outlineWidth);
  84484. this._effect.setColor4("color", useOverlay ? mesh.overlayColor : mesh.outlineColor, useOverlay ? mesh.overlayAlpha : material.alpha);
  84485. this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  84486. // Bones
  84487. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  84488. this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  84489. }
  84490. mesh._bind(subMesh, this._effect, BABYLON.Material.TriangleFillMode);
  84491. // Alpha test
  84492. if (material && material.needAlphaTesting()) {
  84493. var alphaTexture = material.getAlphaTestTexture();
  84494. if (alphaTexture) {
  84495. this._effect.setTexture("diffuseSampler", alphaTexture);
  84496. this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  84497. }
  84498. }
  84499. engine.setZOffset(-this.zOffset);
  84500. mesh._processRendering(subMesh, this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { _this._effect.setMatrix("world", world); });
  84501. engine.setZOffset(0);
  84502. };
  84503. OutlineRenderer.prototype.isReady = function (subMesh, useInstances) {
  84504. var defines = [];
  84505. var attribs = [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.NormalKind];
  84506. var mesh = subMesh.getMesh();
  84507. var material = subMesh.getMaterial();
  84508. if (material) {
  84509. // Alpha test
  84510. if (material.needAlphaTesting()) {
  84511. defines.push("#define ALPHATEST");
  84512. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  84513. attribs.push(BABYLON.VertexBuffer.UVKind);
  84514. defines.push("#define UV1");
  84515. }
  84516. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  84517. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  84518. defines.push("#define UV2");
  84519. }
  84520. }
  84521. //Logarithmic depth
  84522. if (material.useLogarithmicDepth) {
  84523. defines.push("#define LOGARITHMICDEPTH");
  84524. }
  84525. }
  84526. // Bones
  84527. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  84528. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  84529. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  84530. if (mesh.numBoneInfluencers > 4) {
  84531. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  84532. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  84533. }
  84534. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  84535. defines.push("#define BonesPerMesh " + (mesh.skeleton ? mesh.skeleton.bones.length + 1 : 0));
  84536. }
  84537. else {
  84538. defines.push("#define NUM_BONE_INFLUENCERS 0");
  84539. }
  84540. // Instances
  84541. if (useInstances) {
  84542. defines.push("#define INSTANCES");
  84543. attribs.push("world0");
  84544. attribs.push("world1");
  84545. attribs.push("world2");
  84546. attribs.push("world3");
  84547. }
  84548. // Get correct effect
  84549. var join = defines.join("\n");
  84550. if (this._cachedDefines !== join) {
  84551. this._cachedDefines = join;
  84552. this._effect = this._scene.getEngine().createEffect("outline", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "offset", "color", "logarithmicDepthConstant"], ["diffuseSampler"], join);
  84553. }
  84554. return this._effect.isReady();
  84555. };
  84556. return OutlineRenderer;
  84557. }());
  84558. BABYLON.OutlineRenderer = OutlineRenderer;
  84559. })(BABYLON || (BABYLON = {}));
  84560. //# sourceMappingURL=babylon.outlineRenderer.js.map
  84561. var BABYLON;
  84562. (function (BABYLON) {
  84563. var FaceAdjacencies = /** @class */ (function () {
  84564. function FaceAdjacencies() {
  84565. this.edges = new Array();
  84566. this.edgesConnectedCount = 0;
  84567. }
  84568. return FaceAdjacencies;
  84569. }());
  84570. var EdgesRenderer = /** @class */ (function () {
  84571. // Beware when you use this class with complex objects as the adjacencies computation can be really long
  84572. function EdgesRenderer(source, epsilon, checkVerticesInsteadOfIndices) {
  84573. if (epsilon === void 0) { epsilon = 0.95; }
  84574. if (checkVerticesInsteadOfIndices === void 0) { checkVerticesInsteadOfIndices = false; }
  84575. this.edgesWidthScalerForOrthographic = 1000.0;
  84576. this.edgesWidthScalerForPerspective = 50.0;
  84577. this._linesPositions = new Array();
  84578. this._linesNormals = new Array();
  84579. this._linesIndices = new Array();
  84580. this._buffers = {};
  84581. this._checkVerticesInsteadOfIndices = false;
  84582. this._source = source;
  84583. this._checkVerticesInsteadOfIndices = checkVerticesInsteadOfIndices;
  84584. this._epsilon = epsilon;
  84585. this._prepareRessources();
  84586. this._generateEdgesLines();
  84587. }
  84588. EdgesRenderer.prototype._prepareRessources = function () {
  84589. if (this._lineShader) {
  84590. return;
  84591. }
  84592. this._lineShader = new BABYLON.ShaderMaterial("lineShader", this._source.getScene(), "line", {
  84593. attributes: ["position", "normal"],
  84594. uniforms: ["worldViewProjection", "color", "width", "aspectRatio"]
  84595. });
  84596. this._lineShader.disableDepthWrite = true;
  84597. this._lineShader.backFaceCulling = false;
  84598. };
  84599. EdgesRenderer.prototype._rebuild = function () {
  84600. var buffer = this._buffers[BABYLON.VertexBuffer.PositionKind];
  84601. if (buffer) {
  84602. buffer._rebuild();
  84603. }
  84604. buffer = this._buffers[BABYLON.VertexBuffer.NormalKind];
  84605. if (buffer) {
  84606. buffer._rebuild();
  84607. }
  84608. var scene = this._source.getScene();
  84609. var engine = scene.getEngine();
  84610. this._ib = engine.createIndexBuffer(this._linesIndices);
  84611. };
  84612. EdgesRenderer.prototype.dispose = function () {
  84613. var buffer = this._buffers[BABYLON.VertexBuffer.PositionKind];
  84614. if (buffer) {
  84615. buffer.dispose();
  84616. this._buffers[BABYLON.VertexBuffer.PositionKind] = null;
  84617. }
  84618. buffer = this._buffers[BABYLON.VertexBuffer.NormalKind];
  84619. if (buffer) {
  84620. buffer.dispose();
  84621. this._buffers[BABYLON.VertexBuffer.NormalKind] = null;
  84622. }
  84623. this._source.getScene().getEngine()._releaseBuffer(this._ib);
  84624. this._lineShader.dispose();
  84625. };
  84626. EdgesRenderer.prototype._processEdgeForAdjacencies = function (pa, pb, p0, p1, p2) {
  84627. if (pa === p0 && pb === p1 || pa === p1 && pb === p0) {
  84628. return 0;
  84629. }
  84630. if (pa === p1 && pb === p2 || pa === p2 && pb === p1) {
  84631. return 1;
  84632. }
  84633. if (pa === p2 && pb === p0 || pa === p0 && pb === p2) {
  84634. return 2;
  84635. }
  84636. return -1;
  84637. };
  84638. EdgesRenderer.prototype._processEdgeForAdjacenciesWithVertices = function (pa, pb, p0, p1, p2) {
  84639. if (pa.equalsWithEpsilon(p0) && pb.equalsWithEpsilon(p1) || pa.equalsWithEpsilon(p1) && pb.equalsWithEpsilon(p0)) {
  84640. return 0;
  84641. }
  84642. if (pa.equalsWithEpsilon(p1) && pb.equalsWithEpsilon(p2) || pa.equalsWithEpsilon(p2) && pb.equalsWithEpsilon(p1)) {
  84643. return 1;
  84644. }
  84645. if (pa.equalsWithEpsilon(p2) && pb.equalsWithEpsilon(p0) || pa.equalsWithEpsilon(p0) && pb.equalsWithEpsilon(p2)) {
  84646. return 2;
  84647. }
  84648. return -1;
  84649. };
  84650. EdgesRenderer.prototype._checkEdge = function (faceIndex, edge, faceNormals, p0, p1) {
  84651. var needToCreateLine;
  84652. if (edge === undefined) {
  84653. needToCreateLine = true;
  84654. }
  84655. else {
  84656. var dotProduct = BABYLON.Vector3.Dot(faceNormals[faceIndex], faceNormals[edge]);
  84657. needToCreateLine = dotProduct < this._epsilon;
  84658. }
  84659. if (needToCreateLine) {
  84660. var offset = this._linesPositions.length / 3;
  84661. var normal = p0.subtract(p1);
  84662. normal.normalize();
  84663. // Positions
  84664. this._linesPositions.push(p0.x);
  84665. this._linesPositions.push(p0.y);
  84666. this._linesPositions.push(p0.z);
  84667. this._linesPositions.push(p0.x);
  84668. this._linesPositions.push(p0.y);
  84669. this._linesPositions.push(p0.z);
  84670. this._linesPositions.push(p1.x);
  84671. this._linesPositions.push(p1.y);
  84672. this._linesPositions.push(p1.z);
  84673. this._linesPositions.push(p1.x);
  84674. this._linesPositions.push(p1.y);
  84675. this._linesPositions.push(p1.z);
  84676. // Normals
  84677. this._linesNormals.push(p1.x);
  84678. this._linesNormals.push(p1.y);
  84679. this._linesNormals.push(p1.z);
  84680. this._linesNormals.push(-1);
  84681. this._linesNormals.push(p1.x);
  84682. this._linesNormals.push(p1.y);
  84683. this._linesNormals.push(p1.z);
  84684. this._linesNormals.push(1);
  84685. this._linesNormals.push(p0.x);
  84686. this._linesNormals.push(p0.y);
  84687. this._linesNormals.push(p0.z);
  84688. this._linesNormals.push(-1);
  84689. this._linesNormals.push(p0.x);
  84690. this._linesNormals.push(p0.y);
  84691. this._linesNormals.push(p0.z);
  84692. this._linesNormals.push(1);
  84693. // Indices
  84694. this._linesIndices.push(offset);
  84695. this._linesIndices.push(offset + 1);
  84696. this._linesIndices.push(offset + 2);
  84697. this._linesIndices.push(offset);
  84698. this._linesIndices.push(offset + 2);
  84699. this._linesIndices.push(offset + 3);
  84700. }
  84701. };
  84702. EdgesRenderer.prototype._generateEdgesLines = function () {
  84703. var positions = this._source.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  84704. var indices = this._source.getIndices();
  84705. if (!indices || !positions) {
  84706. return;
  84707. }
  84708. // First let's find adjacencies
  84709. var adjacencies = new Array();
  84710. var faceNormals = new Array();
  84711. var index;
  84712. var faceAdjacencies;
  84713. // Prepare faces
  84714. for (index = 0; index < indices.length; index += 3) {
  84715. faceAdjacencies = new FaceAdjacencies();
  84716. var p0Index = indices[index];
  84717. var p1Index = indices[index + 1];
  84718. var p2Index = indices[index + 2];
  84719. faceAdjacencies.p0 = new BABYLON.Vector3(positions[p0Index * 3], positions[p0Index * 3 + 1], positions[p0Index * 3 + 2]);
  84720. faceAdjacencies.p1 = new BABYLON.Vector3(positions[p1Index * 3], positions[p1Index * 3 + 1], positions[p1Index * 3 + 2]);
  84721. faceAdjacencies.p2 = new BABYLON.Vector3(positions[p2Index * 3], positions[p2Index * 3 + 1], positions[p2Index * 3 + 2]);
  84722. var faceNormal = BABYLON.Vector3.Cross(faceAdjacencies.p1.subtract(faceAdjacencies.p0), faceAdjacencies.p2.subtract(faceAdjacencies.p1));
  84723. faceNormal.normalize();
  84724. faceNormals.push(faceNormal);
  84725. adjacencies.push(faceAdjacencies);
  84726. }
  84727. // Scan
  84728. for (index = 0; index < adjacencies.length; index++) {
  84729. faceAdjacencies = adjacencies[index];
  84730. for (var otherIndex = index + 1; otherIndex < adjacencies.length; otherIndex++) {
  84731. var otherFaceAdjacencies = adjacencies[otherIndex];
  84732. if (faceAdjacencies.edgesConnectedCount === 3) {
  84733. break;
  84734. }
  84735. if (otherFaceAdjacencies.edgesConnectedCount === 3) {
  84736. continue;
  84737. }
  84738. var otherP0 = indices[otherIndex * 3];
  84739. var otherP1 = indices[otherIndex * 3 + 1];
  84740. var otherP2 = indices[otherIndex * 3 + 2];
  84741. for (var edgeIndex = 0; edgeIndex < 3; edgeIndex++) {
  84742. var otherEdgeIndex = 0;
  84743. if (faceAdjacencies.edges[edgeIndex] !== undefined) {
  84744. continue;
  84745. }
  84746. switch (edgeIndex) {
  84747. case 0:
  84748. if (this._checkVerticesInsteadOfIndices) {
  84749. otherEdgeIndex = this._processEdgeForAdjacenciesWithVertices(faceAdjacencies.p0, faceAdjacencies.p1, otherFaceAdjacencies.p0, otherFaceAdjacencies.p1, otherFaceAdjacencies.p2);
  84750. }
  84751. else {
  84752. otherEdgeIndex = this._processEdgeForAdjacencies(indices[index * 3], indices[index * 3 + 1], otherP0, otherP1, otherP2);
  84753. }
  84754. break;
  84755. case 1:
  84756. if (this._checkVerticesInsteadOfIndices) {
  84757. otherEdgeIndex = this._processEdgeForAdjacenciesWithVertices(faceAdjacencies.p1, faceAdjacencies.p2, otherFaceAdjacencies.p0, otherFaceAdjacencies.p1, otherFaceAdjacencies.p2);
  84758. }
  84759. else {
  84760. otherEdgeIndex = this._processEdgeForAdjacencies(indices[index * 3 + 1], indices[index * 3 + 2], otherP0, otherP1, otherP2);
  84761. }
  84762. break;
  84763. case 2:
  84764. if (this._checkVerticesInsteadOfIndices) {
  84765. otherEdgeIndex = this._processEdgeForAdjacenciesWithVertices(faceAdjacencies.p2, faceAdjacencies.p0, otherFaceAdjacencies.p0, otherFaceAdjacencies.p1, otherFaceAdjacencies.p2);
  84766. }
  84767. else {
  84768. otherEdgeIndex = this._processEdgeForAdjacencies(indices[index * 3 + 2], indices[index * 3], otherP0, otherP1, otherP2);
  84769. }
  84770. break;
  84771. }
  84772. if (otherEdgeIndex === -1) {
  84773. continue;
  84774. }
  84775. faceAdjacencies.edges[edgeIndex] = otherIndex;
  84776. otherFaceAdjacencies.edges[otherEdgeIndex] = index;
  84777. faceAdjacencies.edgesConnectedCount++;
  84778. otherFaceAdjacencies.edgesConnectedCount++;
  84779. if (faceAdjacencies.edgesConnectedCount === 3) {
  84780. break;
  84781. }
  84782. }
  84783. }
  84784. }
  84785. // Create lines
  84786. for (index = 0; index < adjacencies.length; index++) {
  84787. // 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
  84788. var current = adjacencies[index];
  84789. this._checkEdge(index, current.edges[0], faceNormals, current.p0, current.p1);
  84790. this._checkEdge(index, current.edges[1], faceNormals, current.p1, current.p2);
  84791. this._checkEdge(index, current.edges[2], faceNormals, current.p2, current.p0);
  84792. }
  84793. // Merge into a single mesh
  84794. var engine = this._source.getScene().getEngine();
  84795. this._buffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(engine, this._linesPositions, BABYLON.VertexBuffer.PositionKind, false);
  84796. this._buffers[BABYLON.VertexBuffer.NormalKind] = new BABYLON.VertexBuffer(engine, this._linesNormals, BABYLON.VertexBuffer.NormalKind, false, false, 4);
  84797. this._ib = engine.createIndexBuffer(this._linesIndices);
  84798. this._indicesCount = this._linesIndices.length;
  84799. };
  84800. EdgesRenderer.prototype.render = function () {
  84801. var scene = this._source.getScene();
  84802. if (!this._lineShader.isReady() || !scene.activeCamera) {
  84803. return;
  84804. }
  84805. var engine = scene.getEngine();
  84806. this._lineShader._preBind();
  84807. // VBOs
  84808. engine.bindBuffers(this._buffers, this._ib, this._lineShader.getEffect());
  84809. scene.resetCachedMaterial();
  84810. this._lineShader.setColor4("color", this._source.edgesColor);
  84811. if (scene.activeCamera.mode === BABYLON.Camera.ORTHOGRAPHIC_CAMERA) {
  84812. this._lineShader.setFloat("width", this._source.edgesWidth / this.edgesWidthScalerForOrthographic);
  84813. }
  84814. else {
  84815. this._lineShader.setFloat("width", this._source.edgesWidth / this.edgesWidthScalerForPerspective);
  84816. }
  84817. this._lineShader.setFloat("aspectRatio", engine.getAspectRatio(scene.activeCamera));
  84818. this._lineShader.bind(this._source.getWorldMatrix());
  84819. // Draw order
  84820. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, this._indicesCount);
  84821. this._lineShader.unbind();
  84822. engine.setDepthWrite(true);
  84823. };
  84824. return EdgesRenderer;
  84825. }());
  84826. BABYLON.EdgesRenderer = EdgesRenderer;
  84827. })(BABYLON || (BABYLON = {}));
  84828. //# sourceMappingURL=babylon.edgesRenderer.js.map
  84829. var __assign = (this && this.__assign) || Object.assign || function(t) {
  84830. for (var s, i = 1, n = arguments.length; i < n; i++) {
  84831. s = arguments[i];
  84832. for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
  84833. t[p] = s[p];
  84834. }
  84835. return t;
  84836. };
  84837. var BABYLON;
  84838. (function (BABYLON) {
  84839. /**
  84840. * The effect layer Helps adding post process effect blended with the main pass.
  84841. *
  84842. * This can be for instance use to generate glow or higlight effects on the scene.
  84843. *
  84844. * The effect layer class can not be used directly and is intented to inherited from to be
  84845. * customized per effects.
  84846. */
  84847. var EffectLayer = /** @class */ (function () {
  84848. /**
  84849. * Instantiates a new effect Layer and references it in the scene.
  84850. * @param name The name of the layer
  84851. * @param scene The scene to use the layer in
  84852. */
  84853. function EffectLayer(
  84854. /** The Friendly of the effect in the scene */
  84855. name, scene) {
  84856. this.name = name;
  84857. this._vertexBuffers = {};
  84858. this._maxSize = 0;
  84859. this._mainTextureDesiredSize = { width: 0, height: 0 };
  84860. this._shouldRender = true;
  84861. this._postProcesses = [];
  84862. this._textures = [];
  84863. this._emissiveTextureAndColor = { texture: null, color: new BABYLON.Color4() };
  84864. /**
  84865. * The clear color of the texture used to generate the glow map.
  84866. */
  84867. this.neutralColor = new BABYLON.Color4();
  84868. /**
  84869. * Specifies wether the highlight layer is enabled or not.
  84870. */
  84871. this.isEnabled = true;
  84872. /**
  84873. * An event triggered when the effect layer has been disposed.
  84874. */
  84875. this.onDisposeObservable = new BABYLON.Observable();
  84876. /**
  84877. * An event triggered when the effect layer is about rendering the main texture with the glowy parts.
  84878. */
  84879. this.onBeforeRenderMainTextureObservable = new BABYLON.Observable();
  84880. /**
  84881. * An event triggered when the generated texture is being merged in the scene.
  84882. */
  84883. this.onBeforeComposeObservable = new BABYLON.Observable();
  84884. /**
  84885. * An event triggered when the generated texture has been merged in the scene.
  84886. */
  84887. this.onAfterComposeObservable = new BABYLON.Observable();
  84888. /**
  84889. * An event triggered when the efffect layer changes its size.
  84890. */
  84891. this.onSizeChangedObservable = new BABYLON.Observable();
  84892. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  84893. this._engine = scene.getEngine();
  84894. this._maxSize = this._engine.getCaps().maxTextureSize;
  84895. this._scene.effectLayers.push(this);
  84896. // Generate Buffers
  84897. this._generateIndexBuffer();
  84898. this._genrateVertexBuffer();
  84899. }
  84900. Object.defineProperty(EffectLayer.prototype, "camera", {
  84901. /**
  84902. * Gets the camera attached to the layer.
  84903. */
  84904. get: function () {
  84905. return this._effectLayerOptions.camera;
  84906. },
  84907. enumerable: true,
  84908. configurable: true
  84909. });
  84910. /**
  84911. * Initializes the effect layer with the required options.
  84912. * @param options Sets of none mandatory options to use with the layer (see IEffectLayerOptions for more information)
  84913. */
  84914. EffectLayer.prototype._init = function (options) {
  84915. // Adapt options
  84916. this._effectLayerOptions = __assign({ mainTextureRatio: 0.5, alphaBlendingMode: BABYLON.Engine.ALPHA_COMBINE, camera: null }, options);
  84917. this._setMainTextureSize();
  84918. this._createMainTexture();
  84919. this._createTextureAndPostProcesses();
  84920. this._mergeEffect = this._createMergeEffect();
  84921. };
  84922. /**
  84923. * Generates the index buffer of the full screen quad blending to the main canvas.
  84924. */
  84925. EffectLayer.prototype._generateIndexBuffer = function () {
  84926. // Indices
  84927. var indices = [];
  84928. indices.push(0);
  84929. indices.push(1);
  84930. indices.push(2);
  84931. indices.push(0);
  84932. indices.push(2);
  84933. indices.push(3);
  84934. this._indexBuffer = this._engine.createIndexBuffer(indices);
  84935. };
  84936. /**
  84937. * Generates the vertex buffer of the full screen quad blending to the main canvas.
  84938. */
  84939. EffectLayer.prototype._genrateVertexBuffer = function () {
  84940. // VBO
  84941. var vertices = [];
  84942. vertices.push(1, 1);
  84943. vertices.push(-1, 1);
  84944. vertices.push(-1, -1);
  84945. vertices.push(1, -1);
  84946. var vertexBuffer = new BABYLON.VertexBuffer(this._engine, vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  84947. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = vertexBuffer;
  84948. };
  84949. /**
  84950. * Sets the main texture desired size which is the closest power of two
  84951. * of the engine canvas size.
  84952. */
  84953. EffectLayer.prototype._setMainTextureSize = function () {
  84954. if (this._effectLayerOptions.mainTextureFixedSize) {
  84955. this._mainTextureDesiredSize.width = this._effectLayerOptions.mainTextureFixedSize;
  84956. this._mainTextureDesiredSize.height = this._effectLayerOptions.mainTextureFixedSize;
  84957. }
  84958. else {
  84959. this._mainTextureDesiredSize.width = this._engine.getRenderWidth() * this._effectLayerOptions.mainTextureRatio;
  84960. this._mainTextureDesiredSize.height = this._engine.getRenderHeight() * this._effectLayerOptions.mainTextureRatio;
  84961. this._mainTextureDesiredSize.width = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(this._mainTextureDesiredSize.width, this._maxSize) : this._mainTextureDesiredSize.width;
  84962. this._mainTextureDesiredSize.height = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(this._mainTextureDesiredSize.height, this._maxSize) : this._mainTextureDesiredSize.height;
  84963. }
  84964. this._mainTextureDesiredSize.width = Math.floor(this._mainTextureDesiredSize.width);
  84965. this._mainTextureDesiredSize.height = Math.floor(this._mainTextureDesiredSize.height);
  84966. };
  84967. /**
  84968. * Creates the main texture for the effect layer.
  84969. */
  84970. EffectLayer.prototype._createMainTexture = function () {
  84971. var _this = this;
  84972. this._mainTexture = new BABYLON.RenderTargetTexture("HighlightLayerMainRTT", {
  84973. width: this._mainTextureDesiredSize.width,
  84974. height: this._mainTextureDesiredSize.height
  84975. }, this._scene, false, true, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  84976. this._mainTexture.activeCamera = this._effectLayerOptions.camera;
  84977. this._mainTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  84978. this._mainTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  84979. this._mainTexture.anisotropicFilteringLevel = 1;
  84980. this._mainTexture.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  84981. this._mainTexture.renderParticles = false;
  84982. this._mainTexture.renderList = null;
  84983. this._mainTexture.ignoreCameraViewport = true;
  84984. // Custom render function
  84985. this._mainTexture.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes) {
  84986. _this.onBeforeRenderMainTextureObservable.notifyObservers(_this);
  84987. var index;
  84988. var engine = _this._scene.getEngine();
  84989. if (depthOnlySubMeshes.length) {
  84990. engine.setColorWrite(false);
  84991. for (index = 0; index < depthOnlySubMeshes.length; index++) {
  84992. _this._renderSubMesh(depthOnlySubMeshes.data[index]);
  84993. }
  84994. engine.setColorWrite(true);
  84995. }
  84996. for (index = 0; index < opaqueSubMeshes.length; index++) {
  84997. _this._renderSubMesh(opaqueSubMeshes.data[index]);
  84998. }
  84999. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  85000. _this._renderSubMesh(alphaTestSubMeshes.data[index]);
  85001. }
  85002. for (index = 0; index < transparentSubMeshes.length; index++) {
  85003. _this._renderSubMesh(transparentSubMeshes.data[index]);
  85004. }
  85005. };
  85006. this._mainTexture.onClearObservable.add(function (engine) {
  85007. engine.clear(_this.neutralColor, true, true, true);
  85008. });
  85009. };
  85010. /**
  85011. * Checks for the readiness of the element composing the layer.
  85012. * @param subMesh the mesh to check for
  85013. * @param useInstances specify wether or not to use instances to render the mesh
  85014. * @param emissiveTexture the associated emissive texture used to generate the glow
  85015. * @return true if ready otherwise, false
  85016. */
  85017. EffectLayer.prototype._isReady = function (subMesh, useInstances, emissiveTexture) {
  85018. var material = subMesh.getMaterial();
  85019. if (!material) {
  85020. return false;
  85021. }
  85022. if (!material.isReady(subMesh.getMesh(), useInstances)) {
  85023. return false;
  85024. }
  85025. var defines = [];
  85026. var attribs = [BABYLON.VertexBuffer.PositionKind];
  85027. var mesh = subMesh.getMesh();
  85028. var uv1 = false;
  85029. var uv2 = false;
  85030. // Alpha test
  85031. if (material && material.needAlphaTesting()) {
  85032. var alphaTexture = material.getAlphaTestTexture();
  85033. if (alphaTexture) {
  85034. defines.push("#define ALPHATEST");
  85035. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind) &&
  85036. alphaTexture.coordinatesIndex === 1) {
  85037. defines.push("#define DIFFUSEUV2");
  85038. uv2 = true;
  85039. }
  85040. else if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  85041. defines.push("#define DIFFUSEUV1");
  85042. uv1 = true;
  85043. }
  85044. }
  85045. }
  85046. // Emissive
  85047. if (emissiveTexture) {
  85048. defines.push("#define EMISSIVE");
  85049. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind) &&
  85050. emissiveTexture.coordinatesIndex === 1) {
  85051. defines.push("#define EMISSIVEUV2");
  85052. uv2 = true;
  85053. }
  85054. else if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  85055. defines.push("#define EMISSIVEUV1");
  85056. uv1 = true;
  85057. }
  85058. }
  85059. if (uv1) {
  85060. attribs.push(BABYLON.VertexBuffer.UVKind);
  85061. defines.push("#define UV1");
  85062. }
  85063. if (uv2) {
  85064. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  85065. defines.push("#define UV2");
  85066. }
  85067. // Bones
  85068. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  85069. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  85070. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  85071. if (mesh.numBoneInfluencers > 4) {
  85072. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  85073. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  85074. }
  85075. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  85076. defines.push("#define BonesPerMesh " + (mesh.skeleton ? (mesh.skeleton.bones.length + 1) : 0));
  85077. }
  85078. else {
  85079. defines.push("#define NUM_BONE_INFLUENCERS 0");
  85080. }
  85081. // Instances
  85082. if (useInstances) {
  85083. defines.push("#define INSTANCES");
  85084. attribs.push("world0");
  85085. attribs.push("world1");
  85086. attribs.push("world2");
  85087. attribs.push("world3");
  85088. }
  85089. // Get correct effect
  85090. var join = defines.join("\n");
  85091. if (this._cachedDefines !== join) {
  85092. this._cachedDefines = join;
  85093. this._effectLayerMapGenerationEffect = this._scene.getEngine().createEffect("glowMapGeneration", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "color", "emissiveMatrix"], ["diffuseSampler", "emissiveSampler"], join);
  85094. }
  85095. return this._effectLayerMapGenerationEffect.isReady();
  85096. };
  85097. /**
  85098. * Renders the glowing part of the scene by blending the blurred glowing meshes on top of the rendered scene.
  85099. */
  85100. EffectLayer.prototype.render = function () {
  85101. var currentEffect = this._mergeEffect;
  85102. // Check
  85103. if (!currentEffect.isReady())
  85104. return;
  85105. for (var i = 0; i < this._postProcesses.length; i++) {
  85106. if (!this._postProcesses[i].isReady()) {
  85107. return;
  85108. }
  85109. }
  85110. var engine = this._scene.getEngine();
  85111. this.onBeforeComposeObservable.notifyObservers(this);
  85112. // Render
  85113. engine.enableEffect(currentEffect);
  85114. engine.setState(false);
  85115. // VBOs
  85116. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, currentEffect);
  85117. // Cache
  85118. var previousAlphaMode = engine.getAlphaMode();
  85119. // Go Blend.
  85120. engine.setAlphaMode(this._effectLayerOptions.alphaBlendingMode);
  85121. // Blends the map on the main canvas.
  85122. this._internalRender(currentEffect);
  85123. // Restore Alpha
  85124. engine.setAlphaMode(previousAlphaMode);
  85125. this.onAfterComposeObservable.notifyObservers(this);
  85126. // Handle size changes.
  85127. var size = this._mainTexture.getSize();
  85128. this._setMainTextureSize();
  85129. if (size.width !== this._mainTextureDesiredSize.width || size.height !== this._mainTextureDesiredSize.height) {
  85130. // Recreate RTT and post processes on size change.
  85131. this.onSizeChangedObservable.notifyObservers(this);
  85132. this._disposeTextureAndPostProcesses();
  85133. this._createMainTexture();
  85134. this._createTextureAndPostProcesses();
  85135. }
  85136. };
  85137. /**
  85138. * Determine if a given mesh will be used in the current effect.
  85139. * @param mesh mesh to test
  85140. * @returns true if the mesh will be used
  85141. */
  85142. EffectLayer.prototype.hasMesh = function (mesh) {
  85143. return true;
  85144. };
  85145. /**
  85146. * Returns true if the layer contains information to display, otherwise false.
  85147. * @returns true if the glow layer should be rendered
  85148. */
  85149. EffectLayer.prototype.shouldRender = function () {
  85150. return this.isEnabled && this._shouldRender;
  85151. };
  85152. /**
  85153. * Returns true if the mesh should render, otherwise false.
  85154. * @param mesh The mesh to render
  85155. * @returns true if it should render otherwise false
  85156. */
  85157. EffectLayer.prototype._shouldRenderMesh = function (mesh) {
  85158. return true;
  85159. };
  85160. /**
  85161. * Returns true if the mesh should render, otherwise false.
  85162. * @param mesh The mesh to render
  85163. * @returns true if it should render otherwise false
  85164. */
  85165. EffectLayer.prototype._shouldRenderEmissiveTextureForMesh = function (mesh) {
  85166. return true;
  85167. };
  85168. /**
  85169. * Renders the submesh passed in parameter to the generation map.
  85170. */
  85171. EffectLayer.prototype._renderSubMesh = function (subMesh) {
  85172. var _this = this;
  85173. if (!this.shouldRender()) {
  85174. return;
  85175. }
  85176. var material = subMesh.getMaterial();
  85177. var mesh = subMesh.getRenderingMesh();
  85178. var scene = this._scene;
  85179. var engine = scene.getEngine();
  85180. if (!material) {
  85181. return;
  85182. }
  85183. // Do not block in blend mode.
  85184. if (material.needAlphaBlendingForMesh(mesh)) {
  85185. return;
  85186. }
  85187. // Culling
  85188. engine.setState(material.backFaceCulling);
  85189. // Managing instances
  85190. var batch = mesh._getInstancesRenderList(subMesh._id);
  85191. if (batch.mustReturn) {
  85192. return;
  85193. }
  85194. // Early Exit per mesh
  85195. if (!this._shouldRenderMesh(mesh)) {
  85196. return;
  85197. }
  85198. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  85199. this._setEmissiveTextureAndColor(mesh, subMesh, material);
  85200. if (this._isReady(subMesh, hardwareInstancedRendering, this._emissiveTextureAndColor.texture)) {
  85201. engine.enableEffect(this._effectLayerMapGenerationEffect);
  85202. mesh._bind(subMesh, this._effectLayerMapGenerationEffect, BABYLON.Material.TriangleFillMode);
  85203. this._effectLayerMapGenerationEffect.setMatrix("viewProjection", scene.getTransformMatrix());
  85204. this._effectLayerMapGenerationEffect.setFloat4("color", this._emissiveTextureAndColor.color.r, this._emissiveTextureAndColor.color.g, this._emissiveTextureAndColor.color.b, this._emissiveTextureAndColor.color.a);
  85205. // Alpha test
  85206. if (material && material.needAlphaTesting()) {
  85207. var alphaTexture = material.getAlphaTestTexture();
  85208. if (alphaTexture) {
  85209. this._effectLayerMapGenerationEffect.setTexture("diffuseSampler", alphaTexture);
  85210. var textureMatrix = alphaTexture.getTextureMatrix();
  85211. if (textureMatrix) {
  85212. this._effectLayerMapGenerationEffect.setMatrix("diffuseMatrix", textureMatrix);
  85213. }
  85214. }
  85215. }
  85216. // Glow emissive only
  85217. if (this._emissiveTextureAndColor.texture) {
  85218. this._effectLayerMapGenerationEffect.setTexture("emissiveSampler", this._emissiveTextureAndColor.texture);
  85219. this._effectLayerMapGenerationEffect.setMatrix("emissiveMatrix", this._emissiveTextureAndColor.texture.getTextureMatrix());
  85220. }
  85221. // Bones
  85222. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  85223. this._effectLayerMapGenerationEffect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  85224. }
  85225. // Draw
  85226. mesh._processRendering(subMesh, this._effectLayerMapGenerationEffect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effectLayerMapGenerationEffect.setMatrix("world", world); });
  85227. }
  85228. else {
  85229. // Need to reset refresh rate of the shadowMap
  85230. this._mainTexture.resetRefreshCounter();
  85231. }
  85232. };
  85233. /**
  85234. * Rebuild the required buffers.
  85235. * @ignore Internal use only.
  85236. */
  85237. EffectLayer.prototype._rebuild = function () {
  85238. var vb = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  85239. if (vb) {
  85240. vb._rebuild();
  85241. }
  85242. this._generateIndexBuffer();
  85243. };
  85244. /**
  85245. * Dispose only the render target textures and post process.
  85246. */
  85247. EffectLayer.prototype._disposeTextureAndPostProcesses = function () {
  85248. this._mainTexture.dispose();
  85249. for (var i = 0; i < this._postProcesses.length; i++) {
  85250. if (this._postProcesses[i]) {
  85251. this._postProcesses[i].dispose();
  85252. }
  85253. }
  85254. this._postProcesses = [];
  85255. for (var i = 0; i < this._textures.length; i++) {
  85256. if (this._textures[i]) {
  85257. this._textures[i].dispose();
  85258. }
  85259. }
  85260. this._textures = [];
  85261. };
  85262. /**
  85263. * Dispose the highlight layer and free resources.
  85264. */
  85265. EffectLayer.prototype.dispose = function () {
  85266. var vertexBuffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  85267. if (vertexBuffer) {
  85268. vertexBuffer.dispose();
  85269. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  85270. }
  85271. if (this._indexBuffer) {
  85272. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  85273. this._indexBuffer = null;
  85274. }
  85275. // Clean textures and post processes
  85276. this._disposeTextureAndPostProcesses();
  85277. // Remove from scene
  85278. var index = this._scene.effectLayers.indexOf(this, 0);
  85279. if (index > -1) {
  85280. this._scene.effectLayers.splice(index, 1);
  85281. }
  85282. // Callback
  85283. this.onDisposeObservable.notifyObservers(this);
  85284. this.onDisposeObservable.clear();
  85285. this.onBeforeRenderMainTextureObservable.clear();
  85286. this.onBeforeComposeObservable.clear();
  85287. this.onAfterComposeObservable.clear();
  85288. this.onSizeChangedObservable.clear();
  85289. };
  85290. return EffectLayer;
  85291. }());
  85292. BABYLON.EffectLayer = EffectLayer;
  85293. })(BABYLON || (BABYLON = {}));
  85294. //# sourceMappingURL=babylon.effectLayer.js.map
  85295. var BABYLON;
  85296. (function (BABYLON) {
  85297. /**
  85298. * Special Glow Blur post process only blurring the alpha channel
  85299. * It enforces keeping the most luminous color in the color channel.
  85300. */
  85301. var GlowBlurPostProcess = /** @class */ (function (_super) {
  85302. __extends(GlowBlurPostProcess, _super);
  85303. function GlowBlurPostProcess(name, direction, kernel, options, camera, samplingMode, engine, reusable) {
  85304. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  85305. var _this = _super.call(this, name, "glowBlurPostProcess", ["screenSize", "direction", "blurWidth"], null, options, camera, samplingMode, engine, reusable) || this;
  85306. _this.direction = direction;
  85307. _this.kernel = kernel;
  85308. _this.onApplyObservable.add(function (effect) {
  85309. effect.setFloat2("screenSize", _this.width, _this.height);
  85310. effect.setVector2("direction", _this.direction);
  85311. effect.setFloat("blurWidth", _this.kernel);
  85312. });
  85313. return _this;
  85314. }
  85315. return GlowBlurPostProcess;
  85316. }(BABYLON.PostProcess));
  85317. /**
  85318. * The highlight layer Helps adding a glow effect around a mesh.
  85319. *
  85320. * Once instantiated in a scene, simply use the pushMesh or removeMesh method to add or remove
  85321. * glowy meshes to your scene.
  85322. *
  85323. * !!! THIS REQUIRES AN ACTIVE STENCIL BUFFER ON THE CANVAS !!!
  85324. */
  85325. var HighlightLayer = /** @class */ (function (_super) {
  85326. __extends(HighlightLayer, _super);
  85327. /**
  85328. * Instantiates a new highlight Layer and references it to the scene..
  85329. * @param name The name of the layer
  85330. * @param scene The scene to use the layer in
  85331. * @param options Sets of none mandatory options to use with the layer (see IHighlightLayerOptions for more information)
  85332. */
  85333. function HighlightLayer(name, scene, options) {
  85334. var _this = _super.call(this, name, scene) || this;
  85335. _this.name = name;
  85336. /**
  85337. * Specifies whether or not the inner glow is ACTIVE in the layer.
  85338. */
  85339. _this.innerGlow = true;
  85340. /**
  85341. * Specifies whether or not the outer glow is ACTIVE in the layer.
  85342. */
  85343. _this.outerGlow = true;
  85344. /**
  85345. * An event triggered when the highlight layer is being blurred.
  85346. */
  85347. _this.onBeforeBlurObservable = new BABYLON.Observable();
  85348. /**
  85349. * An event triggered when the highlight layer has been blurred.
  85350. */
  85351. _this.onAfterBlurObservable = new BABYLON.Observable();
  85352. _this._instanceGlowingMeshStencilReference = HighlightLayer.GlowingMeshStencilReference++;
  85353. _this._meshes = {};
  85354. _this._excludedMeshes = {};
  85355. _this.neutralColor = HighlightLayer.NeutralColor;
  85356. // Warn on stencil
  85357. if (!_this._engine.isStencilEnable) {
  85358. 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 }");
  85359. }
  85360. // Adapt options
  85361. _this._options = __assign({ mainTextureRatio: 0.5, blurTextureSizeRatio: 0.5, blurHorizontalSize: 1.0, blurVerticalSize: 1.0, alphaBlendingMode: BABYLON.Engine.ALPHA_COMBINE, camera: null }, options);
  85362. // Initialize the layer
  85363. _this._init({
  85364. alphaBlendingMode: _this._options.alphaBlendingMode,
  85365. camera: _this._options.camera,
  85366. mainTextureFixedSize: _this._options.mainTextureFixedSize,
  85367. mainTextureRatio: _this._options.mainTextureRatio
  85368. });
  85369. // Do not render as long as no meshes have been added
  85370. _this._shouldRender = false;
  85371. return _this;
  85372. }
  85373. Object.defineProperty(HighlightLayer.prototype, "blurHorizontalSize", {
  85374. /**
  85375. * Gets the horizontal size of the blur.
  85376. */
  85377. get: function () {
  85378. return this._horizontalBlurPostprocess.kernel;
  85379. },
  85380. /**
  85381. * Specifies the horizontal size of the blur.
  85382. */
  85383. set: function (value) {
  85384. this._horizontalBlurPostprocess.kernel = value;
  85385. },
  85386. enumerable: true,
  85387. configurable: true
  85388. });
  85389. Object.defineProperty(HighlightLayer.prototype, "blurVerticalSize", {
  85390. /**
  85391. * Gets the vertical size of the blur.
  85392. */
  85393. get: function () {
  85394. return this._verticalBlurPostprocess.kernel;
  85395. },
  85396. /**
  85397. * Specifies the vertical size of the blur.
  85398. */
  85399. set: function (value) {
  85400. this._verticalBlurPostprocess.kernel = value;
  85401. },
  85402. enumerable: true,
  85403. configurable: true
  85404. });
  85405. /**
  85406. * Get the effect name of the layer.
  85407. * @return The effect name
  85408. */
  85409. HighlightLayer.prototype.getEffectName = function () {
  85410. return HighlightLayer.EffectName;
  85411. };
  85412. /**
  85413. * Create the merge effect. This is the shader use to blit the information back
  85414. * to the main canvas at the end of the scene rendering.
  85415. */
  85416. HighlightLayer.prototype._createMergeEffect = function () {
  85417. // Effect
  85418. return this._engine.createEffect("glowMapMerge", [BABYLON.VertexBuffer.PositionKind], ["offset"], ["textureSampler"], this._options.isStroke ? "#define STROKE \n" : undefined);
  85419. };
  85420. /**
  85421. * Creates the render target textures and post processes used in the highlight layer.
  85422. */
  85423. HighlightLayer.prototype._createTextureAndPostProcesses = function () {
  85424. var _this = this;
  85425. var blurTextureWidth = this._mainTextureDesiredSize.width * this._options.blurTextureSizeRatio;
  85426. var blurTextureHeight = this._mainTextureDesiredSize.height * this._options.blurTextureSizeRatio;
  85427. blurTextureWidth = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(blurTextureWidth, this._maxSize) : blurTextureWidth;
  85428. blurTextureHeight = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(blurTextureHeight, this._maxSize) : blurTextureHeight;
  85429. this._blurTexture = new BABYLON.RenderTargetTexture("HighlightLayerBlurRTT", {
  85430. width: blurTextureWidth,
  85431. height: blurTextureHeight
  85432. }, this._scene, false, true, BABYLON.Engine.TEXTURETYPE_HALF_FLOAT);
  85433. this._blurTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  85434. this._blurTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  85435. this._blurTexture.anisotropicFilteringLevel = 16;
  85436. this._blurTexture.updateSamplingMode(BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  85437. this._blurTexture.renderParticles = false;
  85438. this._blurTexture.ignoreCameraViewport = true;
  85439. this._textures = [this._blurTexture];
  85440. if (this._options.alphaBlendingMode === BABYLON.Engine.ALPHA_COMBINE) {
  85441. this._downSamplePostprocess = new BABYLON.PassPostProcess("HighlightLayerPPP", this._options.blurTextureSizeRatio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine());
  85442. this._downSamplePostprocess.onApplyObservable.add(function (effect) {
  85443. effect.setTexture("textureSampler", _this._mainTexture);
  85444. });
  85445. this._horizontalBlurPostprocess = new GlowBlurPostProcess("HighlightLayerHBP", new BABYLON.Vector2(1.0, 0), this._options.blurHorizontalSize, 1, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine());
  85446. this._horizontalBlurPostprocess.onApplyObservable.add(function (effect) {
  85447. effect.setFloat2("screenSize", blurTextureWidth, blurTextureHeight);
  85448. });
  85449. this._verticalBlurPostprocess = new GlowBlurPostProcess("HighlightLayerVBP", new BABYLON.Vector2(0, 1.0), this._options.blurVerticalSize, 1, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine());
  85450. this._verticalBlurPostprocess.onApplyObservable.add(function (effect) {
  85451. effect.setFloat2("screenSize", blurTextureWidth, blurTextureHeight);
  85452. });
  85453. this._postProcesses = [this._downSamplePostprocess, this._horizontalBlurPostprocess, this._verticalBlurPostprocess];
  85454. }
  85455. else {
  85456. this._horizontalBlurPostprocess = new BABYLON.BlurPostProcess("HighlightLayerHBP", new BABYLON.Vector2(1.0, 0), this._options.blurHorizontalSize / 2, {
  85457. width: blurTextureWidth,
  85458. height: blurTextureHeight
  85459. }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, BABYLON.Engine.TEXTURETYPE_HALF_FLOAT);
  85460. this._horizontalBlurPostprocess.width = blurTextureWidth;
  85461. this._horizontalBlurPostprocess.height = blurTextureHeight;
  85462. this._horizontalBlurPostprocess.onApplyObservable.add(function (effect) {
  85463. effect.setTexture("textureSampler", _this._mainTexture);
  85464. });
  85465. this._verticalBlurPostprocess = new BABYLON.BlurPostProcess("HighlightLayerVBP", new BABYLON.Vector2(0, 1.0), this._options.blurVerticalSize / 2, {
  85466. width: blurTextureWidth,
  85467. height: blurTextureHeight
  85468. }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, BABYLON.Engine.TEXTURETYPE_HALF_FLOAT);
  85469. this._postProcesses = [this._horizontalBlurPostprocess, this._verticalBlurPostprocess];
  85470. }
  85471. this._mainTexture.onAfterUnbindObservable.add(function () {
  85472. _this.onBeforeBlurObservable.notifyObservers(_this);
  85473. var internalTexture = _this._blurTexture.getInternalTexture();
  85474. if (internalTexture) {
  85475. _this._scene.postProcessManager.directRender(_this._postProcesses, internalTexture, true);
  85476. }
  85477. _this.onAfterBlurObservable.notifyObservers(_this);
  85478. });
  85479. // Prevent autoClear.
  85480. this._postProcesses.map(function (pp) { pp.autoClear = false; });
  85481. };
  85482. /**
  85483. * Returns wether or nood the layer needs stencil enabled during the mesh rendering.
  85484. */
  85485. HighlightLayer.prototype.needStencil = function () {
  85486. return true;
  85487. };
  85488. /**
  85489. * Checks for the readiness of the element composing the layer.
  85490. * @param subMesh the mesh to check for
  85491. * @param useInstances specify wether or not to use instances to render the mesh
  85492. * @param emissiveTexture the associated emissive texture used to generate the glow
  85493. * @return true if ready otherwise, false
  85494. */
  85495. HighlightLayer.prototype.isReady = function (subMesh, useInstances) {
  85496. var material = subMesh.getMaterial();
  85497. var mesh = subMesh.getRenderingMesh();
  85498. if (!material || !mesh || !this._meshes) {
  85499. return false;
  85500. }
  85501. var emissiveTexture = null;
  85502. var highlightLayerMesh = this._meshes[mesh.uniqueId];
  85503. if (highlightLayerMesh && highlightLayerMesh.glowEmissiveOnly && material) {
  85504. emissiveTexture = material.emissiveTexture;
  85505. }
  85506. return _super.prototype._isReady.call(this, subMesh, useInstances, emissiveTexture);
  85507. };
  85508. /**
  85509. * Implementation specific of rendering the generating effect on the main canvas.
  85510. * @param effect The effect used to render through
  85511. */
  85512. HighlightLayer.prototype._internalRender = function (effect) {
  85513. // Texture
  85514. effect.setTexture("textureSampler", this._blurTexture);
  85515. // Cache
  85516. var engine = this._engine;
  85517. var previousStencilBuffer = engine.getStencilBuffer();
  85518. var previousStencilFunction = engine.getStencilFunction();
  85519. var previousStencilMask = engine.getStencilMask();
  85520. var previousStencilOperationPass = engine.getStencilOperationPass();
  85521. var previousStencilOperationFail = engine.getStencilOperationFail();
  85522. var previousStencilOperationDepthFail = engine.getStencilOperationDepthFail();
  85523. var previousStencilReference = engine.getStencilFunctionReference();
  85524. // Stencil operations
  85525. engine.setStencilOperationPass(BABYLON.Engine.REPLACE);
  85526. engine.setStencilOperationFail(BABYLON.Engine.KEEP);
  85527. engine.setStencilOperationDepthFail(BABYLON.Engine.KEEP);
  85528. // Draw order
  85529. engine.setStencilMask(0x00);
  85530. engine.setStencilBuffer(true);
  85531. engine.setStencilFunctionReference(this._instanceGlowingMeshStencilReference);
  85532. // 2 passes inner outer
  85533. if (this.outerGlow) {
  85534. effect.setFloat("offset", 0);
  85535. engine.setStencilFunction(BABYLON.Engine.NOTEQUAL);
  85536. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  85537. }
  85538. if (this.innerGlow) {
  85539. effect.setFloat("offset", 1);
  85540. engine.setStencilFunction(BABYLON.Engine.EQUAL);
  85541. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  85542. }
  85543. // Restore Cache
  85544. engine.setStencilFunction(previousStencilFunction);
  85545. engine.setStencilMask(previousStencilMask);
  85546. engine.setStencilBuffer(previousStencilBuffer);
  85547. engine.setStencilOperationPass(previousStencilOperationPass);
  85548. engine.setStencilOperationFail(previousStencilOperationFail);
  85549. engine.setStencilOperationDepthFail(previousStencilOperationDepthFail);
  85550. engine.setStencilFunctionReference(previousStencilReference);
  85551. };
  85552. /**
  85553. * Returns true if the layer contains information to display, otherwise false.
  85554. */
  85555. HighlightLayer.prototype.shouldRender = function () {
  85556. if (_super.prototype.shouldRender.call(this)) {
  85557. return this._meshes ? true : false;
  85558. }
  85559. return false;
  85560. };
  85561. /**
  85562. * Returns true if the mesh should render, otherwise false.
  85563. * @param mesh The mesh to render
  85564. * @returns true if it should render otherwise false
  85565. */
  85566. HighlightLayer.prototype._shouldRenderMesh = function (mesh) {
  85567. // Excluded Mesh
  85568. if (this._excludedMeshes && this._excludedMeshes[mesh.uniqueId]) {
  85569. return false;
  85570. }
  85571. ;
  85572. return true;
  85573. };
  85574. /**
  85575. * Sets the required values for both the emissive texture and and the main color.
  85576. */
  85577. HighlightLayer.prototype._setEmissiveTextureAndColor = function (mesh, subMesh, material) {
  85578. var highlightLayerMesh = this._meshes[mesh.uniqueId];
  85579. if (highlightLayerMesh) {
  85580. this._emissiveTextureAndColor.color.set(highlightLayerMesh.color.r, highlightLayerMesh.color.g, highlightLayerMesh.color.b, 1.0);
  85581. }
  85582. else {
  85583. this._emissiveTextureAndColor.color.set(this.neutralColor.r, this.neutralColor.g, this.neutralColor.b, this.neutralColor.a);
  85584. }
  85585. if (highlightLayerMesh && highlightLayerMesh.glowEmissiveOnly && material) {
  85586. this._emissiveTextureAndColor.texture = material.emissiveTexture;
  85587. this._emissiveTextureAndColor.color.set(1.0, 1.0, 1.0, 1.0);
  85588. }
  85589. else {
  85590. this._emissiveTextureAndColor.texture = null;
  85591. }
  85592. };
  85593. /**
  85594. * Add a mesh in the exclusion list to prevent it to impact or being impacted by the highlight layer.
  85595. * @param mesh The mesh to exclude from the highlight layer
  85596. */
  85597. HighlightLayer.prototype.addExcludedMesh = function (mesh) {
  85598. if (!this._excludedMeshes) {
  85599. return;
  85600. }
  85601. var meshExcluded = this._excludedMeshes[mesh.uniqueId];
  85602. if (!meshExcluded) {
  85603. this._excludedMeshes[mesh.uniqueId] = {
  85604. mesh: mesh,
  85605. beforeRender: mesh.onBeforeRenderObservable.add(function (mesh) {
  85606. mesh.getEngine().setStencilBuffer(false);
  85607. }),
  85608. afterRender: mesh.onAfterRenderObservable.add(function (mesh) {
  85609. mesh.getEngine().setStencilBuffer(true);
  85610. }),
  85611. };
  85612. }
  85613. };
  85614. /**
  85615. * Remove a mesh from the exclusion list to let it impact or being impacted by the highlight layer.
  85616. * @param mesh The mesh to highlight
  85617. */
  85618. HighlightLayer.prototype.removeExcludedMesh = function (mesh) {
  85619. if (!this._excludedMeshes) {
  85620. return;
  85621. }
  85622. var meshExcluded = this._excludedMeshes[mesh.uniqueId];
  85623. if (meshExcluded) {
  85624. if (meshExcluded.beforeRender) {
  85625. mesh.onBeforeRenderObservable.remove(meshExcluded.beforeRender);
  85626. }
  85627. if (meshExcluded.afterRender) {
  85628. mesh.onAfterRenderObservable.remove(meshExcluded.afterRender);
  85629. }
  85630. }
  85631. this._excludedMeshes[mesh.uniqueId] = null;
  85632. };
  85633. /**
  85634. * Determine if a given mesh will be highlighted by the current HighlightLayer
  85635. * @param mesh mesh to test
  85636. * @returns true if the mesh will be highlighted by the current HighlightLayer
  85637. */
  85638. HighlightLayer.prototype.hasMesh = function (mesh) {
  85639. if (!this._meshes) {
  85640. return false;
  85641. }
  85642. return this._meshes[mesh.uniqueId] !== undefined && this._meshes[mesh.uniqueId] !== null;
  85643. };
  85644. /**
  85645. * Add a mesh in the highlight layer in order to make it glow with the chosen color.
  85646. * @param mesh The mesh to highlight
  85647. * @param color The color of the highlight
  85648. * @param glowEmissiveOnly Extract the glow from the emissive texture
  85649. */
  85650. HighlightLayer.prototype.addMesh = function (mesh, color, glowEmissiveOnly) {
  85651. var _this = this;
  85652. if (glowEmissiveOnly === void 0) { glowEmissiveOnly = false; }
  85653. if (!this._meshes) {
  85654. return;
  85655. }
  85656. var meshHighlight = this._meshes[mesh.uniqueId];
  85657. if (meshHighlight) {
  85658. meshHighlight.color = color;
  85659. }
  85660. else {
  85661. this._meshes[mesh.uniqueId] = {
  85662. mesh: mesh,
  85663. color: color,
  85664. // Lambda required for capture due to Observable this context
  85665. observerHighlight: mesh.onBeforeRenderObservable.add(function (mesh) {
  85666. if (_this._excludedMeshes && _this._excludedMeshes[mesh.uniqueId]) {
  85667. _this._defaultStencilReference(mesh);
  85668. }
  85669. else {
  85670. mesh.getScene().getEngine().setStencilFunctionReference(_this._instanceGlowingMeshStencilReference);
  85671. }
  85672. }),
  85673. observerDefault: mesh.onAfterRenderObservable.add(this._defaultStencilReference),
  85674. glowEmissiveOnly: glowEmissiveOnly
  85675. };
  85676. }
  85677. this._shouldRender = true;
  85678. };
  85679. /**
  85680. * Remove a mesh from the highlight layer in order to make it stop glowing.
  85681. * @param mesh The mesh to highlight
  85682. */
  85683. HighlightLayer.prototype.removeMesh = function (mesh) {
  85684. if (!this._meshes) {
  85685. return;
  85686. }
  85687. var meshHighlight = this._meshes[mesh.uniqueId];
  85688. if (meshHighlight) {
  85689. if (meshHighlight.observerHighlight) {
  85690. mesh.onBeforeRenderObservable.remove(meshHighlight.observerHighlight);
  85691. }
  85692. if (meshHighlight.observerDefault) {
  85693. mesh.onAfterRenderObservable.remove(meshHighlight.observerDefault);
  85694. }
  85695. delete this._meshes[mesh.uniqueId];
  85696. }
  85697. this._shouldRender = false;
  85698. for (var meshHighlightToCheck in this._meshes) {
  85699. if (this._meshes[meshHighlightToCheck]) {
  85700. this._shouldRender = true;
  85701. break;
  85702. }
  85703. }
  85704. };
  85705. /**
  85706. * Force the stencil to the normal expected value for none glowing parts
  85707. */
  85708. HighlightLayer.prototype._defaultStencilReference = function (mesh) {
  85709. mesh.getScene().getEngine().setStencilFunctionReference(HighlightLayer.NormalMeshStencilReference);
  85710. };
  85711. /**
  85712. * Free any resources and references associated to a mesh.
  85713. * Internal use
  85714. * @param mesh The mesh to free.
  85715. */
  85716. HighlightLayer.prototype._disposeMesh = function (mesh) {
  85717. this.removeMesh(mesh);
  85718. this.removeExcludedMesh(mesh);
  85719. };
  85720. /**
  85721. * Dispose the highlight layer and free resources.
  85722. */
  85723. HighlightLayer.prototype.dispose = function () {
  85724. if (this._meshes) {
  85725. // Clean mesh references
  85726. for (var id in this._meshes) {
  85727. var meshHighlight = this._meshes[id];
  85728. if (meshHighlight && meshHighlight.mesh) {
  85729. if (meshHighlight.observerHighlight) {
  85730. meshHighlight.mesh.onBeforeRenderObservable.remove(meshHighlight.observerHighlight);
  85731. }
  85732. if (meshHighlight.observerDefault) {
  85733. meshHighlight.mesh.onAfterRenderObservable.remove(meshHighlight.observerDefault);
  85734. }
  85735. }
  85736. }
  85737. this._meshes = null;
  85738. }
  85739. if (this._excludedMeshes) {
  85740. for (var id in this._excludedMeshes) {
  85741. var meshHighlight = this._excludedMeshes[id];
  85742. if (meshHighlight) {
  85743. if (meshHighlight.beforeRender) {
  85744. meshHighlight.mesh.onBeforeRenderObservable.remove(meshHighlight.beforeRender);
  85745. }
  85746. if (meshHighlight.afterRender) {
  85747. meshHighlight.mesh.onAfterRenderObservable.remove(meshHighlight.afterRender);
  85748. }
  85749. }
  85750. }
  85751. this._excludedMeshes = null;
  85752. }
  85753. _super.prototype.dispose.call(this);
  85754. };
  85755. /**
  85756. * Effect Name of the highlight layer.
  85757. */
  85758. HighlightLayer.EffectName = "HighlightLayer";
  85759. /**
  85760. * The neutral color used during the preparation of the glow effect.
  85761. * This is black by default as the blend operation is a blend operation.
  85762. */
  85763. HighlightLayer.NeutralColor = new BABYLON.Color4(0, 0, 0, 0);
  85764. /**
  85765. * Stencil value used for glowing meshes.
  85766. */
  85767. HighlightLayer.GlowingMeshStencilReference = 0x02;
  85768. /**
  85769. * Stencil value used for the other meshes in the scene.
  85770. */
  85771. HighlightLayer.NormalMeshStencilReference = 0x01;
  85772. return HighlightLayer;
  85773. }(BABYLON.EffectLayer));
  85774. BABYLON.HighlightLayer = HighlightLayer;
  85775. })(BABYLON || (BABYLON = {}));
  85776. //# sourceMappingURL=babylon.highlightLayer.js.map
  85777. var BABYLON;
  85778. (function (BABYLON) {
  85779. /**
  85780. * The glow layer Helps adding a glow effect around the emissive parts of a mesh.
  85781. *
  85782. * Once instantiated in a scene, simply use the pushMesh or removeMesh method to add or remove
  85783. * glowy meshes to your scene.
  85784. *
  85785. * Documentation: https://doc.babylonjs.com/how_to/glow_layer
  85786. */
  85787. var GlowLayer = /** @class */ (function (_super) {
  85788. __extends(GlowLayer, _super);
  85789. /**
  85790. * Instantiates a new glow Layer and references it to the scene.
  85791. * @param name The name of the layer
  85792. * @param scene The scene to use the layer in
  85793. * @param options Sets of none mandatory options to use with the layer (see IGlowLayerOptions for more information)
  85794. */
  85795. function GlowLayer(name, scene, options) {
  85796. var _this = _super.call(this, name, scene) || this;
  85797. _this.name = name;
  85798. _this._intensity = 1.0;
  85799. _this._includedOnlyMeshes = [];
  85800. _this._excludedMeshes = [];
  85801. _this.neutralColor = new BABYLON.Color4(0, 0, 0, 1);
  85802. // Adapt options
  85803. _this._options = __assign({ mainTextureRatio: GlowLayer.DefaultTextureRatio, blurKernelSize: 32, mainTextureFixedSize: undefined, camera: null, mainTextureSamples: 1 }, options);
  85804. // Initialize the layer
  85805. _this._init({
  85806. alphaBlendingMode: BABYLON.Engine.ALPHA_ADD,
  85807. camera: _this._options.camera,
  85808. mainTextureFixedSize: _this._options.mainTextureFixedSize,
  85809. mainTextureRatio: _this._options.mainTextureRatio
  85810. });
  85811. return _this;
  85812. }
  85813. Object.defineProperty(GlowLayer.prototype, "blurKernelSize", {
  85814. /**
  85815. * Gets the kernel size of the blur.
  85816. */
  85817. get: function () {
  85818. return this._horizontalBlurPostprocess1.kernel;
  85819. },
  85820. /**
  85821. * Sets the kernel size of the blur.
  85822. */
  85823. set: function (value) {
  85824. this._horizontalBlurPostprocess1.kernel = value;
  85825. this._verticalBlurPostprocess1.kernel = value;
  85826. this._horizontalBlurPostprocess2.kernel = value;
  85827. this._verticalBlurPostprocess2.kernel = value;
  85828. },
  85829. enumerable: true,
  85830. configurable: true
  85831. });
  85832. Object.defineProperty(GlowLayer.prototype, "intensity", {
  85833. /**
  85834. * Gets the glow intensity.
  85835. */
  85836. get: function () {
  85837. return this._intensity;
  85838. },
  85839. /**
  85840. * Sets the glow intensity.
  85841. */
  85842. set: function (value) {
  85843. this._intensity = value;
  85844. },
  85845. enumerable: true,
  85846. configurable: true
  85847. });
  85848. /**
  85849. * Get the effect name of the layer.
  85850. * @return The effect name
  85851. */
  85852. GlowLayer.prototype.getEffectName = function () {
  85853. return GlowLayer.EffectName;
  85854. };
  85855. /**
  85856. * Create the merge effect. This is the shader use to blit the information back
  85857. * to the main canvas at the end of the scene rendering.
  85858. */
  85859. GlowLayer.prototype._createMergeEffect = function () {
  85860. // Effect
  85861. return this._engine.createEffect("glowMapMerge", [BABYLON.VertexBuffer.PositionKind], ["offset"], ["textureSampler", "textureSampler2"], "#define EMISSIVE \n");
  85862. };
  85863. /**
  85864. * Creates the render target textures and post processes used in the glow layer.
  85865. */
  85866. GlowLayer.prototype._createTextureAndPostProcesses = function () {
  85867. var _this = this;
  85868. var blurTextureWidth = this._mainTextureDesiredSize.width;
  85869. var blurTextureHeight = this._mainTextureDesiredSize.height;
  85870. blurTextureWidth = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(blurTextureWidth, this._maxSize) : blurTextureWidth;
  85871. blurTextureHeight = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(blurTextureHeight, this._maxSize) : blurTextureHeight;
  85872. this._blurTexture1 = new BABYLON.RenderTargetTexture("GlowLayerBlurRTT", {
  85873. width: blurTextureWidth,
  85874. height: blurTextureHeight
  85875. }, this._scene, false, true, BABYLON.Engine.TEXTURETYPE_HALF_FLOAT);
  85876. this._blurTexture1.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  85877. this._blurTexture1.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  85878. this._blurTexture1.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  85879. this._blurTexture1.renderParticles = false;
  85880. this._blurTexture1.ignoreCameraViewport = true;
  85881. var blurTextureWidth2 = Math.floor(blurTextureWidth / 2);
  85882. var blurTextureHeight2 = Math.floor(blurTextureHeight / 2);
  85883. this._blurTexture2 = new BABYLON.RenderTargetTexture("GlowLayerBlurRTT2", {
  85884. width: blurTextureWidth2,
  85885. height: blurTextureHeight2
  85886. }, this._scene, false, true, BABYLON.Engine.TEXTURETYPE_HALF_FLOAT);
  85887. this._blurTexture2.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  85888. this._blurTexture2.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  85889. this._blurTexture2.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  85890. this._blurTexture2.renderParticles = false;
  85891. this._blurTexture2.ignoreCameraViewport = true;
  85892. this._textures = [this._blurTexture1, this._blurTexture2];
  85893. this._horizontalBlurPostprocess1 = new BABYLON.BlurPostProcess("GlowLayerHBP1", new BABYLON.Vector2(1.0, 0), this._options.blurKernelSize / 2, {
  85894. width: blurTextureWidth,
  85895. height: blurTextureHeight
  85896. }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, BABYLON.Engine.TEXTURETYPE_HALF_FLOAT);
  85897. this._horizontalBlurPostprocess1.width = blurTextureWidth;
  85898. this._horizontalBlurPostprocess1.height = blurTextureHeight;
  85899. this._horizontalBlurPostprocess1.onApplyObservable.add(function (effect) {
  85900. effect.setTexture("textureSampler", _this._mainTexture);
  85901. });
  85902. this._verticalBlurPostprocess1 = new BABYLON.BlurPostProcess("GlowLayerVBP1", new BABYLON.Vector2(0, 1.0), this._options.blurKernelSize / 2, {
  85903. width: blurTextureWidth,
  85904. height: blurTextureHeight
  85905. }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, BABYLON.Engine.TEXTURETYPE_HALF_FLOAT);
  85906. this._horizontalBlurPostprocess2 = new BABYLON.BlurPostProcess("GlowLayerHBP2", new BABYLON.Vector2(1.0, 0), this._options.blurKernelSize / 2, {
  85907. width: blurTextureWidth2,
  85908. height: blurTextureHeight2
  85909. }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, BABYLON.Engine.TEXTURETYPE_HALF_FLOAT);
  85910. this._horizontalBlurPostprocess2.width = blurTextureWidth2;
  85911. this._horizontalBlurPostprocess2.height = blurTextureHeight2;
  85912. this._horizontalBlurPostprocess2.onApplyObservable.add(function (effect) {
  85913. effect.setTexture("textureSampler", _this._blurTexture1);
  85914. });
  85915. this._verticalBlurPostprocess2 = new BABYLON.BlurPostProcess("GlowLayerVBP2", new BABYLON.Vector2(0, 1.0), this._options.blurKernelSize / 2, {
  85916. width: blurTextureWidth2,
  85917. height: blurTextureHeight2
  85918. }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, BABYLON.Engine.TEXTURETYPE_HALF_FLOAT);
  85919. this._postProcesses = [this._horizontalBlurPostprocess1, this._verticalBlurPostprocess1, this._horizontalBlurPostprocess2, this._verticalBlurPostprocess2];
  85920. this._postProcesses1 = [this._horizontalBlurPostprocess1, this._verticalBlurPostprocess1];
  85921. this._postProcesses2 = [this._horizontalBlurPostprocess2, this._verticalBlurPostprocess2];
  85922. this._mainTexture.samples = this._options.mainTextureSamples;
  85923. this._mainTexture.onAfterUnbindObservable.add(function () {
  85924. var internalTexture = _this._blurTexture1.getInternalTexture();
  85925. if (internalTexture) {
  85926. _this._scene.postProcessManager.directRender(_this._postProcesses1, internalTexture, true);
  85927. internalTexture = _this._blurTexture2.getInternalTexture();
  85928. if (internalTexture) {
  85929. _this._scene.postProcessManager.directRender(_this._postProcesses2, internalTexture, true);
  85930. }
  85931. }
  85932. });
  85933. // Prevent autoClear.
  85934. this._postProcesses.map(function (pp) { pp.autoClear = false; });
  85935. };
  85936. /**
  85937. * Checks for the readiness of the element composing the layer.
  85938. * @param subMesh the mesh to check for
  85939. * @param useInstances specify wether or not to use instances to render the mesh
  85940. * @param emissiveTexture the associated emissive texture used to generate the glow
  85941. * @return true if ready otherwise, false
  85942. */
  85943. GlowLayer.prototype.isReady = function (subMesh, useInstances) {
  85944. var material = subMesh.getMaterial();
  85945. var mesh = subMesh.getRenderingMesh();
  85946. if (!material || !mesh) {
  85947. return false;
  85948. }
  85949. var emissiveTexture = material.emissiveTexture;
  85950. return _super.prototype._isReady.call(this, subMesh, useInstances, emissiveTexture);
  85951. };
  85952. /**
  85953. * Returns wether or nood the layer needs stencil enabled during the mesh rendering.
  85954. */
  85955. GlowLayer.prototype.needStencil = function () {
  85956. return false;
  85957. };
  85958. /**
  85959. * Implementation specific of rendering the generating effect on the main canvas.
  85960. * @param effect The effect used to render through
  85961. */
  85962. GlowLayer.prototype._internalRender = function (effect) {
  85963. // Texture
  85964. effect.setTexture("textureSampler", this._blurTexture1);
  85965. effect.setTexture("textureSampler2", this._blurTexture2);
  85966. effect.setFloat("offset", this._intensity);
  85967. // Cache
  85968. var engine = this._engine;
  85969. var previousStencilBuffer = engine.getStencilBuffer();
  85970. // Draw order
  85971. engine.setStencilBuffer(false);
  85972. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  85973. // Draw order
  85974. engine.setStencilBuffer(previousStencilBuffer);
  85975. };
  85976. /**
  85977. * Sets the required values for both the emissive texture and and the main color.
  85978. */
  85979. GlowLayer.prototype._setEmissiveTextureAndColor = function (mesh, subMesh, material) {
  85980. var textureLevel = 1.0;
  85981. if (this.customEmissiveTextureSelector) {
  85982. this._emissiveTextureAndColor.texture = this.customEmissiveTextureSelector(mesh, subMesh, material);
  85983. }
  85984. else {
  85985. if (material) {
  85986. this._emissiveTextureAndColor.texture = material.emissiveTexture;
  85987. if (this._emissiveTextureAndColor.texture) {
  85988. textureLevel = this._emissiveTextureAndColor.texture.level;
  85989. }
  85990. }
  85991. else {
  85992. this._emissiveTextureAndColor.texture = null;
  85993. }
  85994. }
  85995. if (this.customEmissiveColorSelector) {
  85996. this.customEmissiveColorSelector(mesh, subMesh, material, this._emissiveTextureAndColor.color);
  85997. }
  85998. else {
  85999. if (material.emissiveColor) {
  86000. this._emissiveTextureAndColor.color.set(material.emissiveColor.r * textureLevel, material.emissiveColor.g * textureLevel, material.emissiveColor.b * textureLevel, 1.0);
  86001. }
  86002. else {
  86003. this._emissiveTextureAndColor.color.set(this.neutralColor.r, this.neutralColor.g, this.neutralColor.b, this.neutralColor.a);
  86004. }
  86005. }
  86006. };
  86007. /**
  86008. * Returns true if the mesh should render, otherwise false.
  86009. * @param mesh The mesh to render
  86010. * @returns true if it should render otherwise false
  86011. */
  86012. GlowLayer.prototype._shouldRenderMesh = function (mesh) {
  86013. return this.hasMesh(mesh);
  86014. };
  86015. /**
  86016. * Add a mesh in the exclusion list to prevent it to impact or being impacted by the glow layer.
  86017. * @param mesh The mesh to exclude from the glow layer
  86018. */
  86019. GlowLayer.prototype.addExcludedMesh = function (mesh) {
  86020. if (this._excludedMeshes.indexOf(mesh.uniqueId) === -1) {
  86021. this._excludedMeshes.push(mesh.uniqueId);
  86022. }
  86023. };
  86024. /**
  86025. * Remove a mesh from the exclusion list to let it impact or being impacted by the glow layer.
  86026. * @param mesh The mesh to remove
  86027. */
  86028. GlowLayer.prototype.removeExcludedMesh = function (mesh) {
  86029. var index = this._excludedMeshes.indexOf(mesh.uniqueId);
  86030. if (index !== -1) {
  86031. this._excludedMeshes.splice(index, 1);
  86032. }
  86033. };
  86034. /**
  86035. * Add a mesh in the inclusion list to impact or being impacted by the glow layer.
  86036. * @param mesh The mesh to include in the glow layer
  86037. */
  86038. GlowLayer.prototype.addIncludedOnlyMesh = function (mesh) {
  86039. if (this._includedOnlyMeshes.indexOf(mesh.uniqueId) === -1) {
  86040. this._includedOnlyMeshes.push(mesh.uniqueId);
  86041. }
  86042. };
  86043. /**
  86044. * Remove a mesh from the Inclusion list to prevent it to impact or being impacted by the glow layer.
  86045. * @param mesh The mesh to remove
  86046. */
  86047. GlowLayer.prototype.removeIncludedOnlyMesh = function (mesh) {
  86048. var index = this._includedOnlyMeshes.indexOf(mesh.uniqueId);
  86049. if (index !== -1) {
  86050. this._includedOnlyMeshes.splice(index, 1);
  86051. }
  86052. };
  86053. /**
  86054. * Determine if a given mesh will be used in the glow layer
  86055. * @param mesh The mesh to test
  86056. * @returns true if the mesh will be highlighted by the current glow layer
  86057. */
  86058. GlowLayer.prototype.hasMesh = function (mesh) {
  86059. // Included Mesh
  86060. if (this._includedOnlyMeshes.length) {
  86061. return this._includedOnlyMeshes.indexOf(mesh.uniqueId) !== -1;
  86062. }
  86063. ;
  86064. // Excluded Mesh
  86065. if (this._excludedMeshes.length) {
  86066. return this._excludedMeshes.indexOf(mesh.uniqueId) === -1;
  86067. }
  86068. ;
  86069. return true;
  86070. };
  86071. /**
  86072. * Free any resources and references associated to a mesh.
  86073. * Internal use
  86074. * @param mesh The mesh to free.
  86075. */
  86076. GlowLayer.prototype._disposeMesh = function (mesh) {
  86077. this.removeIncludedOnlyMesh(mesh);
  86078. this.removeExcludedMesh(mesh);
  86079. };
  86080. /**
  86081. * Effect Name of the layer.
  86082. */
  86083. GlowLayer.EffectName = "GlowLayer";
  86084. /**
  86085. * The default blur kernel size used for the glow.
  86086. */
  86087. GlowLayer.DefaultBlurKernelSize = 32;
  86088. /**
  86089. * The default texture size ratio used for the glow.
  86090. */
  86091. GlowLayer.DefaultTextureRatio = 0.5;
  86092. return GlowLayer;
  86093. }(BABYLON.EffectLayer));
  86094. BABYLON.GlowLayer = GlowLayer;
  86095. })(BABYLON || (BABYLON = {}));
  86096. //# sourceMappingURL=babylon.glowLayer.js.map
  86097. var BABYLON;
  86098. (function (BABYLON) {
  86099. /**
  86100. * Defines the list of states available for a task inside a {BABYLON.AssetsManager}
  86101. */
  86102. var AssetTaskState;
  86103. (function (AssetTaskState) {
  86104. /**
  86105. * Initialization
  86106. */
  86107. AssetTaskState[AssetTaskState["INIT"] = 0] = "INIT";
  86108. /**
  86109. * Running
  86110. */
  86111. AssetTaskState[AssetTaskState["RUNNING"] = 1] = "RUNNING";
  86112. /**
  86113. * Done
  86114. */
  86115. AssetTaskState[AssetTaskState["DONE"] = 2] = "DONE";
  86116. /**
  86117. * Error
  86118. */
  86119. AssetTaskState[AssetTaskState["ERROR"] = 3] = "ERROR";
  86120. })(AssetTaskState = BABYLON.AssetTaskState || (BABYLON.AssetTaskState = {}));
  86121. /**
  86122. * Define an abstract asset task used with a {BABYLON.AssetsManager} class to load assets into a scene
  86123. */
  86124. var AbstractAssetTask = /** @class */ (function () {
  86125. /**
  86126. * Creates a new {BABYLON.AssetsManager}
  86127. * @param name defines the name of the task
  86128. */
  86129. function AbstractAssetTask(
  86130. /**
  86131. * Task name
  86132. */ name) {
  86133. this.name = name;
  86134. this._isCompleted = false;
  86135. this._taskState = AssetTaskState.INIT;
  86136. }
  86137. Object.defineProperty(AbstractAssetTask.prototype, "isCompleted", {
  86138. /**
  86139. * Get if the task is completed
  86140. */
  86141. get: function () {
  86142. return this._isCompleted;
  86143. },
  86144. enumerable: true,
  86145. configurable: true
  86146. });
  86147. Object.defineProperty(AbstractAssetTask.prototype, "taskState", {
  86148. /**
  86149. * Gets the current state of the task
  86150. */
  86151. get: function () {
  86152. return this._taskState;
  86153. },
  86154. enumerable: true,
  86155. configurable: true
  86156. });
  86157. Object.defineProperty(AbstractAssetTask.prototype, "errorObject", {
  86158. /**
  86159. * Gets the current error object (if task is in error)
  86160. */
  86161. get: function () {
  86162. return this._errorObject;
  86163. },
  86164. enumerable: true,
  86165. configurable: true
  86166. });
  86167. /**
  86168. * Internal only
  86169. * @ignore
  86170. */
  86171. AbstractAssetTask.prototype._setErrorObject = function (message, exception) {
  86172. if (this._errorObject) {
  86173. return;
  86174. }
  86175. this._errorObject = {
  86176. message: message,
  86177. exception: exception
  86178. };
  86179. };
  86180. /**
  86181. * Execute the current task
  86182. * @param scene defines the scene where you want your assets to be loaded
  86183. * @param onSuccess is a callback called when the task is successfully executed
  86184. * @param onError is a callback called if an error occurs
  86185. */
  86186. AbstractAssetTask.prototype.run = function (scene, onSuccess, onError) {
  86187. var _this = this;
  86188. this._taskState = AssetTaskState.RUNNING;
  86189. this.runTask(scene, function () {
  86190. _this.onDoneCallback(onSuccess, onError);
  86191. }, function (msg, exception) {
  86192. _this.onErrorCallback(onError, msg, exception);
  86193. });
  86194. };
  86195. /**
  86196. * Execute the current task
  86197. * @param scene defines the scene where you want your assets to be loaded
  86198. * @param onSuccess is a callback called when the task is successfully executed
  86199. * @param onError is a callback called if an error occurs
  86200. */
  86201. AbstractAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  86202. throw new Error("runTask is not implemented");
  86203. };
  86204. AbstractAssetTask.prototype.onErrorCallback = function (onError, message, exception) {
  86205. this._taskState = AssetTaskState.ERROR;
  86206. this._errorObject = {
  86207. message: message,
  86208. exception: exception
  86209. };
  86210. if (this.onError) {
  86211. this.onError(this, message, exception);
  86212. }
  86213. onError();
  86214. };
  86215. AbstractAssetTask.prototype.onDoneCallback = function (onSuccess, onError) {
  86216. try {
  86217. this._taskState = AssetTaskState.DONE;
  86218. this._isCompleted = true;
  86219. if (this.onSuccess) {
  86220. this.onSuccess(this);
  86221. }
  86222. onSuccess();
  86223. }
  86224. catch (e) {
  86225. this.onErrorCallback(onError, "Task is done, error executing success callback(s)", e);
  86226. }
  86227. };
  86228. return AbstractAssetTask;
  86229. }());
  86230. BABYLON.AbstractAssetTask = AbstractAssetTask;
  86231. /**
  86232. * Class used to share progress information about assets loading
  86233. */
  86234. var AssetsProgressEvent = /** @class */ (function () {
  86235. /**
  86236. * Creates a {BABYLON.AssetsProgressEvent}
  86237. * @param remainingCount defines the number of remaining tasks to process
  86238. * @param totalCount defines the total number of tasks
  86239. * @param task defines the task that was just processed
  86240. */
  86241. function AssetsProgressEvent(remainingCount, totalCount, task) {
  86242. this.remainingCount = remainingCount;
  86243. this.totalCount = totalCount;
  86244. this.task = task;
  86245. }
  86246. return AssetsProgressEvent;
  86247. }());
  86248. BABYLON.AssetsProgressEvent = AssetsProgressEvent;
  86249. /**
  86250. * Define a task used by {BABYLON.AssetsManager} to load meshes
  86251. */
  86252. var MeshAssetTask = /** @class */ (function (_super) {
  86253. __extends(MeshAssetTask, _super);
  86254. /**
  86255. * Creates a new {BABYLON.MeshAssetTask}
  86256. * @param name defines the name of the task
  86257. * @param meshesNames defines the list of mesh's names you want to load
  86258. * @param rootUrl defines the root url to use as a base to load your meshes and associated resources
  86259. * @param sceneFilename defines the filename of the scene to load from
  86260. */
  86261. function MeshAssetTask(
  86262. /**
  86263. * Defines the name of the task
  86264. */
  86265. name,
  86266. /**
  86267. * Defines the list of mesh's names you want to load
  86268. */
  86269. meshesNames,
  86270. /**
  86271. * Defines the root url to use as a base to load your meshes and associated resources
  86272. */
  86273. rootUrl,
  86274. /**
  86275. * Defines the filename of the scene to load from
  86276. */
  86277. sceneFilename) {
  86278. var _this = _super.call(this, name) || this;
  86279. _this.name = name;
  86280. _this.meshesNames = meshesNames;
  86281. _this.rootUrl = rootUrl;
  86282. _this.sceneFilename = sceneFilename;
  86283. return _this;
  86284. }
  86285. /**
  86286. * Execute the current task
  86287. * @param scene defines the scene where you want your assets to be loaded
  86288. * @param onSuccess is a callback called when the task is successfully executed
  86289. * @param onError is a callback called if an error occurs
  86290. */
  86291. MeshAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  86292. var _this = this;
  86293. BABYLON.SceneLoader.ImportMesh(this.meshesNames, this.rootUrl, this.sceneFilename, scene, function (meshes, particleSystems, skeletons) {
  86294. _this.loadedMeshes = meshes;
  86295. _this.loadedParticleSystems = particleSystems;
  86296. _this.loadedSkeletons = skeletons;
  86297. onSuccess();
  86298. }, null, function (scene, message, exception) {
  86299. onError(message, exception);
  86300. });
  86301. };
  86302. return MeshAssetTask;
  86303. }(AbstractAssetTask));
  86304. BABYLON.MeshAssetTask = MeshAssetTask;
  86305. /**
  86306. * Define a task used by {BABYLON.AssetsManager} to load text content
  86307. */
  86308. var TextFileAssetTask = /** @class */ (function (_super) {
  86309. __extends(TextFileAssetTask, _super);
  86310. /**
  86311. * Creates a new TextFileAssetTask object
  86312. * @param name defines the name of the task
  86313. * @param url defines the location of the file to load
  86314. */
  86315. function TextFileAssetTask(
  86316. /**
  86317. * Defines the name of the task
  86318. */
  86319. name,
  86320. /**
  86321. * Defines the location of the file to load
  86322. */
  86323. url) {
  86324. var _this = _super.call(this, name) || this;
  86325. _this.name = name;
  86326. _this.url = url;
  86327. return _this;
  86328. }
  86329. /**
  86330. * Execute the current task
  86331. * @param scene defines the scene where you want your assets to be loaded
  86332. * @param onSuccess is a callback called when the task is successfully executed
  86333. * @param onError is a callback called if an error occurs
  86334. */
  86335. TextFileAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  86336. var _this = this;
  86337. scene._loadFile(this.url, function (data) {
  86338. _this.text = data;
  86339. onSuccess();
  86340. }, undefined, false, false, function (request, exception) {
  86341. if (request) {
  86342. onError(request.status + " " + request.statusText, exception);
  86343. }
  86344. });
  86345. };
  86346. return TextFileAssetTask;
  86347. }(AbstractAssetTask));
  86348. BABYLON.TextFileAssetTask = TextFileAssetTask;
  86349. /**
  86350. * Define a task used by {BABYLON.AssetsManager} to load binary data
  86351. */
  86352. var BinaryFileAssetTask = /** @class */ (function (_super) {
  86353. __extends(BinaryFileAssetTask, _super);
  86354. /**
  86355. * Creates a new BinaryFileAssetTask object
  86356. * @param name defines the name of the new task
  86357. * @param url defines the location of the file to load
  86358. */
  86359. function BinaryFileAssetTask(
  86360. /**
  86361. * Defines the name of the task
  86362. */
  86363. name,
  86364. /**
  86365. * Defines the location of the file to load
  86366. */
  86367. url) {
  86368. var _this = _super.call(this, name) || this;
  86369. _this.name = name;
  86370. _this.url = url;
  86371. return _this;
  86372. }
  86373. /**
  86374. * Execute the current task
  86375. * @param scene defines the scene where you want your assets to be loaded
  86376. * @param onSuccess is a callback called when the task is successfully executed
  86377. * @param onError is a callback called if an error occurs
  86378. */
  86379. BinaryFileAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  86380. var _this = this;
  86381. scene._loadFile(this.url, function (data) {
  86382. _this.data = data;
  86383. onSuccess();
  86384. }, undefined, true, true, function (request, exception) {
  86385. if (request) {
  86386. onError(request.status + " " + request.statusText, exception);
  86387. }
  86388. });
  86389. };
  86390. return BinaryFileAssetTask;
  86391. }(AbstractAssetTask));
  86392. BABYLON.BinaryFileAssetTask = BinaryFileAssetTask;
  86393. /**
  86394. * Define a task used by {BABYLON.AssetsManager} to load images
  86395. */
  86396. var ImageAssetTask = /** @class */ (function (_super) {
  86397. __extends(ImageAssetTask, _super);
  86398. /**
  86399. * Creates a new ImageAssetTask
  86400. * @param name defines the name of the task
  86401. * @param url defines the location of the image to load
  86402. */
  86403. function ImageAssetTask(
  86404. /**
  86405. * Defines the name of the task
  86406. */
  86407. name,
  86408. /**
  86409. * Defines the location of the image to load
  86410. */
  86411. url) {
  86412. var _this = _super.call(this, name) || this;
  86413. _this.name = name;
  86414. _this.url = url;
  86415. return _this;
  86416. }
  86417. /**
  86418. * Execute the current task
  86419. * @param scene defines the scene where you want your assets to be loaded
  86420. * @param onSuccess is a callback called when the task is successfully executed
  86421. * @param onError is a callback called if an error occurs
  86422. */
  86423. ImageAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  86424. var _this = this;
  86425. var img = new Image();
  86426. BABYLON.Tools.SetCorsBehavior(this.url, img);
  86427. img.onload = function () {
  86428. _this.image = img;
  86429. onSuccess();
  86430. };
  86431. img.onerror = function (err) {
  86432. onError("Error loading image", err);
  86433. };
  86434. img.src = this.url;
  86435. };
  86436. return ImageAssetTask;
  86437. }(AbstractAssetTask));
  86438. BABYLON.ImageAssetTask = ImageAssetTask;
  86439. /**
  86440. * Define a task used by {BABYLON.AssetsManager} to load 2D textures
  86441. */
  86442. var TextureAssetTask = /** @class */ (function (_super) {
  86443. __extends(TextureAssetTask, _super);
  86444. /**
  86445. * Creates a new TextureAssetTask object
  86446. * @param name defines the name of the task
  86447. * @param url defines the location of the file to load
  86448. * @param noMipmap defines if mipmap should not be generated (default is false)
  86449. * @param invertY defines if texture must be inverted on Y axis (default is false)
  86450. * @param samplingMode defines the sampling mode to use (default is BABYLON.Texture.TRILINEAR_SAMPLINGMODE)
  86451. */
  86452. function TextureAssetTask(
  86453. /**
  86454. * Defines the name of the task
  86455. */
  86456. name,
  86457. /**
  86458. * Defines the location of the file to load
  86459. */
  86460. url,
  86461. /**
  86462. * Defines if mipmap should not be generated (default is false)
  86463. */
  86464. noMipmap,
  86465. /**
  86466. * Defines if texture must be inverted on Y axis (default is false)
  86467. */
  86468. invertY,
  86469. /**
  86470. * Defines the sampling mode to use (default is BABYLON.Texture.TRILINEAR_SAMPLINGMODE)
  86471. */
  86472. samplingMode) {
  86473. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  86474. var _this = _super.call(this, name) || this;
  86475. _this.name = name;
  86476. _this.url = url;
  86477. _this.noMipmap = noMipmap;
  86478. _this.invertY = invertY;
  86479. _this.samplingMode = samplingMode;
  86480. return _this;
  86481. }
  86482. /**
  86483. * Execute the current task
  86484. * @param scene defines the scene where you want your assets to be loaded
  86485. * @param onSuccess is a callback called when the task is successfully executed
  86486. * @param onError is a callback called if an error occurs
  86487. */
  86488. TextureAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  86489. var onload = function () {
  86490. onSuccess();
  86491. };
  86492. var onerror = function (message, exception) {
  86493. onError(message, exception);
  86494. };
  86495. this.texture = new BABYLON.Texture(this.url, scene, this.noMipmap, this.invertY, this.samplingMode, onload, onerror);
  86496. };
  86497. return TextureAssetTask;
  86498. }(AbstractAssetTask));
  86499. BABYLON.TextureAssetTask = TextureAssetTask;
  86500. /**
  86501. * Define a task used by {BABYLON.AssetsManager} to load cube textures
  86502. */
  86503. var CubeTextureAssetTask = /** @class */ (function (_super) {
  86504. __extends(CubeTextureAssetTask, _super);
  86505. /**
  86506. * Creates a new CubeTextureAssetTask
  86507. * @param name defines the name of the task
  86508. * @param url defines the location of the files to load (You have to specify the folder where the files are + filename with no extension)
  86509. * @param extensions defines the extensions to use to load files (["_px", "_py", "_pz", "_nx", "_ny", "_nz"] by default)
  86510. * @param noMipmap defines if mipmaps should not be generated (default is false)
  86511. * @param files defines the explicit list of files (undefined by default)
  86512. */
  86513. function CubeTextureAssetTask(
  86514. /**
  86515. * Defines the name of the task
  86516. */
  86517. name,
  86518. /**
  86519. * Defines the location of the files to load (You have to specify the folder where the files are + filename with no extension)
  86520. */
  86521. url,
  86522. /**
  86523. * Defines the extensions to use to load files (["_px", "_py", "_pz", "_nx", "_ny", "_nz"] by default)
  86524. */
  86525. extensions,
  86526. /**
  86527. * Defines if mipmaps should not be generated (default is false)
  86528. */
  86529. noMipmap,
  86530. /**
  86531. * Defines the explicit list of files (undefined by default)
  86532. */
  86533. files) {
  86534. var _this = _super.call(this, name) || this;
  86535. _this.name = name;
  86536. _this.url = url;
  86537. _this.extensions = extensions;
  86538. _this.noMipmap = noMipmap;
  86539. _this.files = files;
  86540. return _this;
  86541. }
  86542. /**
  86543. * Execute the current task
  86544. * @param scene defines the scene where you want your assets to be loaded
  86545. * @param onSuccess is a callback called when the task is successfully executed
  86546. * @param onError is a callback called if an error occurs
  86547. */
  86548. CubeTextureAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  86549. var onload = function () {
  86550. onSuccess();
  86551. };
  86552. var onerror = function (message, exception) {
  86553. onError(message, exception);
  86554. };
  86555. this.texture = new BABYLON.CubeTexture(this.url, scene, this.extensions, this.noMipmap, this.files, onload, onerror);
  86556. };
  86557. return CubeTextureAssetTask;
  86558. }(AbstractAssetTask));
  86559. BABYLON.CubeTextureAssetTask = CubeTextureAssetTask;
  86560. /**
  86561. * Define a task used by {BABYLON.AssetsManager} to load HDR cube textures
  86562. */
  86563. var HDRCubeTextureAssetTask = /** @class */ (function (_super) {
  86564. __extends(HDRCubeTextureAssetTask, _super);
  86565. /**
  86566. * Creates a new HDRCubeTextureAssetTask object
  86567. * @param name defines the name of the task
  86568. * @param url defines the location of the file to load
  86569. * @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.
  86570. * @param noMipmap defines if mipmaps should not be generated (default is false)
  86571. * @param generateHarmonics specifies whether you want to extract the polynomial harmonics during the generation process (default is true)
  86572. * @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)
  86573. * @param usePMREMGenerator specifies whether or not to generate the CubeMap through CubeMapGen to avoid seams issue at run time (default is false)
  86574. */
  86575. function HDRCubeTextureAssetTask(
  86576. /**
  86577. * Defines the name of the task
  86578. */
  86579. name,
  86580. /**
  86581. * Defines the location of the file to load
  86582. */
  86583. url,
  86584. /**
  86585. * 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.
  86586. */
  86587. size,
  86588. /**
  86589. * Defines if mipmaps should not be generated (default is false)
  86590. */
  86591. noMipmap,
  86592. /**
  86593. * Specifies whether you want to extract the polynomial harmonics during the generation process (default is true)
  86594. */
  86595. generateHarmonics,
  86596. /**
  86597. * 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)
  86598. */
  86599. useInGammaSpace,
  86600. /**
  86601. * Specifies whether or not to generate the CubeMap through CubeMapGen to avoid seams issue at run time (default is false)
  86602. */
  86603. usePMREMGenerator) {
  86604. if (noMipmap === void 0) { noMipmap = false; }
  86605. if (generateHarmonics === void 0) { generateHarmonics = true; }
  86606. if (useInGammaSpace === void 0) { useInGammaSpace = false; }
  86607. if (usePMREMGenerator === void 0) { usePMREMGenerator = false; }
  86608. var _this = _super.call(this, name) || this;
  86609. _this.name = name;
  86610. _this.url = url;
  86611. _this.size = size;
  86612. _this.noMipmap = noMipmap;
  86613. _this.generateHarmonics = generateHarmonics;
  86614. _this.useInGammaSpace = useInGammaSpace;
  86615. _this.usePMREMGenerator = usePMREMGenerator;
  86616. return _this;
  86617. }
  86618. /**
  86619. * Execute the current task
  86620. * @param scene defines the scene where you want your assets to be loaded
  86621. * @param onSuccess is a callback called when the task is successfully executed
  86622. * @param onError is a callback called if an error occurs
  86623. */
  86624. HDRCubeTextureAssetTask.prototype.run = function (scene, onSuccess, onError) {
  86625. var onload = function () {
  86626. onSuccess();
  86627. };
  86628. var onerror = function (message, exception) {
  86629. onError(message, exception);
  86630. };
  86631. this.texture = new BABYLON.HDRCubeTexture(this.url, scene, this.size, this.noMipmap, this.generateHarmonics, this.useInGammaSpace, this.usePMREMGenerator, onload, onerror);
  86632. };
  86633. return HDRCubeTextureAssetTask;
  86634. }(AbstractAssetTask));
  86635. BABYLON.HDRCubeTextureAssetTask = HDRCubeTextureAssetTask;
  86636. /**
  86637. * This class can be used to easily import assets into a scene
  86638. * @see http://doc.babylonjs.com/how_to/how_to_use_assetsmanager
  86639. */
  86640. var AssetsManager = /** @class */ (function () {
  86641. /**
  86642. * Creates a new AssetsManager
  86643. * @param scene defines the scene to work on
  86644. */
  86645. function AssetsManager(scene) {
  86646. this._isLoading = false;
  86647. this._tasks = new Array();
  86648. this._waitingTasksCount = 0;
  86649. this._totalTasksCount = 0;
  86650. /**
  86651. * Observable called when all tasks are processed
  86652. */
  86653. this.onTaskSuccessObservable = new BABYLON.Observable();
  86654. /**
  86655. * Observable called when a task had an error
  86656. */
  86657. this.onTaskErrorObservable = new BABYLON.Observable();
  86658. /**
  86659. * Observable called when a task is successful
  86660. */
  86661. this.onTasksDoneObservable = new BABYLON.Observable();
  86662. /**
  86663. * Observable called when a task is done (whatever the result is)
  86664. */
  86665. this.onProgressObservable = new BABYLON.Observable();
  86666. /**
  86667. * Gets or sets a boolean defining if the {BABYLON.AssetsManager} should use the default loading screen
  86668. * @see http://doc.babylonjs.com/how_to/creating_a_custom_loading_screen
  86669. */
  86670. this.useDefaultLoadingScreen = true;
  86671. this._scene = scene;
  86672. }
  86673. /**
  86674. * Add a {BABYLON.MeshAssetTask} to the list of active tasks
  86675. * @param taskName defines the name of the new task
  86676. * @param meshesNames defines the name of meshes to load
  86677. * @param rootUrl defines the root url to use to locate files
  86678. * @param sceneFilename defines the filename of the scene file
  86679. * @returns a new {BABYLON.MeshAssetTask} object
  86680. */
  86681. AssetsManager.prototype.addMeshTask = function (taskName, meshesNames, rootUrl, sceneFilename) {
  86682. var task = new MeshAssetTask(taskName, meshesNames, rootUrl, sceneFilename);
  86683. this._tasks.push(task);
  86684. return task;
  86685. };
  86686. /**
  86687. * Add a {BABYLON.TextFileAssetTask} to the list of active tasks
  86688. * @param taskName defines the name of the new task
  86689. * @param url defines the url of the file to load
  86690. * @returns a new {BABYLON.TextFileAssetTask} object
  86691. */
  86692. AssetsManager.prototype.addTextFileTask = function (taskName, url) {
  86693. var task = new TextFileAssetTask(taskName, url);
  86694. this._tasks.push(task);
  86695. return task;
  86696. };
  86697. /**
  86698. * Add a {BABYLON.BinaryFileAssetTask} to the list of active tasks
  86699. * @param taskName defines the name of the new task
  86700. * @param url defines the url of the file to load
  86701. * @returns a new {BABYLON.BinaryFileAssetTask} object
  86702. */
  86703. AssetsManager.prototype.addBinaryFileTask = function (taskName, url) {
  86704. var task = new BinaryFileAssetTask(taskName, url);
  86705. this._tasks.push(task);
  86706. return task;
  86707. };
  86708. /**
  86709. * Add a {BABYLON.ImageAssetTask} to the list of active tasks
  86710. * @param taskName defines the name of the new task
  86711. * @param url defines the url of the file to load
  86712. * @returns a new {BABYLON.ImageAssetTask} object
  86713. */
  86714. AssetsManager.prototype.addImageTask = function (taskName, url) {
  86715. var task = new ImageAssetTask(taskName, url);
  86716. this._tasks.push(task);
  86717. return task;
  86718. };
  86719. /**
  86720. * Add a {BABYLON.TextureAssetTask} to the list of active tasks
  86721. * @param taskName defines the name of the new task
  86722. * @param url defines the url of the file to load
  86723. * @param noMipmap defines if the texture must not receive mipmaps (false by default)
  86724. * @param invertY defines if you want to invert Y axis of the loaded texture (false by default)
  86725. * @param samplingMode defines the sampling mode to use (BABYLON.Texture.TRILINEAR_SAMPLINGMODE by default)
  86726. * @returns a new {BABYLON.TextureAssetTask} object
  86727. */
  86728. AssetsManager.prototype.addTextureTask = function (taskName, url, noMipmap, invertY, samplingMode) {
  86729. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  86730. var task = new TextureAssetTask(taskName, url, noMipmap, invertY, samplingMode);
  86731. this._tasks.push(task);
  86732. return task;
  86733. };
  86734. /**
  86735. * Add a {BABYLON.CubeTextureAssetTask} to the list of active tasks
  86736. * @param taskName defines the name of the new task
  86737. * @param url defines the url of the file to load
  86738. * @param extensions defines the extension to use to load the cube map (can be null)
  86739. * @param noMipmap defines if the texture must not receive mipmaps (false by default)
  86740. * @param files defines the list of files to load (can be null)
  86741. * @returns a new {BABYLON.CubeTextureAssetTask} object
  86742. */
  86743. AssetsManager.prototype.addCubeTextureTask = function (taskName, url, extensions, noMipmap, files) {
  86744. var task = new CubeTextureAssetTask(taskName, url, extensions, noMipmap, files);
  86745. this._tasks.push(task);
  86746. return task;
  86747. };
  86748. /**
  86749. *
  86750. * Add a {BABYLON.HDRCubeTextureAssetTask} to the list of active tasks
  86751. * @param taskName defines the name of the new task
  86752. * @param url defines the url of the file to load
  86753. * @param size defines the size you want for the cubemap (can be null)
  86754. * @param noMipmap defines if the texture must not receive mipmaps (false by default)
  86755. * @param generateHarmonics defines if you want to automatically generate (true by default)
  86756. * @param useInGammaSpace defines if the texture must be considered in gamma space (false by default)
  86757. * @param usePMREMGenerator is a reserved parameter and must be set to false or ignored
  86758. * @returns a new {BABYLON.HDRCubeTextureAssetTask} object
  86759. */
  86760. AssetsManager.prototype.addHDRCubeTextureTask = function (taskName, url, size, noMipmap, generateHarmonics, useInGammaSpace, usePMREMGenerator) {
  86761. if (noMipmap === void 0) { noMipmap = false; }
  86762. if (generateHarmonics === void 0) { generateHarmonics = true; }
  86763. if (useInGammaSpace === void 0) { useInGammaSpace = false; }
  86764. if (usePMREMGenerator === void 0) { usePMREMGenerator = false; }
  86765. var task = new HDRCubeTextureAssetTask(taskName, url, size, noMipmap, generateHarmonics, useInGammaSpace, usePMREMGenerator);
  86766. this._tasks.push(task);
  86767. return task;
  86768. };
  86769. AssetsManager.prototype._decreaseWaitingTasksCount = function (task) {
  86770. var _this = this;
  86771. this._waitingTasksCount--;
  86772. try {
  86773. if (task.taskState === AssetTaskState.DONE) {
  86774. // Let's remove successfull tasks
  86775. BABYLON.Tools.SetImmediate(function () {
  86776. var index = _this._tasks.indexOf(task);
  86777. if (index > -1) {
  86778. _this._tasks.splice(index, 1);
  86779. }
  86780. });
  86781. }
  86782. if (this.onProgress) {
  86783. this.onProgress(this._waitingTasksCount, this._totalTasksCount, task);
  86784. }
  86785. this.onProgressObservable.notifyObservers(new AssetsProgressEvent(this._waitingTasksCount, this._totalTasksCount, task));
  86786. }
  86787. catch (e) {
  86788. BABYLON.Tools.Error("Error running progress callbacks.");
  86789. console.log(e);
  86790. }
  86791. if (this._waitingTasksCount === 0) {
  86792. try {
  86793. if (this.onFinish) {
  86794. this.onFinish(this._tasks);
  86795. }
  86796. this.onTasksDoneObservable.notifyObservers(this._tasks);
  86797. }
  86798. catch (e) {
  86799. BABYLON.Tools.Error("Error running tasks-done callbacks.");
  86800. console.log(e);
  86801. }
  86802. this._isLoading = false;
  86803. this._scene.getEngine().hideLoadingUI();
  86804. }
  86805. };
  86806. AssetsManager.prototype._runTask = function (task) {
  86807. var _this = this;
  86808. var done = function () {
  86809. try {
  86810. if (_this.onTaskSuccess) {
  86811. _this.onTaskSuccess(task);
  86812. }
  86813. _this.onTaskSuccessObservable.notifyObservers(task);
  86814. _this._decreaseWaitingTasksCount(task);
  86815. }
  86816. catch (e) {
  86817. error("Error executing task success callbacks", e);
  86818. }
  86819. };
  86820. var error = function (message, exception) {
  86821. task._setErrorObject(message, exception);
  86822. if (_this.onTaskError) {
  86823. _this.onTaskError(task);
  86824. }
  86825. _this.onTaskErrorObservable.notifyObservers(task);
  86826. _this._decreaseWaitingTasksCount(task);
  86827. };
  86828. task.run(this._scene, done, error);
  86829. };
  86830. /**
  86831. * Reset the {BABYLON.AssetsManager} and remove all tasks
  86832. * @return the current instance of the {BABYLON.AssetsManager}
  86833. */
  86834. AssetsManager.prototype.reset = function () {
  86835. this._isLoading = false;
  86836. this._tasks = new Array();
  86837. return this;
  86838. };
  86839. /**
  86840. * Start the loading process
  86841. * @return the current instance of the {BABYLON.AssetsManager}
  86842. */
  86843. AssetsManager.prototype.load = function () {
  86844. if (this._isLoading) {
  86845. return this;
  86846. }
  86847. this._isLoading = true;
  86848. this._waitingTasksCount = this._tasks.length;
  86849. this._totalTasksCount = this._tasks.length;
  86850. if (this._waitingTasksCount === 0) {
  86851. this._isLoading = false;
  86852. if (this.onFinish) {
  86853. this.onFinish(this._tasks);
  86854. }
  86855. this.onTasksDoneObservable.notifyObservers(this._tasks);
  86856. return this;
  86857. }
  86858. if (this.useDefaultLoadingScreen) {
  86859. this._scene.getEngine().displayLoadingUI();
  86860. }
  86861. for (var index = 0; index < this._tasks.length; index++) {
  86862. var task = this._tasks[index];
  86863. this._runTask(task);
  86864. }
  86865. return this;
  86866. };
  86867. return AssetsManager;
  86868. }());
  86869. BABYLON.AssetsManager = AssetsManager;
  86870. })(BABYLON || (BABYLON = {}));
  86871. //# sourceMappingURL=babylon.assetsManager.js.map
  86872. var BABYLON;
  86873. (function (BABYLON) {
  86874. var serializedGeometries = [];
  86875. var serializeGeometry = function (geometry, serializationGeometries) {
  86876. if (serializedGeometries[geometry.id]) {
  86877. return;
  86878. }
  86879. if (geometry.doNotSerialize) {
  86880. return;
  86881. }
  86882. if (geometry instanceof BABYLON.BoxGeometry) {
  86883. serializationGeometries.boxes.push(geometry.serialize());
  86884. }
  86885. else if (geometry instanceof BABYLON.SphereGeometry) {
  86886. serializationGeometries.spheres.push(geometry.serialize());
  86887. }
  86888. else if (geometry instanceof BABYLON.CylinderGeometry) {
  86889. serializationGeometries.cylinders.push(geometry.serialize());
  86890. }
  86891. else if (geometry instanceof BABYLON.TorusGeometry) {
  86892. serializationGeometries.toruses.push(geometry.serialize());
  86893. }
  86894. else if (geometry instanceof BABYLON.GroundGeometry) {
  86895. serializationGeometries.grounds.push(geometry.serialize());
  86896. }
  86897. else if (geometry instanceof BABYLON.Plane) {
  86898. serializationGeometries.planes.push(geometry.serialize());
  86899. }
  86900. else if (geometry instanceof BABYLON.TorusKnotGeometry) {
  86901. serializationGeometries.torusKnots.push(geometry.serialize());
  86902. }
  86903. else if (geometry instanceof BABYLON._PrimitiveGeometry) {
  86904. throw new Error("Unknown primitive type");
  86905. }
  86906. else {
  86907. serializationGeometries.vertexData.push(geometry.serializeVerticeData());
  86908. }
  86909. serializedGeometries[geometry.id] = true;
  86910. };
  86911. var serializeMesh = function (mesh, serializationScene) {
  86912. var serializationObject = {};
  86913. // Geometry
  86914. var geometry = mesh._geometry;
  86915. if (geometry) {
  86916. if (!mesh.getScene().getGeometryByID(geometry.id)) {
  86917. // 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
  86918. serializeGeometry(geometry, serializationScene.geometries);
  86919. }
  86920. }
  86921. // Custom
  86922. if (mesh.serialize) {
  86923. mesh.serialize(serializationObject);
  86924. }
  86925. return serializationObject;
  86926. };
  86927. var finalizeSingleMesh = function (mesh, serializationObject) {
  86928. //only works if the mesh is already loaded
  86929. if (mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE) {
  86930. //serialize material
  86931. if (mesh.material) {
  86932. if (mesh.material instanceof BABYLON.StandardMaterial) {
  86933. serializationObject.materials = serializationObject.materials || [];
  86934. if (!serializationObject.materials.some(function (mat) { return (mat.id === mesh.material.id); })) {
  86935. serializationObject.materials.push(mesh.material.serialize());
  86936. }
  86937. }
  86938. else if (mesh.material instanceof BABYLON.MultiMaterial) {
  86939. serializationObject.multiMaterials = serializationObject.multiMaterials || [];
  86940. if (!serializationObject.multiMaterials.some(function (mat) { return (mat.id === mesh.material.id); })) {
  86941. serializationObject.multiMaterials.push(mesh.material.serialize());
  86942. }
  86943. }
  86944. }
  86945. //serialize geometry
  86946. var geometry = mesh._geometry;
  86947. if (geometry) {
  86948. if (!serializationObject.geometries) {
  86949. serializationObject.geometries = {};
  86950. serializationObject.geometries.boxes = [];
  86951. serializationObject.geometries.spheres = [];
  86952. serializationObject.geometries.cylinders = [];
  86953. serializationObject.geometries.toruses = [];
  86954. serializationObject.geometries.grounds = [];
  86955. serializationObject.geometries.planes = [];
  86956. serializationObject.geometries.torusKnots = [];
  86957. serializationObject.geometries.vertexData = [];
  86958. }
  86959. serializeGeometry(geometry, serializationObject.geometries);
  86960. }
  86961. // Skeletons
  86962. if (mesh.skeleton) {
  86963. serializationObject.skeletons = serializationObject.skeletons || [];
  86964. serializationObject.skeletons.push(mesh.skeleton.serialize());
  86965. }
  86966. //serialize the actual mesh
  86967. serializationObject.meshes = serializationObject.meshes || [];
  86968. serializationObject.meshes.push(serializeMesh(mesh, serializationObject));
  86969. }
  86970. };
  86971. var SceneSerializer = /** @class */ (function () {
  86972. function SceneSerializer() {
  86973. }
  86974. SceneSerializer.ClearCache = function () {
  86975. serializedGeometries = [];
  86976. };
  86977. SceneSerializer.Serialize = function (scene) {
  86978. var serializationObject = {};
  86979. SceneSerializer.ClearCache();
  86980. // Scene
  86981. serializationObject.useDelayedTextureLoading = scene.useDelayedTextureLoading;
  86982. serializationObject.autoClear = scene.autoClear;
  86983. serializationObject.clearColor = scene.clearColor.asArray();
  86984. serializationObject.ambientColor = scene.ambientColor.asArray();
  86985. serializationObject.gravity = scene.gravity.asArray();
  86986. serializationObject.collisionsEnabled = scene.collisionsEnabled;
  86987. serializationObject.workerCollisions = scene.workerCollisions;
  86988. // Fog
  86989. if (scene.fogMode && scene.fogMode !== 0) {
  86990. serializationObject.fogMode = scene.fogMode;
  86991. serializationObject.fogColor = scene.fogColor.asArray();
  86992. serializationObject.fogStart = scene.fogStart;
  86993. serializationObject.fogEnd = scene.fogEnd;
  86994. serializationObject.fogDensity = scene.fogDensity;
  86995. }
  86996. //Physics
  86997. if (scene.isPhysicsEnabled()) {
  86998. var physicEngine = scene.getPhysicsEngine();
  86999. if (physicEngine) {
  87000. serializationObject.physicsEnabled = true;
  87001. serializationObject.physicsGravity = physicEngine.gravity.asArray();
  87002. serializationObject.physicsEngine = physicEngine.getPhysicsPluginName();
  87003. }
  87004. }
  87005. // Metadata
  87006. if (scene.metadata) {
  87007. serializationObject.metadata = scene.metadata;
  87008. }
  87009. // Morph targets
  87010. serializationObject.morphTargetManagers = [];
  87011. for (var _i = 0, _a = scene.meshes; _i < _a.length; _i++) {
  87012. var abstractMesh = _a[_i];
  87013. var manager = abstractMesh.morphTargetManager;
  87014. if (manager) {
  87015. serializationObject.morphTargetManagers.push(manager.serialize());
  87016. }
  87017. }
  87018. // Lights
  87019. serializationObject.lights = [];
  87020. var index;
  87021. var light;
  87022. for (index = 0; index < scene.lights.length; index++) {
  87023. light = scene.lights[index];
  87024. if (!light.doNotSerialize) {
  87025. serializationObject.lights.push(light.serialize());
  87026. }
  87027. }
  87028. // Cameras
  87029. serializationObject.cameras = [];
  87030. for (index = 0; index < scene.cameras.length; index++) {
  87031. var camera = scene.cameras[index];
  87032. if (!camera.doNotSerialize) {
  87033. serializationObject.cameras.push(camera.serialize());
  87034. }
  87035. }
  87036. if (scene.activeCamera) {
  87037. serializationObject.activeCameraID = scene.activeCamera.id;
  87038. }
  87039. // Animations
  87040. BABYLON.Animation.AppendSerializedAnimations(scene, serializationObject);
  87041. // Materials
  87042. serializationObject.materials = [];
  87043. serializationObject.multiMaterials = [];
  87044. var material;
  87045. for (index = 0; index < scene.materials.length; index++) {
  87046. material = scene.materials[index];
  87047. if (!material.doNotSerialize) {
  87048. serializationObject.materials.push(material.serialize());
  87049. }
  87050. }
  87051. // MultiMaterials
  87052. serializationObject.multiMaterials = [];
  87053. for (index = 0; index < scene.multiMaterials.length; index++) {
  87054. var multiMaterial = scene.multiMaterials[index];
  87055. serializationObject.multiMaterials.push(multiMaterial.serialize());
  87056. }
  87057. // Environment texture
  87058. if (scene.environmentTexture) {
  87059. serializationObject.environmentTexture = scene.environmentTexture.name;
  87060. }
  87061. // Skeletons
  87062. serializationObject.skeletons = [];
  87063. for (index = 0; index < scene.skeletons.length; index++) {
  87064. var skeleton = scene.skeletons[index];
  87065. if (!skeleton.doNotSerialize) {
  87066. serializationObject.skeletons.push(skeleton.serialize());
  87067. }
  87068. }
  87069. // Transform nodes
  87070. serializationObject.transformNodes = [];
  87071. for (index = 0; index < scene.transformNodes.length; index++) {
  87072. serializationObject.transformNodes.push(scene.transformNodes[index].serialize());
  87073. }
  87074. // Geometries
  87075. serializationObject.geometries = {};
  87076. serializationObject.geometries.boxes = [];
  87077. serializationObject.geometries.spheres = [];
  87078. serializationObject.geometries.cylinders = [];
  87079. serializationObject.geometries.toruses = [];
  87080. serializationObject.geometries.grounds = [];
  87081. serializationObject.geometries.planes = [];
  87082. serializationObject.geometries.torusKnots = [];
  87083. serializationObject.geometries.vertexData = [];
  87084. serializedGeometries = [];
  87085. var geometries = scene.getGeometries();
  87086. for (index = 0; index < geometries.length; index++) {
  87087. var geometry = geometries[index];
  87088. if (geometry.isReady()) {
  87089. serializeGeometry(geometry, serializationObject.geometries);
  87090. }
  87091. }
  87092. // Meshes
  87093. serializationObject.meshes = [];
  87094. for (index = 0; index < scene.meshes.length; index++) {
  87095. var abstractMesh = scene.meshes[index];
  87096. if (abstractMesh instanceof BABYLON.Mesh) {
  87097. var mesh = abstractMesh;
  87098. if (!mesh.doNotSerialize) {
  87099. if (mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE) {
  87100. serializationObject.meshes.push(serializeMesh(mesh, serializationObject));
  87101. }
  87102. }
  87103. }
  87104. }
  87105. // Particles Systems
  87106. serializationObject.particleSystems = [];
  87107. for (index = 0; index < scene.particleSystems.length; index++) {
  87108. serializationObject.particleSystems.push(scene.particleSystems[index].serialize());
  87109. }
  87110. // Lens flares
  87111. serializationObject.lensFlareSystems = [];
  87112. for (index = 0; index < scene.lensFlareSystems.length; index++) {
  87113. serializationObject.lensFlareSystems.push(scene.lensFlareSystems[index].serialize());
  87114. }
  87115. // Shadows
  87116. serializationObject.shadowGenerators = [];
  87117. for (index = 0; index < scene.lights.length; index++) {
  87118. light = scene.lights[index];
  87119. var shadowGenerator = light.getShadowGenerator();
  87120. if (shadowGenerator) {
  87121. serializationObject.shadowGenerators.push(shadowGenerator.serialize());
  87122. }
  87123. }
  87124. // Action Manager
  87125. if (scene.actionManager) {
  87126. serializationObject.actions = scene.actionManager.serialize("scene");
  87127. }
  87128. // Audio
  87129. serializationObject.sounds = [];
  87130. for (index = 0; index < scene.soundTracks.length; index++) {
  87131. var soundtrack = scene.soundTracks[index];
  87132. for (var soundId = 0; soundId < soundtrack.soundCollection.length; soundId++) {
  87133. serializationObject.sounds.push(soundtrack.soundCollection[soundId].serialize());
  87134. }
  87135. }
  87136. return serializationObject;
  87137. };
  87138. SceneSerializer.SerializeMesh = function (toSerialize /* Mesh || Mesh[] */, withParents, withChildren) {
  87139. if (withParents === void 0) { withParents = false; }
  87140. if (withChildren === void 0) { withChildren = false; }
  87141. var serializationObject = {};
  87142. SceneSerializer.ClearCache();
  87143. toSerialize = (toSerialize instanceof Array) ? toSerialize : [toSerialize];
  87144. if (withParents || withChildren) {
  87145. //deliberate for loop! not for each, appended should be processed as well.
  87146. for (var i = 0; i < toSerialize.length; ++i) {
  87147. if (withChildren) {
  87148. toSerialize[i].getDescendants().forEach(function (node) {
  87149. if (node instanceof BABYLON.Mesh && (toSerialize.indexOf(node) < 0)) {
  87150. toSerialize.push(node);
  87151. }
  87152. });
  87153. }
  87154. //make sure the array doesn't contain the object already
  87155. if (withParents && toSerialize[i].parent && (toSerialize.indexOf(toSerialize[i].parent) < 0)) {
  87156. toSerialize.push(toSerialize[i].parent);
  87157. }
  87158. }
  87159. }
  87160. toSerialize.forEach(function (mesh) {
  87161. finalizeSingleMesh(mesh, serializationObject);
  87162. });
  87163. return serializationObject;
  87164. };
  87165. return SceneSerializer;
  87166. }());
  87167. BABYLON.SceneSerializer = SceneSerializer;
  87168. })(BABYLON || (BABYLON = {}));
  87169. //# sourceMappingURL=babylon.sceneSerializer.js.map
  87170. var BABYLON;
  87171. (function (BABYLON) {
  87172. var ReflectionProbe = /** @class */ (function () {
  87173. function ReflectionProbe(name, size, scene, generateMipMaps) {
  87174. if (generateMipMaps === void 0) { generateMipMaps = true; }
  87175. var _this = this;
  87176. this.name = name;
  87177. this._viewMatrix = BABYLON.Matrix.Identity();
  87178. this._target = BABYLON.Vector3.Zero();
  87179. this._add = BABYLON.Vector3.Zero();
  87180. this._invertYAxis = false;
  87181. this.position = BABYLON.Vector3.Zero();
  87182. this._scene = scene;
  87183. this._scene.reflectionProbes.push(this);
  87184. this._renderTargetTexture = new BABYLON.RenderTargetTexture(name, size, scene, generateMipMaps, true, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT, true);
  87185. this._renderTargetTexture.onBeforeRenderObservable.add(function (faceIndex) {
  87186. switch (faceIndex) {
  87187. case 0:
  87188. _this._add.copyFromFloats(1, 0, 0);
  87189. break;
  87190. case 1:
  87191. _this._add.copyFromFloats(-1, 0, 0);
  87192. break;
  87193. case 2:
  87194. _this._add.copyFromFloats(0, _this._invertYAxis ? 1 : -1, 0);
  87195. break;
  87196. case 3:
  87197. _this._add.copyFromFloats(0, _this._invertYAxis ? -1 : 1, 0);
  87198. break;
  87199. case 4:
  87200. _this._add.copyFromFloats(0, 0, 1);
  87201. break;
  87202. case 5:
  87203. _this._add.copyFromFloats(0, 0, -1);
  87204. break;
  87205. }
  87206. if (_this._attachedMesh) {
  87207. _this.position.copyFrom(_this._attachedMesh.getAbsolutePosition());
  87208. }
  87209. _this.position.addToRef(_this._add, _this._target);
  87210. BABYLON.Matrix.LookAtLHToRef(_this.position, _this._target, BABYLON.Vector3.Up(), _this._viewMatrix);
  87211. scene.setTransformMatrix(_this._viewMatrix, _this._projectionMatrix);
  87212. scene._forcedViewPosition = _this.position;
  87213. });
  87214. this._renderTargetTexture.onAfterUnbindObservable.add(function () {
  87215. scene._forcedViewPosition = null;
  87216. scene.updateTransformMatrix(true);
  87217. });
  87218. if (scene.activeCamera) {
  87219. this._projectionMatrix = BABYLON.Matrix.PerspectiveFovLH(Math.PI / 2, 1, scene.activeCamera.minZ, scene.activeCamera.maxZ);
  87220. }
  87221. }
  87222. Object.defineProperty(ReflectionProbe.prototype, "samples", {
  87223. get: function () {
  87224. return this._renderTargetTexture.samples;
  87225. },
  87226. set: function (value) {
  87227. this._renderTargetTexture.samples = value;
  87228. },
  87229. enumerable: true,
  87230. configurable: true
  87231. });
  87232. Object.defineProperty(ReflectionProbe.prototype, "refreshRate", {
  87233. get: function () {
  87234. return this._renderTargetTexture.refreshRate;
  87235. },
  87236. set: function (value) {
  87237. this._renderTargetTexture.refreshRate = value;
  87238. },
  87239. enumerable: true,
  87240. configurable: true
  87241. });
  87242. ReflectionProbe.prototype.getScene = function () {
  87243. return this._scene;
  87244. };
  87245. Object.defineProperty(ReflectionProbe.prototype, "cubeTexture", {
  87246. get: function () {
  87247. return this._renderTargetTexture;
  87248. },
  87249. enumerable: true,
  87250. configurable: true
  87251. });
  87252. Object.defineProperty(ReflectionProbe.prototype, "renderList", {
  87253. get: function () {
  87254. return this._renderTargetTexture.renderList;
  87255. },
  87256. enumerable: true,
  87257. configurable: true
  87258. });
  87259. ReflectionProbe.prototype.attachToMesh = function (mesh) {
  87260. this._attachedMesh = mesh;
  87261. };
  87262. /**
  87263. * Specifies whether or not the stencil and depth buffer are cleared between two rendering groups.
  87264. *
  87265. * @param renderingGroupId The rendering group id corresponding to its index
  87266. * @param autoClearDepthStencil Automatically clears depth and stencil between groups if true.
  87267. */
  87268. ReflectionProbe.prototype.setRenderingAutoClearDepthStencil = function (renderingGroupId, autoClearDepthStencil) {
  87269. this._renderTargetTexture.setRenderingAutoClearDepthStencil(renderingGroupId, autoClearDepthStencil);
  87270. };
  87271. ReflectionProbe.prototype.dispose = function () {
  87272. var index = this._scene.reflectionProbes.indexOf(this);
  87273. if (index !== -1) {
  87274. // Remove from the scene if found
  87275. this._scene.reflectionProbes.splice(index, 1);
  87276. }
  87277. if (this._renderTargetTexture) {
  87278. this._renderTargetTexture.dispose();
  87279. this._renderTargetTexture = null;
  87280. }
  87281. };
  87282. return ReflectionProbe;
  87283. }());
  87284. BABYLON.ReflectionProbe = ReflectionProbe;
  87285. })(BABYLON || (BABYLON = {}));
  87286. //# sourceMappingURL=babylon.reflectionProbe.js.map
  87287. var BABYLON;
  87288. (function (BABYLON) {
  87289. var Layer = /** @class */ (function () {
  87290. function Layer(name, imgUrl, scene, isBackground, color) {
  87291. this.name = name;
  87292. this.scale = new BABYLON.Vector2(1, 1);
  87293. this.offset = new BABYLON.Vector2(0, 0);
  87294. this.alphaBlendingMode = BABYLON.Engine.ALPHA_COMBINE;
  87295. this.layerMask = 0x0FFFFFFF;
  87296. this._vertexBuffers = {};
  87297. // Events
  87298. /**
  87299. * An event triggered when the layer is disposed.
  87300. * @type {BABYLON.Observable}
  87301. */
  87302. this.onDisposeObservable = new BABYLON.Observable();
  87303. /**
  87304. * An event triggered before rendering the scene
  87305. * @type {BABYLON.Observable}
  87306. */
  87307. this.onBeforeRenderObservable = new BABYLON.Observable();
  87308. /**
  87309. * An event triggered after rendering the scene
  87310. * @type {BABYLON.Observable}
  87311. */
  87312. this.onAfterRenderObservable = new BABYLON.Observable();
  87313. this.texture = imgUrl ? new BABYLON.Texture(imgUrl, scene, true) : null;
  87314. this.isBackground = isBackground === undefined ? true : isBackground;
  87315. this.color = color === undefined ? new BABYLON.Color4(1, 1, 1, 1) : color;
  87316. this._scene = (scene || BABYLON.Engine.LastCreatedScene);
  87317. this._scene.layers.push(this);
  87318. var engine = this._scene.getEngine();
  87319. // VBO
  87320. var vertices = [];
  87321. vertices.push(1, 1);
  87322. vertices.push(-1, 1);
  87323. vertices.push(-1, -1);
  87324. vertices.push(1, -1);
  87325. var vertexBuffer = new BABYLON.VertexBuffer(engine, vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  87326. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = vertexBuffer;
  87327. this._createIndexBuffer();
  87328. // Effects
  87329. this._effect = engine.createEffect("layer", [BABYLON.VertexBuffer.PositionKind], ["textureMatrix", "color", "scale", "offset"], ["textureSampler"], "");
  87330. this._alphaTestEffect = engine.createEffect("layer", [BABYLON.VertexBuffer.PositionKind], ["textureMatrix", "color", "scale", "offset"], ["textureSampler"], "#define ALPHATEST");
  87331. }
  87332. Object.defineProperty(Layer.prototype, "onDispose", {
  87333. set: function (callback) {
  87334. if (this._onDisposeObserver) {
  87335. this.onDisposeObservable.remove(this._onDisposeObserver);
  87336. }
  87337. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  87338. },
  87339. enumerable: true,
  87340. configurable: true
  87341. });
  87342. Object.defineProperty(Layer.prototype, "onBeforeRender", {
  87343. set: function (callback) {
  87344. if (this._onBeforeRenderObserver) {
  87345. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  87346. }
  87347. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  87348. },
  87349. enumerable: true,
  87350. configurable: true
  87351. });
  87352. Object.defineProperty(Layer.prototype, "onAfterRender", {
  87353. set: function (callback) {
  87354. if (this._onAfterRenderObserver) {
  87355. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  87356. }
  87357. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  87358. },
  87359. enumerable: true,
  87360. configurable: true
  87361. });
  87362. Layer.prototype._createIndexBuffer = function () {
  87363. var engine = this._scene.getEngine();
  87364. // Indices
  87365. var indices = [];
  87366. indices.push(0);
  87367. indices.push(1);
  87368. indices.push(2);
  87369. indices.push(0);
  87370. indices.push(2);
  87371. indices.push(3);
  87372. this._indexBuffer = engine.createIndexBuffer(indices);
  87373. };
  87374. Layer.prototype._rebuild = function () {
  87375. var vb = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  87376. if (vb) {
  87377. vb._rebuild();
  87378. }
  87379. this._createIndexBuffer();
  87380. };
  87381. Layer.prototype.render = function () {
  87382. var currentEffect = this.alphaTest ? this._alphaTestEffect : this._effect;
  87383. // Check
  87384. if (!currentEffect.isReady() || !this.texture || !this.texture.isReady())
  87385. return;
  87386. var engine = this._scene.getEngine();
  87387. this.onBeforeRenderObservable.notifyObservers(this);
  87388. // Render
  87389. engine.enableEffect(currentEffect);
  87390. engine.setState(false);
  87391. // Texture
  87392. currentEffect.setTexture("textureSampler", this.texture);
  87393. currentEffect.setMatrix("textureMatrix", this.texture.getTextureMatrix());
  87394. // Color
  87395. currentEffect.setFloat4("color", this.color.r, this.color.g, this.color.b, this.color.a);
  87396. // Scale / offset
  87397. currentEffect.setVector2("offset", this.offset);
  87398. currentEffect.setVector2("scale", this.scale);
  87399. // VBOs
  87400. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, currentEffect);
  87401. // Draw order
  87402. if (!this.alphaTest) {
  87403. engine.setAlphaMode(this.alphaBlendingMode);
  87404. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  87405. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  87406. }
  87407. else {
  87408. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  87409. }
  87410. this.onAfterRenderObservable.notifyObservers(this);
  87411. };
  87412. Layer.prototype.dispose = function () {
  87413. var vertexBuffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  87414. if (vertexBuffer) {
  87415. vertexBuffer.dispose();
  87416. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  87417. }
  87418. if (this._indexBuffer) {
  87419. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  87420. this._indexBuffer = null;
  87421. }
  87422. if (this.texture) {
  87423. this.texture.dispose();
  87424. this.texture = null;
  87425. }
  87426. // Remove from scene
  87427. var index = this._scene.layers.indexOf(this);
  87428. this._scene.layers.splice(index, 1);
  87429. // Callback
  87430. this.onDisposeObservable.notifyObservers(this);
  87431. this.onDisposeObservable.clear();
  87432. this.onAfterRenderObservable.clear();
  87433. this.onBeforeRenderObservable.clear();
  87434. };
  87435. return Layer;
  87436. }());
  87437. BABYLON.Layer = Layer;
  87438. })(BABYLON || (BABYLON = {}));
  87439. //# sourceMappingURL=babylon.layer.js.map
  87440. var BABYLON;
  87441. (function (BABYLON) {
  87442. var TextureTools = /** @class */ (function () {
  87443. function TextureTools() {
  87444. }
  87445. /**
  87446. * Uses the GPU to create a copy texture rescaled at a given size
  87447. * @param texture Texture to copy from
  87448. * @param width Desired width
  87449. * @param height Desired height
  87450. * @return Generated texture
  87451. */
  87452. TextureTools.CreateResizedCopy = function (texture, width, height, useBilinearMode) {
  87453. if (useBilinearMode === void 0) { useBilinearMode = true; }
  87454. var scene = texture.getScene();
  87455. var engine = scene.getEngine();
  87456. var rtt = new BABYLON.RenderTargetTexture('resized' + texture.name, { width: width, height: height }, scene, !texture.noMipmap, true, texture._texture.type, false, texture._samplingMode, false);
  87457. rtt.wrapU = texture.wrapU;
  87458. rtt.wrapV = texture.wrapV;
  87459. rtt.uOffset = texture.uOffset;
  87460. rtt.vOffset = texture.vOffset;
  87461. rtt.uScale = texture.uScale;
  87462. rtt.vScale = texture.vScale;
  87463. rtt.uAng = texture.uAng;
  87464. rtt.vAng = texture.vAng;
  87465. rtt.wAng = texture.wAng;
  87466. rtt.coordinatesIndex = texture.coordinatesIndex;
  87467. rtt.level = texture.level;
  87468. rtt.anisotropicFilteringLevel = texture.anisotropicFilteringLevel;
  87469. rtt._texture.isReady = false;
  87470. texture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  87471. texture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  87472. var passPostProcess = new BABYLON.PassPostProcess("pass", 1, null, useBilinearMode ? BABYLON.Texture.BILINEAR_SAMPLINGMODE : BABYLON.Texture.NEAREST_SAMPLINGMODE, engine, false, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  87473. passPostProcess.getEffect().executeWhenCompiled(function () {
  87474. passPostProcess.onApply = function (effect) {
  87475. effect.setTexture("textureSampler", texture);
  87476. };
  87477. var internalTexture = rtt.getInternalTexture();
  87478. if (internalTexture) {
  87479. scene.postProcessManager.directRender([passPostProcess], internalTexture);
  87480. engine.unBindFramebuffer(internalTexture);
  87481. rtt.disposeFramebufferObjects();
  87482. passPostProcess.dispose();
  87483. internalTexture.isReady = true;
  87484. }
  87485. });
  87486. return rtt;
  87487. };
  87488. TextureTools.GetEnvironmentBRDFTexture = function (scene) {
  87489. if (!scene._environmentBRDFTexture) {
  87490. var texture = BABYLON.Texture.CreateFromBase64String(this._environmentBRDFBase64Texture, "EnvironmentBRDFTexture", scene, true, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  87491. texture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  87492. texture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  87493. scene._environmentBRDFTexture = texture;
  87494. }
  87495. return scene._environmentBRDFTexture;
  87496. };
  87497. 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=";
  87498. return TextureTools;
  87499. }());
  87500. BABYLON.TextureTools = TextureTools;
  87501. })(BABYLON || (BABYLON = {}));
  87502. //# sourceMappingURL=babylon.textureTools.js.map
  87503. var BABYLON;
  87504. (function (BABYLON) {
  87505. var FramingBehavior = /** @class */ (function () {
  87506. function FramingBehavior() {
  87507. this._mode = FramingBehavior.FitFrustumSidesMode;
  87508. this._radiusScale = 1.0;
  87509. this._positionScale = 0.5;
  87510. this._defaultElevation = 0.3;
  87511. this._elevationReturnTime = 1500;
  87512. this._elevationReturnWaitTime = 1000;
  87513. this._zoomStopsAnimation = false;
  87514. this._framingTime = 1500;
  87515. this._isPointerDown = false;
  87516. this._lastInteractionTime = -Infinity;
  87517. // Framing control
  87518. this._animatables = new Array();
  87519. this._betaIsAnimating = false;
  87520. }
  87521. Object.defineProperty(FramingBehavior.prototype, "name", {
  87522. get: function () {
  87523. return "Framing";
  87524. },
  87525. enumerable: true,
  87526. configurable: true
  87527. });
  87528. Object.defineProperty(FramingBehavior.prototype, "mode", {
  87529. /**
  87530. * Gets current mode used by the behavior.
  87531. */
  87532. get: function () {
  87533. return this._mode;
  87534. },
  87535. /**
  87536. * Sets the current mode used by the behavior
  87537. */
  87538. set: function (mode) {
  87539. this._mode = mode;
  87540. },
  87541. enumerable: true,
  87542. configurable: true
  87543. });
  87544. Object.defineProperty(FramingBehavior.prototype, "radiusScale", {
  87545. /**
  87546. * Gets the scale applied to the radius
  87547. */
  87548. get: function () {
  87549. return this._radiusScale;
  87550. },
  87551. /**
  87552. * Sets the scale applied to the radius (1 by default)
  87553. */
  87554. set: function (radius) {
  87555. this._radiusScale = radius;
  87556. },
  87557. enumerable: true,
  87558. configurable: true
  87559. });
  87560. Object.defineProperty(FramingBehavior.prototype, "positionScale", {
  87561. /**
  87562. * Gets the scale to apply on Y axis to position camera focus. 0.5 by default which means the center of the bounding box.
  87563. */
  87564. get: function () {
  87565. return this._positionScale;
  87566. },
  87567. /**
  87568. * Sets the scale to apply on Y axis to position camera focus. 0.5 by default which means the center of the bounding box.
  87569. */
  87570. set: function (scale) {
  87571. this._positionScale = scale;
  87572. },
  87573. enumerable: true,
  87574. configurable: true
  87575. });
  87576. Object.defineProperty(FramingBehavior.prototype, "defaultElevation", {
  87577. /**
  87578. * Gets the angle above/below the horizontal plane to return to when the return to default elevation idle
  87579. * behaviour is triggered, in radians.
  87580. */
  87581. get: function () {
  87582. return this._defaultElevation;
  87583. },
  87584. /**
  87585. * Sets the angle above/below the horizontal plane to return to when the return to default elevation idle
  87586. * behaviour is triggered, in radians.
  87587. */
  87588. set: function (elevation) {
  87589. this._defaultElevation = elevation;
  87590. },
  87591. enumerable: true,
  87592. configurable: true
  87593. });
  87594. Object.defineProperty(FramingBehavior.prototype, "elevationReturnTime", {
  87595. /**
  87596. * Gets the time (in milliseconds) taken to return to the default beta position.
  87597. * Negative value indicates camera should not return to default.
  87598. */
  87599. get: function () {
  87600. return this._elevationReturnTime;
  87601. },
  87602. /**
  87603. * Sets the time (in milliseconds) taken to return to the default beta position.
  87604. * Negative value indicates camera should not return to default.
  87605. */
  87606. set: function (speed) {
  87607. this._elevationReturnTime = speed;
  87608. },
  87609. enumerable: true,
  87610. configurable: true
  87611. });
  87612. Object.defineProperty(FramingBehavior.prototype, "elevationReturnWaitTime", {
  87613. /**
  87614. * Gets the delay (in milliseconds) taken before the camera returns to the default beta position.
  87615. */
  87616. get: function () {
  87617. return this._elevationReturnWaitTime;
  87618. },
  87619. /**
  87620. * Sets the delay (in milliseconds) taken before the camera returns to the default beta position.
  87621. */
  87622. set: function (time) {
  87623. this._elevationReturnWaitTime = time;
  87624. },
  87625. enumerable: true,
  87626. configurable: true
  87627. });
  87628. Object.defineProperty(FramingBehavior.prototype, "zoomStopsAnimation", {
  87629. /**
  87630. * Gets the flag that indicates if user zooming should stop animation.
  87631. */
  87632. get: function () {
  87633. return this._zoomStopsAnimation;
  87634. },
  87635. /**
  87636. * Sets the flag that indicates if user zooming should stop animation.
  87637. */
  87638. set: function (flag) {
  87639. this._zoomStopsAnimation = flag;
  87640. },
  87641. enumerable: true,
  87642. configurable: true
  87643. });
  87644. Object.defineProperty(FramingBehavior.prototype, "framingTime", {
  87645. /**
  87646. * Gets the transition time when framing the mesh, in milliseconds
  87647. */
  87648. get: function () {
  87649. return this._framingTime;
  87650. },
  87651. /**
  87652. * Sets the transition time when framing the mesh, in milliseconds
  87653. */
  87654. set: function (time) {
  87655. this._framingTime = time;
  87656. },
  87657. enumerable: true,
  87658. configurable: true
  87659. });
  87660. FramingBehavior.prototype.init = function () {
  87661. // Do notihng
  87662. };
  87663. FramingBehavior.prototype.attach = function (camera) {
  87664. var _this = this;
  87665. this._attachedCamera = camera;
  87666. var scene = this._attachedCamera.getScene();
  87667. FramingBehavior.EasingFunction.setEasingMode(FramingBehavior.EasingMode);
  87668. this._onPrePointerObservableObserver = scene.onPrePointerObservable.add(function (pointerInfoPre) {
  87669. if (pointerInfoPre.type === BABYLON.PointerEventTypes.POINTERDOWN) {
  87670. _this._isPointerDown = true;
  87671. return;
  87672. }
  87673. if (pointerInfoPre.type === BABYLON.PointerEventTypes.POINTERUP) {
  87674. _this._isPointerDown = false;
  87675. }
  87676. });
  87677. this._onMeshTargetChangedObserver = camera.onMeshTargetChangedObservable.add(function (mesh) {
  87678. if (mesh) {
  87679. _this.zoomOnMesh(mesh);
  87680. }
  87681. });
  87682. this._onAfterCheckInputsObserver = camera.onAfterCheckInputsObservable.add(function () {
  87683. // Stop the animation if there is user interaction and the animation should stop for this interaction
  87684. _this._applyUserInteraction();
  87685. // Maintain the camera above the ground. If the user pulls the camera beneath the ground plane, lift it
  87686. // back to the default position after a given timeout
  87687. _this._maintainCameraAboveGround();
  87688. });
  87689. };
  87690. FramingBehavior.prototype.detach = function () {
  87691. if (!this._attachedCamera) {
  87692. return;
  87693. }
  87694. var scene = this._attachedCamera.getScene();
  87695. if (this._onPrePointerObservableObserver) {
  87696. scene.onPrePointerObservable.remove(this._onPrePointerObservableObserver);
  87697. }
  87698. if (this._onAfterCheckInputsObserver) {
  87699. this._attachedCamera.onAfterCheckInputsObservable.remove(this._onAfterCheckInputsObserver);
  87700. }
  87701. if (this._onMeshTargetChangedObserver) {
  87702. this._attachedCamera.onMeshTargetChangedObservable.remove(this._onMeshTargetChangedObserver);
  87703. }
  87704. this._attachedCamera = null;
  87705. };
  87706. /**
  87707. * Targets the given mesh and updates zoom level accordingly.
  87708. * @param mesh The mesh to target.
  87709. * @param radius Optional. If a cached radius position already exists, overrides default.
  87710. * @param framingPositionY Position on mesh to center camera focus where 0 corresponds bottom of its bounding box and 1, the top
  87711. * @param focusOnOriginXZ Determines if the camera should focus on 0 in the X and Z axis instead of the mesh
  87712. * @param onAnimationEnd Callback triggered at the end of the framing animation
  87713. */
  87714. FramingBehavior.prototype.zoomOnMesh = function (mesh, focusOnOriginXZ, onAnimationEnd) {
  87715. if (focusOnOriginXZ === void 0) { focusOnOriginXZ = false; }
  87716. if (onAnimationEnd === void 0) { onAnimationEnd = null; }
  87717. mesh.computeWorldMatrix(true);
  87718. var boundingBox = mesh.getBoundingInfo().boundingBox;
  87719. this.zoomOnBoundingInfo(boundingBox.minimumWorld, boundingBox.maximumWorld, focusOnOriginXZ, onAnimationEnd);
  87720. };
  87721. /**
  87722. * Targets the given mesh with its children and updates zoom level accordingly.
  87723. * @param mesh The mesh to target.
  87724. * @param radius Optional. If a cached radius position already exists, overrides default.
  87725. * @param framingPositionY Position on mesh to center camera focus where 0 corresponds bottom of its bounding box and 1, the top
  87726. * @param focusOnOriginXZ Determines if the camera should focus on 0 in the X and Z axis instead of the mesh
  87727. * @param onAnimationEnd Callback triggered at the end of the framing animation
  87728. */
  87729. FramingBehavior.prototype.zoomOnMeshHierarchy = function (mesh, focusOnOriginXZ, onAnimationEnd) {
  87730. if (focusOnOriginXZ === void 0) { focusOnOriginXZ = false; }
  87731. if (onAnimationEnd === void 0) { onAnimationEnd = null; }
  87732. mesh.computeWorldMatrix(true);
  87733. var boundingBox = mesh.getHierarchyBoundingVectors(true);
  87734. this.zoomOnBoundingInfo(boundingBox.min, boundingBox.max, focusOnOriginXZ, onAnimationEnd);
  87735. };
  87736. /**
  87737. * Targets the given meshes with their children and updates zoom level accordingly.
  87738. * @param meshes The mesh to target.
  87739. * @param radius Optional. If a cached radius position already exists, overrides default.
  87740. * @param framingPositionY Position on mesh to center camera focus where 0 corresponds bottom of its bounding box and 1, the top
  87741. * @param focusOnOriginXZ Determines if the camera should focus on 0 in the X and Z axis instead of the mesh
  87742. * @param onAnimationEnd Callback triggered at the end of the framing animation
  87743. */
  87744. FramingBehavior.prototype.zoomOnMeshesHierarchy = function (meshes, focusOnOriginXZ, onAnimationEnd) {
  87745. if (focusOnOriginXZ === void 0) { focusOnOriginXZ = false; }
  87746. if (onAnimationEnd === void 0) { onAnimationEnd = null; }
  87747. var min = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  87748. var max = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  87749. for (var i = 0; i < meshes.length; i++) {
  87750. var boundingInfo = meshes[i].getHierarchyBoundingVectors(true);
  87751. BABYLON.Tools.CheckExtends(boundingInfo.min, min, max);
  87752. BABYLON.Tools.CheckExtends(boundingInfo.max, min, max);
  87753. }
  87754. this.zoomOnBoundingInfo(min, max, focusOnOriginXZ, onAnimationEnd);
  87755. };
  87756. /**
  87757. * Targets the given mesh and updates zoom level accordingly.
  87758. * @param mesh The mesh to target.
  87759. * @param radius Optional. If a cached radius position already exists, overrides default.
  87760. * @param framingPositionY Position on mesh to center camera focus where 0 corresponds bottom of its bounding box and 1, the top
  87761. * @param focusOnOriginXZ Determines if the camera should focus on 0 in the X and Z axis instead of the mesh
  87762. * @param onAnimationEnd Callback triggered at the end of the framing animation
  87763. */
  87764. FramingBehavior.prototype.zoomOnBoundingInfo = function (minimumWorld, maximumWorld, focusOnOriginXZ, onAnimationEnd) {
  87765. var _this = this;
  87766. if (focusOnOriginXZ === void 0) { focusOnOriginXZ = false; }
  87767. if (onAnimationEnd === void 0) { onAnimationEnd = null; }
  87768. var zoomTarget;
  87769. if (!this._attachedCamera) {
  87770. return;
  87771. }
  87772. // Find target by interpolating from bottom of bounding box in world-space to top via framingPositionY
  87773. var bottom = minimumWorld.y;
  87774. var top = maximumWorld.y;
  87775. var zoomTargetY = bottom + (top - bottom) * this._positionScale;
  87776. var radiusWorld = maximumWorld.subtract(minimumWorld).scale(0.5);
  87777. if (focusOnOriginXZ) {
  87778. zoomTarget = new BABYLON.Vector3(0, zoomTargetY, 0);
  87779. }
  87780. else {
  87781. var centerWorld = minimumWorld.add(radiusWorld);
  87782. zoomTarget = new BABYLON.Vector3(centerWorld.x, zoomTargetY, centerWorld.z);
  87783. }
  87784. if (!this._vectorTransition) {
  87785. this._vectorTransition = BABYLON.Animation.CreateAnimation("target", BABYLON.Animation.ANIMATIONTYPE_VECTOR3, 60, FramingBehavior.EasingFunction);
  87786. }
  87787. this._betaIsAnimating = true;
  87788. var animatable = BABYLON.Animation.TransitionTo("target", zoomTarget, this._attachedCamera, this._attachedCamera.getScene(), 60, this._vectorTransition, this._framingTime);
  87789. if (animatable) {
  87790. this._animatables.push(animatable);
  87791. }
  87792. // sets the radius and lower radius bounds
  87793. // Small delta ensures camera is not always at lower zoom limit.
  87794. var radius = 0;
  87795. if (this._mode === FramingBehavior.FitFrustumSidesMode) {
  87796. var position = this._calculateLowerRadiusFromModelBoundingSphere(minimumWorld, maximumWorld);
  87797. this._attachedCamera.lowerRadiusLimit = radiusWorld.length() + this._attachedCamera.minZ;
  87798. radius = position;
  87799. }
  87800. else if (this._mode === FramingBehavior.IgnoreBoundsSizeMode) {
  87801. radius = this._calculateLowerRadiusFromModelBoundingSphere(minimumWorld, maximumWorld);
  87802. if (this._attachedCamera.lowerRadiusLimit === null) {
  87803. this._attachedCamera.lowerRadiusLimit = this._attachedCamera.minZ;
  87804. }
  87805. }
  87806. // Set sensibilities
  87807. var extend = maximumWorld.subtract(minimumWorld).length();
  87808. this._attachedCamera.panningSensibility = 5000 / extend;
  87809. this._attachedCamera.wheelPrecision = 100 / radius;
  87810. // transition to new radius
  87811. if (!this._radiusTransition) {
  87812. this._radiusTransition = BABYLON.Animation.CreateAnimation("radius", BABYLON.Animation.ANIMATIONTYPE_FLOAT, 60, FramingBehavior.EasingFunction);
  87813. }
  87814. animatable = BABYLON.Animation.TransitionTo("radius", radius, this._attachedCamera, this._attachedCamera.getScene(), 60, this._radiusTransition, this._framingTime, function () {
  87815. _this.stopAllAnimations();
  87816. if (onAnimationEnd) {
  87817. onAnimationEnd();
  87818. }
  87819. if (_this._attachedCamera) {
  87820. _this._attachedCamera.storeState();
  87821. }
  87822. });
  87823. if (animatable) {
  87824. this._animatables.push(animatable);
  87825. }
  87826. };
  87827. /**
  87828. * Calculates the lowest radius for the camera based on the bounding box of the mesh.
  87829. * @param mesh The mesh on which to base the calculation. mesh boundingInfo used to estimate necessary
  87830. * frustum width.
  87831. * @return The minimum distance from the primary mesh's center point at which the camera must be kept in order
  87832. * to fully enclose the mesh in the viewing frustum.
  87833. */
  87834. FramingBehavior.prototype._calculateLowerRadiusFromModelBoundingSphere = function (minimumWorld, maximumWorld) {
  87835. var size = maximumWorld.subtract(minimumWorld);
  87836. var boxVectorGlobalDiagonal = size.length();
  87837. var frustumSlope = this._getFrustumSlope();
  87838. // Formula for setting distance
  87839. // (Good explanation: http://stackoverflow.com/questions/2866350/move-camera-to-fit-3d-scene)
  87840. var radiusWithoutFraming = boxVectorGlobalDiagonal * 0.5;
  87841. // Horizon distance
  87842. var radius = radiusWithoutFraming * this._radiusScale;
  87843. var distanceForHorizontalFrustum = radius * Math.sqrt(1.0 + 1.0 / (frustumSlope.x * frustumSlope.x));
  87844. var distanceForVerticalFrustum = radius * Math.sqrt(1.0 + 1.0 / (frustumSlope.y * frustumSlope.y));
  87845. var distance = Math.max(distanceForHorizontalFrustum, distanceForVerticalFrustum);
  87846. var camera = this._attachedCamera;
  87847. if (!camera) {
  87848. return 0;
  87849. }
  87850. if (camera.lowerRadiusLimit && this._mode === FramingBehavior.IgnoreBoundsSizeMode) {
  87851. // Don't exceed the requested limit
  87852. distance = distance < camera.lowerRadiusLimit ? camera.lowerRadiusLimit : distance;
  87853. }
  87854. // Don't exceed the upper radius limit
  87855. if (camera.upperRadiusLimit) {
  87856. distance = distance > camera.upperRadiusLimit ? camera.upperRadiusLimit : distance;
  87857. }
  87858. return distance;
  87859. };
  87860. /**
  87861. * Keeps the camera above the ground plane. If the user pulls the camera below the ground plane, the camera
  87862. * is automatically returned to its default position (expected to be above ground plane).
  87863. */
  87864. FramingBehavior.prototype._maintainCameraAboveGround = function () {
  87865. var _this = this;
  87866. if (this._elevationReturnTime < 0) {
  87867. return;
  87868. }
  87869. var timeSinceInteraction = BABYLON.Tools.Now - this._lastInteractionTime;
  87870. var defaultBeta = Math.PI * 0.5 - this._defaultElevation;
  87871. var limitBeta = Math.PI * 0.5;
  87872. // Bring the camera back up if below the ground plane
  87873. if (this._attachedCamera && !this._betaIsAnimating && this._attachedCamera.beta > limitBeta && timeSinceInteraction >= this._elevationReturnWaitTime) {
  87874. this._betaIsAnimating = true;
  87875. //Transition to new position
  87876. this.stopAllAnimations();
  87877. if (!this._betaTransition) {
  87878. this._betaTransition = BABYLON.Animation.CreateAnimation("beta", BABYLON.Animation.ANIMATIONTYPE_FLOAT, 60, FramingBehavior.EasingFunction);
  87879. }
  87880. var animatabe = BABYLON.Animation.TransitionTo("beta", defaultBeta, this._attachedCamera, this._attachedCamera.getScene(), 60, this._betaTransition, this._elevationReturnTime, function () {
  87881. _this._clearAnimationLocks();
  87882. _this.stopAllAnimations();
  87883. });
  87884. if (animatabe) {
  87885. this._animatables.push(animatabe);
  87886. }
  87887. }
  87888. };
  87889. /**
  87890. * Returns the frustum slope based on the canvas ratio and camera FOV
  87891. * @returns The frustum slope represented as a Vector2 with X and Y slopes
  87892. */
  87893. FramingBehavior.prototype._getFrustumSlope = function () {
  87894. // Calculate the viewport ratio
  87895. // Aspect Ratio is Height/Width.
  87896. var camera = this._attachedCamera;
  87897. if (!camera) {
  87898. return BABYLON.Vector2.Zero();
  87899. }
  87900. var engine = camera.getScene().getEngine();
  87901. var aspectRatio = engine.getAspectRatio(camera);
  87902. // Camera FOV is the vertical field of view (top-bottom) in radians.
  87903. // Slope of the frustum top/bottom planes in view space, relative to the forward vector.
  87904. var frustumSlopeY = Math.tan(camera.fov / 2);
  87905. // Slope of the frustum left/right planes in view space, relative to the forward vector.
  87906. // Provides the amount that one side (e.g. left) of the frustum gets wider for every unit
  87907. // along the forward vector.
  87908. var frustumSlopeX = frustumSlopeY * aspectRatio;
  87909. return new BABYLON.Vector2(frustumSlopeX, frustumSlopeY);
  87910. };
  87911. /**
  87912. * Removes all animation locks. Allows new animations to be added to any of the arcCamera properties.
  87913. */
  87914. FramingBehavior.prototype._clearAnimationLocks = function () {
  87915. this._betaIsAnimating = false;
  87916. };
  87917. /**
  87918. * Applies any current user interaction to the camera. Takes into account maximum alpha rotation.
  87919. */
  87920. FramingBehavior.prototype._applyUserInteraction = function () {
  87921. if (this.isUserIsMoving) {
  87922. this._lastInteractionTime = BABYLON.Tools.Now;
  87923. this.stopAllAnimations();
  87924. this._clearAnimationLocks();
  87925. }
  87926. };
  87927. /**
  87928. * Stops and removes all animations that have been applied to the camera
  87929. */
  87930. FramingBehavior.prototype.stopAllAnimations = function () {
  87931. if (this._attachedCamera) {
  87932. this._attachedCamera.animations = [];
  87933. }
  87934. while (this._animatables.length) {
  87935. if (this._animatables[0]) {
  87936. this._animatables[0].onAnimationEnd = null;
  87937. this._animatables[0].stop();
  87938. }
  87939. this._animatables.shift();
  87940. }
  87941. };
  87942. Object.defineProperty(FramingBehavior.prototype, "isUserIsMoving", {
  87943. /**
  87944. * Gets a value indicating if the user is moving the camera
  87945. */
  87946. get: function () {
  87947. if (!this._attachedCamera) {
  87948. return false;
  87949. }
  87950. return this._attachedCamera.inertialAlphaOffset !== 0 ||
  87951. this._attachedCamera.inertialBetaOffset !== 0 ||
  87952. this._attachedCamera.inertialRadiusOffset !== 0 ||
  87953. this._attachedCamera.inertialPanningX !== 0 ||
  87954. this._attachedCamera.inertialPanningY !== 0 ||
  87955. this._isPointerDown;
  87956. },
  87957. enumerable: true,
  87958. configurable: true
  87959. });
  87960. /**
  87961. * The easing function used by animations
  87962. */
  87963. FramingBehavior.EasingFunction = new BABYLON.ExponentialEase();
  87964. /**
  87965. * The easing mode used by animations
  87966. */
  87967. FramingBehavior.EasingMode = BABYLON.EasingFunction.EASINGMODE_EASEINOUT;
  87968. // Statics
  87969. /**
  87970. * The camera can move all the way towards the mesh.
  87971. */
  87972. FramingBehavior.IgnoreBoundsSizeMode = 0;
  87973. /**
  87974. * The camera is not allowed to zoom closer to the mesh than the point at which the adjusted bounding sphere touches the frustum sides
  87975. */
  87976. FramingBehavior.FitFrustumSidesMode = 1;
  87977. return FramingBehavior;
  87978. }());
  87979. BABYLON.FramingBehavior = FramingBehavior;
  87980. })(BABYLON || (BABYLON = {}));
  87981. //# sourceMappingURL=babylon.framingBehavior.js.map
  87982. var BABYLON;
  87983. (function (BABYLON) {
  87984. /**
  87985. * Add a bouncing effect to an ArcRotateCamera when reaching a specified minimum and maximum radius
  87986. */
  87987. var BouncingBehavior = /** @class */ (function () {
  87988. function BouncingBehavior() {
  87989. /**
  87990. * The duration of the animation, in milliseconds
  87991. */
  87992. this.transitionDuration = 450;
  87993. /**
  87994. * Length of the distance animated by the transition when lower radius is reached
  87995. */
  87996. this.lowerRadiusTransitionRange = 2;
  87997. /**
  87998. * Length of the distance animated by the transition when upper radius is reached
  87999. */
  88000. this.upperRadiusTransitionRange = -2;
  88001. this._autoTransitionRange = false;
  88002. // Animations
  88003. this._radiusIsAnimating = false;
  88004. this._radiusBounceTransition = null;
  88005. this._animatables = new Array();
  88006. }
  88007. Object.defineProperty(BouncingBehavior.prototype, "name", {
  88008. get: function () {
  88009. return "Bouncing";
  88010. },
  88011. enumerable: true,
  88012. configurable: true
  88013. });
  88014. Object.defineProperty(BouncingBehavior.prototype, "autoTransitionRange", {
  88015. /**
  88016. * Gets a value indicating if the lowerRadiusTransitionRange and upperRadiusTransitionRange are defined automatically
  88017. */
  88018. get: function () {
  88019. return this._autoTransitionRange;
  88020. },
  88021. /**
  88022. * Sets a value indicating if the lowerRadiusTransitionRange and upperRadiusTransitionRange are defined automatically
  88023. * Transition ranges will be set to 5% of the bounding box diagonal in world space
  88024. */
  88025. set: function (value) {
  88026. var _this = this;
  88027. if (this._autoTransitionRange === value) {
  88028. return;
  88029. }
  88030. this._autoTransitionRange = value;
  88031. var camera = this._attachedCamera;
  88032. if (!camera) {
  88033. return;
  88034. }
  88035. if (value) {
  88036. this._onMeshTargetChangedObserver = camera.onMeshTargetChangedObservable.add(function (mesh) {
  88037. if (!mesh) {
  88038. return;
  88039. }
  88040. mesh.computeWorldMatrix(true);
  88041. var diagonal = mesh.getBoundingInfo().diagonalLength;
  88042. _this.lowerRadiusTransitionRange = diagonal * 0.05;
  88043. _this.upperRadiusTransitionRange = diagonal * 0.05;
  88044. });
  88045. }
  88046. else if (this._onMeshTargetChangedObserver) {
  88047. camera.onMeshTargetChangedObservable.remove(this._onMeshTargetChangedObserver);
  88048. }
  88049. },
  88050. enumerable: true,
  88051. configurable: true
  88052. });
  88053. BouncingBehavior.prototype.init = function () {
  88054. // Do notihng
  88055. };
  88056. BouncingBehavior.prototype.attach = function (camera) {
  88057. var _this = this;
  88058. this._attachedCamera = camera;
  88059. this._onAfterCheckInputsObserver = camera.onAfterCheckInputsObservable.add(function () {
  88060. if (!_this._attachedCamera) {
  88061. return;
  88062. }
  88063. // Add the bounce animation to the lower radius limit
  88064. if (_this._isRadiusAtLimit(_this._attachedCamera.lowerRadiusLimit)) {
  88065. _this._applyBoundRadiusAnimation(_this.lowerRadiusTransitionRange);
  88066. }
  88067. // Add the bounce animation to the upper radius limit
  88068. if (_this._isRadiusAtLimit(_this._attachedCamera.upperRadiusLimit)) {
  88069. _this._applyBoundRadiusAnimation(_this.upperRadiusTransitionRange);
  88070. }
  88071. });
  88072. };
  88073. BouncingBehavior.prototype.detach = function () {
  88074. if (!this._attachedCamera) {
  88075. return;
  88076. }
  88077. if (this._onAfterCheckInputsObserver) {
  88078. this._attachedCamera.onAfterCheckInputsObservable.remove(this._onAfterCheckInputsObserver);
  88079. }
  88080. if (this._onMeshTargetChangedObserver) {
  88081. this._attachedCamera.onMeshTargetChangedObservable.remove(this._onMeshTargetChangedObserver);
  88082. }
  88083. this._attachedCamera = null;
  88084. };
  88085. /**
  88086. * Checks if the camera radius is at the specified limit. Takes into account animation locks.
  88087. * @param radiusLimit The limit to check against.
  88088. * @return Bool to indicate if at limit.
  88089. */
  88090. BouncingBehavior.prototype._isRadiusAtLimit = function (radiusLimit) {
  88091. if (!this._attachedCamera) {
  88092. return false;
  88093. }
  88094. if (this._attachedCamera.radius === radiusLimit && !this._radiusIsAnimating) {
  88095. return true;
  88096. }
  88097. return false;
  88098. };
  88099. /**
  88100. * Applies an animation to the radius of the camera, extending by the radiusDelta.
  88101. * @param radiusDelta The delta by which to animate to. Can be negative.
  88102. */
  88103. BouncingBehavior.prototype._applyBoundRadiusAnimation = function (radiusDelta) {
  88104. var _this = this;
  88105. if (!this._attachedCamera) {
  88106. return;
  88107. }
  88108. if (!this._radiusBounceTransition) {
  88109. BouncingBehavior.EasingFunction.setEasingMode(BouncingBehavior.EasingMode);
  88110. this._radiusBounceTransition = BABYLON.Animation.CreateAnimation("radius", BABYLON.Animation.ANIMATIONTYPE_FLOAT, 60, BouncingBehavior.EasingFunction);
  88111. }
  88112. // Prevent zoom until bounce has completed
  88113. this._cachedWheelPrecision = this._attachedCamera.wheelPrecision;
  88114. this._attachedCamera.wheelPrecision = Infinity;
  88115. this._attachedCamera.inertialRadiusOffset = 0;
  88116. // Animate to the radius limit
  88117. this.stopAllAnimations();
  88118. this._radiusIsAnimating = true;
  88119. var animatable = BABYLON.Animation.TransitionTo("radius", this._attachedCamera.radius + radiusDelta, this._attachedCamera, this._attachedCamera.getScene(), 60, this._radiusBounceTransition, this.transitionDuration, function () { return _this._clearAnimationLocks(); });
  88120. if (animatable) {
  88121. this._animatables.push(animatable);
  88122. }
  88123. };
  88124. /**
  88125. * Removes all animation locks. Allows new animations to be added to any of the camera properties.
  88126. */
  88127. BouncingBehavior.prototype._clearAnimationLocks = function () {
  88128. this._radiusIsAnimating = false;
  88129. if (this._attachedCamera) {
  88130. this._attachedCamera.wheelPrecision = this._cachedWheelPrecision;
  88131. }
  88132. };
  88133. /**
  88134. * Stops and removes all animations that have been applied to the camera
  88135. */
  88136. BouncingBehavior.prototype.stopAllAnimations = function () {
  88137. if (this._attachedCamera) {
  88138. this._attachedCamera.animations = [];
  88139. }
  88140. while (this._animatables.length) {
  88141. this._animatables[0].onAnimationEnd = null;
  88142. this._animatables[0].stop();
  88143. this._animatables.shift();
  88144. }
  88145. };
  88146. /**
  88147. * The easing function used by animations
  88148. */
  88149. BouncingBehavior.EasingFunction = new BABYLON.BackEase(0.3);
  88150. /**
  88151. * The easing mode used by animations
  88152. */
  88153. BouncingBehavior.EasingMode = BABYLON.EasingFunction.EASINGMODE_EASEOUT;
  88154. return BouncingBehavior;
  88155. }());
  88156. BABYLON.BouncingBehavior = BouncingBehavior;
  88157. })(BABYLON || (BABYLON = {}));
  88158. //# sourceMappingURL=babylon.bouncingBehavior.js.map
  88159. var BABYLON;
  88160. (function (BABYLON) {
  88161. var AutoRotationBehavior = /** @class */ (function () {
  88162. function AutoRotationBehavior() {
  88163. this._zoomStopsAnimation = false;
  88164. this._idleRotationSpeed = 0.05;
  88165. this._idleRotationWaitTime = 2000;
  88166. this._idleRotationSpinupTime = 2000;
  88167. this._isPointerDown = false;
  88168. this._lastFrameTime = null;
  88169. this._lastInteractionTime = -Infinity;
  88170. this._cameraRotationSpeed = 0;
  88171. this._lastFrameRadius = 0;
  88172. }
  88173. Object.defineProperty(AutoRotationBehavior.prototype, "name", {
  88174. get: function () {
  88175. return "AutoRotation";
  88176. },
  88177. enumerable: true,
  88178. configurable: true
  88179. });
  88180. Object.defineProperty(AutoRotationBehavior.prototype, "zoomStopsAnimation", {
  88181. /**
  88182. * Gets the flag that indicates if user zooming should stop animation.
  88183. */
  88184. get: function () {
  88185. return this._zoomStopsAnimation;
  88186. },
  88187. /**
  88188. * Sets the flag that indicates if user zooming should stop animation.
  88189. */
  88190. set: function (flag) {
  88191. this._zoomStopsAnimation = flag;
  88192. },
  88193. enumerable: true,
  88194. configurable: true
  88195. });
  88196. Object.defineProperty(AutoRotationBehavior.prototype, "idleRotationSpeed", {
  88197. /**
  88198. * Gets the default speed at which the camera rotates around the model.
  88199. */
  88200. get: function () {
  88201. return this._idleRotationSpeed;
  88202. },
  88203. /**
  88204. * Sets the default speed at which the camera rotates around the model.
  88205. */
  88206. set: function (speed) {
  88207. this._idleRotationSpeed = speed;
  88208. },
  88209. enumerable: true,
  88210. configurable: true
  88211. });
  88212. Object.defineProperty(AutoRotationBehavior.prototype, "idleRotationWaitTime", {
  88213. /**
  88214. * Gets the time (milliseconds) to wait after user interaction before the camera starts rotating.
  88215. */
  88216. get: function () {
  88217. return this._idleRotationWaitTime;
  88218. },
  88219. /**
  88220. * Sets the time (in milliseconds) to wait after user interaction before the camera starts rotating.
  88221. */
  88222. set: function (time) {
  88223. this._idleRotationWaitTime = time;
  88224. },
  88225. enumerable: true,
  88226. configurable: true
  88227. });
  88228. Object.defineProperty(AutoRotationBehavior.prototype, "idleRotationSpinupTime", {
  88229. /**
  88230. * Gets the time (milliseconds) to take to spin up to the full idle rotation speed.
  88231. */
  88232. get: function () {
  88233. return this._idleRotationSpinupTime;
  88234. },
  88235. /**
  88236. * Sets the time (milliseconds) to take to spin up to the full idle rotation speed.
  88237. */
  88238. set: function (time) {
  88239. this._idleRotationSpinupTime = time;
  88240. },
  88241. enumerable: true,
  88242. configurable: true
  88243. });
  88244. Object.defineProperty(AutoRotationBehavior.prototype, "rotationInProgress", {
  88245. /**
  88246. * Gets a value indicating if the camera is currently rotating because of this behavior
  88247. */
  88248. get: function () {
  88249. return Math.abs(this._cameraRotationSpeed) > 0;
  88250. },
  88251. enumerable: true,
  88252. configurable: true
  88253. });
  88254. AutoRotationBehavior.prototype.init = function () {
  88255. // Do notihng
  88256. };
  88257. AutoRotationBehavior.prototype.attach = function (camera) {
  88258. var _this = this;
  88259. this._attachedCamera = camera;
  88260. var scene = this._attachedCamera.getScene();
  88261. this._onPrePointerObservableObserver = scene.onPrePointerObservable.add(function (pointerInfoPre) {
  88262. if (pointerInfoPre.type === BABYLON.PointerEventTypes.POINTERDOWN) {
  88263. _this._isPointerDown = true;
  88264. return;
  88265. }
  88266. if (pointerInfoPre.type === BABYLON.PointerEventTypes.POINTERUP) {
  88267. _this._isPointerDown = false;
  88268. }
  88269. });
  88270. this._onAfterCheckInputsObserver = camera.onAfterCheckInputsObservable.add(function () {
  88271. var now = BABYLON.Tools.Now;
  88272. var dt = 0;
  88273. if (_this._lastFrameTime != null) {
  88274. dt = now - _this._lastFrameTime;
  88275. }
  88276. _this._lastFrameTime = now;
  88277. // Stop the animation if there is user interaction and the animation should stop for this interaction
  88278. _this._applyUserInteraction();
  88279. var timeToRotation = now - _this._lastInteractionTime - _this._idleRotationWaitTime;
  88280. var scale = Math.max(Math.min(timeToRotation / (_this._idleRotationSpinupTime), 1), 0);
  88281. _this._cameraRotationSpeed = _this._idleRotationSpeed * scale;
  88282. // Step camera rotation by rotation speed
  88283. if (_this._attachedCamera) {
  88284. _this._attachedCamera.alpha -= _this._cameraRotationSpeed * (dt / 1000);
  88285. }
  88286. });
  88287. };
  88288. AutoRotationBehavior.prototype.detach = function () {
  88289. if (!this._attachedCamera) {
  88290. return;
  88291. }
  88292. var scene = this._attachedCamera.getScene();
  88293. if (this._onPrePointerObservableObserver) {
  88294. scene.onPrePointerObservable.remove(this._onPrePointerObservableObserver);
  88295. }
  88296. this._attachedCamera.onAfterCheckInputsObservable.remove(this._onAfterCheckInputsObserver);
  88297. this._attachedCamera = null;
  88298. };
  88299. /**
  88300. * Returns true if user is scrolling.
  88301. * @return true if user is scrolling.
  88302. */
  88303. AutoRotationBehavior.prototype._userIsZooming = function () {
  88304. if (!this._attachedCamera) {
  88305. return false;
  88306. }
  88307. return this._attachedCamera.inertialRadiusOffset !== 0;
  88308. };
  88309. AutoRotationBehavior.prototype._shouldAnimationStopForInteraction = function () {
  88310. if (!this._attachedCamera) {
  88311. return false;
  88312. }
  88313. var zoomHasHitLimit = false;
  88314. if (this._lastFrameRadius === this._attachedCamera.radius && this._attachedCamera.inertialRadiusOffset !== 0) {
  88315. zoomHasHitLimit = true;
  88316. }
  88317. // Update the record of previous radius - works as an approx. indicator of hitting radius limits
  88318. this._lastFrameRadius = this._attachedCamera.radius;
  88319. return this._zoomStopsAnimation ? zoomHasHitLimit : this._userIsZooming();
  88320. };
  88321. /**
  88322. * Applies any current user interaction to the camera. Takes into account maximum alpha rotation.
  88323. */
  88324. AutoRotationBehavior.prototype._applyUserInteraction = function () {
  88325. if (this._userIsMoving() && !this._shouldAnimationStopForInteraction()) {
  88326. this._lastInteractionTime = BABYLON.Tools.Now;
  88327. }
  88328. };
  88329. // Tools
  88330. AutoRotationBehavior.prototype._userIsMoving = function () {
  88331. if (!this._attachedCamera) {
  88332. return false;
  88333. }
  88334. return this._attachedCamera.inertialAlphaOffset !== 0 ||
  88335. this._attachedCamera.inertialBetaOffset !== 0 ||
  88336. this._attachedCamera.inertialRadiusOffset !== 0 ||
  88337. this._attachedCamera.inertialPanningX !== 0 ||
  88338. this._attachedCamera.inertialPanningY !== 0 ||
  88339. this._isPointerDown;
  88340. };
  88341. return AutoRotationBehavior;
  88342. }());
  88343. BABYLON.AutoRotationBehavior = AutoRotationBehavior;
  88344. })(BABYLON || (BABYLON = {}));
  88345. //# sourceMappingURL=babylon.autoRotationBehavior.js.map
  88346. var BABYLON;
  88347. (function (BABYLON) {
  88348. var NullEngineOptions = /** @class */ (function () {
  88349. function NullEngineOptions() {
  88350. this.renderWidth = 512;
  88351. this.renderHeight = 256;
  88352. this.textureSize = 512;
  88353. this.deterministicLockstep = false;
  88354. this.lockstepMaxSteps = 4;
  88355. }
  88356. return NullEngineOptions;
  88357. }());
  88358. BABYLON.NullEngineOptions = NullEngineOptions;
  88359. /**
  88360. * The null engine class provides support for headless version of babylon.js.
  88361. * This can be used in server side scenario or for testing purposes
  88362. */
  88363. var NullEngine = /** @class */ (function (_super) {
  88364. __extends(NullEngine, _super);
  88365. function NullEngine(options) {
  88366. if (options === void 0) { options = new NullEngineOptions(); }
  88367. var _this = _super.call(this, null) || this;
  88368. if (options.deterministicLockstep === undefined) {
  88369. options.deterministicLockstep = false;
  88370. }
  88371. if (options.lockstepMaxSteps === undefined) {
  88372. options.lockstepMaxSteps = 4;
  88373. }
  88374. _this._options = options;
  88375. // Init caps
  88376. // We consider we are on a webgl1 capable device
  88377. _this._caps = new BABYLON.EngineCapabilities();
  88378. _this._caps.maxTexturesImageUnits = 16;
  88379. _this._caps.maxVertexTextureImageUnits = 16;
  88380. _this._caps.maxTextureSize = 512;
  88381. _this._caps.maxCubemapTextureSize = 512;
  88382. _this._caps.maxRenderTextureSize = 512;
  88383. _this._caps.maxVertexAttribs = 16;
  88384. _this._caps.maxVaryingVectors = 16;
  88385. _this._caps.maxFragmentUniformVectors = 16;
  88386. _this._caps.maxVertexUniformVectors = 16;
  88387. // Extensions
  88388. _this._caps.standardDerivatives = false;
  88389. _this._caps.astc = null;
  88390. _this._caps.s3tc = null;
  88391. _this._caps.pvrtc = null;
  88392. _this._caps.etc1 = null;
  88393. _this._caps.etc2 = null;
  88394. _this._caps.textureAnisotropicFilterExtension = null;
  88395. _this._caps.maxAnisotropy = 0;
  88396. _this._caps.uintIndices = false;
  88397. _this._caps.fragmentDepthSupported = false;
  88398. _this._caps.highPrecisionShaderSupported = true;
  88399. _this._caps.colorBufferFloat = false;
  88400. _this._caps.textureFloat = false;
  88401. _this._caps.textureFloatLinearFiltering = false;
  88402. _this._caps.textureFloatRender = false;
  88403. _this._caps.textureHalfFloat = false;
  88404. _this._caps.textureHalfFloatLinearFiltering = false;
  88405. _this._caps.textureHalfFloatRender = false;
  88406. _this._caps.textureLOD = false;
  88407. _this._caps.drawBuffersExtension = false;
  88408. _this._caps.depthTextureExtension = false;
  88409. _this._caps.vertexArrayObject = false;
  88410. _this._caps.instancedArrays = false;
  88411. BABYLON.Tools.Log("Babylon.js null engine (v" + BABYLON.Engine.Version + ") launched");
  88412. // Wrappers
  88413. if (typeof URL === "undefined") {
  88414. URL = {
  88415. createObjectURL: function () { },
  88416. revokeObjectURL: function () { }
  88417. };
  88418. }
  88419. if (typeof Blob === "undefined") {
  88420. Blob = function () { };
  88421. }
  88422. return _this;
  88423. }
  88424. NullEngine.prototype.isDeterministicLockStep = function () {
  88425. return this._options.deterministicLockstep;
  88426. };
  88427. NullEngine.prototype.getLockstepMaxSteps = function () {
  88428. return this._options.lockstepMaxSteps;
  88429. };
  88430. NullEngine.prototype.getHardwareScalingLevel = function () {
  88431. return 1.0;
  88432. };
  88433. NullEngine.prototype.createVertexBuffer = function (vertices) {
  88434. return {
  88435. capacity: 0,
  88436. references: 1,
  88437. is32Bits: false
  88438. };
  88439. };
  88440. NullEngine.prototype.createIndexBuffer = function (indices) {
  88441. return {
  88442. capacity: 0,
  88443. references: 1,
  88444. is32Bits: false
  88445. };
  88446. };
  88447. NullEngine.prototype.clear = function (color, backBuffer, depth, stencil) {
  88448. if (stencil === void 0) { stencil = false; }
  88449. };
  88450. NullEngine.prototype.getRenderWidth = function (useScreen) {
  88451. if (useScreen === void 0) { useScreen = false; }
  88452. if (!useScreen && this._currentRenderTarget) {
  88453. return this._currentRenderTarget.width;
  88454. }
  88455. return this._options.renderWidth;
  88456. };
  88457. NullEngine.prototype.getRenderHeight = function (useScreen) {
  88458. if (useScreen === void 0) { useScreen = false; }
  88459. if (!useScreen && this._currentRenderTarget) {
  88460. return this._currentRenderTarget.height;
  88461. }
  88462. return this._options.renderHeight;
  88463. };
  88464. NullEngine.prototype.setViewport = function (viewport, requiredWidth, requiredHeight) {
  88465. this._cachedViewport = viewport;
  88466. };
  88467. NullEngine.prototype.createShaderProgram = function (vertexCode, fragmentCode, defines, context) {
  88468. return {
  88469. transformFeedback: null,
  88470. __SPECTOR_rebuildProgram: null
  88471. };
  88472. };
  88473. NullEngine.prototype.getUniforms = function (shaderProgram, uniformsNames) {
  88474. return [];
  88475. };
  88476. NullEngine.prototype.getAttributes = function (shaderProgram, attributesNames) {
  88477. return [];
  88478. };
  88479. NullEngine.prototype.bindSamplers = function (effect) {
  88480. this._currentEffect = null;
  88481. };
  88482. NullEngine.prototype.enableEffect = function (effect) {
  88483. this._currentEffect = effect;
  88484. if (effect.onBind) {
  88485. effect.onBind(effect);
  88486. }
  88487. effect.onBindObservable.notifyObservers(effect);
  88488. };
  88489. NullEngine.prototype.setState = function (culling, zOffset, force, reverseSide) {
  88490. if (zOffset === void 0) { zOffset = 0; }
  88491. if (reverseSide === void 0) { reverseSide = false; }
  88492. };
  88493. NullEngine.prototype.setIntArray = function (uniform, array) {
  88494. };
  88495. NullEngine.prototype.setIntArray2 = function (uniform, array) {
  88496. };
  88497. NullEngine.prototype.setIntArray3 = function (uniform, array) {
  88498. };
  88499. NullEngine.prototype.setIntArray4 = function (uniform, array) {
  88500. };
  88501. NullEngine.prototype.setFloatArray = function (uniform, array) {
  88502. };
  88503. NullEngine.prototype.setFloatArray2 = function (uniform, array) {
  88504. };
  88505. NullEngine.prototype.setFloatArray3 = function (uniform, array) {
  88506. };
  88507. NullEngine.prototype.setFloatArray4 = function (uniform, array) {
  88508. };
  88509. NullEngine.prototype.setArray = function (uniform, array) {
  88510. };
  88511. NullEngine.prototype.setArray2 = function (uniform, array) {
  88512. };
  88513. NullEngine.prototype.setArray3 = function (uniform, array) {
  88514. };
  88515. NullEngine.prototype.setArray4 = function (uniform, array) {
  88516. };
  88517. NullEngine.prototype.setMatrices = function (uniform, matrices) {
  88518. };
  88519. NullEngine.prototype.setMatrix = function (uniform, matrix) {
  88520. };
  88521. NullEngine.prototype.setMatrix3x3 = function (uniform, matrix) {
  88522. };
  88523. NullEngine.prototype.setMatrix2x2 = function (uniform, matrix) {
  88524. };
  88525. NullEngine.prototype.setFloat = function (uniform, value) {
  88526. };
  88527. NullEngine.prototype.setFloat2 = function (uniform, x, y) {
  88528. };
  88529. NullEngine.prototype.setFloat3 = function (uniform, x, y, z) {
  88530. };
  88531. NullEngine.prototype.setBool = function (uniform, bool) {
  88532. };
  88533. NullEngine.prototype.setFloat4 = function (uniform, x, y, z, w) {
  88534. };
  88535. NullEngine.prototype.setColor3 = function (uniform, color3) {
  88536. };
  88537. NullEngine.prototype.setColor4 = function (uniform, color3, alpha) {
  88538. };
  88539. NullEngine.prototype.setAlphaMode = function (mode, noDepthWriteChange) {
  88540. if (noDepthWriteChange === void 0) { noDepthWriteChange = false; }
  88541. if (this._alphaMode === mode) {
  88542. return;
  88543. }
  88544. this._alphaState.alphaBlend = (mode !== BABYLON.Engine.ALPHA_DISABLE);
  88545. if (!noDepthWriteChange) {
  88546. this.setDepthWrite(mode === BABYLON.Engine.ALPHA_DISABLE);
  88547. }
  88548. this._alphaMode = mode;
  88549. };
  88550. NullEngine.prototype.bindBuffers = function (vertexBuffers, indexBuffer, effect) {
  88551. };
  88552. NullEngine.prototype.wipeCaches = function (bruteForce) {
  88553. if (this.preventCacheWipeBetweenFrames) {
  88554. return;
  88555. }
  88556. this.resetTextureCache();
  88557. this._currentEffect = null;
  88558. if (bruteForce) {
  88559. this._currentProgram = null;
  88560. this._stencilState.reset();
  88561. this._depthCullingState.reset();
  88562. this._alphaState.reset();
  88563. }
  88564. this._cachedVertexBuffers = null;
  88565. this._cachedIndexBuffer = null;
  88566. this._cachedEffectForVertexBuffers = null;
  88567. };
  88568. NullEngine.prototype.draw = function (useTriangles, indexStart, indexCount, instancesCount) {
  88569. };
  88570. NullEngine.prototype.drawElementsType = function (fillMode, indexStart, indexCount, instancesCount) {
  88571. };
  88572. NullEngine.prototype.drawArraysType = function (fillMode, verticesStart, verticesCount, instancesCount) {
  88573. };
  88574. NullEngine.prototype._createTexture = function () {
  88575. return {};
  88576. };
  88577. NullEngine.prototype.createTexture = function (urlArg, noMipmap, invertY, scene, samplingMode, onLoad, onError, buffer, fallBack, format) {
  88578. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  88579. if (onLoad === void 0) { onLoad = null; }
  88580. if (onError === void 0) { onError = null; }
  88581. if (buffer === void 0) { buffer = null; }
  88582. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_URL);
  88583. var url = String(urlArg);
  88584. texture.url = url;
  88585. texture.generateMipMaps = !noMipmap;
  88586. texture.samplingMode = samplingMode;
  88587. texture.invertY = invertY;
  88588. texture.baseWidth = this._options.textureSize;
  88589. texture.baseHeight = this._options.textureSize;
  88590. texture.width = this._options.textureSize;
  88591. texture.height = this._options.textureSize;
  88592. if (format) {
  88593. texture.format = format;
  88594. }
  88595. texture.isReady = true;
  88596. if (onLoad) {
  88597. onLoad();
  88598. }
  88599. return texture;
  88600. };
  88601. NullEngine.prototype.createRenderTargetTexture = function (size, options) {
  88602. var fullOptions = new BABYLON.RenderTargetCreationOptions();
  88603. if (options !== undefined && typeof options === "object") {
  88604. fullOptions.generateMipMaps = options.generateMipMaps;
  88605. fullOptions.generateDepthBuffer = options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  88606. fullOptions.generateStencilBuffer = fullOptions.generateDepthBuffer && options.generateStencilBuffer;
  88607. fullOptions.type = options.type === undefined ? BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT : options.type;
  88608. fullOptions.samplingMode = options.samplingMode === undefined ? BABYLON.Texture.TRILINEAR_SAMPLINGMODE : options.samplingMode;
  88609. }
  88610. else {
  88611. fullOptions.generateMipMaps = options;
  88612. fullOptions.generateDepthBuffer = true;
  88613. fullOptions.generateStencilBuffer = false;
  88614. fullOptions.type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  88615. fullOptions.samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE;
  88616. }
  88617. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_RENDERTARGET);
  88618. var width = size.width || size;
  88619. var height = size.height || size;
  88620. texture._depthStencilBuffer = {};
  88621. texture._framebuffer = {};
  88622. texture.baseWidth = width;
  88623. texture.baseHeight = height;
  88624. texture.width = width;
  88625. texture.height = height;
  88626. texture.isReady = true;
  88627. texture.samples = 1;
  88628. texture.generateMipMaps = fullOptions.generateMipMaps ? true : false;
  88629. texture.samplingMode = fullOptions.samplingMode;
  88630. texture.type = fullOptions.type;
  88631. texture._generateDepthBuffer = fullOptions.generateDepthBuffer;
  88632. texture._generateStencilBuffer = fullOptions.generateStencilBuffer ? true : false;
  88633. return texture;
  88634. };
  88635. NullEngine.prototype.updateTextureSamplingMode = function (samplingMode, texture) {
  88636. texture.samplingMode = samplingMode;
  88637. };
  88638. NullEngine.prototype.bindFramebuffer = function (texture, faceIndex, requiredWidth, requiredHeight, forceFullscreenViewport) {
  88639. if (this._currentRenderTarget) {
  88640. this.unBindFramebuffer(this._currentRenderTarget);
  88641. }
  88642. this._currentRenderTarget = texture;
  88643. this._currentFramebuffer = texture._MSAAFramebuffer ? texture._MSAAFramebuffer : texture._framebuffer;
  88644. if (this._cachedViewport && !forceFullscreenViewport) {
  88645. this.setViewport(this._cachedViewport, requiredWidth, requiredHeight);
  88646. }
  88647. };
  88648. NullEngine.prototype.unBindFramebuffer = function (texture, disableGenerateMipMaps, onBeforeUnbind) {
  88649. if (disableGenerateMipMaps === void 0) { disableGenerateMipMaps = false; }
  88650. this._currentRenderTarget = null;
  88651. if (onBeforeUnbind) {
  88652. if (texture._MSAAFramebuffer) {
  88653. this._currentFramebuffer = texture._framebuffer;
  88654. }
  88655. onBeforeUnbind();
  88656. }
  88657. this._currentFramebuffer = null;
  88658. };
  88659. NullEngine.prototype.createDynamicVertexBuffer = function (vertices) {
  88660. var vbo = {
  88661. capacity: 1,
  88662. references: 1,
  88663. is32Bits: false
  88664. };
  88665. return vbo;
  88666. };
  88667. NullEngine.prototype.updateDynamicIndexBuffer = function (indexBuffer, indices, offset) {
  88668. if (offset === void 0) { offset = 0; }
  88669. };
  88670. NullEngine.prototype.updateDynamicVertexBuffer = function (vertexBuffer, vertices, offset, count) {
  88671. };
  88672. NullEngine.prototype._bindTextureDirectly = function (target, texture) {
  88673. if (this._boundTexturesCache[this._activeChannel] !== texture) {
  88674. this._boundTexturesCache[this._activeChannel] = texture;
  88675. }
  88676. };
  88677. NullEngine.prototype._bindTexture = function (channel, texture) {
  88678. if (channel < 0) {
  88679. return;
  88680. }
  88681. this._bindTextureDirectly(0, texture);
  88682. };
  88683. NullEngine.prototype._releaseBuffer = function (buffer) {
  88684. buffer.references--;
  88685. if (buffer.references === 0) {
  88686. return true;
  88687. }
  88688. return false;
  88689. };
  88690. return NullEngine;
  88691. }(BABYLON.Engine));
  88692. BABYLON.NullEngine = NullEngine;
  88693. })(BABYLON || (BABYLON = {}));
  88694. //# sourceMappingURL=babylon.nullEngine.js.map
  88695. var BABYLON;
  88696. (function (BABYLON) {
  88697. /**
  88698. * This class can be used to get instrumentation data from a Babylon engine
  88699. */
  88700. var EngineInstrumentation = /** @class */ (function () {
  88701. function EngineInstrumentation(engine) {
  88702. this.engine = engine;
  88703. this._captureGPUFrameTime = false;
  88704. this._gpuFrameTime = new BABYLON.PerfCounter();
  88705. this._captureShaderCompilationTime = false;
  88706. this._shaderCompilationTime = new BABYLON.PerfCounter();
  88707. // Observers
  88708. this._onBeginFrameObserver = null;
  88709. this._onEndFrameObserver = null;
  88710. this._onBeforeShaderCompilationObserver = null;
  88711. this._onAfterShaderCompilationObserver = null;
  88712. }
  88713. Object.defineProperty(EngineInstrumentation.prototype, "gpuFrameTimeCounter", {
  88714. // Properties
  88715. /**
  88716. * Gets the perf counter used for GPU frame time
  88717. */
  88718. get: function () {
  88719. return this._gpuFrameTime;
  88720. },
  88721. enumerable: true,
  88722. configurable: true
  88723. });
  88724. Object.defineProperty(EngineInstrumentation.prototype, "captureGPUFrameTime", {
  88725. /**
  88726. * Gets the GPU frame time capture status
  88727. */
  88728. get: function () {
  88729. return this._captureGPUFrameTime;
  88730. },
  88731. /**
  88732. * Enable or disable the GPU frame time capture
  88733. */
  88734. set: function (value) {
  88735. var _this = this;
  88736. if (value === this._captureGPUFrameTime) {
  88737. return;
  88738. }
  88739. this._captureGPUFrameTime = value;
  88740. if (value) {
  88741. this._onBeginFrameObserver = this.engine.onBeginFrameObservable.add(function () {
  88742. if (!_this._gpuFrameTimeToken) {
  88743. _this._gpuFrameTimeToken = _this.engine.startTimeQuery();
  88744. }
  88745. });
  88746. this._onEndFrameObserver = this.engine.onEndFrameObservable.add(function () {
  88747. if (!_this._gpuFrameTimeToken) {
  88748. return;
  88749. }
  88750. var time = _this.engine.endTimeQuery(_this._gpuFrameTimeToken);
  88751. if (time > -1) {
  88752. _this._gpuFrameTimeToken = null;
  88753. _this._gpuFrameTime.fetchNewFrame();
  88754. _this._gpuFrameTime.addCount(time, true);
  88755. }
  88756. });
  88757. }
  88758. else {
  88759. this.engine.onBeginFrameObservable.remove(this._onBeginFrameObserver);
  88760. this._onBeginFrameObserver = null;
  88761. this.engine.onEndFrameObservable.remove(this._onEndFrameObserver);
  88762. this._onEndFrameObserver = null;
  88763. }
  88764. },
  88765. enumerable: true,
  88766. configurable: true
  88767. });
  88768. Object.defineProperty(EngineInstrumentation.prototype, "shaderCompilationTimeCounter", {
  88769. /**
  88770. * Gets the perf counter used for shader compilation time
  88771. */
  88772. get: function () {
  88773. return this._shaderCompilationTime;
  88774. },
  88775. enumerable: true,
  88776. configurable: true
  88777. });
  88778. Object.defineProperty(EngineInstrumentation.prototype, "captureShaderCompilationTime", {
  88779. /**
  88780. * Gets the shader compilation time capture status
  88781. */
  88782. get: function () {
  88783. return this._captureShaderCompilationTime;
  88784. },
  88785. /**
  88786. * Enable or disable the shader compilation time capture
  88787. */
  88788. set: function (value) {
  88789. var _this = this;
  88790. if (value === this._captureShaderCompilationTime) {
  88791. return;
  88792. }
  88793. this._captureShaderCompilationTime = value;
  88794. if (value) {
  88795. this._onBeforeShaderCompilationObserver = this.engine.onBeforeShaderCompilationObservable.add(function () {
  88796. _this._shaderCompilationTime.fetchNewFrame();
  88797. _this._shaderCompilationTime.beginMonitoring();
  88798. });
  88799. this._onAfterShaderCompilationObserver = this.engine.onAfterShaderCompilationObservable.add(function () {
  88800. _this._shaderCompilationTime.endMonitoring();
  88801. });
  88802. }
  88803. else {
  88804. this.engine.onBeforeShaderCompilationObservable.remove(this._onBeforeShaderCompilationObserver);
  88805. this._onBeforeShaderCompilationObserver = null;
  88806. this.engine.onAfterShaderCompilationObservable.remove(this._onAfterShaderCompilationObserver);
  88807. this._onAfterShaderCompilationObserver = null;
  88808. }
  88809. },
  88810. enumerable: true,
  88811. configurable: true
  88812. });
  88813. EngineInstrumentation.prototype.dispose = function () {
  88814. this.engine.onBeginFrameObservable.remove(this._onBeginFrameObserver);
  88815. this._onBeginFrameObserver = null;
  88816. this.engine.onEndFrameObservable.remove(this._onEndFrameObserver);
  88817. this._onEndFrameObserver = null;
  88818. this.engine.onBeforeShaderCompilationObservable.remove(this._onBeforeShaderCompilationObserver);
  88819. this._onBeforeShaderCompilationObserver = null;
  88820. this.engine.onAfterShaderCompilationObservable.remove(this._onAfterShaderCompilationObserver);
  88821. this._onAfterShaderCompilationObserver = null;
  88822. this.engine = null;
  88823. };
  88824. return EngineInstrumentation;
  88825. }());
  88826. BABYLON.EngineInstrumentation = EngineInstrumentation;
  88827. })(BABYLON || (BABYLON = {}));
  88828. //# sourceMappingURL=babylon.engineInstrumentation.js.map
  88829. var BABYLON;
  88830. (function (BABYLON) {
  88831. /**
  88832. * This class can be used to get instrumentation data from a Babylon engine
  88833. */
  88834. var SceneInstrumentation = /** @class */ (function () {
  88835. function SceneInstrumentation(scene) {
  88836. var _this = this;
  88837. this.scene = scene;
  88838. this._captureActiveMeshesEvaluationTime = false;
  88839. this._activeMeshesEvaluationTime = new BABYLON.PerfCounter();
  88840. this._captureRenderTargetsRenderTime = false;
  88841. this._renderTargetsRenderTime = new BABYLON.PerfCounter();
  88842. this._captureFrameTime = false;
  88843. this._frameTime = new BABYLON.PerfCounter();
  88844. this._captureRenderTime = false;
  88845. this._renderTime = new BABYLON.PerfCounter();
  88846. this._captureInterFrameTime = false;
  88847. this._interFrameTime = new BABYLON.PerfCounter();
  88848. this._captureParticlesRenderTime = false;
  88849. this._particlesRenderTime = new BABYLON.PerfCounter();
  88850. this._captureSpritesRenderTime = false;
  88851. this._spritesRenderTime = new BABYLON.PerfCounter();
  88852. this._capturePhysicsTime = false;
  88853. this._physicsTime = new BABYLON.PerfCounter();
  88854. this._captureAnimationsTime = false;
  88855. this._animationsTime = new BABYLON.PerfCounter();
  88856. // Observers
  88857. this._onBeforeActiveMeshesEvaluationObserver = null;
  88858. this._onAfterActiveMeshesEvaluationObserver = null;
  88859. this._onBeforeRenderTargetsRenderObserver = null;
  88860. this._onAfterRenderTargetsRenderObserver = null;
  88861. this._onAfterRenderObserver = null;
  88862. this._onBeforeDrawPhaseObserver = null;
  88863. this._onAfterDrawPhaseObserver = null;
  88864. this._onBeforeAnimationsObserver = null;
  88865. this._onBeforeParticlesRenderingObserver = null;
  88866. this._onAfterParticlesRenderingObserver = null;
  88867. this._onBeforeSpritesRenderingObserver = null;
  88868. this._onAfterSpritesRenderingObserver = null;
  88869. this._onBeforePhysicsObserver = null;
  88870. this._onAfterPhysicsObserver = null;
  88871. this._onAfterAnimationsObserver = null;
  88872. // Before render
  88873. this._onBeforeAnimationsObserver = scene.onBeforeAnimationsObservable.add(function () {
  88874. if (_this._captureActiveMeshesEvaluationTime) {
  88875. _this._activeMeshesEvaluationTime.fetchNewFrame();
  88876. }
  88877. if (_this._captureRenderTargetsRenderTime) {
  88878. _this._renderTargetsRenderTime.fetchNewFrame();
  88879. }
  88880. if (_this._captureFrameTime) {
  88881. BABYLON.Tools.StartPerformanceCounter("Scene rendering");
  88882. _this._frameTime.beginMonitoring();
  88883. }
  88884. if (_this._captureInterFrameTime) {
  88885. _this._interFrameTime.endMonitoring();
  88886. }
  88887. if (_this._captureParticlesRenderTime) {
  88888. _this._particlesRenderTime.fetchNewFrame();
  88889. }
  88890. if (_this._captureSpritesRenderTime) {
  88891. _this._spritesRenderTime.fetchNewFrame();
  88892. }
  88893. if (_this._captureAnimationsTime) {
  88894. _this._animationsTime.beginMonitoring();
  88895. }
  88896. _this.scene.getEngine()._drawCalls.fetchNewFrame();
  88897. _this.scene.getEngine()._textureCollisions.fetchNewFrame();
  88898. });
  88899. // After render
  88900. this._onAfterRenderObserver = scene.onAfterRenderObservable.add(function () {
  88901. if (_this._captureFrameTime) {
  88902. BABYLON.Tools.EndPerformanceCounter("Scene rendering");
  88903. _this._frameTime.endMonitoring();
  88904. }
  88905. if (_this._captureRenderTime) {
  88906. _this._renderTime.endMonitoring(false);
  88907. }
  88908. if (_this._captureInterFrameTime) {
  88909. _this._interFrameTime.beginMonitoring();
  88910. }
  88911. });
  88912. }
  88913. Object.defineProperty(SceneInstrumentation.prototype, "activeMeshesEvaluationTimeCounter", {
  88914. // Properties
  88915. /**
  88916. * Gets the perf counter used for active meshes evaluation time
  88917. */
  88918. get: function () {
  88919. return this._activeMeshesEvaluationTime;
  88920. },
  88921. enumerable: true,
  88922. configurable: true
  88923. });
  88924. Object.defineProperty(SceneInstrumentation.prototype, "captureActiveMeshesEvaluationTime", {
  88925. /**
  88926. * Gets the active meshes evaluation time capture status
  88927. */
  88928. get: function () {
  88929. return this._captureActiveMeshesEvaluationTime;
  88930. },
  88931. /**
  88932. * Enable or disable the active meshes evaluation time capture
  88933. */
  88934. set: function (value) {
  88935. var _this = this;
  88936. if (value === this._captureActiveMeshesEvaluationTime) {
  88937. return;
  88938. }
  88939. this._captureActiveMeshesEvaluationTime = value;
  88940. if (value) {
  88941. this._onBeforeActiveMeshesEvaluationObserver = this.scene.onBeforeActiveMeshesEvaluationObservable.add(function () {
  88942. BABYLON.Tools.StartPerformanceCounter("Active meshes evaluation");
  88943. _this._activeMeshesEvaluationTime.beginMonitoring();
  88944. });
  88945. this._onAfterActiveMeshesEvaluationObserver = this.scene.onAfterActiveMeshesEvaluationObservable.add(function () {
  88946. BABYLON.Tools.EndPerformanceCounter("Active meshes evaluation");
  88947. _this._activeMeshesEvaluationTime.endMonitoring();
  88948. });
  88949. }
  88950. else {
  88951. this.scene.onBeforeActiveMeshesEvaluationObservable.remove(this._onBeforeActiveMeshesEvaluationObserver);
  88952. this._onBeforeActiveMeshesEvaluationObserver = null;
  88953. this.scene.onAfterActiveMeshesEvaluationObservable.remove(this._onAfterActiveMeshesEvaluationObserver);
  88954. this._onAfterActiveMeshesEvaluationObserver = null;
  88955. }
  88956. },
  88957. enumerable: true,
  88958. configurable: true
  88959. });
  88960. Object.defineProperty(SceneInstrumentation.prototype, "renderTargetsRenderTimeCounter", {
  88961. /**
  88962. * Gets the perf counter used for render targets render time
  88963. */
  88964. get: function () {
  88965. return this._renderTargetsRenderTime;
  88966. },
  88967. enumerable: true,
  88968. configurable: true
  88969. });
  88970. Object.defineProperty(SceneInstrumentation.prototype, "captureRenderTargetsRenderTime", {
  88971. /**
  88972. * Gets the render targets render time capture status
  88973. */
  88974. get: function () {
  88975. return this._captureRenderTargetsRenderTime;
  88976. },
  88977. /**
  88978. * Enable or disable the render targets render time capture
  88979. */
  88980. set: function (value) {
  88981. var _this = this;
  88982. if (value === this._captureRenderTargetsRenderTime) {
  88983. return;
  88984. }
  88985. this._captureRenderTargetsRenderTime = value;
  88986. if (value) {
  88987. this._onBeforeRenderTargetsRenderObserver = this.scene.OnBeforeRenderTargetsRenderObservable.add(function () {
  88988. BABYLON.Tools.StartPerformanceCounter("Render targets rendering");
  88989. _this._renderTargetsRenderTime.beginMonitoring();
  88990. });
  88991. this._onAfterRenderTargetsRenderObserver = this.scene.OnAfterRenderTargetsRenderObservable.add(function () {
  88992. BABYLON.Tools.EndPerformanceCounter("Render targets rendering");
  88993. _this._renderTargetsRenderTime.endMonitoring(false);
  88994. });
  88995. }
  88996. else {
  88997. this.scene.OnBeforeRenderTargetsRenderObservable.remove(this._onBeforeRenderTargetsRenderObserver);
  88998. this._onBeforeRenderTargetsRenderObserver = null;
  88999. this.scene.OnAfterRenderTargetsRenderObservable.remove(this._onAfterRenderTargetsRenderObserver);
  89000. this._onAfterRenderTargetsRenderObserver = null;
  89001. }
  89002. },
  89003. enumerable: true,
  89004. configurable: true
  89005. });
  89006. Object.defineProperty(SceneInstrumentation.prototype, "particlesRenderTimeCounter", {
  89007. /**
  89008. * Gets the perf counter used for particles render time
  89009. */
  89010. get: function () {
  89011. return this._particlesRenderTime;
  89012. },
  89013. enumerable: true,
  89014. configurable: true
  89015. });
  89016. Object.defineProperty(SceneInstrumentation.prototype, "captureParticlesRenderTime", {
  89017. /**
  89018. * Gets the particles render time capture status
  89019. */
  89020. get: function () {
  89021. return this._captureParticlesRenderTime;
  89022. },
  89023. /**
  89024. * Enable or disable the particles render time capture
  89025. */
  89026. set: function (value) {
  89027. var _this = this;
  89028. if (value === this._captureParticlesRenderTime) {
  89029. return;
  89030. }
  89031. this._captureParticlesRenderTime = value;
  89032. if (value) {
  89033. this._onBeforeParticlesRenderingObserver = this.scene.onBeforeParticlesRenderingObservable.add(function () {
  89034. BABYLON.Tools.StartPerformanceCounter("Particles");
  89035. _this._particlesRenderTime.beginMonitoring();
  89036. });
  89037. this._onAfterParticlesRenderingObserver = this.scene.onAfterParticlesRenderingObservable.add(function () {
  89038. BABYLON.Tools.EndPerformanceCounter("Particles");
  89039. _this._particlesRenderTime.endMonitoring(false);
  89040. });
  89041. }
  89042. else {
  89043. this.scene.onBeforeParticlesRenderingObservable.remove(this._onBeforeParticlesRenderingObserver);
  89044. this._onBeforeParticlesRenderingObserver = null;
  89045. this.scene.onAfterParticlesRenderingObservable.remove(this._onAfterParticlesRenderingObserver);
  89046. this._onAfterParticlesRenderingObserver = null;
  89047. }
  89048. },
  89049. enumerable: true,
  89050. configurable: true
  89051. });
  89052. Object.defineProperty(SceneInstrumentation.prototype, "spritesRenderTimeCounter", {
  89053. /**
  89054. * Gets the perf counter used for sprites render time
  89055. */
  89056. get: function () {
  89057. return this._spritesRenderTime;
  89058. },
  89059. enumerable: true,
  89060. configurable: true
  89061. });
  89062. Object.defineProperty(SceneInstrumentation.prototype, "captureSpritesRenderTime", {
  89063. /**
  89064. * Gets the sprites render time capture status
  89065. */
  89066. get: function () {
  89067. return this._captureSpritesRenderTime;
  89068. },
  89069. /**
  89070. * Enable or disable the sprites render time capture
  89071. */
  89072. set: function (value) {
  89073. var _this = this;
  89074. if (value === this._captureSpritesRenderTime) {
  89075. return;
  89076. }
  89077. this._captureSpritesRenderTime = value;
  89078. if (value) {
  89079. this._onBeforeSpritesRenderingObserver = this.scene.onBeforeSpritesRenderingObservable.add(function () {
  89080. BABYLON.Tools.StartPerformanceCounter("Sprites");
  89081. _this._spritesRenderTime.beginMonitoring();
  89082. });
  89083. this._onAfterSpritesRenderingObserver = this.scene.onAfterSpritesRenderingObservable.add(function () {
  89084. BABYLON.Tools.EndPerformanceCounter("Sprites");
  89085. _this._spritesRenderTime.endMonitoring(false);
  89086. });
  89087. }
  89088. else {
  89089. this.scene.onBeforeSpritesRenderingObservable.remove(this._onBeforeSpritesRenderingObserver);
  89090. this._onBeforeSpritesRenderingObserver = null;
  89091. this.scene.onAfterSpritesRenderingObservable.remove(this._onAfterSpritesRenderingObserver);
  89092. this._onAfterSpritesRenderingObserver = null;
  89093. }
  89094. },
  89095. enumerable: true,
  89096. configurable: true
  89097. });
  89098. Object.defineProperty(SceneInstrumentation.prototype, "physicsTimeCounter", {
  89099. /**
  89100. * Gets the perf counter used for physics time
  89101. */
  89102. get: function () {
  89103. return this._physicsTime;
  89104. },
  89105. enumerable: true,
  89106. configurable: true
  89107. });
  89108. Object.defineProperty(SceneInstrumentation.prototype, "capturePhysicsTime", {
  89109. /**
  89110. * Gets the physics time capture status
  89111. */
  89112. get: function () {
  89113. return this._capturePhysicsTime;
  89114. },
  89115. /**
  89116. * Enable or disable the physics time capture
  89117. */
  89118. set: function (value) {
  89119. var _this = this;
  89120. if (value === this._capturePhysicsTime) {
  89121. return;
  89122. }
  89123. this._capturePhysicsTime = value;
  89124. if (value) {
  89125. this._onBeforePhysicsObserver = this.scene.onBeforePhysicsObservable.add(function () {
  89126. BABYLON.Tools.StartPerformanceCounter("Physics");
  89127. _this._physicsTime.beginMonitoring();
  89128. });
  89129. this._onAfterPhysicsObserver = this.scene.onAfterPhysicsObservable.add(function () {
  89130. BABYLON.Tools.EndPerformanceCounter("Physics");
  89131. _this._physicsTime.endMonitoring();
  89132. });
  89133. }
  89134. else {
  89135. this.scene.onBeforePhysicsObservable.remove(this._onBeforePhysicsObserver);
  89136. this._onBeforePhysicsObserver = null;
  89137. this.scene.onAfterPhysicsObservable.remove(this._onAfterPhysicsObserver);
  89138. this._onAfterPhysicsObserver = null;
  89139. }
  89140. },
  89141. enumerable: true,
  89142. configurable: true
  89143. });
  89144. Object.defineProperty(SceneInstrumentation.prototype, "animationsTimeCounter", {
  89145. /**
  89146. * Gets the perf counter used for animations time
  89147. */
  89148. get: function () {
  89149. return this._animationsTime;
  89150. },
  89151. enumerable: true,
  89152. configurable: true
  89153. });
  89154. Object.defineProperty(SceneInstrumentation.prototype, "captureAnimationsTime", {
  89155. /**
  89156. * Gets the animations time capture status
  89157. */
  89158. get: function () {
  89159. return this._captureAnimationsTime;
  89160. },
  89161. /**
  89162. * Enable or disable the animations time capture
  89163. */
  89164. set: function (value) {
  89165. var _this = this;
  89166. if (value === this._captureAnimationsTime) {
  89167. return;
  89168. }
  89169. this._captureAnimationsTime = value;
  89170. if (value) {
  89171. this._onAfterAnimationsObserver = this.scene.onAfterAnimationsObservable.add(function () {
  89172. _this._animationsTime.endMonitoring();
  89173. });
  89174. }
  89175. else {
  89176. this.scene.onAfterAnimationsObservable.remove(this._onAfterAnimationsObserver);
  89177. this._onAfterAnimationsObserver = null;
  89178. }
  89179. },
  89180. enumerable: true,
  89181. configurable: true
  89182. });
  89183. Object.defineProperty(SceneInstrumentation.prototype, "frameTimeCounter", {
  89184. /**
  89185. * Gets the perf counter used for frame time capture
  89186. */
  89187. get: function () {
  89188. return this._frameTime;
  89189. },
  89190. enumerable: true,
  89191. configurable: true
  89192. });
  89193. Object.defineProperty(SceneInstrumentation.prototype, "captureFrameTime", {
  89194. /**
  89195. * Gets the frame time capture status
  89196. */
  89197. get: function () {
  89198. return this._captureFrameTime;
  89199. },
  89200. /**
  89201. * Enable or disable the frame time capture
  89202. */
  89203. set: function (value) {
  89204. this._captureFrameTime = value;
  89205. },
  89206. enumerable: true,
  89207. configurable: true
  89208. });
  89209. Object.defineProperty(SceneInstrumentation.prototype, "interFrameTimeCounter", {
  89210. /**
  89211. * Gets the perf counter used for inter-frames time capture
  89212. */
  89213. get: function () {
  89214. return this._interFrameTime;
  89215. },
  89216. enumerable: true,
  89217. configurable: true
  89218. });
  89219. Object.defineProperty(SceneInstrumentation.prototype, "captureInterFrameTime", {
  89220. /**
  89221. * Gets the inter-frames time capture status
  89222. */
  89223. get: function () {
  89224. return this._captureInterFrameTime;
  89225. },
  89226. /**
  89227. * Enable or disable the inter-frames time capture
  89228. */
  89229. set: function (value) {
  89230. this._captureInterFrameTime = value;
  89231. },
  89232. enumerable: true,
  89233. configurable: true
  89234. });
  89235. Object.defineProperty(SceneInstrumentation.prototype, "renderTimeCounter", {
  89236. /**
  89237. * Gets the perf counter used for render time capture
  89238. */
  89239. get: function () {
  89240. return this._renderTime;
  89241. },
  89242. enumerable: true,
  89243. configurable: true
  89244. });
  89245. Object.defineProperty(SceneInstrumentation.prototype, "captureRenderTime", {
  89246. /**
  89247. * Gets the render time capture status
  89248. */
  89249. get: function () {
  89250. return this._captureRenderTime;
  89251. },
  89252. /**
  89253. * Enable or disable the render time capture
  89254. */
  89255. set: function (value) {
  89256. var _this = this;
  89257. if (value === this._captureRenderTime) {
  89258. return;
  89259. }
  89260. this._captureRenderTime = value;
  89261. if (value) {
  89262. this._onBeforeDrawPhaseObserver = this.scene.onBeforeDrawPhaseObservable.add(function () {
  89263. _this._renderTime.beginMonitoring();
  89264. BABYLON.Tools.StartPerformanceCounter("Main render");
  89265. });
  89266. this._onAfterDrawPhaseObserver = this.scene.onAfterDrawPhaseObservable.add(function () {
  89267. _this._renderTime.endMonitoring(false);
  89268. BABYLON.Tools.EndPerformanceCounter("Main render");
  89269. });
  89270. }
  89271. else {
  89272. this.scene.onBeforeDrawPhaseObservable.remove(this._onBeforeDrawPhaseObserver);
  89273. this._onBeforeDrawPhaseObserver = null;
  89274. this.scene.onAfterDrawPhaseObservable.remove(this._onAfterDrawPhaseObserver);
  89275. this._onAfterDrawPhaseObserver = null;
  89276. }
  89277. },
  89278. enumerable: true,
  89279. configurable: true
  89280. });
  89281. Object.defineProperty(SceneInstrumentation.prototype, "drawCallsCounter", {
  89282. /**
  89283. * Gets the perf counter used for draw calls
  89284. */
  89285. get: function () {
  89286. return this.scene.getEngine()._drawCalls;
  89287. },
  89288. enumerable: true,
  89289. configurable: true
  89290. });
  89291. Object.defineProperty(SceneInstrumentation.prototype, "textureCollisionsCounter", {
  89292. /**
  89293. * Gets the perf counter used for texture collisions
  89294. */
  89295. get: function () {
  89296. return this.scene.getEngine()._textureCollisions;
  89297. },
  89298. enumerable: true,
  89299. configurable: true
  89300. });
  89301. SceneInstrumentation.prototype.dispose = function () {
  89302. this.scene.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  89303. this._onAfterRenderObserver = null;
  89304. this.scene.onBeforeActiveMeshesEvaluationObservable.remove(this._onBeforeActiveMeshesEvaluationObserver);
  89305. this._onBeforeActiveMeshesEvaluationObserver = null;
  89306. this.scene.onAfterActiveMeshesEvaluationObservable.remove(this._onAfterActiveMeshesEvaluationObserver);
  89307. this._onAfterActiveMeshesEvaluationObserver = null;
  89308. this.scene.OnBeforeRenderTargetsRenderObservable.remove(this._onBeforeRenderTargetsRenderObserver);
  89309. this._onBeforeRenderTargetsRenderObserver = null;
  89310. this.scene.OnAfterRenderTargetsRenderObservable.remove(this._onAfterRenderTargetsRenderObserver);
  89311. this._onAfterRenderTargetsRenderObserver = null;
  89312. this.scene.onBeforeAnimationsObservable.remove(this._onBeforeAnimationsObserver);
  89313. this._onBeforeAnimationsObserver = null;
  89314. this.scene.onBeforeParticlesRenderingObservable.remove(this._onBeforeParticlesRenderingObserver);
  89315. this._onBeforeParticlesRenderingObserver = null;
  89316. this.scene.onAfterParticlesRenderingObservable.remove(this._onAfterParticlesRenderingObserver);
  89317. this._onAfterParticlesRenderingObserver = null;
  89318. this.scene.onBeforeSpritesRenderingObservable.remove(this._onBeforeSpritesRenderingObserver);
  89319. this._onBeforeSpritesRenderingObserver = null;
  89320. this.scene.onAfterSpritesRenderingObservable.remove(this._onAfterSpritesRenderingObserver);
  89321. this._onAfterSpritesRenderingObserver = null;
  89322. this.scene.onBeforeDrawPhaseObservable.remove(this._onBeforeDrawPhaseObserver);
  89323. this._onBeforeDrawPhaseObserver = null;
  89324. this.scene.onAfterDrawPhaseObservable.remove(this._onAfterDrawPhaseObserver);
  89325. this._onAfterDrawPhaseObserver = null;
  89326. this.scene.onBeforePhysicsObservable.remove(this._onBeforePhysicsObserver);
  89327. this._onBeforePhysicsObserver = null;
  89328. this.scene.onAfterPhysicsObservable.remove(this._onAfterPhysicsObserver);
  89329. this._onAfterPhysicsObserver = null;
  89330. this.scene.onAfterAnimationsObservable.remove(this._onAfterAnimationsObserver);
  89331. this._onAfterAnimationsObserver = null;
  89332. this.scene = null;
  89333. };
  89334. return SceneInstrumentation;
  89335. }());
  89336. BABYLON.SceneInstrumentation = SceneInstrumentation;
  89337. })(BABYLON || (BABYLON = {}));
  89338. //# sourceMappingURL=babylon.sceneInstrumentation.js.map
  89339. var BABYLON;
  89340. (function (BABYLON) {
  89341. var _TimeToken = /** @class */ (function () {
  89342. function _TimeToken() {
  89343. this._timeElapsedQueryEnded = false;
  89344. }
  89345. return _TimeToken;
  89346. }());
  89347. BABYLON._TimeToken = _TimeToken;
  89348. })(BABYLON || (BABYLON = {}));
  89349. //# sourceMappingURL=babylon.timeToken.js.map
  89350. var BABYLON;
  89351. (function (BABYLON) {
  89352. /**
  89353. * Background material defines definition.
  89354. * @ignore Mainly internal Use
  89355. */
  89356. var BackgroundMaterialDefines = /** @class */ (function (_super) {
  89357. __extends(BackgroundMaterialDefines, _super);
  89358. /**
  89359. * Constructor of the defines.
  89360. */
  89361. function BackgroundMaterialDefines() {
  89362. var _this = _super.call(this) || this;
  89363. /**
  89364. * True if the diffuse texture is in use.
  89365. */
  89366. _this.DIFFUSE = false;
  89367. /**
  89368. * The direct UV channel to use.
  89369. */
  89370. _this.DIFFUSEDIRECTUV = 0;
  89371. /**
  89372. * True if the diffuse texture is in gamma space.
  89373. */
  89374. _this.GAMMADIFFUSE = false;
  89375. /**
  89376. * True if the diffuse texture has opacity in the alpha channel.
  89377. */
  89378. _this.DIFFUSEHASALPHA = false;
  89379. /**
  89380. * True if you want the material to fade to transparent at grazing angle.
  89381. */
  89382. _this.OPACITYFRESNEL = false;
  89383. /**
  89384. * True if an extra blur needs to be added in the reflection.
  89385. */
  89386. _this.REFLECTIONBLUR = false;
  89387. /**
  89388. * True if you want the material to fade to reflection at grazing angle.
  89389. */
  89390. _this.REFLECTIONFRESNEL = false;
  89391. /**
  89392. * True if you want the material to falloff as far as you move away from the scene center.
  89393. */
  89394. _this.REFLECTIONFALLOFF = false;
  89395. /**
  89396. * False if the current Webgl implementation does not support the texture lod extension.
  89397. */
  89398. _this.TEXTURELODSUPPORT = false;
  89399. /**
  89400. * True to ensure the data are premultiplied.
  89401. */
  89402. _this.PREMULTIPLYALPHA = false;
  89403. /**
  89404. * True if the texture contains cooked RGB values and not gray scaled multipliers.
  89405. */
  89406. _this.USERGBCOLOR = false;
  89407. /**
  89408. * True to add noise in order to reduce the banding effect.
  89409. */
  89410. _this.NOISE = false;
  89411. /**
  89412. * is the reflection texture in BGR color scheme?
  89413. * Mainly used to solve a bug in ios10 video tag
  89414. */
  89415. _this.REFLECTIONBGR = false;
  89416. _this.IMAGEPROCESSING = false;
  89417. _this.VIGNETTE = false;
  89418. _this.VIGNETTEBLENDMODEMULTIPLY = false;
  89419. _this.VIGNETTEBLENDMODEOPAQUE = false;
  89420. _this.TONEMAPPING = false;
  89421. _this.CONTRAST = false;
  89422. _this.COLORCURVES = false;
  89423. _this.COLORGRADING = false;
  89424. _this.COLORGRADING3D = false;
  89425. _this.SAMPLER3DGREENDEPTH = false;
  89426. _this.SAMPLER3DBGRMAP = false;
  89427. _this.IMAGEPROCESSINGPOSTPROCESS = false;
  89428. _this.EXPOSURE = false;
  89429. _this.GRAIN = false;
  89430. // Reflection.
  89431. _this.REFLECTION = false;
  89432. _this.REFLECTIONMAP_3D = false;
  89433. _this.REFLECTIONMAP_SPHERICAL = false;
  89434. _this.REFLECTIONMAP_PLANAR = false;
  89435. _this.REFLECTIONMAP_CUBIC = false;
  89436. _this.REFLECTIONMAP_PROJECTION = false;
  89437. _this.REFLECTIONMAP_SKYBOX = false;
  89438. _this.REFLECTIONMAP_EXPLICIT = false;
  89439. _this.REFLECTIONMAP_EQUIRECTANGULAR = false;
  89440. _this.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  89441. _this.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  89442. _this.INVERTCUBICMAP = false;
  89443. _this.REFLECTIONMAP_OPPOSITEZ = false;
  89444. _this.LODINREFLECTIONALPHA = false;
  89445. _this.GAMMAREFLECTION = false;
  89446. _this.EQUIRECTANGULAR_RELFECTION_FOV = false;
  89447. // Default BJS.
  89448. _this.MAINUV1 = false;
  89449. _this.MAINUV2 = false;
  89450. _this.UV1 = false;
  89451. _this.UV2 = false;
  89452. _this.CLIPPLANE = false;
  89453. _this.POINTSIZE = false;
  89454. _this.FOG = false;
  89455. _this.NORMAL = false;
  89456. _this.NUM_BONE_INFLUENCERS = 0;
  89457. _this.BonesPerMesh = 0;
  89458. _this.INSTANCES = false;
  89459. _this.SHADOWFLOAT = false;
  89460. _this.rebuild();
  89461. return _this;
  89462. }
  89463. return BackgroundMaterialDefines;
  89464. }(BABYLON.MaterialDefines));
  89465. /**
  89466. * Background material used to create an efficient environement around your scene.
  89467. */
  89468. var BackgroundMaterial = /** @class */ (function (_super) {
  89469. __extends(BackgroundMaterial, _super);
  89470. /**
  89471. * Instantiates a Background Material in the given scene
  89472. * @param name The friendly name of the material
  89473. * @param scene The scene to add the material to
  89474. */
  89475. function BackgroundMaterial(name, scene) {
  89476. var _this = _super.call(this, name, scene) || this;
  89477. /**
  89478. * Key light Color (multiply against the R channel of the environement texture)
  89479. */
  89480. _this.primaryColor = BABYLON.Color3.White();
  89481. /**
  89482. * Key light Level (allowing HDR output of the background)
  89483. */
  89484. _this.primaryLevel = 1;
  89485. /**
  89486. * Secondary light Color (multiply against the G channel of the environement texture)
  89487. */
  89488. _this.secondaryColor = BABYLON.Color3.Gray();
  89489. /**
  89490. * Secondary light Level (allowing HDR output of the background)
  89491. */
  89492. _this.secondaryLevel = 1;
  89493. /**
  89494. * Tertiary light Color (multiply against the B channel of the environement texture)
  89495. */
  89496. _this.tertiaryColor = BABYLON.Color3.Black();
  89497. /**
  89498. * Tertiary light Level (allowing HDR output of the background)
  89499. */
  89500. _this.tertiaryLevel = 1;
  89501. /**
  89502. * Reflection Texture used in the material.
  89503. * Should be author in a specific way for the best result (refer to the documentation).
  89504. */
  89505. _this.reflectionTexture = null;
  89506. /**
  89507. * Reflection Texture level of blur.
  89508. *
  89509. * Can be use to reuse an existing HDR Texture and target a specific LOD to prevent authoring the
  89510. * texture twice.
  89511. */
  89512. _this.reflectionBlur = 0;
  89513. /**
  89514. * Diffuse Texture used in the material.
  89515. * Should be author in a specific way for the best result (refer to the documentation).
  89516. */
  89517. _this.diffuseTexture = null;
  89518. _this._shadowLights = null;
  89519. /**
  89520. * Specify the list of lights casting shadow on the material.
  89521. * All scene shadow lights will be included if null.
  89522. */
  89523. _this.shadowLights = null;
  89524. /**
  89525. * For the lights having a blurred shadow generator, this can add a second blur pass in order to reach
  89526. * soft lighting on the background.
  89527. */
  89528. _this.shadowBlurScale = 1;
  89529. /**
  89530. * Helps adjusting the shadow to a softer level if required.
  89531. * 0 means black shadows and 1 means no shadows.
  89532. */
  89533. _this.shadowLevel = 0;
  89534. /**
  89535. * In case of opacity Fresnel or reflection falloff, this is use as a scene center.
  89536. * It is usually zero but might be interesting to modify according to your setup.
  89537. */
  89538. _this.sceneCenter = BABYLON.Vector3.Zero();
  89539. /**
  89540. * This helps specifying that the material is falling off to the sky box at grazing angle.
  89541. * This helps ensuring a nice transition when the camera goes under the ground.
  89542. */
  89543. _this.opacityFresnel = true;
  89544. /**
  89545. * This helps specifying that the material is falling off from diffuse to the reflection texture at grazing angle.
  89546. * This helps adding a mirror texture on the ground.
  89547. */
  89548. _this.reflectionFresnel = false;
  89549. /**
  89550. * This helps specifying the falloff radius off the reflection texture from the sceneCenter.
  89551. * This helps adding a nice falloff effect to the reflection if used as a mirror for instance.
  89552. */
  89553. _this.reflectionFalloffDistance = 0.0;
  89554. /**
  89555. * This specifies the weight of the reflection against the background in case of reflection Fresnel.
  89556. */
  89557. _this.reflectionAmount = 1.0;
  89558. /**
  89559. * This specifies the weight of the reflection at grazing angle.
  89560. */
  89561. _this.reflectionReflectance0 = 0.05;
  89562. /**
  89563. * This specifies the weight of the reflection at a perpendicular point of view.
  89564. */
  89565. _this.reflectionReflectance90 = 0.5;
  89566. /**
  89567. * Helps to directly use the maps channels instead of their level.
  89568. */
  89569. _this.useRGBColor = true;
  89570. /**
  89571. * This helps reducing the banding effect that could occur on the background.
  89572. */
  89573. _this.enableNoise = false;
  89574. _this._fovMultiplier = 1.0;
  89575. /**
  89576. * Enable the FOV adjustment feature controlled by fovMultiplier.
  89577. * @type {boolean}
  89578. */
  89579. _this.useEquirectangularFOV = false;
  89580. _this._maxSimultaneousLights = 4;
  89581. /**
  89582. * Number of Simultaneous lights allowed on the material.
  89583. */
  89584. _this.maxSimultaneousLights = 4;
  89585. /**
  89586. * Keep track of the image processing observer to allow dispose and replace.
  89587. */
  89588. _this._imageProcessingObserver = null;
  89589. /**
  89590. * Due to a bug in iOS10, video tags (which are using the background material) are in BGR and not RGB.
  89591. * Setting this flag to true (not done automatically!) will convert it back to RGB.
  89592. */
  89593. _this.switchToBGR = false;
  89594. // Temp values kept as cache in the material.
  89595. _this._renderTargets = new BABYLON.SmartArray(16);
  89596. _this._reflectionControls = BABYLON.Vector4.Zero();
  89597. // Setup the default processing configuration to the scene.
  89598. _this._attachImageProcessingConfiguration(null);
  89599. _this.getRenderTargetTextures = function () {
  89600. _this._renderTargets.reset();
  89601. if (_this._diffuseTexture && _this._diffuseTexture.isRenderTarget) {
  89602. _this._renderTargets.push(_this._diffuseTexture);
  89603. }
  89604. if (_this._reflectionTexture && _this._reflectionTexture.isRenderTarget) {
  89605. _this._renderTargets.push(_this._reflectionTexture);
  89606. }
  89607. return _this._renderTargets;
  89608. };
  89609. return _this;
  89610. }
  89611. Object.defineProperty(BackgroundMaterial.prototype, "reflectionStandardFresnelWeight", {
  89612. /**
  89613. * Sets the reflection reflectance fresnel values according to the default standard
  89614. * empirically know to work well :-)
  89615. */
  89616. set: function (value) {
  89617. var reflectionWeight = value;
  89618. if (reflectionWeight < 0.5) {
  89619. reflectionWeight = reflectionWeight * 2.0;
  89620. this.reflectionReflectance0 = BackgroundMaterial.StandardReflectance0 * reflectionWeight;
  89621. this.reflectionReflectance90 = BackgroundMaterial.StandardReflectance90 * reflectionWeight;
  89622. }
  89623. else {
  89624. reflectionWeight = reflectionWeight * 2.0 - 1.0;
  89625. this.reflectionReflectance0 = BackgroundMaterial.StandardReflectance0 + (1.0 - BackgroundMaterial.StandardReflectance0) * reflectionWeight;
  89626. this.reflectionReflectance90 = BackgroundMaterial.StandardReflectance90 + (1.0 - BackgroundMaterial.StandardReflectance90) * reflectionWeight;
  89627. }
  89628. },
  89629. enumerable: true,
  89630. configurable: true
  89631. });
  89632. Object.defineProperty(BackgroundMaterial.prototype, "fovMultiplier", {
  89633. /**
  89634. * The current fov(field of view) multiplier, 0.0 - 2.0. Defaults to 1.0. Lower values "zoom in" and higher values "zoom out".
  89635. * Best used when trying to implement visual zoom effects like fish-eye or binoculars while not adjusting camera fov.
  89636. * Recommended to be keep at 1.0 except for special cases.
  89637. */
  89638. get: function () {
  89639. return this._fovMultiplier;
  89640. },
  89641. set: function (value) {
  89642. if (isNaN(value)) {
  89643. value = 1.0;
  89644. }
  89645. this._fovMultiplier = Math.max(0.0, Math.min(2.0, value));
  89646. },
  89647. enumerable: true,
  89648. configurable: true
  89649. });
  89650. /**
  89651. * Attaches a new image processing configuration to the PBR Material.
  89652. * @param configuration (if null the scene configuration will be use)
  89653. */
  89654. BackgroundMaterial.prototype._attachImageProcessingConfiguration = function (configuration) {
  89655. var _this = this;
  89656. if (configuration === this._imageProcessingConfiguration) {
  89657. return;
  89658. }
  89659. // Detaches observer.
  89660. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  89661. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  89662. }
  89663. // Pick the scene configuration if needed.
  89664. if (!configuration) {
  89665. this._imageProcessingConfiguration = this.getScene().imageProcessingConfiguration;
  89666. }
  89667. else {
  89668. this._imageProcessingConfiguration = configuration;
  89669. }
  89670. // Attaches observer.
  89671. this._imageProcessingObserver = this._imageProcessingConfiguration.onUpdateParameters.add(function (conf) {
  89672. _this._markAllSubMeshesAsImageProcessingDirty();
  89673. });
  89674. };
  89675. Object.defineProperty(BackgroundMaterial.prototype, "imageProcessingConfiguration", {
  89676. /**
  89677. * Gets the image processing configuration used either in this material.
  89678. */
  89679. get: function () {
  89680. return this._imageProcessingConfiguration;
  89681. },
  89682. /**
  89683. * Sets the Default image processing configuration used either in the this material.
  89684. *
  89685. * If sets to null, the scene one is in use.
  89686. */
  89687. set: function (value) {
  89688. this._attachImageProcessingConfiguration(value);
  89689. // Ensure the effect will be rebuilt.
  89690. this._markAllSubMeshesAsTexturesDirty();
  89691. },
  89692. enumerable: true,
  89693. configurable: true
  89694. });
  89695. Object.defineProperty(BackgroundMaterial.prototype, "cameraColorCurvesEnabled", {
  89696. /**
  89697. * Gets wether the color curves effect is enabled.
  89698. */
  89699. get: function () {
  89700. return this.imageProcessingConfiguration.colorCurvesEnabled;
  89701. },
  89702. /**
  89703. * Sets wether the color curves effect is enabled.
  89704. */
  89705. set: function (value) {
  89706. this.imageProcessingConfiguration.colorCurvesEnabled = value;
  89707. },
  89708. enumerable: true,
  89709. configurable: true
  89710. });
  89711. Object.defineProperty(BackgroundMaterial.prototype, "cameraColorGradingEnabled", {
  89712. /**
  89713. * Gets wether the color grading effect is enabled.
  89714. */
  89715. get: function () {
  89716. return this.imageProcessingConfiguration.colorGradingEnabled;
  89717. },
  89718. /**
  89719. * Gets wether the color grading effect is enabled.
  89720. */
  89721. set: function (value) {
  89722. this.imageProcessingConfiguration.colorGradingEnabled = value;
  89723. },
  89724. enumerable: true,
  89725. configurable: true
  89726. });
  89727. Object.defineProperty(BackgroundMaterial.prototype, "cameraToneMappingEnabled", {
  89728. /**
  89729. * Gets wether tonemapping is enabled or not.
  89730. */
  89731. get: function () {
  89732. return this._imageProcessingConfiguration.toneMappingEnabled;
  89733. },
  89734. /**
  89735. * Sets wether tonemapping is enabled or not
  89736. */
  89737. set: function (value) {
  89738. this._imageProcessingConfiguration.toneMappingEnabled = value;
  89739. },
  89740. enumerable: true,
  89741. configurable: true
  89742. });
  89743. ;
  89744. ;
  89745. Object.defineProperty(BackgroundMaterial.prototype, "cameraExposure", {
  89746. /**
  89747. * The camera exposure used on this material.
  89748. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  89749. * This corresponds to a photographic exposure.
  89750. */
  89751. get: function () {
  89752. return this._imageProcessingConfiguration.exposure;
  89753. },
  89754. /**
  89755. * The camera exposure used on this material.
  89756. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  89757. * This corresponds to a photographic exposure.
  89758. */
  89759. set: function (value) {
  89760. this._imageProcessingConfiguration.exposure = value;
  89761. },
  89762. enumerable: true,
  89763. configurable: true
  89764. });
  89765. ;
  89766. ;
  89767. Object.defineProperty(BackgroundMaterial.prototype, "cameraContrast", {
  89768. /**
  89769. * Gets The camera contrast used on this material.
  89770. */
  89771. get: function () {
  89772. return this._imageProcessingConfiguration.contrast;
  89773. },
  89774. /**
  89775. * Sets The camera contrast used on this material.
  89776. */
  89777. set: function (value) {
  89778. this._imageProcessingConfiguration.contrast = value;
  89779. },
  89780. enumerable: true,
  89781. configurable: true
  89782. });
  89783. Object.defineProperty(BackgroundMaterial.prototype, "cameraColorGradingTexture", {
  89784. /**
  89785. * Gets the Color Grading 2D Lookup Texture.
  89786. */
  89787. get: function () {
  89788. return this._imageProcessingConfiguration.colorGradingTexture;
  89789. },
  89790. /**
  89791. * Sets the Color Grading 2D Lookup Texture.
  89792. */
  89793. set: function (value) {
  89794. this.imageProcessingConfiguration.colorGradingTexture = value;
  89795. },
  89796. enumerable: true,
  89797. configurable: true
  89798. });
  89799. Object.defineProperty(BackgroundMaterial.prototype, "cameraColorCurves", {
  89800. /**
  89801. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  89802. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  89803. * 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;
  89804. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  89805. */
  89806. get: function () {
  89807. return this.imageProcessingConfiguration.colorCurves;
  89808. },
  89809. /**
  89810. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  89811. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  89812. * 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;
  89813. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  89814. */
  89815. set: function (value) {
  89816. this.imageProcessingConfiguration.colorCurves = value;
  89817. },
  89818. enumerable: true,
  89819. configurable: true
  89820. });
  89821. /**
  89822. * The entire material has been created in order to prevent overdraw.
  89823. * @returns false
  89824. */
  89825. BackgroundMaterial.prototype.needAlphaTesting = function () {
  89826. return true;
  89827. };
  89828. /**
  89829. * The entire material has been created in order to prevent overdraw.
  89830. * @returns true if blending is enable
  89831. */
  89832. BackgroundMaterial.prototype.needAlphaBlending = function () {
  89833. return ((this.alpha < 0) || (this._diffuseTexture != null && this._diffuseTexture.hasAlpha));
  89834. };
  89835. /**
  89836. * Checks wether the material is ready to be rendered for a given mesh.
  89837. * @param mesh The mesh to render
  89838. * @param subMesh The submesh to check against
  89839. * @param useInstances Specify wether or not the material is used with instances
  89840. * @returns true if all the dependencies are ready (Textures, Effects...)
  89841. */
  89842. BackgroundMaterial.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  89843. var _this = this;
  89844. if (useInstances === void 0) { useInstances = false; }
  89845. if (subMesh.effect && this.isFrozen) {
  89846. if (this._wasPreviouslyReady) {
  89847. return true;
  89848. }
  89849. }
  89850. if (!subMesh._materialDefines) {
  89851. subMesh._materialDefines = new BackgroundMaterialDefines();
  89852. }
  89853. var scene = this.getScene();
  89854. var defines = subMesh._materialDefines;
  89855. if (!this.checkReadyOnEveryCall && subMesh.effect) {
  89856. if (defines._renderId === scene.getRenderId()) {
  89857. return true;
  89858. }
  89859. }
  89860. var engine = scene.getEngine();
  89861. // Lights
  89862. BABYLON.MaterialHelper.PrepareDefinesForLights(scene, mesh, defines, false, this._maxSimultaneousLights);
  89863. defines._needNormals = true;
  89864. // Textures
  89865. if (defines._areTexturesDirty) {
  89866. defines._needUVs = false;
  89867. if (scene.texturesEnabled) {
  89868. if (scene.getEngine().getCaps().textureLOD) {
  89869. defines.TEXTURELODSUPPORT = true;
  89870. }
  89871. if (this._diffuseTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  89872. if (!this._diffuseTexture.isReadyOrNotBlocking()) {
  89873. return false;
  89874. }
  89875. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._diffuseTexture, defines, "DIFFUSE");
  89876. defines.DIFFUSEHASALPHA = this._diffuseTexture.hasAlpha;
  89877. defines.GAMMADIFFUSE = this._diffuseTexture.gammaSpace;
  89878. defines.OPACITYFRESNEL = this._opacityFresnel;
  89879. }
  89880. else {
  89881. defines.DIFFUSE = false;
  89882. defines.DIFFUSEHASALPHA = false;
  89883. defines.GAMMADIFFUSE = false;
  89884. defines.OPACITYFRESNEL = false;
  89885. }
  89886. var reflectionTexture = this._reflectionTexture;
  89887. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  89888. if (!reflectionTexture.isReadyOrNotBlocking()) {
  89889. return false;
  89890. }
  89891. defines.REFLECTION = true;
  89892. defines.GAMMAREFLECTION = reflectionTexture.gammaSpace;
  89893. defines.REFLECTIONBLUR = this._reflectionBlur > 0;
  89894. defines.REFLECTIONMAP_OPPOSITEZ = this.getScene().useRightHandedSystem ? !reflectionTexture.invertZ : reflectionTexture.invertZ;
  89895. defines.LODINREFLECTIONALPHA = reflectionTexture.lodLevelInAlpha;
  89896. defines.EQUIRECTANGULAR_RELFECTION_FOV = this.useEquirectangularFOV;
  89897. defines.REFLECTIONBGR = this.switchToBGR;
  89898. if (reflectionTexture.coordinatesMode === BABYLON.Texture.INVCUBIC_MODE) {
  89899. defines.INVERTCUBICMAP = true;
  89900. }
  89901. defines.REFLECTIONMAP_3D = reflectionTexture.isCube;
  89902. switch (reflectionTexture.coordinatesMode) {
  89903. case BABYLON.Texture.CUBIC_MODE:
  89904. case BABYLON.Texture.INVCUBIC_MODE:
  89905. defines.REFLECTIONMAP_CUBIC = true;
  89906. break;
  89907. case BABYLON.Texture.EXPLICIT_MODE:
  89908. defines.REFLECTIONMAP_EXPLICIT = true;
  89909. break;
  89910. case BABYLON.Texture.PLANAR_MODE:
  89911. defines.REFLECTIONMAP_PLANAR = true;
  89912. break;
  89913. case BABYLON.Texture.PROJECTION_MODE:
  89914. defines.REFLECTIONMAP_PROJECTION = true;
  89915. break;
  89916. case BABYLON.Texture.SKYBOX_MODE:
  89917. defines.REFLECTIONMAP_SKYBOX = true;
  89918. break;
  89919. case BABYLON.Texture.SPHERICAL_MODE:
  89920. defines.REFLECTIONMAP_SPHERICAL = true;
  89921. break;
  89922. case BABYLON.Texture.EQUIRECTANGULAR_MODE:
  89923. defines.REFLECTIONMAP_EQUIRECTANGULAR = true;
  89924. break;
  89925. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MODE:
  89926. defines.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = true;
  89927. break;
  89928. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE:
  89929. defines.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = true;
  89930. break;
  89931. }
  89932. if (this.reflectionFresnel) {
  89933. defines.REFLECTIONFRESNEL = true;
  89934. defines.REFLECTIONFALLOFF = this.reflectionFalloffDistance > 0;
  89935. this._reflectionControls.x = this.reflectionAmount;
  89936. this._reflectionControls.y = this.reflectionReflectance0;
  89937. this._reflectionControls.z = this.reflectionReflectance90;
  89938. this._reflectionControls.w = 1 / this.reflectionFalloffDistance;
  89939. }
  89940. else {
  89941. defines.REFLECTIONFRESNEL = false;
  89942. defines.REFLECTIONFALLOFF = false;
  89943. }
  89944. }
  89945. else {
  89946. defines.REFLECTION = false;
  89947. defines.REFLECTIONFALLOFF = false;
  89948. defines.REFLECTIONBLUR = false;
  89949. defines.REFLECTIONMAP_3D = false;
  89950. defines.REFLECTIONMAP_SPHERICAL = false;
  89951. defines.REFLECTIONMAP_PLANAR = false;
  89952. defines.REFLECTIONMAP_CUBIC = false;
  89953. defines.REFLECTIONMAP_PROJECTION = false;
  89954. defines.REFLECTIONMAP_SKYBOX = false;
  89955. defines.REFLECTIONMAP_EXPLICIT = false;
  89956. defines.REFLECTIONMAP_EQUIRECTANGULAR = false;
  89957. defines.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  89958. defines.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  89959. defines.INVERTCUBICMAP = false;
  89960. defines.REFLECTIONMAP_OPPOSITEZ = false;
  89961. defines.LODINREFLECTIONALPHA = false;
  89962. defines.GAMMAREFLECTION = false;
  89963. }
  89964. }
  89965. defines.PREMULTIPLYALPHA = (this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED || this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED_PORTERDUFF);
  89966. defines.USERGBCOLOR = this._useRGBColor;
  89967. defines.NOISE = this._enableNoise;
  89968. }
  89969. if (defines._areImageProcessingDirty) {
  89970. if (!this._imageProcessingConfiguration.isReady()) {
  89971. return false;
  89972. }
  89973. this._imageProcessingConfiguration.prepareDefines(defines);
  89974. }
  89975. // Misc.
  89976. BABYLON.MaterialHelper.PrepareDefinesForMisc(mesh, scene, false, this.pointsCloud, this.fogEnabled, this._shouldTurnAlphaTestOn(mesh), defines);
  89977. // Values that need to be evaluated on every frame
  89978. BABYLON.MaterialHelper.PrepareDefinesForFrameBoundValues(scene, engine, defines, useInstances);
  89979. // Attribs
  89980. if (BABYLON.MaterialHelper.PrepareDefinesForAttributes(mesh, defines, false, true, false)) {
  89981. if (mesh) {
  89982. if (!scene.getEngine().getCaps().standardDerivatives && !mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  89983. mesh.createNormals(true);
  89984. BABYLON.Tools.Warn("BackgroundMaterial: Normals have been created for the mesh: " + mesh.name);
  89985. }
  89986. }
  89987. }
  89988. // Get correct effect
  89989. if (defines.isDirty) {
  89990. defines.markAsProcessed();
  89991. scene.resetCachedMaterial();
  89992. // Fallbacks
  89993. var fallbacks = new BABYLON.EffectFallbacks();
  89994. if (defines.FOG) {
  89995. fallbacks.addFallback(0, "FOG");
  89996. }
  89997. if (defines.POINTSIZE) {
  89998. fallbacks.addFallback(1, "POINTSIZE");
  89999. }
  90000. BABYLON.MaterialHelper.HandleFallbacksForShadows(defines, fallbacks, this._maxSimultaneousLights);
  90001. if (defines.NUM_BONE_INFLUENCERS > 0) {
  90002. fallbacks.addCPUSkinningFallback(0, mesh);
  90003. }
  90004. //Attributes
  90005. var attribs = [BABYLON.VertexBuffer.PositionKind];
  90006. if (defines.NORMAL) {
  90007. attribs.push(BABYLON.VertexBuffer.NormalKind);
  90008. }
  90009. if (defines.UV1) {
  90010. attribs.push(BABYLON.VertexBuffer.UVKind);
  90011. }
  90012. if (defines.UV2) {
  90013. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  90014. }
  90015. BABYLON.MaterialHelper.PrepareAttributesForBones(attribs, mesh, defines, fallbacks);
  90016. BABYLON.MaterialHelper.PrepareAttributesForInstances(attribs, defines);
  90017. var uniforms = ["world", "view", "viewProjection", "vEyePosition", "vLightsType",
  90018. "vFogInfos", "vFogColor", "pointSize",
  90019. "vClipPlane", "mBones",
  90020. "vPrimaryColor", "vSecondaryColor", "vTertiaryColor",
  90021. "vReflectionInfos", "reflectionMatrix", "vReflectionMicrosurfaceInfos", "fFovMultiplier",
  90022. "shadowLevel", "alpha",
  90023. "vBackgroundCenter", "vReflectionControl",
  90024. "vDiffuseInfos", "diffuseMatrix",
  90025. ];
  90026. var samplers = ["diffuseSampler", "reflectionSampler", "reflectionSamplerLow", "reflectionSamplerHigh"];
  90027. var uniformBuffers = ["Material", "Scene"];
  90028. BABYLON.ImageProcessingConfiguration.PrepareUniforms(uniforms, defines);
  90029. BABYLON.ImageProcessingConfiguration.PrepareSamplers(samplers, defines);
  90030. BABYLON.MaterialHelper.PrepareUniformsAndSamplersList({
  90031. uniformsNames: uniforms,
  90032. uniformBuffersNames: uniformBuffers,
  90033. samplers: samplers,
  90034. defines: defines,
  90035. maxSimultaneousLights: this._maxSimultaneousLights
  90036. });
  90037. var onCompiled = function (effect) {
  90038. if (_this.onCompiled) {
  90039. _this.onCompiled(effect);
  90040. }
  90041. _this.bindSceneUniformBuffer(effect, scene.getSceneUniformBuffer());
  90042. };
  90043. var join = defines.toString();
  90044. subMesh.setEffect(scene.getEngine().createEffect("background", {
  90045. attributes: attribs,
  90046. uniformsNames: uniforms,
  90047. uniformBuffersNames: uniformBuffers,
  90048. samplers: samplers,
  90049. defines: join,
  90050. fallbacks: fallbacks,
  90051. onCompiled: onCompiled,
  90052. onError: this.onError,
  90053. indexParameters: { maxSimultaneousLights: this._maxSimultaneousLights }
  90054. }, engine), defines);
  90055. this.buildUniformLayout();
  90056. }
  90057. if (!subMesh.effect || !subMesh.effect.isReady()) {
  90058. return false;
  90059. }
  90060. defines._renderId = scene.getRenderId();
  90061. this._wasPreviouslyReady = true;
  90062. return true;
  90063. };
  90064. /**
  90065. * Build the uniform buffer used in the material.
  90066. */
  90067. BackgroundMaterial.prototype.buildUniformLayout = function () {
  90068. // Order is important !
  90069. this._uniformBuffer.addUniform("vPrimaryColor", 4);
  90070. this._uniformBuffer.addUniform("vSecondaryColor", 4);
  90071. this._uniformBuffer.addUniform("vTertiaryColor", 4);
  90072. this._uniformBuffer.addUniform("vDiffuseInfos", 2);
  90073. this._uniformBuffer.addUniform("vReflectionInfos", 2);
  90074. this._uniformBuffer.addUniform("diffuseMatrix", 16);
  90075. this._uniformBuffer.addUniform("reflectionMatrix", 16);
  90076. this._uniformBuffer.addUniform("vReflectionMicrosurfaceInfos", 3);
  90077. this._uniformBuffer.addUniform("fFovMultiplier", 1);
  90078. this._uniformBuffer.addUniform("pointSize", 1);
  90079. this._uniformBuffer.addUniform("shadowLevel", 1);
  90080. this._uniformBuffer.addUniform("alpha", 1);
  90081. this._uniformBuffer.addUniform("vBackgroundCenter", 3);
  90082. this._uniformBuffer.addUniform("vReflectionControl", 4);
  90083. this._uniformBuffer.create();
  90084. };
  90085. /**
  90086. * Unbind the material.
  90087. */
  90088. BackgroundMaterial.prototype.unbind = function () {
  90089. if (this._diffuseTexture && this._diffuseTexture.isRenderTarget) {
  90090. this._uniformBuffer.setTexture("diffuseSampler", null);
  90091. }
  90092. if (this._reflectionTexture && this._reflectionTexture.isRenderTarget) {
  90093. this._uniformBuffer.setTexture("reflectionSampler", null);
  90094. }
  90095. _super.prototype.unbind.call(this);
  90096. };
  90097. /**
  90098. * Bind only the world matrix to the material.
  90099. * @param world The world matrix to bind.
  90100. */
  90101. BackgroundMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  90102. this._activeEffect.setMatrix("world", world);
  90103. };
  90104. /**
  90105. * Bind the material for a dedicated submeh (every used meshes will be considered opaque).
  90106. * @param world The world matrix to bind.
  90107. * @param subMesh The submesh to bind for.
  90108. */
  90109. BackgroundMaterial.prototype.bindForSubMesh = function (world, mesh, subMesh) {
  90110. var scene = this.getScene();
  90111. var defines = subMesh._materialDefines;
  90112. if (!defines) {
  90113. return;
  90114. }
  90115. var effect = subMesh.effect;
  90116. if (!effect) {
  90117. return;
  90118. }
  90119. this._activeEffect = effect;
  90120. // Matrices
  90121. this.bindOnlyWorldMatrix(world);
  90122. // Bones
  90123. BABYLON.MaterialHelper.BindBonesParameters(mesh, this._activeEffect);
  90124. var mustRebind = this._mustRebind(scene, effect, mesh.visibility);
  90125. if (mustRebind) {
  90126. this._uniformBuffer.bindToEffect(effect, "Material");
  90127. this.bindViewProjection(effect);
  90128. var reflectionTexture = this._reflectionTexture;
  90129. if (!this._uniformBuffer.useUbo || !this.isFrozen || !this._uniformBuffer.isSync) {
  90130. // Texture uniforms
  90131. if (scene.texturesEnabled) {
  90132. if (this._diffuseTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  90133. this._uniformBuffer.updateFloat2("vDiffuseInfos", this._diffuseTexture.coordinatesIndex, this._diffuseTexture.level);
  90134. BABYLON.MaterialHelper.BindTextureMatrix(this._diffuseTexture, this._uniformBuffer, "diffuse");
  90135. }
  90136. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  90137. this._uniformBuffer.updateMatrix("reflectionMatrix", reflectionTexture.getReflectionTextureMatrix());
  90138. this._uniformBuffer.updateFloat2("vReflectionInfos", reflectionTexture.level, this._reflectionBlur);
  90139. this._uniformBuffer.updateFloat3("vReflectionMicrosurfaceInfos", reflectionTexture.getSize().width, reflectionTexture.lodGenerationScale, reflectionTexture.lodGenerationOffset);
  90140. }
  90141. }
  90142. if (this.shadowLevel > 0) {
  90143. this._uniformBuffer.updateFloat("shadowLevel", this.shadowLevel);
  90144. }
  90145. this._uniformBuffer.updateFloat("alpha", this.alpha);
  90146. // Point size
  90147. if (this.pointsCloud) {
  90148. this._uniformBuffer.updateFloat("pointSize", this.pointSize);
  90149. }
  90150. this._uniformBuffer.updateColor4("vPrimaryColor", this._primaryColor, this._primaryLevel);
  90151. this._uniformBuffer.updateColor4("vSecondaryColor", this._secondaryColor, this._secondaryLevel);
  90152. this._uniformBuffer.updateColor4("vTertiaryColor", this._tertiaryColor, this._tertiaryLevel);
  90153. }
  90154. this._uniformBuffer.updateFloat("fFovMultiplier", this._fovMultiplier);
  90155. // Textures
  90156. if (scene.texturesEnabled) {
  90157. if (this._diffuseTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  90158. this._uniformBuffer.setTexture("diffuseSampler", this._diffuseTexture);
  90159. }
  90160. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  90161. if (defines.REFLECTIONBLUR && defines.TEXTURELODSUPPORT) {
  90162. this._uniformBuffer.setTexture("reflectionSampler", reflectionTexture);
  90163. }
  90164. else if (!defines.REFLECTIONBLUR) {
  90165. this._uniformBuffer.setTexture("reflectionSampler", reflectionTexture);
  90166. }
  90167. else {
  90168. this._uniformBuffer.setTexture("reflectionSampler", reflectionTexture._lodTextureMid || reflectionTexture);
  90169. this._uniformBuffer.setTexture("reflectionSamplerLow", reflectionTexture._lodTextureLow || reflectionTexture);
  90170. this._uniformBuffer.setTexture("reflectionSamplerHigh", reflectionTexture._lodTextureHigh || reflectionTexture);
  90171. }
  90172. if (defines.REFLECTIONFRESNEL) {
  90173. this._uniformBuffer.updateFloat3("vBackgroundCenter", this.sceneCenter.x, this.sceneCenter.y, this.sceneCenter.z);
  90174. this._uniformBuffer.updateFloat4("vReflectionControl", this._reflectionControls.x, this._reflectionControls.y, this._reflectionControls.z, this._reflectionControls.w);
  90175. }
  90176. }
  90177. }
  90178. // Clip plane
  90179. BABYLON.MaterialHelper.BindClipPlane(this._activeEffect, scene);
  90180. BABYLON.MaterialHelper.BindEyePosition(effect, scene);
  90181. }
  90182. if (mustRebind || !this.isFrozen) {
  90183. if (scene.lightsEnabled) {
  90184. BABYLON.MaterialHelper.BindLights(scene, mesh, this._activeEffect, defines, this._maxSimultaneousLights, false);
  90185. }
  90186. // View
  90187. this.bindView(effect);
  90188. // Fog
  90189. BABYLON.MaterialHelper.BindFogParameters(scene, mesh, this._activeEffect);
  90190. // image processing
  90191. this._imageProcessingConfiguration.bind(this._activeEffect);
  90192. }
  90193. this._uniformBuffer.update();
  90194. this._afterBind(mesh);
  90195. };
  90196. /**
  90197. * Dispose the material.
  90198. * @param forceDisposeEffect Force disposal of the associated effect.
  90199. * @param forceDisposeTextures Force disposal of the associated textures.
  90200. */
  90201. BackgroundMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  90202. if (forceDisposeEffect === void 0) { forceDisposeEffect = false; }
  90203. if (forceDisposeTextures === void 0) { forceDisposeTextures = false; }
  90204. if (forceDisposeTextures) {
  90205. if (this.diffuseTexture) {
  90206. this.diffuseTexture.dispose();
  90207. }
  90208. if (this.reflectionTexture) {
  90209. this.reflectionTexture.dispose();
  90210. }
  90211. }
  90212. this._renderTargets.dispose();
  90213. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  90214. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  90215. }
  90216. _super.prototype.dispose.call(this, forceDisposeEffect);
  90217. };
  90218. /**
  90219. * Clones the material.
  90220. * @param name The cloned name.
  90221. * @returns The cloned material.
  90222. */
  90223. BackgroundMaterial.prototype.clone = function (name) {
  90224. var _this = this;
  90225. return BABYLON.SerializationHelper.Clone(function () { return new BackgroundMaterial(name, _this.getScene()); }, this);
  90226. };
  90227. /**
  90228. * Serializes the current material to its JSON representation.
  90229. * @returns The JSON representation.
  90230. */
  90231. BackgroundMaterial.prototype.serialize = function () {
  90232. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  90233. serializationObject.customType = "BABYLON.BackgroundMaterial";
  90234. return serializationObject;
  90235. };
  90236. /**
  90237. * Gets the class name of the material
  90238. * @returns "BackgroundMaterial"
  90239. */
  90240. BackgroundMaterial.prototype.getClassName = function () {
  90241. return "BackgroundMaterial";
  90242. };
  90243. /**
  90244. * Parse a JSON input to create back a background material.
  90245. * @param source The JSON data to parse
  90246. * @param scene The scene to create the parsed material in
  90247. * @param rootUrl The root url of the assets the material depends upon
  90248. * @returns the instantiated BackgroundMaterial.
  90249. */
  90250. BackgroundMaterial.Parse = function (source, scene, rootUrl) {
  90251. return BABYLON.SerializationHelper.Parse(function () { return new BackgroundMaterial(source.name, scene); }, source, scene, rootUrl);
  90252. };
  90253. /**
  90254. * Standard reflectance value at parallel view angle.
  90255. */
  90256. BackgroundMaterial.StandardReflectance0 = 0.05;
  90257. /**
  90258. * Standard reflectance value at grazing angle.
  90259. */
  90260. BackgroundMaterial.StandardReflectance90 = 0.5;
  90261. __decorate([
  90262. BABYLON.serializeAsColor3()
  90263. ], BackgroundMaterial.prototype, "_primaryColor", void 0);
  90264. __decorate([
  90265. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  90266. ], BackgroundMaterial.prototype, "primaryColor", void 0);
  90267. __decorate([
  90268. BABYLON.serialize()
  90269. ], BackgroundMaterial.prototype, "_primaryLevel", void 0);
  90270. __decorate([
  90271. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  90272. ], BackgroundMaterial.prototype, "primaryLevel", void 0);
  90273. __decorate([
  90274. BABYLON.serializeAsColor3()
  90275. ], BackgroundMaterial.prototype, "_secondaryColor", void 0);
  90276. __decorate([
  90277. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  90278. ], BackgroundMaterial.prototype, "secondaryColor", void 0);
  90279. __decorate([
  90280. BABYLON.serialize()
  90281. ], BackgroundMaterial.prototype, "_secondaryLevel", void 0);
  90282. __decorate([
  90283. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  90284. ], BackgroundMaterial.prototype, "secondaryLevel", void 0);
  90285. __decorate([
  90286. BABYLON.serializeAsColor3()
  90287. ], BackgroundMaterial.prototype, "_tertiaryColor", void 0);
  90288. __decorate([
  90289. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  90290. ], BackgroundMaterial.prototype, "tertiaryColor", void 0);
  90291. __decorate([
  90292. BABYLON.serialize()
  90293. ], BackgroundMaterial.prototype, "_tertiaryLevel", void 0);
  90294. __decorate([
  90295. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  90296. ], BackgroundMaterial.prototype, "tertiaryLevel", void 0);
  90297. __decorate([
  90298. BABYLON.serializeAsTexture()
  90299. ], BackgroundMaterial.prototype, "_reflectionTexture", void 0);
  90300. __decorate([
  90301. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  90302. ], BackgroundMaterial.prototype, "reflectionTexture", void 0);
  90303. __decorate([
  90304. BABYLON.serialize()
  90305. ], BackgroundMaterial.prototype, "_reflectionBlur", void 0);
  90306. __decorate([
  90307. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  90308. ], BackgroundMaterial.prototype, "reflectionBlur", void 0);
  90309. __decorate([
  90310. BABYLON.serializeAsTexture()
  90311. ], BackgroundMaterial.prototype, "_diffuseTexture", void 0);
  90312. __decorate([
  90313. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  90314. ], BackgroundMaterial.prototype, "diffuseTexture", void 0);
  90315. __decorate([
  90316. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  90317. ], BackgroundMaterial.prototype, "shadowLights", void 0);
  90318. __decorate([
  90319. BABYLON.serialize()
  90320. ], BackgroundMaterial.prototype, "_shadowBlurScale", void 0);
  90321. __decorate([
  90322. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  90323. ], BackgroundMaterial.prototype, "shadowBlurScale", void 0);
  90324. __decorate([
  90325. BABYLON.serialize()
  90326. ], BackgroundMaterial.prototype, "_shadowLevel", void 0);
  90327. __decorate([
  90328. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  90329. ], BackgroundMaterial.prototype, "shadowLevel", void 0);
  90330. __decorate([
  90331. BABYLON.serializeAsVector3()
  90332. ], BackgroundMaterial.prototype, "_sceneCenter", void 0);
  90333. __decorate([
  90334. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  90335. ], BackgroundMaterial.prototype, "sceneCenter", void 0);
  90336. __decorate([
  90337. BABYLON.serialize()
  90338. ], BackgroundMaterial.prototype, "_opacityFresnel", void 0);
  90339. __decorate([
  90340. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  90341. ], BackgroundMaterial.prototype, "opacityFresnel", void 0);
  90342. __decorate([
  90343. BABYLON.serialize()
  90344. ], BackgroundMaterial.prototype, "_reflectionFresnel", void 0);
  90345. __decorate([
  90346. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  90347. ], BackgroundMaterial.prototype, "reflectionFresnel", void 0);
  90348. __decorate([
  90349. BABYLON.serialize()
  90350. ], BackgroundMaterial.prototype, "_reflectionFalloffDistance", void 0);
  90351. __decorate([
  90352. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  90353. ], BackgroundMaterial.prototype, "reflectionFalloffDistance", void 0);
  90354. __decorate([
  90355. BABYLON.serialize()
  90356. ], BackgroundMaterial.prototype, "_reflectionAmount", void 0);
  90357. __decorate([
  90358. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  90359. ], BackgroundMaterial.prototype, "reflectionAmount", void 0);
  90360. __decorate([
  90361. BABYLON.serialize()
  90362. ], BackgroundMaterial.prototype, "_reflectionReflectance0", void 0);
  90363. __decorate([
  90364. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  90365. ], BackgroundMaterial.prototype, "reflectionReflectance0", void 0);
  90366. __decorate([
  90367. BABYLON.serialize()
  90368. ], BackgroundMaterial.prototype, "_reflectionReflectance90", void 0);
  90369. __decorate([
  90370. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  90371. ], BackgroundMaterial.prototype, "reflectionReflectance90", void 0);
  90372. __decorate([
  90373. BABYLON.serialize()
  90374. ], BackgroundMaterial.prototype, "_useRGBColor", void 0);
  90375. __decorate([
  90376. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  90377. ], BackgroundMaterial.prototype, "useRGBColor", void 0);
  90378. __decorate([
  90379. BABYLON.serialize()
  90380. ], BackgroundMaterial.prototype, "_enableNoise", void 0);
  90381. __decorate([
  90382. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  90383. ], BackgroundMaterial.prototype, "enableNoise", void 0);
  90384. __decorate([
  90385. BABYLON.serialize()
  90386. ], BackgroundMaterial.prototype, "_maxSimultaneousLights", void 0);
  90387. __decorate([
  90388. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  90389. ], BackgroundMaterial.prototype, "maxSimultaneousLights", void 0);
  90390. __decorate([
  90391. BABYLON.serializeAsImageProcessingConfiguration()
  90392. ], BackgroundMaterial.prototype, "_imageProcessingConfiguration", void 0);
  90393. return BackgroundMaterial;
  90394. }(BABYLON.PushMaterial));
  90395. BABYLON.BackgroundMaterial = BackgroundMaterial;
  90396. })(BABYLON || (BABYLON = {}));
  90397. //# sourceMappingURL=babylon.backgroundMaterial.js.map
  90398. var __assign = (this && this.__assign) || Object.assign || function(t) {
  90399. for (var s, i = 1, n = arguments.length; i < n; i++) {
  90400. s = arguments[i];
  90401. for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
  90402. t[p] = s[p];
  90403. }
  90404. return t;
  90405. };
  90406. var BABYLON;
  90407. (function (BABYLON) {
  90408. /**
  90409. * The Environment helper class can be used to add a fully featuread none expensive background to your scene.
  90410. * It includes by default a skybox and a ground relying on the BackgroundMaterial.
  90411. * It also helps with the default setup of your imageProcessing configuration.
  90412. */
  90413. var EnvironmentHelper = /** @class */ (function () {
  90414. /**
  90415. * constructor
  90416. * @param options
  90417. * @param scene The scene to add the material to
  90418. */
  90419. function EnvironmentHelper(options, scene) {
  90420. var _this = this;
  90421. this._errorHandler = function (message, exception) {
  90422. _this.onErrorObservable.notifyObservers({ message: message, exception: exception });
  90423. };
  90424. this._options = __assign({}, EnvironmentHelper._getDefaultOptions(), options);
  90425. this._scene = scene;
  90426. this.onErrorObservable = new BABYLON.Observable();
  90427. this._setupBackground();
  90428. this._setupImageProcessing();
  90429. }
  90430. /**
  90431. * Creates the default options for the helper.
  90432. */
  90433. EnvironmentHelper._getDefaultOptions = function () {
  90434. return {
  90435. createGround: true,
  90436. groundSize: 15,
  90437. groundTexture: this._groundTextureCDNUrl,
  90438. groundColor: new BABYLON.Color3(0.2, 0.2, 0.3).toLinearSpace().scale(3),
  90439. groundOpacity: 0.9,
  90440. enableGroundShadow: true,
  90441. groundShadowLevel: 0.5,
  90442. enableGroundMirror: false,
  90443. groundMirrorSizeRatio: 0.3,
  90444. groundMirrorBlurKernel: 64,
  90445. groundMirrorAmount: 1,
  90446. groundMirrorFresnelWeight: 1,
  90447. groundMirrorFallOffDistance: 0,
  90448. groundMirrorTextureType: BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT,
  90449. groundYBias: 0.00001,
  90450. createSkybox: true,
  90451. skyboxSize: 20,
  90452. skyboxTexture: this._skyboxTextureCDNUrl,
  90453. skyboxColor: new BABYLON.Color3(0.2, 0.2, 0.3).toLinearSpace().scale(3),
  90454. backgroundYRotation: 0,
  90455. sizeAuto: true,
  90456. rootPosition: BABYLON.Vector3.Zero(),
  90457. setupImageProcessing: true,
  90458. environmentTexture: this._environmentTextureCDNUrl,
  90459. cameraExposure: 0.8,
  90460. cameraContrast: 1.2,
  90461. toneMappingEnabled: true,
  90462. };
  90463. };
  90464. Object.defineProperty(EnvironmentHelper.prototype, "rootMesh", {
  90465. /**
  90466. * Gets the root mesh created by the helper.
  90467. */
  90468. get: function () {
  90469. return this._rootMesh;
  90470. },
  90471. enumerable: true,
  90472. configurable: true
  90473. });
  90474. Object.defineProperty(EnvironmentHelper.prototype, "skybox", {
  90475. /**
  90476. * Gets the skybox created by the helper.
  90477. */
  90478. get: function () {
  90479. return this._skybox;
  90480. },
  90481. enumerable: true,
  90482. configurable: true
  90483. });
  90484. Object.defineProperty(EnvironmentHelper.prototype, "skyboxTexture", {
  90485. /**
  90486. * Gets the skybox texture created by the helper.
  90487. */
  90488. get: function () {
  90489. return this._skyboxTexture;
  90490. },
  90491. enumerable: true,
  90492. configurable: true
  90493. });
  90494. Object.defineProperty(EnvironmentHelper.prototype, "skyboxMaterial", {
  90495. /**
  90496. * Gets the skybox material created by the helper.
  90497. */
  90498. get: function () {
  90499. return this._skyboxMaterial;
  90500. },
  90501. enumerable: true,
  90502. configurable: true
  90503. });
  90504. Object.defineProperty(EnvironmentHelper.prototype, "ground", {
  90505. /**
  90506. * Gets the ground mesh created by the helper.
  90507. */
  90508. get: function () {
  90509. return this._ground;
  90510. },
  90511. enumerable: true,
  90512. configurable: true
  90513. });
  90514. Object.defineProperty(EnvironmentHelper.prototype, "groundTexture", {
  90515. /**
  90516. * Gets the ground texture created by the helper.
  90517. */
  90518. get: function () {
  90519. return this._groundTexture;
  90520. },
  90521. enumerable: true,
  90522. configurable: true
  90523. });
  90524. Object.defineProperty(EnvironmentHelper.prototype, "groundMirror", {
  90525. /**
  90526. * Gets the ground mirror created by the helper.
  90527. */
  90528. get: function () {
  90529. return this._groundMirror;
  90530. },
  90531. enumerable: true,
  90532. configurable: true
  90533. });
  90534. Object.defineProperty(EnvironmentHelper.prototype, "groundMirrorRenderList", {
  90535. /**
  90536. * Gets the ground mirror render list to helps pushing the meshes
  90537. * you wish in the ground reflection.
  90538. */
  90539. get: function () {
  90540. if (this._groundMirror) {
  90541. return this._groundMirror.renderList;
  90542. }
  90543. return null;
  90544. },
  90545. enumerable: true,
  90546. configurable: true
  90547. });
  90548. Object.defineProperty(EnvironmentHelper.prototype, "groundMaterial", {
  90549. /**
  90550. * Gets the ground material created by the helper.
  90551. */
  90552. get: function () {
  90553. return this._groundMaterial;
  90554. },
  90555. enumerable: true,
  90556. configurable: true
  90557. });
  90558. /**
  90559. * Updates the background according to the new options
  90560. * @param options
  90561. */
  90562. EnvironmentHelper.prototype.updateOptions = function (options) {
  90563. var newOptions = __assign({}, this._options, options);
  90564. if (this._ground && !newOptions.createGround) {
  90565. this._ground.dispose();
  90566. this._ground = null;
  90567. }
  90568. if (this._groundMaterial && !newOptions.createGround) {
  90569. this._groundMaterial.dispose();
  90570. this._groundMaterial = null;
  90571. }
  90572. if (this._groundTexture) {
  90573. if (this._options.groundTexture != newOptions.groundTexture) {
  90574. this._groundTexture.dispose();
  90575. this._groundTexture = null;
  90576. }
  90577. }
  90578. if (this._skybox && !newOptions.createSkybox) {
  90579. this._skybox.dispose();
  90580. this._skybox = null;
  90581. }
  90582. if (this._skyboxMaterial && !newOptions.createSkybox) {
  90583. this._skyboxMaterial.dispose();
  90584. this._skyboxMaterial = null;
  90585. }
  90586. if (this._skyboxTexture) {
  90587. if (this._options.skyboxTexture != newOptions.skyboxTexture) {
  90588. this._skyboxTexture.dispose();
  90589. this._skyboxTexture = null;
  90590. }
  90591. }
  90592. if (this._groundMirror && !newOptions.enableGroundMirror) {
  90593. this._groundMirror.dispose();
  90594. this._groundMirror = null;
  90595. }
  90596. if (this._scene.environmentTexture) {
  90597. if (this._options.environmentTexture != newOptions.environmentTexture) {
  90598. this._scene.environmentTexture.dispose();
  90599. }
  90600. }
  90601. this._options = newOptions;
  90602. this._setupBackground();
  90603. this._setupImageProcessing();
  90604. };
  90605. /**
  90606. * Sets the primary color of all the available elements.
  90607. * @param color
  90608. */
  90609. EnvironmentHelper.prototype.setMainColor = function (color) {
  90610. if (this.groundMaterial) {
  90611. this.groundMaterial.primaryColor = color;
  90612. }
  90613. if (this.skyboxMaterial) {
  90614. this.skyboxMaterial.primaryColor = color;
  90615. }
  90616. if (this.groundMirror) {
  90617. this.groundMirror.clearColor = new BABYLON.Color4(color.r, color.g, color.b, 1.0);
  90618. }
  90619. };
  90620. /**
  90621. * Setup the image processing according to the specified options.
  90622. */
  90623. EnvironmentHelper.prototype._setupImageProcessing = function () {
  90624. if (this._options.setupImageProcessing) {
  90625. this._scene.imageProcessingConfiguration.contrast = this._options.cameraContrast;
  90626. this._scene.imageProcessingConfiguration.exposure = this._options.cameraExposure;
  90627. this._scene.imageProcessingConfiguration.toneMappingEnabled = this._options.toneMappingEnabled;
  90628. this._setupEnvironmentTexture();
  90629. }
  90630. };
  90631. /**
  90632. * Setup the environment texture according to the specified options.
  90633. */
  90634. EnvironmentHelper.prototype._setupEnvironmentTexture = function () {
  90635. if (this._scene.environmentTexture) {
  90636. return;
  90637. }
  90638. if (this._options.environmentTexture instanceof BABYLON.BaseTexture) {
  90639. this._scene.environmentTexture = this._options.environmentTexture;
  90640. return;
  90641. }
  90642. var environmentTexture = BABYLON.CubeTexture.CreateFromPrefilteredData(this._options.environmentTexture, this._scene);
  90643. this._scene.environmentTexture = environmentTexture;
  90644. };
  90645. /**
  90646. * Setup the background according to the specified options.
  90647. */
  90648. EnvironmentHelper.prototype._setupBackground = function () {
  90649. if (!this._rootMesh) {
  90650. this._rootMesh = new BABYLON.Mesh("BackgroundHelper", this._scene);
  90651. }
  90652. this._rootMesh.rotation.y = this._options.backgroundYRotation;
  90653. var sceneSize = this._getSceneSize();
  90654. if (this._options.createGround) {
  90655. this._setupGround(sceneSize);
  90656. this._setupGroundMaterial();
  90657. this._setupGroundDiffuseTexture();
  90658. if (this._options.enableGroundMirror) {
  90659. this._setupGroundMirrorTexture(sceneSize);
  90660. }
  90661. this._setupMirrorInGroundMaterial();
  90662. }
  90663. if (this._options.createSkybox) {
  90664. this._setupSkybox(sceneSize);
  90665. this._setupSkyboxMaterial();
  90666. this._setupSkyboxReflectionTexture();
  90667. }
  90668. this._rootMesh.position.x = sceneSize.rootPosition.x;
  90669. this._rootMesh.position.z = sceneSize.rootPosition.z;
  90670. this._rootMesh.position.y = sceneSize.rootPosition.y;
  90671. };
  90672. /**
  90673. * Get the scene sizes according to the setup.
  90674. */
  90675. EnvironmentHelper.prototype._getSceneSize = function () {
  90676. var _this = this;
  90677. var groundSize = this._options.groundSize;
  90678. var skyboxSize = this._options.skyboxSize;
  90679. var rootPosition = this._options.rootPosition;
  90680. if (!this._scene.meshes || this._scene.meshes.length === 1) {
  90681. return { groundSize: groundSize, skyboxSize: skyboxSize, rootPosition: rootPosition };
  90682. }
  90683. var sceneExtends = this._scene.getWorldExtends(function (mesh) {
  90684. return (mesh !== _this._ground && mesh !== _this._rootMesh && mesh !== _this._skybox);
  90685. });
  90686. var sceneDiagonal = sceneExtends.max.subtract(sceneExtends.min);
  90687. if (this._options.sizeAuto) {
  90688. if (this._scene.activeCamera instanceof BABYLON.ArcRotateCamera &&
  90689. this._scene.activeCamera.upperRadiusLimit) {
  90690. groundSize = this._scene.activeCamera.upperRadiusLimit * 2;
  90691. skyboxSize = groundSize;
  90692. }
  90693. var sceneDiagonalLenght = sceneDiagonal.length();
  90694. if (sceneDiagonalLenght > groundSize) {
  90695. groundSize = sceneDiagonalLenght * 2;
  90696. skyboxSize = groundSize;
  90697. }
  90698. // 10 % bigger.
  90699. groundSize *= 1.1;
  90700. skyboxSize *= 1.5;
  90701. rootPosition = sceneExtends.min.add(sceneDiagonal.scale(0.5));
  90702. rootPosition.y = sceneExtends.min.y - this._options.groundYBias;
  90703. }
  90704. return { groundSize: groundSize, skyboxSize: skyboxSize, rootPosition: rootPosition };
  90705. };
  90706. /**
  90707. * Setup the ground according to the specified options.
  90708. */
  90709. EnvironmentHelper.prototype._setupGround = function (sceneSize) {
  90710. var _this = this;
  90711. if (!this._ground) {
  90712. this._ground = BABYLON.Mesh.CreatePlane("BackgroundPlane", sceneSize.groundSize, this._scene);
  90713. this._ground.rotation.x = Math.PI / 2; // Face up by default.
  90714. this._ground.parent = this._rootMesh;
  90715. this._ground.onDisposeObservable.add(function () { _this._ground = null; });
  90716. }
  90717. this._ground.receiveShadows = this._options.enableGroundShadow;
  90718. };
  90719. /**
  90720. * Setup the ground material according to the specified options.
  90721. */
  90722. EnvironmentHelper.prototype._setupGroundMaterial = function () {
  90723. if (!this._groundMaterial) {
  90724. this._groundMaterial = new BABYLON.BackgroundMaterial("BackgroundPlaneMaterial", this._scene);
  90725. }
  90726. this._groundMaterial.alpha = this._options.groundOpacity;
  90727. this._groundMaterial.alphaMode = BABYLON.Engine.ALPHA_PREMULTIPLIED_PORTERDUFF;
  90728. this._groundMaterial.shadowLevel = this._options.groundShadowLevel;
  90729. this._groundMaterial.primaryLevel = 1;
  90730. this._groundMaterial.primaryColor = this._options.groundColor;
  90731. this._groundMaterial.secondaryLevel = 0;
  90732. this._groundMaterial.tertiaryLevel = 0;
  90733. this._groundMaterial.useRGBColor = false;
  90734. this._groundMaterial.enableNoise = true;
  90735. if (this._ground) {
  90736. this._ground.material = this._groundMaterial;
  90737. }
  90738. };
  90739. /**
  90740. * Setup the ground diffuse texture according to the specified options.
  90741. */
  90742. EnvironmentHelper.prototype._setupGroundDiffuseTexture = function () {
  90743. if (!this._groundMaterial) {
  90744. return;
  90745. }
  90746. if (this._groundTexture) {
  90747. return;
  90748. }
  90749. if (this._options.groundTexture instanceof BABYLON.BaseTexture) {
  90750. this._groundMaterial.diffuseTexture = this._options.groundTexture;
  90751. return;
  90752. }
  90753. var diffuseTexture = new BABYLON.Texture(this._options.groundTexture, this._scene, undefined, undefined, undefined, undefined, this._errorHandler);
  90754. diffuseTexture.gammaSpace = false;
  90755. diffuseTexture.hasAlpha = true;
  90756. this._groundMaterial.diffuseTexture = diffuseTexture;
  90757. };
  90758. /**
  90759. * Setup the ground mirror texture according to the specified options.
  90760. */
  90761. EnvironmentHelper.prototype._setupGroundMirrorTexture = function (sceneSize) {
  90762. var wrapping = BABYLON.Texture.CLAMP_ADDRESSMODE;
  90763. if (!this._groundMirror) {
  90764. this._groundMirror = new BABYLON.MirrorTexture("BackgroundPlaneMirrorTexture", { ratio: this._options.groundMirrorSizeRatio }, this._scene, false, this._options.groundMirrorTextureType, BABYLON.Texture.BILINEAR_SAMPLINGMODE, true);
  90765. this._groundMirror.mirrorPlane = new BABYLON.Plane(0, -1, 0, sceneSize.rootPosition.y);
  90766. this._groundMirror.anisotropicFilteringLevel = 1;
  90767. this._groundMirror.wrapU = wrapping;
  90768. this._groundMirror.wrapV = wrapping;
  90769. this._groundMirror.gammaSpace = false;
  90770. if (this._groundMirror.renderList) {
  90771. for (var i = 0; i < this._scene.meshes.length; i++) {
  90772. var mesh = this._scene.meshes[i];
  90773. if (mesh !== this._ground &&
  90774. mesh !== this._skybox &&
  90775. mesh !== this._rootMesh) {
  90776. this._groundMirror.renderList.push(mesh);
  90777. }
  90778. }
  90779. }
  90780. }
  90781. this._groundMirror.clearColor = new BABYLON.Color4(this._options.groundColor.r, this._options.groundColor.g, this._options.groundColor.b, 1);
  90782. this._groundMirror.adaptiveBlurKernel = this._options.groundMirrorBlurKernel;
  90783. };
  90784. /**
  90785. * Setup the ground to receive the mirror texture.
  90786. */
  90787. EnvironmentHelper.prototype._setupMirrorInGroundMaterial = function () {
  90788. if (this._groundMaterial) {
  90789. this._groundMaterial.reflectionTexture = this._groundMirror;
  90790. this._groundMaterial.reflectionFresnel = true;
  90791. this._groundMaterial.reflectionAmount = this._options.groundMirrorAmount;
  90792. this._groundMaterial.reflectionStandardFresnelWeight = this._options.groundMirrorFresnelWeight;
  90793. this._groundMaterial.reflectionFalloffDistance = this._options.groundMirrorFallOffDistance;
  90794. }
  90795. };
  90796. /**
  90797. * Setup the skybox according to the specified options.
  90798. */
  90799. EnvironmentHelper.prototype._setupSkybox = function (sceneSize) {
  90800. var _this = this;
  90801. if (!this._skybox) {
  90802. this._skybox = BABYLON.Mesh.CreateBox("BackgroundSkybox", sceneSize.skyboxSize, this._scene, undefined, BABYLON.Mesh.BACKSIDE);
  90803. this._skybox.onDisposeObservable.add(function () { _this._skybox = null; });
  90804. }
  90805. this._skybox.parent = this._rootMesh;
  90806. };
  90807. /**
  90808. * Setup the skybox material according to the specified options.
  90809. */
  90810. EnvironmentHelper.prototype._setupSkyboxMaterial = function () {
  90811. if (!this._skybox) {
  90812. return;
  90813. }
  90814. if (!this._skyboxMaterial) {
  90815. this._skyboxMaterial = new BABYLON.BackgroundMaterial("BackgroundSkyboxMaterial", this._scene);
  90816. }
  90817. this._skyboxMaterial.useRGBColor = false;
  90818. this._skyboxMaterial.primaryLevel = 1;
  90819. this._skyboxMaterial.primaryColor = this._options.skyboxColor;
  90820. this._skyboxMaterial.secondaryLevel = 0;
  90821. this._skyboxMaterial.tertiaryLevel = 0;
  90822. this._skyboxMaterial.enableNoise = true;
  90823. this._skybox.material = this._skyboxMaterial;
  90824. };
  90825. /**
  90826. * Setup the skybox reflection texture according to the specified options.
  90827. */
  90828. EnvironmentHelper.prototype._setupSkyboxReflectionTexture = function () {
  90829. if (!this._skyboxMaterial) {
  90830. return;
  90831. }
  90832. if (this._skyboxTexture) {
  90833. return;
  90834. }
  90835. if (this._options.skyboxTexture instanceof BABYLON.BaseTexture) {
  90836. this._skyboxMaterial.reflectionTexture = this._skyboxTexture;
  90837. return;
  90838. }
  90839. this._skyboxTexture = new BABYLON.CubeTexture(this._options.skyboxTexture, this._scene, undefined, undefined, undefined, undefined, this._errorHandler);
  90840. this._skyboxTexture.coordinatesMode = BABYLON.Texture.SKYBOX_MODE;
  90841. this._skyboxTexture.gammaSpace = false;
  90842. this._skyboxMaterial.reflectionTexture = this._skyboxTexture;
  90843. };
  90844. /**
  90845. * Dispose all the elements created by the Helper.
  90846. */
  90847. EnvironmentHelper.prototype.dispose = function () {
  90848. if (this._groundMaterial) {
  90849. this._groundMaterial.dispose(true, true);
  90850. }
  90851. if (this._skyboxMaterial) {
  90852. this._skyboxMaterial.dispose(true, true);
  90853. }
  90854. this._rootMesh.dispose(false);
  90855. };
  90856. /**
  90857. * Default ground texture URL.
  90858. */
  90859. EnvironmentHelper._groundTextureCDNUrl = "https://assets.babylonjs.com/environments/backgroundGround.png";
  90860. /**
  90861. * Default skybox texture URL.
  90862. */
  90863. EnvironmentHelper._skyboxTextureCDNUrl = "https://assets.babylonjs.com/environments/backgroundSkybox.dds";
  90864. /**
  90865. * Default environment texture URL.
  90866. */
  90867. EnvironmentHelper._environmentTextureCDNUrl = "https://assets.babylonjs.com/environments/environmentSpecular.dds";
  90868. return EnvironmentHelper;
  90869. }());
  90870. BABYLON.EnvironmentHelper = EnvironmentHelper;
  90871. })(BABYLON || (BABYLON = {}));
  90872. //# sourceMappingURL=babylon.environmentHelper.js.map
  90873. var BABYLON;
  90874. (function (BABYLON) {
  90875. /**
  90876. * Display a 360 degree video on an approximately spherical surface, useful for VR applications or skyboxes.
  90877. * As a subclass of Node, this allow parenting to the camera or multiple videos with different locations in the scene.
  90878. * This class achieves its effect with a VideoTexture and a correctly configured BackgroundMaterial on an inverted sphere.
  90879. * Potential additions to this helper include zoom and and non-infinite distance rendering effects.
  90880. */
  90881. var VideoDome = /** @class */ (function (_super) {
  90882. __extends(VideoDome, _super);
  90883. /**
  90884. * Create an instance of this class and pass through the parameters to the relevant classes, VideoTexture, StandardMaterial, and Mesh.
  90885. * @param name Element's name, child elements will append suffixes for their own names.
  90886. * @param urlsOrVideo
  90887. * @param options An object containing optional or exposed sub element properties:
  90888. * @param options **resolution=12** Integer, lower resolutions have more artifacts at extreme fovs
  90889. * @param options **clickToPlay=false** Add a click to play listener to the video, does not prevent autoplay.
  90890. * @param options **autoPlay=true** Automatically attempt to being playing the video.
  90891. * @param options **loop=true** Automatically loop video on end.
  90892. * @param options **size=1000** Physical radius to create the dome at, defaults to approximately half the far clip plane.
  90893. */
  90894. function VideoDome(name, urlsOrVideo, options, scene) {
  90895. var _this = _super.call(this, name, scene) || this;
  90896. // set defaults and manage values
  90897. name = name || "videoDome";
  90898. options.resolution = (Math.abs(options.resolution) | 0) || 12;
  90899. options.clickToPlay = Boolean(options.clickToPlay);
  90900. options.autoPlay = options.autoPlay === undefined ? true : Boolean(options.autoPlay);
  90901. options.loop = options.loop === undefined ? true : Boolean(options.loop);
  90902. options.size = Math.abs(options.size) || (scene.activeCamera ? scene.activeCamera.maxZ * 0.48 : 1000);
  90903. // create
  90904. var tempOptions = { loop: options.loop, autoPlay: options.autoPlay, autoUpdateTexture: true };
  90905. var material = _this._material = new BABYLON.BackgroundMaterial(name + "_material", scene);
  90906. var texture = _this._videoTexture = new BABYLON.VideoTexture(name + "_texture", urlsOrVideo, scene, false, false, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, tempOptions);
  90907. _this._mesh = BABYLON.MeshBuilder.CreateIcoSphere(name + "_mesh", {
  90908. flat: false,
  90909. radius: options.size,
  90910. subdivisions: options.resolution,
  90911. sideOrientation: BABYLON.Mesh.BACKSIDE // needs to be inside out
  90912. }, scene);
  90913. // configure material
  90914. texture.coordinatesMode = BABYLON.Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE; // matches orientation
  90915. texture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE; // always clamp the up/down
  90916. material.reflectionTexture = _this._videoTexture;
  90917. material.useEquirectangularFOV = true;
  90918. material.fovMultiplier = 1.0;
  90919. // configure mesh
  90920. _this._mesh.material = material;
  90921. _this._mesh.parent = _this;
  90922. // optional configuration
  90923. if (options.clickToPlay) {
  90924. scene.onPointerUp = function () {
  90925. _this._videoTexture.video.play();
  90926. };
  90927. }
  90928. return _this;
  90929. }
  90930. Object.defineProperty(VideoDome.prototype, "fovMultiplier", {
  90931. /**
  90932. * The current fov(field of view) multiplier, 0.0 - 2.0. Defaults to 1.0. Lower values "zoom in" and higher values "zoom out".
  90933. * Also see the options.resolution property.
  90934. */
  90935. get: function () {
  90936. return this._material.fovMultiplier;
  90937. },
  90938. set: function (value) {
  90939. this._material.fovMultiplier = value;
  90940. },
  90941. enumerable: true,
  90942. configurable: true
  90943. });
  90944. /**
  90945. * Releases resources associated with this node.
  90946. * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default)
  90947. * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default)
  90948. */
  90949. VideoDome.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  90950. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  90951. this._videoTexture.dispose();
  90952. this._mesh.dispose();
  90953. this._material.dispose();
  90954. _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
  90955. };
  90956. return VideoDome;
  90957. }(BABYLON.Node));
  90958. BABYLON.VideoDome = VideoDome;
  90959. })(BABYLON || (BABYLON = {}));
  90960. //# sourceMappingURL=babylon.videoDome.js.map
  90961. 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\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=toLinearSpace(texture2D(lightmapSampler,vLightmapUV+uvOffset).rgb)*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\nvec3 finalDiffuse=diffuseBase;\nfinalDiffuse.rgb+=vAmbientColor;\nfinalDiffuse*=surfaceAlbedo.rgb;\nfinalDiffuse=max(finalDiffuse,0.0);\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\nvec3 finalEmissive=vEmissiveColor;\n#ifdef EMISSIVE\nvec3 emissiveColorTex=texture2D(emissiveSampler,vEmissiveUV+uvOffset).rgb;\nfinalEmissive*=toLinearSpace(emissiveColorTex.rgb);\nfinalEmissive*=vEmissiveInfos.y;\n#endif\n\n#ifdef 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\n\n\nvec4 finalColor=vec4(finalDiffuse*ambientOcclusionColor*vLightingIntensity.x +\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\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 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) {\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/height;\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+gravity)*timeDelta;\noutAge=age+timeDelta;\noutLife=life;\noutSeed=seed;\noutColor=color;\noutSize=size;\noutDirection=direction;\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#include<bonesDeclaration>\n\n#include<instancesDeclaration>\nuniform mat4 viewProjection;\nuniform vec2 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{\n#include<instancesVertex>\n#include<bonesVertex>\nvec4 worldPos=finalWorld*vec4(position,1.0);\ngl_Position=viewProjection*worldPos;\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 vec2 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.y*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","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;\ngl_FragColor=original;\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}","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":"\nuniform sampler2D textureSampler;\nuniform sampler2D originalSampler;\nuniform sampler2D circleOfConfusionSampler;\n#if BLUR_LEVEL>0\nuniform sampler2D blurStep1;\n#endif\n#if BLUR_LEVEL>1\nuniform sampler2D blurStep2;\n#endif\n\nvarying vec2 vUV;\nvoid main(void)\n{\nfloat coc=texture2D(circleOfConfusionSampler,vUV).r;\nvec4 original=texture2D(originalSampler,vUV);\n#if BLUR_LEVEL == 0\nvec4 blurred1=texture2D(textureSampler,vUV);\ngl_FragColor=mix(original,blurred1,coc);\n#endif\n#if BLUR_LEVEL == 1\nvec4 blurred1=texture2D(blurStep1,vUV);\nvec4 blurred2=texture2D(textureSampler,vUV); \nif(coc<0.5){\ngl_FragColor=mix(original,blurred1,coc/0.5);\n}else{\ngl_FragColor=mix(blurred1,blurred2,(coc-0.5)/0.5);\n}\n#endif\n#if BLUR_LEVEL == 2\nvec4 blurred1=texture2D(blurStep1,vUV);\nvec4 blurred2=texture2D(blurStep2,vUV);\nvec4 blurred3=texture2D(textureSampler,vUV);\nif(coc<0.33){\ngl_FragColor=mix(original,blurred1,coc/0.33);\n}else if(coc<0.66){\ngl_FragColor=mix(blurred1,blurred2,(coc-0.33)/0.33);\n}else{\ngl_FragColor=mix(blurred2,blurred3,(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","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\n#ifdef GRAIN\nvec2 seed=vUV*(grainAnimatedSeed);\nfloat grain=dither(seed,grainVarianceAmount);\n\nfloat lum=getLuminance(result.rgb);\nfloat grainAmount=(cos(-PI+(lum*PI*2.))+1.)/2.;\nresult.rgb+=grain*grainAmount;\nresult.rgb=max(result.rgb,0.0);\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\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{\n#include<instancesVertex>\n#include<bonesVertex>\n#ifdef CUBEMAP\nvPosition=finalWorld*vec4(position,1.0);\ngl_Position=viewProjection*finalWorld*vec4(position,1.0);\n#else\nvPosition=viewProjection*finalWorld*vec4(position,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#ifndef GRAIN \n#ifdef NOISE\ncolor.rgb+=dither(vPositionW.xy,0.5);\ncolor=max(color,0.0);\n#endif\n#endif\ngl_FragColor=color;\n}\n"};
  90962. 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};\nuniform sampler2D shadowSampler{X};\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};\nuniform sampler2D shadowSampler{X};\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 computeShadowWithPCFCube(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 computeShadowWithPCF(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#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\n#ifdef GRAIN\nuniform float grainVarianceAmount;\nuniform float grainAnimatedSeed;\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#else\n#ifdef 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#else \n#ifdef SHADOWPCF{X}\n#if defined(SHADOWCUBE{X})\nshadow=computeShadowWithPCFCube(light{X}.vLightData.xyz,shadowSampler{X},light{X}.shadowsInfo.y,light{X}.shadowsInfo.x,light{X}.depthValues);\n#else\nshadow=computeShadowWithPCF(vPositionFromLight{X},vDepthMetric{X},shadowSampler{X},light{X}.shadowsInfo.y,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#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);
  90963. globalObject["BABYLON"] = BABYLON;
  90964. 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 SharpenPostProcess = BABYLON.SharpenPostProcess;var BlurPostProcess = BABYLON.BlurPostProcess;var DepthOfFieldBlurPostProcess = BABYLON.DepthOfFieldBlurPostProcess;var DepthOfFieldMergePostProcess = BABYLON.DepthOfFieldMergePostProcess;var CircleOfConfusionPostProcess = BABYLON.CircleOfConfusionPostProcess;var DepthOfFieldEffect = BABYLON.DepthOfFieldEffect;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;
  90965. 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,SharpenPostProcess,BlurPostProcess,DepthOfFieldBlurPostProcess,DepthOfFieldMergePostProcess,CircleOfConfusionPostProcess,DepthOfFieldEffect,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 };